code
stringlengths
3
1.05M
repo_name
stringlengths
4
116
path
stringlengths
3
942
language
stringclasses
30 values
license
stringclasses
15 values
size
int32
3
1.05M
////////////////////////////////////////////////////////////////////////////// // Copyright 2004-2014, SenseGraphics AB // // This file is part of H3D API. // // H3D API 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. // // H3D API 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 H3D API; if not, write to the Free Software // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA // // A commercial license is also available. Please contact us at // www.sensegraphics.com for more information. // // /// \file FreeImageLoader.cpp /// \brief CPP file for FreeImageLoader, a image loader using the FreeImage /// library to read images. /// // ////////////////////////////////////////////////////////////////////////////// #include <H3D/FreeImageLoader.h> #ifdef HAVE_FREEIMAGE #include <H3DUtil/FreeImageImage.h> #include <FreeImage.h> using namespace H3D; // Add this node to the H3DNodeDatabase system. H3DNodeDatabase FreeImageLoader::database( "FreeImageLoader", &(newInstance<FreeImageLoader>), typeid( FreeImageLoader ) ); H3DImageLoaderNode::FileReaderRegistration FreeImageLoader::reader_registration( "FreeImageLoader", &(newImageLoaderNode< FreeImageLoader >), &FreeImageLoader::supportsFileType, &FreeImageLoader::supportsStreamType ); bool FreeImageLoader::supportsFileType( const string &url ) { FREE_IMAGE_FORMAT format = FreeImage_GetFileType( url.c_str() ); return format != FIF_UNKNOWN; } bool FreeImageLoader::supportsStreamType( istream &is ) { FREE_IMAGE_FORMAT format = FreeImage_GetFileTypeFromHandle ( FreeImageImage::getIStreamIO(), static_cast<fi_handle>(&is) ); return format != FIF_UNKNOWN; } #endif // HAVE_FREEIMAGE
JakeFountain/H3DAPIwithOculusSupport
src/FreeImageLoader.cpp
C++
gpl-2.0
2,411
package Dist::Zilla::Plugin::MetaTests; # ABSTRACT: common extra tests for META.yml $Dist::Zilla::Plugin::MetaTests::VERSION = '5.037'; use Moose; extends 'Dist::Zilla::Plugin::InlineFiles'; with 'Dist::Zilla::Role::PrereqSource'; use namespace::autoclean; #pod =head1 DESCRIPTION #pod #pod This is an extension of L<Dist::Zilla::Plugin::InlineFiles>, providing the #pod following files: #pod #pod xt/release/meta-yaml.t - a standard Test::CPAN::Meta test #pod #pod L<Test::CPAN::Meta> will be added as a C<develop requires> dependency (which #pod can be installed via C<< dzil listdeps --author | cpanm >>). #pod #pod =head1 SEE ALSO #pod #pod Core Dist::Zilla plugins: #pod L<MetaResources|Dist::Zilla::Plugin::MetaResources>, #pod L<MetaNoIndex|Dist::Zilla::Plugin::MetaNoIndex>, #pod L<MetaYAML|Dist::Zilla::Plugin::MetaYAML>, #pod L<MetaJSON|Dist::Zilla::Plugin::MetaJSON>, #pod L<MetaConfig|Dist::Zilla::Plugin::MetaConfig>. #pod #pod =cut # Register the release test prereq as a "develop requires" # so it will be listed in "dzil listdeps --author" sub register_prereqs { my ($self) = @_; $self->zilla->register_prereqs( { phase => 'develop', type => 'requires', }, 'Test::CPAN::Meta' => 0, ); } __PACKAGE__->meta->make_immutable; 1; =pod =encoding UTF-8 =head1 NAME Dist::Zilla::Plugin::MetaTests - common extra tests for META.yml =head1 VERSION version 5.037 =head1 DESCRIPTION This is an extension of L<Dist::Zilla::Plugin::InlineFiles>, providing the following files: xt/release/meta-yaml.t - a standard Test::CPAN::Meta test L<Test::CPAN::Meta> will be added as a C<develop requires> dependency (which can be installed via C<< dzil listdeps --author | cpanm >>). =head1 SEE ALSO Core Dist::Zilla plugins: L<MetaResources|Dist::Zilla::Plugin::MetaResources>, L<MetaNoIndex|Dist::Zilla::Plugin::MetaNoIndex>, L<MetaYAML|Dist::Zilla::Plugin::MetaYAML>, L<MetaJSON|Dist::Zilla::Plugin::MetaJSON>, L<MetaConfig|Dist::Zilla::Plugin::MetaConfig>. =head1 AUTHOR Ricardo SIGNES <rjbs@cpan.org> =head1 COPYRIGHT AND LICENSE This software is copyright (c) 2015 by Ricardo SIGNES. This is free software; you can redistribute it and/or modify it under the same terms as the Perl 5 programming language system itself. =cut __DATA__ ___[ xt/release/distmeta.t ]___ #!perl # This file was automatically generated by Dist::Zilla::Plugin::MetaTests. use Test::CPAN::Meta; meta_yaml_ok();
mishin/dwimperl-windows
strawberry-perl-5.20.0.1-32bit-portable/perl/site/lib/Dist/Zilla/Plugin/MetaTests.pm
Perl
gpl-2.0
2,441
<?php /* Copyright 2005 Flávio Ribeiro This file is part of OCOMON. OCOMON 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. OCOMON 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 Foobar; if not, write to the Free Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA */session_start(); include ("../../includes/include_geral.inc.php"); include ("../../includes/include_geral_II.inc.php"); include ('includes/header.php'); $_SESSION['s_page_invmon'] = $_SERVER['PHP_SELF']; $cab = new headers; $cab->set_title(TRANS('TTL_INVMON')); $auth = new auth; $auth->testa_user($_SESSION['s_usuario'],$_SESSION['s_nivel'],$_SESSION['s_nivel_desc'],2); $hoje = date("Y-m-d H:i:s"); $cor = TD_COLOR; $cor1 = TD_COLOR; $cor3 = BODY_COLOR; $query = $QRY["vencimentos_full"]; $result = mysql_query($query); //----------------TABELA -----------------// print "<br><br><p align='center'>".TRANS('TTL_PREVIEWS_EXP_GUARANTEE_FULL').": <a href='estat_vencimentos.php'>".TRANS('SHOW_ONLY_3_YEARS')."</a></p>"; print "<table cellspacing='0' border='1' align='center' style=\"{border-collapse:collapse;}\">"; print "<tr><td ><b>".TRANS('COL_DATE_2')."</b></td><td ><b>".TRANS('COL_AMOUNT')."</b></td><td ><b>".TRANS('COL_TYPE_2')."</b></td><td ><b>".TRANS('COL_MODEL_2')."</b></td></tr>"; //-----------------FINAL DA TABELA -----------------------// $tt_garant = 0; while ($row=mysql_fetch_array($result)) { $temp1 = explode(" ",$row['vencimento']); $temp = explode(" ",datab($row['vencimento'])); $vencimento1 = $temp1[0]; $vencimento = $temp[0]; $tt_garant+= $row['quantidade']; print "<tr><td ><a onClick=\"popup('mostra_consulta_comp.php?VENCIMENTO=".$vencimento1."')\">".$vencimento."</a></td>". "<td align='center'><a onClick=\"popup('mostra_consulta_comp.php?VENCIMENTO=".$vencimento1."')\">".$row['quantidade']."</a></td>". "<td >".$row['tipo']."</td><td >".$row['fabricante']." ".$row['modelo']."</td></tr>"; } // while print "<tr><td ><b>".TRANS('COL_OVERALL')."</b></td><td colspan='3'><b>".$tt_garant."</b></td></tr>"; print "</table><br><br>"; print "<TABLE width='80%' align='center'>"; print "<tr><td ></TD></tr>"; print "<tr><td ></TD></tr>"; print "<tr><td ></TD></tr>"; print "<tr><td ></TD></tr>"; print "<tr><td width='80%' align='center'><b>".TRANS('SLOGAN_OCOMON')." <a href='http://www.yip.com.br' target='_blank'>".TRANS('COMPANY')."</a>.</b></td></tr>"; print "</TABLE>"; print "</BODY>"; print "</HTML>"; ?>
danfmsouza/yipservicedesk
invmon/geral/estat_vencimentos_full.php
PHP
gpl-2.0
3,077
<html> <HEAD> <LINK REL="StyleSheet" TYPE="text/css" HREF="exportdetails_item_standard_black.css"></LINK> <META http-equiv="Content-Type" content="text/html; charset=UTF-8"/> <TITLE>Gen 13, Vol. 2 (1995-2002) #15</TITLE> </HEAD> <BODY onload="initPage();"> <div align="center"> <div class="navigation" align="center"> <div class="navigationline"> <div class="navlink" id="first"> <a href="14178.html">First</a> </div> <div class="navlink" id="prev"> <a href="5934.html">Previous</a> </div> <div class="navlink" id="up"> <a href="../index6.html">Up</a> </div> <div class="navlink" id="next"> <a href="5936.html">Next</a> </div> <div class="navlink" id="last"> <a href="23761.html">Last</a> </div> </div> </div> </div> <div id="frontcover"> <a href="../images/5935f.jpg"> <img src="../images/5935f.jpg" class="coverimage"/> </a> </div> <table border="0" class="opacity"> <tr> <td id="maintitle">Gen 13, Vol. 2 (1995-2002)&#160;#15</td> </tr> <tr> <td class="publisher">Image Comics&#160;(Wildstorm)</td> </tr> <tr> <td style="padding-top:4px;">Wanted <br/> <span id="indexvalue">#371</span> <div> <span class="fieldvaluelarge">0* </span> </div> </td> </tr> <tr> <td class="fieldvaluelarge" style="padding-top:7px;">Higher Learning, Part 2</td> </tr> <tr> <td class="fieldvaluelarge" style="padding-top:1px;"> <b>December 1996</b> </td> </tr> <tr> <td class="fieldvaluelarge" style="padding-top:1px;"> <b>Comic</b>&#160; Modern&#160;Age&#160;$2.50</td> </tr> <tr> <td class="fieldvaluelarge" style="padding-top:1px;"> <b>Read It:&#160;Yes</b>&#160;32&#160;Pages</td> </tr> </table> <br style="clear:both;"/> <div> <table border="0" width="100%" style="margin-top:5px;"> <tr> <td valign="top" width="40%"> <div id="productdetails"> <table border="0" cellspacing="0" cellpadding="0" class="opacity"> <tr> <td class="header" colspan="2">Creators</td> </tr> <tr> <td> <tr valign="top"> <td nowrap="1" class="fieldlabel">Writer</td> <td class="fieldvalue">Brandon Choi, Jim Lee, J. Scott Campbell</td> </tr> <tr valign="top"> <td nowrap="1" class="fieldlabel">Penciller</td> <td class="fieldvalue">Al Rio, Luke Ross</td> </tr> <tr valign="top"> <td nowrap="1" class="fieldlabel">Inker</td> <td class="fieldvalue">Sandra Hope</td> </tr> <tr valign="top"> <td nowrap="1" class="fieldlabel">Colorist</td> <td class="fieldvalue">Joe Chiodo</td> </tr> <tr valign="top"> <td nowrap="1" class="fieldlabel">Letterer</td> <td class="fieldvalue">Bill O'Neil</td> </tr> <tr valign="top"> <td nowrap="1" class="fieldlabel">Cover Penciller</td> <td class="fieldvalue">J. Scott Campbell</td> </tr> <tr valign="top"> <td nowrap="1" class="fieldlabel">Cover Inker</td> <td class="fieldvalue">Alex Garner</td> </tr> <tr valign="top"> <td nowrap="1" class="fieldlabel">Editor</td> <td class="fieldvalue">Sarah Becker</td> </tr> <tr valign="top"> <td nowrap="1" class="fieldlabel">Editor In Chief</td> <td class="fieldvalue">Michael Heisler</td> </tr> </td> </tr> </table> </div> </td> <td valign="top"> <div id="productdetails"> <table border="0" cellspacing="0" cellpadding="0" class="opacity"> <tr> <td class="header" colspan="2">Characters</td> </tr> <tr> <td class="character">Burnout (Bobby Lane) <br/>Fairchild (Caitlin Fairchild) <br/>Freefall (Roxanne Spaulding) <br/>Grunge (Percival Edmund Chang) <br/>John Lynch <br/>Rainmaker (Sarah Rainmaker) <br/> </td> </tr> </table> </div> </td> </tr> <tr> <td valign="top"> <p></p> <div id="productdetails"> <table border="0" cellspacing="0" cellpadding="0" class="opacity"> <tr> <td class="header" colspan="2">Product Details</td> </tr> <tr valign="top"> <td class="fieldlabel" width="10%" nowrap="1">Series Group</td> <td class="fieldvalue">Gen 13</td> </tr> <tr valign="top"> <td class="fieldlabel" width="10%" nowrap="1">Genre</td> <td class="fieldvalue">Adventure, Super-Heroes, Action</td> </tr> <tr valign="top"> <td class="fieldlabel" width="10%" nowrap="1">Color</td> <td class="fieldvalue">Color</td> </tr> <tr valign="top"> <td class="fieldlabel" width="10%" nowrap="1">Barcode</td> <td class="fieldvalue">7098530460211</td> </tr> <tr valign="top"> <td class="fieldlabel" width="10%" nowrap="1">Country</td> <td class="fieldvalue">USA</td> </tr> <tr valign="top"> <td class="fieldlabel" width="10%" nowrap="1">Language</td> <td class="fieldvalue">English</td> </tr> <tr valign="top"> <td class="fieldlabel" width="10%" nowrap="1">Release Date</td> <td class="fieldvalue">December 1996</td> </tr> </table> </div> </td> <td valign="top"> <p></p> <div id="personaldetails"> <table border="0" cellspacing="0" cellpadding="0" class="opacity"> <tr> <td class="header" colspan="2">Personal Details</td> </tr> <tr valign="top"> <td class="fieldlabel" width="10%" nowrap="1">Collection Status</td> <td class="fieldvalue">Wanted</td> </tr> <tr valign="top"> <td class="fieldlabel" width="10%" nowrap="1">Links</td> <td class="fieldvalue"> <a href="http://connect.collectorz.com/comics/database/gen-13-vol-2-1995-2002/15-47024" class="link">Gen 13, Vol. 2 (1995-2002) #15 at Comic Collector Connect</a> <br/> </td> </tr> </table> </div> </td> </tr> </table> <p></p> </div> </BODY> </html>
MiniSEC/MiniSEC.github.io
assets/comics/Wishlist/details/5935.html
HTML
gpl-2.0
7,869
/* * Copyright (C) 2013-2015 DeathCore <http://www.noffearrdeathproject.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/>. */ #ifndef DB2STORE_H #define DB2STORE_H #include "DB2FileLoader.h" #include "Common.h" #include "ByteBuffer.h" #include <vector> /// Interface class for common access class DB2StorageBase { public: virtual ~DB2StorageBase() { } uint32 GetHash() const { return tableHash; } virtual bool HasRecord(uint32 id) const = 0; virtual void WriteRecord(uint32 id, uint32 locale, ByteBuffer& buffer) const = 0; protected: uint32 tableHash; }; template<class T> class DB2Storage; template<class T> bool DB2StorageHasEntry(DB2Storage<T> const& store, uint32 id) { return store.LookupEntry(id) != NULL; } template<class T> void WriteDB2RecordToPacket(DB2Storage<T> const& store, uint32 id, uint32 locale, ByteBuffer& buffer) { uint8 const* entry = (uint8 const*)store.LookupEntry(id); ASSERT(entry); std::string format = store.GetFormat(); for (uint32 i = 0; i < format.length(); ++i) { switch (format[i]) { case FT_IND: case FT_INT: buffer << *(uint32*)entry; entry += 4; break; case FT_FLOAT: buffer << *(float*)entry; entry += 4; break; case FT_BYTE: buffer << *(uint8*)entry; entry += 1; break; case FT_STRING: { LocalizedString* locStr = *(LocalizedString**)entry; if (locStr->Str[locale][0] == '\0') locale = 0; char const* str = locStr->Str[locale]; size_t len = strlen(str); buffer << uint16(len); if (len) buffer << str; entry += sizeof(char*); break; } case FT_NA: case FT_SORT: buffer << uint32(0); break; case FT_NA_BYTE: buffer << uint8(0); break; } } } template<class T> class DB2Storage : public DB2StorageBase { typedef std::list<char*> StringPoolList; typedef std::vector<T*> DataTableEx; typedef bool(*EntryChecker)(DB2Storage<T> const&, uint32); typedef void(*PacketWriter)(DB2Storage<T> const&, uint32, uint32, ByteBuffer&); public: DB2Storage(char const* f, EntryChecker checkEntry = NULL, PacketWriter writePacket = NULL) : nCount(0), fieldCount(0), fmt(f), m_dataTable(NULL) { indexTable.asT = NULL; CheckEntry = checkEntry ? checkEntry : (EntryChecker)&DB2StorageHasEntry<T>; WritePacket = writePacket ? writePacket : (PacketWriter)&WriteDB2RecordToPacket<T>; } ~DB2Storage() { Clear(); } bool HasRecord(uint32 id) const { return CheckEntry(*this, id); } T const* LookupEntry(uint32 id) const { return (id >= nCount) ? NULL : indexTable.asT[id]; } uint32 GetNumRows() const { return nCount; } char const* GetFormat() const { return fmt; } uint32 GetFieldCount() const { return fieldCount; } void WriteRecord(uint32 id, uint32 locale, ByteBuffer& buffer) const { WritePacket(*this, id, locale, buffer); } T* CreateEntry(uint32 id, bool evenIfExists = false) { if (evenIfExists && LookupEntry(id)) return NULL; if (id >= nCount) { // reallocate index table char** tmpIdxTable = new char*[id + 1]; memset(tmpIdxTable, 0, (id + 1) * sizeof(char*)); memcpy(tmpIdxTable, indexTable.asChar, nCount * sizeof(char*)); delete[] reinterpret_cast<char*>(indexTable.asT); nCount = id + 1; indexTable.asChar = tmpIdxTable; } T* entryDst = new T; m_dataTableEx.push_back(entryDst); indexTable.asT[id] = entryDst; return entryDst; } void EraseEntry(uint32 id) { indexTable.asT[id] = NULL; } bool Load(char const* fn, uint32 locale) { DB2FileLoader db2; // Check if load was sucessful, only then continue if (!db2.Load(fn, fmt)) return false; fieldCount = db2.GetCols(); tableHash = db2.GetHash(); // load raw non-string data m_dataTable = reinterpret_cast<T*>(db2.AutoProduceData(fmt, nCount, indexTable.asChar)); // create string holders for loaded string fields m_stringPoolList.push_back(db2.AutoProduceStringsArrayHolders(fmt, (char*)m_dataTable)); // load strings from dbc data m_stringPoolList.push_back(db2.AutoProduceStrings(fmt, (char*)m_dataTable, locale)); // error in dbc file at loading if NULL return indexTable.asT != NULL; } bool LoadStringsFrom(char const* fn, uint32 locale) { // DBC must be already loaded using Load if (!indexTable.asT) return false; DB2FileLoader db2; // Check if load was successful, only then continue if (!db2.Load(fn, fmt)) return false; // load strings from another locale dbc data m_stringPoolList.push_back(db2.AutoProduceStrings(fmt, (char*)m_dataTable, locale)); return true; } void Clear() { if (!indexTable.asT) return; delete[] reinterpret_cast<char*>(indexTable.asT); indexTable.asT = NULL; delete[] reinterpret_cast<char*>(m_dataTable); m_dataTable = NULL; for (typename DataTableEx::iterator itr = m_dataTableEx.begin(); itr != m_dataTableEx.end(); ++itr) delete *itr; m_dataTableEx.clear(); while (!m_stringPoolList.empty()) { delete[] m_stringPoolList.front(); m_stringPoolList.pop_front(); } nCount = 0; } EntryChecker CheckEntry; PacketWriter WritePacket; private: uint32 nCount; uint32 fieldCount; char const* fmt; union { T** asT; char** asChar; } indexTable; T* m_dataTable; DataTableEx m_dataTableEx; StringPoolList m_stringPoolList; }; #endif
Stenlibg/4.3.4
src/server/shared/DataStores/DB2Store.h
C
gpl-2.0
6,849
DOUBLE PRECISION FUNCTION DNRM2 ( N, X, INCX ) * .. Scalar Arguments .. INTEGER INCX, N * .. Array Arguments .. DOUBLE PRECISION X( * ) * .. * * DNRM2 returns the euclidean norm of a vector via the function * name, so that * * DNRM2 := sqrt( x'*x ) * * * * -- This version written on 25-October-1982. * Modified on 14-October-1993 to inline the call to DLASSQ. * Sven Hammarling, Nag Ltd. * * * .. Parameters .. DOUBLE PRECISION ONE , ZERO PARAMETER ( ONE = 1.0D+0, ZERO = 0.0D+0 ) * .. Local Scalars .. INTEGER IX DOUBLE PRECISION ABSXI, NORM, SCALE, SSQ * .. Intrinsic Functions .. INTRINSIC ABS, SQRT * .. * .. Executable Statements .. IF( N.LT.1 .OR. INCX.LT.1 )THEN NORM = ZERO ELSE IF( N.EQ.1 )THEN NORM = ABS( X( 1 ) ) ELSE SCALE = ZERO SSQ = ONE * The following loop is equivalent to this call to the LAPACK * auxiliary routine: * CALL DLASSQ( N, X, INCX, SCALE, SSQ ) * DO 10 IX = 1, 1 + ( N - 1 )*INCX, INCX IF( X( IX ).NE.ZERO )THEN ABSXI = ABS( X( IX ) ) IF( SCALE.LT.ABSXI )THEN SSQ = ONE + SSQ*( SCALE/ABSXI )**2 SCALE = ABSXI ELSE SSQ = SSQ + ( ABSXI/SCALE )**2 END IF END IF 10 CONTINUE NORM = SCALE * SQRT( SSQ ) END IF * DNRM2 = NORM RETURN * * End of DNRM2. * END
aarestad/gradschool-stuff
clocc/src/f2cl/packages/blas/dnrm2.f
FORTRAN
gpl-2.0
1,657
<?php require_once 'PHPUnit/Framework/TestCase.php'; require_once 'PHPUnit/Util/Filter.php'; require_once dirname(__FILE__) . '/constraints/image.php'; require_once dirname(__FILE__) . '/../src/image.php'; require_once dirname(__FILE__) . '/../src/imageGD.php'; require_once dirname(__FILE__) . '/../src/imageGmagick.php'; require_once dirname(__FILE__) . '/../src/imageImagick.php'; require_once dirname(__FILE__) . '/../src/imagePlaceholder.php'; //PHPUnit_Util_Filter::addFileToFilter(__FILE__, 'PHPUNIT'); define('TEST_BACKGROUND', dirname(__FILE__) . '/files/blank.jpg'); define('TEST_FOREGROUND', dirname(__FILE__) . '/files/a.png'); abstract class MyTestCase extends PHPUnit_Framework_TestCase { /** * Asserts that the compared images are same * * Uses the compare binary of the imagemagick package to compare to images * and will fail if the difference between two images is higher then zero. * * @param string $image New image * @param string $expectedImage Image to compare with * @param string $message Message to append to the fail message * @access public * @return void */ public function assertImageSame( $expectedImage, $image, $message = '' ) { if ($image instanceof Image) $image = $image->toFile(); if ($expectedImage instanceof Image) $expectedImage = $expectedImage->toFile(); $constraint = new ezcTestConstraintSimilarImage( $expectedImage ); self::assertThat( $image, $constraint, $message ); } public function assertImageNotSame( $expectedImage, $image, $message = '' ) { if ($image instanceof Image) $image = $image->toFile(); if ($expectedImage instanceof Image) $expectedImage = $expectedImage->toFile(); $constraint = new ezcTestConstraintSimilarImage( $expectedImage ); self::assertThat( $image, $this->logicalNot($constraint), $message ); } /** * Asserts that the compared images are similar * * Uses the compare binary of the imagemagick package to compare to images * and will fail if the difference between two images is higher then the * defined value. * * See http://www.imagemagick.org/script/compare.php for details. The * difference is logarithmical scaled. * * @param string $image New image * @param string $expectedImage Image to compare with * @param string $message Message to append to the fail message * @param int $maxDifference Maximum difference between images * @access public * @return void */ public function assertImageSimilar( $expectedImage, $image, $message = '', $maxDifference = 0 ) { $constraint = new ezcTestConstraintSimilarImage( $expectedImage, $maxDifference ); self::assertThat( $image, $constraint, $message ); } public function assertImageSize($expectedImageSize, Image $image, $message = '') { list($width, $height) = explode('x', $expectedImageSize); $size = $image->getWidth() . 'x' . $image->getHeight(); self::assertThat($height, $this->equalTo($image->getHeight()), "Incorrect height (Size is $size)\n" . $message ); self::assertThat($width, $this->equalTo($image->getWidth()), "Incorrect width (Size is $size)\n" . $message ); } }
benjaminpick/yaial
tests/MyTestCase.php
PHP
gpl-2.0
3,242
<? $sub_menu = "300100"; include_once('./_common.php'); if ($w == 'u') check_demo(); auth_check($auth[$sub_menu], 'w'); if ($_POST['admin_password']) { if ($member['mb_password'] != sql_password($_POST['admin_password'])) { alert('관리자 패스워드가 틀립니다.'); } } else { alert('관리자 패스워드를 입력하세요.'); } if (!$_POST['gr_id']) { alert('그룹 ID는 반드시 선택하세요.'); } if (!$bo_table) { alert('게시판 TABLE명은 반드시 입력하세요.'); } if (!preg_match("/^([A-Za-z0-9_]{1,20})$/", $bo_table)) { alert('게시판 TABLE명은 공백없이 영문자, 숫자, _ 만 사용 가능합니다. (20자 이내)'); } if (!$_POST['bo_subject']) { alert('게시판 제목을 입력하세요.'); } if ($file = $_POST['bo_include_head']) { if (!preg_match("/\.(php|htm['l']?)$/i", $file)) { alert('상단 파일 경로가 php, html 파일이 아닙니다.'); } } if ($file = $_POST['bo_include_tail']) { if (!preg_match("/\.(php|htm['l']?)$/i", $file)) { alert('하단 파일 경로가 php, html 파일이 아닙니다.'); } } $board_path = G4_DATA_PATH.'/file/'.$bo_table; // 게시판 디렉토리 생성 @mkdir($board_path, 0707); @chmod($board_path, 0707); // 디렉토리에 있는 파일의 목록을 보이지 않게 한다. $file = $board_path . '/index.php'; $f = @fopen($file, 'w'); @fwrite($f, ''); @fclose($f); @chmod($file, 0606); // 분류에 & 나 = 는 사용이 불가하므로 2바이트로 바꾼다. $src_char = array('&', '='); $dst_char = array('&', '〓'); $bo_category_list = str_replace($src_char, $dst_char, $bo_category_list); $sql_common = " gr_id = '{$_POST['gr_id']}', bo_subject = '{$_POST['bo_subject']}', bo_device = '{$_POST['bo_device']}', bo_admin = '{$_POST['bo_admin']}', bo_list_level = '{$_POST['bo_list_level']}', bo_read_level = '{$_POST['bo_read_level']}', bo_write_level = '{$_POST['bo_write_level']}', bo_reply_level = '{$_POST['bo_reply_level']}', bo_comment_level = '{$_POST['bo_comment_level']}', bo_html_level = '{$_POST['bo_html_level']}', bo_link_level = '{$_POST['bo_link_level']}', bo_count_modify = '{$_POST['bo_count_modify']}', bo_count_delete = '{$_POST['bo_count_delete']}', bo_upload_level = '{$_POST['bo_upload_level']}', bo_download_level = '{$_POST['bo_download_level']}', bo_read_point = '{$_POST['bo_read_point']}', bo_write_point = '{$_POST['bo_write_point']}', bo_comment_point = '{$_POST['bo_comment_point']}', bo_download_point = '{$_POST['bo_download_point']}', bo_use_category = '{$_POST['bo_use_category']}', bo_category_list = '{$_POST['bo_category_list']}', bo_use_sideview = '{$_POST['bo_use_sideview']}', bo_use_file_content = '{$_POST['bo_use_file_content']}', bo_use_secret = '{$_POST['bo_use_secret']}', bo_use_dhtml_editor = '{$_POST['bo_use_dhtml_editor']}', bo_use_rss_view = '{$_POST['bo_use_rss_view']}', bo_use_good = '{$_POST['bo_use_good']}', bo_use_nogood = '{$_POST['bo_use_nogood']}', bo_use_name = '{$_POST['bo_use_name']}', bo_use_signature = '{$_POST['bo_use_signature']}', bo_use_ip_view = '{$_POST['bo_use_ip_view']}', bo_use_list_view = '{$_POST['bo_use_list_view']}', bo_use_list_content = '{$_POST['bo_use_list_content']}', bo_use_email = '{$_POST['bo_use_email']}', bo_table_width = '{$_POST['bo_table_width']}', bo_subject_len = '{$_POST['bo_subject_len']}', bo_page_rows = '{$_POST['bo_page_rows']}', bo_new = '{$_POST['bo_new']}', bo_hot = '{$_POST['bo_hot']}', bo_image_width = '{$_POST['bo_image_width']}', bo_skin = '{$_POST['bo_skin']}', bo_include_head = '{$_POST['bo_include_head']}', bo_include_tail = '{$_POST['bo_include_tail']}', bo_content_head = '{$_POST['bo_content_head']}', bo_content_tail = '{$_POST['bo_content_tail']}', bo_insert_content = '{$_POST['bo_insert_content']}', bo_gallery_cols = '{$_POST['bo_gallery_cols']}', bo_upload_count = '{$_POST['bo_upload_count']}', bo_upload_size = '{$_POST['bo_upload_size']}', bo_reply_order = '{$_POST['bo_reply_order']}', bo_use_search = '{$_POST['bo_use_search']}', bo_order_search = '{$_POST['bo_order_search']}', bo_write_min = '{$_POST['bo_write_min']}', bo_write_max = '{$_POST['bo_write_max']}', bo_comment_min = '{$_POST['bo_comment_min']}', bo_comment_max = '{$_POST['bo_comment_max']}', bo_sort_field = '{$_POST['bo_sort_field']}', bo_1_subj = '{$_POST['bo_1_subj']}', bo_2_subj = '{$_POST['bo_2_subj']}', bo_3_subj = '{$_POST['bo_3_subj']}', bo_4_subj = '{$_POST['bo_4_subj']}', bo_5_subj = '{$_POST['bo_5_subj']}', bo_6_subj = '{$_POST['bo_6_subj']}', bo_7_subj = '{$_POST['bo_7_subj']}', bo_8_subj = '{$_POST['bo_8_subj']}', bo_9_subj = '{$_POST['bo_9_subj']}', bo_10_subj = '{$_POST['bo_10_subj']}', bo_1 = '{$_POST['bo_1']}', bo_2 = '{$_POST['bo_2']}', bo_3 = '{$_POST['bo_3']}', bo_4 = '{$_POST['bo_4']}', bo_5 = '{$_POST['bo_5']}', bo_6 = '{$_POST['bo_6']}', bo_7 = '{$_POST['bo_7']}', bo_8 = '{$_POST['bo_8']}', bo_9 = '{$_POST['bo_9']}', bo_10 = '{$_POST['bo_10']}' "; if ($w == '') { $row = sql_fetch(" select count(*) as cnt from {$g4['board_table']} where bo_table = '{$bo_table}' "); if ($row['cnt']) alert($bo_table.' 은(는) 이미 존재하는 TABLE 입니다.'); $sql = " insert into {$g4['board_table']} set bo_table = '{$bo_table}', bo_count_write = '0', bo_count_comment = '0', $sql_common "; sql_query($sql); // 게시판 테이블 생성 $file = file('./sql_write.sql'); $sql = implode($file, "\n"); $create_table = $g4['write_prefix'] . $bo_table; // sql_board.sql 파일의 테이블명을 변환 $source = array('/__TABLE_NAME__/', '/;/'); $target = array($create_table, ''); $sql = preg_replace($source, $target, $sql); sql_query($sql, FALSE); } else if ($w == 'u') { // 게시판의 글 수 $sql = " select count(*) as cnt from {$g4['write_prefix']}{$bo_table} where wr_is_comment = 0 "; $row = sql_fetch($sql); $bo_count_write = $row['cnt']; // 게시판의 코멘트 수 $sql = " select count(*) as cnt from {$g4['write_prefix']}{$bo_table} where wr_is_comment = 1 "; $row = sql_fetch($sql); $bo_count_comment = $row['cnt']; // 글수 조정 if (isset($_POST['proc_count'])) { // 원글을 얻습니다. $sql = " select wr_id from {$g4['write_prefix']}{$bo_table} where wr_is_comment = 0 "; $result = sql_query($sql); for ($i=0; $row=sql_fetch_array($result); $i++) { // 코멘트수를 얻습니다. $sql2 = " select count(*) as cnt from {$g4['write_prefix']}$bo_table where wr_parent = '{$row['wr_id']}' and wr_is_comment = 1 "; $row2 = sql_fetch($sql2); sql_query(" update {$g4['write_prefix']}{$bo_table} set wr_comment = '{$row2['cnt']}' where wr_id = '{$row['wr_id']}' "); } } // 공지사항에는 등록되어 있지만 실제 존재하지 않는 글 아이디는 삭제합니다. $bo_notice = ""; $lf = ""; if ($board['bo_notice']) { $tmp_array = explode("\n", $board['bo_notice']); for ($i=0; $i<count($tmp_array); $i++) { $tmp_wr_id = trim($tmp_array[$i]); $row = sql_fetch(" select count(*) as cnt from {$g4['write_prefix']}{$bo_table} where wr_id = '{$tmp_wr_id}' "); if ($row['cnt']) { $bo_notice .= $lf . $tmp_wr_id; $lf = "\n"; } } } $sql = " update {$g4['board_table']} set bo_notice = '{$bo_notice}', bo_count_write = '{$bo_count_write}', bo_count_comment = '{$bo_count_comment}', {$sql_common} where bo_table = '{$bo_table}' "; sql_query($sql); } // 같은 그룹내 게시판 동일 옵션 적용 $fields = ""; if (is_checked('chk_use')) $fields .= " , bo_use = '{$bo_use}' "; if (is_checked('chk_admin')) $fields .= " , bo_admin = '{$bo_admin}' "; if (is_checked('chk_list_level')) $fields .= " , bo_list_level = '{$bo_list_level}' "; if (is_checked('chk_read_level')) $fields .= " , bo_read_level = '{$bo_read_level}' "; if (is_checked('chk_write_level')) $fields .= " , bo_write_level = '{$bo_write_level}' "; if (is_checked('chk_reply_level')) $fields .= " , bo_reply_level = '{$bo_reply_level}' "; if (is_checked('chk_comment_level')) $fields .= " , bo_comment_level = '{$bo_comment_level}' "; if (is_checked('chk_link_level')) $fields .= " , bo_link_level = '{$bo_link_level}' "; if (is_checked('chk_upload_level')) $fields .= " , bo_upload_level = '{$bo_upload_level}' "; if (is_checked('chk_download_level')) $fields .= " , bo_download_level = '{$bo_download_level}' "; if (is_checked('chk_html_level')) $fields .= " , bo_html_level = '{$bo_html_level}' "; if (is_checked('chk_count_modify')) $fields .= " , bo_count_modify = '{$bo_count_modify}' "; if (is_checked('chk_count_delete')) $fields .= " , bo_count_delete = '{$bo_count_delete}' "; if (is_checked('chk_read_point')) $fields .= " , bo_read_point = '{$bo_read_point}' "; if (is_checked('chk_write_point')) $fields .= " , bo_write_point = '{$bo_write_point}' "; if (is_checked('chk_comment_point')) $fields .= " , bo_comment_point = '{$bo_comment_point}' "; if (is_checked('chk_download_point')) $fields .= " , bo_download_point = '{$bo_download_point}' "; if (is_checked('chk_category_list')) { $fields .= " , bo_category_list = '{$bo_category_list}' "; $fields .= " , bo_use_category = '{$bo_use_category}' "; } if (is_checked('chk_use_sideview')) $fields .= " , bo_use_sideview = '{$bo_use_sideview}' "; if (is_checked('chk_use_file_content')) $fields .= " , bo_use_file_content = '{$bo_use_file_content}' "; if (is_checked('chk_use_secret')) $fields .= " , bo_use_secret = '{$bo_use_secret}' "; if (is_checked('chk_use_dhtml_editor')) $fields .= " , bo_use_dhtml_editor = '{$bo_use_dhtml_editor}' "; if (is_checked('chk_use_rss_view')) $fields .= " , bo_use_rss_view = '{$bo_use_rss_view}' "; if (is_checked('chk_use_good')) $fields .= " , bo_use_good = '{$bo_use_good}' "; if (is_checked('chk_use_nogood')) $fields .= " , bo_use_nogood = '{$bo_use_nogood}' "; if (is_checked('chk_use_name')) $fields .= " , bo_use_name = '{$bo_use_name}' "; if (is_checked('chk_use_signature')) $fields .= " , bo_use_signature = '{$bo_use_signature}' "; if (is_checked('chk_use_ip_view')) $fields .= " , bo_use_ip_view = '{$bo_use_ip_view}' "; if (is_checked('chk_use_list_view')) $fields .= " , bo_use_list_view = '{$bo_use_list_view}' "; if (is_checked('chk_use_list_content')) $fields .= " , bo_use_list_content = '{$bo_use_list_content}' "; if (is_checked('chk_use_email')) $fields .= " , bo_use_email = '{$bo_use_email}' "; if (is_checked('chk_skin')) $fields .= " , bo_skin = '{$bo_skin}' "; if (is_checked('chk_gallery_cols')) $fields .= " , bo_gallery_cols = '{$bo_gallery_cols}' "; if (is_checked('chk_table_width')) $fields .= " , bo_table_width = '{$bo_table_width}' "; if (is_checked('chk_page_rows')) $fields .= " , bo_page_rows = '{$bo_page_rows}' "; if (is_checked('chk_subject_len')) $fields .= " , bo_subject_len = '{$bo_subject_len}' "; if (is_checked('chk_new')) $fields .= " , bo_new = '{$bo_new}' "; if (is_checked('chk_hot')) $fields .= " , bo_hot = '{$bo_hot}' "; if (is_checked('chk_image_width')) $fields .= " , bo_image_width = '{$bo_image_width}' "; if (is_checked('chk_reply_order')) $fields .= " , bo_reply_order = '{$bo_reply_order}' "; if (is_checked('chk_sort_field')) $fields .= " , bo_sort_field = '{$bo_sort_field}' "; if (is_checked('chk_write_min')) $fields .= " , bo_write_min = '{$bo_write_min}' "; if (is_checked('chk_write_max')) $fields .= " , bo_write_max = '{$bo_write_max}' "; if (is_checked('chk_comment_min')) $fields .= " , bo_comment_min = '{$bo_comment_min}' "; if (is_checked('chk_comment_max')) $fields .= " , bo_comment_max = '{$bo_comment_max}' "; if (is_checked('chk_upload_count')) $fields .= " , bo_upload_count = '{$bo_upload_count}' "; if (is_checked('chk_upload_size')) $fields .= " , bo_upload_size = '{$bo_upload_size}' "; if (is_checked('chk_include_head')) $fields .= " , bo_include_head = '{$bo_include_head}' "; if (is_checked('chk_include_tail')) $fields .= " , bo_include_tail = '{$bo_include_tail}' "; if (is_checked('chk_content_head')) $fields .= " , bo_content_head = '{$bo_content_head}' "; if (is_checked('chk_content_tail')) $fields .= " , bo_content_tail = '{$bo_content_tail}' "; if (is_checked('chk_insert_content')) $fields .= " , bo_insert_content = '{$bo_insert_content}' "; if (is_checked('chk_use_search')) $fields .= " , bo_use_search = '{$bo_use_search}' "; if (is_checked('chk_order_search')) $fields .= " , bo_order_search = '{$bo_order_search}' "; for ($i=1; $i<=10; $i++) { if (is_checked('chk_'.$i)) { $fields .= " , bo_{$i}_subj = '".$_POST['bo_'.$i.'_subj']."' "; $fields .= " , bo_{$i} = '".$_POST['bo_'.$i]."' "; } } if ($fields) { $sql = " update {$g4['board_table']} set bo_table = bo_table {$fields} where gr_id = '$gr_id' "; sql_query($sql); } delete_cache_latest($bo_table); goto_url("./board_form.php?w=u&bo_table={$bo_table}&amp;{$qstr}"); ?>
gnuboard/sanso
adm/board_form_update.php
PHP
gpl-2.0
15,251
/*------------------------------------------------------------------------------ Copyright 2012 Sony Corporation Last Updated : $Date:: 2012-06-12 13:06:10 #$ File Revision : $Revision:: 5540 $ ------------------------------------------------------------------------------*/ #include <linux/types.h> #include <linux/init.h> #include <linux/kernel.h> #include <linux/module.h> #include <linux/string.h> #include <linux/delay.h> #include "sony_common.h" #include "sony_demod.h" #include "sony_integ.h" #include "mxl603/MxL603_TunerApi.h" /*------------------------------------------------------------------------------ Functions ------------------------------------------------------------------------------*/ sony_result_t sony_integ_Create (sony_integ_t * pInteg, sony_demod_xtal_t xtalFreq, uint8_t i2cAddress, sony_i2c_t * pDemodI2c, sony_demod_t * pDemod #ifdef SONY_DEMOD_SUPPORT_TERR_OR_CABLE ,sony_tuner_terr_cable_t * pTunerTerrCable #endif #ifdef SONY_DEMOD_SUPPORT_DVBS_S2 ,sony_tuner_sat_t * pTunerSat, sony_lnbc_t * pLnbc #endif ) { sony_result_t result = SONY_RESULT_OK; SONY_TRACE_ENTER ("sony_integ_Create"); if ((!pInteg) || (!pDemodI2c) || (!pDemod)) { SONY_TRACE_RETURN (SONY_RESULT_ERROR_ARG); } /* Create demodulator instance */ result = sony_demod_Create (pDemod, xtalFreq, i2cAddress, pDemodI2c); if (result != SONY_RESULT_OK) { SONY_TRACE_RETURN (result); } /* Populate the integration structure */ pInteg->pDemod = pDemod; #ifdef SONY_DEMOD_SUPPORT_TERR_OR_CABLE pInteg->pTunerTerrCable = pTunerTerrCable; #endif #ifdef SONY_DEMOD_SUPPORT_DVBS_S2 pInteg->pTunerSat = pTunerSat; pInteg->pLnbc = pLnbc; #endif sony_atomic_set (&(pInteg->cancel), 0); SONY_TRACE_RETURN (result); } #ifdef SONY_DEMOD_SUPPORT_TERR_OR_CABLE sony_result_t sony_integ_InitializeT_C (sony_integ_t * pInteg) { sony_result_t result = SONY_RESULT_OK; SONY_TRACE_ENTER ("sony_integ_InitializeT_C"); if ((!pInteg) || (!pInteg->pDemod)) { SONY_TRACE_RETURN (SONY_RESULT_ERROR_ARG); } result = sony_demod_InitializeT_C (pInteg->pDemod); if (result != SONY_RESULT_OK) { SONY_TRACE_RETURN (result); } #ifndef SONY_DISABLE_I2C_REPEATER /* Enable the I2C repeater */ result = sony_demod_I2cRepeaterEnable (pInteg->pDemod, 0x01); if (result != SONY_RESULT_OK) { SONY_TRACE_RETURN (result); } #endif #ifdef CONFIG_TH_CXD2837_TUNER_MXL603 MXL603_INIT(); #else if ((pInteg->pTunerTerrCable) && (pInteg->pTunerTerrCable->Initialize)) { /* Initialize the terrestrial / cable tuner. */ result = pInteg->pTunerTerrCable->Initialize (pInteg->pTunerTerrCable); if (result != SONY_RESULT_OK) { printk("turner iinitialize error\n"); SONY_TRACE_RETURN (result); } } #endif #ifdef SONY_DEMOD_SUPPORT_DVBS_S2 if ((pInteg->pTunerSat) && (pInteg->pTunerSat->Initialize)) { /* Initialize the satellite tuner. */ result = pInteg->pTunerSat->Initialize (pInteg->pTunerSat); if (result != SONY_RESULT_OK) { SONY_TRACE_RETURN (result); } } #endif #ifndef SONY_DISABLE_I2C_REPEATER /* Disable the I2C repeater */ result = sony_demod_I2cRepeaterEnable (pInteg->pDemod, 0x00); if (result != SONY_RESULT_OK) { SONY_TRACE_RETURN (result); } #endif #ifdef SONY_DEMOD_SUPPORT_DVBS_S2 if ((pInteg->pLnbc) && (pInteg->pLnbc->Initialize)) { /* Initialize the lnb controller. */ result = pInteg->pLnbc->Initialize (pInteg->pLnbc); if (result != SONY_RESULT_OK) { SONY_TRACE_RETURN (result); } } if ((pInteg->pLnbc) && (pInteg->pLnbc->Sleep)) { /* Sleep the lnb controller */ result = pInteg->pLnbc->Sleep (pInteg->pLnbc); if (result != SONY_RESULT_OK) { SONY_TRACE_RETURN (result); } } #endif SONY_TRACE_RETURN (result); } #endif #ifdef SONY_DEMOD_SUPPORT_DVBS_S2 sony_result_t sony_integ_InitializeS (sony_integ_t * pInteg) { sony_result_t result = SONY_RESULT_OK; SONY_TRACE_ENTER ("sony_integ_InitializeS"); if ((!pInteg) || (!pInteg->pDemod)) { SONY_TRACE_RETURN (SONY_RESULT_ERROR_ARG); } result = sony_demod_InitializeS (pInteg->pDemod); if (result != SONY_RESULT_OK) { SONY_TRACE_RETURN (result); } #ifndef SONY_DISABLE_I2C_REPEATER /* Enable the I2C repeater */ result = sony_demod_I2cRepeaterEnable (pInteg->pDemod, 0x01); if (result != SONY_RESULT_OK) { SONY_TRACE_RETURN (result); } #endif #ifdef SONY_DEMOD_SUPPORT_TERR_OR_CABLE if ((pInteg->pTunerTerrCable) && (pInteg->pTunerTerrCable->Initialize)) { /* Initialize the terrestrial / cable tuner. */ result = pInteg->pTunerTerrCable->Initialize (pInteg->pTunerTerrCable); if (result != SONY_RESULT_OK) { SONY_TRACE_RETURN (result); } } #endif if ((pInteg->pTunerSat) && (pInteg->pTunerSat->Initialize)) { /* Initialize the satellite tuner. */ result = pInteg->pTunerSat->Initialize (pInteg->pTunerSat); if (result != SONY_RESULT_OK) { SONY_TRACE_RETURN (result); } } #ifndef SONY_DISABLE_I2C_REPEATER /* Disable the I2C repeater */ result = sony_demod_I2cRepeaterEnable (pInteg->pDemod, 0x00); if (result != SONY_RESULT_OK) { SONY_TRACE_RETURN (result); } #endif if ((pInteg->pLnbc) && (pInteg->pLnbc->Initialize)) { /* Initialize the lnb controller. */ result = pInteg->pLnbc->Initialize (pInteg->pLnbc); if (result != SONY_RESULT_OK) { SONY_TRACE_RETURN (result); } } SONY_TRACE_RETURN (result); } #endif #ifdef SONY_DEMOD_SUPPORT_TERR_OR_CABLE sony_result_t sony_integ_SleepT_C (sony_integ_t * pInteg) { sony_result_t result = SONY_RESULT_OK; SONY_TRACE_ENTER ("sony_integ_SleepT_C"); if ((!pInteg) || (!pInteg->pDemod)) { SONY_TRACE_RETURN (SONY_RESULT_ERROR_ARG); } if ((pInteg->pDemod->state != SONY_DEMOD_STATE_SLEEP_T_C) && (pInteg->pDemod->state != SONY_DEMOD_STATE_SLEEP_S) && (pInteg->pDemod->state != SONY_DEMOD_STATE_ACTIVE_T_C) && (pInteg->pDemod->state != SONY_DEMOD_STATE_ACTIVE_S) && (pInteg->pDemod->state != SONY_DEMOD_STATE_SHUTDOWN)) { /* This api is accepted in SLEEP, ACTIVE and SHUTDOWN states only */ SONY_TRACE_RETURN (SONY_RESULT_ERROR_SW_STATE); } #ifndef SONY_DISABLE_I2C_REPEATER /* Enable the I2C repeater */ result = sony_demod_I2cRepeaterEnable (pInteg->pDemod, 0x01); if (result != SONY_RESULT_OK) { SONY_TRACE_RETURN (result); } #endif #ifdef CONFIG_TH_CXD2837_TUNER_MXL603 #else if ((pInteg->pTunerTerrCable) && (pInteg->pTunerTerrCable->Sleep)) { /* Call the terrestrial / cable tuner Sleep implementation */ result = pInteg->pTunerTerrCable->Sleep (pInteg->pTunerTerrCable); if (result != SONY_RESULT_OK) { SONY_TRACE_RETURN (result); } } #endif #ifdef SONY_DEMOD_SUPPORT_DVBS_S2 if ((pInteg->pTunerSat) && (pInteg->pTunerSat->Sleep)) { /* Call the satellite tuner Sleep implementation */ result = pInteg->pTunerSat->Sleep (pInteg->pTunerSat); if (result != SONY_RESULT_OK) { SONY_TRACE_RETURN (result); } } #endif #ifndef SONY_DISABLE_I2C_REPEATER /* Disable the I2C repeater */ result = sony_demod_I2cRepeaterEnable (pInteg->pDemod, 0x00); if (result != SONY_RESULT_OK) { SONY_TRACE_RETURN (result); } #endif #ifdef SONY_DEMOD_SUPPORT_DVBS_S2 if ((pInteg->pLnbc) && (pInteg->pLnbc->Sleep)) { /* Sleep the lnb controller. */ result = pInteg->pLnbc->Sleep (pInteg->pLnbc); if (result != SONY_RESULT_OK) { SONY_TRACE_RETURN (result); } } #endif /* Call the demodulator Sleep function for DVB-C / C2 / T / T2 */ result = sony_demod_SleepT_C (pInteg->pDemod); if (result != SONY_RESULT_OK) { SONY_TRACE_RETURN (result); } SONY_TRACE_RETURN (result); } #endif #ifdef SONY_DEMOD_SUPPORT_DVBS_S2 sony_result_t sony_integ_SleepS (sony_integ_t * pInteg) { sony_result_t result = SONY_RESULT_OK; SONY_TRACE_ENTER ("sony_integ_SleepS"); if ((!pInteg) || (!pInteg->pDemod)) { SONY_TRACE_RETURN (SONY_RESULT_ERROR_ARG); } if ((pInteg->pDemod->state != SONY_DEMOD_STATE_SLEEP_T_C) && (pInteg->pDemod->state != SONY_DEMOD_STATE_SLEEP_S) && (pInteg->pDemod->state != SONY_DEMOD_STATE_ACTIVE_T_C) && (pInteg->pDemod->state != SONY_DEMOD_STATE_ACTIVE_S) && (pInteg->pDemod->state != SONY_DEMOD_STATE_SHUTDOWN)) { /* This api is accepted in SLEEP, ACTIVE and SHUTDOWN states only */ SONY_TRACE_RETURN (SONY_RESULT_ERROR_SW_STATE); } #ifndef SONY_DISABLE_I2C_REPEATER /* Enable the I2C repeater */ result = sony_demod_I2cRepeaterEnable (pInteg->pDemod, 0x01); if (result != SONY_RESULT_OK) { SONY_TRACE_RETURN (result); } #endif #ifdef SONY_DEMOD_SUPPORT_TERR_OR_CABLE if ((pInteg->pTunerTerrCable) && (pInteg->pTunerTerrCable->Sleep)) { /* Call the terrestrial / cable tuner Sleep implementation */ result = pInteg->pTunerTerrCable->Sleep (pInteg->pTunerTerrCable); if (result != SONY_RESULT_OK) { SONY_TRACE_RETURN (result); } } #endif if ((pInteg->pTunerSat) && (pInteg->pTunerSat->Sleep)) { /* Call the satellite tuner Sleep implementation */ result = pInteg->pTunerSat->Sleep (pInteg->pTunerSat); if (result != SONY_RESULT_OK) { SONY_TRACE_RETURN (result); } } #ifndef SONY_DISABLE_I2C_REPEATER /* Disable the I2C repeater */ result = sony_demod_I2cRepeaterEnable (pInteg->pDemod, 0x00); if (result != SONY_RESULT_OK) { SONY_TRACE_RETURN (result); } #endif if ((pInteg->pLnbc) && (pInteg->pLnbc->WakeUp)) { /* Call the lnb controller WakeUp implementation. */ result = pInteg->pLnbc->WakeUp (pInteg->pLnbc); if (result != SONY_RESULT_OK) { SONY_TRACE_RETURN (result); } } /* Call the demodulator Sleep function for DVB-S / S2 */ result = sony_demod_SleepS (pInteg->pDemod); if (result != SONY_RESULT_OK) { SONY_TRACE_RETURN (result); } SONY_TRACE_RETURN (result); } #endif sony_result_t sony_integ_Shutdown (sony_integ_t * pInteg) { sony_result_t result = SONY_RESULT_OK; SONY_TRACE_ENTER ("sony_integ_Shutdown"); if ((!pInteg) || (!pInteg->pDemod)) { SONY_TRACE_RETURN (SONY_RESULT_ERROR_ARG); } if ((pInteg->pDemod->state != SONY_DEMOD_STATE_SLEEP_T_C) && (pInteg->pDemod->state != SONY_DEMOD_STATE_SLEEP_S) && (pInteg->pDemod->state != SONY_DEMOD_STATE_ACTIVE_T_C) && (pInteg->pDemod->state != SONY_DEMOD_STATE_ACTIVE_S) && (pInteg->pDemod->state != SONY_DEMOD_STATE_SHUTDOWN)) { /* This api is accepted in SLEEP, ACTIVE and SHUTDOWN states only */ SONY_TRACE_RETURN (SONY_RESULT_ERROR_SW_STATE); } #ifndef SONY_DISABLE_I2C_REPEATER /* Enable the I2C repeater */ result = sony_demod_I2cRepeaterEnable (pInteg->pDemod, 0x01); if (result != SONY_RESULT_OK) { SONY_TRACE_RETURN (result); } #endif #ifdef SONY_DEMOD_SUPPORT_TERR_OR_CABLE if ((pInteg->pTunerTerrCable) && (pInteg->pTunerTerrCable->Shutdown)) { /* Call the terrestrial / cable tuner Shutdown implementation */ result = pInteg->pTunerTerrCable->Shutdown (pInteg->pTunerTerrCable); if (result != SONY_RESULT_OK) { SONY_TRACE_RETURN (result); } } #endif #ifdef SONY_DEMOD_SUPPORT_DVBS_S2 if ((pInteg->pTunerSat) && (pInteg->pTunerSat->Shutdown)) { /* Call the satellite tuner Shutdown implementation */ result = pInteg->pTunerSat->Shutdown (pInteg->pTunerSat); if (result != SONY_RESULT_OK) { SONY_TRACE_RETURN (result); } } #endif #ifndef SONY_DISABLE_I2C_REPEATER /* Disable the I2C repeater */ result = sony_demod_I2cRepeaterEnable (pInteg->pDemod, 0x00); if (result != SONY_RESULT_OK) { SONY_TRACE_RETURN (result); } #endif #ifdef SONY_DEMOD_SUPPORT_DVBS_S2 if ((pInteg->pLnbc) && (pInteg->pLnbc->Sleep)) { /* Sleep the lnb controller. */ result = pInteg->pLnbc->Sleep (pInteg->pLnbc); if (result != SONY_RESULT_OK) { SONY_TRACE_RETURN (result); } } #endif /* Call the demodulator Shutdown function */ result = sony_demod_Shutdown (pInteg->pDemod); if (result != SONY_RESULT_OK) { SONY_TRACE_RETURN (result); } SONY_TRACE_RETURN (result); } sony_result_t sony_integ_Cancel (sony_integ_t * pInteg) { SONY_TRACE_ENTER ("sony_integ_Cancel"); /* Argument verification. */ if ((!pInteg)) { SONY_TRACE_RETURN (SONY_RESULT_ERROR_ARG); } /* Set the cancellation flag. */ sony_atomic_set (&(pInteg->cancel), 1); SONY_TRACE_RETURN (SONY_RESULT_OK); }
EPDCenter/android_kernel_amlogic_s805_3go_aplay2
drivers/amlogic/dvb_tv/cxd2837/sony_integ.c
C
gpl-2.0
13,890
package com.wernicke.utils; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.io.UnsupportedEncodingException; import java.util.List; import org.apache.http.HttpEntity; import org.apache.http.HttpResponse; import org.apache.http.NameValuePair; import org.apache.http.client.ClientProtocolException; import org.apache.http.client.entity.UrlEncodedFormEntity; import org.apache.http.client.methods.HttpGet; import org.apache.http.client.methods.HttpPost; import org.apache.http.client.utils.URLEncodedUtils; import org.apache.http.impl.client.DefaultHttpClient; import org.json.JSONException; import org.json.JSONObject; import android.util.Log; public class JSONParser { static InputStream is = null; static JSONObject jObj = null; static String json = ""; // constructor public JSONParser() { } // function get json from url // by making HTTP POST or GET mehtod public JSONObject makeHttpRequest(String url, String method, List<NameValuePair> params) { // Making HTTP request try { // check for request method if (method == "POST") { // request method is POST // defaultHttpClient DefaultHttpClient httpClient = new DefaultHttpClient(); HttpPost httpPost = new HttpPost(url); UrlEncodedFormEntity uefe = new UrlEncodedFormEntity(params); httpPost.setEntity(uefe); HttpResponse httpResponse = httpClient.execute(httpPost); HttpEntity httpEntity = httpResponse.getEntity(); is = httpEntity.getContent(); } else if (method == "GET") { // request method is GET DefaultHttpClient httpClient = new DefaultHttpClient(); String paramString = URLEncodedUtils.format(params, "utf-8"); url += "?" + paramString; HttpGet httpGet = new HttpGet(url); HttpResponse httpResponse = httpClient.execute(httpGet); HttpEntity httpEntity = httpResponse.getEntity(); is = httpEntity.getContent(); } } catch (UnsupportedEncodingException e) { e.printStackTrace(); } catch (ClientProtocolException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } try { BufferedReader reader = new BufferedReader(new InputStreamReader(is, "iso-8859-1"), 8); StringBuilder sb = new StringBuilder(); String line = null; while ((line = reader.readLine()) != null) { sb.append(line + "\n"); } is.close(); json = sb.toString(); } catch (Exception e) { Log.e("Buffer Error", "Error converting result " + e.toString()); } // try parse the string to a JSON object try { jObj = new JSONObject(json); } catch (JSONException e) { Log.e("JSON Parser", "Error parsing data " + e.toString() + json); } // return JSON String return jObj; } }
3ch01c/heracles
android/src/com/wernicke/utils/JSONParser.java
Java
gpl-2.0
2,870
/* //@HEADER // ************************************************************************ // // Kokkos v. 3.0 // Copyright (2020) National Technology & Engineering // Solutions of Sandia, LLC (NTESS). // // Under the terms of Contract DE-NA0003525 with NTESS, // the U.S. Government retains certain rights in this software. // // 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 the Corporation nor the names of the // contributors may be used to endorse or promote products derived from // this software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY NTESS "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 NTESS OR THE // 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. // // Questions? Contact Christian R. Trott (crtrott@sandia.gov) // // ************************************************************************ //@HEADER */ #include <threads/TestThreads_Category.hpp> #include <TestViewMapping_a.hpp>
pastewka/lammps
lib/kokkos/core/unit_test/threads/TestThreads_ViewMapping_a.cpp
C++
gpl-2.0
2,057
using System.Reflection; 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("Integration.Tests")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("Hewlett-Packard Company")] [assembly: AssemblyProduct("Integration.Tests")] [assembly: AssemblyCopyright("Copyright © Hewlett-Packard Company 2014")] [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("43c64bba-2946-4a18-9874-d1e05c2e10ad")] // 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")]
12-South-Studios/realmmud
Source/Database/Integration.Tests/Properties/AssemblyInfo.cs
C#
gpl-2.0
1,417
package com.example.gramos.raportiti; import android.annotation.SuppressLint; import android.app.AlertDialog; import android.app.Service; import android.content.Context; import android.content.DialogInterface; import android.content.Intent; import android.location.Location; import android.location.LocationListener; import android.location.LocationManager; import android.os.Bundle; import android.os.IBinder; import android.provider.Settings; import android.util.Log; import static android.location.LocationManager.GPS_PROVIDER; @SuppressLint("Registered") public class GPSTracker extends Service implements LocationListener { private final Context aContext; // GPS status private boolean canGetLocation = false; private Location location; // location(lokacioni) private double latitude; // latitude(gjeresia) private double longitude; // longitude(gjatesia) // The minimum distance to change Updates in meters (distanca minimale per me e ba update coor.) private static final long MIN_DISTANCE_CHANGE_FOR_UPDATES = 10; // 10 meters // The minimum time between updates in milliseconds (koha minimale qe duhet me ba update) private static final long MIN_TIME_BW_UPDATES = 1000 * 60; // 1 minute public GPSTracker(Context context){ this.aContext = context; getLocation(); } @SuppressWarnings("UnusedReturnValue") private Location getLocation(){ try { LocationManager locationManager = (LocationManager) aContext.getSystemService(LOCATION_SERVICE); // getting GPS status boolean isGPSEnabled = locationManager.isProviderEnabled(GPS_PROVIDER); // getting network status boolean isNetworkEnabled = locationManager.isProviderEnabled(LocationManager.NETWORK_PROVIDER); //noinspection StatementWithEmptyBody if(!isGPSEnabled && !isNetworkEnabled){ // no network provider is enabled } else { this.canGetLocation = true; // First get location from Network Provider if (isNetworkEnabled) { locationManager.requestLocationUpdates( LocationManager.NETWORK_PROVIDER, MIN_TIME_BW_UPDATES, MIN_DISTANCE_CHANGE_FOR_UPDATES, this); Log.d("Network", "Network"); location = locationManager.getLastKnownLocation(LocationManager.NETWORK_PROVIDER); if (location != null){ latitude = location.getLatitude(); longitude = location.getLongitude(); } // if GPS Enabled get lat/long using GPS services if(isGPSEnabled) { if (location == null) { locationManager.requestLocationUpdates( LocationManager.GPS_PROVIDER, MIN_TIME_BW_UPDATES, MIN_DISTANCE_CHANGE_FOR_UPDATES, this); Log.d("GPS Enabled", "GPS Enabled"); location = locationManager.getLastKnownLocation(GPS_PROVIDER); if (location != null) { latitude = location.getLatitude(); longitude = location.getLongitude(); } } } } } } catch (Exception e){ e.printStackTrace(); } return location; } /** * Stop using GPS listener * Calling this function will stop using GPS in your app * public void stopUsingGPS(){ if(locationManager != null){ locationManager.removeUpdates(GPSTracker.this); } } */ /** * Function to get latitude * */ public double getLatitude(){ if(location != null){ latitude = location.getLatitude(); } // return latitude return latitude; } /** * Function to get longitude * */ public double getLongitude(){ if(location != null){ longitude = location.getLongitude(); } // return longitude return longitude; } /** * Function to check GPS/wifi enabled * @return boolean * */ public boolean canGetLocation() { return this.canGetLocation; } /** * Function to show settings alert dialog * On pressing Settings button will launch Settings Options **/ public void showOneButtonDialog(){ AlertDialog.Builder dialogBuilder = new AlertDialog.Builder(aContext); // setting dialog title dialogBuilder.setTitle("GPS is required!"); // setting dialog message dialogBuilder.setMessage("Please, go to the Settings button. Hurry up :)!! "); dialogBuilder.setPositiveButton("Settings", new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { Intent intent = new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS); aContext.startActivity(intent); } }); // on pressing cancel button dialogBuilder.setNegativeButton("Cancel", new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int which) { dialog.cancel(); } }); // showing alert message dialogBuilder.show(); } @Override public void onLocationChanged(Location location) { } @Override public void onStatusChanged(String provider, int status, Bundle extras) { } @Override public void onProviderEnabled(String provider) { } @Override public void onProviderDisabled(String provider) { } @Override public IBinder onBind(Intent intent) { return null; } }
opendatakosovo/android-dev
RaportiTi/app/src/main/java/com/example/gramos/raportiti/GPSTracker.java
Java
gpl-2.0
6,019
/* * linux/include/linux/cpufreq.h * * Copyright (C) 2001 Russell King * (C) 2002 - 2003 Dominik Brodowski <linux@brodo.de> * * 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. */ #ifndef _LINUX_CPUFREQ_H #define _LINUX_CPUFREQ_H #include <linux/cpumask.h> #include <linux/completion.h> #include <linux/kobject.h> #include <linux/notifier.h> #include <linux/sysfs.h> #include <asm/cputime.h> #define CPUFREQ_NAME_LEN 16 /* Print length for names. Extra 1 space for accomodating '\n' in prints */ #define CPUFREQ_NAME_PLEN (CPUFREQ_NAME_LEN + 1) /********************************************************************* * CPUFREQ NOTIFIER INTERFACE * *********************************************************************/ #define CPUFREQ_TRANSITION_NOTIFIER (0) #define CPUFREQ_POLICY_NOTIFIER (1) #ifdef CONFIG_CPU_FREQ int cpufreq_register_notifier(struct notifier_block *nb, unsigned int list); int cpufreq_unregister_notifier(struct notifier_block *nb, unsigned int list); extern void disable_cpufreq(void); #else /* CONFIG_CPU_FREQ */ static inline int cpufreq_register_notifier(struct notifier_block *nb, unsigned int list) { return 0; } static inline int cpufreq_unregister_notifier(struct notifier_block *nb, unsigned int list) { return 0; } static inline void disable_cpufreq(void) { } #endif /* CONFIG_CPU_FREQ */ /* if (cpufreq_driver->target) exists, the ->governor decides what frequency * within the limits is used. If (cpufreq_driver->setpolicy> exists, these * two generic policies are available: */ #define CPUFREQ_POLICY_POWERSAVE (1) #define CPUFREQ_POLICY_PERFORMANCE (2) /* Frequency values here are CPU kHz so that hardware which doesn't run * with some frequencies can complain without having to guess what per * cent / per mille means. * Maximum transition latency is in nanoseconds - if it's unknown, * CPUFREQ_ETERNAL shall be used. */ struct cpufreq_governor; /* /sys/devices/system/cpu/cpufreq: entry point for global variables */ extern struct kobject *cpufreq_global_kobject; #define CPUFREQ_ETERNAL (-1) struct cpufreq_cpuinfo { unsigned int max_freq; unsigned int min_freq; /* in 10^(-9) s = nanoseconds */ unsigned int transition_latency; }; struct cpufreq_real_policy { unsigned int min; /* in kHz */ unsigned int max; /* in kHz */ unsigned int policy; /* see above */ struct cpufreq_governor *governor; /* see below */ }; struct cpufreq_policy { /* CPUs sharing clock, require sw coordination */ cpumask_var_t cpus; /* Online CPUs only */ cpumask_var_t related_cpus; /* Online + Offline CPUs */ unsigned int shared_type; /* ACPI: ANY or ALL affected CPUs should set cpufreq */ unsigned int cpu; /* cpu nr of CPU managing this policy */ unsigned int last_cpu; /* cpu nr of previous CPU that managed * this policy */ struct cpufreq_cpuinfo cpuinfo;/* see above */ unsigned int min; /* in kHz */ unsigned int max; /* in kHz */ unsigned int cur; /* in kHz, only needed if cpufreq * governors are used */ unsigned int policy; /* see above */ struct cpufreq_governor *governor; /* see below */ void *governor_data; bool governor_enabled; /* governor start/stop flag */ struct work_struct update; /* if update_policy() needs to be * called, but you're in IRQ context */ struct cpufreq_real_policy user_policy; struct kobject kobj; struct completion kobj_unregister; }; #define CPUFREQ_ADJUST (0) #define CPUFREQ_INCOMPATIBLE (1) #define CPUFREQ_NOTIFY (2) #define CPUFREQ_START (3) #define CPUFREQ_UPDATE_POLICY_CPU (4) /* Only for ACPI */ #define CPUFREQ_SHARED_TYPE_NONE (0) /* None */ #define CPUFREQ_SHARED_TYPE_HW (1) /* HW does needed coordination */ #define CPUFREQ_SHARED_TYPE_ALL (2) /* All dependent CPUs should set freq */ #define CPUFREQ_SHARED_TYPE_ANY (3) /* Freq can be set from any dependent CPU*/ static inline bool policy_is_shared(struct cpufreq_policy *policy) { return cpumask_weight(policy->cpus) > 1; } /******************** cpufreq transition notifiers *******************/ #define CPUFREQ_PRECHANGE (0) #define CPUFREQ_POSTCHANGE (1) #define CPUFREQ_RESUMECHANGE (8) #define CPUFREQ_SUSPENDCHANGE (9) struct cpufreq_freqs { unsigned int cpu; /* cpu nr */ unsigned int old; unsigned int new; u8 flags; /* flags of cpufreq_driver, see below. */ }; /** * cpufreq_scale - "old * mult / div" calculation for large values (32-bit-arch safe) * @old: old value * @div: divisor * @mult: multiplier * * * new = old * mult / div */ static inline unsigned long cpufreq_scale(unsigned long old, u_int div, u_int mult) { #if BITS_PER_LONG == 32 u64 result = ((u64) old) * ((u64) mult); do_div(result, div); return (unsigned long) result; #elif BITS_PER_LONG == 64 unsigned long result = old * ((u64) mult); result /= div; return result; #endif }; /********************************************************************* * CPUFREQ GOVERNORS * *********************************************************************/ #define CPUFREQ_GOV_START 1 #define CPUFREQ_GOV_STOP 2 #define CPUFREQ_GOV_LIMITS 3 #define CPUFREQ_GOV_POLICY_INIT 4 #define CPUFREQ_GOV_POLICY_EXIT 5 struct cpufreq_governor { char name[CPUFREQ_NAME_LEN]; int initialized; int (*governor) (struct cpufreq_policy *policy, unsigned int event); ssize_t (*show_setspeed) (struct cpufreq_policy *policy, char *buf); int (*store_setspeed) (struct cpufreq_policy *policy, unsigned int freq); unsigned int max_transition_latency; /* HW must be able to switch to next freq faster than this value in nano secs or we will fallback to performance governor */ struct list_head governor_list; struct module *owner; }; /* * Pass a target to the cpufreq driver. */ extern int cpufreq_driver_target(struct cpufreq_policy *policy, unsigned int target_freq, unsigned int relation); extern int __cpufreq_driver_target(struct cpufreq_policy *policy, unsigned int target_freq, unsigned int relation); extern int __cpufreq_driver_getavg(struct cpufreq_policy *policy, unsigned int cpu); int cpufreq_register_governor(struct cpufreq_governor *governor); void cpufreq_unregister_governor(struct cpufreq_governor *governor); /********************************************************************* * CPUFREQ DRIVER INTERFACE * *********************************************************************/ #define CPUFREQ_RELATION_L 0 /* lowest frequency at or above target */ #define CPUFREQ_RELATION_H 1 /* highest frequency below or at target */ struct freq_attr; struct cpufreq_driver { struct module *owner; char name[CPUFREQ_NAME_LEN]; u8 flags; /* * This should be set by platforms having multiple clock-domains, i.e. * supporting multiple policies. With this sysfs directories of governor * would be created in cpu/cpu<num>/cpufreq/ directory and so they can * use the same governor with different tunables for different clusters. */ bool have_governor_per_policy; /* needed by all drivers */ int (*init) (struct cpufreq_policy *policy); int (*verify) (struct cpufreq_policy *policy); /* define one out of two */ int (*setpolicy) (struct cpufreq_policy *policy); int (*target) (struct cpufreq_policy *policy, unsigned int target_freq, unsigned int relation); /* should be defined, if possible */ unsigned int (*get) (unsigned int cpu); /* optional */ unsigned int (*getavg) (struct cpufreq_policy *policy, unsigned int cpu); int (*bios_limit) (int cpu, unsigned int *limit); int (*exit) (struct cpufreq_policy *policy); int (*suspend) (struct cpufreq_policy *policy); int (*resume) (struct cpufreq_policy *policy); struct freq_attr **attr; }; /* flags */ #define CPUFREQ_STICKY 0x01 /* the driver isn't removed even if * all ->init() calls failed */ #define CPUFREQ_CONST_LOOPS 0x02 /* loops_per_jiffy or other kernel * "constants" aren't affected by * frequency transitions */ #define CPUFREQ_PM_NO_WARN 0x04 /* don't warn on suspend/resume speed * mismatches */ int cpufreq_register_driver(struct cpufreq_driver *driver_data); int cpufreq_unregister_driver(struct cpufreq_driver *driver_data); void cpufreq_notify_transition(struct cpufreq_freqs *freqs, unsigned int state); static inline void cpufreq_verify_within_limits(struct cpufreq_policy *policy, unsigned int min, unsigned int max) { if (policy->min < min) policy->min = min; if (policy->max < min) policy->max = min; if (policy->min > max) policy->min = max; if (policy->max > max) policy->max = max; if (policy->min > policy->max) policy->min = policy->max; return; } struct freq_attr { struct attribute attr; ssize_t (*show)(struct cpufreq_policy *, char *); ssize_t (*store)(struct cpufreq_policy *, const char *, size_t count); }; #define cpufreq_freq_attr_ro(_name) \ static struct freq_attr _name = \ __ATTR(_name, 0444, show_##_name, NULL) #define cpufreq_freq_attr_ro_perm(_name, _perm) \ static struct freq_attr _name = \ __ATTR(_name, _perm, show_##_name, NULL) #define cpufreq_freq_attr_rw(_name) \ static struct freq_attr _name = \ __ATTR(_name, 0644, show_##_name, store_##_name) struct global_attr { struct attribute attr; ssize_t (*show)(struct kobject *kobj, struct attribute *attr, char *buf); ssize_t (*store)(struct kobject *a, struct attribute *b, const char *c, size_t count); }; #define define_one_global_ro(_name) \ static struct global_attr _name = \ __ATTR(_name, 0444, show_##_name, NULL) #define define_one_global_rw(_name) \ static struct global_attr _name = \ __ATTR(_name, 0644, show_##_name, store_##_name) struct cpufreq_policy *cpufreq_cpu_get(unsigned int cpu); void cpufreq_cpu_put(struct cpufreq_policy *data); const char *cpufreq_get_current_driver(void); /********************************************************************* * CPUFREQ 2.6. INTERFACE * *********************************************************************/ u64 get_cpu_idle_time(unsigned int cpu, u64 *wall, int io_busy); int cpufreq_get_policy(struct cpufreq_policy *policy, unsigned int cpu); int cpufreq_update_policy(unsigned int cpu); bool have_governor_per_policy(void); int cpufreq_set_gov(char *target_gov, unsigned int cpu); struct kobject *get_governor_parent_kobj(struct cpufreq_policy *policy); #ifdef CONFIG_CPU_FREQ /* query the current CPU frequency (in kHz). If zero, cpufreq couldn't detect it */ unsigned int cpufreq_get(unsigned int cpu); #else static inline unsigned int cpufreq_get(unsigned int cpu) { return 0; } #endif /* query the last known CPU freq (in kHz). If zero, cpufreq couldn't detect it */ #ifdef CONFIG_CPU_FREQ unsigned int cpufreq_quick_get(unsigned int cpu); unsigned int cpufreq_quick_get_max(unsigned int cpu); #else static inline unsigned int cpufreq_quick_get(unsigned int cpu) { return 0; } static inline unsigned int cpufreq_quick_get_max(unsigned int cpu) { return 0; } #endif /********************************************************************* * CPUFREQ DEFAULT GOVERNOR * *********************************************************************/ /* Performance governor is fallback governor if any other gov failed to auto load due latency restrictions */ #ifdef CONFIG_CPU_FREQ_GOV_PERFORMANCE extern struct cpufreq_governor cpufreq_gov_performance; #endif #ifdef CONFIG_CPU_FREQ_DEFAULT_GOV_PERFORMANCE #define CPUFREQ_DEFAULT_GOVERNOR (&cpufreq_gov_performance) #elif defined(CONFIG_CPU_FREQ_DEFAULT_GOV_POWERSAVE) extern struct cpufreq_governor cpufreq_gov_powersave; #define CPUFREQ_DEFAULT_GOVERNOR (&cpufreq_gov_powersave) #elif defined(CONFIG_CPU_FREQ_DEFAULT_GOV_USERSPACE) extern struct cpufreq_governor cpufreq_gov_userspace; #define CPUFREQ_DEFAULT_GOVERNOR (&cpufreq_gov_userspace) #elif defined(CONFIG_CPU_FREQ_DEFAULT_GOV_ONDEMAND) extern struct cpufreq_governor cpufreq_gov_ondemand; #define CPUFREQ_DEFAULT_GOVERNOR (&cpufreq_gov_ondemand) #elif defined(CONFIG_CPU_FREQ_DEFAULT_GOV_CONSERVATIVE) extern struct cpufreq_governor cpufreq_gov_conservative; #define CPUFREQ_DEFAULT_GOVERNOR (&cpufreq_gov_conservative) #elif defined(CONFIG_CPU_FREQ_DEFAULT_GOV_INTERACTIVE) extern struct cpufreq_governor cpufreq_gov_interactive; #define CPUFREQ_DEFAULT_GOVERNOR (&cpufreq_gov_interactive) #endif /********************************************************************* * FREQUENCY TABLE HELPERS * *********************************************************************/ #define CPUFREQ_ENTRY_INVALID ~0 #define CPUFREQ_TABLE_END ~1 struct cpufreq_frequency_table { unsigned int index; /* any */ unsigned int frequency; /* kHz - doesn't need to be in ascending * order */ }; int cpufreq_frequency_table_cpuinfo(struct cpufreq_policy *policy, struct cpufreq_frequency_table *table); int cpufreq_frequency_table_verify(struct cpufreq_policy *policy, struct cpufreq_frequency_table *table); int cpufreq_frequency_table_target(struct cpufreq_policy *policy, struct cpufreq_frequency_table *table, unsigned int target_freq, unsigned int relation, unsigned int *index); /* the following 3 funtions are for cpufreq core use only */ struct cpufreq_frequency_table *cpufreq_frequency_get_table(unsigned int cpu); /* the following are really really optional */ extern struct freq_attr cpufreq_freq_attr_scaling_available_freqs; void cpufreq_frequency_table_get_attr(struct cpufreq_frequency_table *table, unsigned int cpu); void cpufreq_frequency_table_update_policy_cpu(struct cpufreq_policy *policy); void cpufreq_frequency_table_put_attr(unsigned int cpu); /********************************************************************* * CPUFREQ STATS * *********************************************************************/ void acct_update_power(struct task_struct *p, cputime_t cputime); #endif /* _LINUX_CPUFREQ_H */
arter97/android_kernel_nvidia_shieldtablet
include/linux/cpufreq.h
C
gpl-2.0
14,385
/******************************************************************************* * Filename: target_core_transport.c * * This file contains the Generic Target Engine Core. * * (c) Copyright 2002-2013 Datera, Inc. * * Nicholas A. Bellinger <nab@kernel.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 <linux/net.h> #include <linux/delay.h> #include <linux/string.h> #include <linux/timer.h> #include <linux/slab.h> #include <linux/spinlock.h> #include <linux/kthread.h> #include <linux/in.h> #include <linux/cdrom.h> #include <linux/module.h> #include <linux/ratelimit.h> #include <asm/unaligned.h> #include <net/sock.h> #include <net/tcp.h> #include <scsi/scsi.h> #include <scsi/scsi_cmnd.h> #include <scsi/scsi_tcq.h> #include <target/target_core_base.h> #include <target/target_core_backend.h> #include <target/target_core_fabric.h> #include <target/target_core_configfs.h> #include "target_core_internal.h" #include "target_core_alua.h" #include "target_core_pr.h" #include "target_core_ua.h" #define CREATE_TRACE_POINTS #include <trace/events/target.h> static struct workqueue_struct *target_completion_wq; static struct kmem_cache *se_sess_cache; struct kmem_cache *se_ua_cache; struct kmem_cache *t10_pr_reg_cache; struct kmem_cache *t10_alua_lu_gp_cache; struct kmem_cache *t10_alua_lu_gp_mem_cache; struct kmem_cache *t10_alua_tg_pt_gp_cache; struct kmem_cache *t10_alua_tg_pt_gp_mem_cache; struct kmem_cache *t10_alua_lba_map_cache; struct kmem_cache *t10_alua_lba_map_mem_cache; static void transport_complete_task_attr(struct se_cmd *cmd); static void transport_handle_queue_full(struct se_cmd *cmd, struct se_device *dev); static int transport_put_cmd(struct se_cmd *cmd); static void target_complete_ok_work(struct work_struct *work); int init_se_kmem_caches(void) { se_sess_cache = kmem_cache_create("se_sess_cache", sizeof(struct se_session), __alignof__(struct se_session), 0, NULL); if (!se_sess_cache) { pr_err("kmem_cache_create() for struct se_session" " failed\n"); goto out; } se_ua_cache = kmem_cache_create("se_ua_cache", sizeof(struct se_ua), __alignof__(struct se_ua), 0, NULL); if (!se_ua_cache) { pr_err("kmem_cache_create() for struct se_ua failed\n"); goto out_free_sess_cache; } t10_pr_reg_cache = kmem_cache_create("t10_pr_reg_cache", sizeof(struct t10_pr_registration), __alignof__(struct t10_pr_registration), 0, NULL); if (!t10_pr_reg_cache) { pr_err("kmem_cache_create() for struct t10_pr_registration" " failed\n"); goto out_free_ua_cache; } t10_alua_lu_gp_cache = kmem_cache_create("t10_alua_lu_gp_cache", sizeof(struct t10_alua_lu_gp), __alignof__(struct t10_alua_lu_gp), 0, NULL); if (!t10_alua_lu_gp_cache) { pr_err("kmem_cache_create() for t10_alua_lu_gp_cache" " failed\n"); goto out_free_pr_reg_cache; } t10_alua_lu_gp_mem_cache = kmem_cache_create("t10_alua_lu_gp_mem_cache", sizeof(struct t10_alua_lu_gp_member), __alignof__(struct t10_alua_lu_gp_member), 0, NULL); if (!t10_alua_lu_gp_mem_cache) { pr_err("kmem_cache_create() for t10_alua_lu_gp_mem_" "cache failed\n"); goto out_free_lu_gp_cache; } t10_alua_tg_pt_gp_cache = kmem_cache_create("t10_alua_tg_pt_gp_cache", sizeof(struct t10_alua_tg_pt_gp), __alignof__(struct t10_alua_tg_pt_gp), 0, NULL); if (!t10_alua_tg_pt_gp_cache) { pr_err("kmem_cache_create() for t10_alua_tg_pt_gp_" "cache failed\n"); goto out_free_lu_gp_mem_cache; } t10_alua_tg_pt_gp_mem_cache = kmem_cache_create( "t10_alua_tg_pt_gp_mem_cache", sizeof(struct t10_alua_tg_pt_gp_member), __alignof__(struct t10_alua_tg_pt_gp_member), 0, NULL); if (!t10_alua_tg_pt_gp_mem_cache) { pr_err("kmem_cache_create() for t10_alua_tg_pt_gp_" "mem_t failed\n"); goto out_free_tg_pt_gp_cache; } t10_alua_lba_map_cache = kmem_cache_create( "t10_alua_lba_map_cache", sizeof(struct t10_alua_lba_map), __alignof__(struct t10_alua_lba_map), 0, NULL); if (!t10_alua_lba_map_cache) { pr_err("kmem_cache_create() for t10_alua_lba_map_" "cache failed\n"); goto out_free_tg_pt_gp_mem_cache; } t10_alua_lba_map_mem_cache = kmem_cache_create( "t10_alua_lba_map_mem_cache", sizeof(struct t10_alua_lba_map_member), __alignof__(struct t10_alua_lba_map_member), 0, NULL); if (!t10_alua_lba_map_mem_cache) { pr_err("kmem_cache_create() for t10_alua_lba_map_mem_" "cache failed\n"); goto out_free_lba_map_cache; } target_completion_wq = alloc_workqueue("target_completion", WQ_MEM_RECLAIM, 0); if (!target_completion_wq) goto out_free_lba_map_mem_cache; return 0; out_free_lba_map_mem_cache: kmem_cache_destroy(t10_alua_lba_map_mem_cache); out_free_lba_map_cache: kmem_cache_destroy(t10_alua_lba_map_cache); out_free_tg_pt_gp_mem_cache: kmem_cache_destroy(t10_alua_tg_pt_gp_mem_cache); out_free_tg_pt_gp_cache: kmem_cache_destroy(t10_alua_tg_pt_gp_cache); out_free_lu_gp_mem_cache: kmem_cache_destroy(t10_alua_lu_gp_mem_cache); out_free_lu_gp_cache: kmem_cache_destroy(t10_alua_lu_gp_cache); out_free_pr_reg_cache: kmem_cache_destroy(t10_pr_reg_cache); out_free_ua_cache: kmem_cache_destroy(se_ua_cache); out_free_sess_cache: kmem_cache_destroy(se_sess_cache); out: return -ENOMEM; } void release_se_kmem_caches(void) { destroy_workqueue(target_completion_wq); kmem_cache_destroy(se_sess_cache); kmem_cache_destroy(se_ua_cache); kmem_cache_destroy(t10_pr_reg_cache); kmem_cache_destroy(t10_alua_lu_gp_cache); kmem_cache_destroy(t10_alua_lu_gp_mem_cache); kmem_cache_destroy(t10_alua_tg_pt_gp_cache); kmem_cache_destroy(t10_alua_tg_pt_gp_mem_cache); kmem_cache_destroy(t10_alua_lba_map_cache); kmem_cache_destroy(t10_alua_lba_map_mem_cache); } /* This code ensures unique mib indexes are handed out. */ static DEFINE_SPINLOCK(scsi_mib_index_lock); static u32 scsi_mib_index[SCSI_INDEX_TYPE_MAX]; /* * Allocate a new row index for the entry type specified */ u32 scsi_get_new_index(scsi_index_t type) { u32 new_index; BUG_ON((type < 0) || (type >= SCSI_INDEX_TYPE_MAX)); spin_lock(&scsi_mib_index_lock); new_index = ++scsi_mib_index[type]; spin_unlock(&scsi_mib_index_lock); return new_index; } void transport_subsystem_check_init(void) { int ret; static int sub_api_initialized; if (sub_api_initialized) return; ret = request_module("target_core_iblock"); if (ret != 0) pr_err("Unable to load target_core_iblock\n"); ret = request_module("target_core_file"); if (ret != 0) pr_err("Unable to load target_core_file\n"); ret = request_module("target_core_pscsi"); if (ret != 0) pr_err("Unable to load target_core_pscsi\n"); ret = request_module("target_core_user"); if (ret != 0) pr_err("Unable to load target_core_user\n"); sub_api_initialized = 1; } struct se_session *transport_init_session(enum target_prot_op sup_prot_ops) { struct se_session *se_sess; se_sess = kmem_cache_zalloc(se_sess_cache, GFP_KERNEL); if (!se_sess) { pr_err("Unable to allocate struct se_session from" " se_sess_cache\n"); return ERR_PTR(-ENOMEM); } INIT_LIST_HEAD(&se_sess->sess_list); INIT_LIST_HEAD(&se_sess->sess_acl_list); INIT_LIST_HEAD(&se_sess->sess_cmd_list); INIT_LIST_HEAD(&se_sess->sess_wait_list); spin_lock_init(&se_sess->sess_cmd_lock); kref_init(&se_sess->sess_kref); se_sess->sup_prot_ops = sup_prot_ops; return se_sess; } EXPORT_SYMBOL(transport_init_session); int transport_alloc_session_tags(struct se_session *se_sess, unsigned int tag_num, unsigned int tag_size) { int rc; se_sess->sess_cmd_map = kzalloc(tag_num * tag_size, GFP_KERNEL | __GFP_NOWARN | __GFP_REPEAT); if (!se_sess->sess_cmd_map) { se_sess->sess_cmd_map = vzalloc(tag_num * tag_size); if (!se_sess->sess_cmd_map) { pr_err("Unable to allocate se_sess->sess_cmd_map\n"); return -ENOMEM; } } rc = percpu_ida_init(&se_sess->sess_tag_pool, tag_num); if (rc < 0) { pr_err("Unable to init se_sess->sess_tag_pool," " tag_num: %u\n", tag_num); if (is_vmalloc_addr(se_sess->sess_cmd_map)) vfree(se_sess->sess_cmd_map); else kfree(se_sess->sess_cmd_map); se_sess->sess_cmd_map = NULL; return -ENOMEM; } return 0; } EXPORT_SYMBOL(transport_alloc_session_tags); struct se_session *transport_init_session_tags(unsigned int tag_num, unsigned int tag_size, enum target_prot_op sup_prot_ops) { struct se_session *se_sess; int rc; se_sess = transport_init_session(sup_prot_ops); if (IS_ERR(se_sess)) return se_sess; rc = transport_alloc_session_tags(se_sess, tag_num, tag_size); if (rc < 0) { transport_free_session(se_sess); return ERR_PTR(-ENOMEM); } return se_sess; } EXPORT_SYMBOL(transport_init_session_tags); /* * Called with spin_lock_irqsave(&struct se_portal_group->session_lock called. */ void __transport_register_session( struct se_portal_group *se_tpg, struct se_node_acl *se_nacl, struct se_session *se_sess, void *fabric_sess_ptr) { const struct target_core_fabric_ops *tfo = se_tpg->se_tpg_tfo; unsigned char buf[PR_REG_ISID_LEN]; se_sess->se_tpg = se_tpg; se_sess->fabric_sess_ptr = fabric_sess_ptr; /* * Used by struct se_node_acl's under ConfigFS to locate active se_session-t * * Only set for struct se_session's that will actually be moving I/O. * eg: *NOT* discovery sessions. */ if (se_nacl) { /* * * Determine if fabric allows for T10-PI feature bits exposed to * initiators for device backends with !dev->dev_attrib.pi_prot_type. * * If so, then always save prot_type on a per se_node_acl node * basis and re-instate the previous sess_prot_type to avoid * disabling PI from below any previously initiator side * registered LUNs. */ if (se_nacl->saved_prot_type) se_sess->sess_prot_type = se_nacl->saved_prot_type; else if (tfo->tpg_check_prot_fabric_only) se_sess->sess_prot_type = se_nacl->saved_prot_type = tfo->tpg_check_prot_fabric_only(se_tpg); /* * If the fabric module supports an ISID based TransportID, * save this value in binary from the fabric I_T Nexus now. */ if (se_tpg->se_tpg_tfo->sess_get_initiator_sid != NULL) { memset(&buf[0], 0, PR_REG_ISID_LEN); se_tpg->se_tpg_tfo->sess_get_initiator_sid(se_sess, &buf[0], PR_REG_ISID_LEN); se_sess->sess_bin_isid = get_unaligned_be64(&buf[0]); } kref_get(&se_nacl->acl_kref); spin_lock_irq(&se_nacl->nacl_sess_lock); /* * The se_nacl->nacl_sess pointer will be set to the * last active I_T Nexus for each struct se_node_acl. */ se_nacl->nacl_sess = se_sess; list_add_tail(&se_sess->sess_acl_list, &se_nacl->acl_sess_list); spin_unlock_irq(&se_nacl->nacl_sess_lock); } list_add_tail(&se_sess->sess_list, &se_tpg->tpg_sess_list); pr_debug("TARGET_CORE[%s]: Registered fabric_sess_ptr: %p\n", se_tpg->se_tpg_tfo->get_fabric_name(), se_sess->fabric_sess_ptr); } EXPORT_SYMBOL(__transport_register_session); void transport_register_session( struct se_portal_group *se_tpg, struct se_node_acl *se_nacl, struct se_session *se_sess, void *fabric_sess_ptr) { unsigned long flags; spin_lock_irqsave(&se_tpg->session_lock, flags); __transport_register_session(se_tpg, se_nacl, se_sess, fabric_sess_ptr); spin_unlock_irqrestore(&se_tpg->session_lock, flags); } EXPORT_SYMBOL(transport_register_session); static void target_release_session(struct kref *kref) { struct se_session *se_sess = container_of(kref, struct se_session, sess_kref); struct se_portal_group *se_tpg = se_sess->se_tpg; se_tpg->se_tpg_tfo->close_session(se_sess); } void target_get_session(struct se_session *se_sess) { kref_get(&se_sess->sess_kref); } EXPORT_SYMBOL(target_get_session); void target_put_session(struct se_session *se_sess) { struct se_portal_group *tpg = se_sess->se_tpg; if (tpg->se_tpg_tfo->put_session != NULL) { tpg->se_tpg_tfo->put_session(se_sess); return; } kref_put(&se_sess->sess_kref, target_release_session); } EXPORT_SYMBOL(target_put_session); ssize_t target_show_dynamic_sessions(struct se_portal_group *se_tpg, char *page) { struct se_session *se_sess; ssize_t len = 0; spin_lock_bh(&se_tpg->session_lock); list_for_each_entry(se_sess, &se_tpg->tpg_sess_list, sess_list) { if (!se_sess->se_node_acl) continue; if (!se_sess->se_node_acl->dynamic_node_acl) continue; if (strlen(se_sess->se_node_acl->initiatorname) + 1 + len > PAGE_SIZE) break; len += snprintf(page + len, PAGE_SIZE - len, "%s\n", se_sess->se_node_acl->initiatorname); len += 1; /* Include NULL terminator */ } spin_unlock_bh(&se_tpg->session_lock); return len; } EXPORT_SYMBOL(target_show_dynamic_sessions); static void target_complete_nacl(struct kref *kref) { struct se_node_acl *nacl = container_of(kref, struct se_node_acl, acl_kref); complete(&nacl->acl_free_comp); } void target_put_nacl(struct se_node_acl *nacl) { kref_put(&nacl->acl_kref, target_complete_nacl); } void transport_deregister_session_configfs(struct se_session *se_sess) { struct se_node_acl *se_nacl; unsigned long flags; /* * Used by struct se_node_acl's under ConfigFS to locate active struct se_session */ se_nacl = se_sess->se_node_acl; if (se_nacl) { spin_lock_irqsave(&se_nacl->nacl_sess_lock, flags); if (se_nacl->acl_stop == 0) list_del(&se_sess->sess_acl_list); /* * If the session list is empty, then clear the pointer. * Otherwise, set the struct se_session pointer from the tail * element of the per struct se_node_acl active session list. */ if (list_empty(&se_nacl->acl_sess_list)) se_nacl->nacl_sess = NULL; else { se_nacl->nacl_sess = container_of( se_nacl->acl_sess_list.prev, struct se_session, sess_acl_list); } spin_unlock_irqrestore(&se_nacl->nacl_sess_lock, flags); } } EXPORT_SYMBOL(transport_deregister_session_configfs); void transport_free_session(struct se_session *se_sess) { if (se_sess->sess_cmd_map) { percpu_ida_destroy(&se_sess->sess_tag_pool); if (is_vmalloc_addr(se_sess->sess_cmd_map)) vfree(se_sess->sess_cmd_map); else kfree(se_sess->sess_cmd_map); } kmem_cache_free(se_sess_cache, se_sess); } EXPORT_SYMBOL(transport_free_session); void transport_deregister_session(struct se_session *se_sess) { struct se_portal_group *se_tpg = se_sess->se_tpg; const struct target_core_fabric_ops *se_tfo; struct se_node_acl *se_nacl; unsigned long flags; bool comp_nacl = true; if (!se_tpg) { transport_free_session(se_sess); return; } se_tfo = se_tpg->se_tpg_tfo; spin_lock_irqsave(&se_tpg->session_lock, flags); list_del(&se_sess->sess_list); se_sess->se_tpg = NULL; se_sess->fabric_sess_ptr = NULL; spin_unlock_irqrestore(&se_tpg->session_lock, flags); /* * Determine if we need to do extra work for this initiator node's * struct se_node_acl if it had been previously dynamically generated. */ se_nacl = se_sess->se_node_acl; spin_lock_irqsave(&se_tpg->acl_node_lock, flags); if (se_nacl && se_nacl->dynamic_node_acl) { if (!se_tfo->tpg_check_demo_mode_cache(se_tpg)) { list_del(&se_nacl->acl_list); se_tpg->num_node_acls--; spin_unlock_irqrestore(&se_tpg->acl_node_lock, flags); core_tpg_wait_for_nacl_pr_ref(se_nacl); core_free_device_list_for_node(se_nacl, se_tpg); se_tfo->tpg_release_fabric_acl(se_tpg, se_nacl); comp_nacl = false; spin_lock_irqsave(&se_tpg->acl_node_lock, flags); } } spin_unlock_irqrestore(&se_tpg->acl_node_lock, flags); pr_debug("TARGET_CORE[%s]: Deregistered fabric_sess\n", se_tpg->se_tpg_tfo->get_fabric_name()); /* * If last kref is dropping now for an explicit NodeACL, awake sleeping * ->acl_free_comp caller to wakeup configfs se_node_acl->acl_group * removal context. */ if (se_nacl && comp_nacl) target_put_nacl(se_nacl); transport_free_session(se_sess); } EXPORT_SYMBOL(transport_deregister_session); static void target_remove_from_state_list(struct se_cmd *cmd) { struct se_device *dev = cmd->se_dev; unsigned long flags; if (!dev) return; if (cmd->transport_state & CMD_T_BUSY) return; spin_lock_irqsave(&dev->execute_task_lock, flags); if (cmd->state_active) { list_del(&cmd->state_list); cmd->state_active = false; } spin_unlock_irqrestore(&dev->execute_task_lock, flags); } static int transport_cmd_check_stop(struct se_cmd *cmd, bool remove_from_lists, bool write_pending) { unsigned long flags; if (remove_from_lists) { target_remove_from_state_list(cmd); /* * Clear struct se_cmd->se_lun before the handoff to FE. */ cmd->se_lun = NULL; } spin_lock_irqsave(&cmd->t_state_lock, flags); if (write_pending) cmd->t_state = TRANSPORT_WRITE_PENDING; /* * Determine if frontend context caller is requesting the stopping of * this command for frontend exceptions. */ if (cmd->transport_state & CMD_T_STOP) { pr_debug("%s:%d CMD_T_STOP for ITT: 0x%08x\n", __func__, __LINE__, cmd->se_tfo->get_task_tag(cmd)); spin_unlock_irqrestore(&cmd->t_state_lock, flags); complete_all(&cmd->t_transport_stop_comp); return 1; } cmd->transport_state &= ~CMD_T_ACTIVE; if (remove_from_lists) { /* * Some fabric modules like tcm_loop can release * their internally allocated I/O reference now and * struct se_cmd now. * * Fabric modules are expected to return '1' here if the * se_cmd being passed is released at this point, * or zero if not being released. */ if (cmd->se_tfo->check_stop_free != NULL) { spin_unlock_irqrestore(&cmd->t_state_lock, flags); return cmd->se_tfo->check_stop_free(cmd); } } spin_unlock_irqrestore(&cmd->t_state_lock, flags); return 0; } static int transport_cmd_check_stop_to_fabric(struct se_cmd *cmd) { return transport_cmd_check_stop(cmd, true, false); } static void transport_lun_remove_cmd(struct se_cmd *cmd) { struct se_lun *lun = cmd->se_lun; if (!lun) return; if (cmpxchg(&cmd->lun_ref_active, true, false)) percpu_ref_put(&lun->lun_ref); } void transport_cmd_finish_abort(struct se_cmd *cmd, int remove) { bool ack_kref = (cmd->se_cmd_flags & SCF_ACK_KREF); if (cmd->se_cmd_flags & SCF_SE_LUN_CMD) transport_lun_remove_cmd(cmd); /* * Allow the fabric driver to unmap any resources before * releasing the descriptor via TFO->release_cmd() */ if (remove) cmd->se_tfo->aborted_task(cmd); if (transport_cmd_check_stop_to_fabric(cmd)) return; if (remove && ack_kref) transport_put_cmd(cmd); } static void target_complete_failure_work(struct work_struct *work) { struct se_cmd *cmd = container_of(work, struct se_cmd, work); transport_generic_request_failure(cmd, TCM_LOGICAL_UNIT_COMMUNICATION_FAILURE); } /* * Used when asking transport to copy Sense Data from the underlying * Linux/SCSI struct scsi_cmnd */ static unsigned char *transport_get_sense_buffer(struct se_cmd *cmd) { struct se_device *dev = cmd->se_dev; WARN_ON(!cmd->se_lun); if (!dev) return NULL; if (cmd->se_cmd_flags & SCF_SENT_CHECK_CONDITION) return NULL; cmd->scsi_sense_length = TRANSPORT_SENSE_BUFFER; pr_debug("HBA_[%u]_PLUG[%s]: Requesting sense for SAM STATUS: 0x%02x\n", dev->se_hba->hba_id, dev->transport->name, cmd->scsi_status); return cmd->sense_buffer; } void target_complete_cmd(struct se_cmd *cmd, u8 scsi_status) { struct se_device *dev = cmd->se_dev; int success = scsi_status == GOOD; unsigned long flags; cmd->scsi_status = scsi_status; spin_lock_irqsave(&cmd->t_state_lock, flags); cmd->transport_state &= ~CMD_T_BUSY; if (dev && dev->transport->transport_complete) { dev->transport->transport_complete(cmd, cmd->t_data_sg, transport_get_sense_buffer(cmd)); if (cmd->se_cmd_flags & SCF_TRANSPORT_TASK_SENSE) success = 1; } /* * See if we are waiting to complete for an exception condition. */ if (cmd->transport_state & CMD_T_REQUEST_STOP) { spin_unlock_irqrestore(&cmd->t_state_lock, flags); complete(&cmd->task_stop_comp); return; } /* * Check for case where an explicit ABORT_TASK has been received * and transport_wait_for_tasks() will be waiting for completion.. */ if (cmd->transport_state & CMD_T_ABORTED || cmd->transport_state & CMD_T_STOP) { spin_unlock_irqrestore(&cmd->t_state_lock, flags); complete_all(&cmd->t_transport_stop_comp); return; } else if (!success) { INIT_WORK(&cmd->work, target_complete_failure_work); } else { INIT_WORK(&cmd->work, target_complete_ok_work); } cmd->t_state = TRANSPORT_COMPLETE; cmd->transport_state |= (CMD_T_COMPLETE | CMD_T_ACTIVE); spin_unlock_irqrestore(&cmd->t_state_lock, flags); queue_work(target_completion_wq, &cmd->work); } EXPORT_SYMBOL(target_complete_cmd); void target_complete_cmd_with_length(struct se_cmd *cmd, u8 scsi_status, int length) { if (scsi_status == SAM_STAT_GOOD && length < cmd->data_length) { if (cmd->se_cmd_flags & SCF_UNDERFLOW_BIT) { cmd->residual_count += cmd->data_length - length; } else { cmd->se_cmd_flags |= SCF_UNDERFLOW_BIT; cmd->residual_count = cmd->data_length - length; } cmd->data_length = length; } target_complete_cmd(cmd, scsi_status); } EXPORT_SYMBOL(target_complete_cmd_with_length); static void target_add_to_state_list(struct se_cmd *cmd) { struct se_device *dev = cmd->se_dev; unsigned long flags; spin_lock_irqsave(&dev->execute_task_lock, flags); if (!cmd->state_active) { list_add_tail(&cmd->state_list, &dev->state_list); cmd->state_active = true; } spin_unlock_irqrestore(&dev->execute_task_lock, flags); } /* * Handle QUEUE_FULL / -EAGAIN and -ENOMEM status */ static void transport_write_pending_qf(struct se_cmd *cmd); static void transport_complete_qf(struct se_cmd *cmd); void target_qf_do_work(struct work_struct *work) { struct se_device *dev = container_of(work, struct se_device, qf_work_queue); LIST_HEAD(qf_cmd_list); struct se_cmd *cmd, *cmd_tmp; spin_lock_irq(&dev->qf_cmd_lock); list_splice_init(&dev->qf_cmd_list, &qf_cmd_list); spin_unlock_irq(&dev->qf_cmd_lock); list_for_each_entry_safe(cmd, cmd_tmp, &qf_cmd_list, se_qf_node) { list_del(&cmd->se_qf_node); atomic_dec_mb(&dev->dev_qf_count); pr_debug("Processing %s cmd: %p QUEUE_FULL in work queue" " context: %s\n", cmd->se_tfo->get_fabric_name(), cmd, (cmd->t_state == TRANSPORT_COMPLETE_QF_OK) ? "COMPLETE_OK" : (cmd->t_state == TRANSPORT_COMPLETE_QF_WP) ? "WRITE_PENDING" : "UNKNOWN"); if (cmd->t_state == TRANSPORT_COMPLETE_QF_WP) transport_write_pending_qf(cmd); else if (cmd->t_state == TRANSPORT_COMPLETE_QF_OK) transport_complete_qf(cmd); } } unsigned char *transport_dump_cmd_direction(struct se_cmd *cmd) { switch (cmd->data_direction) { case DMA_NONE: return "NONE"; case DMA_FROM_DEVICE: return "READ"; case DMA_TO_DEVICE: return "WRITE"; case DMA_BIDIRECTIONAL: return "BIDI"; default: break; } return "UNKNOWN"; } void transport_dump_dev_state( struct se_device *dev, char *b, int *bl) { *bl += sprintf(b + *bl, "Status: "); if (dev->export_count) *bl += sprintf(b + *bl, "ACTIVATED"); else *bl += sprintf(b + *bl, "DEACTIVATED"); *bl += sprintf(b + *bl, " Max Queue Depth: %d", dev->queue_depth); *bl += sprintf(b + *bl, " SectorSize: %u HwMaxSectors: %u\n", dev->dev_attrib.block_size, dev->dev_attrib.hw_max_sectors); *bl += sprintf(b + *bl, " "); } void transport_dump_vpd_proto_id( struct t10_vpd *vpd, unsigned char *p_buf, int p_buf_len) { unsigned char buf[VPD_TMP_BUF_SIZE]; int len; memset(buf, 0, VPD_TMP_BUF_SIZE); len = sprintf(buf, "T10 VPD Protocol Identifier: "); switch (vpd->protocol_identifier) { case 0x00: sprintf(buf+len, "Fibre Channel\n"); break; case 0x10: sprintf(buf+len, "Parallel SCSI\n"); break; case 0x20: sprintf(buf+len, "SSA\n"); break; case 0x30: sprintf(buf+len, "IEEE 1394\n"); break; case 0x40: sprintf(buf+len, "SCSI Remote Direct Memory Access" " Protocol\n"); break; case 0x50: sprintf(buf+len, "Internet SCSI (iSCSI)\n"); break; case 0x60: sprintf(buf+len, "SAS Serial SCSI Protocol\n"); break; case 0x70: sprintf(buf+len, "Automation/Drive Interface Transport" " Protocol\n"); break; case 0x80: sprintf(buf+len, "AT Attachment Interface ATA/ATAPI\n"); break; default: sprintf(buf+len, "Unknown 0x%02x\n", vpd->protocol_identifier); break; } if (p_buf) strncpy(p_buf, buf, p_buf_len); else pr_debug("%s", buf); } void transport_set_vpd_proto_id(struct t10_vpd *vpd, unsigned char *page_83) { /* * Check if the Protocol Identifier Valid (PIV) bit is set.. * * from spc3r23.pdf section 7.5.1 */ if (page_83[1] & 0x80) { vpd->protocol_identifier = (page_83[0] & 0xf0); vpd->protocol_identifier_set = 1; transport_dump_vpd_proto_id(vpd, NULL, 0); } } EXPORT_SYMBOL(transport_set_vpd_proto_id); int transport_dump_vpd_assoc( struct t10_vpd *vpd, unsigned char *p_buf, int p_buf_len) { unsigned char buf[VPD_TMP_BUF_SIZE]; int ret = 0; int len; memset(buf, 0, VPD_TMP_BUF_SIZE); len = sprintf(buf, "T10 VPD Identifier Association: "); switch (vpd->association) { case 0x00: sprintf(buf+len, "addressed logical unit\n"); break; case 0x10: sprintf(buf+len, "target port\n"); break; case 0x20: sprintf(buf+len, "SCSI target device\n"); break; default: sprintf(buf+len, "Unknown 0x%02x\n", vpd->association); ret = -EINVAL; break; } if (p_buf) strncpy(p_buf, buf, p_buf_len); else pr_debug("%s", buf); return ret; } int transport_set_vpd_assoc(struct t10_vpd *vpd, unsigned char *page_83) { /* * The VPD identification association.. * * from spc3r23.pdf Section 7.6.3.1 Table 297 */ vpd->association = (page_83[1] & 0x30); return transport_dump_vpd_assoc(vpd, NULL, 0); } EXPORT_SYMBOL(transport_set_vpd_assoc); int transport_dump_vpd_ident_type( struct t10_vpd *vpd, unsigned char *p_buf, int p_buf_len) { unsigned char buf[VPD_TMP_BUF_SIZE]; int ret = 0; int len; memset(buf, 0, VPD_TMP_BUF_SIZE); len = sprintf(buf, "T10 VPD Identifier Type: "); switch (vpd->device_identifier_type) { case 0x00: sprintf(buf+len, "Vendor specific\n"); break; case 0x01: sprintf(buf+len, "T10 Vendor ID based\n"); break; case 0x02: sprintf(buf+len, "EUI-64 based\n"); break; case 0x03: sprintf(buf+len, "NAA\n"); break; case 0x04: sprintf(buf+len, "Relative target port identifier\n"); break; case 0x08: sprintf(buf+len, "SCSI name string\n"); break; default: sprintf(buf+len, "Unsupported: 0x%02x\n", vpd->device_identifier_type); ret = -EINVAL; break; } if (p_buf) { if (p_buf_len < strlen(buf)+1) return -EINVAL; strncpy(p_buf, buf, p_buf_len); } else { pr_debug("%s", buf); } return ret; } int transport_set_vpd_ident_type(struct t10_vpd *vpd, unsigned char *page_83) { /* * The VPD identifier type.. * * from spc3r23.pdf Section 7.6.3.1 Table 298 */ vpd->device_identifier_type = (page_83[1] & 0x0f); return transport_dump_vpd_ident_type(vpd, NULL, 0); } EXPORT_SYMBOL(transport_set_vpd_ident_type); int transport_dump_vpd_ident( struct t10_vpd *vpd, unsigned char *p_buf, int p_buf_len) { unsigned char buf[VPD_TMP_BUF_SIZE]; int ret = 0; memset(buf, 0, VPD_TMP_BUF_SIZE); switch (vpd->device_identifier_code_set) { case 0x01: /* Binary */ snprintf(buf, sizeof(buf), "T10 VPD Binary Device Identifier: %s\n", &vpd->device_identifier[0]); break; case 0x02: /* ASCII */ snprintf(buf, sizeof(buf), "T10 VPD ASCII Device Identifier: %s\n", &vpd->device_identifier[0]); break; case 0x03: /* UTF-8 */ snprintf(buf, sizeof(buf), "T10 VPD UTF-8 Device Identifier: %s\n", &vpd->device_identifier[0]); break; default: sprintf(buf, "T10 VPD Device Identifier encoding unsupported:" " 0x%02x", vpd->device_identifier_code_set); ret = -EINVAL; break; } if (p_buf) strncpy(p_buf, buf, p_buf_len); else pr_debug("%s", buf); return ret; } int transport_set_vpd_ident(struct t10_vpd *vpd, unsigned char *page_83) { static const char hex_str[] = "0123456789abcdef"; int j = 0, i = 4; /* offset to start of the identifier */ /* * The VPD Code Set (encoding) * * from spc3r23.pdf Section 7.6.3.1 Table 296 */ vpd->device_identifier_code_set = (page_83[0] & 0x0f); switch (vpd->device_identifier_code_set) { case 0x01: /* Binary */ vpd->device_identifier[j++] = hex_str[vpd->device_identifier_type]; while (i < (4 + page_83[3])) { vpd->device_identifier[j++] = hex_str[(page_83[i] & 0xf0) >> 4]; vpd->device_identifier[j++] = hex_str[page_83[i] & 0x0f]; i++; } break; case 0x02: /* ASCII */ case 0x03: /* UTF-8 */ while (i < (4 + page_83[3])) vpd->device_identifier[j++] = page_83[i++]; break; default: break; } return transport_dump_vpd_ident(vpd, NULL, 0); } EXPORT_SYMBOL(transport_set_vpd_ident); sense_reason_t target_cmd_size_check(struct se_cmd *cmd, unsigned int size) { struct se_device *dev = cmd->se_dev; if (cmd->unknown_data_length) { cmd->data_length = size; } else if (size != cmd->data_length) { pr_warn("TARGET_CORE[%s]: Expected Transfer Length:" " %u does not match SCSI CDB Length: %u for SAM Opcode:" " 0x%02x\n", cmd->se_tfo->get_fabric_name(), cmd->data_length, size, cmd->t_task_cdb[0]); if (cmd->data_direction == DMA_TO_DEVICE) { pr_err("Rejecting underflow/overflow" " WRITE data\n"); return TCM_INVALID_CDB_FIELD; } /* * Reject READ_* or WRITE_* with overflow/underflow for * type SCF_SCSI_DATA_CDB. */ if (dev->dev_attrib.block_size != 512) { pr_err("Failing OVERFLOW/UNDERFLOW for LBA op" " CDB on non 512-byte sector setup subsystem" " plugin: %s\n", dev->transport->name); /* Returns CHECK_CONDITION + INVALID_CDB_FIELD */ return TCM_INVALID_CDB_FIELD; } /* * For the overflow case keep the existing fabric provided * ->data_length. Otherwise for the underflow case, reset * ->data_length to the smaller SCSI expected data transfer * length. */ if (size > cmd->data_length) { cmd->se_cmd_flags |= SCF_OVERFLOW_BIT; cmd->residual_count = (size - cmd->data_length); } else { cmd->se_cmd_flags |= SCF_UNDERFLOW_BIT; cmd->residual_count = (cmd->data_length - size); cmd->data_length = size; } } return 0; } /* * Used by fabric modules containing a local struct se_cmd within their * fabric dependent per I/O descriptor. */ void transport_init_se_cmd( struct se_cmd *cmd, const struct target_core_fabric_ops *tfo, struct se_session *se_sess, u32 data_length, int data_direction, int task_attr, unsigned char *sense_buffer) { INIT_LIST_HEAD(&cmd->se_delayed_node); INIT_LIST_HEAD(&cmd->se_qf_node); INIT_LIST_HEAD(&cmd->se_cmd_list); INIT_LIST_HEAD(&cmd->state_list); init_completion(&cmd->t_transport_stop_comp); init_completion(&cmd->cmd_wait_comp); init_completion(&cmd->task_stop_comp); spin_lock_init(&cmd->t_state_lock); kref_init(&cmd->cmd_kref); cmd->transport_state = CMD_T_DEV_ACTIVE; cmd->se_tfo = tfo; cmd->se_sess = se_sess; cmd->data_length = data_length; cmd->data_direction = data_direction; cmd->sam_task_attr = task_attr; cmd->sense_buffer = sense_buffer; cmd->state_active = false; } EXPORT_SYMBOL(transport_init_se_cmd); static sense_reason_t transport_check_alloc_task_attr(struct se_cmd *cmd) { struct se_device *dev = cmd->se_dev; /* * Check if SAM Task Attribute emulation is enabled for this * struct se_device storage object */ if (dev->transport->transport_flags & TRANSPORT_FLAG_PASSTHROUGH) return 0; if (cmd->sam_task_attr == TCM_ACA_TAG) { pr_debug("SAM Task Attribute ACA" " emulation is not supported\n"); return TCM_INVALID_CDB_FIELD; } /* * Used to determine when ORDERED commands should go from * Dormant to Active status. */ cmd->se_ordered_id = atomic_inc_return(&dev->dev_ordered_id); pr_debug("Allocated se_ordered_id: %u for Task Attr: 0x%02x on %s\n", cmd->se_ordered_id, cmd->sam_task_attr, dev->transport->name); return 0; } sense_reason_t target_setup_cmd_from_cdb(struct se_cmd *cmd, unsigned char *cdb) { struct se_device *dev = cmd->se_dev; sense_reason_t ret; /* * Ensure that the received CDB is less than the max (252 + 8) bytes * for VARIABLE_LENGTH_CMD */ if (scsi_command_size(cdb) > SCSI_MAX_VARLEN_CDB_SIZE) { pr_err("Received SCSI CDB with command_size: %d that" " exceeds SCSI_MAX_VARLEN_CDB_SIZE: %d\n", scsi_command_size(cdb), SCSI_MAX_VARLEN_CDB_SIZE); return TCM_INVALID_CDB_FIELD; } /* * If the received CDB is larger than TCM_MAX_COMMAND_SIZE, * allocate the additional extended CDB buffer now.. Otherwise * setup the pointer from __t_task_cdb to t_task_cdb. */ if (scsi_command_size(cdb) > sizeof(cmd->__t_task_cdb)) { cmd->t_task_cdb = kzalloc(scsi_command_size(cdb), GFP_KERNEL); if (!cmd->t_task_cdb) { pr_err("Unable to allocate cmd->t_task_cdb" " %u > sizeof(cmd->__t_task_cdb): %lu ops\n", scsi_command_size(cdb), (unsigned long)sizeof(cmd->__t_task_cdb)); return TCM_OUT_OF_RESOURCES; } } else cmd->t_task_cdb = &cmd->__t_task_cdb[0]; /* * Copy the original CDB into cmd-> */ memcpy(cmd->t_task_cdb, cdb, scsi_command_size(cdb)); trace_target_sequencer_start(cmd); /* * Check for an existing UNIT ATTENTION condition */ ret = target_scsi3_ua_check(cmd); if (ret) return ret; ret = target_alua_state_check(cmd); if (ret) return ret; ret = target_check_reservation(cmd); if (ret) { cmd->scsi_status = SAM_STAT_RESERVATION_CONFLICT; return ret; } ret = dev->transport->parse_cdb(cmd); if (ret) return ret; ret = transport_check_alloc_task_attr(cmd); if (ret) return ret; cmd->se_cmd_flags |= SCF_SUPPORTED_SAM_OPCODE; spin_lock(&cmd->se_lun->lun_sep_lock); if (cmd->se_lun->lun_sep) cmd->se_lun->lun_sep->sep_stats.cmd_pdus++; spin_unlock(&cmd->se_lun->lun_sep_lock); return 0; } EXPORT_SYMBOL(target_setup_cmd_from_cdb); /* * Used by fabric module frontends to queue tasks directly. * Many only be used from process context only */ int transport_handle_cdb_direct( struct se_cmd *cmd) { sense_reason_t ret; if (!cmd->se_lun) { dump_stack(); pr_err("cmd->se_lun is NULL\n"); return -EINVAL; } if (in_interrupt()) { dump_stack(); pr_err("transport_generic_handle_cdb cannot be called" " from interrupt context\n"); return -EINVAL; } /* * Set TRANSPORT_NEW_CMD state and CMD_T_ACTIVE to ensure that * outstanding descriptors are handled correctly during shutdown via * transport_wait_for_tasks() * * Also, we don't take cmd->t_state_lock here as we only expect * this to be called for initial descriptor submission. */ cmd->t_state = TRANSPORT_NEW_CMD; cmd->transport_state |= CMD_T_ACTIVE; /* * transport_generic_new_cmd() is already handling QUEUE_FULL, * so follow TRANSPORT_NEW_CMD processing thread context usage * and call transport_generic_request_failure() if necessary.. */ ret = transport_generic_new_cmd(cmd); if (ret) transport_generic_request_failure(cmd, ret); return 0; } EXPORT_SYMBOL(transport_handle_cdb_direct); sense_reason_t transport_generic_map_mem_to_cmd(struct se_cmd *cmd, struct scatterlist *sgl, u32 sgl_count, struct scatterlist *sgl_bidi, u32 sgl_bidi_count) { if (!sgl || !sgl_count) return 0; /* * Reject SCSI data overflow with map_mem_to_cmd() as incoming * scatterlists already have been set to follow what the fabric * passes for the original expected data transfer length. */ if (cmd->se_cmd_flags & SCF_OVERFLOW_BIT) { pr_warn("Rejecting SCSI DATA overflow for fabric using" " SCF_PASSTHROUGH_SG_TO_MEM_NOALLOC\n"); return TCM_INVALID_CDB_FIELD; } cmd->t_data_sg = sgl; cmd->t_data_nents = sgl_count; if (sgl_bidi && sgl_bidi_count) { cmd->t_bidi_data_sg = sgl_bidi; cmd->t_bidi_data_nents = sgl_bidi_count; } cmd->se_cmd_flags |= SCF_PASSTHROUGH_SG_TO_MEM_NOALLOC; return 0; } /* * target_submit_cmd_map_sgls - lookup unpacked lun and submit uninitialized * se_cmd + use pre-allocated SGL memory. * * @se_cmd: command descriptor to submit * @se_sess: associated se_sess for endpoint * @cdb: pointer to SCSI CDB * @sense: pointer to SCSI sense buffer * @unpacked_lun: unpacked LUN to reference for struct se_lun * @data_length: fabric expected data transfer length * @task_addr: SAM task attribute * @data_dir: DMA data direction * @flags: flags for command submission from target_sc_flags_tables * @sgl: struct scatterlist memory for unidirectional mapping * @sgl_count: scatterlist count for unidirectional mapping * @sgl_bidi: struct scatterlist memory for bidirectional READ mapping * @sgl_bidi_count: scatterlist count for bidirectional READ mapping * @sgl_prot: struct scatterlist memory protection information * @sgl_prot_count: scatterlist count for protection information * * Returns non zero to signal active I/O shutdown failure. All other * setup exceptions will be returned as a SCSI CHECK_CONDITION response, * but still return zero here. * * This may only be called from process context, and also currently * assumes internal allocation of fabric payload buffer by target-core. */ int target_submit_cmd_map_sgls(struct se_cmd *se_cmd, struct se_session *se_sess, unsigned char *cdb, unsigned char *sense, u32 unpacked_lun, u32 data_length, int task_attr, int data_dir, int flags, struct scatterlist *sgl, u32 sgl_count, struct scatterlist *sgl_bidi, u32 sgl_bidi_count, struct scatterlist *sgl_prot, u32 sgl_prot_count) { struct se_portal_group *se_tpg; sense_reason_t rc; int ret; se_tpg = se_sess->se_tpg; BUG_ON(!se_tpg); BUG_ON(se_cmd->se_tfo || se_cmd->se_sess); BUG_ON(in_interrupt()); /* * Initialize se_cmd for target operation. From this point * exceptions are handled by sending exception status via * target_core_fabric_ops->queue_status() callback */ transport_init_se_cmd(se_cmd, se_tpg->se_tpg_tfo, se_sess, data_length, data_dir, task_attr, sense); if (flags & TARGET_SCF_UNKNOWN_SIZE) se_cmd->unknown_data_length = 1; /* * Obtain struct se_cmd->cmd_kref reference and add new cmd to * se_sess->sess_cmd_list. A second kref_get here is necessary * for fabrics using TARGET_SCF_ACK_KREF that expect a second * kref_put() to happen during fabric packet acknowledgement. */ ret = target_get_sess_cmd(se_cmd, flags & TARGET_SCF_ACK_KREF); if (ret) return ret; /* * Signal bidirectional data payloads to target-core */ if (flags & TARGET_SCF_BIDI_OP) se_cmd->se_cmd_flags |= SCF_BIDI; /* * Locate se_lun pointer and attach it to struct se_cmd */ rc = transport_lookup_cmd_lun(se_cmd, unpacked_lun); if (rc) { transport_send_check_condition_and_sense(se_cmd, rc, 0); target_put_sess_cmd(se_cmd); return 0; } rc = target_setup_cmd_from_cdb(se_cmd, cdb); if (rc != 0) { transport_generic_request_failure(se_cmd, rc); return 0; } /* * Save pointers for SGLs containing protection information, * if present. */ if (sgl_prot_count) { se_cmd->t_prot_sg = sgl_prot; se_cmd->t_prot_nents = sgl_prot_count; } /* * When a non zero sgl_count has been passed perform SGL passthrough * mapping for pre-allocated fabric memory instead of having target * core perform an internal SGL allocation.. */ if (sgl_count != 0) { BUG_ON(!sgl); /* * A work-around for tcm_loop as some userspace code via * scsi-generic do not memset their associated read buffers, * so go ahead and do that here for type non-data CDBs. Also * note that this is currently guaranteed to be a single SGL * for this case by target core in target_setup_cmd_from_cdb() * -> transport_generic_cmd_sequencer(). */ if (!(se_cmd->se_cmd_flags & SCF_SCSI_DATA_CDB) && se_cmd->data_direction == DMA_FROM_DEVICE) { unsigned char *buf = NULL; if (sgl) buf = kmap(sg_page(sgl)) + sgl->offset; if (buf) { memset(buf, 0, sgl->length); kunmap(sg_page(sgl)); } } rc = transport_generic_map_mem_to_cmd(se_cmd, sgl, sgl_count, sgl_bidi, sgl_bidi_count); if (rc != 0) { transport_generic_request_failure(se_cmd, rc); return 0; } } /* * Check if we need to delay processing because of ALUA * Active/NonOptimized primary access state.. */ core_alua_check_nonop_delay(se_cmd); transport_handle_cdb_direct(se_cmd); return 0; } EXPORT_SYMBOL(target_submit_cmd_map_sgls); /* * target_submit_cmd - lookup unpacked lun and submit uninitialized se_cmd * * @se_cmd: command descriptor to submit * @se_sess: associated se_sess for endpoint * @cdb: pointer to SCSI CDB * @sense: pointer to SCSI sense buffer * @unpacked_lun: unpacked LUN to reference for struct se_lun * @data_length: fabric expected data transfer length * @task_addr: SAM task attribute * @data_dir: DMA data direction * @flags: flags for command submission from target_sc_flags_tables * * Returns non zero to signal active I/O shutdown failure. All other * setup exceptions will be returned as a SCSI CHECK_CONDITION response, * but still return zero here. * * This may only be called from process context, and also currently * assumes internal allocation of fabric payload buffer by target-core. * * It also assumes interal target core SGL memory allocation. */ int target_submit_cmd(struct se_cmd *se_cmd, struct se_session *se_sess, unsigned char *cdb, unsigned char *sense, u32 unpacked_lun, u32 data_length, int task_attr, int data_dir, int flags) { return target_submit_cmd_map_sgls(se_cmd, se_sess, cdb, sense, unpacked_lun, data_length, task_attr, data_dir, flags, NULL, 0, NULL, 0, NULL, 0); } EXPORT_SYMBOL(target_submit_cmd); static void target_complete_tmr_failure(struct work_struct *work) { struct se_cmd *se_cmd = container_of(work, struct se_cmd, work); se_cmd->se_tmr_req->response = TMR_LUN_DOES_NOT_EXIST; se_cmd->se_tfo->queue_tm_rsp(se_cmd); transport_cmd_check_stop_to_fabric(se_cmd); } /** * target_submit_tmr - lookup unpacked lun and submit uninitialized se_cmd * for TMR CDBs * * @se_cmd: command descriptor to submit * @se_sess: associated se_sess for endpoint * @sense: pointer to SCSI sense buffer * @unpacked_lun: unpacked LUN to reference for struct se_lun * @fabric_context: fabric context for TMR req * @tm_type: Type of TM request * @gfp: gfp type for caller * @tag: referenced task tag for TMR_ABORT_TASK * @flags: submit cmd flags * * Callable from all contexts. **/ int target_submit_tmr(struct se_cmd *se_cmd, struct se_session *se_sess, unsigned char *sense, u32 unpacked_lun, void *fabric_tmr_ptr, unsigned char tm_type, gfp_t gfp, unsigned int tag, int flags) { struct se_portal_group *se_tpg; int ret; se_tpg = se_sess->se_tpg; BUG_ON(!se_tpg); transport_init_se_cmd(se_cmd, se_tpg->se_tpg_tfo, se_sess, 0, DMA_NONE, TCM_SIMPLE_TAG, sense); /* * FIXME: Currently expect caller to handle se_cmd->se_tmr_req * allocation failure. */ ret = core_tmr_alloc_req(se_cmd, fabric_tmr_ptr, tm_type, gfp); if (ret < 0) return -ENOMEM; if (tm_type == TMR_ABORT_TASK) se_cmd->se_tmr_req->ref_task_tag = tag; /* See target_submit_cmd for commentary */ ret = target_get_sess_cmd(se_cmd, flags & TARGET_SCF_ACK_KREF); if (ret) { core_tmr_release_req(se_cmd->se_tmr_req); return ret; } ret = transport_lookup_tmr_lun(se_cmd, unpacked_lun); if (ret) { /* * For callback during failure handling, push this work off * to process context with TMR_LUN_DOES_NOT_EXIST status. */ INIT_WORK(&se_cmd->work, target_complete_tmr_failure); schedule_work(&se_cmd->work); return 0; } transport_generic_handle_tmr(se_cmd); return 0; } EXPORT_SYMBOL(target_submit_tmr); /* * If the cmd is active, request it to be stopped and sleep until it * has completed. */ bool target_stop_cmd(struct se_cmd *cmd, unsigned long *flags) __releases(&cmd->t_state_lock) __acquires(&cmd->t_state_lock) { bool was_active = false; if (cmd->transport_state & CMD_T_BUSY) { cmd->transport_state |= CMD_T_REQUEST_STOP; spin_unlock_irqrestore(&cmd->t_state_lock, *flags); pr_debug("cmd %p waiting to complete\n", cmd); wait_for_completion(&cmd->task_stop_comp); pr_debug("cmd %p stopped successfully\n", cmd); spin_lock_irqsave(&cmd->t_state_lock, *flags); cmd->transport_state &= ~CMD_T_REQUEST_STOP; cmd->transport_state &= ~CMD_T_BUSY; was_active = true; } return was_active; } /* * Handle SAM-esque emulation for generic transport request failures. */ void transport_generic_request_failure(struct se_cmd *cmd, sense_reason_t sense_reason) { int ret = 0, post_ret = 0; pr_debug("-----[ Storage Engine Exception for cmd: %p ITT: 0x%08x" " CDB: 0x%02x\n", cmd, cmd->se_tfo->get_task_tag(cmd), cmd->t_task_cdb[0]); pr_debug("-----[ i_state: %d t_state: %d sense_reason: %d\n", cmd->se_tfo->get_cmd_state(cmd), cmd->t_state, sense_reason); pr_debug("-----[ CMD_T_ACTIVE: %d CMD_T_STOP: %d CMD_T_SENT: %d\n", (cmd->transport_state & CMD_T_ACTIVE) != 0, (cmd->transport_state & CMD_T_STOP) != 0, (cmd->transport_state & CMD_T_SENT) != 0); /* * For SAM Task Attribute emulation for failed struct se_cmd */ transport_complete_task_attr(cmd); /* * Handle special case for COMPARE_AND_WRITE failure, where the * callback is expected to drop the per device ->caw_sem. */ if ((cmd->se_cmd_flags & SCF_COMPARE_AND_WRITE) && cmd->transport_complete_callback) cmd->transport_complete_callback(cmd, false, &post_ret); switch (sense_reason) { case TCM_NON_EXISTENT_LUN: case TCM_UNSUPPORTED_SCSI_OPCODE: case TCM_INVALID_CDB_FIELD: case TCM_INVALID_PARAMETER_LIST: case TCM_PARAMETER_LIST_LENGTH_ERROR: case TCM_LOGICAL_UNIT_COMMUNICATION_FAILURE: case TCM_UNKNOWN_MODE_PAGE: case TCM_WRITE_PROTECTED: case TCM_ADDRESS_OUT_OF_RANGE: case TCM_CHECK_CONDITION_ABORT_CMD: case TCM_CHECK_CONDITION_UNIT_ATTENTION: case TCM_CHECK_CONDITION_NOT_READY: case TCM_LOGICAL_BLOCK_GUARD_CHECK_FAILED: case TCM_LOGICAL_BLOCK_APP_TAG_CHECK_FAILED: case TCM_LOGICAL_BLOCK_REF_TAG_CHECK_FAILED: break; case TCM_OUT_OF_RESOURCES: sense_reason = TCM_LOGICAL_UNIT_COMMUNICATION_FAILURE; break; case TCM_RESERVATION_CONFLICT: /* * No SENSE Data payload for this case, set SCSI Status * and queue the response to $FABRIC_MOD. * * Uses linux/include/scsi/scsi.h SAM status codes defs */ cmd->scsi_status = SAM_STAT_RESERVATION_CONFLICT; /* * For UA Interlock Code 11b, a RESERVATION CONFLICT will * establish a UNIT ATTENTION with PREVIOUS RESERVATION * CONFLICT STATUS. * * See spc4r17, section 7.4.6 Control Mode Page, Table 349 */ if (cmd->se_sess && cmd->se_dev->dev_attrib.emulate_ua_intlck_ctrl == 2) core_scsi3_ua_allocate(cmd->se_sess->se_node_acl, cmd->orig_fe_lun, 0x2C, ASCQ_2CH_PREVIOUS_RESERVATION_CONFLICT_STATUS); trace_target_cmd_complete(cmd); ret = cmd->se_tfo-> queue_status(cmd); if (ret == -EAGAIN || ret == -ENOMEM) goto queue_full; goto check_stop; default: pr_err("Unknown transport error for CDB 0x%02x: %d\n", cmd->t_task_cdb[0], sense_reason); sense_reason = TCM_UNSUPPORTED_SCSI_OPCODE; break; } ret = transport_send_check_condition_and_sense(cmd, sense_reason, 0); if (ret == -EAGAIN || ret == -ENOMEM) goto queue_full; check_stop: transport_lun_remove_cmd(cmd); if (!transport_cmd_check_stop_to_fabric(cmd)) ; return; queue_full: cmd->t_state = TRANSPORT_COMPLETE_QF_OK; transport_handle_queue_full(cmd, cmd->se_dev); } EXPORT_SYMBOL(transport_generic_request_failure); void __target_execute_cmd(struct se_cmd *cmd) { sense_reason_t ret; if (cmd->execute_cmd) { ret = cmd->execute_cmd(cmd); if (ret) { spin_lock_irq(&cmd->t_state_lock); cmd->transport_state &= ~(CMD_T_BUSY|CMD_T_SENT); spin_unlock_irq(&cmd->t_state_lock); transport_generic_request_failure(cmd, ret); } } } static int target_write_prot_action(struct se_cmd *cmd) { u32 sectors; /* * Perform WRITE_INSERT of PI using software emulation when backend * device has PI enabled, if the transport has not already generated * PI using hardware WRITE_INSERT offload. */ switch (cmd->prot_op) { case TARGET_PROT_DOUT_INSERT: if (!(cmd->se_sess->sup_prot_ops & TARGET_PROT_DOUT_INSERT)) sbc_dif_generate(cmd); break; case TARGET_PROT_DOUT_STRIP: if (cmd->se_sess->sup_prot_ops & TARGET_PROT_DOUT_STRIP) break; sectors = cmd->data_length >> ilog2(cmd->se_dev->dev_attrib.block_size); cmd->pi_err = sbc_dif_verify_write(cmd, cmd->t_task_lba, sectors, 0, NULL, 0); if (unlikely(cmd->pi_err)) { spin_lock_irq(&cmd->t_state_lock); cmd->transport_state &= ~(CMD_T_BUSY|CMD_T_SENT); spin_unlock_irq(&cmd->t_state_lock); transport_generic_request_failure(cmd, cmd->pi_err); return -1; } break; default: break; } return 0; } static bool target_handle_task_attr(struct se_cmd *cmd) { struct se_device *dev = cmd->se_dev; if (dev->transport->transport_flags & TRANSPORT_FLAG_PASSTHROUGH) return false; /* * Check for the existence of HEAD_OF_QUEUE, and if true return 1 * to allow the passed struct se_cmd list of tasks to the front of the list. */ switch (cmd->sam_task_attr) { case TCM_HEAD_TAG: pr_debug("Added HEAD_OF_QUEUE for CDB: 0x%02x, " "se_ordered_id: %u\n", cmd->t_task_cdb[0], cmd->se_ordered_id); return false; case TCM_ORDERED_TAG: atomic_inc_mb(&dev->dev_ordered_sync); pr_debug("Added ORDERED for CDB: 0x%02x to ordered list, " " se_ordered_id: %u\n", cmd->t_task_cdb[0], cmd->se_ordered_id); /* * Execute an ORDERED command if no other older commands * exist that need to be completed first. */ if (!atomic_read(&dev->simple_cmds)) return false; break; default: /* * For SIMPLE and UNTAGGED Task Attribute commands */ atomic_inc_mb(&dev->simple_cmds); break; } if (atomic_read(&dev->dev_ordered_sync) == 0) return false; spin_lock(&dev->delayed_cmd_lock); list_add_tail(&cmd->se_delayed_node, &dev->delayed_cmd_list); spin_unlock(&dev->delayed_cmd_lock); pr_debug("Added CDB: 0x%02x Task Attr: 0x%02x to" " delayed CMD list, se_ordered_id: %u\n", cmd->t_task_cdb[0], cmd->sam_task_attr, cmd->se_ordered_id); return true; } static int __transport_check_aborted_status(struct se_cmd *, int); void target_execute_cmd(struct se_cmd *cmd) { /* * Determine if frontend context caller is requesting the stopping of * this command for frontend exceptions. * * If the received CDB has aleady been aborted stop processing it here. */ spin_lock_irq(&cmd->t_state_lock); if (__transport_check_aborted_status(cmd, 1)) { spin_unlock_irq(&cmd->t_state_lock); return; } if (cmd->transport_state & CMD_T_STOP) { pr_debug("%s:%d CMD_T_STOP for ITT: 0x%08x\n", __func__, __LINE__, cmd->se_tfo->get_task_tag(cmd)); spin_unlock_irq(&cmd->t_state_lock); complete_all(&cmd->t_transport_stop_comp); return; } cmd->t_state = TRANSPORT_PROCESSING; cmd->transport_state |= CMD_T_ACTIVE|CMD_T_BUSY|CMD_T_SENT; spin_unlock_irq(&cmd->t_state_lock); if (target_write_prot_action(cmd)) return; if (target_handle_task_attr(cmd)) { spin_lock_irq(&cmd->t_state_lock); cmd->transport_state &= ~(CMD_T_BUSY | CMD_T_SENT); spin_unlock_irq(&cmd->t_state_lock); return; } __target_execute_cmd(cmd); } EXPORT_SYMBOL(target_execute_cmd); /* * Process all commands up to the last received ORDERED task attribute which * requires another blocking boundary */ static void target_restart_delayed_cmds(struct se_device *dev) { for (;;) { struct se_cmd *cmd; spin_lock(&dev->delayed_cmd_lock); if (list_empty(&dev->delayed_cmd_list)) { spin_unlock(&dev->delayed_cmd_lock); break; } cmd = list_entry(dev->delayed_cmd_list.next, struct se_cmd, se_delayed_node); list_del(&cmd->se_delayed_node); spin_unlock(&dev->delayed_cmd_lock); __target_execute_cmd(cmd); if (cmd->sam_task_attr == TCM_ORDERED_TAG) break; } } /* * Called from I/O completion to determine which dormant/delayed * and ordered cmds need to have their tasks added to the execution queue. */ static void transport_complete_task_attr(struct se_cmd *cmd) { struct se_device *dev = cmd->se_dev; if (dev->transport->transport_flags & TRANSPORT_FLAG_PASSTHROUGH) return; if (cmd->sam_task_attr == TCM_SIMPLE_TAG) { atomic_dec_mb(&dev->simple_cmds); dev->dev_cur_ordered_id++; pr_debug("Incremented dev->dev_cur_ordered_id: %u for" " SIMPLE: %u\n", dev->dev_cur_ordered_id, cmd->se_ordered_id); } else if (cmd->sam_task_attr == TCM_HEAD_TAG) { dev->dev_cur_ordered_id++; pr_debug("Incremented dev_cur_ordered_id: %u for" " HEAD_OF_QUEUE: %u\n", dev->dev_cur_ordered_id, cmd->se_ordered_id); } else if (cmd->sam_task_attr == TCM_ORDERED_TAG) { atomic_dec_mb(&dev->dev_ordered_sync); dev->dev_cur_ordered_id++; pr_debug("Incremented dev_cur_ordered_id: %u for ORDERED:" " %u\n", dev->dev_cur_ordered_id, cmd->se_ordered_id); } target_restart_delayed_cmds(dev); } static void transport_complete_qf(struct se_cmd *cmd) { int ret = 0; transport_complete_task_attr(cmd); if (cmd->se_cmd_flags & SCF_TRANSPORT_TASK_SENSE) { trace_target_cmd_complete(cmd); ret = cmd->se_tfo->queue_status(cmd); goto out; } switch (cmd->data_direction) { case DMA_FROM_DEVICE: trace_target_cmd_complete(cmd); ret = cmd->se_tfo->queue_data_in(cmd); break; case DMA_TO_DEVICE: if (cmd->se_cmd_flags & SCF_BIDI) { ret = cmd->se_tfo->queue_data_in(cmd); break; } /* Fall through for DMA_TO_DEVICE */ case DMA_NONE: trace_target_cmd_complete(cmd); ret = cmd->se_tfo->queue_status(cmd); break; default: break; } out: if (ret < 0) { transport_handle_queue_full(cmd, cmd->se_dev); return; } transport_lun_remove_cmd(cmd); transport_cmd_check_stop_to_fabric(cmd); } static void transport_handle_queue_full( struct se_cmd *cmd, struct se_device *dev) { spin_lock_irq(&dev->qf_cmd_lock); list_add_tail(&cmd->se_qf_node, &cmd->se_dev->qf_cmd_list); atomic_inc_mb(&dev->dev_qf_count); spin_unlock_irq(&cmd->se_dev->qf_cmd_lock); schedule_work(&cmd->se_dev->qf_work_queue); } static bool target_read_prot_action(struct se_cmd *cmd) { sense_reason_t rc; switch (cmd->prot_op) { case TARGET_PROT_DIN_STRIP: if (!(cmd->se_sess->sup_prot_ops & TARGET_PROT_DIN_STRIP)) { rc = sbc_dif_read_strip(cmd); if (rc) { cmd->pi_err = rc; return true; } } break; case TARGET_PROT_DIN_INSERT: if (cmd->se_sess->sup_prot_ops & TARGET_PROT_DIN_INSERT) break; sbc_dif_generate(cmd); break; default: break; } return false; } static void target_complete_ok_work(struct work_struct *work) { struct se_cmd *cmd = container_of(work, struct se_cmd, work); int ret; /* * Check if we need to move delayed/dormant tasks from cmds on the * delayed execution list after a HEAD_OF_QUEUE or ORDERED Task * Attribute. */ transport_complete_task_attr(cmd); /* * Check to schedule QUEUE_FULL work, or execute an existing * cmd->transport_qf_callback() */ if (atomic_read(&cmd->se_dev->dev_qf_count) != 0) schedule_work(&cmd->se_dev->qf_work_queue); /* * Check if we need to send a sense buffer from * the struct se_cmd in question. */ if (cmd->se_cmd_flags & SCF_TRANSPORT_TASK_SENSE) { WARN_ON(!cmd->scsi_status); ret = transport_send_check_condition_and_sense( cmd, 0, 1); if (ret == -EAGAIN || ret == -ENOMEM) goto queue_full; transport_lun_remove_cmd(cmd); transport_cmd_check_stop_to_fabric(cmd); return; } /* * Check for a callback, used by amongst other things * XDWRITE_READ_10 and COMPARE_AND_WRITE emulation. */ if (cmd->transport_complete_callback) { sense_reason_t rc; bool caw = (cmd->se_cmd_flags & SCF_COMPARE_AND_WRITE); bool zero_dl = !(cmd->data_length); int post_ret = 0; rc = cmd->transport_complete_callback(cmd, true, &post_ret); if (!rc && !post_ret) { if (caw && zero_dl) goto queue_rsp; return; } else if (rc) { ret = transport_send_check_condition_and_sense(cmd, rc, 0); if (ret == -EAGAIN || ret == -ENOMEM) goto queue_full; transport_lun_remove_cmd(cmd); transport_cmd_check_stop_to_fabric(cmd); return; } } queue_rsp: switch (cmd->data_direction) { case DMA_FROM_DEVICE: spin_lock(&cmd->se_lun->lun_sep_lock); if (cmd->se_lun->lun_sep) { cmd->se_lun->lun_sep->sep_stats.tx_data_octets += cmd->data_length; } spin_unlock(&cmd->se_lun->lun_sep_lock); /* * Perform READ_STRIP of PI using software emulation when * backend had PI enabled, if the transport will not be * performing hardware READ_STRIP offload. */ if (target_read_prot_action(cmd)) { ret = transport_send_check_condition_and_sense(cmd, cmd->pi_err, 0); if (ret == -EAGAIN || ret == -ENOMEM) goto queue_full; transport_lun_remove_cmd(cmd); transport_cmd_check_stop_to_fabric(cmd); return; } trace_target_cmd_complete(cmd); ret = cmd->se_tfo->queue_data_in(cmd); if (ret == -EAGAIN || ret == -ENOMEM) goto queue_full; break; case DMA_TO_DEVICE: spin_lock(&cmd->se_lun->lun_sep_lock); if (cmd->se_lun->lun_sep) { cmd->se_lun->lun_sep->sep_stats.rx_data_octets += cmd->data_length; } spin_unlock(&cmd->se_lun->lun_sep_lock); /* * Check if we need to send READ payload for BIDI-COMMAND */ if (cmd->se_cmd_flags & SCF_BIDI) { spin_lock(&cmd->se_lun->lun_sep_lock); if (cmd->se_lun->lun_sep) { cmd->se_lun->lun_sep->sep_stats.tx_data_octets += cmd->data_length; } spin_unlock(&cmd->se_lun->lun_sep_lock); ret = cmd->se_tfo->queue_data_in(cmd); if (ret == -EAGAIN || ret == -ENOMEM) goto queue_full; break; } /* Fall through for DMA_TO_DEVICE */ case DMA_NONE: trace_target_cmd_complete(cmd); ret = cmd->se_tfo->queue_status(cmd); if (ret == -EAGAIN || ret == -ENOMEM) goto queue_full; break; default: break; } transport_lun_remove_cmd(cmd); transport_cmd_check_stop_to_fabric(cmd); return; queue_full: pr_debug("Handling complete_ok QUEUE_FULL: se_cmd: %p," " data_direction: %d\n", cmd, cmd->data_direction); cmd->t_state = TRANSPORT_COMPLETE_QF_OK; transport_handle_queue_full(cmd, cmd->se_dev); } static inline void transport_free_sgl(struct scatterlist *sgl, int nents) { struct scatterlist *sg; int count; for_each_sg(sgl, sg, nents, count) __free_page(sg_page(sg)); kfree(sgl); } static inline void transport_reset_sgl_orig(struct se_cmd *cmd) { /* * Check for saved t_data_sg that may be used for COMPARE_AND_WRITE * emulation, and free + reset pointers if necessary.. */ if (!cmd->t_data_sg_orig) return; kfree(cmd->t_data_sg); cmd->t_data_sg = cmd->t_data_sg_orig; cmd->t_data_sg_orig = NULL; cmd->t_data_nents = cmd->t_data_nents_orig; cmd->t_data_nents_orig = 0; } static inline void transport_free_pages(struct se_cmd *cmd) { if (cmd->se_cmd_flags & SCF_PASSTHROUGH_SG_TO_MEM_NOALLOC) { /* * Release special case READ buffer payload required for * SG_TO_MEM_NOALLOC to function with COMPARE_AND_WRITE */ if (cmd->se_cmd_flags & SCF_COMPARE_AND_WRITE) { transport_free_sgl(cmd->t_bidi_data_sg, cmd->t_bidi_data_nents); cmd->t_bidi_data_sg = NULL; cmd->t_bidi_data_nents = 0; } transport_reset_sgl_orig(cmd); return; } transport_reset_sgl_orig(cmd); transport_free_sgl(cmd->t_data_sg, cmd->t_data_nents); cmd->t_data_sg = NULL; cmd->t_data_nents = 0; transport_free_sgl(cmd->t_bidi_data_sg, cmd->t_bidi_data_nents); cmd->t_bidi_data_sg = NULL; cmd->t_bidi_data_nents = 0; transport_free_sgl(cmd->t_prot_sg, cmd->t_prot_nents); cmd->t_prot_sg = NULL; cmd->t_prot_nents = 0; } /** * transport_put_cmd - release a reference to a command * @cmd: command to release * * This routine releases our reference to the command and frees it if possible. */ static int transport_put_cmd(struct se_cmd *cmd) { BUG_ON(!cmd->se_tfo); /* * If this cmd has been setup with target_get_sess_cmd(), drop * the kref and call ->release_cmd() in kref callback. */ return target_put_sess_cmd(cmd); } void *transport_kmap_data_sg(struct se_cmd *cmd) { struct scatterlist *sg = cmd->t_data_sg; struct page **pages; int i; /* * We need to take into account a possible offset here for fabrics like * tcm_loop who may be using a contig buffer from the SCSI midlayer for * control CDBs passed as SGLs via transport_generic_map_mem_to_cmd() */ if (!cmd->t_data_nents) return NULL; BUG_ON(!sg); if (cmd->t_data_nents == 1) return kmap(sg_page(sg)) + sg->offset; /* >1 page. use vmap */ pages = kmalloc(sizeof(*pages) * cmd->t_data_nents, GFP_KERNEL); if (!pages) return NULL; /* convert sg[] to pages[] */ for_each_sg(cmd->t_data_sg, sg, cmd->t_data_nents, i) { pages[i] = sg_page(sg); } cmd->t_data_vmap = vmap(pages, cmd->t_data_nents, VM_MAP, PAGE_KERNEL); kfree(pages); if (!cmd->t_data_vmap) return NULL; return cmd->t_data_vmap + cmd->t_data_sg[0].offset; } EXPORT_SYMBOL(transport_kmap_data_sg); void transport_kunmap_data_sg(struct se_cmd *cmd) { if (!cmd->t_data_nents) { return; } else if (cmd->t_data_nents == 1) { kunmap(sg_page(cmd->t_data_sg)); return; } vunmap(cmd->t_data_vmap); cmd->t_data_vmap = NULL; } EXPORT_SYMBOL(transport_kunmap_data_sg); int target_alloc_sgl(struct scatterlist **sgl, unsigned int *nents, u32 length, bool zero_page) { struct scatterlist *sg; struct page *page; gfp_t zero_flag = (zero_page) ? __GFP_ZERO : 0; unsigned int nent; int i = 0; nent = DIV_ROUND_UP(length, PAGE_SIZE); sg = kmalloc(sizeof(struct scatterlist) * nent, GFP_KERNEL); if (!sg) return -ENOMEM; sg_init_table(sg, nent); while (length) { u32 page_len = min_t(u32, length, PAGE_SIZE); page = alloc_page(GFP_KERNEL | zero_flag); if (!page) goto out; sg_set_page(&sg[i], page, page_len, 0); length -= page_len; i++; } *sgl = sg; *nents = nent; return 0; out: while (i > 0) { i--; __free_page(sg_page(&sg[i])); } kfree(sg); return -ENOMEM; } /* * Allocate any required resources to execute the command. For writes we * might not have the payload yet, so notify the fabric via a call to * ->write_pending instead. Otherwise place it on the execution queue. */ sense_reason_t transport_generic_new_cmd(struct se_cmd *cmd) { int ret = 0; bool zero_flag = !(cmd->se_cmd_flags & SCF_SCSI_DATA_CDB); /* * Determine is the TCM fabric module has already allocated physical * memory, and is directly calling transport_generic_map_mem_to_cmd() * beforehand. */ if (!(cmd->se_cmd_flags & SCF_PASSTHROUGH_SG_TO_MEM_NOALLOC) && cmd->data_length) { if ((cmd->se_cmd_flags & SCF_BIDI) || (cmd->se_cmd_flags & SCF_COMPARE_AND_WRITE)) { u32 bidi_length; if (cmd->se_cmd_flags & SCF_COMPARE_AND_WRITE) bidi_length = cmd->t_task_nolb * cmd->se_dev->dev_attrib.block_size; else bidi_length = cmd->data_length; ret = target_alloc_sgl(&cmd->t_bidi_data_sg, &cmd->t_bidi_data_nents, bidi_length, zero_flag); if (ret < 0) return TCM_LOGICAL_UNIT_COMMUNICATION_FAILURE; } if (cmd->prot_op != TARGET_PROT_NORMAL) { ret = target_alloc_sgl(&cmd->t_prot_sg, &cmd->t_prot_nents, cmd->prot_length, true); if (ret < 0) return TCM_LOGICAL_UNIT_COMMUNICATION_FAILURE; } ret = target_alloc_sgl(&cmd->t_data_sg, &cmd->t_data_nents, cmd->data_length, zero_flag); if (ret < 0) return TCM_LOGICAL_UNIT_COMMUNICATION_FAILURE; } else if ((cmd->se_cmd_flags & SCF_COMPARE_AND_WRITE) && cmd->data_length) { /* * Special case for COMPARE_AND_WRITE with fabrics * using SCF_PASSTHROUGH_SG_TO_MEM_NOALLOC. */ u32 caw_length = cmd->t_task_nolb * cmd->se_dev->dev_attrib.block_size; ret = target_alloc_sgl(&cmd->t_bidi_data_sg, &cmd->t_bidi_data_nents, caw_length, zero_flag); if (ret < 0) return TCM_LOGICAL_UNIT_COMMUNICATION_FAILURE; } /* * If this command is not a write we can execute it right here, * for write buffers we need to notify the fabric driver first * and let it call back once the write buffers are ready. */ target_add_to_state_list(cmd); if (cmd->data_direction != DMA_TO_DEVICE || cmd->data_length == 0) { target_execute_cmd(cmd); return 0; } transport_cmd_check_stop(cmd, false, true); ret = cmd->se_tfo->write_pending(cmd); if (ret == -EAGAIN || ret == -ENOMEM) goto queue_full; /* fabric drivers should only return -EAGAIN or -ENOMEM as error */ WARN_ON(ret); return (!ret) ? 0 : TCM_LOGICAL_UNIT_COMMUNICATION_FAILURE; queue_full: pr_debug("Handling write_pending QUEUE__FULL: se_cmd: %p\n", cmd); cmd->t_state = TRANSPORT_COMPLETE_QF_WP; transport_handle_queue_full(cmd, cmd->se_dev); return 0; } EXPORT_SYMBOL(transport_generic_new_cmd); static void transport_write_pending_qf(struct se_cmd *cmd) { int ret; ret = cmd->se_tfo->write_pending(cmd); if (ret == -EAGAIN || ret == -ENOMEM) { pr_debug("Handling write_pending QUEUE__FULL: se_cmd: %p\n", cmd); transport_handle_queue_full(cmd, cmd->se_dev); } } static bool __transport_wait_for_tasks(struct se_cmd *, bool, bool *, bool *, unsigned long *flags); static void target_wait_free_cmd(struct se_cmd *cmd, bool *aborted, bool *tas) { unsigned long flags; spin_lock_irqsave(&cmd->t_state_lock, flags); __transport_wait_for_tasks(cmd, true, aborted, tas, &flags); spin_unlock_irqrestore(&cmd->t_state_lock, flags); } int transport_generic_free_cmd(struct se_cmd *cmd, int wait_for_tasks) { int ret = 0; bool aborted = false, tas = false; if (!(cmd->se_cmd_flags & SCF_SE_LUN_CMD)) { if (wait_for_tasks && (cmd->se_cmd_flags & SCF_SCSI_TMR_CDB)) target_wait_free_cmd(cmd, &aborted, &tas); if (!aborted || tas) ret = transport_put_cmd(cmd); } else { if (wait_for_tasks) target_wait_free_cmd(cmd, &aborted, &tas); /* * Handle WRITE failure case where transport_generic_new_cmd() * has already added se_cmd to state_list, but fabric has * failed command before I/O submission. */ if (cmd->state_active) target_remove_from_state_list(cmd); if (cmd->se_lun) transport_lun_remove_cmd(cmd); if (!aborted || tas) ret = transport_put_cmd(cmd); } /* * If the task has been internally aborted due to TMR ABORT_TASK * or LUN_RESET, target_core_tmr.c is responsible for performing * the remaining calls to target_put_sess_cmd(), and not the * callers of this function. */ if (aborted) { pr_debug("Detected CMD_T_ABORTED for ITT: %u\n", cmd->se_tfo->get_task_tag(cmd)); wait_for_completion(&cmd->cmd_wait_comp); cmd->se_tfo->release_cmd(cmd); ret = 1; } return ret; } EXPORT_SYMBOL(transport_generic_free_cmd); /* target_get_sess_cmd - Add command to active ->sess_cmd_list * @se_cmd: command descriptor to add * @ack_kref: Signal that fabric will perform an ack target_put_sess_cmd() */ int target_get_sess_cmd(struct se_cmd *se_cmd, bool ack_kref) { struct se_session *se_sess = se_cmd->se_sess; unsigned long flags; int ret = 0; /* * Add a second kref if the fabric caller is expecting to handle * fabric acknowledgement that requires two target_put_sess_cmd() * invocations before se_cmd descriptor release. */ if (ack_kref) { kref_get(&se_cmd->cmd_kref); se_cmd->se_cmd_flags |= SCF_ACK_KREF; } spin_lock_irqsave(&se_sess->sess_cmd_lock, flags); if (se_sess->sess_tearing_down) { ret = -ESHUTDOWN; goto out; } list_add_tail(&se_cmd->se_cmd_list, &se_sess->sess_cmd_list); out: spin_unlock_irqrestore(&se_sess->sess_cmd_lock, flags); if (ret && ack_kref) target_put_sess_cmd(se_cmd); return ret; } EXPORT_SYMBOL(target_get_sess_cmd); static void target_free_cmd_mem(struct se_cmd *cmd) { transport_free_pages(cmd); if (cmd->se_cmd_flags & SCF_SCSI_TMR_CDB) core_tmr_release_req(cmd->se_tmr_req); if (cmd->t_task_cdb != cmd->__t_task_cdb) kfree(cmd->t_task_cdb); } static void target_release_cmd_kref(struct kref *kref) __releases(&se_cmd->se_sess->sess_cmd_lock) { struct se_cmd *se_cmd = container_of(kref, struct se_cmd, cmd_kref); struct se_session *se_sess = se_cmd->se_sess; bool fabric_stop; spin_lock(&se_cmd->t_state_lock); fabric_stop = (se_cmd->transport_state & CMD_T_FABRIC_STOP) && (se_cmd->transport_state & CMD_T_ABORTED); spin_unlock(&se_cmd->t_state_lock); if (se_cmd->cmd_wait_set || fabric_stop) { list_del_init(&se_cmd->se_cmd_list); spin_unlock(&se_sess->sess_cmd_lock); target_free_cmd_mem(se_cmd); complete(&se_cmd->cmd_wait_comp); return; } list_del_init(&se_cmd->se_cmd_list); spin_unlock(&se_sess->sess_cmd_lock); target_free_cmd_mem(se_cmd); se_cmd->se_tfo->release_cmd(se_cmd); } /* target_put_sess_cmd - Check for active I/O shutdown via kref_put * @se_cmd: command descriptor to drop */ int target_put_sess_cmd(struct se_cmd *se_cmd) { struct se_session *se_sess = se_cmd->se_sess; if (!se_sess) { target_free_cmd_mem(se_cmd); se_cmd->se_tfo->release_cmd(se_cmd); return 1; } return kref_put_spinlock_irqsave(&se_cmd->cmd_kref, target_release_cmd_kref, &se_sess->sess_cmd_lock); } EXPORT_SYMBOL(target_put_sess_cmd); /* target_sess_cmd_list_set_waiting - Flag all commands in * sess_cmd_list to complete cmd_wait_comp. Set * sess_tearing_down so no more commands are queued. * @se_sess: session to flag */ void target_sess_cmd_list_set_waiting(struct se_session *se_sess) { struct se_cmd *se_cmd; unsigned long flags; int rc; spin_lock_irqsave(&se_sess->sess_cmd_lock, flags); if (se_sess->sess_tearing_down) { spin_unlock_irqrestore(&se_sess->sess_cmd_lock, flags); return; } se_sess->sess_tearing_down = 1; list_splice_init(&se_sess->sess_cmd_list, &se_sess->sess_wait_list); list_for_each_entry(se_cmd, &se_sess->sess_wait_list, se_cmd_list) { rc = kref_get_unless_zero(&se_cmd->cmd_kref); if (rc) { se_cmd->cmd_wait_set = 1; spin_lock(&se_cmd->t_state_lock); se_cmd->transport_state |= CMD_T_FABRIC_STOP; spin_unlock(&se_cmd->t_state_lock); } } spin_unlock_irqrestore(&se_sess->sess_cmd_lock, flags); } EXPORT_SYMBOL(target_sess_cmd_list_set_waiting); /* target_wait_for_sess_cmds - Wait for outstanding descriptors * @se_sess: session to wait for active I/O */ void target_wait_for_sess_cmds(struct se_session *se_sess) { struct se_cmd *se_cmd, *tmp_cmd; unsigned long flags; bool tas; list_for_each_entry_safe(se_cmd, tmp_cmd, &se_sess->sess_wait_list, se_cmd_list) { pr_debug("Waiting for se_cmd: %p t_state: %d, fabric state:" " %d\n", se_cmd, se_cmd->t_state, se_cmd->se_tfo->get_cmd_state(se_cmd)); spin_lock_irqsave(&se_cmd->t_state_lock, flags); tas = (se_cmd->transport_state & CMD_T_TAS); spin_unlock_irqrestore(&se_cmd->t_state_lock, flags); if (!target_put_sess_cmd(se_cmd)) { if (tas) target_put_sess_cmd(se_cmd); } wait_for_completion(&se_cmd->cmd_wait_comp); pr_debug("After cmd_wait_comp: se_cmd: %p t_state: %d" " fabric state: %d\n", se_cmd, se_cmd->t_state, se_cmd->se_tfo->get_cmd_state(se_cmd)); se_cmd->se_tfo->release_cmd(se_cmd); } spin_lock_irqsave(&se_sess->sess_cmd_lock, flags); WARN_ON(!list_empty(&se_sess->sess_cmd_list)); spin_unlock_irqrestore(&se_sess->sess_cmd_lock, flags); } EXPORT_SYMBOL(target_wait_for_sess_cmds); static int transport_clear_lun_ref_thread(void *p) { struct se_lun *lun = p; percpu_ref_kill(&lun->lun_ref); wait_for_completion(&lun->lun_ref_comp); complete(&lun->lun_shutdown_comp); return 0; } int transport_clear_lun_ref(struct se_lun *lun) { struct task_struct *kt; kt = kthread_run(transport_clear_lun_ref_thread, lun, "tcm_cl_%u", lun->unpacked_lun); if (IS_ERR(kt)) { pr_err("Unable to start clear_lun thread\n"); return PTR_ERR(kt); } wait_for_completion(&lun->lun_shutdown_comp); return 0; } static bool __transport_wait_for_tasks(struct se_cmd *cmd, bool fabric_stop, bool *aborted, bool *tas, unsigned long *flags) __releases(&cmd->t_state_lock) __acquires(&cmd->t_state_lock) { assert_spin_locked(&cmd->t_state_lock); WARN_ON_ONCE(!irqs_disabled()); if (fabric_stop) cmd->transport_state |= CMD_T_FABRIC_STOP; if (cmd->transport_state & CMD_T_ABORTED) *aborted = true; if (cmd->transport_state & CMD_T_TAS) *tas = true; if (!(cmd->se_cmd_flags & SCF_SE_LUN_CMD) && !(cmd->se_cmd_flags & SCF_SCSI_TMR_CDB)) return false; if (!(cmd->se_cmd_flags & SCF_SUPPORTED_SAM_OPCODE) && !(cmd->se_cmd_flags & SCF_SCSI_TMR_CDB)) return false; if (!(cmd->transport_state & CMD_T_ACTIVE)) return false; if (fabric_stop && *aborted) return false; cmd->transport_state |= CMD_T_STOP; pr_debug("wait_for_tasks: Stopping %p ITT: 0x%08x" " i_state: %d, t_state: %d, CMD_T_STOP\n", cmd, cmd->se_tfo->get_task_tag(cmd), cmd->se_tfo->get_cmd_state(cmd), cmd->t_state); spin_unlock_irqrestore(&cmd->t_state_lock, *flags); wait_for_completion(&cmd->t_transport_stop_comp); spin_lock_irqsave(&cmd->t_state_lock, *flags); cmd->transport_state &= ~(CMD_T_ACTIVE | CMD_T_STOP); pr_debug("wait_for_tasks: Stopped wait_for_completion(" "&cmd->t_transport_stop_comp) for ITT: 0x%08x\n", cmd->se_tfo->get_task_tag(cmd)); return true; } /** * transport_wait_for_tasks - wait for completion to occur * @cmd: command to wait * * Called from frontend fabric context to wait for storage engine * to pause and/or release frontend generated struct se_cmd. */ bool transport_wait_for_tasks(struct se_cmd *cmd) { unsigned long flags; bool ret, aborted = false, tas = false; spin_lock_irqsave(&cmd->t_state_lock, flags); ret = __transport_wait_for_tasks(cmd, false, &aborted, &tas, &flags); spin_unlock_irqrestore(&cmd->t_state_lock, flags); return ret; } EXPORT_SYMBOL(transport_wait_for_tasks); static int transport_get_sense_codes( struct se_cmd *cmd, u8 *asc, u8 *ascq) { *asc = cmd->scsi_asc; *ascq = cmd->scsi_ascq; return 0; } static void transport_err_sector_info(unsigned char *buffer, sector_t bad_sector) { /* Place failed LBA in sense data information descriptor 0. */ buffer[SPC_ADD_SENSE_LEN_OFFSET] = 0xc; buffer[SPC_DESC_TYPE_OFFSET] = 0; /* Information */ buffer[SPC_ADDITIONAL_DESC_LEN_OFFSET] = 0xa; buffer[SPC_VALIDITY_OFFSET] = 0x80; /* Descriptor Information: failing sector */ put_unaligned_be64(bad_sector, &buffer[12]); } int transport_send_check_condition_and_sense(struct se_cmd *cmd, sense_reason_t reason, int from_transport) { unsigned char *buffer = cmd->sense_buffer; unsigned long flags; u8 asc = 0, ascq = 0; spin_lock_irqsave(&cmd->t_state_lock, flags); if (cmd->se_cmd_flags & SCF_SENT_CHECK_CONDITION) { spin_unlock_irqrestore(&cmd->t_state_lock, flags); return 0; } cmd->se_cmd_flags |= SCF_SENT_CHECK_CONDITION; spin_unlock_irqrestore(&cmd->t_state_lock, flags); if (!reason && from_transport) goto after_reason; if (!from_transport) cmd->se_cmd_flags |= SCF_EMULATED_TASK_SENSE; /* * Actual SENSE DATA, see SPC-3 7.23.2 SPC_SENSE_KEY_OFFSET uses * SENSE KEY values from include/scsi/scsi.h */ switch (reason) { case TCM_NO_SENSE: /* CURRENT ERROR */ buffer[0] = 0x70; buffer[SPC_ADD_SENSE_LEN_OFFSET] = 10; /* Not Ready */ buffer[SPC_SENSE_KEY_OFFSET] = NOT_READY; /* NO ADDITIONAL SENSE INFORMATION */ buffer[SPC_ASC_KEY_OFFSET] = 0; buffer[SPC_ASCQ_KEY_OFFSET] = 0; break; case TCM_NON_EXISTENT_LUN: /* CURRENT ERROR */ buffer[0] = 0x70; buffer[SPC_ADD_SENSE_LEN_OFFSET] = 10; /* ILLEGAL REQUEST */ buffer[SPC_SENSE_KEY_OFFSET] = ILLEGAL_REQUEST; /* LOGICAL UNIT NOT SUPPORTED */ buffer[SPC_ASC_KEY_OFFSET] = 0x25; break; case TCM_UNSUPPORTED_SCSI_OPCODE: case TCM_SECTOR_COUNT_TOO_MANY: /* CURRENT ERROR */ buffer[0] = 0x70; buffer[SPC_ADD_SENSE_LEN_OFFSET] = 10; /* ILLEGAL REQUEST */ buffer[SPC_SENSE_KEY_OFFSET] = ILLEGAL_REQUEST; /* INVALID COMMAND OPERATION CODE */ buffer[SPC_ASC_KEY_OFFSET] = 0x20; break; case TCM_UNKNOWN_MODE_PAGE: /* CURRENT ERROR */ buffer[0] = 0x70; buffer[SPC_ADD_SENSE_LEN_OFFSET] = 10; /* ILLEGAL REQUEST */ buffer[SPC_SENSE_KEY_OFFSET] = ILLEGAL_REQUEST; /* INVALID FIELD IN CDB */ buffer[SPC_ASC_KEY_OFFSET] = 0x24; break; case TCM_CHECK_CONDITION_ABORT_CMD: /* CURRENT ERROR */ buffer[0] = 0x70; buffer[SPC_ADD_SENSE_LEN_OFFSET] = 10; /* ABORTED COMMAND */ buffer[SPC_SENSE_KEY_OFFSET] = ABORTED_COMMAND; /* BUS DEVICE RESET FUNCTION OCCURRED */ buffer[SPC_ASC_KEY_OFFSET] = 0x29; buffer[SPC_ASCQ_KEY_OFFSET] = 0x03; break; case TCM_INCORRECT_AMOUNT_OF_DATA: /* CURRENT ERROR */ buffer[0] = 0x70; buffer[SPC_ADD_SENSE_LEN_OFFSET] = 10; /* ABORTED COMMAND */ buffer[SPC_SENSE_KEY_OFFSET] = ABORTED_COMMAND; /* WRITE ERROR */ buffer[SPC_ASC_KEY_OFFSET] = 0x0c; /* NOT ENOUGH UNSOLICITED DATA */ buffer[SPC_ASCQ_KEY_OFFSET] = 0x0d; break; case TCM_INVALID_CDB_FIELD: /* CURRENT ERROR */ buffer[0] = 0x70; buffer[SPC_ADD_SENSE_LEN_OFFSET] = 10; /* ILLEGAL REQUEST */ buffer[SPC_SENSE_KEY_OFFSET] = ILLEGAL_REQUEST; /* INVALID FIELD IN CDB */ buffer[SPC_ASC_KEY_OFFSET] = 0x24; break; case TCM_INVALID_PARAMETER_LIST: /* CURRENT ERROR */ buffer[0] = 0x70; buffer[SPC_ADD_SENSE_LEN_OFFSET] = 10; /* ILLEGAL REQUEST */ buffer[SPC_SENSE_KEY_OFFSET] = ILLEGAL_REQUEST; /* INVALID FIELD IN PARAMETER LIST */ buffer[SPC_ASC_KEY_OFFSET] = 0x26; break; case TCM_PARAMETER_LIST_LENGTH_ERROR: /* CURRENT ERROR */ buffer[0] = 0x70; buffer[SPC_ADD_SENSE_LEN_OFFSET] = 10; /* ILLEGAL REQUEST */ buffer[SPC_SENSE_KEY_OFFSET] = ILLEGAL_REQUEST; /* PARAMETER LIST LENGTH ERROR */ buffer[SPC_ASC_KEY_OFFSET] = 0x1a; break; case TCM_UNEXPECTED_UNSOLICITED_DATA: /* CURRENT ERROR */ buffer[0] = 0x70; buffer[SPC_ADD_SENSE_LEN_OFFSET] = 10; /* ABORTED COMMAND */ buffer[SPC_SENSE_KEY_OFFSET] = ABORTED_COMMAND; /* WRITE ERROR */ buffer[SPC_ASC_KEY_OFFSET] = 0x0c; /* UNEXPECTED_UNSOLICITED_DATA */ buffer[SPC_ASCQ_KEY_OFFSET] = 0x0c; break; case TCM_SERVICE_CRC_ERROR: /* CURRENT ERROR */ buffer[0] = 0x70; buffer[SPC_ADD_SENSE_LEN_OFFSET] = 10; /* ABORTED COMMAND */ buffer[SPC_SENSE_KEY_OFFSET] = ABORTED_COMMAND; /* PROTOCOL SERVICE CRC ERROR */ buffer[SPC_ASC_KEY_OFFSET] = 0x47; /* N/A */ buffer[SPC_ASCQ_KEY_OFFSET] = 0x05; break; case TCM_SNACK_REJECTED: /* CURRENT ERROR */ buffer[0] = 0x70; buffer[SPC_ADD_SENSE_LEN_OFFSET] = 10; /* ABORTED COMMAND */ buffer[SPC_SENSE_KEY_OFFSET] = ABORTED_COMMAND; /* READ ERROR */ buffer[SPC_ASC_KEY_OFFSET] = 0x11; /* FAILED RETRANSMISSION REQUEST */ buffer[SPC_ASCQ_KEY_OFFSET] = 0x13; break; case TCM_WRITE_PROTECTED: /* CURRENT ERROR */ buffer[0] = 0x70; buffer[SPC_ADD_SENSE_LEN_OFFSET] = 10; /* DATA PROTECT */ buffer[SPC_SENSE_KEY_OFFSET] = DATA_PROTECT; /* WRITE PROTECTED */ buffer[SPC_ASC_KEY_OFFSET] = 0x27; break; case TCM_ADDRESS_OUT_OF_RANGE: /* CURRENT ERROR */ buffer[0] = 0x70; buffer[SPC_ADD_SENSE_LEN_OFFSET] = 10; /* ILLEGAL REQUEST */ buffer[SPC_SENSE_KEY_OFFSET] = ILLEGAL_REQUEST; /* LOGICAL BLOCK ADDRESS OUT OF RANGE */ buffer[SPC_ASC_KEY_OFFSET] = 0x21; break; case TCM_CHECK_CONDITION_UNIT_ATTENTION: /* CURRENT ERROR */ buffer[0] = 0x70; buffer[SPC_ADD_SENSE_LEN_OFFSET] = 10; /* UNIT ATTENTION */ buffer[SPC_SENSE_KEY_OFFSET] = UNIT_ATTENTION; core_scsi3_ua_for_check_condition(cmd, &asc, &ascq); buffer[SPC_ASC_KEY_OFFSET] = asc; buffer[SPC_ASCQ_KEY_OFFSET] = ascq; break; case TCM_CHECK_CONDITION_NOT_READY: /* CURRENT ERROR */ buffer[0] = 0x70; buffer[SPC_ADD_SENSE_LEN_OFFSET] = 10; /* Not Ready */ buffer[SPC_SENSE_KEY_OFFSET] = NOT_READY; transport_get_sense_codes(cmd, &asc, &ascq); buffer[SPC_ASC_KEY_OFFSET] = asc; buffer[SPC_ASCQ_KEY_OFFSET] = ascq; break; case TCM_MISCOMPARE_VERIFY: /* CURRENT ERROR */ buffer[0] = 0x70; buffer[SPC_ADD_SENSE_LEN_OFFSET] = 10; buffer[SPC_SENSE_KEY_OFFSET] = MISCOMPARE; /* MISCOMPARE DURING VERIFY OPERATION */ buffer[SPC_ASC_KEY_OFFSET] = 0x1d; buffer[SPC_ASCQ_KEY_OFFSET] = 0x00; break; case TCM_LOGICAL_BLOCK_GUARD_CHECK_FAILED: /* CURRENT ERROR */ buffer[0] = 0x70; buffer[SPC_ADD_SENSE_LEN_OFFSET] = 10; /* ILLEGAL REQUEST */ buffer[SPC_SENSE_KEY_OFFSET] = ILLEGAL_REQUEST; /* LOGICAL BLOCK GUARD CHECK FAILED */ buffer[SPC_ASC_KEY_OFFSET] = 0x10; buffer[SPC_ASCQ_KEY_OFFSET] = 0x01; transport_err_sector_info(buffer, cmd->bad_sector); break; case TCM_LOGICAL_BLOCK_APP_TAG_CHECK_FAILED: /* CURRENT ERROR */ buffer[0] = 0x70; buffer[SPC_ADD_SENSE_LEN_OFFSET] = 10; /* ILLEGAL REQUEST */ buffer[SPC_SENSE_KEY_OFFSET] = ILLEGAL_REQUEST; /* LOGICAL BLOCK APPLICATION TAG CHECK FAILED */ buffer[SPC_ASC_KEY_OFFSET] = 0x10; buffer[SPC_ASCQ_KEY_OFFSET] = 0x02; transport_err_sector_info(buffer, cmd->bad_sector); break; case TCM_LOGICAL_BLOCK_REF_TAG_CHECK_FAILED: /* CURRENT ERROR */ buffer[0] = 0x70; buffer[SPC_ADD_SENSE_LEN_OFFSET] = 10; /* ILLEGAL REQUEST */ buffer[SPC_SENSE_KEY_OFFSET] = ILLEGAL_REQUEST; /* LOGICAL BLOCK REFERENCE TAG CHECK FAILED */ buffer[SPC_ASC_KEY_OFFSET] = 0x10; buffer[SPC_ASCQ_KEY_OFFSET] = 0x03; transport_err_sector_info(buffer, cmd->bad_sector); break; case TCM_LOGICAL_UNIT_COMMUNICATION_FAILURE: default: /* CURRENT ERROR */ buffer[0] = 0x70; buffer[SPC_ADD_SENSE_LEN_OFFSET] = 10; /* * Returning ILLEGAL REQUEST would cause immediate IO errors on * Solaris initiators. Returning NOT READY instead means the * operations will be retried a finite number of times and we * can survive intermittent errors. */ buffer[SPC_SENSE_KEY_OFFSET] = NOT_READY; /* LOGICAL UNIT COMMUNICATION FAILURE */ buffer[SPC_ASC_KEY_OFFSET] = 0x08; break; } /* * This code uses linux/include/scsi/scsi.h SAM status codes! */ cmd->scsi_status = SAM_STAT_CHECK_CONDITION; /* * Automatically padded, this value is encoded in the fabric's * data_length response PDU containing the SCSI defined sense data. */ cmd->scsi_sense_length = TRANSPORT_SENSE_BUFFER; after_reason: trace_target_cmd_complete(cmd); return cmd->se_tfo->queue_status(cmd); } EXPORT_SYMBOL(transport_send_check_condition_and_sense); static int __transport_check_aborted_status(struct se_cmd *cmd, int send_status) __releases(&cmd->t_state_lock) __acquires(&cmd->t_state_lock) { assert_spin_locked(&cmd->t_state_lock); WARN_ON_ONCE(!irqs_disabled()); if (!(cmd->transport_state & CMD_T_ABORTED)) return 0; /* * If cmd has been aborted but either no status is to be sent or it has * already been sent, just return */ if (!send_status || !(cmd->se_cmd_flags & SCF_SEND_DELAYED_TAS)) { if (send_status) cmd->se_cmd_flags |= SCF_SEND_DELAYED_TAS; return 1; } pr_debug("Sending delayed SAM_STAT_TASK_ABORTED status for CDB:" " 0x%02x ITT: 0x%08x\n", cmd->t_task_cdb[0], cmd->se_tfo->get_task_tag(cmd)); cmd->se_cmd_flags &= ~SCF_SEND_DELAYED_TAS; cmd->scsi_status = SAM_STAT_TASK_ABORTED; trace_target_cmd_complete(cmd); spin_unlock_irq(&cmd->t_state_lock); cmd->se_tfo->queue_status(cmd); spin_lock_irq(&cmd->t_state_lock); return 1; } int transport_check_aborted_status(struct se_cmd *cmd, int send_status) { int ret; spin_lock_irq(&cmd->t_state_lock); ret = __transport_check_aborted_status(cmd, send_status); spin_unlock_irq(&cmd->t_state_lock); return ret; } EXPORT_SYMBOL(transport_check_aborted_status); void transport_send_task_abort(struct se_cmd *cmd) { unsigned long flags; spin_lock_irqsave(&cmd->t_state_lock, flags); if (cmd->se_cmd_flags & (SCF_SENT_CHECK_CONDITION)) { spin_unlock_irqrestore(&cmd->t_state_lock, flags); return; } spin_unlock_irqrestore(&cmd->t_state_lock, flags); /* * If there are still expected incoming fabric WRITEs, we wait * until until they have completed before sending a TASK_ABORTED * response. This response with TASK_ABORTED status will be * queued back to fabric module by transport_check_aborted_status(). */ if (cmd->data_direction == DMA_TO_DEVICE) { if (cmd->se_tfo->write_pending_status(cmd) != 0) { spin_lock_irqsave(&cmd->t_state_lock, flags); if (cmd->se_cmd_flags & SCF_SEND_DELAYED_TAS) { spin_unlock_irqrestore(&cmd->t_state_lock, flags); goto send_abort; } cmd->se_cmd_flags |= SCF_SEND_DELAYED_TAS; spin_unlock_irqrestore(&cmd->t_state_lock, flags); return; } } send_abort: cmd->scsi_status = SAM_STAT_TASK_ABORTED; transport_lun_remove_cmd(cmd); pr_debug("Setting SAM_STAT_TASK_ABORTED status for CDB: 0x%02x," " ITT: 0x%08x\n", cmd->t_task_cdb[0], cmd->se_tfo->get_task_tag(cmd)); trace_target_cmd_complete(cmd); cmd->se_tfo->queue_status(cmd); } static void target_tmr_work(struct work_struct *work) { struct se_cmd *cmd = container_of(work, struct se_cmd, work); struct se_device *dev = cmd->se_dev; struct se_tmr_req *tmr = cmd->se_tmr_req; unsigned long flags; int ret; spin_lock_irqsave(&cmd->t_state_lock, flags); if (cmd->transport_state & CMD_T_ABORTED) { tmr->response = TMR_FUNCTION_REJECTED; spin_unlock_irqrestore(&cmd->t_state_lock, flags); goto check_stop; } spin_unlock_irqrestore(&cmd->t_state_lock, flags); switch (tmr->function) { case TMR_ABORT_TASK: core_tmr_abort_task(dev, tmr, cmd->se_sess); break; case TMR_ABORT_TASK_SET: case TMR_CLEAR_ACA: case TMR_CLEAR_TASK_SET: tmr->response = TMR_TASK_MGMT_FUNCTION_NOT_SUPPORTED; break; case TMR_LUN_RESET: ret = core_tmr_lun_reset(dev, tmr, NULL, NULL); tmr->response = (!ret) ? TMR_FUNCTION_COMPLETE : TMR_FUNCTION_REJECTED; break; case TMR_TARGET_WARM_RESET: tmr->response = TMR_FUNCTION_REJECTED; break; case TMR_TARGET_COLD_RESET: tmr->response = TMR_FUNCTION_REJECTED; break; default: pr_err("Uknown TMR function: 0x%02x.\n", tmr->function); tmr->response = TMR_FUNCTION_REJECTED; break; } spin_lock_irqsave(&cmd->t_state_lock, flags); if (cmd->transport_state & CMD_T_ABORTED) { spin_unlock_irqrestore(&cmd->t_state_lock, flags); goto check_stop; } cmd->t_state = TRANSPORT_ISTATE_PROCESSING; spin_unlock_irqrestore(&cmd->t_state_lock, flags); cmd->se_tfo->queue_tm_rsp(cmd); check_stop: transport_cmd_check_stop_to_fabric(cmd); } int transport_generic_handle_tmr( struct se_cmd *cmd) { unsigned long flags; spin_lock_irqsave(&cmd->t_state_lock, flags); cmd->transport_state |= CMD_T_ACTIVE; spin_unlock_irqrestore(&cmd->t_state_lock, flags); INIT_WORK(&cmd->work, target_tmr_work); queue_work(cmd->se_dev->tmr_wq, &cmd->work); return 0; } EXPORT_SYMBOL(transport_generic_handle_tmr);
WaRP7/linux-fslc
drivers/target/target_core_transport.c
C
gpl-2.0
87,539
if(typeof(simileTimeplot)=="undefined") { window.simileTimeplot = { records : [], js : {} }; // jQuery("head").append('<script src="http://api.simile-widgets.org/timeplot/1.1/timeplot-api.js"></script>'); } (function($) { var red = new Timeplot.Color('#B9121B'); var lightRed = new Timeplot.Color('#cc8080'); var blue = new Timeplot.Color('#193441'); var green = new Timeplot.Color('#468966'); var lightGreen = new Timeplot.Color('#5C832F'); var gridColor = new Timeplot.Color('#000000'); var timeGeometry = new Timeplot.DefaultTimeGeometry({ gridColor: gridColor, axisLabelsPlacement: "bottom" }); var valueGeometry = new Timeplot.DefaultValueGeometry({ gridColor: gridColor, axisLabelsPlacement: "left" }); var simileTimeplotResizeTimerID = null; var simileTimeplots = []; $(window).resize(function() { if (simileTimeplotResizeTimerID == null) { simileTimeplotResizeTimerID = window.setTimeout(function() { simileTimeplotResizeTimerID = null; for(var i=0;i<simileTimeplots.length;++i) { simileTimeplots[i].repaint(); } }, 300); } }); simileTimeplot.js = { SMWSimile_FillData : function(data, eventSource) { var evt = null, evts = new Array(); for(var i=0;i<data.length;++i) { evt = new Timeplot.DefaultEventSource.NumericEvent( SimileAjax.DateTime.parseIso8601DateTime(data[i].start),data[i].values); evts[i] = evt; } eventSource.addMany(evts); }, SMWSimile_FillEvent : function(data, eventSource) { var evt = null, evts = new Array(); for(var i=0;i<data.length;++i) { evt = new Timeline.DefaultEventSource.Event({ id: undefined, start: SimileAjax.DateTime.parseIso8601DateTime(data[i].start), end: data[i].end ? SimileAjax.DateTime.parseIso8601DateTime(data[i].end): null, text: data[i].title, link: data[i].link, description: data[i].description }); evt._obj = data[i]; evt.getProperty = function(name) { return this._obj[name]; }; evts[i] = evt; } eventSource.addMany(evts); }, renderTimeplot : function() { var plotInfo = []; var eventSource = null; var eventSourceEvt = null; for(var i=0;i<simileTimeplot.records.length;++i) { eventSource = new Timeplot.DefaultEventSource(); eventSourceEvt = new Timeplot.DefaultEventSource(); plotInfo.push( Timeplot.createPlotInfo({ id: "plotEvents" + i, eventSource: eventSourceEvt, timeGeometry: timeGeometry, lineColor: red }) ); for(var j=0;j<simileTimeplot.records[i].count;++j) { plotInfo.push( Timeplot.createPlotInfo({ id: "plot" + i + j, dataSource: new Timeplot.ColumnSource(eventSource, j + 1), valueGeometry: valueGeometry, lineColor: green, dotColor: lightGreen, timeGeometry: timeGeometry, showValues: true }) ); } simileTimeplots.push( Timeplot.create(document.getElementById(simileTimeplot.records[i].div), plotInfo) ); simileTimeplot.js.SMWSimile_FillData(simileTimeplot.records[i].data, eventSource); simileTimeplot.js.SMWSimile_FillEvent(simileTimeplot.records[i].data, eventSourceEvt); } } }; $(document).ready(function(){ simileTimeplot.js.renderTimeplot(); }); })(jQuery);
ontoprise/HaloSMWExtension
extensions/SRFPlus/Simile/scripts/Simile_TimeplotWiki.js
JavaScript
gpl-2.0
3,263
<?php /* core/themes/stable/templates/block/block--system-messages-block.html.twig */ class __TwigTemplate_886740968f827ac8f8ad8553cb8fe62217c4c4c2ec3a7a043b3d35b9acb03e84 extends Twig_Template { public function __construct(Twig_Environment $env) { parent::__construct($env); $this->parent = false; $this->blocks = array( ); } protected function doDisplay(array $context, array $blocks = array()) { $tags = array(); $filters = array(); $functions = array(); try { $this->env->getExtension('sandbox')->checkSecurity( array(), array(), array() ); } catch (Twig_Sandbox_SecurityError $e) { $e->setTemplateFile($this->getTemplateName()); if ($e instanceof Twig_Sandbox_SecurityNotAllowedTagError && isset($tags[$e->getTagName()])) { $e->setTemplateLine($tags[$e->getTagName()]); } elseif ($e instanceof Twig_Sandbox_SecurityNotAllowedFilterError && isset($filters[$e->getFilterName()])) { $e->setTemplateLine($filters[$e->getFilterName()]); } elseif ($e instanceof Twig_Sandbox_SecurityNotAllowedFunctionError && isset($functions[$e->getFunctionName()])) { $e->setTemplateLine($functions[$e->getFunctionName()]); } throw $e; } // line 13 echo $this->env->getExtension('sandbox')->ensureToStringAllowed($this->env->getExtension('drupal_core')->escapeFilter($this->env, (isset($context["content"]) ? $context["content"] : null), "html", null, true)); echo " "; } public function getTemplateName() { return "core/themes/stable/templates/block/block--system-messages-block.html.twig"; } public function isTraitable() { return false; } public function getDebugInfo() { return array ( 43 => 13,); } } /* {#*/ /* /***/ /* * @file*/ /* * Theme override for the messages block.*/ /* **/ /* * Removes wrapper elements from block so that empty block does not appear when*/ /* * there are no messages.*/ /* **/ /* * Available variables:*/ /* * - content: The content of this block.*/ /* *//* */ /* #}*/ /* {{ content }}*/ /* */
nhinq/drupal8
sites/default/files/php/twig/f4bf8926_block--system-messages-block.html.twig_7a0dc1dc8ea56b701f7e4dd579608cdd9d8ad000d4a12d7ea6ca73e50dbb13dd/82014522767b3de45407812e92ff9e01963812469ce6e716fdb44803f716dc8f.php
PHP
gpl-2.0
2,313
/* * This file is part of the coreboot project. * * Copyright 2017 Intel Corp. * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; version 2 of the License. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.See the * GNU General Public License for more details. */ #include <baseboard/gpio.h> #include <baseboard/variants.h> #include <commonlib/helpers.h> /* * Pad configuration in ramstage. The order largely follows the 'GPIO Muxing' * table found in EDS vol 1, but some pins aren't grouped functionally in * the table so those were moved for more logical grouping. */ static const struct pad_config gpio_table[] = { /* NORTHWEST COMMUNITY GPIOS */ PAD_CFG_NF_IOSSTATE_IOSTERM(GPIO_0, DN_20K, DEEP, NF1, IGNORE, ENPD), /* TCK */ PAD_CFG_NF_IOSSTATE_IOSTERM(GPIO_1, DN_20K, DEEP, NF1, IGNORE, ENPD), /* TRST_B */ PAD_CFG_NF_IOSSTATE_IOSTERM(GPIO_2, UP_20K, DEEP, NF1, IGNORE, ENPU), /* TMS */ PAD_CFG_NF_IOSSTATE_IOSTERM(GPIO_3, UP_20K, DEEP, NF1, IGNORE, ENPU), /* TDI */ PAD_CFG_NF_IOSSTATE_IOSTERM(GPIO_4, UP_20K, DEEP, NF1, IGNORE, ENPU), /* TDO */ PAD_CFG_NF_IOSSTATE_IOSTERM(GPIO_5, UP_20K, DEEP, NF1, IGNORE, ENPU), /* JTAGX */ PAD_CFG_NF_IOSSTATE_IOSTERM(GPIO_6, UP_20K, DEEP, NF1, IGNORE, ENPU), /* CX_PREQ_B */ PAD_CFG_NF_IOSSTATE_IOSTERM(GPIO_7, UP_20K, DEEP, NF1, IGNORE, ENPU), /* CX_PRDY_B */ PAD_CFG_NF_IOSSTATE_IOSTERM(GPIO_8, DN_20K, DEEP, NF5, HIZCRx0, DISPUPD), /* TRACE_0_CLK_VNN */ PAD_CFG_NF_IOSSTATE_IOSTERM(GPIO_9, DN_20K, DEEP, NF5, HIZCRx0, DISPUPD), /* TRACE_0_DATA0_VNN */ PAD_CFG_NF_IOSSTATE_IOSTERM(GPIO_10, DN_20K, DEEP, NF5, HIZCRx0, DISPUPD), /* TRACE_0_DATA1_VNN */ PAD_CFG_NF_IOSSTATE_IOSTERM(GPIO_11, DN_20K, DEEP, NF5, HIZCRx0, DISPUPD), /* TRACE_0_DATA2_VNN */ PAD_CFG_NF_IOSSTATE_IOSTERM(GPIO_12, DN_20K, DEEP, NF5, HIZCRx0, DISPUPD), /* TRACE_0_DATA3_VNN */ PAD_CFG_NF_IOSSTATE_IOSTERM(GPIO_13, DN_20K, DEEP, NF5, HIZCRx0, DISPUPD), /* TRACE_0_DATA4_VNN */ PAD_CFG_NF_IOSSTATE_IOSTERM(GPIO_14, DN_20K, DEEP, NF5, HIZCRx0, DISPUPD), /* TRACE_0_DATA5_VNN */ PAD_CFG_NF_IOSSTATE_IOSTERM(GPIO_15, DN_20K, DEEP, NF5, HIZCRx0, DISPUPD), /* TRACE_0_DATA6_VNN */ PAD_CFG_NF_IOSSTATE_IOSTERM(GPIO_16, DN_20K, DEEP, NF5, HIZCRx0, DISPUPD), /* TRACE_0_DATA7_VNN */ PAD_CFG_GPO_IOSSTATE_IOSTERM(GPIO_17, 1, DEEP, UP_20K, TxDRxE, SAME),/*Ec-to-SOC CS Wake */ PAD_CFG_GPI_APIC_IOS(GPIO_18, UP_20K, DEEP, LEVEL, NONE, IGNORE, SAME),/* Touch Pad Interrupt */ PAD_CFG_GPI_APIC_IOS(GPIO_19, UP_20K, DEEP, EDGE_SINGLE, NONE, TxDRxE, SAME),/*PMIC Interrupt*/ PAD_CFG_GPI_APIC_IOS(GPIO_20, UP_20K, DEEP, LEVEL, INVERT, IGNORE, SAME),/* Audio Codec Interrupt*/ PAD_CFG_NF(GPIO_21, UP_20K, DEEP, NF2), /* CNV_MFUART2_RXD */ PAD_CFG_NF_IOSSTATE(GPIO_22, UP_20K, DEEP, NF2, TxDRxE), /* CNV_MFUART2_TXD */ PAD_CFG_NF(GPIO_23, UP_20K, DEEP, NF2), /* CNV_GNSS_PABLANKIt */ PAD_CFG_GPO_GPIO_DRIVER(GPIO_24, 1, DEEP, DN_20K), PAD_CFG_GPO_IOSSTATE_IOSTERM(GPIO_25, 1, DEEP, UP_20K, TxLASTRxE, SAME),/*WWAN /RF_KILL_GPS*/ PAD_CFG_NF_IOSSTATE_IOSTERM(GPIO_26, UP_20K, DEEP, NF2, HIZCRx1, DISPUPD),/* NFC Interrupt */ PAD_CFG_GPO_IOSSTATE_IOSTERM(GPIO_27, 1, DEEP, NONE, IGNORE, DISPUPD),/* RF_KILL_WiFi/WiFi_Disable */ PAD_CFG_GPO_IOSSTATE_IOSTERM(GPIO_28, 1, DEEP, UP_20K, TxLASTRxE, DISPUPD),/* RF_KILL_BT/BT_Disable */ PAD_CFG_GPO_IOSSTATE_IOSTERM(GPIO_29, 1, DEEP, UP_20K, HIZCRx0, DISPUPD),/* Codec Power Down: Output/ISH_GPIO_3*/ PAD_CFG_NF_IOSTANDBY_IGNORE(GPIO_30, DN_20K, DEEP, NF1), /* ISH_GPIO_4 */ PAD_CFG_NF_IOSTANDBY_IGNORE(GPIO_31, DN_20K, DEEP, NF1), /* ISH_GPIO_5 */ PAD_CFG_NF_IOSTANDBY_IGNORE(GPIO_32, DN_20K, DEEP, NF1), /* ISH_GPIO_6 */ PAD_CFG_NF_IOSTANDBY_IGNORE(GPIO_33, DN_20K, DEEP, NF1), /* ISH_GPIO_7 */ PAD_CFG_NF_IOSTANDBY_IGNORE(GPIO_34, DN_20K, DEEP, NF1), /* ISH_GPIO_8/SUSCLK2 (1.8V) */ PAD_CFG_NF_IOSTANDBY_IGNORE(GPIO_35, UP_20K, DEEP, NF6), /* BSSB_CLK */ PAD_CFG_NF_IOSTANDBY_IGNORE(GPIO_36, UP_20K, DEEP, NF6), /* BSSB_DI */ PAD_CFG_GPI_SCI_IOS(GPIO_37, UP_20K, DEEP, EDGE_SINGLE, INVERT, IGNORE, SAME),/*Runtime SCI */ PAD_CFG_GPI_SCI_IOS(GPIO_38, UP_20K, DEEP, EDGE_SINGLE, INVERT, IGNORE, SAME),/*Wake SCI */ PAD_CFG_GPI_APIC_IOS(GPIO_39, DN_20K, DEEP, LEVEL, NONE, IGNORE, SAME),/* Finger Print Sensor Interrupt (DRDY) */ PAD_CFG_NF_IOSTANDBY_IGNORE(GPIO_40, UP_20K, DEEP, NF6),/*IERR (USB Camera Power Enable)*/ PAD_CFG_GPI_SMI_IOS(GPIO_41, UP_20K, DEEP, EDGE_SINGLE, NONE, IGNORE, SAME),/*SOC_EXTSMI_N */ PAD_CFG_NF(GPIO_42, DN_20K, DEEP, NF1), /* GP_INTD_DSI_TE1 */ PAD_CFG_NF(GPIO_43, DN_20K, DEEP, NF1), /* GP_INTD_DSI_TE2 */ PAD_CFG_NF(GPIO_44, UP_20K, DEEP, NF1), /* USB_OC0_B */ PAD_CFG_NF(GPIO_45, UP_20K, DEEP, NF1), /* USB_OC1_B */ PAD_CFG_NF_IOSSTATE_IOSTERM(GPIO_46, DN_20K, DEEP, NF1, HIZCRx1, ENPU), /* DSI_I2C_SDA */ PAD_CFG_NF_IOSSTATE_IOSTERM(GPIO_47, UP_20K, DEEP, NF1, HIZCRx1, ENPU), /* DSI_I2C_SCL */ PAD_CFG_NF_IOSTANDBY_IGNORE(GPIO_48, UP_1K, DEEP, NF1), /* PMC_I2C_SDA */ PAD_CFG_NF_IOSTANDBY_IGNORE(GPIO_49, UP_1K, DEEP, NF1), /* PMC_I2C_SCL */ PAD_CFG_NF_IOSSTATE_IOSTERM(GPIO_50, UP_2K, DEEP, NF1, HIZCRx1, ENPU), /* LPSS_I2C0_SDA - Audio Codec*/ PAD_CFG_NF_IOSSTATE_IOSTERM(GPIO_51, UP_2K, DEEP, NF1, HIZCRx1, ENPU), /* LPSS_I2C0_SCL - Audio Codec */ PAD_CFG_NF_IOSSTATE_IOSTERM(GPIO_52, UP_20K, DEEP, NF1, HIZCRx1, ENPU), /* LPSS_I2C1_SDA - NFC */ PAD_CFG_NF_IOSSTATE_IOSTERM(GPIO_53, UP_20K, DEEP, NF1, HIZCRx1, ENPU), /* LPSS_I2C1_SCL - NFC */ PAD_CFG_GPIO_DRIVER_HI_Z(GPIO_54, UP_20K, DEEP, HIZCRx1, ENPU),/*LPSS_I2C2_SDA*/ PAD_CFG_GPIO_DRIVER_HI_Z(GPIO_55, UP_20K, DEEP, HIZCRx1, ENPU),/*LPSS_I2C2_SCL*/ PAD_CFG_NF_IOSSTATE_IOSTERM(GPIO_56, UP_20K, DEEP, NF1, HIZCRx1, ENPU),/* I2C3-SDA - DBG (PSS, SINAI2, MIPI) */ PAD_CFG_NF_IOSSTATE_IOSTERM(GPIO_57, UP_20K, DEEP, NF1, HIZCRx1, ENPU),/*I2C3-SCL - DBG (PSS, SINAI2, MIPI) */ PAD_CFG_NF_IOSSTATE_IOSTERM(GPIO_58, UP_20K, DEEP, NF1, HIZCRx1, ENPU),/*I2C4-SDA - Touch Pad*/ PAD_CFG_NF_IOSSTATE_IOSTERM(GPIO_59, UP_20K, DEEP, NF1, HIZCRx1, ENPU),/*I2C4-SCL - Touch Pad*/ PAD_CFG_NF_IOSSTATE_IOSTERM(GPIO_60, UP_20K, DEEP, NF1, HIZCRx1, DISPUPD),/* UART0-RXD - M.2dGNSS */ PAD_CFG_NF_IOSSTATE_IOSTERM(GPIO_61, UP_20K, DEEP, NF1, HIZCRx1, DISPUPD),/* UART0-TXD - M.2dGNSS */ PAD_CFG_NF_IOSSTATE_IOSTERM(GPIO_62, UP_20K, DEEP, NF1, HIZCRx1, DISPUPD),/* UART0-RTS_B - M.2 dGNSS */ PAD_CFG_NF_IOSSTATE_IOSTERM(GPIO_63, UP_20K, DEEP, NF1, HIZCRx1, DISPUPD),/* UART0-CTS_B - M.2 dGNSS */ PAD_CFG_NF_IOSSTATE_IOSTERM(GPIO_64, UP_20K, DEEP, NF1, HIZCRx1, DISPUPD),/*LPSS_UART2_RXD*/ PAD_CFG_NF_IOSSTATE_IOSTERM(GPIO_65, UP_20K, DEEP, NF1, TxLASTRxE, DISPUPD),/*LPSS_UART2_TXD*/ PAD_CFG_GPO_IOSSTATE_IOSTERM(GPIO_66, 1, DEEP, UP_20K, TxDRxE, DISPUPD),/*RF_KILL_WWAN */ #if IS_ENABLED(CONFIG_TPM_ON_FAST_SPI) PAD_CFG_GPI_INT(GPIO_67, UP_20K, DEEP, LEVEL),/*SPI TPM Interrupt */ #endif PAD_CFG_NF(GPIO_68, UP_20K, DEEP, NF1),/*PMC_SPI_FS0*/ PAD_CFG_GPI_APIC(GPIO_69, DN_20K, DEEP, EDGE_SINGLE, NONE),/*SIM Detect*/ PAD_CFG_NF(GPIO_70, DN_20K, DEEP, NF1),/*PMC_SPI_FS2*/ PAD_CFG_NF(GPIO_71, DN_20K, DEEP, NF1),/*PMC_SPI_RXD*/ PAD_CFG_NF(GPIO_72, DN_20K, DEEP, NF1),/*PMC_SPI_TXD*/ PAD_CFG_NF(GPIO_73, DN_20K, DEEP, NF1),/*PMC_SPI_CLK*/ PAD_CFG_NF(GPIO_74, DN_20K, DEEP, NF1),/*THERMTRIP_B*/ PAD_CFG_NF_IOSSTATE(GPIO_75, UP_20K, DEEP, NF1, HIZCRx1),/*PROCHOT_B*/ PAD_CFG_NF_IOSSTATE(GPIO_211, UP_20K, DEEP, NF1, HIZCRx1),/*EMMC_RST_B*/ PAD_CFG_GPI_GPIO_DRIVER(GPIO_212, UP_20K, DEEP),/*Touch Panel Int*/ PAD_CFG_GPO_IOSSTATE_IOSTERM(GPIO_213, 1, DEEP, NONE, HIZCRx0, SAME),/*DNX LED - CSE owned*/ PAD_CFG_GPO_IOSSTATE_IOSTERM(GPIO_214, 1, DEEP, NONE, HIZCRx0, SAME),/*LAN Isolate*/ /* NORTH COMMUNITY GPIOS */ PAD_CFG_NF_IOSTANDBY_IGNORE(GPIO_76, UP_20K, DEEP, NF1),/*SVID Alert*/ PAD_CFG_NF_IOSTANDBY_IGNORE(GPIO_77, UP_20K, DEEP, NF1),/* SVID Data */ PAD_CFG_NF_IOSTANDBY_IGNORE(GPIO_78, UP_20K, DEEP, NF1),/* SVID Clk */ PAD_CFG_NF_IOSTANDBY_IGNORE(GPIO_79, NATIVE, DEEP, NF1),/* Finger Print Sensor */ PAD_CFG_NF_IOSTANDBY_IGNORE(GPIO_80, NATIVE, DEEP, NF1),/* Finger Print Sensor CS */ PAD_CFG_NF_IOSTANDBY_IGNORE(GPIO_81, NONE, DEEP, NF3),/* FST_SPI_CS2_B - TPM */ PAD_CFG_NF_IOSTANDBY_IGNORE(GPIO_82, NATIVE, DEEP, NF1),/* Finger Print Sensor */ PAD_CFG_NF_IOSTANDBY_IGNORE(GPIO_83, NATIVE, DEEP, NF1),/* Finger Print Sensor */ PAD_CFG_NF_IOSSTATE(GPIO_84, NONE, DEEP, NF3, HIZCRx1),/* SPI iTouch*/ PAD_CFG_NF_IOSSTATE(GPIO_85, DN_20K, DEEP, NF3, HIZCRx1),/*Function 3: SPI iTouch CS*/ PAD_CFG_NF_IOSSTATE(GPIO_86, DN_20K, DEEP, NF3, HIZCRx1),/*Function 3: SPI iTouch*/ PAD_CFG_NF_IOSSTATE(GPIO_87, DN_20K, DEEP, NF3, HIZCRx1),/*Function 3: SPI iTouch*/ PAD_CFG_NF_IOSSTATE(GPIO_88, DN_20K, DEEP, NF3, HIZCRx1),/*Function 3: SPI iTouch*/ PAD_CFG_NF_IOSSTATE(GPIO_89, DN_20K, DEEP, NF3, HIZCRx1),/*Function 3: SPI iTouch*/ PAD_CFG_NF_IOSTANDBY_IGNORE(GPIO_90, NATIVE, DEEP, NF1),/*Function 1: FST SPI Boot Flash CS*/ PAD_CFG_GPIO_HI_Z(GPIO_91, NATIVE, DEEP, IGNORE, SAME),/*FST_SPI_CS1_B*/ PAD_CFG_NF_IOSTANDBY_IGNORE(GPIO_92, DN_20K, DEEP, NF1),/*FST_SPI_MOSI_IO0*/ PAD_CFG_NF_IOSTANDBY_IGNORE(GPIO_93, NATIVE, DEEP, NF1),/*FST_SPI_MISO_IO1*/ PAD_CFG_NF_IOSTANDBY_IGNORE(GPIO_94, NATIVE, DEEP, NF1),/*FST_SPI_IO2*/ PAD_CFG_NF_IOSTANDBY_IGNORE(GPIO_95, NATIVE, DEEP, NF1),/*FST_SPI_IO3*/ PAD_CFG_NF_IOSTANDBY_IGNORE(GPIO_96, NATIVE, DEEP, NF1),/*FST_SPI_CLK*/ PAD_CFG_NF(GPIO_97, NATIVE, DEEP, NF1),/*FST_SPI_CLK_FB*/ PAD_CFG_NF_IOSTANDBY_IGNORE(GPIO_98, NONE, DEEP, NF1),/*PMU_PLTRST_B*/ PAD_CFG_NF_IOSTANDBY_IGNORE(GPIO_99, UP_20K, DEEP, NF1),/*PMU_PWRBTN_B*/ PAD_CFG_NF_IOSTANDBY_IGNORE(GPIO_100, NONE, DEEP, NF1),/*PMU_SLP_S0_B*/ PAD_CFG_NF_IOSTANDBY_IGNORE(GPIO_101, NONE, DEEP, NF1),/*PMU_SLP_S3_B*/ PAD_CFG_NF_IOSTANDBY_IGNORE(GPIO_102, NONE, DEEP, NF1),/*PMU_SLP_S4_B*/ PAD_CFG_NF_IOSTANDBY_IGNORE(GPIO_103, NONE, DEEP, NF1),/*SUSPWRDNACK*/ PAD_CFG_NF_IOSTANDBY_IGNORE(GPIO_104, UP_20K, DEEP, NF1),/*EMMC_DNX_PWR_EN_B*/ PAD_CFG_GPO_IOSSTATE_IOSTERM(GPIO_105, 0, DEEP, DN_20K, IGNORE, SAME),/*x4 Slot-2 Reset*/ PAD_CFG_NF_IOSTANDBY_IGNORE(GPIO_106, UP_20K, DEEP, NF1),/*PMU_BATLOW_B*/ PAD_CFG_NF_IOSTANDBY_IGNORE(GPIO_107, UP_20K, DEEP, NF1),/*PMU_RESETBUTTON_B*/ PAD_CFG_NF_IOSTANDBY_IGNORE(GPIO_108, NONE, DEEP, NF1),/*PMU_SUSCLK*/ PAD_CFG_NF_IOSTANDBY_IGNORE(GPIO_109, NONE, DEEP, NF1),/*SUS_STAT_B*/ PAD_CFG_NF_IOSSTATE_IOSTERM(GPIO_110, UP_20K, DEEP, NF2, HIZCRx1, ENPU),/*LPSS_I2C5_SDA*/ PAD_CFG_NF_IOSSTATE_IOSTERM(GPIO_111, UP_20K, DEEP, NF2, HIZCRx1, ENPU),/*LPSS_I2C5_SCL*/ PAD_CFG_NF_IOSSTATE_IOSTERM(GPIO_112, UP_20K, DEEP, NF2, HIZCRx1, ENPU),/*LPSS_I2C6_SDA*/ PAD_CFG_NF_IOSSTATE_IOSTERM(GPIO_113, UP_20K, DEEP, NF2, HIZCRx1, ENPU),/*LPSS_I2C6_SCL*/ PAD_CFG_NF_IOSSTATE_IOSTERM(GPIO_114, UP_20K, DEEP, NF1, HIZCRx1, ENPU),/*LPSS_I2C7_SDA*/ PAD_CFG_NF_IOSSTATE_IOSTERM(GPIO_115, UP_20K, DEEP, NF1, HIZCRx1, ENPU),/*LPSS_I2C7_SCL*/ PAD_CFG_NF_IOSTANDBY_IGNORE(GPIO_116, UP_20K, DEEP, NF1),/*PCIE_WAKE0_B*/ PAD_CFG_NF_IOSTANDBY_IGNORE(GPIO_117, UP_20K, DEEP, NF1),/*PCIE_WAKE1_B*/ PAD_CFG_NF_IOSTANDBY_IGNORE(GPIO_118, UP_20K, DEEP, NF1),/*PCIE_WAKE2_B*/ PAD_CFG_NF_IOSTANDBY_IGNORE(GPIO_119, UP_20K, DEEP, NF1),/*PCIE_WAKE3_B*/ PAD_CFG_GPI(GPIO_120, UP_20K, DEEP), /* unused */ PAD_CFG_GPI(GPIO_121, UP_20K, DEEP), /* unused */ PAD_CFG_GPI(GPIO_122, UP_20K, DEEP), /* unused */ PAD_CFG_NF_IOSSTATE(GPIO_123, UP_20K, DEEP, NF1, HIZCRx1),/*PCIE_CLKREQ3_B*/ PAD_CFG_NF_IOSSTATE(GPIO_124, UP_20K, DEEP, NF1, HIZCRx0),/*HV_DDI0_DDC_SDA*/ PAD_CFG_NF_IOSSTATE(GPIO_125, UP_20K, DEEP, NF1, HIZCRx0),/*HV_DDI0_DDC_SCL*/ PAD_CFG_NF_IOSSTATE(GPIO_126, UP_20K, DEEP, NF1, HIZCRx0),/*HV_DDI1_DDC_SDA*/ PAD_CFG_NF_IOSSTATE(GPIO_127, UP_20K, DEEP, NF1, HIZCRx0),/*HV_DDI1_DDC_SCL*/ PAD_CFG_NF_IOSSTATE(GPIO_128, DN_20K, DEEP, NF1, Tx0RxDCRx0),/*PANEL0_VDDEN*/ PAD_CFG_NF_IOSSTATE(GPIO_129, DN_20K, DEEP, NF1, Tx0RxDCRx0),/*PANEL0_BKLTEN*/ PAD_CFG_NF_IOSSTATE(GPIO_130, DN_20K, DEEP, NF1, Tx0RxDCRx0),/*PANEL0_BKLTCTL*/ PAD_CFG_NF_IOSSTATE(GPIO_131, UP_20K, DEEP, NF1, TxDRxE),/*HV_DDI0_HPD*/ PAD_CFG_NF_IOSSTATE(GPIO_132, UP_20K, DEEP, NF1, TxDRxE),/*HV_DDI1_HPD*/ PAD_CFG_NF_IOSSTATE(GPIO_133, UP_20K, DEEP, NF1, TxDRxE),/*HV_EDP_HPD*/ PAD_CFG_GPO_IOSSTATE_IOSTERM(GPIO_134, 1, DEEP, UP_20K, IGNORE, SAME),/*Slot-1 Power Enable*/ PAD_CFG_GPO_IOSSTATE_IOSTERM(GPIO_135, 1, DEEP, UP_20K, IGNORE, SAME),/*Slot-2 Power Enable*/ PAD_CFG_GPO_IOSSTATE_IOSTERM(GPIO_136, 1, DEEP, DN_20K, IGNORE, SAME),/*DGPU Power Select*/ PAD_CFG_GPO_IOSSTATE_IOSTERM(GPIO_137, 1, DEEP, UP_20K, IGNORE, SAME),/*slot-1 Reset*/ PAD_CFG_NF_IOSSTATE_IOSTERM(GPIO_138, UP_20K, DEEP, NF2, HIZCRx1, DISPUPD),/*SATA_GP0 (DC RTD3 need)*/ PAD_CFG_NF_IOSSTATE_IOSTERM(GPIO_139, UP_20K, DEEP, NF2, TxLASTRxE, DISPUPD),/*SATA_GP1 (ZPODD_DEV_DET)*/ PAD_CFG_NF(GPIO_140, UP_20K, DEEP, NF5),/*SATA_DEVSLP0 (DC DEV SLP)*/ PAD_CFG_NF_IOSSTATE(GPIO_141, UP_20K, DEEP, NF5, HIZCRx1),/*SATA_DEVSLP1 (ZPODD DEV ATN)*/ PAD_CFG_NF_IOSSTATE(GPIO_142, UP_20K, DEEP, NF5, HIZCRx1),/*SATA_LED*/ PAD_CFG_GPI_APIC_IOS(GPIO_143, DN_20K, DEEP, LEVEL, NONE, HIZCRx1, SAME),/*DGPU Power Ok*/ PAD_CFG_NF_IOSSTATE(GPIO_144, UP_20K, DEEP, NF5, HIZCRx1),/*PANEL1_VDDEN*/ PAD_CFG_NF_IOSSTATE(GPIO_145, UP_20K, DEEP, NF5, HIZCRx1),/*PANEL1_BKLTEN*/ PAD_CFG_NF_IOSSTATE(GPIO_146, UP_20K, DEEP, NF5, HIZCRx1),/*PANEL1_BKLTCTL*/ PAD_CFG_GPO_IOSSTATE_IOSTERM(GPIO_157, 1, DEEP, UP_20K, IGNORE, SAME),/*WWAN_Reset/dGPS Reset*/ PAD_CFG_GPO_IOSSTATE_IOSTERM(GPIO_158, 0, DEEP, DN_20K, IGNORE, SAME),/*NFC_DFU*/ PAD_CFG_GPO_IOSSTATE_IOSTERM(GPIO_159, 1, DEEP, UP_20K, TxDRxE, ENPD),/*NFC reset*/ PAD_CFG_GPO_IOSSTATE_IOSTERM(GPIO_160, 0, DEEP, UP_20K, IGNORE, SAME),/*SD_MODE for spk*/ PAD_CFG_GPO_IOSSTATE_IOSTERM(GPIO_161, 1, DEEP, UP_20K, IGNORE, SAME),/*Touch panel reset*/ PAD_CFG_NF_IOSSTATE_IOSTERM(GPIO_162, DN_20K, DEEP, NF1, HIZCRx1, SAME),/*AVS_I2S1_BCLK*/ PAD_CFG_NF_IOSSTATE_IOSTERM(GPIO_163, DN_20K, DEEP, NF1, HIZCRx1, SAME),/*AVS_I2S1_WS_SYNC*/ PAD_CFG_GPO_IOSSTATE_IOSTERM(GPIO_164, 1, DEEP, UP_20K, TxDRxE, ENPD),/*Touch Panel Power Enable*/ PAD_CFG_NF_IOSSTATE_IOSTERM(GPIO_165, DN_20K, DEEP, NF1, HIZCRx1, SAME),/*AVS_I2S1_SDO*/ /* AUDIO COMMUNITY GPIOS*/ PAD_CFG_NF_IOSSTATE_IOSTERM(GPIO_166, DN_20K, DEEP, NF2, HIZCRx1, SAME),/*AVS_I2S2_BCLK*/ PAD_CFG_NF_IOSSTATE_IOSTERM(GPIO_167, DN_20K, DEEP, NF2, HIZCRx1, SAME),/*AVS_I2S2_WS_SYNC*/ PAD_CFG_NF_IOSSTATE_IOSTERM(GPIO_168, DN_20K, DEEP, NF2, HIZCRx1, SAME),/* AVS_I2S2_SDI*/ PAD_CFG_NF_IOSSTATE_IOSTERM(GPIO_169, DN_20K, DEEP, NF2, HIZCRx1, SAME),/*AVS_I2S2_SD0*/ PAD_CFG_NF_IOSSTATE_IOSTERM(GPIO_170, DN_20K, DEEP, NF2, HIZCRx1, SAME),/*AVS_I2S1_MCLK*/ PAD_CFG_NF_IOSTANDBY_IGNORE(GPIO_171, DN_20K, DEEP, NF1),/*AVS_M_CLK_A1*/ PAD_CFG_NF_IOSSTATE(GPIO_172, DN_20K, DEEP, NF1, HIZCRx1),/*AVS_M_CLK_B1*/ PAD_CFG_NF_IOSTANDBY_IGNORE(GPIO_173, DN_20K, DEEP, NF1),/*AVS_M_DATA_1*/ PAD_CFG_NF_IOSSTATE(GPIO_174, DN_20K, DEEP, NF1, HIZCRx1),/*AVS_M_CLK_AB2*/ PAD_CFG_NF_IOSSTATE_IOSTERM(GPIO_175, DN_20K, DEEP, NF1, HIZCRx1, ENPD),/*AVS_M_DATA_2*/ /* SCC COMMUNITY GPIOS */ PAD_CFG_NF_IOSTANDBY_IGNORE(GPIO_176, UP_20K, DEEP, NF1),/*SMB_ALERTB*/ PAD_CFG_NF_IOSTANDBY_IGNORE(GPIO_177, UP_20K, DEEP, NF1),/*SMB_CLK*/ PAD_CFG_NF_IOSTANDBY_IGNORE(GPIO_178, UP_20K, DEEP, NF1),/*SMB_DATA*/ PAD_CFG_NF_IOSTANDBY_IGNORE(GPIO_187, DN_20K, DEEP, NF1),/*SDCARD_LVL_WP*/ PAD_CFG_NF_IOSSTATE_IOSTERM(GPIO_179, DN_20K, DEEP, NF1, HIZCRx0, DISPUPD),/*SDCARD_CLK*/ PAD_CFG_NF(GPIO_180, DN_20K, DEEP, NF1),/*SDCARD_CLK_FB*/ PAD_CFG_NF_IOSSTATE_IOSTERM(GPIO_181, UP_20K, DEEP, NF1, HIZCRx1, DISPUPD),/*SDCARD_D0*/ PAD_CFG_NF_IOSSTATE_IOSTERM(GPIO_182, UP_20K, DEEP, NF1, HIZCRx1, DISPUPD),/*SDCARD_D1*/ PAD_CFG_NF_IOSSTATE_IOSTERM(GPIO_183, UP_20K, DEEP, NF1, HIZCRx1, DISPUPD),/*SDCARD_D2*/ PAD_CFG_NF_IOSSTATE_IOSTERM(GPIO_184, UP_20K, DEEP, NF1, HIZCRx1, DISPUPD),/*SDCARD_D3*/ PAD_CFG_NF_IOSSTATE_IOSTERM(GPIO_185, UP_20K, DEEP, NF1, HIZCRx1, DISPUPD),/*SDCARD_CMD*/ PAD_CFG_NF(GPIO_186, NONE, DEEP, NF1),/*SDCARD_CD_B*/ PAD_CFG_GPO_IOSSTATE_IOSTERM(GPIO_188, 0, DEEP, NONE, TxDRxE, SAME),/*SD Card*/ PAD_CFG_GPO_IOSSTATE_IOSTERM(GPIO_210, 1, DEEP, UP_20K, HIZCRx0, DISPUPD), PAD_CFG_NF_IOSSTATE(GPIO_189, DN_20K, DEEP, NF1, HIZCRx0),/*OSC_CLK_OUT_0*/ PAD_CFG_NF_IOSSTATE(GPIO_190, DN_20K, DEEP, NF1, HIZCRx0),/*OSC_CLK_OUT_1*/ PAD_CFG_NF_IOSTANDBY_IGNORE(GPIO_191, NONE, DEEP, NF1),/*CNV_BRI_DT*/ PAD_CFG_NF_IOSTANDBY_IGNORE(GPIO_192, UP_20K, DEEP, NF1),/*CNV_BRI_RSP*/ PAD_CFG_NF_IOSTANDBY_IGNORE(GPIO_193, NONE, DEEP, NF1),/*CNV_RGI_DT*/ PAD_CFG_NF_IOSTANDBY_IGNORE(GPIO_194, UP_20K, DEEP, NF1),/*CNV_RGI_RSP*/ PAD_CFG_NF_IOSTANDBY_IGNORE(GPIO_195, NONE, DEEP, NF1),/*CNV_RF_RESET_B*/ PAD_CFG_NF_IOSTANDBY_IGNORE(GPIO_196, NONE, DEEP, NF1),/*XTAL_CLKREQ*/ PAD_CFG_NF(GPIO_197, DN_20K, DEEP, NF1),/*SDIO_CLK_FB*/ PAD_CFG_NF_IOSSTATE(GPIO_198, DN_20K, DEEP, NF1, HIZCRx0),/*EMMC0_CLK*/ PAD_CFG_NF(GPIO_199, DN_20K, DEEP, NF1),/*EMMC0_CLK_FB*/ PAD_CFG_NF_IOSSTATE(GPIO_200, UP_20K, DEEP, NF1, HIZCRx1),/*EMMC0_D0*/ PAD_CFG_NF_IOSSTATE(GPIO_201, UP_20K, DEEP, NF1, HIZCRx1),/*EMMC0_D1*/ PAD_CFG_NF_IOSSTATE(GPIO_202, UP_20K, DEEP, NF1, HIZCRx1),/*EMMC0_D2*/ PAD_CFG_NF_IOSSTATE(GPIO_203, UP_20K, DEEP, NF1, HIZCRx1),/*EMMC0_D3*/ PAD_CFG_NF_IOSSTATE(GPIO_204, UP_20K, DEEP, NF1, HIZCRx1),/*EMMC0_D4*/ PAD_CFG_NF_IOSSTATE(GPIO_205, UP_20K, DEEP, NF1, HIZCRx1),/*EMMC0_D5*/ PAD_CFG_NF_IOSSTATE(GPIO_206, UP_20K, DEEP, NF1, HIZCRx1),/*EMMC0_D6*/ PAD_CFG_NF_IOSSTATE(GPIO_207, UP_20K, DEEP, NF1, HIZCRx1),/*EMMC0_D7*/ PAD_CFG_NF_IOSSTATE(GPIO_208, UP_20K, DEEP, NF1, HIZCRx1),/*EMMC0_CMD*/ PAD_CFG_NF_IOSSTATE(GPIO_209, DN_20K, DEEP, NF1, HIZCRx0),/*EMMC0_STROBE*/ }; const struct pad_config * __weak variant_gpio_table(size_t *num) { *num = ARRAY_SIZE(gpio_table); return gpio_table; } /* GPIOs needed prior to ramstage. */ static const struct pad_config early_gpio_table[] = { PAD_CFG_NF_IOSTANDBY_IGNORE(GPIO_177, UP_20K, DEEP, NF1), /* SMB_CLK */ PAD_CFG_NF_IOSTANDBY_IGNORE(GPIO_178, UP_20K, DEEP, NF1), /* SMB_DATA */ }; const struct pad_config * __weak variant_early_gpio_table(size_t *num) { *num = ARRAY_SIZE(early_gpio_table); return early_gpio_table; } /* GPIO settings before entering sleep. */ static const struct pad_config sleep_gpio_table[] = { #if 0 PAD_CFG_GPO(GPIO_150, 0, DEEP), /* NFC_RESET_ODL */ PAD_CFG_GPI_APIC_LOW(GPIO_20, NONE, DEEP), /* NFC_INT_L */ #endif }; const struct pad_config * __weak variant_sleep_gpio_table(size_t *num) { *num = ARRAY_SIZE(sleep_gpio_table); return sleep_gpio_table; } static const struct cros_gpio cros_gpios[] = { #if 0 CROS_GPIO_REC_AL(CROS_GPIO_VIRTUAL, CROS_GPIO_DEVICE_NAME), CROS_GPIO_WP_AH(CROS_GPIO_VIRTUAL, CROS_GPIO_DEVICE_NAME), #endif }; const struct cros_gpio * __weak variant_cros_gpios(size_t *num) { *num = ARRAY_SIZE(cros_gpios); return cros_gpios; }
MattDevo/coreboot
src/mainboard/intel/glkrvp/variants/baseboard/gpio.c
C
gpl-2.0
19,059
package com.fantasia.core; import java.security.MessageDigest; import java.security.NoSuchAlgorithmException; public class MD5 { // 全局数组 private final static String[] strDigits = { "0", "1", "2", "3", "4", "5", "6", "7", "8", "9", "a", "b", "c", "d", "e", "f" }; public MD5() { } // 返回形式为数字跟字符串 private static String byteToArrayString(byte bByte) { int iRet = bByte; // System.out.println("iRet="+iRet); if (iRet < 0) { iRet += 256; } int iD1 = iRet / 16; int iD2 = iRet % 16; return strDigits[iD1] + strDigits[iD2]; } // 转换字节数组为16进制字串 private static String byteToString(byte[] bByte) { StringBuffer sBuffer = new StringBuffer(); for (int i = 0; i < bByte.length; i++) { sBuffer.append(byteToArrayString(bByte[i])); } return sBuffer.toString(); } public static String GetMD5Code(String strObj) { String resultString = null; try { resultString = new String(strObj); MessageDigest md = MessageDigest.getInstance("MD5"); // md.digest() 该函数返回值为存放哈希值结果的byte数组 resultString = byteToString(md.digest(strObj.getBytes())); } catch (NoSuchAlgorithmException ex) { ex.printStackTrace(); } return resultString; } }
jiangrenwen/KPI
kpi/src/main/java/com/fantasia/core/MD5.java
Java
gpl-2.0
1,314
<?php $thumb = wp_get_attachment_image_src( get_post_thumbnail_id($post->ID), 'feature-image' ); $url = $thumb['0']; ?> <div class="feature-image overlay-black" style="background-image: url(<?=$url?>);"> <div class="page-banner"> <div class="container"> <div class="row"> <div class="col-sm-12"> <h1 class="text-reverse text-uppercase" style="margin:0;">Digital Government Transformation</h1> </div> </div> </div> </div> <div class="vertical-center"> <div class="container"> <div class="row"> <div class="col-sm-10 col-sm-offset-1"> <h1 class="entry-title text-reverse text-center"><?php the_title(); ?></h1> </div> </div> </div> </div> <?php echo do_shortcode('[image-attribution]'); ?> </div> <section class="content"> <div class="container"> <div class="row"> <div class="col-sm-8"> <?php while (have_posts()) : the_post(); ?> <article <?php post_class(); ?>> <div class="social-sharing"> <?php echo do_shortcode('[marketo-share-custom]');?> </div> <div class="entry-meta"> <p class="hidden-sm hidden-md hidden-lg">By <span><?php if(function_exists('coauthors')) coauthors();?></span> / <?php the_time('F j, Y') ?> / <?php Roots\Sage\Extras\blog_the_categories(); ?></p> <ul class="hidden-xs"> <li class="categories"> <?php $categories = get_the_category(); $separator = ', '; $output = ''; if ( ! empty( $categories ) ) { foreach( $categories as $category ) { $output .= '<a href="' . esc_url( get_category_link( $category->term_id ) ) . '" alt="' . esc_attr( sprintf( __( 'View all posts in %s', 'textdomain' ), $category->name ) ) . '">' . esc_html( $category->name ) . '</a>' . $separator; } echo trim( $output, $separator ); } ?> </li> <li class="date"><?php the_time('F j, Y') ?></li> <?php global $post; $author_id=$post->post_author; foreach( get_coauthors() as $coauthor ): ?> <li class="headshot"><?php echo get_avatar( $coauthor->user_email, '50' ); ?></li> <li class="author">By <?php echo $coauthor->display_name; ?></li> <?php endforeach; ?> </ul> </div> <?php the_content(); ?> <hr/> <div class="row next-prev-posts"> <?php $prev_post = get_previous_post(); if (!empty( $prev_post )): ?> <div class="col-sm-6"> <div class="margin-bottom-15 thumb"><span>Next Article</span><a href="<?php echo get_permalink( $prev_post->ID ); ?>"><?php echo get_the_post_thumbnail($prev_post->ID, 'post-thumbnail', array('class'=>'img-responsive')); ?></a></div> <div class="category-name"> <?php $cats = get_the_category( $prev_post->ID ); echo $cats[0]->cat_name; for ($i = 1; $i < count($cats); $i++) {echo ', ' . $cats[$i]->cat_name ;} ?> </div> <h5><a href="<?php echo get_permalink( $prev_post->ID ); ?>"><?php echo get_the_title( $prev_post->ID ); ?></a></h5> <p><small><?php echo get_the_time( 'F j, Y', $prev_post->ID ); ?></small></p> </div> <?php endif; ?> <?php $next_post = get_next_post(); if (!empty( $next_post )): ?> <div class="col-sm-6"> <div class="margin-bottom-15 thumb"><span>Previous Article</span><a href="<?php echo get_permalink( $next_post->ID ); ?>"><?php echo get_the_post_thumbnail($next_post->ID, 'post-thumbnail', array('class'=>'img-responsive')); ?></a></div> <div class="category-name"> <?php $cats = get_the_category( $next_post->ID ); echo $cats[0]->cat_name; for ($i = 1; $i < count($cats); $i++) {echo ', ' . $cats[$i]->cat_name ;} ?> </div> <h5><a href="<?php echo get_permalink( $next_post->ID ); ?>"><?php echo get_the_title( $next_post->ID ); ?></a></h5> <p><small><?php echo get_the_time( 'F j, Y', $next_post->ID ); ?></small></p> </div> <?php endif; ?> </div> <!-- Begin Outbrain --> <div class="OUTBRAIN hidden-xs" data-widget-id="NA"></div> <script type="text/javascript" async="async" src="https://widgets.outbrain.com/outbrain.js"></script> </article> <?php endwhile; ?> </div> <div class="col-sm-4 hidden-xs"> <?php echo do_shortcode('[newsletter-sidebar]'); ?> <?php $args = array( 'post_type' => 'post', 'order' => 'desc', 'posts_per_page' => 3, 'post_status' => 'publish', ); // The Query $the_query = new WP_Query( $args ); // The Loop if ( $the_query->have_posts() ) { echo '<ul class="no-bullets sidebar-list">'; echo '<li><h5>Recent Articles</h5></li>'; while ( $the_query->have_posts() ) { $the_query->the_post(); { ?> <?php $thumb = wp_get_attachment_image_src( get_post_thumbnail_id($post->ID), 'thumbnail' ); $url = $thumb['0'];?> <li> <div class="article-img-container"> <img src="<?=$url?>" class="img-responsive"> </div> <div class="article-title-container"> <a href="<?php the_permalink() ?>"><?php the_title(); ?></a><br><small><?php the_time('F j, Y') ?></small> </div> </li> <?php } } echo '<li><a href="/digital-government-transformation">View All Articles <i class="fa fa-arrow-circle-o-right"></i></a></li>'; echo '</ul>'; } else { // no posts found } /* Restore original Post Data */ wp_reset_postdata(); ?> <?php $args = array( 'post_type' => 'socrata_videos', 'order' => 'desc', 'posts_per_page' => 3, 'post_status' => 'publish', ); // The Query $the_query = new WP_Query( $args ); // The Loop if ( $the_query->have_posts() ) { echo '<ul class="no-bullets sidebar-list">'; echo '<li><h5>Recent Videos</h5></li>'; while ( $the_query->have_posts() ) { $the_query->the_post(); { ?> <li> <div class="article-img-container"> <img src="https://img.youtube.com/vi/<?php $meta = get_socrata_videos_meta(); echo $meta[1]; ?>/default.jpg" class="img-responsive"> </div> <div class="article-title-container"> <a href="<?php the_permalink() ?>"><?php the_title(); ?></a> </div> </li> <?php } } echo '<li><a href="/videos">View All Videos <i class="fa fa-arrow-circle-o-right"></i></a></li>'; echo '</ul>'; } else { // no posts found } /* Restore original Post Data */ wp_reset_postdata(); ?> <?php $args = array( 'post_type' => 'case_study', 'order' => 'desc', 'posts_per_page' => 3, 'post_status' => 'publish', ); // The Query $the_query = new WP_Query( $args ); // The Loop if ( $the_query->have_posts() ) { echo '<ul class="no-bullets sidebar-list">'; echo '<li><h5>Recent Case Studies</h5></li>'; while ( $the_query->have_posts() ) { $the_query->the_post(); { ?> <?php $thumb = wp_get_attachment_image_src( get_post_thumbnail_id($post->ID), 'thumbnail' ); $url = $thumb['0'];?> <li> <div class="article-img-container"> <img src="<?=$url?>" class="img-responsive"> </div> <div class="article-title-container"> <a href="<?php the_permalink() ?>"><?php the_title(); ?></a> </div> </li> <?php } } echo '<li><a href="/case-studies">View All Case Studies <i class="fa fa-arrow-circle-o-right"></i></a></li>'; echo '</ul>'; } else { // no posts found } /* Restore original Post Data */ wp_reset_postdata(); ?> <?php $today = strtotime('today UTC'); $event_meta_query = array( 'relation' => 'AND', array( 'key' => 'socrata_events_endtime', 'value' => $today, 'compare' => '>=', ) ); $args = array( 'post_type' => 'socrata_events', 'posts_per_page' => 3, 'post_status' => 'publish', 'ignore_sticky_posts' => true, 'meta_key' => 'socrata_events_endtime', 'orderby' => 'meta_value_num', 'order' => 'asc', 'meta_query' => $event_meta_query ); // The Query $the_query = new WP_Query( $args ); // The Loop if ( $the_query->have_posts() ) { echo '<ul class="no-bullets sidebar-list">'; echo '<li><h5>Upcoming Events</h5></li>'; while ( $the_query->have_posts() ) { $the_query->the_post(); { ?> <?php if ( has_term( 'socrata-event','socrata_events_cat' ) ) { ?> <li><small style="text-transform: uppercase;"><?php events_the_categories(); ?></small><br><a href="<?php the_permalink() ?>"><?php the_title(); ?></a><br><small><?php echo rwmb_meta( 'socrata_events_displaydate' );?></small></li> <?php } else { ?> <li><small style="text-transform: uppercase;"><?php events_the_categories(); ?></small><br> <?php $url = rwmb_meta( 'socrata_events_url' ); if ($url) { ?> <a href="<?php echo $url;?>" target="_blank"><?php the_title(); ?></a> <?php } else { ?> <?php the_title(); ?> <?php } ?> <br><small><?php echo rwmb_meta( 'socrata_events_displaydate' );?></small> </li> <?php } ?> <?php } } echo '<li><a href="/events">View All Events <i class="fa fa-arrow-circle-o-right"></i></a></li>'; echo '</ul>'; } else { ?> <ul class="no-bullets sidebar-list"> <li><h5>Upcoming Events</h5></li> <li>No events at this time.</li> </ul> <?php } /* Restore original Post Data */ wp_reset_postdata(); ?> </div> </div> </div> </section>
Socratacom/marketing-site
wp-content/themes/sage/templates/content-single.php
PHP
gpl-2.0
9,873
package org.openRealmOfStars.starMap.planet; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNotEquals; import org.junit.Test; import org.junit.experimental.categories.Category; import org.openRealmOfStars.player.PlayerInfo; import org.openRealmOfStars.player.SpaceRace.SpaceRace; import org.openRealmOfStars.player.SpaceRace.SpaceRaceUtility; import org.openRealmOfStars.starMap.Coordinate; import org.openRealmOfStars.starMap.planet.construction.Building; /** * * Open Realm of Stars game project * Copyright (C) 2016,2017 Tuomo Untinen * * 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/ * * * Test for planet * */ public class PlanetTest { @Test @Category(org.openRealmOfStars.BehaviourTest.class) public void testPlanetCoordinateShouldChangeableWithSideEffect() { Coordinate planetCoordinate = new Coordinate(10, 15); Planet planet = new Planet(planetCoordinate, "Earth", 1, false); planetCoordinate.setX(5); planetCoordinate.setY(10); assertNotEquals(planet.getCoordinate(), planetCoordinate); Coordinate getPlanetCoordinate = planet.getCoordinate(); getPlanetCoordinate.setX(5); getPlanetCoordinate.setY(10); assertNotEquals(planet.getCoordinate(), getPlanetCoordinate); } @Test @Category(org.openRealmOfStars.BehaviourTest.class) public void testPlanetPopulationGrowthAndBuilding() { Coordinate planetCoordinate = new Coordinate(10, 15); Planet planet = new Planet(planetCoordinate, "Earth", 1, false); planet.setRadiationLevel(1); PlayerInfo info = new PlayerInfo(SpaceRace.HUMAN); info.setEmpireName("Alliance of Humans"); planet.setPlanetOwner(0, info); planet.setWorkers(Planet.FOOD_FARMERS, 1); Building factory = BuildingFactory.createByName("Basic factory"); planet.setUnderConstruction(factory); assertEquals("The population of the planet should be one.", 1, planet.getTotalPopulation()); assertEquals("The production time should be 15 turns.", "15 turns", planet.getProductionTime(factory)); for (int i=0;i<5;i++) { // 5 turns to grow one population planet.updateOneTurn(); } assertEquals("The population of the planet should be two.", 2, planet.getTotalPopulation()); for (int i=0;i<10;i++) { // Total of 15 turns for basic factory planet.updateOneTurn(); } assertEquals("Planet should have only one building.", 1, planet.getBuildingList().length); assertEquals("Planet should have a Basic factory.", "Basic factory", planet.getBuildingList()[0].getName()); assertEquals(false,planet.isFullOfPopulation()); } @Test @Category(org.openRealmOfStars.BehaviourTest.class) public void testPlanetTextGenerator() { Coordinate planetCoordinate = new Coordinate(10, 15); Planet planet = new Planet(planetCoordinate, "Earth", 1, false); planet.setGroundSize(10); planet.setAmountMetalInGround(6543); planet.setRadiationLevel(1); planet.setName("Earth"); String tmp = planet.generateInfoText(false); assertEquals("Earth\nRadiation: 1\nSize: below average\n",tmp); tmp = planet.generateInfoText(true); assertEquals("Earth\nRadiation: 1\nSize: below average\nMetal: 6543\n",tmp); planet.setHomeWorldIndex(1); tmp = planet.generateInfoText(false); assertEquals("Earth\nRadiation: 1\nSize: below average\nHome world of\nMechions\n",tmp); tmp = planet.generateInfoText(true); assertEquals("Earth\nRadiation: 1\nSize: below average\nMetal: 6543\nHome world of\nMechions\n",tmp); PlayerInfo info = new PlayerInfo(SpaceRaceUtility.getRaceByName("Mechion")); info.setEmpireName("Mechion Great Empire"); planet.setPlanetOwner(0, info); planet.setWorkers(0, 1); planet.setCulture(5); tmp = planet.generateInfoText(true); assertEquals("Earth\nRadiation: 1\nSize: below average\nMetal: 6543\n" + "Home world of\nMechions\nMechion Great Empire\nPopulation" + ": 1\nCulture: 5",tmp); } }
sigee/Open-Realms-of-Stars
src/test/java/org/openRealmOfStars/starMap/planet/PlanetTest.java
Java
gpl-2.0
4,798
<?php /** * @package Joomla.Administrator * @subpackage Template.hathor * * @copyright Copyright (C) 2005 - 2014 Open Source Matters, Inc. All rights reserved. * @license GNU General Public License version 2 or later; see LICENSE.txt */ defined('_JEXEC') or die; // Include the component HTML helpers. JHtml::addIncludePath(JPATH_COMPONENT.'/helpers/html'); JHtml::_('behavior.multiselect'); $user = JFactory::getUser(); $listOrder = $this->escape($this->state->get('list.ordering')); $listDirn = $this->escape($this->state->get('list.direction')); ?> <form action="<?php echo JRoute::_('index.php?option=com_messages&view=messages'); ?>" method="post" name="adminForm" id="adminForm"> <?php if (!empty( $this->sidebar)) : ?> <div id="j-sidebar-container" class="span2"> <?php echo $this->sidebar; ?> </div> <div id="j-main-container" class="span10"> <?php else : ?> <div id="j-main-container"> <?php endif;?> <fieldset id="filter-bar"> <legend class="element-invisible"><?php echo JText::_('JSEARCH_FILTER_LABEL'); ?></legend> <div class="filter-search"> <label class="filter-search-lbl" for="filter_search"><?php echo JText::_('JSEARCH_FILTER_LABEL'); ?></label> <input type="text" name="filter_search" id="filter_search" value="<?php echo $this->escape($this->state->get('filter.search')); ?>" title="<?php echo JText::_('COM_MESSAGES_SEARCH_IN_SUBJECT'); ?>" /> <button type="submit"><?php echo JText::_('JSEARCH_FILTER_SUBMIT'); ?></button> <button type="button" onclick="document.getElementById('filter_search').value='';this.form.submit();"><?php echo JText::_('JSEARCH_FILTER_CLEAR'); ?></button> </div> <div class="filter-select"> <label class="selectlabel" for="filter_state"> <?php echo JText::_('JOPTION_SELECT_PUBLISHED'); ?> </label> <select name="filter_state" id="filter_state"> <option value=""><?php echo JText::_('JOPTION_SELECT_PUBLISHED');?></option> <?php echo JHtml::_('select.options', MessagesHelper::getStateOptions(), 'value', 'text', $this->state->get('filter.state'));?> </select> <button type="submit" id="filter-go"> <?php echo JText::_('JSUBMIT'); ?></button> </div> </fieldset> <div class="clr"> </div> <table class="adminlist"> <thead> <tr> <th class="checkmark-col"> <input type="checkbox" name="checkall-toggle" value="" title="<?php echo JText::_('JGLOBAL_CHECK_ALL'); ?>" onclick="Joomla.checkAll(this)" /> </th> <th class="title"> <?php echo JHtml::_('grid.sort', 'COM_MESSAGES_HEADING_SUBJECT', 'a.subject', $listDirn, $listOrder); ?> </th> <th class="width-5"> <?php echo JHtml::_('grid.sort', 'COM_MESSAGES_HEADING_READ', 'a.state', $listDirn, $listOrder); ?> </th> <th class="width-15"> <?php echo JHtml::_('grid.sort', 'COM_MESSAGES_HEADING_FROM', 'a.user_id_from', $listDirn, $listOrder); ?> </th> <th class="nowrap width-20"> <?php echo JHtml::_('grid.sort', 'JDATE', 'a.date_time', $listDirn, $listOrder); ?> </th> </tr> </thead> <tbody> <?php foreach ($this->items as $i => $item) : $canChange = $user->authorise('core.edit.state', 'com_messages'); ?> <tr class="row<?php echo $i % 2; ?>"> <td> <?php echo JHtml::_('grid.id', $i, $item->message_id); ?> </td> <td> <a href="<?php echo JRoute::_('index.php?option=com_messages&view=message&message_id='.(int) $item->message_id); ?>"> <?php echo $this->escape($item->subject); ?></a> </td> <td class="center"> <?php echo JHtml::_('messages.state', $item->state, $i, $canChange); ?> </td> <td> <?php echo $item->user_from; ?> </td> <td> <?php echo JHtml::_('date', $item->date_time, JText::_('DATE_FORMAT_LC2')); ?> </td> </tr> <?php endforeach; ?> </tbody> </table> <?php echo $this->pagination->getListFooter(); ?> <input type="hidden" name="task" value="" /> <input type="hidden" name="boxchecked" value="0" /> <input type="hidden" name="filter_order" value="<?php echo $listOrder; ?>" /> <input type="hidden" name="filter_order_Dir" value="<?php echo $listDirn; ?>" /> <?php echo JHtml::_('form.token'); ?> </div> </form>
subtext/joomla-cms
administrator/templates/hathor/html/com_messages/messages/default.php
PHP
gpl-2.0
4,185
<?php $this->placeholder('secBar')->captureStart(); ?> <section id="portal" class="navbar-wrapper<?php echo ($this->usuarioLogado ? ' fixed':'');?>"> <div class="container"> <a class="btn pull-left" target="_top" rel="acceso portal da educação" href="http://educadores.educacao.ba.gov.br"> <h4 class="link-cinza-claro"> <b class="link-cinza-escuro">educacao</b>.ba.gov.br </h4> </a> <ul class="list-inline hidden-sm hidden-xs pull-right"> <li> <a class="btn link-laranja hover-laranja" target="_top" href="http://escolas.educacao.ba.gov.br/"> <i class="fa fa-caret-right fa-lg"></i> escolas </a> </li> <li> <a class="btn link-verde hover-verde" target="_top" href="http://estudantes.educacao.ba.gov.br/"> <i class="fa fa-caret-right fa-lg"></i> estudantes </a> </li> <li> <a class="btn link-vermelho hover-vermelho" target="_top" href="http://educadores.educacao.ba.gov.br/"> <i class="fa fa-caret-right fa-lg"></i> educadores </a> </li> <li> <a class="btn link-azul hover-azul" target="_top" href="http://institucional.educacao.ba.gov.br/"> <i class="fa fa-caret-right fa-lg"></i> institucional </a> </li> <li> <a class="btn link-roxo hover-roxo" target="_top" href="http://municipios.educacao.ba.gov.br/"> <i class="fa fa-caret-right fa-lg"></i> municípios </a> </li> </ul> <!-- <ul class="list-inline navbar-toggle pull-right" style="padding: 0;"> <li><a class="btn link-laranja" target="_top" href="http://escolas.educacao.ba.gov.br/"><i class="fa fa-university fa-lg"></i></a></li> <li><a class="btn link-verde" target="_top" href="http://estudantes.educacao.ba.gov.br/"><i class="fa fa-child fa-lg"></i></a></li> <li><a class="btn link-vermelho" target="_top" href="http://educadores.educacao.ba.gov.br/"><i class="fa fa-users fa-lg"></i></a></li> <li><a class="btn link-azul" target="_top" href="http://institucional.educacao.ba.gov.br/"><i class="fa fa-building fa-lg"></i></a></li> <li><a class="btn link-roxo" target="_top" href="http://municipios.educacao.ba.gov.br/"><i class="fa fa-building-o fa-lg"></i></a></li> </ul> <iframe src="http://educadores.educacao.ba.gov.br/ambiente_educacional" id="portal_educacao" frameborder="0" height="38" width="100%" scrolling="no" style="display:none"></iframe> --> </div> </section> <?php $this->placeholder('secBar')->captureEnd(); ?>
redeanisioteixeira/aew_github
aew_sec/application/layouts/scripts/geral/_sec-bar.php
PHP
gpl-2.0
3,050
/* * COPYRIGHT (c) 1989-2010. * On-Line Applications Research Corporation (OAR). * * The license and distribution terms for this file may be * found in the file LICENSE in this distribution or at * http://www.rtems.com/license/LICENSE. * * $Id$ */ #ifdef HAVE_CONFIG_H #include "config.h" #endif #include <tmacros.h> #include "test_support.h" #include <unistd.h> #include <errno.h> #include <sys/types.h> void test_gid(void) { gid_t gid; int sc; gid = getegid(); printf( "getegid = %d\n", gid ); gid = getgid(); printf( "getgid = %d\n", gid ); puts( "setgid(5)" ); sc = setgid(5); rtems_test_assert( sc == 0 ); gid = getegid(); printf( "getegid = %d\n", gid ); gid = getgid(); printf( "getgid = %d\n", gid ); puts( "setpgid(getpid(), 10) - ENOSYS" ); sc = setpgid( getpid(), 10 ); rtems_test_assert( sc == -1 ); rtems_test_assert( errno == ENOSYS ); } void test_uid(void) { uid_t uid; int sc; uid = geteuid(); printf( "geteuid = %d\n", uid ); uid = getuid(); printf( "getuid = %d\n", uid ); puts( "setuid(5)" ); sc = setuid(5); rtems_test_assert( sc == 0 ); uid = geteuid(); printf( "geteuid = %d\n", uid ); uid = getuid(); printf( "getuid = %d\n", uid ); } pid_t __getpid(void); int issetugid(void); void test_pid(void) { pid_t pid; int sc; pid = getpid(); printf( "getpid = %d\n", pid ); pid = __getpid(); printf( "__getpid = %d\n", pid ); pid = getppid(); printf( "getppid = %d\n", pid ); puts( "setsid - EPERM" ); pid = setsid(); rtems_test_assert( pid == -1 ); rtems_test_assert( errno == EPERM ); sc = issetugid(); rtems_test_assert( sc == 0 ); puts( "getpgrp - return local node - OK" ); pid = getpgrp(); printf( "getpgrp returned %d\n", pid ); puts( "getgroups - return 0 - OK" ); sc = getgroups( 0, NULL ); rtems_test_assert( sc == 0 ); } void test_getlogin(void) { int sc; char ch; puts( "setuid(5)" ); sc = setuid(5); rtems_test_assert( sc == 0 ); printf( "getlogin() -- (%s)\n", getlogin() ); puts( "setuid(0)" ); sc = setuid(0); rtems_test_assert( sc == 0 ); printf( "getlogin() -- (%s)\n", getlogin() ); puts( "getlogin_r(NULL, LOGIN_NAME_MAX) -- EFAULT" ); sc = getlogin_r( NULL, LOGIN_NAME_MAX ); rtems_test_assert( sc == EFAULT ); puts( "getlogin_r(buffer, 0) -- ERANGE" ); sc = getlogin_r( &ch, 0 ); rtems_test_assert( sc == ERANGE ); } rtems_task Init( rtems_task_argument argument ) { puts( "\n\n*** TEST ID 01 ***" ); test_gid(); puts( "" ); test_uid(); puts( "" ); test_pid(); puts( "" ); test_getlogin(); puts( "*** END OF TEST ID 01 ***" ); rtems_test_exit(0); } /* configuration information */ #define CONFIGURE_APPLICATION_NEEDS_CONSOLE_DRIVER #define CONFIGURE_APPLICATION_NEEDS_CLOCK_DRIVER #define CONFIGURE_MAXIMUM_TASKS 1 /* so we can write /etc/passwd and /etc/group */ #define CONFIGURE_LIBIO_MAXIMUM_FILE_DESCRIPTORS 4 #define CONFIGURE_RTEMS_INIT_TASKS_TABLE #define CONFIGURE_INIT #include <rtems/confdefs.h> /* end of file */
daniel-hellstrom/leon-rtems
testsuites/psxtests/psxid01/init.c
C
gpl-2.0
3,102
/****************************************************************************** Copyright(C)2013,Hisilicon Co. LTD. ****************************************************************************** File Name : ImsaProcApsMsg.c Description : ¸ÃCÎļþʵÏÖAPSÏûÏ¢´¦ÀíºÍAPSÏûÏ¢·¢ËÍ History : 1.sunbing 49683 2013-06-19 Draft Enact ******************************************************************************/ /***************************************************************************** 1 Include HeadFile *****************************************************************************/ #include "ImsaConnManagement.h" #include "ImsaProcApsMsg.h" #include "TafApsApi.h" #include "ImsaPublic.h" #include "ImsaIntraInterface.h" #include "ImsaProcAtMsg.h" #include "ImsaCallManagement.h" #include "ImsaServiceManagement.h" #include "ImsaRegManagement.h" /*lint -e767*/ #define THIS_FILE_ID PS_FILE_ID_IMSAPROCAPSMSG_C #define THIS_NAS_FILE_ID NAS_FILE_ID_IMSAPROCAPSMSG_C /*lint +e767*/ /***************************************************************************** 1.1 Cplusplus Announce *****************************************************************************/ #ifdef __cplusplus #if __cplusplus extern "C" { #endif #endif #if (FEATURE_ON == FEATURE_IMS) /***************************************************************************** 2 Declare the Global Variable *****************************************************************************/ const IMSA_CONN_PS_EVT_FUNC_TBL_STRU g_astImsaConnPsEvtFuncTbl[] = { /* PS CALL */ {ID_EVT_TAF_PS_CALL_PDP_ACTIVATE_CNF, IMSA_CONN_ProcTafPsEvtPdpActivateCnf}, {ID_EVT_TAF_PS_CALL_PDP_ACTIVATE_REJ, IMSA_CONN_ProcTafPsEvtPdpActivateRej}, {ID_EVT_TAF_PS_CALL_PDP_ACTIVATE_IND, IMSA_CONN_ProcTafPsEvtPdpActivateInd}, {ID_EVT_TAF_PS_CALL_PDP_MODIFY_IND, IMSA_CONN_ProcTafPsEvtPdpModifyInd}, {ID_EVT_TAF_PS_CALL_PDP_DEACTIVATE_CNF, IMSA_CONN_ProcTafPsEvtPdpDeactivateCnf}, {ID_EVT_TAF_PS_CALL_PDP_DEACTIVATE_IND, IMSA_CONN_ProcTafPsEvtPdpDeactivateInd}, {ID_EVT_TAF_PS_CALL_PDP_IPV6_INFO_IND, IMSA_CONN_ProcTafPsEvtPdpIpv6InfoInd}, {ID_EVT_TAF_PS_CALL_ORIG_CNF, IMSA_CONN_ProcTafPsEvtCallOrigCnf}, {ID_EVT_TAF_PS_CALL_END_CNF, IMSA_CONN_ProcTafPsEvtCallEndCnf}, {ID_EVT_TAF_PS_SRVCC_CANCEL_NOTIFY_IND, IMSA_CONN_ProcTafPsEvtSrvccCancelInd}, }; const VOS_UINT32 g_ulImsaConnPsEvtFuncTblSize = sizeof(g_astImsaConnPsEvtFuncTbl) / sizeof(g_astImsaConnPsEvtFuncTbl[0]); extern VOS_VOID IMSA_CONN_WaitForIpv6InfoProc ( IMSA_CONN_TYPE_ENUM_UINT32 enConnType ); /* extern VOS_UINT32 IMSA_CONN_SipSignalPdpActOrig ( IMSA_CONN_TYPE_ENUM_UINT32 enConnType, VOS_UINT8 ucCid, IMSA_IP_TYPE_ENUM_UINT8 enIpType ); */ extern VOS_VOID IMSA_CONN_ProcActCnfBack ( const TAF_PS_CALL_PDP_ACTIVATE_CNF_STRU *pstPdpActivateCnf ); extern VOS_VOID IMSA_CONN_ProcIpv4ActCnf ( IMSA_CONN_TYPE_ENUM_UINT32 enConnType, const TAF_PS_CALL_PDP_ACTIVATE_CNF_STRU *pstPdpActivateCnf ); extern VOS_VOID IMSA_CONN_ProcIpv6ActCnf ( IMSA_CONN_TYPE_ENUM_UINT32 enConnType, const TAF_PS_CALL_PDP_ACTIVATE_CNF_STRU *pstPdpActivateCnf ); extern VOS_VOID IMSA_CONN_ProcIpv4v6ActCnf ( IMSA_CONN_TYPE_ENUM_UINT32 enConnType ); extern VOS_VOID IMSA_CONN_ProcActRejCurReqIpv4v6 ( IMSA_CONN_TYPE_ENUM_UINT32 enConnType, const TAF_PS_CALL_PDP_ACTIVATE_REJ_STRU *pstPdpActivateRej ); extern VOS_VOID IMSA_CONN_ProcActRejCurReqIpv4 ( IMSA_CONN_TYPE_ENUM_UINT32 enConnType, const TAF_PS_CALL_PDP_ACTIVATE_REJ_STRU *pstPdpActivateRej ); extern VOS_VOID IMSA_CONN_ProcActRejCurReqIpv6 ( IMSA_CONN_TYPE_ENUM_UINT32 enConnType, const TAF_PS_CALL_PDP_ACTIVATE_REJ_STRU *pstPdpActivateRej ); extern VOS_UINT32 IMSA_CONN_MatchIPV4V6FallBackCause ( TAF_PS_CAUSE_ENUM_UINT32 enCause ); /***************************************************************************** 3 Function *****************************************************************************/ /*lint -e960*/ /*lint -e961*/ VOS_VOID IMSA_CONN_ProcTafPsEvt ( TAF_PS_EVT_STRU *pstEvt ) { VOS_UINT32 i = IMSA_NULL; VOS_UINT32 ulResult = IMSA_NULL; IMSA_CONN_PS_EVT_FUNC pPsEvtFunc = VOS_NULL_PTR; /* ÔÚʼþ´¦Àí±íÖвéÕÒ´¦Àíº¯Êý */ for ( i = 0; i < g_ulImsaConnPsEvtFuncTblSize; i++ ) { if ( pstEvt->ulEvtId == g_astImsaConnPsEvtFuncTbl[i].ulEvtId ) { /* ʼþIDÆ¥Åä */ pPsEvtFunc = g_astImsaConnPsEvtFuncTbl[i].pPsEvtFunc; break; } } /* Èç¹û´¦Àíº¯Êý´æÔÚÔòµ÷Óà */ if ( VOS_NULL_PTR != pPsEvtFunc ) { ulResult = pPsEvtFunc(pstEvt->aucContent); } else { IMSA_ERR_LOG1("IMSA_CONN_ProcTafPsEvt: Unexpected event received! <EvtId>", pstEvt->ulEvtId); ulResult = VOS_ERR; } if ( VOS_OK != ulResult ) { IMSA_ERR_LOG1("IMSA_CONN_ProcTafPsEvt: Handle this event failed! <EvtId>", pstEvt->ulEvtId); } return; } VOS_VOID IMSA_CONN_WaitForIpv6InfoProc ( IMSA_CONN_TYPE_ENUM_UINT32 enConnType ) { IMSA_NORMAL_CONN_STRU *pstNormalConn = VOS_NULL_PTR; IMSA_EMC_CONN_STRU *pstEmcConn = VOS_NULL_PTR; IMSA_IP_ADDRESS_STRU *pstPdpIpAddr = VOS_NULL_PTR; VOS_UINT32 i = IMSA_NULL; VOS_UINT8 aucTemp[IMSA_IPV6_PREFIX_LEN] = {0}; /* »ñÈ¡PRIM PDP²ÎÊýµÄ¸ñʽ */ if (IMSA_CONN_TYPE_NORMAL == enConnType) { pstNormalConn = IMSA_CONN_GetNormalConnAddr(); for (i = 0; i < pstNormalConn->ulSipSignalPdpNum; i++) { pstPdpIpAddr = &pstNormalConn->astSipSignalPdpArray[i].stPdpAddr; if (((IMSA_IP_TYPE_IPV6 == pstPdpIpAddr->enIpType) || (IMSA_IP_TYPE_IPV4V6 == pstPdpIpAddr->enIpType)) && (0 == IMSA_MEM_CMP(aucTemp, pstPdpIpAddr->aucIpV6Addr, IMSA_IPV6_PREFIX_LEN))) { /* Æô¶¯µÈ´ýIPV6²ÎÊý¶¨Ê±Æ÷£¬µÈ´ýAPSµÄID_EVT_TAF_PS_CALL_PDP_IPV6_INFO_INDÏûÏ¢£¬ ²»ÐÞ¸ÄÁ¬½Ó״̬ */ IMSA_CONN_StartTimer(IMSA_CONN_TYPE_NORMAL, TI_IMSA_WAIT_IPV6_INFO); return ; } } } else { pstEmcConn = IMSA_CONN_GetEmcConnAddr(); pstPdpIpAddr = &pstEmcConn->stSipSignalPdp.stPdpAddr; if (((IMSA_IP_TYPE_IPV6 == pstPdpIpAddr->enIpType) || (IMSA_IP_TYPE_IPV4V6 == pstPdpIpAddr->enIpType)) && (0 == IMSA_MEM_CMP(aucTemp, pstPdpIpAddr->aucIpV6Addr, IMSA_IPV6_PREFIX_LEN))) { /* Æô¶¯µÈ´ýIPV6²ÎÊý¶¨Ê±Æ÷£¬µÈ´ýAPSµÄID_EVT_TAF_PS_CALL_PDP_IPV6_INFO_INDÏûÏ¢£¬ ²»ÐÞ¸ÄÁ¬½Ó״̬ */ IMSA_CONN_StartTimer(IMSA_CONN_TYPE_EMC, TI_IMSA_WAIT_IPV6_INFO); return ; } } IMSA_CONN_SetupConnSucc(enConnType); } VOS_UINT32 IMSA_CONN_SipSignalPdpActOrig ( IMSA_CONN_TYPE_ENUM_UINT32 enConnType, VOS_UINT8 ucCid, IMSA_IP_TYPE_ENUM_UINT8 enIpType ) { TAF_PS_DIAL_PARA_STRU *pstDialParaInfo = VOS_NULL_PTR; /* TAF_PDP_PRIM_CONTEXT_EXT_STRU stPdpPrimContextExt = {0}; */ IMSA_NORMAL_CONN_STRU *pstNormalConn = VOS_NULL_PTR; IMSA_EMC_CONN_STRU *pstEmcConn = VOS_NULL_PTR; VOS_UINT8 ucOpid = IMSA_NULL; pstNormalConn = IMSA_CONN_GetNormalConnAddr(); pstEmcConn = IMSA_CONN_GetEmcConnAddr(); IMSA_INFO_LOG1("IMSA_CONN_SipSignalPdpActOrig: enConnType:", enConnType); IMSA_INFO_LOG1("IMSA_CONN_SipSignalPdpActOrig: ucCid:", ucCid); IMSA_INFO_LOG1("IMSA_CONN_SipSignalPdpActOrig: enIpType:", enIpType); /* »ñÈ¡PRIM PDP²ÎÊýµÄ¸ñʽ */ /* if (IMSA_CONN_TYPE_NORMAL == enConnType) { IMSA_CONN_GetPrimPdpCntFromSelSdfPara(&pstNormalConn->stSelSdfPara, &stPdpPrimContextExt); } else { IMSA_CONN_GetPrimPdpCntFromSelSdfPara(&pstEmcConn->stSelSdfPara, &stPdpPrimContextExt); } stPdpPrimContextExt.enPdpType = enIpType; stPdpPrimContextExt.ucCid = ucCid; IMSA_CONN_AssignOpid(enConnType, &ucOpid); if (VOS_ERR == TAF_PS_SetPrimPdpContextInfo(PS_PID_IMSA, IMSA_CLIENT_ID, ucOpid, &stPdpPrimContextExt)) { IMSA_ERR_LOG("IMSA_CONN_SipSignalPdpActOrig:TAF_PS_SetPrimPdpContextInfo failed!"); return IMSA_FAIL; } */ /* »ñÈ¡²¦ºÅ²ÎÊý */ pstDialParaInfo = IMSA_MEM_ALLOC(sizeof(TAF_PS_DIAL_PARA_STRU)); if (VOS_NULL_PTR == pstDialParaInfo) { /*´òÓ¡²»ºÏ·¨ÐÅÏ¢*/ IMSA_ERR_LOG("IMSA_CONN_SipSignalPdpActOrig:TAF_PS_DIAL_PARA_STRU ERROR: Mem alloc fail!"); return IMSA_FAIL; } if (IMSA_CONN_TYPE_NORMAL == enConnType) { IMSA_CONN_GetImsDailParaFromSelSdfPara(&pstNormalConn->stSelSdfPara, pstDialParaInfo); pstNormalConn->stSelSdfPara.ucCid = ucCid; pstNormalConn->stSelSdfPara.enPdnType = enIpType; } else { IMSA_CONN_GetImsDailParaFromSelSdfPara(&pstEmcConn->stSelSdfPara, pstDialParaInfo); pstEmcConn->stSelSdfPara.ucCid = ucCid; pstEmcConn->stSelSdfPara.enPdnType = enIpType; } pstDialParaInfo->ucCid = ucCid; pstDialParaInfo->enPdpType = enIpType; IMSA_CONN_AssignOpid(enConnType, &ucOpid); /* IMSA_CONN_SetNormalConnOpid(ucOpid); */ IMSA_CONN_SetOpid(enConnType, ucOpid); if (VOS_OK == TAF_PS_CallOrig(PS_PID_IMSA,IMSA_CLIENT_ID, ucOpid, pstDialParaInfo)) { /* Æô¶¯IMS²¦ºÅ¶¨Ê±Æ÷ */ IMSA_CONN_StartTimer(enConnType, TI_IMSA_SIP_SIGAL_PDP_ORIG); /* Ð޸ĵ±Ç°²¦ºÅÇëÇóµÄPDNÀàÐÍ */ IMSA_CONN_SaveCurReqPdnType(enConnType, enIpType); IMSA_MEM_FREE(pstDialParaInfo); return IMSA_SUCC; } IMSA_MEM_FREE(pstDialParaInfo); return IMSA_FAIL; } VOS_VOID IMSA_CONN_ProcActCnfBack ( const TAF_PS_CALL_PDP_ACTIVATE_CNF_STRU *pstPdpActivateCnf ) { VOS_UINT8 ucCid = IMSA_NULL; VOS_UINT32 ulRet = IMSA_FAIL; VOS_UINT8 ucOpid = IMSA_NULL; IMSA_INFO_LOG("IMSA_CONN_ProcActCnfBack is entered!"); if ((VOS_TRUE == pstPdpActivateCnf->bitOpCause) && (TAF_PS_CAUSE_SM_NW_SINGLE_ADDR_BEARERS_ONLY_ALLOWED != pstPdpActivateCnf->enCause)) { IMSA_INFO_LOG("IMSA_CONN_ProcActCnfBack:Not Back!"); /* ²»»á·¢ÆðÁíÒ»¸öSIPÐÅÁî³ÐÔØµÄ½¨Á¢ */ /* Èç¹ûIPV6È«¾ÖµØÖ·ÒÑ»ñµÃ£¬»Ø¸´Á¬½Ó½¨Á¢³É¹¦£»·ñÔòÆô¶¯µÈ´ýIPV6²ÎÊý¶¨Ê±Æ÷ */ IMSA_CONN_WaitForIpv6InfoProc(IMSA_CONN_TYPE_NORMAL); return ; } if (TAF_PDP_IPV4 == pstPdpActivateCnf->stPdpAddr.enPdpType) { if (IMSA_PDP_STATE_ACTIVE == IMSA_CONN_GetSipSignalPdpState(IMSA_CONN_TYPE_NORMAL, TAF_PDP_IPV6)) { IMSA_INFO_LOG("IMSA_CONN_ProcActCnfBack:IPV6 is already active!"); /* Èç¹ûIPV6È«¾ÖµØÖ·ÒÑ»ñµÃ£¬»Ø¸´Á¬½Ó½¨Á¢³É¹¦£»·ñÔòÆô¶¯µÈ´ýIPV6²ÎÊý¶¨Ê±Æ÷ */ IMSA_CONN_WaitForIpv6InfoProc(IMSA_CONN_TYPE_NORMAL); return ; } /* ²éÕÒÒ»¸öδ¼¤»îµÄCID½øÐ줻î */ IMSA_CONN_AssignOpid(IMSA_CONN_TYPE_NORMAL, &ucOpid); ulRet = TAF_PS_GetUnusedCid(PS_PID_IMSA, IMSA_CLIENT_ID, ucOpid, &ucCid); if (VOS_OK != ulRet) { IMSA_WARN_LOG("IMSA_CONN_ProcActCnfBack:IPV4,get cid failed"); IMSA_CONN_SetupConnSucc(IMSA_CONN_TYPE_NORMAL); return ; } ulRet = IMSA_CONN_SipSignalPdpActOrig(IMSA_CONN_TYPE_NORMAL, ucCid, TAF_PDP_IPV6); if (IMSA_SUCC != ulRet) { IMSA_WARN_LOG("IMSA_CONN_ProcActCnfBack:IPV4,IMSA_CONN_SipSignalPdpActOrig failed"); IMSA_CONN_SetupConnSucc(IMSA_CONN_TYPE_NORMAL); return ; } return ; } else if (TAF_PDP_IPV6 == pstPdpActivateCnf->stPdpAddr.enPdpType) { if (IMSA_PDP_STATE_ACTIVE == IMSA_CONN_GetSipSignalPdpState(IMSA_CONN_TYPE_NORMAL, TAF_PDP_IPV4)) { IMSA_INFO_LOG("IMSA_CONN_ProcActCnfBack:IPV4 is already active!"); /* Èç¹ûIPV6È«¾ÖµØÖ·ÒÑ»ñµÃ£¬»Ø¸´Á¬½Ó½¨Á¢³É¹¦£»·ñÔòÆô¶¯µÈ´ýIPV6²ÎÊý¶¨Ê±Æ÷ */ IMSA_CONN_WaitForIpv6InfoProc(IMSA_CONN_TYPE_NORMAL);\ return ; } /* ²éÕÒÒ»¸öδ¼¤»îµÄCID½øÐ줻î */ IMSA_CONN_AssignOpid(IMSA_CONN_TYPE_NORMAL, &ucOpid); ulRet = TAF_PS_GetUnusedCid(PS_PID_IMSA, IMSA_CLIENT_ID, ucOpid, &ucCid); if (VOS_OK != ulRet) { IMSA_WARN_LOG("IMSA_CONN_ProcActCnfBack:IPV6,get cid failed"); /* Èç¹ûIPV6È«¾ÖµØÖ·ÒÑ»ñµÃ£¬»Ø¸´Á¬½Ó½¨Á¢³É¹¦£»·ñÔòÆô¶¯µÈ´ýIPV6²ÎÊý¶¨Ê±Æ÷ */ IMSA_CONN_WaitForIpv6InfoProc(IMSA_CONN_TYPE_NORMAL); return ; } ulRet = IMSA_CONN_SipSignalPdpActOrig(IMSA_CONN_TYPE_NORMAL, ucCid, TAF_PDP_IPV4); if (IMSA_SUCC != ulRet) { IMSA_WARN_LOG("IMSA_CONN_ProcActCnfBack:IPV6,IMSA_CONN_SipSignalPdpActOrig failed"); /* Èç¹ûIPV6È«¾ÖµØÖ·ÒÑ»ñµÃ£¬»Ø¸´Á¬½Ó½¨Á¢³É¹¦£»·ñÔòÆô¶¯µÈ´ýIPV6²ÎÊý¶¨Ê±Æ÷ */ IMSA_CONN_WaitForIpv6InfoProc(IMSA_CONN_TYPE_NORMAL); return ; } return ; } else { ; } return; } VOS_VOID IMSA_CONN_ProcIpv4ActCnf ( IMSA_CONN_TYPE_ENUM_UINT32 enConnType, const TAF_PS_CALL_PDP_ACTIVATE_CNF_STRU *pstPdpActivateCnf ) { IMSA_NORMAL_CONN_STRU *pstNormalConn = VOS_NULL_PTR; VOS_UINT8 ucCid = IMSA_NULL; VOS_UINT32 ulRet = IMSA_FAIL; VOS_UINT8 ucOpid = IMSA_NULL; if (IMSA_CONN_TYPE_EMC == enConnType) { IMSA_INFO_LOG("IMSA_CONN_ProcIpv4ActCnf:EMC!"); /* ÓÉÓÚ3GPPЭÒéÒªÇóͬһʱ¿ÌÖ»ÄÜ´æÔÚÒ»¸ö½ô¼±³ÐÔØ£¬Òò´Ë²»»áÔÙ·¢ÆðÁíÒ»¸ö½ô¼± ³ÐÔØ½¨Á¢ */ IMSA_CONN_SetupConnSucc(IMSA_CONN_TYPE_EMC); return ; } pstNormalConn = IMSA_CONN_GetNormalConnAddr(); /* Èç¹ûÊÇIPV4V6£¬ÐèÒª¼¤»îÁíÒ»¸öPDP */ if (IMSA_IP_TYPE_IPV4V6 != pstNormalConn->enFirstReqPdnType) { IMSA_INFO_LOG("IMSA_CONN_ProcIpv4ActCnf:Not ipv4v6"); IMSA_CONN_SetupConnSucc(IMSA_CONN_TYPE_NORMAL); return ; } switch (pstNormalConn->enCurReqPdnType) { /* ÕâÖÖÇé¿ö²»ÊôÓÚPDP»ØÍË£¬ÊÇÇ°ÃæPDP¼¤»î±»¾Ü¾øºó£¬·Ö±ð·¢ÆðIPV4¡¢ IPV6µÄPDP¼¤»î¡£*/ case IMSA_IP_TYPE_IPV4: if (IMSA_PDP_STATE_ACTIVE == IMSA_CONN_GetSipSignalPdpState(IMSA_CONN_TYPE_NORMAL, IMSA_IP_TYPE_IPV6)) { IMSA_INFO_LOG("IMSA_CONN_ProcIpv4ActCnf:ipv6 already active"); /* Èç¹ûIPV6È«¾ÖµØÖ·ÒÑ»ñµÃ£¬»Ø¸´Á¬½Ó½¨Á¢³É¹¦£»·ñÔòÆô¶¯µÈ´ýIPV6²ÎÊý¶¨Ê±Æ÷ */ IMSA_CONN_WaitForIpv6InfoProc(IMSA_CONN_TYPE_NORMAL); return ; } /* ²éÕÒÒ»¸öδ¼¤»îµÄCID½øÐ줻î */ IMSA_CONN_AssignOpid(enConnType, &ucOpid); ulRet = TAF_PS_GetUnusedCid(PS_PID_IMSA, IMSA_CLIENT_ID, ucOpid, &ucCid); if (VOS_OK != ulRet) { IMSA_WARN_LOG("IMSA_CONN_ProcIpv4ActCnf:get cid failed!"); IMSA_CONN_SetupConnSucc(IMSA_CONN_TYPE_NORMAL); return ; } ulRet = IMSA_CONN_SipSignalPdpActOrig(IMSA_CONN_TYPE_NORMAL, ucCid, TAF_PDP_IPV6); if (IMSA_SUCC != ulRet) { IMSA_WARN_LOG("IMSA_CONN_ProcIpv4ActCnf:IMSA_CONN_SipSignalPdpActOrig failed!"); IMSA_CONN_SetupConnSucc(IMSA_CONN_TYPE_NORMAL); return ; } break; /* ÕâÀïÊÇPDP¼¤»î»ØÍ˹¦ÄÜʵÏÖ */ case IMSA_IP_TYPE_IPV4V6: IMSA_CONN_ProcActCnfBack(pstPdpActivateCnf); break; default: IMSA_WARN_LOG("IMSA_CONN_ProcIpv4ActCnf:current requst Pdn Type is error!"); break; } return; } VOS_VOID IMSA_CONN_ProcIpv6ActCnf ( IMSA_CONN_TYPE_ENUM_UINT32 enConnType, const TAF_PS_CALL_PDP_ACTIVATE_CNF_STRU *pstPdpActivateCnf ) { IMSA_NORMAL_CONN_STRU *pstNormalConn = VOS_NULL_PTR; if (IMSA_CONN_TYPE_EMC == enConnType) { /* ÓÉÓÚ3GPPЭÒéÒªÇóͬһʱ¿ÌÖ»ÄÜ´æÔÚÒ»¸ö½ô¼±³ÐÔØ£¬Òò´Ë²»»áÔÙ·¢ÆðÁíÒ»¸ö½ô¼± ³ÐÔØ½¨Á¢ */ /* Èç¹ûIPV6È«¾ÖµØÖ·ÒÑ»ñµÃ£¬»Ø¸´Á¬½Ó½¨Á¢³É¹¦£»·ñÔòÆô¶¯µÈ´ýIPV6²ÎÊý¶¨Ê±Æ÷ */ IMSA_CONN_WaitForIpv6InfoProc(IMSA_CONN_TYPE_EMC); return ; } pstNormalConn = IMSA_CONN_GetNormalConnAddr(); /* Èç¹ûÊÇIPV4V6£¬ÐèÒª¼¤»îÁíÒ»¸öPDP */ if (IMSA_IP_TYPE_IPV4V6 != pstNormalConn->enFirstReqPdnType) { IMSA_INFO_LOG("IMSA_CONN_ProcIpv6ActCnf:Not ipv4v6"); /* Èç¹ûIPV6È«¾ÖµØÖ·ÒÑ»ñµÃ£¬»Ø¸´Á¬½Ó½¨Á¢³É¹¦£»·ñÔòÆô¶¯µÈ´ýIPV6²ÎÊý¶¨Ê±Æ÷ */ IMSA_CONN_WaitForIpv6InfoProc(IMSA_CONN_TYPE_NORMAL); return ; } /* Èç¹ûÊÇIPV4V6£¬ÐèÒª¼¤»îÁíÒ»¸öPDP */ switch (pstNormalConn->enCurReqPdnType) { case TAF_PDP_IPV6: /* ÕâÖÖÇé¿ö²»ÊôÓÚPDP»ØÍË£¬ÊÇÇ°ÃæPDP¼¤»î±»¾Ü¾øºó£¬·Ö±ð·¢ÆðIPV4¡¢ IPV6µÄPDP¼¤»î, IPV6¼¤»îºó²»ÔÙ·¢ÆðIPV4µÄPDP¼¤»î */ /* Èç¹ûIPV6È«¾ÖµØÖ·ÒÑ»ñµÃ£¬»Ø¸´Á¬½Ó½¨Á¢³É¹¦£»·ñÔòÆô¶¯µÈ´ýIPV6²ÎÊý¶¨Ê±Æ÷ */ IMSA_CONN_WaitForIpv6InfoProc(IMSA_CONN_TYPE_NORMAL); break; /* ÕâÀïÊÇPDP¼¤»î»ØÍ˹¦ÄÜʵÏÖ */ case TAF_PDP_IPV4V6: IMSA_CONN_ProcActCnfBack(pstPdpActivateCnf); break; default: IMSA_WARN_LOG("IMSA_CONN_ProcIpv4ActCnf:current requst Pdn Type is error!"); break; } return; } VOS_VOID IMSA_CONN_ProcIpv4v6ActCnf ( IMSA_CONN_TYPE_ENUM_UINT32 enConnType ) { /* Èç¹ûIPV6È«¾ÖµØÖ·ÒÑ»ñµÃ£¬»Ø¸´Á¬½Ó½¨Á¢³É¹¦£»·ñÔòÆô¶¯µÈ´ýIPV6²ÎÊý¶¨Ê±Æ÷ */ IMSA_CONN_WaitForIpv6InfoProc(enConnType); } VOS_UINT32 IMSA_CONN_MatchIPV4V6FallBackCause ( TAF_PS_CAUSE_ENUM_UINT32 enCause ) { IMSA_CONN_MANAGER_STRU *pstConnManager; VOS_UINT32 ulCnt = IMSA_NULL; IMSA_INFO_LOG("IMSA_CONN_MatchIPV4V6FallBackCause is entered!"); if (TAF_PS_CAUSE_SM_NW_UNKNOWN_PDP_ADDR_OR_TYPE == enCause) { IMSA_INFO_LOG("IMSA_CONN_MatchIPV4V6FallBackCause: cause match #28!"); return IMSA_SUCC; } pstConnManager = IMSA_CONN_GetConnManagerAddr(); for (ulCnt = 0; ulCnt < pstConnManager->stIpv6FallBackExtCause.ulCauseNum; ulCnt++) { if (pstConnManager->stIpv6FallBackExtCause.aenPsCause[ulCnt] == enCause) { IMSA_INFO_LOG("IMSA_CONN_MatchIPV4V6FallBackCause: cause match succ!"); return IMSA_SUCC; } } return IMSA_FAIL; } VOS_VOID IMSA_CONN_ProcActRejCurReqIpv4v6 ( IMSA_CONN_TYPE_ENUM_UINT32 enConnType, const TAF_PS_CALL_PDP_ACTIVATE_REJ_STRU *pstPdpActivateRej ) { VOS_UINT32 ulResult = IMSA_FAIL; VOS_UINT8 ucCid = IMSA_NULL; /* ÕâÖÖÇé¿ö£¬ÐèÒª·Ö±ð·¢ÆðIPv4¡¢IPv6µÄPDP¼¤»î */ if (IMSA_SUCC == IMSA_CONN_MatchIPV4V6FallBackCause(pstPdpActivateRej->enCause)) { IMSA_INFO_LOG("IMSA_CONN_ProcActRejCurReqIpv4v6: match fallback cause succ!"); IMSA_CONN_GetConnSelectedCid(enConnType, ucCid); ulResult = IMSA_CONN_SipSignalPdpActOrig(enConnType, ucCid, IMSA_IP_TYPE_IPV4); if (IMSA_SUCC != ulResult) { IMSA_WARN_LOG("IMSA_CONN_ProcActRejCurReqIpv4v6:unknown pdp addr or type,IMSA_CONN_SipSignalPdpActOrig failed!"); IMSA_CONN_SetupConnFail(enConnType, IMSA_CONN_RESULT_FAIL_CN_REJ,pstPdpActivateRej->enCause); return ; } return ; } if (IMSA_IP_TYPE_IPV4V6 == pstPdpActivateRej->enPdpType) { IMSA_WARN_LOG("IMSA_CONN_ProcActRejCurReqIpv4v6:ipv4v6"); IMSA_CONN_SetupConnFail(enConnType, IMSA_CONN_RESULT_FAIL_CN_REJ,pstPdpActivateRej->enCause); return ; } if ((IMSA_OP_TRUE == pstPdpActivateRej->bitOpCauseEx) && (TAF_PS_CAUSE_SM_NW_SINGLE_ADDR_BEARERS_ONLY_ALLOWED != pstPdpActivateRej->enCauseEx)) { IMSA_WARN_LOG("IMSA_CONN_ProcActRejCurReqIpv4v6:Causeex is not sigle addr bearers only allowed!"); IMSA_CONN_SetupConnFail(enConnType, IMSA_CONN_RESULT_FAIL_CN_REJ,pstPdpActivateRej->enCause); return ; } if (IMSA_IP_TYPE_IPV4 == pstPdpActivateRej->enPdpType) { IMSA_CONN_GetConnSelectedCid(enConnType, ucCid); ulResult = IMSA_CONN_SipSignalPdpActOrig(enConnType, ucCid, IMSA_IP_TYPE_IPV6); if (IMSA_SUCC != ulResult) { IMSA_WARN_LOG("IMSA_CONN_ProcActRejCurReqIpv4v6:qos not accepted,ipv4,IMSA_CONN_SipSignalPdpActOrig failed!"); IMSA_CONN_SetupConnFail(enConnType, IMSA_CONN_RESULT_FAIL_CN_REJ,pstPdpActivateRej->enCause); return ; } return ; } else { IMSA_CONN_GetConnSelectedCid(enConnType, ucCid); ulResult = IMSA_CONN_SipSignalPdpActOrig(enConnType, ucCid, IMSA_IP_TYPE_IPV4); if (IMSA_SUCC != ulResult) { IMSA_WARN_LOG("IMSA_CONN_ProcActRejCurReqIpv4v6:qos not accepted,ipv6,IMSA_CONN_SipSignalPdpActOrig failed!"); IMSA_CONN_SetupConnFail(enConnType, IMSA_CONN_RESULT_FAIL_CN_REJ,pstPdpActivateRej->enCause); return ; } /* ÓÉÓÚIPV6ÒѾ­È·¶¨²»»á³É¹¦£¬ÎªÁË·ÀÖ¹ºóÐøÔÙ³¢ÊÔIPV6ÀàÐÍ£¬½« first requst pdn typeÉèÖÃΪIPV4 */ IMSA_CONN_SaveFirstReqPdnType(enConnType, IMSA_IP_TYPE_IPV4); return ; } } VOS_VOID IMSA_CONN_ProcActRejCurReqIpv4 ( IMSA_CONN_TYPE_ENUM_UINT32 enConnType, const TAF_PS_CALL_PDP_ACTIVATE_REJ_STRU *pstPdpActivateRej ) { VOS_UINT32 ulResult = IMSA_FAIL; VOS_UINT8 ucCid = IMSA_NULL; /* Óû§·¢ÆðIPv4v6ÀàÐ͵ÄPDP¼¤»î, ¶øÇÒ±»ÍøÂç¾Ü¾ø, Ô­ÒòΪ28, ЭÒéÕ»ÐèÒª ·Ö±ð·¢ÆðIPv4/IPv6ÀàÐ͵ÄPDP¼¤»î, ЭÒéÕ»Ê×ÏÈ·¢ÆðIPv4, ÔÙ·¢ÆðIPv6, Èç¹ûIPV4ÀàÐ͵ÄPDP¼¤»îÔٴα»ÍøÂç¾Ü¾ø, ЭÒéÕ»»¹ÐèÒª³¢ÊÔIPV6ÀàÐ굀 PDP¼¤»îΪÁË·ÀÖ¹PDP¼¤»îǶÌ×, Èç¹ûIPv6ÀàÐ͵ÄPDP¼¤»îʧ°Ü, ½«²»ÔÙ³¢ÊÔ IPv4ÀàÐ͵ÄPDP¼¤»î */ if (IMSA_PDP_STATE_ACTIVE == IMSA_CONN_GetSipSignalPdpState(enConnType, IMSA_IP_TYPE_IPV6)) { IMSA_INFO_LOG("IMSA_CONN_ProcActRejCurReqIpv4:ipv6 already active"); /* Èç¹ûIPV6È«¾ÖµØÖ·ÒÑ»ñµÃ£¬»Ø¸´Á¬½Ó½¨Á¢³É¹¦£»·ñÔòÆô¶¯µÈ´ýIPV6²ÎÊý¶¨Ê±Æ÷ */ IMSA_CONN_WaitForIpv6InfoProc(enConnType); return ; } IMSA_CONN_GetConnSelectedCid(enConnType, ucCid); ulResult = IMSA_CONN_SipSignalPdpActOrig(enConnType, ucCid, IMSA_IP_TYPE_IPV6); if (IMSA_SUCC != ulResult) { IMSA_WARN_LOG("IMSA_CONN_ProcActRejCurReqIpv4:IMSA_CONN_SipSignalPdpActOrig failed!"); IMSA_CONN_SetupConnFail(enConnType, IMSA_CONN_RESULT_FAIL_CN_REJ,pstPdpActivateRej->enCause); return ; } } VOS_VOID IMSA_CONN_ProcActRejCurReqIpv6 ( IMSA_CONN_TYPE_ENUM_UINT32 enConnType, const TAF_PS_CALL_PDP_ACTIVATE_REJ_STRU *pstPdpActivateRej ) { if (IMSA_PDP_STATE_ACTIVE == IMSA_CONN_GetSipSignalPdpState(enConnType, IMSA_IP_TYPE_IPV4)) { IMSA_INFO_LOG("IMSA_CONN_ProcActRejCurReqIpv6:ipv4 already active"); IMSA_CONN_SetupConnSucc(enConnType); return ; } else { IMSA_WARN_LOG("IMSA_CONN_ProcActRejCurReqIpv6:ipv4 not active,ipv6 rej!"); IMSA_CONN_SetupConnFail(enConnType, IMSA_CONN_RESULT_FAIL_CN_REJ,pstPdpActivateRej->enCause); return ; } } VOS_UINT32 IMSA_CONN_ProcTafPsEvtPdpActivateCnf ( VOS_VOID *pEvtInfo ) { VOS_UINT32 ulResult = IMSA_FAIL; TAF_PS_CALL_PDP_ACTIVATE_CNF_STRU *pstPdpActivateCnf = VOS_NULL_PTR; IMSA_CONN_TYPE_ENUM_UINT32 enConnType = IMSA_CONN_TYPE_BUTT; IMSA_NORMAL_CONN_STRU *pstNormalConn = VOS_NULL_PTR; IMSA_EMC_CONN_STRU *pstEmcConn = VOS_NULL_PTR; IMSA_PDP_CNTXT_INFO_STRU *pstPdpInfo = VOS_NULL_PTR; /* ³õʼ»¯ */ pstPdpActivateCnf = (TAF_PS_CALL_PDP_ACTIVATE_CNF_STRU*)pEvtInfo; IMSA_INFO_LOG1("IMSA_CONN_ProcTafPsEvtPdpActivateCnf is entered! opid:", pstPdpActivateCnf->stCtrl.ucOpId); pstNormalConn = IMSA_CONN_GetNormalConnAddr(); pstEmcConn = IMSA_CONN_GetEmcConnAddr(); /* ¸ù¾ÝOPID²éÕÒÆä¹ØÁªµÄÁ¬½ÓʵÌåÀàÐÍ */ ulResult = IMSA_CONN_GetConnTypeByOpid( pstPdpActivateCnf->stCtrl.ucOpId, &enConnType); /* Èç¹û²éÕÒʧ°Ü£¬ÔòÖ±½ÓÍ˳ö */ if (IMSA_FAIL == ulResult) { IMSA_WARN_LOG("IMSA_CONN_ProcTafPsCallEvtPdpActivateCnf:Get Opid Failed!"); return IMSA_FAIL; } /* ²»ÊÇCONNING״̬£¬ÔòÖ±½ÓÍ˳ö */ if (IMSA_FALSE == IMSA_CONN_IsConnStatusEqual(enConnType, IMSA_CONN_STATUS_CONNING)) { IMSA_WARN_LOG("IMSA_CONN_ProcTafPsCallEvtPdpActivateCnf:CONNING state!"); return IMSA_FAIL; } /* Èç¹û²»ÊÇȱʡ³ÐÔØ£¬ÔòÖ±½Ó¶ªÆú£¬ÔÝʱ֧³Öȱʡ³ÐÔØÀàÐ͵ÄSIPÐÅÁî³ÐÔØ */ if (IMSA_OP_TRUE == pstPdpActivateCnf->bitOpLinkdRabId) { IMSA_WARN_LOG("IMSA_CONN_ProcTafPsCallEvtPdpActivateCnf:Illegal Bearer Type!"); return IMSA_FAIL; } /* ´æ´¢SIPÐÅÁî³ÐÔØÐÅÏ¢£¬°üÀ¨P-CSCF¡¢DNS¡¢IPµØÖ·ÐÅÏ¢µÈ */ if (IMSA_CONN_TYPE_NORMAL == enConnType) { if (IMSA_CONN_MAX_NORMAL_SIP_SIGNAL_PDP_NUM == pstNormalConn->ulSipSignalPdpNum) { IMSA_WARN_LOG("IMSA_CONN_ProcTafPsCallEvtPdpActivateCnf:signal pdp is already max num!"); return IMSA_FAIL; } pstPdpInfo = &pstNormalConn->astSipSignalPdpArray[pstNormalConn->ulSipSignalPdpNum]; IMSA_CONN_SaveSipSignalPdpInfo( pstPdpInfo, pstPdpActivateCnf); pstNormalConn->ulSipSignalPdpNum++; } else { pstPdpInfo = &pstEmcConn->stSipSignalPdp; IMSA_CONN_SaveSipSignalPdpInfo( pstPdpInfo, pstPdpActivateCnf); } /* ¸øREGÄ£¿éÅäÖõØÖ·¶Ô */ IMSA_CONN_ConfigPdpInfo2Reg(enConnType, pstPdpInfo); /* ¸øµ×ÈíÅäÖÃIPµØÖ·ºÍDNSµØÖ· */ /* IMSA_CONN_ConfigPdpInfo2Bsp(pstPdpInfo); */ /* Í£Ö¹IMS²¦ºÅ¶¨Ê±Æ÷ */ IMSA_CONN_StopTimer(enConnType, TI_IMSA_SIP_SIGAL_PDP_ORIG); /* ¸øCDSÅäÖÃÏÂÐйýÂ˳ÐÔØ */ IMSA_CONN_SndCdsSetImsBearerReq(); /* ¸ù¾ÝPDPÀàÐÍ·Ö±ð´¦Àí*/ switch ( pstPdpActivateCnf->stPdpAddr.enPdpType ) { case TAF_PDP_IPV4: IMSA_CONN_ProcIpv4ActCnf(enConnType, pstPdpActivateCnf); break; case TAF_PDP_IPV6: IMSA_CONN_ProcIpv6ActCnf(enConnType, pstPdpActivateCnf); break; case TAF_PDP_IPV4V6: IMSA_CONN_ProcIpv4v6ActCnf(enConnType); break; default: IMSA_WARN_LOG("IMSA_CONN_ProcTafPsCallEvtPdpActivateCnf:pdp type invaild!"); break; } return IMSA_SUCC; } VOS_UINT32 IMSA_CONN_ProcTafPsEvtPdpActivateRej ( VOS_VOID *pEvtInfo ) { VOS_UINT32 ulResult = IMSA_FAIL; TAF_PS_CALL_PDP_ACTIVATE_REJ_STRU *pstPdpActivateRej = VOS_NULL_PTR; IMSA_CONN_TYPE_ENUM_UINT32 enConnType = IMSA_CONN_TYPE_BUTT; IMSA_IP_TYPE_ENUM_UINT8 enFirstReqPdnType = IMSA_IP_TYPE_BUTT; IMSA_IP_TYPE_ENUM_UINT8 enCurReqPdnType = IMSA_IP_TYPE_BUTT; /* ³õʼ»¯ */ pstPdpActivateRej = (TAF_PS_CALL_PDP_ACTIVATE_REJ_STRU*)pEvtInfo; IMSA_INFO_LOG1("IMSA_CONN_ProcTafPsEvtPdpActivateRej is entered! opid:", pstPdpActivateRej->stCtrl.ucOpId); /* ¸ù¾ÝOPID²éÕÒÆä¹ØÁªµÄÁ¬½ÓʵÌåÀàÐÍ */ ulResult = IMSA_CONN_GetConnTypeByOpid( pstPdpActivateRej->stCtrl.ucOpId, &enConnType); /* Èç¹û²éÕÒʧ°Ü£¬ÔòÖ±½ÓÍ˳ö */ if (IMSA_FAIL == ulResult) { IMSA_WARN_LOG("IMSA_CONN_ProcTafPsEvtPdpActivateRej:Get Conn Type Failed!"); return IMSA_FAIL; } /* ²»ÊÇCONNING״̬£¬ÔòÖ±½ÓÍ˳ö */ if (IMSA_FALSE == IMSA_CONN_IsConnStatusEqual(enConnType, IMSA_CONN_STATUS_CONNING)) { IMSA_WARN_LOG("IMSA_CONN_ProcTafPsEvtPdpActivateRej:NOT CONNING state!"); return IMSA_FAIL; } /* Í£Ö¹IMS²¦ºÅ¶¨Ê±Æ÷ */ IMSA_CONN_StopTimer(enConnType, TI_IMSA_SIP_SIGAL_PDP_ORIG); IMSA_CONN_GetConnFirstReqPdnType(enConnType, enFirstReqPdnType); IMSA_CONN_GetConnCurReqPdnType(enConnType, enCurReqPdnType); IMSA_INFO_LOG1("enFirstReqPdnType:", enFirstReqPdnType); /* Èç¹ûÊÇIPV4 ONLY¡¢IPV6 ONLYÖ±½ÓÉϱ¨²¦ºÅʧ°Ü. */ if (IMSA_IP_TYPE_IPV4V6 != enFirstReqPdnType) { if (IMSA_TRUE == IMSA_CONN_HasActiveSipSignalPdp(enConnType)) { IMSA_CONN_SndConnSetupInd( IMSA_CONN_RESULT_SUCCESS, enConnType, IMSA_CONN_SIP_PDP_TYPE_SIGNAL); return IMSA_SUCC; } IMSA_CONN_SetupConnFail(enConnType, IMSA_CONN_RESULT_FAIL_CN_REJ, pstPdpActivateRej->enCause); return IMSA_SUCC; } /* IPV4V6ÔòÐèÒªÊÓ¾ßÌåʵÏÖ·Ö±ð·¢ÆðIPv4£¬IPv6ÀàÐ͵ÄPDP¼¤»î */ if (IMSA_IP_TYPE_IPV4V6 == enCurReqPdnType) { IMSA_CONN_ProcActRejCurReqIpv4v6(enConnType, pstPdpActivateRej); } else if (IMSA_IP_TYPE_IPV4 == enCurReqPdnType) { IMSA_CONN_ProcActRejCurReqIpv4(enConnType, pstPdpActivateRej); } else { IMSA_CONN_ProcActRejCurReqIpv6(enConnType, pstPdpActivateRej); } return IMSA_SUCC; } VOS_UINT32 IMSA_CONN_ProcTafPsEvtPdpActivateInd ( VOS_VOID *pEvtInfo ) { TAF_PS_CALL_PDP_ACTIVATE_IND_STRU *pstPdpActivateInd = VOS_NULL_PTR; IMSA_CONN_TYPE_ENUM_UINT32 enConnType = IMSA_CONN_TYPE_BUTT; IMSA_NORMAL_CONN_STRU *pstNormalConn = VOS_NULL_PTR; IMSA_EMC_CONN_STRU *pstEmcConn = VOS_NULL_PTR; IMSA_CONN_SIP_PDP_TYPE_ENUM_UINT32 enSipPdpType = IMSA_CONN_SIP_PDP_TYPE_BUTT; IMSA_PDP_CNTXT_INFO_STRU *pstPdpContext = VOS_NULL_PTR; VOS_UINT32 ulCurSipMediaPdpNum = IMSA_NULL; IMSA_INFO_LOG("IMSA_CONN_ProcTafPsEvtPdpActivateInd is entered!"); /* ³õʼ»¯ */ pstPdpActivateInd = (TAF_PS_CALL_PDP_ACTIVATE_IND_STRU*)pEvtInfo; /* Èç¹û²»ÊÇרÓгÐÔØ£¬ÔòÖ±½ÓÍ˳ö */ if (IMSA_OP_TRUE != pstPdpActivateInd->bitOpLinkdRabId) { IMSA_WARN_LOG("IMSA_CONN_ProcTafPsEvtPdpActivateInd:not dedicated!"); return IMSA_FAIL; } /* »ñÈ¡³ÐÔØÉÏÏÂÎÄ */ if (IMSA_SUCC != IMSA_CONN_GetPdpContextByPdpId( IMSA_CONN_TYPE_NORMAL, pstPdpActivateInd->ucLinkdRabId, &enSipPdpType, &pstPdpContext)) { if (IMSA_SUCC != IMSA_CONN_GetPdpContextByPdpId( IMSA_CONN_TYPE_EMC, pstPdpActivateInd->ucLinkdRabId, &enSipPdpType, &pstPdpContext)) { IMSA_WARN_LOG("IMSA_CONN_ProcTafPsEvtPdpActivateInd:Get LinkRabId context failed!"); return IMSA_FAIL; } else { enConnType = IMSA_CONN_TYPE_EMC; pstEmcConn = IMSA_CONN_GetEmcConnAddr(); ulCurSipMediaPdpNum = pstEmcConn->ulSipMediaPdpNum; } } else { enConnType = IMSA_CONN_TYPE_NORMAL; pstNormalConn = IMSA_CONN_GetNormalConnAddr(); ulCurSipMediaPdpNum = pstNormalConn->ulSipMediaPdpNum; } if (IMSA_CONN_SIP_PDP_TYPE_SIGNAL != enSipPdpType) { IMSA_WARN_LOG("IMSA_CONN_ProcTafPsEvtPdpActivateInd:linked pdp is not signal pdp!"); return IMSA_FAIL; } /* ²»ÊÇCONN״̬£¬ÔòÖ±½ÓÍ˳ö */ if (IMSA_FALSE == IMSA_CONN_IsConnStatusEqual( enConnType, IMSA_CONN_STATUS_CONN)) { IMSA_WARN_LOG("IMSA_CONN_ProcTafPsEvtPdpActivateInd:Not CONN state!"); return IMSA_FAIL; } if (IMSA_CONN_MAX_NORMAL_SIP_MEDIA_PDP_NUM <= ulCurSipMediaPdpNum) { IMSA_WARN_LOG("IMSA_CONN_ProcTafPsEvtPdpActivateInd:media pdp num is already 2!"); return IMSA_FAIL; } /* ´æ´¢SIPýÌå³ÐÔØÐÅÏ¢ */ IMSA_CONN_SaveSipMediaPdpInfo(enConnType, pstPdpActivateInd); /* ֪ͨSERVICEÄ£¿éýÌå³ÐÔØ½¨Á¢³É¹¦ */ IMSA_CONN_SndConnSetupInd( IMSA_CONN_RESULT_SUCCESS, enConnType, IMSA_CONN_SIP_PDP_TYPE_MEDIA); /* Èç¹ûµ±Ç°¼¤»îµÄÊÇÊÓÆµ³ÐÔØ£¬²»ÐèÒª¸øCDSÅäÖóÐÔØÐÅÏ¢ */ if ((IMSA_OP_TRUE == pstPdpActivateInd->bitOpTft) && (IMSA_FALSE == IMSA_CONN_IsImsBearNeedSetToCds((IMSA_PDP_TFT_INFO_STRU *)&pstPdpActivateInd->stTft)) && (IMSA_FALSE == IMSA_CONN_CheckLocalPortRange((IMSA_PDP_TFT_INFO_STRU *)&pstPdpActivateInd->stTft))) { return IMSA_SUCC; } /* ¸øCDSÅäÖÃÏÂÐйýÂ˳ÐÔØ */ IMSA_CONN_SndCdsSetImsBearerReq(); return IMSA_SUCC; } VOS_UINT32 IMSA_CONN_ProcTafPsEvtPdpModifyInd ( VOS_VOID *pEvtInfo ) { TAF_PS_CALL_PDP_MODIFY_IND_STRU *pstPdpModifyInd = VOS_NULL_PTR; IMSA_CONN_TYPE_ENUM_UINT32 enConnType = IMSA_CONN_TYPE_BUTT; IMSA_CONN_SIP_PDP_TYPE_ENUM_UINT32 enSipPdpType = IMSA_CONN_SIP_PDP_TYPE_BUTT; IMSA_PDP_CNTXT_INFO_STRU *pstPdpContext = VOS_NULL_PTR; IMSA_INFO_LOG("IMSA_CONN_ProcTafPsEvtPdpModifyInd is entered!"); /* ³õʼ»¯ */ pstPdpModifyInd = (TAF_PS_CALL_PDP_MODIFY_IND_STRU*)pEvtInfo; /* »ñÈ¡³ÐÔØÉÏÏÂÎÄ */ if (IMSA_SUCC != IMSA_CONN_GetPdpContextByPdpId( IMSA_CONN_TYPE_NORMAL, pstPdpModifyInd->ucRabId, &enSipPdpType, &pstPdpContext)) { if (IMSA_SUCC != IMSA_CONN_GetPdpContextByPdpId( IMSA_CONN_TYPE_EMC, pstPdpModifyInd->ucRabId, &enSipPdpType, &pstPdpContext)) { IMSA_WARN_LOG("IMSA_CONN_ProcTafPsEvtPdpModifyInd:Get pdp context failed!"); return IMSA_FAIL; } else { enConnType = IMSA_CONN_TYPE_EMC; } } else { enConnType = IMSA_CONN_TYPE_NORMAL; } IMSA_INFO_LOG1("IMSA_CONN_ProcTafPsEvtPdpModifyInd: Conn type :", enConnType); /* Èç¹ûÊÇIDLE״̬£¬ÔòÖ±½ÓÍ˳ö */ if (IMSA_TRUE == IMSA_CONN_IsConnStatusEqual(enConnType, IMSA_CONN_STATUS_IDLE)) { IMSA_WARN_LOG("IMSA_CONN_ProcTafPsEvtPdpModifyInd:IDLE state!"); return IMSA_FAIL; } /* ÐÞ¸ÄSIP³ÐÔØÐÅÏ¢ */ IMSA_CONN_ModifySipPdpInfo(enSipPdpType, pstPdpContext, pstPdpModifyInd); /* Èç¹ûÊÇýÌå³ÐÔØ£¬Ôò֪ͨSERVICEýÌå³ÐÔØÐÞ¸Ä */ if (IMSA_CONN_SIP_PDP_TYPE_MEDIA == enSipPdpType) { IMSA_CONN_SndConnMediaPdpModifyInd(enConnType); } /* Èç¹ûµ±Ç°¼¤»îµÄÊÇÊÓÆµ³ÐÔØ£¬²»ÐèÒª¸øCDSÅäÖóÐÔØÐÅÏ¢ */ if ((IMSA_OP_TRUE == pstPdpModifyInd->bitOpTft) && (IMSA_FALSE == IMSA_CONN_IsImsBearNeedSetToCds((IMSA_PDP_TFT_INFO_STRU *)&pstPdpModifyInd->stTft)) && (IMSA_FALSE == IMSA_CONN_CheckLocalPortRange((IMSA_PDP_TFT_INFO_STRU *)&pstPdpModifyInd->stTft))) { return IMSA_SUCC; } /* ¸øCDSÅäÖÃÏÂÐйýÂ˳ÐÔØ */ IMSA_CONN_SndCdsSetImsBearerReq(); return IMSA_SUCC; } VOS_UINT32 IMSA_CONN_ProcTafPsEvtPdpDeactivateCnf ( VOS_VOID *pEvtInfo ) { TAF_PS_CALL_PDP_DEACTIVATE_CNF_STRU *pstPdpDeactivateCnf = VOS_NULL_PTR; VOS_UINT32 ulResult = IMSA_FAIL; IMSA_CONN_TYPE_ENUM_UINT32 enConnType = IMSA_CONN_TYPE_BUTT; IMSA_CONN_SIP_PDP_TYPE_ENUM_UINT32 enSipPdpType = IMSA_CONN_SIP_PDP_TYPE_BUTT; IMSA_PDP_CNTXT_INFO_STRU *pstPdpContext = VOS_NULL_PTR; VOS_UINT32 ulRegParaInvalidFlag= IMSA_NULL; pstPdpDeactivateCnf = (TAF_PS_CALL_PDP_DEACTIVATE_CNF_STRU*)pEvtInfo; IMSA_INFO_LOG1("IMSA_CONN_ProcTafPsEvtPdpDeactivateCnf is entered! opid:", pstPdpDeactivateCnf->stCtrl.ucOpId); /* ¸ù¾ÝOPID²éÕÒÆä¹ØÁªµÄÁ¬½ÓʵÌåÀàÐÍ */ ulResult = IMSA_CONN_GetConnTypeByOpid( pstPdpDeactivateCnf->stCtrl.ucOpId, &enConnType); /* Èç¹û²éÕÒʧ°Ü£¬ÔòÖ±½ÓÍ˳ö */ if (IMSA_FAIL == ulResult) { IMSA_WARN_LOG("IMSA_CONN_ProcTafPsEvtPdpDeactivateCnf:Get Opid Failed!"); return IMSA_FAIL; } /* ²»ÊÇRELEASING״̬£¬ÔòÖ±½ÓÍ˳ö */ if (IMSA_FALSE == IMSA_CONN_IsConnStatusEqual(enConnType, IMSA_CONN_STATUS_RELEASING)) { IMSA_WARN_LOG("IMSA_CONN_ProcTafPsEvtPdpDeactivateCnf:Not releasing state!"); return IMSA_FAIL; } /* CID²»´æÔÚ£¬ÔòÖ±½ÓÍ˳ö */ if (IMSA_SUCC != IMSA_CONN_GetPdpContextByCid( enConnType, pstPdpDeactivateCnf->ucCid, &enSipPdpType, &pstPdpContext)) { IMSA_WARN_LOG("IMSA_CONN_ProcTafPsEvtPdpDeactivateCnf:cid not exist!"); return IMSA_SUCC; } /* Èç¹û²»ÊÇÐÅÁî³ÐÔØ£¬ÔòÖ±½ÓÍ˳ö */ if (IMSA_CONN_SIP_PDP_TYPE_SIGNAL != enSipPdpType) { IMSA_WARN_LOG("IMSA_CONN_ProcTafPsEvtPdpDeactivateCnf:Not signal pdp!"); return IMSA_FAIL; } /* Í£Ö¹IMS²¦ºÅ¶¨Ê±Æ÷ */ IMSA_CONN_StopTimer(enConnType, TI_IMSA_SIP_SIGAL_PDP_END); /* ɾ³ýÐÅÁî³ÐÔØÐÅÏ¢ */ IMSA_CONN_DeletePdpInfo(enConnType, pstPdpDeactivateCnf->ucCid, &ulRegParaInvalidFlag); if (IMSA_TRUE == IMSA_CONN_HasActiveSipSignalPdp(enConnType)) { /* ÇëÇóAPSÊÍ·ÅÁ¬½Ó */ IMSA_CONN_RequestApsRelConn(enConnType); } else { IMSA_CONN_ClearConnResourceExeptMedia(enConnType); /* ֪ͨSERVICEÄ£¿éÁ¬½ÓÊÍ·Å */ IMSA_CONN_SndConnRelInd(enConnType, IMSA_CONN_SIP_PDP_TYPE_SIGNAL); } return IMSA_SUCC; } VOS_UINT32 IMSA_CONN_ProcTafPsEvtPdpDeactivateInd ( VOS_VOID *pEvtInfo ) { TAF_PS_CALL_PDP_DEACTIVATE_IND_STRU *pstPdpDeactivateInd = VOS_NULL_PTR; IMSA_CONN_TYPE_ENUM_UINT32 enConnType = IMSA_CONN_TYPE_BUTT; IMSA_CONN_SIP_PDP_TYPE_ENUM_UINT32 enSipPdpType = IMSA_CONN_SIP_PDP_TYPE_BUTT; IMSA_PDP_CNTXT_INFO_STRU *pstPdpContext = VOS_NULL_PTR; VOS_UINT32 ulRegParaValidFlag = IMSA_NULL; IMSA_INFO_LOG("IMSA_CONN_ProcTafPsEvtPdpDeactivateInd is entered!"); /* ³õʼ»¯ */ pstPdpDeactivateInd = (TAF_PS_CALL_PDP_DEACTIVATE_IND_STRU*)pEvtInfo; /* »ñÈ¡³ÐÔØÉÏÏÂÎÄ */ if (IMSA_SUCC != IMSA_CONN_GetPdpContextByCid( IMSA_CONN_TYPE_NORMAL, pstPdpDeactivateInd->ucCid, &enSipPdpType, &pstPdpContext)) { if (IMSA_SUCC != IMSA_CONN_GetPdpContextByCid( IMSA_CONN_TYPE_EMC, pstPdpDeactivateInd->ucCid, &enSipPdpType, &pstPdpContext)) { IMSA_WARN_LOG("IMSA_CONN_ProcTafPsEvtPdpDeactivateInd:Get pdp context failed!"); return IMSA_FAIL; } else { enConnType = IMSA_CONN_TYPE_EMC; } } else { enConnType = IMSA_CONN_TYPE_NORMAL; } /* ɾ³ý³ÐÔØÐÅϢǰ£¬±¸·ÝÊͷųÐÔØµÄÀàÐͺÍCID */ if (IMSA_SRV_STATUS_CONN_REG == IMSA_SRV_GetEmcSrvStatus() || IMSA_SRV_STATUS_CONN_REG == IMSA_SRV_GetNormalSrvStatus()) { IMSA_RegSaveRegedPara((IMSA_REG_TYPE_ENUM_UINT8)enConnType, pstPdpDeactivateInd->ucCid, pstPdpDeactivateInd->enPdpType); } /* ɾ³ý³ÐÔØÐÅÏ¢ */ IMSA_CONN_DeletePdpInfo(enConnType, pstPdpDeactivateInd->ucCid, &ulRegParaValidFlag); if (IMSA_CONN_TYPE_EMC == enConnType) { if (IMSA_CONN_SIP_PDP_TYPE_MEDIA == enSipPdpType) { IMSA_INFO_LOG("IMSA_CONN_ProcTafPsEvtPdpDeactivateInd:EMC media"); IMSA_CONN_SndConnRelInd(enConnType, IMSA_CONN_SIP_PDP_TYPE_MEDIA); return IMSA_SUCC; } IMSA_INFO_LOG("IMSA_CONN_ProcTafPsEvtPdpDeactivateInd:EMC sig"); /* Í£Ö¹IMS²¦ºÅ¶¨Ê±Æ÷ */ IMSA_CONN_StopTimer(enConnType, TI_IMSA_SIP_SIGAL_PDP_END); /* Çå³ýÁ¬½Ó×ÊÔ´ */ /* IMSA_CONN_ClearConnResource(enConnType); */ /*IMSA_CONN_SetConnStatus(IMSA_CONN_TYPE_EMC, IMSA_CONN_STATUS_IDLE);*/ IMSA_CONN_ClearConnResourceExeptMedia(enConnType); /* ֪ͨSERVICEÄ£¿éÁ¬½ÓÊÍ·Å */ IMSA_CONN_SndConnRelInd(enConnType, IMSA_CONN_SIP_PDP_TYPE_SIGNAL); return IMSA_SUCC; } if (IMSA_CONN_SIP_PDP_TYPE_MEDIA == enSipPdpType) { IMSA_INFO_LOG("IMSA_CONN_ProcTafPsEvtPdpDeactivateInd:MEDIA"); IMSA_CONN_SndConnRelInd(enConnType, IMSA_CONN_SIP_PDP_TYPE_MEDIA); return IMSA_SUCC; } if (IMSA_CONN_STATUS_CONNING == IMSA_CONN_GetNormalConnStatus()) { IMSA_INFO_LOG("IMSA_CONN_ProcTafPsEvtPdpDeactivateInd:normal,conning"); /* Í£Ö¹µÈ´ýIPV6²ÎÊý¶¨Ê±Æ÷ */ IMSA_CONN_StopTimer(enConnType, TI_IMSA_WAIT_IPV6_INFO); IMSA_CONN_ClearConnResourceExeptMedia(enConnType); IMSA_CONN_SndConnRelInd(enConnType, IMSA_CONN_SIP_PDP_TYPE_SIGNAL); return IMSA_SUCC; } if (IMSA_CONN_STATUS_RELEASING == IMSA_CONN_GetNormalConnStatus()) { IMSA_INFO_LOG("IMSA_CONN_ProcTafPsEvtPdpDeactivateInd:normal,releasing"); if (IMSA_TRUE != IMSA_CONN_HasActiveSipSignalPdp(enConnType)) { /* Í£Ö¹IMS²¦ºÅ¶¨Ê±Æ÷ */ IMSA_CONN_StopTimer(enConnType, TI_IMSA_SIP_SIGAL_PDP_END); /* Çå³ýÁ¬½Ó×ÊÔ´ */ IMSA_CONN_ClearConnResourceExeptMedia(enConnType); /* ֪ͨSERVICEÄ£¿éÁ¬½ÓÊÍ·Å */ IMSA_CONN_SndConnRelInd(enConnType, IMSA_CONN_SIP_PDP_TYPE_SIGNAL); } return IMSA_SUCC; } if (IMSA_TRUE != IMSA_CONN_HasActiveSipSignalPdp(enConnType)) { IMSA_INFO_LOG("IMSA_CONN_ProcTafPsEvtPdpDeactivateInd:normal,conn,no active pdp!"); /* Çå³ýÁ¬½Ó×ÊÔ´ */ /* IMSA_CONN_ClearConnResource(enConnType); */ /*IMSA_CONN_SetConnStatus(IMSA_CONN_TYPE_NORMAL, IMSA_CONN_STATUS_IDLE);*/ IMSA_CONN_ClearConnResourceExeptMedia(enConnType); /* ֪ͨSERVICEÄ£¿éÁ¬½ÓÊÍ·Å */ IMSA_CONN_SndConnRelInd(enConnType, IMSA_CONN_SIP_PDP_TYPE_SIGNAL); return IMSA_SUCC; } /* Èç¹û×¢²á²ÎÊýʧЧ£¬ÇÒ»¹ÓÐÆäËû¼¤»îµÄÐÅÁî³ÐÔØÊ±£¬Í¨ÖªSERVICEÄ£¿é×¢²á²ÎÊýʧЧ */ if (IMSA_CONN_REG_PARA_INVALID == ulRegParaValidFlag) { IMSA_INFO_LOG("IMSA_CONN_ProcTafPsEvtPdpDeactivateInd:normal,conn,active pdp,reg para invalid!"); IMSA_CONN_SndConnRegParaInvalid(); return IMSA_SUCC; } return IMSA_SUCC; } /* lihong00150010 ims begin 2013-01-08 ·ÀÖ¹Íø²àÖØ²¥Â·Óɹ«¸æ */ VOS_UINT32 IMSA_CONN_IsIpv6PrefixChanged ( const IMSA_PDP_CNTXT_INFO_STRU *pstPdpInfo, const TAF_PS_IPV6_INFO_IND_STRU *pstIpv6InfoInd ) { if (0 == IMSA_MEM_CMP( pstPdpInfo->stPdpAddr.aucIpV6Addr, pstIpv6InfoInd->stIpv6RaInfo.astPrefixList[0].aucPrefix, IMSA_IPV6_PREFIX_LEN)) { return IMSA_FALSE; } return IMSA_TRUE; } /* lihong00150010 ims end 2013-01-08 ·ÀÖ¹Íø²àÖØ²¥Â·Óɹ«¸æ */ VOS_UINT32 IMSA_CONN_ProcTafPsEvtPdpIpv6InfoInd ( VOS_VOID *pEvtInfo ) { TAF_PS_IPV6_INFO_IND_STRU *pstPsIpv6InfoInd = VOS_NULL_PTR; IMSA_CONN_TYPE_ENUM_UINT32 enConnType = IMSA_CONN_TYPE_BUTT; IMSA_CONN_SIP_PDP_TYPE_ENUM_UINT32 enSipPdpType = IMSA_CONN_SIP_PDP_TYPE_BUTT; IMSA_PDP_CNTXT_INFO_STRU *pstPdpContext = VOS_NULL_PTR; VOS_CHAR acUeAddr[IMSA_IPV6_ADDR_STRING_LEN + 1] = {0}; IMSA_INFO_LOG("IMSA_CONN_ProcTafPsEvtPdpIpv6InfoInd is entered!"); /* ³õʼ»¯ */ pstPsIpv6InfoInd = (TAF_PS_IPV6_INFO_IND_STRU*)pEvtInfo; /* Èç¹ûûÓÐЯ´øÇ°×ºÐÅÏ¢£¬ÔòÖ±½ÓÍ˳ö */ if (0 == pstPsIpv6InfoInd->stIpv6RaInfo.ulPrefixNum) { IMSA_WARN_LOG("IMSA_CONN_ProcTafPsEvtPdpIpv6InfoInd:No prefix!"); return IMSA_FAIL; } /* »ñÈ¡³ÐÔØÉÏÏÂÎÄ */ if (IMSA_SUCC != IMSA_CONN_GetPdpContextByPdpId( IMSA_CONN_TYPE_NORMAL, pstPsIpv6InfoInd->ucRabId, &enSipPdpType, &pstPdpContext)) { if (IMSA_SUCC != IMSA_CONN_GetPdpContextByPdpId( IMSA_CONN_TYPE_EMC, pstPsIpv6InfoInd->ucRabId, &enSipPdpType, &pstPdpContext)) { IMSA_WARN_LOG("IMSA_CONN_ProcTafPsEvtPdpIpv6InfoInd:Get pdp context failed!"); return IMSA_FAIL; } else { enConnType = IMSA_CONN_TYPE_EMC; } } else { enConnType = IMSA_CONN_TYPE_NORMAL; } if (IMSA_CONN_SIP_PDP_TYPE_MEDIA == enSipPdpType) { IMSA_WARN_LOG("IMSA_CONN_ProcTafPsEvtPdpIpv6InfoInd:not signal pdp type!"); return IMSA_FAIL; } /* Èç¹ûÊÇCONN״̬£¬Ôò¸üÐÂPDPÉÏÏÂÎÄ */ if (IMSA_TRUE == IMSA_CONN_IsConnStatusEqual(enConnType, IMSA_CONN_STATUS_CONN)) { IMSA_INFO_LOG("IMSA_CONN_ProcTafPsEvtPdpModifyInd:CONN state!"); /* ´æ´¢IPV6ÐÅÏ¢ */ /* lihong00150010 ims begin 2013-01-08 ·ÀÖ¹Íø²àÖØ²¥Â·Óɹ«¸æ */ if (IMSA_TRUE == IMSA_CONN_IsIpv6PrefixChanged(pstPdpContext, pstPsIpv6InfoInd)) { IMSA_CONN_SaveIpv6Info(pstPdpContext, pstPsIpv6InfoInd); /* ¸øREGÄ£¿éÅäÖÃIPV6µØÖ· */ IMSA_CONN_ConvertIpAddress2String( IMSA_IP_TYPE_IPV6, pstPdpContext->stPdpAddr.aucIpV6Addr, acUeAddr); (VOS_VOID)IMSA_RegAddrPairMgrAddUeAddr( (IMSA_REG_TYPE_ENUM_UINT8)enConnType, IMSA_IP_TYPE_IPV6, acUeAddr); /* ¸øµ×ÈíÅäÖÃIPv6µØÖ·ºÍIPv6 DNSµØÖ· */ /* IMSA_CONN_ConfigPdpIPv6Info2Bsp(pstPdpContext); */ } /* lihong00150010 ims end 2013-01-08 ·ÀÖ¹Íø²àÖØ²¥Â·Óɹ«¸æ */ return IMSA_SUCC; } /* Èç¹ûÊÇCONNING״̬£¬Ôò¸üÐÂPDPÉÏÏÂÎÄ£¬Í¨ÖªSERVICEÁ¬½Ó½¨Á¢³É¹¦ */ if (IMSA_TRUE == IMSA_CONN_IsConnStatusEqual(enConnType, IMSA_CONN_STATUS_CONNING)) { IMSA_INFO_LOG("IMSA_CONN_ProcTafPsEvtPdpModifyInd:CONNING state!"); /* ´æ´¢IPV6ÐÅÏ¢ */ /* lihong00150010 ims begin 2013-01-08 ·ÀÖ¹Íø²àÖØ²¥Â·Óɹ«¸æ */ if (IMSA_TRUE == IMSA_CONN_IsIpv6PrefixChanged(pstPdpContext, pstPsIpv6InfoInd)) { IMSA_CONN_SaveIpv6Info(pstPdpContext, pstPsIpv6InfoInd); /* ¸øREGÄ£¿éÅäÖÃIPV6µØÖ· */ IMSA_CONN_ConvertIpAddress2String( IMSA_IP_TYPE_IPV6, pstPdpContext->stPdpAddr.aucIpV6Addr, acUeAddr); (VOS_VOID)IMSA_RegAddrPairMgrAddUeAddr( (IMSA_REG_TYPE_ENUM_UINT8)enConnType, IMSA_IP_TYPE_IPV6, acUeAddr); /* ¸øµ×ÈíÅäÖÃIPv6µØÖ·ºÍIPv6 DNSµØÖ· */ /* IMSA_CONN_ConfigPdpIPv6Info2Bsp(pstPdpContext); */ } /* lihong00150010 ims end 2013-01-08 ·ÀÖ¹Íø²àÖØ²¥Â·Óɹ«¸æ */ /* Èç¹ûµ±Ç°»¹ÔÚÇëÇóIPV4µÄSIPÐÅÁî³ÐÔØ½¨Á¢£¬ÔòµÈ´ýIPV4ÐÅÁî³ÐÔØ½¨Á¢Íê³Éºó ÔÙ֪ͨSERVICEÄ£¿éÁ¬½Ó½¨Á¢³É¹¦ */ if (IMSA_TRUE == IMSA_CONN_IsEqualToSelectedCid(enConnType, pstPsIpv6InfoInd->ucCid)) { /* ֪ͨSERIVCEÁ¬½Ó½¨Á¢³É¹¦ */ IMSA_CONN_SetupConnSucc(enConnType); } /* Í£Ö¹µÈ´ýIPV6²ÎÊý¶¨Ê±Æ÷ */ IMSA_CONN_StopTimer(enConnType, TI_IMSA_WAIT_IPV6_INFO); return IMSA_SUCC; } return IMSA_FAIL; } VOS_UINT32 IMSA_CONN_ProcTafPsEvtCallOrigCnf ( VOS_VOID *pEvtInfo ) { TAF_PS_CALL_ORIG_CNF_STRU *pstCallOrigCnf = VOS_NULL_PTR; VOS_UINT32 ulResult = IMSA_FAIL; IMSA_CONN_TYPE_ENUM_UINT32 enConnType = IMSA_CONN_TYPE_BUTT; pstCallOrigCnf = (TAF_PS_CALL_ORIG_CNF_STRU*)pEvtInfo; IMSA_INFO_LOG1("IMSA_CONN_ProcTafPsEvtCallOrigCnf is entered! opid:", pstCallOrigCnf->stCtrl.ucOpId); /* ¸ù¾ÝOPID²éÕÒÆä¹ØÁªµÄÁ¬½ÓʵÌåÀàÐÍ */ ulResult = IMSA_CONN_GetConnTypeByOpid( pstCallOrigCnf->stCtrl.ucOpId, &enConnType); /* Èç¹û²éÕÒʧ°Ü£¬ÔòÖ±½ÓÍ˳ö */ if (IMSA_FAIL == ulResult) { IMSA_WARN_LOG("IMSA_CONN_ProcTafPsEvtCallOrigCnf:Get Opid Failed!"); return IMSA_FAIL; } /* ²»ÊÇCONNING״̬£¬ÔòÖ±½ÓÍ˳ö */ if (IMSA_FALSE == IMSA_CONN_IsConnStatusEqual(enConnType, IMSA_CONN_STATUS_CONNING)) { IMSA_WARN_LOG("IMSA_CONN_ProcTafPsEvtCallOrigCnf:Not CONNING state!"); return IMSA_FAIL; } /* APS²ÎÊý¼ì²éÕýÈ·£¬Ö±½ÓÍ˳ö */ if (TAF_PS_CAUSE_SUCCESS == pstCallOrigCnf->enCause) { return IMSA_SUCC; } /* Í£Ö¹IMS²¦ºÅ¶¨Ê±Æ÷ */ IMSA_CONN_StopTimer(enConnType, TI_IMSA_SIP_SIGAL_PDP_ORIG); if (IMSA_TRUE == IMSA_CONN_HasActiveSipSignalPdp(enConnType)) { /* Èç¹ûIPV6È«¾ÖµØÖ·ÒÑ»ñµÃ£¬»Ø¸´Á¬½Ó½¨Á¢³É¹¦£»·ñÔòÆô¶¯µÈ´ýIPV6²ÎÊý¶¨Ê±Æ÷ */ IMSA_CONN_WaitForIpv6InfoProc(enConnType); return IMSA_SUCC; } /* ¸øSERVICE»Ø¸´IMSA_CONN_SETUP_INDÏûÏ¢£¬Èç¹ûÊÇTAF_PS_CAUSE_PDP_ACTIVATE_LIMIT£¬ Ôò½á¹ûÖµÌîΪFAIL_PDP_ACTIVATE_LIMIT£¬·ñÔòÌîΪFAIL_PARA_ERR */ if (TAF_PS_CAUSE_PDP_ACTIVATE_LIMIT == pstCallOrigCnf->enCause) { IMSA_CONN_SetupConnFail(enConnType, IMSA_CONN_RESULT_FAIL_PDP_ACTIVATE_LIMIT, (TAF_PS_CAUSE_ENUM_UINT32)TAF_PS_CAUSE_BUTT); } else if (TAF_PS_CAUSE_OPERATION_CONFLICT == pstCallOrigCnf->enCause) { IMSA_CONN_SetupConnFail(enConnType, IMSA_CONN_RESULT_FAIL_SAME_APN_OPERATING, (TAF_PS_CAUSE_ENUM_UINT32)TAF_PS_CAUSE_BUTT); } else { IMSA_CONN_SetupConnFail(enConnType, IMSA_CONN_RESULT_FAIL_PARA_ERR, (TAF_PS_CAUSE_ENUM_UINT32)TAF_PS_CAUSE_BUTT); } return IMSA_SUCC; } VOS_UINT32 IMSA_CONN_ProcTafPsEvtCallEndCnf ( VOS_VOID *pEvtInfo ) { TAF_PS_CALL_END_CNF_STRU *pstCallEndCnf = VOS_NULL_PTR; VOS_UINT32 ulResult = IMSA_FAIL; IMSA_CONN_TYPE_ENUM_UINT32 enConnType = IMSA_CONN_TYPE_BUTT; IMSA_CONN_SIP_PDP_TYPE_ENUM_UINT32 enSipPdpType = IMSA_CONN_SIP_PDP_TYPE_BUTT; IMSA_PDP_CNTXT_INFO_STRU *pstPdpContext = VOS_NULL_PTR; VOS_UINT32 ulRegParaInvalidFlag = IMSA_NULL; pstCallEndCnf = (TAF_PS_CALL_END_CNF_STRU*)pEvtInfo; IMSA_INFO_LOG1("IMSA_CONN_ProcTafPsEvtCallEndCnf is entered! opid:",pstCallEndCnf->stCtrl.ucOpId); /* ¸ù¾ÝOPID²éÕÒÆä¹ØÁªµÄÁ¬½ÓʵÌåÀàÐÍ */ ulResult = IMSA_CONN_GetConnTypeByOpid( pstCallEndCnf->stCtrl.ucOpId, &enConnType); /* Èç¹û²éÕÒʧ°Ü£¬ÔòÖ±½ÓÍ˳ö */ if (IMSA_FAIL == ulResult) { IMSA_WARN_LOG("IMSA_CONN_ProcTafPsEvtCallEndCnf:Get Opid Failed!"); return IMSA_FAIL; } /* ²»ÊÇRELEASING״̬£¬ÔòÖ±½ÓÍ˳ö */ if (IMSA_FALSE == IMSA_CONN_IsConnStatusEqual(enConnType, IMSA_CONN_STATUS_RELEASING)) { IMSA_WARN_LOG("IMSA_CONN_ProcTafPsEvtCallEndCnf:Not releasing state!"); return IMSA_FAIL; } /* APS²ÎÊý¼ì²éÕýÈ·£¬Ö±½ÓÍ˳ö */ if (TAF_PS_CAUSE_SUCCESS == pstCallEndCnf->enCause) { return IMSA_SUCC; } /* CID²»´æÔÚ£¬ÔòÖ±½ÓÍ˳ö */ if (IMSA_SUCC != IMSA_CONN_GetPdpContextByCid( enConnType, pstCallEndCnf->ucCid, &enSipPdpType, &pstPdpContext)) { IMSA_WARN_LOG("IMSA_CONN_ProcTafPsEvtCallEndCnf:cid not exist!"); return IMSA_SUCC; } /* Í£Ö¹IMS²¦ºÅ¶¨Ê±Æ÷ */ IMSA_CONN_StopTimer(enConnType, TI_IMSA_SIP_SIGAL_PDP_END); /* ɾ³ýÐÅÁî³ÐÔØÐÅÏ¢ */ IMSA_CONN_DeletePdpInfo(enConnType, pstCallEndCnf->ucCid, &ulRegParaInvalidFlag); if (IMSA_TRUE == IMSA_CONN_HasActiveSipSignalPdp(enConnType)) { /* ÇëÇóAPSÊÍ·ÅÁ¬½Ó */ IMSA_CONN_RequestApsRelConn(enConnType); } return IMSA_SUCC; } /***************************************************************************** Function Name : IMSA_CONN_ProcTafPsEvtSrvccCancelInd Description : IMSA CONNÄ£¿é´¦ÀíSRVCC CANCELʼþ Input : pEvtInfo--------------ʼþÐÅÏ¢Ö¸Õë Output : VOS_VOID Return Value : VOS_VOID History : 1.sunbing 49683 2013-10-14 Draft Enact *****************************************************************************/ VOS_UINT32 IMSA_CONN_ProcTafPsEvtSrvccCancelInd ( VOS_VOID *pEvtInfo ) { IMSA_INFO_LOG("IMSA_CONN_ProcTafPsEvtSrvccCancelInd is entered!"); (VOS_VOID)pEvtInfo; /*Çå³ýµÈ´ýÒìϵͳָʾ±êʾ*/ IMSA_CallSetSrvccFlag(IMSA_FALSE); /* Çå³ý²»ÄÜÉϱ¨ALL RELEASEDʼþ±êʶ */ IMSA_CallSetNotReportAllReleasedFlag(IMSA_FALSE); /*ÊÕµ½¸ÃÏûϢʱ£¬Öն˵ÄÒìϵͳÁ÷³Ì»¹Ã»ÓÐÆô¶¯£¬³öÁË֪ͨIMSºÍATÉϱ¨£¬²»ÐèÒª×öÌØÊâ´¦Àí*/ /*ÊÕµ½ESM/SM Notification indʼþ£¬ÐèҪ֪ͨIMSЭÒéÕ»·¢Æðre-inviteÁ÷³Ì*/ (VOS_VOID)IMSA_CallSendImsMsgSrvcc(IMSA_IMS_INPUT_CALL_REASON_SRVCC_CANCELED); /*Éϱ¨HOʧ°Ü*/ IMSA_SndMsgAtCirephInd(AT_IMSA_SRVCC_HANDOVER_FAILURE); return IMSA_SUCC; } VOS_VOID IMSA_CONN_ProcTimerMsgSipSignalPdpOrigExp ( const VOS_VOID *pMsg ) { IMSA_CONN_TYPE_ENUM_UINT32 enConnType = IMSA_CONN_TYPE_BUTT; IMSA_INFO_LOG("IMSA_CONN_ProcTimerMsgSipSignalPdpOrigExp is entered!"); enConnType = PS_GET_REL_TIMER_PARA(pMsg); if (enConnType >= IMSA_CONN_TYPE_BUTT) { IMSA_ERR_LOG("IMSA_CONN_ProcTimerMsgSipSignalPdpOrigExp:Illegal Para!"); return ; } /* ²»ÊÇCONNING״̬£¬ÔòÖ±½ÓÍ˳ö */ if (IMSA_FALSE == IMSA_CONN_IsConnStatusEqual(enConnType, IMSA_CONN_STATUS_CONNING)) { IMSA_WARN_LOG("IMSA_CONN_ProcTimerMsgSipSignalPdpEndExp:Not CONNING state!"); return ; } if (IMSA_CONN_TYPE_EMC == enConnType) { IMSA_INFO_LOG("IMSA_CONN_ProcTimerMsgSipSignalPdpOrigExp:EMC,conning!"); IMSA_CONN_SetupConnFail(enConnType, IMSA_CONN_RESULT_FAIL_TIMER_EXP, (TAF_PS_CAUSE_ENUM_UINT32)TAF_PS_CAUSE_BUTT); return ; } IMSA_INFO_LOG("IMSA_CONN_ProcTimerMsgSipSignalPdpOrigExp:normal,conning!"); if (IMSA_TRUE == IMSA_CONN_HasActiveSipSignalPdp(enConnType)) { /* Èç¹ûIPV6È«¾ÖµØÖ·ÒÑ»ñµÃ£¬»Ø¸´Á¬½Ó½¨Á¢³É¹¦£»·ñÔòÆô¶¯µÈ´ýIPV6²ÎÊý¶¨Ê±Æ÷ */ IMSA_CONN_WaitForIpv6InfoProc(enConnType); } else { IMSA_CONN_SetupConnFail(enConnType, IMSA_CONN_RESULT_FAIL_TIMER_EXP, (TAF_PS_CAUSE_ENUM_UINT32)TAF_PS_CAUSE_BUTT); } return ; } VOS_VOID IMSA_CONN_ProcTimerMsgSipSignalPdpEndExp ( const VOS_VOID *pMsg ) { IMSA_CONN_TYPE_ENUM_UINT32 enConnType = IMSA_CONN_TYPE_BUTT; VOS_UINT32 ulRegParaInvalidFlag = IMSA_NULL; IMSA_NORMAL_CONN_STRU *pstNormalConn = VOS_NULL_PTR; IMSA_EMC_CONN_STRU *pstEmcConn = VOS_NULL_PTR; IMSA_INFO_LOG("IMSA_CONN_ProcTimerMsgSipSignalPdpEndExp is entered!"); enConnType = PS_GET_REL_TIMER_PARA(pMsg); if (enConnType >= IMSA_CONN_TYPE_BUTT) { IMSA_ERR_LOG("IMSA_CONN_ProcTimerMsgSipSignalPdpEndExp:Illegal Para!"); return ; } /* ²»ÊÇRELEASING״̬£¬ÔòÖ±½ÓÍ˳ö */ if (IMSA_FALSE == IMSA_CONN_IsConnStatusEqual(enConnType, IMSA_CONN_STATUS_RELEASING)) { IMSA_WARN_LOG("IMSA_CONN_ProcTimerMsgSipSignalPdpEndExp:Not releasing state!"); return ; } if (IMSA_CONN_TYPE_NORMAL == enConnType) { pstNormalConn = IMSA_CONN_GetNormalConnAddr(); /* ɾ³ýÐÅÁî³ÐÔØÐÅÏ¢ */ IMSA_CONN_DeletePdpInfo( enConnType, pstNormalConn->astSipSignalPdpArray[0].ucCid, &ulRegParaInvalidFlag); } else { pstEmcConn = IMSA_CONN_GetEmcConnAddr(); /* ɾ³ýÐÅÁî³ÐÔØÐÅÏ¢ */ IMSA_CONN_DeletePdpInfo( enConnType, pstEmcConn->stSipSignalPdp.ucCid, &ulRegParaInvalidFlag); } if (IMSA_TRUE == IMSA_CONN_HasActiveSipSignalPdp(enConnType)) { /* ÇëÇóAPSÊÍ·ÅÁ¬½Ó */ IMSA_CONN_RequestApsRelConn(enConnType); } else { IMSA_CONN_ClearConnResourceExeptMedia(enConnType); /* ֪ͨSERVICEÄ£¿éÁ¬½ÓÊÍ·Å */ IMSA_CONN_SndConnRelInd(enConnType, IMSA_CONN_SIP_PDP_TYPE_SIGNAL); } return ; } VOS_VOID IMSA_CONN_ProcTimerMsgWaitIpv6InfoExp ( const VOS_VOID *pMsg ) { IMSA_CONN_TYPE_ENUM_UINT32 enConnType = IMSA_CONN_TYPE_BUTT; IMSA_INFO_LOG("IMSA_CONN_ProcTimerMsgWaitIpv6InfoExp is entered!"); enConnType = PS_GET_REL_TIMER_PARA(pMsg); if (enConnType >= IMSA_CONN_TYPE_BUTT) { IMSA_ERR_LOG("IMSA_CONN_ProcTimerMsgWaitIpv6InfoExp:Illegal Para!"); return ; } /* ²»ÊÇCONNING״̬£¬ÔòÖ±½ÓÍ˳ö */ if (IMSA_FALSE == IMSA_CONN_IsConnStatusEqual(enConnType, IMSA_CONN_STATUS_CONNING)) { IMSA_WARN_LOG("IMSA_CONN_ProcTimerMsgSipSignalPdpEndExp:Not CONNING state!"); return ; } if ((IMSA_PDP_STATE_ACTIVE == IMSA_CONN_GetSipSignalPdpState(enConnType, IMSA_IP_TYPE_IPV4)) || (IMSA_PDP_STATE_ACTIVE == IMSA_CONN_GetSipSignalPdpState(enConnType, IMSA_IP_TYPE_IPV4V6))) { IMSA_WARN_LOG("IMSA_CONN_ProcTimerMsgSipSignalPdpEndExp:IPV4 OR IPV4V6 PDP!"); IMSA_CONN_SetupConnSucc(enConnType); } return ; } /*lint +e961*/ /*lint +e960*/ #endif #ifdef __cplusplus #if __cplusplus } #endif #endif /* end of ImsaProcApsMsg.c*/
wbrambley/Grace-kernel
drivers/vendor/hisi/modem/ps/nas/tl/lte/IMSA/Src/ImsaProcApsMsg.c
C
gpl-2.0
62,299
#!/bin/bash # #FILE # /usr/sbin/container-rsync.sh # $Id$ # #PURPOSE # Test alpha dev script for unxsVZ hot spare container sync # Keep a container on this host rsync'd with a source container on a remote host # #AUTHOR/LEGAL # (C) 2009- Gary Wallis for Unixservice. GPLv2 Licensed. # # if [ "$1" == "" ] || [ "$2" == "" ] || [ "$3" == "" ];then echo "usage $0 <local clone veid> <remote production veid> <remote-server hostname/ip>"; exit 0; fi ssh $3 "ls /vz/private/$2" > /dev/null 2>&1; if [ $? != 0 ]; then echo "no $3 /vz/private/$2"; exit 1; fi grep -l "\-clone" /etc/vz/conf/$1.conf > /dev/null 2>&1; if [ $? != 0 ]; then echo "local veid:$1 does not appear to be a clone"; exit 1; fi ls /vz/private/$1 > /dev/null 2>&1; if [ $? != 0 ]; then echo "no local /vz/private/$1"; exit 1; fi #/usr/bin/rsync -avxlH --dry-run\ /usr/bin/rsync -avxlH \ --delete \ --exclude "/proc" --exclude "/sys" --exclude "/dev" --exclude "/tmp" \ --exclude "/var/run" --exclude "/etc/sysconfig/network" --exclude "/etc/sysconfig/network-scripts/" \ --exclude "/var/lock" --exclude "etc/hosts" --exclude "etc/resolv.conf" \ --exclude "/var/lib/mlocate/mlocate.db" --exclude "/etc/rc.d/rc6.d/S00vzreboot" \ --exclude "/var/log/" --exclude "/var/lib/random-seed" --exclude "/var/spool/" \ --exclude "/etc/aliases.db" \ -e 'ssh -c blowfish -ax' \ $3:/vz/private/$2/* \ /vz/private/$1
unxs0/unxsVZ
tools/openvz/container-rsync.sh
Shell
gpl-2.0
1,414
/* map */ /* sidebar */ .site:before { background-color: rgba(0, 0, 0, 0.8); content: ""; display: none; height: 100%; position: absolute; top: 0; right: 0; width: 182px; z-index: 3 !important; }
drleewarden/2014-bootstrap
wp-content/themes/arcade-basic/src/sass/features/_features.css
CSS
gpl-2.0
214
from rest_framework import permissions class IsOwner(permissions.BasePermission): def has_object_permission(self, request, view, obj): # Only allow owners of an object to view or edit it return obj.owner == request.user
lesavoie/nagiosservice
controlserver/servicelevelinterface/permissions.py
Python
gpl-2.0
238
/* TEMU is Copyright (C) 2006-2010, BitBlaze Team. You can redistribute and modify it under the terms of the GNU LGPL, version 2.1 or later, but it is made available WITHOUT ANY WARRANTY. */ #ifndef _IHOOK_HELPER_H_ #define _IHOOK_HELPER_H_ #include <inttypes.h> #include <stdlib.h> typedef int (*fcn_hook_t)(void *); typedef struct { const char *module; const char *name; fcn_hook_t fcn; } hook_table_entry_t; typedef struct { int type; //0: data, 1: pointer int dir; //0: in, 1: out, 2: in & out int size; //0: string, -1: wide string, >0: actual size } argument_info_t; typedef struct { char function_name[128]; int nr_args; argument_info_t arguments[12]; int has_retval; uint32_t call_no; uint32_t hook_handle; uint32_t stack[13]; } function_hook_info_t; class ihook_helper_t { public: virtual ~ihook_helper_t(){}; virtual void function_call_entry(function_hook_info_t *hook_info) = 0; virtual void function_call_return(function_hook_info_t *hook_info) = 0; virtual int immediate_return(function_hook_info_t *hook_info, int pop_args) = 0; virtual void hook_return_address(function_hook_info_t *hook_info, fcn_hook_t hook_proc) = 0; virtual void set_hooks(hook_table_entry_t *hook_table) = 0; }; #endif //_IHOOK_HELPER_H_
ntddk/temu
shared/hooks/ihook_helper.h
C
gpl-2.0
1,270
<?php return array( 'extends' => 'root', 'css' => array( //'vendor/bootstrap.min.css', //'vendor/bootstrap-accessibility.css', //'bootstrap-custom.css', 'compiled.css', 'vendor/font-awesome.min.css', 'vendor/bootstrap-slider.css', 'print.css:print', 'ol.css' ), 'js' => array( 'vendor/base64.js:lt IE 10', // btoa polyfill 'vendor/jquery.min.js', 'vendor/bootstrap.min.js', 'vendor/bootstrap-accessibility.min.js', //'vendor/bootlint.min.js', 'vendor/typeahead.js', 'vendor/validator.min.js', 'vendor/rc4.js', 'common.js', 'lightbox.js', ), 'less' => array( 'active' => false, 'compiled.less' ), 'favicon' => 'vufind-favicon.ico', 'helpers' => array( 'factories' => array( 'flashmessages' => 'VuFind\View\Helper\Bootstrap3\Factory::getFlashmessages', 'layoutclass' => 'VuFind\View\Helper\Bootstrap3\Factory::getLayoutClass', ), 'invokables' => array( 'highlight' => 'VuFind\View\Helper\Bootstrap3\Highlight', 'search' => 'VuFind\View\Helper\Bootstrap3\Search', 'vudl' => 'VuDL\View\Helper\Bootstrap3\VuDL', ) ) );
paulusova/VuFind-2.x
themes/bootstrap3/theme.config.php
PHP
gpl-2.0
1,306
/* * Copyright (C) 2005 - 2011 MaNGOS <http://www.getmangos.org/> * * Copyright (C) 2008 - 2011 TrinityCore <http://www.trinitycore.org/> * * Copyright (C) 2011 TrilliumEMU <http://www.trilliumemu.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, see <http://www.gnu.org/licenses/>. */ #include "ScriptMgr.h" #include "BattlegroundAB.h" #include "BattlegroundWS.h" #include "BattlegroundIC.h" #include "BattlegroundSA.h" #include "BattlegroundAV.h" #include "Vehicle.h" class achievement_storm_glory : public AchievementCriteriaScript { public: achievement_storm_glory() : AchievementCriteriaScript("achievement_storm_glory") { } bool OnCheck(Player* source, Unit* /*target*/) { if (source->GetBattlegroundTypeId() != BATTLEGROUND_EY) return false; Battleground *pEotS = source->GetBattleground(); if (!pEotS) return false; return pEotS->IsAllNodesConrolledByTeam(source->GetTeam()); } }; class achievement_resilient_victory : public AchievementCriteriaScript { public: achievement_resilient_victory() : AchievementCriteriaScript("achievement_resilient_victory") { } bool OnCheck(Player* source, Unit* /*target*/) { Battleground* bg = source->GetBattleground(); if (!bg) return false; if (bg->GetTypeID(true) != BATTLEGROUND_AB) return false; if (!static_cast<BattlegroundAB*>(bg)->IsTeamScores500Disadvantage(source->GetTeam())) return false; return true; } }; class achievement_bg_control_all_nodes : public AchievementCriteriaScript { public: achievement_bg_control_all_nodes() : AchievementCriteriaScript("achievement_bg_control_all_nodes") { } bool OnCheck(Player* source, Unit* /*target*/) { Battleground* bg = source->GetBattleground(); if (!bg) return false; if (!bg->IsAllNodesConrolledByTeam(source->GetTeam())) return false; return true; } }; class achievement_save_the_day : public AchievementCriteriaScript { public: achievement_save_the_day() : AchievementCriteriaScript("achievement_save_the_day") { } bool OnCheck(Player* source, Unit* target) { if (!target) return false; if (Player const* player = target->ToPlayer()) { if (source->GetBattlegroundTypeId() != BATTLEGROUND_WS || !source->GetBattleground()) return false; BattlegroundWS* pWSG = static_cast<BattlegroundWS*>(source->GetBattleground()); if (pWSG->GetFlagState(player->GetTeam()) == BG_WS_FLAG_STATE_ON_BASE) return true; } return false; } }; class achievement_bg_ic_resource_glut : public AchievementCriteriaScript { public: achievement_bg_ic_resource_glut() : AchievementCriteriaScript("achievement_bg_ic_resource_glut") { } bool OnCheck(Player* source, Unit* /*target*/) { if (source->HasAura(SPELL_OIL_REFINERY) && source->HasAura(SPELL_QUARRY)) return true; return false; } }; class achievement_bg_ic_glaive_grave : public AchievementCriteriaScript { public: achievement_bg_ic_glaive_grave() : AchievementCriteriaScript("achievement_bg_ic_glaive_grave") { } bool OnCheck(Player* source, Unit* /*target*/) { if (Creature* vehicle = source->GetVehicleCreatureBase()) { if (vehicle->GetEntry() == NPC_GLAIVE_THROWER_H || vehicle->GetEntry() == NPC_GLAIVE_THROWER_A) return true; } return false; } }; class achievement_bg_ic_mowed_down : public AchievementCriteriaScript { public: achievement_bg_ic_mowed_down() : AchievementCriteriaScript("achievement_bg_ic_mowed_down") { } bool OnCheck(Player* source, Unit* /*target*/) { if (Creature* vehicle = source->GetVehicleCreatureBase()) { if (vehicle->GetEntry() == NPC_KEEP_CANNON) return true; } return false; } }; class achievement_bg_sa_artillery : public AchievementCriteriaScript { public: achievement_bg_sa_artillery() : AchievementCriteriaScript("achievement_bg_sa_artillery") { } bool OnCheck(Player* source, Unit* /*target*/) { if (Creature* vehicle = source->GetVehicleCreatureBase()) { if (vehicle->GetEntry() == NPC_ANTI_PERSONNAL_CANNON) return true; } return false; } }; class achievement_arena_kills : public AchievementCriteriaScript { public: achievement_arena_kills(char const* name, uint8 arenaType) : AchievementCriteriaScript(name), _arenaType(arenaType) { } bool OnCheck(Player* source, Unit* /*target*/) { // this checks GetBattleground() for NULL already if (!source->InArena()) return false; return source->GetBattleground()->GetArenaType() == _arenaType; } private: uint8 const _arenaType; }; class achievement_sickly_gazelle : public AchievementCriteriaScript { public: achievement_sickly_gazelle() : AchievementCriteriaScript("achievement_sickly_gazelle") { } bool OnCheck(Player* /*source*/, Unit* target) { if (!target) return false; if (Player* victim = target->ToPlayer()) if (victim->IsMounted()) return true; return false; } }; class achievement_everything_counts : public AchievementCriteriaScript { public: achievement_everything_counts() : AchievementCriteriaScript("achievement_everything_counts") { } bool OnCheck(Player* source, Unit* /*target*/) { Battleground* bg = source->GetBattleground(); if (!bg) return false; if (source->GetBattlegroundTypeId() != BATTLEGROUND_AV) return false; if (static_cast<BattlegroundAV*>(bg)->IsBothMinesControlledByTeam(source->GetTeam())) return true; return false; } }; class achievement_bg_av_perfection : public AchievementCriteriaScript { public: achievement_bg_av_perfection() : AchievementCriteriaScript("achievement_bg_av_perfection") { } bool OnCheck(Player* source, Unit* /*target*/) { Battleground* bg = source->GetBattleground(); if (!bg) return false; if (source->GetBattlegroundTypeId() != BATTLEGROUND_AV) return false; if (static_cast<BattlegroundAV*>(bg)->IsAllTowersControlledAndCaptainAlive(source->GetTeam())) return true; return false; } }; class achievement_wg_didnt_stand_a_chance : public AchievementCriteriaScript { public: achievement_wg_didnt_stand_a_chance() : AchievementCriteriaScript("achievement_wg_didnt_stand_a_chance") { } bool OnCheck(Player* source, Unit* target) { if (!target) return false; if (Player* victim = target->ToPlayer()) { if (!victim->IsMounted()) return false; if (Vehicle* vehicle = source->GetVehicle()) if (vehicle->GetVehicleInfo()->m_ID == 244) // Wintergrasp Tower Cannon return true; } return false; } }; class achievement_bg_sa_defense_of_ancients : public AchievementCriteriaScript { public: achievement_bg_sa_defense_of_ancients() : AchievementCriteriaScript("achievement_bg_sa_defense_of_ancients") { } bool OnCheck(Player* player, Unit* /*target*/) { if (!player) return false; Battleground* battleground = player->GetBattleground(); if (!battleground) return false; if (player->GetTeamId() == static_cast<BattlegroundSA*>(battleground)->Attackers) return false; if (!static_cast<BattlegroundSA*>(battleground)->gateDestroyed) return true; return false; } }; void AddSC_achievement_scripts() { new achievement_storm_glory(); new achievement_resilient_victory(); new achievement_bg_control_all_nodes(); new achievement_save_the_day(); new achievement_bg_ic_resource_glut(); new achievement_bg_ic_glaive_grave(); new achievement_bg_ic_mowed_down(); new achievement_bg_sa_artillery(); new achievement_sickly_gazelle(); new achievement_wg_didnt_stand_a_chance(); new achievement_everything_counts(); new achievement_bg_av_perfection(); new achievement_arena_kills("achievement_arena_2v2_kills", ARENA_TYPE_2v2); new achievement_arena_kills("achievement_arena_3v3_kills", ARENA_TYPE_3v3); new achievement_arena_kills("achievement_arena_5v5_kills", ARENA_TYPE_5v5); new achievement_bg_sa_defense_of_ancients(); }
AwkwardDev/TrilliumEMU
src/server/scripts/World/achievement_scripts.cpp
C++
gpl-2.0
9,912
/* solution.c: Functions for reading and writing the solution files. * * Copyright (C) 2001-2006 by Brian Raiter, under the GNU General Public * License. No warranty. See COPYING for details. */ #include <stdio.h> #include <stdlib.h> #include <string.h> #include <ctype.h> #include "err.h" #include "fileio.h" #include "solution.h" /* * The following is a description of the solution file format. Note that * numeric values are always stored in little-endian order, consistent * with the data file. * * The header is at least eight bytes long, and contains the following * values: * * HEADER * 0-3 signature bytes (35 33 9B 99) * 4 ruleset (1=Lynx, 2=MS) * 5 other options (currently always zero) * 6 other options (currently always zero) * 7 count of bytes in remainder of header (currently always zero) * * After the header are level solutions, usually but not necessarily * in numerical order. Each solution begins with the following values: * * PER LEVEL * 0-3 offset to next solution (from the end of this field) * 4-5 level number * 6-9 level password (four ASCII characters in "cleartext") * 10 other flags (currently always zero) * 11 initial random slide direction and stepping value * 12-15 initial random number generator value * 16-19 time of solution in ticks * 20-xx solution bytes * * If the offset field is 0, then none of the other fields are * present. (This permits the file to contain padding.) If the offset * field is 6, then the level's number and password are present but * without a saved game. Otherwise, the offset should never be less * than 16. * * Note that byte 11 contains the initial random slide direction in * the bottom three bits, and the initial stepping value in the next * three bits. The top two bits are unused. (The initial random slide * direction is always zero under the MS ruleset.) * * The solution bytes consist of a stream of values indicating the * moves of the solution. The values vary in size from one to five * bytes in length. The size of each value is always specified in the * first byte. There are five different formats for the values. (Note * that in the following byte diagrams, the bits are laid out * little-endian instead of the usual MSB-first.) * * The first format can be either one or two bytes long. The two-byte * form is shown here: * * #1: 01234567 89012345 * NNDDDTTT TTTTTTTT * * The two lowest bits, marked with Ns, contain either one (01) or two * (10), and indicate how many bytes are used. The next three bits, * marked with Ds, contain the direction of the move. The remaining * bits are marked with Ts, and these indicate the amount of time, in * ticks, between this move and the prior move, less one. (Thus, a * value of T=0 indicates a move that occurs on the tick immediately * following the previous move.) The very first move of a solution is * an exception: it is not decremented, as that would sometimes * require a negative value to be stored. If the one-byte version is * used, then T is only three bits in size; otherwise T is 11 bits * long. * * The second format is four bytes in length: * * #2: 01234567 89012345 67890123 45678901 * 11DD0TTT TTTTTTTT TTTTTTTT TTTTTTTT * * This format allocates 27 bits for the time value. (The top four * bits will always be zero, however, as the game's timer is currently * limited to 23 bits.) Since there are only two bits available for * storing the direction, this format can only be used to store * orthogonal moves (i.e. it cannot be used to store a Lynx diagonal * move). * * The third format has the form: * * #3: 01234567 * 00DDEEFF * * This value encodes three separate moves (DD, EE, and FF) packed * into a single byte. Each move has an implicit time value of four * ticks separating it from the prior move (i.e. T=3). Like the second * format, only two bits are used to store each move. * * The fourth and final format, like the first format, can vary in * size. It can be two, three, four, or five bytes long, depending on * how many bits are needed to store the time interval. It is shown * here in its largest form: * * #4: 01234567 89012345 67890123 45678901 23456789 * 11NN1DDD DDDDDDTT TTTTTTTT TTTTTTTT TTTTTTTT * * The two bits marked NN indicate the size of the field in bytes, * less two (i.e., 00 for a two-byte value, 11 for a five-byte value). * Seven bits are used to indicate the move's direction, which allows * this field to store MS mouse moves. The time value is encoded * normally, and can be 2, 10, 18, or 26 bits long. */ /* The signature bytes of the solution files. */ #define CSSIG 0x999B3335UL /* Translate move directions between three-bit and four-bit * representations. * * 0 = NORTH = 0001 = 1 * 1 = WEST = 0010 = 2 * 2 = SOUTH = 0100 = 4 * 3 = EAST = 1000 = 8 * 4 = NORTH | WEST = 0011 = 3 * 5 = SOUTH | WEST = 0110 = 6 * 6 = NORTH | EAST = 1001 = 9 * 7 = SOUTH | EAST = 1100 = 12 */ static int const diridx8[16] = { -1, 0, 1, 4, 2, -1, 5, -1, 3, 6, -1, -1, 7, -1, -1, -1 }; static int const idxdir8[8] = { NORTH, WEST, SOUTH, EAST, NORTH | WEST, SOUTH | WEST, NORTH | EAST, SOUTH | EAST }; #define isdirectmove(dir) (directionalcmd(dir)) #define ismousemove(dir) (!isdirectmove(dir)) #define isdiagonal(dir) (isdirectmove(dir) && diridx8[dir] > 3) #define isorthogonal(dir) (isdirectmove(dir) && diridx8[dir] <= 3) #define dirtoindex(dir) (diridx8[dir]) #define indextodir(dir) (idxdir8[dir]) /* * Functions for manipulating move lists. */ /* Initialize or reinitialize list as empty. */ void initmovelist(actlist *list) { if (!list->allocated || !list->list) { list->allocated = 16; xalloc(list->list, list->allocated * sizeof *list->list); } list->count = 0; } /* Append move to the end of list. */ void addtomovelist(actlist *list, action move) { if (list->count >= list->allocated) { list->allocated *= 2; xalloc(list->list, list->allocated * sizeof *list->list); } list->list[list->count++] = move; } /* Make to an independent copy of from. */ void copymovelist(actlist *to, actlist const *from) { if (!to->allocated || !to->list) to->allocated = 16; while (to->allocated < from->count) to->allocated *= 2; xalloc(to->list, to->allocated * sizeof *to->list); to->count = from->count; if (from->count) memcpy(to->list, from->list, from->count * sizeof *from->list); } /* Deallocate list. */ void destroymovelist(actlist *list) { if (list->list) free(list->list); list->allocated = 0; list->list = NULL; } /* * Functions for handling the solution file header. */ /* Read the header bytes of the given solution file. flags receives * the option bytes (bytes 5-6). extra receives any bytes in the * header that this code doesn't recognize. */ int readsolutionheader(fileinfo *file, int *ruleset, int *flags, int *extrasize, unsigned char *extra) { unsigned long sig; unsigned short f; unsigned char n; if (!filereadint32(file, &sig, "not a valid solution file")) return FALSE; if (sig != CSSIG) return fileerr(file, "not a valid solution file"); if (!filereadint8(file, &n, "not a valid solution file")) return FALSE; if (!filereadint16(file, &f, "not a valid solution file")) return FALSE; *ruleset = (int)n; *flags = (int)f; if (!filereadint8(file, &n, "not a valid solution file")) return FALSE; *extrasize = n; if (n) if (!fileread(file, extra, *extrasize, "not a valid solution file")) return FALSE; return TRUE; } /* Write the header bytes to the given solution file. */ /* static int writesolutionheader(fileinfo *file, int ruleset, int flags, int extrasize, unsigned char const *extra) { return filewriteint32(file, CSSIG, NULL) && filewriteint8(file, ruleset, NULL) && filewriteint16(file, flags, NULL) && filewriteint8(file, extrasize, NULL) && filewrite(file, extra, extrasize, NULL); } */ /* Write the name of the level set to the given solution file. */ /* static int writesolutionsetname(fileinfo *file, char const *setname) { char zeroes[16] = ""; int n; n = strlen(setname) + 1; return filewriteint32(file, n + 16, NULL) && filewrite(file, zeroes, 16, NULL) && filewrite(file, setname, n, NULL); } */ /* * Solution translation. */ /* Expand a level's solution data into an actual list of moves. */ int expandsolution(solutioninfo *solution, gamesetup const *game) { unsigned char const *dataend; unsigned char const *p; action act; int n; if (game->solutionsize <= 16) return FALSE; solution->flags = game->solutiondata[6]; solution->rndslidedir = indextodir(game->solutiondata[7] & 7); solution->stepping = (game->solutiondata[7] >> 3) & 7; solution->rndseed = game->solutiondata[8] | (game->solutiondata[9] << 8) | (game->solutiondata[10] << 16) | (game->solutiondata[11] << 24); initmovelist(&solution->moves); act.when = -1; p = game->solutiondata + 16; dataend = game->solutiondata + game->solutionsize; while (p < dataend) { switch (*p & 0x03) { case 0: act.dir = indextodir((*p >> 2) & 0x03); act.when += 4; addtomovelist(&solution->moves, act); act.dir = indextodir((*p >> 4) & 0x03); act.when += 4; addtomovelist(&solution->moves, act); act.dir = indextodir((*p >> 6) & 0x03); act.when += 4; addtomovelist(&solution->moves, act); ++p; break; case 1: act.dir = indextodir((*p >> 2) & 0x07); act.when += ((*p >> 5) & 0x07) + 1; addtomovelist(&solution->moves, act); ++p; break; case 2: if (p + 2 > dataend) goto truncated; act.dir = indextodir((*p >> 2) & 0x07); act.when += ((p[0] >> 5) & 0x07) + ((unsigned long)p[1] << 3) + 1; addtomovelist(&solution->moves, act); p += 2; break; case 3: if (*p & 0x10) { n = (*p >> 2) & 0x03; if (p + 2 + n > dataend) goto truncated; act.dir = ((p[0] >> 5) & 0x07) | ((p[1] & 0x3F) << 3); act.when += (p[1] >> 6) & 0x03; while (n--) act.when += (unsigned long)p[2 + n] << (2 + n * 8); ++act.when; p += 2 + ((*p >> 2) & 0x03); } else { if (p + 4 > dataend) goto truncated; act.dir = indextodir((*p >> 2) & 0x03); act.when += ((p[0] >> 5) & 0x07) | ((unsigned long)p[1] << 3) | ((unsigned long)p[2] << 11) | ((unsigned long)p[3] << 19); ++act.when; p += 4; } addtomovelist(&solution->moves, act); break; } } return TRUE; truncated: errmsg(NULL, "level %d: truncated solution data", game->number); initmovelist(&solution->moves); return FALSE; } /* Take the given solution and compress it, storing the compressed * data as part of the level's setup. */ int contractsolution(solutioninfo const *solution, gamesetup *game) { action const *move; unsigned char *data; int size, delta, when, i; free(game->solutiondata); game->solutionsize = 0; game->solutiondata = NULL; if (!solution->moves.count) return TRUE; size = 21; move = solution->moves.list + 1; for (i = 1 ; i < solution->moves.count ; ++i, ++move) size += !isorthogonal(move->dir) ? 5 : move[0].when - move[-1].when <= (1 << 3) ? 1 : move[0].when - move[-1].when <= (1 << 11) ? 2 : 4; data = malloc(size); if (!data) { errmsg(NULL, "failed to record level %d solution:" " out of memory", game->number); return FALSE; } data[0] = game->number & 0xFF; data[1] = (game->number >> 8) & 0xFF; data[2] = game->passwd[0]; data[3] = game->passwd[1]; data[4] = game->passwd[2]; data[5] = game->passwd[3]; data[6] = solution->flags; data[7] = dirtoindex(solution->rndslidedir) | (solution->stepping << 3); data[8] = solution->rndseed & 0xFF; data[9] = (solution->rndseed >> 8) & 0xFF; data[10] = (solution->rndseed >> 16) & 0xFF; data[11] = (solution->rndseed >> 24) & 0xFF; data[12] = game->besttime & 0xFF; data[13] = (game->besttime >> 8) & 0xFF; data[14] = (game->besttime >> 16) & 0xFF; data[15] = (game->besttime >> 24) & 0xFF; when = -1; size = 16; move = solution->moves.list; for (i = 0 ; i < solution->moves.count ; ++i, ++move) { delta = -when - 1; when = move->when; delta += when; if (ismousemove(move->dir) || (isdiagonal(move->dir) && delta >= (1 << 11))) { data[size] = 0x13 | ((move->dir << 5) & 0xE0); data[size + 1] = ((move->dir >> 3) & 0x3F) | ((delta & 0x03) << 6); if (delta < (1 << 2)) { size += 2; } else { data[size + 2] = (delta >> 2) & 0xFF; if (delta < (1 << 10)) { data[size] |= 1 << 2; size += 3; } else { data[size + 3] = (delta >> 10) & 0xFF; if (delta < (1 << 18)) { data[size] |= 2 << 2; size += 4; } else { data[size + 4] = (delta >> 18) & 0xFF; data[size] |= 3 << 2; size += 5; } } } } else if (delta == 3 && i + 2 < solution->moves.count && isorthogonal(move[0].dir) && move[1].when - move[0].when == 4 && isorthogonal(move[1].dir) && move[2].when - move[1].when == 4 && isorthogonal(move[2].dir)) { data[size++] = (dirtoindex(move[0].dir) << 2) | (dirtoindex(move[1].dir) << 4) | (dirtoindex(move[2].dir) << 6); move += 2; i += 2; when = move->when; } else if (delta < (1 << 3)) { data[size++] = 0x01 | (dirtoindex(move->dir) << 2) | ((delta << 5) & 0xE0); } else if (delta < (1 << 11)) { data[size++] = 0x02 | (dirtoindex(move->dir) << 2) | ((delta << 5) & 0xE0); data[size++] = (delta >> 3) & 0xFF; } else { data[size++] = 0x03 | (dirtoindex(move->dir) << 2) | ((delta << 5) & 0xE0); data[size++] = (delta >> 3) & 0xFF; data[size++] = (delta >> 11) & 0xFF; data[size++] = (delta >> 19) & 0xFF; } } game->solutionsize = size; game->solutiondata = realloc(data, size); if (!game->solutiondata) game->solutiondata = data; return TRUE; } /* * File I/O for level solutions. */ /* Read the data of a one complete solution from the given file into * a gamesetup structure. */ int readsolution(fileinfo *file, gamesetup *game) { unsigned long size; game->number = 0; game->sgflags = 0; game->besttime = TIME_NIL; game->solutionsize = 0; game->solutiondata = NULL; if (!file->fp) return TRUE; if (!filereadint32(file, &size, NULL) || size == 0xFFFFFFFF) return FALSE; if (!size) return TRUE; game->solutionsize = size; game->solutiondata = filereadbuf(file, size, "unexpected EOF"); if (!game->solutiondata || (size <= 16 && size != 6)) { free(game->solutiondata); game->solutionsize = 0; game->solutiondata = NULL; return fileerr(file, "invalid data in solution file"); } game->number = (game->solutiondata[1] << 8) | game->solutiondata[0]; memcpy(game->passwd, game->solutiondata + 2, 4); game->passwd[4] = '\0'; game->sgflags |= SGF_HASPASSWD; if (size == 6) return TRUE; game->besttime = game->solutiondata[12] | (game->solutiondata[13] << 8) | (game->solutiondata[14] << 16) | (game->solutiondata[15] << 24); if (!game->number && !*game->passwd) { size -= 16; game->sgflags |= SGF_SETNAME; if (size > 255) size = 255; memcpy(game->name, game->solutiondata + 16, size); game->name[size] = '\0'; free(game->solutiondata); game->solutionsize = 0; game->solutiondata = NULL; } return TRUE; } /* Write the data of one complete solution from the appropriate fields * of game to the given file. */ /* static int writesolution(fileinfo *file, gamesetup const *game) { if (game->solutionsize) { if (!filewriteint32(file, game->solutionsize, "write error") || !filewrite(file, game->solutiondata, game->solutionsize, "write error")) return FALSE; } else if (game->sgflags & SGF_HASPASSWD) { if (!filewriteint32(file, 6, "write error") || !filewriteint16(file, game->number, "write error") || !filewrite(file, game->passwd, 4, "write error")) return FALSE; } return TRUE; }*/ /* Free all memory allocated for storing a solution. */ void clearsolution(gamesetup *game) { free(game->solutiondata); game->besttime = TIME_NIL; game->sgflags = 0; game->solutionsize = 0; game->solutiondata = NULL; }
magical/tws2json
solution.c
C
gpl-2.0
16,573
<?php include_once(INCLUDE_DIR.'staff/login.header.php'); defined('OSTSCPINC') or die('Invalid path'); $info = ($_POST)?Format::htmlchars($_POST):array(); ?> <div id="loginBox"> <div class="tape"></div> <div id="blur"> <div id="background"></div> </div> <h1 id="logo"><a href="index.php"> <span class="valign-helper"></span> <img src="logo.php?login" alt="osTicket :: <?php echo __('Agent Password Reset');?>" /> </a></h1> <h3><?php echo Format::htmlchars($msg); ?></h3> <form action="pwreset.php" method="post"> <?php csrf_token(); ?> <input type="hidden" name="do" value="newpasswd"/> <input type="hidden" name="token" value="<?php echo Format::htmlchars($_REQUEST['token']); ?>"/> <fieldset> <input type="text" name="userid" id="name" value="<?php echo $info['userid']; ?>" placeholder="<?php echo __('Email or Username'); ?>" autocorrect="off" autocapitalize="off"/> </fieldset> <input class="submit" type="submit" name="submit" value="Login"/> </form> <div id="company"> <div class="content"> <?php echo __('Copyright'); ?> &copy; <?php echo Format::htmlchars($ost->company) ?: date('Y'); ?> </div> </div> </div> <div id="poweredBy"><?php echo __('Powered by'); ?> <a href="http://www.osticket.com" target="_blank"> <img alt="osTicket" src="images/osticket-grey.png" class="osticket-logo"> </a> </div> <script> document.addEventListener('DOMContentLoaded', function() { if (undefined === window.getComputedStyle(document.documentElement).backgroundBlendMode) { document.getElementById('background-compat').style.display = 'block'; document.getElementById('loginBox').style.backgroundColor = 'white'; } }); </script> </body> </html>
garyns/osTicket-lyn
include/staff/pwreset.login.php
PHP
gpl-2.0
1,896
/* Copyright 2003-2014 Ciaran Anscomb * * This file is part of XRoar. * * XRoar 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. * * XRoar 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 XRoar. If not, see <http://www.gnu.org/licenses/>. */ #include "config.h" #include <assert.h> #include <ctype.h> #include <stdint.h> #include <stdio.h> #include <stdlib.h> #include "xalloc.h" #include "logging.h" #include "xroar.h" int log_level = 1; enum log_type { LOG_HEXDUMP, }; struct log_handle { enum log_type type; const char *prefix; union { struct { unsigned address; unsigned nbytes; uint8_t buf[16]; unsigned flag; } hexdump; } ctx; }; static void log_open(struct log_handle **lp, const char *prefix, enum log_type type) { assert(lp != NULL); log_close(lp); struct log_handle *l = xzalloc(sizeof(*l)); l->type = type; l->prefix = prefix; *lp = l; } void log_open_hexdump(struct log_handle **lp, const char *prefix) { log_open(lp, prefix, LOG_HEXDUMP); struct log_handle *l = *lp; l->ctx.hexdump.address = 0; l->ctx.hexdump.nbytes = 0; l->ctx.hexdump.flag = -1; } void log_close(struct log_handle **lp) { assert(lp != NULL); struct log_handle *l = *lp; if (!l) return; switch (l->type) { case LOG_HEXDUMP: log_hexdump_line(l); break; default: break; } free(l); *lp = NULL; } void log_hexdump_set_addr(struct log_handle *l, unsigned addr) { if (!l) return; if (l->ctx.hexdump.address != addr) { log_hexdump_line(l); l->ctx.hexdump.address = addr; } } void log_hexdump_line(struct log_handle *l) { if (!l) return; assert(l->prefix != NULL); assert(l->type == LOG_HEXDUMP); if (l->ctx.hexdump.nbytes == 0) return; LOG_PRINT("%s: %04x ", l->prefix, l->ctx.hexdump.address); unsigned i; for (i = 0; i < l->ctx.hexdump.nbytes; i++) { int f = ((i + 1) == l->ctx.hexdump.flag) ? '*' : ' '; LOG_PRINT("%02x%c", l->ctx.hexdump.buf[i], f); if (i == 8) LOG_PRINT(" "); } for (; i < 16; i++) { LOG_PRINT(" "); if (i == 8) LOG_PRINT(" "); } LOG_PRINT(" |"); for (i = 0; i < l->ctx.hexdump.nbytes; i++) { int c = l->ctx.hexdump.buf[i]; LOG_PRINT("%c", isprint(c) ? c : (int)'.'); } LOG_PRINT("|\n"); l->ctx.hexdump.address += l->ctx.hexdump.nbytes; l->ctx.hexdump.nbytes = 0; l->ctx.hexdump.flag = -1; } void log_hexdump_byte(struct log_handle *l, uint8_t b) { if (!l) return; assert(l->type == LOG_HEXDUMP); if (l->ctx.hexdump.nbytes >= 16) log_hexdump_line(l); l->ctx.hexdump.buf[l->ctx.hexdump.nbytes++] = b; } void log_hexdump_flag(struct log_handle *l) { if (!l) return; assert(l->type == LOG_HEXDUMP); l->ctx.hexdump.flag = l->ctx.hexdump.nbytes; }
jedie/XRoar
src/logging.c
C
gpl-2.0
3,142
/* * $Id$ * * DEBUG: section 28 Access Control * AUTHOR: Duane Wessels * * SQUID Web Proxy Cache http://www.squid-cache.org/ * ---------------------------------------------------------- * * Squid is the result of efforts by numerous individuals from * the Internet community; see the CONTRIBUTORS file for full * details. Many organizations have provided support for Squid's * development; see the SPONSORS file for full details. Squid is * Copyrighted (C) 2001 by the Regents of the University of * California; see the COPYRIGHT file for full details. Squid * incorporates software developed and/or copyrighted by other * sources; see the CREDITS file for full details. * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111, USA. * * * Copyright (c) 2003, Robert Collins <robertc@squid-cache.org> */ #include "squid.h" #include "acl/CertificateData.h" #include "acl/Checklist.h" #include "wordlist.h" ACLCertificateData::ACLCertificateData(SSLGETATTRIBUTE *sslStrategy) : attribute (NULL), values (), sslAttributeCall (sslStrategy) {} ACLCertificateData::ACLCertificateData(ACLCertificateData const &old) : attribute (NULL), values (old.values), sslAttributeCall (old.sslAttributeCall) { if (old.attribute) attribute = xstrdup (old.attribute); } template<class T> inline void xRefFree(T &thing) { xfree (thing); } ACLCertificateData::~ACLCertificateData() { safe_free (attribute); } template<class T> inline int splaystrcmp (T&l, T&r) { return strcmp ((char *)l,(char *)r); } bool ACLCertificateData::match(SSL *ssl) { if (!ssl) return 0; char const *value = sslAttributeCall(ssl, attribute); if (value == NULL) return 0; return values.match(value); } static void aclDumpAttributeListWalkee(char * const & node_data, void *outlist) { /* outlist is really a wordlist ** */ wordlistAdd((wordlist **)outlist, node_data); } wordlist * ACLCertificateData::dump() { wordlist *wl = NULL; wordlistAdd(&wl, attribute); /* damn this is VERY inefficient for long ACL lists... filling * a wordlist this way costs Sum(1,N) iterations. For instance * a 1000-elements list will be filled in 499500 iterations. */ /* XXX FIXME: don't break abstraction */ values.values->walk(aclDumpAttributeListWalkee, &wl); return wl; } void ACLCertificateData::parse() { char *newAttribute = strtokFile(); if (!newAttribute) self_destruct(); /* an acl must use consistent attributes in all config lines */ if (attribute) { if (strcasecmp(newAttribute, attribute) != 0) self_destruct(); } else attribute = xstrdup(newAttribute); values.parse(); } bool ACLCertificateData::empty() const { return values.empty(); } ACLData<SSL *> * ACLCertificateData::clone() const { /* Splay trees don't clone yet. */ return new ACLCertificateData(*this); }
schmurfy/squid
src/acl/CertificateData.cc
C++
gpl-2.0
3,610
# Install script for directory: /home/hsean/Documents/pcl/tests/test06_ContinuousVideo # Set the install prefix IF(NOT DEFINED CMAKE_INSTALL_PREFIX) SET(CMAKE_INSTALL_PREFIX "/usr/local") ENDIF(NOT DEFINED CMAKE_INSTALL_PREFIX) STRING(REGEX REPLACE "/$" "" CMAKE_INSTALL_PREFIX "${CMAKE_INSTALL_PREFIX}") # Set the install configuration name. IF(NOT DEFINED CMAKE_INSTALL_CONFIG_NAME) IF(BUILD_TYPE) STRING(REGEX REPLACE "^[^A-Za-z0-9_]+" "" CMAKE_INSTALL_CONFIG_NAME "${BUILD_TYPE}") ELSE(BUILD_TYPE) SET(CMAKE_INSTALL_CONFIG_NAME "") ENDIF(BUILD_TYPE) MESSAGE(STATUS "Install configuration: \"${CMAKE_INSTALL_CONFIG_NAME}\"") ENDIF(NOT DEFINED CMAKE_INSTALL_CONFIG_NAME) # Set the component getting installed. IF(NOT CMAKE_INSTALL_COMPONENT) IF(COMPONENT) MESSAGE(STATUS "Install component: \"${COMPONENT}\"") SET(CMAKE_INSTALL_COMPONENT "${COMPONENT}") ELSE(COMPONENT) SET(CMAKE_INSTALL_COMPONENT) ENDIF(COMPONENT) ENDIF(NOT CMAKE_INSTALL_COMPONENT) # Install shared libraries without execute permission? IF(NOT DEFINED CMAKE_INSTALL_SO_NO_EXE) SET(CMAKE_INSTALL_SO_NO_EXE "1") ENDIF(NOT DEFINED CMAKE_INSTALL_SO_NO_EXE) IF(CMAKE_INSTALL_COMPONENT) SET(CMAKE_INSTALL_MANIFEST "install_manifest_${CMAKE_INSTALL_COMPONENT}.txt") ELSE(CMAKE_INSTALL_COMPONENT) SET(CMAKE_INSTALL_MANIFEST "install_manifest.txt") ENDIF(CMAKE_INSTALL_COMPONENT) FILE(WRITE "/home/hsean/Documents/pcl/tests/test06_ContinuousVideo/build/${CMAKE_INSTALL_MANIFEST}" "") FOREACH(file ${CMAKE_INSTALL_MANIFEST_FILES}) FILE(APPEND "/home/hsean/Documents/pcl/tests/test06_ContinuousVideo/build/${CMAKE_INSTALL_MANIFEST}" "${file}\n") ENDFOREACH(file)
hsean/Capstone-44-Object-Segmentation
SEAN/PCL/OLDER_PROJECTS/test06_ContinuousVideo/build/cmake_install.cmake
CMake
gpl-2.0
1,684
<!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/html; charset=utf-8" /> <title>广州谱式达-人力资源-知识产权-工商财税-人才服务-户口手续办理</title> <meta name="description" content="广州谱式达人力资源服务有限公司。拥有多年工商注册-户口办理手续-户口手续办理-广州社保-广州公积金-人事代理-代理招聘-财税服务-ICP办理-商标注册-商标设计-专利业务-版权业务等经验,专业、免费为用户提供企业一条龙服务,广州户口,广州社保,广州公积金知识产权,内资注册,外资注册,专利版权等业务代办,办理请认准广州谱式达人力资源服务有限公司。" /> <meta name="keywords" content="广州谱式达,广州谱式达人力资源服务有限公司,工商注册,知识产权,办理户口手续,户口手续办理,广州户口手续办理,社保办理,公积金办理,代办工商财税,广州商标注册,企业服务,代理招聘" /> <link rel="stylesheet" type="text/css" href="/templets/css/a.css"> <link rel="stylesheet" type="text/css" href="/templets/css/style.css"/> <link rel="stylesheet" type="text/css" href="/templets/css/global.css"/> <script type="text/javascript" src="/templets/js/jquery.js"></script> </head> <body> <div id="head"> <div id="body"> <div class="logo"><img src="/img/logo.png" alt="广州谱式达"/> <div class="logotel"> <div id="nav"> <ul class="c"> <li><a href="/">首页</a></li> <li><a href="/a/psd/" rel="12">关于我们</A></li> <li><a href="/a/rcfw/" rel="61">人才服务</a></li> <li><a href="/a/zscq/" rel="62">知识产权</a></li> <li><a href="/a/qyfw/" rel="60">工商财税</a></li> <li><a href="/a/zhishiku/" rel="81">晓·资讯</a></li> <li><a href="/a/lxwm/" rel="64">联系我们</a></li> </ul> </div> </div> </div> </div> <SCRIPT type=text/javascript> $(function(){ var _p = window.location.pathname; $("#nav .c a").each(function(){ var _h=$(this).attr("href"); $(this).removeClass("sele"); if((_p.indexOf(_h)!=-1 && _h!="/") || _p==_h){$(this).addClass("sele");} }); }); </SCRIPT> </div> <div id="focusBar"> <a href="javascript:void(0)" class="arrL" onClick="prePage()"></a> <a href="javascript:void(0)" class="arrR" onClick="nextPage()"></a> <ul class="mypng"> <li id="f_slider1" style="background:url(/templets/default/images/gsmmadbg.jpg) no-repeat center center; display:block;"> <div class="focusL"></div> <div class="focusR"><a href="/a/jt/gszx.html" target="_blank"><img src="/templets/default/images/gsmmad.png" width="1900" height="279" alt="公司注销-公司转让" /></a></div> </li> <li id="f_slider2" style="background:url(/templets/default/images/sbzcadbg.jpg) no-repeat center center; display:none;"> <div class="focusL"></div> <div class="focusR"><a href="/a/jt/sbzc.html" target="_blank"><img src="/templets/default/images/sbzcad.png" width="1920" height="279" alt="广州商标注册代理"/></a></div> </li> <li id="f_slider3" style="background:url(/templets/default/images/zlbqadbg.jpg) no-repeat center center; display:none;"> <div class="focusL"></div> <div class="focusR"><a href="/a/zscq/" target="_blank"><img src="/templets/default/images/zlbqad.png" width="1920" height="279" alt="广州知识产权代办"/></a></div> </li> </ul> <div class="adnum"></div> </div> <script src="/templets/js/jquery.easing.1.3.js"></script> <script src="/templets/js/hcad.js"></script> <div class="wapper_02"> <div class="new_box"> <div class="news_main"> <div class="news_menu"> <h2>>信息中心</h2> <div class="info_ul"> <ul> <li><a href='/a/zscq/sbzc/' class='thisclass'>商标注册</a></li> <li><a href='/a/zscq/sbsj/'>商标设计</a></li> <li><a href='/a/zscq/zlbq/'>专利版权</a></li> <li><a href='/a/zscq/ppjs/'>品牌建设</a></li> </ul> </div> <div class="img_list"> <a href="/a/rcfw/rsdl"><img src="/templets/images/bui_img2.png" alt="办理户口" width="210" /></a> </div> <div class="n_list"> <div class="list_title">户口社保<span><a href="/a/rcfw/rsdl" title="更多...">更多>></a>&nbsp;&nbsp;</span></div> <ul> <li><a href="/a/rcfw/rsdl/2014/1117/699.html">广州市各区社保局地址</a></li> <li><a href="/a/rcfw/rsdl/2014/1105/651.html">单位社保挂靠</a></li> <li><a href="/a/rcfw/rsdl/2014/1105/650.html">单位社保注销</a></li> <li><a href="/a/rcfw/rsdl/2014/1105/649.html">个人信息变更</a></li> <li><a href="/a/rcfw/rsdl/2014/1105/648.html">个人社保挂靠</a></li> <li><a href="/a/rcfw/rsdl/2014/1105/644.html">应届毕业生可办理暂缓就</a></li> </ul> </div> <div class="n_list"> <div class="list_title">工商财税<span><a href="/a/qyfw" title="更多...">更多>></a>&nbsp;&nbsp;</span></div> <ul> <li><a href="/a/qyfw/nzzc/2014/1127/720.html">广州公司营业单位开业登</a></li> <li><a href="/a/qyfw/nzzc/2014/1127/719.html">广州公司营业单位注销登</a></li> <li><a href="/a/qyfw/gsfw/2014/1127/718.html">广州公司出资方式变更登</a></li> <li><a href="/a/qyfw/nzzc/2014/1121/713.html">营业执照的补办程序</a></li> <li><a href="/a/qyfw/nzzc/2014/1120/710.html">个人独资企业设立资料</a></li> <li><a href="/a/qyfw/gsfw/2014/1120/709.html">进出口权申请</a></li> </ul> </div> <div class="n_list"> <div class="list_title">知识库<span><a href="/a/zhishiku" title="更多...">更多>></a>&nbsp;&nbsp;</span></div> <ul> <li><a href="/a/zhishiku/cjwt/2014/1204/745.html">2014年广州积分入户入围</a></li> <li><a href="/a/zhishiku/hyzx/2014/1204/744.html">2015年深圳积分入户政策变</a></li> <li><a href="/a/zhishiku/hyzx/2014/1204/742.html">8、社会医疗保险缴费月数</a></li> <li><a href="/a/zhishiku/hyzx/2014/1204/741.html">8、社会医疗保险缴费月数</a></li> <li><a href="/a/zhishiku/hyzx/2014/1204/740.html">7、社会医疗保险缴费月数</a></li> <li><a href="/a/zhishiku/hyzx/2014/1204/739.html">7、社会医疗保险缴费月数</a></li> </ul> </div> <div class="n_list"> <div class="list_title">常见问题<span><a href="/a/zhishiku/cjwt" title="更多...">更多>></a>&nbsp;&nbsp;</span></div> <ul> </ul> </div> </div> <div class="news_list"> <div class="postion"> <span>您当前的位置:</span><a href='/'>广州谱式达</a> > <a href='/a/zscq/'>知识产权</a> > <a href='/a/zscq/sbzc/'>商标注册</a> > </div> <div class="contents"> <ul> <li> <div class="biaoti"><a href="/a/zscq/sbzc/2014/0926/342.html">知识产权的申请</a> 发布于:<span>2014-09-26 17:43:37</span> </div> <div class="descript">对于既独特新颖,又兼具实用性的构思,应在生产或公开前尽快申请知识产权的专利或外观设计注册,以获得法律上的保护;而商标注册亦可保障商标持有人在业务上的权益及防止被不...</div> </li><li> <div class="biaoti"><a href="/a/zscq/sbzc/2014/0926/333.html">补发商标注册证申请注意事项</a> 发布于:<span>2014-09-26 17:41:08</span> </div> <div class="descript">补发商标注册证含义是指《商标注册证》遗失或者破损的向国家商标局申请补发商标注册证。(商标注册证在补发申请时应将破损的商标注册证一并交回商标局。) 需提交的材料 :...</div> </li><li> <div class="biaoti"><a href="/a/zscq/sbzc/2014/0926/332.html">香港知识产权问题</a> 发布于:<span>2014-09-26 17:36:47</span> </div> <div class="descript">中国政府对香港恢复行使主权后,香港特别行政区设有单独的专利制度,施行香港《专利条例》和《注册外观设计条例》。为方便中国内地、香港特别行政区以及其他国家和地区的申请...</div> </li><li> <div class="biaoti"><a href="/a/zscq/sbzc/2014/0924/316.html">商标注册申请的类型</a> 发布于:<span>2014-09-24 14:02:58</span> </div> <div class="descript">(一)商标注册申请; (二)办理商标注册人名义及地址申请; (三)注册商标转让申请; (四)注册商标续展申请; (五)商标注册证补发申请; (六)注册商标注销申请; (七...</div> </li><li> <div class="biaoti"><a href="/a/zscq/sbzc/2014/0924/315.html">撤销连续三年停止使用注册商标申请</a> 发布于:<span>2014-09-24 14:02:04</span> </div> <div class="descript">1、《撤销连续三年停止使用注册商标申请书》一份,撤销理由和证明材料一份另附。 2、申请人如是公司需提交《营业执照》复印件一份,如是个人需提交身份证复印件一份。 3、委托...</div> </li><li> <div class="biaoti"><a href="/a/zscq/sbzc/2014/0924/314.html">商标网上申请试用阶段注意事项</a> 发布于:<span>2014-09-24 13:59:18</span> </div> <div class="descript">1、试用阶段商标网上申请仅对商标代理组织开放,商标申请人暂不能直接提交网上申请。 2、为了信息安全,网上申请采用电子签名技术。商标代理组织(需在商标局备案且无不良记录...</div> </li><li> <div class="biaoti"><a href="/a/zscq/sbzc/2014/0923/281.html">受理集体商标注册</a> 发布于:<span>2014-09-23 14:14:45</span> </div> <div class="descript">集体商标(COLLECTIVE MARK),是指以团体、协会或者其他组织名义注册,专供该组织成员在商事活动中使用,以表明使用者在该组织中的成员资格的标志。在有些国家,也可能由一些企业...</div> </li><li> <div class="biaoti"><a href="/a/zscq/sbzc/2014/0923/280.html">注册涉外商标的注意事项</a> 发布于:<span>2014-09-23 14:08:12</span> </div> <div class="descript">1、申请人必须具有一定的主体资格。申请人应在我国有真实有效的工商营业所;如果没有,应在我国境内有住所;如果没有住所,申请人应有我国国籍。非马德里联盟成员国的国民,若在...</div> </li><li> <div class="biaoti"><a href="/a/zscq/sbzc/2014/0923/279.html">商标复审</a> 发布于:<span>2014-09-23 14:07:58</span> </div> <div class="descript">商标复审是指:根据商标法实施条例第28条的规定,商标评审委员会有权审理商标注册复审案件、商标异议复审案件和商标撤销复审案件。 商标注册复审案件是指商标注册申请人对商标...</div> </li><li> <div class="biaoti"><a href="/a/zscq/sbzc/2014/0922/246.html">商标异议程序</a> 发布于:<span>2014-09-22 14:22:31</span> </div> <div class="descript">异议是指社会公众对商标局初步审定予以公告的商标,提出反对注册的意见。即商标局受理商标注册申请后,根据商标法的规定进行审查。将符合注册条件的商标注册申请,在《商标公...</div> </li> </ul> </div> <div class="page"><a href='list_73_1.html'>首页</a> <a href='list_73_1.html'>上一页</a> <a href='list_73_1.html'>1</a> 2 <a href='list_73_3.html'>3</a> <a href='list_73_4.html'>4</a> <a href='list_73_3.html'>下一页</a> <a href='list_73_4.html'>末页</a> <select name='sldd' style='width:36px' onchange='location.href=this.options[this.selectedIndex].value;'> <option value='list_73_1.html'>1</option> <option value='list_73_2.html' selected>2</option> <option value='list_73_3.html'>3</option> <option value='list_73_4.html'>4</option> </select> <span class="pageinfo">共 <strong>4</strong>页<strong>33</strong>条</span> </div> </div> </div> </div> </div> <div style="clear:both;"></div>  <!----尾部开始-----> <div class="footer"> <ul class="foot"> <li class="f_w1"> <h1>联系我们</h1> <p> 广州谱式达人力资源服务有限公司<br> 地址: 广州市海珠区昌岗中路 166 号<br> 富盈国际大厦 807室<br> 热线 : 4006-020-308<br> 电话 : 020-34479170<br> Email: <a href="mailto:36908589@qq.com">36908589@qq.com</a> </p> </li> <li class="f_w2"> <h1>&nbsp;</h1> <p> “谱式达”EAP服务中心<br> 地址 : 广州海珠区珠江帝景克莱公寓A座2604室<br> Email:908927417@qq.com </p> </li> <li class="f_w3"> <h1>&nbsp;</h1> <div class="share"> <!-- Baidu Button BEGIN --> <div id="bdshare" class="bdshare_t bds_tools_32 get-codes-bdshare"><div class="bdsharebuttonbox"><a class="bds_more" href="#" data-cmd="more"></a><a class="bds_qzone" title="分享到QQ空间" href="#" data-cmd="qzone"></a><a class="bds_tsina" title="分享到新浪微博" href="#" data-cmd="tsina"></a><a class="bds_tqq" title="分享到腾讯微博" href="#" data-cmd="tqq"></a><a class="bds_renren" title="分享到人人网" href="#" data-cmd="renren"></a><a class="bds_weixin" title="分享到微信" href="#" data-cmd="weixin"></a><a class="bds_fx" title="分享到飞信" href="#" data-cmd="fx"></a><a class="bds_bdhome" title="分享到百度新首页" href="#" data-cmd="bdhome"></a></div> <script>window._bd_share_config={"common":{"bdSnsKey":{},"bdText":"","bdMini":"2","bdMiniList":false,"bdPic":"","bdStyle":"0","bdSize":"32"},"share":{}};with(document)0[(getElementsByTagName('head')[0]||body).appendChild(createElement('script')).src='http://bdimg.share.baidu.com/static/api/js/share.js?v=89860593.js?cdnversion='+~(-new Date()/36e5)];</script></div> <!-- Baidu Button END --> </div> <p> Copyright © 2015 谱式达 all rights reserved. <br> 版权所有:广州谱式达人力资源服务有限公司<br> 粤ICP备1503025-1 </p> </li> </ul> </div> <!----尾部结束-----> <div class="psdkf"> <div class="psdl"> <a style="display: none" id="psdpanel_show" class="btnopen" title="查看在线客服" onclick="javascript:$('#psdpanel').animate({width: 'show', opacity: 'show'}, 'normal',function(){ $('#psdpanel').show();});$('#psdpanel_show').attr('style','display:none');$('#psdpanel_hide').attr('style','display:block');" href="javascript:void(0);">展开</a> <a id="psdpanel_hide" class="btnctn" title="关闭在线客服" onclick="javascript:$('#psdpanel').animate({width: 'hide', opacity: 'hide'}, 'normal',function(){$('#psdpanel').hide();});$('#psdpanel_show').attr('style','display:block');$('#psdpanel_hide').attr('style','display:none');" href="javascript:void(0);">收缩</a> </div> <div id="psdpanel" class="psdtr"> <div class="p_top"></div> <div class="p_main"> <ul> <li class="kf_t">达&middot;服务</li> <li><a class="icobd webMsg" href="javascript:void(0);" title="在线咨询-广州谱式达">商桥咨询</a></li> <li><a class="icoqq group1" target="_blank" href="http://wpa.qq.com/msgrd?v=3&uin=3160963951&site=qq&menu=yes" title="在线咨询-入户难,广州谱式达为你解决!">户口/社保</a></li> <li><a class="icoqq group2" target="_blank" href="http://wpa.qq.com/msgrd?v=3&uin=3079510171&site=qq&menu=yes" title="在线咨询-广州户口社保问题为您解答!">户口/社保</a></li> <li><a class="icoqq group3" href="http://wpa.qq.com/msgrd?v=3&uin=3160963951&site=qq&menu=yes" title="在线咨询-DM派单业务问题为您解答!">派单咨询</a></li> <li class="bot"><a class="icoqq group4" target="_blank" href="http://wpa.qq.com/msgrd?v=3&uin=3079510171&site=qq&menu=yes" title="在线咨询-资深业务经理问题为您解答!">咨询经理</a></li> </ul> <ul class="push114"> <li class="push114_c"><a href="/" target="_blank">谱式达官网</a></li> </ul> <ul class="psdtel"> <li class="psdtel_c"><span class="icotel">4006-020-308</span></li> </ul> </div> </div> </div> <script type="text/javascript" src="/js/webmsg.js"></script> <span> <script type="text/javascript">var _bdhmProtocol = (("https:" == document.location.protocol) ? " https://" : " http://"); document.write(unescape("%3Cscript src='" + _bdhmProtocol + "hm.baidu.com/h.js%3F9359da697d59255f1b44e8f39e24cb08' type='text/javascript'%3E%3C/script%3E")) </script> </span> </body> </html>
chuing/Push
a/zscq/sbzc/list_73_2.html
HTML
gpl-2.0
17,613
/* -*- mode: C; c-file-style: "gnu"; indent-tabs-mode: nil; -*- */ /* * st-widget.c: Base class for St actors * * Copyright 2007 OpenedHand * Copyright 2008, 2009 Intel Corporation. * Copyright 2009, 2010 Red Hat, Inc. * Copyright 2009 Abderrahim Kitouni * Copyright 2009, 2010 Florian Müllner * Copyright 2010 Adel Gadllah * Copyright 2012 Igalia, S.L. * * This program is free software; you can redistribute it and/or modify it * under the terms and conditions of the GNU Lesser General Public License, * version 2.1, as published by the Free Software Foundation. * * This program is distributed in the hope it will be useful, but WITHOUT ANY * WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS * FOR A PARTICULAR PURPOSE. See the GNU 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/>. */ #ifdef HAVE_CONFIG_H #include "config.h" #endif #include <stdlib.h> #include <string.h> #include <math.h> #include <clutter/clutter.h> #include "st-widget.h" #include "st-label.h" #include "st-private.h" #include "st-settings.h" #include "st-texture-cache.h" #include "st-theme-context.h" #include "st-theme-node-transition.h" #include "st-theme-node-private.h" #include "st-drawing-area.h" #include "st-widget-accessible.h" #include <atk/atk-enum-types.h> /* This is set in stone and also hard-coded in GDK. */ #define VIRTUAL_CORE_POINTER_ID 2 /* * Forward declaration for sake of StWidgetChild */ typedef struct _StWidgetPrivate StWidgetPrivate; struct _StWidgetPrivate { StThemeNode *theme_node; gchar *pseudo_class; gchar *style_class; gchar *inline_style; StThemeNodeTransition *transition_animation; guint is_style_dirty : 1; guint first_child_dirty : 1; guint last_child_dirty : 1; guint draw_bg_color : 1; guint draw_border_internal : 1; guint track_hover : 1; guint hover : 1; guint can_focus : 1; gulong texture_file_changed_id; guint update_child_styles_id; AtkObject *accessible; AtkRole accessible_role; AtkStateSet *local_state_set; ClutterActor *label_actor; gchar *accessible_name; StWidget *last_visible_child; StWidget *first_visible_child; StThemeNodePaintState paint_states[2]; int current_paint_state : 2; }; /** * SECTION:st-widget * @short_description: Base class for stylable actors * * #StWidget is a simple abstract class on top of #ClutterActor. It * provides basic themeing properties. * * Actors in the St library should subclass #StWidget if they plan * to obey to a certain #StStyle. */ enum { PROP_0, PROP_PSEUDO_CLASS, PROP_STYLE_CLASS, PROP_STYLE, PROP_TRACK_HOVER, PROP_HOVER, PROP_CAN_FOCUS, PROP_LABEL_ACTOR, PROP_ACCESSIBLE_ROLE, PROP_ACCESSIBLE_NAME, N_PROPS }; static GParamSpec *props[N_PROPS] = { NULL, }; enum { STYLE_CHANGED, POPUP_MENU, LAST_SIGNAL }; static guint signals[LAST_SIGNAL] = { 0, }; G_DEFINE_TYPE_WITH_PRIVATE (StWidget, st_widget, CLUTTER_TYPE_ACTOR); #define ST_WIDGET_PRIVATE(w) ((StWidgetPrivate *)st_widget_get_instance_private (w)) static void st_widget_recompute_style (StWidget *widget, StThemeNode *old_theme_node); static gboolean st_widget_real_navigate_focus (StWidget *widget, ClutterActor *from, StDirectionType direction); static AtkObject * st_widget_get_accessible (ClutterActor *actor); static gboolean st_widget_has_accessible (ClutterActor *actor); static void st_widget_update_insensitive (StWidget *widget) { if (clutter_actor_get_reactive (CLUTTER_ACTOR (widget))) st_widget_remove_style_pseudo_class (widget, "insensitive"); else st_widget_add_style_pseudo_class (widget, "insensitive"); } static void st_widget_set_property (GObject *gobject, guint prop_id, const GValue *value, GParamSpec *pspec) { StWidget *actor = ST_WIDGET (gobject); switch (prop_id) { case PROP_PSEUDO_CLASS: st_widget_set_style_pseudo_class (actor, g_value_get_string (value)); break; case PROP_STYLE_CLASS: st_widget_set_style_class_name (actor, g_value_get_string (value)); break; case PROP_STYLE: st_widget_set_style (actor, g_value_get_string (value)); break; case PROP_TRACK_HOVER: st_widget_set_track_hover (actor, g_value_get_boolean (value)); break; case PROP_HOVER: st_widget_set_hover (actor, g_value_get_boolean (value)); break; case PROP_CAN_FOCUS: st_widget_set_can_focus (actor, g_value_get_boolean (value)); break; case PROP_LABEL_ACTOR: st_widget_set_label_actor (actor, g_value_get_object (value)); break; case PROP_ACCESSIBLE_ROLE: st_widget_set_accessible_role (actor, g_value_get_enum (value)); break; case PROP_ACCESSIBLE_NAME: st_widget_set_accessible_name (actor, g_value_get_string (value)); break; default: G_OBJECT_WARN_INVALID_PROPERTY_ID (gobject, prop_id, pspec); break; } } static void st_widget_get_property (GObject *gobject, guint prop_id, GValue *value, GParamSpec *pspec) { StWidget *actor = ST_WIDGET (gobject); StWidgetPrivate *priv = st_widget_get_instance_private (ST_WIDGET (gobject)); switch (prop_id) { case PROP_PSEUDO_CLASS: g_value_set_string (value, priv->pseudo_class); break; case PROP_STYLE_CLASS: g_value_set_string (value, priv->style_class); break; case PROP_STYLE: g_value_set_string (value, priv->inline_style); break; case PROP_TRACK_HOVER: g_value_set_boolean (value, priv->track_hover); break; case PROP_HOVER: g_value_set_boolean (value, priv->hover); break; case PROP_CAN_FOCUS: g_value_set_boolean (value, priv->can_focus); break; case PROP_LABEL_ACTOR: g_value_set_object (value, priv->label_actor); break; case PROP_ACCESSIBLE_ROLE: g_value_set_enum (value, st_widget_get_accessible_role (actor)); break; case PROP_ACCESSIBLE_NAME: g_value_set_string (value, priv->accessible_name); break; default: G_OBJECT_WARN_INVALID_PROPERTY_ID (gobject, prop_id, pspec); break; } } static void st_widget_constructed (GObject *gobject) { G_OBJECT_CLASS (st_widget_parent_class)->constructed (gobject); st_widget_update_insensitive (ST_WIDGET (gobject)); } static void st_widget_remove_transition (StWidget *widget) { StWidgetPrivate *priv = st_widget_get_instance_private (widget); if (priv->transition_animation) { g_object_run_dispose (G_OBJECT (priv->transition_animation)); g_object_unref (priv->transition_animation); priv->transition_animation = NULL; } } static void next_paint_state (StWidget *widget) { StWidgetPrivate *priv = st_widget_get_instance_private (widget); priv->current_paint_state = (priv->current_paint_state + 1) % G_N_ELEMENTS (priv->paint_states); } static StThemeNodePaintState * current_paint_state (StWidget *widget) { StWidgetPrivate *priv = st_widget_get_instance_private (widget); return &priv->paint_states[priv->current_paint_state]; } static void st_widget_texture_cache_changed (StTextureCache *cache, GFile *file, gpointer user_data) { StWidget *actor = ST_WIDGET (user_data); StWidgetPrivate *priv = st_widget_get_instance_private (actor); gboolean changed = FALSE; int i; for (i = 0; i < G_N_ELEMENTS (priv->paint_states); i++) { StThemeNodePaintState *paint_state = &priv->paint_states[i]; changed |= st_theme_node_paint_state_invalidate_for_file (paint_state, file); } if (changed && clutter_actor_is_mapped (CLUTTER_ACTOR (actor))) clutter_actor_queue_redraw (CLUTTER_ACTOR (actor)); } static void st_widget_dispose (GObject *gobject) { StWidget *actor = ST_WIDGET (gobject); StWidgetPrivate *priv = st_widget_get_instance_private (actor); g_clear_pointer (&priv->theme_node, g_object_unref); st_widget_remove_transition (actor); g_clear_pointer (&priv->label_actor, g_object_unref); g_clear_signal_handler (&priv->texture_file_changed_id, st_texture_cache_get_default ()); g_clear_object (&priv->first_visible_child); g_clear_object (&priv->last_visible_child); G_OBJECT_CLASS (st_widget_parent_class)->dispose (gobject); g_clear_handle_id (&priv->update_child_styles_id, g_source_remove); } static void st_widget_finalize (GObject *gobject) { StWidgetPrivate *priv = st_widget_get_instance_private (ST_WIDGET (gobject)); guint i; g_free (priv->style_class); g_free (priv->pseudo_class); g_object_unref (priv->local_state_set); g_free (priv->accessible_name); g_free (priv->inline_style); for (i = 0; i < G_N_ELEMENTS (priv->paint_states); i++) st_theme_node_paint_state_free (&priv->paint_states[i]); G_OBJECT_CLASS (st_widget_parent_class)->finalize (gobject); } static void st_widget_get_preferred_width (ClutterActor *self, gfloat for_height, gfloat *min_width_p, gfloat *natural_width_p) { StThemeNode *theme_node = st_widget_get_theme_node (ST_WIDGET (self)); st_theme_node_adjust_for_width (theme_node, &for_height); CLUTTER_ACTOR_CLASS (st_widget_parent_class)->get_preferred_width (self, for_height, min_width_p, natural_width_p); st_theme_node_adjust_preferred_width (theme_node, min_width_p, natural_width_p); } static void st_widget_get_preferred_height (ClutterActor *self, gfloat for_width, gfloat *min_height_p, gfloat *natural_height_p) { StThemeNode *theme_node = st_widget_get_theme_node (ST_WIDGET (self)); st_theme_node_adjust_for_width (theme_node, &for_width); CLUTTER_ACTOR_CLASS (st_widget_parent_class)->get_preferred_height (self, for_width, min_height_p, natural_height_p); st_theme_node_adjust_preferred_height (theme_node, min_height_p, natural_height_p); } static void st_widget_allocate (ClutterActor *actor, const ClutterActorBox *box) { StThemeNode *theme_node = st_widget_get_theme_node (ST_WIDGET (actor)); ClutterActorBox content_box; /* Note that we can't just chain up to clutter_actor_real_allocate -- * Clutter does some dirty tricks for backwards compatibility. * Clutter also passes the actor's allocation directly to the layout * manager, meaning that we can't modify it for children only. */ clutter_actor_set_allocation (actor, box); st_theme_node_get_content_box (theme_node, box, &content_box); /* If we've chained up to here, we want to allocate the children using the * currently installed layout manager */ clutter_layout_manager_allocate (clutter_actor_get_layout_manager (actor), CLUTTER_CONTAINER (actor), &content_box); } /** * st_widget_paint_background: * @widget: The #StWidget * * Paint the background of the widget. This is meant to be called by * subclasses of StWidget that need to paint the background without * painting children. */ void st_widget_paint_background (StWidget *widget, ClutterPaintContext *paint_context) { StWidgetPrivate *priv = st_widget_get_instance_private (widget); CoglFramebuffer *framebuffer; StThemeNode *theme_node; ClutterActorBox allocation; float resource_scale; guint8 opacity; resource_scale = clutter_actor_get_resource_scale (CLUTTER_ACTOR (widget)); framebuffer = clutter_paint_context_get_framebuffer (paint_context); theme_node = st_widget_get_theme_node (widget); clutter_actor_get_allocation_box (CLUTTER_ACTOR (widget), &allocation); opacity = clutter_actor_get_paint_opacity (CLUTTER_ACTOR (widget)); if (priv->transition_animation) st_theme_node_transition_paint (priv->transition_animation, framebuffer, &allocation, opacity, resource_scale); else st_theme_node_paint (theme_node, current_paint_state (widget), framebuffer, &allocation, opacity, resource_scale); } static void st_widget_paint (ClutterActor *actor, ClutterPaintContext *paint_context) { st_widget_paint_background (ST_WIDGET (actor), paint_context); /* Chain up so we paint children. */ CLUTTER_ACTOR_CLASS (st_widget_parent_class)->paint (actor, paint_context); } static void st_widget_parent_set (ClutterActor *widget, ClutterActor *old_parent) { StWidget *self = ST_WIDGET (widget); ClutterActorClass *parent_class; parent_class = CLUTTER_ACTOR_CLASS (st_widget_parent_class); if (parent_class->parent_set) parent_class->parent_set (widget, old_parent); st_widget_style_changed (self); } static void st_widget_map (ClutterActor *actor) { StWidget *self = ST_WIDGET (actor); CLUTTER_ACTOR_CLASS (st_widget_parent_class)->map (actor); st_widget_ensure_style (self); } static void st_widget_unmap (ClutterActor *actor) { StWidget *self = ST_WIDGET (actor); StWidgetPrivate *priv = st_widget_get_instance_private (self); CLUTTER_ACTOR_CLASS (st_widget_parent_class)->unmap (actor); if (priv->track_hover && priv->hover) st_widget_set_hover (self, FALSE); } static void notify_children_of_style_change (ClutterActor *self) { ClutterActorIter iter; ClutterActor *actor; clutter_actor_iter_init (&iter, self); while (clutter_actor_iter_next (&iter, &actor)) { if (ST_IS_WIDGET (actor)) st_widget_style_changed (ST_WIDGET (actor)); else notify_children_of_style_change (actor); } } static void st_widget_real_style_changed (StWidget *self) { clutter_actor_queue_redraw ((ClutterActor *) self); } void st_widget_style_changed (StWidget *widget) { StWidgetPrivate *priv = st_widget_get_instance_private (widget); StThemeNode *old_theme_node = NULL; priv->is_style_dirty = TRUE; if (priv->theme_node) { old_theme_node = priv->theme_node; priv->theme_node = NULL; } /* update the style only if we are mapped */ if (clutter_actor_is_mapped (CLUTTER_ACTOR (widget))) st_widget_recompute_style (widget, old_theme_node); /* Descend through all children. If the actor is not mapped, * children will clear their theme node without recomputing style. */ notify_children_of_style_change (CLUTTER_ACTOR (widget)); if (old_theme_node) g_object_unref (old_theme_node); } static void on_theme_context_changed (StThemeContext *context, ClutterStage *stage) { notify_children_of_style_change (CLUTTER_ACTOR (stage)); } static StThemeNode * get_root_theme_node (ClutterStage *stage) { StThemeContext *context = st_theme_context_get_for_stage (stage); if (!g_object_get_data (G_OBJECT (context), "st-theme-initialized")) { g_object_set_data (G_OBJECT (context), "st-theme-initialized", GUINT_TO_POINTER (1)); g_signal_connect (G_OBJECT (context), "changed", G_CALLBACK (on_theme_context_changed), stage); } return st_theme_context_get_root_node (context); } /** * st_widget_get_theme_node: * @widget: a #StWidget * * Gets the theme node holding style information for the widget. * The theme node is used to access standard and custom CSS * properties of the widget. * * Note: it is a fatal error to call this on a widget that is * not been added to a stage. * * Returns: (transfer none): the theme node for the widget. * This is owned by the widget. When attributes of the widget * or the environment that affect the styling change (for example * the style_class property of the widget), it will be recreated, * and the ::style-changed signal will be emitted on the widget. */ StThemeNode * st_widget_get_theme_node (StWidget *widget) { StWidgetPrivate *priv; g_return_val_if_fail (ST_IS_WIDGET (widget), NULL); priv = st_widget_get_instance_private (widget); if (priv->theme_node == NULL) { StThemeContext *context; StThemeNode *tmp_node; StThemeNode *parent_node = NULL; ClutterStage *stage = NULL; ClutterActor *parent; char *pseudo_class, *direction_pseudo_class; parent = clutter_actor_get_parent (CLUTTER_ACTOR (widget)); while (parent != NULL) { if (parent_node == NULL && ST_IS_WIDGET (parent)) parent_node = st_widget_get_theme_node (ST_WIDGET (parent)); else if (CLUTTER_IS_STAGE (parent)) stage = CLUTTER_STAGE (parent); parent = clutter_actor_get_parent (parent); } if (stage == NULL) { g_autofree char *desc = st_describe_actor (CLUTTER_ACTOR (widget)); g_critical ("st_widget_get_theme_node called on the widget %s which is not in the stage.", desc); return g_object_new (ST_TYPE_THEME_NODE, NULL); } if (parent_node == NULL) parent_node = get_root_theme_node (CLUTTER_STAGE (stage)); /* Always append a "magic" pseudo class indicating the text * direction, to allow to adapt the CSS when necessary without * requiring separate style sheets. */ if (clutter_actor_get_text_direction (CLUTTER_ACTOR (widget)) == CLUTTER_TEXT_DIRECTION_RTL) direction_pseudo_class = (char *)"rtl"; else direction_pseudo_class = (char *)"ltr"; if (priv->pseudo_class) pseudo_class = g_strconcat(priv->pseudo_class, " ", direction_pseudo_class, NULL); else pseudo_class = direction_pseudo_class; context = st_theme_context_get_for_stage (stage); tmp_node = st_theme_node_new (context, parent_node, NULL, G_OBJECT_TYPE (widget), clutter_actor_get_name (CLUTTER_ACTOR (widget)), priv->style_class, pseudo_class, priv->inline_style); if (pseudo_class != direction_pseudo_class) g_free (pseudo_class); priv->theme_node = g_object_ref (st_theme_context_intern_node (context, tmp_node)); g_object_unref (tmp_node); } return priv->theme_node; } /** * st_widget_peek_theme_node: * @widget: a #StWidget * * Returns the theme node for the widget if it has already been * computed, %NULL if the widget hasn't been added to a stage or the theme * node hasn't been computed. If %NULL is returned, then ::style-changed * will be reliably emitted before the widget is allocated or painted. * * Returns: (transfer none): the theme node for the widget. * This is owned by the widget. When attributes of the widget * or the environment that affect the styling change (for example * the style_class property of the widget), it will be recreated, * and the ::style-changed signal will be emitted on the widget. */ StThemeNode * st_widget_peek_theme_node (StWidget *widget) { g_return_val_if_fail (ST_IS_WIDGET (widget), NULL); return ST_WIDGET_PRIVATE (widget)->theme_node; } static gboolean st_widget_enter (ClutterActor *actor, ClutterCrossingEvent *event) { StWidgetPrivate *priv = st_widget_get_instance_private (ST_WIDGET (actor)); if (priv->track_hover) { ClutterStage *stage; ClutterActor *target; stage = clutter_event_get_stage ((ClutterEvent *) event); target = clutter_stage_get_event_actor (stage, (ClutterEvent *) event); if (clutter_actor_contains (actor, target)) st_widget_set_hover (ST_WIDGET (actor), TRUE); else { /* The widget has a grab and is being told about an * enter-event outside its hierarchy. Hopefully we already * got a leave-event, but if not, handle it now. */ st_widget_set_hover (ST_WIDGET (actor), FALSE); } } if (CLUTTER_ACTOR_CLASS (st_widget_parent_class)->enter_event) return CLUTTER_ACTOR_CLASS (st_widget_parent_class)->enter_event (actor, event); else return FALSE; } static gboolean st_widget_leave (ClutterActor *actor, ClutterCrossingEvent *event) { StWidgetPrivate *priv = st_widget_get_instance_private (ST_WIDGET (actor)); if (priv->track_hover) { if (!event->related || !clutter_actor_contains (actor, event->related)) st_widget_set_hover (ST_WIDGET (actor), FALSE); } if (CLUTTER_ACTOR_CLASS (st_widget_parent_class)->leave_event) return CLUTTER_ACTOR_CLASS (st_widget_parent_class)->leave_event (actor, event); else return FALSE; } static void st_widget_key_focus_in (ClutterActor *actor) { StWidget *widget = ST_WIDGET (actor); st_widget_add_style_pseudo_class (widget, "focus"); } static void st_widget_key_focus_out (ClutterActor *actor) { StWidget *widget = ST_WIDGET (actor); st_widget_remove_style_pseudo_class (widget, "focus"); } static gboolean st_widget_key_press_event (ClutterActor *actor, ClutterKeyEvent *event) { if (event->keyval == CLUTTER_KEY_Menu || (event->keyval == CLUTTER_KEY_F10 && (event->modifier_state & CLUTTER_SHIFT_MASK))) { st_widget_popup_menu (ST_WIDGET (actor)); return TRUE; } return FALSE; } static gboolean st_widget_get_paint_volume (ClutterActor *self, ClutterPaintVolume *volume) { ClutterActorBox paint_box, alloc_box; StThemeNode *theme_node; StWidgetPrivate *priv; graphene_point3d_t origin; /* Setting the paint volume does not make sense when we don't have any allocation */ if (!clutter_actor_has_allocation (self)) return FALSE; priv = st_widget_get_instance_private (ST_WIDGET (self)); theme_node = st_widget_get_theme_node (ST_WIDGET (self)); clutter_actor_get_allocation_box (self, &alloc_box); if (priv->transition_animation) st_theme_node_transition_get_paint_box (priv->transition_animation, &alloc_box, &paint_box); else st_theme_node_get_paint_box (theme_node, &alloc_box, &paint_box); origin.x = paint_box.x1 - alloc_box.x1; origin.y = paint_box.y1 - alloc_box.y1; origin.z = 0.0f; clutter_paint_volume_set_origin (volume, &origin); clutter_paint_volume_set_width (volume, paint_box.x2 - paint_box.x1); clutter_paint_volume_set_height (volume, paint_box.y2 - paint_box.y1); if (!clutter_actor_get_clip_to_allocation (self)) { ClutterActor *child; StShadow *shadow_spec = st_theme_node_get_text_shadow (theme_node); if (shadow_spec) { ClutterActorBox shadow_box; st_shadow_get_box (shadow_spec, &alloc_box, &shadow_box); clutter_paint_volume_union_box (volume, &shadow_box); } /* Based on ClutterGroup/ClutterBox; include the children's * paint volumes, since they may paint outside our allocation. */ for (child = clutter_actor_get_first_child (self); child != NULL; child = clutter_actor_get_next_sibling (child)) { const ClutterPaintVolume *child_volume; if (!clutter_actor_is_visible (child)) continue; child_volume = clutter_actor_get_transformed_paint_volume (child, self); if (!child_volume) return FALSE; clutter_paint_volume_union (volume, child_volume); } } return TRUE; } static GList * st_widget_real_get_focus_chain (StWidget *widget) { GList *children, *l, *visible = NULL; children = clutter_actor_get_children (CLUTTER_ACTOR (widget)); for (l = children; l; l = l->next) { if (clutter_actor_is_visible (CLUTTER_ACTOR (l->data))) visible = g_list_prepend (visible, l->data); } g_list_free (children); return g_list_reverse (visible); } static void st_widget_resource_scale_changed (ClutterActor *actor) { StWidget *widget = ST_WIDGET (actor); StWidgetPrivate *priv = st_widget_get_instance_private (widget); int i; for (i = 0; i < G_N_ELEMENTS (priv->paint_states); i++) st_theme_node_paint_state_invalidate (&priv->paint_states[i]); if (CLUTTER_ACTOR_CLASS (st_widget_parent_class)->resource_scale_changed) CLUTTER_ACTOR_CLASS (st_widget_parent_class)->resource_scale_changed (actor); } static void st_widget_class_init (StWidgetClass *klass) { GObjectClass *gobject_class = G_OBJECT_CLASS (klass); ClutterActorClass *actor_class = CLUTTER_ACTOR_CLASS (klass); gobject_class->set_property = st_widget_set_property; gobject_class->get_property = st_widget_get_property; gobject_class->constructed = st_widget_constructed; gobject_class->dispose = st_widget_dispose; gobject_class->finalize = st_widget_finalize; actor_class->get_preferred_width = st_widget_get_preferred_width; actor_class->get_preferred_height = st_widget_get_preferred_height; actor_class->allocate = st_widget_allocate; actor_class->paint = st_widget_paint; actor_class->get_paint_volume = st_widget_get_paint_volume; actor_class->parent_set = st_widget_parent_set; actor_class->map = st_widget_map; actor_class->unmap = st_widget_unmap; actor_class->enter_event = st_widget_enter; actor_class->leave_event = st_widget_leave; actor_class->key_focus_in = st_widget_key_focus_in; actor_class->key_focus_out = st_widget_key_focus_out; actor_class->key_press_event = st_widget_key_press_event; actor_class->get_accessible = st_widget_get_accessible; actor_class->has_accessible = st_widget_has_accessible; actor_class->resource_scale_changed = st_widget_resource_scale_changed; klass->style_changed = st_widget_real_style_changed; klass->navigate_focus = st_widget_real_navigate_focus; klass->get_accessible_type = st_widget_accessible_get_type; klass->get_focus_chain = st_widget_real_get_focus_chain; /** * StWidget:pseudo-class: * * The pseudo-class of the actor. Typical values include "hover", "active", * "focus". */ props[PROP_PSEUDO_CLASS] = g_param_spec_string ("pseudo-class", "Pseudo Class", "Pseudo class for styling", "", ST_PARAM_READWRITE | G_PARAM_EXPLICIT_NOTIFY); /** * StWidget:style-class: * * The style-class of the actor for use in styling. */ props[PROP_STYLE_CLASS] = g_param_spec_string ("style-class", "Style Class", "Style class for styling", "", ST_PARAM_READWRITE | G_PARAM_EXPLICIT_NOTIFY); /** * StWidget:style: * * Inline style information for the actor as a ';'-separated list of * CSS properties. */ props[PROP_STYLE] = g_param_spec_string ("style", "Style", "Inline style string", "", ST_PARAM_READWRITE | G_PARAM_EXPLICIT_NOTIFY); /** * StWidget:track-hover: * * Determines whether the widget tracks pointer hover state. If * %TRUE (and the widget is visible and reactive), the * #StWidget:hover property and "hover" style pseudo class will be * adjusted automatically as the pointer moves in and out of the * widget. */ props[PROP_TRACK_HOVER] = g_param_spec_boolean ("track-hover", "Track hover", "Determines whether the widget tracks hover state", FALSE, ST_PARAM_READWRITE | G_PARAM_EXPLICIT_NOTIFY); /** * StWidget:hover: * * Whether or not the pointer is currently hovering over the widget. This is * only tracked automatically if #StWidget:track-hover is %TRUE, but you can * adjust it manually in any case. */ props[PROP_HOVER] = g_param_spec_boolean ("hover", "Hover", "Whether the pointer is hovering over the widget", FALSE, ST_PARAM_READWRITE | G_PARAM_EXPLICIT_NOTIFY); /** * StWidget:can-focus: * * Whether or not the widget can be focused via keyboard navigation. */ props[PROP_CAN_FOCUS] = g_param_spec_boolean ("can-focus", "Can focus", "Whether the widget can be focused via keyboard navigation", FALSE, ST_PARAM_READWRITE | G_PARAM_EXPLICIT_NOTIFY); /** * StWidget:label-actor: * * An actor that labels this widget. */ props[PROP_LABEL_ACTOR] = g_param_spec_object ("label-actor", "Label", "Label that identifies this widget", CLUTTER_TYPE_ACTOR, ST_PARAM_READWRITE | G_PARAM_EXPLICIT_NOTIFY); /** * StWidget:accessible-role: * * The accessible role of this object */ props[PROP_ACCESSIBLE_ROLE] = g_param_spec_enum ("accessible-role", "Accessible Role", "The accessible role of this object", ATK_TYPE_ROLE, ATK_ROLE_INVALID, ST_PARAM_READWRITE | G_PARAM_EXPLICIT_NOTIFY); /** * StWidget:accessible-name: * * Object instance's name for assistive technology access. */ props[PROP_ACCESSIBLE_NAME] = g_param_spec_string ("accessible-name", "Accessible name", "Object instance's name for assistive technology access.", NULL, ST_PARAM_READWRITE | G_PARAM_EXPLICIT_NOTIFY); g_object_class_install_properties (gobject_class, N_PROPS, props); /** * StWidget::style-changed: * @widget: the #StWidget * * Emitted when the style information that the widget derives from the * theme changes */ signals[STYLE_CHANGED] = g_signal_new ("style-changed", G_TYPE_FROM_CLASS (klass), G_SIGNAL_RUN_LAST, G_STRUCT_OFFSET (StWidgetClass, style_changed), NULL, NULL, NULL, G_TYPE_NONE, 0); /** * StWidget::popup-menu: * @widget: the #StWidget * * Emitted when the user has requested a context menu (eg, via a keybinding) */ signals[POPUP_MENU] = g_signal_new ("popup-menu", G_TYPE_FROM_CLASS (klass), G_SIGNAL_RUN_LAST, G_STRUCT_OFFSET (StWidgetClass, popup_menu), NULL, NULL, NULL, G_TYPE_NONE, 0); } static const gchar * find_class_name (const gchar *class_list, const gchar *class_name) { gint len = strlen (class_name); const gchar *match; if (!class_list) return NULL; for (match = strstr (class_list, class_name); match; match = strstr (match + 1, class_name)) { if ((match == class_list || g_ascii_isspace (match[-1])) && (match[len] == '\0' || g_ascii_isspace (match[len]))) return match; } return NULL; } static gboolean set_class_list (gchar **class_list, const gchar *new_class_list) { if (g_strcmp0 (*class_list, new_class_list) != 0) { g_free (*class_list); *class_list = g_strdup (new_class_list); return TRUE; } else return FALSE; } static gboolean add_class_name (gchar **class_list, const gchar *class_name) { gchar *new_class_list; if (*class_list) { if (find_class_name (*class_list, class_name)) return FALSE; new_class_list = g_strdup_printf ("%s %s", *class_list, class_name); g_free (*class_list); *class_list = new_class_list; } else *class_list = g_strdup (class_name); return TRUE; } static gboolean remove_class_name (gchar **class_list, const gchar *class_name) { const gchar *match, *end; gchar *new_class_list; if (!*class_list) return FALSE; if (strcmp (*class_list, class_name) == 0) { g_free (*class_list); *class_list = NULL; return TRUE; } match = find_class_name (*class_list, class_name); if (!match) return FALSE; end = match + strlen (class_name); /* Adjust either match or end to include a space as well. * (One or the other must be possible at this point.) */ if (match != *class_list) match--; else end++; new_class_list = g_strdup_printf ("%.*s%s", (int)(match - *class_list), *class_list, end); g_free (*class_list); *class_list = new_class_list; return TRUE; } /** * st_widget_set_style_class_name: * @actor: a #StWidget * @style_class_list: (nullable): a new style class list string * * Set the style class name list. @style_class_list can either be * %NULL, for no classes, or a space-separated list of style class * names. See also st_widget_add_style_class_name() and * st_widget_remove_style_class_name(). */ void st_widget_set_style_class_name (StWidget *actor, const gchar *style_class_list) { StWidgetPrivate *priv; g_return_if_fail (ST_IS_WIDGET (actor)); priv = st_widget_get_instance_private (actor); if (set_class_list (&priv->style_class, style_class_list)) { st_widget_style_changed (actor); g_object_notify_by_pspec (G_OBJECT (actor), props[PROP_STYLE_CLASS]); } } /** * st_widget_add_style_class_name: * @actor: a #StWidget * @style_class: a style class name string * * Adds @style_class to @actor's style class name list, if it is not * already present. */ void st_widget_add_style_class_name (StWidget *actor, const gchar *style_class) { StWidgetPrivate *priv; g_return_if_fail (ST_IS_WIDGET (actor)); g_return_if_fail (style_class != NULL); priv = st_widget_get_instance_private (actor); if (add_class_name (&priv->style_class, style_class)) { st_widget_style_changed (actor); g_object_notify_by_pspec (G_OBJECT (actor), props[PROP_STYLE_CLASS]); } } /** * st_widget_remove_style_class_name: * @actor: a #StWidget * @style_class: a style class name string * * Removes @style_class from @actor's style class name, if it is * present. */ void st_widget_remove_style_class_name (StWidget *actor, const gchar *style_class) { StWidgetPrivate *priv; g_return_if_fail (ST_IS_WIDGET (actor)); g_return_if_fail (style_class != NULL); priv = st_widget_get_instance_private (actor); if (remove_class_name (&priv->style_class, style_class)) { st_widget_style_changed (actor); g_object_notify_by_pspec (G_OBJECT (actor), props[PROP_STYLE_CLASS]); } } /** * st_widget_get_style_class_name: * @actor: a #StWidget * * Get the current style class name * * Returns: the class name string. The string is owned by the #StWidget and * should not be modified or freed. */ const gchar* st_widget_get_style_class_name (StWidget *actor) { g_return_val_if_fail (ST_IS_WIDGET (actor), NULL); return ST_WIDGET_PRIVATE (actor)->style_class; } /** * st_widget_has_style_class_name: * @actor: a #StWidget * @style_class: a style class string * * Tests if @actor's style class list includes @style_class. * * Returns: whether or not @actor's style class list includes * @style_class. */ gboolean st_widget_has_style_class_name (StWidget *actor, const gchar *style_class) { StWidgetPrivate *priv; g_return_val_if_fail (ST_IS_WIDGET (actor), FALSE); priv = st_widget_get_instance_private (actor); return find_class_name (priv->style_class, style_class) != NULL; } /** * st_widget_get_style_pseudo_class: * @actor: a #StWidget * * Get the current style pseudo class list. * * Note that an actor can have multiple pseudo classes; if you just * want to test for the presence of a specific pseudo class, use * st_widget_has_style_pseudo_class(). * * Returns: the pseudo class list string. The string is owned by the * #StWidget and should not be modified or freed. */ const gchar* st_widget_get_style_pseudo_class (StWidget *actor) { g_return_val_if_fail (ST_IS_WIDGET (actor), NULL); return ST_WIDGET_PRIVATE (actor)->pseudo_class; } /** * st_widget_has_style_pseudo_class: * @actor: a #StWidget * @pseudo_class: a pseudo class string * * Tests if @actor's pseudo class list includes @pseudo_class. * * Returns: whether or not @actor's pseudo class list includes * @pseudo_class. */ gboolean st_widget_has_style_pseudo_class (StWidget *actor, const gchar *pseudo_class) { StWidgetPrivate *priv; g_return_val_if_fail (ST_IS_WIDGET (actor), FALSE); priv = st_widget_get_instance_private (actor); return find_class_name (priv->pseudo_class, pseudo_class) != NULL; } /** * st_widget_set_style_pseudo_class: * @actor: a #StWidget * @pseudo_class_list: (nullable): a new pseudo class list string * * Set the style pseudo class list. @pseudo_class_list can either be * %NULL, for no classes, or a space-separated list of pseudo class * names. See also st_widget_add_style_pseudo_class() and * st_widget_remove_style_pseudo_class(). */ void st_widget_set_style_pseudo_class (StWidget *actor, const gchar *pseudo_class_list) { StWidgetPrivate *priv; g_return_if_fail (ST_IS_WIDGET (actor)); priv = st_widget_get_instance_private (actor); if (set_class_list (&priv->pseudo_class, pseudo_class_list)) { st_widget_style_changed (actor); g_object_notify_by_pspec (G_OBJECT (actor), props[PROP_PSEUDO_CLASS]); } } /** * st_widget_add_style_pseudo_class: * @actor: a #StWidget * @pseudo_class: a pseudo class string * * Adds @pseudo_class to @actor's pseudo class list, if it is not * already present. */ void st_widget_add_style_pseudo_class (StWidget *actor, const gchar *pseudo_class) { StWidgetPrivate *priv; g_return_if_fail (ST_IS_WIDGET (actor)); g_return_if_fail (pseudo_class != NULL); priv = st_widget_get_instance_private (actor); if (add_class_name (&priv->pseudo_class, pseudo_class)) { st_widget_style_changed (actor); g_object_notify_by_pspec (G_OBJECT (actor), props[PROP_PSEUDO_CLASS]); } } /** * st_widget_remove_style_pseudo_class: * @actor: a #StWidget * @pseudo_class: a pseudo class string * * Removes @pseudo_class from @actor's pseudo class, if it is present. */ void st_widget_remove_style_pseudo_class (StWidget *actor, const gchar *pseudo_class) { StWidgetPrivate *priv; g_return_if_fail (ST_IS_WIDGET (actor)); g_return_if_fail (pseudo_class != NULL); priv = st_widget_get_instance_private (actor); if (remove_class_name (&priv->pseudo_class, pseudo_class)) { st_widget_style_changed (actor); g_object_notify_by_pspec (G_OBJECT (actor), props[PROP_PSEUDO_CLASS]); } } /** * st_widget_set_style: * @actor: a #StWidget * @style: (nullable): a inline style string, or %NULL * * Set the inline style string for this widget. The inline style string is an * optional ';'-separated list of CSS properties that override the style as * determined from the stylesheets of the current theme. */ void st_widget_set_style (StWidget *actor, const gchar *style) { StWidgetPrivate *priv; g_return_if_fail (ST_IS_WIDGET (actor)); priv = st_widget_get_instance_private (actor); if (g_strcmp0 (style, priv->inline_style)) { g_free (priv->inline_style); priv->inline_style = g_strdup (style); st_widget_style_changed (actor); g_object_notify_by_pspec (G_OBJECT (actor), props[PROP_STYLE]); } } /** * st_widget_get_style: * @actor: a #StWidget * * Get the current inline style string. See st_widget_set_style(). * * Returns: (transfer none) (nullable): The inline style string, or %NULL. The * string is owned by the #StWidget and should not be modified or freed. */ const gchar* st_widget_get_style (StWidget *actor) { g_return_val_if_fail (ST_IS_WIDGET (actor), NULL); return ST_WIDGET_PRIVATE (actor)->inline_style; } static void st_widget_set_first_visible_child (StWidget *widget, ClutterActor *actor) { StWidgetPrivate *priv = st_widget_get_instance_private (widget); if (priv->first_visible_child == NULL && actor == NULL) return; if (priv->first_visible_child != NULL && CLUTTER_ACTOR (priv->first_visible_child) == actor) return; if (priv->first_visible_child != NULL) { st_widget_remove_style_pseudo_class (priv->first_visible_child, "first-child"); g_clear_object (&priv->first_visible_child); } if (actor == NULL) return; if (ST_IS_WIDGET (actor)) { st_widget_add_style_pseudo_class (ST_WIDGET (actor), "first-child"); priv->first_visible_child = g_object_ref (ST_WIDGET (actor)); } } static void st_widget_set_last_visible_child (StWidget *widget, ClutterActor *actor) { StWidgetPrivate *priv = st_widget_get_instance_private (widget); if (priv->last_visible_child == NULL && actor == NULL) return; if (priv->last_visible_child != NULL && CLUTTER_ACTOR (priv->last_visible_child) == actor) return; if (priv->last_visible_child != NULL) { st_widget_remove_style_pseudo_class (priv->last_visible_child, "last-child"); g_clear_object (&priv->last_visible_child); } if (actor == NULL) return; if (ST_IS_WIDGET (actor)) { st_widget_add_style_pseudo_class (ST_WIDGET (actor), "last-child"); priv->last_visible_child = g_object_ref (ST_WIDGET (actor)); } } static void st_widget_name_notify (StWidget *widget, GParamSpec *pspec, gpointer data) { st_widget_style_changed (widget); } static void st_widget_reactive_notify (StWidget *widget, GParamSpec *pspec, gpointer data) { StWidgetPrivate *priv = st_widget_get_instance_private (widget); st_widget_update_insensitive (widget); if (priv->track_hover) st_widget_sync_hover(widget); } static ClutterActor * find_nearest_visible_backwards (ClutterActor *actor) { ClutterActor *prev = actor; while (prev != NULL && !clutter_actor_is_visible (prev)) prev = clutter_actor_get_previous_sibling (prev); return prev; } static ClutterActor * find_nearest_visible_forward (ClutterActor *actor) { ClutterActor *next = actor; while (next != NULL && !clutter_actor_is_visible (next)) next = clutter_actor_get_next_sibling (next); return next; } static gboolean st_widget_update_child_styles (StWidget *widget) { StWidgetPrivate *priv = st_widget_get_instance_private (widget); if (priv->first_child_dirty) { ClutterActor *first_child; priv->first_child_dirty = FALSE; first_child = clutter_actor_get_first_child (CLUTTER_ACTOR (widget)); st_widget_set_first_visible_child (widget, find_nearest_visible_forward (first_child)); } if (priv->last_child_dirty) { ClutterActor *last_child; priv->last_child_dirty = FALSE; last_child = clutter_actor_get_last_child (CLUTTER_ACTOR (widget)); st_widget_set_last_visible_child (widget, find_nearest_visible_backwards (last_child)); } priv->update_child_styles_id = 0; return G_SOURCE_REMOVE; } static void st_widget_queue_child_styles_update (StWidget *widget) { StWidgetPrivate *priv = st_widget_get_instance_private (widget); if (priv->update_child_styles_id != 0) return; priv->update_child_styles_id = g_idle_add ((GSourceFunc) st_widget_update_child_styles, widget); } static void st_widget_visible_notify (StWidget *widget, GParamSpec *pspec, gpointer data) { StWidgetPrivate *parent_priv; ClutterActor *actor = CLUTTER_ACTOR (widget); ClutterActor *parent = clutter_actor_get_parent (actor); if (parent == NULL || !ST_IS_WIDGET (parent)) return; parent_priv = st_widget_get_instance_private (ST_WIDGET (parent)); if (clutter_actor_is_visible (actor)) { ClutterActor *before, *after; before = clutter_actor_get_previous_sibling (actor); if (find_nearest_visible_backwards (before) == NULL) parent_priv->first_child_dirty = TRUE; after = clutter_actor_get_next_sibling (actor); if (find_nearest_visible_forward (after) == NULL) parent_priv->last_child_dirty = TRUE; } else { if (st_widget_has_style_pseudo_class (widget, "first-child")) parent_priv->first_child_dirty = TRUE; if (st_widget_has_style_pseudo_class (widget, "last-child")) parent_priv->last_child_dirty = TRUE; } if (parent_priv->first_child_dirty || parent_priv->last_child_dirty) st_widget_queue_child_styles_update (ST_WIDGET (parent)); } static void st_widget_first_child_notify (StWidget *widget, GParamSpec *pspec, gpointer data) { StWidgetPrivate *priv = st_widget_get_instance_private (widget); priv->first_child_dirty = TRUE; st_widget_queue_child_styles_update (widget); } static void st_widget_last_child_notify (StWidget *widget, GParamSpec *pspec, gpointer data) { StWidgetPrivate *priv = st_widget_get_instance_private (widget); priv->last_child_dirty = TRUE; st_widget_queue_child_styles_update (widget); } static void st_widget_init (StWidget *actor) { StWidgetPrivate *priv; guint i; priv = st_widget_get_instance_private (actor); priv->transition_animation = NULL; priv->local_state_set = atk_state_set_new (); /* connect style changed */ g_signal_connect (actor, "notify::name", G_CALLBACK (st_widget_name_notify), NULL); g_signal_connect (actor, "notify::reactive", G_CALLBACK (st_widget_reactive_notify), NULL); g_signal_connect (actor, "notify::visible", G_CALLBACK (st_widget_visible_notify), NULL); g_signal_connect (actor, "notify::first-child", G_CALLBACK (st_widget_first_child_notify), NULL); g_signal_connect (actor, "notify::last-child", G_CALLBACK (st_widget_last_child_notify), NULL); priv->texture_file_changed_id = g_signal_connect (st_texture_cache_get_default (), "texture-file-changed", G_CALLBACK (st_widget_texture_cache_changed), actor); for (i = 0; i < G_N_ELEMENTS (priv->paint_states); i++) st_theme_node_paint_state_init (&priv->paint_states[i]); } static void on_transition_completed (StThemeNodeTransition *transition, StWidget *widget) { next_paint_state (widget); st_theme_node_paint_state_copy (current_paint_state (widget), st_theme_node_transition_get_new_paint_state (transition)); st_widget_remove_transition (widget); } static void st_widget_recompute_style (StWidget *widget, StThemeNode *old_theme_node) { StWidgetPrivate *priv = st_widget_get_instance_private (widget); StThemeNode *new_theme_node = st_widget_get_theme_node (widget); int transition_duration; StSettings *settings; gboolean paint_equal, geometry_equal = FALSE; gboolean animations_enabled; if (new_theme_node == old_theme_node) { priv->is_style_dirty = FALSE; return; } _st_theme_node_apply_margins (new_theme_node, CLUTTER_ACTOR (widget)); if (old_theme_node) geometry_equal = st_theme_node_geometry_equal (old_theme_node, new_theme_node); if (!geometry_equal) clutter_actor_queue_relayout ((ClutterActor *) widget); transition_duration = st_theme_node_get_transition_duration (new_theme_node); paint_equal = st_theme_node_paint_equal (old_theme_node, new_theme_node); settings = st_settings_get (); g_object_get (settings, "enable-animations", &animations_enabled, NULL); if (animations_enabled && transition_duration > 0) { if (priv->transition_animation != NULL) { st_theme_node_transition_update (priv->transition_animation, new_theme_node); } else if (old_theme_node && !paint_equal) { /* Since our transitions are only of the painting done by StThemeNode, we * only want to start a transition when what is painted changes; if * other visual aspects like the foreground color of a label change, * we can't animate that anyways. */ priv->transition_animation = st_theme_node_transition_new (CLUTTER_ACTOR (widget), old_theme_node, new_theme_node, current_paint_state (widget), transition_duration); g_signal_connect (priv->transition_animation, "completed", G_CALLBACK (on_transition_completed), widget); g_signal_connect_swapped (priv->transition_animation, "new-frame", G_CALLBACK (clutter_actor_queue_redraw), widget); } } else if (priv->transition_animation) { st_widget_remove_transition (widget); } if (!paint_equal) { clutter_actor_invalidate_paint_volume (CLUTTER_ACTOR (widget)); next_paint_state (widget); if (!st_theme_node_paint_equal (new_theme_node, current_paint_state (widget)->node)) st_theme_node_paint_state_invalidate (current_paint_state (widget)); } g_signal_emit (widget, signals[STYLE_CHANGED], 0); priv->is_style_dirty = FALSE; } /** * st_widget_ensure_style: * @widget: A #StWidget * * Ensures that @widget has read its style information and propagated any * changes to its children. */ void st_widget_ensure_style (StWidget *widget) { StWidgetPrivate *priv; g_return_if_fail (ST_IS_WIDGET (widget)); priv = st_widget_get_instance_private (widget); if (priv->is_style_dirty) { st_widget_recompute_style (widget, NULL); notify_children_of_style_change (CLUTTER_ACTOR (widget)); } } /** * st_widget_set_track_hover: * @widget: A #StWidget * @track_hover: %TRUE if the widget should track the pointer hover state * * Enables hover tracking on the #StWidget. * * If hover tracking is enabled, and the widget is visible and * reactive, then @widget's #StWidget:hover property will be updated * automatically to reflect whether the pointer is in @widget (or one * of its children), and @widget's #StWidget:pseudo-class will have * the "hover" class added and removed from it accordingly. * * Note that currently it is not possible to correctly track the hover * state when another actor has a pointer grab. You can use * st_widget_sync_hover() to update the property manually in this * case. */ void st_widget_set_track_hover (StWidget *widget, gboolean track_hover) { StWidgetPrivate *priv; g_return_if_fail (ST_IS_WIDGET (widget)); priv = st_widget_get_instance_private (widget); if (priv->track_hover != track_hover) { priv->track_hover = track_hover; g_object_notify_by_pspec (G_OBJECT (widget), props[PROP_TRACK_HOVER]); if (priv->track_hover) st_widget_sync_hover (widget); else st_widget_set_hover (widget, FALSE); } } /** * st_widget_get_track_hover: * @widget: A #StWidget * * Returns the current value of the #StWidget:track-hover property. See * st_widget_set_track_hover() for more information. * * Returns: current value of track-hover on @widget */ gboolean st_widget_get_track_hover (StWidget *widget) { g_return_val_if_fail (ST_IS_WIDGET (widget), FALSE); return ST_WIDGET_PRIVATE (widget)->track_hover; } /** * st_widget_set_hover: * @widget: A #StWidget * @hover: whether the pointer is hovering over the widget * * Sets @widget's hover property and adds or removes "hover" from its * pseudo class accordingly. * * If you have set #StWidget:track-hover, you should not need to call * this directly. You can call st_widget_sync_hover() if the hover * state might be out of sync due to another actor's pointer grab. */ void st_widget_set_hover (StWidget *widget, gboolean hover) { StWidgetPrivate *priv; g_return_if_fail (ST_IS_WIDGET (widget)); priv = st_widget_get_instance_private (widget); if (priv->hover != hover) { priv->hover = hover; if (priv->hover) st_widget_add_style_pseudo_class (widget, "hover"); else st_widget_remove_style_pseudo_class (widget, "hover"); g_object_notify_by_pspec (G_OBJECT (widget), props[PROP_HOVER]); } } /** * st_widget_sync_hover: * @widget: A #StWidget * * Sets @widget's hover state according to the current pointer * position. This can be used to ensure that it is correct after * (or during) a pointer grab. */ void st_widget_sync_hover (StWidget *widget) { ClutterInputDevice *pointer; ClutterActor *stage; ClutterActor *pointer_actor; ClutterSeat *seat; seat = clutter_backend_get_default_seat (clutter_get_default_backend ()); pointer = clutter_seat_get_pointer (seat); stage = clutter_actor_get_stage (CLUTTER_ACTOR (widget)); if (!stage) return; pointer_actor = clutter_stage_get_device_actor (CLUTTER_STAGE (stage), pointer, NULL); if (pointer_actor && clutter_actor_get_reactive (CLUTTER_ACTOR (widget))) st_widget_set_hover (widget, clutter_actor_contains (CLUTTER_ACTOR (widget), pointer_actor)); else st_widget_set_hover (widget, FALSE); } /** * st_widget_get_hover: * @widget: A #StWidget * * If #StWidget:track-hover is set, this returns whether the pointer * is currently over the widget. * * Returns: current value of hover on @widget */ gboolean st_widget_get_hover (StWidget *widget) { g_return_val_if_fail (ST_IS_WIDGET (widget), FALSE); return ST_WIDGET_PRIVATE (widget)->hover; } /** * st_widget_set_can_focus: * @widget: A #StWidget * @can_focus: %TRUE if the widget can receive keyboard focus * via keyboard navigation * * Marks @widget as being able to receive keyboard focus via * keyboard navigation. */ void st_widget_set_can_focus (StWidget *widget, gboolean can_focus) { StWidgetPrivate *priv; g_return_if_fail (ST_IS_WIDGET (widget)); priv = st_widget_get_instance_private (widget); if (priv->can_focus != can_focus) { priv->can_focus = can_focus; g_object_notify_by_pspec (G_OBJECT (widget), props[PROP_CAN_FOCUS]); } } /** * st_widget_get_can_focus: * @widget: A #StWidget * * Returns the current value of the can-focus property. See * st_widget_set_can_focus() for more information. * * Returns: current value of can-focus on @widget */ gboolean st_widget_get_can_focus (StWidget *widget) { g_return_val_if_fail (ST_IS_WIDGET (widget), FALSE); return ST_WIDGET_PRIVATE (widget)->can_focus; } /** * st_widget_popup_menu: * @self: A #StWidget * * Asks the widget to pop-up a context menu by emitting #StWidget::popup-menu. */ void st_widget_popup_menu (StWidget *self) { g_signal_emit (self, signals[POPUP_MENU], 0); } /* filter @children to contain only only actors that overlap @rbox * when moving in @direction. (Assuming no transformations.) */ static GList * filter_by_position (GList *children, ClutterActorBox *rbox, StDirectionType direction) { ClutterActorBox cbox; graphene_point3d_t abs_vertices[4]; GList *l, *ret; ClutterActor *child; for (l = children, ret = NULL; l; l = l->next) { child = l->data; clutter_actor_get_abs_allocation_vertices (child, abs_vertices); clutter_actor_box_from_vertices (&cbox, abs_vertices); /* Filter out children if they are in the wrong direction from * @rbox, or if they don't overlap it. To account for floating- * point imprecision, an actor is "down" (etc.) from an another * actor even if it overlaps it by up to 0.1 pixels. */ switch (direction) { case ST_DIR_UP: if (cbox.y2 > rbox->y1 + 0.1) continue; break; case ST_DIR_DOWN: if (cbox.y1 < rbox->y2 - 0.1) continue; break; case ST_DIR_LEFT: if (cbox.x2 > rbox->x1 + 0.1) continue; break; case ST_DIR_RIGHT: if (cbox.x1 < rbox->x2 - 0.1) continue; break; case ST_DIR_TAB_BACKWARD: case ST_DIR_TAB_FORWARD: default: g_return_val_if_reached (NULL); } ret = g_list_prepend (ret, child); } g_list_free (children); return ret; } static void get_midpoint (ClutterActorBox *box, int *x, int *y) { *x = (box->x1 + box->x2) / 2; *y = (box->y1 + box->y2) / 2; } static double get_distance (ClutterActor *actor, ClutterActorBox *bbox) { int ax, ay, bx, by, dx, dy; ClutterActorBox abox; graphene_point3d_t abs_vertices[4]; clutter_actor_get_abs_allocation_vertices (actor, abs_vertices); clutter_actor_box_from_vertices (&abox, abs_vertices); get_midpoint (&abox, &ax, &ay); get_midpoint (bbox, &bx, &by); dx = ax - bx; dy = ay - by; /* Not the exact distance, but good enough to sort by. */ return dx*dx + dy*dy; } static int sort_by_distance (gconstpointer a, gconstpointer b, gpointer user_data) { ClutterActor *actor_a = (ClutterActor *)a; ClutterActor *actor_b = (ClutterActor *)b; ClutterActorBox *box = user_data; return get_distance (actor_a, box) - get_distance (actor_b, box); } static gboolean st_widget_real_navigate_focus (StWidget *widget, ClutterActor *from, StDirectionType direction) { StWidgetPrivate *priv = st_widget_get_instance_private (widget); ClutterActor *widget_actor, *focus_child; GList *children, *l; widget_actor = CLUTTER_ACTOR (widget); if (from == widget_actor) return FALSE; /* Figure out if @from is a descendant of @widget, and if so, * set @focus_child to the immediate child of @widget that * contains (or *is*) @from. */ focus_child = from; while (focus_child && clutter_actor_get_parent (focus_child) != widget_actor) focus_child = clutter_actor_get_parent (focus_child); if (priv->can_focus) { if (!focus_child) { if (clutter_actor_is_mapped (widget_actor)) { /* Accept focus from outside */ clutter_actor_grab_key_focus (widget_actor); return TRUE; } else { /* Refuse to set focus on hidden actors */ return FALSE; } } else { /* Yield focus from within: since @widget itself is * focusable we don't allow the focus to be navigated * within @widget. */ return FALSE; } } /* See if we can navigate within @focus_child */ if (focus_child && ST_IS_WIDGET (focus_child)) { if (st_widget_navigate_focus (ST_WIDGET (focus_child), from, direction, FALSE)) return TRUE; } children = st_widget_get_focus_chain (widget); if (direction == ST_DIR_TAB_FORWARD || direction == ST_DIR_TAB_BACKWARD) { /* At this point we know that we want to navigate focus to one of * @widget's immediate children; the next one after @focus_child, or the * first one if @focus_child is %NULL. (With "next" and "first" being * determined by @direction.) */ if (direction == ST_DIR_TAB_BACKWARD) children = g_list_reverse (children); if (focus_child) { /* Remove focus_child and any earlier children */ while (children && children->data != focus_child) children = g_list_delete_link (children, children); if (children) children = g_list_delete_link (children, children); } } else /* direction is an arrow key, not tab */ { ClutterActorBox sort_box; graphene_point3d_t abs_vertices[4]; /* Compute the allocation box of the previous focused actor. If there * was no previous focus, use the coordinates of the appropriate edge of * @widget. * * Note that all of this code assumes the actors are not * transformed (or at most, they are all scaled by the same * amount). If @widget or any of its children is rotated, or * any child is inconsistently scaled, then the focus chain will * probably be unpredictable. */ if (from) { clutter_actor_get_abs_allocation_vertices (from, abs_vertices); clutter_actor_box_from_vertices (&sort_box, abs_vertices); } else { clutter_actor_get_abs_allocation_vertices (widget_actor, abs_vertices); clutter_actor_box_from_vertices (&sort_box, abs_vertices); switch (direction) { case ST_DIR_UP: sort_box.y1 = sort_box.y2; break; case ST_DIR_DOWN: sort_box.y2 = sort_box.y1; break; case ST_DIR_LEFT: sort_box.x1 = sort_box.x2; break; case ST_DIR_RIGHT: sort_box.x2 = sort_box.x1; break; case ST_DIR_TAB_FORWARD: case ST_DIR_TAB_BACKWARD: default: g_warn_if_reached (); } } if (from) children = filter_by_position (children, &sort_box, direction); if (children) children = g_list_sort_with_data (children, sort_by_distance, &sort_box); } /* Now try each child in turn */ for (l = children; l; l = l->next) { if (ST_IS_WIDGET (l->data)) { if (st_widget_navigate_focus (l->data, from, direction, FALSE)) { g_list_free (children); return TRUE; } } } g_list_free (children); return FALSE; } /** * st_widget_navigate_focus: * @widget: the "top level" container * @from: (nullable): the actor that the focus is coming from * @direction: the direction focus is moving in * @wrap_around: whether focus should wrap around * * Tries to update the keyboard focus within @widget in response to a * keyboard event. * * If @from is a descendant of @widget, this attempts to move the * keyboard focus to the next descendant of @widget (in the order * implied by @direction) that has the #StWidget:can-focus property * set. If @from is %NULL, this attempts to focus either @widget * itself, or its first descendant in the order implied by * @direction. If @from is outside of @widget, it behaves as if it was * a descendant if @direction is one of the directional arrows and as * if it was %NULL otherwise. * * If a container type is marked #StWidget:can-focus, the expected * behavior is that it will only take up a single slot on the focus * chain as a whole, rather than allowing navigation between its child * actors (or having a distinction between itself being focused and * one of its children being focused). * * Some widget classes might have slightly different behavior from the * above, where that would make more sense. * * If @wrap_around is %TRUE and @from is a child of @widget, but the * widget has no further children that can accept the focus in the * given direction, then st_widget_navigate_focus() will try a second * time, using a %NULL @from, which should cause it to reset the focus * to the first available widget in the given direction. * * Returns: %TRUE if clutter_actor_grab_key_focus() has been * called on an actor. %FALSE if not. */ gboolean st_widget_navigate_focus (StWidget *widget, ClutterActor *from, StDirectionType direction, gboolean wrap_around) { g_return_val_if_fail (ST_IS_WIDGET (widget), FALSE); if (ST_WIDGET_GET_CLASS (widget)->navigate_focus (widget, from, direction)) return TRUE; if (wrap_around && from && clutter_actor_contains (CLUTTER_ACTOR (widget), from)) return ST_WIDGET_GET_CLASS (widget)->navigate_focus (widget, NULL, direction); return FALSE; } static gboolean append_actor_text (GString *desc, ClutterActor *actor) { if (CLUTTER_IS_TEXT (actor)) { g_string_append_printf (desc, " (\"%s\")", clutter_text_get_text (CLUTTER_TEXT (actor))); return TRUE; } else if (ST_IS_LABEL (actor)) { g_string_append_printf (desc, " (\"%s\")", st_label_get_text (ST_LABEL (actor))); return TRUE; } else return FALSE; } /** * st_describe_actor: * @actor: a #ClutterActor * * Creates a string describing @actor, for use in debugging. This * includes the class name and actor name (if any), plus if @actor * is an #StWidget, its style class and pseudo class names. * * Returns: the debug name. */ char * st_describe_actor (ClutterActor *actor) { GString *desc; const char *name; int i; if (!actor) return g_strdup ("[null]"); desc = g_string_new (NULL); g_string_append_printf (desc, "[%p %s", actor, G_OBJECT_TYPE_NAME (actor)); if (ST_IS_WIDGET (actor)) { const char *style_class = st_widget_get_style_class_name (ST_WIDGET (actor)); const char *pseudo_class = st_widget_get_style_pseudo_class (ST_WIDGET (actor)); char **classes; if (style_class) { classes = g_strsplit (style_class, ",", -1); for (i = 0; classes[i]; i++) { g_strchug (classes[i]); g_string_append_printf (desc, ".%s", classes[i]); } g_strfreev (classes); } if (pseudo_class) { classes = g_strsplit (pseudo_class, ",", -1); for (i = 0; classes[i]; i++) { g_strchug (classes[i]); g_string_append_printf (desc, ":%s", classes[i]); } g_strfreev (classes); } } name = clutter_actor_get_name (actor); if (name) g_string_append_printf (desc, " \"%s\"", name); if (!append_actor_text (desc, actor)) { GList *children, *l; /* Do a limited search of @actor's children looking for a label */ children = clutter_actor_get_children (actor); for (l = children, i = 0; l && i < 20; l = l->next, i++) { if (append_actor_text (desc, l->data)) break; children = g_list_concat (children, clutter_actor_get_children (l->data)); } g_list_free (children); } g_string_append_c (desc, ']'); return g_string_free (desc, FALSE); } /** * st_widget_get_label_actor: * @widget: a #StWidget * * Gets the label that identifies @widget if it is defined * * Returns: (transfer none): the label that identifies the widget */ ClutterActor * st_widget_get_label_actor (StWidget *widget) { g_return_val_if_fail (ST_IS_WIDGET (widget), NULL); return ST_WIDGET_PRIVATE (widget)->label_actor; } /** * st_widget_set_label_actor: * @widget: a #StWidget * @label: a #ClutterActor * * Sets @label as the #ClutterActor that identifies (labels) * @widget. @label can be %NULL to indicate that @widget is not * labelled any more */ void st_widget_set_label_actor (StWidget *widget, ClutterActor *label) { StWidgetPrivate *priv; g_return_if_fail (ST_IS_WIDGET (widget)); priv = st_widget_get_instance_private (widget); if (priv->label_actor != label) { if (priv->label_actor) g_object_unref (priv->label_actor); if (label != NULL) priv->label_actor = g_object_ref (label); else priv->label_actor = NULL; g_object_notify_by_pspec (G_OBJECT (widget), props[PROP_LABEL_ACTOR]); } } /** * st_widget_set_accessible_name: * @widget: widget to set the accessible name for * @name: (nullable): a character string to be set as the accessible name * * This method sets @name as the accessible name for @widget. * * Usually you will have no need to set the accessible name for an * object, as usually there is a label for most of the interface * elements. So in general it is better to just use * @st_widget_set_label_actor. This method is only required when you * need to set an accessible name and there is no available label * object. * */ void st_widget_set_accessible_name (StWidget *widget, const gchar *name) { StWidgetPrivate *priv; g_return_if_fail (ST_IS_WIDGET (widget)); priv = st_widget_get_instance_private (widget); if (priv->accessible_name != NULL) g_free (priv->accessible_name); priv->accessible_name = g_strdup (name); g_object_notify_by_pspec (G_OBJECT (widget), props[PROP_ACCESSIBLE_NAME]); } /** * st_widget_get_accessible_name: * @widget: widget to get the accessible name for * * Gets the accessible name for this widget. See * st_widget_set_accessible_name() for more information. * * Returns: a character string representing the accessible name * of the widget. */ const gchar * st_widget_get_accessible_name (StWidget *widget) { g_return_val_if_fail (ST_IS_WIDGET (widget), NULL); return ST_WIDGET_PRIVATE (widget)->accessible_name; } /** * st_widget_set_accessible_role: * @widget: widget to set the accessible role for * @role: The role to use * * This method sets @role as the accessible role for @widget. This * role describes what kind of user interface element @widget is and * is provided so that assistive technologies know how to present * @widget to the user. * * Usually you will have no need to set the accessible role for an * object, as this information is extracted from the context of the * object (ie: a #StButton has by default a push button role). This * method is only required when you need to redefine the role * currently associated with the widget, for instance if it is being * used in an unusual way (ie: a #StButton used as a togglebutton), or * if a generic object is used directly (ie: a container as a menu * item). * * If @role is #ATK_ROLE_INVALID, the role will not be changed * and the accessible's default role will be used instead. */ void st_widget_set_accessible_role (StWidget *widget, AtkRole role) { StWidgetPrivate *priv; g_return_if_fail (ST_IS_WIDGET (widget)); priv = st_widget_get_instance_private (widget); priv->accessible_role = role; g_object_notify_by_pspec (G_OBJECT (widget), props[PROP_ACCESSIBLE_ROLE]); } /** * st_widget_get_accessible_role: * @widget: widget to get the accessible role for * * Gets the #AtkRole for this widget. See * st_widget_set_accessible_role() for more information. * * Returns: accessible #AtkRole for this widget */ AtkRole st_widget_get_accessible_role (StWidget *widget) { StWidgetPrivate *priv; AtkRole role = ATK_ROLE_INVALID; g_return_val_if_fail (ST_IS_WIDGET (widget), ATK_ROLE_INVALID); priv = st_widget_get_instance_private (widget); if (priv->accessible_role != ATK_ROLE_INVALID) role = priv->accessible_role; else if (priv->accessible != NULL) role = atk_object_get_role (priv->accessible); return role; } static void notify_accessible_state_change (StWidget *widget, AtkStateType state, gboolean value) { StWidgetPrivate *priv = st_widget_get_instance_private (widget); if (priv->accessible != NULL) atk_object_notify_state_change (priv->accessible, state, value); } /** * st_widget_add_accessible_state: * @widget: A #StWidget * @state: #AtkStateType state to add * * This method adds @state as one of the accessible states for * @widget. The list of states of a widget describes the current state * of user interface element @widget and is provided so that assistive * technologies know how to present @widget to the user. * * Usually you will have no need to add accessible states for an * object, as the accessible object can extract most of the states * from the object itself (ie: a #StButton knows when it is pressed). * This method is only required when one cannot extract the * information automatically from the object itself (i.e.: a generic * container used as a toggle menu item will not automatically include * the toggled state). * */ void st_widget_add_accessible_state (StWidget *widget, AtkStateType state) { StWidgetPrivate *priv; g_return_if_fail (ST_IS_WIDGET (widget)); priv = st_widget_get_instance_private (widget); if (atk_state_set_add_state (priv->local_state_set, state)) notify_accessible_state_change (widget, state, TRUE); } /** * st_widget_remove_accessible_state: * @widget: A #StWidget * @state: #AtkState state to remove * * This method removes @state as on of the accessible states for * @widget. See st_widget_add_accessible_state() for more information. * */ void st_widget_remove_accessible_state (StWidget *widget, AtkStateType state) { StWidgetPrivate *priv; g_return_if_fail (ST_IS_WIDGET (widget)); priv = st_widget_get_instance_private (widget); if (atk_state_set_remove_state (priv->local_state_set, state)) notify_accessible_state_change (widget, state, FALSE); } /******************************************************************************/ /*************************** ACCESSIBILITY SUPPORT ****************************/ /******************************************************************************/ /* GObject */ static void st_widget_accessible_dispose (GObject *gobject); /* AtkObject */ static AtkStateSet *st_widget_accessible_ref_state_set (AtkObject *obj); static void st_widget_accessible_initialize (AtkObject *obj, gpointer data); static AtkRole st_widget_accessible_get_role (AtkObject *obj); /* Private methods */ static void on_pseudo_class_notify (GObject *gobject, GParamSpec *pspec, gpointer data); static void on_can_focus_notify (GObject *gobject, GParamSpec *pspec, gpointer data); static void on_label_notify (GObject *gobject, GParamSpec *pspec, gpointer data); static void check_pseudo_class (StWidgetAccessible *self, StWidget *widget); static void check_labels (StWidgetAccessible *self, StWidget *widget); struct _StWidgetAccessiblePrivate { /* Cached values (used to avoid extra notifications) */ gboolean selected; gboolean checked; /* The current_label. Right now there are the proper atk * relationships between this object and the label */ AtkObject *current_label; }; G_DEFINE_TYPE_WITH_PRIVATE (StWidgetAccessible, st_widget_accessible, CALLY_TYPE_ACTOR) static gboolean st_widget_has_accessible (ClutterActor *actor) { StWidget *widget; StWidgetPrivate *priv; g_return_val_if_fail (ST_IS_WIDGET (actor), FALSE); widget = ST_WIDGET (actor); priv = st_widget_get_instance_private (widget); return priv->accessible != NULL; } static AtkObject * st_widget_get_accessible (ClutterActor *actor) { StWidget *widget = NULL; StWidgetPrivate *priv; g_return_val_if_fail (ST_IS_WIDGET (actor), NULL); widget = ST_WIDGET (actor); priv = st_widget_get_instance_private (widget); if (priv->accessible == NULL) { priv->accessible = g_object_new (ST_WIDGET_GET_CLASS (widget)->get_accessible_type (), NULL); atk_object_initialize (priv->accessible, actor); /* AtkGObjectAccessible, which StWidgetAccessible derives from, clears * the back reference to the object in a weak notify for the object; * weak-ref notification, which occurs during g_object_real_dispose(), * is then the optimal time to clear the forward reference. We * can't clear the reference in dispose() before chaining up, since * clutter_actor_dispose() causes notifications to be sent out, which * will result in a new accessible object being created. */ g_object_add_weak_pointer (G_OBJECT (actor), (gpointer *)&priv->accessible); } return priv->accessible; } /** * st_widget_set_accessible: * @widget: A #StWidget * @accessible: an accessible (#AtkObject) * * This method allows to set a customly created accessible object to * this widget. For example if you define a new subclass of * #StWidgetAccessible at the javascript code. * * NULL is a valid value for @accessible. That contemplates the * hypothetical case of not needing anymore a custom accessible object * for the widget. Next call of st_widget_get_accessible() would * create and return a default accessible. * * It assumes that the call to atk_object_initialize that bound the * gobject with the custom accessible object was already called, so * not a responsibility of this method. * */ void st_widget_set_accessible (StWidget *widget, AtkObject *accessible) { StWidgetPrivate *priv; g_return_if_fail (ST_IS_WIDGET (widget)); g_return_if_fail (accessible == NULL || ATK_IS_GOBJECT_ACCESSIBLE (accessible)); priv = st_widget_get_instance_private (widget); if (priv->accessible != accessible) { if (priv->accessible) { g_object_remove_weak_pointer (G_OBJECT (widget), (gpointer *)&priv->accessible); g_object_unref (priv->accessible); priv->accessible = NULL; } if (accessible) { priv->accessible = g_object_ref (accessible); /* See note in st_widget_get_accessible() */ g_object_add_weak_pointer (G_OBJECT (widget), (gpointer *)&priv->accessible); } else priv->accessible = NULL; } } static const gchar * st_widget_accessible_get_name (AtkObject *obj) { const gchar* name = NULL; g_return_val_if_fail (ST_IS_WIDGET_ACCESSIBLE (obj), NULL); name = ATK_OBJECT_CLASS (st_widget_accessible_parent_class)->get_name (obj); if (name == NULL) { StWidget *widget = NULL; widget = ST_WIDGET (atk_gobject_accessible_get_object (ATK_GOBJECT_ACCESSIBLE (obj))); if (widget == NULL) name = NULL; else name = st_widget_get_accessible_name (widget); } return name; } static void st_widget_accessible_class_init (StWidgetAccessibleClass *klass) { GObjectClass *gobject_class = G_OBJECT_CLASS (klass); AtkObjectClass *atk_class = ATK_OBJECT_CLASS (klass); gobject_class->dispose = st_widget_accessible_dispose; atk_class->ref_state_set = st_widget_accessible_ref_state_set; atk_class->initialize = st_widget_accessible_initialize; atk_class->get_role = st_widget_accessible_get_role; atk_class->get_name = st_widget_accessible_get_name; } static void st_widget_accessible_init (StWidgetAccessible *self) { StWidgetAccessiblePrivate *priv = st_widget_accessible_get_instance_private (self); self->priv = priv; } static void st_widget_accessible_dispose (GObject *gobject) { StWidgetAccessible *self = ST_WIDGET_ACCESSIBLE (gobject); if (self->priv->current_label) { g_object_unref (self->priv->current_label); self->priv->current_label = NULL; } G_OBJECT_CLASS (st_widget_accessible_parent_class)->dispose (gobject); } static void on_accessible_name_notify (GObject *gobject, GParamSpec *pspec, AtkObject *accessible) { g_object_notify (G_OBJECT (accessible), "accessible-name"); } static void st_widget_accessible_initialize (AtkObject *obj, gpointer data) { ATK_OBJECT_CLASS (st_widget_accessible_parent_class)->initialize (obj, data); g_signal_connect (data, "notify::pseudo-class", G_CALLBACK (on_pseudo_class_notify), obj); g_signal_connect (data, "notify::can-focus", G_CALLBACK (on_can_focus_notify), obj); g_signal_connect (data, "notify::label-actor", G_CALLBACK (on_label_notify), obj); g_signal_connect (data, "notify::accessible-name", G_CALLBACK (on_accessible_name_notify), obj); /* Check the cached selected state and notify the first selection. * Ie: it is required to ensure a first notification when Alt+Tab * popup appears */ check_pseudo_class (ST_WIDGET_ACCESSIBLE (obj), ST_WIDGET (data)); check_labels (ST_WIDGET_ACCESSIBLE (obj), ST_WIDGET (data)); } static AtkStateSet * st_widget_accessible_ref_state_set (AtkObject *obj) { AtkStateSet *result = NULL; AtkStateSet *aux_set = NULL; ClutterActor *actor = NULL; StWidget *widget = NULL; StWidgetPrivate *widget_priv; StWidgetAccessible *self = NULL; result = ATK_OBJECT_CLASS (st_widget_accessible_parent_class)->ref_state_set (obj); actor = CLUTTER_ACTOR (atk_gobject_accessible_get_object (ATK_GOBJECT_ACCESSIBLE (obj))); if (actor == NULL) /* State is defunct */ return result; widget = ST_WIDGET (actor); self = ST_WIDGET_ACCESSIBLE (obj); widget_priv = st_widget_get_instance_private (widget); /* priv->selected should be properly updated on the * ATK_STATE_SELECTED notification callbacks */ if (self->priv->selected) atk_state_set_add_state (result, ATK_STATE_SELECTED); if (self->priv->checked) atk_state_set_add_state (result, ATK_STATE_CHECKED); /* On clutter there isn't any tip to know if a actor is focusable or * not, anyone can receive the key_focus. For this reason * cally_actor sets any actor as FOCUSABLE. This is not the case on * St, where we have can_focus. But this means that we need to * remove the state FOCUSABLE if it is not focusable */ if (st_widget_get_can_focus (widget)) atk_state_set_add_state (result, ATK_STATE_FOCUSABLE); else atk_state_set_remove_state (result, ATK_STATE_FOCUSABLE); /* We add the states added externally if required */ if (!atk_state_set_is_empty (widget_priv->local_state_set)) { aux_set = atk_state_set_or_sets (result, widget_priv->local_state_set); g_object_unref (result); /* previous result will not be used */ result = aux_set; } return result; } static AtkRole st_widget_accessible_get_role (AtkObject *obj) { StWidget *widget = NULL; StWidgetPrivate *priv; g_return_val_if_fail (ST_IS_WIDGET_ACCESSIBLE (obj), ATK_ROLE_INVALID); widget = ST_WIDGET (atk_gobject_accessible_get_object (ATK_GOBJECT_ACCESSIBLE (obj))); if (widget == NULL) return ATK_ROLE_INVALID; priv = st_widget_get_instance_private (widget); if (priv->accessible_role != ATK_ROLE_INVALID) return priv->accessible_role; return ATK_OBJECT_CLASS (st_widget_accessible_parent_class)->get_role (obj); } static void on_pseudo_class_notify (GObject *gobject, GParamSpec *pspec, gpointer data) { check_pseudo_class (ST_WIDGET_ACCESSIBLE (data), ST_WIDGET (gobject)); } /* * In some cases the only way to check some states are checking the * pseudo-class. Like if the object is selected (see bug 637830) or if * the object is toggled. This method also notifies a state change if * the value is different to the one cached. * * We also assume that if the object uses that pseudo-class, it makes * sense to notify that state change. It would be possible to refine * that behaviour checking the role (ie: notify CHECKED changes only * for CHECK_BUTTON roles). * * In a ideal world we would have a more standard way to get the * state, like the widget-context (as in the case of * gtktreeview-cells), or something like the property "can-focus". But * for the moment this is enough, and we can update that in the future * if required. */ static void check_pseudo_class (StWidgetAccessible *self, StWidget *widget) { gboolean found = FALSE; found = st_widget_has_style_pseudo_class (widget, "selected"); if (found != self->priv->selected) { self->priv->selected = found; atk_object_notify_state_change (ATK_OBJECT (self), ATK_STATE_SELECTED, found); } found = st_widget_has_style_pseudo_class (widget, "checked"); if (found != self->priv->checked) { self->priv->checked = found; atk_object_notify_state_change (ATK_OBJECT (self), ATK_STATE_CHECKED, found); } } static void on_can_focus_notify (GObject *gobject, GParamSpec *pspec, gpointer data) { gboolean can_focus = st_widget_get_can_focus (ST_WIDGET (gobject)); atk_object_notify_state_change (ATK_OBJECT (data), ATK_STATE_FOCUSABLE, can_focus); } static void on_label_notify (GObject *gobject, GParamSpec *pspec, gpointer data) { check_labels (ST_WIDGET_ACCESSIBLE (data), ST_WIDGET (gobject)); } static void check_labels (StWidgetAccessible *widget_accessible, StWidget *widget) { ClutterActor *label = NULL; AtkObject *label_accessible = NULL; /* We only call this method at startup, and when the label changes, * so it is fine to remove the previous relationships if we have the * current_label by default */ if (widget_accessible->priv->current_label != NULL) { AtkObject *previous_label = widget_accessible->priv->current_label; atk_object_remove_relationship (ATK_OBJECT (widget_accessible), ATK_RELATION_LABELLED_BY, previous_label); atk_object_remove_relationship (previous_label, ATK_RELATION_LABEL_FOR, ATK_OBJECT (widget_accessible)); g_object_unref (previous_label); } label = st_widget_get_label_actor (widget); if (label == NULL) { widget_accessible->priv->current_label = NULL; } else { label_accessible = clutter_actor_get_accessible (label); widget_accessible->priv->current_label = g_object_ref (label_accessible); atk_object_add_relationship (ATK_OBJECT (widget_accessible), ATK_RELATION_LABELLED_BY, label_accessible); atk_object_add_relationship (label_accessible, ATK_RELATION_LABEL_FOR, ATK_OBJECT (widget_accessible)); } } /** * st_widget_get_focus_chain: * @widget: An #StWidget * * Gets a list of the focusable children of @widget, in "Tab" * order. By default, this returns all visible * (as in clutter_actor_is_visible()) children of @widget. * * Returns: (element-type Clutter.Actor) (transfer container): * @widget's focusable children */ GList * st_widget_get_focus_chain (StWidget *widget) { return ST_WIDGET_GET_CLASS (widget)->get_focus_chain (widget); }
GNOME/gnome-shell
src/st/st-widget.c
C
gpl-2.0
89,709
# # Copyright 2012-2013 Red Hat, Inc. # # This program is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 2 of the License, or # (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program; if not, write to the Free Software # Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA # # Refer to the README and COPYING files for full details of the license # import os.path import contextlib import errno import logging import sys import threading from testrunner import VdsmTestCase as TestCaseBase from testrunner import permutations, expandPermutations from testValidation import checkSudo from testValidation import stresstest from vdsm import utils from vdsm import constants import time EXT_SLEEP = "sleep" class RetryTests(TestCaseBase): def testStopCallback(self): counter = [0] limit = 4 def stopCallback(): counter[0] += 1 if counter[0] == limit: return True return False def foo(): raise RuntimeError("If at first you don't succeed, try, try again." "Then quit. There's no point in being a damn" "fool about it.") # W. C. Fields self.assertRaises(RuntimeError, utils.retry, foo, tries=(limit + 10), sleep=0, stopCallback=stopCallback) # Make sure we had the proper amount of iterations before failing self.assertEquals(counter[0], limit) class PidStatTests(TestCaseBase): def test(self): args = ["sleep", "3"] sproc = utils.execCmd(args, sync=False) stats = utils.pidStat(sproc.pid) pid = int(stats.pid) # procName comes in the format of (procname) name = stats.comm self.assertEquals(pid, sproc.pid) self.assertEquals(name, args[0]) sproc.kill() sproc.wait() class PgrepTests(TestCaseBase): def test(self): sleepProcs = [] for i in range(3): sleepProcs.append(utils.execCmd([EXT_SLEEP, "3"], sync=False, sudo=False)) pids = utils.pgrep(EXT_SLEEP) for proc in sleepProcs: self.assertTrue(proc.pid in pids, "pid %d was not located by pgrep" % proc.pid) for proc in sleepProcs: proc.kill() proc.wait() class GetCmdArgsTests(TestCaseBase): def test(self): args = [EXT_SLEEP, "4"] sproc = utils.execCmd(args, sync=False) try: self.assertEquals(utils.getCmdArgs(sproc.pid), tuple(args)) finally: sproc.kill() sproc.wait() def testZombie(self): args = [EXT_SLEEP, "0"] sproc = utils.execCmd(args, sync=False) sproc.kill() try: test = lambda: self.assertEquals(utils.getCmdArgs(sproc.pid), tuple()) utils.retry(AssertionError, test, tries=10, sleep=0.1) finally: sproc.wait() class CommandPathTests(TestCaseBase): def testExisting(self): cp = utils.CommandPath('sh', 'utter nonsense', '/bin/sh') self.assertEquals(cp.cmd, '/bin/sh') def testMissing(self): NAME = 'nonsense' try: utils.CommandPath(NAME, 'utter nonsense').cmd except OSError as e: self.assertEquals(e.errno, errno.ENOENT) self.assertIn(NAME, e.strerror) class GeneralUtilsTests(TestCaseBase): def testPanic(self): self.assertRaises(AssertionError, utils.panic, "panic test") def testAnyFnmatch(self): self.assertTrue(utils.anyFnmatch('test1', ['test0', 'test1'])) def testReadMemInfo(self): meminfo = utils.readMemInfo() # most common fields as per man 5 proc # add your own here fields = ('MemTotal', 'MemFree', 'Buffers', 'Cached', 'SwapCached', 'Active', 'Inactive', 'SwapTotal', 'SwapFree', 'Dirty', 'Writeback', 'Mapped', 'Slab', 'VmallocTotal', 'VmallocUsed', 'VmallocChunk') for field in fields: self.assertIn(field, meminfo) self.assertTrue(isinstance(meminfo[field], int)) def testParseMemInfo(self): testPath = os.path.realpath(__file__) dirName = os.path.dirname(testPath) path = os.path.join(dirName, "mem_info.out") with open(path) as f: meminfo = utils._parseMemInfo(f.readlines()) # testing some random fields self.assertEquals(meminfo['NFS_Unstable'], 0) self.assertEquals(meminfo['KernelStack'], 2760) self.assertEquals(meminfo['Inactive'], 1432748) def testGrouper(self): iterable = '1234567890' grouped = [('1', '2'), ('3', '4'), ('5', '6'), ('7', '8'), ('9', '0')] self.assertEquals(list(utils.grouper(iterable, 2)), grouped) iterable += 'a' grouped.append(('a', None)) self.assertEquals(list(utils.grouper(iterable, 2)), grouped) iterable += 'bcde' grouped = [('1', '2', '3'), ('4', '5', '6'), ('7', '8', '9'), ('0', 'a', 'b'), ('c', 'd', 'e')] self.assertEquals(list(utils.grouper(iterable, 3)), grouped) grouped = [('1', '2', '3', '4', '5'), ('6', '7', '8', '9', '0'), ('a', 'b', 'c', 'd', 'e')] self.assertEquals(list(utils.grouper(iterable, 5)), grouped) class AsyncProcessOperationTests(TestCaseBase): def _echo(self, text): proc = utils.execCmd(["echo", "-n", "test"], sync=False) def parse(rc, out, err): return out return utils.AsyncProcessOperation(proc, parse) def _sleep(self, t): proc = utils.execCmd(["sleep", str(t)], sync=False) return utils.AsyncProcessOperation(proc) def _fail(self, t): proc = utils.execCmd(["sleep", str(t)], sync=False) def parse(rc, out, err): raise Exception("TEST!!!") return utils.AsyncProcessOperation(proc, parse) def test(self): aop = self._sleep(1) self.assertEquals(aop.result(), ((0, "", ""), None)) def testAlreadyExitedSuccess(self): aop = self._sleep(0) time.sleep(1) self.assertEquals(aop.result(), ((0, "", ""), None)) def testAlreadyExitedFail(self): aop = self._sleep("hello") time.sleep(1) ((rc, out, err), err) = aop.result() self.assertEquals(err, None) self.assertEquals(rc, 1) def testWait(self): aop = self._sleep(1) aop.wait(timeout=2) def testParser(self): aop = self._echo("test") self.assertEquals(aop.result(), ("test", None)) def testStop(self): aop = self._sleep(10) aop.stop() start = time.time() aop.result() end = time.time() duration = end - start self.assertTrue(duration < 2) def testException(self): aop = self._fail(1) res, err = aop.result() self.assertEquals(res, None) self.assertNotEquals(err, None) class CallbackChainTests(TestCaseBase): def testCanPassIterableOfCallbacks(self): f = lambda: False callbacks = [f] * 10 chain = utils.CallbackChain(callbacks) self.assertEqual(list(chain.callbacks), callbacks) def testEmptyChainIsNoop(self): chain = utils.CallbackChain() self.assertFalse(chain.callbacks) chain.start() chain.join() # assert exception isn't thrown in start on empty chain def testAllCallbacksAreInvokedIfTheyReturnFalse(self): n = 10 counter = [n] def callback(): counter[0] -= 1 return False chain = utils.CallbackChain([callback] * n) chain.start() chain.join() self.assertEqual(counter[0], 0) def testChainStopsAfterSuccessfulCallback(self): n = 10 counter = [n] def callback(): counter[0] -= 1 return counter[0] == 5 chain = utils.CallbackChain([callback] * n) chain.start() chain.join() self.assertEquals(counter[0], 5) def testArgsPassedToCallback(self): callbackArgs = ('arg', 42, 'and another') callbackKwargs = {'some': 42, 'kwargs': []} def callback(*args, **kwargs): self.assertEqual(args, callbackArgs) self.assertEqual(kwargs, callbackKwargs) chain = utils.CallbackChain() chain.addCallback(callback, *callbackArgs, **callbackKwargs) chain.start() chain.join() @contextlib.contextmanager def loghandler(handler, logger=""): log = logging.getLogger(logger) log.addHandler(handler) try: yield {} finally: log.removeHandler(handler) class TracebackTests(TestCaseBase): def __init__(self, *a, **kw): self.record = None super(TestCaseBase, self).__init__(*a, **kw) def testDefaults(self): @utils.traceback() def fail(): raise Exception with loghandler(self): self.assertRaises(Exception, fail) self.assertEquals(self.record.name, "root") self.assertTrue(self.record.exc_text is not None) def testOn(self): logger = "test" @utils.traceback(on=logger) def fail(): raise Exception with loghandler(self, logger=logger): self.assertRaises(Exception, fail) self.assertEquals(self.record.name, logger) def testMsg(self): @utils.traceback(msg="WAT") def fail(): raise Exception with loghandler(self): self.assertRaises(Exception, fail) self.assertEquals(self.record.message, "WAT") # Logging handler interface level = logging.DEBUG def acquire(self): pass def release(self): pass def handle(self, record): assert self.record is None self.record = record class RollbackContextTests(TestCaseBase): class UndoException(Exception): """A special exception for testing exceptions during undo functions""" class OriginalException(Exception): """A special exception for testing exceptions in the with statement""" def setUp(self): self._called = 0 def _callDef(self): self._called += 1 self.log.info("Incremented call count (%d)", self._called) def _raiseDef(self, ex=Exception()): self.log.info("Raised exception (%s)", ex.__class__.__name__) raise ex def test(self): with utils.RollbackContext() as rollback: rollback.prependDefer(self._callDef) self.assertEquals(self._called, 1) def testRaise(self): """ Test that raising an exception in a deferred action does not block all subsequent actions from running """ try: with utils.RollbackContext() as rollback: rollback.prependDefer(self._callDef) rollback.prependDefer(self._raiseDef) rollback.prependDefer(self._callDef) except Exception: self.assertEquals(self._called, 2) return self.fail("Exception was not raised") def testFirstUndoException(self): """ Test that if multiple actions raise an exception only the first one is raised. When performing a batch rollback operations, probably the first exception is the root cause. """ try: with utils.RollbackContext() as rollback: rollback.prependDefer(self._callDef) rollback.prependDefer(self._raiseDef) rollback.prependDefer(self._callDef) rollback.prependDefer(self._raiseDef, RuntimeError()) rollback.prependDefer(self._callDef) except RuntimeError: self.assertEquals(self._called, 3) return except Exception: self.fail("Wrong exception was raised") self.fail("Exception was not raised") def testKeyError(self): """ KeyError is raised as a tuple and not expection. Re-raising it should be aware of this fact and handled carfully. """ try: with utils.RollbackContext(): {}['aKey'] except KeyError: return except Exception: self.fail("Wrong exception was raised") self.fail("Exception was not raised") def testPreferOriginalException(self): """ Test that if an exception is raised both from the with statement and from the finally clause, the one from the with statement is the one that's actually raised. More info in: http://docs.python.org/ 2.6/library/stdtypes.html#contextmanager.__exit__ """ try: with utils.RollbackContext() as rollback: rollback.prependDefer(self._raiseDef, self.UndoException()) raise self.OriginalException() except self.OriginalException: return except self.UndoException: self.fail("Wrong exception was raised - from undo function. \ should have re-raised OriginalException") except Exception: self.fail("Wrong exception was raised") self.fail("Exception was not raised") @expandPermutations class ExecCmdTest(TestCaseBase): CMD_TYPES = ((tuple,), (list,), (iter,)) @permutations(CMD_TYPES) def testNormal(self, cmd): rc, out, _ = utils.execCmd(cmd(('echo', 'hello world'))) self.assertEquals(rc, 0) self.assertEquals(out[0], 'hello world') @permutations(CMD_TYPES) def testIoClass(self, cmd): rc, out, _ = utils.execCmd(cmd(('ionice',)), ioclass=2, ioclassdata=3) self.assertEquals(rc, 0) self.assertEquals(out[0].strip(), 'best-effort: prio 3') @permutations(CMD_TYPES) def testNice(self, cmd): rc, out, _ = utils.execCmd(cmd(('cat', '/proc/self/stat')), nice=7) self.assertEquals(rc, 0) self.assertEquals(int(out[0].split()[18]), 7) @permutations(CMD_TYPES) def testSetSid(self, cmd): cmd_args = (constants.EXT_PYTHON, '-c', 'import os; print os.getsid(os.getpid())') rc, out, _ = utils.execCmd(cmd(cmd_args), setsid=True) self.assertNotEquals(int(out[0]), os.getsid(os.getpid())) @permutations(CMD_TYPES) def testSudo(self, cmd): checkSudo(['echo']) rc, out, _ = utils.execCmd(cmd(('grep', 'Uid', '/proc/self/status')), sudo=True) self.assertEquals(rc, 0) self.assertEquals(int(out[0].split()[2]), 0) class ExecCmdStressTest(TestCaseBase): CONCURRENCY = 50 FUNC_DELAY = 0.01 FUNC_CALLS = 40 BLOCK_SIZE = 4096 BLOCK_COUNT = 256 def setUp(self): self.data = None # Written to process stdin self.workers = [] self.resume = threading.Event() @stresstest def test_read_stderr(self): self.check(self.read_stderr) @stresstest def test_read_stdout_stderr(self): self.check(self.read_stdout_stderr) @stresstest def test_write_stdin_read_stderr(self): self.data = 'x' * self.BLOCK_SIZE * self.BLOCK_COUNT self.check(self.write_stdin_read_stderr) def check(self, func): for i in xrange(self.CONCURRENCY): worker = Worker(self.resume, func, self.FUNC_CALLS, self.FUNC_DELAY) self.workers.append(worker) worker.start() for worker in self.workers: worker.wait() self.resume.set() for worker in self.workers: worker.join() for worker in self.workers: if worker.exc_info: t, v, tb = worker.exc_info raise t, v, tb def read_stderr(self): args = ['if=/dev/zero', 'of=/dev/null', 'bs=%d' % self.BLOCK_SIZE, 'count=%d' % self.BLOCK_COUNT] self.run_dd(args) def read_stdout_stderr(self): args = ['if=/dev/zero', 'bs=%d' % self.BLOCK_SIZE, 'count=%d' % self.BLOCK_COUNT] out = self.run_dd(args) size = self.BLOCK_SIZE * self.BLOCK_COUNT if len(out) < size: raise self.failureException("Partial read: %d/%d" % ( len(out), size)) def write_stdin_read_stderr(self): args = ['of=/dev/null', 'bs=%d' % self.BLOCK_SIZE, 'count=%d' % self.BLOCK_COUNT] self.run_dd(args) def run_dd(self, args): cmd = [constants.EXT_DD] cmd.extend(args) rc, out, err = utils.execCmd(cmd, raw=True, data=self.data) if rc != 0: raise self.failureException("Process failed: rc=%d err=%r" % (rc, err)) if err == '': raise self.failureException("No data from stderr") return out class Worker(object): def __init__(self, resume, func, func_calls, func_delay): self.exc_info = None self._resume = resume self._func = func self._func_calls = func_calls self._func_delay = func_delay self._ready = threading.Event() self._thread = threading.Thread(target=self._run) self._thread.daemon = True def start(self): self._thread.start() def wait(self): self._ready.wait() def join(self): self._thread.join() def _run(self): try: self._ready.set() self._resume.wait() for n in range(self._func_calls): self._func() time.sleep(self._func_delay) except Exception: self.exc_info = sys.exc_info() class List2CmdlineeTests(TestCaseBase): def test_simple(self): args = ['/usr/bin/dd', 'iflag=direct', 'if=/dev/a70a4106-24f2-4599-be3e-934fee6e4499/metadata', 'bs=4096', 'count=1'] line = ' '.join(args) self.assertEquals(utils._list2cmdline(args), line) def test_whitespace(self): args = ['a b', ' c ', 'd\t', '\ne'] line = "'a b' ' c ' 'd\t' '\ne'" self.assertEquals(utils._list2cmdline(args), line) def test_unsafe(self): args = [c for c in '><*?[]`$|;&()#$\\"'] line = ' '.join("'" + c + "'" for c in args) self.assertEquals(utils._list2cmdline(args), line) def test_safe(self): # Stolen from pipes._safechars line = ' '.join('%+,-./0123456789:=@ABCDEFGHIJKLMNOPQRSTUVWXYZ_abcdef' 'ghijklmnopqrstuvwxyz') args = line.split() self.assertEquals(utils._list2cmdline(args), line) def test_single_quote(self): args = ["don't", "try 'this'", "'at home'"] line = r"'don'\''t' 'try '\''this'\''' ''\''at home'\'''" self.assertEquals(utils._list2cmdline(args), line) def test_empty_arg(self): self.assertEquals(utils._list2cmdline(['a', '', 'b']), "a '' b") def test_empty(self): self.assertEquals(utils._list2cmdline([]), "")
futurice/vdsm
tests/utilsTests.py
Python
gpl-2.0
19,919
<?php /*-----------------------------------------------------------------------------------*/ /* This theme supports WooCommerce, woo! */ /*-----------------------------------------------------------------------------------*/ add_action( 'after_setup_theme', 'woocommerce_support' ); function woocommerce_support() { add_theme_support( 'woocommerce' ); } /*-----------------------------------------------------------------------------------*/ /* Any WooCommerce overrides and functions can be found here /*-----------------------------------------------------------------------------------*/ // Add html5 shim add_action('wp_head', 'wootique_html5_shim'); function wootique_html5_shim() { ?> <!-- Load Google HTML5 shim to provide support for <IE9 --> <!--[if lt IE 9]> <script src="https://html5shim.googlecode.com/svn/trunk/html5.js"></script> <![endif]--> <?php } // Disable WooCommerce styles if ( version_compare( WOOCOMMERCE_VERSION, "2.1" ) >= 0 ) { // WooCommerce 2.1 or above is active add_filter( 'woocommerce_enqueue_styles', '__return_false' ); } else { // WooCommerce is less than 2.1 define( 'WOOCOMMERCE_USE_CSS', false ); } /*-----------------------------------------------------------------------------------*/ /* Header /*-----------------------------------------------------------------------------------*/ // Hook in the search add_action('woo_nav_before', 'wootique_header_search'); function wootique_header_search() { ?> <div id="search-top"> <form role="search" method="get" id="searchform" class="searchform" action="<?php echo home_url(); ?>"> <label class="screen-reader-text" for="s"><?php _e('Search for:', 'woothemes'); ?></label> <input type="text" value="<?php the_search_query(); ?>" name="s" id="s" class="field s" placeholder="<?php _e('Cari Kuliner', 'woothemes'); ?>" /> <input type="image" class="submit btn" name="submit" value="<?php _e('Search', 'woothemes'); ?>" src="<?php echo get_template_directory_uri(); ?>/images/ico-search.png"> <?php if ( wootique_get_woo_option( 'woo_header_search_scope' ) == 'products' ) { echo '<input type="hidden" name="post_type" value="product" />'; } else { echo '<input type="hidden" name="post_type" value="post" />'; } ?> </form> <div class="fix"></div> </div><!-- /.search-top --> <?php } // Remove WC sidebar remove_action( 'woocommerce_sidebar', 'woocommerce_get_sidebar', 10); // Adjust markup on all WooCommerce pages remove_action( 'woocommerce_before_main_content', 'woocommerce_output_content_wrapper', 10); remove_action( 'woocommerce_after_main_content', 'woocommerce_output_content_wrapper_end', 10); add_action('woocommerce_before_main_content', 'woostore_before_content', 10); add_action('woocommerce_after_main_content', 'woostore_after_content', 20); // Fix the layout etc function woostore_before_content() { ?> <!-- #content Starts --> <?php woo_content_before(); ?> <div id="content" class="col-full"> <!-- #main Starts --> <?php woo_main_before(); ?> <div id="main" class="col-left"> <?php } function woostore_after_content() { ?> <?php if ( is_search() && is_post_type_archive() ) { add_filter( 'woo_pagination_args', 'woocommerceframework_add_search_fragment', 10 ); } ?> <?php woo_pagenav(); ?> </div><!-- /#main --> <?php woo_main_after(); ?> </div><!-- /#content --> <?php woo_content_after(); ?> <?php } function woocommerceframework_add_search_fragment ( $settings ) { $settings['add_fragment'] = '&post_type=product'; return $settings; } // End woocommerceframework_add_search_fragment() // Add the WC sidebar in the right place add_action( 'woo_main_after', 'woocommerce_get_sidebar', 10); // Remove breadcrumb (we're using the WooFramework default breadcrumb) remove_action( 'woocommerce_before_main_content', 'woocommerce_breadcrumb', 20, 0); add_action( 'woocommerce_before_main_content', 'woostore_breadcrumb', 01, 0); function woostore_breadcrumb() { if ( wootique_get_woo_option( 'woo_breadcrumbs_show' ) == 'true' ) { woo_breadcrumbs(); } } // Remove pagination (we're using the WooFramework default pagination) remove_action( 'woocommerce_pagination', 'woocommerce_pagination', 10 ); // <2.0 remove_action( 'woocommerce_after_shop_loop', 'woocommerce_pagination', 10 ); // 2.0+ // Adjust the star rating in the sidebar add_filter('woocommerce_star_rating_size_sidebar', 'woostore_star_sidebar'); function woostore_star_sidebar() { return 12; } // Adjust the star rating in the recent reviews add_filter('woocommerce_star_rating_size_recent_reviews', 'woostore_star_reviews'); function woostore_star_reviews() { return 12; } // Change columns in product loop to 3 add_filter('loop_shop_columns', 'woostore_loop_columns'); function woostore_loop_columns() { return 3; } // Change columns in related products output to 3 remove_action( 'woocommerce_after_single_product_summary', 'woocommerce_output_related_products', 20); add_action( 'woocommerce_after_single_product_summary', 'woocommerce_output_related_products', 20); if ( ! function_exists('woocommerce_output_related_products') && version_compare( WOOCOMMERCE_VERSION, "2.1" ) < 0 ) { function woocommerce_output_related_products() { woocommerce_related_products( 3,3 ); } } add_filter( 'woocommerce_output_related_products_args', 'wootique_related_products' ); function wootique_related_products() { $args = array( 'posts_per_page' => 3, 'columns' => 3, ); return $args; } if ( ! function_exists( 'woo_upsell_display' ) ) { function woo_upsell_display() { // Display up sells in correct layout. woocommerce_upsell_display( -1, 3 ); } } remove_action( 'woocommerce_after_single_product_summary', 'woocommerce_upsell_display', 15 ); add_action( 'woocommerce_after_single_product_summary', 'woo_upsell_display', 15 ); // If theme lightbox is enabled, disable the WooCommerce lightbox and make product images prettyPhoto galleries /*add_action( 'wp_footer', 'woocommerce_prettyphoto' ); function woocommerce_prettyphoto() { if ( wootique_get_woo_option( 'woo_enable_lightbox' ) == "true" ) { update_option( 'woocommerce_enable_lightbox', false ); ?> <script> jQuery(document).ready(function(){ jQuery('.images a').attr('rel', 'prettyPhoto[product-gallery]'); }); </script> <?php } }*/ // Move the price below the excerpt on the single product page remove_action( 'woocommerce_template_single_summary', 'woocommerce_template_single_price', 10, 2); add_action( 'woocommerce_template_single_summary', 'woocommerce_template_single_price', 25, 2); // Display 12 products per page add_filter('loop_shop_per_page', create_function('$cols', 'return 12;')); add_action('woo_nav_after', 'woocommerce_cart_link', 10); add_action('woo_nav_after', 'wootique_checkout_button', 10); function woocommerce_cart_link() { global $woocommerce; ?> <a href="<?php echo $woocommerce->cart->get_cart_url(); ?>" title="'<?php _e( 'View your shopping cart', 'woothemes' ); ?>'" class="cart-button"> <span><?php echo sprintf(_n( '%d item &ndash; ', '%d items &ndash; ', $woocommerce->cart->get_cart_contents_count(), 'woothemes'), $woocommerce->cart->get_cart_contents_count()) . $woocommerce->cart->get_cart_total(); ?></span> </a> <?php } function wootique_checkout_button() { global $woocommerce; ?> <?php if (sizeof($woocommerce->cart->cart_contents)>0) : echo '<a href="'.$woocommerce->cart->get_checkout_url().'" class="checkout-link">'.__('Checkout','woothemes').'</a>'; endif; ?> <?php } add_filter('add_to_cart_fragments', 'header_add_to_cart_fragment'); function header_add_to_cart_fragment( $fragments ) { global $woocommerce; ob_start(); woocommerce_cart_link(); $fragments['.cart-button'] = ob_get_clean(); return $fragments; }
jarqo/wootique
wp-content/themes/wootique/includes/theme-woocommerce.php
PHP
gpl-2.0
7,820
using System; using System.Text; using System.Collections; using Server; using Server.Prompts; using Server.Gumps; using Server.Network; using Server.Items; using Server.Misc; namespace Server.Mobiles { public interface ITownCrierEntryList { ArrayList Entries{ get; } TownCrierEntry GetRandomEntry(); TownCrierEntry AddEntry( string[] lines, TimeSpan duration ); void RemoveEntry( TownCrierEntry entry ); } public class GlobalTownCrierEntryList : ITownCrierEntryList { private static GlobalTownCrierEntryList m_Instance; public static void Initialize() { Server.Commands.Register( "TownCriers", AccessLevel.GameMaster, new CommandEventHandler( TownCriers_OnCommand ) ); } [Usage( "TownCriers" )] [Description( "Manages the global town crier list." )] public static void TownCriers_OnCommand( CommandEventArgs e ) { e.Mobile.SendGump( new TownCrierGump( e.Mobile, Instance ) ); } public static GlobalTownCrierEntryList Instance { get { if ( m_Instance == null ) m_Instance = new GlobalTownCrierEntryList(); return m_Instance; } } public bool IsEmpty{ get{ return ( m_Entries == null || m_Entries.Count == 0 ); } } public GlobalTownCrierEntryList() { } private ArrayList m_Entries; public ArrayList Entries { get{ return m_Entries; } } public TownCrierEntry GetRandomEntry() { if ( m_Entries == null || m_Entries.Count == 0 ) return null; for ( int i = m_Entries.Count - 1; m_Entries != null && i >= 0; --i ) { if ( i >= m_Entries.Count ) continue; TownCrierEntry tce = (TownCrierEntry)m_Entries[i]; if ( tce.Expired ) RemoveEntry( tce ); } if ( m_Entries == null || m_Entries.Count == 0 ) return null; return (TownCrierEntry)m_Entries[Utility.Random( m_Entries.Count )]; } public TownCrierEntry AddEntry( string[] lines, TimeSpan duration ) { if ( m_Entries == null ) m_Entries = new ArrayList(); TownCrierEntry tce = new TownCrierEntry( lines, duration ); m_Entries.Add( tce ); ArrayList instances = TownCrier.Instances; for ( int i = 0; i < instances.Count; ++i ) ((TownCrier)instances[i]).ForceBeginAutoShout(); return tce; } public void RemoveEntry( TownCrierEntry tce ) { if ( m_Entries == null ) return; m_Entries.Remove( tce ); if ( m_Entries.Count == 0 ) m_Entries = null; } } public class TownCrierEntry { private string[] m_Lines; private DateTime m_ExpireTime; public string[] Lines{ get{ return m_Lines; } } public DateTime ExpireTime{ get{ return m_ExpireTime; } } public bool Expired{ get{ return ( Core.Now >= m_ExpireTime ); } } public TownCrierEntry( string[] lines, TimeSpan duration ) { m_Lines = lines; if ( duration < TimeSpan.Zero ) duration = TimeSpan.Zero; else if ( duration > TimeSpan.FromDays( 365.0 ) ) duration = TimeSpan.FromDays( 365.0 ); m_ExpireTime = Core.Now + duration; } } public class TownCrierDurationPrompt : Prompt { private ITownCrierEntryList m_Owner; public TownCrierDurationPrompt( ITownCrierEntryList owner ) { m_Owner = owner; } public override void OnResponse( Mobile from, string text ) { TimeSpan ts; try { ts = TimeSpan.Parse( text ); } catch { from.SendMessage( "Value was not properly formatted. Use: <hours:minutes:seconds>" ); from.SendGump( new TownCrierGump( from, m_Owner ) ); return; } if ( ts < TimeSpan.Zero ) ts = TimeSpan.Zero; from.SendMessage( "Duration set to: {0}", ts ); from.SendMessage( "Enter the first line to shout:" ); from.Prompt = new TownCrierLinesPrompt( m_Owner, null, new ArrayList(), ts ); } public override void OnCancel( Mobile from ) { from.SendLocalizedMessage( 502980 ); // Message entry cancelled. from.SendGump( new TownCrierGump( from, m_Owner ) ); } } public class TownCrierLinesPrompt : Prompt { private ITownCrierEntryList m_Owner; private TownCrierEntry m_Entry; private ArrayList m_Lines; private TimeSpan m_Duration; public TownCrierLinesPrompt( ITownCrierEntryList owner, TownCrierEntry entry, ArrayList lines, TimeSpan duration ) { m_Owner = owner; m_Entry = entry; m_Lines = lines; m_Duration = duration; } public override void OnResponse( Mobile from, string text ) { m_Lines.Add( text ); from.SendMessage( "Enter the next line to shout, or press <ESC> if the message is finished." ); from.Prompt = new TownCrierLinesPrompt( m_Owner, m_Entry, m_Lines, m_Duration ); } public override void OnCancel( Mobile from ) { if ( m_Entry != null ) m_Owner.RemoveEntry( m_Entry ); if ( m_Lines.Count > 0 ) { m_Owner.AddEntry( (string[])m_Lines.ToArray( typeof( string ) ), m_Duration ); from.SendMessage( "Message has been set." ); } else { if ( m_Entry != null ) from.SendMessage( "Message deleted." ); else from.SendLocalizedMessage( 502980 ); // Message entry cancelled. } from.SendGump( new TownCrierGump( from, m_Owner ) ); } } public class TownCrierGump : Gump { private Mobile m_From; private ITownCrierEntryList m_Owner; public override void OnResponse( NetState sender, RelayInfo info ) { if ( info.ButtonID == 1 ) { m_From.SendMessage( "Enter the duration for the new message. Format: <hours:minutes:seconds>" ); m_From.Prompt = new TownCrierDurationPrompt( m_Owner ); } else if ( info.ButtonID > 1 ) { ArrayList entries = m_Owner.Entries; int index = info.ButtonID - 2; if ( entries != null && index < entries.Count ) { TownCrierEntry tce = (TownCrierEntry)entries[index]; TimeSpan ts = tce.ExpireTime - Core.Now; if ( ts < TimeSpan.Zero ) ts = TimeSpan.Zero; m_From.SendMessage( "Editing entry #{0}.", index + 1 ); m_From.SendMessage( "Enter the first line to shout:" ); m_From.Prompt = new TownCrierLinesPrompt( m_Owner, tce, new ArrayList(), ts ); } } } public TownCrierGump( Mobile from, ITownCrierEntryList owner ) : base( 50, 50 ) { m_From = from; m_Owner = owner; from.CloseGump( typeof( TownCrierGump ) ); AddPage( 0 ); ArrayList entries = owner.Entries; owner.GetRandomEntry(); // force expiration checks int count = 0; if ( entries != null ) count = entries.Count; AddImageTiled( 0, 0, 300, 38 + (count == 0 ? 20 : (count * 85)), 0xA40 ); AddAlphaRegion( 1, 1, 298, 36 + (count == 0 ? 20 : (count * 85)) ); AddHtml( 8, 8, 300 - 8 - 30, 20, "<basefont color=#FFFFFF><center>TOWN CRIER MESSAGES</center></basefont>", false, false ); AddButton( 300 - 8 - 30, 8, 0xFAB, 0xFAD, 1, GumpButtonType.Reply, 0 ); if ( count == 0 ) { AddHtml( 8, 30, 284, 20, "<basefont color=#FFFFFF>The crier has no news.</basefont>", false, false ); } else { for ( int i = 0; i < entries.Count; ++i ) { TownCrierEntry tce = (TownCrierEntry)entries[i]; TimeSpan toExpire = tce.ExpireTime - Core.Now; if ( toExpire < TimeSpan.Zero ) toExpire = TimeSpan.Zero; StringBuilder sb = new StringBuilder(); sb.Append( "[Expires: " ); if ( toExpire.TotalHours >= 1 ) { sb.Append( (int)toExpire.TotalHours ); sb.Append( ':' ); sb.Append( toExpire.Minutes.ToString( "D2" ) ); } else { sb.Append( toExpire.Minutes ); } sb.Append( ':' ); sb.Append( toExpire.Seconds.ToString( "D2" ) ); sb.Append( "] " ); for ( int j = 0; j < tce.Lines.Length; ++j ) { if ( j > 0 ) sb.Append( "<br>" ); sb.Append( tce.Lines[j] ); } AddHtml( 8, 35 + (i * 85), 254, 80, sb.ToString(), true, true ); AddButton( 300 - 8 - 26, 35 + (i * 85), 0x15E1, 0x15E5, 2 + i, GumpButtonType.Reply, 0 ); } } } } public class TownCrier : Mobile, ITownCrierEntryList { private ArrayList m_Entries; private Timer m_NewsTimer; private Timer m_AutoShoutTimer; public ArrayList Entries { get{ return m_Entries; } } public TownCrierEntry GetRandomEntry() { if ( m_Entries == null || m_Entries.Count == 0 ) return GlobalTownCrierEntryList.Instance.GetRandomEntry(); for ( int i = m_Entries.Count - 1; m_Entries != null && i >= 0; --i ) { if ( i >= m_Entries.Count ) continue; TownCrierEntry tce = (TownCrierEntry)m_Entries[i]; if ( tce.Expired ) RemoveEntry( tce ); } if ( m_Entries == null || m_Entries.Count == 0 ) return GlobalTownCrierEntryList.Instance.GetRandomEntry(); TownCrierEntry entry = GlobalTownCrierEntryList.Instance.GetRandomEntry(); if ( entry == null || Utility.RandomBool() ) entry = (TownCrierEntry)m_Entries[Utility.Random( m_Entries.Count )]; return entry; } public void ForceBeginAutoShout() { if ( m_AutoShoutTimer == null ) m_AutoShoutTimer = Timer.DelayCall( TimeSpan.FromSeconds( 5.0 ), TimeSpan.FromMinutes( 1.0 ), new TimerCallback( AutoShout_Callback ) ); } public TownCrierEntry AddEntry( string[] lines, TimeSpan duration ) { if ( m_Entries == null ) m_Entries = new ArrayList(); TownCrierEntry tce = new TownCrierEntry( lines, duration ); m_Entries.Add( tce ); if ( m_AutoShoutTimer == null ) m_AutoShoutTimer = Timer.DelayCall( TimeSpan.FromSeconds( 5.0 ), TimeSpan.FromMinutes( 1.0 ), new TimerCallback( AutoShout_Callback ) ); return tce; } public void RemoveEntry( TownCrierEntry tce ) { if ( m_Entries == null ) return; m_Entries.Remove( tce ); if ( m_Entries.Count == 0 ) m_Entries = null; if ( m_Entries == null && GlobalTownCrierEntryList.Instance.IsEmpty ) { if ( m_AutoShoutTimer != null ) m_AutoShoutTimer.Stop(); m_AutoShoutTimer = null; } } private void AutoShout_Callback() { TownCrierEntry tce = GetRandomEntry(); if ( tce == null ) { if ( m_AutoShoutTimer != null ) m_AutoShoutTimer.Stop(); m_AutoShoutTimer = null; } else if ( m_NewsTimer == null ) { m_NewsTimer = Timer.DelayCall( TimeSpan.FromSeconds( 1.0 ), TimeSpan.FromSeconds( 3.0 ), new TimerStateCallback( ShoutNews_Callback ), new object[]{ tce, 0 } ); PublicOverheadMessage( MessageType.Regular, 0x3B2, 502976 ); // Hear ye! Hear ye! } } private void ShoutNews_Callback( object state ) { object[] states = (object[])state; TownCrierEntry tce = (TownCrierEntry)states[0]; int index = (int)states[1]; if ( index < 0 || index >= tce.Lines.Length ) { if ( m_NewsTimer != null ) m_NewsTimer.Stop(); m_NewsTimer = null; } else { PublicOverheadMessage( MessageType.Regular, 0x3B2, false, tce.Lines[index] ); states[1] = index + 1; } } public override void OnDoubleClick( Mobile from ) { if ( from.AccessLevel >= AccessLevel.GameMaster ) from.SendGump( new TownCrierGump( from, this ) ); else base.OnDoubleClick( from ); } public override bool HandlesOnSpeech( Mobile from ) { return ( m_NewsTimer == null && from.Alive && InRange( from, 12 ) ); } public override void OnSpeech( SpeechEventArgs e ) { if ( m_NewsTimer == null && e.HasKeyword( 0x30 ) && e.Mobile.Alive && InRange( e.Mobile, 12 ) ) // *news* { Direction = GetDirectionTo( e.Mobile ); TownCrierEntry tce = GetRandomEntry(); if ( tce == null ) { PublicOverheadMessage( MessageType.Regular, 0x3B2, 1005643 ); // I have no news at this time. } else { m_NewsTimer = Timer.DelayCall( TimeSpan.FromSeconds( 1.0 ), TimeSpan.FromSeconds( 3.0 ), new TimerStateCallback( ShoutNews_Callback ), new object[]{ tce, 0 } ); PublicOverheadMessage( MessageType.Regular, 0x3B2, 502978 ); // Some of the latest news! } } } private static ArrayList m_Instances = new ArrayList(); public static ArrayList Instances { get{ return m_Instances; } } [Constructable] public TownCrier() { m_Instances.Add( this ); InitStats( 100, 100, 25 ); Title = "the town crier"; Hue = Utility.RandomSkinHue(); if ( !Core.AOS ) NameHue = 0x35; if ( this.Female = Utility.RandomBool() ) { this.Body = 0x191; this.Name = NameList.RandomName( "female" ); } else { this.Body = 0x190; this.Name = NameList.RandomName( "male" ); } AddItem( new FancyShirt( Utility.RandomBlueHue() ) ); Item skirt; switch ( Utility.Random( 2 ) ) { case 0: skirt = new Skirt(); break; default: case 1: skirt = new Kilt(); break; } skirt.Hue = Utility.RandomGreenHue(); AddItem( skirt ); AddItem( new FeatheredHat( Utility.RandomGreenHue() ) ); Item boots; switch ( Utility.Random( 2 ) ) { case 0: boots = new Boots(); break; default: case 1: boots = new ThighBoots(); break; } AddItem( boots ); Item hair = new Item( Utility.RandomList( 0x203B, 0x2049, 0x2048, 0x204A ) ); hair.Hue = Utility.RandomNondyedHue(); hair.Layer = Layer.Hair; hair.Movable = false; AddItem( hair ); } public override bool CanBeDamaged() { return false; } public override void OnDelete() { m_Instances.Remove( this ); base.OnDelete(); } public TownCrier( Serial serial ) : base( serial ) { m_Instances.Add( this ); } public override void Serialize( GenericWriter writer ) { base.Serialize( writer ); writer.Write( (int) 0 ); // version } public override void Deserialize( GenericReader reader ) { base.Deserialize( reader ); /*int version = */reader.ReadInt(); if ( Core.AOS && NameHue == 0x35 ) NameHue = -1; } } }
brodock/sunuo
scripts/legacy/Mobiles/Townfolk/TownCrier.cs
C#
gpl-2.0
13,658
<?php /** * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ namespace Magento\GroupedProduct\Model\Product\Link\CollectionProvider; class Grouped implements \Magento\Catalog\Model\ProductLink\CollectionProviderInterface { /** * {@inheritdoc} */ public function getLinkedProducts(\Magento\Catalog\Model\Product $product) { return $product->getTypeInstance()->getAssociatedProducts($product); } }
kunj1988/Magento2
app/code/Magento/GroupedProduct/Model/Product/Link/CollectionProvider/Grouped.php
PHP
gpl-2.0
476
/** @file This library registers RSA 2048 SHA 256 guided section handler to parse RSA 2048 SHA 256 encapsulation section and extract raw data. It uses the BaseCrypyLib based on OpenSSL to authenticate the signature. Copyright (c) 2013 - 2014, Intel Corporation. All rights reserved.<BR> This program and the accompanying materials are licensed and made available under the terms and conditions of the BSD License which accompanies this distribution. The full text of the license may be found at http://opensource.org/licenses/bsd-license.php THE PROGRAM IS DISTRIBUTED UNDER THE BSD LICENSE ON AN "AS IS" BASIS, WITHOUT WARRANTIES OR REPRESENTATIONS OF ANY KIND, EITHER EXPRESS OR IMPLIED. **/ #include <PiPei.h> #include <Protocol/Hash.h> #include <Library/ExtractGuidedSectionLib.h> #include <Library/DebugLib.h> #include <Library/BaseMemoryLib.h> #include <Library/MemoryAllocationLib.h> #include <Library/PcdLib.h> #include <Guid/WinCertificate.h> #include <Library/BaseCryptLib.h> #include <Library/PerformanceLib.h> #include <Guid/SecurityPkgTokenSpace.h> /// /// RSA 2048 SHA 256 Guided Section header /// typedef struct { EFI_GUID_DEFINED_SECTION GuidedSectionHeader; ///< EFI guided section header EFI_CERT_BLOCK_RSA_2048_SHA256 CertBlockRsa2048Sha256; ///< RSA 2048-bit Signature } RSA_2048_SHA_256_SECTION_HEADER; typedef struct { EFI_GUID_DEFINED_SECTION2 GuidedSectionHeader; ///< EFI guided section header EFI_CERT_BLOCK_RSA_2048_SHA256 CertBlockRsa2048Sha256; ///< RSA 2048-bit Signature } RSA_2048_SHA_256_SECTION2_HEADER; /// /// Public Exponent of RSA Key. /// CONST UINT8 mRsaE[] = { 0x01, 0x00, 0x01 }; /** GetInfo gets raw data size and attribute of the input guided section. It first checks whether the input guid section is supported. If not, EFI_INVALID_PARAMETER will return. @param InputSection Buffer containing the input GUIDed section to be processed. @param OutputBufferSize The size of OutputBuffer. @param ScratchBufferSize The size of ScratchBuffer. @param SectionAttribute The attribute of the input guided section. @retval EFI_SUCCESS The size of destination buffer, the size of scratch buffer and the attribute of the input section are successull retrieved. @retval EFI_INVALID_PARAMETER The GUID in InputSection does not match this instance guid. **/ EFI_STATUS EFIAPI Rsa2048Sha256GuidedSectionGetInfo ( IN CONST VOID *InputSection, OUT UINT32 *OutputBufferSize, OUT UINT32 *ScratchBufferSize, OUT UINT16 *SectionAttribute ) { if (IS_SECTION2 (InputSection)) { // // Check whether the input guid section is recognized. // if (!CompareGuid ( &gEfiCertTypeRsa2048Sha256Guid, &(((EFI_GUID_DEFINED_SECTION2 *) InputSection)->SectionDefinitionGuid))) { return EFI_INVALID_PARAMETER; } // // Retrieve the size and attribute of the input section data. // *SectionAttribute = ((EFI_GUID_DEFINED_SECTION2 *) InputSection)->Attributes; *ScratchBufferSize = 0; *OutputBufferSize = SECTION2_SIZE (InputSection) - ((EFI_GUID_DEFINED_SECTION2 *) InputSection)->DataOffset; } else { // // Check whether the input guid section is recognized. // if (!CompareGuid ( &gEfiCertTypeRsa2048Sha256Guid, &(((EFI_GUID_DEFINED_SECTION *) InputSection)->SectionDefinitionGuid))) { return EFI_INVALID_PARAMETER; } // // Retrieve the size and attribute of the input section data. // *SectionAttribute = ((EFI_GUID_DEFINED_SECTION *) InputSection)->Attributes; *ScratchBufferSize = 0; *OutputBufferSize = SECTION_SIZE (InputSection) - ((EFI_GUID_DEFINED_SECTION *) InputSection)->DataOffset; } return EFI_SUCCESS; } /** Extraction handler tries to extract raw data from the input guided section. It also does authentication check for RSA 2048 SHA 256 signature in the input guided section. It first checks whether the input guid section is supported. If not, EFI_INVALID_PARAMETER will return. @param InputSection Buffer containing the input GUIDed section to be processed. @param OutputBuffer Buffer to contain the output raw data allocated by the caller. @param ScratchBuffer A pointer to a caller-allocated buffer for function internal use. @param AuthenticationStatus A pointer to a caller-allocated UINT32 that indicates the authentication status of the output buffer. @retval EFI_SUCCESS Section Data and Auth Status is extracted successfully. @retval EFI_INVALID_PARAMETER The GUID in InputSection does not match this instance guid. **/ EFI_STATUS EFIAPI Rsa2048Sha256GuidedSectionHandler ( IN CONST VOID *InputSection, OUT VOID **OutputBuffer, IN VOID *ScratchBuffer, OPTIONAL OUT UINT32 *AuthenticationStatus ) { EFI_STATUS Status; UINT32 OutputBufferSize; EFI_CERT_BLOCK_RSA_2048_SHA256 *CertBlockRsa2048Sha256; BOOLEAN CryptoStatus; UINT8 Digest[SHA256_DIGEST_SIZE]; UINT8 *PublicKey; UINTN PublicKeyBufferSize; VOID *HashContext; VOID *Rsa; HashContext = NULL; Rsa = NULL; if (IS_SECTION2 (InputSection)) { // // Check whether the input guid section is recognized. // if (!CompareGuid ( &gEfiCertTypeRsa2048Sha256Guid, &(((EFI_GUID_DEFINED_SECTION2 *)InputSection)->SectionDefinitionGuid))) { return EFI_INVALID_PARAMETER; } // // Get the RSA 2048 SHA 256 information. // CertBlockRsa2048Sha256 = &((RSA_2048_SHA_256_SECTION2_HEADER *) InputSection)->CertBlockRsa2048Sha256; OutputBufferSize = SECTION2_SIZE (InputSection) - sizeof (RSA_2048_SHA_256_SECTION2_HEADER); if ((((EFI_GUID_DEFINED_SECTION *)InputSection)->Attributes & EFI_GUIDED_SECTION_PROCESSING_REQUIRED) != 0) { PERF_START (NULL, "RsaCopy", "PEI", 0); CopyMem (*OutputBuffer, (UINT8 *)InputSection + sizeof (RSA_2048_SHA_256_SECTION2_HEADER), OutputBufferSize); PERF_END (NULL, "RsaCopy", "PEI", 0); } else { *OutputBuffer = (UINT8 *)InputSection + sizeof (RSA_2048_SHA_256_SECTION2_HEADER); } // // Implicitly RSA 2048 SHA 256 GUIDed section should have STATUS_VALID bit set // ASSERT ((((EFI_GUID_DEFINED_SECTION2 *)InputSection)->Attributes & EFI_GUIDED_SECTION_AUTH_STATUS_VALID) != 0); *AuthenticationStatus = EFI_AUTH_STATUS_IMAGE_SIGNED; } else { // // Check whether the input guid section is recognized. // if (!CompareGuid ( &gEfiCertTypeRsa2048Sha256Guid, &(((EFI_GUID_DEFINED_SECTION *)InputSection)->SectionDefinitionGuid))) { return EFI_INVALID_PARAMETER; } // // Get the RSA 2048 SHA 256 information. // CertBlockRsa2048Sha256 = &((RSA_2048_SHA_256_SECTION_HEADER *)InputSection)->CertBlockRsa2048Sha256; OutputBufferSize = SECTION_SIZE (InputSection) - sizeof (RSA_2048_SHA_256_SECTION_HEADER); if ((((EFI_GUID_DEFINED_SECTION *)InputSection)->Attributes & EFI_GUIDED_SECTION_PROCESSING_REQUIRED) != 0) { PERF_START (NULL, "RsaCopy", "PEI", 0); CopyMem (*OutputBuffer, (UINT8 *)InputSection + sizeof (RSA_2048_SHA_256_SECTION_HEADER), OutputBufferSize); PERF_END (NULL, "RsaCopy", "PEI", 0); } else { *OutputBuffer = (UINT8 *)InputSection + sizeof (RSA_2048_SHA_256_SECTION_HEADER); } // // Implicitly RSA 2048 SHA 256 GUIDed section should have STATUS_VALID bit set // ASSERT ((((EFI_GUID_DEFINED_SECTION *) InputSection)->Attributes & EFI_GUIDED_SECTION_AUTH_STATUS_VALID) != 0); *AuthenticationStatus = EFI_AUTH_STATUS_IMAGE_SIGNED; } // // All paths from here return EFI_SUCESS and result is returned in AuthenticationStatus // Status = EFI_SUCCESS; // // Fail if the HashType is not SHA 256 // if (!CompareGuid (&gEfiHashAlgorithmSha256Guid, &CertBlockRsa2048Sha256->HashType)) { DEBUG ((DEBUG_ERROR, "PeiRsa2048Sha256: HASH type of section is not supported\n")); *AuthenticationStatus |= EFI_AUTH_STATUS_TEST_FAILED; goto Done; } // // Allocate hash context buffer required for SHA 256 // HashContext = AllocatePool (Sha256GetContextSize ()); if (HashContext == NULL) { DEBUG ((DEBUG_ERROR, "PeiRsa2048Sha256: Can not allocate hash context\n")); *AuthenticationStatus |= EFI_AUTH_STATUS_TEST_FAILED; goto Done; } // // Hash public key from data payload with SHA256. // ZeroMem (Digest, SHA256_DIGEST_SIZE); CryptoStatus = Sha256Init (HashContext); if (!CryptoStatus) { DEBUG ((DEBUG_ERROR, "PeiRsa2048Sha256: Sha256Init() failed\n")); *AuthenticationStatus |= EFI_AUTH_STATUS_TEST_FAILED; goto Done; } CryptoStatus = Sha256Update (HashContext, &CertBlockRsa2048Sha256->PublicKey, sizeof(CertBlockRsa2048Sha256->PublicKey)); if (!CryptoStatus) { DEBUG ((DEBUG_ERROR, "PeiRsa2048Sha256: Sha256Update() failed\n")); *AuthenticationStatus |= EFI_AUTH_STATUS_TEST_FAILED; goto Done; } CryptoStatus = Sha256Final (HashContext, Digest); if (!CryptoStatus) { DEBUG ((DEBUG_ERROR, "PeiRsa2048Sha256: Sha256Final() failed\n")); *AuthenticationStatus |= EFI_AUTH_STATUS_TEST_FAILED; goto Done; } // // Fail if the PublicKey is not one of the public keys in PcdRsa2048Sha256PublicKeyBuffer // PublicKey = (UINT8 *)PcdGetPtr (PcdRsa2048Sha256PublicKeyBuffer); DEBUG ((DEBUG_VERBOSE, "PeiPcdRsa2048Sha256: PublicKeyBuffer = %p\n", PublicKey)); ASSERT (PublicKey != NULL); DEBUG ((DEBUG_VERBOSE, "PeiPcdRsa2048Sha256: PublicKeyBuffer Token = %08x\n", PcdToken (PcdRsa2048Sha256PublicKeyBuffer))); PublicKeyBufferSize = LibPcdGetExSize (&gEfiSecurityPkgTokenSpaceGuid, PcdToken (PcdRsa2048Sha256PublicKeyBuffer)); DEBUG ((DEBUG_VERBOSE, "PeiPcdRsa2048Sha256: PublicKeyBuffer Size = %08x\n", PublicKeyBufferSize)); ASSERT ((PublicKeyBufferSize % SHA256_DIGEST_SIZE) == 0); CryptoStatus = FALSE; while (PublicKeyBufferSize != 0) { if (CompareMem (Digest, PublicKey, SHA256_DIGEST_SIZE) == 0) { CryptoStatus = TRUE; break; } PublicKey = PublicKey + SHA256_DIGEST_SIZE; PublicKeyBufferSize = PublicKeyBufferSize - SHA256_DIGEST_SIZE; } if (!CryptoStatus) { DEBUG ((DEBUG_ERROR, "PeiRsa2048Sha256: Public key in section is not supported\n")); *AuthenticationStatus |= EFI_AUTH_STATUS_TEST_FAILED; goto Done; } // // Generate & Initialize RSA Context. // Rsa = RsaNew (); if (Rsa == NULL) { DEBUG ((DEBUG_ERROR, "PeiRsa2048Sha256: RsaNew() failed\n")); *AuthenticationStatus |= EFI_AUTH_STATUS_TEST_FAILED; goto Done; } // // Set RSA Key Components. // NOTE: Only N and E are needed to be set as RSA public key for signature verification. // CryptoStatus = RsaSetKey (Rsa, RsaKeyN, CertBlockRsa2048Sha256->PublicKey, sizeof(CertBlockRsa2048Sha256->PublicKey)); if (!CryptoStatus) { DEBUG ((DEBUG_ERROR, "PeiRsa2048Sha256: RsaSetKey(RsaKeyN) failed\n")); *AuthenticationStatus |= EFI_AUTH_STATUS_TEST_FAILED; goto Done; } CryptoStatus = RsaSetKey (Rsa, RsaKeyE, mRsaE, sizeof (mRsaE)); if (!CryptoStatus) { DEBUG ((DEBUG_ERROR, "PeiRsa2048Sha256: RsaSetKey(RsaKeyE) failed\n")); *AuthenticationStatus |= EFI_AUTH_STATUS_TEST_FAILED; goto Done; } // // Hash data payload with SHA256. // ZeroMem (Digest, SHA256_DIGEST_SIZE); CryptoStatus = Sha256Init (HashContext); if (!CryptoStatus) { DEBUG ((DEBUG_ERROR, "PeiRsa2048Sha256: Sha256Init() failed\n")); *AuthenticationStatus |= EFI_AUTH_STATUS_TEST_FAILED; goto Done; } PERF_START (NULL, "RsaShaData", "PEI", 0); CryptoStatus = Sha256Update (HashContext, *OutputBuffer, OutputBufferSize); PERF_END (NULL, "RsaShaData", "PEI", 0); if (!CryptoStatus) { DEBUG ((DEBUG_ERROR, "PeiRsa2048Sha256: Sha256Update() failed\n")); *AuthenticationStatus |= EFI_AUTH_STATUS_TEST_FAILED; goto Done; } CryptoStatus = Sha256Final (HashContext, Digest); if (!CryptoStatus) { DEBUG ((DEBUG_ERROR, "PeiRsa2048Sha256: Sha256Final() failed\n")); *AuthenticationStatus |= EFI_AUTH_STATUS_TEST_FAILED; goto Done; } // // Verify the RSA 2048 SHA 256 signature. // PERF_START (NULL, "RsaVerify", "PEI", 0); CryptoStatus = RsaPkcs1Verify ( Rsa, Digest, SHA256_DIGEST_SIZE, CertBlockRsa2048Sha256->Signature, sizeof (CertBlockRsa2048Sha256->Signature) ); PERF_END (NULL, "RsaVerify", "PEI", 0); if (!CryptoStatus) { // // If RSA 2048 SHA 256 signature verification fails, AUTH tested failed bit is set. // DEBUG ((DEBUG_ERROR, "PeiRsa2048Sha256: RsaPkcs1Verify() failed\n")); *AuthenticationStatus |= EFI_AUTH_STATUS_TEST_FAILED; } Done: // // Free allocated resources used to perform RSA 2048 SHA 256 signature verification // if (Rsa != NULL) { RsaFree (Rsa); } if (HashContext != NULL) { FreePool (HashContext); } // // Temp solution until PeiCore checks AUTH Status. // if ((*AuthenticationStatus & (EFI_AUTH_STATUS_TEST_FAILED | EFI_AUTH_STATUS_NOT_TESTED)) != 0) { Status = EFI_ACCESS_DENIED; } DEBUG ((DEBUG_VERBOSE, "PeiRsa2048Sha256: Status = %r AuthenticationStatus = %08x\n", Status, *AuthenticationStatus)); return Status; } /** Register the handler to extract RSA 2048 SHA 256 guided section. @param FileHandle The handle of FFS header the loaded driver. @param PeiServices The pointer to the PEI services. @retval EFI_SUCCESS Register successfully. @retval EFI_OUT_OF_RESOURCES Not enough memory to register this handler. **/ EFI_STATUS EFIAPI PeiRsa2048Sha256GuidedSectionExtractLibConstructor ( IN EFI_PEI_FILE_HANDLE FileHandle, IN CONST EFI_PEI_SERVICES **PeiServices ) { return ExtractGuidedSectionRegisterHandlers ( &gEfiCertTypeRsa2048Sha256Guid, Rsa2048Sha256GuidedSectionGetInfo, Rsa2048Sha256GuidedSectionHandler ); }
miguelinux/vbox
src/VBox/Devices/EFI/Firmware/SecurityPkg/Library/PeiRsa2048Sha256GuidedSectionExtractLib/PeiRsa2048Sha256GuidedSectionExtractLib.c
C
gpl-2.0
14,381
/* * Copyright (C) 2004 * Swiss Federal Institute of Technology, Lausanne. All rights reserved. * * Author: Roland Philippsen <roland dot philippsen at gmx dot net> * Autonomous Systems Lab <http://asl.epfl.ch/> * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 * USA */ #ifndef OCAMERA_HPP #define OCAMERA_HPP #include <npm/gfx/Camera.hpp> namespace sfl { class DynamicWindow; } class OCamera : public npm::Camera { public: OCamera(const std::string & name, const sfl::DynamicWindow & dwa); virtual void ConfigureView(npm::View & view); private: const sfl::DynamicWindow & m_dwa; }; #endif // OCAMERA_HPP
poftwaresatent/sfl2
npm/ext/expo02/OCamera.hpp
C++
gpl-2.0
1,314
/** * asyn Driver for Serial port on Camera Link grabber. Functions like standard rs232 port in ASyn. * *@author Timothy Madden *@date 2013 */ #ifndef camLinkSerial_H #define camLinkSerial_H #include "asynPortDriver.h" #include "comportInterface.h" #include "siswSerialPort.h" #include "sw_com_port.h" #include "logfile.h" #ifdef _WIN32 #include "cl_com_port2.h" #endif #include <string.h> #include <map> /** * Class for serial port on grabber. Acts like asyn rs232 driver. */ class epicsShareFunc camLinkSerial : public asynPortDriver { public: camLinkSerial(const char *portName, const char *comportname, int maxAddr, int interfaceMask, int interruptMask, int asynFlags, int autoConnect, int priority, int stackSize); /* These are the methods that we override from asynPortDriver */ virtual asynStatus readOctet(asynUser *pasynUser, char *value, size_t maxChars, size_t *nActual, int *eomReason); virtual asynStatus writeOctet(asynUser *pasynUser, const char *value, size_t maxChars, size_t *nActual); virtual asynStatus flushOctet(asynUser *pasynUser); virtual void report(FILE *fp, int details); void optionsToSerial(void); virtual asynStatus readOption(asynUser *pasynUser, const char *key, char *value, int maxChars); virtual asynStatus writeOption(asynUser *pasynUser, const char *key, const char *value); protected: // map for the option key val pairs std::map<std::string, std::string> option_pairs; comportInterface *serial_port; // // params // int clser_first; #define FIRST_CLS_PARAM clser_first int clser_portname; int clser_last; #define LAST_CLS_PARAM clser_last // // End params // log_file lf; }; #define NUM_CLS_PARAMS (&LAST_CLS_PARAM - &FIRST_CLS_PARAM + 1) #endif
argonnexraydetector/ADCameralink
cameralinkApp/src/camLinkSerial.h
C
gpl-2.0
1,949
#!/usr/bin/env python # coding: utf-8 # Copyright (c) 2014 # Gmail:liuzheng712 # __author__ = 'liuzheng' from django.conf.urls import patterns, include, url from django.contrib import admin import os urlpatterns = patterns('', # Examples: # url(r'^$', 'pyHBase.views.home', name='home'), # url(r'^blog/', include('blog.urls')), url(r'^$', 'pyHBase.views.index'), url(r'^admin/(.*)$', 'pyHBase.views.admin'), url(r'^DJadmin/', include(admin.site.urls)), url(r'^css/(?P<path>.*)$', 'django.views.static.serve', {'document_root': os.path.join(os.path.dirname(__file__), '../templates/css').replace('\\', '/')}), url(r'^js/(?P<path>.*)$', 'django.views.static.serve', {'document_root': os.path.join(os.path.dirname(__file__), '../templates/js').replace('\\', '/')}), url(r'^img/(?P<path>.*)$', 'django.views.static.serve', {'document_root': os.path.join(os.path.dirname(__file__), '../templates/img').replace('\\', '/')}), (r'^api/', include('api.urls')), )
liuzheng712/pyHBaseadmin
pyHBase/pyHBase/urls.py
Python
gpl-2.0
1,013
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <!-- NewPage --> <html lang="en"> <head> <!-- Generated by javadoc (version 1.7.0_17) on Sun Oct 12 14:22:55 CDT 2014 --> <title>com.flamingOctoIronman.timer Class Hierarchy</title> <meta name="date" content="2014-10-12"> <link rel="stylesheet" type="text/css" href="../../../stylesheet.css" title="Style"> </head> <body> <script type="text/javascript"><!-- if (location.href.indexOf('is-external=true') == -1) { parent.document.title="com.flamingOctoIronman.timer Class Hierarchy"; } //--> </script> <noscript> <div>JavaScript is disabled on your browser.</div> </noscript> <!-- ========= START OF TOP NAVBAR ======= --> <div class="topNav"><a name="navbar_top"> <!-- --> </a><a href="#skip-navbar_top" title="Skip navigation links"></a><a name="navbar_top_firstrow"> <!-- --> </a> <ul class="navList" title="Navigation"> <li><a href="../../../overview-summary.html">Overview</a></li> <li><a href="package-summary.html">Package</a></li> <li>Class</li> <li>Use</li> <li class="navBarCell1Rev">Tree</li> <li><a href="../../../deprecated-list.html">Deprecated</a></li> <li><a href="../../../index-files/index-1.html">Index</a></li> <li><a href="../../../help-doc.html">Help</a></li> </ul> </div> <div class="subNav"> <ul class="navList"> <li><a href="../../../com/flamingOctoIronman/math/vector/package-tree.html">Prev</a></li> <li><a href="../../../com/flamingOctoIronman/tools/package-tree.html">Next</a></li> </ul> <ul class="navList"> <li><a href="../../../index.html?com/flamingOctoIronman/timer/package-tree.html" target="_top">Frames</a></li> <li><a href="package-tree.html" target="_top">No Frames</a></li> </ul> <ul class="navList" id="allclasses_navbar_top"> <li><a href="../../../allclasses-noframe.html">All Classes</a></li> </ul> <div> <script type="text/javascript"><!-- allClassesLink = document.getElementById("allclasses_navbar_top"); if(window==top) { allClassesLink.style.display = "block"; } else { allClassesLink.style.display = "none"; } //--> </script> </div> <a name="skip-navbar_top"> <!-- --> </a></div> <!-- ========= END OF TOP NAVBAR ========= --> <div class="header"> <h1 class="title">Hierarchy For Package com.flamingOctoIronman.timer</h1> <span class="strong">Package Hierarchies:</span> <ul class="horizontal"> <li><a href="../../../overview-tree.html">All Packages</a></li> </ul> </div> <div class="contentContainer"> <h2 title="Class Hierarchy">Class Hierarchy</h2> <ul> <li type="circle">java.lang.Object <ul> <li type="circle">com.flamingOctoIronman.timer.<a href="../../../com/flamingOctoIronman/timer/TickCalculator.html" title="class in com.flamingOctoIronman.timer"><span class="strong">TickCalculator</span></a></li> <li type="circle">com.flamingOctoIronman.timer.<a href="../../../com/flamingOctoIronman/timer/Timer.html" title="class in com.flamingOctoIronman.timer"><span class="strong">Timer</span></a></li> </ul> </li> </ul> </div> <!-- ======= START OF BOTTOM NAVBAR ====== --> <div class="bottomNav"><a name="navbar_bottom"> <!-- --> </a><a href="#skip-navbar_bottom" title="Skip navigation links"></a><a name="navbar_bottom_firstrow"> <!-- --> </a> <ul class="navList" title="Navigation"> <li><a href="../../../overview-summary.html">Overview</a></li> <li><a href="package-summary.html">Package</a></li> <li>Class</li> <li>Use</li> <li class="navBarCell1Rev">Tree</li> <li><a href="../../../deprecated-list.html">Deprecated</a></li> <li><a href="../../../index-files/index-1.html">Index</a></li> <li><a href="../../../help-doc.html">Help</a></li> </ul> </div> <div class="subNav"> <ul class="navList"> <li><a href="../../../com/flamingOctoIronman/math/vector/package-tree.html">Prev</a></li> <li><a href="../../../com/flamingOctoIronman/tools/package-tree.html">Next</a></li> </ul> <ul class="navList"> <li><a href="../../../index.html?com/flamingOctoIronman/timer/package-tree.html" target="_top">Frames</a></li> <li><a href="package-tree.html" target="_top">No Frames</a></li> </ul> <ul class="navList" id="allclasses_navbar_bottom"> <li><a href="../../../allclasses-noframe.html">All Classes</a></li> </ul> <div> <script type="text/javascript"><!-- allClassesLink = document.getElementById("allclasses_navbar_bottom"); if(window==top) { allClassesLink.style.display = "block"; } else { allClassesLink.style.display = "none"; } //--> </script> </div> <a name="skip-navbar_bottom"> <!-- --> </a></div> <!-- ======== END OF BOTTOM NAVBAR ======= --> </body> </html>
fh3/flaming-octo-ironman
doc/com/flamingOctoIronman/timer/package-tree.html
HTML
gpl-2.0
4,715
/******************************************************************************************* Copyright 2010 Broadcom Corporation. All rights reserved. Unless you and Broadcom execute a separate written software license agreement governing use of this software, this software is licensed to you under the terms of the GNU General Public License version 2, available at http://www.gnu.org/copyleft/gpl.html (the "GPL"). Notwithstanding the above, under no circumstances may you combine this software in any way with any other Broadcom software provided under a license other than the GPL, without Broadcom's express prior written consent. *******************************************************************************************/ //*************************************************************************** /** * * @file xscript_kernel.h * * @brief Interface to the xscript kernel driver. * * @note This driver is typically used for handling xScript kernel APIs. * ****************************************************************************/ #ifndef XSCRIPT_KERNEL_H__ #define XSCRIPT_KERNEL_H__ #ifdef __cplusplus extern "C" { #endif // __cplusplus #define XSCRIPT_KERNEL_MODULE_NAME "bcm_xscript" /** * * ioctl commands * **/ enum { XSCRIPT_KERNEL_CMD_CLK_GET = 200 ///< Get clock. Data: XS_KERNEL_ClkGet_t ,XSCRIPT_KERNEL_CMD_CLK_GET_RATE = 201 ///< Get clock rate. Data: XS_KERNEL_ClkGetRate_t ,XSCRIPT_KERNEL_CMD_CLK_SET_RATE = 202 ///< Set clock rate. Data: XS_KERNEL_ClkSetRate_t }; /** * for ioctl cmd XSCRIPT_KERNEL_CMD_CLK_GET, a variable of this type * is passed as the 'arg' to ioctl() */ typedef struct { struct device * fDev; ///< device for clock "consumer" XS_BcmClk_t fId; ///< clock comsumer ID struct clk * fOutClk; ///< (output) clock source } XS_KERNEL_ClkGet_t; /** * for ioctl cmd XSCRIPT_KERNEL_CMD_CLK_GET_RATE, a variable of this type * is passed as the 'arg' to ioctl() */ typedef struct { struct clk * fClk; ///< clock source unsigned long fOutRate; ///< (output) clock rate in Hz } XS_KERNEL_ClkGetRate_t; /** * for ioctl cmd XSCRIPT_KERNEL_CMD_CLK_SET_RATE, a variable of this type * is passed as the 'arg' to ioctl() */ typedef struct { struct clk * fClk; ///< clock source unsigned long fRate; ///< desired clock rate in Hz unsigned long fOutErrno;///< (output) 0 on success, or errno if error occurred. } XS_KERNEL_ClkSetRate_t; #ifdef __cplusplus } #endif // __cplusplus #endif // XSCRIPT_KERNEL_H__
Maroc-OS/Merruk-Technology
modules/drivers/char/brcm/xscript/xscript_kernel.h
C
gpl-2.0
2,509
<!DOCTYPE html> <html> <head> <meta charset="utf-8"> <meta name="renderer" content="webkit"/> <title>答案解析</title> <meta name="keywords" content="navigation"/> <meta name="descration" contant="work"/> <meta name="viewport" content="initial-scale=1,width=device-width,maximum-scale=1,minimum-scale=1,user-scalable=no"> <meta name="apple-mobile-web-app-capable" content="yes"> <meta name='apple-touch-fullscreen' content='yes'> <meta name="apple-mobile-web-app-status-bar-style" content="black"> <meta name="format-detection" content="telephone=no"> <meta name="format-detection" content="address=no"> <link type="text/css" rel="stylesheet" href="../css/daanjiexi.css" source="widget"/> </head> <body> <div class="header clearfix"> <b></b> <p>答案解析</p> </div> <div class="video1"> <img src="image/bofang2.png"/> <a href="#"></a> </div> <div class="daan1 clearfix"> <img src="image/suxing.png"/> <a href="#">下载</a> <div class="su1"> <span>苏醒</span><b></b> <p>北京师范大学附属中学</p> </div> </div> <div class="clear"></div> <div class="daan2"> <a class="a1" href="#"></a><h3>题目</h3> <div class="dada"> <p>下列有关文学常识的表述,不正确的一项是( )</p> <p>A.被称作“前四史”的史书是:《史记》《汉书》</p> <p>B.元曲四大家是:关汉卿、白朴、马致远和</p> </div> </div> <div class="daan3"> <h3>答案及解析</h3> <p>1.把n个不同元素放在圆周n个无编号位置上的排列,顺序(例如按顺时钟)不同的排法才算不同的排列,而位之分</p> <p>2.顺序相同(即旋转一下就可以重合)的排法认为是相同的,它与普通排列的区别在于</p> </div> <div class="tancen"> </div> <div class="tancen2 clearfix"> <img src="image/daxiang.png"/> <a href="#"><img src="image/don.png"/><p>下载</p></a> <div class="zj"> <h3>天天象上</h3> <h4>学海无涯 考试无忧</h4> </div> </div> </body> </html>
queena1993/queena1993.github.io
eigth/html/daanjiexi.html
HTML
gpl-2.0
2,100
package com.opentravelsoft.entity.product; import com.opentravelsoft.util.MD5; /** * * @author <a herf="mailto:zhangsitao@gmail.com">Steven Zhang</a> * @version $Revision: 1.1 $ $Date: 2009/03/01 16:23:32 $ */ public class NetPayEntity { /** * 商户号,这里为测试商户号1001,替换为自己的商户号(老版商户号为4位或5位,新版为8位)即可 */ private String mid; /** * 如果您还没有设置MD5密钥请登陆我们为您提供商户后台,<br> * 地址:https://merchant3.chinabank.com.cn/ * 登陆后在上面的导航栏里可能找到“B2C”,在二级导航栏里有“MD5密钥设置” * 建议您设置一个16位以上的密钥或更高,密钥最多64位,但设置16位已经足够了 */ private String key; /** 商户自定义返回接收支付结果的页面 */ private String url; /** 订单号 */ private String oid; /** 订单金额 */ private String amount; /** 币种 */ private String moneytype; /** 对拼凑串MD5私钥加密后的值 */ private String md5info; /** 收货人 */ private String rcvname; /** 收货地址 */ private String rcvaddr; /** 收货人电话 */ private String rcvtel; /** 收货人邮编 */ private String rcvpost; /** 收货人邮件 */ private String rcvemail; /** 收货人手机号 */ private String rcvmobile; // ------------------------------------------------------------------------- /** 订货人姓名 */ private String ordername; /** 订货人地址 */ private String orderaddr; /** 订货人电话 */ private String ordertel; /** 订货人邮编 */ private String orderpost; /** 订货人邮件 */ private String orderemail; /** 订货人手机号 */ private String ordermobile; // ------------------------------------------------------------------------- /** 备注字段1 */ private String remark1; /** 备注字段2 */ private String remark2; public NetPayEntity() { // 初始化定义参数 mid = "1001"; url = "http://www.opentravelsoft.com/ReceivePay.action"; key = "test"; moneytype = "CNY"; } public String getMid() { return mid; } public void setMid(String mid) { this.mid = mid; } public String getKey() { return key; } public void setKey(String key) { this.key = key; } public String getUrl() { return url; } public void setUrl(String url) { this.url = url; } public String getOid() { return oid; } public void setOid(String oid) { this.oid = oid; } public String getAmount() { return amount; } public void setAmount(String amount) { this.amount = amount; } public String getMoneytype() { return moneytype; } public void setMoneytype(String moneytype) { this.moneytype = moneytype; } public String getMd5info() { return md5info; } public void setMd5info(String md5info) { this.md5info = md5info; } public String getRcvname() { return rcvname; } public void setRcvname(String rcvname) { this.rcvname = rcvname; } public String getRcvaddr() { return rcvaddr; } public void setRcvaddr(String rcvaddr) { this.rcvaddr = rcvaddr; } public String getRcvtel() { return rcvtel; } public void setRcvtel(String rcvtel) { this.rcvtel = rcvtel; } public String getRcvpost() { return rcvpost; } public void setRcvpost(String rcvpost) { this.rcvpost = rcvpost; } public String getRcvemail() { return rcvemail; } public void setRcvemail(String rcvemail) { this.rcvemail = rcvemail; } public String getRcvmobile() { return rcvmobile; } public void setRcvmobile(String rcvmobile) { this.rcvmobile = rcvmobile; } public String getOrdername() { return ordername; } public void setOrdername(String ordername) { this.ordername = ordername; } public String getOrderaddr() { return orderaddr; } public void setOrderaddr(String orderaddr) { this.orderaddr = orderaddr; } public String getOrdertel() { return ordertel; } public void setOrdertel(String ordertel) { this.ordertel = ordertel; } public String getOrderpost() { return orderpost; } public void setOrderpost(String orderpost) { this.orderpost = orderpost; } public String getOrderemail() { return orderemail; } public void setOrderemail(String orderemail) { this.orderemail = orderemail; } public String getOrdermobile() { return ordermobile; } public void setOrdermobile(String ordermobile) { this.ordermobile = ordermobile; } public String getRemark1() { return remark1; } public void setRemark1(String remark1) { this.remark1 = remark1; } public String getRemark2() { return remark2; } public void setRemark2(String remark2) { this.remark2 = remark2; } public void refreshMd5key() { String text = amount + moneytype + oid + mid + url + key; // 拼凑加密串 md5info = new MD5().getMD5ofStr(text); // // 网银支付平台对MD5值只认大写字符串,所以小写的MD5值得转换为大写 } }
stevenzh/tourismwork
src/modules/model/src/main/java/com/opentravelsoft/entity/product/NetPayEntity.java
Java
gpl-2.0
5,861
@iamtakashi @iandstewart @dd32 @mor10 @grapplerulrich @davidakennedy @frank-klein @tywayne @wenthemes @monika @metodiew @nhuja @headonfire @Chrisdc1 @philiparthurmoore @karpstrucking @cais @mt8.biz @fjarrett @sdavis2702 @SergeyBiryukov @eduardozulian @webdevmattcrom @ehtis @peterwilsoncc @tfrommen @fsylum @wonderboymusic @ocean90 @obenland
cchuang6/wp_adora
wp-content/themes/twentysixteen/CONTRIBUTORS.md
Markdown
gpl-2.0
342
.tab { padding: 0 0 2pt 4pt; margin: 0; border-bottom: 1px solid black; } .tab li { margin: 0; padding: 0pt 1pt; display: inline; } .tab li a { padding: 2pt; cursor: pointer; border: 1px solid black; text-decoration: none; background-color:#eee; color: black; } .tab li.tabActive a { padding: 3.5pt 3.5pt 2pt 3.5pt; font-weight: bold; background-color: #fff; border-bottom: 1px solid white; } .tab li a:hover { color: #fff; background-color:#182e7a; border: 1px solid black; } .tabContent { } .tabHidden { display: none; }
xemle/phtagr
webroot/css/tab.css
CSS
gpl-2.0
564
<?php /** * All the functions releated to databases is here. * * This file will include stuff like, connect, write, read, remove etc. * * @category Database * @package ControlPanel * @author Dennis &lt;dennistryy3@gmail.com> * @copyright 2014 Dennis Planting */ class Commands { /** * Broadcast a message. * * @param string $message The message to broadcast. * @param string $name Incase you want a different name then the default select it here. <i>Default is "Server"</i> * @param string $default If you want to send a broadcast through the vanilla command or through a plugin like Essentials. * * @return If the command was successfully sent or not. */ function broadcast($message, $name="", $default=false) { } } ?>
ExpandH/EMCP
Core/Function/Plugins/Commands.php
PHP
gpl-2.0
817
package CtrLayer; import ModelLayer.*; /** * Controller for anythign related to Person management. * * @author Jacob Pedersen * @version (11-12-2014) dd-mm-yyyy */ public class PersonController { private PersonContainer personContainer; /** * Constructor for objects of class PersonController */ public PersonController() { personContainer = PersonContainer.getPersonContainer(); addTestPeople(); } /** * Create a new worker and add it to the person container. * @param name the workers name. * @param adress the workes adress. * @param phoneNumber the workes phone number. * @param email The workers e-mail. * @param age The workers age. * @param isLeader if the worker is a leader or not. * @param role The workes role in the company * @param department The department which the worker works in. * @return true if the worker was added successfully. false if not. */ public boolean addWorker(String name, String adress, String phoneNumber, String email, int age, boolean isLeader, String role, String department) { if(personContainer.findPersonByPhoneNumber(phoneNumber) == null) { int id = personContainer.getLastId() + 1; Worker worker = new Worker(id, name, adress, phoneNumber, email, age, isLeader, role, department); personContainer.addWorker(worker); return true; } return false; } /** * Create a new customer and add it to the person container. * @param name the customers name. * @param adress the customers adress. * @param phoneNumber the customers phone number. * @param email The customers e-mail. * @param age The customers age. * @return true if the worker was added successfully. false if not. */ public boolean addCustomer(String name, String adress, String phoneNumber, String email, int age) { if(personContainer.findPersonByPhoneNumber(phoneNumber) == null) { int id = personContainer.getLastId() + 1; Customer customer = new Customer(id, name, adress, phoneNumber, email, age); personContainer.addCustomer(customer); return true; } return false; } /** * Remove a specific person given by it's id. * @param id The persons id. * @return true if the person was removed successfully. false if not. */ public boolean removePersonById(int id) { return personContainer.removePerson(id); } /** * Remove a specific person given by it's phone number. * @param phoneNumber The persons phone number. * @return true if the person was found successfully. false if not. */ public boolean removePersonByPhoneNumber(String phoneNumber) { Person person = personContainer.findPersonByPhoneNumber(phoneNumber); if(person != null) { int id = person.getId(); return personContainer.removePerson(id); } return false; } /** * Find a specific person by the given id. * @param id The persons id. * @return The person if the person was found successfully. null if not. */ public Person findPerson(int id) { return personContainer.findPersonById(id); } /** * Find a specific person by the given phone number. * @param id The persons phone number. * @return The person if the person was found successfully. null if not. */ public Person findPersonByPhoneNumber(String phoneNumber) { return personContainer.findPersonByPhoneNumber(phoneNumber); } /** * Checks if the person is of the type Customer or not * @param person The person to check. * @return true if the person is of the type Customer. false if not. */ public boolean isCustomer(Person person) { if(person instanceof Customer) { return true; } return false; } /** * Add money to a customers balance. * @param person The customer to add the money to of the type person. * @param amount The amount to add to the custoemr. */ public boolean addToCustomerBalanceById(Person person, double amount) { if(isCustomer(person)) { Customer customer = (Customer)person; customer.addToBalance(amount); return true; } return false; } public void addTestPeople() { addWorker("Hans", "Hansevej", "27834173", "gud@gudenet.dk", 20, true, "boss", "all"); addWorker("Jens", "Hansevej", "27834174", "guden@gudenet.dk", 20, true, "boss", "all"); addCustomer("Sofie", "Sofievej", "88888888", "sofie@sofienet.dk", 20); } }
dmab0914-Gruppe-2/Vestbjerg-Byggecenter
src/CtrLayer/PersonController.java
Java
gpl-2.0
4,942
package containernode import ( "math/rand" "sort" "github.com/obieq/goar/db/couchbase/Godeps/_workspace/src/github.com/onsi/ginkgo/internal/leafnodes" "github.com/obieq/goar/db/couchbase/Godeps/_workspace/src/github.com/onsi/ginkgo/types" ) type subjectOrContainerNode struct { containerNode *ContainerNode subjectNode leafnodes.SubjectNode } func (n subjectOrContainerNode) text() string { if n.containerNode != nil { return n.containerNode.Text() } else { return n.subjectNode.Text() } } type CollatedNodes struct { Containers []*ContainerNode Subject leafnodes.SubjectNode } type ContainerNode struct { text string flag types.FlagType codeLocation types.CodeLocation setupNodes []leafnodes.BasicNode subjectAndContainerNodes []subjectOrContainerNode } func New(text string, flag types.FlagType, codeLocation types.CodeLocation) *ContainerNode { return &ContainerNode{ text: text, flag: flag, codeLocation: codeLocation, } } func (container *ContainerNode) Shuffle(r *rand.Rand) { sort.Sort(container) permutation := r.Perm(len(container.subjectAndContainerNodes)) shuffledNodes := make([]subjectOrContainerNode, len(container.subjectAndContainerNodes)) for i, j := range permutation { shuffledNodes[i] = container.subjectAndContainerNodes[j] } container.subjectAndContainerNodes = shuffledNodes } func (node *ContainerNode) BackPropagateProgrammaticFocus() bool { if node.flag == types.FlagTypePending { return false } shouldUnfocus := false for _, subjectOrContainerNode := range node.subjectAndContainerNodes { if subjectOrContainerNode.containerNode != nil { shouldUnfocus = subjectOrContainerNode.containerNode.BackPropagateProgrammaticFocus() || shouldUnfocus } else { shouldUnfocus = (subjectOrContainerNode.subjectNode.Flag() == types.FlagTypeFocused) || shouldUnfocus } } if shouldUnfocus { if node.flag == types.FlagTypeFocused { node.flag = types.FlagTypeNone } return true } return node.flag == types.FlagTypeFocused } func (node *ContainerNode) Collate() []CollatedNodes { return node.collate([]*ContainerNode{}) } func (node *ContainerNode) collate(enclosingContainers []*ContainerNode) []CollatedNodes { collated := make([]CollatedNodes, 0) containers := make([]*ContainerNode, len(enclosingContainers)) copy(containers, enclosingContainers) containers = append(containers, node) for _, subjectOrContainer := range node.subjectAndContainerNodes { if subjectOrContainer.containerNode != nil { collated = append(collated, subjectOrContainer.containerNode.collate(containers)...) } else { collated = append(collated, CollatedNodes{ Containers: containers, Subject: subjectOrContainer.subjectNode, }) } } return collated } func (node *ContainerNode) PushContainerNode(container *ContainerNode) { node.subjectAndContainerNodes = append(node.subjectAndContainerNodes, subjectOrContainerNode{containerNode: container}) } func (node *ContainerNode) PushSubjectNode(subject leafnodes.SubjectNode) { node.subjectAndContainerNodes = append(node.subjectAndContainerNodes, subjectOrContainerNode{subjectNode: subject}) } func (node *ContainerNode) PushSetupNode(setupNode leafnodes.BasicNode) { node.setupNodes = append(node.setupNodes, setupNode) } func (node *ContainerNode) SetupNodesOfType(nodeType types.SpecComponentType) []leafnodes.BasicNode { nodes := []leafnodes.BasicNode{} for _, setupNode := range node.setupNodes { if setupNode.Type() == nodeType { nodes = append(nodes, setupNode) } } return nodes } func (node *ContainerNode) Text() string { return node.text } func (node *ContainerNode) CodeLocation() types.CodeLocation { return node.codeLocation } func (node *ContainerNode) Flag() types.FlagType { return node.flag } //sort.Interface func (node *ContainerNode) Len() int { return len(node.subjectAndContainerNodes) } func (node *ContainerNode) Less(i, j int) bool { return node.subjectAndContainerNodes[i].text() < node.subjectAndContainerNodes[j].text() } func (node *ContainerNode) Swap(i, j int) { node.subjectAndContainerNodes[i], node.subjectAndContainerNodes[j] = node.subjectAndContainerNodes[j], node.subjectAndContainerNodes[i] }
obieq/goar
db/couchbase/Godeps/_workspace/src/github.com/onsi/ginkgo/internal/containernode/container_node.go
GO
gpl-2.0
4,264
<?php /** * The template for displaying archive pages * * @link https://codex.wordpress.org/Template_Hierarchy * * @package whank */ get_header(); ?> <?php do_action( 'whank_before_body_content' ); ?> <div id="primary" class="content-area col-md-8"> <main id="main" class="site-main"> <div class="container-fluid"> <div class="row"> <div class="archive page"> <?php if ( have_posts() ) : ?> <header class="page-header page-title text-center"> <?php the_archive_title( '<h2 class="page-title">', '</h2>' ); the_archive_description( '<div class="archive-description">', '</div>' ); ?> </header><!-- .page-header --> <div class=""> <?php /* Start the Loop */ while ( have_posts() ) : the_post(); /* * Include the Post-Format-specific template for the content. * If you want to override this in a child theme, then include a file * called content-___.php (where ___ is the Post Format name) and that will be used instead. */ get_template_part( 'template-parts/content', get_post_format() ); endwhile; get_template_part( 'navigation', 'none'); ?> </div> <?php the_posts_navigation(); else : get_template_part( 'template-parts/content', 'none' ); endif; ?> </div> <!-- archive page div end --> </div> <!-- row end --> </div> <!-- container-fluid --> </main><!-- #main --> </div><!-- #primary --> <?php get_sidebar(); do_action( 'whank_before_body_content' ); get_footer();
saazaan7/whank
archive.php
PHP
gpl-2.0
1,581
package FusionInventory::Agent::Task::Inventory::Virtualization::Virtuozzo; use strict; use warnings; use FusionInventory::Agent::Tools; sub isInventoryEnabled { return can_run('vzlist'); } sub doInventory { my (%params) = @_; my $inventory = $params{inventory}; my $logger = $params{logger}; my $handle = getFileHandle( command => 'vzlist --all --no-header -o hostname,ctid,cpulimit,status,ostemplate', logger => $logger ); return unless $handle; # no service containers in glpi my $line = <$handle>; while (my $line = <$handle>) { chomp $line; my ($name, $uuid, $cpus, $status, $subsys) = split(/[ \t]+/, $line); my $memory = getFirstMatch( file => "/etc/vz/conf/$uuid.conf", pattern => qr/^SLMMEMORYLIMIT="\d+:(\d+)"$/, logger => $logger, ); $memory = $memory / 1024 / 1024 if $memory; $inventory->addVirtualMachine({ NAME => $name, VCPU => $cpus, UUID => $uuid, MEMORY => $memory, STATUS => $status, SUBSYSTEM => $subsys, VMTYPE => "Virtuozzo", }); } close $handle; } 1;
krimdomu/fusioninventory-agent
lib/FusionInventory/Agent/Task/Inventory/Virtualization/Virtuozzo.pm
Perl
gpl-2.0
1,265
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <meta http-equiv="Content-Type" content="text/xhtml;charset=UTF-8"/> <meta http-equiv="X-UA-Compatible" content="IE=9"/> <meta name="generator" content="Doxygen 1.8.4"/> <title>Group Modeling App: HelpSectionViewController Class Reference</title> <link href="tabs.css" rel="stylesheet" type="text/css"/> <script type="text/javascript" src="jquery.js"></script> <script type="text/javascript" src="dynsections.js"></script> <link href="search/search.css" rel="stylesheet" type="text/css"/> <script type="text/javascript" src="search/search.js"></script> <script type="text/javascript"> $(document).ready(function() { searchBox.OnSelectItem(0); }); </script> <link href="doxygen.css" rel="stylesheet" type="text/css" /> </head> <body> <div id="top"><!-- do not remove this div, it is closed by doxygen! --> <div id="titlearea"> <table cellspacing="0" cellpadding="0"> <tbody> <tr style="height: 56px;"> <td style="padding-left: 0.5em;"> <div id="projectname">Group Modeling App </div> </td> </tr> </tbody> </table> </div> <!-- end header part --> <!-- Generated by Doxygen 1.8.4 --> <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><a href="pages.html"><span>Related&#160;Pages</span></a></li> <li class="current"><a href="annotated.html"><span>Data&#160;Structures</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>Data&#160;Structures</span></a></li> <li><a href="classes.html"><span>Data&#160;Structure&#160;Index</span></a></li> <li><a href="hierarchy.html"><span>Class&#160;Hierarchy</span></a></li> <li><a href="functions.html"><span>Data&#160;Fields</span></a></li> </ul> </div> <!-- window showing the filter options --> <div id="MSearchSelectWindow" onmouseover="return searchBox.OnSearchSelectShow()" onmouseout="return searchBox.OnSearchSelectHide()" onkeydown="return searchBox.OnSearchSelectKey(event)"> <a class="SelectItem" href="javascript:void(0)" onclick="searchBox.OnSelectItem(0)"><span class="SelectionMark">&#160;</span>All</a><a class="SelectItem" href="javascript:void(0)" onclick="searchBox.OnSelectItem(1)"><span class="SelectionMark">&#160;</span>Data Structures</a><a class="SelectItem" href="javascript:void(0)" onclick="searchBox.OnSelectItem(2)"><span class="SelectionMark">&#160;</span>Functions</a><a class="SelectItem" href="javascript:void(0)" onclick="searchBox.OnSelectItem(3)"><span class="SelectionMark">&#160;</span>Properties</a><a class="SelectItem" href="javascript:void(0)" onclick="searchBox.OnSelectItem(4)"><span class="SelectionMark">&#160;</span>Pages</a></div> <!-- iframe showing the search results (closed by default) --> <div id="MSearchResultsWindow"> <iframe src="javascript:void(0)" frameborder="0" name="MSearchResults" id="MSearchResults"> </iframe> </div> </div><!-- top --> <div class="header"> <div class="summary"> <a href="#pub-methods">Instance Methods</a> </div> <div class="headertitle"> <div class="title">HelpSectionViewController Class Reference</div> </div> </div><!--header--> <div class="contents"> <p>A Table view controller used to handle the help section. <a href="interface_help_section_view_controller.html#details">More...</a></p> <p><code>#import &lt;<a class="el" href="_help_section_view_controller_8h_source.html">HelpSectionViewController.h</a>&gt;</code></p> <div class="dynheader"> Inheritance diagram for HelpSectionViewController:</div> <div class="dyncontent"> <div class="center"> <img src="interface_help_section_view_controller.png" usemap="#HelpSectionViewController_map" alt=""/> <map id="HelpSectionViewController_map" name="HelpSectionViewController_map"> </map> </div></div> <table class="memberdecls"> <tr class="heading"><td colspan="2"><h2 class="groupheader"><a name="pub-methods"></a> Instance Methods</h2></td></tr> <tr class="memitem:ad9f497773e1c2f5e420929a60f3bf7df"><td class="memItemLeft" align="right" valign="top">(<a class="el" href="interface_m_f_side_menu_container_view_controller.html">MFSideMenuContainerViewController</a> *)&#160;</td><td class="memItemRight" valign="bottom">- <a class="el" href="interface_help_section_view_controller.html#ad9f497773e1c2f5e420929a60f3bf7df">menuContainerViewController</a></td></tr> <tr class="separator:ad9f497773e1c2f5e420929a60f3bf7df"><td class="memSeparator" colspan="2">&#160;</td></tr> <tr class="memitem:a9644bcb73520daa217ad0709b0e6bd64"><td class="memItemLeft" align="right" valign="top"><a class="anchor" id="a9644bcb73520daa217ad0709b0e6bd64"></a> (void)&#160;</td><td class="memItemRight" valign="bottom">- <a class="el" href="interface_help_section_view_controller.html#a9644bcb73520daa217ad0709b0e6bd64">setupMenuBarButtonItems</a></td></tr> <tr class="memdesc:a9644bcb73520daa217ad0709b0e6bd64"><td class="mdescLeft">&#160;</td><td class="mdescRight">Sets up the menu bar of the view controller. <br/></td></tr> <tr class="separator:a9644bcb73520daa217ad0709b0e6bd64"><td class="memSeparator" colspan="2">&#160;</td></tr> <tr class="memitem:afb11718c8a0c6f7abd85dfbc7adb1cd1"><td class="memItemLeft" align="right" valign="top">(UIBarButtonItem *)&#160;</td><td class="memItemRight" valign="bottom">- <a class="el" href="interface_help_section_view_controller.html#afb11718c8a0c6f7abd85dfbc7adb1cd1">leftMenuBarButtonItem</a></td></tr> <tr class="separator:afb11718c8a0c6f7abd85dfbc7adb1cd1"><td class="memSeparator" colspan="2">&#160;</td></tr> <tr class="memitem:a738b842dc5261f08da93880f0b006b55"><td class="memItemLeft" align="right" valign="top">(void)&#160;</td><td class="memItemRight" valign="bottom">- <a class="el" href="interface_help_section_view_controller.html#a738b842dc5261f08da93880f0b006b55">leftSideMenuButtonPressed:</a></td></tr> <tr class="separator:a738b842dc5261f08da93880f0b006b55"><td class="memSeparator" colspan="2">&#160;</td></tr> </table> <a name="details" id="details"></a><h2 class="groupheader">Detailed Description</h2> <div class="textblock"><p>A Table view controller used to handle the help section. </p> </div><h2 class="groupheader">Method Documentation</h2> <a class="anchor" id="afb11718c8a0c6f7abd85dfbc7adb1cd1"></a> <div class="memitem"> <div class="memproto"> <table class="memname"> <tr> <td class="memname">- (UIBarButtonItem *) leftMenuBarButtonItem </td> <td></td> <td class="paramname"></td> <td></td> </tr> </table> </div><div class="memdoc"> <p>Creates the left menu bar button item. This item will be responsible for opening the menu. </p> <dl class="section return"><dt>Returns</dt><dd>the left menu bar button item. </dd></dl> </div> </div> <a class="anchor" id="a738b842dc5261f08da93880f0b006b55"></a> <div class="memitem"> <div class="memproto"> <table class="memname"> <tr> <td class="memname">- (void) leftSideMenuButtonPressed: </td> <td></td> <td class="paramtype">(id)&#160;</td> <td class="paramname"><em>sender</em></td> <td></td> </tr> </table> </div><div class="memdoc"> <p>Callback for when the left menu button is pressed. </p> <dl class="params"><dt>Parameters</dt><dd> <table class="params"> <tr><td class="paramname">sender</td><td>the id of the sender object. </td></tr> </table> </dd> </dl> </div> </div> <a class="anchor" id="ad9f497773e1c2f5e420929a60f3bf7df"></a> <div class="memitem"> <div class="memproto"> <table class="memname"> <tr> <td class="memname">- (<a class="el" href="interface_m_f_side_menu_container_view_controller.html">MFSideMenuContainerViewController</a> *) menuContainerViewController </td> <td></td> <td class="paramname"></td> <td></td> </tr> </table> </div><div class="memdoc"> <p>Gets the menu container view controller. </p> <dl class="section return"><dt>Returns</dt><dd>the menu container view controller. </dd></dl> </div> </div> <hr/>The documentation for this class was generated from the following files:<ul> <li>GroupModelingApp/<a class="el" href="_help_section_view_controller_8h_source.html">HelpSectionViewController.h</a></li> <li>GroupModelingApp/HelpSectionViewController.m</li> </ul> </div><!-- contents --> <!-- start footer part --> <hr class="footer"/><address class="footer"><small> Generated on Tue Sep 17 2013 20:07:27 for Group Modeling App by &#160;<a href="http://www.doxygen.org/index.html"> <img class="footer" src="doxygen.png" alt="doxygen"/> </a> 1.8.4 </small></address> </body> </html>
mdburch/GroupModeling
Documentation/html/interface_help_section_view_controller.html
HTML
gpl-2.0
9,830
# # upgrade_bootloader_gui.py: gui bootloader dialog for upgrades # # Copyright (C) 2002, 2007 Red Hat, Inc. All rights reserved. # # This program is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 2 of the License, or # (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program. If not, see <http://www.gnu.org/licenses/>. # # Author(s): Jeremy Katz <katzj@redhat.com> # # must replace with explcit form so update disks will work from iw_gui import * import gtk from booty import checkbootloader from storage.devices import devicePathToName from constants import * import gettext _ = lambda x: gettext.ldgettext("anaconda", x) import logging log = logging.getLogger("anaconda") class UpgradeBootloaderWindow (InstallWindow): windowTitle = N_("Upgrade Boot Loader Configuration") def getPrev(self): pass def getNext(self): if self.nobl_radio.get_active(): self.dispatch.skipStep("bootloadersetup", skip = 1) self.dispatch.skipStep("bootloader", skip = 1) self.dispatch.skipStep("bootloaderadvanced", skip = 1) self.dispatch.skipStep("instbootloader", skip = 1) elif self.newbl_radio.get_active(): self.dispatch.skipStep("bootloadersetup", skip = 0) self.dispatch.skipStep("bootloader", skip = 0) self.dispatch.skipStep("bootloaderadvanced", skip = 0) self.dispatch.skipStep("instbootloader", skip = 0) self.bl.doUpgradeOnly = 0 else: self.dispatch.skipStep("bootloadersetup", skip = 0) self.dispatch.skipStep("bootloader", skip = 1) self.dispatch.skipStep("bootloaderadvanced", skip = 1) self.dispatch.skipStep("instbootloader", skip = 0) self.bl.doUpgradeOnly = 1 if self.type == "GRUB": self.bl.useGrubVal = 1 else: self.bl.useGrubVal = 0 self.bl.setDevice(devicePathToName(self.bootDev)) def _newToLibata(self, rootPath): # NOTE: any changes here need to be done in upgrade_bootloader_text too try: f = open("/proc/modules", "r") buf = f.read() if buf.find("libata") == -1: return False except: log.debug("error reading /proc/modules") pass try: f = open(rootPath + "/etc/modprobe.conf") except: log.debug("error reading /etc/modprobe.conf") return False modlines = f.readlines() f.close() try: f = open("/tmp/scsidisks") except: log.debug("error reading /tmp/scsidisks") return False mods = [] for l in f.readlines(): (disk, mod) = l.split() if mod.strip() not in mods: mods.append(mod.strip()) f.close() for l in modlines: stripped = l.strip() if stripped == "" or stripped[0] == "#": continue if stripped.find("scsi_hostadapter") != -1: mod = stripped.split()[-1] if mod in mods: mods.remove(mod) if len(mods) > 0: return True return False def getScreen(self, anaconda): self.dispatch = anaconda.dispatch self.bl = anaconda.id.bootloader newToLibata = self._newToLibata(anaconda.rootPath) (self.type, self.bootDev) = \ checkbootloader.getBootloaderTypeAndBoot(anaconda.rootPath, storage=anaconda.id.storage) self.update_radio = gtk.RadioButton(None, _("_Update boot loader configuration")) updatestr = _("This will update your current boot loader.") if newToLibata or (self.type is None or self.bootDev is None): if newToLibata: current = _("Due to system changes, your boot loader " "configuration can not be automatically updated.") else: current = _("The installer is unable to detect the boot loader " "currently in use on your system.") self.update_label = gtk.Label("%s" % (updatestr,)) self.update_radio.set_sensitive(False) self.update_label.set_sensitive(False) update = 0 else: current = _("The installer has detected the %(type)s boot loader " "currently installed on %(bootDev)s.") \ % {'type': self.type, 'bootDev': self.bootDev} self.update_label = gtk.Label("%s %s" % (updatestr, _("This is the recommended option."))) self.update_radio.set_active(False) update = 1 self.newbl_radio = gtk.RadioButton(self.update_radio, _("_Create new boot loader " "configuration")) self.newbl_label = gtk.Label(_("This option creates a " "new boot loader configuration. If " "you wish to switch boot loaders, you " "should choose this.")) self.newbl_radio.set_active(False) self.nobl_radio = gtk.RadioButton(self.update_radio, _("_Skip boot loader updating")) self.nobl_label = gtk.Label(_("This option makes no changes to boot " "loader configuration. If you are " "using a third party boot loader, you " "should choose this.")) self.nobl_radio.set_active(False) for label in [self.update_label, self.nobl_label, self.newbl_label]: label.set_alignment(0.8, 0) label.set_size_request(275, -1) label.set_line_wrap(True) str = _("What would you like to do?") # if they have one, the default is to update, otherwise the # default is to not touch anything if update == 1: default = self.update_radio elif newToLibata: default = self.newbl_radio else: default = self.nobl_radio if not self.dispatch.stepInSkipList("bootloader"): self.newbl_radio.set_active(True) elif self.dispatch.stepInSkipList("instbootloader"): self.nobl_radio.set_active(True) else: default.set_active(True) box = gtk.VBox(False, 5) label = gtk.Label(current) label.set_line_wrap(True) label.set_alignment(0.5, 0.0) label.set_size_request(300, -1) label2 = gtk.Label(str) label2.set_line_wrap(True) label2.set_alignment(0.5, 0.0) label2.set_size_request(300, -1) box.pack_start(label, False) box.pack_start(label2, False, padding = 10) box.pack_start(self.update_radio, False) box.pack_start(self.update_label, False) box.pack_start(self.nobl_radio, False) box.pack_start(self.nobl_label, False) box.pack_start(self.newbl_radio, False) box.pack_start(self.newbl_label, False) a = gtk.Alignment(0.2, 0.1) a.add(box) return a
icomfort/anaconda
iw/upgrade_bootloader_gui.py
Python
gpl-2.0
7,815
/* * Copyright (C) 2013-2015 DeathCore <http://www.noffearrdeathproject.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/>. */ /* * Scripts for spells with SPELLFAMILY_GENERIC spells used by items. * Ordered alphabetically using scriptname. * Scriptnames of files in this file should be prefixed with "spell_item_". */ #include "Player.h" #include "ScriptMgr.h" #include "ScriptedCreature.h" #include "SpellScript.h" #include "SpellAuraEffects.h" #include "SkillDiscovery.h" #include "Battleground.h" // Generic script for handling item dummy effects which trigger another spell. class spell_item_trigger_spell : public SpellScriptLoader { private: uint32 _triggeredSpellId; public: spell_item_trigger_spell(const char* name, uint32 triggeredSpellId) : SpellScriptLoader(name), _triggeredSpellId(triggeredSpellId) { } class spell_item_trigger_spell_SpellScript : public SpellScript { PrepareSpellScript(spell_item_trigger_spell_SpellScript); private: uint32 _triggeredSpellId; public: spell_item_trigger_spell_SpellScript(uint32 triggeredSpellId) : SpellScript(), _triggeredSpellId(triggeredSpellId) { } bool Validate(SpellInfo const* /*spellEntry*/) { if (!sSpellMgr->GetSpellInfo(_triggeredSpellId)) return false; return true; } void HandleDummy(SpellEffIndex /*effIndex*/) { Unit* caster = GetCaster(); if (Item* item = GetCastItem()) caster->CastSpell(caster, _triggeredSpellId, true, item); } void Register() { OnEffectHit += SpellEffectFn(spell_item_trigger_spell_SpellScript::HandleDummy, EFFECT_0, SPELL_EFFECT_DUMMY); } }; SpellScript* GetSpellScript() const { return new spell_item_trigger_spell_SpellScript(_triggeredSpellId); } }; enum AegisOfPreservation { SPELL_AEGIS_HEAL = 23781 }; // 23780 - Aegis of Preservation class spell_item_aegis_of_preservation : public SpellScriptLoader { public: spell_item_aegis_of_preservation() : SpellScriptLoader("spell_item_aegis_of_preservation") { } class spell_item_aegis_of_preservation_AuraScript : public AuraScript { PrepareAuraScript(spell_item_aegis_of_preservation_AuraScript); bool Validate(SpellInfo const* /*spellInfo*/) { if (!sSpellMgr->GetSpellInfo(SPELL_AEGIS_HEAL)) return false; return true; } void HandleProc(AuraEffect const* aurEff, ProcEventInfo& /*eventInfo*/) { PreventDefaultAction(); GetTarget()->CastSpell(GetTarget(), SPELL_AEGIS_HEAL, true, NULL, aurEff); } void Register() { OnEffectProc += AuraEffectProcFn(spell_item_aegis_of_preservation_AuraScript::HandleProc, EFFECT_1, SPELL_AURA_PROC_TRIGGER_SPELL); } }; AuraScript* GetAuraScript() const { return new spell_item_aegis_of_preservation_AuraScript(); } }; // 26400 - Arcane Shroud class spell_item_arcane_shroud : public SpellScriptLoader { public: spell_item_arcane_shroud() : SpellScriptLoader("spell_item_arcane_shroud") { } class spell_item_arcane_shroud_AuraScript : public AuraScript { PrepareAuraScript(spell_item_arcane_shroud_AuraScript); void CalculateAmount(AuraEffect const* /*aurEff*/, int32& amount, bool& /*canBeRecalculated*/) { int32 diff = GetUnitOwner()->getLevel() - 60; if (diff > 0) amount += 2 * diff; } void Register() { DoEffectCalcAmount += AuraEffectCalcAmountFn(spell_item_arcane_shroud_AuraScript::CalculateAmount, EFFECT_0, SPELL_AURA_MOD_THREAT); } }; AuraScript* GetAuraScript() const { return new spell_item_arcane_shroud_AuraScript(); } }; // 64411 - Blessing of Ancient Kings (Val'anyr, Hammer of Ancient Kings) enum BlessingOfAncientKings { SPELL_PROTECTION_OF_ANCIENT_KINGS = 64413 }; class spell_item_blessing_of_ancient_kings : public SpellScriptLoader { public: spell_item_blessing_of_ancient_kings() : SpellScriptLoader("spell_item_blessing_of_ancient_kings") { } class spell_item_blessing_of_ancient_kings_AuraScript : public AuraScript { PrepareAuraScript(spell_item_blessing_of_ancient_kings_AuraScript); bool Validate(SpellInfo const* /*spellInfo*/) { if (!sSpellMgr->GetSpellInfo(SPELL_PROTECTION_OF_ANCIENT_KINGS)) return false; return true; } bool CheckProc(ProcEventInfo& eventInfo) { return eventInfo.GetProcTarget(); } void HandleProc(AuraEffect const* aurEff, ProcEventInfo& eventInfo) { PreventDefaultAction(); int32 absorb = int32(CalculatePct(eventInfo.GetHealInfo()->GetHeal(), 15.0f)); if (AuraEffect* protEff = eventInfo.GetProcTarget()->GetAuraEffect(SPELL_PROTECTION_OF_ANCIENT_KINGS, 0, eventInfo.GetActor()->GetGUID())) { // The shield can grow to a maximum size of 20,000 damage absorbtion protEff->SetAmount(std::min<int32>(protEff->GetAmount() + absorb, 20000)); // Refresh and return to prevent replacing the aura aurEff->GetBase()->RefreshDuration(); } else GetTarget()->CastCustomSpell(SPELL_PROTECTION_OF_ANCIENT_KINGS, SPELLVALUE_BASE_POINT0, absorb, eventInfo.GetProcTarget(), true, NULL, aurEff); } void Register() { DoCheckProc += AuraCheckProcFn(spell_item_blessing_of_ancient_kings_AuraScript::CheckProc); OnEffectProc += AuraEffectProcFn(spell_item_blessing_of_ancient_kings_AuraScript::HandleProc, EFFECT_0, SPELL_AURA_DUMMY); } }; AuraScript* GetAuraScript() const { return new spell_item_blessing_of_ancient_kings_AuraScript(); } }; // 8342 - Defibrillate (Goblin Jumper Cables) have 33% chance on success // 22999 - Defibrillate (Goblin Jumper Cables XL) have 50% chance on success // 54732 - Defibrillate (Gnomish Army Knife) have 67% chance on success enum Defibrillate { SPELL_GOBLIN_JUMPER_CABLES_FAIL = 8338, SPELL_GOBLIN_JUMPER_CABLES_XL_FAIL = 23055 }; class spell_item_defibrillate : public SpellScriptLoader { public: spell_item_defibrillate(char const* name, uint8 chance, uint32 failSpell = 0) : SpellScriptLoader(name), _chance(chance), _failSpell(failSpell) { } class spell_item_defibrillate_SpellScript : public SpellScript { PrepareSpellScript(spell_item_defibrillate_SpellScript); public: spell_item_defibrillate_SpellScript(uint8 chance, uint32 failSpell) : SpellScript(), _chance(chance), _failSpell(failSpell) { } bool Validate(SpellInfo const* /*spellInfo*/) { if (_failSpell && !sSpellMgr->GetSpellInfo(_failSpell)) return false; return true; } void HandleScript(SpellEffIndex effIndex) { if (roll_chance_i(_chance)) { PreventHitDefaultEffect(effIndex); if (_failSpell) GetCaster()->CastSpell(GetCaster(), _failSpell, true, GetCastItem()); } } void Register() { OnEffectHitTarget += SpellEffectFn(spell_item_defibrillate_SpellScript::HandleScript, EFFECT_0, SPELL_EFFECT_RESURRECT); } private: uint8 _chance; uint32 _failSpell; }; SpellScript* GetSpellScript() const { return new spell_item_defibrillate_SpellScript(_chance, _failSpell); } private: uint8 _chance; uint32 _failSpell; }; enum DesperateDefense { SPELL_DESPERATE_RAGE = 33898 }; // 33896 - Desperate Defense class spell_item_desperate_defense : public SpellScriptLoader { public: spell_item_desperate_defense() : SpellScriptLoader("spell_item_desperate_defense") { } class spell_item_desperate_defense_AuraScript : public AuraScript { PrepareAuraScript(spell_item_desperate_defense_AuraScript); bool Validate(SpellInfo const* /*spellInfo*/) { if (!sSpellMgr->GetSpellInfo(SPELL_DESPERATE_RAGE)) return false; return true; } void HandleProc(AuraEffect const* aurEff, ProcEventInfo& /*eventInfo*/) { PreventDefaultAction(); GetTarget()->CastSpell(GetTarget(), SPELL_DESPERATE_RAGE, true, NULL, aurEff); } void Register() { OnEffectProc += AuraEffectProcFn(spell_item_desperate_defense_AuraScript::HandleProc, EFFECT_2, SPELL_AURA_PROC_TRIGGER_SPELL); } }; AuraScript* GetAuraScript() const { return new spell_item_desperate_defense_AuraScript(); } }; // http://www.wowhead.com/item=6522 Deviate Fish // 8063 Deviate Fish enum DeviateFishSpells { SPELL_SLEEPY = 8064, SPELL_INVIGORATE = 8065, SPELL_SHRINK = 8066, SPELL_PARTY_TIME = 8067, SPELL_HEALTHY_SPIRIT = 8068, }; class spell_item_deviate_fish : public SpellScriptLoader { public: spell_item_deviate_fish() : SpellScriptLoader("spell_item_deviate_fish") { } class spell_item_deviate_fish_SpellScript : public SpellScript { PrepareSpellScript(spell_item_deviate_fish_SpellScript); bool Load() { return GetCaster()->GetTypeId() == TYPEID_PLAYER; } bool Validate(SpellInfo const* /*spellEntry*/) { for (uint32 spellId = SPELL_SLEEPY; spellId <= SPELL_HEALTHY_SPIRIT; ++spellId) if (!sSpellMgr->GetSpellInfo(spellId)) return false; return true; } void HandleDummy(SpellEffIndex /*effIndex*/) { Unit* caster = GetCaster(); uint32 spellId = urand(SPELL_SLEEPY, SPELL_HEALTHY_SPIRIT); caster->CastSpell(caster, spellId, true, NULL); } void Register() { OnEffectHit += SpellEffectFn(spell_item_deviate_fish_SpellScript::HandleDummy, EFFECT_0, SPELL_EFFECT_DUMMY); } }; SpellScript* GetSpellScript() const { return new spell_item_deviate_fish_SpellScript(); } }; // http://www.wowhead.com/item=47499 Flask of the North // 67019 Flask of the North enum FlaskOfTheNorthSpells { SPELL_FLASK_OF_THE_NORTH_SP = 67016, SPELL_FLASK_OF_THE_NORTH_AP = 67017, SPELL_FLASK_OF_THE_NORTH_STR = 67018, }; class spell_item_flask_of_the_north : public SpellScriptLoader { public: spell_item_flask_of_the_north() : SpellScriptLoader("spell_item_flask_of_the_north") { } class spell_item_flask_of_the_north_SpellScript : public SpellScript { PrepareSpellScript(spell_item_flask_of_the_north_SpellScript); bool Validate(SpellInfo const* /*spellEntry*/) { if (!sSpellMgr->GetSpellInfo(SPELL_FLASK_OF_THE_NORTH_SP) || !sSpellMgr->GetSpellInfo(SPELL_FLASK_OF_THE_NORTH_AP) || !sSpellMgr->GetSpellInfo(SPELL_FLASK_OF_THE_NORTH_STR)) return false; return true; } void HandleDummy(SpellEffIndex /*effIndex*/) { Unit* caster = GetCaster(); std::vector<uint32> possibleSpells; switch (caster->getClass()) { case CLASS_WARLOCK: case CLASS_MAGE: case CLASS_PRIEST: possibleSpells.push_back(SPELL_FLASK_OF_THE_NORTH_SP); break; case CLASS_DEATH_KNIGHT: case CLASS_WARRIOR: possibleSpells.push_back(SPELL_FLASK_OF_THE_NORTH_STR); break; case CLASS_ROGUE: case CLASS_HUNTER: possibleSpells.push_back(SPELL_FLASK_OF_THE_NORTH_AP); break; case CLASS_DRUID: case CLASS_PALADIN: possibleSpells.push_back(SPELL_FLASK_OF_THE_NORTH_SP); possibleSpells.push_back(SPELL_FLASK_OF_THE_NORTH_STR); break; case CLASS_SHAMAN: possibleSpells.push_back(SPELL_FLASK_OF_THE_NORTH_SP); possibleSpells.push_back(SPELL_FLASK_OF_THE_NORTH_AP); break; } caster->CastSpell(caster, possibleSpells[irand(0, (possibleSpells.size() - 1))], true, NULL); } void Register() { OnEffectHit += SpellEffectFn(spell_item_flask_of_the_north_SpellScript::HandleDummy, EFFECT_0, SPELL_EFFECT_DUMMY); } }; SpellScript* GetSpellScript() const { return new spell_item_flask_of_the_north_SpellScript(); } }; // http://www.wowhead.com/item=10645 Gnomish Death Ray // 13280 Gnomish Death Ray enum GnomishDeathRay { SPELL_GNOMISH_DEATH_RAY_SELF = 13493, SPELL_GNOMISH_DEATH_RAY_TARGET = 13279, }; class spell_item_gnomish_death_ray : public SpellScriptLoader { public: spell_item_gnomish_death_ray() : SpellScriptLoader("spell_item_gnomish_death_ray") { } class spell_item_gnomish_death_ray_SpellScript : public SpellScript { PrepareSpellScript(spell_item_gnomish_death_ray_SpellScript); bool Validate(SpellInfo const* /*spellEntry*/) { if (!sSpellMgr->GetSpellInfo(SPELL_GNOMISH_DEATH_RAY_SELF) || !sSpellMgr->GetSpellInfo(SPELL_GNOMISH_DEATH_RAY_TARGET)) return false; return true; } void HandleDummy(SpellEffIndex /*effIndex*/) { Unit* caster = GetCaster(); if (Unit* target = GetHitUnit()) { if (urand(0, 99) < 15) caster->CastSpell(caster, SPELL_GNOMISH_DEATH_RAY_SELF, true, NULL); // failure else caster->CastSpell(target, SPELL_GNOMISH_DEATH_RAY_TARGET, true, NULL); } } void Register() { OnEffectHitTarget += SpellEffectFn(spell_item_gnomish_death_ray_SpellScript::HandleDummy, EFFECT_0, SPELL_EFFECT_DUMMY); } }; SpellScript* GetSpellScript() const { return new spell_item_gnomish_death_ray_SpellScript(); } }; // http://www.wowhead.com/item=27388 Mr. Pinchy // 33060 Make a Wish enum MakeAWish { SPELL_MR_PINCHYS_BLESSING = 33053, SPELL_SUMMON_MIGHTY_MR_PINCHY = 33057, SPELL_SUMMON_FURIOUS_MR_PINCHY = 33059, SPELL_TINY_MAGICAL_CRAWDAD = 33062, SPELL_MR_PINCHYS_GIFT = 33064, }; class spell_item_make_a_wish : public SpellScriptLoader { public: spell_item_make_a_wish() : SpellScriptLoader("spell_item_make_a_wish") { } class spell_item_make_a_wish_SpellScript : public SpellScript { PrepareSpellScript(spell_item_make_a_wish_SpellScript); bool Load() { return GetCaster()->GetTypeId() == TYPEID_PLAYER; } bool Validate(SpellInfo const* /*spellEntry*/) { if (!sSpellMgr->GetSpellInfo(SPELL_MR_PINCHYS_BLESSING) || !sSpellMgr->GetSpellInfo(SPELL_SUMMON_MIGHTY_MR_PINCHY) || !sSpellMgr->GetSpellInfo(SPELL_SUMMON_FURIOUS_MR_PINCHY) || !sSpellMgr->GetSpellInfo(SPELL_TINY_MAGICAL_CRAWDAD) || !sSpellMgr->GetSpellInfo(SPELL_MR_PINCHYS_GIFT)) return false; return true; } void HandleDummy(SpellEffIndex /*effIndex*/) { Unit* caster = GetCaster(); uint32 spellId = SPELL_MR_PINCHYS_GIFT; switch (urand(1, 5)) { case 1: spellId = SPELL_MR_PINCHYS_BLESSING; break; case 2: spellId = SPELL_SUMMON_MIGHTY_MR_PINCHY; break; case 3: spellId = SPELL_SUMMON_FURIOUS_MR_PINCHY; break; case 4: spellId = SPELL_TINY_MAGICAL_CRAWDAD; break; } caster->CastSpell(caster, spellId, true, NULL); } void Register() { OnEffectHit += SpellEffectFn(spell_item_make_a_wish_SpellScript::HandleDummy, EFFECT_0, SPELL_EFFECT_DUMMY); } }; SpellScript* GetSpellScript() const { return new spell_item_make_a_wish_SpellScript(); } }; // http://www.wowhead.com/item=32686 Mingo's Fortune Giblets // 40802 Mingo's Fortune Generator class spell_item_mingos_fortune_generator : public SpellScriptLoader { public: spell_item_mingos_fortune_generator() : SpellScriptLoader("spell_item_mingos_fortune_generator") { } class spell_item_mingos_fortune_generator_SpellScript : public SpellScript { PrepareSpellScript(spell_item_mingos_fortune_generator_SpellScript); void HandleDummy(SpellEffIndex effIndex) { // Selecting one from Bloodstained Fortune item uint32 newitemid; switch (urand(1, 20)) { case 1: newitemid = 32688; break; case 2: newitemid = 32689; break; case 3: newitemid = 32690; break; case 4: newitemid = 32691; break; case 5: newitemid = 32692; break; case 6: newitemid = 32693; break; case 7: newitemid = 32700; break; case 8: newitemid = 32701; break; case 9: newitemid = 32702; break; case 10: newitemid = 32703; break; case 11: newitemid = 32704; break; case 12: newitemid = 32705; break; case 13: newitemid = 32706; break; case 14: newitemid = 32707; break; case 15: newitemid = 32708; break; case 16: newitemid = 32709; break; case 17: newitemid = 32710; break; case 18: newitemid = 32711; break; case 19: newitemid = 32712; break; case 20: newitemid = 32713; break; default: return; } CreateItem(effIndex, newitemid); } void Register() { OnEffectHit += SpellEffectFn(spell_item_mingos_fortune_generator_SpellScript::HandleDummy, EFFECT_0, SPELL_EFFECT_DUMMY); } }; SpellScript* GetSpellScript() const { return new spell_item_mingos_fortune_generator_SpellScript(); } }; // 71875, 71877 - Item - Black Bruise: Necrotic Touch Proc enum NecroticTouch { SPELL_ITEM_NECROTIC_TOUCH_PROC = 71879 }; class spell_item_necrotic_touch : public SpellScriptLoader { public: spell_item_necrotic_touch() : SpellScriptLoader("spell_item_necrotic_touch") { } class spell_item_necrotic_touch_AuraScript : public AuraScript { PrepareAuraScript(spell_item_necrotic_touch_AuraScript); bool Validate(SpellInfo const* /*spellInfo*/) { if (!sSpellMgr->GetSpellInfo(SPELL_ITEM_NECROTIC_TOUCH_PROC)) return false; return true; } void HandleProc(AuraEffect const* aurEff, ProcEventInfo& eventInfo) { PreventDefaultAction(); int32 bp = CalculatePct(int32(eventInfo.GetDamageInfo()->GetDamage()), aurEff->GetAmount()); GetTarget()->CastCustomSpell(SPELL_ITEM_NECROTIC_TOUCH_PROC, SPELLVALUE_BASE_POINT0, bp, GetTarget(), true, NULL, aurEff); } void Register() { OnEffectProc += AuraEffectProcFn(spell_item_necrotic_touch_AuraScript::HandleProc, EFFECT_0, SPELL_AURA_DUMMY); } }; AuraScript* GetAuraScript() const { return new spell_item_necrotic_touch_AuraScript(); } }; // http://www.wowhead.com/item=10720 Gnomish Net-o-Matic Projector // 13120 Net-o-Matic enum NetOMaticSpells { SPELL_NET_O_MATIC_TRIGGERED1 = 16566, SPELL_NET_O_MATIC_TRIGGERED2 = 13119, SPELL_NET_O_MATIC_TRIGGERED3 = 13099, }; class spell_item_net_o_matic : public SpellScriptLoader { public: spell_item_net_o_matic() : SpellScriptLoader("spell_item_net_o_matic") { } class spell_item_net_o_matic_SpellScript : public SpellScript { PrepareSpellScript(spell_item_net_o_matic_SpellScript); bool Validate(SpellInfo const* /*spellEntry*/) { if (!sSpellMgr->GetSpellInfo(SPELL_NET_O_MATIC_TRIGGERED1) || !sSpellMgr->GetSpellInfo(SPELL_NET_O_MATIC_TRIGGERED2) || !sSpellMgr->GetSpellInfo(SPELL_NET_O_MATIC_TRIGGERED3)) return false; return true; } void HandleDummy(SpellEffIndex /*effIndex*/) { if (Unit* target = GetHitUnit()) { uint32 spellId = SPELL_NET_O_MATIC_TRIGGERED3; uint32 roll = urand(0, 99); if (roll < 2) // 2% for 30 sec self root (off-like chance unknown) spellId = SPELL_NET_O_MATIC_TRIGGERED1; else if (roll < 4) // 2% for 20 sec root, charge to target (off-like chance unknown) spellId = SPELL_NET_O_MATIC_TRIGGERED2; GetCaster()->CastSpell(target, spellId, true, NULL); } } void Register() { OnEffectHitTarget += SpellEffectFn(spell_item_net_o_matic_SpellScript::HandleDummy, EFFECT_0, SPELL_EFFECT_DUMMY); } }; SpellScript* GetSpellScript() const { return new spell_item_net_o_matic_SpellScript(); } }; // http://www.wowhead.com/item=8529 Noggenfogger Elixir // 16589 Noggenfogger Elixir enum NoggenfoggerElixirSpells { SPELL_NOGGENFOGGER_ELIXIR_TRIGGERED1 = 16595, SPELL_NOGGENFOGGER_ELIXIR_TRIGGERED2 = 16593, SPELL_NOGGENFOGGER_ELIXIR_TRIGGERED3 = 16591, }; class spell_item_noggenfogger_elixir : public SpellScriptLoader { public: spell_item_noggenfogger_elixir() : SpellScriptLoader("spell_item_noggenfogger_elixir") { } class spell_item_noggenfogger_elixir_SpellScript : public SpellScript { PrepareSpellScript(spell_item_noggenfogger_elixir_SpellScript); bool Load() { return GetCaster()->GetTypeId() == TYPEID_PLAYER; } bool Validate(SpellInfo const* /*spellEntry*/) { if (!sSpellMgr->GetSpellInfo(SPELL_NOGGENFOGGER_ELIXIR_TRIGGERED1) || !sSpellMgr->GetSpellInfo(SPELL_NOGGENFOGGER_ELIXIR_TRIGGERED2) || !sSpellMgr->GetSpellInfo(SPELL_NOGGENFOGGER_ELIXIR_TRIGGERED3)) return false; return true; } void HandleDummy(SpellEffIndex /*effIndex*/) { Unit* caster = GetCaster(); uint32 spellId = SPELL_NOGGENFOGGER_ELIXIR_TRIGGERED3; switch (urand(1, 3)) { case 1: spellId = SPELL_NOGGENFOGGER_ELIXIR_TRIGGERED1; break; case 2: spellId = SPELL_NOGGENFOGGER_ELIXIR_TRIGGERED2; break; } caster->CastSpell(caster, spellId, true, NULL); } void Register() { OnEffectHit += SpellEffectFn(spell_item_noggenfogger_elixir_SpellScript::HandleDummy, EFFECT_0, SPELL_EFFECT_DUMMY); } }; SpellScript* GetSpellScript() const { return new spell_item_noggenfogger_elixir_SpellScript(); } }; // 17512 - Piccolo of the Flaming Fire class spell_item_piccolo_of_the_flaming_fire : public SpellScriptLoader { public: spell_item_piccolo_of_the_flaming_fire() : SpellScriptLoader("spell_item_piccolo_of_the_flaming_fire") { } class spell_item_piccolo_of_the_flaming_fire_SpellScript : public SpellScript { PrepareSpellScript(spell_item_piccolo_of_the_flaming_fire_SpellScript); void HandleScript(SpellEffIndex effIndex) { PreventHitDefaultEffect(effIndex); if (Player* target = GetHitPlayer()) target->HandleEmoteCommand(EMOTE_STATE_DANCE); } void Register() { OnEffectHitTarget += SpellEffectFn(spell_item_piccolo_of_the_flaming_fire_SpellScript::HandleScript, EFFECT_0, SPELL_EFFECT_SCRIPT_EFFECT); } }; SpellScript* GetSpellScript() const { return new spell_item_piccolo_of_the_flaming_fire_SpellScript(); } }; // http://www.wowhead.com/item=6657 Savory Deviate Delight // 8213 Savory Deviate Delight enum SavoryDeviateDelight { SPELL_FLIP_OUT_MALE = 8219, SPELL_FLIP_OUT_FEMALE = 8220, SPELL_YAAARRRR_MALE = 8221, SPELL_YAAARRRR_FEMALE = 8222, }; class spell_item_savory_deviate_delight : public SpellScriptLoader { public: spell_item_savory_deviate_delight() : SpellScriptLoader("spell_item_savory_deviate_delight") { } class spell_item_savory_deviate_delight_SpellScript : public SpellScript { PrepareSpellScript(spell_item_savory_deviate_delight_SpellScript); bool Load() { return GetCaster()->GetTypeId() == TYPEID_PLAYER; } bool Validate(SpellInfo const* /*spellEntry*/) { for (uint32 spellId = SPELL_FLIP_OUT_MALE; spellId <= SPELL_YAAARRRR_FEMALE; ++spellId) if (!sSpellMgr->GetSpellInfo(spellId)) return false; return true; } void HandleDummy(SpellEffIndex /*effIndex*/) { Unit* caster = GetCaster(); uint32 spellId = 0; switch (urand(1, 2)) { // Flip Out - ninja case 1: spellId = (caster->getGender() == GENDER_MALE ? SPELL_FLIP_OUT_MALE : SPELL_FLIP_OUT_FEMALE); break; // Yaaarrrr - pirate case 2: spellId = (caster->getGender() == GENDER_MALE ? SPELL_YAAARRRR_MALE : SPELL_YAAARRRR_FEMALE); break; } caster->CastSpell(caster, spellId, true, NULL); } void Register() { OnEffectHit += SpellEffectFn(spell_item_savory_deviate_delight_SpellScript::HandleDummy, EFFECT_0, SPELL_EFFECT_DUMMY); } }; SpellScript* GetSpellScript() const { return new spell_item_savory_deviate_delight_SpellScript(); } }; // 48129 - Scroll of Recall // 60320 - Scroll of Recall II // 60321 - Scroll of Recall III enum ScrollOfRecall { SPELL_SCROLL_OF_RECALL_I = 48129, SPELL_SCROLL_OF_RECALL_II = 60320, SPELL_SCROLL_OF_RECALL_III = 60321, SPELL_LOST = 60444, SPELL_SCROLL_OF_RECALL_FAIL_ALLIANCE_1 = 60323, SPELL_SCROLL_OF_RECALL_FAIL_HORDE_1 = 60328, }; class spell_item_scroll_of_recall : public SpellScriptLoader { public: spell_item_scroll_of_recall() : SpellScriptLoader("spell_item_scroll_of_recall") { } class spell_item_scroll_of_recall_SpellScript : public SpellScript { PrepareSpellScript(spell_item_scroll_of_recall_SpellScript); bool Load() { return GetCaster()->GetTypeId() == TYPEID_PLAYER; } void HandleScript(SpellEffIndex effIndex) { Unit* caster = GetCaster(); uint8 maxSafeLevel = 0; switch (GetSpellInfo()->Id) { case SPELL_SCROLL_OF_RECALL_I: // Scroll of Recall maxSafeLevel = 40; break; case SPELL_SCROLL_OF_RECALL_II: // Scroll of Recall II maxSafeLevel = 70; break; case SPELL_SCROLL_OF_RECALL_III: // Scroll of Recal III maxSafeLevel = 80; break; default: break; } if (caster->getLevel() > maxSafeLevel) { caster->CastSpell(caster, SPELL_LOST, true); // ALLIANCE from 60323 to 60330 - HORDE from 60328 to 60335 uint32 spellId = SPELL_SCROLL_OF_RECALL_FAIL_ALLIANCE_1; if (GetCaster()->ToPlayer()->GetTeam() == HORDE) spellId = SPELL_SCROLL_OF_RECALL_FAIL_HORDE_1; GetCaster()->CastSpell(GetCaster(), spellId + urand(0, 7), true); PreventHitDefaultEffect(effIndex); } } void Register() { OnEffectHitTarget += SpellEffectFn(spell_item_scroll_of_recall_SpellScript::HandleScript, EFFECT_0, SPELL_EFFECT_TELEPORT_UNITS); } }; SpellScript* GetSpellScript() const { return new spell_item_scroll_of_recall_SpellScript(); } }; // 71169 - Shadow's Fate (Shadowmourne questline) enum ShadowsFate { SPELL_SOUL_FEAST = 71203, QUEST_A_FEAST_OF_SOULS = 24547 }; class spell_item_shadows_fate : public SpellScriptLoader { public: spell_item_shadows_fate() : SpellScriptLoader("spell_item_shadows_fate") { } class spell_item_shadows_fate_AuraScript : public AuraScript { PrepareAuraScript(spell_item_shadows_fate_AuraScript); bool Validate(SpellInfo const* /*spellInfo*/) { if (!sSpellMgr->GetSpellInfo(SPELL_SOUL_FEAST)) return false; if (!sObjectMgr->GetQuestTemplate(QUEST_A_FEAST_OF_SOULS)) return false; return true; } bool Load() { _procTarget = NULL; return true; } bool CheckProc(ProcEventInfo& /*eventInfo*/) { _procTarget = GetCaster(); return _procTarget && _procTarget->GetTypeId() == TYPEID_PLAYER && _procTarget->ToPlayer()->GetQuestStatus(QUEST_A_FEAST_OF_SOULS) == QUEST_STATUS_INCOMPLETE; } void HandleProc(AuraEffect const* /*aurEff*/, ProcEventInfo& /*eventInfo*/) { PreventDefaultAction(); GetTarget()->CastSpell(_procTarget, SPELL_SOUL_FEAST, true); } void Register() { DoCheckProc += AuraCheckProcFn(spell_item_shadows_fate_AuraScript::CheckProc); OnEffectProc += AuraEffectProcFn(spell_item_shadows_fate_AuraScript::HandleProc, EFFECT_0, SPELL_AURA_DUMMY); } private: Unit* _procTarget; }; AuraScript* GetAuraScript() const { return new spell_item_shadows_fate_AuraScript(); } }; enum Shadowmourne { SPELL_SHADOWMOURNE_CHAOS_BANE_DAMAGE = 71904, SPELL_SHADOWMOURNE_SOUL_FRAGMENT = 71905, SPELL_SHADOWMOURNE_VISUAL_LOW = 72521, SPELL_SHADOWMOURNE_VISUAL_HIGH = 72523, SPELL_SHADOWMOURNE_CHAOS_BANE_BUFF = 73422, }; // 71903 - Item - Shadowmourne Legendary class spell_item_shadowmourne : public SpellScriptLoader { public: spell_item_shadowmourne() : SpellScriptLoader("spell_item_shadowmourne") { } class spell_item_shadowmourne_AuraScript : public AuraScript { PrepareAuraScript(spell_item_shadowmourne_AuraScript); bool Validate(SpellInfo const* /*spellInfo*/) { if (!sSpellMgr->GetSpellInfo(SPELL_SHADOWMOURNE_CHAOS_BANE_DAMAGE)) return false; if (!sSpellMgr->GetSpellInfo(SPELL_SHADOWMOURNE_SOUL_FRAGMENT)) return false; if (!sSpellMgr->GetSpellInfo(SPELL_SHADOWMOURNE_CHAOS_BANE_BUFF)) return false; return true; } bool CheckProc(ProcEventInfo& eventInfo) { if (GetTarget()->HasAura(SPELL_SHADOWMOURNE_CHAOS_BANE_BUFF)) // cant collect shards while under effect of Chaos Bane buff return false; return eventInfo.GetProcTarget() && eventInfo.GetProcTarget()->isAlive(); } void HandleProc(AuraEffect const* aurEff, ProcEventInfo& eventInfo) { PreventDefaultAction(); GetTarget()->CastSpell(GetTarget(), SPELL_SHADOWMOURNE_SOUL_FRAGMENT, true, NULL, aurEff); // this can't be handled in AuraScript of SoulFragments because we need to know victim if (Aura* soulFragments = GetTarget()->GetAura(SPELL_SHADOWMOURNE_SOUL_FRAGMENT)) { if (soulFragments->GetStackAmount() >= 10) { GetTarget()->CastSpell(eventInfo.GetProcTarget(), SPELL_SHADOWMOURNE_CHAOS_BANE_DAMAGE, true, NULL, aurEff); soulFragments->Remove(); } } } void Register() { DoCheckProc += AuraCheckProcFn(spell_item_shadowmourne_AuraScript::CheckProc); OnEffectProc += AuraEffectProcFn(spell_item_shadowmourne_AuraScript::HandleProc, EFFECT_0, SPELL_AURA_DUMMY); } }; AuraScript* GetAuraScript() const { return new spell_item_shadowmourne_AuraScript(); } }; // 71905 - Soul Fragment class spell_item_shadowmourne_soul_fragment : public SpellScriptLoader { public: spell_item_shadowmourne_soul_fragment() : SpellScriptLoader("spell_item_shadowmourne_soul_fragment") { } class spell_item_shadowmourne_soul_fragment_AuraScript : public AuraScript { PrepareAuraScript(spell_item_shadowmourne_soul_fragment_AuraScript); bool Validate(SpellInfo const* /*spellInfo*/) { if (!sSpellMgr->GetSpellInfo(SPELL_SHADOWMOURNE_VISUAL_LOW) || !sSpellMgr->GetSpellInfo(SPELL_SHADOWMOURNE_VISUAL_HIGH) || !sSpellMgr->GetSpellInfo(SPELL_SHADOWMOURNE_CHAOS_BANE_BUFF)) return false; return true; } void OnStackChange(AuraEffect const* /*aurEff*/, AuraEffectHandleModes /*mode*/) { Unit* target = GetTarget(); switch (GetStackAmount()) { case 1: target->CastSpell(target, SPELL_SHADOWMOURNE_VISUAL_LOW, true); break; case 6: target->RemoveAurasDueToSpell(SPELL_SHADOWMOURNE_VISUAL_LOW); target->CastSpell(target, SPELL_SHADOWMOURNE_VISUAL_HIGH, true); break; case 10: target->RemoveAurasDueToSpell(SPELL_SHADOWMOURNE_VISUAL_HIGH); target->CastSpell(target, SPELL_SHADOWMOURNE_CHAOS_BANE_BUFF, true); break; default: break; } } void OnRemove(AuraEffect const* /*aurEff*/, AuraEffectHandleModes /*mode*/) { Unit* target = GetTarget(); target->RemoveAurasDueToSpell(SPELL_SHADOWMOURNE_VISUAL_LOW); target->RemoveAurasDueToSpell(SPELL_SHADOWMOURNE_VISUAL_HIGH); } void Register() { AfterEffectApply += AuraEffectApplyFn(spell_item_shadowmourne_soul_fragment_AuraScript::OnStackChange, EFFECT_0, SPELL_AURA_MOD_STAT, AuraEffectHandleModes(AURA_EFFECT_HANDLE_REAL | AURA_EFFECT_HANDLE_REAPPLY)); AfterEffectRemove += AuraEffectRemoveFn(spell_item_shadowmourne_soul_fragment_AuraScript::OnRemove, EFFECT_0, SPELL_AURA_MOD_STAT, AURA_EFFECT_HANDLE_REAL); } }; AuraScript* GetAuraScript() const { return new spell_item_shadowmourne_soul_fragment_AuraScript(); } }; // http://www.wowhead.com/item=7734 Six Demon Bag // 14537 Six Demon Bag enum SixDemonBagSpells { SPELL_FROSTBOLT = 11538, SPELL_POLYMORPH = 14621, SPELL_SUMMON_FELHOUND_MINION = 14642, SPELL_FIREBALL = 15662, SPELL_CHAIN_LIGHTNING = 21179, SPELL_ENVELOPING_WINDS = 25189, }; class spell_item_six_demon_bag : public SpellScriptLoader { public: spell_item_six_demon_bag() : SpellScriptLoader("spell_item_six_demon_bag") { } class spell_item_six_demon_bag_SpellScript : public SpellScript { PrepareSpellScript(spell_item_six_demon_bag_SpellScript); bool Validate(SpellInfo const* /*spellEntry*/) { if (!sSpellMgr->GetSpellInfo(SPELL_FROSTBOLT) || !sSpellMgr->GetSpellInfo(SPELL_POLYMORPH) || !sSpellMgr->GetSpellInfo(SPELL_SUMMON_FELHOUND_MINION) || !sSpellMgr->GetSpellInfo(SPELL_FIREBALL) || !sSpellMgr->GetSpellInfo(SPELL_CHAIN_LIGHTNING) || !sSpellMgr->GetSpellInfo(SPELL_ENVELOPING_WINDS)) return false; return true; } void HandleDummy(SpellEffIndex /*effIndex*/) { Unit* caster = GetCaster(); if (Unit* target = GetHitUnit()) { uint32 spellId = 0; uint32 rand = urand(0, 99); if (rand < 25) // Fireball (25% chance) spellId = SPELL_FIREBALL; else if (rand < 50) // Frostball (25% chance) spellId = SPELL_FROSTBOLT; else if (rand < 70) // Chain Lighting (20% chance) spellId = SPELL_CHAIN_LIGHTNING; else if (rand < 80) // Polymorph (10% chance) { spellId = SPELL_POLYMORPH; if (urand(0, 100) <= 30) // 30% chance to self-cast target = caster; } else if (rand < 95) // Enveloping Winds (15% chance) spellId = SPELL_ENVELOPING_WINDS; else // Summon Felhund minion (5% chance) { spellId = SPELL_SUMMON_FELHOUND_MINION; target = caster; } caster->CastSpell(target, spellId, true, GetCastItem()); } } void Register() { OnEffectHitTarget += SpellEffectFn(spell_item_six_demon_bag_SpellScript::HandleDummy, EFFECT_0, SPELL_EFFECT_DUMMY); } }; SpellScript* GetSpellScript() const { return new spell_item_six_demon_bag_SpellScript(); } }; // 28862 - The Eye of Diminution class spell_item_the_eye_of_diminution : public SpellScriptLoader { public: spell_item_the_eye_of_diminution() : SpellScriptLoader("spell_item_the_eye_of_diminution") { } class spell_item_the_eye_of_diminution_AuraScript : public AuraScript { PrepareAuraScript(spell_item_the_eye_of_diminution_AuraScript); void CalculateAmount(AuraEffect const* /*aurEff*/, int32& amount, bool& /*canBeRecalculated*/) { int32 diff = GetUnitOwner()->getLevel() - 60; if (diff > 0) amount += diff; } void Register() { DoEffectCalcAmount += AuraEffectCalcAmountFn(spell_item_the_eye_of_diminution_AuraScript::CalculateAmount, EFFECT_0, SPELL_AURA_MOD_THREAT); } }; AuraScript* GetAuraScript() const { return new spell_item_the_eye_of_diminution_AuraScript(); } }; // http://www.wowhead.com/item=44012 Underbelly Elixir // 59640 Underbelly Elixir enum UnderbellyElixirSpells { SPELL_UNDERBELLY_ELIXIR_TRIGGERED1 = 59645, SPELL_UNDERBELLY_ELIXIR_TRIGGERED2 = 59831, SPELL_UNDERBELLY_ELIXIR_TRIGGERED3 = 59843, }; class spell_item_underbelly_elixir : public SpellScriptLoader { public: spell_item_underbelly_elixir() : SpellScriptLoader("spell_item_underbelly_elixir") { } class spell_item_underbelly_elixir_SpellScript : public SpellScript { PrepareSpellScript(spell_item_underbelly_elixir_SpellScript); bool Load() { return GetCaster()->GetTypeId() == TYPEID_PLAYER; } bool Validate(SpellInfo const* /*spellEntry*/) { if (!sSpellMgr->GetSpellInfo(SPELL_UNDERBELLY_ELIXIR_TRIGGERED1) || !sSpellMgr->GetSpellInfo(SPELL_UNDERBELLY_ELIXIR_TRIGGERED2) || !sSpellMgr->GetSpellInfo(SPELL_UNDERBELLY_ELIXIR_TRIGGERED3)) return false; return true; } void HandleDummy(SpellEffIndex /*effIndex*/) { Unit* caster = GetCaster(); uint32 spellId = SPELL_UNDERBELLY_ELIXIR_TRIGGERED3; switch (urand(1, 3)) { case 1: spellId = SPELL_UNDERBELLY_ELIXIR_TRIGGERED1; break; case 2: spellId = SPELL_UNDERBELLY_ELIXIR_TRIGGERED2; break; } caster->CastSpell(caster, spellId, true, NULL); } void Register() { OnEffectHit += SpellEffectFn(spell_item_underbelly_elixir_SpellScript::HandleDummy, EFFECT_0, SPELL_EFFECT_DUMMY); } }; SpellScript* GetSpellScript() const { return new spell_item_underbelly_elixir_SpellScript(); } }; enum AirRifleSpells { SPELL_AIR_RIFLE_HOLD_VISUAL = 65582, SPELL_AIR_RIFLE_SHOOT = 67532, SPELL_AIR_RIFLE_SHOOT_SELF = 65577, }; class spell_item_red_rider_air_rifle : public SpellScriptLoader { public: spell_item_red_rider_air_rifle() : SpellScriptLoader("spell_item_red_rider_air_rifle") { } class spell_item_red_rider_air_rifle_SpellScript : public SpellScript { PrepareSpellScript(spell_item_red_rider_air_rifle_SpellScript); bool Validate(SpellInfo const* /*spell*/) { if (!sSpellMgr->GetSpellInfo(SPELL_AIR_RIFLE_HOLD_VISUAL) || !sSpellMgr->GetSpellInfo(SPELL_AIR_RIFLE_SHOOT) || !sSpellMgr->GetSpellInfo(SPELL_AIR_RIFLE_SHOOT_SELF)) return false; return true; } void HandleScript(SpellEffIndex effIndex) { PreventHitDefaultEffect(effIndex); Unit* caster = GetCaster(); if (Unit* target = GetHitUnit()) { caster->CastSpell(caster, SPELL_AIR_RIFLE_HOLD_VISUAL, true); // needed because this spell shares GCD with its triggered spells (which must not be cast with triggered flag) if (Player* player = caster->ToPlayer()) player->GetGlobalCooldownMgr().CancelGlobalCooldown(GetSpellInfo()); if (urand(0, 4)) caster->CastSpell(target, SPELL_AIR_RIFLE_SHOOT, false); else caster->CastSpell(caster, SPELL_AIR_RIFLE_SHOOT_SELF, false); } } void Register() { OnEffectHitTarget += SpellEffectFn(spell_item_red_rider_air_rifle_SpellScript::HandleScript, EFFECT_0, SPELL_EFFECT_SCRIPT_EFFECT); } }; SpellScript* GetSpellScript() const { return new spell_item_red_rider_air_rifle_SpellScript(); } }; enum GenericData { SPELL_ARCANITE_DRAGONLING = 19804, SPELL_BATTLE_CHICKEN = 13166, SPELL_MECHANICAL_DRAGONLING = 4073, SPELL_MITHRIL_MECHANICAL_DRAGONLING = 12749, }; enum CreateHeartCandy { ITEM_HEART_CANDY_1 = 21818, ITEM_HEART_CANDY_2 = 21817, ITEM_HEART_CANDY_3 = 21821, ITEM_HEART_CANDY_4 = 21819, ITEM_HEART_CANDY_5 = 21816, ITEM_HEART_CANDY_6 = 21823, ITEM_HEART_CANDY_7 = 21822, ITEM_HEART_CANDY_8 = 21820, }; class spell_item_create_heart_candy : public SpellScriptLoader { public: spell_item_create_heart_candy() : SpellScriptLoader("spell_item_create_heart_candy") { } class spell_item_create_heart_candy_SpellScript : public SpellScript { PrepareSpellScript(spell_item_create_heart_candy_SpellScript); void HandleScript(SpellEffIndex effIndex) { PreventHitDefaultEffect(effIndex); if (Player* target = GetHitPlayer()) { static const uint32 items[] = {ITEM_HEART_CANDY_1, ITEM_HEART_CANDY_2, ITEM_HEART_CANDY_3, ITEM_HEART_CANDY_4, ITEM_HEART_CANDY_5, ITEM_HEART_CANDY_6, ITEM_HEART_CANDY_7, ITEM_HEART_CANDY_8}; target->AddItem(items[urand(0, 7)], 1); } } void Register() { OnEffectHitTarget += SpellEffectFn(spell_item_create_heart_candy_SpellScript::HandleScript, EFFECT_0, SPELL_EFFECT_SCRIPT_EFFECT); } }; SpellScript* GetSpellScript() const { return new spell_item_create_heart_candy_SpellScript(); } }; class spell_item_book_of_glyph_mastery : public SpellScriptLoader { public: spell_item_book_of_glyph_mastery() : SpellScriptLoader("spell_item_book_of_glyph_mastery") {} class spell_item_book_of_glyph_mastery_SpellScript : public SpellScript { PrepareSpellScript(spell_item_book_of_glyph_mastery_SpellScript); bool Load() { return GetCaster()->GetTypeId() == TYPEID_PLAYER; } SpellCastResult CheckRequirement() { if (HasDiscoveredAllSpells(GetSpellInfo()->Id, GetCaster()->ToPlayer())) { SetCustomCastResultMessage(SPELL_CUSTOM_ERROR_LEARNED_EVERYTHING); return SPELL_FAILED_CUSTOM_ERROR; } return SPELL_CAST_OK; } void HandleScript(SpellEffIndex /*effIndex*/) { Player* caster = GetCaster()->ToPlayer(); uint32 spellId = GetSpellInfo()->Id; // learn random explicit discovery recipe (if any) if (uint32 discoveredSpellId = GetExplicitDiscoverySpell(spellId, caster)) caster->learnSpell(discoveredSpellId, false); } void Register() { OnCheckCast += SpellCheckCastFn(spell_item_book_of_glyph_mastery_SpellScript::CheckRequirement); OnEffectHitTarget += SpellEffectFn(spell_item_book_of_glyph_mastery_SpellScript::HandleScript, EFFECT_0, SPELL_EFFECT_SCRIPT_EFFECT); } }; SpellScript* GetSpellScript() const { return new spell_item_book_of_glyph_mastery_SpellScript(); } }; enum GiftOfTheHarvester { NPC_GHOUL = 28845, MAX_GHOULS = 5, }; class spell_item_gift_of_the_harvester : public SpellScriptLoader { public: spell_item_gift_of_the_harvester() : SpellScriptLoader("spell_item_gift_of_the_harvester") {} class spell_item_gift_of_the_harvester_SpellScript : public SpellScript { PrepareSpellScript(spell_item_gift_of_the_harvester_SpellScript); SpellCastResult CheckRequirement() { std::list<Creature*> ghouls; GetCaster()->GetAllMinionsByEntry(ghouls, NPC_GHOUL); if (ghouls.size() >= MAX_GHOULS) { SetCustomCastResultMessage(SPELL_CUSTOM_ERROR_TOO_MANY_GHOULS); return SPELL_FAILED_CUSTOM_ERROR; } return SPELL_CAST_OK; } void Register() { OnCheckCast += SpellCheckCastFn(spell_item_gift_of_the_harvester_SpellScript::CheckRequirement); } }; SpellScript* GetSpellScript() const { return new spell_item_gift_of_the_harvester_SpellScript(); } }; enum Sinkholes { NPC_SOUTH_SINKHOLE = 25664, NPC_NORTHEAST_SINKHOLE = 25665, NPC_NORTHWEST_SINKHOLE = 25666, }; class spell_item_map_of_the_geyser_fields : public SpellScriptLoader { public: spell_item_map_of_the_geyser_fields() : SpellScriptLoader("spell_item_map_of_the_geyser_fields") {} class spell_item_map_of_the_geyser_fields_SpellScript : public SpellScript { PrepareSpellScript(spell_item_map_of_the_geyser_fields_SpellScript); SpellCastResult CheckSinkholes() { Unit* caster = GetCaster(); if (caster->FindNearestCreature(NPC_SOUTH_SINKHOLE, 30.0f, true) || caster->FindNearestCreature(NPC_NORTHEAST_SINKHOLE, 30.0f, true) || caster->FindNearestCreature(NPC_NORTHWEST_SINKHOLE, 30.0f, true)) return SPELL_CAST_OK; SetCustomCastResultMessage(SPELL_CUSTOM_ERROR_MUST_BE_CLOSE_TO_SINKHOLE); return SPELL_FAILED_CUSTOM_ERROR; } void Register() { OnCheckCast += SpellCheckCastFn(spell_item_map_of_the_geyser_fields_SpellScript::CheckSinkholes); } }; SpellScript* GetSpellScript() const { return new spell_item_map_of_the_geyser_fields_SpellScript(); } }; enum VanquishedClutchesSpells { SPELL_CRUSHER = 64982, SPELL_CONSTRICTOR = 64983, SPELL_CORRUPTOR = 64984, }; class spell_item_vanquished_clutches : public SpellScriptLoader { public: spell_item_vanquished_clutches() : SpellScriptLoader("spell_item_vanquished_clutches") { } class spell_item_vanquished_clutches_SpellScript : public SpellScript { PrepareSpellScript(spell_item_vanquished_clutches_SpellScript); bool Validate(SpellInfo const* /*spellEntry*/) { if (!sSpellMgr->GetSpellInfo(SPELL_CRUSHER) || !sSpellMgr->GetSpellInfo(SPELL_CONSTRICTOR) || !sSpellMgr->GetSpellInfo(SPELL_CORRUPTOR)) return false; return true; } void HandleDummy(SpellEffIndex /*effIndex*/) { uint32 spellId = RAND(SPELL_CRUSHER, SPELL_CONSTRICTOR, SPELL_CORRUPTOR); Unit* caster = GetCaster(); caster->CastSpell(caster, spellId, true); } void Register() { OnEffectHit += SpellEffectFn(spell_item_vanquished_clutches_SpellScript::HandleDummy, EFFECT_0, SPELL_EFFECT_DUMMY); } }; SpellScript* GetSpellScript() const { return new spell_item_vanquished_clutches_SpellScript(); } }; enum AshbringerSounds { SOUND_ASHBRINGER_1 = 8906, // "I was pure once" SOUND_ASHBRINGER_2 = 8907, // "Fought for righteousness" SOUND_ASHBRINGER_3 = 8908, // "I was once called Ashbringer" SOUND_ASHBRINGER_4 = 8920, // "Betrayed by my order" SOUND_ASHBRINGER_5 = 8921, // "Destroyed by Kel'Thuzad" SOUND_ASHBRINGER_6 = 8922, // "Made to serve" SOUND_ASHBRINGER_7 = 8923, // "My son watched me die" SOUND_ASHBRINGER_8 = 8924, // "Crusades fed his rage" SOUND_ASHBRINGER_9 = 8925, // "Truth is unknown to him" SOUND_ASHBRINGER_10 = 8926, // "Scarlet Crusade is pure no longer" SOUND_ASHBRINGER_11 = 8927, // "Balnazzar's crusade corrupted my son" SOUND_ASHBRINGER_12 = 8928, // "Kill them all!" }; class spell_item_ashbringer : public SpellScriptLoader { public: spell_item_ashbringer() : SpellScriptLoader("spell_item_ashbringer") {} class spell_item_ashbringer_SpellScript : public SpellScript { PrepareSpellScript(spell_item_ashbringer_SpellScript); bool Load() { return GetCaster()->GetTypeId() == TYPEID_PLAYER; } void OnDummyEffect(SpellEffIndex effIndex) { PreventHitDefaultEffect(effIndex); Player* player = GetCaster()->ToPlayer(); uint32 sound_id = RAND( SOUND_ASHBRINGER_1, SOUND_ASHBRINGER_2, SOUND_ASHBRINGER_3, SOUND_ASHBRINGER_4, SOUND_ASHBRINGER_5, SOUND_ASHBRINGER_6, SOUND_ASHBRINGER_7, SOUND_ASHBRINGER_8, SOUND_ASHBRINGER_9, SOUND_ASHBRINGER_10, SOUND_ASHBRINGER_11, SOUND_ASHBRINGER_12 ); // Ashbringers effect (spellID 28441) retriggers every 5 seconds, with a chance of making it say one of the above 12 sounds if (urand(0, 60) < 1) player->PlayDirectSound(sound_id, player); } void Register() { OnEffectHit += SpellEffectFn(spell_item_ashbringer_SpellScript::OnDummyEffect, EFFECT_0, SPELL_EFFECT_DUMMY); } }; SpellScript* GetSpellScript() const { return new spell_item_ashbringer_SpellScript(); } }; enum MagicEater { SPELL_WILD_MAGIC = 58891, SPELL_WELL_FED_1 = 57288, SPELL_WELL_FED_2 = 57139, SPELL_WELL_FED_3 = 57111, SPELL_WELL_FED_4 = 57286, SPELL_WELL_FED_5 = 57291, }; class spell_magic_eater_food : public SpellScriptLoader { public: spell_magic_eater_food() : SpellScriptLoader("spell_magic_eater_food") {} class spell_magic_eater_food_AuraScript : public AuraScript { PrepareAuraScript(spell_magic_eater_food_AuraScript); void HandleTriggerSpell(AuraEffect const* /*aurEff*/) { PreventDefaultAction(); Unit* target = GetTarget(); switch (urand(0, 5)) { case 0: target->CastSpell(target, SPELL_WILD_MAGIC, true); break; case 1: target->CastSpell(target, SPELL_WELL_FED_1, true); break; case 2: target->CastSpell(target, SPELL_WELL_FED_2, true); break; case 3: target->CastSpell(target, SPELL_WELL_FED_3, true); break; case 4: target->CastSpell(target, SPELL_WELL_FED_4, true); break; case 5: target->CastSpell(target, SPELL_WELL_FED_5, true); break; } } void Register() { OnEffectPeriodic += AuraEffectPeriodicFn(spell_magic_eater_food_AuraScript::HandleTriggerSpell, EFFECT_1, SPELL_AURA_PERIODIC_TRIGGER_SPELL); } }; AuraScript* GetAuraScript() const { return new spell_magic_eater_food_AuraScript(); } }; class spell_item_shimmering_vessel : public SpellScriptLoader { public: spell_item_shimmering_vessel() : SpellScriptLoader("spell_item_shimmering_vessel") { } class spell_item_shimmering_vessel_SpellScript : public SpellScript { PrepareSpellScript(spell_item_shimmering_vessel_SpellScript); void HandleDummy(SpellEffIndex /* effIndex */) { if (Creature* target = GetHitCreature()) target->setDeathState(JUST_RESPAWNED); } void Register() { OnEffectHitTarget += SpellEffectFn(spell_item_shimmering_vessel_SpellScript::HandleDummy, EFFECT_0, SPELL_EFFECT_DUMMY); } }; SpellScript* GetSpellScript() const { return new spell_item_shimmering_vessel_SpellScript(); } }; enum PurifyHelboarMeat { SPELL_SUMMON_PURIFIED_HELBOAR_MEAT = 29277, SPELL_SUMMON_TOXIC_HELBOAR_MEAT = 29278, }; class spell_item_purify_helboar_meat : public SpellScriptLoader { public: spell_item_purify_helboar_meat() : SpellScriptLoader("spell_item_purify_helboar_meat") { } class spell_item_purify_helboar_meat_SpellScript : public SpellScript { PrepareSpellScript(spell_item_purify_helboar_meat_SpellScript); bool Load() { return GetCaster()->GetTypeId() == TYPEID_PLAYER; } bool Validate(SpellInfo const* /*spell*/) { if (!sSpellMgr->GetSpellInfo(SPELL_SUMMON_PURIFIED_HELBOAR_MEAT) || !sSpellMgr->GetSpellInfo(SPELL_SUMMON_TOXIC_HELBOAR_MEAT)) return false; return true; } void HandleDummy(SpellEffIndex /* effIndex */) { Unit* caster = GetCaster(); caster->CastSpell(caster, roll_chance_i(50) ? SPELL_SUMMON_PURIFIED_HELBOAR_MEAT : SPELL_SUMMON_TOXIC_HELBOAR_MEAT, true, NULL); } void Register() { OnEffectHitTarget += SpellEffectFn(spell_item_purify_helboar_meat_SpellScript::HandleDummy, EFFECT_0, SPELL_EFFECT_DUMMY); } }; SpellScript* GetSpellScript() const { return new spell_item_purify_helboar_meat_SpellScript(); } }; enum CrystalPrison { OBJECT_IMPRISONED_DOOMGUARD = 179644, }; class spell_item_crystal_prison_dummy_dnd : public SpellScriptLoader { public: spell_item_crystal_prison_dummy_dnd() : SpellScriptLoader("spell_item_crystal_prison_dummy_dnd") { } class spell_item_crystal_prison_dummy_dnd_SpellScript : public SpellScript { PrepareSpellScript(spell_item_crystal_prison_dummy_dnd_SpellScript); bool Validate(SpellInfo const* /*spell*/) { if (!sObjectMgr->GetGameObjectTemplate(OBJECT_IMPRISONED_DOOMGUARD)) return false; return true; } void HandleDummy(SpellEffIndex /* effIndex */) { if (Creature* target = GetHitCreature()) if (target->isDead() && !target->isPet()) { GetCaster()->SummonGameObject(OBJECT_IMPRISONED_DOOMGUARD, target->GetPositionX(), target->GetPositionY(), target->GetPositionZ(), target->GetOrientation(), 0, 0, 0, 0, uint32(target->GetRespawnTime()-time(NULL))); target->DespawnOrUnsummon(); } } void Register() { OnEffectHitTarget += SpellEffectFn(spell_item_crystal_prison_dummy_dnd_SpellScript::HandleDummy, EFFECT_0, SPELL_EFFECT_DUMMY); } }; SpellScript* GetSpellScript() const { return new spell_item_crystal_prison_dummy_dnd_SpellScript(); } }; enum ReindeerTransformation { SPELL_FLYING_REINDEER_310 = 44827, SPELL_FLYING_REINDEER_280 = 44825, SPELL_FLYING_REINDEER_60 = 44824, SPELL_REINDEER_100 = 25859, SPELL_REINDEER_60 = 25858, }; class spell_item_reindeer_transformation : public SpellScriptLoader { public: spell_item_reindeer_transformation() : SpellScriptLoader("spell_item_reindeer_transformation") { } class spell_item_reindeer_transformation_SpellScript : public SpellScript { PrepareSpellScript(spell_item_reindeer_transformation_SpellScript); bool Validate(SpellInfo const* /*spell*/) { if (!sSpellMgr->GetSpellInfo(SPELL_FLYING_REINDEER_310) || !sSpellMgr->GetSpellInfo(SPELL_FLYING_REINDEER_280) || !sSpellMgr->GetSpellInfo(SPELL_FLYING_REINDEER_60) || !sSpellMgr->GetSpellInfo(SPELL_REINDEER_100) || !sSpellMgr->GetSpellInfo(SPELL_REINDEER_60)) return false; return true; } void HandleDummy(SpellEffIndex /* effIndex */) { Unit* caster = GetCaster(); if (caster->HasAuraType(SPELL_AURA_MOUNTED)) { float flyspeed = caster->GetSpeedRate(MOVE_FLIGHT); float speed = caster->GetSpeedRate(MOVE_RUN); caster->RemoveAurasByType(SPELL_AURA_MOUNTED); //5 different spells used depending on mounted speed and if mount can fly or not if (flyspeed >= 4.1f) // Flying Reindeer caster->CastSpell(caster, SPELL_FLYING_REINDEER_310, true); //310% flying Reindeer else if (flyspeed >= 3.8f) // Flying Reindeer caster->CastSpell(caster, SPELL_FLYING_REINDEER_280, true); //280% flying Reindeer else if (flyspeed >= 1.6f) // Flying Reindeer caster->CastSpell(caster, SPELL_FLYING_REINDEER_60, true); //60% flying Reindeer else if (speed >= 2.0f) // Reindeer caster->CastSpell(caster, SPELL_REINDEER_100, true); //100% ground Reindeer else // Reindeer caster->CastSpell(caster, SPELL_REINDEER_60, true); //60% ground Reindeer } } void Register() { OnEffectHitTarget += SpellEffectFn(spell_item_reindeer_transformation_SpellScript::HandleDummy, EFFECT_0, SPELL_EFFECT_DUMMY); } }; SpellScript* GetSpellScript() const { return new spell_item_reindeer_transformation_SpellScript(); } }; enum NighInvulnerability { SPELL_NIGH_INVULNERABILITY = 30456, SPELL_COMPLETE_VULNERABILITY = 30457, }; class spell_item_nigh_invulnerability : public SpellScriptLoader { public: spell_item_nigh_invulnerability() : SpellScriptLoader("spell_item_nigh_invulnerability") { } class spell_item_nigh_invulnerability_SpellScript : public SpellScript { PrepareSpellScript(spell_item_nigh_invulnerability_SpellScript); bool Validate(SpellInfo const* /*spell*/) { if (!sSpellMgr->GetSpellInfo(SPELL_NIGH_INVULNERABILITY) || !sSpellMgr->GetSpellInfo(SPELL_COMPLETE_VULNERABILITY)) return false; return true; } void HandleDummy(SpellEffIndex /* effIndex */) { Unit* caster = GetCaster(); if (Item* castItem = GetCastItem()) { if (roll_chance_i(86)) // Nigh-Invulnerability - success caster->CastSpell(caster, SPELL_NIGH_INVULNERABILITY, true, castItem); else // Complete Vulnerability - backfire in 14% casts caster->CastSpell(caster, SPELL_COMPLETE_VULNERABILITY, true, castItem); } } void Register() { OnEffectHitTarget += SpellEffectFn(spell_item_nigh_invulnerability_SpellScript::HandleDummy, EFFECT_0, SPELL_EFFECT_DUMMY); } }; SpellScript* GetSpellScript() const { return new spell_item_nigh_invulnerability_SpellScript(); } }; enum Poultryzer { SPELL_POULTRYIZER_SUCCESS = 30501, SPELL_POULTRYIZER_BACKFIRE = 30504, }; class spell_item_poultryizer : public SpellScriptLoader { public: spell_item_poultryizer() : SpellScriptLoader("spell_item_poultryizer") { } class spell_item_poultryizer_SpellScript : public SpellScript { PrepareSpellScript(spell_item_poultryizer_SpellScript); bool Validate(SpellInfo const* /*spell*/) { if (!sSpellMgr->GetSpellInfo(SPELL_POULTRYIZER_SUCCESS) || !sSpellMgr->GetSpellInfo(SPELL_POULTRYIZER_BACKFIRE)) return false; return true; } void HandleDummy(SpellEffIndex /* effIndex */) { if (GetCastItem() && GetHitUnit()) GetCaster()->CastSpell(GetHitUnit(), roll_chance_i(80) ? SPELL_POULTRYIZER_SUCCESS : SPELL_POULTRYIZER_BACKFIRE, true, GetCastItem()); } void Register() { OnEffectHitTarget += SpellEffectFn(spell_item_poultryizer_SpellScript::HandleDummy, EFFECT_0, SPELL_EFFECT_DUMMY); } }; SpellScript* GetSpellScript() const { return new spell_item_poultryizer_SpellScript(); } }; enum SocretharsStone { SPELL_SOCRETHAR_TO_SEAT = 35743, SPELL_SOCRETHAR_FROM_SEAT = 35744, }; class spell_item_socrethars_stone : public SpellScriptLoader { public: spell_item_socrethars_stone() : SpellScriptLoader("spell_item_socrethars_stone") { } class spell_item_socrethars_stone_SpellScript : public SpellScript { PrepareSpellScript(spell_item_socrethars_stone_SpellScript); bool Load() { return (GetCaster()->GetAreaId() == 3900 || GetCaster()->GetAreaId() == 3742); } bool Validate(SpellInfo const* /*spell*/) { if (!sSpellMgr->GetSpellInfo(SPELL_SOCRETHAR_TO_SEAT) || !sSpellMgr->GetSpellInfo(SPELL_SOCRETHAR_FROM_SEAT)) return false; return true; } void HandleDummy(SpellEffIndex /* effIndex */) { Unit* caster = GetCaster(); switch (caster->GetAreaId()) { case 3900: caster->CastSpell(caster, SPELL_SOCRETHAR_TO_SEAT, true); break; case 3742: caster->CastSpell(caster, SPELL_SOCRETHAR_FROM_SEAT, true); break; default: return; } } void Register() { OnEffectHitTarget += SpellEffectFn(spell_item_socrethars_stone_SpellScript::HandleDummy, EFFECT_0, SPELL_EFFECT_DUMMY); } }; SpellScript* GetSpellScript() const { return new spell_item_socrethars_stone_SpellScript(); } }; enum DemonBroiledSurprise { QUEST_SUPER_HOT_STEW = 11379, SPELL_CREATE_DEMON_BROILED_SURPRISE = 43753, NPC_ABYSSAL_FLAMEBRINGER = 19973, }; class spell_item_demon_broiled_surprise : public SpellScriptLoader { public: spell_item_demon_broiled_surprise() : SpellScriptLoader("spell_item_demon_broiled_surprise") { } class spell_item_demon_broiled_surprise_SpellScript : public SpellScript { PrepareSpellScript(spell_item_demon_broiled_surprise_SpellScript); bool Validate(SpellInfo const* /*spell*/) { if (!sSpellMgr->GetSpellInfo(SPELL_CREATE_DEMON_BROILED_SURPRISE) || !sObjectMgr->GetCreatureTemplate(NPC_ABYSSAL_FLAMEBRINGER) || !sObjectMgr->GetQuestTemplate(QUEST_SUPER_HOT_STEW)) return false; return true; } bool Load() { return GetCaster()->GetTypeId() == TYPEID_PLAYER; } void HandleDummy(SpellEffIndex /* effIndex */) { Unit* player = GetCaster(); player->CastSpell(player, SPELL_CREATE_DEMON_BROILED_SURPRISE, false); } SpellCastResult CheckRequirement() { Player* player = GetCaster()->ToPlayer(); if (player->GetQuestStatus(QUEST_SUPER_HOT_STEW) != QUEST_STATUS_INCOMPLETE) return SPELL_FAILED_CANT_DO_THAT_RIGHT_NOW; if (Creature* creature = player->FindNearestCreature(NPC_ABYSSAL_FLAMEBRINGER, 10, false)) if (creature->isDead()) return SPELL_CAST_OK; return SPELL_FAILED_NOT_HERE; } void Register() { OnEffectHitTarget += SpellEffectFn(spell_item_demon_broiled_surprise_SpellScript::HandleDummy, EFFECT_1, SPELL_EFFECT_DUMMY); OnCheckCast += SpellCheckCastFn(spell_item_demon_broiled_surprise_SpellScript::CheckRequirement); } }; SpellScript* GetSpellScript() const { return new spell_item_demon_broiled_surprise_SpellScript(); } }; enum CompleteRaptorCapture { SPELL_RAPTOR_CAPTURE_CREDIT = 42337, }; class spell_item_complete_raptor_capture : public SpellScriptLoader { public: spell_item_complete_raptor_capture() : SpellScriptLoader("spell_item_complete_raptor_capture") { } class spell_item_complete_raptor_capture_SpellScript : public SpellScript { PrepareSpellScript(spell_item_complete_raptor_capture_SpellScript); bool Validate(SpellInfo const* /*spell*/) { if (!sSpellMgr->GetSpellInfo(SPELL_RAPTOR_CAPTURE_CREDIT)) return false; return true; } void HandleDummy(SpellEffIndex /* effIndex */) { Unit* caster = GetCaster(); if (GetHitCreature()) { GetHitCreature()->DespawnOrUnsummon(); //cast spell Raptor Capture Credit caster->CastSpell(caster, SPELL_RAPTOR_CAPTURE_CREDIT, true, NULL); } } void Register() { OnEffectHitTarget += SpellEffectFn(spell_item_complete_raptor_capture_SpellScript::HandleDummy, EFFECT_0, SPELL_EFFECT_DUMMY); } }; SpellScript* GetSpellScript() const { return new spell_item_complete_raptor_capture_SpellScript(); } }; enum ImpaleLeviroth { NPC_LEVIROTH = 26452, SPELL_LEVIROTH_SELF_IMPALE = 49882, }; class spell_item_impale_leviroth : public SpellScriptLoader { public: spell_item_impale_leviroth() : SpellScriptLoader("spell_item_impale_leviroth") { } class spell_item_impale_leviroth_SpellScript : public SpellScript { PrepareSpellScript(spell_item_impale_leviroth_SpellScript); bool Validate(SpellInfo const* /*spell*/) { if (!sObjectMgr->GetCreatureTemplate(NPC_LEVIROTH)) return false; return true; } void HandleDummy(SpellEffIndex /* effIndex */) { if (Unit* target = GetHitCreature()) if (target->GetEntry() == NPC_LEVIROTH && !target->HealthBelowPct(95)) target->CastSpell(target, SPELL_LEVIROTH_SELF_IMPALE, true); } void Register() { OnEffectHitTarget += SpellEffectFn(spell_item_impale_leviroth_SpellScript::HandleDummy, EFFECT_0, SPELL_EFFECT_DUMMY); } }; SpellScript* GetSpellScript() const { return new spell_item_impale_leviroth_SpellScript(); } }; enum BrewfestMountTransformation { SPELL_MOUNT_RAM_100 = 43900, SPELL_MOUNT_RAM_60 = 43899, SPELL_MOUNT_KODO_100 = 49379, SPELL_MOUNT_KODO_60 = 49378, SPELL_BREWFEST_MOUNT_TRANSFORM = 49357, SPELL_BREWFEST_MOUNT_TRANSFORM_REVERSE = 52845, }; class spell_item_brewfest_mount_transformation : public SpellScriptLoader { public: spell_item_brewfest_mount_transformation() : SpellScriptLoader("spell_item_brewfest_mount_transformation") { } class spell_item_brewfest_mount_transformation_SpellScript : public SpellScript { PrepareSpellScript(spell_item_brewfest_mount_transformation_SpellScript); bool Validate(SpellInfo const* /*spell*/) { if (!sSpellMgr->GetSpellInfo(SPELL_MOUNT_RAM_100) || !sSpellMgr->GetSpellInfo(SPELL_MOUNT_RAM_60) || !sSpellMgr->GetSpellInfo(SPELL_MOUNT_KODO_100) || !sSpellMgr->GetSpellInfo(SPELL_MOUNT_KODO_60)) return false; return true; } void HandleDummy(SpellEffIndex /* effIndex */) { Player* caster = GetCaster()->ToPlayer(); if (caster->HasAuraType(SPELL_AURA_MOUNTED)) { caster->RemoveAurasByType(SPELL_AURA_MOUNTED); uint32 spell_id; switch (GetSpellInfo()->Id) { case SPELL_BREWFEST_MOUNT_TRANSFORM: if (caster->GetSpeedRate(MOVE_RUN) >= 2.0f) spell_id = caster->GetTeam() == ALLIANCE ? SPELL_MOUNT_RAM_100 : SPELL_MOUNT_KODO_100; else spell_id = caster->GetTeam() == ALLIANCE ? SPELL_MOUNT_RAM_60 : SPELL_MOUNT_KODO_60; break; case SPELL_BREWFEST_MOUNT_TRANSFORM_REVERSE: if (caster->GetSpeedRate(MOVE_RUN) >= 2.0f) spell_id = caster->GetTeam() == HORDE ? SPELL_MOUNT_RAM_100 : SPELL_MOUNT_KODO_100; else spell_id = caster->GetTeam() == HORDE ? SPELL_MOUNT_RAM_60 : SPELL_MOUNT_KODO_60; break; default: return; } caster->CastSpell(caster, spell_id, true); } } void Register() { OnEffectHitTarget += SpellEffectFn(spell_item_brewfest_mount_transformation_SpellScript::HandleDummy, EFFECT_0, SPELL_EFFECT_DUMMY); } }; SpellScript* GetSpellScript() const { return new spell_item_brewfest_mount_transformation_SpellScript(); } }; enum NitroBoots { SPELL_NITRO_BOOTS_SUCCESS = 54861, SPELL_NITRO_BOOTS_BACKFIRE = 46014, }; class spell_item_nitro_boots : public SpellScriptLoader { public: spell_item_nitro_boots() : SpellScriptLoader("spell_item_nitro_boots") { } class spell_item_nitro_boots_SpellScript : public SpellScript { PrepareSpellScript(spell_item_nitro_boots_SpellScript); bool Load() { if (!GetCastItem()) return false; return true; } bool Validate(SpellInfo const* /*spell*/) { if (!sSpellMgr->GetSpellInfo(SPELL_NITRO_BOOTS_SUCCESS) || !sSpellMgr->GetSpellInfo(SPELL_NITRO_BOOTS_BACKFIRE)) return false; return true; } void HandleDummy(SpellEffIndex /* effIndex */) { Unit* caster = GetCaster(); bool success = caster->GetMap()->IsDungeon() || roll_chance_i(95); caster->CastSpell(caster, success ? SPELL_NITRO_BOOTS_SUCCESS : SPELL_NITRO_BOOTS_BACKFIRE, true, GetCastItem()); } void Register() { OnEffectHitTarget += SpellEffectFn(spell_item_nitro_boots_SpellScript::HandleDummy, EFFECT_0, SPELL_EFFECT_DUMMY); } }; SpellScript* GetSpellScript() const { return new spell_item_nitro_boots_SpellScript(); } }; enum TeachLanguage { SPELL_LEARN_GNOMISH_BINARY = 50242, SPELL_LEARN_GOBLIN_BINARY = 50246, }; class spell_item_teach_language : public SpellScriptLoader { public: spell_item_teach_language() : SpellScriptLoader("spell_item_teach_language") { } class spell_item_teach_language_SpellScript : public SpellScript { PrepareSpellScript(spell_item_teach_language_SpellScript); bool Load() { return GetCaster()->GetTypeId() == TYPEID_PLAYER; } bool Validate(SpellInfo const* /*spell*/) { if (!sSpellMgr->GetSpellInfo(SPELL_LEARN_GNOMISH_BINARY) || !sSpellMgr->GetSpellInfo(SPELL_LEARN_GOBLIN_BINARY)) return false; return true; } void HandleDummy(SpellEffIndex /* effIndex */) { Player* caster = GetCaster()->ToPlayer(); if (roll_chance_i(34)) caster->CastSpell(caster, caster->GetTeam() == ALLIANCE ? SPELL_LEARN_GNOMISH_BINARY : SPELL_LEARN_GOBLIN_BINARY, true); } void Register() { OnEffectHitTarget += SpellEffectFn(spell_item_teach_language_SpellScript::HandleDummy, EFFECT_0, SPELL_EFFECT_DUMMY); } }; SpellScript* GetSpellScript() const { return new spell_item_teach_language_SpellScript(); } }; enum RocketBoots { SPELL_ROCKET_BOOTS_PROC = 30452, }; class spell_item_rocket_boots : public SpellScriptLoader { public: spell_item_rocket_boots() : SpellScriptLoader("spell_item_rocket_boots") { } class spell_item_rocket_boots_SpellScript : public SpellScript { PrepareSpellScript(spell_item_rocket_boots_SpellScript); bool Load() { return GetCaster()->GetTypeId() == TYPEID_PLAYER; } bool Validate(SpellInfo const* /*spell*/) { if (!sSpellMgr->GetSpellInfo(SPELL_ROCKET_BOOTS_PROC)) return false; return true; } void HandleDummy(SpellEffIndex /* effIndex */) { Player* caster = GetCaster()->ToPlayer(); if (Battleground* bg = caster->GetBattleground()) bg->EventPlayerDroppedFlag(caster); caster->RemoveSpellCooldown(SPELL_ROCKET_BOOTS_PROC); caster->CastSpell(caster, SPELL_ROCKET_BOOTS_PROC, true, NULL); } SpellCastResult CheckCast() { if (GetCaster()->IsInWater()) return SPELL_FAILED_ONLY_ABOVEWATER; return SPELL_CAST_OK; } void Register() { OnCheckCast += SpellCheckCastFn(spell_item_rocket_boots_SpellScript::CheckCast); OnEffectHitTarget += SpellEffectFn(spell_item_rocket_boots_SpellScript::HandleDummy, EFFECT_0, SPELL_EFFECT_DUMMY); } }; SpellScript* GetSpellScript() const { return new spell_item_rocket_boots_SpellScript(); } }; enum PygmyOil { SPELL_PYGMY_OIL_PYGMY_AURA = 53806, SPELL_PYGMY_OIL_SMALLER_AURA = 53805, }; class spell_item_pygmy_oil : public SpellScriptLoader { public: spell_item_pygmy_oil() : SpellScriptLoader("spell_item_pygmy_oil") { } class spell_item_pygmy_oil_SpellScript : public SpellScript { PrepareSpellScript(spell_item_pygmy_oil_SpellScript); bool Validate(SpellInfo const* /*spell*/) { if (!sSpellMgr->GetSpellInfo(SPELL_PYGMY_OIL_PYGMY_AURA) || !sSpellMgr->GetSpellInfo(SPELL_PYGMY_OIL_SMALLER_AURA)) return false; return true; } void HandleDummy(SpellEffIndex /* effIndex */) { Unit* caster = GetCaster(); if (Aura* aura = caster->GetAura(SPELL_PYGMY_OIL_PYGMY_AURA)) aura->RefreshDuration(); else { aura = caster->GetAura(SPELL_PYGMY_OIL_SMALLER_AURA); if (!aura || aura->GetStackAmount() < 5 || !roll_chance_i(50)) caster->CastSpell(caster, SPELL_PYGMY_OIL_SMALLER_AURA, true); else { aura->Remove(); caster->CastSpell(caster, SPELL_PYGMY_OIL_PYGMY_AURA, true); } } } void Register() { OnEffectHitTarget += SpellEffectFn(spell_item_pygmy_oil_SpellScript::HandleDummy, EFFECT_0, SPELL_EFFECT_DUMMY); } }; SpellScript* GetSpellScript() const { return new spell_item_pygmy_oil_SpellScript(); } }; class spell_item_unusual_compass : public SpellScriptLoader { public: spell_item_unusual_compass() : SpellScriptLoader("spell_item_unusual_compass") { } class spell_item_unusual_compass_SpellScript : public SpellScript { PrepareSpellScript(spell_item_unusual_compass_SpellScript); void HandleDummy(SpellEffIndex /* effIndex */) { Unit* caster = GetCaster(); caster->SetFacingTo(frand(0.0f, 62832.0f) / 10000.0f); } void Register() { OnEffectHitTarget += SpellEffectFn(spell_item_unusual_compass_SpellScript::HandleDummy, EFFECT_0, SPELL_EFFECT_DUMMY); } }; SpellScript* GetSpellScript() const { return new spell_item_unusual_compass_SpellScript(); } }; enum ChickenCover { SPELL_CHICKEN_NET = 51959, SPELL_CAPTURE_CHICKEN_ESCAPE = 51037, QUEST_CHICKEN_PARTY = 12702, QUEST_FLOWN_THE_COOP = 12532, }; class spell_item_chicken_cover : public SpellScriptLoader { public: spell_item_chicken_cover() : SpellScriptLoader("spell_item_chicken_cover") { } class spell_item_chicken_cover_SpellScript : public SpellScript { PrepareSpellScript(spell_item_chicken_cover_SpellScript); bool Load() { return GetCaster()->GetTypeId() == TYPEID_PLAYER; } bool Validate(SpellInfo const* /*spell*/) { if (!sSpellMgr->GetSpellInfo(SPELL_CHICKEN_NET) || !sSpellMgr->GetSpellInfo(SPELL_CAPTURE_CHICKEN_ESCAPE) || !sObjectMgr->GetQuestTemplate(QUEST_CHICKEN_PARTY) || !sObjectMgr->GetQuestTemplate(QUEST_FLOWN_THE_COOP)) return false; return true; } void HandleDummy(SpellEffIndex /* effIndex */) { Player* caster = GetCaster()->ToPlayer(); if (Unit* target = GetHitUnit()) { if (!target->HasAura(SPELL_CHICKEN_NET) && (caster->GetQuestStatus(QUEST_CHICKEN_PARTY) == QUEST_STATUS_INCOMPLETE || caster->GetQuestStatus(QUEST_FLOWN_THE_COOP) == QUEST_STATUS_INCOMPLETE)) { caster->CastSpell(caster, SPELL_CAPTURE_CHICKEN_ESCAPE, true); target->Kill(target); } } } void Register() { OnEffectHitTarget += SpellEffectFn(spell_item_chicken_cover_SpellScript::HandleDummy, EFFECT_0, SPELL_EFFECT_DUMMY); } }; SpellScript* GetSpellScript() const { return new spell_item_chicken_cover_SpellScript(); } }; enum Refocus { SPELL_AIMED_SHOT = 19434, SPELL_MULTISHOT = 2643, SPELL_VOLLEY = 42243, }; class spell_item_refocus : public SpellScriptLoader { public: spell_item_refocus() : SpellScriptLoader("spell_item_refocus") { } class spell_item_refocus_SpellScript : public SpellScript { PrepareSpellScript(spell_item_refocus_SpellScript); void HandleDummy(SpellEffIndex /*effIndex*/) { Player* caster = GetCaster()->ToPlayer(); if (!caster || caster->getClass() != CLASS_HUNTER) return; if (caster->HasSpellCooldown(SPELL_AIMED_SHOT)) caster->RemoveSpellCooldown(SPELL_AIMED_SHOT, true); if (caster->HasSpellCooldown(SPELL_MULTISHOT)) caster->RemoveSpellCooldown(SPELL_MULTISHOT, true); if (caster->HasSpellCooldown(SPELL_VOLLEY)) caster->RemoveSpellCooldown(SPELL_VOLLEY, true); } void Register() { OnEffectHitTarget += SpellEffectFn(spell_item_refocus_SpellScript::HandleDummy, EFFECT_0, SPELL_EFFECT_DUMMY); } }; SpellScript* GetSpellScript() const { return new spell_item_refocus_SpellScript(); } }; class spell_item_muisek_vessel : public SpellScriptLoader { public: spell_item_muisek_vessel() : SpellScriptLoader("spell_item_muisek_vessel") { } class spell_item_muisek_vessel_SpellScript : public SpellScript { PrepareSpellScript(spell_item_muisek_vessel_SpellScript); void HandleDummy(SpellEffIndex /*effIndex*/) { if (Creature* target = GetHitCreature()) if (target->isDead()) target->DespawnOrUnsummon(); } void Register() { OnEffectHitTarget += SpellEffectFn(spell_item_muisek_vessel_SpellScript::HandleDummy, EFFECT_0, SPELL_EFFECT_DUMMY); } }; SpellScript* GetSpellScript() const { return new spell_item_muisek_vessel_SpellScript(); } }; enum GreatmothersSoulcather { SPELL_FORCE_CAST_SUMMON_GNOME_SOUL = 46486, }; class spell_item_greatmothers_soulcatcher : public SpellScriptLoader { public: spell_item_greatmothers_soulcatcher() : SpellScriptLoader("spell_item_greatmothers_soulcatcher") { } class spell_item_greatmothers_soulcatcher_SpellScript : public SpellScript { PrepareSpellScript(spell_item_greatmothers_soulcatcher_SpellScript); void HandleDummy(SpellEffIndex /*effIndex*/) { if (GetHitUnit()) GetCaster()->CastSpell(GetCaster(), SPELL_FORCE_CAST_SUMMON_GNOME_SOUL); } void Register() { OnEffectHitTarget += SpellEffectFn(spell_item_greatmothers_soulcatcher_SpellScript::HandleDummy, EFFECT_0, SPELL_EFFECT_DUMMY); } }; SpellScript* GetSpellScript() const { return new spell_item_greatmothers_soulcatcher_SpellScript(); } }; class spell_item_healthstone : public SpellScriptLoader { public: spell_item_healthstone() : SpellScriptLoader("spell_item_healthstone") { } class spell_item_healthstone_SpellScript : public SpellScript { PrepareSpellScript(spell_item_healthstone_SpellScript); bool inSoulburn; bool Load() { inSoulburn = false; return true; } void HandleOnHit(SpellEffIndex effIndex) { Unit* caster = GetCaster(); if (!caster) return; uint32 amount = CalculatePct(caster->GetCreateHealth(), GetSpellInfo()->Effects[effIndex].BasePoints); SetEffectDamage(amount); if (inSoulburn) caster->CastSpell(caster, 79437, true); } void HandleOnCast() { if (Unit* caster = GetCaster()) if (caster->HasAura(74434)) { inSoulburn = true; caster->RemoveAurasDueToSpell(74434); } } void Register() { OnEffectLaunchTarget += SpellEffectFn(spell_item_healthstone_SpellScript::HandleOnHit, EFFECT_0, SPELL_EFFECT_HEAL); OnCast += SpellCastFn(spell_item_healthstone_SpellScript::HandleOnCast); } }; SpellScript* GetSpellScript() const { return new spell_item_healthstone_SpellScript(); } }; enum FlaskOfTheEnchancementSpells { SPELL_FLASK_OF_ENHANCEMENT_STR = 79638, SPELL_FLASK_OF_ENHANCEMENT_AP = 79639, SPELL_FLASK_OF_ENHANCEMENT_SP = 79640, }; class spell_item_flask_of_enhancement : public SpellScriptLoader { public: spell_item_flask_of_enhancement() : SpellScriptLoader("spell_item_flask_of_enhancement") { } class spell_item_flask_of_enhancement_SpellScript : public SpellScript { PrepareSpellScript(spell_item_flask_of_enhancement_SpellScript); bool Validate(SpellInfo const* /*spellEntry*/) { if (!sSpellMgr->GetSpellInfo(SPELL_FLASK_OF_ENHANCEMENT_STR) || !sSpellMgr->GetSpellInfo(SPELL_FLASK_OF_ENHANCEMENT_AP) || !sSpellMgr->GetSpellInfo(SPELL_FLASK_OF_ENHANCEMENT_SP)) return false; return true; } void HandleDummy(SpellEffIndex /*effIndex*/) { Unit* caster = GetCaster(); if(caster->GetStat(STAT_AGILITY) > std::max(caster->GetStat(STAT_INTELLECT),caster->GetStat(STAT_STRENGTH))) // Druid CAC { caster->CastSpell(caster, SPELL_FLASK_OF_ENHANCEMENT_AP, true, NULL); } else if(caster->GetStat(STAT_STRENGTH) > std::max(caster->GetStat(STAT_INTELLECT),caster->GetStat(STAT_AGILITY))) // PALA CAC { caster->CastSpell(caster, SPELL_FLASK_OF_ENHANCEMENT_STR, true, NULL); } else if(caster->GetStat(STAT_INTELLECT) > std::max(caster->GetStat(STAT_AGILITY),caster->GetStat(STAT_STRENGTH))) // PALA Heal { caster->CastSpell(caster, SPELL_FLASK_OF_ENHANCEMENT_SP, true, NULL); } } void Register() { OnEffectHit += SpellEffectFn(spell_item_flask_of_enhancement_SpellScript::HandleDummy, EFFECT_0, SPELL_EFFECT_DUMMY); } }; SpellScript* GetSpellScript() const { return new spell_item_flask_of_enhancement_SpellScript(); } }; // http://cata.openwow.com/spell=82175 enum synapse_springs_spells { SYNAPSE_SPRINGS_SPELLS_AGI = 96228, SYNAPSE_SPRINGS_SPELLS_STR = 96229, SYNAPSE_SPRINGS_SPELLS_SP = 96230, }; class spell_item_synapse_springs : public SpellScriptLoader { public: spell_item_synapse_springs() : SpellScriptLoader("spell_item_synapse_springs") { } class spell_item_synapse_springs_SpellScript : public SpellScript { PrepareSpellScript(spell_item_synapse_springs_SpellScript); bool Validate(SpellInfo const* /*spellEntry*/) { if (!sSpellMgr->GetSpellInfo(SYNAPSE_SPRINGS_SPELLS_STR) || !sSpellMgr->GetSpellInfo(SYNAPSE_SPRINGS_SPELLS_AGI) || !sSpellMgr->GetSpellInfo(SYNAPSE_SPRINGS_SPELLS_SP)) return false; return true; } void HandleDummy(SpellEffIndex /*effIndex*/) { Unit* caster = GetCaster(); if(caster->GetStat(STAT_INTELLECT) > std::max(caster->GetStat(STAT_AGILITY),caster->GetStat(STAT_STRENGTH))) // Intel Stats { caster->CastSpell(caster, SYNAPSE_SPRINGS_SPELLS_SP, true, NULL); } else if(caster->GetStat(STAT_AGILITY) > std::max(caster->GetStat(STAT_INTELLECT),caster->GetStat(STAT_STRENGTH))) // Agi Stats { caster->CastSpell(caster, SYNAPSE_SPRINGS_SPELLS_AGI, true, NULL); } else if(caster->GetStat(STAT_STRENGTH) > std::max(caster->GetStat(STAT_INTELLECT),caster->GetStat(STAT_AGILITY))) // Strengh Stats { caster->CastSpell(caster, SYNAPSE_SPRINGS_SPELLS_STR, true, NULL); } } void Register() { OnEffectHit += SpellEffectFn(spell_item_synapse_springs_SpellScript::HandleDummy, EFFECT_0, SPELL_EFFECT_DUMMY); } }; SpellScript* GetSpellScript() const { return new spell_item_synapse_springs_SpellScript(); } }; // http://cata.openwow.com/spell=82627 // http://www.wowhead.com/spell=84427#comments Bad side Effect enum grounded_plasma_shield_spells { SPELL_GROUNDED_PLASMA_SHIELD_SUCCESS = 82627, // Proc 18k absorb SPELL_REVERSED_SHIELD = 82406, // Debuff Side Effect 1 //TODO SPELL_MAGNETIZED = 82403, // Debuff Side Effect 2 SPELL_PAINFUL_SHOCK = 82407, // Debuff Side Effect 3 Active le buff 4 SPELL_PLASMA_MISFIRE = 94549, // Debuff Side Effect 4 }; class grounded_plasma_shield : public SpellScriptLoader { public: grounded_plasma_shield() : SpellScriptLoader("grounded_plasma_shield") { } class grounded_plasma_shield_SpellScript : public SpellScript { PrepareSpellScript(grounded_plasma_shield_SpellScript); bool Load() { if (GetCastItem()) return false; return true; } bool Validate(SpellInfo const* /*spell*/) { if (!sSpellMgr->GetSpellInfo(SPELL_GROUNDED_PLASMA_SHIELD_SUCCESS) || !sSpellMgr->GetSpellInfo(SPELL_REVERSED_SHIELD) || !sSpellMgr->GetSpellInfo(SPELL_MAGNETIZED) || !sSpellMgr->GetSpellInfo(SPELL_PAINFUL_SHOCK)) return false; return true; } void HandleDummy(SpellEffIndex /* effIndex */) { Unit* caster = GetCaster(); // Need more random 1/4 bad sideeffect spells caster->CastSpell(caster, roll_chance_i(95) ? SPELL_GROUNDED_PLASMA_SHIELD_SUCCESS : SPELL_REVERSED_SHIELD, true, GetCastItem()); } void Register() { OnEffectHitTarget += SpellEffectFn(grounded_plasma_shield_SpellScript::HandleDummy, EFFECT_0, SPELL_EFFECT_DUMMY); } }; SpellScript* GetSpellScript() const { return new grounded_plasma_shield_SpellScript(); } }; // 71610, 71641 - Echoes of Light (Althor's Abacus) class spell_item_echoes_of_light : public SpellScriptLoader { public: spell_item_echoes_of_light() : SpellScriptLoader("spell_item_echoes_of_light") { } class spell_item_echoes_of_light_SpellScript : public SpellScript { PrepareSpellScript(spell_item_echoes_of_light_SpellScript); void FilterTargets(std::list<WorldObject*>& targets) { if (targets.size() < 2) return; targets.sort(Trinity::HealthPctOrderPred()); WorldObject* target = targets.front(); targets.clear(); targets.push_back(target); } void Register() { OnObjectAreaTargetSelect += SpellObjectAreaTargetSelectFn(spell_item_echoes_of_light_SpellScript::FilterTargets, EFFECT_0, TARGET_UNIT_DEST_AREA_ALLY); } }; SpellScript* GetSpellScript() const { return new spell_item_echoes_of_light_SpellScript(); } }; void AddSC_item_spell_scripts() { // 23074 Arcanite Dragonling new spell_item_trigger_spell("spell_item_arcanite_dragonling", SPELL_ARCANITE_DRAGONLING); // 23133 Gnomish Battle Chicken new spell_item_trigger_spell("spell_item_gnomish_battle_chicken", SPELL_BATTLE_CHICKEN); // 23076 Mechanical Dragonling new spell_item_trigger_spell("spell_item_mechanical_dragonling", SPELL_MECHANICAL_DRAGONLING); // 23075 Mithril Mechanical Dragonling new spell_item_trigger_spell("spell_item_mithril_mechanical_dragonling", SPELL_MITHRIL_MECHANICAL_DRAGONLING); new spell_item_aegis_of_preservation(); new spell_item_arcane_shroud(); new spell_item_blessing_of_ancient_kings(); new spell_item_defibrillate("spell_item_goblin_jumper_cables", 67, SPELL_GOBLIN_JUMPER_CABLES_FAIL); new spell_item_defibrillate("spell_item_goblin_jumper_cables_xl", 50, SPELL_GOBLIN_JUMPER_CABLES_XL_FAIL); new spell_item_defibrillate("spell_item_gnomish_army_knife", 33); new spell_item_deviate_fish(); new spell_item_desperate_defense(); new spell_item_flask_of_the_north(); new spell_item_gnomish_death_ray(); new spell_item_make_a_wish(); new spell_item_mingos_fortune_generator(); new spell_item_necrotic_touch(); new spell_item_net_o_matic(); new spell_item_noggenfogger_elixir(); new spell_item_piccolo_of_the_flaming_fire(); new spell_item_savory_deviate_delight(); new spell_item_scroll_of_recall(); new spell_item_shadows_fate(); new spell_item_shadowmourne(); new spell_item_shadowmourne_soul_fragment(); new spell_item_six_demon_bag(); new spell_item_the_eye_of_diminution(); new spell_item_underbelly_elixir(); new spell_item_red_rider_air_rifle(); new spell_item_create_heart_candy(); new spell_item_book_of_glyph_mastery(); new spell_item_gift_of_the_harvester(); new spell_item_map_of_the_geyser_fields(); new spell_item_vanquished_clutches(); new spell_item_ashbringer(); new spell_magic_eater_food(); new spell_item_refocus(); new spell_item_shimmering_vessel(); new spell_item_purify_helboar_meat(); new spell_item_crystal_prison_dummy_dnd(); new spell_item_reindeer_transformation(); new spell_item_nigh_invulnerability(); new spell_item_poultryizer(); new spell_item_socrethars_stone(); new spell_item_demon_broiled_surprise(); new spell_item_complete_raptor_capture(); new spell_item_impale_leviroth(); new spell_item_brewfest_mount_transformation(); new spell_item_nitro_boots(); new spell_item_teach_language(); new spell_item_rocket_boots(); new spell_item_pygmy_oil(); new spell_item_unusual_compass(); new spell_item_chicken_cover(); new spell_item_muisek_vessel(); new spell_item_greatmothers_soulcatcher(); new spell_item_healthstone(); new spell_item_flask_of_enhancement(); // Spell - 79637 new spell_item_synapse_springs(); // Spell - 82174 new grounded_plasma_shield(); // Spell - 82626 new spell_item_echoes_of_light(); }
LordPsyan/WoWSource434_V10
src/server/scripts/Spells/spell_item.cpp
C++
gpl-2.0
102,670
( function( $ ) { $( 'time.entry-published' ).on( "click", function() { var old_date = $(this).html().trim(); $(this).html( $(this).attr( 'data-display-toggle' ) ); $(this).attr( 'data-display-toggle', old_date ); } ); } )( jQuery );
aprea/adoration
js/adoration.js
JavaScript
gpl-2.0
244
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <meta http-equiv="Content-Type" content="text/xhtml;charset=UTF-8"/> <meta http-equiv="X-UA-Compatible" content="IE=9"/> <meta name="generator" content="Doxygen 1.8.13"/> <meta name="viewport" content="width=device-width, initial-scale=1"/> <title>PLUTO: /Users/mignone/PLUTO/Src/int_bound_reset.c File Reference</title> <link href="tabs.css" rel="stylesheet" type="text/css"/> <script type="text/javascript" src="jquery.js"></script> <script type="text/javascript" src="dynsections.js"></script> <link href="search/search.css" rel="stylesheet" type="text/css"/> <script type="text/javascript" src="search/searchdata.js"></script> <script type="text/javascript" src="search/search.js"></script> <link href="doxygen.css" rel="stylesheet" type="text/css" /> </head> <body> <div id="top"><!-- do not remove this div, it is closed by doxygen! --> <div id="titlearea"> <table cellspacing="0" cellpadding="0"> <tbody> <tr style="height: 56px;"> <td id="projectalign" style="padding-left: 0.5em;"> <div id="projectname">PLUTO &#160;<span id="projectnumber">4.3</span> </div> </td> </tr> </tbody> </table> </div> <!-- end header part --> <!-- Generated by Doxygen 1.8.13 --> <script type="text/javascript"> var searchBox = new SearchBox("searchBox", "search",false,'Search'); </script> <script type="text/javascript" src="menudata.js"></script> <script type="text/javascript" src="menu.js"></script> <script type="text/javascript"> $(function() { initMenu('',true,false,'search.php','Search'); $(document).ready(function() { init_search(); }); }); </script> <div id="main-nav"></div> <!-- window showing the filter options --> <div id="MSearchSelectWindow" onmouseover="return searchBox.OnSearchSelectShow()" onmouseout="return searchBox.OnSearchSelectHide()" onkeydown="return searchBox.OnSearchSelectKey(event)"> </div> <!-- iframe showing the search results (closed by default) --> <div id="MSearchResultsWindow"> <iframe src="javascript:void(0)" frameborder="0" name="MSearchResults" id="MSearchResults"> </iframe> </div> <div id="nav-path" class="navpath"> <ul> <li class="navelem"><a class="el" href="dir_413f4e031a85da0d68269c6fd2f76e1c.html">Src</a></li> </ul> </div> </div><!-- top --> <div class="header"> <div class="headertitle"> <div class="title">int_bound_reset.c File Reference</div> </div> </div><!--header--> <div class="contents"> <p>Reset to zero the right hand side in the internal boundary. <a href="#details">More...</a></p> <div class="textblock"><code>#include &quot;<a class="el" href="pluto_8h_source.html">pluto.h</a>&quot;</code><br /> </div><a name="details" id="details"></a><h2 class="groupheader">Detailed Description</h2> <div class="textblock"><p>Set to zero the right hand side of the conservative equations in those cells that have been flagged with <a class="el" href="pluto_8h.html#a7a8bdcff8ca238ef861f28f4c604d91d">FLAG_INTERNAL_BOUNDARY</a>.</p> <dl class="section author"><dt>Author</dt><dd>A. Mignone (<a href="#" onclick="location.href='mai'+'lto:'+'mig'+'no'+'ne@'+'ph'+'.un'+'it'+'o.i'+'t'; return false;">migno<span style="display: none;">.nosp@m.</span>ne@p<span style="display: none;">.nosp@m.</span>h.uni<span style="display: none;">.nosp@m.</span>to.i<span style="display: none;">.nosp@m.</span>t</a>) </dd></dl> <dl class="section date"><dt>Date</dt><dd>July 22, 2015 </dd></dl> </div></div><!-- contents --> <!-- start footer part --> <hr class="footer"/><address class="footer"><small> Generated on Thu Jun 7 2018 18:33:50 for PLUTO by &#160;<a href="http://www.doxygen.org/index.html"> <img class="footer" src="doxygen.png" alt="doxygen"/> </a> 1.8.13 </small></address> </body> </html>
JohannesBuchner/PLUTO
Doc/Doxygen/html/int__bound__reset_8c.html
HTML
gpl-2.0
3,864
<?php /* * gwolle_gb_get_entry_count * Get the number of entries. * * Parameter $args is an Array: * - checked string: 'checked' or 'unchecked', List the entries that are checked or not checked * - trash string: 'trash' or 'notrash', List the entries that are deleted or not deleted * - spam string: 'spam' or 'nospam', List the entries marked as spam or as no spam * - all string: 'all', List all entries * * Return: * - int with the count of the entries * - false if there's an error. */ function gwolle_gb_get_entry_count($args) { global $wpdb; $where = " 1 = %d"; $values = Array(1); if ( !is_array($args) ) { return false; } if ( isset($args['checked']) ) { if ( $args['checked'] == 'checked' || $args['checked'] == 'unchecked' ) { $where .= " AND ischecked = %d"; if ( $args['checked'] == 'checked' ) { $values[] = 1; } else if ( $args['checked'] == 'unchecked' ) { $values[] = 0; } } } if ( isset($args['spam']) ) { if ( $args['spam'] == 'spam' || $args['spam'] == 'nospam' ) { $where .= " AND isspam = %d"; if ( $args['spam'] == 'spam' ) { $values[] = 1; } else if ( $args['spam'] == 'nospam' ) { $values[] = 0; } } } if ( isset($args['trash']) ) { if ( $args['trash'] == 'trash' || $args['trash'] == 'notrash' ) { $where .= " AND istrash = %d"; if ( $args['trash'] == 'trash' ) { $values[] = 1; } else if ( $args['trash'] == 'notrash' ) { $values[] = 0; } } } $tablename = $wpdb->prefix . "gwolle_gb_entries"; $sql = " SELECT COUNT(id) AS count FROM " . $tablename . " WHERE " . $where . " ;"; // If All is set, do not use $wpdb->prepare() if ( isset($args['all']) ) { if ( $args['all'] == 'all' ) { $sql = " SELECT COUNT(id) AS count FROM " . $tablename . ";"; } } else { $sql = $wpdb->prepare( $sql, $values ); } $data = $wpdb->get_results( $sql, ARRAY_A ); return (int) $data[0]['count']; }
TheNexusMan/Rest-a-Dom
wp-content/plugins/gwolle-gb/functions/function.get_entry_count.php
PHP
gpl-2.0
2,010
/** * @file * @brief Miscellaneous debugging functions. **/ #include "AppHdr.h" #include "dbg-util.h" #include "artefact.h" #include "cio.h" #include "coord.h" #include "dungeon.h" #include "env.h" #include "libutil.h" #include "message.h" #include "mon-stuff.h" #include "mon-util.h" #include "religion.h" #include "shopping.h" #include "skills2.h" #include "spl-util.h" monster_type debug_prompt_for_monster(void) { char specs[80]; mpr("Which monster by name? ", MSGCH_PROMPT); if (!cancelable_get_line_autohist(specs, sizeof specs)) { if (specs[0] == '\0') return (MONS_NO_MONSTER); return (get_monster_by_name(specs)); } return (MONS_NO_MONSTER); } static void _dump_vault_table(const CrawlHashTable &table) { if (!table.empty()) { CrawlHashTable::const_iterator i = table.begin(); for (; i != table.end(); ++i) mprf(" %s: %s", i->first.c_str(), i->second.get_string().c_str()); } } void debug_dump_levgen() { if (crawl_state.game_is_arena()) return; CrawlHashTable &props = env.properties; std::string method; std::string type; if (Generating_Level) { mpr("Currently generating level."); method = env.level_build_method; type = comma_separated_line(env.level_layout_types.begin(), env.level_layout_types.end(), ", "); } else { if (!props.exists(BUILD_METHOD_KEY)) method = "ABSENT"; else method = props[BUILD_METHOD_KEY].get_string(); if (!props.exists(LAYOUT_TYPE_KEY)) type = "ABSENT"; else type = props[LAYOUT_TYPE_KEY].get_string(); } mprf("level build method = %s", method.c_str()); mprf("level layout type = %s", type.c_str()); if (props.exists(LEVEL_EXTRAS_KEY)) { mpr("Level extras:"); const CrawlHashTable &extras = props[LEVEL_EXTRAS_KEY].get_table(); _dump_vault_table(extras); } if (props.exists(LEVEL_VAULTS_KEY)) { mpr("Level vaults:"); const CrawlHashTable &vaults = props[LEVEL_VAULTS_KEY].get_table(); _dump_vault_table(vaults); } mpr(""); } void error_message_to_player(void) { mpr("Oh dear. There appears to be a bug in the program."); mpr("I suggest you leave this level then save as soon as possible."); } std::string debug_coord_str(const coord_def &pos) { return make_stringf("(%d, %d)%s", pos.x, pos.y, !in_bounds(pos) ? " <OoB>" : ""); } std::string debug_mon_str(const monster* mon) { const int midx = mon->mindex(); if (invalid_monster_index(midx)) return make_stringf("Invalid monster index %d", midx); std::string out = "Monster '" + mon->full_name(DESC_PLAIN, true) + "' "; out += make_stringf("%s [midx = %d]", debug_coord_str(mon->pos()).c_str(), midx); return (out); } void debug_dump_mon(const monster* mon, bool recurse) { const int midx = mon->mindex(); if (invalid_monster_index(midx) || invalid_monster_type(mon->type)) return; fprintf(stderr, "<<<<<<<<<\n"); fprintf(stderr, "Name: %s\n", mon->name(DESC_PLAIN, true).c_str()); fprintf(stderr, "Base name: %s\n", mon->base_name(DESC_PLAIN, true).c_str()); fprintf(stderr, "Full name: %s\n\n", mon->full_name(DESC_PLAIN, true).c_str()); if (in_bounds(mon->pos())) { std::string feat = raw_feature_description(grd(mon->pos()), NUM_TRAPS, true); fprintf(stderr, "On/in/over feature: %s\n\n", feat.c_str()); } fprintf(stderr, "Foe: "); if (mon->foe == MHITNOT) fprintf(stderr, "none"); else if (mon->foe == MHITYOU) fprintf(stderr, "player"); else if (invalid_monster_index(mon->foe)) fprintf(stderr, "invalid monster index %d", mon->foe); else if (mon->foe == midx) fprintf(stderr, "self"); else fprintf(stderr, "%s", debug_mon_str(&menv[mon->foe]).c_str()); fprintf(stderr, "\n"); fprintf(stderr, "Target: "); if (mon->target.origin()) fprintf(stderr, "none\n"); else fprintf(stderr, "%s\n", debug_coord_str(mon->target).c_str()); int target = MHITNOT; fprintf(stderr, "At target: "); if (mon->target.origin()) fprintf(stderr, "N/A"); else if (mon->target == you.pos()) { fprintf(stderr, "player"); target = MHITYOU; } else if (mon->target == mon->pos()) { fprintf(stderr, "self"); target = midx; } else if (in_bounds(mon->target)) { target = mgrd(mon->target); if (target == NON_MONSTER) fprintf(stderr, "nothing"); else if (target == midx) fprintf(stderr, "improperly linked self"); else if (target == mon->foe) fprintf(stderr, "same as foe"); else if (invalid_monster_index(target)) fprintf(stderr, "invalid monster index %d", target); else fprintf(stderr, "%s", debug_mon_str(&menv[target]).c_str()); } else fprintf(stderr, "<OoB>"); fprintf(stderr, "\n"); if (mon->is_patrolling()) { fprintf(stderr, "Patrolling: %s\n\n", debug_coord_str(mon->patrol_point).c_str()); } if (mon->travel_target != MTRAV_NONE) { fprintf(stderr, "\nTravelling:\n"); fprintf(stderr, " travel_target = %d\n", mon->travel_target); fprintf(stderr, " travel_path.size() = %u\n", (unsigned int)mon->travel_path.size()); if (mon->travel_path.size() > 0) { fprintf(stderr, " next travel step: %s\n", debug_coord_str(mon->travel_path.back()).c_str()); fprintf(stderr, " last travel step: %s\n", debug_coord_str(mon->travel_path.front()).c_str()); } } fprintf(stderr, "\n"); fprintf(stderr, "Inventory:\n"); for (int i = 0; i < NUM_MONSTER_SLOTS; ++i) { const int idx = mon->inv[i]; if (idx == NON_ITEM) continue; fprintf(stderr, " slot #%d: ", i); if (idx < 0 || idx > MAX_ITEMS) { fprintf(stderr, "invalid item index %d\n", idx); continue; } const item_def &item(mitm[idx]); if (!item.defined()) { fprintf(stderr, "invalid item\n"); continue; } fprintf(stderr, "%s", item.name(DESC_PLAIN, false, true).c_str()); if (!item.held_by_monster()) { fprintf(stderr, " [not held by monster, pos = %s]", debug_coord_str(item.pos).c_str()); } else if (item.holding_monster() != mon) { fprintf(stderr, " [held by other monster: %s]", debug_mon_str(item.holding_monster()).c_str()); } fprintf(stderr, "\n"); } fprintf(stderr, "\n"); if (mon->can_use_spells()) { fprintf(stderr, "Spells:\n"); for (int i = 0; i < NUM_MONSTER_SPELL_SLOTS; ++i) { spell_type spell = mon->spells[i]; if (spell == SPELL_NO_SPELL) continue; fprintf(stderr, " slot #%d: ", i); if (!is_valid_spell(spell)) fprintf(stderr, "Invalid spell #%d\n", (int) spell); else fprintf(stderr, "%s\n", spell_title(spell)); } fprintf(stderr, "\n"); } fprintf(stderr, "attitude: %d, behaviour: %d, number: %d, flags: 0x%"PRIx64"\n", mon->attitude, mon->behaviour, mon->number, mon->flags); fprintf(stderr, "colour: %d, foe_memory: %d, shield_blocks:%d, " "experience: %u\n", mon->colour, mon->foe_memory, mon->shield_blocks, mon->experience); fprintf(stderr, "god: %s, seen_context: %s\n", god_name(mon->god).c_str(), mon->seen_context.c_str()); fprintf(stderr, ">>>>>>>>>\n\n"); if (!recurse) return; if (!invalid_monster_index(mon->foe) && mon->foe != midx && !invalid_monster_type(menv[mon->foe].type)) { fprintf(stderr, "Foe:\n"); debug_dump_mon(&menv[mon->foe], false); } if (!invalid_monster_index(target) && target != midx && target != mon->foe && !invalid_monster_type(menv[target].type)) { fprintf(stderr, "Target:\n"); debug_dump_mon(&menv[target], false); } } //--------------------------------------------------------------- // // debug_prompt_for_skill // //--------------------------------------------------------------- skill_type debug_prompt_for_skill(const char *prompt) { char specs[80]; msgwin_get_line_autohist(prompt, specs, sizeof(specs)); if (specs[0] == '\0') return (SK_NONE); skill_type skill = SK_NONE; for (int i = SK_FIRST_SKILL; i < NUM_SKILLS; ++i) { skill_type sk = static_cast<skill_type>(i); // Avoid the bad values. if (is_invalid_skill(sk)) continue; char sk_name[80]; strncpy(sk_name, skill_name(sk), sizeof(sk_name)); char *ptr = strstr(strlwr(sk_name), strlwr(specs)); if (ptr != NULL) { if (ptr == sk_name && strlen(specs) > 0) { // We prefer prefixes over partial matches. skill = sk; break; } else skill = sk; } } return (skill); } std::string debug_art_val_str(const item_def& item) { ASSERT(is_artefact(item)); return make_stringf("art val: %d, item val: %d", artefact_value(item), item_value(item, true)); } int debug_cap_stat(int stat) { return (stat < 1 ? 1 : stat > 127 ? 127 : stat); } #ifdef DEBUG static FILE *debugf = 0; void debuglog(const char *format, ...) { va_list args; if (!debugf) { debugf = fopen("debuglog.txt", "w"); ASSERT(debugf); } va_start(args, format); vfprintf(debugf, format, args); va_end(args); fflush(debugf); } #endif
dtsund/dtsund-crawl-mod
source/dbg-util.cc
C++
gpl-2.0
10,334
package com.feedback.rest; import java.util.ArrayList; import java.util.Date; import java.util.List; import javax.ws.rs.GET; import javax.ws.rs.Path; import javax.ws.rs.Produces; import javax.ws.rs.core.MediaType; import com.feedback.beans.DataUnit; import com.feedback.data.Data; /** * A resource for generating data sets for testing purposes */ @Path("test") public class TestResource { /** * Create a randomly generated data set of 100 values between 0 and 10 * * @param dataSetSize * size of the data set to create * * @param maxValue * max value of each data unit created * * @return the generated data set */ private List<DataUnit> createRandomDataSet(int dataSetSize, int maxValue) { double random; List<DataUnit> outputList = new ArrayList<DataUnit>(); Date now = new Date(); DataUnit dataUnit; for (int i = 0; i < dataSetSize; i++) { random = Math.random(); dataUnit = new DataUnit(); dataUnit.setCreatedAt(now); now = new Date((long) (now.getTime() + random * 100000000)); dataUnit.setValue(random * maxValue); outputList.add(dataUnit); } return outputList; } /** * Get a randomly generated data set of 100 values between 0 and 10 * * @return the generated data set */ @GET @Produces(MediaType.APPLICATION_JSON) public Data getTest() { Data data = new Data(); data.setDataUnits(createRandomDataSet(100, 10)); return data; } }
tzbee/feedback
src/main/java/com/feedback/rest/TestResource.java
Java
gpl-2.0
1,446
"use strict"; function Bola(context) { this.context = context; this.x = 0; this.y = 0; this.velocidadeX = 0; this.velocidadeY = 0; this.cor = 'black'; this.raio = 10; } Bola.prototype = { // - Interface utilizada em animacao.js atualizar : function() { var ctx = this.context; if (this.x < this.raio || this.x > ctx.canvas.width - this.raio) this.velocidadeX *= -1; if (this.y < this.raio || this.y > ctx.canvas.height - this.raio) this.velocidadeY *= -1; this.x += this.velocidadeX; this.y += this.velocidadeY; }, desenhar: function() { var ctx = this.context; ctx.save(); ctx.fillStyle = this.cor; ctx.beginPath(); ctx.arc(this.x, this.y, this.raio, 0, 2 * Math.PI, false); ctx.fill(); ctx.restore(); }, // - Interface utilizada em colisor.js retangulosColisao: function() { return [{ x: this.x - this.raio, y: this.y - this.raio, largura: this.raio * 2, altura: this.raio * 2 }]; }, colidiuCom: function(sprite) { if (this.x < sprite.x) this.velocidadeX = -Math.abs(this.velocidadeX); else this.velocidadeX = Math.abs(this.velocidadeX); if (this.y < sprite.y) this.velocidadeY = -Math.abs(this.velocidadeY); else this.velocidadeY = Math.abs(this.velocidadeY); } }
edgarberlinck/edgarberlinck.github.io
canvas/10-colisoes/bola.js
JavaScript
gpl-2.0
1,324
# ========================================================================== # Build system # ========================================================================== SKIP_STRIP=y cmd_busybox__ = \ $(CC) \ -o $@.js \ --memory-init-file 0 \ -Wl,--start-group \ $(CFLAGS) \ $(CFLAGS_busybox) \ $(LDFLAGS) \ $(EM_LDFLAGS) \ $(EXTRA_LDFLAGS) \ $(core-y) \ $(libs-y) \ $(patsubst %,-l%,$(subst :, ,$(LDLIBS))) \ -Wl,--end-group \ && mv $@.js $@
tbfleming/em-busybox
arch/em/Makefile
Makefile
gpl-2.0
528
/* -*- Mode: C++; c-file-style: "gnu"; indent-tabs-mode:nil; -*- */ /* * Copyright (c) 2011 Centre Tecnologic de Telecomunicacions de Catalunya (CTTC) * Copyright (c) 2015, NYU WIRELESS, Tandon School of Engineering, New York University * Copyright (c) 2016, University of Padova, Dep. of Information Engineering, SIGNET lab. * * 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:100cento * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA * * Author: Marco Miozzo <marco.miozzo@cttc.es> * Nicola Baldo <nbaldo@cttc.es> * * Modified by: Marco Mezzavilla < mezzavilla@nyu.edu> * Sourjya Dutta <sdutta@nyu.edu> * Russell Ford <russell.ford@nyu.edu> * Menglei Zhang <menglei@nyu.edu> * * Modified by: Michele Polese <michele.polese@gmail.com> * Dual Connectivity and Handover functionalities */ #ifndef SRC_MMWAVE_MODEL_MMWAVE_UE_PHY_H_ #define SRC_MMWAVE_MODEL_MMWAVE_UE_PHY_H_ #include <ns3/mmwave-phy.h> #include "mmwave-phy-mac-common.h" #include <ns3/ptr.h> #include "mmwave-amc.h" #include <map> #include <ns3/lte-ue-phy-sap.h> #include <ns3/lte-ue-cphy-sap.h> #include <ns3/mmwave-harq-phy.h> #include "mmwave-enb-net-device.h" namespace ns3 { class PacketBurst; namespace mmwave { class mmwEnbPhy; class MmWaveUePhy : public MmWavePhy { friend class UeMemberLteUePhySapProvider; friend class MemberLteUeCphySapProvider<MmWaveUePhy>; public: MmWaveUePhy (); MmWaveUePhy (Ptr<MmWaveSpectrumPhy> ulPhy, Ptr<MmWaveSpectrumPhy> dlPhy); virtual ~MmWaveUePhy (); // inherited from Object static TypeId GetTypeId (void); virtual void DoInitialize (void); virtual void DoDispose (void); LteUeCphySapProvider* GetUeCphySapProvider (); void SetUeCphySapUser (LteUeCphySapUser* s); void SetTxPower (double pow); double GetTxPower () const; void SetNoiseFigure (double pf); double GetNoiseFigure () const; bool SendPacket(Ptr<Packet> packet); Ptr<SpectrumValue> CreateTxPowerSpectralDensity(); void DoSetSubChannels(); void SetSubChannelsForReception(std::vector <int> mask); std::vector <int> GetSubChannelsForReception(void); void SetSubChannelsForTransmission(std::vector <int> mask); std::vector <int> GetSubChannelsForTransmission(void); void DoSendControlMessage (Ptr<MmWaveControlMessage> msg); void RegisterToEnb (uint16_t cellId, Ptr<MmWavePhyMacCommon> config); void RegisterOtherEnb (uint16_t cellId, Ptr<MmWavePhyMacCommon> config, Ptr<MmWaveEnbNetDevice> enb); Ptr<MmWaveSpectrumPhy> GetDlSpectrumPhy () const; Ptr<MmWaveSpectrumPhy> GetUlSpectrumPhy () const; void ReceiveControlMessageList (std::list<Ptr<MmWaveControlMessage> > msgList); void SubframeIndication (uint16_t frameNum, uint8_t subframeNum); void StartSlot (); void EndSlot (); uint32_t GetSubframeNumber (void); void PhyDataPacketReceived (Ptr<Packet> p); void DelayPhyDataPacketReceived (Ptr<Packet> p); void SendDataChannels (Ptr<PacketBurst> pb, std::list<Ptr<MmWaveControlMessage> > ctrlMsg, Time duration, uint8_t slotInd); void SendCtrlChannels (std::list<Ptr<MmWaveControlMessage> > ctrlMsg, Time prd); uint32_t GetAbsoluteSubframeNo (); // Used for tracing purposes Ptr<MmWaveDlCqiMessage> CreateDlCqiFeedbackMessage (const SpectrumValue& sinr); void GenerateDlCqiReport (const SpectrumValue& sinr); void SetImsi (uint64_t imsi); uint64_t GetImsi () const; bool IsReceptionEnabled (); void ResetReception (); uint16_t GetRnti (); void SetPhySapUser (MmWaveUePhySapUser* ptr); void SetHarqPhyModule (Ptr<MmWaveHarqPhy> harq); void ReceiveLteDlHarqFeedback (DlHarqInfo m); void UpdateSinrEstimate(uint16_t cellId, double sinr); private: void DoReset (); void DoStartCellSearch (uint16_t dlEarfcn); void DoSynchronizeWithEnb (uint16_t cellId); void DoSynchronizeWithEnb (uint16_t cellId, uint16_t dlEarfcn); void DoSetPa (double pa); void DoSetDlBandwidth (uint8_t ulBandwidth); void DoConfigureUplink (uint16_t ulEarfcn, uint8_t ulBandwidth); void DoConfigureReferenceSignalPower (int8_t referenceSignalPower); void DoSetRnti (uint16_t rnti); void DoSetTransmissionMode (uint8_t txMode); void DoSetSrsConfigurationIndex (uint16_t srcCi); void ReceiveDataPeriod (uint32_t slotNum); void QueueUlTbAlloc (TbAllocInfo tbAllocInfo); std::list<TbAllocInfo> DequeueUlTbAlloc (); MmWaveUePhySapUser* m_phySapUser; LteUeCphySapProvider* m_ueCphySapProvider; LteUeCphySapUser* m_ueCphySapUser; Ptr<MmWaveAmc> m_amc; std::vector <int> m_subChannelsForTx; std::vector <int> m_subChannelsforRx; uint32_t m_numRbg; Time m_wbCqiPeriod; /**< Wideband Periodic CQI: 2, 5, 10, 16, 20, 32, 40, 64, 80 or 160 ms */ Time m_wbCqiLast; SlotAllocInfo::TddMode m_prevSlotDir; SfAllocInfo m_currSfAllocInfo; std::vector< std::list<TbAllocInfo> > m_ulTbAllocQueue; // for storing info on future UL TB transmissions bool m_ulGrant; // true if no uplink grant in subframe, need to transmit UL control in PUCCH instead bool m_sfAllocInfoUpdated; Time m_dlCtrlPeriod; Time m_ulCtrlPeriod; Time m_dataPeriod; // data period length in microseconds Time m_sfPeriod; Time m_lastSfStart; bool m_dlConfigured; bool m_ulConfigured; TracedCallback< uint64_t, SpectrumValue&, SpectrumValue& > m_reportCurrentCellRsrpSinrTrace; TracedCallback<uint64_t, uint64_t> m_reportUlTbSize; TracedCallback<uint64_t, uint64_t> m_reportDlTbSize; uint8_t m_prevSlot; bool m_receptionEnabled; uint16_t m_rnti; uint64_t m_imsi; Ptr<MmWaveHarqPhy> m_harqPhyModule; std::vector<int> m_channelChunks; SlotAllocInfo m_currSlot; std::map<uint16_t, std::pair<Ptr<MmWavePhyMacCommon>, Ptr<MmWaveEnbNetDevice> > > m_registeredEnb; EventId m_sendDataChannelEvent; EventId m_sendDlHarqFeedbackEvent; bool m_phyReset; std::map<uint16_t, double> m_cellSinrMap; uint8_t m_consecutiveSinrBelowThreshold; long double m_outageThreshold; uint8_t m_n310; }; } } #endif /* SRC_MMWAVE_MODEL_MMWAVE_UE_PHY_H_ */
nyuwireless-unipd/mmwave
model/mmwave-ue-phy.h
C
gpl-2.0
6,538
<?php /* Remove Unwanted Header Links */ remove_action('wp_head', 'rsd_link'); remove_action('wp_head', 'wp_generator'); remove_action('wp_head', 'feed_links', 2); remove_action('wp_head', 'index_rel_link'); remove_action('wp_head', 'wlwmanifest_link'); remove_action('wp_head', 'feed_links_extra', 3); remove_action('wp_head', 'start_post_rel_link', 10, 0); remove_action('wp_head', 'parent_post_rel_link', 10, 0); remove_action('wp_head', 'adjacent_posts_rel_link', 10, 0); /* remove WP default inline CSS for ".recentcomments a" from header */ add_action('widgets_init', 'my_remove_recent_comments_style'); function my_remove_recent_comments_style() { global $wp_widget_factory; remove_action('wp_head', array($wp_widget_factory->widgets['WP_Widget_Recent_Comments'], 'recent_comments_style')); } /* remove unwanted Tags */ function remove_invalid_tags($str, $tags) { foreach($tags as $tag) { $str = preg_replace('#^<\/'.$tag.'>|<'.$tag.'>$#', '', $str); } return $str; } ?>
matt-tyas/matthewtyas.com
lab/gmfootballcentre/wp-content/themes/tisa-wp/inc/remove.php
PHP
gpl-2.0
1,004
#include "Input.hpp" Input::Input(){ _keybinds.insert({ { "up", SDL_SCANCODE_UP }, { "down", SDL_SCANCODE_DOWN }, { "left", SDL_SCANCODE_LEFT }, { "right", SDL_SCANCODE_RIGHT }, { "w", SDL_SCANCODE_W }, { "s", SDL_SCANCODE_S }, { "a", SDL_SCANCODE_A }, { "d", SDL_SCANCODE_D }, { "z", SDL_SCANCODE_Z }, { "x", SDL_SCANCODE_X }, { "q", SDL_SCANCODE_Q }, { "e", SDL_SCANCODE_E }, { "ctrl", SDL_SCANCODE_LCTRL }, { "space", SDL_SCANCODE_SPACE }, { "shift", SDL_SCANCODE_LSHIFT } }); } void Input::update(double dt){ const Uint8* keysDown = SDL_GetKeyboardState(0); for (KeyMap::iterator i = _keybinds.begin(); i != _keybinds.end(); i++){ StringSet::iterator keyString = _down.find(i->first); if (keysDown[i->second]){ if (keyString == _down.end()) _down.insert(i->first); } else{ if (keyString != _down.end()) _down.erase(i->first); } } } bool Input::isDown(const std::string& key){ StringSet::iterator keyString = _down.find(key); if (keyString == _down.end()) return false; return true; }
Stormatree/Component-Engine
engine/Component/Input.cpp
C++
gpl-2.0
1,058
set -e # Abort on error ./bin/trailing_whitespace_test.sh ./bin/indentation.sh ./bin/hlint_health.sh ./bin/sanity.sh
NorfairKing/the-notes
bin/code_health.sh
Shell
gpl-2.0
117
/* * Island Aruma ACPI support * written by Stefan Reinauer <stepan@openbios.org> * (C) 2005 Stefan Reinauer * * * Copyright 2005 AMD * 2005.9 yhlu modify that to more dynamic for AMD Opteron Based MB */ #include <console/console.h> #include <string.h> #include <arch/acpi.h> #include <arch/smp/mpspec.h> #include <device/pci.h> #include <device/pci_ids.h> #include <cpu/x86/msr.h> #include <cpu/amd/mtrr.h> #include <cpu/amd/amdk8_sysconf.h> #include "northbridge/amd/amdk8/acpi.h" #include <cpu/amd/model_fxx_powernow.h> extern const unsigned char AmlCode[]; unsigned long acpi_fill_mcfg(unsigned long current) { return current; } /* APIC */ unsigned long acpi_fill_madt(unsigned long current) { unsigned long apic_addr; device_t dev; /* create all subtables for processors */ current = acpi_create_madt_lapics(current); /* Write NVIDIA CK804 IOAPIC. */ dev = dev_find_slot(0x0, PCI_DEVFN(0x1,0)); if (dev) { apic_addr = pci_read_config32(dev, PCI_BASE_ADDRESS_1) & ~0xf; current += acpi_create_madt_ioapic((acpi_madt_ioapic_t *) current, 4, apic_addr, 0); /* Initialize interrupt mapping if mptable.c didn't. */ #if (!CONFIG_GENERATE_MP_TABLE) { u32 dword; dword = 0x0120d218; pci_write_config32(dev, 0x7c, dword); dword = 0x12008a00; pci_write_config32(dev, 0x80, dword); dword = 0x00080d7d; pci_write_config32(dev, 0x84, dword); } #endif } /* Write AMD 8131 two IOAPICs. */ dev = dev_find_slot(0x40, PCI_DEVFN(0x0,1)); if (dev) { apic_addr = pci_read_config32(dev, PCI_BASE_ADDRESS_0) & ~0xf; current += acpi_create_madt_ioapic((acpi_madt_ioapic_t *) current, 5, apic_addr, 0x18); } dev = dev_find_slot(0x40, PCI_DEVFN(0x1, 1)); if (dev) { apic_addr = pci_read_config32(dev, PCI_BASE_ADDRESS_0) & ~0xf; current += acpi_create_madt_ioapic((acpi_madt_ioapic_t *) current, 6, apic_addr, 0x1C); } /* Write second NVIDIA CK804 IOAPIC. */ dev = dev_find_slot(0x80, PCI_DEVFN(0x1, 0)); if (dev) { apic_addr = pci_read_config32(dev, PCI_BASE_ADDRESS_1) & ~0xf; current += acpi_create_madt_ioapic((acpi_madt_ioapic_t *) current, 7, apic_addr, 0x20); /* Initialize interrupt mapping if mptable.c didn't. */ #if (!CONFIG_GENERATE_MP_TABLE) { u32 dword; dword = 0x0000d218; // Why does the factory BIOS have 0? pci_write_config32(dev, 0x7c, dword); dword = 0x00000000; pci_write_config32(dev, 0x80, dword); dword = 0x00000d00; // Same here. pci_write_config32(dev, 0x84, dword); } #endif } /* IRQ9 */ current += acpi_create_madt_irqoverride((acpi_madt_irqoverride_t *) current, 0, 9, 9, MP_IRQ_TRIGGER_EDGE | MP_IRQ_POLARITY_LOW); /* IRQ0 -> APIC IRQ2. */ /* Doesn't work on this board. */ /* 0: mean bus 0--->ISA */ /* 0: PIC 0 */ /* 2: APIC 2 */ /* 5 mean: 0101 --> Edge-triggered, Active high */ /* create all subtables for processors */ /* acpi_create_madt_lapic_nmis returns current, not size. */ current = acpi_create_madt_lapic_nmis(current, 5, 1); return current; } unsigned long acpi_fill_ssdt_generator(unsigned long current, const char *oem_table_id) { k8acpi_write_vars(); amd_model_fxx_generate_powernow(0, 0, 0); return (unsigned long) (acpigen_get_current()); } unsigned long write_acpi_tables(unsigned long start) { unsigned long current; acpi_rsdp_t *rsdp; acpi_srat_t *srat; acpi_rsdt_t *rsdt; acpi_hpet_t *hpet; acpi_madt_t *madt; acpi_fadt_t *fadt; acpi_facs_t *facs; acpi_slit_t *slit; acpi_header_t *ssdt; acpi_header_t *dsdt; /* Align ACPI tables to 16 byte. */ start = (start + 0x0f) & -0x10; current = start; printk(BIOS_INFO, "ACPI: Writing ACPI tables at %lx.\n", start); /* We need at least an RSDP and an RSDT Table */ rsdp = (acpi_rsdp_t *) current; current += sizeof(acpi_rsdp_t); current = ALIGN(current, 16); rsdt = (acpi_rsdt_t *) current; current += sizeof(acpi_rsdt_t); /* Clear all table memory. */ memset((void *) start, 0, current - start); acpi_write_rsdp(rsdp, rsdt, NULL); acpi_write_rsdt(rsdt); current = ALIGN(current, 64); facs = (acpi_facs_t *) current; printk(BIOS_DEBUG, "ACPI: * FACS %p\n", facs); current += sizeof(acpi_facs_t); acpi_create_facs(facs); /* DSDT */ current = ALIGN(current, 16); dsdt = (acpi_header_t *) current; printk(BIOS_DEBUG, "ACPI: * DSDT %p\n", dsdt); memcpy(dsdt, &AmlCode, sizeof(acpi_header_t)); current += dsdt->length; memcpy(dsdt, &AmlCode, dsdt->length); printk(BIOS_DEBUG, "ACPI: * DSDT @ %p Length %x\n",dsdt,dsdt->length); current = ALIGN(current, 16); fadt = (acpi_fadt_t *) current; printk(BIOS_DEBUG, "ACPI: * FACP (FADT) @ %p\n", fadt); current += sizeof(acpi_fadt_t); /* Add FADT now that we have facs and dsdt. */ acpi_create_fadt(fadt, facs, dsdt); acpi_add_table(rsdp, fadt); current = ALIGN(current, 16); hpet = (acpi_hpet_t *) current; printk(BIOS_DEBUG, "ACPI: * HPET @ %p\n", hpet); current += sizeof(acpi_hpet_t); acpi_create_hpet(hpet); acpi_add_table(rsdp, hpet); current = ALIGN(current, 16); madt = (acpi_madt_t *) current; printk(BIOS_DEBUG, "ACPI: * APIC/MADT @ %p\n", madt); acpi_create_madt(madt); current += madt->header.length; acpi_add_table(rsdp, madt); current = ALIGN(current, 16); srat = (acpi_srat_t *) current; printk(BIOS_DEBUG, "ACPI: * SRAT @ %p\n", srat); acpi_create_srat(srat); current += srat->header.length; acpi_add_table(rsdp, srat); /* SLIT */ current = ALIGN(current, 16); slit = (acpi_slit_t *) current; printk(BIOS_DEBUG, "ACPI: * SLIT @ %p\n", slit); acpi_create_slit(slit); current+=slit->header.length; acpi_add_table(rsdp,slit); /* SSDT */ current = ALIGN(current, 16); ssdt = (acpi_header_t *)current; printk(BIOS_DEBUG, "ACPI: * SSDT @ %p\n", ssdt); acpi_create_ssdt_generator(ssdt, ACPI_TABLE_CREATOR); current += ssdt->length; acpi_add_table(rsdp, ssdt); printk(BIOS_INFO, "ACPI: done %p.\n", (void *)current); return current; }
XVilka/coreboot
src/mainboard/tyan/s2895/acpi_tables.c
C
gpl-2.0
5,961
<!DOCTYPE html> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8" /> <title>纯CSS实现固定表头</title> <style> /* 基本样式{{ */ body { background: #FFF; color: #000; font: normal normal 12px Verdana, Geneva, Arial, Helvetica, sans-serif; margin: 10px; padding: 0 } table, td, a { color: #000; font: normal normal 12px Verdana, Geneva, Arial, Helvetica, sans-serif } h1 { font: normal normal 18px Verdana, Geneva, Arial, Helvetica, sans-serif; margin: 0 0 5px 0 } h2 { font: normal normal 16px Verdana, Geneva, Arial, Helvetica, sans-serif; margin: 0 0 5px 0 } h3 { font: normal normal 13px Verdana, Geneva, Arial, Helvetica, sans-serif; color: #008000; margin: 0 0 15px 0 } /* 基本样式}} */ /*定义可滚动区域宽、高样式,其中,增加滚动条的16px*/ div.tableContainer { clear: both; border: 1px solid #963; height: 285px; overflow: auto; width: 756px } /* 定义overflow为hidden */ html>body div.tableContainer { overflow: hidden; width: 756px } /* 定义表格宽度 */ div.tableContainer table { float: left; width: 740px } /* define width of table. Add 16px to width for scrollbar. */ /* All other non-IE browsers. */ html>body div.tableContainer table { width: 756px } thead.fixedHeader tr { position: relative } /*设置thead样式*/ html>body thead.fixedHeader tr { display: block } /*定义th样式*/ thead.fixedHeader th { background: #C96; border-left: 1px solid #EB8; border-right: 1px solid #B74; border-top: 1px solid #EB8; font-weight: normal; padding: 4px 3px; text-align: left } /*定义a元素样式*/ thead.fixedHeader a, thead.fixedHeader a:link, thead.fixedHeader a:visited { color: #FFF; display: block; text-decoration: none; width: 100% } /*a:hover样式*/ thead.fixedHeader a:hover { color: #FFF; display: block; text-decoration: underline; width: 100% } /*定义表格内容可滚动样式,tbody元素为块级元素*/ html>body tbody.scrollContent { display: block; height: 262px; overflow: auto; width: 100% } /*td元素样式*/ tbody.scrollContent td, tbody.scrollContent tr.normalRow td { background: #FFF; border-bottom: none; border-left: none; border-right: 1px solid #CCC; border-top: 1px solid #DDD; padding: 2px 3px 3px 4px } tbody.scrollContent tr.alternateRow td { background: #EEE; border-bottom: none; border-left: none; border-right: 1px solid #CCC; border-top: 1px solid #DDD; padding: 2px 3px 3px 4px } /*th样式*/ html>body thead.fixedHeader th { width: 200px } html>body thead.fixedHeader th + th { width: 240px } html>body thead.fixedHeader th + th + th { width: 316px } /*td元素样式*/ html>body tbody.scrollContent td { width: 200px } html>body tbody.scrollContent td + td { width: 240px } html>body tbody.scrollContent td + td + td { width: 300px } </style> </head> <body> <div id="tableContainer" class="tableContainer"> <table border="0" cellpadding="0" cellspacing="0" width="100%" class="scrollTable"> <thead class="fixedHeader"> <tr class="alternateRow"> <th><a href="#">固定表头 1</a></th> <th><a href="#">固定表头 2</a></th> <th><a href="#">固定表头 3</a></th> </tr> </thead> <tbody class="scrollContent"> <tr class="normalRow"> <td>固定表头的CSS表格 1</td> <td>固定表头的CSS表格 2</td> <td>固定表头的CSS表格 3</td> </tr> <tr class="alternateRow"> <td>固定表头的CSS表格 1</td> <td>固定表头的CSS表格 2</td> <td>固定表头的CSS表格 3</td> </tr> <tr class="normalRow"> <td>固定表头的CSS表格 1</td> <td>固定表头的CSS表格 2</td> <td>固定表头的CSS表格 3</td> </tr> <tr class="alternateRow"> <td>固定表头的CSS表格 1</td> <td>固定表头的CSS表格 2</td> <td>固定表头的CSS表格 3</td> </tr> <tr class="normalRow"> <td>固定表头的CSS表格 1</td> <td>固定表头的CSS表格 2</td> <td>固定表头的CSS表格 3</td> </tr> <tr class="alternateRow"> <td>固定表头的CSS表格 1</td> <td>固定表头的CSS表格 2</td> <td>固定表头的CSS表格 3</td> </tr> <tr class="normalRow"> <td>固定表头的CSS表格 1</td> <td>固定表头的CSS表格 2</td> <td>固定表头的CSS表格 3</td> </tr> <tr class="alternateRow"> <td>固定表头的CSS表格 1</td> <td>固定表头的CSS表格 2</td> <td>固定表头的CSS表格 3</td> </tr> <tr class="normalRow"> <td>固定表头的CSS表格 1</td> <td>固定表头的CSS表格 2</td> <td>固定表头的CSS表格 3</td> </tr> <tr class="alternateRow"> <td>固定表头的CSS表格 1</td> <td>固定表头的CSS表格 2</td> <td>固定表头的CSS表格 3</td> </tr> <tr class="normalRow"> <td>固定表头的CSS表格 1</td> <td>固定表头的CSS表格 2</td> <td>固定表头的CSS表格 3</td> </tr> <tr class="alternateRow"> <td>固定表头的CSS表格 1</td> <td>固定表头的CSS表格 2</td> <td>固定表头的CSS表格 3</td> </tr> <tr class="normalRow"> <td>固定表头的CSS表格 1</td> <td>固定表头的CSS表格 2</td> <td>固定表头的CSS表格 3</td> </tr> <tr class="alternateRow"> <td>固定表头的CSS表格 1</td> <td>固定表头的CSS表格 2</td> <td>固定表头的CSS表格 3</td> </tr> <tr class="normalRow"> <td>固定表头的CSS表格 1</td> <td>固定表头的CSS表格 2</td> <td>固定表头的CSS表格 3</td> </tr> <tr class="alternateRow"> <td>固定表头的CSS表格 1</td> <td>固定表头的CSS表格 2</td> <td>固定表头的CSS表格 3</td> </tr> <tr class="normalRow"> <td>固定表头的CSS表格 1</td> <td>固定表头的CSS表格 2</td> <td>固定表头的CSS表格 3</td> </tr> <tr class="alternateRow"> <td>固定表头的CSS表格 1</td> <td>固定表头的CSS表格 2</td> <td>固定表头的CSS表格 3</td> </tr> <tr class="normalRow"> <td>固定表头的CSS表格 1</td> <td>固定表头的CSS表格 2</td> <td>固定表头的CSS表格 3</td> </tr> <tr class="alternateRow"> <td>固定表头的CSS表格 1</td> <td>固定表头的CSS表格 2</td> <td>固定表头的CSS表格 3</td> </tr> <tr class="normalRow"> <td>固定表头的CSS表格 1</td> <td>固定表头的CSS表格 2</td> <td>固定表头的CSS表格 3</td> </tr> <tr class="alternateRow"> <td>固定表头的CSS表格 1</td> <td>固定表头的CSS表格 2</td> <td>固定表头的CSS表格 3</td> </tr> <tr class="normalRow"> <td>固定表头的CSS表格 1</td> <td>固定表头的CSS表格 2</td> <td>固定表头的CSS表格 3</td> </tr> <tr class="alternateRow"> <td>固定表头的CSS表格 1</td> <td>固定表头的CSS表格 2</td> <td>固定表头的CSS表格 3</td> </tr> <tr class="normalRow"> <td>固定表头的CSS表格 1</td> <td>固定表头的CSS表格 2</td> <td>固定表头的CSS表格 3</td> </tr> <tr class="alternateRow"> <td>固定表头的CSS表格 1</td> <td>固定表头的CSS表格 2</td> <td>固定表头的CSS表格 3</td> </tr> </tbody> </table> </div> </body> </html>
letshare/code
css/6/6.19/纯CSS实现固定表头.html
HTML
gpl-2.0
7,710
#!/usr/bin/env python # # This script makes a checkout of cartoweb cvs, and launches the unit tests. # If no update of cvs was done, it does not run the tests. # # In case of a test failure, an email is sent to a specified address. # Configuration: change to match your environment DISABLING_FILE = "/tmp/auto_test_disabled" CVSROOT=':pserver:username@example.com:/var/lib/cvs/projects/cw3' EMAIL = "your.email@example.com" PHP_PATH = "php" BASE_URL="'http://example.com/auto_test/'" SMTP_SERVER = "example.com" # You shouldn't need to change these CVS_DIR='cvs' LOG_FILE='log.txt' import commands, sys, os, os.path, datetime, smtplib, email.Utils, random import os.path as path class TestsException(Exception): pass def prepare(): print "prepare" if not path.isdir(CVS_DIR): os.makedirs(CVS_DIR) print "Enter your cvs password when prompted ..." ret = commands.getoutput("cd %s; cvs -d %s login" % (CVS_DIR, CVSROOT)) ret = commands.getoutput("cd %s; cvs -d %s co cartoweb3" % (CVS_DIR, CVSROOT)) print ret def is_uptodate(): out = commands.getoutput('cd %s/cartoweb3;cvs update -dP' % CVS_DIR) for l in out.split("\n"): #if l.startswith("U") or l.startswith("P"): if not l.startswith("cvs update"): print "FAILED line:", l return False #print "LINE", l #print "Not updated" return True def run(cmd): exitvalue = os.system(cmd) if exitvalue != 0: print >>log, "Failed to execute %s, exitting" % cmd raise TestsException('Failed to execute command: %s' % cmd) def fetch_cartoweb(): cmds = """[ -d cartoweb3 ] && rm -rf cartoweb3 || : cp -r cvs/cartoweb3 . (cd cartoweb3; %s cw3setup.php --install --base-url %s --debug) || true (cd cartoweb3; %s cw3setup.php --fetch-demo) || true""" % (PHP_PATH, BASE_URL, PHP_PATH) for cmd in cmds.split("\n"): run(cmd) def rd(s, sep="."): i = random.randint(0, len(s)) return s[0:i] + sep + s[i:] def send_mail(kind, output): print >>log, "Test failure, sending mail to %s" % EMAIL server = smtplib.SMTP(SMTP_SERVER) FROM_ADDRESS="noreply@camptocamp.com" subject = rd("auto_test_report", " ") body = ("This is an error report from the automatic cartoweb testing. \n" + \ " The error type is: '%s' \n\n" + \ " The error message is: \n\n%s") % (kind, output) msg = ("Date: %s\r\nFrom: %s\r\nTo: %s\r\nSubject: %s\r\n\r\n%s" % (email.Utils.formatdate(), FROM_ADDRESS, EMAIL, subject, body)) server.sendmail(FROM_ADDRESS, EMAIL, msg) def run_tests(): print >>log, "Running tests" (status, output) = commands.getstatusoutput("cd cartoweb3/tests/; %s phpunit.php AllTests" % PHP_PATH) # truncate to 50k maximum MAX_SIZE = 25 * 1024 output = output[:MAX_SIZE] if len(output) == MAX_SIZE: output += " <TRUNCATED> " print >>log, "Test output", output print >>log, "Test status", status # for debugging: #status = 1 if status != 0 or "Failure" in output: send_mail('Unit test failure', output) def main(): print >>log, "\n" + "=" * 80 print >>log, "Script launched at ", datetime.datetime.now().__str__() log.flush() if "-prepare" in sys.argv: prepare() sys.exit() if os.path.exists(DISABLING_FILE): print >>log, "Disabling file (%s) is there, skipping tests" % DISABLING_FILE sys.exit() SKIP_UPDATE_CHECK=False if "-skip-update-check" in sys.argv or SKIP_UPDATE_CHECK: uptodate = False else: uptodate = is_uptodate() print "Uptodate: ", uptodate if uptodate: print >>log, "CVS up to date, skipping tests" sys.exit() fetch_cartoweb() run_tests() print >>log, "End of tests\n" + "=" * 80 if __name__ == '__main__': os.chdir(path.abspath(path.dirname(__file__))) if "-debug" in sys.argv: log = sys.stderr else: log = open(LOG_FILE, 'a') try: main() except TestsException, e: print "TestsException: ", e send_mail('Auto test setup failure', e)
camptocamp/cartoweb3
scripts/run_auto_test.py
Python
gpl-2.0
4,194
<?php /** * Template Name: Posty użytkownika * */ get_header(); ?> <div class="row"> <div class="col-md-9 col-sm-6 col-xs-12"> <?php $query = new WP_Query(array( 'author' => $_GET['id'] )); ?> <?php if ($query->have_posts()): ?> <div class="container-fluid"> <?php while ($query->have_posts()) : $query->the_post(); ?> <div class="post"> <div class="row header "> <div class="title col-md-6"> <a href="<?php the_permalink(); ?>"> <?php the_title(); ?> </a> </div> <div class="col-md-6 text-right small"> Ocena: <?php $data = get_post_meta(get_the_ID(), 'rating'); echo $data[0]; ?> | <?php the_modified_date(); ?> <?php the_modified_time(); ?> </div> </div> </div> <?php endwhile; ?> </div> <?php endif; ?> </div> <div class="col-md-3 col-sm-6 col-xs-12"> <?php get_sidebar(); ?> </div> </div> <!--div.row--> <?php get_footer(); ?>
damian-kociuba/wordpressSimplePage
wp-content/themes/testtheme/page_posts.php
PHP
gpl-2.0
1,535
! Here we define everything related to the LaBo code. Should be done in separate modules. ! By the way, that's a lot of work and I'm not sure how pertinent it is. ! For now we're stuck to D3Q19 module system use precision_kinds use constants, only: x, y, z use mod_lbmodel, only: lbm implicit none ! ! The solvent ! ! ! Solvent population n (x,y,z,velocity) ! REAL(dp), ALLOCATABLE, DIMENSION(:,:,:,:) :: n ! time integer(i2b) :: time ! time in simu, from 0 to tmax integer(i2b) :: t_equil, tmom, tmax ! 0->t_equil; t_equil->tmom; t_mom->tmax ! equilibration integer(i2b) :: D_equil ! number of equilibration steps whithout constraints nor flux integer(i2b) :: D_iter ! supercell geometry related ! integer(i2b) :: wall integer(i0b), parameter, public :: fluid=0, liquid=0, solid=1 type type_dimensions real(dp), dimension(x:z) :: length integer(i2b), dimension(x:z) :: indiceMin integer(i2b), dimension(x:z) :: indiceMax end type type type_geometry integer(i2b) :: label type(type_dimensions), public :: dimensions end type type type_latticenode integer(kind(fluid)) :: nature ! solid liquid ! real(dp), dimension(x:z) :: normal ! vector normal to interface if interfacial site logical :: isInterfacial real(dp) :: solventDensity ! mass rho real(dp), dimension(x:z) :: solventFlux ! flux j end type type type_supercell integer(i2b), dimension(x:z) :: length, lengthMin, lengthMax ! type (type_latticenode), public, allocatable, dimension(:,:,:) :: node type(type_geometry), public :: geometry end type type (type_supercell), public :: supercell ! supercell%node(i,j,k)%nature supercell%node(i,j,k)%normal(x) supercell%length supercell%lengthmin:supercell%lengthmax type (type_latticenode), allocatable, public :: node(:,:,:) ! should replace supercell%node !!!!!!!!!!!!!!!!!!!!! DANGER !real(dp), allocatable, dimension(:,:,:,:) :: n ! population of position and velocities !!!!!!!!!!!!!!!!!!!!!!! ! real(dp), allocatable, dimension(:,:,:) :: rho ! rho(i,j,k) = sum_l n(i,j,k,l) ! real(dp), allocatable, dimension(:,:,:) :: jx, jy, jz ! jx(i,j,k) = sum_l c_x(l) * n(i,j,k,l) where c_x(l) = c(1,l) real(dp), allocatable, dimension(:,:,:) :: flux_site_plus, flux_site_minus real(dp) :: anormf0 ! electrostatic related real(dp) :: bjl ! Bjerum length real(dp) :: lambda_D ! debye length. <0 means salt free fluid real(dp) :: sigma ! sigma is the number of charges the user want to put in solid and surface. read from input file. real(dp) :: D_plus, D_minus ! diffusion coefficient of ions real(dp), allocatable, dimension(:,:,:) :: c_plus, c_minus ! concentrations real(dp), allocatable, dimension(:,:,:) :: phi ! internal potential (calculated by the sucessive overrelaxation methode) real(dp), allocatable, dimension(:,:,:) :: phi2 ! DONT KNOW WHAT IT IS FOR. IT IS USED IN ELEC_POT, CALLED DURING TRACER MOMENT PROPAGATION, BUT COMPLETELY USELESS real(dp), allocatable, dimension(:,:,:) :: phi_tot ! total electrostatic potential = phi + phi external real(dp), allocatable, dimension(:,:,:) :: phi_old, c_plus_old, c_minus_old ! backups of phi, c_plus and c_minus at previous steps for checking convergence character(len=3) :: charge_distrib real(dp), dimension(x:z) :: elec_slope, lncb_slope real(dp) :: el_curr_x, el_curr_y, el_curr_z real(dp) :: ion_curr_x, ion_curr_y, ion_curr_z real(dp) :: rho_ch ! charge density? ! external force given by user real(dp), dimension(x:z) :: f_ext ! external force (constraints) applied to flux real(dp), allocatable, dimension(:,:,:,:) :: solute_force ! (lx, ly, lz, 3) ! thermo real(dp), parameter :: kBT = 1.0_dp/3.0_dp ! boltzmann constant * temperature real(dp), parameter :: beta = 1.0_dp/kBT contains pure function pbc (i,direction) ! Apply periodic boundary conditions to node indices implicit none integer :: pbc integer, intent(in) :: i, direction integer :: imax imax = supercell%geometry%dimensions%indiceMax(direction) if (i==0) then pbc = imax else if (i==imax+1) then pbc = 1 else pbc = i end if end function pbc ! ! pure function pbc3 (i) ! Apply periodic boundary conditions to node indices ! implicit none ! integer :: pbc3(x:z) ! integer, intent(in) :: i(x:z) ! pbc3 = [ pbc(i(1),x) , pbc(i(2),y) , pbc(i(3),z) ] ! end function pbc3 ! end module system
maxlevesque/laboetie
src/module_system.f90
FORTRAN
gpl-2.0
4,656
/* SPDX-License-Identifier: LGPL-2.1-or-later */ #include <net/if_arp.h> #include "sd-id128.h" #include "arphrd-util.h" #include "id128-util.h" #include "memory-util.h" #include "networkd-address-generation.h" #include "networkd-link.h" #include "networkd-network.h" #include "string-util.h" #define DAD_CONFLICTS_IDGEN_RETRIES_RFC7217 3 /* https://www.iana.org/assignments/ipv6-interface-ids/ipv6-interface-ids.xml */ #define SUBNET_ROUTER_ANYCAST_ADDRESS ((const struct in6_addr) { .s6_addr = { 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00 } }) #define SUBNET_ROUTER_ANYCAST_PREFIXLEN 64 #define RESERVED_INTERFACE_IDENTIFIERS_ADDRESS ((const struct in6_addr) { .s6_addr = { 0x02, 0x00, 0x5E, 0xFF, 0xFE } }) #define RESERVED_INTERFACE_IDENTIFIERS_PREFIXLEN 40 #define RESERVED_SUBNET_ANYCAST_ADDRESSES ((const struct in6_addr) { .s6_addr = { 0xFD, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0x80 } }) #define RESERVED_SUBNET_ANYCAST_PREFIXLEN 57 #define DHCP_PD_APP_ID SD_ID128_MAKE(fb,b9,37,ca,4a,ed,4a,4d,b0,70,7f,aa,71,c0,c9,85) #define NDISC_APP_ID SD_ID128_MAKE(13,ac,81,a7,d5,3f,49,78,92,79,5d,0c,29,3a,bc,7e) #define RADV_APP_ID SD_ID128_MAKE(1f,1e,90,c8,5c,78,4f,dc,8e,61,2d,59,0d,53,c1,25) typedef enum AddressGenerationType { ADDRESS_GENERATION_EUI64, ADDRESS_GENERATION_STATIC, ADDRESS_GENERATION_PREFIXSTABLE, _ADDRESS_GENERATION_TYPE_MAX, _ADDRESS_GENERATION_TYPE_INVALID = -EINVAL, } AddressGenerationType; typedef struct IPv6Token { AddressGenerationType type; struct in6_addr address; sd_id128_t secret_key; } IPv6Token; static int generate_eui64_address(const Link *link, const struct in6_addr *prefix, struct in6_addr *ret) { assert(link); assert(prefix); assert(ret); memcpy(ret->s6_addr, prefix, 8); switch (link->iftype) { case ARPHRD_INFINIBAND: /* Use last 8 byte. See RFC4391 section 8 */ memcpy(&ret->s6_addr[8], &link->hw_addr.infiniband[INFINIBAND_ALEN - 8], 8); break; case ARPHRD_ETHER: /* see RFC4291 section 2.5.1 */ ret->s6_addr[8] = link->hw_addr.ether.ether_addr_octet[0]; ret->s6_addr[9] = link->hw_addr.ether.ether_addr_octet[1]; ret->s6_addr[10] = link->hw_addr.ether.ether_addr_octet[2]; ret->s6_addr[11] = 0xff; ret->s6_addr[12] = 0xfe; ret->s6_addr[13] = link->hw_addr.ether.ether_addr_octet[3]; ret->s6_addr[14] = link->hw_addr.ether.ether_addr_octet[4]; ret->s6_addr[15] = link->hw_addr.ether.ether_addr_octet[5]; break; default: return log_link_debug_errno(link, SYNTHETIC_ERRNO(EINVAL), "Token=eui64 is not supported for interface type %s, ignoring.", strna(arphrd_to_name(link->iftype))); } ret->s6_addr[8] ^= 1 << 1; return 0; } static bool stable_private_address_is_valid(const struct in6_addr *addr) { assert(addr); /* According to rfc4291, generated address should not be in the following ranges. */ if (in6_addr_prefix_covers(&SUBNET_ROUTER_ANYCAST_ADDRESS, SUBNET_ROUTER_ANYCAST_PREFIXLEN, addr)) return false; if (in6_addr_prefix_covers(&RESERVED_INTERFACE_IDENTIFIERS_ADDRESS, RESERVED_INTERFACE_IDENTIFIERS_PREFIXLEN, addr)) return false; if (in6_addr_prefix_covers(&RESERVED_SUBNET_ANYCAST_ADDRESSES, RESERVED_SUBNET_ANYCAST_PREFIXLEN, addr)) return false; return true; } static void generate_stable_private_address_one( Link *link, const sd_id128_t *secret_key, const struct in6_addr *prefix, uint8_t dad_counter, struct in6_addr *ret) { struct siphash state; uint64_t rid; assert(link); assert(secret_key); assert(prefix); assert(ret); /* According to RFC7217 section 5.1 * RID = F(Prefix, Net_Iface, Network_ID, DAD_Counter, secret_key) */ siphash24_init(&state, secret_key->bytes); siphash24_compress(prefix, 8, &state); siphash24_compress_string(link->ifname, &state); if (link->iftype == ARPHRD_INFINIBAND) /* Only last 8 bytes of IB MAC are stable */ siphash24_compress(&link->hw_addr.infiniband[INFINIBAND_ALEN - 8], 8, &state); else siphash24_compress(link->hw_addr.bytes, link->hw_addr.length, &state); siphash24_compress(&dad_counter, sizeof(uint8_t), &state); rid = htole64(siphash24_finalize(&state)); memcpy(ret->s6_addr, prefix->s6_addr, 8); memcpy(ret->s6_addr + 8, &rid, 8); } static int generate_stable_private_address( Link *link, const sd_id128_t *app_id, const sd_id128_t *secret_key, const struct in6_addr *prefix, struct in6_addr *ret) { sd_id128_t secret_machine_key; struct in6_addr addr; uint8_t i; int r; assert(link); assert(app_id); assert(secret_key); assert(prefix); assert(ret); if (sd_id128_is_null(*secret_key)) { r = sd_id128_get_machine_app_specific(*app_id, &secret_machine_key); if (r < 0) return log_link_debug_errno(link, r, "Failed to generate secret key for IPv6 stable private address: %m"); secret_key = &secret_machine_key; } /* While this loop uses dad_counter and a retry limit as specified in RFC 7217, the loop does * not actually attempt Duplicate Address Detection; the counter will be incremented only when * the address generation algorithm produces an invalid address, and the loop may exit with an * address which ends up being unusable due to duplication on the link. */ for (i = 0; i < DAD_CONFLICTS_IDGEN_RETRIES_RFC7217; i++) { generate_stable_private_address_one(link, secret_key, prefix, i, &addr); if (stable_private_address_is_valid(&addr)) break; } if (i >= DAD_CONFLICTS_IDGEN_RETRIES_RFC7217) /* propagate recognizable errors. */ return log_link_debug_errno(link, SYNTHETIC_ERRNO(ENOANO), "Failed to generate stable private address."); *ret = addr; return 0; } static int generate_addresses( Link *link, Set *tokens, const sd_id128_t *app_id, const struct in6_addr *prefix, uint8_t prefixlen, Set **ret) { _cleanup_set_free_ Set *addresses = NULL; struct in6_addr masked; IPv6Token *j; int r; assert(link); assert(app_id); assert(prefix); assert(prefixlen > 0 && prefixlen <= 64); assert(ret); masked = *prefix; in6_addr_mask(&masked, prefixlen); SET_FOREACH(j, tokens) { struct in6_addr addr, *copy; switch (j->type) { case ADDRESS_GENERATION_EUI64: if (generate_eui64_address(link, &masked, &addr) < 0) continue; break; case ADDRESS_GENERATION_STATIC: memcpy(addr.s6_addr, masked.s6_addr, 8); memcpy(addr.s6_addr + 8, j->address.s6_addr + 8, 8); break; case ADDRESS_GENERATION_PREFIXSTABLE: if (in6_addr_is_set(&j->address) && !in6_addr_equal(&j->address, &masked)) continue; if (generate_stable_private_address(link, app_id, &j->secret_key, &masked, &addr) < 0) continue; break; default: assert_not_reached(); } copy = newdup(struct in6_addr, &addr, 1); if (!copy) return -ENOMEM; r = set_ensure_consume(&addresses, &in6_addr_hash_ops_free, copy); if (r < 0) return r; } /* fall back to EUI-64 if no token is provided */ if (set_isempty(addresses)) { _cleanup_free_ struct in6_addr *addr = NULL; addr = new(struct in6_addr, 1); if (!addr) return -ENOMEM; if (IN_SET(link->iftype, ARPHRD_ETHER, ARPHRD_INFINIBAND)) r = generate_eui64_address(link, &masked, addr); else r = generate_stable_private_address(link, app_id, &SD_ID128_NULL, &masked, addr); if (r < 0) return r; r = set_ensure_consume(&addresses, &in6_addr_hash_ops_free, TAKE_PTR(addr)); if (r < 0) return r; } *ret = TAKE_PTR(addresses); return 0; } int dhcp_pd_generate_addresses(Link *link, const struct in6_addr *prefix, uint8_t prefixlen, Set **ret) { return generate_addresses(link, link->network->dhcp_pd_tokens, &DHCP_PD_APP_ID, prefix, prefixlen, ret); } int ndisc_generate_addresses(Link *link, const struct in6_addr *prefix, uint8_t prefixlen, Set **ret) { return generate_addresses(link, link->network->ndisc_tokens, &NDISC_APP_ID, prefix, prefixlen, ret); } int radv_generate_addresses(Link *link, Set *tokens, const struct in6_addr *prefix, uint8_t prefixlen, Set **ret) { return generate_addresses(link, tokens, &RADV_APP_ID, prefix, prefixlen, ret); } static void ipv6_token_hash_func(const IPv6Token *p, struct siphash *state) { siphash24_compress(&p->type, sizeof(p->type), state); siphash24_compress(&p->address, sizeof(p->address), state); id128_hash_func(&p->secret_key, state); } static int ipv6_token_compare_func(const IPv6Token *a, const IPv6Token *b) { int r; r = CMP(a->type, b->type); if (r != 0) return r; r = memcmp(&a->address, &b->address, sizeof(struct in6_addr)); if (r != 0) return r; return id128_compare_func(&a->secret_key, &b->secret_key); } DEFINE_PRIVATE_HASH_OPS_WITH_KEY_DESTRUCTOR( ipv6_token_hash_ops, IPv6Token, ipv6_token_hash_func, ipv6_token_compare_func, free); static int ipv6_token_add(Set **tokens, AddressGenerationType type, const struct in6_addr *addr, const sd_id128_t *secret_key) { IPv6Token *p; assert(tokens); assert(type >= 0 && type < _ADDRESS_GENERATION_TYPE_MAX); assert(addr); assert(secret_key); p = new(IPv6Token, 1); if (!p) return -ENOMEM; *p = (IPv6Token) { .type = type, .address = *addr, .secret_key = *secret_key, }; return set_ensure_consume(tokens, &ipv6_token_hash_ops, p); } int config_parse_address_generation_type( const char *unit, const char *filename, unsigned line, const char *section, unsigned section_line, const char *lvalue, int ltype, const char *rvalue, void *data, void *userdata) { _cleanup_free_ char *addr_alloc = NULL; sd_id128_t secret_key = SD_ID128_NULL; union in_addr_union buffer = {}; AddressGenerationType type; Set **tokens = data; const char *addr; int r; assert(filename); assert(lvalue); assert(rvalue); assert(data); if (isempty(rvalue)) { *tokens = set_free(*tokens); return 0; } if ((addr = startswith(rvalue, "prefixstable"))) { const char *comma; type = ADDRESS_GENERATION_PREFIXSTABLE; if (*addr == ':') { addr++; comma = strchr(addr, ','); if (comma) { addr_alloc = strndup(addr, comma - addr); if (!addr_alloc) return log_oom(); addr = addr_alloc; } } else if (*addr == ',') { comma = addr; addr = NULL; } else if (*addr == '\0') { comma = NULL; addr = NULL; } else { log_syntax(unit, LOG_WARNING, filename, line, 0, "Invalid IPv6 token mode in %s=, ignoring assignment: %s", lvalue, rvalue); return 0; } if (comma) { r = sd_id128_from_string(comma + 1, &secret_key); if (r < 0) { log_syntax(unit, LOG_WARNING, filename, line, r, "Failed to parse secret key in %s=, ignoring assignment: %s", lvalue, rvalue); return 0; } if (sd_id128_is_null(secret_key)) { log_syntax(unit, LOG_WARNING, filename, line, 0, "Secret key in %s= cannot be null, ignoring assignment: %s", lvalue, rvalue); return 0; } } } else if (streq(rvalue, "eui64")) { type = ADDRESS_GENERATION_EUI64; addr = NULL; } else { type = ADDRESS_GENERATION_STATIC; addr = startswith(rvalue, "static:"); if (!addr) addr = rvalue; } if (addr) { r = in_addr_from_string(AF_INET6, addr, &buffer); if (r < 0) { log_syntax(unit, LOG_WARNING, filename, line, r, "Failed to parse IP address in %s=, ignoring assignment: %s", lvalue, rvalue); return 0; } } switch (type) { case ADDRESS_GENERATION_EUI64: assert(in6_addr_is_null(&buffer.in6)); break; case ADDRESS_GENERATION_STATIC: /* Only last 64 bits are used. */ memzero(buffer.in6.s6_addr, 8); if (in6_addr_is_null(&buffer.in6)) { log_syntax(unit, LOG_WARNING, filename, line, 0, "IPv6 address in %s= cannot be the ANY address, ignoring assignment: %s", lvalue, rvalue); return 0; } break; case ADDRESS_GENERATION_PREFIXSTABLE: /* At most, the initial 64 bits are used. */ (void) in6_addr_mask(&buffer.in6, 64); break; default: assert_not_reached(); } r = ipv6_token_add(tokens, type, &buffer.in6, &secret_key); if (r < 0) return log_oom(); return 0; }
piotrdrag/systemd
src/network/networkd-address-generation.c
C
gpl-2.0
16,040
package net.demilich.metastone.game.spells.custom; import java.util.Map; import net.demilich.metastone.game.GameContext; import net.demilich.metastone.game.Player; import net.demilich.metastone.game.entities.Actor; import net.demilich.metastone.game.entities.Entity; import net.demilich.metastone.game.spells.Spell; import net.demilich.metastone.game.spells.desc.SpellArg; import net.demilich.metastone.game.spells.desc.SpellDesc; public class BetrayalSpell extends Spell { public static SpellDesc create() { Map<SpellArg, Object> arguments = SpellDesc.build(BetrayalSpell.class); return new SpellDesc(arguments); } @Override protected void onCast(GameContext context, Player player, SpellDesc desc, Entity source, Entity target) { Actor attacker = (Actor) target; for (Actor adjacentMinion : context.getAdjacentMinions(player, target.getReference())) { context.getLogic().damage(player, adjacentMinion, attacker.getAttack(), attacker); } } }
rafaelkalan/metastone
src/main/java/net/demilich/metastone/game/spells/custom/BetrayalSpell.java
Java
gpl-2.0
967
<?php /** * The template for displaying the footer. * * Contains the closing of the #content div and all content after * * @package storefront */ ?> </div><!-- .col-full --> </div><!-- #content --> <?php do_action( 'storefront_before_footer' ); ?> <footer id="colophon" class="site-footer" role="contentinfo"> <div class="col-full"> <?php /** * @hooked storefront_footer_widgets - 10 * @hooked storefront_credit - 20 */ do_action( 'storefront_footer' ); ?> </div><!-- .col-full --> </footer><!-- #colophon --> <?php do_action( 'storefront_after_footer' ); ?> </div><!-- #page --> <?php wp_footer(); ?> <script type="text/javascript" src="<?php bloginfo('url'); ?>/wp-content/themes/groworganiclocal/js/bootstrap.min.js"></script> </body> </html>
DogburnDesign/groworganiclocal
wp-content/themes/groworganiclocal/footer.php
PHP
gpl-2.0
793
#!/usr/bin/env php <?php /** * File containing the ezexec.php script. * * @copyright Copyright (C) 1999-2011 eZ Systems AS. All rights reserved. * @license http://www.gnu.org/licenses/gpl-2.0.txt GNU General Public License v2 * @version 2011.12 * @package kernel */ require 'autoload.php'; $cli = eZCLI::instance(); $script = eZScript::instance( array( 'description' => ( "eZ Publish Script Executor\n\n" . "Allows execution of simple PHP scripts which uses eZ Publish functionality,\n" . "when the script is called all necessary initialization is done\n" . "\n" . "ezexec.php myscript.php" ), 'use-session' => false, 'use-modules' => true, 'use-extensions' => true ) ); $script->startup(); $options = $script->getOptions( "", "[scriptfile]", array() ); $script->initialize(); if ( count( $options['arguments'] ) < 1 ) { $script->shutdown( 1, "Missing script file" ); } $scriptFile = $options['arguments'][0]; if ( !file_exists( $scriptFile ) ) $script->shutdown( 1, "Could execute the script '$scriptFile', file was not found" ); $retCode = include( $scriptFile ); if ( $retCode != 1 ) $script->setExitCode( 1 ); $script->shutdown(); ?>
ETSGlobal/ezpublish_built
bin/php/ezexec.php
PHP
gpl-2.0
1,568
/* File: WaveClient.h Program: KisMAC Author: Michael Ro§berg mick@binaervarianz.de Changes: Vitalii Parovishnyk(1012-2015) Description: KisMAC is a wireless stumbler for MacOS X. This file is part of KisMAC. Most parts of this file are based on aircrack by Christophe Devine. KisMAC 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; KisMAC 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 KisMAC; if not, write to the Free Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA */ @class WavePacket; @interface WaveClient : NSObject { NSString *_ID, *_vendor; NSString * _IPAddress; NSDate *_date; NSUInteger _curSignal; CGFloat _receivedBytes; CGFloat _sentBytes; BOOL _changed; //WPA NSData *_aNonce, *_sNonce, *_MIC, *_packet; NSUInteger _wpaKeyCipher; //LEAP NSData *_leapChallenge, *_leapResponse; NSString *_leapUsername; } - (id)initWithDataDictionary:(NSDictionary*)dict; - (NSDictionary*)dataDictionary; - (void)parseFrameAsIncoming:(WavePacket*)w; - (void)parseFrameAsOutgoing:(WavePacket*)w; - (NSString *)received; - (NSString *)sent; - (NSString *)vendor; - (NSString *)date; - (NSString *)getIPAddress; - (CGFloat)receivedBytes; - (CGFloat)sentBytes; - (NSUInteger)curSignal; - (NSDate *)rawDate; //WPA stuff - (NSData *)sNonce; - (NSData *)aNonce; - (NSData *)eapolMIC; - (NSData *)eapolPacket; - (NSData *)rawID; - (BOOL) eapolDataAvailable; - (NSUInteger) wpaKeyCipher; //LEAP stuff - (NSData *)leapChallenge; - (NSData *)leapResponse; - (NSString *)leapUsername; - (BOOL) leapDataAvailable; - (NSString *)ID; - (BOOL)changed; - (void)wasChanged; @end
IGRSoft/KisMac2
Sources/Core/WaveClient.h
C
gpl-2.0
2,096
/** * Title: StanfordMaxEnt<p> * Description: A Maximum Entropy Toolkit<p> * Copyright: Copyright (c) Kristina Toutanova<p> * Company: Stanford University<p> * @author Kristina Toutanova * @version 1.0 */ package com.infoecos.util.io; import java.io.*; //: com:bruceeckel:tools:OutFile.java // Shorthand class for opening an output file // for data storage. public class OutDataStreamFile extends DataOutputStream { public OutDataStreamFile(String filename) throws IOException { this(new File(filename)); } public OutDataStreamFile(File file) throws IOException { super(new BufferedOutputStream(new FileOutputStream(file))); } } ///:~
javajoker/infoecos
src/com/infoecos/util/io/OutDataStreamFile.java
Java
gpl-2.0
680
#!/usr/bin/env python3 """ # TOP2049 Open Source programming suite # # Commandline utility # # Copyright (c) 2014 Pavel Stemberk <stemberk@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 Street, Fifth Floor, Boston, MA 02110-1301 USA. """ import re import sys import os def substitute(input, oldSocket, newSocket): input = re.sub('(^\s*packages).*', lambda m:'{} = (("DIP10", ""), ),'.format(m.group(1)), input) input = re.sub('(^\s*chipPackage).*', lambda m:'{} = "DIP10",'.format(m.group(1)), input) input = re.sub('(^\s*chipPinVCC).*', lambda m:'{} = 9,'.format(m.group(1)), input) input = re.sub('(^\s*chipPinsVPP).*', lambda m:'{} = 10,'.format(m.group(1)), input) input = re.sub('(^\s*chipPinGND).*', lambda m:'{} = 8,'.format(m.group(1)), input) input = re.sub('(^\s*runtimeID).*', lambda m:'{} = (0xDF05, 0x01),'.format(m.group(1)), input) input = re.sub('(^\s*description).+"(.*)".*', lambda m:'{} = "{} - ICD",'.format(m.group(1), m.group(2)), input) input = re.sub('(^\s*bitfile).*', lambda m:'{} = "microchip16sip6",'.format(m.group(1)), input) input = re.sub("{}".format(oldSocket), "{}".format(newSocket), input) input = re.sub("{}".format(oldSocket.upper()), "{}".format(newSocket.upper()), input) return input def makeSip(): inputFileName = '__init__.py' fin = open(inputFileName) dMCU = {} for line in fin: matchObj = re.match('.*(pic[0-9]+l?f\w+)(sip[0-9a]+).*', line) if matchObj: continue matchObj = re.match('.*(pic[0-9]+l?f\w+)(dip[0-9a]+).*', line) if not matchObj: print("{} did not match".format(line)) continue # print('matched {} - {}'.format(matchObj.group(1), matchObj.group(2))) dMCU.setdefault(matchObj.group(1), matchObj.group(2)) fin.close() for item in dMCU.items(): fin = open("{}{}.py".format(item[0], item[1])) fout = open("{}sip6.py".format(item[0]), 'w') fout.write("#\n") fout.write("# THIS FILE WAS AUTOGENERATED BY makeSip6.py\n") fout.write("# Do not edit this file manually. All changes will be lost.\n") fout.write("#\n\n") for line in fin: fout.write(substitute(line, "{}".format(item[1]), "sip6")) fout.close() fin.close() def main(argv): makeSip() if __name__ == "__main__": exit(main(sys.argv))
mbuesch/toprammer
libtoprammer/chips/microchip16/makeSip6.py
Python
gpl-2.0
2,873
/* * gedit-spell-plugin.c * * Copyright (C) 2002-2005 Paolo Maggi * Copyright (C) 2015-2016 Sébastien Wilmet * * 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, 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 "gedit-spell-plugin.h" #include <glib/gi18n.h> #include <gedit/gedit-debug.h> #include <gedit/gedit-app.h> #include <gedit/gedit-window.h> #include <gedit/gedit-window-activatable.h> #include <gspell/gspell.h> #include <libpeas-gtk/peas-gtk-configurable.h> #include "gedit-spell-app-activatable.h" #ifdef G_OS_WIN32 #define GEDIT_METADATA_ATTRIBUTE_SPELL_LANGUAGE "spell-language" #define GEDIT_METADATA_ATTRIBUTE_SPELL_ENABLED "spell-enabled" #else #define GEDIT_METADATA_ATTRIBUTE_SPELL_LANGUAGE "metadata::gedit-spell-language" #define GEDIT_METADATA_ATTRIBUTE_SPELL_ENABLED "metadata::gedit-spell-enabled" #endif #define SPELL_ENABLED_STR "1" #define SPELL_BASE_SETTINGS "org.gnome.gedit.plugins.spell" #define SETTINGS_KEY_HIGHLIGHT_MISSPELLED "highlight-misspelled" static void gedit_window_activatable_iface_init (GeditWindowActivatableInterface *iface); static void peas_gtk_configurable_iface_init (PeasGtkConfigurableInterface *iface); struct _GeditSpellPluginPrivate { GeditWindow *window; GSettings *settings; }; enum { PROP_0, PROP_WINDOW }; typedef struct _SpellConfigureWidget SpellConfigureWidget; struct _SpellConfigureWidget { GtkWidget *content; GtkWidget *highlight_button; GSettings *settings; }; G_DEFINE_DYNAMIC_TYPE_EXTENDED (GeditSpellPlugin, gedit_spell_plugin, PEAS_TYPE_EXTENSION_BASE, 0, G_IMPLEMENT_INTERFACE_DYNAMIC (GEDIT_TYPE_WINDOW_ACTIVATABLE, gedit_window_activatable_iface_init) G_IMPLEMENT_INTERFACE_DYNAMIC (PEAS_GTK_TYPE_CONFIGURABLE, peas_gtk_configurable_iface_init) G_ADD_PRIVATE_DYNAMIC (GeditSpellPlugin)) static void gedit_spell_plugin_set_property (GObject *object, guint prop_id, const GValue *value, GParamSpec *pspec) { GeditSpellPlugin *plugin = GEDIT_SPELL_PLUGIN (object); switch (prop_id) { case PROP_WINDOW: plugin->priv->window = GEDIT_WINDOW (g_value_dup_object (value)); break; default: G_OBJECT_WARN_INVALID_PROPERTY_ID (object, prop_id, pspec); break; } } static void gedit_spell_plugin_get_property (GObject *object, guint prop_id, GValue *value, GParamSpec *pspec) { GeditSpellPlugin *plugin = GEDIT_SPELL_PLUGIN (object); switch (prop_id) { case PROP_WINDOW: g_value_set_object (value, plugin->priv->window); break; default: G_OBJECT_WARN_INVALID_PROPERTY_ID (object, prop_id, pspec); break; } } static void gedit_spell_plugin_dispose (GObject *object) { GeditSpellPlugin *plugin = GEDIT_SPELL_PLUGIN (object); gedit_debug_message (DEBUG_PLUGINS, "GeditSpellPlugin disposing"); g_clear_object (&plugin->priv->window); g_clear_object (&plugin->priv->settings); G_OBJECT_CLASS (gedit_spell_plugin_parent_class)->dispose (object); } static void gedit_spell_plugin_class_init (GeditSpellPluginClass *klass) { GObjectClass *object_class = G_OBJECT_CLASS (klass); object_class->set_property = gedit_spell_plugin_set_property; object_class->get_property = gedit_spell_plugin_get_property; object_class->dispose = gedit_spell_plugin_dispose; g_object_class_override_property (object_class, PROP_WINDOW, "window"); } static void gedit_spell_plugin_class_finalize (GeditSpellPluginClass *klass) { } static void gedit_spell_plugin_init (GeditSpellPlugin *plugin) { gedit_debug_message (DEBUG_PLUGINS, "GeditSpellPlugin initializing"); plugin->priv = gedit_spell_plugin_get_instance_private (plugin); plugin->priv->settings = g_settings_new (SPELL_BASE_SETTINGS); } static GspellChecker * get_spell_checker (GeditDocument *doc) { GspellTextBuffer *gspell_buffer; gspell_buffer = gspell_text_buffer_get_from_gtk_text_buffer (GTK_TEXT_BUFFER (doc)); return gspell_text_buffer_get_spell_checker (gspell_buffer); } static const GspellLanguage * get_language_from_metadata (GeditDocument *doc) { const GspellLanguage *lang = NULL; gchar *language_code = NULL; language_code = gedit_document_get_metadata (doc, GEDIT_METADATA_ATTRIBUTE_SPELL_LANGUAGE); if (language_code != NULL) { lang = gspell_language_lookup (language_code); g_free (language_code); } return lang; } static void check_spell_cb (GSimpleAction *action, GVariant *parameter, gpointer data) { GeditSpellPlugin *plugin = GEDIT_SPELL_PLUGIN (data); GeditSpellPluginPrivate *priv; GeditView *view; GspellNavigator *navigator; GtkWidget *dialog; gedit_debug (DEBUG_PLUGINS); priv = plugin->priv; view = gedit_window_get_active_view (priv->window); g_return_if_fail (view != NULL); navigator = gspell_navigator_text_view_new (GTK_TEXT_VIEW (view)); dialog = gspell_checker_dialog_new (GTK_WINDOW (priv->window), navigator); gtk_widget_show (dialog); } static void language_dialog_response_cb (GtkDialog *dialog, gint response_id, gpointer user_data) { if (response_id == GTK_RESPONSE_HELP) { gedit_app_show_help (GEDIT_APP (g_application_get_default ()), GTK_WINDOW (dialog), NULL, "gedit-spellcheck"); return; } gtk_widget_destroy (GTK_WIDGET (dialog)); } static void set_language_cb (GSimpleAction *action, GVariant *parameter, gpointer data) { GeditSpellPlugin *plugin = GEDIT_SPELL_PLUGIN (data); GeditSpellPluginPrivate *priv; GeditDocument *doc; GspellChecker *checker; const GspellLanguage *lang; GtkWidget *dialog; GtkWindowGroup *window_group; gedit_debug (DEBUG_PLUGINS); priv = plugin->priv; doc = gedit_window_get_active_document (priv->window); g_return_if_fail (doc != NULL); checker = get_spell_checker (doc); g_return_if_fail (checker != NULL); lang = gspell_checker_get_language (checker); dialog = gspell_language_chooser_dialog_new (GTK_WINDOW (priv->window), lang, GTK_DIALOG_MODAL | GTK_DIALOG_DESTROY_WITH_PARENT); g_object_bind_property (dialog, "language", checker, "language", G_BINDING_DEFAULT); window_group = gedit_window_get_group (priv->window); gtk_window_group_add_window (window_group, GTK_WINDOW (dialog)); gtk_dialog_add_button (GTK_DIALOG (dialog), _("_Help"), GTK_RESPONSE_HELP); g_signal_connect (dialog, "response", G_CALLBACK (language_dialog_response_cb), NULL); gtk_widget_show (dialog); } static void inline_checker_activate_cb (GSimpleAction *action, GVariant *parameter, gpointer data) { GeditSpellPlugin *plugin = GEDIT_SPELL_PLUGIN (data); GeditSpellPluginPrivate *priv = plugin->priv; GVariant *state; gboolean active; GeditView *view; gedit_debug (DEBUG_PLUGINS); state = g_action_get_state (G_ACTION (action)); g_return_if_fail (state != NULL); active = g_variant_get_boolean (state); g_variant_unref (state); /* We must toggle ourself the value. */ active = !active; g_action_change_state (G_ACTION (action), g_variant_new_boolean (active)); view = gedit_window_get_active_view (priv->window); if (view != NULL) { GeditDocument *doc; doc = GEDIT_DOCUMENT (gtk_text_view_get_buffer (GTK_TEXT_VIEW (view))); /* Set metadata in the "activate" handler, not in "change-state" * because "change-state" is called every time the state * changes, not specifically when the user has changed the state * herself. For example "change-state" is called to initialize * the sate to the default value specified in the GActionEntry. */ gedit_document_set_metadata (doc, GEDIT_METADATA_ATTRIBUTE_SPELL_ENABLED, active ? SPELL_ENABLED_STR : NULL, NULL); } } static void inline_checker_change_state_cb (GSimpleAction *action, GVariant *state, gpointer data) { GeditSpellPlugin *plugin = GEDIT_SPELL_PLUGIN (data); GeditSpellPluginPrivate *priv = plugin->priv; GeditView *view; gboolean active; gedit_debug (DEBUG_PLUGINS); active = g_variant_get_boolean (state); gedit_debug_message (DEBUG_PLUGINS, active ? "Inline Checker activated" : "Inline Checker deactivated"); view = gedit_window_get_active_view (priv->window); if (view != NULL) { GspellTextView *gspell_view; gspell_view = gspell_text_view_get_from_gtk_text_view (GTK_TEXT_VIEW (view)); gspell_text_view_set_inline_spell_checking (gspell_view, active); g_simple_action_set_state (action, g_variant_new_boolean (active)); } } static void update_ui (GeditSpellPlugin *plugin) { GeditSpellPluginPrivate *priv; GeditTab *tab; GeditView *view = NULL; gboolean editable_view; GAction *check_spell_action; GAction *config_spell_action; GAction *inline_checker_action; gedit_debug (DEBUG_PLUGINS); priv = plugin->priv; tab = gedit_window_get_active_tab (priv->window); if (tab != NULL) { view = gedit_tab_get_view (tab); } editable_view = (view != NULL) && gtk_text_view_get_editable (GTK_TEXT_VIEW (view)); check_spell_action = g_action_map_lookup_action (G_ACTION_MAP (priv->window), "check-spell"); g_simple_action_set_enabled (G_SIMPLE_ACTION (check_spell_action), editable_view); config_spell_action = g_action_map_lookup_action (G_ACTION_MAP (priv->window), "config-spell"); g_simple_action_set_enabled (G_SIMPLE_ACTION (config_spell_action), editable_view); inline_checker_action = g_action_map_lookup_action (G_ACTION_MAP (priv->window), "inline-spell-checker"); g_simple_action_set_enabled (G_SIMPLE_ACTION (inline_checker_action), editable_view); /* Update only on normal state to avoid garbage changes during e.g. file * loading. */ if (tab != NULL && gedit_tab_get_state (tab) == GEDIT_TAB_STATE_NORMAL) { GspellTextView *gspell_view; gboolean inline_checking_enabled; gspell_view = gspell_text_view_get_from_gtk_text_view (GTK_TEXT_VIEW (view)); inline_checking_enabled = gspell_text_view_get_inline_spell_checking (gspell_view); g_action_change_state (inline_checker_action, g_variant_new_boolean (inline_checking_enabled)); } } static void setup_inline_checker_from_metadata (GeditSpellPlugin *plugin, GeditView *view) { GeditDocument *doc; gboolean enabled; gchar *enabled_str; GspellTextView *gspell_view; GeditView *active_view; doc = GEDIT_DOCUMENT (gtk_text_view_get_buffer (GTK_TEXT_VIEW (view))); enabled = g_settings_get_boolean(plugin->priv->settings, SETTINGS_KEY_HIGHLIGHT_MISSPELLED); enabled_str = gedit_document_get_metadata (doc, GEDIT_METADATA_ATTRIBUTE_SPELL_ENABLED); if (enabled_str != NULL) { enabled = g_str_equal (enabled_str, SPELL_ENABLED_STR); g_free (enabled_str); } gspell_view = gspell_text_view_get_from_gtk_text_view (GTK_TEXT_VIEW (view)); gspell_text_view_set_inline_spell_checking (gspell_view, enabled); /* In case that the view is the active one we mark the spell action */ active_view = gedit_window_get_active_view (plugin->priv->window); if (active_view == view) { GAction *action; action = g_action_map_lookup_action (G_ACTION_MAP (plugin->priv->window), "inline-spell-checker"); g_action_change_state (action, g_variant_new_boolean (enabled)); } } static void language_notify_cb (GspellChecker *checker, GParamSpec *pspec, GeditDocument *doc) { const GspellLanguage *lang; const gchar *language_code; g_return_if_fail (GEDIT_IS_DOCUMENT (doc)); lang = gspell_checker_get_language (checker); g_return_if_fail (lang != NULL); language_code = gspell_language_get_code (lang); g_return_if_fail (language_code != NULL); gedit_document_set_metadata (doc, GEDIT_METADATA_ATTRIBUTE_SPELL_LANGUAGE, language_code, NULL); } static void on_document_loaded (GeditDocument *doc, GeditSpellPlugin *plugin) { GspellChecker *checker; GeditTab *tab; GeditView *view; checker = get_spell_checker (doc); if (checker != NULL) { const GspellLanguage *lang; lang = get_language_from_metadata (doc); if (lang != NULL) { g_signal_handlers_block_by_func (checker, language_notify_cb, doc); gspell_checker_set_language (checker, lang); g_signal_handlers_unblock_by_func (checker, language_notify_cb, doc); } } tab = gedit_tab_get_from_document (doc); view = gedit_tab_get_view (tab); setup_inline_checker_from_metadata (plugin, view); } static void on_document_saved (GeditDocument *doc, gpointer user_data) { GeditTab *tab; GeditView *view; GspellChecker *checker; const gchar *language_code = NULL; GspellTextView *gspell_view; gboolean inline_checking_enabled; /* Make sure to save the metadata here too */ checker = get_spell_checker (doc); if (checker != NULL) { const GspellLanguage *lang; lang = gspell_checker_get_language (checker); if (lang != NULL) { language_code = gspell_language_get_code (lang); } } tab = gedit_tab_get_from_document (doc); view = gedit_tab_get_view (tab); gspell_view = gspell_text_view_get_from_gtk_text_view (GTK_TEXT_VIEW (view)); inline_checking_enabled = gspell_text_view_get_inline_spell_checking (gspell_view); gedit_document_set_metadata (doc, GEDIT_METADATA_ATTRIBUTE_SPELL_ENABLED, inline_checking_enabled ? SPELL_ENABLED_STR : NULL, GEDIT_METADATA_ATTRIBUTE_SPELL_LANGUAGE, language_code, NULL); } static void activate_spell_checking_in_view (GeditSpellPlugin *plugin, GeditView *view) { GeditDocument *doc; doc = GEDIT_DOCUMENT (gtk_text_view_get_buffer (GTK_TEXT_VIEW (view))); /* It is possible that a GspellChecker has already been set, for example * if a GeditTab has moved to another window. */ if (get_spell_checker (doc) == NULL) { const GspellLanguage *lang; GspellChecker *checker; GspellTextBuffer *gspell_buffer; lang = get_language_from_metadata (doc); checker = gspell_checker_new (lang); g_signal_connect_object (checker, "notify::language", G_CALLBACK (language_notify_cb), doc, 0); gspell_buffer = gspell_text_buffer_get_from_gtk_text_buffer (GTK_TEXT_BUFFER (doc)); gspell_text_buffer_set_spell_checker (gspell_buffer, checker); g_object_unref (checker); setup_inline_checker_from_metadata (plugin, view); } g_signal_connect_object (doc, "loaded", G_CALLBACK (on_document_loaded), plugin, 0); g_signal_connect_object (doc, "saved", G_CALLBACK (on_document_saved), plugin, 0); } static void disconnect_view (GeditSpellPlugin *plugin, GeditView *view) { GtkTextBuffer *buffer; buffer = gtk_text_view_get_buffer (GTK_TEXT_VIEW (view)); /* It should still be the same buffer as the one where the signal * handlers were connected. If not, we assume that the old buffer is * finalized. And it is anyway safe to call * g_signal_handlers_disconnect_by_func() if no signal handlers are * found. */ g_signal_handlers_disconnect_by_func (buffer, on_document_loaded, plugin); g_signal_handlers_disconnect_by_func (buffer, on_document_saved, plugin); } static void deactivate_spell_checking_in_view (GeditSpellPlugin *plugin, GeditView *view) { GtkTextBuffer *gtk_buffer; GspellTextBuffer *gspell_buffer; GspellTextView *gspell_view; disconnect_view (plugin, view); gtk_buffer = gtk_text_view_get_buffer (GTK_TEXT_VIEW (view)); gspell_buffer = gspell_text_buffer_get_from_gtk_text_buffer (gtk_buffer); gspell_text_buffer_set_spell_checker (gspell_buffer, NULL); gspell_view = gspell_text_view_get_from_gtk_text_view (GTK_TEXT_VIEW (view)); gspell_text_view_set_inline_spell_checking (gspell_view, FALSE); } static void tab_added_cb (GeditWindow *window, GeditTab *tab, GeditSpellPlugin *plugin) { activate_spell_checking_in_view (plugin, gedit_tab_get_view (tab)); } static void tab_removed_cb (GeditWindow *window, GeditTab *tab, GeditSpellPlugin *plugin) { /* Don't deactivate completely the spell checking in @tab, since the tab * can be moved to another window and we don't want to loose the spell * checking settings (they are not saved in metadata for unsaved * documents). */ disconnect_view (plugin, gedit_tab_get_view (tab)); } static void gedit_spell_plugin_activate (GeditWindowActivatable *activatable) { GeditSpellPlugin *plugin; GeditSpellPluginPrivate *priv; GList *views; GList *l; const GActionEntry action_entries[] = { { "check-spell", check_spell_cb }, { "config-spell", set_language_cb }, { "inline-spell-checker", inline_checker_activate_cb, NULL, "false", inline_checker_change_state_cb } }; gedit_debug (DEBUG_PLUGINS); plugin = GEDIT_SPELL_PLUGIN (activatable); priv = plugin->priv; g_action_map_add_action_entries (G_ACTION_MAP (priv->window), action_entries, G_N_ELEMENTS (action_entries), activatable); update_ui (plugin); views = gedit_window_get_views (priv->window); for (l = views; l != NULL; l = l->next) { activate_spell_checking_in_view (plugin, GEDIT_VIEW (l->data)); } g_signal_connect (priv->window, "tab-added", G_CALLBACK (tab_added_cb), activatable); g_signal_connect (priv->window, "tab-removed", G_CALLBACK (tab_removed_cb), activatable); } static void gedit_spell_plugin_deactivate (GeditWindowActivatable *activatable) { GeditSpellPlugin *plugin; GeditSpellPluginPrivate *priv; GList *views; GList *l; gedit_debug (DEBUG_PLUGINS); plugin = GEDIT_SPELL_PLUGIN (activatable); priv = plugin->priv; g_action_map_remove_action (G_ACTION_MAP (priv->window), "check-spell"); g_action_map_remove_action (G_ACTION_MAP (priv->window), "config-spell"); g_action_map_remove_action (G_ACTION_MAP (priv->window), "inline-spell-checker"); g_signal_handlers_disconnect_by_func (priv->window, tab_added_cb, activatable); g_signal_handlers_disconnect_by_func (priv->window, tab_removed_cb, activatable); views = gedit_window_get_views (priv->window); for (l = views; l != NULL; l = l->next) { deactivate_spell_checking_in_view (plugin, GEDIT_VIEW (l->data)); } } static void gedit_spell_plugin_update_state (GeditWindowActivatable *activatable) { gedit_debug (DEBUG_PLUGINS); update_ui (GEDIT_SPELL_PLUGIN (activatable)); } static void gedit_window_activatable_iface_init (GeditWindowActivatableInterface *iface) { iface->activate = gedit_spell_plugin_activate; iface->deactivate = gedit_spell_plugin_deactivate; iface->update_state = gedit_spell_plugin_update_state; } G_MODULE_EXPORT void peas_register_types (PeasObjectModule *module) { gedit_spell_plugin_register_type (G_TYPE_MODULE (module)); gedit_spell_app_activatable_register (G_TYPE_MODULE (module)); peas_object_module_register_extension_type (module, GEDIT_TYPE_WINDOW_ACTIVATABLE, GEDIT_TYPE_SPELL_PLUGIN); peas_object_module_register_extension_type (module, PEAS_GTK_TYPE_CONFIGURABLE, GEDIT_TYPE_SPELL_PLUGIN); } static void highlight_button_toggled (GtkToggleButton *button, SpellConfigureWidget *widget) { gboolean status = gtk_toggle_button_get_active (button); g_settings_set_boolean(widget->settings, SETTINGS_KEY_HIGHLIGHT_MISSPELLED, status); } static void configure_widget_destroyed (GtkWidget *widget, gpointer data) { SpellConfigureWidget *conf_widget = (SpellConfigureWidget *)data; gedit_debug (DEBUG_PLUGINS); g_object_unref (conf_widget->settings); g_slice_free (SpellConfigureWidget, data); gedit_debug_message (DEBUG_PLUGINS, "END"); } static SpellConfigureWidget * get_configure_widget (GeditSpellPlugin *plugin) { SpellConfigureWidget *widget; GtkBuilder *builder; gchar *root_objects[] = { "spell_dialog_content", NULL }; gedit_debug (DEBUG_PLUGINS); widget = g_slice_new (SpellConfigureWidget); widget->settings = g_object_ref (plugin->priv->settings); builder = gtk_builder_new (); gtk_builder_add_objects_from_resource (builder, "/org/gnome/gedit/plugins/spell/ui/gedit-spell-setup-dialog.ui", root_objects, NULL); widget->content = GTK_WIDGET (gtk_builder_get_object (builder, "spell_dialog_content")); g_object_ref (widget->content); widget->highlight_button = GTK_WIDGET (gtk_builder_get_object (builder, "highlight_button")); g_object_unref (builder); gboolean status = g_settings_get_boolean(widget->settings, SETTINGS_KEY_HIGHLIGHT_MISSPELLED); gtk_toggle_button_set_active (GTK_TOGGLE_BUTTON (widget->highlight_button), status); g_signal_connect (widget->highlight_button, "toggled", G_CALLBACK (highlight_button_toggled), widget); g_signal_connect (widget->content, "destroy", G_CALLBACK (configure_widget_destroyed), widget); return widget; } static GtkWidget * gedit_spell_plugin_create_configure_widget (PeasGtkConfigurable *configurable) { SpellConfigureWidget *widget; widget = get_configure_widget (GEDIT_SPELL_PLUGIN (configurable)); return widget->content; } static void peas_gtk_configurable_iface_init (PeasGtkConfigurableInterface *iface) { iface->create_configure_widget = gedit_spell_plugin_create_configure_widget; } /* ex:set ts=8 noet: */
GNOME/gedit
plugins/spell/gedit-spell-plugin.c
C
gpl-2.0
22,110
#include "Transform2D.h" Transform2D::Transform2D(glm::vec2 p_pos, float p_rot, glm::vec2 p_scale) { m_pos = p_pos; m_rot = p_rot; m_scale = p_scale; m_z = 0; } Transform2D::~Transform2D() { } glm::mat4 const & Transform2D::getModel() { glm::mat4 posMatrix = glm::translate(glm::vec3(m_pos, m_z)); glm::mat4 rotZMatrix = glm::rotate(m_rot, glm::vec3(0.0, 0.0, 1.0)); glm::mat4 scaleMatrix = glm::scale(glm::vec3(m_scale, 1.0)); m_model = posMatrix * rotZMatrix * scaleMatrix; return m_model; } glm::vec2 const & Transform2D::getPos() const { return m_pos; } glm::vec2 & Transform2D::getPos() { return m_pos; } float const & Transform2D::getRot() const { return m_rot; } float & Transform2D::getRot() { return m_rot; } glm::vec2 const & Transform2D::getScale() const { return m_scale; } glm::vec2 & Transform2D::getScale() { return m_scale; }
baadfood/myCode
Project3/Transform2D.cpp
C++
gpl-2.0
883
/** * Created with JetBrains WebStorm. * User: eder * Date: 14-7-14 * Time: 上午11:36 * To change this template use File | Settings | File Templates. */ var gameConst = require('../../tools/constValue'); var pomelo = require('pomelo'); var logger = require('pomelo/node_modules/pomelo-logger').getLogger(pomelo.app.getServerId(), __filename); var templateManager = require('../../tools/templateManager'); var templateConst = require('../../../template/templateConst'); var eVipInfo = gameConst.eVipInfo; var config = require('../../tools/config'); var ePlayerInfo = gameConst.ePlayerInfo; module.exports = function (owner) { return new Handler(owner); }; var Handler = function (owner) { this.owner = owner; this.roleID = 0; this.buyPvpNum = 0; this.freeSweepNum = 0; this.physicalNum = 0; this.freeReliveNum = 0; this.mineSweepNum = 0; /** * 额外贵族点数,运营商通过idip调整的,只在idip中才会用到这个 * 正常贵族点数是以米大师为准的,但如果运营需要调整,则总贵族点数为 * 米大师返回的值加上底下这个值,这个值也可能是负值 * */ this.extraVipPoint = 0; }; var handler = Handler.prototype; handler.LoadDataByDB = function (dataList) { var self = this; if (null != dataList && dataList.length > 0) { self.roleID = dataList[eVipInfo.RoleID]; self.buyPvpNum = dataList[eVipInfo.BuyPVPNum]; self.freeSweepNum = dataList[eVipInfo.FreeSweepNum]; self.physicalNum = dataList[eVipInfo.PhysicalNum]; self.freeReliveNum = dataList[eVipInfo.FreeReliveNum]; self.mineSweepNum = dataList[eVipInfo.MineSweepNum]; } }; /** * idip调整vip点数用到,上线时从库中取这个值再和米大师返回的值求合 * */ handler.LoadExtraVipPoint = function(data) { var GameSvrId = this.owner.playerInfo[ePlayerInfo.serverUid]; var point = null; for(var index in data) { if(data[index]['serverUid'] == GameSvrId) { point = data[index]['point'] || 0; break; } } point = point == null ? 0 : point; this.extraVipPoint = point; }; handler.GetExtraVipPoint = function() { return this.extraVipPoint || 0; }; handler.GetSqlStr = function (roleID) { var info = ''; info += '('; info += roleID + ',' + this.buyPvpNum + ',' + this.freeSweepNum + ',' + this.physicalNum + ',' + this.freeReliveNum + ',' + this.mineSweepNum ; info += ')'; return info; }; handler.UpdateVip12Info = function () { this.buyPvpNum = 0; this.freeSweepNum = 0; this.physicalNum = 0; this.freeReliveNum = 0; this.mineSweepNum = 0; }; handler.InitNumByType = function (roleID, type, num) { var self = this; if (this.roleID == 0) { this.roleID = roleID; } switch (type) { case eVipInfo.BuyPVPNum: self.buyPvpNum = num; break; case eVipInfo.FreeSweepNum: self.freeSweepNum = num; break; case eVipInfo.PhysicalNum: self.physicalNum = num; break; case eVipInfo.FreeReliveNum: self.freeReliveNum = num; break; case eVipInfo.MineSweepNum: self.mineSweepNum = num; break; default : logger.error("重置vip次数有错误类型"); } }; //加上用过的次数 handler.setNumByType = function (roleID, type, num) { var self = this; if (this.roleID == 0) { this.roleID = roleID; } switch (type) { case eVipInfo.BuyPVPNum: self.buyPvpNum += num; break; case eVipInfo.FreeSweepNum: self.freeSweepNum += num; break; case eVipInfo.PhysicalNum: self.physicalNum += num; break; case eVipInfo.FreeReliveNum: self.freeReliveNum += num; break; case eVipInfo.MineSweepNum: self.mineSweepNum += num; break; default : logger.error("更新vip次数有错误类型"); } }; handler.getNumByType = function (type) { switch (type) { case eVipInfo.BuyPVPNum: return this.buyPvpNum; break; case eVipInfo.FreeSweepNum: return this.freeSweepNum; break; case eVipInfo.PhysicalNum: return this.physicalNum; break; case eVipInfo.FreeReliveNum: return this.freeReliveNum; break; case eVipInfo.MineSweepNum: return this.mineSweepNum; break; default : logger.error("get vip次数有错误类型"); } }; handler.SendFreeSweepNum = function () { var self = this; var player = self.owner; var vipLevel = player.GetPlayerInfo(gameConst.ePlayerInfo.VipLevel); var vipTemplate = null; if (null == vipLevel || vipLevel == 0) { vipTemplate = templateManager.GetTemplateByID('VipTemplate', 1); } else { vipTemplate = templateManager.GetTemplateByID('VipTemplate', vipLevel + 1); } var route = "ServerSendFreeWeeepNum"; var msg = {num: 0}; if (null !== vipTemplate) { msg.num = vipTemplate[templateConst.tVipTemp.freeSweep] - self.freeSweepNum; } // logger.warn('SendFreeSweepNum, roleID: %j', this.owner.GetPlayerInfo(gameConst.ePlayerInfo.ROLEID)); player.SendMessage(route, msg); }; //VIP等级升级时重置vip扫荡次数 handler.SetVipInfoNum = function ( vipLevel) { var self = this; var vipTemplate = templateManager.GetTemplateByID('VipTemplate', vipLevel + 1); if (null == vipTemplate) { return; } var sweepNum = self.getNumByType(gameConst.eVipInfo.FreeSweepNum); var vipNum = vipTemplate[templateConst.tVipTemp.freeSweep]; if (vipNum <= 0) { return; } self.InitNumByType(self.owner.GetPlayerInfo(gameConst.ePlayerInfo.ROLEID), gameConst.eVipInfo.FreeSweepNum, sweepNum); self.SendFreeSweepNum(); }; handler.GetVipTemplate = function () { var ownerVipLevel = this.owner.GetPlayerInfo(gameConst.ePlayerInfo.VipLevel); var vipTemplate = null; if (null == ownerVipLevel || ownerVipLevel == 0) { vipTemplate = templateManager.GetTemplateByID('VipTemplate', 1); } else { vipTemplate = templateManager.GetTemplateByID('VipTemplate', ownerVipLevel + 1); } return vipTemplate; };
huojiecs/game1
game-server/app/cs/vipInfo/vipInfoManager.js
JavaScript
gpl-2.0
6,562
package tv.emby.embyatv.ui; import android.content.Context; import android.util.AttributeSet; import android.view.LayoutInflater; import android.widget.FrameLayout; import tv.emby.embyatv.R; /** * Created by Eric on 11/22/2015. */ public class DetailRowView extends FrameLayout { public DetailRowView(Context context) { super(context); inflateView(context); } public DetailRowView(Context context, AttributeSet attrs) { super(context, attrs); inflateView(context); } private void inflateView(Context context) { LayoutInflater inflater = LayoutInflater.from(context); inflater.inflate(R.layout.details_overview_row, this); } }
letroll/Emby.AndroidTv
EmbyAndroidTv/app/src/main/java/tv/emby/embyatv/ui/DetailRowView.java
Java
gpl-2.0
708
<?php /*------------------------------------------------------------------------ # com_xcideveloper - Seamless merging of CI Development Style with Joomla CMS # ------------------------------------------------------------------------ # author Xavoc International / Gowrav Vishwakarma # copyright Copyright (C) 2011 xavoc.com. All Rights Reserved. # @license - http://www.gnu.org/licenses/gpl-2.0.html GNU/GPL # Websites: http://www.xavoc.com # Technical Support: Forum - http://xavoc.com/index.php?option=com_discussions&view=index&Itemid=157 -------------------------------------------------------------------------*/ // no direct access defined( '_JEXEC' ) or die( 'Restricted access' ); ?><?php if ( ! defined('BASEPATH')) exit('No direct script access allowed'); /** * CodeIgniter * * An open source application development framework for PHP 5.1.6 or newer * * @package CodeIgniter * @author ExpressionEngine Dev Team * @copyright Copyright (c) 2008 - 2011, EllisLab, Inc. * @license http://codeigniter.com/user_guide/license.html * @link http://codeigniter.com * @since Version 1.0 * @filesource */ // ------------------------------------------------------------------------ /** * CodeIgniter Security Helpers * * @package CodeIgniter * @subpackage Helpers * @category Helpers * @author ExpressionEngine Dev Team * @link http://codeigniter.com/user_guide/helpers/security_helper.html */ // ------------------------------------------------------------------------ /** * XSS Filtering * * @access public * @param string * @param bool whether or not the content is an image file * @return string */ if ( ! function_exists('xss_clean')) { function xss_clean($str, $is_image = FALSE) { $CI =& get_instance(); return $CI->security->xss_clean($str, $is_image); } } // ------------------------------------------------------------------------ /** * Sanitize Filename * * @access public * @param string * @return string */ if ( ! function_exists('sanitize_filename')) { function sanitize_filename($filename) { $CI =& get_instance(); return $CI->security->sanitize_filename($filename); } } // -------------------------------------------------------------------- /** * Hash encode a string * * This is simply an alias for do_hash() * dohash() is now deprecated */ if ( ! function_exists('dohash')) { function dohash($str, $type = 'sha1') { return do_hash($str, $type); } } // -------------------------------------------------------------------- /** * Hash encode a string * * @access public * @param string * @return string */ if ( ! function_exists('do_hash')) { function do_hash($str, $type = 'sha1') { if ($type == 'sha1') { if ( ! function_exists('sha1')) { if ( ! function_exists('mhash')) { require_once(BASEPATH.'libraries/Sha1'.EXT); $SH = new CI_SHA; return $SH->generate($str); } else { return bin2hex(mhash(MHASH_SHA1, $str)); } } else { return sha1($str); } } else { return md5($str); } } } // ------------------------------------------------------------------------ /** * Strip Image Tags * * @access public * @param string * @return string */ if ( ! function_exists('strip_image_tags')) { function strip_image_tags($str) { $str = preg_replace("#<img\s+.*?src\s*=\s*[\"'](.+?)[\"'].*?\>#", "\\1", $str); $str = preg_replace("#<img\s+.*?src\s*=\s*(.+?).*?\>#", "\\1", $str); return $str; } } // ------------------------------------------------------------------------ /** * Convert PHP tags to entities * * @access public * @param string * @return string */ if ( ! function_exists('encode_php_tags')) { function encode_php_tags($str) { return str_replace(array('<?php', '<?php', '<?', '?>'), array('&lt;?php', '&lt;?PHP', '&lt;?', '?&gt;'), $str); } } /* End of file security_helper.php */ /* Location: ./system/helpers/security_helper.php */
gowrav-vishwakarma/ffm
administrator/components/com_mlm/system/helpers/security_helper.php
PHP
gpl-2.0
3,951
/* * This file is part of the TrinityCore Project. See AUTHORS file for Copyright information * * 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/>. */ #ifndef TRINITY_SMARTSCRIPTMGR_H #define TRINITY_SMARTSCRIPTMGR_H #include "Define.h" #include "ObjectGuid.h" #include "WaypointDefines.h" #include <map> #include <string> #include <unordered_map> class WorldObject; enum SpellEffIndex : uint8; enum eSmartAI { SMART_EVENT_PARAM_COUNT = 4, SMART_ACTION_PARAM_COUNT = 6, SMART_SUMMON_COUNTER = 0xFFFFFF, SMART_ESCORT_LAST_OOC_POINT = 0xFFFFFF, SMART_RANDOM_POINT = 0xFFFFFE, SMART_ESCORT_TARGETS = 0xFFFFFF }; enum SMART_EVENT_PHASE { SMART_EVENT_PHASE_ALWAYS = 0, SMART_EVENT_PHASE_1 = 1, SMART_EVENT_PHASE_2 = 2, SMART_EVENT_PHASE_3 = 3, SMART_EVENT_PHASE_4 = 4, SMART_EVENT_PHASE_5 = 5, SMART_EVENT_PHASE_6 = 6, SMART_EVENT_PHASE_7 = 7, SMART_EVENT_PHASE_8 = 8, SMART_EVENT_PHASE_9 = 9, SMART_EVENT_PHASE_10 = 10, SMART_EVENT_PHASE_11 = 11, SMART_EVENT_PHASE_12 = 12, SMART_EVENT_PHASE_MAX = 13, SMART_EVENT_PHASE_COUNT = 12 }; enum SMART_EVENT_PHASE_BITS { SMART_EVENT_PHASE_ALWAYS_BIT = 0, SMART_EVENT_PHASE_1_BIT = 1, SMART_EVENT_PHASE_2_BIT = 2, SMART_EVENT_PHASE_3_BIT = 4, SMART_EVENT_PHASE_4_BIT = 8, SMART_EVENT_PHASE_5_BIT = 16, SMART_EVENT_PHASE_6_BIT = 32, SMART_EVENT_PHASE_7_BIT = 64, SMART_EVENT_PHASE_8_BIT = 128, SMART_EVENT_PHASE_9_BIT = 256, SMART_EVENT_PHASE_10_BIT = 512, SMART_EVENT_PHASE_11_BIT = 1024, SMART_EVENT_PHASE_12_BIT = 2048, SMART_EVENT_PHASE_ALL = SMART_EVENT_PHASE_1_BIT + SMART_EVENT_PHASE_2_BIT + SMART_EVENT_PHASE_3_BIT + SMART_EVENT_PHASE_4_BIT + SMART_EVENT_PHASE_5_BIT + SMART_EVENT_PHASE_6_BIT + SMART_EVENT_PHASE_7_BIT + SMART_EVENT_PHASE_8_BIT + SMART_EVENT_PHASE_9_BIT + SMART_EVENT_PHASE_10_BIT + SMART_EVENT_PHASE_11_BIT + SMART_EVENT_PHASE_12_BIT }; const uint32 SmartPhaseMask[SMART_EVENT_PHASE_COUNT][2] = { {SMART_EVENT_PHASE_1, SMART_EVENT_PHASE_1_BIT }, {SMART_EVENT_PHASE_2, SMART_EVENT_PHASE_2_BIT }, {SMART_EVENT_PHASE_3, SMART_EVENT_PHASE_3_BIT }, {SMART_EVENT_PHASE_4, SMART_EVENT_PHASE_4_BIT }, {SMART_EVENT_PHASE_5, SMART_EVENT_PHASE_5_BIT }, {SMART_EVENT_PHASE_6, SMART_EVENT_PHASE_6_BIT }, {SMART_EVENT_PHASE_7, SMART_EVENT_PHASE_7_BIT }, {SMART_EVENT_PHASE_8, SMART_EVENT_PHASE_8_BIT }, {SMART_EVENT_PHASE_9, SMART_EVENT_PHASE_9_BIT }, {SMART_EVENT_PHASE_10, SMART_EVENT_PHASE_10_BIT }, {SMART_EVENT_PHASE_11, SMART_EVENT_PHASE_11_BIT }, {SMART_EVENT_PHASE_12, SMART_EVENT_PHASE_12_BIT } }; enum SMART_EVENT { SMART_EVENT_UPDATE_IC = 0, // InitialMin, InitialMax, RepeatMin, RepeatMax SMART_EVENT_UPDATE_OOC = 1, // InitialMin, InitialMax, RepeatMin, RepeatMax SMART_EVENT_HEALTH_PCT = 2, // HPMin%, HPMax%, RepeatMin, RepeatMax SMART_EVENT_MANA_PCT = 3, // ManaMin%, ManaMax%, RepeatMin, RepeatMax SMART_EVENT_AGGRO = 4, // NONE SMART_EVENT_KILL = 5, // CooldownMin0, CooldownMax1, playerOnly2, else creature entry3 SMART_EVENT_DEATH = 6, // NONE SMART_EVENT_EVADE = 7, // NONE SMART_EVENT_SPELLHIT = 8, // SpellID, School, CooldownMin, CooldownMax SMART_EVENT_RANGE = 9, // MinDist, MaxDist, RepeatMin, RepeatMax SMART_EVENT_OOC_LOS = 10, // NoHostile, MaxRnage, CooldownMin, CooldownMax SMART_EVENT_RESPAWN = 11, // type, MapId, ZoneId SMART_EVENT_TARGET_HEALTH_PCT = 12, // HPMin%, HPMax%, RepeatMin, RepeatMax SMART_EVENT_VICTIM_CASTING = 13, // RepeatMin, RepeatMax, spellid SMART_EVENT_FRIENDLY_HEALTH = 14, // HPDeficit, Radius, RepeatMin, RepeatMax SMART_EVENT_FRIENDLY_IS_CC = 15, // Radius, RepeatMin, RepeatMax SMART_EVENT_FRIENDLY_MISSING_BUFF = 16, // SpellId, Radius, RepeatMin, RepeatMax SMART_EVENT_SUMMONED_UNIT = 17, // CreatureId(0 all), CooldownMin, CooldownMax SMART_EVENT_TARGET_MANA_PCT = 18, // ManaMin%, ManaMax%, RepeatMin, RepeatMax SMART_EVENT_ACCEPTED_QUEST = 19, // QuestID (0 = any), CooldownMin, CooldownMax SMART_EVENT_REWARD_QUEST = 20, // QuestID (0 = any), CooldownMin, CooldownMax SMART_EVENT_REACHED_HOME = 21, // NONE SMART_EVENT_RECEIVE_EMOTE = 22, // EmoteId, CooldownMin, CooldownMax, condition, val1, val2, val3 SMART_EVENT_HAS_AURA = 23, // Param1 = SpellID, Param2 = Stack amount, Param3/4 RepeatMin, RepeatMax SMART_EVENT_TARGET_BUFFED = 24, // Param1 = SpellID, Param2 = Stack amount, Param3/4 RepeatMin, RepeatMax SMART_EVENT_RESET = 25, // Called after combat, when the creature respawn and spawn. SMART_EVENT_IC_LOS = 26, // NoHostile, MaxRnage, CooldownMin, CooldownMax SMART_EVENT_PASSENGER_BOARDED = 27, // CooldownMin, CooldownMax SMART_EVENT_PASSENGER_REMOVED = 28, // CooldownMin, CooldownMax SMART_EVENT_CHARMED = 29, // onRemove (0 - on apply, 1 - on remove) SMART_EVENT_CHARMED_TARGET = 30, // NONE SMART_EVENT_SPELLHIT_TARGET = 31, // SpellID, School, CooldownMin, CooldownMax SMART_EVENT_DAMAGED = 32, // MinDmg, MaxDmg, CooldownMin, CooldownMax SMART_EVENT_DAMAGED_TARGET = 33, // MinDmg, MaxDmg, CooldownMin, CooldownMax SMART_EVENT_MOVEMENTINFORM = 34, // MovementType(any), PointID SMART_EVENT_SUMMON_DESPAWNED = 35, // Entry, CooldownMin, CooldownMax SMART_EVENT_CORPSE_REMOVED = 36, // NONE SMART_EVENT_AI_INIT = 37, // NONE SMART_EVENT_DATA_SET = 38, // Id, Value, CooldownMin, CooldownMax SMART_EVENT_WAYPOINT_START = 39, // PointId(0any), pathID(0any) SMART_EVENT_WAYPOINT_REACHED = 40, // PointId(0any), pathID(0any) SMART_EVENT_TRANSPORT_ADDPLAYER = 41, // NONE SMART_EVENT_TRANSPORT_ADDCREATURE = 42, // Entry (0 any) SMART_EVENT_TRANSPORT_REMOVE_PLAYER = 43, // NONE SMART_EVENT_TRANSPORT_RELOCATE = 44, // PointId SMART_EVENT_INSTANCE_PLAYER_ENTER = 45, // Team (0 any), CooldownMin, CooldownMax SMART_EVENT_AREATRIGGER_ONTRIGGER = 46, // TriggerId(0 any) SMART_EVENT_QUEST_ACCEPTED = 47, // none SMART_EVENT_QUEST_OBJ_COPLETETION = 48, // none SMART_EVENT_QUEST_COMPLETION = 49, // none SMART_EVENT_QUEST_REWARDED = 50, // none SMART_EVENT_QUEST_FAIL = 51, // none SMART_EVENT_TEXT_OVER = 52, // GroupId from creature_text, creature entry who talks (0 any) SMART_EVENT_RECEIVE_HEAL = 53, // MinHeal, MaxHeal, CooldownMin, CooldownMax SMART_EVENT_JUST_SUMMONED = 54, // none SMART_EVENT_WAYPOINT_PAUSED = 55, // PointId(0any), pathID(0any) SMART_EVENT_WAYPOINT_RESUMED = 56, // PointId(0any), pathID(0any) SMART_EVENT_WAYPOINT_STOPPED = 57, // PointId(0any), pathID(0any) SMART_EVENT_WAYPOINT_ENDED = 58, // PointId(0any), pathID(0any) SMART_EVENT_TIMED_EVENT_TRIGGERED = 59, // id SMART_EVENT_UPDATE = 60, // InitialMin, InitialMax, RepeatMin, RepeatMax SMART_EVENT_LINK = 61, // INTERNAL USAGE, no params, used to link together multiple events, does not use any extra resources to iterate event lists needlessly SMART_EVENT_GOSSIP_SELECT = 62, // menuID, actionID SMART_EVENT_JUST_CREATED = 63, // none SMART_EVENT_GOSSIP_HELLO = 64, // noReportUse (for GOs) SMART_EVENT_FOLLOW_COMPLETED = 65, // none SMART_EVENT_EVENT_PHASE_CHANGE = 66, // event phase mask (<= SMART_EVENT_PHASE_ALL) SMART_EVENT_IS_BEHIND_TARGET = 67, // cooldownMin, CooldownMax SMART_EVENT_GAME_EVENT_START = 68, // game_event.Entry SMART_EVENT_GAME_EVENT_END = 69, // game_event.Entry SMART_EVENT_GO_LOOT_STATE_CHANGED = 70, // go LootState SMART_EVENT_GO_EVENT_INFORM = 71, // eventId SMART_EVENT_ACTION_DONE = 72, // eventId (SharedDefines.EventId) SMART_EVENT_ON_SPELLCLICK = 73, // clicker (unit) SMART_EVENT_FRIENDLY_HEALTH_PCT = 74, // minHpPct, maxHpPct, repeatMin, repeatMax SMART_EVENT_DISTANCE_CREATURE = 75, // guid, entry, distance, repeat SMART_EVENT_DISTANCE_GAMEOBJECT = 76, // guid, entry, distance, repeat SMART_EVENT_COUNTER_SET = 77, // id, value, cooldownMin, cooldownMax SMART_EVENT_SCENE_START = 78, // don't use on 3.3.5a SMART_EVENT_SCENE_TRIGGER = 79, // don't use on 3.3.5a SMART_EVENT_SCENE_CANCEL = 80, // don't use on 3.3.5a SMART_EVENT_SCENE_COMPLETE = 81, // don't use on 3.3.5a SMART_EVENT_SUMMONED_UNIT_DIES = 82, // CreatureId(0 all), CooldownMin, CooldownMax SMART_EVENT_END = 83 }; struct SmartEvent { SMART_EVENT type; uint32 event_phase_mask; uint32 event_chance; uint32 event_flags; union { struct { uint32 min; uint32 max; uint32 repeatMin; uint32 repeatMax; } minMaxRepeat; struct { uint32 cooldownMin; uint32 cooldownMax; uint32 playerOnly; uint32 creature; } kill; struct { uint32 spell; uint32 school; uint32 cooldownMin; uint32 cooldownMax; } spellHit; struct { uint32 noHostile; uint32 maxDist; uint32 cooldownMin; uint32 cooldownMax; uint32 playerOnly; } los; struct { uint32 type; uint32 map; uint32 area; } respawn; struct { uint32 repeatMin; uint32 repeatMax; } minMax; struct { uint32 repeatMin; uint32 repeatMax; uint32 spellId; } targetCasting; struct { uint32 hpDeficit; uint32 radius; uint32 repeatMin; uint32 repeatMax; } friendlyHealth; struct { uint32 radius; uint32 repeatMin; uint32 repeatMax; } friendlyCC; struct { uint32 spell; uint32 radius; uint32 repeatMin; uint32 repeatMax; } missingBuff; struct { uint32 creature; uint32 cooldownMin; uint32 cooldownMax; } summoned; struct { uint32 quest; uint32 cooldownMin; uint32 cooldownMax; } quest; struct { uint32 emote; uint32 cooldownMin; uint32 cooldownMax; } emote; struct { uint32 spell; uint32 count; uint32 repeatMin; uint32 repeatMax; } aura; struct { uint32 onRemove; } charm; struct { uint32 spell; uint32 count; uint32 repeatMin; uint32 repeatMax; } targetAura; struct { uint32 type; uint32 id; } movementInform; struct { uint32 id; uint32 value; uint32 cooldownMin; uint32 cooldownMax; } dataSet; struct { uint32 pointID; uint32 pathID; } waypoint; struct { uint32 creature; } transportAddCreature; struct { uint32 pointID; } transportRelocate; struct { uint32 team; uint32 cooldownMin; uint32 cooldownMax; } instancePlayerEnter; struct { uint32 id; } areatrigger; struct { uint32 textGroupID; uint32 creatureEntry; } textOver; struct { uint32 id; } timedEvent; struct { uint32 filter; } gossipHello; struct { uint32 sender; uint32 action; } gossip; struct { uint32 spell; uint32 effIndex; } dummy; struct { uint32 phasemask; } eventPhaseChange; struct { uint32 cooldownMin; uint32 cooldownMax; } behindTarget; struct { uint32 gameEventId; } gameEvent; struct { uint32 lootState; } goLootStateChanged; struct { uint32 eventId; } eventInform; struct { uint32 eventId; } doAction; struct { uint32 minHpPct; uint32 maxHpPct; uint32 repeatMin; uint32 repeatMax; uint32 radius; } friendlyHealthPct; struct { uint32 guid; uint32 entry; uint32 dist; uint32 repeat; } distance; struct { uint32 id; uint32 value; uint32 cooldownMin; uint32 cooldownMax; } counter; struct { uint32 param1; uint32 param2; uint32 param3; uint32 param4; uint32 param5; } raw; }; }; enum SMART_SCRIPT_RESPAWN_CONDITION { SMART_SCRIPT_RESPAWN_CONDITION_NONE = 0, SMART_SCRIPT_RESPAWN_CONDITION_MAP = 1, SMART_SCRIPT_RESPAWN_CONDITION_AREA = 2, SMART_SCRIPT_RESPAWN_CONDITION_END = 3 }; enum SMART_ACTION { SMART_ACTION_NONE = 0, // No action SMART_ACTION_TALK = 1, // groupID from creature_text, duration to wait before TEXT_OVER event is triggered, useTalkTarget (0/1) - use target as talk target SMART_ACTION_SET_FACTION = 2, // FactionId (or 0 for default) SMART_ACTION_MORPH_TO_ENTRY_OR_MODEL = 3, // Creature_template entry(param1) OR ModelId (param2) (or 0 for both to demorph) SMART_ACTION_SOUND = 4, // SoundId, onlySelf SMART_ACTION_PLAY_EMOTE = 5, // EmoteId SMART_ACTION_FAIL_QUEST = 6, // QuestID SMART_ACTION_OFFER_QUEST = 7, // QuestID, directAdd SMART_ACTION_SET_REACT_STATE = 8, // state SMART_ACTION_ACTIVATE_GOBJECT = 9, // SMART_ACTION_RANDOM_EMOTE = 10, // EmoteId1, EmoteId2, EmoteId3... SMART_ACTION_CAST = 11, // SpellId, CastFlags, TriggeredFlags SMART_ACTION_SUMMON_CREATURE = 12, // CreatureID, summonType, duration in ms, attackInvoker SMART_ACTION_THREAT_SINGLE_PCT = 13, // Threat% SMART_ACTION_THREAT_ALL_PCT = 14, // Threat% SMART_ACTION_CALL_AREAEXPLOREDOREVENTHAPPENS = 15, // QuestID SMART_ACTION_RESERVED_16 = 16, // used on 4.3.4 and higher scripts SMART_ACTION_SET_EMOTE_STATE = 17, // emoteID SMART_ACTION_SET_UNIT_FLAG = 18, // Flags (may be more than one field OR'd together), Target SMART_ACTION_REMOVE_UNIT_FLAG = 19, // Flags (may be more than one field OR'd together), Target SMART_ACTION_AUTO_ATTACK = 20, // AllowAttackState (0 = stop attack, anything else means continue attacking) SMART_ACTION_ALLOW_COMBAT_MOVEMENT = 21, // AllowCombatMovement (0 = stop combat based movement, anything else continue attacking) SMART_ACTION_SET_EVENT_PHASE = 22, // Phase SMART_ACTION_INC_EVENT_PHASE = 23, // Value (may be negative to decrement phase, should not be 0) SMART_ACTION_EVADE = 24, // toRespawnPosition (0 = Move to RespawnPosition, 1 = Move to last stored home position) SMART_ACTION_FLEE_FOR_ASSIST = 25, // With Emote SMART_ACTION_CALL_GROUPEVENTHAPPENS = 26, // QuestID SMART_ACTION_COMBAT_STOP = 27, // SMART_ACTION_REMOVEAURASFROMSPELL = 28, // Spellid (0 removes all auras), charges (0 removes aura) SMART_ACTION_FOLLOW = 29, // Distance (0 = default), Angle (0 = default), EndCreatureEntry, credit, creditType (0monsterkill, 1event) SMART_ACTION_RANDOM_PHASE = 30, // PhaseId1, PhaseId2, PhaseId3... SMART_ACTION_RANDOM_PHASE_RANGE = 31, // PhaseMin, PhaseMax SMART_ACTION_RESET_GOBJECT = 32, // SMART_ACTION_CALL_KILLEDMONSTER = 33, // CreatureId, SMART_ACTION_SET_INST_DATA = 34, // Field, Data, Type (0 = SetData, 1 = SetBossState) SMART_ACTION_SET_INST_DATA64 = 35, // Field, SMART_ACTION_UPDATE_TEMPLATE = 36, // Entry SMART_ACTION_DIE = 37, // No Params SMART_ACTION_SET_IN_COMBAT_WITH_ZONE = 38, // No Params SMART_ACTION_CALL_FOR_HELP = 39, // Radius, With Emote SMART_ACTION_SET_SHEATH = 40, // Sheath (0-unarmed, 1-melee, 2-ranged) SMART_ACTION_FORCE_DESPAWN = 41, // timer SMART_ACTION_SET_INVINCIBILITY_HP_LEVEL = 42, // MinHpValue(+pct, -flat) SMART_ACTION_MOUNT_TO_ENTRY_OR_MODEL = 43, // Creature_template entry(param1) OR ModelId (param2) (or 0 for both to dismount) SMART_ACTION_SET_INGAME_PHASE_MASK = 44, // mask SMART_ACTION_SET_DATA = 45, // Field, Data (only creature @todo) SMART_ACTION_ATTACK_STOP = 46, // SMART_ACTION_SET_VISIBILITY = 47, // on/off SMART_ACTION_SET_ACTIVE = 48, // on/off SMART_ACTION_ATTACK_START = 49, // SMART_ACTION_SUMMON_GO = 50, // GameObjectID, DespawnTime in s SMART_ACTION_KILL_UNIT = 51, // SMART_ACTION_ACTIVATE_TAXI = 52, // TaxiID SMART_ACTION_WP_START = 53, // run/walk, pathID, canRepeat, quest, despawntime, reactState SMART_ACTION_WP_PAUSE = 54, // time SMART_ACTION_WP_STOP = 55, // despawnTime, quest, fail? SMART_ACTION_ADD_ITEM = 56, // itemID, count SMART_ACTION_REMOVE_ITEM = 57, // itemID, count SMART_ACTION_INSTALL_AI_TEMPLATE = 58, // AITemplateID SMART_ACTION_SET_RUN = 59, // 0/1 SMART_ACTION_SET_DISABLE_GRAVITY = 60, // 0/1 SMART_ACTION_SET_SWIM = 61, // 0/1 SMART_ACTION_TELEPORT = 62, // mapID, SMART_ACTION_SET_COUNTER = 63, // id, value, reset (0/1) SMART_ACTION_STORE_TARGET_LIST = 64, // varID, SMART_ACTION_WP_RESUME = 65, // none SMART_ACTION_SET_ORIENTATION = 66, // SMART_ACTION_CREATE_TIMED_EVENT = 67, // id, InitialMin, InitialMax, RepeatMin(only if it repeats), RepeatMax(only if it repeats), chance SMART_ACTION_PLAYMOVIE = 68, // entry SMART_ACTION_MOVE_TO_POS = 69, // PointId, transport, disablePathfinding, ContactDistance SMART_ACTION_ENABLE_TEMP_GOBJ = 70, // despawnTimer (sec) SMART_ACTION_EQUIP = 71, // entry, slotmask slot1, slot2, slot3 , only slots with mask set will be sent to client, bits are 1, 2, 4, leaving mask 0 is defaulted to mask 7 (send all), slots1-3 are only used if no entry is set SMART_ACTION_CLOSE_GOSSIP = 72, // none SMART_ACTION_TRIGGER_TIMED_EVENT = 73, // id(>1) SMART_ACTION_REMOVE_TIMED_EVENT = 74, // id(>1) SMART_ACTION_ADD_AURA = 75, // spellid, targets SMART_ACTION_OVERRIDE_SCRIPT_BASE_OBJECT = 76, // WARNING: CAN CRASH CORE, do not use if you dont know what you are doing SMART_ACTION_RESET_SCRIPT_BASE_OBJECT = 77, // none SMART_ACTION_CALL_SCRIPT_RESET = 78, // none SMART_ACTION_SET_RANGED_MOVEMENT = 79, // Distance, angle SMART_ACTION_CALL_TIMED_ACTIONLIST = 80, // ID (overwrites already running actionlist), stop after combat?(0/1), timer update type(0-OOC, 1-IC, 2-ALWAYS) SMART_ACTION_SET_NPC_FLAG = 81, // Flags SMART_ACTION_ADD_NPC_FLAG = 82, // Flags SMART_ACTION_REMOVE_NPC_FLAG = 83, // Flags SMART_ACTION_SIMPLE_TALK = 84, // groupID, can be used to make players say groupID, Text_over event is not triggered, whisper can not be used (Target units will say the text) SMART_ACTION_SELF_CAST = 85, // spellID, castFlags SMART_ACTION_CROSS_CAST = 86, // spellID, castFlags, CasterTargetType, CasterTarget param1, CasterTarget param2, CasterTarget param3, ( + the origonal target fields as Destination target), CasterTargets will cast spellID on all Targets (use with caution if targeting multiple * multiple units) SMART_ACTION_CALL_RANDOM_TIMED_ACTIONLIST = 87, // script9 ids 1-9 SMART_ACTION_CALL_RANDOM_RANGE_TIMED_ACTIONLIST = 88, // script9 id min, max SMART_ACTION_RANDOM_MOVE = 89, // maxDist SMART_ACTION_SET_UNIT_FIELD_BYTES_1 = 90, // bytes, target SMART_ACTION_REMOVE_UNIT_FIELD_BYTES_1 = 91, // bytes, target SMART_ACTION_INTERRUPT_SPELL = 92, SMART_ACTION_SEND_GO_CUSTOM_ANIM = 93, // anim id SMART_ACTION_SET_DYNAMIC_FLAG = 94, // Flags SMART_ACTION_ADD_DYNAMIC_FLAG = 95, // Flags SMART_ACTION_REMOVE_DYNAMIC_FLAG = 96, // Flags SMART_ACTION_JUMP_TO_POS = 97, // speedXY, speedZ, targetX, targetY, targetZ SMART_ACTION_SEND_GOSSIP_MENU = 98, // menuId, optionId SMART_ACTION_GO_SET_LOOT_STATE = 99, // state SMART_ACTION_SEND_TARGET_TO_TARGET = 100, // id SMART_ACTION_SET_HOME_POS = 101, // none SMART_ACTION_SET_HEALTH_REGEN = 102, // 0/1 SMART_ACTION_SET_ROOT = 103, // off/on SMART_ACTION_SET_GO_FLAG = 104, // Flags SMART_ACTION_ADD_GO_FLAG = 105, // Flags SMART_ACTION_REMOVE_GO_FLAG = 106, // Flags SMART_ACTION_SUMMON_CREATURE_GROUP = 107, // Group, attackInvoker SMART_ACTION_SET_POWER = 108, // PowerType, newPower SMART_ACTION_ADD_POWER = 109, // PowerType, newPower SMART_ACTION_REMOVE_POWER = 110, // PowerType, newPower SMART_ACTION_GAME_EVENT_STOP = 111, // GameEventId SMART_ACTION_GAME_EVENT_START = 112, // GameEventId SMART_ACTION_START_CLOSEST_WAYPOINT = 113, // wp1, wp2, wp3, wp4, wp5, wp6, wp7 SMART_ACTION_MOVE_OFFSET = 114, SMART_ACTION_RANDOM_SOUND = 115, // soundId1, soundId2, soundId3, soundId4, soundId5, onlySelf SMART_ACTION_SET_CORPSE_DELAY = 116, // timer SMART_ACTION_DISABLE_EVADE = 117, // 0/1 (1 = disabled, 0 = enabled) SMART_ACTION_GO_SET_GO_STATE = 118, // state SMART_ACTION_SET_CAN_FLY = 119, // 0/1 SMART_ACTION_REMOVE_AURAS_BY_TYPE = 120, // type SMART_ACTION_SET_SIGHT_DIST = 121, // sightDistance SMART_ACTION_FLEE = 122, // fleeTime SMART_ACTION_ADD_THREAT = 123, // +threat, -threat SMART_ACTION_LOAD_EQUIPMENT = 124, // id SMART_ACTION_TRIGGER_RANDOM_TIMED_EVENT = 125, // id min range, id max range SMART_ACTION_REMOVE_ALL_GAMEOBJECTS = 126, SMART_ACTION_PAUSE_MOVEMENT = 127, // MovementSlot (default = 0, active = 1, controlled = 2), PauseTime (ms), Force SMART_ACTION_PLAY_ANIMKIT = 128, // don't use on 3.3.5a SMART_ACTION_SCENE_PLAY = 129, // don't use on 3.3.5a SMART_ACTION_SCENE_CANCEL = 130, // don't use on 3.3.5a SMART_ACTION_SPAWN_SPAWNGROUP = 131, // Group ID, min secs, max secs, spawnflags SMART_ACTION_DESPAWN_SPAWNGROUP = 132, // Group ID, min secs, max secs, spawnflags SMART_ACTION_RESPAWN_BY_SPAWNID = 133, // spawnType, spawnId SMART_ACTION_INVOKER_CAST = 134, // spellID, castFlags SMART_ACTION_PLAY_CINEMATIC = 135, // entry, cinematic SMART_ACTION_SET_MOVEMENT_SPEED = 136, // movementType, speedInteger, speedFraction SMART_ACTION_PLAY_SPELL_VISUAL_KIT = 137, // spellVisualKitId (RESERVED, PENDING CHERRYPICK) SMART_ACTION_OVERRIDE_LIGHT = 138, // zoneId, overrideLightID, transitionMilliseconds SMART_ACTION_OVERRIDE_WEATHER = 139, // zoneId, weatherId, intensity SMART_ACTION_SET_AI_ANIM_KIT = 140, // don't use on 3.3.5a SMART_ACTION_SET_HOVER = 141, // 0/1 SMART_ACTION_SET_HEALTH_PCT = 142, // percent SMART_ACTION_CREATE_CONVERSATION = 143, // don't use on 3.3.5a SMART_ACTION_END = 144 }; struct SmartAction { SMART_ACTION type; union { struct { uint32 textGroupID; uint32 duration; uint32 useTalkTarget; } talk; struct { uint32 factionID; } faction; struct { uint32 creature; uint32 model; } morphOrMount; struct { uint32 sound; uint32 onlySelf; uint32 distance; uint32 keyBroadcastTextId; // UNUSED: param reserved for compatibility with master branch } sound; struct { uint32 emote; } emote; struct { uint32 quest; } quest; struct { uint32 questID; uint32 directAdd; } questOffer; struct { uint32 state; } react; struct { uint32 emotes[SMART_ACTION_PARAM_COUNT]; } randomEmote; struct { uint32 spell; uint32 castFlags; uint32 triggerFlags; uint32 targetsLimit; } cast; struct { uint32 spell; uint32 castFlags; uint32 targetType; uint32 targetParam1; uint32 targetParam2; uint32 targetParam3; } crossCast; struct { uint32 creature; uint32 type; uint32 duration; uint32 attackInvoker; uint32 flags; // SmartActionSummonCreatureFlags // reserved, pending cherry-pick } summonCreature; struct { uint32 threatINC; uint32 threatDEC; } threatPCT; struct { uint32 flag1; uint32 flag2; uint32 flag3; uint32 flag4; uint32 flag5; uint32 flag6; } addUnitFlag; struct { uint32 flag1; uint32 flag2; uint32 flag3; uint32 flag4; uint32 flag5; uint32 flag6; } removeUnitFlag; struct { uint32 attack; } autoAttack; struct { uint32 move; } combatMove; struct { uint32 phase; } setEventPhase; struct { uint32 inc; uint32 dec; } incEventPhase; struct { uint32 spell; uint32 charges; uint32 onlyOwnedAuras; } removeAura; struct { uint32 dist; uint32 angle; uint32 entry; uint32 credit; uint32 creditType; } follow; struct { uint32 phases[SMART_ACTION_PARAM_COUNT]; } randomPhase; struct { uint32 phaseMin; uint32 phaseMax; } randomPhaseRange; struct { uint32 creature; } killedMonster; struct { uint32 field; uint32 data; uint32 type; } setInstanceData; struct { uint32 field; } setInstanceData64; struct { uint32 creature; uint32 updateLevel; } updateTemplate; struct { uint32 range; uint32 withEmote; } callHelp; struct { uint32 sheath; } setSheath; struct { uint32 delay; uint32 forceRespawnTimer; } forceDespawn; struct { uint32 minHP; uint32 percent; } invincHP; struct { uint32 mask; } ingamePhaseMask; struct { uint32 field; uint32 data; } setData; struct { uint32 distance; } moveRandom; struct { uint32 state; } visibility; struct { uint32 entry; uint32 despawnTime; uint32 summonType; } summonGO; struct { uint32 state; } active; struct { uint32 id; } taxi; struct { uint32 run; uint32 pathID; uint32 repeat; uint32 quest; uint32 despawnTime; uint32 reactState; } wpStart; struct { uint32 delay; } wpPause; struct { uint32 despawnTime; uint32 quest; uint32 fail; } wpStop; struct { uint32 entry; uint32 count; } item; struct { uint32 id; uint32 param1; uint32 param2; uint32 param3; uint32 param4; uint32 param5; } installTtemplate; struct { uint32 run; } setRun; struct { uint32 disable; } setDisableGravity; struct { uint32 fly; } setFly; struct { uint32 swim; } setSwim; struct { uint32 mapID; } teleport; struct { uint32 counterId; uint32 value; uint32 reset; } setCounter; struct { uint32 id; uint32 number; } storeVar; struct { uint32 id; } storeTargets; struct { uint32 id; uint32 min; uint32 max; uint32 repeatMin; uint32 repeatMax; uint32 chance; } timeEvent; struct { uint32 entry; } movie; struct { uint32 entry; uint32 mask; uint32 slot1; uint32 slot2; uint32 slot3; } equip; struct { uint32 flag; uint32 type; } unitFlag; struct { uint32 byte1; uint32 type; } setunitByte; struct { uint32 byte1; uint32 type; } delunitByte; struct { uint32 seat; } enterVehicle; struct { uint32 id; uint32 timerType; uint32 allowOverride; } timedActionList; struct { uint32 actionLists[SMART_ACTION_PARAM_COUNT]; } randTimedActionList; struct { uint32 withDelayed; uint32 spell_id; uint32 withInstant; } interruptSpellCasting; struct { uint32 anim; } sendGoCustomAnim; struct { uint32 speedxy; uint32 speedz; } jump; struct { uint32 withEmote; } fleeAssist; struct { uint32 fleeTime; } flee; struct { uint32 duration; } enableTempGO; struct { uint32 pointId; uint32 transport; uint32 disablePathfinding; uint32 ContactDistance; } MoveToPos; struct { uint32 gossipMenuId; uint32 gossipNpcTextId; } sendGossipMenu; struct { uint32 state; } setGoLootState; struct { uint32 id; } sendTargetToTarget; struct { uint32 distance; uint32 angle; } setRangedMovement; struct { uint32 regenHealth; } setHealthRegen; struct { uint32 root; } setRoot; struct { uint32 flag; } goFlag; struct { uint32 state; } goState; struct { uint32 group; uint32 attackInvoker; } creatureGroup; struct { uint32 powerType; uint32 newPower; } power; struct { uint32 id; } gameEventStop; struct { uint32 id; } gameEventStart; struct { uint32 wps[SMART_ACTION_PARAM_COUNT]; } closestWaypointFromList; struct { uint32 sounds[SMART_ACTION_PARAM_COUNT - 2]; uint32 onlySelf; uint32 distance; } randomSound; struct { uint32 timer; uint32 includeDecayRatio; } corpseDelay; struct { uint32 disable; } disableEvade; struct { uint32 groupId; uint32 minDelay; uint32 maxDelay; uint32 spawnflags; } groupSpawn; struct { uint32 type; } auraType; struct { uint32 dist; } sightDistance; struct { uint32 id; uint32 force; } loadEquipment; struct { uint32 minId; uint32 maxId; } randomTimedEvent; struct { uint32 movementSlot; uint32 pauseTimer; uint32 force; } pauseMovement; struct { uint32 spawnType; uint32 spawnId; } respawnData; struct { uint32 entry; } cinematic; struct { uint32 movementType; uint32 speedInteger; uint32 speedFraction; } movementSpeed; struct { uint32 zoneId; uint32 areaLightId; uint32 overrideLightId; uint32 transitionMilliseconds; } overrideLight; struct { uint32 zoneId; uint32 weatherId; uint32 intensity; } overrideWeather; struct { uint32 enable; } setHover; struct { uint32 toRespawnPosition; } evade; struct { uint32 percent; } setHealthPct; //! Note for any new future actions //! All parameters must have type uint32 struct { uint32 param1; uint32 param2; uint32 param3; uint32 param4; uint32 param5; uint32 param6; } raw; }; }; enum SMARTAI_SPAWN_FLAGS { SMARTAI_SPAWN_FLAG_NONE = 0x00, SMARTAI_SPAWN_FLAG_IGNORE_RESPAWN = 0x01, SMARTAI_SPAWN_FLAG_FORCE_SPAWN = 0x02, SMARTAI_SPAWN_FLAG_NOSAVE_RESPAWN = 0x04, }; enum SMARTAI_TEMPLATE { SMARTAI_TEMPLATE_BASIC = 0, //nothing is preset SMARTAI_TEMPLATE_CASTER = 1, //spellid, repeatMin, repeatMax, range, manaPCT +JOIN: target_param1 as castFlag SMARTAI_TEMPLATE_TURRET = 2, //spellid, repeatMin, repeatMax +JOIN: target_param1 as castFlag SMARTAI_TEMPLATE_PASSIVE = 3, SMARTAI_TEMPLATE_CAGED_GO_PART = 4, //creatureID, give credit at point end?, SMARTAI_TEMPLATE_CAGED_NPC_PART = 5, //gameObjectID, despawntime, run?, dist, TextGroupID SMARTAI_TEMPLATE_END = 6 }; enum SMARTAI_TARGETS { SMART_TARGET_NONE = 0, // NONE SMART_TARGET_SELF = 1, // Self cast SMART_TARGET_VICTIM = 2, // Our current target (ie: highest aggro) SMART_TARGET_HOSTILE_SECOND_AGGRO = 3, // Second highest aggro, maxdist, playerOnly, powerType + 1 SMART_TARGET_HOSTILE_LAST_AGGRO = 4, // Dead last on aggro, maxdist, playerOnly, powerType + 1 SMART_TARGET_HOSTILE_RANDOM = 5, // Just any random target on our threat list, maxdist, playerOnly, powerType + 1 SMART_TARGET_HOSTILE_RANDOM_NOT_TOP = 6, // Any random target except top threat, maxdist, playerOnly, powerType + 1 SMART_TARGET_ACTION_INVOKER = 7, // Unit who caused this Event to occur SMART_TARGET_POSITION = 8, // use xyz from event params SMART_TARGET_CREATURE_RANGE = 9, // CreatureEntry(0any), minDist, maxDist SMART_TARGET_CREATURE_GUID = 10, // guid, entry SMART_TARGET_CREATURE_DISTANCE = 11, // CreatureEntry(0any), maxDist SMART_TARGET_STORED = 12, // id, uses pre-stored target(list) SMART_TARGET_GAMEOBJECT_RANGE = 13, // entry(0any), min, max SMART_TARGET_GAMEOBJECT_GUID = 14, // guid, entry SMART_TARGET_GAMEOBJECT_DISTANCE = 15, // entry(0any), maxDist SMART_TARGET_INVOKER_PARTY = 16, // invoker's party members SMART_TARGET_PLAYER_RANGE = 17, // min, max SMART_TARGET_PLAYER_DISTANCE = 18, // maxDist SMART_TARGET_CLOSEST_CREATURE = 19, // CreatureEntry(0any), maxDist, dead? SMART_TARGET_CLOSEST_GAMEOBJECT = 20, // entry(0any), maxDist SMART_TARGET_CLOSEST_PLAYER = 21, // maxDist SMART_TARGET_ACTION_INVOKER_VEHICLE = 22, // Unit's vehicle who caused this Event to occur SMART_TARGET_OWNER_OR_SUMMONER = 23, // Unit's owner or summoner, Use Owner/Charmer of this unit SMART_TARGET_THREAT_LIST = 24, // All units on creature's threat list, maxdist SMART_TARGET_CLOSEST_ENEMY = 25, // maxDist, playerOnly SMART_TARGET_CLOSEST_FRIENDLY = 26, // maxDist, playerOnly SMART_TARGET_LOOT_RECIPIENTS = 27, // all players that have tagged this creature (for kill credit) SMART_TARGET_FARTHEST = 28, // maxDist, playerOnly, isInLos SMART_TARGET_VEHICLE_PASSENGER = 29, // seatMask (0 - all seats) SMART_TARGET_CLOSEST_UNSPAWNED_GAMEOBJECT = 30, // entry(0any), maxDist SMART_TARGET_END = 31 }; struct SmartTarget { SmartTarget (SMARTAI_TARGETS t = SMART_TARGET_NONE, uint32 p1 = 0, uint32 p2 = 0, uint32 p3 = 0, uint32 p4 = 0) { type = t; raw.param1 = p1; raw.param2 = p2; raw.param3 = p3; raw.param4 = p4; x = 0.0f; y = 0.0f; z = 0.0f; o = 0.0f; } SMARTAI_TARGETS type; float x, y, z, o; union { struct { uint32 maxDist; uint32 playerOnly; uint32 powerType; } hostilRandom; struct { uint32 maxDist; uint32 playerOnly; uint32 isInLos; } farthest; struct { uint32 creature; uint32 minDist; uint32 maxDist; uint32 maxSize; } unitRange; struct { uint32 dbGuid; uint32 entry; } unitGUID; struct { uint32 creature; uint32 dist; uint32 maxSize; } unitDistance; struct { uint32 dist; } playerDistance; struct { uint32 minDist; uint32 maxDist; } playerRange; struct { uint32 id; } stored; struct { uint32 entry; uint32 minDist; uint32 maxDist; uint32 maxSize; } goRange; struct { uint32 dbGuid; uint32 entry; } goGUID; struct { uint32 entry; uint32 dist; uint32 maxSize; } goDistance; struct { uint32 map; } position; struct { uint32 entry; uint32 dist; uint32 dead; } closest; struct { uint32 maxDist; uint32 playerOnly; } closestAttackable; struct { uint32 maxDist; uint32 playerOnly; } closestFriendly; struct { uint32 useCharmerOrOwner; } owner; struct { uint32 param1; uint32 param2; uint32 param3; uint32 param4; } raw; struct { uint32 seatMask; } vehicle; }; }; enum SmartScriptType { SMART_SCRIPT_TYPE_CREATURE = 0, //done SMART_SCRIPT_TYPE_GAMEOBJECT = 1, //done SMART_SCRIPT_TYPE_AREATRIGGER = 2, //done SMART_SCRIPT_TYPE_EVENT = 3, // SMART_SCRIPT_TYPE_GOSSIP = 4, // SMART_SCRIPT_TYPE_QUEST = 5, // SMART_SCRIPT_TYPE_SPELL = 6, // SMART_SCRIPT_TYPE_TRANSPORT = 7, // SMART_SCRIPT_TYPE_INSTANCE = 8, // SMART_SCRIPT_TYPE_TIMED_ACTIONLIST = 9, // SMART_SCRIPT_TYPE_SCENE = 10, // RESERVED master branch SMART_SCRIPT_TYPE_AREATRIGGER_ENTITY = 11, // RESERVED master branch SMART_SCRIPT_TYPE_AREATRIGGER_ENTITY_SERVERSIDE = 12, // RESERVED master branch SMART_SCRIPT_TYPE_MAX }; enum SmartAITypeMaskId { SMART_SCRIPT_TYPE_MASK_CREATURE = 1, SMART_SCRIPT_TYPE_MASK_GAMEOBJECT = 2, SMART_SCRIPT_TYPE_MASK_AREATRIGGER = 4, SMART_SCRIPT_TYPE_MASK_EVENT = 8, SMART_SCRIPT_TYPE_MASK_GOSSIP = 16, SMART_SCRIPT_TYPE_MASK_QUEST = 32, SMART_SCRIPT_TYPE_MASK_SPELL = 64, SMART_SCRIPT_TYPE_MASK_TRANSPORT = 128, SMART_SCRIPT_TYPE_MASK_INSTANCE = 256, SMART_SCRIPT_TYPE_MASK_TIMED_ACTIONLIST = 512 }; const uint32 SmartAITypeMask[SMART_SCRIPT_TYPE_MAX][2] = { {SMART_SCRIPT_TYPE_CREATURE, SMART_SCRIPT_TYPE_MASK_CREATURE }, {SMART_SCRIPT_TYPE_GAMEOBJECT, SMART_SCRIPT_TYPE_MASK_GAMEOBJECT }, {SMART_SCRIPT_TYPE_AREATRIGGER, SMART_SCRIPT_TYPE_MASK_AREATRIGGER }, {SMART_SCRIPT_TYPE_EVENT, SMART_SCRIPT_TYPE_MASK_EVENT }, {SMART_SCRIPT_TYPE_GOSSIP, SMART_SCRIPT_TYPE_MASK_GOSSIP }, {SMART_SCRIPT_TYPE_QUEST, SMART_SCRIPT_TYPE_MASK_QUEST }, {SMART_SCRIPT_TYPE_SPELL, SMART_SCRIPT_TYPE_MASK_SPELL }, {SMART_SCRIPT_TYPE_TRANSPORT, SMART_SCRIPT_TYPE_MASK_TRANSPORT }, {SMART_SCRIPT_TYPE_INSTANCE, SMART_SCRIPT_TYPE_MASK_INSTANCE }, {SMART_SCRIPT_TYPE_TIMED_ACTIONLIST, SMART_SCRIPT_TYPE_MASK_TIMED_ACTIONLIST }, {SMART_SCRIPT_TYPE_SCENE, 0 }, {SMART_SCRIPT_TYPE_AREATRIGGER_ENTITY, 0 }, {SMART_SCRIPT_TYPE_AREATRIGGER_ENTITY_SERVERSIDE, 0 } }; const uint32 SmartAIEventMask[SMART_EVENT_END][2] = { {SMART_EVENT_UPDATE_IC, SMART_SCRIPT_TYPE_MASK_CREATURE + SMART_SCRIPT_TYPE_MASK_TIMED_ACTIONLIST}, {SMART_EVENT_UPDATE_OOC, SMART_SCRIPT_TYPE_MASK_CREATURE + SMART_SCRIPT_TYPE_MASK_GAMEOBJECT + SMART_SCRIPT_TYPE_MASK_INSTANCE }, {SMART_EVENT_HEALTH_PCT, SMART_SCRIPT_TYPE_MASK_CREATURE }, {SMART_EVENT_MANA_PCT, SMART_SCRIPT_TYPE_MASK_CREATURE }, {SMART_EVENT_AGGRO, SMART_SCRIPT_TYPE_MASK_CREATURE }, {SMART_EVENT_KILL, SMART_SCRIPT_TYPE_MASK_CREATURE }, {SMART_EVENT_DEATH, SMART_SCRIPT_TYPE_MASK_CREATURE }, {SMART_EVENT_EVADE, SMART_SCRIPT_TYPE_MASK_CREATURE }, {SMART_EVENT_SPELLHIT, SMART_SCRIPT_TYPE_MASK_CREATURE + SMART_SCRIPT_TYPE_MASK_GAMEOBJECT }, {SMART_EVENT_RANGE, SMART_SCRIPT_TYPE_MASK_CREATURE }, {SMART_EVENT_OOC_LOS, SMART_SCRIPT_TYPE_MASK_CREATURE }, {SMART_EVENT_RESPAWN, SMART_SCRIPT_TYPE_MASK_CREATURE + SMART_SCRIPT_TYPE_MASK_GAMEOBJECT }, {SMART_EVENT_TARGET_HEALTH_PCT, SMART_SCRIPT_TYPE_MASK_CREATURE }, {SMART_EVENT_VICTIM_CASTING, SMART_SCRIPT_TYPE_MASK_CREATURE }, {SMART_EVENT_FRIENDLY_HEALTH, SMART_SCRIPT_TYPE_MASK_CREATURE }, {SMART_EVENT_FRIENDLY_IS_CC, SMART_SCRIPT_TYPE_MASK_CREATURE }, {SMART_EVENT_FRIENDLY_MISSING_BUFF, SMART_SCRIPT_TYPE_MASK_CREATURE }, {SMART_EVENT_SUMMONED_UNIT, SMART_SCRIPT_TYPE_MASK_CREATURE + SMART_SCRIPT_TYPE_MASK_GAMEOBJECT }, {SMART_EVENT_TARGET_MANA_PCT, SMART_SCRIPT_TYPE_MASK_CREATURE }, {SMART_EVENT_ACCEPTED_QUEST, SMART_SCRIPT_TYPE_MASK_CREATURE + SMART_SCRIPT_TYPE_MASK_GAMEOBJECT }, {SMART_EVENT_REWARD_QUEST, SMART_SCRIPT_TYPE_MASK_CREATURE + SMART_SCRIPT_TYPE_MASK_GAMEOBJECT }, {SMART_EVENT_REACHED_HOME, SMART_SCRIPT_TYPE_MASK_CREATURE }, {SMART_EVENT_RECEIVE_EMOTE, SMART_SCRIPT_TYPE_MASK_CREATURE }, {SMART_EVENT_HAS_AURA, SMART_SCRIPT_TYPE_MASK_CREATURE }, {SMART_EVENT_TARGET_BUFFED, SMART_SCRIPT_TYPE_MASK_CREATURE }, {SMART_EVENT_RESET, SMART_SCRIPT_TYPE_MASK_CREATURE }, {SMART_EVENT_IC_LOS, SMART_SCRIPT_TYPE_MASK_CREATURE }, {SMART_EVENT_PASSENGER_BOARDED, SMART_SCRIPT_TYPE_MASK_CREATURE }, {SMART_EVENT_PASSENGER_REMOVED, SMART_SCRIPT_TYPE_MASK_CREATURE }, {SMART_EVENT_CHARMED, SMART_SCRIPT_TYPE_MASK_CREATURE }, {SMART_EVENT_CHARMED_TARGET, SMART_SCRIPT_TYPE_MASK_CREATURE }, {SMART_EVENT_SPELLHIT_TARGET, SMART_SCRIPT_TYPE_MASK_CREATURE }, {SMART_EVENT_DAMAGED, SMART_SCRIPT_TYPE_MASK_CREATURE }, {SMART_EVENT_DAMAGED_TARGET, SMART_SCRIPT_TYPE_MASK_CREATURE }, {SMART_EVENT_MOVEMENTINFORM, SMART_SCRIPT_TYPE_MASK_CREATURE }, {SMART_EVENT_SUMMON_DESPAWNED, SMART_SCRIPT_TYPE_MASK_CREATURE + SMART_SCRIPT_TYPE_MASK_GAMEOBJECT }, {SMART_EVENT_CORPSE_REMOVED, SMART_SCRIPT_TYPE_MASK_CREATURE }, {SMART_EVENT_AI_INIT, SMART_SCRIPT_TYPE_MASK_CREATURE + SMART_SCRIPT_TYPE_MASK_GAMEOBJECT }, {SMART_EVENT_DATA_SET, SMART_SCRIPT_TYPE_MASK_CREATURE + SMART_SCRIPT_TYPE_MASK_GAMEOBJECT }, {SMART_EVENT_WAYPOINT_START, SMART_SCRIPT_TYPE_MASK_CREATURE }, {SMART_EVENT_WAYPOINT_REACHED, SMART_SCRIPT_TYPE_MASK_CREATURE }, {SMART_EVENT_TRANSPORT_ADDPLAYER, SMART_SCRIPT_TYPE_MASK_TRANSPORT }, {SMART_EVENT_TRANSPORT_ADDCREATURE, SMART_SCRIPT_TYPE_MASK_TRANSPORT }, {SMART_EVENT_TRANSPORT_REMOVE_PLAYER, SMART_SCRIPT_TYPE_MASK_TRANSPORT }, {SMART_EVENT_TRANSPORT_RELOCATE, SMART_SCRIPT_TYPE_MASK_TRANSPORT }, {SMART_EVENT_INSTANCE_PLAYER_ENTER, SMART_SCRIPT_TYPE_MASK_INSTANCE }, {SMART_EVENT_AREATRIGGER_ONTRIGGER, SMART_SCRIPT_TYPE_MASK_AREATRIGGER }, {SMART_EVENT_QUEST_ACCEPTED, SMART_SCRIPT_TYPE_MASK_QUEST }, {SMART_EVENT_QUEST_OBJ_COPLETETION, SMART_SCRIPT_TYPE_MASK_QUEST }, {SMART_EVENT_QUEST_REWARDED, SMART_SCRIPT_TYPE_MASK_QUEST }, {SMART_EVENT_QUEST_COMPLETION, SMART_SCRIPT_TYPE_MASK_QUEST }, {SMART_EVENT_QUEST_FAIL, SMART_SCRIPT_TYPE_MASK_QUEST }, {SMART_EVENT_TEXT_OVER, SMART_SCRIPT_TYPE_MASK_CREATURE + SMART_SCRIPT_TYPE_MASK_GAMEOBJECT }, {SMART_EVENT_RECEIVE_HEAL, SMART_SCRIPT_TYPE_MASK_CREATURE }, {SMART_EVENT_JUST_SUMMONED, SMART_SCRIPT_TYPE_MASK_CREATURE }, {SMART_EVENT_WAYPOINT_PAUSED, SMART_SCRIPT_TYPE_MASK_CREATURE }, {SMART_EVENT_WAYPOINT_RESUMED, SMART_SCRIPT_TYPE_MASK_CREATURE }, {SMART_EVENT_WAYPOINT_STOPPED, SMART_SCRIPT_TYPE_MASK_CREATURE }, {SMART_EVENT_WAYPOINT_ENDED, SMART_SCRIPT_TYPE_MASK_CREATURE }, {SMART_EVENT_TIMED_EVENT_TRIGGERED, SMART_SCRIPT_TYPE_MASK_CREATURE + SMART_SCRIPT_TYPE_MASK_GAMEOBJECT }, {SMART_EVENT_UPDATE, SMART_SCRIPT_TYPE_MASK_CREATURE + SMART_SCRIPT_TYPE_MASK_GAMEOBJECT }, {SMART_EVENT_LINK, SMART_SCRIPT_TYPE_MASK_CREATURE + SMART_SCRIPT_TYPE_MASK_GAMEOBJECT + SMART_SCRIPT_TYPE_MASK_AREATRIGGER + SMART_SCRIPT_TYPE_MASK_EVENT + SMART_SCRIPT_TYPE_MASK_GOSSIP + SMART_SCRIPT_TYPE_MASK_QUEST + SMART_SCRIPT_TYPE_MASK_SPELL + SMART_SCRIPT_TYPE_MASK_TRANSPORT + SMART_SCRIPT_TYPE_MASK_INSTANCE }, {SMART_EVENT_GOSSIP_SELECT, SMART_SCRIPT_TYPE_MASK_CREATURE + SMART_SCRIPT_TYPE_MASK_GAMEOBJECT }, {SMART_EVENT_JUST_CREATED, SMART_SCRIPT_TYPE_MASK_CREATURE + SMART_SCRIPT_TYPE_MASK_GAMEOBJECT }, {SMART_EVENT_GOSSIP_HELLO, SMART_SCRIPT_TYPE_MASK_CREATURE + SMART_SCRIPT_TYPE_MASK_GAMEOBJECT }, {SMART_EVENT_FOLLOW_COMPLETED, SMART_SCRIPT_TYPE_MASK_CREATURE }, {SMART_EVENT_EVENT_PHASE_CHANGE, SMART_SCRIPT_TYPE_MASK_CREATURE + SMART_SCRIPT_TYPE_MASK_GAMEOBJECT }, {SMART_EVENT_IS_BEHIND_TARGET, SMART_SCRIPT_TYPE_MASK_CREATURE }, {SMART_EVENT_GAME_EVENT_START, SMART_SCRIPT_TYPE_MASK_CREATURE + SMART_SCRIPT_TYPE_MASK_GAMEOBJECT }, {SMART_EVENT_GAME_EVENT_END, SMART_SCRIPT_TYPE_MASK_CREATURE + SMART_SCRIPT_TYPE_MASK_GAMEOBJECT }, {SMART_EVENT_GO_LOOT_STATE_CHANGED, SMART_SCRIPT_TYPE_MASK_GAMEOBJECT }, {SMART_EVENT_GO_EVENT_INFORM, SMART_SCRIPT_TYPE_MASK_GAMEOBJECT }, {SMART_EVENT_ACTION_DONE, SMART_SCRIPT_TYPE_MASK_CREATURE }, {SMART_EVENT_ON_SPELLCLICK, SMART_SCRIPT_TYPE_MASK_CREATURE }, {SMART_EVENT_FRIENDLY_HEALTH_PCT, SMART_SCRIPT_TYPE_MASK_CREATURE }, {SMART_EVENT_DISTANCE_CREATURE, SMART_SCRIPT_TYPE_MASK_CREATURE }, {SMART_EVENT_DISTANCE_GAMEOBJECT, SMART_SCRIPT_TYPE_MASK_CREATURE }, {SMART_EVENT_COUNTER_SET, SMART_SCRIPT_TYPE_MASK_CREATURE + SMART_SCRIPT_TYPE_MASK_GAMEOBJECT }, {SMART_EVENT_SCENE_START, 0 }, {SMART_EVENT_SCENE_TRIGGER, 0 }, {SMART_EVENT_SCENE_CANCEL, 0 }, {SMART_EVENT_SCENE_COMPLETE, 0 }, {SMART_EVENT_SUMMONED_UNIT_DIES, SMART_SCRIPT_TYPE_MASK_CREATURE + SMART_SCRIPT_TYPE_MASK_GAMEOBJECT }, }; enum SmartEventFlags { SMART_EVENT_FLAG_NOT_REPEATABLE = 0x001, //Event can not repeat SMART_EVENT_FLAG_DIFFICULTY_0 = 0x002, //Event only occurs in instance difficulty 0 SMART_EVENT_FLAG_DIFFICULTY_1 = 0x004, //Event only occurs in instance difficulty 1 SMART_EVENT_FLAG_DIFFICULTY_2 = 0x008, //Event only occurs in instance difficulty 2 SMART_EVENT_FLAG_DIFFICULTY_3 = 0x010, //Event only occurs in instance difficulty 3 SMART_EVENT_FLAG_RESERVED_5 = 0x020, SMART_EVENT_FLAG_RESERVED_6 = 0x040, SMART_EVENT_FLAG_DEBUG_ONLY = 0x080, //Event only occurs in debug build SMART_EVENT_FLAG_DONT_RESET = 0x100, //Event will not reset in SmartScript::OnReset() SMART_EVENT_FLAG_WHILE_CHARMED = 0x200, //Event occurs even if AI owner is charmed SMART_EVENT_FLAG_DIFFICULTY_ALL = (SMART_EVENT_FLAG_DIFFICULTY_0|SMART_EVENT_FLAG_DIFFICULTY_1|SMART_EVENT_FLAG_DIFFICULTY_2|SMART_EVENT_FLAG_DIFFICULTY_3), SMART_EVENT_FLAGS_ALL = (SMART_EVENT_FLAG_NOT_REPEATABLE|SMART_EVENT_FLAG_DIFFICULTY_ALL|SMART_EVENT_FLAG_RESERVED_5|SMART_EVENT_FLAG_RESERVED_6|SMART_EVENT_FLAG_DEBUG_ONLY|SMART_EVENT_FLAG_DONT_RESET|SMART_EVENT_FLAG_WHILE_CHARMED), // Temp flags, used only at runtime, never stored in DB SMART_EVENT_FLAG_TEMP_IGNORE_CHANCE_ROLL = 0x40000000, //Event occurs no matter what roll_chance_i(e.event.event_chance) returns. }; enum SmartCastFlags { SMARTCAST_INTERRUPT_PREVIOUS = 0x01, // Interrupt any spell casting SMARTCAST_TRIGGERED = 0x02, // Triggered (this makes spell cost zero mana and have no cast time) //SMARTCAST_FORCE_CAST = 0x04, //Forces cast even if creature is out of mana or out of range //SMARTCAST_NO_MELEE_IF_OOM = 0x08, //Prevents creature from entering melee if out of mana or out of range //SMARTCAST_FORCE_TARGET_SELF = 0x10, //Forces the target to cast this spell on itself SMARTCAST_AURA_NOT_PRESENT = 0x20, // Only casts the spell if the target does not have an aura from the spell SMARTCAST_COMBAT_MOVE = 0x40 // Prevents combat movement if cast successful. Allows movement on range, OOM, LOS }; // one line in DB is one event struct SmartScriptHolder { SmartScriptHolder() : entryOrGuid(0), source_type(SMART_SCRIPT_TYPE_CREATURE) , event_id(0), link(0), event(), action(), target(), timer(0), priority(DEFAULT_PRIORITY), active(false), runOnce(false) , enableTimed(false) { } int32 entryOrGuid; SmartScriptType source_type; uint32 event_id; uint32 link; SmartEvent event; SmartAction action; SmartTarget target; uint32 GetScriptType() const { return (uint32)source_type; } uint32 GetEventType() const { return (uint32)event.type; } uint32 GetActionType() const { return (uint32)action.type; } uint32 GetTargetType() const { return (uint32)target.type; } uint32 timer; uint32 priority; bool active; bool runOnce; bool enableTimed; operator bool() const { return entryOrGuid != 0; } // Default comparision operator using priority field as first ordering field bool operator<(SmartScriptHolder const& other) const { return std::tie(priority, entryOrGuid, source_type, event_id, link) < std::tie(other.priority, other.entryOrGuid, other.source_type, other.event_id, other.link); } static constexpr uint32 DEFAULT_PRIORITY = std::numeric_limits<uint32>::max(); }; typedef std::vector<WorldObject*> ObjectVector; class ObjectGuidVector { public: explicit ObjectGuidVector(ObjectVector const& objectVector); ObjectVector const* GetObjectVector(WorldObject const& ref) const { UpdateObjects(ref); return &_objectVector; } ~ObjectGuidVector() { } private: GuidVector _guidVector; mutable ObjectVector _objectVector; //sanitize vector using _guidVector void UpdateObjects(WorldObject const& ref) const; }; typedef std::unordered_map<uint32, ObjectGuidVector> ObjectVectorMap; class TC_GAME_API SmartWaypointMgr { public: static SmartWaypointMgr* instance(); void LoadFromDB(); WaypointPath const* GetPath(uint32 id); private: SmartWaypointMgr() { } ~SmartWaypointMgr() { } std::unordered_map<uint32, WaypointPath> _waypointStore; }; #define sSmartWaypointMgr SmartWaypointMgr::instance() // all events for a single entry typedef std::vector<SmartScriptHolder> SmartAIEventList; typedef std::vector<SmartScriptHolder> SmartAIEventStoredList; // all events for all entries / guids typedef std::unordered_map<int32, SmartAIEventList> SmartAIEventMap; // Helper Stores typedef std::map<uint32 /*entry*/, std::pair<uint32 /*spellId*/, SpellEffIndex /*effIndex*/> > CacheSpellContainer; typedef std::pair<CacheSpellContainer::const_iterator, CacheSpellContainer::const_iterator> CacheSpellContainerBounds; class TC_GAME_API SmartAIMgr { private: SmartAIMgr() { } ~SmartAIMgr() { } public: static SmartAIMgr* instance(); void LoadSmartAIFromDB(); SmartAIEventList GetScript(int32 entry, SmartScriptType type); static SmartScriptHolder& FindLinkedSourceEvent(SmartAIEventList& list, uint32 eventId); static SmartScriptHolder& FindLinkedEvent(SmartAIEventList& list, uint32 link); private: //event stores SmartAIEventMap mEventMap[SMART_SCRIPT_TYPE_MAX]; static bool EventHasInvoker(SMART_EVENT event); bool IsEventValid(SmartScriptHolder& e); bool IsTargetValid(SmartScriptHolder const& e); static bool IsMinMaxValid(SmartScriptHolder const& e, uint32 min, uint32 max); static bool NotNULL(SmartScriptHolder const& e, uint32 data); static bool IsCreatureValid(SmartScriptHolder const& e, uint32 entry); static bool IsQuestValid(SmartScriptHolder const& e, uint32 entry); static bool IsGameObjectValid(SmartScriptHolder const& e, uint32 entry); static bool IsSpellValid(SmartScriptHolder const& e, uint32 entry); static bool IsItemValid(SmartScriptHolder const& e, uint32 entry); static bool IsTextEmoteValid(SmartScriptHolder const& e, uint32 entry); static bool IsEmoteValid(SmartScriptHolder const& e, uint32 entry); static bool IsAreaTriggerValid(SmartScriptHolder const& e, uint32 entry); static bool IsSoundValid(SmartScriptHolder const& e, uint32 entry); static bool IsTextValid(SmartScriptHolder const& e, uint32 id); // Helpers void LoadHelperStores(); void UnLoadHelperStores(); CacheSpellContainerBounds GetSummonCreatureSpellContainerBounds(uint32 creatureEntry) const; CacheSpellContainerBounds GetSummonGameObjectSpellContainerBounds(uint32 gameObjectEntry) const; CacheSpellContainerBounds GetKillCreditSpellContainerBounds(uint32 killCredit) const; CacheSpellContainerBounds GetCreateItemSpellContainerBounds(uint32 itemId) const; CacheSpellContainer SummonCreatureSpellStore; CacheSpellContainer SummonGameObjectSpellStore; CacheSpellContainer KillCreditSpellStore; CacheSpellContainer CreateItemSpellStore; }; #define sSmartScriptMgr SmartAIMgr::instance() #endif
kemlg/trinitycore-conciens
src/server/game/AI/SmartScripts/SmartScriptMgr.h
C
gpl-2.0
63,512
<?php /** * Element: Header * Displays a title with a bunch of extras, like: description, image, versioncheck * * @package NoNumber Framework * @version 12.4.4 * * @author Peter van Westen <peter@nonumber.nl> * @link http://www.nonumber.nl * @copyright Copyright © 2012 NoNumber All Rights Reserved * @license http://www.gnu.org/licenses/gpl-2.0.html GNU/GPL */ // No direct access defined('_JEXEC') or die; // Load common functions require_once JPATH_PLUGINS.'/system/nnframework/helpers/functions.php'; /** * Header Element * * Available extra parameters: * title The title * description The description * xml The xml file for grabbing data * language_file Main name part of the language php file * image Image (and path) to show on the right * image_w Image width * image_h Image height * url The main url * help_url The url of the help page */ class nnFieldHeader { var $_version = '12.4.4'; function getInput($name, $id, $value, $params, $children, $j15 = 0) { $this->params = $params; $document = JFactory::getDocument(); $document->addStyleSheet(JURI::root(true).'/plugins/system/nnframework/css/style.css?v='.$this->_version); $title = $this->def('label'); $description = $this->def('description'); $xml = $this->def('xml'); $lang_file = $this->def('language_file'); $image = $this->def('image'); $image_w = $this->def('image_w'); $image_h = $this->def('image_h'); $url = $this->def('url'); $help_url = $this->def('help_url'); if ($description) { // variables $v1 = $this->def('var1'); $v2 = $this->def('var2'); $v3 = $this->def('var3'); $v4 = $this->def('var4'); $v5 = $this->def('var5'); $description = NNFrameworkFunctions::html_entity_decoder(trim(JText::sprintf($description, $v1, $v2, $v3, $v4, $v5))); } if ($lang_file) { jimport('joomla.filesystem.file'); // Include extra language file $language = JFactory::getLanguage(); $lang = str_replace('_', '-', $language->getTag()); $inc = ''; $lang_path = 'language/'.$lang.'/'.$lang.'.'.$lang_file.'.inc.php'; if (JFile::exists(JPATH_ADMINISTRATOR.'/'.$lang_path)) { $inc = JPATH_ADMINISTRATOR.'/'.$lang_path; } else if (JFile::exists(JPATH_SITE.'/'.$lang_path)) { $inc = JPATH_SITE.'/'.$lang_path; } if (!$inc && $lang != 'en-GB') { $lang = 'en-GB'; $lang_path = 'language/'.$lang.'/'.$lang.'.'.$lang_file.'.inc.php'; if (JFile::exists(JPATH_ADMINISTRATOR.'/'.$lang_path)) { $inc = JPATH_ADMINISTRATOR.'/'.$lang_path; } else if (JFile::exists(JPATH_SITE.'/'.$lang_path)) { $inc = JPATH_SITE.'/'.$lang_path; } } if ($inc) { include $inc; } } if ($title) { $title = JText::_($title); } if ($description) { $description = str_replace('span style="font-family:monospace;"', 'span class="nn_code"', $description); if ($description['0'] != '<') { $description = '<p>'.$description.'</p>'; } } if ($xml) { $xml = JApplicationHelper::parseXMLInstallFile(JPATH_SITE.'/'.$xml); $version = 0; if ($xml && isset($xml['version'])) { $version = $xml['version']; } if ($version) { if (!(strpos($version, 'PRO') === false)) { $version = str_replace('PRO', '', $version); $version .= ' <small style="color:green">[PRO]</small>'; } else if (!(strpos($version, 'FREE') === false)) { $version = str_replace('FREE', '', $version); $version .= ' <small style="color:green">[FREE]</small>'; } if ($title) { $title .= ' v'; } else { $title = JText::_('Version').' '; } $title .= $version; } } if ($url) { $url = '<a href="'.$url.'" target="_blank" title="'.preg_replace('#<[^>]*>#', '', $title).'">'; } $html = array(); $html[] = '<div class="panel nn_panel'.($j15 ? ' nn_panel_15' : '').'"><div class="nn_block nn_title">'; if ($image) { $image = str_replace('/', "\n", str_replace('\\', '/', $image)); $image = explode("\n", trim($image)); if ($image['0'] == 'administrator') { $image['0'] = JURI::base(true); } else { $image['0'] = JURI::root(true).'/'.$image['0']; } $image = '<img src="'.implode('/', $image).'" border="0" style="float:right;margin-left:10px" alt=""'; if ($image_w) { $image .= ' width="'.$image_w.'"'; } if ($image_h) { $image .= ' height="'.$image_h.'"'; } $image .= ' />'; if ($url) { $image = $url.$image.'</a>'; } $html[] = $image; } if ($title) { if ($url) { $title = $url.$title.'</a>'; } $html[] = '<h4 style="margin: 0px;">'.NNFrameworkFunctions::html_entity_decoder($title).'</h4>'; } if ($description) { $html[] = $description; } if ($help_url) { $html[] = '<p><a href="'.$help_url.'" target="_blank" title="'.JText::_('NN_MORE_INFO').'">'.JText::_('NN_MORE_INFO').'...</a></p>'; } $html[] = '<div style="clear: both;"></div>'; $html[] = '</div></div>'; return implode('', $html); } private function def($val, $default = '') { return (isset($this->params[$val]) && (string) $this->params[$val] != '') ? (string) $this->params[$val] : $default; } } if (version_compare(JVERSION, '1.6.0', 'l')) { // For Joomla 1.5 class JElementNN_Header extends JElement { /** * Element name * * @access protected * @var string */ var $_name = 'Header'; function fetchTooltip($label, $description, &$node, $control_name, $name) { $this->_nnfield = new nnFieldHeader(); return; } function fetchElement($name, $value, &$node, $control_name) { return $this->_nnfield->getInput($control_name.'['.$name.']', $control_name.$name, $value, $node->attributes(), $node->children(), 1); } } } else { // For Joomla 1.6 class JFormFieldNN_Header extends JFormField { /** * The form field type * * @var string */ public $type = 'Header'; protected function getLabel() { $this->_nnfield = new nnFieldHeader(); return; } protected function getInput() { return $this->_nnfield->getInput($this->name, $this->id, $this->value, $this->element->attributes(), $this->element->children()); } } }
MA-Ponyvriedjes/ponyvriendjes
plugins/system/nnframework/fields/header.php
PHP
gpl-2.0
6,158
local mc = require "multicast" channel = channel or {} function channel.init() channel.channels = {} channel.add("world") end function channel.add(name,...) if select("#",...) > 0 then local args = table.pack(...) table.insert(args,1,name) name = table.concat(args,"#") end assert(name) assert(channel.channels[name]==nil) local chan = mc.new() logger.log("info","channel",string.format("[add] name=%s channel=%s",name,chan.channel)) channel.channels[name] = chan end function channel.del(name,...) if select("#",...) > 0 then local args = table.pack(...) table.insert(args,1,name) name = table.concat(args,"#") end local chan = channel.get(name) if chan then logger.log("info","channel",string.format("[del] name=%s channel=%s",name,chan.channel)) chan:delete() channel.channels[name] = nil end end function channel.get(name,...) if select("#",...) > 0 then local args = table.pack(...) table.insert(args,1,name) name = table.concat(args,"#") end return channel.channels[name] end function channel.publish(name,...) local chan = channel.get(name) if chan then logger.log("debug","channel",format("[publish] name=%s channel=%s pack=%s",name,chan.channel,{...})) chan:publish(...) end end function channel.subscribe(name,pid) local chan = channel.get(name) if not chan then return end local player = playermgr.getplayer(pid) if not player then return end local agent = player.__agent logger.log("info","channel",string.format("[subscribe] name=%s channel=%s pid=%s",name,chan.channel,pid)) skynet.send(agent,"lua","subscribe",chan.channel) end function channel.unsubscribe(name,pid,reason) local chan = channel.get(name) if not chan then return end local player = playermgr.getplayer(pid) if not player then return end local agent = player.__agent logger.log("info","channel",string.format("[unsubscribe] name=%s channel=%s pid=%s reason=%s",name,chan.channel,pid,reason)) skynet.send(agent,"lua","unsubscribe",chan.channel) end return channel
sundream/gamesrv
script/channel.lua
Lua
gpl-2.0
2,026
<?php /** * @Project NUKEVIET 3.x * @Author VINADES.,JSC (contact@vinades.vn) * @Copyright (C) 2012 VINADES.,JSC. All rights reserved * @Createdate 28/10/2012, 14:51 */ // Xác định root site define( 'NV_ROOTDIR', pathinfo( str_replace( DIRECTORY_SEPARATOR, '/', __file__ ), PATHINFO_DIRNAME ) ); class Token { public $type; public $contents; public function __construct( $rawToken ) { if( is_array( $rawToken ) ) { $this->type = $rawToken[0]; $this->contents = $rawToken[1]; } else { $this->type = - 1; $this->contents = $rawToken; } } } function nv_fomat_dir( $dirname, $all = false ) { $dh = opendir( NV_ROOTDIR . '/' . $dirname ); if( $dh ) { while( ($file = readdir( $dh )) !== false ) { if( preg_match( '/^([a-zA-Z0-9\-\_\/\.]+)\.php$/', $file ) ) { if( ! nv_fomat_file_php( NV_ROOTDIR . '/' . $dirname . '/' . $file ) ) { echo $dirname . '/' . $file . ' ---------------------- no change ----------------------<br>'; } else { echo $dirname . '/' . $file . '<br>'; } } elseif( preg_match( "/^([a-zA-Z0-9\-\_\/\.]+)\.js$/", $file ) ) { if( ! nv_fomat_file_js( NV_ROOTDIR . '/' . $dirname . '/' . $file ) ) { echo $dirname . '/' . $file . ' ---------------------- no change ----------------------<br>'; } else { echo $file . '<br>'; } } elseif( preg_match( "/^([a-zA-Z0-9\-\_\/\.]+)\.tpl$/", $file ) ) { if( ! nv_fomat_file_tpl( NV_ROOTDIR . '/' . $dirname . '/' . $file ) ) { echo $dirname . '/' . $file . ' ---------------------- no change ----------------------<br>'; } else { echo $dirname . '/' . $file . '<br>'; } } elseif( $all and preg_match( "/^([a-zA-Z0-9\-\_\/]+)$/", $file ) and is_dir( NV_ROOTDIR . '/' . $dirname . '/' . $file ) ) { nv_fomat_dir( $dirname . '/' . $file, $all ); } } } } /** * @param strimg $filename * @return number */ function nv_fomat_file_php( $filename ) { // ap dung cho Aptana Studio 3 $array_file_not_fomat = array( ); $array_file_not_fomat[] = NV_ROOTDIR . '/includes/class/idna_convert.class.php'; $array_file_not_fomat[] = NV_ROOTDIR . '/includes/class/openid.class.php'; $array_file_not_fomat[] = NV_ROOTDIR . '/includes/class/pclzip.class.php'; $array_file_not_fomat[] = NV_ROOTDIR . '/includes/class/SimpleCaptcha.class.php'; $array_file_not_fomat[] = NV_ROOTDIR . '/includes/class/xtemplate.class.php'; $array_file_not_fomat[] = NV_ROOTDIR . '/includes/phpmailer/class.phpmailer.php'; $array_file_not_fomat[] = NV_ROOTDIR . '/includes/phpmailer/class.pop3.php'; $array_file_not_fomat[] = NV_ROOTDIR . '/includes/phpmailer/class.smtp.php'; $array_file_not_fomat[] = NV_ROOTDIR . '/editors/ckeditor/plugins/ckeditor_wiris/integration/api.php'; $array_file_not_fomat[] = NV_ROOTDIR . '/editors/ckeditor/plugins/ckeditor_wiris/integration/cas.php'; $array_file_not_fomat[] = NV_ROOTDIR . '/editors/ckeditor/plugins/ckeditor_wiris/integration/ConfigurationUpdater.php'; $array_file_not_fomat[] = NV_ROOTDIR . '/editors/ckeditor/plugins/ckeditor_wiris/integration/createcasimage.php'; $array_file_not_fomat[] = NV_ROOTDIR . '/editors/ckeditor/plugins/ckeditor_wiris/integration/createimage.php'; $array_file_not_fomat[] = NV_ROOTDIR . '/editors/ckeditor/plugins/ckeditor_wiris/integration/getconfig.php'; $array_file_not_fomat[] = NV_ROOTDIR . '/editors/ckeditor/plugins/ckeditor_wiris/integration/getmathml.php'; $array_file_not_fomat[] = NV_ROOTDIR . '/editors/ckeditor/plugins/ckeditor_wiris/integration/libwiris.php'; $array_file_not_fomat[] = NV_ROOTDIR . '/editors/ckeditor/plugins/ckeditor_wiris/integration/service.php'; $array_file_not_fomat[] = NV_ROOTDIR . '/editors/ckeditor/plugins/ckeditor_wiris/integration/showcasimage.php'; $array_file_not_fomat[] = NV_ROOTDIR . '/editors/ckeditor/plugins/ckeditor_wiris/integration/showimage.php'; if( ! in_array( $filename, $array_file_not_fomat ) ) { $contents = file_get_contents( $filename ); // Thêm dòng trắng đầu file $output_data = preg_replace( '/^\<\?php/', "<?php\n", trim( $contents ) ); // Thêm dòng trắng ở cuối file $output_data = preg_replace( '/\?\>$/', "\n?>", $output_data ); //Xóa các dòng trống có tab, hoặc có nhiều hơn 1 dòng trống $output_data = trim( preg_replace( '/\n([\t\n]+)\n/', "\n\n", $output_data ) ); $output_data = preg_replace( '/\,\s\-\s/', ', -', $output_data ); //Không xuống dòng nếu if có 1 lệnh $output_data = preg_replace( '/if\((.*)\)\n([\t\s]+)([^\{\s]{1}+)/', "if(\\1) \\3", $output_data ); //Thêm khoảng cách vào sau và trước dấu mở ngoặc đơn $raw_tokens = token_get_all( $output_data ); $array_tokend = array( ); foreach( $raw_tokens as $rawToken ) { $array_tokend[] = new Token( $rawToken ); } foreach( $array_tokend as $key => $tokend ) { if( $tokend->contents == '(' ) { if( $array_tokend[$key + 1]->type != T_WHITESPACE ) { $array_tokend[$key]->contents = '( '; } } elseif( $tokend->contents == ')' ) { if( $array_tokend[$key - 1]->type != T_WHITESPACE ) { $array_tokend[$key]->contents = ' )'; } } } $output_data = ''; foreach( $array_tokend as $key => $tokend ) { $output_data .= $tokend->contents; } //Xử lý mảng $raw_tokens = token_get_all( $output_data ); $array_tokend = array( ); foreach( $raw_tokens as $rawToken ) { $array_tokend[] = new Token( $rawToken ); } $output_data = ''; $this_line_tab = ''; // Thut dau dong dong hien tai $is_in_array = 0; // Trong array - array cap thu bao nhieu $num_open_parentheses = array( ); // Dem so dau ( $num_close_parentheses = array( ); // Dem so dau ) $is_double_arrow = array( ); // Array co xuong hang hay khong $total_tokend = sizeof( $array_tokend ); foreach( $array_tokend as $key => $tokend ) { // Xac dinh so tab if( $tokend->type == T_WHITESPACE and preg_match( "/\n/", $tokend->contents ) and $is_in_array <= 0 ) { $tab = array_filter( explode( "\n", $tokend->contents ) ); $tab = end( $tab ); $this_line_tab = $tab; } elseif( $tokend->type == T_CATCH and $array_tokend[$key + 1]->type == T_WHITESPACE ) { $array_tokend[$key + 1]->contents = ''; } // Danh dau array bat dau if( $tokend->type == T_ARRAY ) { $is_in_array++; $is_double_arrow[$is_in_array] = 0; // Mac dinh khong co mui ten hoac array con $key_close_array = $key; // Tim trong array nay co mui ten => hay la array con hay khong $j = $key; $_num_open_parentheses = 0; $_num_close_parentheses = 0; while( $j < $total_tokend ) { $j++; if( $array_tokend[$j]->contents == "(" ) $_num_open_parentheses++; if( $array_tokend[$j]->contents == ")" ) $_num_close_parentheses++; if( $array_tokend[$j]->type == T_DOUBLE_ARROW or $array_tokend[$j]->type == T_ARRAY or ($array_tokend[$j]->type == T_COMMENT and $array_tokend[$j - 2]->contents == ",") ) { $is_double_arrow[$is_in_array]++; } if( $_num_open_parentheses > 0 and $_num_open_parentheses == $_num_close_parentheses ) { $key_close_array = $j; break; } } $is_double_arrow[$is_in_array] = $is_double_arrow[$is_in_array] > 2 ? true : false; $num_open_parentheses[$is_in_array] = 0; $num_close_parentheses[$is_in_array] = 0; } if( $is_in_array > 0 ) { if( empty( $is_double_arrow[$is_in_array] ) and $tokend->type == T_WHITESPACE ) { $tokend->contents = str_replace( array( "\n", "\t" ), array( " ", "" ), $tokend->contents ); } // Xoa dau , cuoi cung cua array if( $key == ($key_close_array - 2) and $tokend->contents == "," and $tokend->type == - 1 ) { $tokend->contents = ''; } elseif( $tokend->type == T_WHITESPACE and preg_match( "/\n/", $tokend->contents ) and ! empty( $is_double_arrow[$is_in_array] ) ) { $tokend->contents = "\n" . $this_line_tab; for( $i = 0; $i < $is_in_array; ++$i ) { $tokend->contents .= "\t"; } } // Dong mo array if( $tokend->contents == "(" ) $num_open_parentheses[$is_in_array]++; if( $tokend->contents == ")" ) $num_close_parentheses[$is_in_array]++; if( $num_open_parentheses[$is_in_array] > 0 and $num_open_parentheses[$is_in_array] == $num_close_parentheses[$is_in_array] ) { if( ! empty( $is_double_arrow[$is_in_array] ) ) { $output_data = trim( $output_data ) . "\n" . $this_line_tab; for( $i = 1; $i < $is_in_array; ++$i ) { $output_data .= "\t"; } } $output_data .= ")"; $is_in_array--; } else { $output_data .= $tokend->contents; } } else { $output_data .= $tokend->contents; } } // Loại bỏ khoảng trắng ( ) $output_data = preg_replace( '/\([\s]+\)/', '()', $output_data ); $output_data = preg_replace( "/[ ]+/", " ", $output_data ); if( $output_data != $contents ) { return file_put_contents( $filename, trim( $output_data ), LOCK_EX ); } } return 0; } function nv_fomat_file_js( $filename ) { // ap dung cho Zend Studio 9.0.4 $contents = file_get_contents( $filename ); $output_data = preg_replace( '/\n([\t\n]+)\n/', "\n\n", $contents ); //Xóa các dòng trống có tab, hoặc có nhiều hơn 1 dòng trống $output_data = str_replace( '( var ', '(var ', $output_data ); if( $output_data != $contents ) { return file_put_contents( $filename, trim( $output_data ), LOCK_EX ); } return 0; } function nv_fomat_file_tpl( $filename ) { $contents = file_get_contents( $filename ); // Xóa dòng trống ở cuối và sửa khoảng trống <textarea $contentssave = trim( preg_replace( '/\>\s*\<textarea\s*/', '><textarea ', $contents ) ); $contentssave = str_replace( '<td></td>', '<td>&nbsp;</td>', $contentssave ); $contentssave = str_replace( '<tbody{', '<tbody {', $contentssave ); $contentssave = str_replace( '<li{', '<li {', $contentssave ); $contentssave = str_replace( '<blockquote{CLASS}>', '<blockquote {CLASS}>', $contentssave ); $dom = new DOMDocument( ); $dom->loadHTML( $contentssave ); $dom->preserveWhiteSpace = false; $Tagname = $dom->getElementsByTagname( 'script' ); foreach( $Tagname as $child ) { $tmp_dom = new DOMDocument( ); $tmp_dom->appendChild( $tmp_dom->importNode( $child, true ) ); $html = trim( $tmp_dom->saveHTML( ) ); if( preg_match( '/\<\!\-\-\s*BEGIN:\s*([a-zA-Z0-9\-\_]+)\s*\-\-\>/', $html, $m ) ) { print_r( "Xtemplate: " . $m[1] . " trong JS file: " . $filename ); return 0; } elseif( preg_match_all( '/\{\s*\n*\t*([a-zA-Z0-9\-\_\.]+)\s*\n*\t*\}/i', $html, $m ) ) { $s = sizeof( $m[0] ); for( $i = 0; $i <= $s; $i++ ) { $contentssave = ( string )str_replace( $m[0][$i], '{' . trim( $m[1][$i] ) . '}', $contentssave ); } } } //Xóa các dòng trống có tab, hoặc có nhiều hơn 1 dòng trống $contentssave = trim( preg_replace( '/\n([\t\n]+)\n/', "\n\n", $contentssave ) ); if( $contentssave != $contents ) { return file_put_contents( $filename, $contentssave, LOCK_EX ); } return 0; } $filename = isset( $_GET['f'] ) ? trim( $_GET['f'] ) : ''; $filename = str_replace( '..', '', $filename ); if( preg_match( "/^([a-zA-Z0-9\-\_\/\.]+)\.php$/", $filename ) ) { if( ! nv_fomat_file_php( NV_ROOTDIR . '/' . $filename ) ) { echo $filename . ' ---------------------- no change ----------------------<br>'; } else { echo $filename . '<br>'; } } elseif( preg_match( "/^([a-zA-Z0-9\-\_\/\.]+)\.tpl$/", $filename ) ) { if( ! nv_fomat_file_tpl( NV_ROOTDIR . '/' . $filename ) ) { echo $filename . ' ---------------------- no change ----------------------<br>'; } else { echo $filename . '<br>'; } } elseif( preg_match( "/^([a-zA-Z0-9\-\_\/\.]+)\.js$/", $filename ) ) { if( ! nv_fomat_file_js( NV_ROOTDIR . '/' . $filename ) ) { echo $filename . ' ---------------------- no change ----------------------<br>'; } else { echo $filename . '<br>'; } } elseif( (preg_match( "/^([a-zA-Z0-9\-\_\/]+)$/", $filename ) or $filename == '') and is_dir( NV_ROOTDIR . '/' . $filename ) ) { $all = isset( $_GET['all'] ) ? intval( $_GET['all'] ) : 0; nv_fomat_dir( $filename, $all ); } else { die( $filename ); } ?>
teammhst13-27/mhst13-27
fa.php
PHP
gpl-2.0
12,410
/* * linux/drivers/video/modedb.c -- Standard video mode database management * * Copyright (C) 1999 Geert Uytterhoeven * * 2001 - Documented with DocBook * - Brad Douglas <brad@neruo.com> * * This file is subject to the terms and conditions of the GNU General Public * License. See the file COPYING in the main directory of this archive for * more details. */ #include <linux/module.h> #include <linux/slab.h> #include <linux/fb.h> #include <linux/kernel.h> #undef DEBUG #define name_matches(v, s, l) \ ((v).name && !strncmp((s), (v).name, (l)) && strlen((v).name) == (l)) #define res_matches(v, x, y) \ ((v).xres == (x) && (v).yres == (y)) #ifdef DEBUG #define DPRINTK(fmt, args...) printk("modedb %s: " fmt, __func__ , ## args) #else #define DPRINTK(fmt, args...) #endif const char *fb_mode_option; EXPORT_SYMBOL_GPL(fb_mode_option); /* * Standard video mode definitions (taken from XFree86) */ static const struct fb_videomode modedb[] = { /* 640x400 @ 70 Hz, 31.5 kHz hsync */ { NULL, 70, 640, 400, 39721, 40, 24, 39, 9, 96, 2, 0, FB_VMODE_NONINTERLACED }, /* 640x480 @ 60 Hz, 31.5 kHz hsync */ { NULL, 60, 640, 480, 39721, 40, 24, 32, 11, 96, 2, 0, FB_VMODE_NONINTERLACED }, /* 800x600 @ 56 Hz, 35.15 kHz hsync */ { NULL, 56, 800, 600, 27777, 128, 24, 22, 1, 72, 2, 0, FB_VMODE_NONINTERLACED }, /* 1024x768 @ 87 Hz interlaced, 35.5 kHz hsync */ { NULL, 87, 1024, 768, 22271, 56, 24, 33, 8, 160, 8, 0, FB_VMODE_INTERLACED }, /* 640x400 @ 85 Hz, 37.86 kHz hsync */ { NULL, 85, 640, 400, 31746, 96, 32, 41, 1, 64, 3, FB_SYNC_VERT_HIGH_ACT, FB_VMODE_NONINTERLACED }, /* 640x480 @ 72 Hz, 36.5 kHz hsync */ { NULL, 72, 640, 480, 31746, 144, 40, 30, 8, 40, 3, 0, FB_VMODE_NONINTERLACED }, /* 640x480 @ 75 Hz, 37.50 kHz hsync */ { NULL, 75, 640, 480, 31746, 120, 16, 16, 1, 64, 3, 0, FB_VMODE_NONINTERLACED }, /* 800x600 @ 60 Hz, 37.8 kHz hsync */ { NULL, 60, 800, 600, 25000, 88, 40, 23, 1, 128, 4, FB_SYNC_HOR_HIGH_ACT | FB_SYNC_VERT_HIGH_ACT, FB_VMODE_NONINTERLACED }, /* 640x480 @ 85 Hz, 43.27 kHz hsync */ { NULL, 85, 640, 480, 27777, 80, 56, 25, 1, 56, 3, 0, FB_VMODE_NONINTERLACED }, /* 1152x864 @ 89 Hz interlaced, 44 kHz hsync */ { NULL, 89, 1152, 864, 15384, 96, 16, 110, 1, 216, 10, 0, FB_VMODE_INTERLACED }, /* 800x600 @ 72 Hz, 48.0 kHz hsync */ { NULL, 72, 800, 600, 20000, 64, 56, 23, 37, 120, 6, FB_SYNC_HOR_HIGH_ACT | FB_SYNC_VERT_HIGH_ACT, FB_VMODE_NONINTERLACED }, /* 1024x768 @ 60 Hz, 48.4 kHz hsync */ { NULL, 60, 1024, 768, 15384, 168, 8, 29, 3, 144, 6, 0, FB_VMODE_NONINTERLACED }, /* 640x480 @ 100 Hz, 53.01 kHz hsync */ { NULL, 100, 640, 480, 21834, 96, 32, 36, 8, 96, 6, 0, FB_VMODE_NONINTERLACED }, /* 1152x864 @ 60 Hz, 53.5 kHz hsync */ { NULL, 60, 1152, 864, 11123, 208, 64, 16, 4, 256, 8, 0, FB_VMODE_NONINTERLACED }, /* 800x600 @ 85 Hz, 55.84 kHz hsync */ { NULL, 85, 800, 600, 16460, 160, 64, 36, 16, 64, 5, 0, FB_VMODE_NONINTERLACED }, /* 1024x768 @ 70 Hz, 56.5 kHz hsync */ { NULL, 70, 1024, 768, 13333, 144, 24, 29, 3, 136, 6, 0, FB_VMODE_NONINTERLACED }, /* 1280x1024 @ 87 Hz interlaced, 51 kHz hsync */ { NULL, 87, 1280, 1024, 12500, 56, 16, 128, 1, 216, 12, 0, FB_VMODE_INTERLACED }, /* 800x600 @ 100 Hz, 64.02 kHz hsync */ { NULL, 100, 800, 600, 14357, 160, 64, 30, 4, 64, 6, 0, FB_VMODE_NONINTERLACED }, /* 1024x768 @ 76 Hz, 62.5 kHz hsync */ { NULL, 76, 1024, 768, 11764, 208, 8, 36, 16, 120, 3, 0, FB_VMODE_NONINTERLACED }, /* 1152x864 @ 70 Hz, 62.4 kHz hsync */ { NULL, 70, 1152, 864, 10869, 106, 56, 20, 1, 160, 10, 0, FB_VMODE_NONINTERLACED }, /* 1280x1024 @ 61 Hz, 64.2 kHz hsync */ { NULL, 61, 1280, 1024, 9090, 200, 48, 26, 1, 184, 3, 0, FB_VMODE_NONINTERLACED }, /* 1400x1050 @ 60Hz, 63.9 kHz hsync */ { NULL, 60, 1400, 1050, 9259, 136, 40, 13, 1, 112, 3, 0, FB_VMODE_NONINTERLACED }, /* 1400x1050 @ 75,107 Hz, 82,392 kHz +hsync +vsync*/ { NULL, 75, 1400, 1050, 7190, 120, 56, 23, 10, 112, 13, FB_SYNC_HOR_HIGH_ACT | FB_SYNC_VERT_HIGH_ACT, FB_VMODE_NONINTERLACED }, /* 1400x1050 @ 60 Hz, ? kHz +hsync +vsync*/ { NULL, 60, 1400, 1050, 9259, 128, 40, 12, 0, 112, 3, FB_SYNC_HOR_HIGH_ACT | FB_SYNC_VERT_HIGH_ACT, FB_VMODE_NONINTERLACED }, /* 1024x768 @ 85 Hz, 70.24 kHz hsync */ { NULL, 85, 1024, 768, 10111, 192, 32, 34, 14, 160, 6, 0, FB_VMODE_NONINTERLACED }, /* 1152x864 @ 78 Hz, 70.8 kHz hsync */ { NULL, 78, 1152, 864, 9090, 228, 88, 32, 0, 84, 12, 0, FB_VMODE_NONINTERLACED }, /* 1280x1024 @ 70 Hz, 74.59 kHz hsync */ { NULL, 70, 1280, 1024, 7905, 224, 32, 28, 8, 160, 8, 0, FB_VMODE_NONINTERLACED }, /* 1600x1200 @ 60Hz, 75.00 kHz hsync */ { NULL, 60, 1600, 1200, 6172, 304, 64, 46, 1, 192, 3, FB_SYNC_HOR_HIGH_ACT | FB_SYNC_VERT_HIGH_ACT, FB_VMODE_NONINTERLACED }, /* 1152x864 @ 84 Hz, 76.0 kHz hsync */ { NULL, 84, 1152, 864, 7407, 184, 312, 32, 0, 128, 12, 0, FB_VMODE_NONINTERLACED }, /* 1280x1024 @ 74 Hz, 78.85 kHz hsync */ { NULL, 74, 1280, 1024, 7407, 256, 32, 34, 3, 144, 3, 0, FB_VMODE_NONINTERLACED }, /* 1024x768 @ 100Hz, 80.21 kHz hsync */ { NULL, 100, 1024, 768, 8658, 192, 32, 21, 3, 192, 10, 0, FB_VMODE_NONINTERLACED }, /* 1280x1024 @ 76 Hz, 81.13 kHz hsync */ { NULL, 76, 1280, 1024, 7407, 248, 32, 34, 3, 104, 3, 0, FB_VMODE_NONINTERLACED }, /* 1600x1200 @ 70 Hz, 87.50 kHz hsync */ { NULL, 70, 1600, 1200, 5291, 304, 64, 46, 1, 192, 3, 0, FB_VMODE_NONINTERLACED }, /* 1152x864 @ 100 Hz, 89.62 kHz hsync */ { NULL, 100, 1152, 864, 7264, 224, 32, 17, 2, 128, 19, 0, FB_VMODE_NONINTERLACED }, /* 1280x1024 @ 85 Hz, 91.15 kHz hsync */ { NULL, 85, 1280, 1024, 6349, 224, 64, 44, 1, 160, 3, FB_SYNC_HOR_HIGH_ACT | FB_SYNC_VERT_HIGH_ACT, FB_VMODE_NONINTERLACED }, /* 1600x1200 @ 75 Hz, 93.75 kHz hsync */ { NULL, 75, 1600, 1200, 4938, 304, 64, 46, 1, 192, 3, FB_SYNC_HOR_HIGH_ACT | FB_SYNC_VERT_HIGH_ACT, FB_VMODE_NONINTERLACED }, /* 1680x1050 @ 60 Hz, 65.191 kHz hsync */ { NULL, 60, 1680, 1050, 6848, 280, 104, 30, 3, 176, 6, FB_SYNC_HOR_HIGH_ACT | FB_SYNC_VERT_HIGH_ACT, FB_VMODE_NONINTERLACED }, /* 1600x1200 @ 85 Hz, 105.77 kHz hsync */ { NULL, 85, 1600, 1200, 4545, 272, 16, 37, 4, 192, 3, FB_SYNC_HOR_HIGH_ACT | FB_SYNC_VERT_HIGH_ACT, FB_VMODE_NONINTERLACED }, /* 1280x1024 @ 100 Hz, 107.16 kHz hsync */ { NULL, 100, 1280, 1024, 5502, 256, 32, 26, 7, 128, 15, 0, FB_VMODE_NONINTERLACED }, /* 1800x1440 @ 64Hz, 96.15 kHz hsync */ { NULL, 64, 1800, 1440, 4347, 304, 96, 46, 1, 192, 3, FB_SYNC_HOR_HIGH_ACT | FB_SYNC_VERT_HIGH_ACT, FB_VMODE_NONINTERLACED }, /* 1800x1440 @ 70Hz, 104.52 kHz hsync */ { NULL, 70, 1800, 1440, 4000, 304, 96, 46, 1, 192, 3, FB_SYNC_HOR_HIGH_ACT | FB_SYNC_VERT_HIGH_ACT, FB_VMODE_NONINTERLACED }, /* 512x384 @ 78 Hz, 31.50 kHz hsync */ { NULL, 78, 512, 384, 49603, 48, 16, 16, 1, 64, 3, 0, FB_VMODE_NONINTERLACED }, /* 512x384 @ 85 Hz, 34.38 kHz hsync */ { NULL, 85, 512, 384, 45454, 48, 16, 16, 1, 64, 3, 0, FB_VMODE_NONINTERLACED }, /* 320x200 @ 70 Hz, 31.5 kHz hsync, 8:5 aspect ratio */ { NULL, 70, 320, 200, 79440, 16, 16, 20, 4, 48, 1, 0, FB_VMODE_DOUBLE }, /* 320x240 @ 60 Hz, 31.5 kHz hsync, 4:3 aspect ratio */ { NULL, 60, 320, 240, 79440, 16, 16, 16, 5, 48, 1, 0, FB_VMODE_DOUBLE }, /* 320x240 @ 72 Hz, 36.5 kHz hsync */ { NULL, 72, 320, 240, 63492, 16, 16, 16, 4, 48, 2, 0, FB_VMODE_DOUBLE }, /* 400x300 @ 56 Hz, 35.2 kHz hsync, 4:3 aspect ratio */ { NULL, 56, 400, 300, 55555, 64, 16, 10, 1, 32, 1, 0, FB_VMODE_DOUBLE }, /* 400x300 @ 60 Hz, 37.8 kHz hsync */ { NULL, 60, 400, 300, 50000, 48, 16, 11, 1, 64, 2, 0, FB_VMODE_DOUBLE }, /* 400x300 @ 72 Hz, 48.0 kHz hsync */ { NULL, 72, 400, 300, 40000, 32, 24, 11, 19, 64, 3, 0, FB_VMODE_DOUBLE }, /* 480x300 @ 56 Hz, 35.2 kHz hsync, 8:5 aspect ratio */ { NULL, 56, 480, 300, 46176, 80, 16, 10, 1, 40, 1, 0, FB_VMODE_DOUBLE }, /* 480x300 @ 60 Hz, 37.8 kHz hsync */ { NULL, 60, 480, 300, 41858, 56, 16, 11, 1, 80, 2, 0, FB_VMODE_DOUBLE }, /* 480x300 @ 63 Hz, 39.6 kHz hsync */ { NULL, 63, 480, 300, 40000, 56, 16, 11, 1, 80, 2, 0, FB_VMODE_DOUBLE }, /* 480x300 @ 72 Hz, 48.0 kHz hsync */ { NULL, 72, 480, 300, 33386, 40, 24, 11, 19, 80, 3, 0, FB_VMODE_DOUBLE }, /* 1920x1200 @ 60 Hz, 74.5 Khz hsync */ { NULL, 60, 1920, 1200, 5177, 128, 336, 1, 38, 208, 3, FB_SYNC_HOR_HIGH_ACT | FB_SYNC_VERT_HIGH_ACT, FB_VMODE_NONINTERLACED }, /* 1152x768, 60 Hz, PowerBook G4 Titanium I and II */ { NULL, 60, 1152, 768, 14047, 158, 26, 29, 3, 136, 6, FB_SYNC_HOR_HIGH_ACT | FB_SYNC_VERT_HIGH_ACT, FB_VMODE_NONINTERLACED }, /* 1366x768, 60 Hz, 47.403 kHz hsync, WXGA 16:9 aspect ratio */ { NULL, 60, 1366, 768, 13806, 120, 10, 14, 3, 32, 5, 0, FB_VMODE_NONINTERLACED }, /* 1280x800, 60 Hz, 47.403 kHz hsync, WXGA 16:10 aspect ratio */ { NULL, 60, 1280, 800, 12048, 200, 64, 24, 1, 136, 3, 0, FB_VMODE_NONINTERLACED }, /* 720x576i @ 50 Hz, 15.625 kHz hsync (PAL RGB) */ { NULL, 50, 720, 576, 74074, 64, 16, 39, 5, 64, 5, 0, FB_VMODE_INTERLACED }, /* 800x520i @ 50 Hz, 15.625 kHz hsync (PAL RGB) */ { NULL, 50, 800, 520, 58823, 144, 64, 72, 28, 80, 5, 0, FB_VMODE_INTERLACED }, /* 864x480 @ 60 Hz, 35.15 kHz hsync */ { NULL, 60, 864, 480, 27777, 1, 1, 1, 1, 0, 0, 0, FB_VMODE_NONINTERLACED }, }; #ifdef CONFIG_FB_MODE_HELPERS const struct fb_videomode cea_modes[64] = { /* #1: 640x480p@59.94/60Hz */ [1] = { NULL, 60, 640, 480, 39722, 48, 16, 33, 10, 96, 2, 0, FB_VMODE_NONINTERLACED, 0, }, /* #3: 720x480p@59.94/60Hz */ [3] = { NULL, 60, 720, 480, 37037, 60, 16, 30, 9, 62, 6, 0, FB_VMODE_NONINTERLACED, 0, }, /* #5: 1920x1080i@59.94/60Hz */ [5] = { NULL, 60, 1920, 1080, 13763, 148, 88, 15, 2, 44, 5, FB_SYNC_HOR_HIGH_ACT | FB_SYNC_VERT_HIGH_ACT, FB_VMODE_INTERLACED, 0, }, /* #7: 720(1440)x480iH@59.94/60Hz */ [7] = { NULL, 60, 1440, 480, 18554/*37108*/, 114, 38, 15, 4, 124, 3, 0, FB_VMODE_INTERLACED, 0, }, /* #9: 720(1440)x240pH@59.94/60Hz */ [9] = { NULL, 60, 1440, 240, 18554, 114, 38, 16, 4, 124, 3, 0, FB_VMODE_NONINTERLACED, 0, }, /* #18: 720x576pH@50Hz */ [18] = { NULL, 50, 720, 576, 37037, 68, 12, 39, 5, 64, 5, 0, FB_VMODE_NONINTERLACED, 0, }, /* #19: 1280x720p@50Hz */ [19] = { NULL, 50, 1280, 720, 13468, 220, 440, 20, 5, 40, 5, FB_SYNC_HOR_HIGH_ACT | FB_SYNC_VERT_HIGH_ACT, FB_VMODE_NONINTERLACED, 0, }, /* #20: 1920x1080i@50Hz */ [20] = { NULL, 50, 1920, 1080, 13480, 148, 528, 15, 5, 528, 5, FB_SYNC_HOR_HIGH_ACT | FB_SYNC_VERT_HIGH_ACT, FB_VMODE_INTERLACED, 0, }, /* #32: 1920x1080p@23.98/24Hz */ [32] = { NULL, 24, 1920, 1080, 13468, 148, 638, 36, 4, 44, 5, FB_SYNC_HOR_HIGH_ACT | FB_SYNC_VERT_HIGH_ACT, FB_VMODE_NONINTERLACED, 0, }, /* #35: (2880)x480p4x@59.94/60Hz */ [35] = { NULL, 60, 2880, 480, 9250, 240, 64, 30, 9, 248, 6, 0, FB_VMODE_NONINTERLACED, 0, }, }; const struct fb_videomode vesa_modes[] = { /* 0 640x350-85 VESA */ { NULL, 85, 640, 350, 31746, 96, 32, 60, 32, 64, 3, FB_SYNC_HOR_HIGH_ACT, FB_VMODE_NONINTERLACED, FB_MODE_IS_VESA}, /* 1 640x400-85 VESA */ { NULL, 85, 640, 400, 31746, 96, 32, 41, 01, 64, 3, FB_SYNC_VERT_HIGH_ACT, FB_VMODE_NONINTERLACED, FB_MODE_IS_VESA }, /* 2 720x400-85 VESA */ { NULL, 85, 721, 400, 28169, 108, 36, 42, 01, 72, 3, FB_SYNC_VERT_HIGH_ACT, FB_VMODE_NONINTERLACED, FB_MODE_IS_VESA }, /* 3 640x480-60 VESA */ { NULL, 60, 640, 480, 39682, 48, 16, 33, 10, 96, 2, 0, FB_VMODE_NONINTERLACED, FB_MODE_IS_VESA }, /* 4 640x480-72 VESA */ { NULL, 72, 640, 480, 31746, 128, 24, 29, 9, 40, 2, 0, FB_VMODE_NONINTERLACED, FB_MODE_IS_VESA }, /* 5 640x480-75 VESA */ { NULL, 75, 640, 480, 31746, 120, 16, 16, 01, 64, 3, 0, FB_VMODE_NONINTERLACED, FB_MODE_IS_VESA }, /* 6 640x480-85 VESA */ { NULL, 85, 640, 480, 27777, 80, 56, 25, 01, 56, 3, 0, FB_VMODE_NONINTERLACED, FB_MODE_IS_VESA }, /* 7 800x600-56 VESA */ { NULL, 56, 800, 600, 27777, 128, 24, 22, 01, 72, 2, FB_SYNC_HOR_HIGH_ACT | FB_SYNC_VERT_HIGH_ACT, FB_VMODE_NONINTERLACED, FB_MODE_IS_VESA }, /* 8 800x600-60 VESA */ { NULL, 60, 800, 600, 25000, 88, 40, 23, 01, 128, 4, FB_SYNC_HOR_HIGH_ACT | FB_SYNC_VERT_HIGH_ACT, FB_VMODE_NONINTERLACED, FB_MODE_IS_VESA }, /* 9 800x600-72 VESA */ { NULL, 72, 800, 600, 20000, 64, 56, 23, 37, 120, 6, FB_SYNC_HOR_HIGH_ACT | FB_SYNC_VERT_HIGH_ACT, FB_VMODE_NONINTERLACED, FB_MODE_IS_VESA }, /* 10 800x600-75 VESA */ { NULL, 75, 800, 600, 20202, 160, 16, 21, 01, 80, 3, FB_SYNC_HOR_HIGH_ACT | FB_SYNC_VERT_HIGH_ACT, FB_VMODE_NONINTERLACED, FB_MODE_IS_VESA }, /* 11 800x600-85 VESA */ { NULL, 85, 800, 600, 17761, 152, 32, 27, 01, 64, 3, FB_SYNC_HOR_HIGH_ACT | FB_SYNC_VERT_HIGH_ACT, FB_VMODE_NONINTERLACED, FB_MODE_IS_VESA }, /* 12 1024x768i-43 VESA */ { NULL, 43, 1024, 768, 22271, 56, 8, 41, 0, 176, 8, FB_SYNC_HOR_HIGH_ACT | FB_SYNC_VERT_HIGH_ACT, FB_VMODE_INTERLACED, FB_MODE_IS_VESA }, /* 13 1024x768-60 VESA */ { NULL, 60, 1024, 768, 15384, 160, 24, 29, 3, 136, 6, 0, FB_VMODE_NONINTERLACED, FB_MODE_IS_VESA }, /* 14 1024x768-70 VESA */ { NULL, 70, 1024, 768, 13333, 144, 24, 29, 3, 136, 6, 0, FB_VMODE_NONINTERLACED, FB_MODE_IS_VESA }, /* 15 1024x768-75 VESA */ { NULL, 75, 1024, 768, 12690, 176, 16, 28, 1, 96, 3, FB_SYNC_HOR_HIGH_ACT | FB_SYNC_VERT_HIGH_ACT, FB_VMODE_NONINTERLACED, FB_MODE_IS_VESA }, /* 16 1024x768-85 VESA */ { NULL, 85, 1024, 768, 10582, 208, 48, 36, 1, 96, 3, FB_SYNC_HOR_HIGH_ACT | FB_SYNC_VERT_HIGH_ACT, FB_VMODE_NONINTERLACED, FB_MODE_IS_VESA }, /* 17 1152x864-75 VESA */ { NULL, 75, 1152, 864, 9259, 256, 64, 32, 1, 128, 3, FB_SYNC_HOR_HIGH_ACT | FB_SYNC_VERT_HIGH_ACT, FB_VMODE_NONINTERLACED, FB_MODE_IS_VESA }, /* 18 1280x960-60 VESA */ { NULL, 60, 1280, 960, 9259, 312, 96, 36, 1, 112, 3, FB_SYNC_HOR_HIGH_ACT | FB_SYNC_VERT_HIGH_ACT, FB_VMODE_NONINTERLACED, FB_MODE_IS_VESA }, /* 19 1280x960-85 VESA */ { NULL, 85, 1280, 960, 6734, 224, 64, 47, 1, 160, 3, FB_SYNC_HOR_HIGH_ACT | FB_SYNC_VERT_HIGH_ACT, FB_VMODE_NONINTERLACED, FB_MODE_IS_VESA }, /* 20 1280x1024-60 VESA */ { NULL, 60, 1280, 1024, 9259, 248, 48, 38, 1, 112, 3, FB_SYNC_HOR_HIGH_ACT | FB_SYNC_VERT_HIGH_ACT, FB_VMODE_NONINTERLACED, FB_MODE_IS_VESA }, /* 21 1280x1024-75 VESA */ { NULL, 75, 1280, 1024, 7407, 248, 16, 38, 1, 144, 3, FB_SYNC_HOR_HIGH_ACT | FB_SYNC_VERT_HIGH_ACT, FB_VMODE_NONINTERLACED, FB_MODE_IS_VESA }, /* 22 1280x1024-85 VESA */ { NULL, 85, 1280, 1024, 6349, 224, 64, 44, 1, 160, 3, FB_SYNC_HOR_HIGH_ACT | FB_SYNC_VERT_HIGH_ACT, FB_VMODE_NONINTERLACED, FB_MODE_IS_VESA }, /* 23 1600x1200-60 VESA */ { NULL, 60, 1600, 1200, 6172, 304, 64, 46, 1, 192, 3, FB_SYNC_HOR_HIGH_ACT | FB_SYNC_VERT_HIGH_ACT, FB_VMODE_NONINTERLACED, FB_MODE_IS_VESA }, /* 24 1600x1200-65 VESA */ { NULL, 65, 1600, 1200, 5698, 304, 64, 46, 1, 192, 3, FB_SYNC_HOR_HIGH_ACT | FB_SYNC_VERT_HIGH_ACT, FB_VMODE_NONINTERLACED, FB_MODE_IS_VESA }, /* 25 1600x1200-70 VESA */ { NULL, 70, 1600, 1200, 5291, 304, 64, 46, 1, 192, 3, FB_SYNC_HOR_HIGH_ACT | FB_SYNC_VERT_HIGH_ACT, FB_VMODE_NONINTERLACED, FB_MODE_IS_VESA }, /* 26 1600x1200-75 VESA */ { NULL, 75, 1600, 1200, 4938, 304, 64, 46, 1, 192, 3, FB_SYNC_HOR_HIGH_ACT | FB_SYNC_VERT_HIGH_ACT, FB_VMODE_NONINTERLACED, FB_MODE_IS_VESA }, /* 27 1600x1200-85 VESA */ { NULL, 85, 1600, 1200, 4357, 304, 64, 46, 1, 192, 3, FB_SYNC_HOR_HIGH_ACT | FB_SYNC_VERT_HIGH_ACT, FB_VMODE_NONINTERLACED, FB_MODE_IS_VESA }, /* 28 1792x1344-60 VESA */ { NULL, 60, 1792, 1344, 4882, 328, 128, 46, 1, 200, 3, FB_SYNC_VERT_HIGH_ACT, FB_VMODE_NONINTERLACED, FB_MODE_IS_VESA }, /* 29 1792x1344-75 VESA */ { NULL, 75, 1792, 1344, 3831, 352, 96, 69, 1, 216, 3, FB_SYNC_VERT_HIGH_ACT, FB_VMODE_NONINTERLACED, FB_MODE_IS_VESA }, /* 30 1856x1392-60 VESA */ { NULL, 60, 1856, 1392, 4580, 352, 96, 43, 1, 224, 3, FB_SYNC_VERT_HIGH_ACT, FB_VMODE_NONINTERLACED, FB_MODE_IS_VESA }, /* 31 1856x1392-75 VESA */ { NULL, 75, 1856, 1392, 3472, 352, 128, 104, 1, 224, 3, FB_SYNC_VERT_HIGH_ACT, FB_VMODE_NONINTERLACED, FB_MODE_IS_VESA }, /* 32 1920x1440-60 VESA */ { NULL, 60, 1920, 1440, 4273, 344, 128, 56, 1, 200, 3, FB_SYNC_VERT_HIGH_ACT, FB_VMODE_NONINTERLACED, FB_MODE_IS_VESA }, /* 33 1920x1440-75 VESA */ { NULL, 75, 1920, 1440, 3367, 352, 144, 56, 1, 224, 3, FB_SYNC_VERT_HIGH_ACT, FB_VMODE_NONINTERLACED, FB_MODE_IS_VESA }, /* 34 1920x1200-60 RB VESA */ { NULL, 60, 1920, 1200, 6493, 80, 48, 26, 3, 32, 6, FB_SYNC_VERT_HIGH_ACT, FB_VMODE_NONINTERLACED, FB_MODE_IS_VESA }, /* 35 1920x1200-60 VESA */ { NULL, 60, 1920, 1200, 5174, 336, 136, 36, 3, 200, 6, FB_SYNC_VERT_HIGH_ACT, FB_VMODE_NONINTERLACED, FB_MODE_IS_VESA }, /* 36 1920x1200-75 VESA */ { NULL, 75, 1920, 1200, 4077, 344, 136, 46, 3, 208, 6, FB_SYNC_VERT_HIGH_ACT, FB_VMODE_NONINTERLACED, FB_MODE_IS_VESA }, /* 37 1920x1200-85 VESA */ { NULL, 85, 1920, 1200, 3555, 352, 144, 53, 3, 208, 6, FB_SYNC_VERT_HIGH_ACT, FB_VMODE_NONINTERLACED, FB_MODE_IS_VESA }, /* 38 2560x1600-60 RB VESA */ { NULL, 60, 2560, 1600, 3724, 80, 48, 37, 3, 32, 6, FB_SYNC_HOR_HIGH_ACT, FB_VMODE_NONINTERLACED, FB_MODE_IS_VESA }, /* 39 2560x1600-60 VESA */ { NULL, 60, 2560, 1600, 2869, 472, 192, 49, 3, 280, 6, FB_SYNC_VERT_HIGH_ACT, FB_VMODE_NONINTERLACED, FB_MODE_IS_VESA }, /* 40 2560x1600-75 VESA */ { NULL, 75, 2560, 1600, 2256, 488, 208, 63, 3, 280, 6, FB_SYNC_VERT_HIGH_ACT, FB_VMODE_NONINTERLACED, FB_MODE_IS_VESA }, /* 41 2560x1600-85 VESA */ { NULL, 85, 2560, 1600, 1979, 488, 208, 73, 3, 280, 6, FB_SYNC_VERT_HIGH_ACT, FB_VMODE_NONINTERLACED, FB_MODE_IS_VESA }, /* 42 2560x1600-120 RB VESA */ { NULL, 120, 2560, 1600, 1809, 80, 48, 85, 3, 32, 6, FB_SYNC_HOR_HIGH_ACT, FB_VMODE_NONINTERLACED, FB_MODE_IS_VESA }, /* 43 1360x768-60 VESA */ { NULL, 60, 1360, 768, 11695, 256, 64, 18, 3, 112, 6, FB_SYNC_HOR_HIGH_ACT | FB_SYNC_VERT_HIGH_ACT, FB_VMODE_NONINTERLACED, FB_MODE_IS_VESA }, /* 44 1366x768-60 VESA */ { NULL, 60, 1366, 768, 11695, 213, 70, 24, 3, 143, 3, FB_SYNC_HOR_HIGH_ACT | FB_SYNC_VERT_HIGH_ACT, FB_VMODE_NONINTERLACED, FB_MODE_IS_VESA }, /* 45 1440x900-60 VESA */ { NULL, 60, 1440, 900, 9389, 232, 80, 25, 3, 152, 6, FB_SYNC_VERT_HIGH_ACT, FB_VMODE_NONINTERLACED, FB_MODE_IS_VESA }, /* 46 1600x900-60 VESA */ { NULL, 60, 1600, 900, 9259, 96, 24, 96, 1, 80, 3, FB_SYNC_VERT_HIGH_ACT, FB_VMODE_NONINTERLACED, FB_MODE_IS_VESA }, /* 47 1680x1050-60 VESA */ { NULL, 60, 1680, 1050, 6837, 280, 104, 30, 3, 176, 6, FB_SYNC_VERT_HIGH_ACT, FB_VMODE_NONINTERLACED, FB_MODE_IS_VESA }, }; EXPORT_SYMBOL(vesa_modes); #endif /* CONFIG_FB_MODE_HELPERS */ /** * fb_try_mode - test a video mode * @var: frame buffer user defined part of display * @info: frame buffer info structure * @mode: frame buffer video mode structure * @bpp: color depth in bits per pixel * * Tries a video mode to test it's validity for device @info. * * Returns 1 on success. * */ static int fb_try_mode(struct fb_var_screeninfo *var, struct fb_info *info, const struct fb_videomode *mode, unsigned int bpp) { int err = 0; DPRINTK("Trying mode %s %dx%d-%d@%d\n", mode->name ? mode->name : "noname", mode->xres, mode->yres, bpp, mode->refresh); var->xres = mode->xres; var->yres = mode->yres; var->xres_virtual = mode->xres; var->yres_virtual = mode->yres; var->xoffset = 0; var->yoffset = 0; var->bits_per_pixel = bpp; var->activate |= FB_ACTIVATE_TEST; var->pixclock = mode->pixclock; var->left_margin = mode->left_margin; var->right_margin = mode->right_margin; var->upper_margin = mode->upper_margin; var->lower_margin = mode->lower_margin; var->hsync_len = mode->hsync_len; var->vsync_len = mode->vsync_len; var->sync = mode->sync; var->vmode = mode->vmode; if (info->fbops->fb_check_var) err = info->fbops->fb_check_var(var, info); var->activate &= ~FB_ACTIVATE_TEST; return err; } /** * fb_find_mode - finds a valid video mode * @var: frame buffer user defined part of display * @info: frame buffer info structure * @mode_option: string video mode to find * @db: video mode database * @dbsize: size of @db * @default_mode: default video mode to fall back to * @default_bpp: default color depth in bits per pixel * * Finds a suitable video mode, starting with the specified mode * in @mode_option with fallback to @default_mode. If * @default_mode fails, all modes in the video mode database will * be tried. * * Valid mode specifiers for @mode_option: * * <xres>x<yres>[M][R][-<bpp>][@<refresh>][i][m] or * <name>[-<bpp>][@<refresh>] * * with <xres>, <yres>, <bpp> and <refresh> decimal numbers and * <name> a string. * * If 'M' is present after yres (and before refresh/bpp if present), * the function will compute the timings using VESA(tm) Coordinated * Video Timings (CVT). If 'R' is present after 'M', will compute with * reduced blanking (for flatpanels). If 'i' is present, compute * interlaced mode. If 'm' is present, add margins equal to 1.8% * of xres rounded down to 8 pixels, and 1.8% of yres. The char * 'i' and 'm' must be after 'M' and 'R'. Example: * * 1024x768MR-8@60m - Reduced blank with margins at 60Hz. * * NOTE: The passed struct @var is _not_ cleared! This allows you * to supply values for e.g. the grayscale and accel_flags fields. * * Returns zero for failure, 1 if using specified @mode_option, * 2 if using specified @mode_option with an ignored refresh rate, * 3 if default mode is used, 4 if fall back to any valid mode. * */ int fb_find_mode(struct fb_var_screeninfo *var, struct fb_info *info, const char *mode_option, const struct fb_videomode *db, unsigned int dbsize, const struct fb_videomode *default_mode, unsigned int default_bpp) { int i; /* Set up defaults */ if (!db) { db = modedb; dbsize = ARRAY_SIZE(modedb); } if (!default_mode) default_mode = &db[0]; if (!default_bpp) default_bpp = 8; /* Did the user specify a video mode? */ if (!mode_option) mode_option = fb_mode_option; if (mode_option) { const char *name = mode_option; unsigned int namelen = strlen(name); int res_specified = 0, bpp_specified = 0, refresh_specified = 0; unsigned int xres = 0, yres = 0, bpp = default_bpp, refresh = 0; int yres_specified = 0, cvt = 0, rb = 0, interlace = 0; int margins = 0; u32 best, diff, tdiff; for (i = namelen-1; i >= 0; i--) { switch (name[i]) { case '@': namelen = i; if (!refresh_specified && !bpp_specified && !yres_specified) { refresh = simple_strtol(&name[i+1], NULL, 10); refresh_specified = 1; if (cvt || rb) cvt = 0; } else goto done; break; case '-': namelen = i; if (!bpp_specified && !yres_specified) { bpp = simple_strtol(&name[i+1], NULL, 10); bpp_specified = 1; if (cvt || rb) cvt = 0; } else goto done; break; case 'x': if (!yres_specified) { yres = simple_strtol(&name[i+1], NULL, 10); yres_specified = 1; } else goto done; break; case '0' ... '9': break; case 'M': if (!yres_specified) cvt = 1; break; case 'R': if (!cvt) rb = 1; break; case 'm': if (!cvt) margins = 1; break; case 'i': if (!cvt) interlace = 1; break; default: goto done; } } if (i < 0 && yres_specified) { xres = simple_strtol(name, NULL, 10); res_specified = 1; } done: if (cvt) { struct fb_videomode cvt_mode; int ret; DPRINTK("CVT mode %dx%d@%dHz%s%s%s\n", xres, yres, (refresh) ? refresh : 60, (rb) ? " reduced blanking" : "", (margins) ? " with margins" : "", (interlace) ? " interlaced" : ""); memset(&cvt_mode, 0, sizeof(cvt_mode)); cvt_mode.xres = xres; cvt_mode.yres = yres; cvt_mode.refresh = (refresh) ? refresh : 60; if (interlace) cvt_mode.vmode |= FB_VMODE_INTERLACED; else cvt_mode.vmode &= ~FB_VMODE_INTERLACED; ret = fb_find_mode_cvt(&cvt_mode, margins, rb); if (!ret && !fb_try_mode(var, info, &cvt_mode, bpp)) { DPRINTK("modedb CVT: CVT mode ok\n"); return 1; } DPRINTK("CVT mode invalid, getting mode from database\n"); } DPRINTK("Trying specified video mode%s %ix%i\n", refresh_specified ? "" : " (ignoring refresh rate)", xres, yres); if (!refresh_specified) { /* * If the caller has provided a custom mode database and * a valid monspecs structure, we look for the mode with * the highest refresh rate. Otherwise we play it safe * it and try to find a mode with a refresh rate closest * to the standard 60 Hz. */ if (db != modedb && info->monspecs.vfmin && info->monspecs.vfmax && info->monspecs.hfmin && info->monspecs.hfmax && info->monspecs.dclkmax) { refresh = 1000; } else { refresh = 60; } } diff = -1; best = -1; for (i = 0; i < dbsize; i++) { if ((name_matches(db[i], name, namelen) || (res_specified && res_matches(db[i], xres, yres))) && !fb_try_mode(var, info, &db[i], bpp)) { if (refresh_specified && db[i].refresh == refresh) return 1; if (abs(db[i].refresh - refresh) < diff) { diff = abs(db[i].refresh - refresh); best = i; } } } if (best != -1) { fb_try_mode(var, info, &db[best], bpp); return (refresh_specified) ? 2 : 1; } diff = 2 * (xres + yres); best = -1; DPRINTK("Trying best-fit modes\n"); for (i = 0; i < dbsize; i++) { DPRINTK("Trying %ix%i\n", db[i].xres, db[i].yres); if (!fb_try_mode(var, info, &db[i], bpp)) { tdiff = abs(db[i].xres - xres) + abs(db[i].yres - yres); /* * Penalize modes with resolutions smaller * than requested. */ if (xres > db[i].xres || yres > db[i].yres) tdiff += xres + yres; if (diff > tdiff) { diff = tdiff; best = i; } } } if (best != -1) { fb_try_mode(var, info, &db[best], bpp); return 5; } } DPRINTK("Trying default video mode\n"); if (!fb_try_mode(var, info, default_mode, default_bpp)) return 3; DPRINTK("Trying all modes\n"); for (i = 0; i < dbsize; i++) if (!fb_try_mode(var, info, &db[i], default_bpp)) return 4; DPRINTK("No valid mode found\n"); return 0; } /** * fb_var_to_videomode - convert fb_var_screeninfo to fb_videomode * @mode: pointer to struct fb_videomode * @var: pointer to struct fb_var_screeninfo */ void fb_var_to_videomode(struct fb_videomode *mode, const struct fb_var_screeninfo *var) { u32 pixclock, hfreq, htotal, vtotal; mode->name = NULL; mode->xres = var->xres; mode->yres = var->yres; mode->pixclock = var->pixclock; mode->hsync_len = var->hsync_len; mode->vsync_len = var->vsync_len; mode->left_margin = var->left_margin; mode->right_margin = var->right_margin; mode->upper_margin = var->upper_margin; mode->lower_margin = var->lower_margin; mode->sync = var->sync; mode->vmode = var->vmode & FB_VMODE_MASK; mode->flag = FB_MODE_IS_FROM_VAR; mode->refresh = 0; if (!var->pixclock) return; pixclock = PICOS2KHZ(var->pixclock) * 1000; htotal = var->xres + var->right_margin + var->hsync_len + var->left_margin; vtotal = var->yres + var->lower_margin + var->vsync_len + var->upper_margin; if (var->vmode & FB_VMODE_INTERLACED) vtotal /= 2; if (var->vmode & FB_VMODE_DOUBLE) vtotal *= 2; hfreq = pixclock/htotal; mode->refresh = hfreq/vtotal; } /** * fb_videomode_to_var - convert fb_videomode to fb_var_screeninfo * @var: pointer to struct fb_var_screeninfo * @mode: pointer to struct fb_videomode */ void fb_videomode_to_var(struct fb_var_screeninfo *var, const struct fb_videomode *mode) { var->xres = mode->xres; var->yres = mode->yres; var->xres_virtual = mode->xres; var->yres_virtual = mode->yres; var->xoffset = 0; var->yoffset = 0; var->pixclock = mode->pixclock; var->left_margin = mode->left_margin; var->right_margin = mode->right_margin; var->upper_margin = mode->upper_margin; var->lower_margin = mode->lower_margin; var->hsync_len = mode->hsync_len; var->vsync_len = mode->vsync_len; var->sync = mode->sync; var->vmode = mode->vmode & FB_VMODE_MASK; } /** * fb_mode_is_equal - compare 2 videomodes * @mode1: first videomode * @mode2: second videomode * * RETURNS: * 1 if equal, 0 if not */ int fb_mode_is_equal(const struct fb_videomode *mode1, const struct fb_videomode *mode2) { return (mode1->xres == mode2->xres && mode1->yres == mode2->yres && mode1->pixclock == mode2->pixclock && mode1->hsync_len == mode2->hsync_len && mode1->vsync_len == mode2->vsync_len && mode1->left_margin == mode2->left_margin && mode1->right_margin == mode2->right_margin && mode1->upper_margin == mode2->upper_margin && mode1->lower_margin == mode2->lower_margin && mode1->sync == mode2->sync && mode1->vmode == mode2->vmode); } /** * fb_find_best_mode - find best matching videomode * @var: pointer to struct fb_var_screeninfo * @head: pointer to struct list_head of modelist * * RETURNS: * struct fb_videomode, NULL if none found * * IMPORTANT: * This function assumes that all modelist entries in * info->modelist are valid. * * NOTES: * Finds best matching videomode which has an equal or greater dimension than * var->xres and var->yres. If more than 1 videomode is found, will return * the videomode with the highest refresh rate */ const struct fb_videomode *fb_find_best_mode(const struct fb_var_screeninfo *var, struct list_head *head) { struct list_head *pos; struct fb_modelist *modelist; struct fb_videomode *mode, *best = NULL; u32 diff = -1; list_for_each(pos, head) { u32 d; modelist = list_entry(pos, struct fb_modelist, list); mode = &modelist->mode; if (mode->xres >= var->xres && mode->yres >= var->yres) { d = (mode->xres - var->xres) + (mode->yres - var->yres); if (diff > d) { diff = d; best = mode; } else if (diff == d && best && mode->refresh > best->refresh) best = mode; } } return best; } /** * fb_find_nearest_mode - find closest videomode * * @mode: pointer to struct fb_videomode * @head: pointer to modelist * * Finds best matching videomode, smaller or greater in dimension. * If more than 1 videomode is found, will return the videomode with * the closest refresh rate. */ const struct fb_videomode *fb_find_nearest_mode(const struct fb_videomode *mode, struct list_head *head) { struct list_head *pos; struct fb_modelist *modelist; struct fb_videomode *cmode, *best = NULL; u32 diff = -1, diff_refresh = -1; list_for_each(pos, head) { u32 d; modelist = list_entry(pos, struct fb_modelist, list); cmode = &modelist->mode; d = abs(cmode->xres - mode->xres) + abs(cmode->yres - mode->yres); if (diff > d) { diff = d; diff_refresh = abs(cmode->refresh - mode->refresh); best = cmode; } else if (diff == d) { d = abs(cmode->refresh - mode->refresh); if (diff_refresh > d) { diff_refresh = d; best = cmode; } } } return best; } /** * fb_match_mode - find a videomode which exactly matches the timings in var * @var: pointer to struct fb_var_screeninfo * @head: pointer to struct list_head of modelist * * RETURNS: * struct fb_videomode, NULL if none found */ const struct fb_videomode *fb_match_mode(const struct fb_var_screeninfo *var, struct list_head *head) { struct list_head *pos; struct fb_modelist *modelist; struct fb_videomode *m, mode; fb_var_to_videomode(&mode, var); list_for_each(pos, head) { modelist = list_entry(pos, struct fb_modelist, list); m = &modelist->mode; if (fb_mode_is_equal(m, &mode)) return m; } return NULL; } /** * fb_add_videomode - adds videomode entry to modelist * @mode: videomode to add * @head: struct list_head of modelist * * NOTES: * Will only add unmatched mode entries */ int fb_add_videomode(const struct fb_videomode *mode, struct list_head *head) { struct list_head *pos; struct fb_modelist *modelist; struct fb_videomode *m; int found = 0; list_for_each(pos, head) { modelist = list_entry(pos, struct fb_modelist, list); m = &modelist->mode; if (fb_mode_is_equal(m, mode)) { found = 1; break; } } if (!found) { modelist = kmalloc(sizeof(struct fb_modelist), GFP_KERNEL); if (!modelist) return -ENOMEM; modelist->mode = *mode; list_add(&modelist->list, head); } return 0; } /** * fb_delete_videomode - removed videomode entry from modelist * @mode: videomode to remove * @head: struct list_head of modelist * * NOTES: * Will remove all matching mode entries */ void fb_delete_videomode(const struct fb_videomode *mode, struct list_head *head) { struct list_head *pos, *n; struct fb_modelist *modelist; struct fb_videomode *m; list_for_each_safe(pos, n, head) { modelist = list_entry(pos, struct fb_modelist, list); m = &modelist->mode; if (fb_mode_is_equal(m, mode)) { list_del(pos); kfree(pos); } } } /** * fb_destroy_modelist - destroy modelist * @head: struct list_head of modelist */ void fb_destroy_modelist(struct list_head *head) { struct list_head *pos, *n; list_for_each_safe(pos, n, head) { list_del(pos); kfree(pos); } } EXPORT_SYMBOL_GPL(fb_destroy_modelist); /** * fb_videomode_to_modelist - convert mode array to mode list * @modedb: array of struct fb_videomode * @num: number of entries in array * @head: struct list_head of modelist */ void fb_videomode_to_modelist(const struct fb_videomode *modedb, int num, struct list_head *head) { int i; INIT_LIST_HEAD(head); for (i = 0; i < num; i++) { if (fb_add_videomode(&modedb[i], head)) return; } } const struct fb_videomode *fb_find_best_display(const struct fb_monspecs *specs, struct list_head *head) { struct list_head *pos; struct fb_modelist *modelist; const struct fb_videomode *m, *m1 = NULL, *md = NULL, *best = NULL; int first = 0; if (!head->prev || !head->next || list_empty(head)) goto finished; /* get the first detailed mode and the very first mode */ list_for_each(pos, head) { modelist = list_entry(pos, struct fb_modelist, list); m = &modelist->mode; if (!first) { m1 = m; first = 1; } if (m->flag & FB_MODE_IS_FIRST) { md = m; break; } } /* first detailed timing is preferred */ if (specs->misc & FB_MISC_1ST_DETAIL) { best = md; goto finished; } /* find best mode based on display width and height */ if (specs->max_x && specs->max_y) { struct fb_var_screeninfo var; memset(&var, 0, sizeof(struct fb_var_screeninfo)); var.xres = (specs->max_x * 7200)/254; var.yres = (specs->max_y * 7200)/254; m = fb_find_best_mode(&var, head); if (m) { best = m; goto finished; } } /* use first detailed mode */ if (md) { best = md; goto finished; } /* last resort, use the very first mode */ best = m1; finished: return best; } EXPORT_SYMBOL(fb_find_best_display); EXPORT_SYMBOL(fb_videomode_to_var); EXPORT_SYMBOL(fb_var_to_videomode); EXPORT_SYMBOL(fb_mode_is_equal); EXPORT_SYMBOL(fb_add_videomode); EXPORT_SYMBOL(fb_match_mode); EXPORT_SYMBOL(fb_find_best_mode); EXPORT_SYMBOL(fb_find_nearest_mode); EXPORT_SYMBOL(fb_videomode_to_modelist); EXPORT_SYMBOL(fb_find_mode); EXPORT_SYMBOL(fb_find_mode_cvt);
geekboxzone/mmallow_kernel
drivers/video/modedb.c
C
gpl-2.0
35,482
#ifndef CONDPARSER_H #define CONDPARSER_H /** * Copyright (C) 1997-2015 by Dimitri van Heesch. * * Permission to use, copy, modify, and distribute this software and its * documentation under the terms of the GNU General Public License is hereby * granted. No representations are made about the suitability of this software * for any purpose. It is provided "as is" without express or implied warranty. * See the GNU General Public License for more details. * * Documents produced by Doxygen are derivative works derived from the * input used in their production; they are not affected by this license. * * C++ Expression parser for ENABLED_SECTIONS in Doxygen * * Features used: * Operators: * && AND operator * || OR operator * ! NOT operator */ #include <qcstring.h> class CondParser { // public functions public: CondParser() : m_e(0), m_tokenType(NOTHING) {} bool parse(const char *fileName,int lineNr,const char *expr); // enumerations private: enum TOKENTYPE { NOTHING = -1, DELIMITER, VARIABLE, UNKNOWN }; enum OPERATOR_ID { UNKNOWN_OP = -1, AND = 1, OR, NOT }; // data private: QCString m_err; //!< error state QCString m_expr; //!< holds the expression const char *m_e; //!< points to a character in expr QCString m_token; //!< holds the token TOKENTYPE m_tokenType; //!< type of the token // private functions private: void getToken(); bool parseLevel1(); bool parseLevel2(); bool parseLevel3(); bool parseVar(); bool evalOperator(const int opId, bool lhs, bool rhs); bool evalVariable(const char *varName); int getOperatorId(const QCString &opName); }; #endif
ktd2004/doxygen
src/condparser.h
C
gpl-2.0
1,866
/***************************************************************** * SQUID - a library of functions for biological sequence analysis * Copyright (C) 1992-2002 Washington University School of Medicine * * This source code is freely distributed under the terms of the * GNU General Public License. See the files COPYRIGHT and LICENSE * for details. *****************************************************************/ /* seqencode.c * * Routines for creating and manipulating encoded sequence strings. * RCS $Id: seqencode.c,v 1.3 1999/05/02 21:55:27 eddy Exp $ */ #include <stdio.h> #include <string.h> #include <ctype.h> #include "squid.h" #ifdef MEMDEBUG #include "dbmalloc.h" #endif /* seqcmp() returns 0 if s1 == s2 mismatch number otherwise */ int seqcmp(char *s1, char *s2, int allow) { int mmat = 0; while ((*s1 != NTEND) && (*s2 != NTEND) && (mmat <= allow)) { if (!(ntmatch(*s1, *s2))) mmat++;; s1++; s2++; } while ((*s1++ != NTEND) && (mmat <= allow)) mmat++; return(mmat); } /* seqncmp() same as seqcmp but it looks at, at most, n positions */ int seqncmp(char *s1, char *s2, int n, int allow) { int mmat = 0; while ((*s2 != NTEND) && (n-- != 0)) { if ((!(ntmatch(*s1, *s2))) && (++mmat > allow)) return(mmat); s1++; s2++; } while ((n-- != 0) && (*s1++ != NTEND) && (mmat <= allow)) mmat++; return (mmat); } /* seqencode() given a character text string str (A,C,G,T), convert to an encoded seq string; return 1 for success, 0 if fail */ int seqencode(char *codeseq, /* pre-allocated space for answer */ char *str) /* character string to convert */ { char *ptr; int idx; ptr = codeseq; while (*str != '\0') { if (islower((int) (*str))) *str = (char) toupper((int) (*str)); for (idx = 0; *str != iupac[idx].sym && idx <= IUPACSYMNUM; idx++) ; if (idx > IUPACSYMNUM) { *ptr = (char) NTEND; return 0; } else *ptr = iupac[idx].code; ptr++; str++; } *ptr = NTEND; return 1; } int coded_revcomp(char *comp, char *seq) { long bases; char *bckp, *fwdp; int idx; long pos; bases = strlen(seq); fwdp = comp; bckp = seq + bases -1; for (pos = 0; pos < bases; pos++) { for (idx = 0; *bckp != iupac[idx].code && idx < IUPACSYMNUM; idx++); if (idx > IUPACSYMNUM) { *fwdp = NTEND; return 0; } else *fwdp = iupac[idx].comp; fwdp++; bckp--; } *fwdp = NTEND; return(1); } int seqdecode(char *str, char *codeseq) { int idx; int pos; pos = 0; while (*codeseq != NTEND) { for (idx = 0; *codeseq != iupac[idx].code && idx < IUPACSYMNUM; idx++) ; if (idx > IUPACSYMNUM) { str[pos] = 'X'; return 0; } else str[pos] = iupac[idx].sym; codeseq++; pos++; } str[pos] = '\0'; return 1; } int seqndecode( char *str, /* pre-allocated string to write into */ char *codeseq, /* sequence to decode */ int n) /* how many bases to decode */ { int idx; int pos = 0; while (--n >= 0) { for (idx = 0; *codeseq != iupac[idx].code && idx < IUPACSYMNUM; idx++); if (idx > IUPACSYMNUM) { str[pos] = 'X'; return 0; } else str[pos] = iupac[idx].sym; codeseq++; pos++; } str[pos] = '\0'; return 1; }
eb00/randfold
src/squid-1.9g/seqencode.c
C
gpl-2.0
3,458
<?php require_once(drupal_get_path('theme','heshel').'/tpl/header.tpl.php'); global $base_url; drupal_set_title(''); ?> <?php if (!empty($tabs['#primary']) || !empty($tabs['#secondary'])): print render($tabs); endif; print $messages; unset($page['content']['system_main']['default_message']); ?> <div class="wrapper"> <div class="container"> <div class="content_block row no-sidebar"> <div class="page_title"> <h1><?php print drupal_get_title(); ?></h1> </div> <div class="fl-container"> <div class="posts-block"> <div class="contentarea"> <div class="rounded-corners" style="max-width:976px; margin-left:auto; margin-right:auto; background-color:#EEEEEE; padding:10px;"> <?php if($page['content']):?> <?php print render($page['content']); ?> <?php endif; ?> <?php if($page['section_content']):?> <?php print render($page['section_content']); ?> <?php endif; ?> </div> </div> </div> </div> </div> </div> <br /> <br /> <?php require_once(drupal_get_path('theme','heshel').'/tpl/footer.tpl.php'); ?>
agroknow/agreri
sites/all/themes/heshel/tpl/page--project.tpl.php
PHP
gpl-2.0
1,723
/* Temporary CSS File */ /*-------------------------------------------------------------- 2.6 - Custom Modal --------------------------------------------------------------*/ .md-overlay { background: rgba(255,255,255,.7); position: fixed; top: 0; left: 0; width: 100%; height: 100%; z-index: 9998; display: none; } .md-overlay ~ .md-content { display: none; background: #fff; position: fixed; top: 20%; left: 50%; margin-left: -280px; width: 560px; z-index: 9999; overflow: hidden; border: 1px solid #dcdee0; border-bottom-width: 4px; border-bottom-color: #dadada; box-shadow: 0 1px 0 #dcdee0; border-radius: 8px; /*padding: 20px;*/ } .md-content:after { clear: both; content: ''; display: table; } .md-overlay.show { display: block; } .md-overlay.show ~ .md-content { display: block; } .md-content .login-title { font-size: 1.25em; font-family: 'OpenSansSemibold', sans-serif; padding-bottom: 20px; border-bottom: 1px solid #dcdee0; } .md-content #login-text { float: right; background: #ecedef; box-shadow: inset 1px 0 0 0 rgba(255,255,255,.8); width: 40%; padding: 20px; min-height: 270px; position: relative; border-left: 1px solid #dcdee0; } .md-content .standard-form { float: left; width: 60%; padding: 20px; } .md-content .standard-form label { display: block; margin-bottom: 10px; } .md-content .standard-form label span { display: inline-block; width: 22%; } .md-content .standard-form .forgetmenot { padding-left: 22%; } .md-content .standard-form input[type="text"], .md-content .standard-form input[type="password"] { width: 76%; display: inline-block; padding: 7px; border: 1px solid #dadada; color: #999; } .md-content .standard-form input[type="text"]:hover, .md-content .standard-form input[type="email"]:hover { color: #555; } .md-content .standard-form input[type="text"]:focus, .md-content .standard-form input[type="email"]:focus { color: #333; } .md-content .button { padding: 8px 15px; min-width: 95px; text-align: center; font-size: 1em } .md-content #login-text .button { width: 83%; padding: 12px 15px; position: absolute; bottom: 20px; } /*-------------------------------------------------------------- 4.1 - Post and Page Navigation --------------------------------------------------------------*/ .navigation { clear: both; margin: 0 0 .5em; } .navigation:after { clear: both; content: ''; display: table; } .navigation a { /*font-size: 2.5em;*/ color: #333; } .navigation a:hover { color: #da0734; } div.post .navigation { margin: 3em 0 .5em; padding: 10px 0; } div.post .navigation a { font-size: 1em; text-decoration: none; } /*-------------------------------------------------------------- 5.2 - Comments --------------------------------------------------------------*/ .comment-navigation { overflow: hidden; font-size: 14px; font-style: italic; margin: 5px 0 25px 0; padding: 5px 0; } .comments { float: right; } #trackbacks { margin-top: 30px; } .commentlist .bypostauthor { } #comments { margin-top: 30px; } #comments ol.commentlist { margin: 0; } #comments ol.commentlist ol { list-style-type: decimal; margin: 0 0 18px 2.5em; } #comments ol.commentlist ol ol { list-style: lower-alpha; margin-bottom: 0px; } #comments ol.commentlist ol ol ol { list-style: lower-roman; } ol.commentlist li.comment { border: 1px solid #e4e4e4; clear: left; list-style: none; margin-bottom: 15px; padding: 10px 10px 0; position: relative; border-radius: 3px; } ol.commentlist li.comment:after { clear: both; content: ''; display: table; } ol.commentlist ul.children li { margin-bottom: 0; } ol.commentlist div.comment-avatar-box { float: left; margin: 0 15px 10px 0; } .commentlist ul.children div.comment-avatar-box { float: left; margin: 0 10px 10px 0; } div.comment-avatar-box img { border: 2px solid #eee; } div.comment-content { overflow: hidden; margin-bottom: 10px; } div.comment-content p { margin-bottom: 1em; } ul.children .comment-entry { margin-bottom: 10px; } div.comment-meta { color: #888; margin: 0 0 .5em; width: 100%; } div.comment-meta a { color: #da0734; text-decoration: none; } div.comment-meta a:hover { color: #404040; } div.comment-meta .author { font-family: 'OpenSansSemibold', sans-serif; font-size: 1.125em; line-height: 1; } div.comment-meta .time-since { font-size: .875em; } div.comment-meta em { font-style: normal; } #reply-title { margin-top: 0; font-size: 1.5em; } #reply-title small { float: right; font-size: 11px; font-weight: normal; } #reply-title small a { margin-right: 0; } .commentlist ul.children { /*background: #f5f5f5;*/ -moz-border-radius: 4px; -webkit-border-radius: 4px; border-radius: 4px; margin: 15px 0 15px 70px; padding: 0 10px; } .commentlist ul.children ul { margin: 0 0 0 25px; padding-right: 0; } .commentlist ul.children img.avatar { /*border-style: none; height: 25px; width: 25px; margin: 0;*/ } .commentlist ul.children li { border: 1px solid #E4E4E4; padding: 10px; } #respond { margin: 1em 0; color: #3a3a3a; } #respond:after { clear: both; content: ''; display: table; } #respond .avb img { float: inherit; } #respond .comment-form .comment-form-author, #respond .comment-form .comment-form-email { float: left; width: 49%; } #respond .comment-form .comment-form-author { margin-right: 2%; } #respond .comment-form label { margin-bottom: 3px; display: inline-block; } #respond .comment-form .required { color: #e55555; } #respond .comment-form input[type="text"], #respond .comment-form input[type="email"], #respond .comment-form textarea { padding: 7px; display: block; width: 100%; border: 1px solid #dadada; color: #999; } #respond .comment-form textarea { min-height: 150px; } #respond .comment-form input[type="text"]:hover, #respond .comment-form input[type="email"]:hover, #respond .comment-form textarea:hover { color: #555; } #respond .comment-form input[type="text"]:focus, #respond .comment-form input[type="email"]:focus, #respond .comment-form textarea:focus { color: #333; } #respond .comment-form input[type="submit"] { background: #da0734; border: none; border-radius: 3px; padding: 7px; color: #fff; float: right; display: block; min-width: 150px; font-family: 'OpenSansSemibold', sans-serif; cursor: pointer; } #respond .comment-form input[type="submit"]:hover, #respond .comment-form input[type="submit"]:focus { background: #a80528; border: 1px solid #555; } ol.commentlist #respond { clear: left; margin-left: 70px; } .commentlist ul.children #respond { margin-bottom: 10px; margin-left: 35px; margin-right: 20px; } h3#reply .comments-header { font-size: 14px; } #respond div.comment-content { border-style: none; } .comment-options { position: absolute; top: 10px; right: 10px; } .comment-options .comment-reply-link, .comment-options .comment-edit-link { margin-right: 5px; text-decoration: none; } /*-------------------------------------------------------------- 5.5.2 - Contact Page --------------------------------------------------------------*/ .site-content.withmap { padding-top: 500px; } .gmap { position: absolute !important; top: 109px; left: 0; width: 100%; height: 450px; overflow: hidden; } .contact-form-container { float: left; width: 49%; padding-right: 3%; } .contact-form-container:after { clear: both; content: ''; display: table; } .contact-form-container label { display: inline-block; margin-bottom: 3px; } .contact-form-container label i { color: #da0734; } .contact-form-container input[type="text"], .contact-form-container input[type="email"], .contact-form-container textarea { padding: 8px; border: 1px solid #dadada; border-radius: 2px; display: block; width: 100%; } .contact-form-container textarea { min-height: 100px; } .contact-form-container input[type="text"]:hover, .contact-form-container input[type="email"]:hover, .contact-form-container textarea:hover { color: #555; border: 1px solid #aaa; } .contact-form-container input[type="text"]:focus, .contact-form-container input[type="email"]:focus, .contact-form-container textarea:focus { color: #333; border: 1px solid #555; } .contact-form-container button[type="submit"] { background: #da0734; border: none; border-radius: 3px; padding: 7px; color: #fff; float: right; display: block; min-width: 150px; font-family: 'OpenSansSemibold', sans-serif; cursor: pointer; } .contact-form-container button[type="submit"]:hover, .contact-form-container button[type="submit"]:focus { background: #a80528; }
kylemclaren/buddypress
wp-content/themes/chum/_inc/css/temp.css
CSS
gpl-2.0
8,546
/* * Copyright (C) 2015 TinyCore <http://www.tinycore.net/> * Copyright (C) 2006-2009 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: The_Eye SD%Complete: 100 SDComment: SDCategory: Tempest Keep, The Eye EndScriptData */ /* ContentData npc_crystalcore_devastator EndContentData */ #include "ScriptMgr.h" #include "ScriptedCreature.h" #include "the_eye.h" enum Spells { SPELL_COUNTERCHARGE = 35035, SPELL_KNOCKAWAY = 22893, }; class npc_crystalcore_devastator : public CreatureScript { public: npc_crystalcore_devastator() : CreatureScript("npc_crystalcore_devastator") { } struct npc_crystalcore_devastatorAI : public ScriptedAI { npc_crystalcore_devastatorAI(Creature* creature) : ScriptedAI(creature) { Initialize(); } void Initialize() { Countercharge_Timer = 9000; Knockaway_Timer = 25000; } uint32 Knockaway_Timer; uint32 Countercharge_Timer; void Reset() override { Initialize(); } void EnterCombat(Unit* /*who*/) override { } void UpdateAI(uint32 diff) override { if (!UpdateVictim()) return; //Check if we have a current target //Knockaway_Timer if (Knockaway_Timer <= diff) { DoCastVictim(SPELL_KNOCKAWAY, true); // current aggro target is knocked away pick new target Unit* target = SelectTarget(SELECT_TARGET_TOPAGGRO, 0); if (!target || target == me->GetVictim()) target = SelectTarget(SELECT_TARGET_TOPAGGRO, 1); if (target) me->TauntApply(target); Knockaway_Timer = 23000; } else Knockaway_Timer -= diff; //Countercharge_Timer if (Countercharge_Timer <= diff) { DoCast(me, SPELL_COUNTERCHARGE); Countercharge_Timer = 45000; } else Countercharge_Timer -= diff; DoMeleeAttackIfReady(); } }; CreatureAI* GetAI(Creature* creature) const override { return new npc_crystalcore_devastatorAI(creature); } }; void AddSC_the_eye() { new npc_crystalcore_devastator(); }
AwkwardDev/TinyCore
src/server/scripts/Outland/TempestKeep/Eye/the_eye.cpp
C++
gpl-2.0
3,339
<?php /** * The themes Header file. * * Displays all of the <head> section and everything up till <div id="main-wrap"> * * @package Moka * @since Moka 1.0 */ ?><!DOCTYPE html> <html id="doc" <?php language_attributes(); ?>> <head> <meta charset="<?php bloginfo( 'charset' ); ?>" /> <meta name="viewport" content="width=device-width,initial-scale=1"> <link rel="shortcut icon" href="http://blog.kochabo.at/wp-content/uploads/2014/02/kochabo-at-favicon.png" /> <title><?php wp_title( '|', true, 'right' ); ?></title> <link rel="profile" href="http://gmpg.org/xfn/11" /> <link href='http://fonts.googleapis.com/css?family=Muli' rel='stylesheet' type='text/css'> <?php // Loads HTML5 JavaScript file to add support for HTML5 elements in older IE versions. ?> <!--[if lt IE 9]> <script src="<?php echo get_template_directory_uri(); ?>/js/html5.js"></script> <![endif]--> <?php wp_head(); ?> <?php if(get_site_url()=="http://blog.kochabo.at") : ?> <script type="text/javascript"> var _gaq = _gaq || []; _gaq.push(['_setAccount', 'UA-29618342-1']); _gaq.push(['_setDomainName', 'blog.kochabo.at']); _gaq.push(['_trackPageview']); (function() { var ga = document.createElement('script'); ga.type = 'text/javascript'; ga.async = true; ga.src = ('https:' == document.location.protocol ? 'https://ssl' : 'http://www') + '.google-analytics.com/ga.js'; var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(ga, s); })(); </script> <script type="text/javascript"> function saveEmailLead(){ var email = document.getElementById('lead-signup-email').value; jQuery.ajax({ url: 'http://www.kochabo.at/kochabo/ajax/saveFacebookLead', data: ({email:email, source: 'blog-sidebar'}), success: function() { } }); document.getElementById('signupsuccess').style.display = 'block'; } </script> <?php elseif(get_site_url()=="http://blog.kochpost.ch") : ?> <script type="text/javascript"> var _gaq = _gaq || []; _gaq.push(['_setAccount', 'UA-26604164-1']); _gaq.push(['_setDomainName', 'blog.kochpost.ch']); _gaq.push(['_trackPageview']); (function() { var ga = document.createElement('script'); ga.type = 'text/javascript'; ga.async = true; ga.src = ('https:' == document.location.protocol ? 'https://ssl' : 'http://www') + '.google-analytics.com/ga.js'; var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(ga, s); })(); </script> <script type="text/javascript"> function saveEmailLead(){ var email = document.getElementById('lead-signup-email').value; jQuery.ajax({ url: 'http://www.kochpost.ch/kochabo/ajax/saveFacebookLead', data: ({email:email, source: 'blog-sidebar'}), success: function() { } }); document.getElementById('signupsuccess').style.display = 'block'; } </script> <?php endif; ?> <script type="text/javascript"> jQuery(function() { jQuery('body').hide().show(); }); </script> </head> <body <?php body_class(); ?>> <div id="container"> <div class="search-overlay"> <div class="search-wrap"> <?php get_template_part( 'search-main' ); ?> <div class="search-close"><?php _e('Close Search', 'moka') ?></div> <p class="search-info"><?php _e('Type your search terms above and press return to see the search results.', 'moka') ?></p> </div><!-- end .search-wrap --> </div><!-- end .search-overlay --> <div id="sidebar-wrap"> <div id="sidebar"> <header id="masthead" class="clearfix" role="banner"> <div id="site-title"> <h1><a href="<?php echo esc_url( home_url( '/' ) ); ?>" title="<?php echo esc_attr( get_bloginfo( 'name', 'display' ) ); ?>"><?php bloginfo( 'name' ); ?></a></h1> <?php if ( '' != get_bloginfo('description') ) : ?> <h2 class="site-description"><?php bloginfo( 'description' ); ?></h2> <?php endif; ?> </div><!-- end #site-title --> </header><!-- end #masthead --> <a href="#nav-mobile" id="mobile-menu-btn"><span><?php _e('Menu', 'moka') ?></span></a> <nav id="site-nav" class="clearfix"> <?php wp_nav_menu( array( 'theme_location' => 'primary', 'container' => 'false') ); ?> <div style="margin-top:25px;"> <?php if(get_site_url()=="http://blog.kochabo.at") : ?> <a href="http://www.facebook.com/kochabo" target="_BLANK"><img src="http://blog.kochabo.at/wp-content/uploads/2014/03/facebook-icon.png" width="40" alt="KochAbo.at Facebook" /></a>&nbsp; <a href="http://www.twitter.com/kochabo_at" target="_BLANK"><img src="http://blog.kochabo.at/wp-content/uploads/2014/03/twitter-icon.png" width="40" alt="KochAbo.at Twitter" /></a>&nbsp; <a href="http://www.youtube.com/KochAboAT" target="_BLANK"><img src="http://blog.kochabo.at/wp-content/uploads/2014/03/youtube-icon.png" width="40" alt="KochAbo.at Youtube" /></a> <?php elseif(get_site_url()=="http://blog.kochpost.ch") : ?> <a href="http://www.facebook.com/kochpost" target="_BLANK"><img src="http://blog.kochabo.at/wp-content/uploads/2014/03/facebook-icon.png" width="40" alt="KochAbo.at Facebook" /></a>&nbsp; <a href="http://www.youtube.com/kochpost" target="_BLANK"><img src="http://blog.kochabo.at/wp-content/uploads/2014/03/youtube-icon.png" width="40" alt="KochAbo.at Youtube" /></a> <?php endif; ?> <div style="margin-top:20px; font-size:14px;"> Woche für Woche köstliche Rezepte per E-Mail. Jetzt anmelden! <div id="signupsuccess" style="display:none; color:green;">Danke für deine Anmeldung!</div> </div> <div style="margin-top:10px;"> <form action='javascript:saveEmailLead()' id='signup' name='signup' method='GET'> <input id='lead-signup-email' placeholder='Deine E-Mail Adresse' size='28' type='text'> <a style="margin-top:5px;" class="standard-btn red-btn xsmall-btn" href="javascript:document.signup.submit()"> <span>Eintragen</span> </a> </form> </div> </div> <div id="search-btn"><?php _e('Suche', 'moka') ?></div> </nav><!-- end #site-nav --> </div><!-- end #sidebar --> </div><!-- end #sidebar-wrap --> <div id="main-wrap">
Designer023/wp-at-blog
wp-content/themes/moka/header.php
PHP
gpl-2.0
6,225
angular.module('starter.controllers') .controller('ChartsCtrl', function($scope,ChartData, $ionicLoading){ $scope.labels = []; $scope.series = ['']; $scope.chartOptions = { datasetFill:false, animation:false, showScale:true, scaleShowGridLines: true, pointDot:false, bezierCurve:false }; $scope.startDate = moment().subtract(30, 'days').toDate(); $scope.endDate = new Date(); var showMonthXLabels = false; $scope.getChart = function(shareIndex, startDate, endDate,report) { $ionicLoading.show({template: "loading..."}); ChartData.chartData(shareIndex, startDate, endDate, report) .error(function(){ alert('Ugh, something went wrong with loading the chart. Please try again or contact us for support.'); $ionicLoading.hide(); }) .success(function(data){ $ionicLoading.hide(); var results = []; for (var i = 0; i < data.Rows.length; i++){ results.push(data.Rows[i]); } //TODO: Eish, figure out a way to do this better!!! if (results.length > 20) { showMonthXLabels = true; } else{ showMonthXLabels = false; } var fillColor = "rgba(252,7,31,0)"; var datasets = []; if (report == "MyPortfolioReport"){ var portfolioOverallValues = results.map(function(row){return row.portfolioOverallValue/100;}) var labels = results.map(function(row){ if (showMonthXLabels){ return showFirstDateOfMonthOrNothing(new Date(row.date)); } else return toJSONLocal(new Date(row.date)); }); $scope.labels = labels; $scope.series = ['Portfolio Value']; $scope.data = [portfolioOverallValues]; } if (report == "RsiReport"){ var labels = results.map(function(row){ if (showMonthXLabels){ return showFirstDateOfMonthOrNothing(new Date(row.date)); } else return toJSONLocal(new Date(row.date)); }); var rsi = results.map(function(row){ return parseInt(row.rsi);}); $scope.labels = labels; $scope.series = ['Relative Strength']; $scope.data = [rsi]; } if (report == "SingleStockMacdReport"){ var labels = results.map(function(row){ if (showMonthXLabels){ return showFirstDateOfMonthOrNothing(new Date(row.date)); } else return toJSONLocal(new Date(row.date)); }); macd = results.map(function(row){ return parseInt(row.macd_line);}); histogram = results.map(function(row){ return parseInt(row.histogram);}); divergence = results.map(function(row){ return parseInt(row.signal_line);}); $scope.labels = labels; $scope.series = ['Macd','Divergence']; $scope.data = [macd,divergence]; } if (report == "DailyCloseStockPriceReport"){ var labels = results.map(function(row){ if (showMonthXLabels){ return showFirstDateOfMonthOrNothing(new Date(row.dateOfPrice)); } else return toJSONLocal(new Date(row.dateOfPrice)); }); close_prices = results.map(function(row){return row.closePrice / 100;}) $scope.labels = labels; $scope.data = [close_prices] $scope.series = ['Close Prices'] } }); }; }); var lastDate = undefined; var dateCount = 0; function showFirstDateOfMonthOrNothing(date){ var returnValue = ""; if (dateCount == 0){ returnValue = toJSONLocal(date); } else if (dateCount % 10 == 0){ returnValue = toJSONLocal(date); } dateCount ++; return returnValue; }
tbohnen/EquityTrader
StockRetriever.Ui.Mobile/www/js/chartsController.js
JavaScript
gpl-2.0
3,667