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
-- ============================================= -- Author: <Author,,Name> -- Create date: <Create Date,,> -- Description: <Description,,> -- ============================================= CREATE PROCEDURE [dbo].[UpdateMainFellowship] (@orgid INT) AS BEGIN -- SET NOCOUNT ON added to prevent extra result sets from -- interfering with SELECT statements. SET NOCOUNT ON; UPDATE dbo.People SET BibleFellowshipClassId = dbo.BibleFellowshipClassId(p.PeopleId) FROM dbo.People p JOIN dbo.OrganizationMembers om ON p.PeopleId = om.PeopleId WHERE om.OrganizationId = @orgid END GO IF @@ERROR<>0 AND @@TRANCOUNT>0 ROLLBACK TRANSACTION GO IF @@TRANCOUNT=0 BEGIN INSERT INTO #tmpErrors (Error) SELECT 1 BEGIN TRANSACTION END GO
RGray1959/MyParish
SqlScripts/BuildDb/Creating_dbo_UpdateMainFellowship.sql
SQL
gpl-2.0
728
<?php cherry_get_header(); ?> <div <?php cherry_attr( 'content' ); ?>> <div class="<?php echo apply_filters( 'cherry_get_container_class', 'container' ); ?>"> <?php cherry_get_content(); ?> <?php cherry_get_sidebar( apply_filters( 'cherry_get_main_sidebar', 'sidebar-main' ) ); ?> <?php cherry_get_sidebar( apply_filters( 'cherry_get_secondary_sidebar', 'sidebar-secondary' ) ); ?> </div> </div> <?php cherry_get_footer(); ?>
roberto-alarcon/Neuroglobal
wp-content/themes/cherryframework4/base.php
PHP
gpl-2.0
451
/* * Copyright (C) 2005-2013 Team XBMC * http://xbmc.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, 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 XBMC; see the file COPYING. If not, see * <http://www.gnu.org/licenses/>. * */ #include "MusicInfoLoader.h" #include "MusicDatabase.h" #include "music/infoscanner/MusicInfoScanner.h" #include "music/tags/MusicInfoTagLoaderFactory.h" #include "filesystem/DirectoryCache.h" #include "filesystem/MusicDatabaseDirectory.h" #include "filesystem/MusicDatabaseDirectory/DirectoryNode.h" #include "filesystem/MusicDatabaseDirectory/QueryParams.h" #include "utils/URIUtils.h" #include "music/tags/MusicInfoTag.h" #include "filesystem/File.h" #include "settings/Settings.h" #include "FileItem.h" #include "utils/log.h" #include "utils/Archive.h" #include "Artist.h" #include "Album.h" #include "MusicThumbLoader.h" using namespace std; using namespace XFILE; using namespace MUSIC_INFO; // HACK until we make this threadable - specify 1 thread only for now CMusicInfoLoader::CMusicInfoLoader() : CBackgroundInfoLoader() { m_mapFileItems = new CFileItemList; m_thumbLoader = new CMusicThumbLoader(); } CMusicInfoLoader::~CMusicInfoLoader() { StopThread(); delete m_mapFileItems; delete m_thumbLoader; } void CMusicInfoLoader::OnLoaderStart() { // Load previously cached items from HD if (!m_strCacheFileName.empty()) LoadCache(m_strCacheFileName, *m_mapFileItems); else { m_mapFileItems->SetPath(m_pVecItems->GetPath()); m_mapFileItems->Load(); m_mapFileItems->SetFastLookup(true); } m_strPrevPath.clear(); m_databaseHits = m_tagReads = 0; if (m_pProgressCallback) m_pProgressCallback->SetProgressMax(m_pVecItems->GetFileCount()); m_musicDatabase.Open(); if (m_thumbLoader) m_thumbLoader->OnLoaderStart(); } bool CMusicInfoLoader::LoadAdditionalTagInfo(CFileItem* pItem) { if (!pItem || pItem->m_bIsFolder || pItem->IsPlayList() || pItem->IsNFO() || pItem->IsInternetStream()) return false; if (pItem->GetProperty("hasfullmusictag") == "true") return false; // already have the information std::string path(pItem->GetPath()); if (pItem->IsMusicDb()) { // set the artist / album properties XFILE::MUSICDATABASEDIRECTORY::CQueryParams param; XFILE::MUSICDATABASEDIRECTORY::CDirectoryNode::GetDatabaseInfo(pItem->GetPath(),param); CArtist artist; CMusicDatabase database; database.Open(); if (database.GetArtist(param.GetArtistId(), artist, false)) CMusicDatabase::SetPropertiesFromArtist(*pItem,artist); CAlbum album; if (database.GetAlbum(param.GetAlbumId(), album, false)) CMusicDatabase::SetPropertiesFromAlbum(*pItem,album); path = pItem->GetMusicInfoTag()->GetURL(); } CLog::Log(LOGDEBUG, "Loading additional tag info for file %s", path.c_str()); // we load up the actual tag for this file unique_ptr<IMusicInfoTagLoader> pLoader (CMusicInfoTagLoaderFactory::CreateLoader(path)); if (NULL != pLoader.get()) { CMusicInfoTag tag; pLoader->Load(path, tag); // then we set the fields from the file tags to the item pItem->SetProperty("lyrics", tag.GetLyrics()); pItem->SetProperty("hasfullmusictag", "true"); return true; } return false; } bool CMusicInfoLoader::LoadItem(CFileItem* pItem) { bool result = LoadItemCached(pItem); result |= LoadItemLookup(pItem); return result; } bool CMusicInfoLoader::LoadItemCached(CFileItem* pItem) { if (pItem->m_bIsFolder || pItem->IsPlayList() || pItem->IsNFO() || pItem->IsInternetStream()) return false; // Get thumb for item m_thumbLoader->LoadItem(pItem); return true; } bool CMusicInfoLoader::LoadItemLookup(CFileItem* pItem) { if (m_pProgressCallback && !pItem->m_bIsFolder) m_pProgressCallback->SetProgressAdvance(); if (pItem->m_bIsFolder || pItem->IsPlayList() || pItem->IsNFO() || pItem->IsInternetStream()) return false; if (!pItem->HasMusicInfoTag() || !pItem->GetMusicInfoTag()->Loaded()) { // first check the cached item CFileItemPtr mapItem = (*m_mapFileItems)[pItem->GetPath()]; if (mapItem && mapItem->m_dateTime==pItem->m_dateTime && mapItem->HasMusicInfoTag() && mapItem->GetMusicInfoTag()->Loaded()) { // Query map if we previously cached the file on HD *pItem->GetMusicInfoTag() = *mapItem->GetMusicInfoTag(); if (mapItem->HasArt("thumb")) pItem->SetArt("thumb", mapItem->GetArt("thumb")); } else { std::string strPath = URIUtils::GetDirectory(pItem->GetPath()); URIUtils::AddSlashAtEnd(strPath); if (strPath!=m_strPrevPath) { // The item is from another directory as the last one, // query the database for the new directory... m_musicDatabase.GetSongsByPath(strPath, m_songsMap); m_databaseHits++; } MAPSONGS::iterator it = m_songsMap.find(pItem->GetPath()); if (it != m_songsMap.end()) { // Have we loaded this item from database before pItem->GetMusicInfoTag()->SetSong(it->second); pItem->GetMusicInfoTag()->SetCueSheet(m_musicDatabase.LoadCuesheet(it->second.strFileName)); if (!it->second.strThumb.empty()) pItem->SetArt("thumb", it->second.strThumb); } else if (pItem->IsMusicDb()) { // a music db item that doesn't have tag loaded - grab details from the database XFILE::MUSICDATABASEDIRECTORY::CQueryParams param; XFILE::MUSICDATABASEDIRECTORY::CDirectoryNode::GetDatabaseInfo(pItem->GetPath(),param); CSong song; if (m_musicDatabase.GetSong(param.GetSongId(), song)) { pItem->GetMusicInfoTag()->SetSong(song); if (!song.strThumb.empty()) pItem->SetArt("thumb", song.strThumb); } } else if (CSettings::Get().GetBool("musicfiles.usetags") || pItem->IsCDDA()) { // Nothing found, load tag from file, // always try to load cddb info // get correct tag parser unique_ptr<IMusicInfoTagLoader> pLoader (CMusicInfoTagLoaderFactory::CreateLoader(pItem->GetPath())); if (NULL != pLoader.get()) // get tag pLoader->Load(pItem->GetPath(), *pItem->GetMusicInfoTag()); m_tagReads++; } m_strPrevPath = strPath; } } return true; } void CMusicInfoLoader::OnLoaderFinish() { // cleanup last loaded songs from database m_songsMap.clear(); // cleanup cache loaded from HD m_mapFileItems->Clear(); // Save loaded items to HD if (!m_strCacheFileName.empty()) SaveCache(m_strCacheFileName, *m_pVecItems); else if (!m_bStop && (m_databaseHits > 1 || m_tagReads > 0)) m_pVecItems->Save(); m_musicDatabase.Close(); if (m_thumbLoader) m_thumbLoader->OnLoaderFinish(); } void CMusicInfoLoader::UseCacheOnHD(const std::string& strFileName) { m_strCacheFileName = strFileName; } void CMusicInfoLoader::LoadCache(const std::string& strFileName, CFileItemList& items) { CFile file; if (file.Open(strFileName)) { CArchive ar(&file, CArchive::load); int iSize = 0; ar >> iSize; for (int i = 0; i < iSize; i++) { CFileItemPtr pItem(new CFileItem()); ar >> *pItem; items.Add(pItem); } ar.Close(); file.Close(); items.SetFastLookup(true); } } void CMusicInfoLoader::SaveCache(const std::string& strFileName, CFileItemList& items) { int iSize = items.Size(); if (iSize <= 0) return ; CFile file; if (file.OpenForWrite(strFileName)) { CArchive ar(&file, CArchive::store); ar << (int)items.Size(); for (int i = 0; i < iSize; i++) { CFileItemPtr pItem = items[i]; ar << *pItem; } ar.Close(); file.Close(); } }
mrdominuzq/xbmc
xbmc/music/MusicInfoLoader.cpp
C++
gpl-2.0
8,241
/******************************************************************* * * ftxgdef.h * * TrueType Open GDEF table support * * Copyright 1996-2000 by * David Turner, Robert Wilhelm, and Werner Lemberg. * * This file is part of the FreeType project, and may only be used * modified and distributed under the terms of the FreeType project * license, LICENSE.TXT. By continuing to use, modify, or distribute * this file you indicate that you have read the license and * understand and accept it fully. * ******************************************************************/ #ifndef FTXOPEN_H #error "Don't include this file! Use ftxopen.h instead." #endif #ifndef FTXGDEF_H #define FTXGDEF_H #ifdef __cplusplus extern "C" { #endif #define TTO_Err_Invalid_GDEF_SubTable_Format 0x1030 #define TTO_Err_Invalid_GDEF_SubTable 0x1031 /* GDEF glyph classes */ #define UNCLASSIFIED_GLYPH 0 #define SIMPLE_GLYPH 1 #define LIGATURE_GLYPH 2 #define MARK_GLYPH 3 #define COMPONENT_GLYPH 4 /* GDEF glyph properties, corresponding to class values 1-4. Note that TTO_COMPONENT has no corresponding flag in the LookupFlag field. */ #define TTO_BASE_GLYPH 0x0002 #define TTO_LIGATURE 0x0004 #define TTO_MARK 0x0008 #define TTO_COMPONENT 0x0010 /* Attachment related structures */ struct TTO_AttachPoint_ { FT_UShort PointCount; /* size of the PointIndex array */ FT_UShort* PointIndex; /* array of contour points */ }; typedef struct TTO_AttachPoint_ TTO_AttachPoint; struct TTO_AttachList_ { FT_Bool loaded; TTO_Coverage Coverage; /* Coverage table */ FT_UShort GlyphCount; /* number of glyphs with attachments */ TTO_AttachPoint* AttachPoint; /* array of AttachPoint tables */ }; typedef struct TTO_AttachList_ TTO_AttachList; /* Ligature Caret related structures */ struct TTO_CaretValueFormat1_ { FT_Short Coordinate; /* x or y value (in design units) */ }; typedef struct TTO_CaretValueFormat1_ TTO_CaretValueFormat1; struct TTO_CaretValueFormat2_ { FT_UShort CaretValuePoint; /* contour point index on glyph */ }; typedef struct TTO_CaretValueFormat2_ TTO_CaretValueFormat2; struct TTO_CaretValueFormat3_ { FT_Short Coordinate; /* x or y value (in design units) */ TTO_Device Device; /* Device table for x or y value */ }; typedef struct TTO_CaretValueFormat3_ TTO_CaretValueFormat3; struct TTO_CaretValueFormat4_ { FT_UShort IdCaretValue; /* metric ID */ }; typedef struct TTO_CaretValueFormat4_ TTO_CaretValueFormat4; struct TTO_CaretValue_ { FT_UShort CaretValueFormat; /* 1, 2, 3, or 4 */ union { TTO_CaretValueFormat1 cvf1; TTO_CaretValueFormat2 cvf2; TTO_CaretValueFormat3 cvf3; TTO_CaretValueFormat4 cvf4; } cvf; }; typedef struct TTO_CaretValue_ TTO_CaretValue; struct TTO_LigGlyph_ { FT_Bool loaded; FT_UShort CaretCount; /* number of caret values */ TTO_CaretValue* CaretValue; /* array of caret values */ }; typedef struct TTO_LigGlyph_ TTO_LigGlyph; struct TTO_LigCaretList_ { FT_Bool loaded; TTO_Coverage Coverage; /* Coverage table */ FT_UShort LigGlyphCount; /* number of ligature glyphs */ TTO_LigGlyph* LigGlyph; /* array of LigGlyph tables */ }; typedef struct TTO_LigCaretList_ TTO_LigCaretList; /* The `NewGlyphClasses' field is not defined in the TTO specification. We use it for fonts with a constructed `GlyphClassDef' structure (i.e., which don't have a GDEF table) to collect glyph classes assigned during the lookup process. The number of arrays in this pointer array is GlyphClassDef->cd.cd2.ClassRangeCount+1; the nth array then contains the glyph class values of the glyphs not covered by the ClassRangeRecords structures with index n-1 and n. We store glyph class values for four glyphs in a single array element. `LastGlyph' is identical to the number of glyphs minus one in the font; we need it only if `NewGlyphClasses' is not NULL (to have an upper bound for the last array). Note that we first store the file offset to the `MarkAttachClassDef' field (which has been introduced in OpenType 1.2) -- since the `Version' field value hasn't been increased to indicate that we have one more field for some obscure reason, we must parse the GSUB table to find out whether class values refer to this table. Only then we can finally load the MarkAttachClassDef structure if necessary. */ struct TTO_GDEFHeader_ { FT_Memory memory; FT_ULong offset; FT_Fixed Version; TTO_ClassDefinition GlyphClassDef; TTO_AttachList AttachList; TTO_LigCaretList LigCaretList; FT_ULong MarkAttachClassDef_offset; TTO_ClassDefinition MarkAttachClassDef; /* new in OT 1.2 */ FT_UShort LastGlyph; FT_UShort** NewGlyphClasses; }; typedef struct TTO_GDEFHeader_ TTO_GDEFHeader; typedef struct TTO_GDEFHeader_* TTO_GDEF; /* finally, the GDEF API */ /* EXPORT_DEF FT_Error TT_Init_GDEF_Extension( TT_Engine engine ); */ EXPORT_FUNC FT_Error TT_New_GDEF_Table( FT_Face face, TTO_GDEFHeader** retptr ); EXPORT_DEF FT_Error TT_Load_GDEF_Table( FT_Face face, TTO_GDEFHeader** gdef ); EXPORT_DEF FT_Error TT_Done_GDEF_Table ( TTO_GDEFHeader* gdef ); EXPORT_DEF FT_Error TT_GDEF_Get_Glyph_Property( TTO_GDEFHeader* gdef, FT_UShort glyphID, FT_UShort* property ); EXPORT_DEF FT_Error TT_GDEF_Build_ClassDefinition( TTO_GDEFHeader* gdef, FT_UShort num_glyphs, FT_UShort glyph_count, FT_UShort* glyph_array, FT_UShort* class_array ); #ifdef __cplusplus } #endif #endif /* FTXGDEF_H */ /* END */
gestiweb/eneboo
src/qt/src/3rdparty/opentype/ftxgdef.h
C
gpl-2.0
6,557
#!/usr/bin/env python import sys from cd3modelgen import * s = Simulation("ParallelSimulation") def gen_sewers(s, count, subreaches): c = ConstSource() s.nodes+=[c] old = c for i in xrange(count): sewer = Sewer(subreaches) s.nodes+=[sewer] s.cons+=[Connection(old, sewer)] old = sewer return old def main(): par = seq = subs = 0 s = None if (len(sys.argv) < 3): sys.stderr.write("usage: gen-parallel-model num-par num-seq [sim-class] [sub-reaches]\n") return if (len(sys.argv) >= 3): par = int(sys.argv[1]) seq = int(sys.argv[2]) if (len(sys.argv) >= 4): s = Simulation(sys.argv[3]) else: s = Simulation("ParallelSimulation") if (len(sys.argv) >= 5): subs = int(sys.argv[4]) else: subs = 11 m = Mixer(par) for i in range(par): sewer = gen_sewers(s, seq, subs) s.cons += [Connection(sewer, m, "out", "inputs[%d]" % i)] f = FileOut("tmp/par-test.txt") s.nodes += [f, m] s.cons += [Connection(m, f)] s.render() if __name__ == "__main__": main()
gregorburger/CityDrain3
data/models/gen-parallel-model.py
Python
gpl-2.0
1,141
<?php function cml_frontend_hide_translations_for_tags($wp_query) { global $wpCeceppaML, $wpdb; /* Può capitare che l'utente invece di tradurre un tag ne usa uno nuovo per l'articolo. In questo caso aggiungendo all'url ?lang=##, viene visualizzato il messaggio 404 se per quella lingua non c'è nessun articolo con quel tag, il ché può essere un po' noioso. Dagli articoli da escludere rimuovo tutti quelli che non hanno quel tag. Così se assegno 2 tag diversi all'articolo e alla sua traduzione non mi ritrovo con un 404. Il metodo, a causa dei vari cicli da eseguire, probabilmente porterà dei rallentamenti nel caricamento delle pagine dei tag, però è anche l'unico modo di evitare pagine 404 se all'utente piace assegnare tag diversi invece di tradurli... */ $tag_name = $wp_query->query_vars['tag']; $i = 0; if( ! is_object( $wpCeceppaML ) || ! is_array( $wpCeceppaML->_hide_posts ) ) return; foreach( $wpCeceppaML->_hide_posts as $id ) : $tags = wp_get_post_tags($id); $lang_id = $wpCeceppaML->get_language_id_by_post_id($id); foreach($tags as $tag) : if($tag->name == $tag_name && $lang_id != $wpCeceppaML->get_current_lang_id(false)) : //Controllo che per questa articolo non esista nessuna traduzione nella lingua corrente con la stessa categoria $nid = cml_get_linked_post($lang_id, null, $id, $wpCeceppaML->get_current_lang_id(false)); echo $nid . ", " . $id; if(!empty($nid)) : //Verifico le categorie dell'articolo collegato $_tags = wp_get_post_tags($nid); $found = false; foreach($_tags as $_tag) : if($_tag->name == $tag_name) : $found = true; break; endif; endforeach; if(!$found) : unset($wpCeceppaML->_hide_posts[$i]); break; endif; endif; endif; endforeach; $i++; endforeach; } ?>
dantruongxp/sp
wp-content/plugins/ceceppa-multilingua/frontend/deprecated.php
PHP
gpl-2.0
1,858
/* * (C) Copyright 2012 * Joe Hershberger, National Instruments, [email protected] * * SPDX-License-Identifier: GPL-2.0+ */ #ifndef __ENV_FLAGS_H__ #define __ENV_FLAGS_H__ enum env_flags_vartype { env_flags_vartype_string, env_flags_vartype_decimal, env_flags_vartype_hex, env_flags_vartype_bool, #ifdef CONFIG_CMD_NET env_flags_vartype_ipaddr, env_flags_vartype_macaddr, #endif env_flags_vartype_end }; enum env_flags_varaccess { env_flags_varaccess_any, env_flags_varaccess_readonly, env_flags_varaccess_writeonce, env_flags_varaccess_changedefault, env_flags_varaccess_end }; #define ENV_FLAGS_VAR ".flags" #define ENV_FLAGS_ATTR_MAX_LEN 2 #define ENV_FLAGS_VARTYPE_LOC 0 #define ENV_FLAGS_VARACCESS_LOC 1 #ifndef CONFIG_ENV_FLAGS_LIST_STATIC #define CONFIG_ENV_FLAGS_LIST_STATIC "" #endif #ifdef CONFIG_CMD_NET #ifdef CONFIG_REGEX #define ETHADDR_WILDCARD "\\d?" #else #define ETHADDR_WILDCARD #endif #ifdef CONFIG_ENV_OVERWRITE #define ETHADDR_FLAGS "eth" ETHADDR_WILDCARD "addr:ma," #else #ifdef CONFIG_OVERWRITE_ETHADDR_ONCE #define ETHADDR_FLAGS "eth" ETHADDR_WILDCARD "addr:mc," #else #define ETHADDR_FLAGS "eth" ETHADDR_WILDCARD "addr:mo," #endif #endif #define NET_FLAGS \ "ipaddr:i," \ "gatewayip:i," \ "netmask:i," \ "serverip:i," \ "nvlan:i," \ "vlan:i," \ "dnsip:i," #else #define ETHADDR_FLAGS #define NET_FLAGS #endif #ifndef CONFIG_ENV_OVERWRITE #define SERIAL_FLAGS "serial#:so," #else #define SERIAL_FLAGS "" #endif #define ENV_FLAGS_LIST_STATIC \ ETHADDR_FLAGS \ NET_FLAGS \ SERIAL_FLAGS \ CONFIG_ENV_FLAGS_LIST_STATIC #ifdef CONFIG_CMD_ENV_FLAGS /* * Print the whole list of available type flags. */ void env_flags_print_vartypes(void); /* * Print the whole list of available access flags. */ void env_flags_print_varaccess(void); /* * Return the name of the type. */ const char *env_flags_get_vartype_name(enum env_flags_vartype type); /* * Return the name of the access. */ const char *env_flags_get_varaccess_name(enum env_flags_varaccess access); #endif /* * Parse the flags string from a .flags attribute list into the vartype enum. */ enum env_flags_vartype env_flags_parse_vartype(const char *flags); /* * Parse the flags string from a .flags attribute list into the varaccess enum. */ enum env_flags_varaccess env_flags_parse_varaccess(const char *flags); /* * Parse the binary flags from a hash table entry into the varaccess enum. */ enum env_flags_varaccess env_flags_parse_varaccess_from_binflags(int binflags); #ifdef CONFIG_CMD_NET /* * Check if a string has the format of an Ethernet MAC address */ int eth_validate_ethaddr_str(const char *addr); #endif #ifdef USE_HOSTCC /* * Look up the type of a variable directly from the .flags var. */ enum env_flags_vartype env_flags_get_type(const char *name); /* * Look up the access of a variable directly from the .flags var. */ enum env_flags_varaccess env_flags_get_access(const char *name); /* * Validate the newval for its type to conform with the requirements defined by * its flags (directly looked at the .flags var). */ int env_flags_validate_type(const char *name, const char *newval); /* * Validate the newval for its access to conform with the requirements defined * by its flags (directly looked at the .flags var). */ int env_flags_validate_access(const char *name, int check_mask); /* * Validate that the proposed access to variable "name" is valid according to * the defined flags for that variable, if any. */ int env_flags_validate_varaccess(const char *name, int check_mask); /* * Validate the parameters passed to "env set" for type compliance */ int env_flags_validate_env_set_params(int argc, char * const argv[]); #else /* !USE_HOSTCC */ #include <search.h> /* * When adding a variable to the environment, initialize the flags for that * variable. */ void env_flags_init(ENTRY *var_entry); /* * Validate the newval for to conform with the requirements defined by its flags */ int env_flags_validate(const ENTRY *item, const char *newval, enum env_op op, int flag); #endif /* USE_HOSTCC */ /* * These are the binary flags used in the environment entry->flags variable to * decribe properties of veriables in the table */ #define ENV_FLAGS_VARTYPE_BIN_MASK 0x00000007 /* The actual variable type values use the enum value (within the mask) */ #define ENV_FLAGS_VARACCESS_PREVENT_DELETE 0x00000008 #define ENV_FLAGS_VARACCESS_PREVENT_CREATE 0x00000010 #define ENV_FLAGS_VARACCESS_PREVENT_OVERWR 0x00000020 #define ENV_FLAGS_VARACCESS_PREVENT_NONDEF_OVERWR 0x00000040 #define ENV_FLAGS_VARACCESS_BIN_MASK 0x00000078 #endif /* __ENV_FLAGS_H__ */
mdxy2010/forlinux-ok6410
u-boot15/include/env_flags.h
C
gpl-2.0
4,643
<?php /* * This file is part of EC-CUBE * * Copyright(c) 2000-2011 LOCKON CO.,LTD. All Rights Reserved. * * http://www.lockon.co.jp/ * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. */ // {{{ requires require_once '../require.php'; require_once CLASS_EX_REALDIR . 'page_extends/regist/LC_Page_Regist_Ex.php'; // }}} // {{{ generate page $objPage = new LC_Page_Regist_Ex(); register_shutdown_function(array($objPage, "destroy")); $objPage->init(); $objPage->process(); ?>
lucent-global/ichiban-shop
html/regist/index.php
PHP
gpl-2.0
1,149
#pragma once #include "ic/ParaDatabase.h" #include "DataProviderManager.h" #include "CharacterDBProvider.h" #include "ChestDBProvider.h" #include "FruitDBProvider.h" #include "ItemDBProvider.h" #include "PetAIDBProvider.h" #include "PetDBProvider.h" #include "PuzzleDBProvider.h" #include "QuestDBProvider.h" #include "StringTable.h" #include "TitleDBProvider.h" namespace ParaEngine { class CCharacterDBProvider; class CChestDBProvider; class CFruitDBProvider; class CItemDBProvider; class CPetAIDBProvider; class CPetDBProvider; class CPuzzleDBProvider; class CQuestDBProvider; class CStringTableDB; class CTitleDBProvider; class CKidsDBProvider { public: CKidsDBProvider(void); ~CKidsDBProvider(void); // ------------------------------- // common function // ------------------------------- /** whether db is opened. */ bool IsValid() {return m_pDataBase.get() !=0;}; /** delete the database and set everything to NULL*/ void Cleanup(); /** get the database object associated with this provider*/ DBEntity* GetDBEntity() {return m_pDataBase.get();}; /** * replace the current database with current one. the old one is closed and the new once will be opened. * @param sConnectionstring: the file path */ void SetDBEntity(const string& sConnectionstring); /** ensure that the database has been set up properly. If not, ResetDatabase() is called to reset the database to blank */ void ValidateDatabase() {assert(m_pDataBase.get()!=0);}; // ------------------------------- // string table functions // ------------------------------- /** Get string from ID * @param ID: ID in kids db's string table. * @return string in the current game language */ static string GetStringbyID(int ID); /** Insert the new string table entry to StringTable_DB * @param str: Entry in the current game language * @return ID of the inserted string */ static int InsertString(const char* strEN, const char * strCN); // ------------------------------- // Puzzle database functions // ------------------------------- /** Insert the new puzzle record to Puzzle_DB * @param record: ID of record will be ignored and filled with actual ID if inserted successfully * @return true if the record is inserted in database */ bool InsertPuzzleRecordFromString(const string& strRecord); /** delete the existing puzzle record from Puzzle_DB * @param ID: ID of target record * @return true if the record is deleted in database */ bool DeletePuzzleRecordByID(int ID); // ------------------------------- // Item database functions // ------------------------------- /** Insert the new item record to Item_DB * @param record: ID of record will be ignored and filled with actual ID if inserted successfully * @return true if the record is inserted in database */ bool InsertItemRecordFromString(const string& strRecord); /** delete the existing item record from Item_DB * @param ID: ID of target record * @return true if the record is deleted in database */ bool DeleteItemRecordByID(int ID); /** Update existing item record of Item_DB * @param strRecord: update record with actual ID * @return true if the record is updated in database */ bool UpdateItemRecordFromString(const string& strRecord); /** Select existing item record of Item_DB * @param record: select record by ID * @return true if the record is selected in database */ const char * SelectItemRecordToString(__int64 ID); // ------------------------------- // Character database functions // ------------------------------- /** Insert the new character record to Character_DB * @param record: ID of record will be ignored and filled with actual ID if inserted successfully * @return true if the record is inserted in database */ bool InsertCharacterRecordFromString(const string& strRecord); /** delete the existing puzzle record from Character_DB * @param ID: ID of target record * @return true if the record is deleted in database */ bool DeleteCharacterRecordByID(int ID); // ------------------------------- // Chest database functions // ------------------------------- /** Insert the new chest record to Chest_DB * @param record: ID of record will be ignored and filled with actual ID if inserted successfully * @return true if the record is inserted in database */ bool InsertChestRecordFromString(const string& strRecord); /** delete the existing chest record from Chest_DB * @param ID: ID of target record * @return true if the record is deleted in database */ bool DeleteChestRecordByID(int ID); // ------------------------------- // Fruit database functions // ------------------------------- /** Insert the new fruit record to Fruit_DB * @param record: ID of record will be ignored and filled with actual ID if inserted successfully * @return true if the record is inserted in database */ bool InsertFruitRecordFromString(const string& strRecord); /** delete the existing fruit record from Fruit_DB * @param ID: ID of target record * @return true if the record is deleted in database */ bool DeleteFruitRecordByID(int ID); // ------------------------------- // PetAI database functions // ------------------------------- /** Insert the new petAI record to PetAI_DB * @param record: ID of record will be ignored and filled with actual ID if inserted successfully * @return true if the record is inserted in database */ bool InsertPetAIRecordFromString(const string& strRecord); /** delete the existing petAI record from PetAI_DB * @param ID: ID of target record * @return true if the record is deleted in database */ bool DeletePetAIRecordByID(int ID); // ------------------------------- // Pet database functions // ------------------------------- /** Insert the new pet record to Pet_DB * @param record: ID of record will be ignored and filled with actual ID if inserted successfully * @return true if the record is inserted in database */ bool InsertPetRecordFromString(const string& strRecord); /** delete the existing pet record from Pet_DB * @param ID: ID of target record * @return true if the record is deleted in database */ bool DeletePetRecordByID(int ID); // ------------------------------- // Quest database functions // ------------------------------- /** Insert the new quest record to Quest_DB * @param record: ID of record will be ignored and filled with actual ID if inserted successfully * @return true if the record is inserted in database */ bool InsertQuestRecordFromString(const string& strRecord); /** delete the existing quest record from Quest_DB * @param ID: ID of target record * @return true if the record is deleted in database */ bool DeleteQuestRecordByID(int ID); // ------------------------------- // Title database functions // ------------------------------- /** Insert the new title record to Title_DB * @param record: ID of record will be ignored and filled with actual ID if inserted successfully * @return true if the record is inserted in database */ bool InsertTitleRecordFromString(const string& strRecord); /** delete the existing title record from Title_DB * @param ID: ID of target record * @return true if the record is deleted in database */ bool DeleteTitleRecordByID(int ID); #ifdef _DEBUG /** test data base*/ void TestDB(); #endif private: // FORMAT: parse record fields and link with ## void ParsePuzzleRecordToString(string& str, const stPuzzleDbRecord& record); void ParseStringToPuzzleRecord(const string& str, stPuzzleDbRecord& record); // Append string table record to str void AppendStringTableRecordToString(string& str, const stStringTableDbRecord& record); // Get string table record to record int GetStringTableRecordFromString(char* str, stStringTableDbRecord& record); // FORMAT: parse record fields and link with ## void ParseItemRecordToString(const stItemDbRecord& record); void ParseStringToItemRecord(const string& str, stItemDbRecord& record); const char * NumToString(__int64 num); const char * NumToString(int num); const char * NumToString(float num); const char * NumToString(bool num); char m_strSelectBuf[MAX_STRING_LENGTH]; // FORMAT: parse record fields and link with ## void ParseCharacterRecordToString(string& str, const stCharacterDbRecord& record); void ParseStringToCharacterRecord(const string& str, stCharacterDbRecord& record); // FORMAT: parse record fields and link with ## void ParseChestRecordToString(string& str, const stChestDbRecord& record); void ParseStringToChestRecord(const string& str, stChestDbRecord& record); // FORMAT: parse record fields and link with ## void ParseFruitRecordToString(string& str, const stFruitDbRecord& record); void ParseStringToFruitRecord(const string& str, stFruitDbRecord& record); // FORMAT: parse record fields and link with ## void ParsePetAIRecordToString(string& str, const stPetAIDbRecord& record); void ParseStringToPetAIRecord(const string& str, stPetAIDbRecord& record); // FORMAT: parse record fields and link with ## void ParsePetRecordToString(string& str, const stPetDbRecord& record); void ParseStringToPetRecord(const string& str, stPetDbRecord& record); // FORMAT: parse record fields and link with ## void ParseQuestRecordToString(string& str, const stQuestDbRecord& record); void ParseStringToQuestRecord(const string& str, stQuestDbRecord& record); // FORMAT: parse record fields and link with ## void ParseTitleRecordToString(string& str, const stTitleDbRecord& record); void ParseStringToTitleRecord(const string& str, stTitleDbRecord& record); /** base database interface */ ParaEngine::asset_ptr<DBEntity> m_pDataBase; // database providers CCharacterDBProvider* m_dbCharacter; CChestDBProvider* m_dbChest; CFruitDBProvider* m_dbFruit; CItemDBProvider* m_dbItem; CPetAIDBProvider* m_dbPetAI; CPetDBProvider* m_dbPet; CPuzzleDBProvider* m_dbPuzzle; CQuestDBProvider* m_dbQuest; CStringTableDB* m_dbStringTable; CTitleDBProvider* m_dbTitle; }; }
kkvskkkk/NPLRuntime
Client/trunk/ParaEngineClient/Engine/KidsDBProvider.h
C
gpl-2.0
10,245
<?php /** * @version 1.4.0 * @package RSform!Pro 1.4.0 * @copyright (C) 2007-2011 www.rsjoomla.com * @license GPL, http://www.gnu.org/copyleft/gpl.html */ defined('_JEXEC') or die('Restricted access'); JHTML::_('behavior.tooltip'); ?> <form action="index.php" method="post" name="adminForm"> <div class="span2"> <?php echo $this->sidebar; ?> </div> <div class="span10"> <div id="dashboard-left"> <?php echo $this->loadTemplate('buttons'); ?> </div> <div id="dashboard-right" class="hidden-phone hidden-tablet"> <?php echo $this->loadTemplate('version'); ?> <p align="center"><a href="http://www.rsjoomla.com/joomla-components/joomla-security.html?utm_source=rsform&amp;utm_medium=banner_approved&amp;utm_campaign=rsfirewall" target="_blank"><img src="components/com_rsform/assets/images/rsfirewall-approved.png" align="middle" alt="RSFirewall! Approved"/></a></p> </div> </div> <input type="hidden" name="option" value="com_rsform" /> <input type="hidden" name="task" value="" /> </form>
ForAEdesWeb/AEW11
administrator/components/com_rsform/views/rsform/tmpl/default.php
PHP
gpl-2.0
1,016
/* $Xorg: ParseCol.c,v 1.4 2001/02/09 02:03:35 xorgcvs Exp $ */ /* Copyright 1985, 1998 The Open Group Permission to use, copy, modify, distribute, and sell this software and its documentation for any purpose is hereby granted without fee, provided that the above copyright notice appear in all copies and that both that copyright notice and this permission notice appear in supporting documentation. The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE OPEN GROUP BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. Except as contained in this notice, the name of The Open Group shall not be used in advertising or otherwise to promote the sale, use or other dealings in this Software without prior written authorization from The Open Group. */ /* $XFree86: xc/lib/X11/ParseCol.c,v 1.6 2003/04/13 19:22:17 dawes Exp $ */ #define NEED_REPLIES #ifdef HAVE_CONFIG_H #include <config.h> #endif #include <stdio.h> #include "Xlibint.h" #include "Xcmsint.h" Status XParseColor ( register Display *dpy, Colormap cmap, _Xconst char *spec, XColor *def) { register int n, i; int r, g, b; char c; XcmsCCC ccc; XcmsColor cmsColor; if (!spec) return(0); n = strlen (spec); if (*spec == '#') { /* * RGB */ spec++; n--; if (n != 3 && n != 6 && n != 9 && n != 12) return (0); n /= 3; g = b = 0; do { r = g; g = b; b = 0; for (i = n; --i >= 0; ) { c = *spec++; b <<= 4; if (c >= '0' && c <= '9') b |= c - '0'; else if (c >= 'A' && c <= 'F') b |= c - ('A' - 10); else if (c >= 'a' && c <= 'f') b |= c - ('a' - 10); else return (0); } } while (*spec != '\0'); n <<= 2; n = 16 - n; def->red = r << n; def->green = g << n; def->blue = b << n; def->flags = DoRed | DoGreen | DoBlue; return (1); } /* * Let's Attempt to use Xcms and i18n approach to Parse Color */ if ((ccc = XcmsCCCOfColormap(dpy, cmap)) != (XcmsCCC)NULL) { const char *tmpName = spec; switch (_XcmsResolveColorString(ccc, &tmpName, &cmsColor, XcmsRGBFormat)) { case XcmsSuccess: case XcmsSuccessWithCompression: cmsColor.pixel = def->pixel; _XcmsRGB_to_XColor(&cmsColor, def, 1); return(1); case XcmsFailure: case _XCMS_NEWNAME: /* * if the result was _XCMS_NEWNAME tmpName points to * a string in cmsColNm.c:pairs table, for example, * gray70 would become tekhvc:0.0/70.0/0.0 */ break; } } /* * Xcms and i18n methods failed, so lets pass it to the server * for parsing. */ { xLookupColorReply reply; register xLookupColorReq *req; LockDisplay(dpy); GetReq (LookupColor, req); req->cmap = cmap; req->nbytes = n = strlen(spec); req->length += (n + 3) >> 2; Data (dpy, spec, (long)n); if (!_XReply (dpy, (xReply *) &reply, 0, xTrue)) { UnlockDisplay(dpy); SyncHandle(); return (0); } def->red = reply.exactRed; def->green = reply.exactGreen; def->blue = reply.exactBlue; def->flags = DoRed | DoGreen | DoBlue; UnlockDisplay(dpy); SyncHandle(); return (1); } }
sunweaver/nx-libs
nx-X11/lib/X11/ParseCol.c
C
gpl-2.0
3,615
class Currency < Momomoto::Table end
nrr-deprecated/pentabarf
rails/app/models/currency.rb
Ruby
gpl-2.0
37
# -*- coding: utf-8 -*- """ *************************************************************************** doMerge.py --------------------- Date : June 2010 Copyright : (C) 2010 by Giuseppe Sucameli Email : brush dot tyler at gmail dot 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. * * * *************************************************************************** """ __author__ = 'Giuseppe Sucameli' __date__ = 'June 2010' __copyright__ = '(C) 2010, Giuseppe Sucameli' # This will get replaced with a git SHA1 when you do a git archive __revision__ = '$Format:%H$' from PyQt4.QtCore import * from PyQt4.QtGui import * from qgis.core import * from qgis.gui import * from ui_widgetMerge import Ui_GdalToolsWidget as Ui_Widget from widgetPluginBase import GdalToolsBasePluginWidget as BasePluginWidget import GdalTools_utils as Utils class GdalToolsDialog(QWidget, Ui_Widget, BasePluginWidget): def __init__(self, iface): QWidget.__init__(self) self.iface = iface self.setupUi(self) BasePluginWidget.__init__(self, self.iface, "gdal_merge.py") self.inSelector.setType( self.inSelector.FILE ) self.outSelector.setType( self.outSelector.FILE ) self.recurseCheck.hide() # use this for approx. previous UI #self.creationOptionsWidget.setType(QgsRasterFormatSaveOptionsWidget.Table) self.outputFormat = Utils.fillRasterOutputFormat() self.extent = None self.setParamsStatus( [ (self.inSelector, SIGNAL("filenameChanged()")), (self.outSelector, SIGNAL("filenameChanged()")), (self.noDataSpin, SIGNAL("valueChanged(int)"), self.noDataCheck), (self.inputDirCheck, SIGNAL("stateChanged(int)")), (self.recurseCheck, SIGNAL("stateChanged(int)"), self.inputDirCheck), ( self.separateCheck, SIGNAL( "stateChanged( int )" ) ), ( self.pctCheck, SIGNAL( "stateChanged( int )" ) ), ( self.intersectCheck, SIGNAL( "stateChanged( int )" ) ), (self.creationOptionsWidget, SIGNAL("optionsChanged()")), (self.creationOptionsGroupBox, SIGNAL("toggled(bool)")) ] ) self.connect(self.inSelector, SIGNAL("selectClicked()"), self.fillInputFilesEdit) self.connect(self.outSelector, SIGNAL("selectClicked()"), self.fillOutputFileEdit) self.connect(self.intersectCheck, SIGNAL("toggled(bool)"), self.refreshExtent) self.connect(self.inputDirCheck, SIGNAL("stateChanged( int )"), self.switchToolMode) self.connect(self.inSelector, SIGNAL("filenameChanged()"), self.refreshExtent) def switchToolMode(self): self.recurseCheck.setVisible( self.inputDirCheck.isChecked() ) self.inSelector.clear() if self.inputDirCheck.isChecked(): self.inFileLabel = self.label.text() self.label.setText( QCoreApplication.translate( "GdalTools", "&Input directory" ) ) QObject.disconnect(self.inSelector, SIGNAL("selectClicked()"), self.fillInputFilesEdit) QObject.connect(self.inSelector, SIGNAL("selectClicked()"), self.fillInputDir) else: self.label.setText( self.inFileLabel ) QObject.connect(self.inSelector, SIGNAL("selectClicked()"), self.fillInputFilesEdit) QObject.disconnect(self.inSelector, SIGNAL("selectClicked()"), self.fillInputDir) def fillInputFilesEdit(self): lastUsedFilter = Utils.FileFilter.lastUsedRasterFilter() files = Utils.FileDialog.getOpenFileNames(self, self.tr( "Select the files to Merge" ), Utils.FileFilter.allRastersFilter(), lastUsedFilter ) if not files: return Utils.FileFilter.setLastUsedRasterFilter(lastUsedFilter) self.inSelector.setFilename(files) def refreshExtent(self): files = self.getInputFileNames() self.intersectCheck.setEnabled( len(files) > 1 ) if not self.intersectCheck.isChecked(): self.someValueChanged() return if len(files) < 2: self.intersectCheck.setChecked( False ) return self.extent = self.getIntersectedExtent( files ) if self.extent == None: QMessageBox.warning( self, self.tr( "Error retrieving the extent" ), self.tr( 'GDAL was unable to retrieve the extent from any file. \nThe "Use intersected extent" option will be unchecked.' ) ) self.intersectCheck.setChecked( False ) return elif self.extent.isEmpty(): QMessageBox.warning( self, self.tr( "Empty extent" ), self.tr( 'The computed extent is empty. \nDisable the "Use intersected extent" option to have a nonempty output.' ) ) self.someValueChanged() def fillOutputFileEdit(self): lastUsedFilter = Utils.FileFilter.lastUsedRasterFilter() outputFile = Utils.FileDialog.getSaveFileName(self, self.tr( "Select where to save the Merge output" ), Utils.FileFilter.allRastersFilter(), lastUsedFilter ) if not outputFile: return Utils.FileFilter.setLastUsedRasterFilter(lastUsedFilter) self.outputFormat = Utils.fillRasterOutputFormat( lastUsedFilter, outputFile ) self.outSelector.setFilename( outputFile ) def fillInputDir( self ): inputDir = Utils.FileDialog.getExistingDirectory( self, self.tr( "Select the input directory with files to Merge" )) if not inputDir: return self.inSelector.setFilename( inputDir ) def getArguments(self): arguments = [] if self.intersectCheck.isChecked(): if self.extent != None: arguments.append("-ul_lr") arguments.append(str( self.extent.xMinimum() )) arguments.append(str( self.extent.yMaximum() )) arguments.append(str( self.extent.xMaximum() )) arguments.append(str( self.extent.yMinimum() )) if self.noDataCheck.isChecked(): arguments.append("-n") arguments.append(str(self.noDataSpin.value())) if Utils.GdalConfig.versionNum() >= 1900: arguments.append("-a_nodata") arguments.append(str(self.noDataSpin.value())) if self.separateCheck.isChecked(): arguments.append("-separate") if self.pctCheck.isChecked(): arguments.append("-pct") if self.creationOptionsGroupBox.isChecked(): for opt in self.creationOptionsWidget.options(): arguments.append("-co") arguments.append(opt) outputFn = self.getOutputFileName() if outputFn: arguments.append("-of") arguments.append(self.outputFormat) arguments.append("-o") arguments.append(outputFn) arguments.extend(self.getInputFileNames()) return arguments def getOutputFileName(self): return self.outSelector.filename() def getInputFileName(self): if self.inputDirCheck.isChecked(): return self.inSelector.filename() return self.inSelector.filename().split(",") def getInputFileNames(self): if self.inputDirCheck.isChecked(): return Utils.getRasterFiles( self.inSelector.filename(), self.recurseCheck.isChecked() ) return self.inSelector.filename().split(",") def addLayerIntoCanvas(self, fileInfo): self.iface.addRasterLayer(fileInfo.filePath()) def getIntersectedExtent(self, files): res = None for fileName in files: if res == None: res = Utils.getRasterExtent( self, fileName ) continue rect2 = Utils.getRasterExtent( self, fileName ) if rect2 == None: continue res = res.intersect( rect2 ) if res.isEmpty(): break return res
mweisman/QGIS
python/plugins/GdalTools/tools/doMerge.py
Python
gpl-2.0
8,061
# # # Licensed under the Apache License, Version 2.0 (the "License"); you may # not use this file except in compliance with the License. You may obtain # a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, WITHOUT # WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the # License for the specific language governing permissions and limitations # under the License. from migrate.changeset.constraint import UniqueConstraint import sqlalchemy from ceilometer.storage.sqlalchemy import models def upgrade(migrate_engine): meta = sqlalchemy.MetaData(bind=migrate_engine) event = sqlalchemy.Table('event', meta, autoload=True) message_id = sqlalchemy.Column('message_id', sqlalchemy.String(50)) event.create_column(message_id) cons = UniqueConstraint('message_id', table=event) cons.create() index = sqlalchemy.Index('idx_event_message_id', models.Event.message_id) index.create(bind=migrate_engine) # Populate the new column ... trait = sqlalchemy.Table('trait', meta, autoload=True) unique_name = sqlalchemy.Table('unique_name', meta, autoload=True) join = trait.join(unique_name, unique_name.c.id == trait.c.name_id) traits = sqlalchemy.select([trait.c.event_id, trait.c.t_string], whereclause=(unique_name.c.key == 'message_id'), from_obj=join) for event_id, value in traits.execute(): (event.update().where(event.c.id == event_id).values(message_id=value). execute()) # Leave the Trait, makes the rollback easier and won't really hurt anyone. def downgrade(migrate_engine): meta = sqlalchemy.MetaData(bind=migrate_engine) event = sqlalchemy.Table('event', meta, autoload=True) message_id = sqlalchemy.Column('message_id', sqlalchemy.String(50)) cons = UniqueConstraint('message_id', table=event) cons.drop() index = sqlalchemy.Index('idx_event_message_id', models.Event.message_id) index.drop(bind=migrate_engine) event.drop_column(message_id)
ChinaMassClouds/copenstack-server
openstack/src/ceilometer-2014.2.2/ceilometer/storage/sqlalchemy/migrate_repo/versions/014_add_event_message_id.py
Python
gpl-2.0
2,211
<?php /** * Function that creates the Manage Fields submenu and populates it with a repeater field form * * @since v.2.0 * * @return void */ function wppb_manage_fields_submenu(){ // create a new sub_menu page which holds the data for the default + extra fields $args = array( 'menu_title' => __( 'Manage Fields', 'profilebuilder' ), 'page_title' => __( 'Manage Default and Extra Fields', 'profilebuilder' ), 'menu_slug' => 'manage-fields', 'page_type' => 'submenu_page', 'capability' => 'manage_options', 'priority' => 5, 'parent_slug' => 'profile-builder' ); $all_fields = new WCK_Page_Creator_PB( $args ); // populate this page $manage_field_types[] = 'Default - Name (Heading)'; $manage_field_types[] = 'Default - Contact Info (Heading)'; $manage_field_types[] = 'Default - About Yourself (Heading)'; $manage_field_types[] = 'Default - Username'; $manage_field_types[] = 'Default - First Name'; $manage_field_types[] = 'Default - Last Name'; $manage_field_types[] = 'Default - Nickname'; $manage_field_types[] = 'Default - E-mail'; $manage_field_types[] = 'Default - Website'; // Default contact methods were removed in WP 3.6. A filter dictates contact methods. if ( apply_filters( 'wppb_remove_default_contact_methods', get_site_option( 'initial_db_version' ) < 23588 ) ){ $manage_field_types[] = 'Default - AIM'; $manage_field_types[] = 'Default - Yahoo IM'; $manage_field_types[] = 'Default - Jabber / Google Talk'; } $manage_field_types[] = 'Default - Password'; $manage_field_types[] = 'Default - Repeat Password'; $manage_field_types[] = 'Default - Biographical Info'; $manage_field_types[] = 'Default - Display name publicly as'; if( PROFILE_BUILDER != 'Profile Builder Free' ) { $manage_field_types[] = 'Heading'; $manage_field_types[] = 'Input'; $manage_field_types[] = 'Input (Hidden)'; $manage_field_types[] = 'Textarea'; $manage_field_types[] = 'WYSIWYG'; $manage_field_types[] = 'Select'; $manage_field_types[] = 'Select (Multiple)'; $manage_field_types[] = 'Select (Country)'; $manage_field_types[] = 'Select (Timezone)'; $manage_field_types[] = 'Select (User Role)'; $manage_field_types[] = 'Checkbox'; $manage_field_types[] = 'Checkbox (Terms and Conditions)'; $manage_field_types[] = 'Radio'; $manage_field_types[] = 'Upload'; $manage_field_types[] = 'Avatar'; $manage_field_types[] = 'Datepicker'; $manage_field_types[] = 'reCAPTCHA'; } //Free to Pro call to action on Manage Fields page $field_description = 'Choose one of the supported field types'; if( PROFILE_BUILDER == 'Profile Builder Free' ) { $field_description .='. Extra Field Types are available in %1$sHobbyist or PRO versions%2$s.'; } //user roles global $wp_roles; $user_roles = array(); foreach( $wp_roles->roles as $user_role_slug => $user_role ) if( $user_role_slug !== 'administrator' ) array_push( $user_roles, '%' . $user_role['name'] . '%' . $user_role_slug ); // set up the fields array $fields = apply_filters( 'wppb_manage_fields', array( array( 'type' => 'text', 'slug' => 'field-title', 'title' => __( 'Field Title', 'profilebuilder' ), 'description' => __( 'Title of the field', 'profilebuilder' ) ), array( 'type' => 'select', 'slug' => 'field', 'title' => __( 'Field', 'profilebuilder' ), 'options' => apply_filters( 'wppb_manage_fields_types', $manage_field_types ), 'default-option' => true, 'description' => sprintf(__( $field_description, 'profilebuilder' ), '<a href="http://www.cozmoslabs.com/wordpress-profile-builder/?utm_source=wpbackend&utm_medium=clientsite&utm_content=manage-fields-link&utm_campaign=PBFree">', '</a>') ), array( 'type' => 'text', 'slug' => 'meta-name', 'title' => __( 'Meta-name', 'profilebuilder' ), 'default' => wppb_get_meta_name(), 'description' => __( 'Use this in conjuction with WordPress functions to display the value in the page of your choosing<br/>Auto-completed but in some cases editable (in which case it must be uniqe)<br/>Changing this might take long in case of a very big user-count', 'profilebuilder' ) ), array( 'type' => 'text', 'slug' => 'id', 'title' => __( 'ID', 'profilebuilder' ), 'default' => wppb_get_unique_id(), 'description' => __( "A unique, auto-generated ID for this particular field<br/>You can use this in conjuction with filters to target this element if needed<br/>Can't be edited", 'profilebuilder' ), 'readonly' => true ), array( 'type' => 'textarea', 'slug' => 'description', 'title' => __( 'Description', 'profilebuilder' ), 'description' => __( 'Enter a (detailed) description of the option for end users to read<br/>Optional', 'profilebuilder') ), array( 'type' => 'text', 'slug' => 'row-count', 'title' => __( 'Row Count', 'profilebuilder' ), 'default' => 5, 'description' => __( "Specify the number of rows for a 'Textarea' field<br/>If not specified, defaults to 5", 'profilebuilder' ) ), array( 'type' => 'text', 'slug' => 'allowed-image-extensions', 'title' => __( 'Allowed Image Extensions', 'profilebuilder' ), 'default' => '.*', 'description' => __( 'Specify the extension(s) you want to limit to upload<br/>Example: .ext1,.ext2,.ext3<br/>If not specified, defaults to: .jpg,.jpeg,.gif,.png (.*)', 'profilebuilder' ) ), array( 'type' => 'text', 'slug' => 'allowed-upload-extensions', 'title' => __( 'Allowed Upload Extensions', 'profilebuilder' ), 'default' => '.*', 'description' => __( 'Specify the extension(s) you want to limit to upload<br/>Example: .ext1,.ext2,.ext3<br/>If not specified, defaults to all WordPress allowed file extensions (.*)', 'profilebuilder' ) ), array( 'type' => 'text', 'slug' => 'avatar-size', 'title' => __( 'Avatar Size', 'profilebuilder' ), 'default' => 100, 'description' => __( "Enter a value (between 20 and 200) for the size of the 'Avatar'<br/>If not specified, defaults to 100", 'profilebuilder' ) ), array( 'type' => 'text', 'slug' => 'date-format', 'title' => __( 'Date-format', 'profilebuilder' ), 'default' => 'mm/dd/yy', 'description' => __( 'Specify the format of the date when using Datepicker<br/>Valid options: mm/dd/yy, mm/yy/dd, dd/yy/mm, dd/mm/yy, yy/dd/mm, yy/mm/dd<br/>If not specified, defaults to mm/dd/yy', 'profilebuilder' ) ), array( 'type' => 'textarea', 'slug' => 'terms-of-agreement', 'title' => __( 'Terms of Agreement', 'profilebuilder' ), 'description' => __( 'Enter a detailed description of the temrs of agreement for the user to read.<br/>Links can be inserted by using standard HTML syntax: &lt;a href="custom_url"&gt;custom_text&lt;/a&gt;', 'profilebuilder' ) ), array( 'type' => 'text', 'slug' => 'options', 'title' => __( 'Options', 'profilebuilder' ), 'description' => __( "Enter a comma separated list of values<br/>This can be anything, as it is hidden from the user, but should not contain special characters or apostrophes", 'profilebuilder' ) ), array( 'type' => 'text', 'slug' => 'labels', 'title' => __( 'Labels', 'profilebuilder' ), 'description' => __( "Enter a comma separated list of labels<br/>Visible for the user", 'profilebuilder' ) ), array( 'type' => 'text', 'slug' => 'public-key', 'title' => __( 'Public Key', 'profilebuilder' ), 'description' => __( 'The public key from Google, <a href="http://www.google.com/recaptcha" target="_blank">www.google.com/recaptcha</a>', 'profilebuilder' ) ), array( 'type' => 'text', 'slug' => 'private-key', 'title' => __( 'Private Key', 'profilebuilder' ), 'description' => __( 'The private key from Google, <a href="http://www.google.com/recaptcha" target="_blank">www.google.com/recaptcha</a>', 'profilebuilder' ) ), array( 'type' => 'checkbox', 'slug' => 'user-roles', 'title' => __( 'User Roles', 'profilebuilder' ), 'options' => $user_roles, 'description' => __( "Select which user roles to show to the user ( drag and drop to re-order )", 'profilebuilder' ) ), array( 'type' => 'text', 'slug' => 'user-roles-sort-order', 'title' => __( 'User Roles Order', 'profilebuilder' ), 'description' => __( "Save the user role order from the user roles checkboxes", 'profilebuilder' ) ), array( 'type' => 'text', 'slug' => 'default-value', 'title' => __( 'Default Value', 'profilebuilder' ), 'description' => __( "Default value of the field", 'profilebuilder' ) ), array( 'type' => 'text', 'slug' => 'default-option', 'title' => __( 'Default Option', 'profilebuilder' ), 'description' => __( "Specify the option which should be selected by default", 'profilebuilder' ) ), array( 'type' => 'text', 'slug' => 'default-options', 'title' => __( 'Default Option(s)', 'profilebuilder' ), 'description' => __( "Specify the option which should be checked by default<br/>If there are multiple values, separate them with a ',' (comma)", 'profilebuilder' ) ), array( 'type' => 'textarea', 'slug' => 'default-content', 'title' => __( 'Default Content', 'profilebuilder' ), 'description' => __( "Default value of the textarea", 'profilebuilder' ) ), array( 'type' => 'select', 'slug' => 'required', 'title' => __( 'Required', 'profilebuilder' ), 'options' => array( 'No', 'Yes' ), 'default' => 'No', 'description' => __( 'Whether the field is required or not', 'profilebuilder' ) ), array( 'type' => 'select', 'slug' => 'overwrite-existing', 'title' => __( 'Overwrite Existing', 'profilebuilder' ), 'options' => array( 'No', 'Yes' ), 'default' => 'No', 'description' => __( "Selecting 'Yes' will add the field to the list, but will overwrite any other field in the database that has the same meta-name<br/>Use this at your own risk", 'profilebuilder' ) ), ) ); // create the new submenu with the above options $args = array( 'metabox_id' => 'manage-fields', 'metabox_title' => __( 'Field Properties', 'profilebuilder' ), 'post_type' => 'manage-fields', 'meta_name' => 'wppb_manage_fields', 'meta_array' => $fields, 'context' => 'option' ); new Wordpress_Creation_Kit_PB( $args ); wppb_prepopulate_fields(); // create the info side meta-box $args = array( 'metabox_id' => 'manage-fields-info', 'metabox_title' => __( 'Registration & Edit Profile', 'profilebuilder' ), 'post_type' => 'manage-fields', 'meta_name' => 'wppb_manage_fields_info', 'meta_array' => '', 'context' => 'option', 'mb_context' => 'side' ); new Wordpress_Creation_Kit_PB( $args ); } add_action( 'init', 'wppb_manage_fields_submenu', 10 ); /** * Function that prepopulates the manage fields list with the default fields of WP * * @since v.2.0 * * @return void */ function wppb_prepopulate_fields(){ $prepopulated_fields[] = array( 'field' => 'Default - Name (Heading)', 'field-title' => __( 'Name', 'profilebuilder' ), 'meta-name' => '', 'overwrite-existing' => 'No', 'id' => '1', 'description' => '', 'row-count' => '5', 'allowed-image-extensions' => '.*', 'allowed-upload-extensions' => '.*', 'avatar-size' => '100', 'date-format' => 'mm/dd/yy', 'terms-of-agreement' => '', 'options' => '', 'labels' => '', 'public-key' => '', 'private-key' => '', 'default-value' => '', 'default-option' => '', 'default-options' => '', 'default-content' => '', 'required' => 'No' ); $prepopulated_fields[] = array( 'field' => 'Default - Username', 'field-title' => __( 'Username', 'profilebuilder' ), 'meta-name' => '', 'overwrite-existing' => 'No', 'id' => '2', 'description' => __( 'Usernames cannot be changed.', 'profilebuilder' ), 'row-count' => '5', 'allowed-image-extensions' => '.*', 'allowed-upload-extensions' => '.*', 'avatar-size' => '100', 'date-format' => 'mm/dd/yy', 'terms-of-agreement' => '', 'options' => '', 'labels' => '', 'public-key' => '', 'private-key' => '', 'default-value' => '', 'default-option' => '', 'default-options' => '', 'default-content' => '', 'required' => 'Yes' ); $prepopulated_fields[] = array( 'field' => 'Default - First Name', 'field-title' => __( 'First Name', 'profilebuilder' ), 'meta-name' => 'first_name', 'overwrite-existing' => 'No', 'id' => '3', 'description' => '', 'row-count' => '5', 'allowed-image-extensions' => '.*', 'allowed-upload-extensions' => '.*', 'avatar-size' => '100', 'date-format' => 'mm/dd/yy', 'terms-of-agreement' => '', 'options' => '', 'labels' => '', 'public-key' => '', 'private-key' => '', 'default-value' => '', 'default-option' => '', 'default-options' => '', 'default-content' => '', 'required' => 'No' ); $prepopulated_fields[] = array( 'field' => 'Default - Last Name', 'field-title' => __( 'Last Name', 'profilebuilder' ), 'meta-name' => 'last_name', 'overwrite-existing' => 'No', 'id' => '4', 'description' => '', 'row-count' => '5', 'allowed-image-extensions' => '.*', 'allowed-upload-extensions' => '.*', 'avatar-size' => '100', 'date-format' => 'mm/dd/yy', 'terms-of-agreement' => '', 'options' => '', 'labels' => '', 'public-key' => '', 'private-key' => '', 'default-value' => '', 'default-option' => '', 'default-options' => '', 'default-content' => '', 'required' => 'No' ); $prepopulated_fields[] = array( 'field' => 'Default - Nickname', 'field-title' => __( 'Nickname', 'profilebuilder' ), 'meta-name' => 'nickname', 'overwrite-existing' => 'No', 'id' => '5', 'description' => '', 'row-count' => '5', 'allowed-image-extensions' => '.*', 'allowed-upload-extensions' => '.*', 'avatar-size' => '100', 'date-format' => 'mm/dd/yy', 'terms-of-agreement' => '', 'options' => '', 'labels' => '', 'public-key' => '', 'private-key' => '', 'default-value' => '', 'default-option' => '', 'default-options' => '', 'default-content' => '', 'required' => 'Yes' ); $prepopulated_fields[] = array( 'field' => 'Default - Display name publicly as', 'field-title' => __( 'Display name publicly as', 'profilebuilder' ), 'meta-name' => '', 'overwrite-existing' => 'No', 'id' => '6', 'description' => '', 'row-count' => '5', 'allowed-image-extensions' => '.*', 'allowed-upload-extensions' => '.*', 'avatar-size' => '100', 'date-format' => 'mm/dd/yy', 'terms-of-agreement' => '', 'options' => '', 'labels' => '', 'public-key' => '', 'private-key' => '', 'default-value' => '', 'default-option' => '', 'default-options' => '', 'default-content' => '', 'required' => 'No' ); $prepopulated_fields[] = array( 'field' => 'Default - Contact Info (Heading)', 'field-title' => __( 'Contact Info', 'profilebuilder' ), 'meta-name' => '', 'overwrite-existing' => 'No', 'id' => '7', 'description' => '', 'row-count' => '5', 'allowed-image-extensions' => '.*', 'allowed-upload-extensions' => '.*', 'avatar-size' => '100', 'date-format' => 'mm/dd/yy', 'terms-of-agreement' => '', 'options' => '', 'labels' => '', 'public-key' => '', 'private-key' => '', 'default-value' => '', 'default-option' => '', 'default-options' => '', 'default-content' => '', 'required' => 'No' ); $prepopulated_fields[] = array( 'field' => 'Default - E-mail', 'field-title' => __( 'E-mail', 'profilebuilder' ), 'meta-name' => '', 'overwrite-existing' => 'No', 'id' => '8', 'description' => '', 'row-count' => '5', 'allowed-image-extensions' => '.*', 'allowed-upload-extensions' => '.*', 'avatar-size' => '100', 'date-format' => 'mm/dd/yy', 'terms-of-agreement' => '', 'options' => '', 'labels' => '', 'public-key' => '', 'private-key' => '', 'default-value' => '', 'default-option' => '', 'default-options' => '', 'default-content' => '', 'required' => 'Yes' ); $prepopulated_fields[] = array( 'field' => 'Default - Website', 'field-title' => __( 'Website', 'profilebuilder' ), 'meta-name' => '', 'overwrite-existing' => 'No', 'id' => '9', 'description' => '', 'row-count' => '5', 'allowed-image-extensions' => '.*', 'allowed-upload-extensions' => '.*', 'avatar-size' => '100', 'date-format' => 'mm/dd/yy', 'terms-of-agreement' => '', 'options' => '', 'labels' => '', 'public-key' => '', 'private-key' => '', 'default-value' => '', 'default-option' => '', 'default-options' => '', 'default-content' => '', 'required' => 'No' ); // Default contact methods were removed in WP 3.6. A filter dictates contact methods. if ( apply_filters( 'wppb_remove_default_contact_methods', get_site_option( 'initial_db_version' ) < 23588 ) ){ $prepopulated_fields[] = array( 'field' => 'Default - AIM', 'field-title' => __( 'AIM', 'profilebuilder' ), 'meta-name' => 'aim', 'overwrite-existing' => 'No', 'id' => '10', 'description' => '', 'row-count' => '5', 'allowed-image-extensions' => '.*', 'allowed-upload-extensions' => '.*', 'avatar-size' => '100', 'date-format' => 'mm/dd/yy', 'terms-of-agreement' => '', 'options' => '', 'labels' => '', 'public-key' => '', 'private-key' => '', 'default-value' => '', 'default-option' => '', 'default-options' => '', 'default-content' => '', 'required' => 'No' ); $prepopulated_fields[] = array( 'field' => 'Default - Yahoo IM', 'field-title' => __( 'Yahoo IM', 'profilebuilder' ), 'meta-name' => 'yim', 'overwrite-existing' => 'No', 'id' => '11', 'description' => '', 'row-count' => '5', 'allowed-image-extensions' => '.*', 'allowed-upload-extensions' => '.*', 'avatar-size' => '100', 'date-format' => 'mm/dd/yy', 'terms-of-agreement' => '', 'options' => '', 'labels' => '', 'public-key' => '', 'private-key' => '', 'default-value' => '', 'default-option' => '', 'default-options' => '', 'default-content' => '', 'required' => 'No' ); $prepopulated_fields[] = array( 'field' => 'Default - Jabber / Google Talk', 'field-title' => __( 'Jabber / Google Talk', 'profilebuilder' ), 'meta-name' => 'jabber', 'overwrite-existing' => 'No', 'id' => '12', 'description' => '', 'row-count' => '5', 'allowed-image-extensions' => '.*', 'allowed-upload-extensions' => '.*', 'avatar-size' => '100', 'date-format' => 'mm/dd/yy', 'terms-of-agreement' => '', 'options' => '', 'labels' => '', 'public-key' => '', 'private-key' => '', 'default-value' => '', 'default-option' => '', 'default-options' => '', 'default-content' => '', 'required' => 'No' ); } $prepopulated_fields[] = array( 'field' => 'Default - About Yourself (Heading)', 'field-title' => __( 'About Yourself', 'profilebuilder' ), 'meta-name' => '', 'overwrite-existing' => 'No', 'id' => '13', 'description' => '', 'row-count' => '5', 'allowed-image-extensions' => '.*', 'allowed-upload-extensions' => '.*', 'avatar-size' => '100', 'date-format' => 'mm/dd/yy', 'terms-of-agreement' => '', 'options' => '', 'labels' => '', 'public-key' => '', 'private-key' => '', 'default-value' => '', 'default-option' => '', 'default-options' => '', 'default-content' => '', 'required' => 'No' ); $prepopulated_fields[] = array( 'field' => 'Default - Biographical Info', 'field-title' => __( 'Biographical Info', 'profilebuilder' ), 'meta-name' => 'description', 'overwrite-existing' => 'No', 'id' => '14', 'description' => __( 'Share a little biographical information to fill out your profile. This may be shown publicly.', 'profilebuilder' ), 'row-count' => '5', 'allowed-image-extensions' => '.*', 'allowed-upload-extensions' => '.*', 'avatar-size' => '100', 'date-format' => 'mm/dd/yy', 'terms-of-agreement' => '', 'options' => '', 'labels' => '', 'public-key' => '', 'private-key' => '', 'default-value' => '', 'default-option' => '', 'default-options' => '', 'required' => 'No' ); $prepopulated_fields[] = array( 'field' => 'Default - Password', 'field-title' => __( 'Password', 'profilebuilder' ), 'meta-name' => '', 'overwrite-existing' => 'No', 'id' => '15', 'description' => __( 'Type your password.', 'profilebuilder' ), 'row-count' => '5', 'allowed-image-extensions' => '.*', 'allowed-upload-extensions' => '.*', 'avatar-size' => '100', 'date-format' => 'mm/dd/yy', 'terms-of-agreement' => '', 'options' => '', 'labels' => '', 'public-key' => '', 'private-key' => '', 'default-value' => '', 'default-option' => '', 'default-options' => '', 'default-content' => '', 'required' => 'Yes' ); $prepopulated_fields[] = array( 'field' => 'Default - Repeat Password', 'field-title' => __( 'Repeat Password', 'profilebuilder' ), 'meta-name' => '', 'overwrite-existing' => 'No', 'id' => '16', 'description' => __( 'Type your password again. ', 'profilebuilder' ), 'row-count' => '5', 'allowed-image-extensions' => '.*', 'allowed-upload-extensions' => '.*', 'avatar-size' => '100', 'date-format' => 'mm/dd/yy', 'terms-of-agreement' => '', 'options' => '', 'labels' => '', 'public-key' => '', 'private-key' => '', 'default-value' => '', 'default-option' => '', 'default-options' => '', 'default-content' => '', 'required' => 'Yes' ); add_option ( 'wppb_manage_fields', apply_filters ( 'wppb_prepopulated_fields', $prepopulated_fields ) ); } /** * Function that returns a unique meta-name * * @since v.2.0 * * @return string */ function wppb_get_meta_name(){ $id = 1; $wppb_manage_fields = get_option( 'wppb_manage_fields', 'not_found' ); if ( ( $wppb_manage_fields === 'not_found' ) || ( empty( $wppb_manage_fields ) ) ){ return 'custom_field_' . $id; } else{ $meta_names = array(); foreach( $wppb_manage_fields as $value ){ if ( strpos( $value['meta-name'], 'custom_field' ) === 0 ){ $meta_names[] = $value['meta-name']; } } if( !empty( $meta_names ) ){ $meta_numbers = array(); foreach( $meta_names as $meta_name ){ $number = str_replace( 'custom_field', '', $meta_name ); /* we should have an underscore present in custom_field_# so remove it */ $number = str_replace( '_', '', $number ); $meta_numbers[] = $number; } if( !empty( $meta_numbers ) ){ rsort( $meta_numbers ); $id = $meta_numbers[0]+1; } } return 'custom_field_' . $id; } } /** * Function that returns a unique, incremented ID * * @since v.2.0 * * @return integer id */ function wppb_get_unique_id(){ $id = 1; $wppb_manage_fields = get_option( 'wppb_manage_fields', 'not_found' ); if ( ( $wppb_manage_fields === 'not_found' ) || ( empty( $wppb_manage_fields ) ) ){ return $id; } else{ $ids_array = array(); foreach( $wppb_manage_fields as $value ){ $ids_array[] = $value['id']; } if( !empty( $ids_array ) ){ rsort( $ids_array ); $id = $ids_array[0] + 1; } } return $id; } /** * Function that checks to see if the id is unique when saving the new field * * @param array $values * * @return array */ function wppb_check_unique_id_on_saving( $values ) { $wppb_manage_fields = get_option( 'wppb_manage_fields', 'not_found' ); if( $wppb_manage_fields != 'not_found' ) { $ids_array = array(); foreach( $wppb_manage_fields as $field ){ $ids_array[] = $field['id']; } if( in_array( $values['id'], $ids_array ) ) { rsort( $ids_array ); $values['id'] = $ids_array[0] + 1; } } return $values; } add_filter( 'wck_add_meta_filter_values_wppb_manage_fields', 'wppb_check_unique_id_on_saving' ); function wppb_return_unique_field_list( $only_default_fields = false ){ $unique_field_list[] = 'Default - Name (Heading)'; $unique_field_list[] = 'Default - Contact Info (Heading)'; $unique_field_list[] = 'Default - About Yourself (Heading)'; $unique_field_list[] = 'Default - Username'; $unique_field_list[] = 'Default - First Name'; $unique_field_list[] = 'Default - Last Name'; $unique_field_list[] = 'Default - Nickname'; $unique_field_list[] = 'Default - E-mail'; $unique_field_list[] = 'Default - Website'; // Default contact methods were removed in WP 3.6. A filter dictates contact methods. if ( apply_filters( 'wppb_remove_default_contact_methods', get_site_option( 'initial_db_version' ) < 23588 ) ){ $unique_field_list[] = 'Default - AIM'; $unique_field_list[] = 'Default - Yahoo IM'; $unique_field_list[] = 'Default - Jabber / Google Talk'; } $unique_field_list[] = 'Default - Password'; $unique_field_list[] = 'Default - Repeat Password'; $unique_field_list[] = 'Default - Biographical Info'; $unique_field_list[] = 'Default - Display name publicly as'; if( !$only_default_fields ){ $unique_field_list[] = 'Avatar'; $unique_field_list[] = 'reCAPTCHA'; $unique_field_list[] = 'Select (User Role)'; } return apply_filters ( 'wppb_unique_field_list', $unique_field_list ); } /** * Function that checks several things when adding/editing the fields * * @since v.2.0 * * @param string $message - the message to be displayed * @param array $fields - the added fields * @param array $required_fields * @param string $meta - the meta-name of the option * @param string $values - The values entered for each option * @param integer $post_id * @return boolean */ function wppb_check_field_on_edit_add( $message, $fields, $required_fields, $meta_name, $posted_values, $post_id ){ global $wpdb; if ( $meta_name == 'wppb_manage_fields' ){ // check for a valid field-type (fallback) if ( $posted_values['field'] == '' ) $message .= __( "You must select a field\n", 'profilebuilder' ); // END check for a valid field-type (fallback) $unique_field_list = wppb_return_unique_field_list(); $all_fields = get_option ( $meta_name, 'not_set' ); // check if the unique fields are only added once if( $all_fields != 'not_set' ){ foreach( $all_fields as $field ){ if ( ( in_array ( $posted_values['field'], $unique_field_list ) ) && ( $posted_values['field'] == $field['field'] ) && ( $posted_values['id'] != $field['id'] ) ){ $message .= __( "Please choose a different field type as this one already exists in your form (must be unique)\n", 'profilebuilder' ); break; } } } // END check if the unique fields are only added once // check for avatar size if ( $posted_values['field'] == 'Avatar' ){ if ( is_numeric( $posted_values['avatar-size'] ) ){ if ( ( $posted_values['avatar-size'] < 20 ) || ( $posted_values['avatar-size'] > 200 ) ) $message .= __( "The entered avatar size is not between 20 and 200\n", 'profilebuilder' ); }else $message .= __( "The entered avatar size is not numerical\n", 'profilebuilder' ); } // END check for avatar size // check for correct row value if ( ( $posted_values['field'] == 'Default - Biographical Info' ) || ( $posted_values['field'] == 'Textarea' ) ){ if ( !is_numeric( $posted_values['row-count'] ) ) $message .= __( "The entered row number is not numerical\n", 'profilebuilder' ); elseif ( trim( $posted_values['row-count'] ) == '' ) $message .= __( "You must enter a value for the row number\n", 'profilebuilder' ); } // END check for correct row value // check for the public and private keys if ( $posted_values['field'] == 'reCAPTCHA'){ if ( trim( $posted_values['public-key'] ) == '' ) $message .= __( "You must enter the public key\n", 'profilebuilder' ); if ( trim( $posted_values['private-key'] ) == '' ) $message .= __( "You must enter the private key\n", 'profilebuilder' ); } // END check for the public and private keys // check for the correct the date-format if ( $posted_values['field'] == 'Datepicker' ){ $date_format = strtolower( $posted_values['date-format'] ); if ( ( trim( $date_format ) != 'mm/dd/yy' ) && ( trim( $date_format ) != 'mm/yy/dd' ) && ( trim( $date_format ) != 'dd/yy/mm' ) && ( trim( $date_format ) != 'dd/mm/yy' ) && ( trim( $date_format ) != 'yy/dd/mm' ) && ( trim( $date_format ) != 'yy/mm/dd' ) ) $message .= __( "The entered value for the Datepicker is not a valid date-format\n", 'profilebuilder' ); elseif ( trim( $date_format ) == '' ) $message .= __( "You must enter a value for the date-format\n", 'profilebuilder' ); } // END check for the correct the date-format //check for empty meta-name and duplicate meta-name if ( $posted_values['overwrite-existing'] == 'No' ){ $skip_check_for_fields = wppb_return_unique_field_list(true); $skip_check_for_fields = apply_filters ( 'wppb_skip_check_for_fields', $skip_check_for_fields ); if ( !in_array( trim( $posted_values['field'] ), $skip_check_for_fields ) ){ $unique_meta_name_list = array( 'first_name', 'last_name', 'nickname', 'description' ); //check to see if meta-name is empty $skip_empty_check_for_fields = array('Heading', 'Select (User Role)', 'reCAPTCHA'); if( !in_array( $posted_values['field'], $skip_empty_check_for_fields ) && empty( $posted_values['meta-name'] ) ) { $message .= __( "The meta-name cannot be empty\n", 'profilebuilder' ); } // Default contact methods were removed in WP 3.6. A filter dictates contact methods. if ( apply_filters( 'wppb_remove_default_contact_methods', get_site_option( 'initial_db_version' ) < 23588 ) ){ $unique_meta_name_list[] = 'aim'; $unique_meta_name_list[] = 'yim'; $unique_meta_name_list[] = 'jabber'; } // if the desired meta-name is one of the following, automatically give an error if ( in_array( trim( $posted_values['meta-name'] ), apply_filters ( 'wppb_unique_meta_name_list', $unique_meta_name_list ) ) ) $message .= __( "That meta-name is already in use\n", 'profilebuilder' ); else{ $found_in_custom_fields = false; if( $all_fields != 'not_set' ) foreach( $all_fields as $field ){ if ( $posted_values['meta-name'] != '' && ( $field['meta-name'] == $posted_values['meta-name'] ) && ( $field['id'] != $posted_values['id'] ) ){ $message .= __( "That meta-name is already in use\n", 'profilebuilder' ); $found_in_custom_fields = true; }elseif ( ( $field['meta-name'] == $posted_values['meta-name'] ) && ( $field['id'] == $posted_values['id'] ) ) $found_in_custom_fields = true; } if ( $found_in_custom_fields === false ){ $found_meta_name = $wpdb->get_row( $wpdb->prepare( "SELECT * FROM $wpdb->usermeta WHERE meta_key = %s", $posted_values['meta-name'] ) ); if ( $found_meta_name != null ) $message .= __( "That meta-name is already in use\n", 'profilebuilder' ); } } } } //END check duplicate meta-name // check for valid default option (checkbox, select, radio) if ( ( $posted_values['field'] == 'Checkbox' ) || ( $posted_values['field'] == 'Select (Multiple)' ) ) { $options = array_map( 'trim', explode( ',', $posted_values['options'] ) ); $default_options = ( ( trim( $posted_values['default-options'] ) == '' ) ? array() : array_map( 'trim', explode( ',', $posted_values['default-options'] ) ) ); /* echo "<script>console.log( Posted options: " . print_r($options, true) . "' );</script>"; echo "<script>console.log( Default options: " . print_r($default_options, true) . "' );</script>"; */ $not_found = ''; foreach ( $default_options as $key => $value ){ if ( !in_array( $value, $options ) ) $not_found .= $value . ', '; } if ( $not_found != '' ) $message .= sprintf( __( "The following option(s) did not coincide with the ones in the options list: %s\n", 'profilebuilder' ), trim( $not_found, ', ' ) ); }elseif ( ( $posted_values['field'] == 'Radio' ) || ( $posted_values['field'] == 'Select' ) ){ if ( ( trim( $posted_values['default-option'] ) != '' ) && ( !in_array( $posted_values['default-option'], array_map( 'trim', explode( ',', $posted_values['options'] ) ) ) ) ) $message .= sprintf( __( "The following option did not coincide with the ones in the options list: %s\n", 'profilebuilder' ), $posted_values['default-option'] ); } // END check for valid default option (checkbox, select, radio) // check to see if any user role is selected (user-role field) if( $posted_values['field'] == 'Select (User Role)' ) { if( empty( $posted_values['user-roles'] ) ) { $message .= __( "Please select at least one user role\n", 'profilebuilder' ); } } // END check to see if Administrator user role has been selected (user-role field) $message = apply_filters( 'wppb_check_extra_manage_fields', $message, $posted_values ); }elseif ( ( $meta_name == 'wppb_rf_fields' ) || ( $meta_name == 'wppb_epf_fields' ) ){ if ( $posted_values['field'] == '' ){ $message .= __( "You must select a field\n", 'profilebuilder' ); }else{ $fields_so_far = get_post_meta ( $post_id, $meta_name, true ); foreach ( $fields_so_far as $key => $value ){ if ( $value['field'] == $posted_values['field'] ) $message .= __( "That field is already added in this form\n", 'profilebuilder' ); } } } return $message; } add_filter( 'wck_extra_message', 'wppb_check_field_on_edit_add', 10, 6 ); /** * Function that calls the wppb_hide_properties_for_already_added_fields after a field-update * * @since v.2.0 * * @param void * * @return string */ function wppb_manage_fields_after_refresh_list( $id ){ echo "<script type=\"text/javascript\">wppb_hide_properties_for_already_added_fields( '#container_wppb_manage_fields' );</script>"; } add_action( "wck_refresh_list_wppb_manage_fields", "wppb_manage_fields_after_refresh_list" ); add_action( "wck_refresh_entry_wppb_manage_fields", "wppb_manage_fields_after_refresh_list" ); /** * Function that calls the wppb_hide_all * * @since v.2.0 * * @param void * * @return string */ function wppb_hide_all_after_add( $id ){ echo "<script type=\"text/javascript\">wppb_hide_all( '#wppb_manage_fields' );</script>"; } add_action("wck_ajax_add_form_wppb_manage_fields", "wppb_hide_all_after_add" ); /** * Function that modifies the table header in Manage Fields to add Field Name, Field Type, Meta Key, Required * * @since v.2.0 * * @param $list, $id * * @return string */ function wppb_manage_fields_header( $list_header ){ return '<thead><tr><th class="wck-number">#</th><th class="wck-content">'. __( '<pre>Title</pre><pre>Type</pre><pre>Meta Name</pre><pre class="wppb-mb-head-required">Required</pre>', 'profilebuilder' ) .'</th><th class="wck-edit">'. __( 'Edit', 'profilebuilder' ) .'</th><th class="wck-delete">'. __( 'Delete', 'profilebuilder' ) .'</th></tr></thead>'; } add_action( 'wck_metabox_content_header_wppb_manage_fields', 'wppb_manage_fields_header' ); /** * Add contextual help to the side of manage fields for the shortcodes * * @since v.2.0 * * @param $hook * * @return string */ function wppb_add_content_before_manage_fields(){ ?> <p><?php _e('Use these shortcodes on the pages you want the forms to be displayed:', 'profilebuilder'); ?></p> <ul> <li><strong class="nowrap">[wppb-register]</strong></li> <li><strong class="nowrap">[wppb-edit-profile]</strong></li> <li><strong class="nowrap">[wppb-register role="author"]</strong></li> </ul> <p><?php _e("If you're interested in displaying different fields in the registration and edit profile forms, please use the Multiple Registration & Edit Profile Forms Addon.", 'profilebuilder'); ?></p> <?php } add_action('wck_metabox_content_wppb_manage_fields_info', 'wppb_add_content_before_manage_fields'); /** * Function that calls the wppb_edit_form_properties * * @since v.2.0 * * @param void * * @return string */ function wppb_remove_properties_from_added_form( $meta_name, $id, $element_id ){ if ( ( $meta_name == 'wppb_epf_fields' ) || ( $meta_name == 'wppb_rf_fields' ) ) echo "<script type=\"text/javascript\">wppb_disable_delete_on_default_mandatory_fields();</script>"; if ( $meta_name == 'wppb_manage_fields' ) echo "<script type=\"text/javascript\">wppb_edit_form_properties( '#container_wppb_manage_fields', 'update_container_wppb_manage_fields_".$element_id."' );</script>"; } add_action("wck_after_adding_form", "wppb_remove_properties_from_added_form", 10, 3); /* * WPML Support for dynamic strings in Profile Builder. Tags: WPML, fields, translate */ add_filter( 'update_option_wppb_manage_fields', 'wppb_wpml_compat_with_fields', 10, 2 ); function wppb_wpml_compat_with_fields( $oldvalue, $_newvalue ){ if ( is_array( $_newvalue ) ){ foreach ( $_newvalue as $field ){ $field_title = $field['field-title']; $field_description = $field['description']; if (function_exists('icl_register_string')){ icl_register_string('plugin profile-builder-pro', 'custom_field_'.$field['id'].'_title_translation' , $field_title); icl_register_string('plugin profile-builder-pro', 'custom_field_'.$field['id'].'_description_translation', $field_description); } } } }
kailagrace/web-app-dmd
wp-content/plugins/profile-builder/admin/manage-fields.php
PHP
gpl-2.0
37,450
#!/usr/bin/env python ## @file @brief Add __str__ and __unicode__ methods to financial objects so that @code print object @endcode leads to human readable results """ @package str_methods.py -- Add __str__ and __unicode__ methods to financial objects Import this module and str(Object) and unicode(Object) where Object is Transaction, Split,Invoice or Entry leads to human readable results. That is handy when using @code print object @endcode I chose to put these functions/methods in a seperate file to develop them like this and maybe if they prove to be useful they can be put in gnucash_core.py. I am searching to find the best way to serialize these complex objects. Ideally this serialization would be configurable. If someone has suggestions how to beautify, purify or improve this code in any way please feel free to do so. This is written as a first approach to a shell-environment using ipython to interactively manipulate GnuCashs Data.""" # @author Christoph Holtermann, [email protected] # @ingroup python_bindings_examples # @date May 2011 # # ToDo : # # * Testing for SWIGtypes # * dealing the cutting format in a bit more elegant way # * having setflag as a classmethod makes it probably impossible to have flags on instance level. Would changing that be useful ? # * It seems useful to have an object for each modification. That is because there is some Initialisation to be done. # import gnucash, function_class # Default values for encoding of strings in GnuCashs Database DEFAULT_ENCODING = "UTF-8" DEFAULT_ERROR = "ignore" def setflag(self, name, value): if not(name in self.OPTIONFLAGS_BY_NAME): self.register_optionflag(name) if value == True: self.optionflags |= self.OPTIONFLAGS_BY_NAME[name] else: self.optionflags &= ~self.OPTIONFLAGS_BY_NAME[name] def getflag(self, name): if not(name in self.OPTIONFLAGS_BY_NAME): raise KeyError(str(name)+" is not a registered key.") return ((self.optionflags & self.OPTIONFLAGS_BY_NAME[name]) != 0) def register_optionflag(self,name): """Taken from doctest.py""" # Create a new flag unless `name` is already known. return self.OPTIONFLAGS_BY_NAME.setdefault(name, 1 << len(self.OPTIONFLAGS_BY_NAME)) def ya_add_method(_class, function, method_name=None, clsmethod=False, noinstance=False): """Calls add_method from function_methods.py but makes it possible to use functions in this module. Also keeps the docstring""" if method_name == None: method_name = function.__name__ setattr(gnucash.gnucash_core_c,function.__name__,function) if clsmethod: mf=_class.ya_add_classmethod(function.__name__,method_name) elif noinstance: mf=_class.add_method(function.__name__,method_name) else: mf=_class.ya_add_method(function.__name__,method_name) if function.__doc__ != None: setattr(mf, "__doc__", function.__doc__) def infect(_class, function, method_name): if not getattr(_class, "OPTIONFLAGS_BY_NAME", None): _class.OPTIONFLAGS_BY_NAME={} _class.optionflags=0 ya_add_method(_class,register_optionflag,clsmethod=True) ya_add_method(_class,setflag,clsmethod=True) ya_add_method(_class,getflag,clsmethod=True) ya_add_method(_class, function, method_name) class ClassWithCutting__format__(): """This class provides a __format__ method which cuts values to a certain width. If width is too big '...' will be put at the end of the resulting string.""" def __init__(self,value): self.value = value def __format__(self, fmt): def get_width(fmt_spec): """Parse fmt_spec to obtain width""" def remove_alignment(fmt_spec): if fmt_spec[1] in ["<","^",">"]: fmt_spec=fmt_spec[2:len(fmt_spec)] return fmt_spec def remove_sign(fmt_spec): if fmt_spec[0] in ["-","+"," "]: fmt_spec=fmt_spec[1:len(fmt_spec)] return fmt_spec def remove_cross(fmt_spec): if fmt_spec[0] in ["#"]: fmt_spec=fmt_spec[1:len(fmt_spec)] return fmt_spec def do_width(fmt_spec): n="" while len(fmt_spec)>0: if fmt_spec[0].isdigit(): n+=fmt_spec[0] fmt_spec=fmt_spec[1:len(fmt_spec)] else: break if n: return int(n) else: return None if len(fmt_spec)>=2: fmt_spec=remove_alignment(fmt_spec) if len(fmt_spec)>=1: fmt_spec=remove_sign(fmt_spec) if len(fmt_spec)>=1: fmt_spec=remove_cross(fmt_spec) width=do_width(fmt_spec) # Stop parsing here for we only need width return width def cut(s, width, replace_string="..."): """Cuts s to width and puts replace_string at it's end.""" #s=s.decode('UTF-8', "replace") if len(s)>width: if len(replace_string)>width: replace_string=replace_string[0:width] s=s[0:width-len(replace_string)] s=s+replace_string return s value=self.value # Replace Tabs and linebreaks import types if type(value) in [types.StringType, types.UnicodeType]: value=value.replace("\t","|") value=value.replace("\n","|") # Do regular formatting of object value=value.__format__(fmt) # Cut resulting value if longer than specified by width width=get_width(fmt) if width: value=cut(value, width, "...") return value def all_as_classwithcutting__format__(*args): """Converts every argument to instance of ClassWithCutting__format__""" import types l=[] for a in args: if type(a) in [types.StringType, types.UnicodeType]: a=a.decode("UTF-8") l.append(ClassWithCutting__format__(a)) return l def all_as_classwithcutting__format__keys(encoding=None, error=None, **keys): """Converts every argument to instance of ClassWithCutting__format__""" import types d={} if encoding==None: encoding=DEFAULT_ENCODING if error==None: error=DEFAULT_ERROR for a in keys: if type(keys[a]) in [types.StringType, types.UnicodeType]: keys[a]=keys[a].decode(encoding,error) d[a]=ClassWithCutting__format__(keys[a]) return d # Split def __split__unicode__(self, encoding=None, error=None): """__unicode__(self, encoding=None, error=None) -> object Serialize the Split object and return as a new Unicode object. Keyword arguments: encoding -- defaults to str_methods.default_encoding error -- defaults to str_methods.default_error See help(unicode) for more details or http://docs.python.org/howto/unicode.html. """ from gnucash import Split import time #self=Split(instance=self) lot=self.GetLot() if lot: if type(lot).__name__ == 'SwigPyObject': lot=gnucash.GncLot(instance=lot) lot_str=lot.get_title() else: lot_str='---' transaction=self.GetParent() # This dict and the return statement can be changed according to individual needs fmt_dict={ "account":self.GetAccount().name, "value":self.GetValue(), "memo":self.GetMemo(), "lot":lot_str} fmt_str= (u"Account: {account:20} "+ u"Value: {value:>10} "+ u"Memo: {memo:30} ") if self.optionflags & self.OPTIONFLAGS_BY_NAME["PRINT_TRANSACTION"]: fmt_t_dict={ "transaction_time":time.ctime(transaction.GetDate()), "transaction2":transaction.GetDescription()} fmt_t_str=( u"Transaction: {transaction_time:30} "+ u"- {transaction2:30} "+ u"Lot: {lot:10}") fmt_dict.update(fmt_t_dict) fmt_str += fmt_t_str return fmt_str.format(**all_as_classwithcutting__format__keys(encoding,error,**fmt_dict)) def __split__str__(self): """Returns a bytestring representation of self.__unicode__""" from gnucash import Split #self=Split(instance=self) return unicode(self).encode('utf-8') # This could be something like an __init__. Maybe we could call it virus because it infects the Split object which # thereafter mutates to have better capabilities. infect(gnucash.Split,__split__str__,"__str__") infect(gnucash.Split,__split__unicode__,"__unicode__") gnucash.Split.register_optionflag("PRINT_TRANSACTION") gnucash.Split.setflag("PRINT_TRANSACTION",True) def __transaction__unicode__(self): """__unicode__ method for Transaction class""" from gnucash import Transaction import time self=Transaction(instance=self) fmt_tuple=('Date:',time.ctime(self.GetDate()), 'Description:',self.GetDescription(), 'Notes:',self.GetNotes()) transaction_str = u"{0:6}{1:25} {2:14}{3:40} {4:7}{5:40}".format( *all_as_classwithcutting__format__(*fmt_tuple)) transaction_str += "\n" splits_str="" for n,split in enumerate(self.GetSplitList()): if not (type(split)==gnucash.Split): split=gnucash.Split(instance=split) transaction_flag = split.getflag("PRINT_TRANSACTION") split.setflag("PRINT_TRANSACTION",False) splits_str += u"[{0:>2}] ".format(unicode(n)) splits_str += unicode(split) splits_str += "\n" split.setflag("PRINT_TRANSACTION",transaction_flag) return transaction_str + splits_str def __transaction__str__(self): """__str__ method for Transaction class""" from gnucash import Transaction self=Transaction(instance=self) return unicode(self).encode('utf-8') # These lines add transaction_str as method __str__ to Transaction object gnucash.gnucash_core_c.__transaction__str__=__transaction__str__ gnucash.Transaction.add_method("__transaction__str__","__str__") gnucash.gnucash_core_c.__transaction__unicode__=__transaction__unicode__ gnucash.Transaction.add_method("__transaction__unicode__","__unicode__") def __invoice__unicode__(self): """__unicode__ method for Invoice""" from gnucash.gnucash_business import Invoice self=Invoice(instance=self) # This dict and the return statement can be changed according to individual needs fmt_dict={ "id_name":"ID:", "id_value":self.GetID(), "notes_name":"Notes:", "notes_value":self.GetNotes(), "active_name":"Active:", "active_value":str(self.GetActive()), "owner_name":"Owner Name:", "owner_value":self.GetOwner().GetName(), "total_name":"Total:", "total_value":str(self.GetTotal()), "currency_mnemonic":self.GetCurrency().get_mnemonic()} ret_invoice= (u"{id_name:4}{id_value:10} {notes_name:7}{notes_value:20} {active_name:8}{active_value:7} {owner_name:12}{owner_value:20}"+ u"{total_name:8}{total_value:10}{currency_mnemonic:3}").\ format(**all_as_classwithcutting__format__keys(**fmt_dict)) ret_entries=u"" entry_list = self.GetEntries() for entry in entry_list: # Type of entry has to be checked if not(type(entry)==Entry): entry=Entry(instance=entry) ret_entries += " "+unicode(entry)+"\n" return ret_invoice+"\n"+ret_entries def __invoice__str__(self): """__str__ method for invoice class""" from gnucash.gnucash_business import Invoice self=Invoice(instance=self) return unicode(self).encode('utf-8') from gnucash.gnucash_business import Invoice gnucash.gnucash_core_c.__invoice__str__=__invoice__str__ gnucash.gnucash_business.Invoice.add_method("__invoice__str__","__str__") gnucash.gnucash_core_c.__invoice__unicode__=__invoice__unicode__ gnucash.gnucash_business.Invoice.add_method("__invoice__unicode__","__unicode__") def __entry__unicode__(self): """__unicode__ method for Entry""" from gnucash.gnucash_business import Entry self=Entry(instance=self) # This dict and the return statement can be changed according to individual needs fmt_dict={ "date_name":"Date:", "date_value":unicode(self.GetDate()), "description_name":"Description:", "description_value":self.GetDescription(), "notes_name":"Notes:", "notes_value":self.GetNotes(), "quant_name":"Quantity:", "quant_value":unicode(gnucash.GncNumeric(instance=self.GetQuantity())), "invprice_name":"InvPrice:", "invprice_value":unicode(gnucash.GncNumeric(instance=self.GetInvPrice()))} return (u"{date_name:6}{date_value:15} {description_name:13}{description_value:20} {notes_name:7}{notes_value:20}"+ u"{quant_name:12}{quant_value:7} {invprice_name:10}{invprice_value:7}").\ format(**all_as_classwithcutting__format__keys(**fmt_dict)) def __entry__str__(self): """__str__ method for Entry class""" from gnucash.gnucash_business import Entry self=Entry(instance=self) return unicode(self).encode('utf-8') from gnucash.gnucash_business import Entry gnucash.gnucash_core_c.__entry__str__=__entry__str__ gnucash.gnucash_business.Entry.add_method("__entry__str__","__str__") gnucash.gnucash_core_c.__entry__unicode__=__entry__unicode__ gnucash.gnucash_business.Entry.add_method("__entry__unicode__","__unicode__")
dimbeni/Gnucash
src/optional/python-bindings/example_scripts/str_methods.py
Python
gpl-2.0
13,811
/* Software floating-point emulation. (*c) = (long double)(a) Copyright (C) 1997-2016 Free Software Foundation, Inc. This file is part of the GNU C Library. Contributed by Richard Henderson ([email protected]) and Jakub Jelinek ([email protected]). The GNU C Library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. The GNU C Library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with the GNU C Library; if not, see <http://www.gnu.org/licenses/>. */ #include "soft-fp.h" #include "quad.h" void _Qp_uitoq(long double *c, const unsigned int a) { FP_DECL_EX; FP_DECL_Q(C); unsigned int b = a; FP_FROM_INT_Q(C, b, 32, unsigned int); FP_PACK_RAW_QP(c, C); QP_NO_EXCEPTIONS; }
Chilledheart/glibc
sysdeps/sparc/sparc64/soft-fp/qp_uitoq.c
C
gpl-2.0
1,185
/* * Copyright (c) 2018 Samsung Electronics Co., Ltd. All rights reserved. * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ #include "vdrawhelper.h" /* result = s dest = s * ca + d * cia */ void comp_func_solid_Source(uint32_t *dest, int length, uint32_t color, uint32_t const_alpha) { int ialpha, i; if (const_alpha == 255) { memfill32(dest, color, length); } else { ialpha = 255 - const_alpha; color = BYTE_MUL(color, const_alpha); for (i = 0; i < length; ++i) dest[i] = color + BYTE_MUL(dest[i], ialpha); } } /* r = s + d * sia dest = r * ca + d * cia = (s + d * sia) * ca + d * cia = s * ca + d * (sia * ca + cia) = s * ca + d * (1 - sa*ca) = s' + d ( 1 - s'a) */ void comp_func_solid_SourceOver(uint32_t *dest, int length, uint32_t color, uint32_t const_alpha) { int ialpha, i; if (const_alpha != 255) color = BYTE_MUL(color, const_alpha); ialpha = 255 - vAlpha(color); for (i = 0; i < length; ++i) dest[i] = color + BYTE_MUL(dest[i], ialpha); } /* result = d * sa dest = d * sa * ca + d * cia = d * (sa * ca + cia) */ static void comp_func_solid_DestinationIn(uint *dest, int length, uint color, uint const_alpha) { uint a = vAlpha(color); if (const_alpha != 255) { a = BYTE_MUL(a, const_alpha) + 255 - const_alpha; } for (int i = 0; i < length; ++i) { dest[i] = BYTE_MUL(dest[i], a); } } /* result = d * sia dest = d * sia * ca + d * cia = d * (sia * ca + cia) */ static void comp_func_solid_DestinationOut(uint *dest, int length, uint color, uint const_alpha) { uint a = vAlpha(~color); if (const_alpha != 255) a = BYTE_MUL(a, const_alpha) + 255 - const_alpha; for (int i = 0; i < length; ++i) { dest[i] = BYTE_MUL(dest[i], a); } } void comp_func_Source(uint32_t *dest, const uint32_t *src, int length, uint32_t const_alpha) { if (const_alpha == 255) { memcpy(dest, src, size_t(length) * sizeof(uint)); } else { uint ialpha = 255 - const_alpha; for (int i = 0; i < length; ++i) { dest[i] = INTERPOLATE_PIXEL_255(src[i], const_alpha, dest[i], ialpha); } } } /* s' = s * ca * d' = s' + d (1 - s'a) */ void comp_func_SourceOver(uint32_t *dest, const uint32_t *src, int length, uint32_t const_alpha) { uint s, sia; if (const_alpha == 255) { for (int i = 0; i < length; ++i) { s = src[i]; if (s >= 0xff000000) dest[i] = s; else if (s != 0) { sia = vAlpha(~s); dest[i] = s + BYTE_MUL(dest[i], sia); } } } else { /* source' = source * const_alpha * dest = source' + dest ( 1- source'a) */ for (int i = 0; i < length; ++i) { uint s = BYTE_MUL(src[i], const_alpha); sia = vAlpha(~s); dest[i] = s + BYTE_MUL(dest[i], sia); } } } void comp_func_DestinationIn(uint *dest, const uint *src, int length, uint const_alpha) { if (const_alpha == 255) { for (int i = 0; i < length; ++i) { dest[i] = BYTE_MUL(dest[i], vAlpha(src[i])); } } else { uint cia = 255 - const_alpha; for (int i = 0; i < length; ++i) { uint a = BYTE_MUL(vAlpha(src[i]), const_alpha) + cia; dest[i] = BYTE_MUL(dest[i], a); } } } void comp_func_DestinationOut(uint *dest, const uint *src, int length, uint const_alpha) { if (const_alpha == 255) { for (int i = 0; i < length; ++i) { dest[i] = BYTE_MUL(dest[i], vAlpha(~src[i])); } } else { uint cia = 255 - const_alpha; for (int i = 0; i < length; ++i) { uint sia = BYTE_MUL(vAlpha(~src[i]), const_alpha) + cia; dest[i] = BYTE_MUL(dest[i], sia); } } } CompositionFunctionSolid COMP_functionForModeSolid_C[] = { comp_func_solid_Source, comp_func_solid_SourceOver, comp_func_solid_DestinationIn, comp_func_solid_DestinationOut}; CompositionFunction COMP_functionForMode_C[] = { comp_func_Source, comp_func_SourceOver, comp_func_DestinationIn, comp_func_DestinationOut}; void vInitBlendFunctions() {}
CzBiX/Telegram
TMessagesProj/jni/rlottie/src/vector/vcompositionfunctions.cpp
C++
gpl-2.0
5,241
/* // Boost.Range library // // Copyright Thorsten Ottosen 2003-2008. Use, modification and // distribution is subject to the Boost Software License, Version // 1.0. (See accompanying file LICENSE_1_0.txt or copy at // http://www.boost.org/LICENSE_1_0.txt) // // For more information, see http://www.boost.org/libs/range/ // */ pre{ BORDER-RIGHT: gray 1pt solid; PADDING-RIGHT: 2pt; BORDER-TOP: gray 1pt solid; DISPLAY: block; PADDING-LEFT: 2pt; PADDING-BOTTOM: 2pt; BORDER-LEFT: gray 1pt solid; MARGIN-RIGHT: 32pt; PADDING-TOP: 2pt; BORDER-BOTTOM: gray 1pt solid; FONT-FAMILY: "Courier New", Courier, mono; background-color: #EEEEEE; } .keyword{color: #0000FF;} .identifier{} .comment{font-style: italic; color: #008000;} .special{color: #800040;} .preprocessor{color: #3F007F;} .string{font-style: italic; color: #666666;} .literal{font-style: italic; color: #666666;} table { cellpadding: 5px; border: 2px; }
scs/uclinux
lib/boost/boost_1_38_0/libs/range/doc/style.css
CSS
gpl-2.0
947
/* * Copyright (c) 2012-2013,2017 The Linux Foundation. All rights reserved. * * Previously licensed under the ISC license by Qualcomm Atheros, Inc. * * * Permission to use, copy, modify, and/or distribute this software for * any purpose with or without fee is hereby granted, provided that the * above copyright notice and this permission notice appear in all * copies. * * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL * WARRANTIES WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE * AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL * DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR * PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER * TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR * PERFORMANCE OF THIS SOFTWARE. */ /* * This file was originally distributed by Qualcomm Atheros, Inc. * under proprietary terms before Copyright ownership was assigned * to the Linux Foundation. */ #if !defined( __I_VOS_PACKET_H ) #define __I_VOS_PACKET_H /**========================================================================= \file i_vos_packet.h \brief virtual Operating System Servies (vOSS) Network Protocol packet/buffer internal include file ========================================================================*/ /* $Header$ */ /*-------------------------------------------------------------------------- Include Files ------------------------------------------------------------------------*/ #include <vos_types.h> #include <vos_list.h> #include <linux/skbuff.h> #include <linux/list.h> #include <wlan_qct_pal_packet.h> #include <wlan_qct_wdi_ds.h> /*-------------------------------------------------------------------------- Preprocessor definitions and constants ------------------------------------------------------------------------*/ // Definitions for the various VOS packet pools. Following are defines // for the SIZE and the NUMBER of vos packets in the vos packet pools. // Note that all of the code is written to allocate and manage the vos // packet pools based on these #defines only. For example, if you want to // change the number of RX_RAW packets, simply change the #define that // defines the number of RX_RAW packets and rebuild VOSS. // the number of Receive vos packets used exclusively for vos packet // allocations of type VOS_PKT_TYPE_RX_RAW #define VPKT_NUM_RX_RAW_PACKETS (1024) // the number of Transmit Management vos packets, used exclusively for // vos packet allocations of type VOS_PKT_TYPE_TX_802_11_MGMT #define VPKT_NUM_TX_MGMT_PACKETS ( 6 ) // the number of Transmit Data vos packets, used exclusively for // vos packet allocations of type VOS_PKT_TYPE_TX_802_3_DATA or // VOS_PKT_TYPE_TX_802_11_DATA #define VPKT_NUM_TX_DATA_PACKETS ( 128 ) // the number of VOS Packets we need. This is the memory we need to // allocate for the vos Packet structures themselves. We need vos // packet structures for all of the packet types (RX_RAW, TX_MGMT, and // TX_DATA). #define VPKT_NUM_VOS_PKT_BUFFERS \ ( VPKT_NUM_RX_RAW_PACKETS \ + VPKT_NUM_TX_MGMT_PACKETS \ + VPKT_NUM_TX_DATA_PACKETS ) // the number of Receive vos packets that we accumulate in the // replenish pool before we attempt to replenish them #define VPKT_RX_REPLENISH_THRESHOLD ( VPKT_NUM_RX_RAW_PACKETS >> 2 ) // magic number which can be used to verify that a structure pointer being // dereferenced is really referencing a struct vos_pkt_t #define VPKT_MAGIC_NUMBER 0x56504B54 /* VPKT in ASCII */ // while allocating the skb->data is cache aligned, so the memory allocated // is more than VPKT_SIZE_BUFFER #define VPKT_SIZE_BUFFER_ALIGNED SKB_DATA_ALIGN(VPKT_SIZE_BUFFER) /*-------------------------------------------------------------------------- Type declarations ------------------------------------------------------------------------*/ /// implementation specific vos packet type struct vos_pkt_t { //palPacket MUST be the first member of vos_pkt_t wpt_packet palPacket; // Node for linking vos packets into a free list struct list_head node; // Node for chaining vos packets into a packet chain struct vos_pkt_t *pNext; // pointer to an OS specific packet descriptor struct sk_buff *pSkb; // packet type VOS_PKT_TYPE packetType; // timestamp v_TIME_t timestamp; // user data pointers v_VOID_t *pvUserData[ VOS_PKT_USER_DATA_ID_MAX ]; v_U64_t pn_num; // magic number for verifying this is really a struct vos_pkt_t v_U32_t magic; }; // Parameters from the vos_pkt_get_packet() call that needs // to be saved in 'low resource' conditions. We need all the // parameters from the original call to vos_pkt_get_packet() // to resolve the packet request when one become available. typedef struct { vos_pkt_get_packet_callback callback; v_VOID_t *userData; v_SIZE_t dataSize; v_SIZE_t numPackets; v_BOOL_t zeroBuffer; } vos_pkt_low_resource_info; // vOSS Packet Context - all context / internal data needed for the // vOSS pPacket module. This consiste of: // - memory for the vos Packet structures // - memory for the vos Packet Head / Tail buffers // - memory for the Rx Raw data buffers // - memory for the Tx Mgmt data buffers. typedef struct vos_pkt_context_s { // place to save the vos Context v_CONTEXT_t vosContext; // the memory for the vos Packet structures.... struct vos_pkt_t vosPktBuffers[ VPKT_NUM_VOS_PKT_BUFFERS ]; // These are the lists to keep the constructed VOS packets that are // available for allocation. There are separate free vos packet // pools for RX_RAW without attached skb, RX_RAW with attached skb, // TX_DATA, and TX_MGMT. struct list_head rxReplenishList; struct list_head rxRawFreeList; struct list_head txDataFreeList; struct list_head txMgmtFreeList; //Existing list_size opearation traverse the list. Too slow for data path. //Add the field to enable faster flow control on tx path v_U32_t uctxDataFreeListCount; // We keep a separate count of the number of RX_RAW packets // waiting to be replenished v_SIZE_t rxReplenishListCount; // Count for the number of packets that could not be replenished // because the memory allocation API failed v_SIZE_t rxReplenishFailCount; //Existing list_size opearation traverse the list. Too slow for data path. //Add the field for a faster rx path v_SIZE_t rxRawFreeListCount; // Number of RX Raw packets that will be reserved; this is a configurable // value to the driver to save the memory usage. v_SIZE_t numOfRxRawPackets; // These are the structs to keep low-resource callback information. // There are separate low-resource callback information blocks for // RX_RAW, TX_DATA, and TX_MGMT. vos_pkt_low_resource_info rxRawLowResourceInfo; vos_pkt_low_resource_info txDataLowResourceInfo; vos_pkt_low_resource_info txMgmtLowResourceInfo; struct mutex rxReplenishListLock; struct mutex rxRawFreeListLock; struct mutex txDataFreeListLock; struct mutex txMgmtFreeListLock; /*Meta Information to be transported with the packet*/ WDI_DS_TxMetaInfoType txMgmtMetaInfo[VPKT_NUM_TX_MGMT_PACKETS]; WDI_DS_TxMetaInfoType txDataMetaInfo[VPKT_NUM_TX_DATA_PACKETS]; WDI_DS_RxMetaInfoType rxMetaInfo[VPKT_NUM_RX_RAW_PACKETS]; } vos_pkt_context_t; /*--------------------------------------------------------------------------- \brief vos_packet_open() - initialize the vOSS Packet module The \a vos_packet_open() function initializes the vOSS Packet module. \param pVosContext - pointer to the global vOSS Context \param pVosPacketContext - pointer to a previously allocated buffer big enough to hold the vos Packet context. \param vosPacketContextSize - the size allocated for the vos packet context. \return VOS_STATUS_SUCCESS - vos Packet module was successfully initialized and is ready to be used. VOS_STATUS_E_RESOURCES - System resources (other than memory) are unavailable to initilize the vos Packet module VOS_STATUS_E_NOMEM - insufficient memory exists to initialize the vos packet module VOS_STATUS_E_INVAL - Invalid parameter passed to the vos open function VOS_STATUS_E_FAILURE - Failure to initialize the vos packet module \sa vos_packet_close() -------------------------------------------------------------------------*/ VOS_STATUS vos_packet_open( v_VOID_t *pVosContext, vos_pkt_context_t *pVosPacketContext, v_SIZE_t vosPacketContextSize ); /*--------------------------------------------------------------------------- \brief vos_packet_close() - Close the vOSS Packet module The \a vos_packet_close() function closes the vOSS Packet module Upon successful close all resources allocated from the OS will be relinquished. \param pVosContext - pointer to the global vOSS Context \return VOS_STATUS_SUCCESS - Packet module was successfully closed. VOS_STATUS_E_INVAL - Invalid parameter passed to the packet close function VOS_STATUS_E_FAILURE - Failure to close the vos Packet module \sa vos_packet_open() ---------------------------------------------------------------------------*/ VOS_STATUS vos_packet_close( v_PVOID_t pVosContext ); #endif // !defined( __I_VOS_PACKET_H )
M8s-dev/kernel_htc_msm8939
drivers/staging/prima/CORE/VOSS/inc/i_vos_packet.h
C
gpl-2.0
9,628
alter table alliance_log change population population bigint not null;
abyssinia/Lacuna-Server-Open
var/upgrades/3.0857.sql
SQL
gpl-2.0
71
/****************************************************************************** * * This file is provided under a dual BSD/GPLv2 license. When using or * redistributing this file, you may do so under either license. * * GPL LICENSE SUMMARY * * Copyright(c) 2007 - 2012 Intel Corporation. All rights reserved. * * This program is free software; you can redistribute it and/or modify * it under the terms of version 2 of the GNU General Public License as * published by the Free Software Foundation. * * This program is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * General Public License for more details. * * 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, * USA * * The full GNU General Public License is included in this distribution * in the file called LICENSE.GPL. * * Contact Information: * Intel Linux Wireless <[email protected]> * Intel Corporation, 5200 N.E. Elam Young Parkway, Hillsboro, OR 97124-6497 * * BSD LICENSE * * Copyright(c) 2005 - 2012 Intel Corporation. All rights reserved. * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in * the documentation and/or other materials provided with the * distribution. * * Neither the name Intel Corporation nor the names of its * contributors may be used to endorse or promote products derived * from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * *****************************************************************************/ #include <linux/pci.h> #include <linux/pci-aspm.h> #include <linux/interrupt.h> #include <linux/debugfs.h> #include <linux/sched.h> #include <linux/bitops.h> #include <linux/gfp.h> #include "iwl-drv.h" #include "iwl-trans.h" #include "iwl-trans-pcie-int.h" #include "iwl-csr.h" #include "iwl-prph.h" #include "iwl-eeprom.h" #include "iwl-agn-hw.h" /* FIXME: need to abstract out TX command (once we know what it looks like) */ #include "iwl-commands.h" #define IWL_MASK(lo, hi) ((1 << (hi)) | ((1 << (hi)) - (1 << (lo)))) #define SCD_QUEUECHAIN_SEL_ALL(trans, trans_pcie) \ (((1<<trans->cfg->base_params->num_of_queues) - 1) &\ (~(1<<(trans_pcie)->cmd_queue))) static int iwl_trans_rx_alloc(struct iwl_trans *trans) { struct iwl_trans_pcie *trans_pcie = IWL_TRANS_GET_PCIE_TRANS(trans); struct iwl_rx_queue *rxq = &trans_pcie->rxq; struct device *dev = trans->dev; memset(&trans_pcie->rxq, 0, sizeof(trans_pcie->rxq)); spin_lock_init(&rxq->lock); if (WARN_ON(rxq->bd || rxq->rb_stts)) return -EINVAL; /* Allocate the circular buffer of Read Buffer Descriptors (RBDs) */ rxq->bd = dma_zalloc_coherent(dev, sizeof(__le32) * RX_QUEUE_SIZE, &rxq->bd_dma, GFP_KERNEL); if (!rxq->bd) goto err_bd; /*Allocate the driver's pointer to receive buffer status */ rxq->rb_stts = dma_zalloc_coherent(dev, sizeof(*rxq->rb_stts), &rxq->rb_stts_dma, GFP_KERNEL); if (!rxq->rb_stts) goto err_rb_stts; return 0; err_rb_stts: dma_free_coherent(dev, sizeof(__le32) * RX_QUEUE_SIZE, rxq->bd, rxq->bd_dma); memset(&rxq->bd_dma, 0, sizeof(rxq->bd_dma)); rxq->bd = NULL; err_bd: return -ENOMEM; } static void iwl_trans_rxq_free_rx_bufs(struct iwl_trans *trans) { struct iwl_trans_pcie *trans_pcie = IWL_TRANS_GET_PCIE_TRANS(trans); struct iwl_rx_queue *rxq = &trans_pcie->rxq; int i; /* Fill the rx_used queue with _all_ of the Rx buffers */ for (i = 0; i < RX_FREE_BUFFERS + RX_QUEUE_SIZE; i++) { /* In the reset function, these buffers may have been allocated * to an SKB, so we need to unmap and free potential storage */ if (rxq->pool[i].page != NULL) { dma_unmap_page(trans->dev, rxq->pool[i].page_dma, PAGE_SIZE << trans_pcie->rx_page_order, DMA_FROM_DEVICE); __free_pages(rxq->pool[i].page, trans_pcie->rx_page_order); rxq->pool[i].page = NULL; } list_add_tail(&rxq->pool[i].list, &rxq->rx_used); } } static void iwl_trans_rx_hw_init(struct iwl_trans *trans, struct iwl_rx_queue *rxq) { struct iwl_trans_pcie *trans_pcie = IWL_TRANS_GET_PCIE_TRANS(trans); u32 rb_size; const u32 rfdnlog = RX_QUEUE_SIZE_LOG; /* 256 RBDs */ u32 rb_timeout = RX_RB_TIMEOUT; /* FIXME: RX_RB_TIMEOUT for all devices? */ if (trans_pcie->rx_buf_size_8k) rb_size = FH_RCSR_RX_CONFIG_REG_VAL_RB_SIZE_8K; else rb_size = FH_RCSR_RX_CONFIG_REG_VAL_RB_SIZE_4K; /* Stop Rx DMA */ iwl_write_direct32(trans, FH_MEM_RCSR_CHNL0_CONFIG_REG, 0); /* Reset driver's Rx queue write index */ iwl_write_direct32(trans, FH_RSCSR_CHNL0_RBDCB_WPTR_REG, 0); /* Tell device where to find RBD circular buffer in DRAM */ iwl_write_direct32(trans, FH_RSCSR_CHNL0_RBDCB_BASE_REG, (u32)(rxq->bd_dma >> 8)); /* Tell device where in DRAM to update its Rx status */ iwl_write_direct32(trans, FH_RSCSR_CHNL0_STTS_WPTR_REG, rxq->rb_stts_dma >> 4); /* Enable Rx DMA * FH_RCSR_CHNL0_RX_IGNORE_RXF_EMPTY is set because of HW bug in * the credit mechanism in 5000 HW RX FIFO * Direct rx interrupts to hosts * Rx buffer size 4 or 8k * RB timeout 0x10 * 256 RBDs */ iwl_write_direct32(trans, FH_MEM_RCSR_CHNL0_CONFIG_REG, FH_RCSR_RX_CONFIG_CHNL_EN_ENABLE_VAL | FH_RCSR_CHNL0_RX_IGNORE_RXF_EMPTY | FH_RCSR_CHNL0_RX_CONFIG_IRQ_DEST_INT_HOST_VAL | rb_size| (rb_timeout << FH_RCSR_RX_CONFIG_REG_IRQ_RBTH_POS)| (rfdnlog << FH_RCSR_RX_CONFIG_RBDCB_SIZE_POS)); /* Set interrupt coalescing timer to default (2048 usecs) */ iwl_write8(trans, CSR_INT_COALESCING, IWL_HOST_INT_TIMEOUT_DEF); } static int iwl_rx_init(struct iwl_trans *trans) { struct iwl_trans_pcie *trans_pcie = IWL_TRANS_GET_PCIE_TRANS(trans); struct iwl_rx_queue *rxq = &trans_pcie->rxq; int i, err; unsigned long flags; if (!rxq->bd) { err = iwl_trans_rx_alloc(trans); if (err) return err; } spin_lock_irqsave(&rxq->lock, flags); INIT_LIST_HEAD(&rxq->rx_free); INIT_LIST_HEAD(&rxq->rx_used); iwl_trans_rxq_free_rx_bufs(trans); for (i = 0; i < RX_QUEUE_SIZE; i++) rxq->queue[i] = NULL; /* Set us so that we have processed and used all buffers, but have * not restocked the Rx queue with fresh buffers */ rxq->read = rxq->write = 0; rxq->write_actual = 0; rxq->free_count = 0; spin_unlock_irqrestore(&rxq->lock, flags); iwlagn_rx_replenish(trans); iwl_trans_rx_hw_init(trans, rxq); spin_lock_irqsave(&trans_pcie->irq_lock, flags); rxq->need_update = 1; iwl_rx_queue_update_write_ptr(trans, rxq); spin_unlock_irqrestore(&trans_pcie->irq_lock, flags); return 0; } static void iwl_trans_pcie_rx_free(struct iwl_trans *trans) { struct iwl_trans_pcie *trans_pcie = IWL_TRANS_GET_PCIE_TRANS(trans); struct iwl_rx_queue *rxq = &trans_pcie->rxq; unsigned long flags; /*if rxq->bd is NULL, it means that nothing has been allocated, * exit now */ if (!rxq->bd) { IWL_DEBUG_INFO(trans, "Free NULL rx context\n"); return; } spin_lock_irqsave(&rxq->lock, flags); iwl_trans_rxq_free_rx_bufs(trans); spin_unlock_irqrestore(&rxq->lock, flags); dma_free_coherent(trans->dev, sizeof(__le32) * RX_QUEUE_SIZE, rxq->bd, rxq->bd_dma); memset(&rxq->bd_dma, 0, sizeof(rxq->bd_dma)); rxq->bd = NULL; if (rxq->rb_stts) dma_free_coherent(trans->dev, sizeof(struct iwl_rb_status), rxq->rb_stts, rxq->rb_stts_dma); else IWL_DEBUG_INFO(trans, "Free rxq->rb_stts which is NULL\n"); memset(&rxq->rb_stts_dma, 0, sizeof(rxq->rb_stts_dma)); rxq->rb_stts = NULL; } static int iwl_trans_rx_stop(struct iwl_trans *trans) { /* stop Rx DMA */ iwl_write_direct32(trans, FH_MEM_RCSR_CHNL0_CONFIG_REG, 0); return iwl_poll_direct_bit(trans, FH_MEM_RSSR_RX_STATUS_REG, FH_RSSR_CHNL0_RX_STATUS_CHNL_IDLE, 1000); } static inline int iwlagn_alloc_dma_ptr(struct iwl_trans *trans, struct iwl_dma_ptr *ptr, size_t size) { if (WARN_ON(ptr->addr)) return -EINVAL; ptr->addr = dma_alloc_coherent(trans->dev, size, &ptr->dma, GFP_KERNEL); if (!ptr->addr) return -ENOMEM; ptr->size = size; return 0; } static inline void iwlagn_free_dma_ptr(struct iwl_trans *trans, struct iwl_dma_ptr *ptr) { if (unlikely(!ptr->addr)) return; dma_free_coherent(trans->dev, ptr->size, ptr->addr, ptr->dma); memset(ptr, 0, sizeof(*ptr)); } static void iwl_trans_pcie_queue_stuck_timer(unsigned long data) { struct iwl_tx_queue *txq = (void *)data; struct iwl_trans_pcie *trans_pcie = txq->trans_pcie; struct iwl_trans *trans = iwl_trans_pcie_get_trans(trans_pcie); spin_lock(&txq->lock); /* check if triggered erroneously */ if (txq->q.read_ptr == txq->q.write_ptr) { spin_unlock(&txq->lock); return; } spin_unlock(&txq->lock); IWL_ERR(trans, "Queue %d stuck for %u ms.\n", txq->q.id, jiffies_to_msecs(trans_pcie->wd_timeout)); IWL_ERR(trans, "Current SW read_ptr %d write_ptr %d\n", txq->q.read_ptr, txq->q.write_ptr); IWL_ERR(trans, "Current HW read_ptr %d write_ptr %d\n", iwl_read_prph(trans, SCD_QUEUE_RDPTR(txq->q.id)) & (TFD_QUEUE_SIZE_MAX - 1), iwl_read_prph(trans, SCD_QUEUE_WRPTR(txq->q.id))); iwl_op_mode_nic_error(trans->op_mode); } static int iwl_trans_txq_alloc(struct iwl_trans *trans, struct iwl_tx_queue *txq, int slots_num, u32 txq_id) { size_t tfd_sz = sizeof(struct iwl_tfd) * TFD_QUEUE_SIZE_MAX; int i; struct iwl_trans_pcie *trans_pcie = IWL_TRANS_GET_PCIE_TRANS(trans); if (WARN_ON(txq->entries || txq->tfds)) return -EINVAL; setup_timer(&txq->stuck_timer, iwl_trans_pcie_queue_stuck_timer, (unsigned long)txq); txq->trans_pcie = trans_pcie; txq->q.n_window = slots_num; txq->entries = kcalloc(slots_num, sizeof(struct iwl_pcie_tx_queue_entry), GFP_KERNEL); if (!txq->entries) goto error; if (txq_id == trans_pcie->cmd_queue) for (i = 0; i < slots_num; i++) { txq->entries[i].cmd = kmalloc(sizeof(struct iwl_device_cmd), GFP_KERNEL); if (!txq->entries[i].cmd) goto error; } /* Circular buffer of transmit frame descriptors (TFDs), * shared with device */ txq->tfds = dma_alloc_coherent(trans->dev, tfd_sz, &txq->q.dma_addr, GFP_KERNEL); if (!txq->tfds) { IWL_ERR(trans, "dma_alloc_coherent(%zd) failed\n", tfd_sz); goto error; } txq->q.id = txq_id; return 0; error: if (txq->entries && txq_id == trans_pcie->cmd_queue) for (i = 0; i < slots_num; i++) kfree(txq->entries[i].cmd); kfree(txq->entries); txq->entries = NULL; return -ENOMEM; } static int iwl_trans_txq_init(struct iwl_trans *trans, struct iwl_tx_queue *txq, int slots_num, u32 txq_id) { int ret; txq->need_update = 0; /* TFD_QUEUE_SIZE_MAX must be power-of-two size, otherwise * iwl_queue_inc_wrap and iwl_queue_dec_wrap are broken. */ BUILD_BUG_ON(TFD_QUEUE_SIZE_MAX & (TFD_QUEUE_SIZE_MAX - 1)); /* Initialize queue's high/low-water marks, and head/tail indexes */ ret = iwl_queue_init(&txq->q, TFD_QUEUE_SIZE_MAX, slots_num, txq_id); if (ret) return ret; spin_lock_init(&txq->lock); /* * Tell nic where to find circular buffer of Tx Frame Descriptors for * given Tx queue, and enable the DMA channel used for that queue. * Circular buffer (TFD queue in DRAM) physical base address */ iwl_write_direct32(trans, FH_MEM_CBBC_QUEUE(txq_id), txq->q.dma_addr >> 8); return 0; } /** * iwl_tx_queue_unmap - Unmap any remaining DMA mappings and free skb's */ static void iwl_tx_queue_unmap(struct iwl_trans *trans, int txq_id) { struct iwl_trans_pcie *trans_pcie = IWL_TRANS_GET_PCIE_TRANS(trans); struct iwl_tx_queue *txq = &trans_pcie->txq[txq_id]; struct iwl_queue *q = &txq->q; enum dma_data_direction dma_dir; if (!q->n_bd) return; /* In the command queue, all the TBs are mapped as BIDI * so unmap them as such. */ if (txq_id == trans_pcie->cmd_queue) dma_dir = DMA_BIDIRECTIONAL; else dma_dir = DMA_TO_DEVICE; spin_lock_bh(&txq->lock); while (q->write_ptr != q->read_ptr) { iwlagn_txq_free_tfd(trans, txq, dma_dir); q->read_ptr = iwl_queue_inc_wrap(q->read_ptr, q->n_bd); } spin_unlock_bh(&txq->lock); } /** * iwl_tx_queue_free - Deallocate DMA queue. * @txq: Transmit queue to deallocate. * * Empty queue by removing and destroying all BD's. * Free all buffers. * 0-fill, but do not free "txq" descriptor structure. */ static void iwl_tx_queue_free(struct iwl_trans *trans, int txq_id) { struct iwl_trans_pcie *trans_pcie = IWL_TRANS_GET_PCIE_TRANS(trans); struct iwl_tx_queue *txq = &trans_pcie->txq[txq_id]; struct device *dev = trans->dev; int i; if (WARN_ON(!txq)) return; iwl_tx_queue_unmap(trans, txq_id); /* De-alloc array of command/tx buffers */ if (txq_id == trans_pcie->cmd_queue) for (i = 0; i < txq->q.n_window; i++) kfree(txq->entries[i].cmd); /* De-alloc circular buffer of TFDs */ if (txq->q.n_bd) { dma_free_coherent(dev, sizeof(struct iwl_tfd) * txq->q.n_bd, txq->tfds, txq->q.dma_addr); memset(&txq->q.dma_addr, 0, sizeof(txq->q.dma_addr)); } kfree(txq->entries); txq->entries = NULL; del_timer_sync(&txq->stuck_timer); /* 0-fill queue descriptor structure */ memset(txq, 0, sizeof(*txq)); } /** * iwl_trans_tx_free - Free TXQ Context * * Destroy all TX DMA queues and structures */ static void iwl_trans_pcie_tx_free(struct iwl_trans *trans) { int txq_id; struct iwl_trans_pcie *trans_pcie = IWL_TRANS_GET_PCIE_TRANS(trans); /* Tx queues */ if (trans_pcie->txq) { for (txq_id = 0; txq_id < trans->cfg->base_params->num_of_queues; txq_id++) iwl_tx_queue_free(trans, txq_id); } kfree(trans_pcie->txq); trans_pcie->txq = NULL; iwlagn_free_dma_ptr(trans, &trans_pcie->kw); iwlagn_free_dma_ptr(trans, &trans_pcie->scd_bc_tbls); } /** * iwl_trans_tx_alloc - allocate TX context * Allocate all Tx DMA structures and initialize them * * @param priv * @return error code */ static int iwl_trans_tx_alloc(struct iwl_trans *trans) { int ret; int txq_id, slots_num; struct iwl_trans_pcie *trans_pcie = IWL_TRANS_GET_PCIE_TRANS(trans); u16 scd_bc_tbls_size = trans->cfg->base_params->num_of_queues * sizeof(struct iwlagn_scd_bc_tbl); /*It is not allowed to alloc twice, so warn when this happens. * We cannot rely on the previous allocation, so free and fail */ if (WARN_ON(trans_pcie->txq)) { ret = -EINVAL; goto error; } ret = iwlagn_alloc_dma_ptr(trans, &trans_pcie->scd_bc_tbls, scd_bc_tbls_size); if (ret) { IWL_ERR(trans, "Scheduler BC Table allocation failed\n"); goto error; } /* Alloc keep-warm buffer */ ret = iwlagn_alloc_dma_ptr(trans, &trans_pcie->kw, IWL_KW_SIZE); if (ret) { IWL_ERR(trans, "Keep Warm allocation failed\n"); goto error; } trans_pcie->txq = kcalloc(trans->cfg->base_params->num_of_queues, sizeof(struct iwl_tx_queue), GFP_KERNEL); if (!trans_pcie->txq) { IWL_ERR(trans, "Not enough memory for txq\n"); ret = ENOMEM; goto error; } /* Alloc and init all Tx queues, including the command queue (#4/#9) */ for (txq_id = 0; txq_id < trans->cfg->base_params->num_of_queues; txq_id++) { slots_num = (txq_id == trans_pcie->cmd_queue) ? TFD_CMD_SLOTS : TFD_TX_CMD_SLOTS; ret = iwl_trans_txq_alloc(trans, &trans_pcie->txq[txq_id], slots_num, txq_id); if (ret) { IWL_ERR(trans, "Tx %d queue alloc failed\n", txq_id); goto error; } } return 0; error: iwl_trans_pcie_tx_free(trans); return ret; } static int iwl_tx_init(struct iwl_trans *trans) { int ret; int txq_id, slots_num; unsigned long flags; bool alloc = false; struct iwl_trans_pcie *trans_pcie = IWL_TRANS_GET_PCIE_TRANS(trans); if (!trans_pcie->txq) { ret = iwl_trans_tx_alloc(trans); if (ret) goto error; alloc = true; } spin_lock_irqsave(&trans_pcie->irq_lock, flags); /* Turn off all Tx DMA fifos */ iwl_write_prph(trans, SCD_TXFACT, 0); /* Tell NIC where to find the "keep warm" buffer */ iwl_write_direct32(trans, FH_KW_MEM_ADDR_REG, trans_pcie->kw.dma >> 4); spin_unlock_irqrestore(&trans_pcie->irq_lock, flags); /* Alloc and init all Tx queues, including the command queue (#4/#9) */ for (txq_id = 0; txq_id < trans->cfg->base_params->num_of_queues; txq_id++) { slots_num = (txq_id == trans_pcie->cmd_queue) ? TFD_CMD_SLOTS : TFD_TX_CMD_SLOTS; ret = iwl_trans_txq_init(trans, &trans_pcie->txq[txq_id], slots_num, txq_id); if (ret) { IWL_ERR(trans, "Tx %d queue init failed\n", txq_id); goto error; } } return 0; error: /*Upon error, free only if we allocated something */ if (alloc) iwl_trans_pcie_tx_free(trans); return ret; } static void iwl_set_pwr_vmain(struct iwl_trans *trans) { /* * (for documentation purposes) * to set power to V_AUX, do: if (pci_pme_capable(priv->pci_dev, PCI_D3cold)) iwl_set_bits_mask_prph(trans, APMG_PS_CTRL_REG, APMG_PS_CTRL_VAL_PWR_SRC_VAUX, ~APMG_PS_CTRL_MSK_PWR_SRC); */ iwl_set_bits_mask_prph(trans, APMG_PS_CTRL_REG, APMG_PS_CTRL_VAL_PWR_SRC_VMAIN, ~APMG_PS_CTRL_MSK_PWR_SRC); } /* PCI registers */ #define PCI_CFG_RETRY_TIMEOUT 0x041 #define PCI_CFG_LINK_CTRL_VAL_L0S_EN 0x01 #define PCI_CFG_LINK_CTRL_VAL_L1_EN 0x02 static u16 iwl_pciexp_link_ctrl(struct iwl_trans *trans) { int pos; u16 pci_lnk_ctl; struct iwl_trans_pcie *trans_pcie = IWL_TRANS_GET_PCIE_TRANS(trans); struct pci_dev *pci_dev = trans_pcie->pci_dev; pos = pci_pcie_cap(pci_dev); pci_read_config_word(pci_dev, pos + PCI_EXP_LNKCTL, &pci_lnk_ctl); return pci_lnk_ctl; } static void iwl_apm_config(struct iwl_trans *trans) { /* * HW bug W/A for instability in PCIe bus L0S->L1 transition. * Check if BIOS (or OS) enabled L1-ASPM on this device. * If so (likely), disable L0S, so device moves directly L0->L1; * costs negligible amount of power savings. * If not (unlikely), enable L0S, so there is at least some * power savings, even without L1. */ u16 lctl = iwl_pciexp_link_ctrl(trans); if ((lctl & PCI_CFG_LINK_CTRL_VAL_L1_EN) == PCI_CFG_LINK_CTRL_VAL_L1_EN) { /* L1-ASPM enabled; disable(!) L0S */ iwl_set_bit(trans, CSR_GIO_REG, CSR_GIO_REG_VAL_L0S_ENABLED); dev_printk(KERN_INFO, trans->dev, "L1 Enabled; Disabling L0S\n"); } else { /* L1-ASPM disabled; enable(!) L0S */ iwl_clear_bit(trans, CSR_GIO_REG, CSR_GIO_REG_VAL_L0S_ENABLED); dev_printk(KERN_INFO, trans->dev, "L1 Disabled; Enabling L0S\n"); } trans->pm_support = !(lctl & PCI_CFG_LINK_CTRL_VAL_L0S_EN); } /* * Start up NIC's basic functionality after it has been reset * (e.g. after platform boot, or shutdown via iwl_apm_stop()) * NOTE: This does not load uCode nor start the embedded processor */ static int iwl_apm_init(struct iwl_trans *trans) { struct iwl_trans_pcie *trans_pcie = IWL_TRANS_GET_PCIE_TRANS(trans); int ret = 0; IWL_DEBUG_INFO(trans, "Init card's basic functions\n"); /* * Use "set_bit" below rather than "write", to preserve any hardware * bits already set by default after reset. */ /* Disable L0S exit timer (platform NMI Work/Around) */ iwl_set_bit(trans, CSR_GIO_CHICKEN_BITS, CSR_GIO_CHICKEN_BITS_REG_BIT_DIS_L0S_EXIT_TIMER); /* * Disable L0s without affecting L1; * don't wait for ICH L0s (ICH bug W/A) */ iwl_set_bit(trans, CSR_GIO_CHICKEN_BITS, CSR_GIO_CHICKEN_BITS_REG_BIT_L1A_NO_L0S_RX); /* Set FH wait threshold to maximum (HW error during stress W/A) */ iwl_set_bit(trans, CSR_DBG_HPET_MEM_REG, CSR_DBG_HPET_MEM_REG_VAL); /* * Enable HAP INTA (interrupt from management bus) to * wake device's PCI Express link L1a -> L0s */ iwl_set_bit(trans, CSR_HW_IF_CONFIG_REG, CSR_HW_IF_CONFIG_REG_BIT_HAP_WAKE_L1A); iwl_apm_config(trans); /* Configure analog phase-lock-loop before activating to D0A */ if (trans->cfg->base_params->pll_cfg_val) iwl_set_bit(trans, CSR_ANA_PLL_CFG, trans->cfg->base_params->pll_cfg_val); /* * Set "initialization complete" bit to move adapter from * D0U* --> D0A* (powered-up active) state. */ iwl_set_bit(trans, CSR_GP_CNTRL, CSR_GP_CNTRL_REG_FLAG_INIT_DONE); /* * Wait for clock stabilization; once stabilized, access to * device-internal resources is supported, e.g. iwl_write_prph() * and accesses to uCode SRAM. */ ret = iwl_poll_bit(trans, CSR_GP_CNTRL, CSR_GP_CNTRL_REG_FLAG_MAC_CLOCK_READY, CSR_GP_CNTRL_REG_FLAG_MAC_CLOCK_READY, 25000); if (ret < 0) { IWL_DEBUG_INFO(trans, "Failed to init the card\n"); goto out; } /* * Enable DMA clock and wait for it to stabilize. * * Write to "CLK_EN_REG"; "1" bits enable clocks, while "0" bits * do not disable clocks. This preserves any hardware bits already * set by default in "CLK_CTRL_REG" after reset. */ iwl_write_prph(trans, APMG_CLK_EN_REG, APMG_CLK_VAL_DMA_CLK_RQT); udelay(20); /* Disable L1-Active */ iwl_set_bits_prph(trans, APMG_PCIDEV_STT_REG, APMG_PCIDEV_STT_VAL_L1_ACT_DIS); set_bit(STATUS_DEVICE_ENABLED, &trans_pcie->status); out: return ret; } static int iwl_apm_stop_master(struct iwl_trans *trans) { int ret = 0; /* stop device's busmaster DMA activity */ iwl_set_bit(trans, CSR_RESET, CSR_RESET_REG_FLAG_STOP_MASTER); ret = iwl_poll_bit(trans, CSR_RESET, CSR_RESET_REG_FLAG_MASTER_DISABLED, CSR_RESET_REG_FLAG_MASTER_DISABLED, 100); if (ret) IWL_WARN(trans, "Master Disable Timed Out, 100 usec\n"); IWL_DEBUG_INFO(trans, "stop master\n"); return ret; } static void iwl_apm_stop(struct iwl_trans *trans) { struct iwl_trans_pcie *trans_pcie = IWL_TRANS_GET_PCIE_TRANS(trans); IWL_DEBUG_INFO(trans, "Stop card, put in low power state\n"); clear_bit(STATUS_DEVICE_ENABLED, &trans_pcie->status); /* Stop device's DMA activity */ iwl_apm_stop_master(trans); /* Reset the entire device */ iwl_set_bit(trans, CSR_RESET, CSR_RESET_REG_FLAG_SW_RESET); udelay(10); /* * Clear "initialization complete" bit to move adapter from * D0A* (powered-up Active) --> D0U* (Uninitialized) state. */ iwl_clear_bit(trans, CSR_GP_CNTRL, CSR_GP_CNTRL_REG_FLAG_INIT_DONE); } static int iwl_nic_init(struct iwl_trans *trans) { struct iwl_trans_pcie *trans_pcie = IWL_TRANS_GET_PCIE_TRANS(trans); unsigned long flags; /* nic_init */ spin_lock_irqsave(&trans_pcie->irq_lock, flags); iwl_apm_init(trans); /* Set interrupt coalescing calibration timer to default (512 usecs) */ iwl_write8(trans, CSR_INT_COALESCING, IWL_HOST_INT_CALIB_TIMEOUT_DEF); spin_unlock_irqrestore(&trans_pcie->irq_lock, flags); iwl_set_pwr_vmain(trans); iwl_op_mode_nic_config(trans->op_mode); #ifndef CONFIG_IWLWIFI_IDI /* Allocate the RX queue, or reset if it is already allocated */ iwl_rx_init(trans); #endif /* Allocate or reset and init all Tx and Command queues */ if (iwl_tx_init(trans)) return -ENOMEM; if (trans->cfg->base_params->shadow_reg_enable) { /* enable shadow regs in HW */ iwl_set_bit(trans, CSR_MAC_SHADOW_REG_CTRL, 0x800FFFFF); } return 0; } #define HW_READY_TIMEOUT (50) /* Note: returns poll_bit return value, which is >= 0 if success */ static int iwl_set_hw_ready(struct iwl_trans *trans) { int ret; iwl_set_bit(trans, CSR_HW_IF_CONFIG_REG, CSR_HW_IF_CONFIG_REG_BIT_NIC_READY); /* See if we got it */ ret = iwl_poll_bit(trans, CSR_HW_IF_CONFIG_REG, CSR_HW_IF_CONFIG_REG_BIT_NIC_READY, CSR_HW_IF_CONFIG_REG_BIT_NIC_READY, HW_READY_TIMEOUT); IWL_DEBUG_INFO(trans, "hardware%s ready\n", ret < 0 ? " not" : ""); return ret; } /* Note: returns standard 0/-ERROR code */ static int iwl_prepare_card_hw(struct iwl_trans *trans) { int ret; IWL_DEBUG_INFO(trans, "iwl_trans_prepare_card_hw enter\n"); ret = iwl_set_hw_ready(trans); /* If the card is ready, exit 0 */ if (ret >= 0) return 0; /* If HW is not ready, prepare the conditions to check again */ iwl_set_bit(trans, CSR_HW_IF_CONFIG_REG, CSR_HW_IF_CONFIG_REG_PREPARE); ret = iwl_poll_bit(trans, CSR_HW_IF_CONFIG_REG, ~CSR_HW_IF_CONFIG_REG_BIT_NIC_PREPARE_DONE, CSR_HW_IF_CONFIG_REG_BIT_NIC_PREPARE_DONE, 150000); if (ret < 0) return ret; /* HW should be ready by now, check again. */ ret = iwl_set_hw_ready(trans); if (ret >= 0) return 0; return ret; } /* * ucode */ static int iwl_load_section(struct iwl_trans *trans, u8 section_num, const struct fw_desc *section) { struct iwl_trans_pcie *trans_pcie = IWL_TRANS_GET_PCIE_TRANS(trans); dma_addr_t phy_addr = section->p_addr; u32 byte_cnt = section->len; u32 dst_addr = section->offset; int ret; trans_pcie->ucode_write_complete = false; iwl_write_direct32(trans, FH_TCSR_CHNL_TX_CONFIG_REG(FH_SRVC_CHNL), FH_TCSR_TX_CONFIG_REG_VAL_DMA_CHNL_PAUSE); iwl_write_direct32(trans, FH_SRVC_CHNL_SRAM_ADDR_REG(FH_SRVC_CHNL), dst_addr); iwl_write_direct32(trans, FH_TFDIB_CTRL0_REG(FH_SRVC_CHNL), phy_addr & FH_MEM_TFDIB_DRAM_ADDR_LSB_MSK); iwl_write_direct32(trans, FH_TFDIB_CTRL1_REG(FH_SRVC_CHNL), (iwl_get_dma_hi_addr(phy_addr) << FH_MEM_TFDIB_REG1_ADDR_BITSHIFT) | byte_cnt); iwl_write_direct32(trans, FH_TCSR_CHNL_TX_BUF_STS_REG(FH_SRVC_CHNL), 1 << FH_TCSR_CHNL_TX_BUF_STS_REG_POS_TB_NUM | 1 << FH_TCSR_CHNL_TX_BUF_STS_REG_POS_TB_IDX | FH_TCSR_CHNL_TX_BUF_STS_REG_VAL_TFDB_VALID); iwl_write_direct32(trans, FH_TCSR_CHNL_TX_CONFIG_REG(FH_SRVC_CHNL), FH_TCSR_TX_CONFIG_REG_VAL_DMA_CHNL_ENABLE | FH_TCSR_TX_CONFIG_REG_VAL_DMA_CREDIT_DISABLE | FH_TCSR_TX_CONFIG_REG_VAL_CIRQ_HOST_ENDTFD); IWL_DEBUG_FW(trans, "[%d] uCode section being loaded...\n", section_num); ret = wait_event_timeout(trans_pcie->ucode_write_waitq, trans_pcie->ucode_write_complete, 5 * HZ); if (!ret) { IWL_ERR(trans, "Could not load the [%d] uCode section\n", section_num); return -ETIMEDOUT; } return 0; } static int iwl_load_given_ucode(struct iwl_trans *trans, const struct fw_img *image) { int ret = 0; int i; for (i = 0; i < IWL_UCODE_SECTION_MAX; i++) { if (!image->sec[i].p_addr) break; ret = iwl_load_section(trans, i, &image->sec[i]); if (ret) return ret; } /* Remove all resets to allow NIC to operate */ iwl_write32(trans, CSR_RESET, 0); return 0; } static int iwl_trans_pcie_start_fw(struct iwl_trans *trans, const struct fw_img *fw) { int ret; bool hw_rfkill; /* This may fail if AMT took ownership of the device */ if (iwl_prepare_card_hw(trans)) { IWL_WARN(trans, "Exit HW not ready\n"); return -EIO; } iwl_enable_rfkill_int(trans); /* If platform's RF_KILL switch is NOT set to KILL */ hw_rfkill = iwl_is_rfkill_set(trans); iwl_op_mode_hw_rf_kill(trans->op_mode, hw_rfkill); if (hw_rfkill) return -ERFKILL; iwl_write32(trans, CSR_INT, 0xFFFFFFFF); ret = iwl_nic_init(trans); if (ret) { IWL_ERR(trans, "Unable to init nic\n"); return ret; } /* make sure rfkill handshake bits are cleared */ iwl_write32(trans, CSR_UCODE_DRV_GP1_CLR, CSR_UCODE_SW_BIT_RFKILL); iwl_write32(trans, CSR_UCODE_DRV_GP1_CLR, CSR_UCODE_DRV_GP1_BIT_CMD_BLOCKED); /* clear (again), then enable host interrupts */ iwl_write32(trans, CSR_INT, 0xFFFFFFFF); iwl_enable_interrupts(trans); /* really make sure rfkill handshake bits are cleared */ iwl_write32(trans, CSR_UCODE_DRV_GP1_CLR, CSR_UCODE_SW_BIT_RFKILL); iwl_write32(trans, CSR_UCODE_DRV_GP1_CLR, CSR_UCODE_SW_BIT_RFKILL); /* Load the given image to the HW */ return iwl_load_given_ucode(trans, fw); } /* * Activate/Deactivate Tx DMA/FIFO channels according tx fifos mask * must be called under the irq lock and with MAC access */ static void iwl_trans_txq_set_sched(struct iwl_trans *trans, u32 mask) { struct iwl_trans_pcie __maybe_unused *trans_pcie = IWL_TRANS_GET_PCIE_TRANS(trans); lockdep_assert_held(&trans_pcie->irq_lock); iwl_write_prph(trans, SCD_TXFACT, mask); } static void iwl_tx_start(struct iwl_trans *trans) { struct iwl_trans_pcie *trans_pcie = IWL_TRANS_GET_PCIE_TRANS(trans); u32 a; unsigned long flags; int i, chan; u32 reg_val; spin_lock_irqsave(&trans_pcie->irq_lock, flags); trans_pcie->scd_base_addr = iwl_read_prph(trans, SCD_SRAM_BASE_ADDR); a = trans_pcie->scd_base_addr + SCD_CONTEXT_MEM_LOWER_BOUND; /* reset conext data memory */ for (; a < trans_pcie->scd_base_addr + SCD_CONTEXT_MEM_UPPER_BOUND; a += 4) iwl_write_targ_mem(trans, a, 0); /* reset tx status memory */ for (; a < trans_pcie->scd_base_addr + SCD_TX_STTS_MEM_UPPER_BOUND; a += 4) iwl_write_targ_mem(trans, a, 0); for (; a < trans_pcie->scd_base_addr + SCD_TRANS_TBL_OFFSET_QUEUE( trans->cfg->base_params->num_of_queues); a += 4) iwl_write_targ_mem(trans, a, 0); iwl_write_prph(trans, SCD_DRAM_BASE_ADDR, trans_pcie->scd_bc_tbls.dma >> 10); /* Enable DMA channel */ for (chan = 0; chan < FH_TCSR_CHNL_NUM ; chan++) iwl_write_direct32(trans, FH_TCSR_CHNL_TX_CONFIG_REG(chan), FH_TCSR_TX_CONFIG_REG_VAL_DMA_CHNL_ENABLE | FH_TCSR_TX_CONFIG_REG_VAL_DMA_CREDIT_ENABLE); /* Update FH chicken bits */ reg_val = iwl_read_direct32(trans, FH_TX_CHICKEN_BITS_REG); iwl_write_direct32(trans, FH_TX_CHICKEN_BITS_REG, reg_val | FH_TX_CHICKEN_BITS_SCD_AUTO_RETRY_EN); iwl_write_prph(trans, SCD_QUEUECHAIN_SEL, SCD_QUEUECHAIN_SEL_ALL(trans, trans_pcie)); iwl_write_prph(trans, SCD_AGGR_SEL, 0); /* initiate the queues */ for (i = 0; i < trans->cfg->base_params->num_of_queues; i++) { iwl_write_prph(trans, SCD_QUEUE_RDPTR(i), 0); iwl_write_direct32(trans, HBUS_TARG_WRPTR, 0 | (i << 8)); iwl_write_targ_mem(trans, trans_pcie->scd_base_addr + SCD_CONTEXT_QUEUE_OFFSET(i), 0); iwl_write_targ_mem(trans, trans_pcie->scd_base_addr + SCD_CONTEXT_QUEUE_OFFSET(i) + sizeof(u32), ((SCD_WIN_SIZE << SCD_QUEUE_CTX_REG2_WIN_SIZE_POS) & SCD_QUEUE_CTX_REG2_WIN_SIZE_MSK) | ((SCD_FRAME_LIMIT << SCD_QUEUE_CTX_REG2_FRAME_LIMIT_POS) & SCD_QUEUE_CTX_REG2_FRAME_LIMIT_MSK)); } iwl_write_prph(trans, SCD_INTERRUPT_MASK, IWL_MASK(0, trans->cfg->base_params->num_of_queues)); /* Activate all Tx DMA/FIFO channels */ iwl_trans_txq_set_sched(trans, IWL_MASK(0, 7)); iwl_trans_set_wr_ptrs(trans, trans_pcie->cmd_queue, 0); /* make sure all queue are not stopped/used */ memset(trans_pcie->queue_stopped, 0, sizeof(trans_pcie->queue_stopped)); memset(trans_pcie->queue_used, 0, sizeof(trans_pcie->queue_used)); for (i = 0; i < trans_pcie->n_q_to_fifo; i++) { int fifo = trans_pcie->setup_q_to_fifo[i]; set_bit(i, trans_pcie->queue_used); iwl_trans_tx_queue_set_status(trans, &trans_pcie->txq[i], fifo, true); } spin_unlock_irqrestore(&trans_pcie->irq_lock, flags); /* Enable L1-Active */ iwl_clear_bits_prph(trans, APMG_PCIDEV_STT_REG, APMG_PCIDEV_STT_VAL_L1_ACT_DIS); } static void iwl_trans_pcie_fw_alive(struct iwl_trans *trans) { iwl_reset_ict(trans); iwl_tx_start(trans); } /** * iwlagn_txq_ctx_stop - Stop all Tx DMA channels */ static int iwl_trans_tx_stop(struct iwl_trans *trans) { int ch, txq_id, ret; unsigned long flags; struct iwl_trans_pcie *trans_pcie = IWL_TRANS_GET_PCIE_TRANS(trans); /* Turn off all Tx DMA fifos */ spin_lock_irqsave(&trans_pcie->irq_lock, flags); iwl_trans_txq_set_sched(trans, 0); /* Stop each Tx DMA channel, and wait for it to be idle */ for (ch = 0; ch < FH_TCSR_CHNL_NUM; ch++) { iwl_write_direct32(trans, FH_TCSR_CHNL_TX_CONFIG_REG(ch), 0x0); ret = iwl_poll_direct_bit(trans, FH_TSSR_TX_STATUS_REG, FH_TSSR_TX_STATUS_REG_MSK_CHNL_IDLE(ch), 1000); if (ret < 0) IWL_ERR(trans, "Failing on timeout while stopping" " DMA channel %d [0x%08x]", ch, iwl_read_direct32(trans, FH_TSSR_TX_STATUS_REG)); } spin_unlock_irqrestore(&trans_pcie->irq_lock, flags); if (!trans_pcie->txq) { IWL_WARN(trans, "Stopping tx queues that aren't allocated..."); return 0; } /* Unmap DMA from host system and free skb's */ for (txq_id = 0; txq_id < trans->cfg->base_params->num_of_queues; txq_id++) iwl_tx_queue_unmap(trans, txq_id); return 0; } static void iwl_trans_pcie_stop_device(struct iwl_trans *trans) { unsigned long flags; struct iwl_trans_pcie *trans_pcie = IWL_TRANS_GET_PCIE_TRANS(trans); /* tell the device to stop sending interrupts */ spin_lock_irqsave(&trans_pcie->irq_lock, flags); iwl_disable_interrupts(trans); spin_unlock_irqrestore(&trans_pcie->irq_lock, flags); /* device going down, Stop using ICT table */ iwl_disable_ict(trans); /* * If a HW restart happens during firmware loading, * then the firmware loading might call this function * and later it might be called again due to the * restart. So don't process again if the device is * already dead. */ if (test_bit(STATUS_DEVICE_ENABLED, &trans_pcie->status)) { iwl_trans_tx_stop(trans); #ifndef CONFIG_IWLWIFI_IDI iwl_trans_rx_stop(trans); #endif /* Power-down device's busmaster DMA clocks */ iwl_write_prph(trans, APMG_CLK_DIS_REG, APMG_CLK_VAL_DMA_CLK_RQT); udelay(5); } /* Make sure (redundant) we've released our request to stay awake */ iwl_clear_bit(trans, CSR_GP_CNTRL, CSR_GP_CNTRL_REG_FLAG_MAC_ACCESS_REQ); /* Stop the device, and put it in low power state */ iwl_apm_stop(trans); /* Upon stop, the APM issues an interrupt if HW RF kill is set. * Clean again the interrupt here */ spin_lock_irqsave(&trans_pcie->irq_lock, flags); iwl_disable_interrupts(trans); spin_unlock_irqrestore(&trans_pcie->irq_lock, flags); iwl_enable_rfkill_int(trans); /* wait to make sure we flush pending tasklet*/ synchronize_irq(trans_pcie->irq); tasklet_kill(&trans_pcie->irq_tasklet); cancel_work_sync(&trans_pcie->rx_replenish); /* stop and reset the on-board processor */ iwl_write32(trans, CSR_RESET, CSR_RESET_REG_FLAG_NEVO_RESET); /* clear all status bits */ clear_bit(STATUS_HCMD_ACTIVE, &trans_pcie->status); clear_bit(STATUS_INT_ENABLED, &trans_pcie->status); clear_bit(STATUS_DEVICE_ENABLED, &trans_pcie->status); clear_bit(STATUS_TPOWER_PMI, &trans_pcie->status); } static void iwl_trans_pcie_wowlan_suspend(struct iwl_trans *trans) { /* let the ucode operate on its own */ iwl_write32(trans, CSR_UCODE_DRV_GP1_SET, CSR_UCODE_DRV_GP1_BIT_D3_CFG_COMPLETE); iwl_disable_interrupts(trans); iwl_clear_bit(trans, CSR_GP_CNTRL, CSR_GP_CNTRL_REG_FLAG_MAC_ACCESS_REQ); } static int iwl_trans_pcie_tx(struct iwl_trans *trans, struct sk_buff *skb, struct iwl_device_cmd *dev_cmd, int txq_id) { struct iwl_trans_pcie *trans_pcie = IWL_TRANS_GET_PCIE_TRANS(trans); struct ieee80211_hdr *hdr = (struct ieee80211_hdr *)skb->data; struct iwl_tx_cmd *tx_cmd = (struct iwl_tx_cmd *) dev_cmd->payload; struct iwl_cmd_meta *out_meta; struct iwl_tx_queue *txq; struct iwl_queue *q; dma_addr_t phys_addr = 0; dma_addr_t txcmd_phys; dma_addr_t scratch_phys; u16 len, firstlen, secondlen; u8 wait_write_ptr = 0; __le16 fc = hdr->frame_control; u8 hdr_len = ieee80211_hdrlen(fc); u16 __maybe_unused wifi_seq; txq = &trans_pcie->txq[txq_id]; q = &txq->q; if (unlikely(!test_bit(txq_id, trans_pcie->queue_used))) { WARN_ON_ONCE(1); return -EINVAL; } spin_lock(&txq->lock); /* Set up driver data for this TFD */ txq->entries[q->write_ptr].skb = skb; txq->entries[q->write_ptr].cmd = dev_cmd; dev_cmd->hdr.cmd = REPLY_TX; dev_cmd->hdr.sequence = cpu_to_le16((u16)(QUEUE_TO_SEQ(txq_id) | INDEX_TO_SEQ(q->write_ptr))); /* Set up first empty entry in queue's array of Tx/cmd buffers */ out_meta = &txq->entries[q->write_ptr].meta; /* * Use the first empty entry in this queue's command buffer array * to contain the Tx command and MAC header concatenated together * (payload data will be in another buffer). * Size of this varies, due to varying MAC header length. * If end is not dword aligned, we'll have 2 extra bytes at the end * of the MAC header (device reads on dword boundaries). * We'll tell device about this padding later. */ len = sizeof(struct iwl_tx_cmd) + sizeof(struct iwl_cmd_header) + hdr_len; firstlen = (len + 3) & ~3; /* Tell NIC about any 2-byte padding after MAC header */ if (firstlen != len) tx_cmd->tx_flags |= TX_CMD_FLG_MH_PAD_MSK; /* Physical address of this Tx command's header (not MAC header!), * within command buffer array. */ txcmd_phys = dma_map_single(trans->dev, &dev_cmd->hdr, firstlen, DMA_BIDIRECTIONAL); if (unlikely(dma_mapping_error(trans->dev, txcmd_phys))) goto out_err; dma_unmap_addr_set(out_meta, mapping, txcmd_phys); dma_unmap_len_set(out_meta, len, firstlen); if (!ieee80211_has_morefrags(fc)) { txq->need_update = 1; } else { wait_write_ptr = 1; txq->need_update = 0; } /* Set up TFD's 2nd entry to point directly to remainder of skb, * if any (802.11 null frames have no payload). */ secondlen = skb->len - hdr_len; if (secondlen > 0) { phys_addr = dma_map_single(trans->dev, skb->data + hdr_len, secondlen, DMA_TO_DEVICE); if (unlikely(dma_mapping_error(trans->dev, phys_addr))) { dma_unmap_single(trans->dev, dma_unmap_addr(out_meta, mapping), dma_unmap_len(out_meta, len), DMA_BIDIRECTIONAL); goto out_err; } } /* Attach buffers to TFD */ iwlagn_txq_attach_buf_to_tfd(trans, txq, txcmd_phys, firstlen, 1); if (secondlen > 0) iwlagn_txq_attach_buf_to_tfd(trans, txq, phys_addr, secondlen, 0); scratch_phys = txcmd_phys + sizeof(struct iwl_cmd_header) + offsetof(struct iwl_tx_cmd, scratch); /* take back ownership of DMA buffer to enable update */ dma_sync_single_for_cpu(trans->dev, txcmd_phys, firstlen, DMA_BIDIRECTIONAL); tx_cmd->dram_lsb_ptr = cpu_to_le32(scratch_phys); tx_cmd->dram_msb_ptr = iwl_get_dma_hi_addr(scratch_phys); IWL_DEBUG_TX(trans, "sequence nr = 0X%x\n", le16_to_cpu(dev_cmd->hdr.sequence)); IWL_DEBUG_TX(trans, "tx_flags = 0X%x\n", le32_to_cpu(tx_cmd->tx_flags)); /* Set up entry for this TFD in Tx byte-count array */ iwl_trans_txq_update_byte_cnt_tbl(trans, txq, le16_to_cpu(tx_cmd->len)); dma_sync_single_for_device(trans->dev, txcmd_phys, firstlen, DMA_BIDIRECTIONAL); trace_iwlwifi_dev_tx(trans->dev, &((struct iwl_tfd *)txq->tfds)[txq->q.write_ptr], sizeof(struct iwl_tfd), &dev_cmd->hdr, firstlen, skb->data + hdr_len, secondlen); /* start timer if queue currently empty */ if (q->read_ptr == q->write_ptr && trans_pcie->wd_timeout) mod_timer(&txq->stuck_timer, jiffies + trans_pcie->wd_timeout); /* Tell device the write index *just past* this latest filled TFD */ q->write_ptr = iwl_queue_inc_wrap(q->write_ptr, q->n_bd); iwl_txq_update_write_ptr(trans, txq); /* * At this point the frame is "transmitted" successfully * and we will get a TX status notification eventually, * regardless of the value of ret. "ret" only indicates * whether or not we should update the write pointer. */ if (iwl_queue_space(q) < q->high_mark) { if (wait_write_ptr) { txq->need_update = 1; iwl_txq_update_write_ptr(trans, txq); } else { iwl_stop_queue(trans, txq); } } spin_unlock(&txq->lock); return 0; out_err: spin_unlock(&txq->lock); return -1; } static int iwl_trans_pcie_start_hw(struct iwl_trans *trans) { struct iwl_trans_pcie *trans_pcie = IWL_TRANS_GET_PCIE_TRANS(trans); int err; bool hw_rfkill; trans_pcie->inta_mask = CSR_INI_SET_MASK; if (!trans_pcie->irq_requested) { tasklet_init(&trans_pcie->irq_tasklet, (void (*)(unsigned long)) iwl_irq_tasklet, (unsigned long)trans); iwl_alloc_isr_ict(trans); err = request_irq(trans_pcie->irq, iwl_isr_ict, IRQF_SHARED, DRV_NAME, trans); if (err) { IWL_ERR(trans, "Error allocating IRQ %d\n", trans_pcie->irq); goto error; } INIT_WORK(&trans_pcie->rx_replenish, iwl_bg_rx_replenish); trans_pcie->irq_requested = true; } err = iwl_prepare_card_hw(trans); if (err) { IWL_ERR(trans, "Error while preparing HW: %d", err); goto err_free_irq; } iwl_apm_init(trans); /* From now on, the op_mode will be kept updated about RF kill state */ iwl_enable_rfkill_int(trans); hw_rfkill = iwl_is_rfkill_set(trans); iwl_op_mode_hw_rf_kill(trans->op_mode, hw_rfkill); return err; err_free_irq: free_irq(trans_pcie->irq, trans); error: iwl_free_isr_ict(trans); tasklet_kill(&trans_pcie->irq_tasklet); return err; } static void iwl_trans_pcie_stop_hw(struct iwl_trans *trans, bool op_mode_leaving) { bool hw_rfkill; unsigned long flags; struct iwl_trans_pcie *trans_pcie = IWL_TRANS_GET_PCIE_TRANS(trans); iwl_apm_stop(trans); spin_lock_irqsave(&trans_pcie->irq_lock, flags); iwl_disable_interrupts(trans); spin_unlock_irqrestore(&trans_pcie->irq_lock, flags); iwl_write32(trans, CSR_INT, 0xFFFFFFFF); if (!op_mode_leaving) { /* * Even if we stop the HW, we still want the RF kill * interrupt */ iwl_enable_rfkill_int(trans); /* * Check again since the RF kill state may have changed while * all the interrupts were disabled, in this case we couldn't * receive the RF kill interrupt and update the state in the * op_mode. */ hw_rfkill = iwl_is_rfkill_set(trans); iwl_op_mode_hw_rf_kill(trans->op_mode, hw_rfkill); } } static void iwl_trans_pcie_reclaim(struct iwl_trans *trans, int txq_id, int ssn, struct sk_buff_head *skbs) { struct iwl_trans_pcie *trans_pcie = IWL_TRANS_GET_PCIE_TRANS(trans); struct iwl_tx_queue *txq = &trans_pcie->txq[txq_id]; /* n_bd is usually 256 => n_bd - 1 = 0xff */ int tfd_num = ssn & (txq->q.n_bd - 1); int freed = 0; spin_lock(&txq->lock); if (txq->q.read_ptr != tfd_num) { IWL_DEBUG_TX_REPLY(trans, "[Q %d] %d -> %d (%d)\n", txq_id, txq->q.read_ptr, tfd_num, ssn); freed = iwl_tx_queue_reclaim(trans, txq_id, tfd_num, skbs); if (iwl_queue_space(&txq->q) > txq->q.low_mark) iwl_wake_queue(trans, txq); } spin_unlock(&txq->lock); } static void iwl_trans_pcie_write8(struct iwl_trans *trans, u32 ofs, u8 val) { writeb(val, IWL_TRANS_GET_PCIE_TRANS(trans)->hw_base + ofs); } static void iwl_trans_pcie_write32(struct iwl_trans *trans, u32 ofs, u32 val) { writel(val, IWL_TRANS_GET_PCIE_TRANS(trans)->hw_base + ofs); } static u32 iwl_trans_pcie_read32(struct iwl_trans *trans, u32 ofs) { return readl(IWL_TRANS_GET_PCIE_TRANS(trans)->hw_base + ofs); } static void iwl_trans_pcie_configure(struct iwl_trans *trans, const struct iwl_trans_config *trans_cfg) { struct iwl_trans_pcie *trans_pcie = IWL_TRANS_GET_PCIE_TRANS(trans); trans_pcie->cmd_queue = trans_cfg->cmd_queue; if (WARN_ON(trans_cfg->n_no_reclaim_cmds > MAX_NO_RECLAIM_CMDS)) trans_pcie->n_no_reclaim_cmds = 0; else trans_pcie->n_no_reclaim_cmds = trans_cfg->n_no_reclaim_cmds; if (trans_pcie->n_no_reclaim_cmds) memcpy(trans_pcie->no_reclaim_cmds, trans_cfg->no_reclaim_cmds, trans_pcie->n_no_reclaim_cmds * sizeof(u8)); trans_pcie->n_q_to_fifo = trans_cfg->n_queue_to_fifo; if (WARN_ON(trans_pcie->n_q_to_fifo > IWL_MAX_HW_QUEUES)) trans_pcie->n_q_to_fifo = IWL_MAX_HW_QUEUES; /* at least the command queue must be mapped */ WARN_ON(!trans_pcie->n_q_to_fifo); memcpy(trans_pcie->setup_q_to_fifo, trans_cfg->queue_to_fifo, trans_pcie->n_q_to_fifo * sizeof(u8)); trans_pcie->rx_buf_size_8k = trans_cfg->rx_buf_size_8k; if (trans_pcie->rx_buf_size_8k) trans_pcie->rx_page_order = get_order(8 * 1024); else trans_pcie->rx_page_order = get_order(4 * 1024); trans_pcie->wd_timeout = msecs_to_jiffies(trans_cfg->queue_watchdog_timeout); trans_pcie->command_names = trans_cfg->command_names; } void iwl_trans_pcie_free(struct iwl_trans *trans) { struct iwl_trans_pcie *trans_pcie = IWL_TRANS_GET_PCIE_TRANS(trans); iwl_trans_pcie_tx_free(trans); #ifndef CONFIG_IWLWIFI_IDI iwl_trans_pcie_rx_free(trans); #endif if (trans_pcie->irq_requested == true) { free_irq(trans_pcie->irq, trans); iwl_free_isr_ict(trans); } pci_disable_msi(trans_pcie->pci_dev); iounmap(trans_pcie->hw_base); pci_release_regions(trans_pcie->pci_dev); pci_disable_device(trans_pcie->pci_dev); kfree(trans); } static void iwl_trans_pcie_set_pmi(struct iwl_trans *trans, bool state) { struct iwl_trans_pcie *trans_pcie = IWL_TRANS_GET_PCIE_TRANS(trans); if (state) set_bit(STATUS_TPOWER_PMI, &trans_pcie->status); else clear_bit(STATUS_TPOWER_PMI, &trans_pcie->status); } #ifdef CONFIG_PM_SLEEP static int iwl_trans_pcie_suspend(struct iwl_trans *trans) { return 0; } static int iwl_trans_pcie_resume(struct iwl_trans *trans) { bool hw_rfkill; iwl_enable_rfkill_int(trans); hw_rfkill = iwl_is_rfkill_set(trans); iwl_op_mode_hw_rf_kill(trans->op_mode, hw_rfkill); if (!hw_rfkill) iwl_enable_interrupts(trans); return 0; } #endif /* CONFIG_PM_SLEEP */ #define IWL_FLUSH_WAIT_MS 2000 static int iwl_trans_pcie_wait_tx_queue_empty(struct iwl_trans *trans) { struct iwl_trans_pcie *trans_pcie = IWL_TRANS_GET_PCIE_TRANS(trans); struct iwl_tx_queue *txq; struct iwl_queue *q; int cnt; unsigned long now = jiffies; int ret = 0; /* waiting for all the tx frames complete might take a while */ for (cnt = 0; cnt < trans->cfg->base_params->num_of_queues; cnt++) { if (cnt == trans_pcie->cmd_queue) continue; txq = &trans_pcie->txq[cnt]; q = &txq->q; while (q->read_ptr != q->write_ptr && !time_after(jiffies, now + msecs_to_jiffies(IWL_FLUSH_WAIT_MS))) msleep(1); if (q->read_ptr != q->write_ptr) { IWL_ERR(trans, "fail to flush all tx fifo queues\n"); ret = -ETIMEDOUT; break; } } return ret; } static const char *get_fh_string(int cmd) { #define IWL_CMD(x) case x: return #x switch (cmd) { IWL_CMD(FH_RSCSR_CHNL0_STTS_WPTR_REG); IWL_CMD(FH_RSCSR_CHNL0_RBDCB_BASE_REG); IWL_CMD(FH_RSCSR_CHNL0_WPTR); IWL_CMD(FH_MEM_RCSR_CHNL0_CONFIG_REG); IWL_CMD(FH_MEM_RSSR_SHARED_CTRL_REG); IWL_CMD(FH_MEM_RSSR_RX_STATUS_REG); IWL_CMD(FH_MEM_RSSR_RX_ENABLE_ERR_IRQ2DRV); IWL_CMD(FH_TSSR_TX_STATUS_REG); IWL_CMD(FH_TSSR_TX_ERROR_REG); default: return "UNKNOWN"; } #undef IWL_CMD } int iwl_dump_fh(struct iwl_trans *trans, char **buf, bool display) { int i; #ifdef CONFIG_IWLWIFI_DEBUG int pos = 0; size_t bufsz = 0; #endif static const u32 fh_tbl[] = { FH_RSCSR_CHNL0_STTS_WPTR_REG, FH_RSCSR_CHNL0_RBDCB_BASE_REG, FH_RSCSR_CHNL0_WPTR, FH_MEM_RCSR_CHNL0_CONFIG_REG, FH_MEM_RSSR_SHARED_CTRL_REG, FH_MEM_RSSR_RX_STATUS_REG, FH_MEM_RSSR_RX_ENABLE_ERR_IRQ2DRV, FH_TSSR_TX_STATUS_REG, FH_TSSR_TX_ERROR_REG }; #ifdef CONFIG_IWLWIFI_DEBUG if (display) { bufsz = ARRAY_SIZE(fh_tbl) * 48 + 40; *buf = kmalloc(bufsz, GFP_KERNEL); if (!*buf) return -ENOMEM; pos += scnprintf(*buf + pos, bufsz - pos, "FH register values:\n"); for (i = 0; i < ARRAY_SIZE(fh_tbl); i++) { pos += scnprintf(*buf + pos, bufsz - pos, " %34s: 0X%08x\n", get_fh_string(fh_tbl[i]), iwl_read_direct32(trans, fh_tbl[i])); } return pos; } #endif IWL_ERR(trans, "FH register values:\n"); for (i = 0; i < ARRAY_SIZE(fh_tbl); i++) { IWL_ERR(trans, " %34s: 0X%08x\n", get_fh_string(fh_tbl[i]), iwl_read_direct32(trans, fh_tbl[i])); } return 0; } static const char *get_csr_string(int cmd) { #define IWL_CMD(x) case x: return #x switch (cmd) { IWL_CMD(CSR_HW_IF_CONFIG_REG); IWL_CMD(CSR_INT_COALESCING); IWL_CMD(CSR_INT); IWL_CMD(CSR_INT_MASK); IWL_CMD(CSR_FH_INT_STATUS); IWL_CMD(CSR_GPIO_IN); IWL_CMD(CSR_RESET); IWL_CMD(CSR_GP_CNTRL); IWL_CMD(CSR_HW_REV); IWL_CMD(CSR_EEPROM_REG); IWL_CMD(CSR_EEPROM_GP); IWL_CMD(CSR_OTP_GP_REG); IWL_CMD(CSR_GIO_REG); IWL_CMD(CSR_GP_UCODE_REG); IWL_CMD(CSR_GP_DRIVER_REG); IWL_CMD(CSR_UCODE_DRV_GP1); IWL_CMD(CSR_UCODE_DRV_GP2); IWL_CMD(CSR_LED_REG); IWL_CMD(CSR_DRAM_INT_TBL_REG); IWL_CMD(CSR_GIO_CHICKEN_BITS); IWL_CMD(CSR_ANA_PLL_CFG); IWL_CMD(CSR_HW_REV_WA_REG); IWL_CMD(CSR_DBG_HPET_MEM_REG); default: return "UNKNOWN"; } #undef IWL_CMD } void iwl_dump_csr(struct iwl_trans *trans) { int i; static const u32 csr_tbl[] = { CSR_HW_IF_CONFIG_REG, CSR_INT_COALESCING, CSR_INT, CSR_INT_MASK, CSR_FH_INT_STATUS, CSR_GPIO_IN, CSR_RESET, CSR_GP_CNTRL, CSR_HW_REV, CSR_EEPROM_REG, CSR_EEPROM_GP, CSR_OTP_GP_REG, CSR_GIO_REG, CSR_GP_UCODE_REG, CSR_GP_DRIVER_REG, CSR_UCODE_DRV_GP1, CSR_UCODE_DRV_GP2, CSR_LED_REG, CSR_DRAM_INT_TBL_REG, CSR_GIO_CHICKEN_BITS, CSR_ANA_PLL_CFG, CSR_HW_REV_WA_REG, CSR_DBG_HPET_MEM_REG }; IWL_ERR(trans, "CSR values:\n"); IWL_ERR(trans, "(2nd byte of CSR_INT_COALESCING is " "CSR_INT_PERIODIC_REG)\n"); for (i = 0; i < ARRAY_SIZE(csr_tbl); i++) { IWL_ERR(trans, " %25s: 0X%08x\n", get_csr_string(csr_tbl[i]), iwl_read32(trans, csr_tbl[i])); } } #ifdef CONFIG_IWLWIFI_DEBUGFS /* create and remove of files */ #define DEBUGFS_ADD_FILE(name, parent, mode) do { \ if (!debugfs_create_file(#name, mode, parent, trans, \ &iwl_dbgfs_##name##_ops)) \ return -ENOMEM; \ } while (0) /* file operation */ #define DEBUGFS_READ_FUNC(name) \ static ssize_t iwl_dbgfs_##name##_read(struct file *file, \ char __user *user_buf, \ size_t count, loff_t *ppos); #define DEBUGFS_WRITE_FUNC(name) \ static ssize_t iwl_dbgfs_##name##_write(struct file *file, \ const char __user *user_buf, \ size_t count, loff_t *ppos); #define DEBUGFS_READ_FILE_OPS(name) \ DEBUGFS_READ_FUNC(name); \ static const struct file_operations iwl_dbgfs_##name##_ops = { \ .read = iwl_dbgfs_##name##_read, \ .open = simple_open, \ .llseek = generic_file_llseek, \ }; #define DEBUGFS_WRITE_FILE_OPS(name) \ DEBUGFS_WRITE_FUNC(name); \ static const struct file_operations iwl_dbgfs_##name##_ops = { \ .write = iwl_dbgfs_##name##_write, \ .open = simple_open, \ .llseek = generic_file_llseek, \ }; #define DEBUGFS_READ_WRITE_FILE_OPS(name) \ DEBUGFS_READ_FUNC(name); \ DEBUGFS_WRITE_FUNC(name); \ static const struct file_operations iwl_dbgfs_##name##_ops = { \ .write = iwl_dbgfs_##name##_write, \ .read = iwl_dbgfs_##name##_read, \ .open = simple_open, \ .llseek = generic_file_llseek, \ }; static ssize_t iwl_dbgfs_tx_queue_read(struct file *file, char __user *user_buf, size_t count, loff_t *ppos) { struct iwl_trans *trans = file->private_data; struct iwl_trans_pcie *trans_pcie = IWL_TRANS_GET_PCIE_TRANS(trans); struct iwl_tx_queue *txq; struct iwl_queue *q; char *buf; int pos = 0; int cnt; int ret; size_t bufsz; bufsz = sizeof(char) * 64 * trans->cfg->base_params->num_of_queues; if (!trans_pcie->txq) return -EAGAIN; buf = kzalloc(bufsz, GFP_KERNEL); if (!buf) return -ENOMEM; for (cnt = 0; cnt < trans->cfg->base_params->num_of_queues; cnt++) { txq = &trans_pcie->txq[cnt]; q = &txq->q; pos += scnprintf(buf + pos, bufsz - pos, "hwq %.2d: read=%u write=%u use=%d stop=%d\n", cnt, q->read_ptr, q->write_ptr, !!test_bit(cnt, trans_pcie->queue_used), !!test_bit(cnt, trans_pcie->queue_stopped)); } ret = simple_read_from_buffer(user_buf, count, ppos, buf, pos); kfree(buf); return ret; } static ssize_t iwl_dbgfs_rx_queue_read(struct file *file, char __user *user_buf, size_t count, loff_t *ppos) { struct iwl_trans *trans = file->private_data; struct iwl_trans_pcie *trans_pcie = IWL_TRANS_GET_PCIE_TRANS(trans); struct iwl_rx_queue *rxq = &trans_pcie->rxq; char buf[256]; int pos = 0; const size_t bufsz = sizeof(buf); pos += scnprintf(buf + pos, bufsz - pos, "read: %u\n", rxq->read); pos += scnprintf(buf + pos, bufsz - pos, "write: %u\n", rxq->write); pos += scnprintf(buf + pos, bufsz - pos, "free_count: %u\n", rxq->free_count); if (rxq->rb_stts) { pos += scnprintf(buf + pos, bufsz - pos, "closed_rb_num: %u\n", le16_to_cpu(rxq->rb_stts->closed_rb_num) & 0x0FFF); } else { pos += scnprintf(buf + pos, bufsz - pos, "closed_rb_num: Not Allocated\n"); } return simple_read_from_buffer(user_buf, count, ppos, buf, pos); } static ssize_t iwl_dbgfs_interrupt_read(struct file *file, char __user *user_buf, size_t count, loff_t *ppos) { struct iwl_trans *trans = file->private_data; struct iwl_trans_pcie *trans_pcie = IWL_TRANS_GET_PCIE_TRANS(trans); struct isr_statistics *isr_stats = &trans_pcie->isr_stats; int pos = 0; char *buf; int bufsz = 24 * 64; /* 24 items * 64 char per item */ ssize_t ret; buf = kzalloc(bufsz, GFP_KERNEL); if (!buf) return -ENOMEM; pos += scnprintf(buf + pos, bufsz - pos, "Interrupt Statistics Report:\n"); pos += scnprintf(buf + pos, bufsz - pos, "HW Error:\t\t\t %u\n", isr_stats->hw); pos += scnprintf(buf + pos, bufsz - pos, "SW Error:\t\t\t %u\n", isr_stats->sw); if (isr_stats->sw || isr_stats->hw) { pos += scnprintf(buf + pos, bufsz - pos, "\tLast Restarting Code: 0x%X\n", isr_stats->err_code); } #ifdef CONFIG_IWLWIFI_DEBUG pos += scnprintf(buf + pos, bufsz - pos, "Frame transmitted:\t\t %u\n", isr_stats->sch); pos += scnprintf(buf + pos, bufsz - pos, "Alive interrupt:\t\t %u\n", isr_stats->alive); #endif pos += scnprintf(buf + pos, bufsz - pos, "HW RF KILL switch toggled:\t %u\n", isr_stats->rfkill); pos += scnprintf(buf + pos, bufsz - pos, "CT KILL:\t\t\t %u\n", isr_stats->ctkill); pos += scnprintf(buf + pos, bufsz - pos, "Wakeup Interrupt:\t\t %u\n", isr_stats->wakeup); pos += scnprintf(buf + pos, bufsz - pos, "Rx command responses:\t\t %u\n", isr_stats->rx); pos += scnprintf(buf + pos, bufsz - pos, "Tx/FH interrupt:\t\t %u\n", isr_stats->tx); pos += scnprintf(buf + pos, bufsz - pos, "Unexpected INTA:\t\t %u\n", isr_stats->unhandled); ret = simple_read_from_buffer(user_buf, count, ppos, buf, pos); kfree(buf); return ret; } static ssize_t iwl_dbgfs_interrupt_write(struct file *file, const char __user *user_buf, size_t count, loff_t *ppos) { struct iwl_trans *trans = file->private_data; struct iwl_trans_pcie *trans_pcie = IWL_TRANS_GET_PCIE_TRANS(trans); struct isr_statistics *isr_stats = &trans_pcie->isr_stats; char buf[8]; int buf_size; u32 reset_flag; memset(buf, 0, sizeof(buf)); buf_size = min(count, sizeof(buf) - 1); if (copy_from_user(buf, user_buf, buf_size)) return -EFAULT; if (sscanf(buf, "%x", &reset_flag) != 1) return -EFAULT; if (reset_flag == 0) memset(isr_stats, 0, sizeof(*isr_stats)); return count; } static ssize_t iwl_dbgfs_csr_write(struct file *file, const char __user *user_buf, size_t count, loff_t *ppos) { struct iwl_trans *trans = file->private_data; char buf[8]; int buf_size; int csr; memset(buf, 0, sizeof(buf)); buf_size = min(count, sizeof(buf) - 1); if (copy_from_user(buf, user_buf, buf_size)) return -EFAULT; if (sscanf(buf, "%d", &csr) != 1) return -EFAULT; iwl_dump_csr(trans); return count; } static ssize_t iwl_dbgfs_fh_reg_read(struct file *file, char __user *user_buf, size_t count, loff_t *ppos) { struct iwl_trans *trans = file->private_data; char *buf; int pos = 0; ssize_t ret = -EFAULT; ret = pos = iwl_dump_fh(trans, &buf, true); if (buf) { ret = simple_read_from_buffer(user_buf, count, ppos, buf, pos); kfree(buf); } return ret; } static ssize_t iwl_dbgfs_fw_restart_write(struct file *file, const char __user *user_buf, size_t count, loff_t *ppos) { struct iwl_trans *trans = file->private_data; if (!trans->op_mode) return -EAGAIN; iwl_op_mode_nic_error(trans->op_mode); return count; } DEBUGFS_READ_WRITE_FILE_OPS(interrupt); DEBUGFS_READ_FILE_OPS(fh_reg); DEBUGFS_READ_FILE_OPS(rx_queue); DEBUGFS_READ_FILE_OPS(tx_queue); DEBUGFS_WRITE_FILE_OPS(csr); DEBUGFS_WRITE_FILE_OPS(fw_restart); /* * Create the debugfs files and directories * */ static int iwl_trans_pcie_dbgfs_register(struct iwl_trans *trans, struct dentry *dir) { DEBUGFS_ADD_FILE(rx_queue, dir, S_IRUSR); DEBUGFS_ADD_FILE(tx_queue, dir, S_IRUSR); DEBUGFS_ADD_FILE(interrupt, dir, S_IWUSR | S_IRUSR); DEBUGFS_ADD_FILE(csr, dir, S_IWUSR); DEBUGFS_ADD_FILE(fh_reg, dir, S_IRUSR); DEBUGFS_ADD_FILE(fw_restart, dir, S_IWUSR); return 0; } #else static int iwl_trans_pcie_dbgfs_register(struct iwl_trans *trans, struct dentry *dir) { return 0; } #endif /*CONFIG_IWLWIFI_DEBUGFS */ static const struct iwl_trans_ops trans_ops_pcie = { .start_hw = iwl_trans_pcie_start_hw, .stop_hw = iwl_trans_pcie_stop_hw, .fw_alive = iwl_trans_pcie_fw_alive, .start_fw = iwl_trans_pcie_start_fw, .stop_device = iwl_trans_pcie_stop_device, .wowlan_suspend = iwl_trans_pcie_wowlan_suspend, .send_cmd = iwl_trans_pcie_send_cmd, .tx = iwl_trans_pcie_tx, .reclaim = iwl_trans_pcie_reclaim, .tx_agg_disable = iwl_trans_pcie_tx_agg_disable, .tx_agg_setup = iwl_trans_pcie_tx_agg_setup, .dbgfs_register = iwl_trans_pcie_dbgfs_register, .wait_tx_queue_empty = iwl_trans_pcie_wait_tx_queue_empty, #ifdef CONFIG_PM_SLEEP .suspend = iwl_trans_pcie_suspend, .resume = iwl_trans_pcie_resume, #endif .write8 = iwl_trans_pcie_write8, .write32 = iwl_trans_pcie_write32, .read32 = iwl_trans_pcie_read32, .configure = iwl_trans_pcie_configure, .set_pmi = iwl_trans_pcie_set_pmi, }; struct iwl_trans *iwl_trans_pcie_alloc(struct pci_dev *pdev, const struct pci_device_id *ent, const struct iwl_cfg *cfg) { struct iwl_trans_pcie *trans_pcie; struct iwl_trans *trans; u16 pci_cmd; int err; trans = kzalloc(sizeof(struct iwl_trans) + sizeof(struct iwl_trans_pcie), GFP_KERNEL); if (WARN_ON(!trans)) return NULL; trans_pcie = IWL_TRANS_GET_PCIE_TRANS(trans); trans->ops = &trans_ops_pcie; trans->cfg = cfg; trans_pcie->trans = trans; spin_lock_init(&trans_pcie->irq_lock); init_waitqueue_head(&trans_pcie->ucode_write_waitq); /* W/A - seems to solve weird behavior. We need to remove this if we * don't want to stay in L1 all the time. This wastes a lot of power */ pci_disable_link_state(pdev, PCIE_LINK_STATE_L0S | PCIE_LINK_STATE_L1 | PCIE_LINK_STATE_CLKPM); if (pci_enable_device(pdev)) { err = -ENODEV; goto out_no_pci; } pci_set_master(pdev); err = pci_set_dma_mask(pdev, DMA_BIT_MASK(36)); if (!err) err = pci_set_consistent_dma_mask(pdev, DMA_BIT_MASK(36)); if (err) { err = pci_set_dma_mask(pdev, DMA_BIT_MASK(32)); if (!err) err = pci_set_consistent_dma_mask(pdev, DMA_BIT_MASK(32)); /* both attempts failed: */ if (err) { dev_printk(KERN_ERR, &pdev->dev, "No suitable DMA available.\n"); goto out_pci_disable_device; } } err = pci_request_regions(pdev, DRV_NAME); if (err) { dev_printk(KERN_ERR, &pdev->dev, "pci_request_regions failed"); goto out_pci_disable_device; } trans_pcie->hw_base = pci_ioremap_bar(pdev, 0); if (!trans_pcie->hw_base) { dev_printk(KERN_ERR, &pdev->dev, "pci_ioremap_bar failed"); err = -ENODEV; goto out_pci_release_regions; } dev_printk(KERN_INFO, &pdev->dev, "pci_resource_len = 0x%08llx\n", (unsigned long long) pci_resource_len(pdev, 0)); dev_printk(KERN_INFO, &pdev->dev, "pci_resource_base = %p\n", trans_pcie->hw_base); dev_printk(KERN_INFO, &pdev->dev, "HW Revision ID = 0x%X\n", pdev->revision); /* We disable the RETRY_TIMEOUT register (0x41) to keep * PCI Tx retries from interfering with C3 CPU state */ pci_write_config_byte(pdev, PCI_CFG_RETRY_TIMEOUT, 0x00); err = pci_enable_msi(pdev); if (err) dev_printk(KERN_ERR, &pdev->dev, "pci_enable_msi failed(0X%x)", err); trans->dev = &pdev->dev; trans_pcie->irq = pdev->irq; trans_pcie->pci_dev = pdev; trans->hw_rev = iwl_read32(trans, CSR_HW_REV); trans->hw_id = (pdev->device << 16) + pdev->subsystem_device; snprintf(trans->hw_id_str, sizeof(trans->hw_id_str), "PCI ID: 0x%04X:0x%04X", pdev->device, pdev->subsystem_device); /* TODO: Move this away, not needed if not MSI */ /* enable rfkill interrupt: hw bug w/a */ pci_read_config_word(pdev, PCI_COMMAND, &pci_cmd); if (pci_cmd & PCI_COMMAND_INTX_DISABLE) { pci_cmd &= ~PCI_COMMAND_INTX_DISABLE; pci_write_config_word(pdev, PCI_COMMAND, pci_cmd); } /* Initialize the wait queue for commands */ init_waitqueue_head(&trans->wait_command_queue); spin_lock_init(&trans->reg_lock); return trans; out_pci_release_regions: pci_release_regions(pdev); out_pci_disable_device: pci_disable_device(pdev); out_no_pci: kfree(trans); return NULL; }
yamahata/linux-umem
drivers/net/wireless/iwlwifi/iwl-trans-pcie.c
C
gpl-2.0
61,690
<?php /** * The partial for display within the head section. * * @package Bow */ // Get theme mods $css = get_theme_mod( 'css' ); $javascript = get_theme_mod( 'javascript' ); /* CSS */ if ( $css ) : ?> <style><?php echo $css; ?></style> <?php endif; /* JavaScript */ if ( $javascript ) : ?> <script><?php echo $javascript; ?></script> <?php endif;
jaunte/starkly
partials/header-meta.php
PHP
gpl-2.0
357
/* Output variables, constants and external declarations, for GNU compiler. Copyright (C) 1996, 1997, 1998, 2000, 2001, 2002, 2004, 2005, 2007, 2008, 2009 Free Software Foundation, Inc. This file is part of GCC. GCC is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 3, or (at your option) any later version. GCC is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with GCC; see the file COPYING3. If not see <http://www.gnu.org/licenses/>. */ #define TARGET_OBJECT_SUFFIX ".obj" #define TARGET_EXECUTABLE_SUFFIX ".exe" /* Alpha/VMS object format is not really Elf, but this makes compiling crtstuff.c and dealing with shared library initialization much easier. */ #define OBJECT_FORMAT_ELF /* This enables certain macros in alpha.h, which will make an indirect reference to an external symbol an invalid address. This needs to be defined before we include alpha.h, since it determines which macros are used for GO_IF_*. */ #define NO_EXTERNAL_INDIRECT_ADDRESS #define TARGET_OS_CPP_BUILTINS() \ do { \ builtin_define_std ("vms"); \ builtin_define_std ("VMS"); \ builtin_define ("__ALPHA"); \ builtin_assert ("system=vms"); \ if (TARGET_FLOAT_VAX) \ builtin_define ("__G_FLOAT"); \ else \ builtin_define ("__IEEE_FLOAT"); \ } while (0) #undef TARGET_DEFAULT #define TARGET_DEFAULT (MASK_FPREGS|MASK_GAS) #undef TARGET_ABI_OPEN_VMS #define TARGET_ABI_OPEN_VMS 1 #undef TARGET_NAME #define TARGET_NAME "OpenVMS/Alpha" #undef TARGET_VERSION #define TARGET_VERSION fprintf (stderr, " (%s)", TARGET_NAME); #define VMS_DEBUG_MAIN_POINTER "TRANSFER$BREAK$GO" #undef PCC_STATIC_STRUCT_RETURN /* "long" is 32 bits, but 64 bits for Ada. */ #undef LONG_TYPE_SIZE #define LONG_TYPE_SIZE 32 #define ADA_LONG_TYPE_SIZE 64 /* Pointer is 32 bits but the hardware has 64-bit addresses, sign extended. */ #undef POINTER_SIZE #define POINTER_SIZE 32 #define POINTERS_EXTEND_UNSIGNED 0 #define HANDLE_SYSV_PRAGMA 1 #define MAX_OFILE_ALIGNMENT 524288 /* 8 x 2^16 by DEC Ada Test CD40VRA */ /* The maximum alignment 'malloc' honors. */ #undef MALLOC_ALIGNMENT #define MALLOC_ALIGNMENT ((TARGET_MALLOC64 ? 16 : 8) * BITS_PER_UNIT) #undef FIXED_REGISTERS #define FIXED_REGISTERS \ {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, \ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, \ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, \ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1 } #undef CALL_USED_REGISTERS #define CALL_USED_REGISTERS \ {1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, \ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, \ 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, \ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1 } /* List the order in which to allocate registers. Each register must be listed once, even those in FIXED_REGISTERS. We allocate in the following order: $f1 (nonsaved floating-point register) $f10-$f15 (likewise) $f22-$f30 (likewise) $f21-$f16 (likewise, but input args) $f0 (nonsaved, but return value) $f2-$f9 (saved floating-point registers) $1 (nonsaved integer registers) $22-$25 (likewise) $28 (likewise) $0 (likewise, but return value) $21-$16 (likewise, but input args) $27 (procedure value in OSF, nonsaved in NT) $2-$8 (saved integer registers) $9-$14 (saved integer registers) $26 (return PC) $15 (frame pointer) $29 (global pointer) $30, $31, $f31 (stack pointer and always zero/ap & fp) */ #undef REG_ALLOC_ORDER #define REG_ALLOC_ORDER \ {33, \ 42, 43, 44, 45, 46, 47, \ 54, 55, 56, 57, 58, 59, 60, 61, 62, \ 53, 52, 51, 50, 49, 48, \ 32, \ 34, 35, 36, 37, 38, 39, 40, 41, \ 1, \ 22, 23, 24, 25, \ 28, \ 0, \ 21, 20, 19, 18, 17, 16, \ 27, \ 2, 3, 4, 5, 6, 7, 8, \ 9, 10, 11, 12, 13, 14, \ 26, \ 15, \ 29, \ 30, 31, 63 } #undef HARD_FRAME_POINTER_REGNUM #define HARD_FRAME_POINTER_REGNUM 29 /* Define registers used by the epilogue and return instruction. */ #undef EPILOGUE_USES #define EPILOGUE_USES(REGNO) ((REGNO) == 26 || (REGNO) == 29) #undef INITIAL_ELIMINATION_OFFSET #define INITIAL_ELIMINATION_OFFSET(FROM, TO, OFFSET) \ ((OFFSET) = alpha_vms_initial_elimination_offset(FROM, TO)) /* Define a data type for recording info about an argument list during the scan of that argument list. This data type should hold all necessary information about the function itself and about the args processed so far, enough to enable macros such as FUNCTION_ARG to determine where the next arg should go. On Alpha/VMS, this is a structure that contains the number of arguments and, for each argument, the datatype of that argument. The number of arguments is a number of words of arguments scanned so far. Thus 6 or more means all following args should go on the stack. */ enum avms_arg_type {I64, FF, FD, FG, FS, FT}; typedef struct {int num_args; enum avms_arg_type atypes[6];} avms_arg_info; #undef CUMULATIVE_ARGS #define CUMULATIVE_ARGS avms_arg_info /* Initialize a variable CUM of type CUMULATIVE_ARGS for a call to a function whose data type is FNTYPE. For a library call, FNTYPE is 0. */ #undef INIT_CUMULATIVE_ARGS #define INIT_CUMULATIVE_ARGS(CUM, FNTYPE, LIBNAME, INDIRECT, N_NAMED_ARGS) \ (CUM).num_args = 0; \ (CUM).atypes[0] = (CUM).atypes[1] = (CUM).atypes[2] = I64; \ (CUM).atypes[3] = (CUM).atypes[4] = (CUM).atypes[5] = I64; #undef FUNCTION_ARG_ADVANCE #define FUNCTION_ARG_ADVANCE(CUM, MODE, TYPE, NAMED) \ if (targetm.calls.must_pass_in_stack (MODE, TYPE)) \ (CUM).num_args += 6; \ else \ { \ if ((CUM).num_args < 6) \ (CUM).atypes[(CUM).num_args] = alpha_arg_type (MODE); \ \ (CUM).num_args += ALPHA_ARG_SIZE (MODE, TYPE, NAMED); \ } #define DEFAULT_PCC_STRUCT_RETURN 0 #undef ASM_WEAKEN_LABEL #define ASM_WEAKEN_LABEL(FILE, NAME) \ do { fputs ("\t.weak\t", FILE); assemble_name (FILE, NAME); \ fputc ('\n', FILE); } while (0) #define READONLY_DATA_SECTION_ASM_OP "\t.rdata" #define CTORS_SECTION_ASM_OP "\t.ctors" #define DTORS_SECTION_ASM_OP "\t.dtors" #define SDATA_SECTION_ASM_OP "\t.sdata" #define CRT_CALL_STATIC_FUNCTION(SECTION_OP, FUNC) \ asm (SECTION_OP "\n\t.long " #FUNC"\n"); #undef ASM_OUTPUT_ADDR_DIFF_ELT #define ASM_OUTPUT_ADDR_DIFF_ELT(FILE, BODY, VALUE, REL) gcc_unreachable () #undef ASM_OUTPUT_ADDR_VEC_ELT #define ASM_OUTPUT_ADDR_VEC_ELT(FILE, VALUE) \ fprintf (FILE, "\t.quad $L%d\n", (VALUE)) #undef CASE_VECTOR_MODE #define CASE_VECTOR_MODE DImode #undef CASE_VECTOR_PC_RELATIVE #undef ASM_OUTPUT_CASE_LABEL #define ASM_OUTPUT_CASE_LABEL(FILE,PREFIX,NUM,TABLEINSN) \ { ASM_OUTPUT_ALIGN (FILE, 3); (*targetm.asm_out.internal_label) (FILE, PREFIX, NUM); } /* This says how to output assembler code to declare an uninitialized external linkage data object. */ #define COMMON_ASM_OP "\t.comm\t" #undef ASM_OUTPUT_ALIGNED_DECL_COMMON #define ASM_OUTPUT_ALIGNED_DECL_COMMON(FILE, DECL, NAME, SIZE, ALIGN) \ vms_output_aligned_decl_common (FILE, DECL, NAME, SIZE, ALIGN) /* Control how constructors and destructors are emitted. */ #define TARGET_ASM_CONSTRUCTOR vms_asm_out_constructor #define TARGET_ASM_DESTRUCTOR vms_asm_out_destructor #undef SDB_DEBUGGING_INFO #undef MIPS_DEBUGGING_INFO #undef DBX_DEBUGGING_INFO #define DWARF2_DEBUGGING_INFO 1 #define VMS_DEBUGGING_INFO 1 #define DWARF2_UNWIND_INFO 1 #undef EH_RETURN_HANDLER_RTX #define EH_RETURN_HANDLER_RTX \ gen_rtx_MEM (Pmode, plus_constant (stack_pointer_rtx, 8)) #define LINK_EH_SPEC "vms-dwarf2eh.o%s " #define LINK_GCC_C_SEQUENCE_SPEC "%G" #ifdef IN_LIBGCC2 /* Get the definition for MD_FALLBACK_FRAME_STATE_FOR from a separate file. This avoids having to recompile the world instead of libgcc only when changes to this macro are exercised. */ #define MD_UNWIND_SUPPORT "config/alpha/vms-unwind.h" #endif #define ASM_OUTPUT_EXTERNAL(FILE, DECL, NAME) \ avms_asm_output_external (FILE, DECL, NAME) typedef struct crtl_name_spec { const char *const name; const char *deccname; int referenced; } crtl_name_spec; #include "config/vms/vms-crtl.h" /* Alias CRTL names to 32/64bit DECCRTL functions. Fixme: This should do a binary search. */ #define DO_CRTL_NAMES \ do \ { \ int i; \ static crtl_name_spec vms_crtl_names[] = CRTL_NAMES; \ static int malloc64_init = 0; \ \ if ((malloc64_init == 0) && TARGET_MALLOC64) \ { \ for (i=0; vms_crtl_names [i].name; i++) \ { \ if (strcmp ("calloc", vms_crtl_names [i].name) == 0) \ vms_crtl_names [i].deccname = "decc$_calloc64"; \ else \ if (strcmp ("malloc", vms_crtl_names [i].name) == 0) \ vms_crtl_names [i].deccname = "decc$_malloc64"; \ else \ if (strcmp ("realloc", vms_crtl_names [i].name) == 0) \ vms_crtl_names [i].deccname = "decc$_realloc64"; \ else \ if (strcmp ("strdup", vms_crtl_names [i].name) == 0) \ vms_crtl_names [i].deccname = "decc$_strdup64"; \ } \ malloc64_init = 1; \ } \ for (i=0; vms_crtl_names [i].name; i++) \ if (!vms_crtl_names [i].referenced && \ (strcmp (name, vms_crtl_names [i].name) == 0)) \ { \ fprintf (file, "\t%s=%s\n", \ name, vms_crtl_names [i].deccname); \ vms_crtl_names [i].referenced = 1; \ } \ } while (0) /* This is how to output an assembler line that says to advance the location counter to a multiple of 2**LOG bytes. */ #undef ASM_OUTPUT_ALIGN #define ASM_OUTPUT_ALIGN(FILE,LOG) \ fprintf (FILE, "\t.align %d\n", LOG); /* Switch into a generic section. */ #define TARGET_ASM_NAMED_SECTION vms_asm_named_section #define ASM_OUTPUT_DEF(FILE,LABEL1,LABEL2) \ do { fprintf ((FILE), "\t.literals\n"); \ in_section = NULL; \ fprintf ((FILE), "\t"); \ assemble_name (FILE, LABEL1); \ fprintf (FILE, " = "); \ assemble_name (FILE, LABEL2); \ fprintf (FILE, "\n"); \ } while (0) #undef PREFERRED_DEBUGGING_TYPE #define PREFERRED_DEBUGGING_TYPE VMS_AND_DWARF2_DEBUG #define ASM_PN_FORMAT "%s___%lu" /* ??? VMS uses different linkage. */ #undef TARGET_ASM_OUTPUT_MI_THUNK #undef ASM_SPEC #undef ASM_FINAL_SPEC /* The VMS convention is to always provide minimal debug info for a traceback unless specifically overridden. */ #undef OVERRIDE_OPTIONS #define OVERRIDE_OPTIONS \ { \ if (write_symbols == NO_DEBUG \ && debug_info_level == DINFO_LEVEL_NONE) \ { \ write_symbols = VMS_DEBUG; \ debug_info_level = DINFO_LEVEL_TERSE; \ } \ override_options (); \ } /* Link with vms-dwarf2.o if -g (except -g0). This causes the VMS link to pull all the dwarf2 debug sections together. */ #undef LINK_SPEC #define LINK_SPEC "%{g:-g vms-dwarf2.o%s} %{g0} %{g1:-g1 vms-dwarf2.o%s} \ %{g2:-g2 vms-dwarf2.o%s} %{g3:-g3 vms-dwarf2.o%s} %{shared} %{v} %{map}" #undef STARTFILE_SPEC #define STARTFILE_SPEC \ "%{!shared:%{mvms-return-codes:vcrt0.o%s} %{!mvms-return-codes:pcrt0.o%s} \ crtbegin.o%s} \ %{!static:%{shared:crtbeginS.o%s}}" #define ENDFILE_SPEC \ "%{!shared:crtend.o%s} %{!static:%{shared:crtendS.o%s}}" #define NAME__MAIN "__gccmain" #define SYMBOL__MAIN __gccmain #define INIT_SECTION_ASM_OP "\t.section LIB$INITIALIZE,GBL,NOWRT" #define LONGLONG_STANDALONE 1 #undef TARGET_VALID_POINTER_MODE #define TARGET_VALID_POINTER_MODE vms_valid_pointer_mode
ccompiler4pic32/pic32-gcc
gcc/config/alpha/vms.h
C
gpl-2.0
13,534
/* * 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. * * Copyright (C) 1994, 1995 by Waldorf Electronics, written by Ralf Baechle. * Copyright (C) 1999 by Silicon Graphics, Inc. * Copyright (C) 1999 by Harald Koerfgen * Copyright (C) 2011 MIPS Technologies, Inc. * * Dump R3000 TLB for debugging purposes. */ #include <linux/kernel.h> #include <linux/mm.h> #include <asm/mipsregs.h> #include <asm/page.h> #include <asm/pgtable.h> #include <asm/tlbdebug.h> extern int r3k_have_wired_reg; /* defined in tlb-r3k.c */ static void dump_tlb(int first, int last) { int i; unsigned int asid; unsigned long entryhi, entrylo0; asid = read_c0_entryhi() & 0xfc0; for (i = first; i <= last; i++) { write_c0_index(i<<8); __asm__ __volatile__( ".set\tnoreorder\n\t" "tlbr\n\t" "nop\n\t" ".set\treorder"); entryhi = read_c0_entryhi(); entrylo0 = read_c0_entrylo0(); /* Unused entries have a virtual address of KSEG0. */ if ((entryhi & 0xffffe000) != 0x80000000 && (entryhi & 0xfc0) == asid) { /* * Only print entries in use */ printk("Index: %2d ", i); printk("va=%08lx asid=%08lx" " [pa=%06lx n=%d d=%d v=%d g=%d]", (entryhi & 0xffffe000), entryhi & 0xfc0, entrylo0 & PAGE_MASK, (entrylo0 & (1 << 11)) ? 1 : 0, (entrylo0 & (1 << 10)) ? 1 : 0, (entrylo0 & (1 << 9)) ? 1 : 0, (entrylo0 & (1 << 8)) ? 1 : 0); } } printk("\n"); write_c0_entryhi(asid); } void dump_tlb_all(void) { dump_tlb(0, current_cpu_data.tlbsize - 1); }
IngenicSemiconductor/kernel-inwatch
arch/mips/lib/r3k_dump_tlb.c
C
gpl-2.0
1,687
import os import sys import glob import traceback from PyQt4.QtCore import QCoreApplication from qgis.core import QgsApplication, QgsMessageLog def load_user_expressions(path): """ Load all user expressions from the given paths """ #Loop all py files and import them modules = glob.glob(path + "/*.py") names = [os.path.basename(f)[:-3] for f in modules] for name in names: if name == "__init__": continue # As user expression functions should be registered with qgsfunction # just importing the file is enough to get it to load the functions into QGIS try: __import__("expressions.{0}".format(name), locals(), globals()) except: error = traceback.format_exc() msgtitle = QCoreApplication.translate("UserExpressions", "User expressions") msg = QCoreApplication.translate("UserExpressions", "The user expression {0} is not valid").format(name) QgsMessageLog.logMessage(msg + "\n" + error, msgtitle, QgsMessageLog.WARNING) userpythonhome = os.path.join(QgsApplication.qgisSettingsDirPath(), "python") expressionspath = os.path.join(userpythonhome, "expressions") startuppy = os.path.join(userpythonhome, "startup.py") sys.path.append(userpythonhome) # exec startup script if os.path.exists(startuppy): exec(compile(open(startuppy).read(), startuppy, 'exec'), locals(), globals()) if not os.path.exists(expressionspath): os.makedirs(expressionspath) initfile = os.path.join(expressionspath, "__init__.py") if not os.path.exists(initfile): open(initfile, "w").close() template = """\"\"\" Define new functions using @qgsfunction. feature and parent must always be the last args. Use args=-1 to pass a list of values as arguments \"\"\" from qgis.core import * from qgis.gui import * @qgsfunction(args='auto', group='Custom') def func(value1, feature, parent): return value1 """ try: import expressions expressions.load = load_user_expressions expressions.load(expressionspath) expressions.template = template except ImportError: # We get a import error and crash for some reason even if we make the expressions package # TODO Fix the crash on first load with no expressions folder # But for now it's not the end of the world if it doesn't laod the first time pass
jarped/QGIS
python/user.py
Python
gpl-2.0
2,363
package Slurm::Constant; use strict; use warnings; use Carp; my %const; my $got = 0; sub _get_constants { seek(DATA, 0, 0); local $/=''; # paragraph mode local $_; while(<DATA>) { next unless /^=item\s+\*\s+(\S+)\s+(\S+)\s*$/; my ($name, $val) = ($1,$2); if ($val =~ /^0x/) { $val = hex($val); } else { $val = int($val); } $const{$name} = sub () { $val }; } $got = 1; } sub import { my $pkg = shift; my $callpkg = caller(0); croak "Please use `use Slurm qw(:constant)' instead of `use Slurm::Constant'." unless $callpkg eq "Slurm"; _get_constants() unless $got; { no strict "refs"; my ($sym, $sub); while (($sym, $sub) = each(%const)) { *{$callpkg . "::$sym"} = $sub; } } } sub import2 { my $pkg = shift; my $callpkg = caller(0); croak "Please use `use Slurm qw(:constant)' instead of `use Slurm::Constant'." unless $callpkg eq "Slurm"; my $main = caller(1); _get_constants() unless $got; { no strict "refs"; my ($sym, $sub); while (($sym, $sub) = each(%const)) { *{$main . "::$sym"} = $sub; } } } 1; __DATA__ =head1 NAME Slurm::Constant - Constants for use with Slurm =head1 SYNOPSIS use Slurm qw(:constant); if ($rc != SLURM_SUCCESS { print STDERR "action failed!\n"; } =head1 DESCRIPTION This package export constants for use with Slurm. This includes enumerations and defined macros. The constants will be exported to package Slurm and the package which "use Slurm qw(:constant);". =head1 EXPORTED CONSTANTS =head2 DEFINED MACROS =head3 Misc values =over 2 =item * TRUE 1 =item * FALSE 0 =item * INFINITE 0xffffffff =item * NO_VAL 0xfffffffe =item * MAX_TASKS_PER_NODE 128 =item * SLURM_BATCH_SCRIPT 0xfffffffe =back =head3 Job state flags =over 2 =item * JOB_STATE_BASE 0x00ff =item * JOB_STATE_FLAGS 0xff00 =item * JOB_COMPLETING 0x8000 =item * JOB_CONFIGURING 0x4000 =item * JOB_RESIZING 0x2000 =item * READY_JOB_FATAL -2 =item * READY_JOB_ERROR -1 =item * READY_NODE_STATE 0x01 =item * READY_JOB_STATE 0x02 =back =head3 Job mail notification =over 2 =item * MAIL_JOB_BEGIN 0x0001 =item * MAIL_JOB_END 0x0002 =item * MAIL_JOB_FAIL 0x0004 =item * MAIL_JOB_REQUEUE 0x0008 =back =head3 Offset for job's nice value =over 2 =item * NICE_OFFSET 10000 =back =head3 Partition state flags =over 2 =item * PARTITION_SUBMIT 0x01 =item * PARTITION_SCHED 0x02 =item * PARTITION_DOWN 0x01 =item * PARTITION_UP 0x03 =item * PARTITION_DRAIN 0x02 =item * PARTITION_INACTIVE 0x00 =back =head3 Open stdout/stderr mode =over 2 =item * OPEN_MODE_APPEND 1 =item * OPEN_MODE_TRUNCATE 2 =back =head3 Node state flags =over 2 =item * NODE_STATE_BASE 0x00ff =item * NODE_STATE_FLAGS 0xff00 =item * NODE_RESUME 0x0100 =item * NODE_STATE_DRAIN 0x0200 =item * NODE_STATE_COMPLETING 0x0400 =item * NODE_STATE_NO_RESPOND 0x0800 =item * NODE_STATE_POWER_SAVE 0x1000 =item * NODE_STATE_FAIL 0x2000 =item * NODE_STATE_POWER_UP 0x4000 =item * NODE_STATE_MAINT 0x8000 =back =head3 Size of the credential signature =over 2 =item * SLURM_SSL_SIGNATURE_LENGTH 128 =back =head3 show_flags of slurm_get_/slurm_load_ function calls =over 2 =item * SHOW_ALL 0x0001 =item * SHOW_DETAIL 0x0002 =back =head3 Consumerable resources parameters =over 2 =item * CR_CPU 0x0001 =item * CR_SOCKET 0x0002 =item * CR_CORE 0x0004 =item * CR_MEMORY 0x0010 =item * CR_ONE_TASK_PER_CORE 0x0100 =item * CR_CORE_DEFAULT_DIST_BLOCK 0x1000 =item * MEM_PER_CPU 0x80000000 =item * SHARED_FORCE 0x8000 =back =head3 Private data values =over 2 =item * PRIVATE_DATA_JOBS 0x0001 =item * PRIVATE_DATA_NODES 0x0002 =item * PRIVATE_DATA_PARTITIONS 0x0004 =item * PRIVATE_DATA_USAGE 0x0008 =item * PRIVATE_DATA_USERS 0x0010 =item * PRIVATE_DATA_ACCOUNTS 0x0020 =item * PRIVATE_DATA_RESERVATIONS 0x0040 =back =head3 Priority reset period =over 2 =item * PRIORITY_RESET_NONE 0x0000 =item * PRIORITY_RESET_NOW 0x0001 =item * PRIORITY_RESET_DAILY 0x0002 =item * PRIORITY_RESET_WEEKLY 0x0003 =item * PRIORITY_RESET_MONTHLY 0x0004 =item * PRIORITY_RESET_QUARTERLY 0x0005 =item * PRIORITY_RESET_YEARLY 0x0006 =back =head3 Process priority propagation =over 2 =item * PROP_PRIO_OFF 0x0000 =item * PROP_PRIO_ON 0x0001 =item * PROP_PRIO_NICER 0x0002 =back =head3 Partition state information =over 2 =item * PART_FLAG_DEFAULT 0x0001 =item * PART_FLAG_HIDDEN 0x0002 =item * PART_FLAG_NO_ROOT 0x0004 =item * PART_FLAG_ROOT_ONLY 0x0008 =item * PART_FLAG_DEFAULT_CLR 0x0100 =item * PART_FLAG_HIDDEN_CLR 0x0200 =item * PART_FLAG_NO_ROOT_CLR 0x0400 =item * PART_FLAG_ROOT_ONLY_CLR 0x0800 =back =head3 Reservation flags =over 2 =item * RESERVE_FLAG_MAINT 0x0001 =item * RESERVE_FLAG_NO_MAINT 0x0002 =item * RESERVE_FLAG_DAILY 0x0004 =item * RESERVE_FLAG_NO_DAILY 0x0008 =item * RESERVE_FLAG_WEEKLY 0x0010 =item * RESERVE_FLAG_NO_WEEKLY 0x0020 =item * RESERVE_FLAG_IGN_JOBS 0x0040 =item * RESERVE_FLAG_NO_IGN_JOB 0x0080 =item * RESERVE_FLAG_OVERLAP 0x4000 =item * RESERVE_FLAG_SPEC_NODES 0x8000 =back =head3 Log debug flags =over 2 =item * DEBUG_FLAG_SELECT_TYPE 0x00000001 =item * DEBUG_FLAG_STEPS 0x00000002 =item * DEBUG_FLAG_TRIGGERS 0x00000004 =item * DEBUG_FLAG_CPU_BIND 0x00000008 =item * DEBUG_FLAG_WIKI 0x00000010 =item * DEBUG_FLAG_NO_CONF_HASH 0x00000020 =item * DEBUG_FLAG_GRES 0x00000040 =item * DEBUG_FLAG_BG_PICK 0x00000080 =item * DEBUG_FLAG_BG_WIRES 0x00000100 =item * DEBUG_FLAG_BG_ALGO 0x00000200 =item * DEBUG_FLAG_BG_ALGO_DEEP 0x00000400 =item * DEBUG_FLAG_PRIO 0x00000800 =item * DEBUG_FLAG_BACKFILL 0x00001000 =item * DEBUG_FLAG_GANG 0x00002000 =item * DEBUG_FLAG_RESERVATION 0x00004000 =back =head3 Group cache =over 2 =item * GROUP_FORCE 0x8000 =item * GROUP_CACHE 0x4000 =item * GROUP_TIME_MASK 0x0fff =back =head3 Preempt mode =over 2 =item * PREEMPT_MODE_OFF 0x0000 =item * PREEMPT_MODE_SUSPEND 0x0001 =item * PREEMPT_MODE_REQUEUE 0x0002 =item * PREEMPT_MODE_CHECKPOINT 0x0004 =item * PREEMPT_MODE_CANCEL 0x0008 =item * PREEMPT_MODE_GANG 0x8000 =back =head3 Trigger type =over 2 =item * TRIGGER_RES_TYPE_JOB 0x0001 =item * TRIGGER_RES_TYPE_NODE 0x0002 =item * TRIGGER_RES_TYPE_SLURMCTLD 0x0003 =item * TRIGGER_RES_TYPE_SLURMDBD 0x0004 =item * TRIGGER_RES_TYPE_DATABASE 0x0005 =item * TRIGGER_TYPE_UP 0x00000001 =item * TRIGGER_TYPE_DOWN 0x00000002 =item * TRIGGER_TYPE_FAIL 0x00000004 =item * TRIGGER_TYPE_TIME 0x00000008 =item * TRIGGER_TYPE_FINI 0x00000010 =item * TRIGGER_TYPE_RECONFIG 0x00000020 =item * TRIGGER_TYPE_BLOCK_ERR 0x00000040 =item * TRIGGER_TYPE_IDLE 0x00000080 =item * TRIGGER_TYPE_DRAINED 0x00000100 =item * TRIGGER_TYPE_PRI_CTLD_FAIL 0x00000200 =item * TRIGGER_TYPE_PRI_CTLD_RES_OP 0x00000400 =item * TRIGGER_TYPE_PRI_CTLD_RES_CTRL 0x00000800 =item * TRIGGER_TYPE_PRI_CTLD_ACCT_FULL 0x00001000 =item * TRIGGER_TYPE_BU_CTLD_FAIL 0x00002000 =item * TRIGGER_TYPE_BU_CTLD_RES_OP 0x00004000 =item * TRIGGER_TYPE_BU_CTLD_AS_CTRL 0x00008000 =item * TRIGGER_TYPE_PRI_DBD_FAIL 0x00010000 =item * TRIGGER_TYPE_PRI_DBD_RES_OP 0x00020000 =item * TRIGGER_TYPE_PRI_DB_FAIL 0x00040000 =item * TRIGGER_TYPE_PRI_DB_RES_OP 0x00080000 =back =head2 Enumerations =head3 Job states =over 2 =item * JOB_PENDING 0 =item * JOB_RUNNING 1 =item * JOB_SUSPENDED 2 =item * JOB_COMPLETE 3 =item * JOB_CANCELLED 4 =item * JOB_FAILED 5 =item * JOB_TIMEOUT 6 =item * JOB_NODE_FAIL 7 =item * JOB_END 8 =back =head3 Job state reason =over 2 =item * WAIT_NO_REASON 0 =item * WAIT_PRIORITY 1 =item * WAIT_DEPENDENCY 2 =item * WAIT_RESOURCES 3 =item * WAIT_PART_NODE_LIMIT 4 =item * WAIT_PART_TIME_LIMIT 5 =item * WAIT_PART_DOWN 6 =item * WAIT_PART_INACTIVE 7 =item * WAIT_HELD 8 =item * WAIT_TIME 9 =item * WAIT_LICENSES 10 =item * WAIT_ASSOC_JOB_LIMIT 11 =item * WAIT_ASSOC_RESOURCE_LIMIT 12 =item * WAIT_ASSOC_TIME_LIMIT 13 =item * WAIT_RESERVATION 14 =item * WAIT_NODE_NOT_AVAIL 15 =item * WAIT_HELD_USER 16 =item * WAIT_TBD2 17 =item * FAIL_DOWN_PARTITION 18 =item * FAIL_DOWN_NODE 19 =item * FAIL_BAD_CONSTRAINTS 20 =item * FAIL_SYSTEM 21 =item * FAIL_LAUNCH 22 =item * FAIL_EXIT_CODE 23 =item * FAIL_TIMEOUT 24 =item * FAIL_INACTIVE_LIMIT 25 =item * FAIL_ACCOUNT 26 =item * FAIL_QOS 27 =item * WAIT_QOS_THRES 28 =back =head3 Job account types =over 2 =item * JOB_START 0 =item * JOB_STEP 1 =item * JOB_SUSPEND 2 =item * JOB_TERMINATED 3 =back =head3 Connection type =over 2 =item * SELECT_MESH 0 =item * SELECT_TORUS 1 =item * SELECT_NAV 2 =item * SELECT_SMALL 3 =item * SELECT_HTC_S 4 =item * SELECT_HTC_D 5 =item * SELECT_HTC_V 6 =item * SELECT_HTC_L 7 =back =head3 Node use type =over 2 =item * SELECT_COPROCESSOR_MODE 0 =item * SELECT_VIRTUAL_NODE_MODE 1 =item * SELECT_NAV_MODE 2 =back =head3 Select jobdata type =over 2 =item * SELECT_JOBDATA_GEOMETRY 0 =item * SELECT_JOBDATA_ROTATE 1 =item * SELECT_JOBDATA_CONN_TYPE 2 =item * SELECT_JOBDATA_BLOCK_ID 3 =item * SELECT_JOBDATA_NODES 4 =item * SELECT_JOBDATA_IONODES 5 =item * SELECT_JOBDATA_NODE_CNT 6 =item * SELECT_JOBDATA_ALTERED 7 =item * SELECT_JOBDATA_BLRTS_IMAGE 8 =item * SELECT_JOBDATA_LINUX_IMAGE 9 =item * SELECT_JOBDATA_MLOADER_IMAGE 10 =item * SELECT_JOBDATA_RAMDISK_IMAGE 11 =item * SELECT_JOBDATA_REBOOT 12 =item * SELECT_JOBDATA_RESV_ID 13 =item * SELECT_JOBDATA_PTR 14 =back =head3 Select nodedata type =over 2 =item * SELECT_NODEDATA_BITMAP_SIZE 0 =item * SELECT_NODEDATA_SUBGRP_SIZE 1 =item * SELECT_NODEDATA_SUBCNT 2 =item * SELECT_NODEDATA_BITMAP 3 =item * SELECT_NODEDATA_STR 4 =item * SELECT_NODEDATA_PTR 5 =back =head3 Select print mode =over 2 =item * SELECT_PRINT_HEAD 0 =item * SELECT_PRINT_DATA 1 =item * SELECT_PRINT_MIXED 2 =item * SELECT_PRINT_MIXED_SHORT 3 =item * SELECT_PRINT_BG_ID 4 =item * SELECT_PRINT_NODES 5 =item * SELECT_PRINT_CONNECTION 6 =item * SELECT_PRINT_ROTATE 7 =item * SELECT_PRINT_GEOMETRY 8 =item * SELECT_PRINT_START 9 =item * SELECT_PRINT_BLRTS_IMAGE 10 =item * SELECT_PRINT_LINUX_IMAGE 11 =item * SELECT_PRINT_MLOADER_IMAGE 12 =item * SELECT_PRINT_RAMDISK_IMAGE 13 =item * SELECT_PRINT_REBOOT 14 =item * SELECT_PRINT_RESV_ID 15 =back =head3 Select node cnt =over 2 =item * SELECT_GET_NODE_SCALING 0 =item * SELECT_GET_NODE_CPU_CNT 1 =item * SELECT_GET_BP_CPU_CNT 2 =item * SELECT_APPLY_NODE_MIN_OFFSET 3 =item * SELECT_APPLY_NODE_MAX_OFFSET 4 =item * SELECT_SET_NODE_CNT 5 =item * SELECT_SET_BP_CNT 6 =back =head3 Jobacct data type =over 2 =item * JOBACCT_DATA_TOTAL 0 =item * JOBACCT_DATA_PIPE 1 =item * JOBACCT_DATA_RUSAGE 2 =item * JOBACCT_DATA_MAX_VSIZE 3 =item * JOBACCT_DATA_MAX_VSIZE_ID 4 =item * JOBACCT_DATA_TOT_VSIZE 5 =item * JOBACCT_DATA_MAX_RSS 6 =item * JOBACCT_DATA_MAX_RSS_ID 7 =item * JOBACCT_DATA_TOT_RSS 8 =item * JOBACCT_DATA_MAX_PAGES 9 =item * JOBACCT_DATA_MAX_PAGES_ID 10 =item * JOBACCT_DATA_TOT_PAGES 11 =item * JOBACCT_DATA_MIN_CPU 12 =item * JOBACCT_DATA_MIN_CPU_ID 13 =item * JOBACCT_DATA_TOT_CPU 14 =back =head3 Task distribution =over 2 =item * SLURM_DIST_CYCLIC 1 =item * SLURM_DIST_BLOCK 2 =item * SLURM_DIST_ARBITRARY 3 =item * SLURM_DIST_PLANE 4 =item * SLURM_DIST_CYCLIC_CYCLIC 5 =item * SLURM_DIST_CYCLIC_BLOCK 6 =item * SLURM_DIST_BLOCK_CYCLIC 7 =item * SLURM_DIST_BLOCK_BLOCK 8 =item * SLURM_NO_LLLP_DIST 9 =item * SLURM_DIST_UNKNOWN 10 =back =head3 CPU bind type =over 2 =item * CPU_BIND_VERBOSE 0x01 =item * CPU_BIND_TO_THREADS 0x02 =item * CPU_BIND_TO_CORES 0x04 =item * CPU_BIND_TO_SOCKETS 0x08 =item * CPU_BIND_TO_LDOMS 0x10 =item * CPU_BIND_NONE 0x20 =item * CPU_BIND_RANK 0x40 =item * CPU_BIND_MAP 0x80 =item * CPU_BIND_MASK 0x100 =item * CPU_BIND_LDRANK 0x200 =item * CPU_BIND_LDMAP 0x400 =item * CPU_BIND_LDMASK 0x800 =item * CPU_BIND_CPUSETS 0x8000 =back =head3 Memory bind type =over 2 =item * MEM_BIND_VERBOSE 0x01 =item * MEM_BIND_NONE 0x02 =item * MEM_BIND_RANK 0x04 =item * MEM_BIND_MAP 0x08 =item * MEM_BIND_MASK 0x10 =item * MEM_BIND_LOCAL 0x20 =back =head3 Node state =over 2 =item * NODE_STATE_UNKNOWN 0 =item * NODE_STATE_DOWN 1 =item * NODE_STATE_IDLE 2 =item * NODE_STATE_ALLOCATED 3 =item * NODE_STATE_ERROR 4 =item * NODE_STATE_MIXED 5 =item * NODE_STATE_FUTURE 6 =item * NODE_STATE_END 7 =back =head3 Ctx keys =over 2 =item * SLURM_STEP_CTX_STEPID 0 =item * SLURM_STEP_CTX_TASKS 1 =item * SLURM_STEP_CTX_TID 2 =item * SLURM_STEP_CTX_RESP 3 =item * SLURM_STEP_CTX_CRED 4 =item * SLURM_STEP_CTX_SWITCH_JOB 5 =item * SLURM_STEP_CTX_NUM_HOSTS 6 =item * SLURM_STEP_CTX_HOST 7 =item * SLURM_STEP_CTX_JOBID 8 =item * SLURM_STEP_CTX_USER_MANAGED_SOCKETS 9 =back head2 SLURM ERRNO =head3 Defined macro error values =over 2 =item * SLURM_SUCCESS 0 =item * SLURM_ERROR -1 =item * SLURM_FAILURE -1 =item * SLURM_SOCKET_ERROR -1 =item * SLURM_PROTOCOL_SUCCESS 0 =item * SLURM_PROTOCOL_ERROR -1 =back =head3 General Message error codes =over 2 =item * SLURM_UNEXPECTED_MSG_ERROR 1000 =item * SLURM_COMMUNICATIONS_CONNECTION_ERROR 1001 =item * SLURM_COMMUNICATIONS_SEND_ERROR 1002 =item * SLURM_COMMUNICATIONS_RECEIVE_ERROR 1003 =item * SLURM_COMMUNICATIONS_SHUTDOWN_ERROR 1004 =item * SLURM_PROTOCOL_VERSION_ERROR 1005 =item * SLURM_PROTOCOL_IO_STREAM_VERSION_ERROR 1006 =item * SLURM_PROTOCOL_AUTHENTICATION_ERROR 1007 =item * SLURM_PROTOCOL_INSANE_MSG_LENGTH 1008 =item * SLURM_MPI_PLUGIN_NAME_INVALID 1009 =item * SLURM_MPI_PLUGIN_PRELAUNCH_SETUP_FAILED 1010 =item * SLURM_PLUGIN_NAME_INVALID 1011 =item * SLURM_UNKNOWN_FORWARD_ADDR 1012 =back =head3 communication failures to/from slurmctld =over 2 =item * SLURMCTLD_COMMUNICATIONS_CONNECTION_ERROR 1800 =item * SLURMCTLD_COMMUNICATIONS_SEND_ERROR 1801 =item * SLURMCTLD_COMMUNICATIONS_RECEIVE_ERROR 1802 =item * SLURMCTLD_COMMUNICATIONS_SHUTDOWN_ERROR 1803 =back =head3 _info.c/communcation layer RESPONSE_SLURM_RC message codes =over 2 =item * SLURM_NO_CHANGE_IN_DATA 1900 =back =head3 slurmctld error codes =over 2 =item * ESLURM_INVALID_PARTITION_NAME 2000 =item * ESLURM_DEFAULT_PARTITION_NOT_SET 2001 =item * ESLURM_ACCESS_DENIED 2002 =item * ESLURM_JOB_MISSING_REQUIRED_PARTITION_GROUP 2003 =item * ESLURM_REQUESTED_NODES_NOT_IN_PARTITION 2004 =item * ESLURM_TOO_MANY_REQUESTED_CPUS 2005 =item * ESLURM_INVALID_NODE_COUNT 2006 =item * ESLURM_ERROR_ON_DESC_TO_RECORD_COPY 2007 =item * ESLURM_JOB_MISSING_SIZE_SPECIFICATION 2008 =item * ESLURM_JOB_SCRIPT_MISSING 2009 =item * ESLURM_USER_ID_MISSING 2010 =item * ESLURM_DUPLICATE_JOB_ID 2011 =item * ESLURM_PATHNAME_TOO_LONG 2012 =item * ESLURM_NOT_TOP_PRIORITY 2013 =item * ESLURM_REQUESTED_NODE_CONFIG_UNAVAILABLE 2014 =item * ESLURM_REQUESTED_PART_CONFIG_UNAVAILABLE 2015 =item * ESLURM_NODES_BUSY 2016 =item * ESLURM_INVALID_JOB_ID 2017 =item * ESLURM_INVALID_NODE_NAME 2018 =item * ESLURM_WRITING_TO_FILE 2019 =item * ESLURM_TRANSITION_STATE_NO_UPDATE 2020 =item * ESLURM_ALREADY_DONE 2021 =item * ESLURM_INTERCONNECT_FAILURE 2022 =item * ESLURM_BAD_DIST 2023 =item * ESLURM_JOB_PENDING 2024 =item * ESLURM_BAD_TASK_COUNT 2025 =item * ESLURM_INVALID_JOB_CREDENTIAL 2026 =item * ESLURM_IN_STANDBY_MODE 2027 =item * ESLURM_INVALID_NODE_STATE 2028 =item * ESLURM_INVALID_FEATURE 2029 =item * ESLURM_INVALID_AUTHTYPE_CHANGE 2030 =item * ESLURM_INVALID_CHECKPOINT_TYPE_CHANGE 2031 =item * ESLURM_INVALID_SCHEDTYPE_CHANGE 2032 =item * ESLURM_INVALID_SELECTTYPE_CHANGE 2033 =item * ESLURM_INVALID_SWITCHTYPE_CHANGE 2034 =item * ESLURM_FRAGMENTATION 2035 =item * ESLURM_NOT_SUPPORTED 2036 =item * ESLURM_DISABLED 2037 =item * ESLURM_DEPENDENCY 2038 =item * ESLURM_BATCH_ONLY 2039 =item * ESLURM_TASKDIST_ARBITRARY_UNSUPPORTED 2040 =item * ESLURM_TASKDIST_REQUIRES_OVERCOMMIT 2041 =item * ESLURM_JOB_HELD 2042 =item * ESLURM_INVALID_CRYPTO_TYPE_CHANGE 2043 =item * ESLURM_INVALID_TASK_MEMORY 2044 =item * ESLURM_INVALID_ACCOUNT 2045 =item * ESLURM_INVALID_PARENT_ACCOUNT 2046 =item * ESLURM_SAME_PARENT_ACCOUNT 2047 =item * ESLURM_INVALID_LICENSES 2048 =item * ESLURM_NEED_RESTART 2049 =item * ESLURM_ACCOUNTING_POLICY 2050 =item * ESLURM_INVALID_TIME_LIMIT 2051 =item * ESLURM_RESERVATION_ACCESS 2052 =item * ESLURM_RESERVATION_INVALID 2053 =item * ESLURM_INVALID_TIME_VALUE 2054 =item * ESLURM_RESERVATION_BUSY 2055 =item * ESLURM_RESERVATION_NOT_USABLE 2056 =item * ESLURM_INVALID_WCKEY 2057 =item * ESLURM_RESERVATION_OVERLAP 2058 =item * ESLURM_PORTS_BUSY 2059 =item * ESLURM_PORTS_INVALID 2060 =item * ESLURM_PROLOG_RUNNING 2061 =item * ESLURM_NO_STEPS 2062 =item * ESLURM_INVALID_BLOCK_STATE 2063 =item * ESLURM_INVALID_BLOCK_LAYOUT 2064 =item * ESLURM_INVALID_BLOCK_NAME 2065 =item * ESLURM_INVALID_QOS 2066 =item * ESLURM_QOS_PREEMPTION_LOOP 2067 =item * ESLURM_NODE_NOT_AVAIL 2068 =item * ESLURM_INVALID_CPU_COUNT 2069 =item * ESLURM_PARTITION_NOT_AVAIL 2070 =item * ESLURM_CIRCULAR_DEPENDENCY 2071 =item * ESLURM_INVALID_GRES 2072 =item * ESLURM_JOB_NOT_PENDING 2073 =back =head3 switch specific error codes specific values defined in plugin module =over 2 =item * ESLURM_SWITCH_MIN 3000 =item * ESLURM_SWITCH_MAX 3099 =item * ESLURM_JOBCOMP_MIN 3100 =item * ESLURM_JOBCOMP_MAX 3199 =item * ESLURM_SCHED_MIN 3200 =item * ESLURM_SCHED_MAX 3299 =back =head3 slurmd error codes =over 2 =item * ESLRUMD_PIPE_ERROR_ON_TASK_SPAWN 4000 =item * ESLURMD_KILL_TASK_FAILED 4001 =item * ESLURMD_KILL_JOB_ALREADY_COMPLETE 4002 =item * ESLURMD_INVALID_ACCT_FREQ 4003 =item * ESLURMD_INVALID_JOB_CREDENTIAL 4004 =item * ESLURMD_UID_NOT_FOUND 4005 =item * ESLURMD_GID_NOT_FOUND 4006 =item * ESLURMD_CREDENTIAL_EXPIRED 4007 =item * ESLURMD_CREDENTIAL_REVOKED 4008 =item * ESLURMD_CREDENTIAL_REPLAYED 4009 =item * ESLURMD_CREATE_BATCH_DIR_ERROR 4010 =item * ESLURMD_MODIFY_BATCH_DIR_ERROR 4011 =item * ESLURMD_CREATE_BATCH_SCRIPT_ERROR 4012 =item * ESLURMD_MODIFY_BATCH_SCRIPT_ERROR 4013 =item * ESLURMD_SETUP_ENVIRONMENT_ERROR 4014 =item * ESLURMD_SHARED_MEMORY_ERROR 4015 =item * ESLURMD_SET_UID_OR_GID_ERROR 4016 =item * ESLURMD_SET_SID_ERROR 4017 =item * ESLURMD_CANNOT_SPAWN_IO_THREAD 4018 =item * ESLURMD_FORK_FAILED 4019 =item * ESLURMD_EXECVE_FAILED 4020 =item * ESLURMD_IO_ERROR 4021 =item * ESLURMD_PROLOG_FAILED 4022 =item * ESLURMD_EPILOG_FAILED 4023 =item * ESLURMD_SESSION_KILLED 4024 =item * ESLURMD_TOOMANYSTEPS 4025 =item * ESLURMD_STEP_EXISTS 4026 =item * ESLURMD_JOB_NOTRUNNING 4027 =item * ESLURMD_STEP_SUSPENDED 4028 =item * ESLURMD_STEP_NOTSUSPENDED 4029 =back =head3 slurmd errors in user batch job =over 2 =item * ESCRIPT_CHDIR_FAILED 4100 =item * ESCRIPT_OPEN_OUTPUT_FAILED 4101 =item * ESCRIPT_NON_ZERO_RETURN 4102 =back =head3 socket specific SLURM communications error =over 2 =item * SLURM_PROTOCOL_SOCKET_IMPL_ZERO_RECV_LENGTH 5000 =item * SLURM_PROTOCOL_SOCKET_IMPL_NEGATIVE_RECV_LENGTH 5001 =item * SLURM_PROTOCOL_SOCKET_IMPL_NOT_ALL_DATA_SENT 5002 =item * ESLURM_PROTOCOL_INCOMPLETE_PACKET 5003 =item * SLURM_PROTOCOL_SOCKET_IMPL_TIMEOUT 5004 =item * SLURM_PROTOCOL_SOCKET_ZERO_BYTES_SENT 5005 =back =head3 slurm_auth errors =over 2 =item * ESLURM_AUTH_CRED_INVALID 6000 =item * ESLURM_AUTH_FOPEN_ERROR 6001 =item * ESLURM_AUTH_NET_ERROR 6002 =item * ESLURM_AUTH_UNABLE_TO_SIGN 6003 =back =head3 accounting errors =over 2 =item * ESLURM_DB_CONNECTION 7000 =item * ESLURM_JOBS_RUNNING_ON_ASSOC 7001 =item * ESLURM_CLUSTER_DELETED 7002 =item * ESLURM_ONE_CHANGE 7003 =back =head2 =head1 SEE ALSO Slurm =head1 AUTHOR This library is created by Hongjia Cao, E<lt>hjcao(AT)nudt.edu.cnE<gt> and Danny Auble, E<lt>da(AT)llnl.govE<gt>. It is distributed with SLURM. =head1 COPYRIGHT AND LICENSE This library is free software; you can redistribute it and/or modify it under the same terms as Perl itself, either Perl version 5.8.4 or, at your option, any later version of Perl 5 you may have available. =cut
lipari/slurm
contribs/perlapi/libslurm/perl/lib/Slurm/Constant.pm
Perl
gpl-2.0
25,232
<?php /** * Zend Framework * * LICENSE * * This source file is subject to the new BSD license that is bundled * with this package in the file LICENSE.txt. * It is also available through the world-wide-web at this URL: * http://framework.zend.com/license/new-bsd * If you did not receive a copy of the license and are unable to * obtain it through the world-wide-web, please send an email * to [email protected] so we can send you a copy immediately. * * @category Zend * @package Zend_XmlRpc * @copyright Copyright (c) 2005-2014 Zend Technologies USA Inc. (http://www.zend.com) * @license http://framework.zend.com/license/new-bsd New BSD License * @version $Id$ */ /** * Zend_Exception */ /** * @category Zend * @package Zend_XmlRpc * @copyright Copyright (c) 2005-2014 Zend Technologies USA Inc. (http://www.zend.com) * @license http://framework.zend.com/license/new-bsd New BSD License */ class Zend_XmlRpc_Exception extends Zend_Exception {}
scibi/icingaweb2
library/vendor/Zend/XmlRpc/Exception.php
PHP
gpl-2.0
1,004
/* * Atmel SDMMC controller driver. * * Copyright (C) 2015 Atmel, * 2015 Ludovic Desroches <[email protected]> * * This software is licensed under the terms of the GNU General Public * License version 2, as published by the Free Software Foundation, and * may be copied, distributed, and modified under those terms. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. */ #include <linux/clk.h> #include <linux/delay.h> #include <linux/err.h> #include <linux/io.h> #include <linux/kernel.h> #include <linux/mmc/host.h> #include <linux/mmc/slot-gpio.h> #include <linux/module.h> #include <linux/of.h> #include <linux/of_device.h> #include <linux/pm.h> #include <linux/pm_runtime.h> #include "sdhci-pltfm.h" #define SDMMC_MC1R 0x204 #define SDMMC_MC1R_DDR BIT(3) #define SDMMC_CACR 0x230 #define SDMMC_CACR_CAPWREN BIT(0) #define SDMMC_CACR_KEY (0x46 << 8) #define SDHCI_AT91_PRESET_COMMON_CONF 0x400 /* drv type B, programmable clock mode */ struct sdhci_at91_priv { struct clk *hclock; struct clk *gck; struct clk *mainck; }; static void sdhci_at91_set_clock(struct sdhci_host *host, unsigned int clock) { u16 clk; unsigned long timeout; host->mmc->actual_clock = 0; /* * There is no requirement to disable the internal clock before * changing the SD clock configuration. Moreover, disabling the * internal clock, changing the configuration and re-enabling the * internal clock causes some bugs. It can prevent to get the internal * clock stable flag ready and an unexpected switch to the base clock * when using presets. */ clk = sdhci_readw(host, SDHCI_CLOCK_CONTROL); clk &= SDHCI_CLOCK_INT_EN; sdhci_writew(host, clk, SDHCI_CLOCK_CONTROL); if (clock == 0) return; clk = sdhci_calc_clk(host, clock, &host->mmc->actual_clock); clk |= SDHCI_CLOCK_INT_EN; sdhci_writew(host, clk, SDHCI_CLOCK_CONTROL); /* Wait max 20 ms */ timeout = 20; while (!((clk = sdhci_readw(host, SDHCI_CLOCK_CONTROL)) & SDHCI_CLOCK_INT_STABLE)) { if (timeout == 0) { pr_err("%s: Internal clock never stabilised.\n", mmc_hostname(host->mmc)); return; } timeout--; mdelay(1); } clk |= SDHCI_CLOCK_CARD_EN; sdhci_writew(host, clk, SDHCI_CLOCK_CONTROL); } /* * In this specific implementation of the SDHCI controller, the power register * needs to have a valid voltage set even when the power supply is managed by * an external regulator. */ static void sdhci_at91_set_power(struct sdhci_host *host, unsigned char mode, unsigned short vdd) { if (!IS_ERR(host->mmc->supply.vmmc)) { struct mmc_host *mmc = host->mmc; spin_unlock_irq(&host->lock); mmc_regulator_set_ocr(mmc, mmc->supply.vmmc, vdd); spin_lock_irq(&host->lock); } sdhci_set_power_noreg(host, mode, vdd); } void sdhci_at91_set_uhs_signaling(struct sdhci_host *host, unsigned int timing) { if (timing == MMC_TIMING_MMC_DDR52) sdhci_writeb(host, SDMMC_MC1R_DDR, SDMMC_MC1R); sdhci_set_uhs_signaling(host, timing); } static const struct sdhci_ops sdhci_at91_sama5d2_ops = { .set_clock = sdhci_at91_set_clock, .set_bus_width = sdhci_set_bus_width, .reset = sdhci_reset, .set_uhs_signaling = sdhci_at91_set_uhs_signaling, .set_power = sdhci_at91_set_power, }; static const struct sdhci_pltfm_data soc_data_sama5d2 = { .ops = &sdhci_at91_sama5d2_ops, }; static const struct of_device_id sdhci_at91_dt_match[] = { { .compatible = "atmel,sama5d2-sdhci", .data = &soc_data_sama5d2 }, {} }; #ifdef CONFIG_PM static int sdhci_at91_runtime_suspend(struct device *dev) { struct sdhci_host *host = dev_get_drvdata(dev); struct sdhci_pltfm_host *pltfm_host = sdhci_priv(host); struct sdhci_at91_priv *priv = sdhci_pltfm_priv(pltfm_host); int ret; ret = sdhci_runtime_suspend_host(host); clk_disable_unprepare(priv->gck); clk_disable_unprepare(priv->hclock); clk_disable_unprepare(priv->mainck); return ret; } static int sdhci_at91_runtime_resume(struct device *dev) { struct sdhci_host *host = dev_get_drvdata(dev); struct sdhci_pltfm_host *pltfm_host = sdhci_priv(host); struct sdhci_at91_priv *priv = sdhci_pltfm_priv(pltfm_host); int ret; ret = clk_prepare_enable(priv->mainck); if (ret) { dev_err(dev, "can't enable mainck\n"); return ret; } ret = clk_prepare_enable(priv->hclock); if (ret) { dev_err(dev, "can't enable hclock\n"); return ret; } ret = clk_prepare_enable(priv->gck); if (ret) { dev_err(dev, "can't enable gck\n"); return ret; } return sdhci_runtime_resume_host(host); } #endif /* CONFIG_PM */ static const struct dev_pm_ops sdhci_at91_dev_pm_ops = { SET_SYSTEM_SLEEP_PM_OPS(pm_runtime_force_suspend, pm_runtime_force_resume) SET_RUNTIME_PM_OPS(sdhci_at91_runtime_suspend, sdhci_at91_runtime_resume, NULL) }; static int sdhci_at91_probe(struct platform_device *pdev) { const struct of_device_id *match; const struct sdhci_pltfm_data *soc_data; struct sdhci_host *host; struct sdhci_pltfm_host *pltfm_host; struct sdhci_at91_priv *priv; unsigned int caps0, caps1; unsigned int clk_base, clk_mul; unsigned int gck_rate, real_gck_rate; int ret; unsigned int preset_div; match = of_match_device(sdhci_at91_dt_match, &pdev->dev); if (!match) return -EINVAL; soc_data = match->data; host = sdhci_pltfm_init(pdev, soc_data, sizeof(*priv)); if (IS_ERR(host)) return PTR_ERR(host); pltfm_host = sdhci_priv(host); priv = sdhci_pltfm_priv(pltfm_host); priv->mainck = devm_clk_get(&pdev->dev, "baseclk"); if (IS_ERR(priv->mainck)) { dev_err(&pdev->dev, "failed to get baseclk\n"); return PTR_ERR(priv->mainck); } priv->hclock = devm_clk_get(&pdev->dev, "hclock"); if (IS_ERR(priv->hclock)) { dev_err(&pdev->dev, "failed to get hclock\n"); return PTR_ERR(priv->hclock); } priv->gck = devm_clk_get(&pdev->dev, "multclk"); if (IS_ERR(priv->gck)) { dev_err(&pdev->dev, "failed to get multclk\n"); return PTR_ERR(priv->gck); } /* * The mult clock is provided by as a generated clock by the PMC * controller. In order to set the rate of gck, we have to get the * base clock rate and the clock mult from capabilities. */ clk_prepare_enable(priv->hclock); caps0 = readl(host->ioaddr + SDHCI_CAPABILITIES); caps1 = readl(host->ioaddr + SDHCI_CAPABILITIES_1); clk_base = (caps0 & SDHCI_CLOCK_V3_BASE_MASK) >> SDHCI_CLOCK_BASE_SHIFT; clk_mul = (caps1 & SDHCI_CLOCK_MUL_MASK) >> SDHCI_CLOCK_MUL_SHIFT; gck_rate = clk_base * 1000000 * (clk_mul + 1); ret = clk_set_rate(priv->gck, gck_rate); if (ret < 0) { dev_err(&pdev->dev, "failed to set gck"); goto hclock_disable_unprepare; } /* * We need to check if we have the requested rate for gck because in * some cases this rate could be not supported. If it happens, the rate * is the closest one gck can provide. We have to update the value * of clk mul. */ real_gck_rate = clk_get_rate(priv->gck); if (real_gck_rate != gck_rate) { clk_mul = real_gck_rate / (clk_base * 1000000) - 1; caps1 &= (~SDHCI_CLOCK_MUL_MASK); caps1 |= ((clk_mul << SDHCI_CLOCK_MUL_SHIFT) & SDHCI_CLOCK_MUL_MASK); /* Set capabilities in r/w mode. */ writel(SDMMC_CACR_KEY | SDMMC_CACR_CAPWREN, host->ioaddr + SDMMC_CACR); writel(caps1, host->ioaddr + SDHCI_CAPABILITIES_1); /* Set capabilities in ro mode. */ writel(0, host->ioaddr + SDMMC_CACR); dev_info(&pdev->dev, "update clk mul to %u as gck rate is %u Hz\n", clk_mul, real_gck_rate); } /* * We have to set preset values because it depends on the clk_mul * value. Moreover, SDR104 is supported in a degraded mode since the * maximum sd clock value is 120 MHz instead of 208 MHz. For that * reason, we need to use presets to support SDR104. */ preset_div = DIV_ROUND_UP(real_gck_rate, 24000000) - 1; writew(SDHCI_AT91_PRESET_COMMON_CONF | preset_div, host->ioaddr + SDHCI_PRESET_FOR_SDR12); preset_div = DIV_ROUND_UP(real_gck_rate, 50000000) - 1; writew(SDHCI_AT91_PRESET_COMMON_CONF | preset_div, host->ioaddr + SDHCI_PRESET_FOR_SDR25); preset_div = DIV_ROUND_UP(real_gck_rate, 100000000) - 1; writew(SDHCI_AT91_PRESET_COMMON_CONF | preset_div, host->ioaddr + SDHCI_PRESET_FOR_SDR50); preset_div = DIV_ROUND_UP(real_gck_rate, 120000000) - 1; writew(SDHCI_AT91_PRESET_COMMON_CONF | preset_div, host->ioaddr + SDHCI_PRESET_FOR_SDR104); preset_div = DIV_ROUND_UP(real_gck_rate, 50000000) - 1; writew(SDHCI_AT91_PRESET_COMMON_CONF | preset_div, host->ioaddr + SDHCI_PRESET_FOR_DDR50); clk_prepare_enable(priv->mainck); clk_prepare_enable(priv->gck); ret = mmc_of_parse(host->mmc); if (ret) goto clocks_disable_unprepare; sdhci_get_of_property(pdev); pm_runtime_get_noresume(&pdev->dev); pm_runtime_set_active(&pdev->dev); pm_runtime_enable(&pdev->dev); pm_runtime_set_autosuspend_delay(&pdev->dev, 50); pm_runtime_use_autosuspend(&pdev->dev); ret = sdhci_add_host(host); if (ret) goto pm_runtime_disable; /* * When calling sdhci_runtime_suspend_host(), the sdhci layer makes * the assumption that all the clocks of the controller are disabled. * It means we can't get irq from it when it is runtime suspended. * For that reason, it is not planned to wake-up on a card detect irq * from the controller. * If we want to use runtime PM and to be able to wake-up on card * insertion, we have to use a GPIO for the card detection or we can * use polling. Be aware that using polling will resume/suspend the * controller between each attempt. * Disable SDHCI_QUIRK_BROKEN_CARD_DETECTION to be sure nobody tries * to enable polling via device tree with broken-cd property. */ if (mmc_card_is_removable(host->mmc) && mmc_gpio_get_cd(host->mmc) < 0) { host->mmc->caps |= MMC_CAP_NEEDS_POLL; host->quirks &= ~SDHCI_QUIRK_BROKEN_CARD_DETECTION; } pm_runtime_put_autosuspend(&pdev->dev); return 0; pm_runtime_disable: pm_runtime_disable(&pdev->dev); pm_runtime_set_suspended(&pdev->dev); pm_runtime_put_noidle(&pdev->dev); clocks_disable_unprepare: clk_disable_unprepare(priv->gck); clk_disable_unprepare(priv->mainck); hclock_disable_unprepare: clk_disable_unprepare(priv->hclock); sdhci_pltfm_free(pdev); return ret; } static int sdhci_at91_remove(struct platform_device *pdev) { struct sdhci_host *host = platform_get_drvdata(pdev); struct sdhci_pltfm_host *pltfm_host = sdhci_priv(host); struct sdhci_at91_priv *priv = sdhci_pltfm_priv(pltfm_host); struct clk *gck = priv->gck; struct clk *hclock = priv->hclock; struct clk *mainck = priv->mainck; pm_runtime_get_sync(&pdev->dev); pm_runtime_disable(&pdev->dev); pm_runtime_put_noidle(&pdev->dev); sdhci_pltfm_unregister(pdev); clk_disable_unprepare(gck); clk_disable_unprepare(hclock); clk_disable_unprepare(mainck); return 0; } static struct platform_driver sdhci_at91_driver = { .driver = { .name = "sdhci-at91", .of_match_table = sdhci_at91_dt_match, .pm = &sdhci_at91_dev_pm_ops, }, .probe = sdhci_at91_probe, .remove = sdhci_at91_remove, }; module_platform_driver(sdhci_at91_driver); MODULE_DESCRIPTION("SDHCI driver for at91"); MODULE_AUTHOR("Ludovic Desroches <[email protected]>"); MODULE_LICENSE("GPL v2");
jumpnow/linux
drivers/mmc/host/sdhci-of-at91.c
C
gpl-2.0
11,348
/* M68KITAB.c Copyright (C) 2007 Paul C. Pratt You can redistribute this file and/or modify it under the terms of version 2 of the GNU General Public License as published by the Free Software Foundation. You should have received a copy of the license along with this file; see the file COPYING. This file 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 license for more details. */ /* Motorola 68K Instructions TABle */ #ifndef AllFiles #include "SYSDEPNS.h" #endif #include "MYOSGLUE.h" #include "EMCONFIG.h" #include "GLOBGLUE.h" #include "M68KITAB.h" struct WorkR { /* expected size : 8 bytes */ ui5b opcode; ui5b opsize; ui4r MainClass; #if WantCycByPriOp ui4r Cycles; #endif DecOpR DecOp; }; typedef struct WorkR WorkR; #define b76(p) ((p->opcode >> 6) & 3) #define b8(p) ((p->opcode >> 8) & 1) #define mode(p) ((p->opcode >> 3) & 7) #define reg(p) (p->opcode & 7) #define md6(p) ((p->opcode >> 6) & 7) #define rg9(p) ((p->opcode >> 9) & 7) enum { kAddrValidAny, kAddrValidData, kAddrValidDataAlt, kAddrValidControl, kAddrValidControlAlt, kAddrValidAltMem, kNumAddrValids }; #define kAddrValidMaskAny (1 << kAddrValidAny) #define kAddrValidMaskData (1 << kAddrValidData) #define kAddrValidMaskDataAlt (1 << kAddrValidDataAlt) #define kAddrValidMaskControl (1 << kAddrValidControl) #define kAddrValidMaskControlAlt (1 << kAddrValidControlAlt) #define kAddrValidMaskAltMem (1 << kAddrValidAltMem) #define CheckInSet(v, m) (0 != ((1 << (v)) & (m))) #define kMyAvgCycPerInstr (10 * kCycleScale + (40 * kCycleScale / 64)) LOCALFUNC MayNotInline ui3r GetArgkRegSz(WorkR *p) { ui3r CurArgk; switch (p->opsize) { case 1: CurArgk = kArgkRegB; break; case 2: default: /* keep compiler happy */ CurArgk = kArgkRegW; break; case 4: CurArgk = kArgkRegL; break; } return CurArgk; } LOCALFUNC MayNotInline ui3r GetArgkMemSz(WorkR *p) { ui3r CurArgk; switch (p->opsize) { case 1: CurArgk = kArgkMemB; break; case 2: default: /* keep compiler happy */ CurArgk = kArgkMemW; break; case 4: CurArgk = kArgkMemL; break; } return CurArgk; } #if WantCycByPriOp LOCALFUNC MayNotInline ui4r OpEACalcCyc(WorkR *p, ui3r m, ui3r r) { ui4r v; switch (m) { case 0: case 1: v = 0; break; case 2: v = ((4 == p->opsize) ? (8 * kCycleScale + 2 * RdAvgXtraCyc) : (4 * kCycleScale + RdAvgXtraCyc)); break; case 3: v = ((4 == p->opsize) ? (8 * kCycleScale + 2 * RdAvgXtraCyc) : (4 * kCycleScale + RdAvgXtraCyc)); break; case 4: v = ((4 == p->opsize) ? (10 * kCycleScale + 2 * RdAvgXtraCyc) : (6 * kCycleScale + RdAvgXtraCyc)); break; case 5: v = ((4 == p->opsize) ? (12 * kCycleScale + 3 * RdAvgXtraCyc) : (8 * kCycleScale + 2 * RdAvgXtraCyc)); break; case 6: v = ((4 == p->opsize) ? (14 * kCycleScale + 3 * RdAvgXtraCyc) : (10 * kCycleScale + 2 * RdAvgXtraCyc)); break; case 7: switch (r) { case 0: v = ((4 == p->opsize) ? (12 * kCycleScale + 3 * RdAvgXtraCyc) : (8 * kCycleScale + 2 * RdAvgXtraCyc)); break; case 1: v = ((4 == p->opsize) ? (16 * kCycleScale + 4 * RdAvgXtraCyc) : (12 * kCycleScale + 3 * RdAvgXtraCyc)); break; case 2: v = ((4 == p->opsize) ? (12 * kCycleScale + 3 * RdAvgXtraCyc) : (8 * kCycleScale + 2 * RdAvgXtraCyc)); break; case 3: v = ((4 == p->opsize) ? (14 * kCycleScale + 3 * RdAvgXtraCyc) : (10 * kCycleScale + 2 * RdAvgXtraCyc)); break; case 4: v = ((4 == p->opsize) ? (8 * kCycleScale + 2 * RdAvgXtraCyc) : (4 * kCycleScale + RdAvgXtraCyc)); break; default: v = 0; break; } break; default: /* keep compiler happy */ v = 0; break; } return v; } #endif #if WantCycByPriOp LOCALFUNC MayNotInline ui4r OpEADestCalcCyc(WorkR *p, ui3r m, ui3r r) { ui4r v; switch (m) { case 0: case 1: v = 0; break; case 2: v = ((4 == p->opsize) ? (8 * kCycleScale + 2 * WrAvgXtraCyc) : (4 * kCycleScale + WrAvgXtraCyc)); break; case 3: v = ((4 == p->opsize) ? (8 * kCycleScale + 2 * WrAvgXtraCyc) : (4 * kCycleScale + WrAvgXtraCyc)); break; case 4: v = ((4 == p->opsize) ? (8 * kCycleScale + 2 * WrAvgXtraCyc) : (4 * kCycleScale + WrAvgXtraCyc)); break; case 5: v = ((4 == p->opsize) ? (12 * kCycleScale + RdAvgXtraCyc + 2 * WrAvgXtraCyc) : (8 * kCycleScale + RdAvgXtraCyc + WrAvgXtraCyc)); break; case 6: v = ((4 == p->opsize) ? (14 * kCycleScale + RdAvgXtraCyc + 2 * WrAvgXtraCyc) : (10 * kCycleScale + RdAvgXtraCyc + WrAvgXtraCyc)); break; case 7: switch (r) { case 0: v = ((4 == p->opsize) ? (12 * kCycleScale + RdAvgXtraCyc + 2 * WrAvgXtraCyc) : (8 * kCycleScale + RdAvgXtraCyc + WrAvgXtraCyc)); break; case 1: v = ((4 == p->opsize) ? (16 * kCycleScale + 2 * RdAvgXtraCyc + 2 * WrAvgXtraCyc) : (12 * kCycleScale + 2 * RdAvgXtraCyc + WrAvgXtraCyc)); break; default: v = 0; break; } break; default: /* keep compiler happy */ v = 0; break; } return v; } #endif LOCALPROC SetDcoArgFields(WorkR *p, blnr src, ui3r CurAMd, ui3r CurArgk, ui3r CurArgDat) { ui5b *pv = src ? (&p->DecOp.B) : (&p->DecOp.A); ui5r v = *pv; SetDcoFldArgDat(v, CurArgDat); SetDcoFldAMd(v, CurAMd); SetDcoFldArgk(v, CurArgk); *pv = v; } LOCALFUNC MayNotInline blnr CheckValidAddrMode(WorkR *p, ui3r m, ui3r r, ui3r v, blnr src) { ui3r CurAMd = 0; /* init to keep compiler happy */ ui3r CurArgk = 0; /* init to keep compiler happy */ ui3r CurArgDat = 0; blnr IsOk; switch (m) { case 0: CurAMd = kAMdReg; CurArgk = GetArgkRegSz(p); CurArgDat = r; IsOk = CheckInSet(v, kAddrValidMaskAny | kAddrValidMaskData | kAddrValidMaskDataAlt); break; case 1: CurAMd = kAMdReg; CurArgk = GetArgkRegSz(p); CurArgDat = r + 8; IsOk = CheckInSet(v, kAddrValidMaskAny); break; case 2: CurAMd = kAMdIndirect; CurArgk = GetArgkMemSz(p); CurArgDat = r + 8; IsOk = CheckInSet(v, kAddrValidMaskAny | kAddrValidMaskData | kAddrValidMaskDataAlt | kAddrValidMaskControl | kAddrValidMaskControlAlt | kAddrValidMaskAltMem); break; case 3: switch (p->opsize) { case 1: if (7 == r) { CurAMd = kAMdAPosIncW; } else { CurAMd = kAMdAPosIncB; } break; case 2: default: /* keep compiler happy */ CurAMd = kAMdAPosIncW; break; case 4: CurAMd = kAMdAPosIncL; break; } CurArgk = GetArgkMemSz(p); CurArgDat = r + 8; IsOk = CheckInSet(v, kAddrValidMaskAny | kAddrValidMaskData | kAddrValidMaskDataAlt | kAddrValidMaskAltMem); break; case 4: switch (p->opsize) { case 1: if (7 == r) { CurAMd = kAMdAPreDecW; } else { CurAMd = kAMdAPreDecB; } break; case 2: default: /* keep compiler happy */ CurAMd = kAMdAPreDecW; break; case 4: CurAMd = kAMdAPreDecL; break; } CurArgk = GetArgkMemSz(p); CurArgDat = r + 8; IsOk = CheckInSet(v, kAddrValidMaskAny | kAddrValidMaskData | kAddrValidMaskDataAlt | kAddrValidMaskAltMem); break; case 5: CurAMd = kAMdADisp; CurArgk = GetArgkMemSz(p); CurArgDat = r + 8; IsOk = CheckInSet(v, kAddrValidMaskAny | kAddrValidMaskData | kAddrValidMaskDataAlt | kAddrValidMaskControl | kAddrValidMaskControlAlt | kAddrValidMaskAltMem); break; case 6: CurAMd = kAMdAIndex; CurArgk = GetArgkMemSz(p); CurArgDat = r + 8; IsOk = CheckInSet(v, kAddrValidMaskAny | kAddrValidMaskData | kAddrValidMaskDataAlt | kAddrValidMaskControl | kAddrValidMaskControlAlt | kAddrValidMaskAltMem); break; case 7: switch (r) { case 0: CurAMd = kAMdAbsW; CurArgk = GetArgkMemSz(p); IsOk = CheckInSet(v, kAddrValidMaskAny | kAddrValidMaskData | kAddrValidMaskDataAlt | kAddrValidMaskControl | kAddrValidMaskControlAlt | kAddrValidMaskAltMem); break; case 1: CurAMd = kAMdAbsL; CurArgk = GetArgkMemSz(p); IsOk = CheckInSet(v, kAddrValidMaskAny | kAddrValidMaskData | kAddrValidMaskDataAlt | kAddrValidMaskControl | kAddrValidMaskControlAlt | kAddrValidMaskAltMem); break; case 2: CurAMd = kAMdPCDisp; CurArgk = GetArgkMemSz(p); IsOk = CheckInSet(v, kAddrValidMaskAny | kAddrValidMaskData | kAddrValidMaskControl); break; case 3: CurAMd = kAMdPCIndex; CurArgk = GetArgkMemSz(p); IsOk = CheckInSet(v, kAddrValidMaskAny | kAddrValidMaskData | kAddrValidMaskControl); break; case 4: switch (p->opsize) { case 1: CurAMd = kAMdImmedB; break; case 2: default: /* keep compiler happy */ CurAMd = kAMdImmedW; break; case 4: CurAMd = kAMdImmedL; break; } CurArgk = kArgkCnst; IsOk = CheckInSet(v, kAddrValidMaskAny | kAddrValidMaskData); break; default: IsOk = falseblnr; break; } break; default: /* keep compiler happy */ IsOk = falseblnr; break; } if (IsOk) { SetDcoArgFields(p, src, CurAMd, CurArgk, CurArgDat); } return IsOk; } #if WantCycByPriOp LOCALFUNC MayNotInline blnr LeaPeaEACalcCyc(WorkR *p, ui3r m, ui3r r) { ui4r v; UnusedParam(p); switch (m) { case 2: v = 0; break; case 5: v = (4 * kCycleScale + RdAvgXtraCyc); break; case 6: v = (8 * kCycleScale + RdAvgXtraCyc); break; case 7: switch (r) { case 0: v = (4 * kCycleScale + RdAvgXtraCyc); break; case 1: v = (8 * kCycleScale + 2 * RdAvgXtraCyc); break; case 2: v = (4 * kCycleScale + RdAvgXtraCyc); break; case 3: v = (8 * kCycleScale + RdAvgXtraCyc); break; default: v = 0; break; } break; default: /* keep compiler happy */ v = 0; break; } return v; } #endif LOCALFUNC blnr IsValidAddrMode(WorkR *p) { return CheckValidAddrMode(p, mode(p), reg(p), kAddrValidAny, falseblnr); } LOCALFUNC MayNotInline blnr CheckDataAltAddrMode(WorkR *p) { return CheckValidAddrMode(p, mode(p), reg(p), kAddrValidDataAlt, falseblnr); } LOCALFUNC MayNotInline blnr CheckDataAddrMode(WorkR *p) { return CheckValidAddrMode(p, mode(p), reg(p), kAddrValidData, falseblnr); } LOCALFUNC MayNotInline blnr CheckControlAddrMode(WorkR *p) { return CheckValidAddrMode(p, mode(p), reg(p), kAddrValidControl, falseblnr); } LOCALFUNC MayNotInline blnr CheckControlAltAddrMode(WorkR *p) { return CheckValidAddrMode(p, mode(p), reg(p), kAddrValidControlAlt, falseblnr); } LOCALFUNC MayNotInline blnr CheckAltMemAddrMode(WorkR *p) { return CheckValidAddrMode(p, mode(p), reg(p), kAddrValidAltMem, falseblnr); } LOCALPROC FindOpSizeFromb76(WorkR *p) { p->opsize = 1 << b76(p); #if 0 switch (b76(p)) { case 0 : p->opsize = 1; break; case 1 : p->opsize = 2; break; case 2 : p->opsize = 4; break; } #endif } LOCALFUNC ui3r OpSizeOffset(WorkR *p) { ui3r v; switch (p->opsize) { case 1 : v = 0; break; case 2 : v = 1; break; case 4 : default : v = 2; break; } return v; } LOCALFUNC ui5r octdat(ui5r x) { if (x == 0) { return 8; } else { return x; } } LOCALPROC MayInline DeCode0(WorkR *p) { if (b8(p) == 1) { if (mode(p) == 1) { /* MoveP 0000ddd1mm001aaa */ #if WantCycByPriOp switch (b76(p)) { case 0: p->Cycles = (16 * kCycleScale + 4 * RdAvgXtraCyc); break; case 1: p->Cycles = (24 * kCycleScale + 6 * RdAvgXtraCyc); break; case 2: p->Cycles = (16 * kCycleScale + 2 * RdAvgXtraCyc + 2 * WrAvgXtraCyc); break; case 3: default: /* keep compiler happy */ p->Cycles = (24 * kCycleScale + 2 * RdAvgXtraCyc + 4 * WrAvgXtraCyc); break; } #endif p->MainClass = kIKindMoveP; } else { /* dynamic bit, Opcode = 0000ddd1ttmmmrrr */ if (mode(p) == 0) { #if WantCycByPriOp switch (b76(p)) { case 0: /* BTst */ p->Cycles = (6 * kCycleScale + RdAvgXtraCyc); break; case 1: /* BChg */ p->Cycles = (8 * kCycleScale + RdAvgXtraCyc); break; case 2: /* BClr */ p->Cycles = (10 * kCycleScale + RdAvgXtraCyc); break; case 3: /* BSet */ p->Cycles = (8 * kCycleScale + RdAvgXtraCyc); break; } #endif p->MainClass = kIKindBitOpDD; } else { if (b76(p) == 0) { /* BTst */ if (CheckDataAddrMode(p)) { #if WantCycByPriOp p->Cycles = (4 * kCycleScale + RdAvgXtraCyc); p->Cycles += OpEACalcCyc(p, mode(p), reg(p)); #endif p->MainClass = kIKindBitOpDM; } } else { if (CheckDataAltAddrMode(p)) { #if WantCycByPriOp p->Cycles = (8 * kCycleScale + RdAvgXtraCyc + WrAvgXtraCyc); p->Cycles += OpEACalcCyc(p, mode(p), reg(p)); #endif p->MainClass = kIKindBitOpDM; } } } } } else { if (rg9(p) == 4) { /* static bit 00001010ssmmmrrr */ if (mode(p) == 0) { #if WantCycByPriOp switch (b76(p)) { case 0: /* BTst */ p->Cycles = (10 * kCycleScale + 2 * RdAvgXtraCyc); break; case 1: /* BChg */ p->Cycles = (12 * kCycleScale + 2 * RdAvgXtraCyc); break; case 2: /* BClr */ p->Cycles = (14 * kCycleScale + 2 * RdAvgXtraCyc); break; case 3: /* BSet */ p->Cycles = (12 * kCycleScale + 2 * RdAvgXtraCyc); break; } #endif p->MainClass = kIKindBitOpND; } else { if (b76(p) == 0) { /* BTst */ if ((mode(p) == 7) && (reg(p) == 4)) { p->MainClass = kIKindIllegal; } else { if (CheckDataAddrMode(p)) { #if WantCycByPriOp p->Cycles = (8 * kCycleScale + 2 * RdAvgXtraCyc); p->Cycles += OpEACalcCyc(p, mode(p), reg(p)); #endif p->MainClass = kIKindBitOpNM; } } } else { if (CheckDataAltAddrMode(p)) { #if WantCycByPriOp p->Cycles = (12 * kCycleScale + 2 * RdAvgXtraCyc + WrAvgXtraCyc); p->Cycles += OpEACalcCyc(p, mode(p), reg(p)); #endif p->MainClass = kIKindBitOpNM; } } } } else if (b76(p) == 3) { #if Use68020 if (rg9(p) < 3) { /* CHK2 or CMP2 00000ss011mmmrrr */ if (CheckControlAddrMode(p)) { #if WantCycByPriOp p->Cycles += OpEACalcCyc(p, mode(p), reg(p)); #endif p->MainClass = kIKindCHK2orCMP2; } } else if (rg9(p) >= 5) { if ((mode(p) == 7) && (reg(p) == 4)) { /* CAS2 00001ss011111100 */ p->MainClass = kIKindCAS2; } else { /* CAS 00001ss011mmmrrr */ p->MainClass = kIKindCAS; } } else if (rg9(p) == 3) { /* CALLM or RTM 0000011011mmmrrr */ p->MainClass = kIKindCallMorRtm; } else #endif { p->MainClass = kIKindIllegal; } } else if (rg9(p) == 6) { /* CMPI 00001100ssmmmrrr */ #if 0 if (CheckDataAltAddrMode(p)) { p->MainClass = kIKindCmpI; } #endif FindOpSizeFromb76(p); if (CheckValidAddrMode(p, 7, 4, kAddrValidAny, trueblnr)) if (CheckValidAddrMode(p, mode(p), reg(p), kAddrValidDataAlt, falseblnr)) { #if WantCycByPriOp if (0 == mode(p)) { p->Cycles = (4 == p->opsize) ? (14 * kCycleScale + 3 * RdAvgXtraCyc) : (8 * kCycleScale + 2 * RdAvgXtraCyc); } else { p->Cycles = (4 == p->opsize) ? (12 * kCycleScale + 3 * RdAvgXtraCyc) : (8 * kCycleScale + 2 * RdAvgXtraCyc); } p->Cycles += OpEACalcCyc(p, mode(p), reg(p)); #endif p->MainClass = kIKindCmpB + OpSizeOffset(p); } } else if (rg9(p) == 7) { #if Use68020 /* MoveS 00001110ssmmmrrr */ if (CheckAltMemAddrMode(p)) { #if WantCycByPriOp p->Cycles += OpEACalcCyc(p, mode(p), reg(p)); #endif p->MainClass = kIKindMoveS; } #else p->MainClass = kIKindIllegal; #endif } else { if ((mode(p) == 7) && (reg(p) == 4)) { switch (rg9(p)) { case 0: case 1: case 5: #if WantCycByPriOp p->Cycles = (20 * kCycleScale + 3 * RdAvgXtraCyc); #endif p->MainClass = kIKindBinOpStatusCCR; break; default: p->MainClass = kIKindIllegal; break; } } else { switch (rg9(p)) { case 0: #if 0 if (CheckDataAltAddrMode(p)) { p->MainClass = kIKindOrI; } #endif FindOpSizeFromb76(p); if (CheckValidAddrMode(p, 7, 4, kAddrValidAny, trueblnr)) if (CheckValidAddrMode(p, mode(p), reg(p), kAddrValidDataAlt, falseblnr)) { #if WantCycByPriOp if (0 != mode(p)) { p->Cycles = (4 == p->opsize) ? (20 * kCycleScale + 3 * RdAvgXtraCyc + 2 * WrAvgXtraCyc) : (12 * kCycleScale + 2 * RdAvgXtraCyc + WrAvgXtraCyc); } else { p->Cycles = (4 == p->opsize) ? (16 * kCycleScale + 3 * RdAvgXtraCyc) : (8 * kCycleScale + 2 * RdAvgXtraCyc); } p->Cycles += OpEACalcCyc(p, mode(p), reg(p)); #endif p->MainClass = kIKindOrI; } break; case 1: #if 0 if (CheckDataAltAddrMode(p)) { p->MainClass = kIKindAndI; } #endif FindOpSizeFromb76(p); if (CheckValidAddrMode(p, 7, 4, kAddrValidAny, trueblnr)) if (CheckValidAddrMode(p, mode(p), reg(p), kAddrValidDataAlt, falseblnr)) { #if WantCycByPriOp if (0 != mode(p)) { p->Cycles = (4 == p->opsize) ? (20 * kCycleScale + 3 * RdAvgXtraCyc + 2 * WrAvgXtraCyc) : (12 * kCycleScale + 2 * RdAvgXtraCyc + WrAvgXtraCyc); } else { p->Cycles = (4 == p->opsize) ? (14 * kCycleScale + 3 * RdAvgXtraCyc) : (8 * kCycleScale + 2 * RdAvgXtraCyc); } p->Cycles += OpEACalcCyc(p, mode(p), reg(p)); #endif p->MainClass = kIKindAndI; } break; case 2: #if 0 if (CheckDataAltAddrMode(p)) { p->MainClass = kIKindSubI; } #endif FindOpSizeFromb76(p); if (CheckValidAddrMode(p, 7, 4, kAddrValidAny, trueblnr)) if (CheckValidAddrMode(p, mode(p), reg(p), kAddrValidDataAlt, falseblnr)) { #if WantCycByPriOp if (0 != mode(p)) { p->Cycles = (4 == p->opsize) ? (20 * kCycleScale + 3 * RdAvgXtraCyc + 2 * WrAvgXtraCyc) : (12 * kCycleScale + 2 * RdAvgXtraCyc + WrAvgXtraCyc); } else { p->Cycles = (4 == p->opsize) ? (16 * kCycleScale + 3 * RdAvgXtraCyc) : (8 * kCycleScale + 2 * RdAvgXtraCyc); } p->Cycles += OpEACalcCyc(p, mode(p), reg(p)); #endif p->MainClass = kIKindSubB + OpSizeOffset(p); } break; case 3: #if 0 if (CheckDataAltAddrMode(p)) { p->MainClass = kIKindAddI; } #endif FindOpSizeFromb76(p); if (CheckValidAddrMode(p, 7, 4, kAddrValidAny, trueblnr)) if (CheckValidAddrMode(p, mode(p), reg(p), kAddrValidDataAlt, falseblnr)) { #if WantCycByPriOp if (0 != mode(p)) { p->Cycles = (4 == p->opsize) ? (20 * kCycleScale + 3 * RdAvgXtraCyc + 2 * WrAvgXtraCyc) : (12 * kCycleScale + 2 * RdAvgXtraCyc + WrAvgXtraCyc); } else { p->Cycles = (4 == p->opsize) ? (16 * kCycleScale + 3 * RdAvgXtraCyc) : (8 * kCycleScale + 2 * RdAvgXtraCyc); } p->Cycles += OpEACalcCyc(p, mode(p), reg(p)); #endif p->MainClass = kIKindAddB + OpSizeOffset(p); } break; case 5: #if 0 if (CheckDataAltAddrMode(p)) { p->MainClass = kIKindEorI; } #endif FindOpSizeFromb76(p); if (CheckValidAddrMode(p, 7, 4, kAddrValidAny, trueblnr)) if (CheckValidAddrMode(p, mode(p), reg(p), kAddrValidDataAlt, falseblnr)) { #if WantCycByPriOp if (0 != mode(p)) { p->Cycles = (4 == p->opsize) ? (20 * kCycleScale + 3 * RdAvgXtraCyc + 2 * WrAvgXtraCyc) : (12 * kCycleScale + 2 * RdAvgXtraCyc + WrAvgXtraCyc); } else { p->Cycles = (4 == p->opsize) ? (16 * kCycleScale + 3 * RdAvgXtraCyc) : (8 * kCycleScale + 2 * RdAvgXtraCyc); } p->Cycles += OpEACalcCyc(p, mode(p), reg(p)); #endif p->MainClass = kIKindEorI; } break; default: /* for compiler. should be 0, 1, 2, 3, or 5 */ p->MainClass = kIKindIllegal; break; } } } } } LOCALPROC MayInline DeCode1(WorkR *p) { p->opsize = 1; if (md6(p) == 1) { /* MOVEA */ p->MainClass = kIKindIllegal; } else if (mode(p) == 1) { /* not allowed for byte sized move */ p->MainClass = kIKindIllegal; } else { if (CheckValidAddrMode(p, mode(p), reg(p), kAddrValidAny, trueblnr)) if (CheckValidAddrMode(p, md6(p), rg9(p), kAddrValidDataAlt, falseblnr)) { #if WantCycByPriOp p->Cycles = (4 * kCycleScale + RdAvgXtraCyc); p->Cycles += OpEACalcCyc(p, mode(p), reg(p)); p->Cycles += OpEADestCalcCyc(p, md6(p), rg9(p)); #endif p->MainClass = kIKindMoveB; } } } LOCALPROC MayInline DeCode2(WorkR *p) { p->opsize = 4; if (md6(p) == 1) { /* MOVEA */ if (CheckValidAddrMode(p, mode(p), reg(p), kAddrValidAny, trueblnr)) if (CheckValidAddrMode(p, 1, rg9(p), kAddrValidAny, falseblnr)) { #if WantCycByPriOp p->Cycles = (4 * kCycleScale + RdAvgXtraCyc); p->Cycles += OpEACalcCyc(p, mode(p), reg(p)); #endif p->MainClass = kIKindMoveAL; } } else { if (CheckValidAddrMode(p, mode(p), reg(p), kAddrValidAny, trueblnr)) if (CheckValidAddrMode(p, md6(p), rg9(p), kAddrValidDataAlt, falseblnr)) { #if WantCycByPriOp p->Cycles = (4 * kCycleScale + RdAvgXtraCyc); p->Cycles += OpEACalcCyc(p, mode(p), reg(p)); p->Cycles += OpEADestCalcCyc(p, md6(p), rg9(p)); #endif p->MainClass = kIKindMoveL; } } } LOCALPROC MayInline DeCode3(WorkR *p) { p->opsize = 2; if (md6(p) == 1) { /* MOVEA */ if (CheckValidAddrMode(p, mode(p), reg(p), kAddrValidAny, trueblnr)) if (CheckValidAddrMode(p, 1, rg9(p), kAddrValidAny, falseblnr)) { #if WantCycByPriOp p->Cycles = (4 * kCycleScale + RdAvgXtraCyc); p->Cycles += OpEACalcCyc(p, mode(p), reg(p)); #endif p->MainClass = kIKindMoveAW; } } else { if (CheckValidAddrMode(p, mode(p), reg(p), kAddrValidAny, trueblnr)) if (CheckValidAddrMode(p, md6(p), rg9(p), kAddrValidDataAlt, falseblnr)) { #if WantCycByPriOp p->Cycles = (4 * kCycleScale + RdAvgXtraCyc); p->Cycles += OpEACalcCyc(p, mode(p), reg(p)); p->Cycles += OpEADestCalcCyc(p, md6(p), rg9(p)); #endif p->MainClass = kIKindMoveW; } } } #if WantCycByPriOp #if WantCloserCyc #define MoveAvgN 0 #else #define MoveAvgN 3 #endif LOCALFUNC MayNotInline ui4r MoveMEACalcCyc(WorkR *p, ui3r m, ui3r r) { ui4r v; UnusedParam(p); switch (m) { case 2: case 3: case 4: v = (8 * kCycleScale + 2 * RdAvgXtraCyc); break; case 5: v = (12 * kCycleScale + 3 * RdAvgXtraCyc); break; case 6: v = (14 * kCycleScale + 3 * RdAvgXtraCyc); break; case 7: switch (r) { case 0: v = (12 * kCycleScale + 3 * RdAvgXtraCyc); break; case 1: v = (16 * kCycleScale + 4 * RdAvgXtraCyc); break; default: v = 0; break; } break; default: /* keep compiler happy */ v = 0; break; } return v; } #endif LOCALPROC MayInline DeCode4(WorkR *p) { if (b8(p) != 0) { switch (b76(p)) { case 0: #if Use68020 /* Chk.L 0100ddd100mmmrrr */ if (CheckDataAddrMode(p)) { #if WantCycByPriOp p->Cycles += OpEACalcCyc(p, mode(p), reg(p)); #endif p->MainClass = kIKindChkL; } #else p->MainClass = kIKindIllegal; #endif break; case 1: p->MainClass = kIKindIllegal; break; case 2: /* Chk.W 0100ddd110mmmrrr */ if (CheckDataAddrMode(p)) { #if WantCycByPriOp p->Cycles = (10 * kCycleScale + RdAvgXtraCyc); p->Cycles += OpEACalcCyc(p, mode(p), reg(p)); #endif p->MainClass = kIKindChkW; } break; case 3: default: /* keep compiler happy */ #if Use68020 if ((0 == mode(p)) && (4 == rg9(p))) { p->MainClass = kIKindEXTBL; } else #endif { /* Lea 0100aaa111mmmrrr */ if (CheckControlAddrMode(p)) { #if WantCycByPriOp p->Cycles = (4 * kCycleScale + RdAvgXtraCyc); p->Cycles += LeaPeaEACalcCyc(p, mode(p), reg(p)); #endif p->MainClass = kIKindLea; } } break; } } else { switch (rg9(p)) { case 0: if (b76(p) != 3) { /* NegX 01000000ssmmmrrr */ FindOpSizeFromb76(p); if (CheckDataAltAddrMode(p)) { #if WantCycByPriOp if (0 != mode(p)) { p->Cycles = (4 == p->opsize) ? (12 * kCycleScale + RdAvgXtraCyc + 2 * WrAvgXtraCyc) : (8 * kCycleScale + RdAvgXtraCyc + WrAvgXtraCyc); } else { p->Cycles = (4 == p->opsize) ? (6 * kCycleScale + RdAvgXtraCyc) : (4 * kCycleScale + RdAvgXtraCyc); } p->Cycles += OpEACalcCyc(p, mode(p), reg(p)); #endif p->MainClass = kIKindNegXB + OpSizeOffset(p); } } else { #if Use68020 /* reference seems incorrect to say not for 68000 */ #endif /* Move from SR 0100000011mmmrrr */ if (CheckDataAltAddrMode(p)) { #if WantCycByPriOp p->Cycles = (12 * kCycleScale + 2 * RdAvgXtraCyc); p->Cycles += OpEACalcCyc(p, mode(p), reg(p)); #endif p->MainClass = kIKindMoveSREa; } } break; case 1: if (b76(p) != 3) { /* Clr 01000010ssmmmrrr */ FindOpSizeFromb76(p); if (CheckDataAltAddrMode(p)) { #if WantCycByPriOp if (0 != mode(p)) { p->Cycles = (4 == p->opsize) ? (12 * kCycleScale + RdAvgXtraCyc + 2 * WrAvgXtraCyc) : (8 * kCycleScale + RdAvgXtraCyc + WrAvgXtraCyc); } else { p->Cycles = (4 == p->opsize) ? (6 * kCycleScale + RdAvgXtraCyc) : (4 * kCycleScale + RdAvgXtraCyc); } p->Cycles += OpEACalcCyc(p, mode(p), reg(p)); #endif p->MainClass = kIKindClr; } } else { #if Use68020 /* Move from CCR 0100001011mmmrrr */ if (CheckDataAltAddrMode(p)) { #if WantCycByPriOp p->Cycles += OpEACalcCyc(p, mode(p), reg(p)); #endif p->MainClass = kIKindMoveCCREa; } #else p->MainClass = kIKindIllegal; #endif } break; case 2: if (b76(p) != 3) { /* Neg 01000100ssmmmrrr */ FindOpSizeFromb76(p); if (CheckDataAltAddrMode(p)) { #if WantCycByPriOp if (0 != mode(p)) { p->Cycles = (4 == p->opsize) ? (12 * kCycleScale + RdAvgXtraCyc + 2 * WrAvgXtraCyc) : (8 * kCycleScale + RdAvgXtraCyc + WrAvgXtraCyc); } else { p->Cycles = (4 == p->opsize) ? (6 * kCycleScale + RdAvgXtraCyc) : (4 * kCycleScale + RdAvgXtraCyc); } p->Cycles += OpEACalcCyc(p, mode(p), reg(p)); #endif p->MainClass = kIKindNegB + OpSizeOffset(p); } } else { /* Move to CCR 0100010011mmmrrr */ if (CheckDataAddrMode(p)) { #if WantCycByPriOp p->Cycles = (12 * kCycleScale + RdAvgXtraCyc); p->Cycles += OpEACalcCyc(p, mode(p), reg(p)); #endif p->MainClass = kIKindMoveEaCCR; } } break; case 3: if (b76(p) != 3) { /* Not 01000110ssmmmrrr */ FindOpSizeFromb76(p); if (CheckDataAltAddrMode(p)) { #if WantCycByPriOp if (0 != mode(p)) { p->Cycles = (4 == p->opsize) ? (12 * kCycleScale + RdAvgXtraCyc + 2 * WrAvgXtraCyc) : (8 * kCycleScale + RdAvgXtraCyc + WrAvgXtraCyc); } else { p->Cycles = (4 == p->opsize) ? (6 * kCycleScale + RdAvgXtraCyc) : (4 * kCycleScale + RdAvgXtraCyc); } p->Cycles += OpEACalcCyc(p, mode(p), reg(p)); #endif p->MainClass = kIKindNot; } } else { /* Move from SR 0100011011mmmrrr */ if (CheckDataAddrMode(p)) { #if WantCycByPriOp if (0 != mode(p)) { p->Cycles = (8 * kCycleScale + RdAvgXtraCyc + WrAvgXtraCyc); } else { p->Cycles = (6 * kCycleScale + RdAvgXtraCyc); } p->Cycles += OpEACalcCyc(p, mode(p), reg(p)); #endif p->MainClass = kIKindMoveEaSR; } } break; case 4: switch (b76(p)) { case 0: #if Use68020 if (mode(p) == 1) { /* Link.L 0100100000001rrr */ p->MainClass = kIKindLinkL; } else #endif { /* Nbcd 0100100000mmmrrr */ if (CheckDataAltAddrMode(p)) { #if WantCycByPriOp if (0 != mode(p)) { p->Cycles = (8 * kCycleScale + RdAvgXtraCyc + WrAvgXtraCyc); } else { p->Cycles = (6 * kCycleScale + RdAvgXtraCyc); } p->Cycles += OpEACalcCyc(p, mode(p), reg(p)); #endif p->MainClass = kIKindNbcd; } } break; case 1: if (mode(p) == 0) { /* Swap 0100100001000rrr */ #if WantCycByPriOp p->Cycles = (4 * kCycleScale + RdAvgXtraCyc); #endif p->MainClass = kIKindSwap; } else #if Use68020 if (mode(p) == 1) { p->MainClass = kIKindBkpt; } else #endif { /* PEA 0100100001mmmrrr */ if (CheckControlAddrMode(p)) { #if WantCycByPriOp p->Cycles = (12 * kCycleScale + RdAvgXtraCyc + 2 * WrAvgXtraCyc); p->Cycles += LeaPeaEACalcCyc(p, mode(p), reg(p)); #endif p->MainClass = kIKindPEA; } } break; case 2: if (mode(p) == 0) { /* EXT.W */ #if WantCycByPriOp p->Cycles = (4 * kCycleScale + RdAvgXtraCyc); #endif p->MainClass = kIKindEXTW; } else { /* MOVEM reg to mem 01001d001ssmmmrrr */ if (mode(p) == 4) { #if WantCycByPriOp p->Cycles = MoveMEACalcCyc(p, mode(p), reg(p)); p->Cycles += MoveAvgN * 4 * kCycleScale + MoveAvgN * WrAvgXtraCyc; #endif p->MainClass = kIKindMOVEMRmMW; } else { if (CheckControlAltAddrMode(p)) { #if WantCycByPriOp p->Cycles = MoveMEACalcCyc(p, mode(p), reg(p)); p->Cycles += MoveAvgN * 4 * kCycleScale + MoveAvgN * WrAvgXtraCyc; #endif p->MainClass = kIKindMOVEMrm; } } } break; case 3: default: /* keep compiler happy */ if (mode(p) == 0) { /* EXT.L */ #if WantCycByPriOp p->Cycles = (4 * kCycleScale + RdAvgXtraCyc); #endif p->MainClass = kIKindEXTL; } else { /* MOVEM reg to mem 01001d001ssmmmrrr */ if (mode(p) == 4) { #if WantCycByPriOp p->Cycles = MoveMEACalcCyc(p, mode(p), reg(p)); p->Cycles += MoveAvgN * 8 * kCycleScale + MoveAvgN * 2 * WrAvgXtraCyc; #endif p->MainClass = kIKindMOVEMRmML; } else { if (CheckControlAltAddrMode(p)) { #if WantCycByPriOp p->Cycles = MoveMEACalcCyc(p, mode(p), reg(p)); p->Cycles += MoveAvgN * 8 * kCycleScale + MoveAvgN * 2 * WrAvgXtraCyc; #endif p->MainClass = kIKindMOVEMrm; } } } break; } break; case 5: if (b76(p) == 3) { if ((mode(p) == 7) && (reg(p) == 4)) { /* the ILLEGAL instruction */ p->MainClass = kIKindIllegal; } else { /* Tas 0100101011mmmrrr */ if (CheckDataAltAddrMode(p)) { #if WantCycByPriOp if (0 != mode(p)) { p->Cycles = (14 * kCycleScale + 2 * RdAvgXtraCyc + WrAvgXtraCyc); } else { p->Cycles = (4 * kCycleScale + RdAvgXtraCyc); } p->Cycles += OpEACalcCyc(p, mode(p), reg(p)); #endif p->MainClass = kIKindTas; } } } else { /* Tst 01001010ssmmmrrr */ FindOpSizeFromb76(p); if (b76(p) == 0) { if (CheckDataAltAddrMode(p)) { #if WantCycByPriOp p->Cycles = (4 * kCycleScale + RdAvgXtraCyc); p->Cycles += OpEACalcCyc(p, mode(p), reg(p)); #endif p->MainClass = kIKindTst; } } else { if (IsValidAddrMode(p)) { #if WantCycByPriOp p->Cycles = (4 * kCycleScale + RdAvgXtraCyc); p->Cycles += OpEACalcCyc(p, mode(p), reg(p)); #endif p->MainClass = kIKindTst; } } } break; case 6: if (((p->opcode >> 7) & 1) == 1) { /* MOVEM mem to reg 0100110011smmmrrr */ FindOpSizeFromb76(p); if (mode(p) == 3) { #if WantCycByPriOp p->Cycles = 4 * kCycleScale + RdAvgXtraCyc; p->Cycles += MoveMEACalcCyc(p, mode(p), reg(p)); if (4 == p->opsize) { p->Cycles += MoveAvgN * 8 * kCycleScale + 2 * MoveAvgN * RdAvgXtraCyc; } else { p->Cycles += MoveAvgN * 4 * kCycleScale + MoveAvgN * RdAvgXtraCyc; } #endif if (b76(p) == 2) { p->MainClass = kIKindMOVEMApRW; } else { p->MainClass = kIKindMOVEMApRL; } } else { if (CheckControlAddrMode(p)) { #if WantCycByPriOp p->Cycles = 4 * kCycleScale + RdAvgXtraCyc; p->Cycles += MoveMEACalcCyc(p, mode(p), reg(p)); if (4 == p->opsize) { p->Cycles += MoveAvgN * 8 * kCycleScale + 2 * MoveAvgN * RdAvgXtraCyc; } else { p->Cycles += MoveAvgN * 4 * kCycleScale + MoveAvgN * RdAvgXtraCyc; } #endif p->MainClass = kIKindMOVEMmr; } } } else { #if Use68020 if (((p->opcode >> 6) & 1) == 1) { /* DIVU 0100110001mmmrrr 0rrr0s0000000rrr */ /* DIVS 0100110001mmmrrr 0rrr1s0000000rrr */ p->MainClass = kIKindDivL; } else { /* MULU 0100110000mmmrrr 0rrr0s0000000rrr */ /* MULS 0100110000mmmrrr 0rrr1s0000000rrr */ p->MainClass = kIKindMulL; } #else p->MainClass = kIKindIllegal; #endif } break; case 7: default: /* keep compiler happy */ switch (b76(p)) { case 0: p->MainClass = kIKindIllegal; break; case 1: switch (mode(p)) { case 0: case 1: /* Trap 010011100100vvvv */ #if WantCycByPriOp p->Cycles = (34 * kCycleScale + 4 * RdAvgXtraCyc + 3 * WrAvgXtraCyc); #endif p->MainClass = kIKindTrap; break; case 2: /* Link */ #if WantCycByPriOp p->Cycles = (16 * kCycleScale + 2 * RdAvgXtraCyc + 2 * WrAvgXtraCyc); #endif if (reg(p) == 6) { p->MainClass = kIKindLinkA6; } else { p->MainClass = kIKindLink; } break; case 3: /* Unlk */ #if WantCycByPriOp p->Cycles = (12 * kCycleScale + 3 * RdAvgXtraCyc); #endif if (reg(p) == 6) { p->MainClass = kIKindUnlkA6; } else { p->MainClass = kIKindUnlk; } break; case 4: /* MOVE USP 0100111001100aaa */ #if WantCycByPriOp p->Cycles = (4 * kCycleScale + RdAvgXtraCyc); #endif p->MainClass = kIKindMoveRUSP; break; case 5: /* MOVE USP 0100111001101aaa */ #if WantCycByPriOp p->Cycles = (4 * kCycleScale + RdAvgXtraCyc); #endif p->MainClass = kIKindMoveUSPR; break; case 6: switch (reg(p)) { case 0: /* Reset 0100111001100000 */ #if WantCycByPriOp p->Cycles = (132 * kCycleScale + RdAvgXtraCyc); #endif p->MainClass = kIKindReset; break; case 1: /* Nop = 0100111001110001 */ #if WantCycByPriOp p->Cycles = (4 * kCycleScale + RdAvgXtraCyc); #endif p->MainClass = kIKindNop; break; case 2: /* Stop 0100111001110010 */ #if WantCycByPriOp p->Cycles = (4 * kCycleScale); #endif p->MainClass = kIKindStop; break; case 3: /* Rte 0100111001110011 */ #if WantCycByPriOp p->Cycles = (20 * kCycleScale + 5 * RdAvgXtraCyc); #endif p->MainClass = kIKindRte; break; case 4: /* Rtd 0100111001110100 */ #if Use68020 p->MainClass = kIKindRtd; #else p->MainClass = kIKindIllegal; #endif break; case 5: /* Rts 0100111001110101 */ #if WantCycByPriOp p->Cycles = (16 * kCycleScale + 4 * RdAvgXtraCyc); #endif p->MainClass = kIKindRts; break; case 6: /* TrapV 0100111001110110 */ #if WantCycByPriOp p->Cycles = (4 * kCycleScale + RdAvgXtraCyc); #endif p->MainClass = kIKindTrapV; break; case 7: default: /* keep compiler happy */ /* Rtr 0100111001110111 */ #if WantCycByPriOp p->Cycles = (20 * kCycleScale + 2 * RdAvgXtraCyc); #endif p->MainClass = kIKindRtr; break; } break; case 7: default: /* keep compiler happy */ #if Use68020 /* MOVEC 010011100111101m */ p->MainClass = kIKindMoveC; #else p->MainClass = kIKindIllegal; #endif break; } break; case 2: /* Jsr 0100111010mmmrrr */ if (CheckControlAddrMode(p)) { #if WantCycByPriOp switch (mode(p)) { case 2: p->Cycles = (16 * kCycleScale + 2 * RdAvgXtraCyc + 2 * WrAvgXtraCyc); break; case 5: p->Cycles = (18 * kCycleScale + 2 * RdAvgXtraCyc + 2 * WrAvgXtraCyc); break; case 6: p->Cycles = (22 * kCycleScale + 2 * RdAvgXtraCyc + 2 * WrAvgXtraCyc); break; case 7: default: /* keep compiler happy */ switch (reg(p)) { case 0: p->Cycles = (18 * kCycleScale + 2 * RdAvgXtraCyc + 2 * WrAvgXtraCyc); break; case 1: p->Cycles = (20 * kCycleScale + 3 * RdAvgXtraCyc + 2 * WrAvgXtraCyc); break; case 2: p->Cycles = (18 * kCycleScale + 2 * RdAvgXtraCyc + 2 * WrAvgXtraCyc); break; case 3: default: /* keep compiler happy */ p->Cycles = (22 * kCycleScale + 2 * RdAvgXtraCyc + 2 * WrAvgXtraCyc); break; } break; } #endif p->MainClass = kIKindJsr; } break; case 3: default: /* keep compiler happy */ /* JMP 0100111011mmmrrr */ if (CheckControlAddrMode(p)) { #if WantCycByPriOp switch (mode(p)) { case 2: p->Cycles = (8 * kCycleScale + 2 * RdAvgXtraCyc); break; case 5: p->Cycles = (10 * kCycleScale + 2 * RdAvgXtraCyc); break; case 6: p->Cycles = (14 * kCycleScale + 2 * RdAvgXtraCyc); break; case 7: default: /* keep compiler happy */ switch (reg(p)) { case 0: p->Cycles = (10 * kCycleScale + 2 * RdAvgXtraCyc); break; case 1: p->Cycles = (12 * kCycleScale + 3 * RdAvgXtraCyc); break; case 2: p->Cycles = (10 * kCycleScale + 2 * RdAvgXtraCyc); break; case 3: default: /* keep compiler happy */ p->Cycles = (14 * kCycleScale + 3 * RdAvgXtraCyc); break; } break; } #endif p->MainClass = kIKindJmp; } break; } break; } } } LOCALPROC MayInline DeCode5(WorkR *p) { if (b76(p) == 3) { if (mode(p) == 1) { /* DBcc 0101cccc11001ddd */ #if WantCycByPriOp #if WantCloserCyc p->Cycles = 0; #else p->Cycles = (11 * kCycleScale + 2 * RdAvgXtraCyc); /* average of cc true 12(2/0), cc false taken 10(2/0), and not 14(3/0) */ #endif #endif if (1 == ((p->opcode >> 8) & 15)) { p->MainClass = kIKindDBF; } else { p->MainClass = kIKindDBcc; } } else { #if Use68020 if ((mode(p) == 7) && (reg(p) >= 2)) { /* TRAPcc 0101cccc11111sss */ p->MainClass = kIKindTRAPcc; } else #endif { p->opsize = 1; /* Scc 0101cccc11mmmrrr */ if (CheckDataAltAddrMode(p)) { #if WantCycByPriOp if (0 != mode(p)) { p->Cycles = (8 * kCycleScale + RdAvgXtraCyc + WrAvgXtraCyc); } else { #if WantCloserCyc p->Cycles = (4 * kCycleScale + RdAvgXtraCyc); #else p->Cycles = (5 * kCycleScale + RdAvgXtraCyc); /* 4 when false, 6 when true */ #endif } p->Cycles += OpEACalcCyc(p, mode(p), reg(p)); #endif p->MainClass = kIKindScc; } } } } else { if (mode(p) == 1) { p->opsize = b8(p) * 2 + 2; SetDcoArgFields(p, trueblnr, kAMdDat4, kArgkCnst, octdat(rg9(p))); SetDcoArgFields(p, falseblnr, kAMdReg, kArgkRegL, reg(p) + 8); /* always long, regardless of opsize */ if (b8(p) == 0) { #if WantCycByPriOp p->Cycles = (4 == p->opsize) ? (8 * kCycleScale + RdAvgXtraCyc) : (4 * kCycleScale + RdAvgXtraCyc); #endif p->MainClass = kIKindAddQA; /* AddQA 0101nnn0ss001rrr */ } else { #if WantCycByPriOp p->Cycles = (8 * kCycleScale + RdAvgXtraCyc); #endif p->MainClass = kIKindSubQA; /* SubQA 0101nnn1ss001rrr */ } } else { FindOpSizeFromb76(p); SetDcoArgFields(p, trueblnr, kAMdDat4, kArgkCnst, octdat(rg9(p))); if (CheckValidAddrMode(p, mode(p), reg(p), kAddrValidDataAlt, falseblnr)) { #if WantCycByPriOp if (0 != mode(p)) { p->Cycles = (4 == p->opsize) ? (12 * kCycleScale + RdAvgXtraCyc + 2 * WrAvgXtraCyc) : (8 * kCycleScale + RdAvgXtraCyc + WrAvgXtraCyc); } else { p->Cycles = (4 == p->opsize) ? (8 * kCycleScale + RdAvgXtraCyc) : (4 * kCycleScale + RdAvgXtraCyc); } p->Cycles += OpEACalcCyc(p, mode(p), reg(p)); #endif if (b8(p) == 0) { /* AddQ 0101nnn0ssmmmrrr */ #if 0 if (CheckDataAltAddrMode(p)) { p->MainClass = kIKindAddQ; } #endif p->MainClass = kIKindAddB + OpSizeOffset(p); } else { /* SubQ 0101nnn1ssmmmrrr */ #if 0 if (CheckDataAltAddrMode(p)) { p->MainClass = kIKindSubQ; } #endif p->MainClass = kIKindSubB + OpSizeOffset(p); } } } } } LOCALPROC MayInline DeCode6(WorkR *p) { ui5b cond = (p->opcode >> 8) & 15; if (cond == 1) { /* Bsr 01100001nnnnnnnn */ #if WantCycByPriOp p->Cycles = (18 * kCycleScale + 2 * RdAvgXtraCyc + 2 * WrAvgXtraCyc); #endif if (0 == (p->opcode & 255)) { p->MainClass = kIKindBsrW; } else #if Use68020 if (255 == (p->opcode & 255)) { p->MainClass = kIKindBsrL; } else #endif { p->MainClass = kIKindBsrB; } } else if (cond == 0) { /* Bra 01100000nnnnnnnn */ #if WantCycByPriOp p->Cycles = (10 * kCycleScale + 2 * RdAvgXtraCyc); #endif if (0 == (p->opcode & 255)) { p->MainClass = kIKindBraW; } else #if Use68020 if (255 == (p->opcode & 255)) { p->MainClass = kIKindBraL; } else #endif { p->MainClass = kIKindBraB; } } else { /* Bcc 0110ccccnnnnnnnn */ if (0 == (p->opcode & 255)) { #if WantCycByPriOp #if WantCloserCyc p->Cycles = 0; #else p->Cycles = (11 * kCycleScale + 2 * RdAvgXtraCyc); /* average of branch taken 10(2/0) and not 12(2/0) */ #endif #endif p->MainClass = kIKindBccW; } else #if Use68020 if (255 == (p->opcode & 255)) { p->MainClass = kIKindBccL; } else #endif { #if WantCycByPriOp #if WantCloserCyc p->Cycles = 0; #else p->Cycles = (9 * kCycleScale + RdAvgXtraCyc + (RdAvgXtraCyc / 2)); /* average of branch taken 10(2/0) and not 8(1/0) */ #endif #endif p->MainClass = kIKindBccB; } } } LOCALPROC MayInline DeCode7(WorkR *p) { if (b8(p) == 0) { p->opsize = 4; #if WantCycByPriOp p->Cycles = (4 * kCycleScale + RdAvgXtraCyc); #endif p->MainClass = kIKindMoveQ; } else { p->MainClass = kIKindIllegal; } } LOCALPROC MayInline DeCode8(WorkR *p) { if (b76(p) == 3) { p->opsize = 2; if (CheckDataAddrMode(p)) { if (b8(p) == 0) { /* DivU 1000ddd011mmmrrr */ #if WantCycByPriOp p->Cycles = RdAvgXtraCyc; p->Cycles += OpEACalcCyc(p, mode(p), reg(p)); #if ! WantCloserCyc p->Cycles += 133 * kCycleScale; /* worse case 140, less than ten percent different from best case */ #endif #endif p->MainClass = kIKindDivU; } else { /* DivS 1000ddd111mmmrrr */ #if WantCycByPriOp p->Cycles = RdAvgXtraCyc; p->Cycles += OpEACalcCyc(p, mode(p), reg(p)); #if ! WantCloserCyc p->Cycles += 150 * kCycleScale; /* worse case 158, less than ten percent different from best case */ #endif #endif p->MainClass = kIKindDivS; } } } else { if (b8(p) == 0) { /* OR 1000ddd0ssmmmrrr */ #if 0 if (CheckDataAddrMode(p)) { p->MainClass = kIKindOrEaD; } #endif FindOpSizeFromb76(p); if (CheckValidAddrMode(p, mode(p), reg(p), kAddrValidData, trueblnr)) if (CheckValidAddrMode(p, 0, rg9(p), kAddrValidAny, falseblnr)) { #if WantCycByPriOp if (4 == p->opsize) { if ((mode(p) < 2) || ((7 == mode(p)) && (reg(p) == 4))) { p->Cycles = (8 * kCycleScale + RdAvgXtraCyc); } else { p->Cycles = (6 * kCycleScale + RdAvgXtraCyc); } } else { p->Cycles = (4 * kCycleScale + RdAvgXtraCyc); } p->Cycles += OpEACalcCyc(p, mode(p), reg(p)); #endif p->MainClass = kIKindOrEaD; } } else { if (mode(p) < 2) { switch (b76(p)) { case 0: /* SBCD 1000xxx10000mxxx */ #if WantCycByPriOp if (0 != mode(p)) { p->Cycles = (18 * kCycleScale + 3 * RdAvgXtraCyc + WrAvgXtraCyc); } else { p->Cycles = (6 * kCycleScale + RdAvgXtraCyc); } #endif if (mode(p) == 0) { p->MainClass = kIKindSbcdr; } else { p->MainClass = kIKindSbcdm; } break; #if Use68020 case 1: /* PACK 1000rrr10100mrrr */ p->MainClass = kIKindPack; break; case 2: /* UNPK 1000rrr11000mrrr */ p->MainClass = kIKindUnpk; break; #endif default: p->MainClass = kIKindIllegal; break; } } else { /* OR 1000ddd1ssmmmrrr */ #if 0 if (CheckDataAltAddrMode(p)) { p->MainClass = kIKindOrDEa; } #endif FindOpSizeFromb76(p); if (CheckValidAddrMode(p, 0, rg9(p), kAddrValidAny, trueblnr)) if (CheckValidAddrMode(p, mode(p), reg(p), kAddrValidAltMem, falseblnr)) { #if WantCycByPriOp p->Cycles = (4 == p->opsize) ? (12 * kCycleScale + RdAvgXtraCyc + 2 * WrAvgXtraCyc) : (8 * kCycleScale + RdAvgXtraCyc + WrAvgXtraCyc); p->Cycles += OpEACalcCyc(p, mode(p), reg(p)); #endif p->MainClass = kIKindOrDEa; } } } } } LOCALPROC MayInline DeCode9(WorkR *p) { if (b76(p) == 3) { /* SUBA 1001dddm11mmmrrr */ #if 0 if (IsValidAddrMode(p)) { p->MainClass = kIKindSubA; } #endif p->opsize = b8(p) * 2 + 2; SetDcoArgFields(p, falseblnr, kAMdReg, kArgkRegL, rg9(p) + 8); /* always long, regardless of opsize */ if (CheckValidAddrMode(p, mode(p), reg(p), kAddrValidAny, trueblnr)) { #if WantCycByPriOp if (4 == p->opsize) { if ((mode(p) < 2) || ((7 == mode(p)) && (reg(p) == 4))) { p->Cycles = (8 * kCycleScale + RdAvgXtraCyc); } else { p->Cycles = (6 * kCycleScale + RdAvgXtraCyc); } } else { p->Cycles = (8 * kCycleScale + RdAvgXtraCyc); } p->Cycles += OpEACalcCyc(p, mode(p), reg(p)); #endif p->MainClass = kIKindSubA; } } else { if (b8(p) == 0) { /* SUB 1001ddd0ssmmmrrr */ #if 0 if (IsValidAddrMode(p)) { p->MainClass = kIKindSubEaR; } #endif FindOpSizeFromb76(p); if (CheckValidAddrMode(p, mode(p), reg(p), kAddrValidAny, trueblnr)) if (CheckValidAddrMode(p, 0, rg9(p), kAddrValidAny, falseblnr)) { #if WantCycByPriOp if (4 == p->opsize) { if ((mode(p) < 2) || ((7 == mode(p)) && (reg(p) == 4))) { p->Cycles = (8 * kCycleScale + RdAvgXtraCyc); } else { p->Cycles = (6 * kCycleScale + RdAvgXtraCyc); } } else { p->Cycles = (4 * kCycleScale + RdAvgXtraCyc); } p->Cycles += OpEACalcCyc(p, mode(p), reg(p)); #endif p->MainClass = kIKindSubB + OpSizeOffset(p); } } else { if (mode(p) == 0) { /* SUBX 1001ddd1ss000rrr */ /* p->MainClass = kIKindSubXd; */ FindOpSizeFromb76(p); if (CheckValidAddrMode(p, 0, reg(p), kAddrValidAny, trueblnr)) if (CheckValidAddrMode(p, 0, rg9(p), kAddrValidAny, falseblnr)) { #if WantCycByPriOp p->Cycles = (4 == p->opsize) ? (8 * kCycleScale + RdAvgXtraCyc) : (4 * kCycleScale + RdAvgXtraCyc); #endif p->MainClass = kIKindSubXB + OpSizeOffset(p); } } else if (mode(p) == 1) { /* SUBX 1001ddd1ss001rrr */ /* p->MainClass = kIKindSubXm; */ FindOpSizeFromb76(p); if (CheckValidAddrMode(p, 4, reg(p), kAddrValidAny, trueblnr)) if (CheckValidAddrMode(p, 4, rg9(p), kAddrValidAny, falseblnr)) { #if WantCycByPriOp p->Cycles = (4 == p->opsize) ? (30 * kCycleScale + 5 * RdAvgXtraCyc + 2 * WrAvgXtraCyc) : (18 * kCycleScale + 3 * RdAvgXtraCyc + 1 * WrAvgXtraCyc); #endif p->MainClass = kIKindSubXB + OpSizeOffset(p); } } else { /* SUB 1001ddd1ssmmmrrr */ #if 0 if (CheckAltMemAddrMode(p)) { p->MainClass = kIKindSubREa; } #endif FindOpSizeFromb76(p); if (CheckValidAddrMode(p, 0, rg9(p), kAddrValidAny, trueblnr)) if (CheckValidAddrMode(p, mode(p), reg(p), kAddrValidAltMem, falseblnr)) { #if WantCycByPriOp p->Cycles = (4 == p->opsize) ? (12 * kCycleScale + RdAvgXtraCyc + 2 * WrAvgXtraCyc) : (8 * kCycleScale + RdAvgXtraCyc + WrAvgXtraCyc); p->Cycles += OpEACalcCyc(p, mode(p), reg(p)); #endif p->MainClass = kIKindSubB + OpSizeOffset(p); } } } } } LOCALPROC MayInline DeCodeA(WorkR *p) { #if WantCycByPriOp p->Cycles = (34 * kCycleScale + 4 * RdAvgXtraCyc + 3 * WrAvgXtraCyc); #endif p->MainClass = kIKindA; } LOCALPROC MayInline DeCodeB(WorkR *p) { if (b76(p) == 3) { /* CMPA 1011ddds11mmmrrr */ #if 0 if (IsValidAddrMode(p)) { p->MainClass = kIKindCmpA; } #endif p->opsize = b8(p) * 2 + 2; SetDcoArgFields(p, falseblnr, kAMdReg, kArgkRegL, rg9(p) + 8); /* always long, regardless of opsize */ if (CheckValidAddrMode(p, mode(p), reg(p), kAddrValidAny, trueblnr)) { #if WantCycByPriOp p->Cycles = (6 * kCycleScale + RdAvgXtraCyc); p->Cycles += OpEACalcCyc(p, mode(p), reg(p)); #endif p->MainClass = kIKindCmpA; } } else if (b8(p) == 1) { if (mode(p) == 1) { /* CmpM 1011ddd1ss001rrr */ #if 0 p->MainClass = kIKindCmpM; #endif FindOpSizeFromb76(p); if (CheckValidAddrMode(p, 3, reg(p), kAddrValidAny, trueblnr)) if (CheckValidAddrMode(p, 3, rg9(p), kAddrValidAny, falseblnr)) { #if WantCycByPriOp p->Cycles = (4 == p->opsize) ? (20 * kCycleScale + 5 * RdAvgXtraCyc) : (12 * kCycleScale + 3 * RdAvgXtraCyc); #endif p->MainClass = kIKindCmpB + OpSizeOffset(p); } } else { #if 0 /* Eor 1011ddd1ssmmmrrr */ if (CheckDataAltAddrMode(p)) { p->MainClass = kIKindEor; } #endif FindOpSizeFromb76(p); if (CheckValidAddrMode(p, 0, rg9(p), kAddrValidAny, trueblnr)) if (CheckValidAddrMode(p, mode(p), reg(p), kAddrValidDataAlt, falseblnr)) { #if WantCycByPriOp if (0 != mode(p)) { p->Cycles = (4 == p->opsize) ? (12 * kCycleScale + RdAvgXtraCyc + 2 * WrAvgXtraCyc) : (8 * kCycleScale + RdAvgXtraCyc + WrAvgXtraCyc); } else { p->Cycles = (4 == p->opsize) ? (8 * kCycleScale + RdAvgXtraCyc) : (4 * kCycleScale + RdAvgXtraCyc); } p->Cycles += OpEACalcCyc(p, mode(p), reg(p)); #endif p->MainClass = kIKindEor; } } } else { /* Cmp 1011ddd0ssmmmrrr */ #if 0 if (IsValidAddrMode(p)) { p->MainClass = kIKindCmp; } #endif FindOpSizeFromb76(p); if (CheckValidAddrMode(p, mode(p), reg(p), kAddrValidAny, trueblnr)) if (CheckValidAddrMode(p, 0, rg9(p), kAddrValidAny, falseblnr)) { #if WantCycByPriOp p->Cycles = (4 == p->opsize) ? (6 * kCycleScale + RdAvgXtraCyc) : (4 * kCycleScale + RdAvgXtraCyc); p->Cycles += OpEACalcCyc(p, mode(p), reg(p)); #endif p->MainClass = kIKindCmpB + OpSizeOffset(p); } } } LOCALPROC MayInline DeCodeC(WorkR *p) { if (b76(p) == 3) { p->opsize = 2; if (CheckDataAddrMode(p)) { #if WantCycByPriOp #if WantCloserCyc p->Cycles = (38 * kCycleScale + RdAvgXtraCyc); #else p->Cycles = (54 * kCycleScale + RdAvgXtraCyc); /* worst case 70, best case 38 */ #endif p->Cycles += OpEACalcCyc(p, mode(p), reg(p)); #endif if (b8(p) == 0) { /* MulU 1100ddd011mmmrrr */ p->MainClass = kIKindMulU; } else { /* MulS 1100ddd111mmmrrr */ p->MainClass = kIKindMulS; } } } else { if (b8(p) == 0) { /* And 1100ddd0ssmmmrrr */ #if 0 if (CheckDataAddrMode(p)) { p->MainClass = kIKindAndEaD; } #endif FindOpSizeFromb76(p); if (CheckValidAddrMode(p, mode(p), reg(p), kAddrValidData, trueblnr)) if (CheckValidAddrMode(p, 0, rg9(p), kAddrValidAny, falseblnr)) { #if WantCycByPriOp if (4 == p->opsize) { if ((mode(p) < 2) || ((7 == mode(p)) && (reg(p) == 4))) { p->Cycles = (8 * kCycleScale + RdAvgXtraCyc); } else { p->Cycles = (6 * kCycleScale + RdAvgXtraCyc); } } else { p->Cycles = (4 * kCycleScale + RdAvgXtraCyc); } p->Cycles += OpEACalcCyc(p, mode(p), reg(p)); #endif p->MainClass = kIKindAndEaD; } } else { if (mode(p) < 2) { switch (b76(p)) { case 0: /* ABCD 1100ddd10000mrrr */ #if WantCycByPriOp if (0 != mode(p)) { p->Cycles = (18 * kCycleScale + 3 * RdAvgXtraCyc + WrAvgXtraCyc); } else { p->Cycles = (6 * kCycleScale + RdAvgXtraCyc); } #endif if (mode(p) == 0) { p->MainClass = kIKindAbcdr; } else { p->MainClass = kIKindAbcdm; } break; case 1: /* Exg 1100ddd10100trrr */ #if WantCycByPriOp p->Cycles = (6 * kCycleScale + RdAvgXtraCyc); #endif if (mode(p) == 0) { p->MainClass = kIKindExgdd; } else { p->MainClass = kIKindExgaa; } break; case 2: default: /* keep compiler happy */ if (mode(p) == 0) { p->MainClass = kIKindIllegal; } else { /* Exg 1100ddd110001rrr */ #if WantCycByPriOp p->Cycles = (6 * kCycleScale + RdAvgXtraCyc); #endif p->MainClass = kIKindExgda; } break; } } else { /* And 1100ddd1ssmmmrrr */ #if 0 if (CheckAltMemAddrMode(p)) { p->MainClass = kIKindAndDEa; } #endif FindOpSizeFromb76(p); if (CheckValidAddrMode(p, 0, rg9(p), kAddrValidAny, trueblnr)) if (CheckValidAddrMode(p, mode(p), reg(p), kAddrValidAltMem, falseblnr)) { #if WantCycByPriOp p->Cycles = (4 == p->opsize) ? (12 * kCycleScale + RdAvgXtraCyc + 2 * WrAvgXtraCyc) : (8 * kCycleScale + RdAvgXtraCyc + WrAvgXtraCyc); p->Cycles += OpEACalcCyc(p, mode(p), reg(p)); #endif p->MainClass = kIKindAndDEa; } } } } } LOCALPROC MayInline DeCodeD(WorkR *p) { if (b76(p) == 3) { /* ADDA 1101dddm11mmmrrr */ p->opsize = b8(p) * 2 + 2; SetDcoArgFields(p, falseblnr, kAMdReg, kArgkRegL, rg9(p) + 8); /* always long, regardless of opsize */ if (CheckValidAddrMode(p, mode(p), reg(p), kAddrValidAny, trueblnr)) { #if WantCycByPriOp if (4 == p->opsize) { if ((mode(p) < 2) || ((7 == mode(p)) && (reg(p) == 4))) { p->Cycles = (8 * kCycleScale + RdAvgXtraCyc); } else { p->Cycles = (6 * kCycleScale + RdAvgXtraCyc); } } else { p->Cycles = (8 * kCycleScale + RdAvgXtraCyc); } p->Cycles += OpEACalcCyc(p, mode(p), reg(p)); #endif p->MainClass = kIKindAddA; } } else { if (b8(p) == 0) { /* ADD 1101ddd0ssmmmrrr */ FindOpSizeFromb76(p); if (CheckValidAddrMode(p, mode(p), reg(p), kAddrValidAny, trueblnr)) if (CheckValidAddrMode(p, 0, rg9(p), kAddrValidAny, falseblnr)) { #if WantCycByPriOp if (4 == p->opsize) { if ((mode(p) < 2) || ((7 == mode(p)) && (reg(p) == 4))) { p->Cycles = (8 * kCycleScale + RdAvgXtraCyc); } else { p->Cycles = (6 * kCycleScale + RdAvgXtraCyc); } } else { p->Cycles = (4 * kCycleScale + RdAvgXtraCyc); } p->Cycles += OpEACalcCyc(p, mode(p), reg(p)); #endif p->MainClass = kIKindAddB + OpSizeOffset(p); } } else { if (mode(p) == 0) { /* ADDX 1101ddd1ss000rrr */ /* p->MainClass = kIKindAddXd; */ FindOpSizeFromb76(p); if (CheckValidAddrMode(p, 0, reg(p), kAddrValidAny, trueblnr)) if (CheckValidAddrMode(p, 0, rg9(p), kAddrValidAny, falseblnr)) { #if WantCycByPriOp p->Cycles = (4 == p->opsize) ? (8 * kCycleScale + RdAvgXtraCyc) : (4 * kCycleScale + RdAvgXtraCyc); #endif p->MainClass = kIKindAddXB + OpSizeOffset(p); } } else if (mode(p) == 1) { /* p->MainClass = kIKindAddXm; */ FindOpSizeFromb76(p); if (CheckValidAddrMode(p, 4, reg(p), kAddrValidAny, trueblnr)) if (CheckValidAddrMode(p, 4, rg9(p), kAddrValidAny, falseblnr)) { #if WantCycByPriOp p->Cycles = (4 == p->opsize) ? (30 * kCycleScale + 5 * RdAvgXtraCyc + 2 * WrAvgXtraCyc) : (18 * kCycleScale + 3 * RdAvgXtraCyc + 1 * WrAvgXtraCyc); #endif p->MainClass = kIKindAddXB + OpSizeOffset(p); } } else { /* ADD 1101ddd1ssmmmrrr */ FindOpSizeFromb76(p); if (CheckValidAddrMode(p, 0, rg9(p), kAddrValidAny, trueblnr)) if (CheckValidAddrMode(p, mode(p), reg(p), kAddrValidAltMem, falseblnr)) { #if WantCycByPriOp p->Cycles = (4 == p->opsize) ? (12 * kCycleScale + RdAvgXtraCyc + 2 * WrAvgXtraCyc) : (8 * kCycleScale + RdAvgXtraCyc + WrAvgXtraCyc); p->Cycles += OpEACalcCyc(p, mode(p), reg(p)); #endif p->MainClass = kIKindAddB + OpSizeOffset(p); } } } } } LOCALPROC MayInline DeCodeE(WorkR *p) { if (b76(p) == 3) { if ((p->opcode & 0x0800) != 0) { #if Use68020 /* 11101???11mmmrrr */ switch (mode(p)) { case 1: case 3: case 4: default: /* keep compiler happy */ p->MainClass = kIKindIllegal; break; case 0: case 2: case 5: case 6: p->MainClass = kIKindBitField; break; case 7: switch (reg(p)) { case 0: case 1: p->MainClass = kIKindBitField; break; case 2: case 3: switch ((p->opcode >> 8) & 7) { case 0: /* BFTST */ case 1: /* BFEXTU */ case 3: /* BFEXTS */ case 5: /* BFFFO */ p->MainClass = kIKindBitField; break; default: p->MainClass = kIKindIllegal; break; } break; default: p->MainClass = kIKindIllegal; break; } break; } #else p->MainClass = kIKindIllegal; #endif } else { /* 11100ttd11mmmddd */ if (CheckAltMemAddrMode(p)) { #if WantCycByPriOp p->Cycles = (8 * kCycleScale + RdAvgXtraCyc + WrAvgXtraCyc); p->Cycles += OpEACalcCyc(p, mode(p), reg(p)); #endif p->MainClass = kIKindRolopNM; } } } else { if (mode(p) < 4) { /* 1110cccdss0ttddd */ #if WantCycByPriOp p->Cycles = (octdat(rg9(p)) * (2 * kCycleScale)) + ((4 == p->opsize) ? (8 * kCycleScale + RdAvgXtraCyc) : (6 * kCycleScale + RdAvgXtraCyc)); #endif p->MainClass = kIKindRolopND; } else { /* 1110rrrdss1ttddd */ #if WantCycByPriOp #if WantCloserCyc p->Cycles = (4 == p->opsize) ? (8 * kCycleScale + RdAvgXtraCyc) : (6 * kCycleScale + RdAvgXtraCyc); #else p->Cycles = (4 == p->opsize) ? ((8 * kCycleScale) + RdAvgXtraCyc + (8 * (2 * kCycleScale))) /* say average shift count of 8 */ : ((6 * kCycleScale) + RdAvgXtraCyc + (4 * (2 * kCycleScale))); /* say average shift count of 4 */ #endif #endif p->MainClass = kIKindRolopDD; } } } LOCALPROC MayInline DeCodeF(WorkR *p) { #if WantCycByPriOp p->Cycles = (34 * kCycleScale + 4 * RdAvgXtraCyc + 3 * WrAvgXtraCyc); #endif p->MainClass = kIKindF; } LOCALPROC DeCodeOneOp(WorkR *p) { switch (p->opcode >> 12) { case 0x0: DeCode0(p); break; case 0x1: DeCode1(p); break; case 0x2: DeCode2(p); break; case 0x3: DeCode3(p); break; case 0x4: DeCode4(p); break; case 0x5: DeCode5(p); break; case 0x6: DeCode6(p); break; case 0x7: DeCode7(p); break; case 0x8: DeCode8(p); break; case 0x9: DeCode9(p); break; case 0xA: DeCodeA(p); break; case 0xB: DeCodeB(p); break; case 0xC: DeCodeC(p); break; case 0xD: DeCodeD(p); break; case 0xE: DeCodeE(p); break; case 0xF: default: /* keep compiler happy */ DeCodeF(p); break; } if (kIKindIllegal == p->MainClass) { #if WantCycByPriOp p->Cycles = (34 * kCycleScale + 4 * RdAvgXtraCyc + 3 * WrAvgXtraCyc); #endif SetDcoSrcAMd(&p->DecOp, 0); SetDcoSrcArgk(&p->DecOp, 0); SetDcoSrcArgDat(&p->DecOp, 0); SetDcoDstAMd(&p->DecOp, 0); SetDcoDstArgk(&p->DecOp, 0); SetDcoDstArgDat(&p->DecOp, 0); } SetDcoMainClas(&p->DecOp, p->MainClass); #if WantCycByPriOp SetDcoCycles(&p->DecOp, p->Cycles); #else SetDcoCycles(&p->DecOp, kMyAvgCycPerInstr); #endif } GLOBALPROC M68KITAB_setup(DecOpR *p) { ui5b i; WorkR r; for (i = 0; i < (ui5b)256 * 256; ++i) { r.opcode = i; r.MainClass = kIKindIllegal; r.DecOp.A = 0; r.DecOp.B = 0; #if WantCycByPriOp r.Cycles = kMyAvgCycPerInstr; #endif DeCodeOneOp(&r); p[i].A = r.DecOp.A; p[i].B = r.DecOp.B; } }
jsdf/minivmac
src/M68KITAB.c
C
gpl-2.0
62,483
/* * Copyright (C) 2004, 2005, 2007 Internet Systems Consortium, Inc. ("ISC") * Copyright (C) 1999-2001 Internet Software Consortium. * * Permission to use, copy, modify, and/or distribute this software for any * purpose with or without fee is hereby granted, provided that the above * copyright notice and this permission notice appear in all copies. * * THE SOFTWARE IS PROVIDED "AS IS" AND ISC DISCLAIMS ALL WARRANTIES WITH * REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY * AND FITNESS. IN NO EVENT SHALL ISC BE LIABLE FOR ANY SPECIAL, DIRECT, * INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM * LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE * OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR * PERFORMANCE OF THIS SOFTWARE. */ /* $Id: nsap-ptr_23.c,v 1.38 2007/06/19 23:47:17 tbox Exp $ */ /* Reviewed: Fri Mar 17 10:16:02 PST 2000 by gson */ /* RFC1348. Obsoleted in RFC 1706 - use PTR instead. */ #ifndef RDATA_IN_1_NSAP_PTR_23_C #define RDATA_IN_1_NSAP_PTR_23_C #define RRTYPE_NSAP_PTR_ATTRIBUTES (0) static inline isc_result_t fromtext_in_nsap_ptr(ARGS_FROMTEXT) { isc_token_t token; dns_name_t name; isc_buffer_t buffer; REQUIRE(type == 23); REQUIRE(rdclass == 1); UNUSED(type); UNUSED(rdclass); UNUSED(callbacks); RETERR(isc_lex_getmastertoken(lexer, &token, isc_tokentype_string, ISC_FALSE)); dns_name_init(&name, NULL); buffer_fromregion(&buffer, &token.value.as_region); origin = (origin != NULL) ? origin : dns_rootname; RETTOK(dns_name_fromtext(&name, &buffer, origin, options, target)); return (ISC_R_SUCCESS); } static inline isc_result_t totext_in_nsap_ptr(ARGS_TOTEXT) { isc_region_t region; dns_name_t name; dns_name_t prefix; isc_boolean_t sub; REQUIRE(rdata->type == 23); REQUIRE(rdata->rdclass == 1); REQUIRE(rdata->length != 0); dns_name_init(&name, NULL); dns_name_init(&prefix, NULL); dns_rdata_toregion(rdata, &region); dns_name_fromregion(&name, &region); sub = name_prefix(&name, tctx->origin, &prefix); return (dns_name_totext(&prefix, sub, target)); } static inline isc_result_t fromwire_in_nsap_ptr(ARGS_FROMWIRE) { dns_name_t name; REQUIRE(type == 23); REQUIRE(rdclass == 1); UNUSED(type); UNUSED(rdclass); dns_decompress_setmethods(dctx, DNS_COMPRESS_NONE); dns_name_init(&name, NULL); return (dns_name_fromwire(&name, source, dctx, options, target)); } static inline isc_result_t towire_in_nsap_ptr(ARGS_TOWIRE) { dns_name_t name; dns_offsets_t offsets; isc_region_t region; REQUIRE(rdata->type == 23); REQUIRE(rdata->rdclass == 1); REQUIRE(rdata->length != 0); dns_compress_setmethods(cctx, DNS_COMPRESS_NONE); dns_name_init(&name, offsets); dns_rdata_toregion(rdata, &region); dns_name_fromregion(&name, &region); return (dns_name_towire(&name, cctx, target)); } static inline int compare_in_nsap_ptr(ARGS_COMPARE) { dns_name_t name1; dns_name_t name2; isc_region_t region1; isc_region_t region2; REQUIRE(rdata1->type == rdata2->type); REQUIRE(rdata1->rdclass == rdata2->rdclass); REQUIRE(rdata1->type == 23); REQUIRE(rdata1->rdclass == 1); REQUIRE(rdata1->length != 0); REQUIRE(rdata2->length != 0); dns_name_init(&name1, NULL); dns_name_init(&name2, NULL); dns_rdata_toregion(rdata1, &region1); dns_rdata_toregion(rdata2, &region2); dns_name_fromregion(&name1, &region1); dns_name_fromregion(&name2, &region2); return (dns_name_rdatacompare(&name1, &name2)); } static inline isc_result_t fromstruct_in_nsap_ptr(ARGS_FROMSTRUCT) { dns_rdata_in_nsap_ptr_t *nsap_ptr = source; isc_region_t region; REQUIRE(type == 23); REQUIRE(rdclass == 1); REQUIRE(source != NULL); REQUIRE(nsap_ptr->common.rdtype == type); REQUIRE(nsap_ptr->common.rdclass == rdclass); UNUSED(type); UNUSED(rdclass); dns_name_toregion(&nsap_ptr->owner, &region); return (isc_buffer_copyregion(target, &region)); } static inline isc_result_t tostruct_in_nsap_ptr(ARGS_TOSTRUCT) { isc_region_t region; dns_rdata_in_nsap_ptr_t *nsap_ptr = target; dns_name_t name; REQUIRE(rdata->type == 23); REQUIRE(rdata->rdclass == 1); REQUIRE(target != NULL); REQUIRE(rdata->length != 0); nsap_ptr->common.rdclass = rdata->rdclass; nsap_ptr->common.rdtype = rdata->type; ISC_LINK_INIT(&nsap_ptr->common, link); dns_name_init(&name, NULL); dns_rdata_toregion(rdata, &region); dns_name_fromregion(&name, &region); dns_name_init(&nsap_ptr->owner, NULL); RETERR(name_duporclone(&name, mctx, &nsap_ptr->owner)); nsap_ptr->mctx = mctx; return (ISC_R_SUCCESS); } static inline void freestruct_in_nsap_ptr(ARGS_FREESTRUCT) { dns_rdata_in_nsap_ptr_t *nsap_ptr = source; REQUIRE(source != NULL); REQUIRE(nsap_ptr->common.rdclass == 1); REQUIRE(nsap_ptr->common.rdtype == 23); if (nsap_ptr->mctx == NULL) return; dns_name_free(&nsap_ptr->owner, nsap_ptr->mctx); nsap_ptr->mctx = NULL; } static inline isc_result_t additionaldata_in_nsap_ptr(ARGS_ADDLDATA) { REQUIRE(rdata->type == 23); REQUIRE(rdata->rdclass == 1); UNUSED(rdata); UNUSED(add); UNUSED(arg); return (ISC_R_SUCCESS); } static inline isc_result_t digest_in_nsap_ptr(ARGS_DIGEST) { isc_region_t r; dns_name_t name; REQUIRE(rdata->type == 23); REQUIRE(rdata->rdclass == 1); dns_rdata_toregion(rdata, &r); dns_name_init(&name, NULL); dns_name_fromregion(&name, &r); return (dns_name_digest(&name, digest, arg)); } static inline isc_boolean_t checkowner_in_nsap_ptr(ARGS_CHECKOWNER) { REQUIRE(type == 23); REQUIRE(rdclass == 1); UNUSED(name); UNUSED(type); UNUSED(rdclass); UNUSED(wildcard); return (ISC_TRUE); } static inline isc_boolean_t checknames_in_nsap_ptr(ARGS_CHECKNAMES) { REQUIRE(rdata->type == 23); REQUIRE(rdata->rdclass == 1); UNUSED(rdata); UNUSED(owner); UNUSED(bad); return (ISC_TRUE); } #endif /* RDATA_IN_1_NSAP_PTR_23_C */
rhuitl/uClinux
user/bind/lib/dns/rdata/in_1/nsap-ptr_23.c
C
gpl-2.0
5,928
<?php /** * Search & Filter Pro * * @package Search_Filter * @author Ross Morsali * @link http://www.designsandcode.com/ * @copyright 2015 Designs & Code */ ?> <div class="wrap"> <h2><?php echo esc_html( get_admin_page_title() ); ?></h2> <h3><?php _e('Search &amp; Filter License'); ?></h3> <form method="post" action="options.php"> <?php settings_fields('search_filter_license'); ?> <?php _e('Enter your license key to enable updates.'); ?> <table class="form-table"> <tbody> <tr valign="top"> <th scope="row" valign="top"> <?php _e('License Key'); ?> </th> <td> <input id="search_filter_license_key" name="search_filter_license_key" type="text" class="regular-text" value="<?php esc_attr_e( $license ); ?>" /> <label class="description" for="search_filter_license_key"><?php _e('Enter your license key'); ?></label> </td> </tr> <?php if( false !== $license ) { ?> <tr valign="top"> <th scope="row" valign="top"> <?php _e('Activate License'); ?> </th> <td> <?php if( $status !== false && $status == 'valid' ) { ?> <span style="color:green;"><?php _e('active'); ?></span> <?php wp_nonce_field( 'search_filter_nonce', 'search_filter_nonce' ); ?> <input type="submit" class="button-secondary" name="edd_license_deactivate" value="<?php _e('Deactivate License'); ?>"/> <?php } else { wp_nonce_field( 'search_filter_nonce', 'search_filter_nonce' ); ?> <input type="submit" class="button-secondary" name="search_filter_license_activate" value="<?php _e('Activate License'); ?>"/> <?php } ?> </td> </tr> <?php } ?> </tbody> </table> <?php submit_button(); ?> </form> </div>
IDS-UK/genderhub
wp-content/plugins/search-filter-pro/admin/views/admin-license-settings.php
PHP
gpl-3.0
1,775
<?php /** * Quotation block hidding * * Plugin that adds a possibility to hide long blocks of cited text in messages. * * Configuration: * // Minimum number of citation lines. Longer citation blocks will be hidden. * // 0 - no limit (no hidding). * $config['hide_blockquote_limit'] = 0; * * @version @package_version@ * @license GNU GPLv3+ * @author Aleksander Machniak <[email protected]> */ class hide_blockquote extends rcube_plugin { public $task = 'mail|settings'; function init() { $rcmail = rcmail::get_instance(); if ($rcmail->task == 'mail' && ($rcmail->action == 'preview' || $rcmail->action == 'show') && ($limit = $rcmail->config->get('hide_blockquote_limit')) ) { // include styles $this->include_stylesheet($this->local_skin_path() . "/style.css"); // Script and localization $this->include_script('hide_blockquote.js'); $this->add_texts('localization', true); // set env variable for client $rcmail->output->set_env('blockquote_limit', $limit); } else if ($rcmail->task == 'settings') { $dont_override = $rcmail->config->get('dont_override', array()); if (!in_array('hide_blockquote_limit', $dont_override)) { $this->add_hook('preferences_list', array($this, 'prefs_table')); $this->add_hook('preferences_save', array($this, 'save_prefs')); } } } function prefs_table($args) { if ($args['section'] != 'mailview') { return $args; } $this->add_texts('localization'); $rcmail = rcmail::get_instance(); $limit = (int) $rcmail->config->get('hide_blockquote_limit'); $field_id = 'hide_blockquote_limit'; $input = new html_inputfield(array('name' => '_'.$field_id, 'id' => $field_id, 'size' => 5)); $args['blocks']['main']['options']['hide_blockquote_limit'] = array( 'title' => $this->gettext('quotelimit'), 'content' => $input->show($limit ?: '') ); return $args; } function save_prefs($args) { if ($args['section'] == 'mailview') { $args['prefs']['hide_blockquote_limit'] = (int) rcube_utils::get_input_value('_hide_blockquote_limit', rcube_utils::INPUT_POST); } return $args; } }
hetznerZApackages/roundcube
plugins/hide_blockquote/hide_blockquote.php
PHP
gpl-3.0
2,439
// Copyright 2019-2020 CERN and copyright holders of ALICE O2. // See https://alice-o2.web.cern.ch/copyright for details of the copyright holders. // All rights not expressly granted are reserved. // // This software is distributed under the terms of the GNU General Public // License v3 (GPL Version 3), copied verbatim in the file "COPYING". // // In applying this license CERN does not waive the privileges and immunities // granted to it by virtue of its status as an Intergovernmental Organization // or submit itself to any jurisdiction. #if !defined(__CLING__) || defined(__ROOTCLING__) #include <iostream> #include <vector> #include <string_view> #include "TString.h" #include "TPCCalibration/DigitDump.h" #endif void dumpDigits(std::vector<std::string_view> fileInfos, TString outputFileName = "", int nevents = 100, float adcMin = -100, float adcMax = 1100, int firstTimeBin = 0, int lastTimeBin = 1000, float noiseThreshold = -1, TString pedestalAndNoiseFile = "", uint32_t verbosity = 0, uint32_t debugLevel = 0) { using namespace o2::tpc; DigitDump dig; dig.setDigitFileName(outputFileName.Data()); dig.setPedestalAndNoiseFile(pedestalAndNoiseFile.Data()); dig.setADCRange(adcMin, adcMax); dig.setTimeBinRange(firstTimeBin, lastTimeBin); dig.setNoiseThreshold(noiseThreshold); dig.setSkipIncompleteEvents(false); dig.checkDuplicates(true); CalibRawBase::ProcessStatus status = CalibRawBase::ProcessStatus::Ok; for (const auto& fileInfo : fileInfos) { dig.setupContainers(fileInfo.data(), verbosity, debugLevel); for (int i = 0; i < nevents; ++i) { status = dig.processEvent(i); std::cout << "Processing event " << i << " with status " << int(status) << '\n'; if (status == CalibRawBase::ProcessStatus::IncompleteEvent) { continue; } else if (status != CalibRawBase::ProcessStatus::Ok) { break; } } } }
sawenzel/AliceO2
Detectors/TPC/calibration/macro/dumpDigits.C
C++
gpl-3.0
1,981
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <!--NewPage--> <HTML> <HEAD> <!-- Generated by javadoc (build 1.6.0_34) on Thu Jan 07 14:13:59 GMT 2016 --> <TITLE> Uses of Class org.apache.fop.render.afp.AFPImageHandlerRawJPEG (Apache FOP 2.1 API) </TITLE> <META NAME="date" CONTENT="2016-01-07"> <LINK REL ="stylesheet" TYPE="text/css" HREF="../../../../../../stylesheet.css" TITLE="Style"> <SCRIPT type="text/javascript"> function windowTitle() { if (location.href.indexOf('is-external=true') == -1) { parent.document.title="Uses of Class org.apache.fop.render.afp.AFPImageHandlerRawJPEG (Apache FOP 2.1 API)"; } } </SCRIPT> <NOSCRIPT> </NOSCRIPT> </HEAD> <BODY BGCOLOR="white" onload="windowTitle();"> <HR> <!-- ========= START OF TOP NAVBAR ======= --> <A NAME="navbar_top"><!-- --></A> <A HREF="#skip-navbar_top" title="Skip navigation links"></A> <TABLE BORDER="0" WIDTH="100%" CELLPADDING="1" CELLSPACING="0" SUMMARY=""> <TR> <TD COLSPAN=2 BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A NAME="navbar_top_firstrow"><!-- --></A> <TABLE BORDER="0" CELLPADDING="0" CELLSPACING="3" SUMMARY=""> <TR ALIGN="center" VALIGN="top"> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../../overview-summary.html"><FONT CLASS="NavBarFont1"><B>Overview</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../package-summary.html"><FONT CLASS="NavBarFont1"><B>Package</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../../org/apache/fop/render/afp/AFPImageHandlerRawJPEG.html" title="class in org.apache.fop.render.afp"><FONT CLASS="NavBarFont1"><B>Class</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#FFFFFF" CLASS="NavBarCell1Rev"> &nbsp;<FONT CLASS="NavBarFont1Rev"><B>Use</B></FONT>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../package-tree.html"><FONT CLASS="NavBarFont1"><B>Tree</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../../deprecated-list.html"><FONT CLASS="NavBarFont1"><B>Deprecated</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../../index-all.html"><FONT CLASS="NavBarFont1"><B>Index</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../../help-doc.html"><FONT CLASS="NavBarFont1"><B>Help</B></FONT></A>&nbsp;</TD> </TR> </TABLE> </TD> <TD ALIGN="right" VALIGN="top" ROWSPAN=3><EM> fop 2.1</EM> </TD> </TR> <TR> <TD BGCOLOR="white" CLASS="NavBarCell2"><FONT SIZE="-2"> &nbsp;PREV&nbsp; &nbsp;NEXT</FONT></TD> <TD BGCOLOR="white" CLASS="NavBarCell2"><FONT SIZE="-2"> <A HREF="../../../../../../index.html?org/apache/fop/render/afp//class-useAFPImageHandlerRawJPEG.html" target="_top"><B>FRAMES</B></A> &nbsp; &nbsp;<A HREF="AFPImageHandlerRawJPEG.html" target="_top"><B>NO FRAMES</B></A> &nbsp; &nbsp;<SCRIPT type="text/javascript"> <!-- if(window==top) { document.writeln('<A HREF="../../../../../../allclasses-noframe.html"><B>All Classes</B></A>'); } //--> </SCRIPT> <NOSCRIPT> <A HREF="../../../../../../allclasses-noframe.html"><B>All Classes</B></A> </NOSCRIPT> </FONT></TD> </TR> </TABLE> <A NAME="skip-navbar_top"></A> <!-- ========= END OF TOP NAVBAR ========= --> <HR> <CENTER> <H2> <B>Uses of Class<br>org.apache.fop.render.afp.AFPImageHandlerRawJPEG</B></H2> </CENTER> No usage of org.apache.fop.render.afp.AFPImageHandlerRawJPEG <P> <HR> <!-- ======= START OF BOTTOM NAVBAR ====== --> <A NAME="navbar_bottom"><!-- --></A> <A HREF="#skip-navbar_bottom" title="Skip navigation links"></A> <TABLE BORDER="0" WIDTH="100%" CELLPADDING="1" CELLSPACING="0" SUMMARY=""> <TR> <TD COLSPAN=2 BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A NAME="navbar_bottom_firstrow"><!-- --></A> <TABLE BORDER="0" CELLPADDING="0" CELLSPACING="3" SUMMARY=""> <TR ALIGN="center" VALIGN="top"> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../../overview-summary.html"><FONT CLASS="NavBarFont1"><B>Overview</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../package-summary.html"><FONT CLASS="NavBarFont1"><B>Package</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../../org/apache/fop/render/afp/AFPImageHandlerRawJPEG.html" title="class in org.apache.fop.render.afp"><FONT CLASS="NavBarFont1"><B>Class</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#FFFFFF" CLASS="NavBarCell1Rev"> &nbsp;<FONT CLASS="NavBarFont1Rev"><B>Use</B></FONT>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../package-tree.html"><FONT CLASS="NavBarFont1"><B>Tree</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../../deprecated-list.html"><FONT CLASS="NavBarFont1"><B>Deprecated</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../../index-all.html"><FONT CLASS="NavBarFont1"><B>Index</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../../help-doc.html"><FONT CLASS="NavBarFont1"><B>Help</B></FONT></A>&nbsp;</TD> </TR> </TABLE> </TD> <TD ALIGN="right" VALIGN="top" ROWSPAN=3><EM> fop 2.1</EM> </TD> </TR> <TR> <TD BGCOLOR="white" CLASS="NavBarCell2"><FONT SIZE="-2"> &nbsp;PREV&nbsp; &nbsp;NEXT</FONT></TD> <TD BGCOLOR="white" CLASS="NavBarCell2"><FONT SIZE="-2"> <A HREF="../../../../../../index.html?org/apache/fop/render/afp//class-useAFPImageHandlerRawJPEG.html" target="_top"><B>FRAMES</B></A> &nbsp; &nbsp;<A HREF="AFPImageHandlerRawJPEG.html" target="_top"><B>NO FRAMES</B></A> &nbsp; &nbsp;<SCRIPT type="text/javascript"> <!-- if(window==top) { document.writeln('<A HREF="../../../../../../allclasses-noframe.html"><B>All Classes</B></A>'); } //--> </SCRIPT> <NOSCRIPT> <A HREF="../../../../../../allclasses-noframe.html"><B>All Classes</B></A> </NOSCRIPT> </FONT></TD> </TR> </TABLE> <A NAME="skip-navbar_bottom"></A> <!-- ======== END OF BOTTOM NAVBAR ======= --> <HR> Copyright 1999-2016 The Apache Software Foundation. All Rights Reserved. </BODY> </HTML>
jbampton/eclipse-cheatsheets-to-dita-to-pdf
src/libs/fop-2.1/javadocs/org/apache/fop/render/afp/class-use/AFPImageHandlerRawJPEG.html
HTML
gpl-3.0
6,183
<?php require_once dirname(__FILE__) . '/../../../src/PHPSQLParser.php'; require_once dirname(__FILE__) . '/../../../src/PHPSQLCreator.php'; require_once dirname(__FILE__) . '/../../test-more.php'; $sql = "INSERT INTO test (`name`, `test`) VALUES ('\'Superman\'', ''), ('\'Superman\'', '')"; $parser = new PHPSQLParser($sql); $creator = new PHPSQLCreator($parser->parsed); $created = $creator->created; $expected = getExpectedValue(dirname(__FILE__), 'insert1.sql', false); ok($created === $expected, 'multiple records within INSERT'); $sql = "INSERT INTO test (`name`, `test`) VALUES ('\'Superman\'', '')"; $parser = new PHPSQLParser($sql); $creator = new PHPSQLCreator($parser->parsed); $created = $creator->created; $expected = getExpectedValue(dirname(__FILE__), 'insert2.sql', false); ok($created === $expected, 'a simple INSERT statement'); $sql = "INSERT INTO test (`name`, `test`) VALUES ('\'Superman\'', ''), ('\'sdfsd\'', '')"; $parser = new PHPSQLParser($sql); $creator = new PHPSQLCreator($parser->parsed); $created = $creator->created; $expected = getExpectedValue(dirname(__FILE__), 'insert3.sql', false); ok($created === $expected, 'multiple records within INSERT (2)'); ?>
ixiom/swanhart-tools
shard-query/include/PHP-SQL-Parser/tests/cases/creator/insert.php
PHP
gpl-3.0
1,196
/* * Copyright(C) 2011-2016 Pedro H. Penna <[email protected]> * * This file is part of Nanvix. * * Nanvix is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3 of the License, or * (at your option) any later version. * * Nanvix 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 Nanvix. If not, see <http://www.gnu.org/licenses/>. */ /* * Copyright (c) 1990 The Regents of the University of California. * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * 3. All advertising materials mentioning features or use of this software * must display the following acknowledgement: * This product includes software developed by the University of * California, Berkeley and its contributors. * 4. Neither the name of the University nor the names of its contributors * may be used to endorse or promote products derived from this software * without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF * SUCH DAMAGE. */ /** * @file * * @brief rand() implementation. */ #include "rand.h" /** * @brief Generates a pseudo-random number. * * @returns A pseudo-random integer. */ int rand(void) { _next = (_next * 1103515245) + 12345; return ((_next >> 16) & 0x7fff); }
fjorgemota/nanvix
src/lib/libc/stdlib/rand.c
C
gpl-3.0
2,833
package j4; /** * @see FT47209#f47209 */ public class FT47209 { public int f47209; public FT47209(String str) {} public void m47209(int x) {} }
Niky4000/UsefulUtils
projects/others/eclipse-platform-parent/eclipse.jdt.core-master/org.eclipse.jdt.core.tests.model/workspace/JavaSearch/src/j4/FT47209.java
Java
gpl-3.0
150
/*************************************************************************** * _ _ ____ _ * Project ___| | | | _ \| | * / __| | | | |_) | | * | (__| |_| | _ <| |___ * \___|\___/|_| \_\_____| * * Copyright (C) 1998 - 2020, Daniel Stenberg, <[email protected]>, et al. * * This software is licensed as described in the file COPYING, which * you should have received as part of this distribution. The terms * are also available at https://curl.se/docs/copyright.html. * * You may opt to use, copy, modify, merge, publish, distribute and/or sell * copies of the Software, and permit persons to whom the Software is * furnished to do so, under the terms of the COPYING file. * * This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY * KIND, either express or implied. * ***************************************************************************/ /* <DESC> * FTP upload a file from memory * </DESC> */ #include <stdio.h> #include <string.h> #include <curl/curl.h> static const char data[]= "Lorem ipsum dolor sit amet, consectetur adipiscing elit. " "Nam rhoncus odio id venenatis volutpat. Vestibulum dapibus " "bibendum ullamcorper. Maecenas finibus elit augue, vel " "condimentum odio maximus nec. In hac habitasse platea dictumst. " "Vestibulum vel dolor et turpis rutrum finibus ac at nulla. " "Vivamus nec neque ac elit blandit pretium vitae maximus ipsum. " "Quisque sodales magna vel erat auctor, sed pellentesque nisi " "rhoncus. Donec vehicula maximus pretium. Aliquam eu tincidunt " "lorem."; struct WriteThis { const char *readptr; size_t sizeleft; }; static size_t read_callback(char *ptr, size_t size, size_t nmemb, void *userp) { struct WriteThis *upload = (struct WriteThis *)userp; size_t max = size*nmemb; if(max < 1) return 0; if(upload->sizeleft) { size_t copylen = max; if(copylen > upload->sizeleft) copylen = upload->sizeleft; memcpy(ptr, upload->readptr, copylen); upload->readptr += copylen; upload->sizeleft -= copylen; return copylen; } return 0; /* no more data left to deliver */ } int main(void) { CURL *curl; CURLcode res; struct WriteThis upload; upload.readptr = data; upload.sizeleft = strlen(data); /* In windows, this will init the winsock stuff */ res = curl_global_init(CURL_GLOBAL_DEFAULT); /* Check for errors */ if(res != CURLE_OK) { fprintf(stderr, "curl_global_init() failed: %s\n", curl_easy_strerror(res)); return 1; } /* get a curl handle */ curl = curl_easy_init(); if(curl) { /* First set the URL, the target file */ curl_easy_setopt(curl, CURLOPT_URL, "ftp://example.com/path/to/upload/file"); /* User and password for the FTP login */ curl_easy_setopt(curl, CURLOPT_USERPWD, "login:secret"); /* Now specify we want to UPLOAD data */ curl_easy_setopt(curl, CURLOPT_UPLOAD, 1L); /* we want to use our own read function */ curl_easy_setopt(curl, CURLOPT_READFUNCTION, read_callback); /* pointer to pass to our read function */ curl_easy_setopt(curl, CURLOPT_READDATA, &upload); /* get verbose debug output please */ curl_easy_setopt(curl, CURLOPT_VERBOSE, 1L); /* Set the expected upload size. */ curl_easy_setopt(curl, CURLOPT_INFILESIZE_LARGE, (curl_off_t)upload.sizeleft); /* Perform the request, res will get the return code */ res = curl_easy_perform(curl); /* Check for errors */ if(res != CURLE_OK) fprintf(stderr, "curl_easy_perform() failed: %s\n", curl_easy_strerror(res)); /* always cleanup */ curl_easy_cleanup(curl); } curl_global_cleanup(); return 0; }
ErikMinekus/sm-ripext
curl/docs/examples/ftpuploadfrommem.c
C
gpl-3.0
3,897
const Base = require('./base') module.exports = class extends Base {}
jmarkbrooks/shine
vendor/bundle/ruby/2.5.0/gems/webpacker-3.5.2/package/environments/test.js
JavaScript
gpl-3.0
71
# This migration comes from instedd_telemetry (originally 20150909174056) class CreateTimespans < ActiveRecord::Migration def change create_table :instedd_telemetry_timespans do |t| t.integer :period_id t.string :bucket, nullable: :false t.text :key_attributes, nullable: :false t.datetime :since, nullable: :false t.datetime :until, nullable: :false end end end
instedd/telemetry_rails
spec/dummy/db/migrate/20150909174500_create_timespans.instedd_telemetry.rb
Ruby
gpl-3.0
442
/* Stockfish, a UCI chess playing engine derived from Glaurung 2.1 Copyright (C) 2004-2008 Tord Romstad (Glaurung author) Copyright (C) 2008-2010 Marco Costalba, Joona Kiiski, Tord Romstad Stockfish is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. Stockfish 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/>. */ //// //// Includes //// #include <algorithm> #include <cassert> #include <map> #include <string> #include <sstream> #include <vector> #include "mersenne.h" #include "misc.h" #include "thread.h" #include "ucioption.h" using std::string; //// //// Local definitions //// namespace { /// /// Types /// enum OptionType { SPIN, COMBO, CHECK, STRING, BUTTON }; typedef std::vector<string> ComboValues; struct Option { string name, defaultValue, currentValue; OptionType type; size_t idx; int minValue, maxValue; ComboValues comboValues; Option(); Option(const char* defaultValue, OptionType = STRING); Option(bool defaultValue, OptionType = CHECK); Option(int defaultValue, int minValue, int maxValue); bool operator<(const Option& o) const { return this->idx < o.idx; } }; typedef std::map<string, Option> Options; /// /// Constants /// // load_defaults populates the options map with the hard // coded names and default values. void load_defaults(Options& o) { o["Use Search Log"] = Option(false); o["Search Log Filename"] = Option("SearchLog.txt"); o["Book File"] = Option("book.bin"); o["Mobility (Middle Game)"] = Option(100, 0, 200); o["Mobility (Endgame)"] = Option(100, 0, 200); o["Pawn Structure (Middle Game)"] = Option(100, 0, 200); o["Pawn Structure (Endgame)"] = Option(100, 0, 200); o["Passed Pawns (Middle Game)"] = Option(100, 0, 200); o["Passed Pawns (Endgame)"] = Option(100, 0, 200); o["Space"] = Option(100, 0, 200); o["Aggressiveness"] = Option(100, 0, 200); o["Cowardice"] = Option(100, 0, 200); o["Play Style"] = Option("Active", COMBO); o["Play Style"].comboValues.push_back("Passive"); o["Play Style"].comboValues.push_back("Solid"); o["Play Style"].comboValues.push_back("Active"); o["Play Style"].comboValues.push_back("Aggressive"); o["Play Style"].comboValues.push_back("Suicidal"); o["Play Style"].comboValues.push_back("Random"); o["Check Extension (PV nodes)"] = Option(2, 0, 2); o["Check Extension (non-PV nodes)"] = Option(1, 0, 2); o["Single Evasion Extension (PV nodes)"] = Option(2, 0, 2); o["Single Evasion Extension (non-PV nodes)"] = Option(2, 0, 2); o["Mate Threat Extension (PV nodes)"] = Option(0, 0, 2); o["Mate Threat Extension (non-PV nodes)"] = Option(0, 0, 2); o["Pawn Push to 7th Extension (PV nodes)"] = Option(1, 0, 2); o["Pawn Push to 7th Extension (non-PV nodes)"] = Option(1, 0, 2); o["Passed Pawn Extension (PV nodes)"] = Option(1, 0, 2); o["Passed Pawn Extension (non-PV nodes)"] = Option(0, 0, 2); o["Pawn Endgame Extension (PV nodes)"] = Option(2, 0, 2); o["Pawn Endgame Extension (non-PV nodes)"] = Option(2, 0, 2); o["Randomness"] = Option(0, 0, 10); o["Minimum Split Depth"] = Option(4, 4, 7); o["Maximum Number of Threads per Split Point"] = Option(5, 4, 8); o["Threads"] = Option(1, 1, MAX_THREADS); o["Hash"] = Option(32, 4, 8192); o["Clear Hash"] = Option(false, BUTTON); o["New Game"] = Option(false, BUTTON); o["Ponder"] = Option(true); o["OwnBook"] = Option(true); o["MultiPV"] = Option(1, 1, 500); o["UCI_Chess960"] = Option(false); o["UCI_AnalyseMode"] = Option(false); o["UCI_LimitStrength"] = Option(false); o["UCI_Elo"] = Option(2450, 800, 2450); // Temporary hack for 1.7.1 to be removed in next release o["Zugzwang detection"] = Option(false); // Any option should know its name so to be easily printed for (Options::iterator it = o.begin(); it != o.end(); ++it) it->second.name = it->first; } void update_play_style(); /// /// Variables /// Options options; // stringify converts a value of type T to a std::string template<typename T> string stringify(const T& v) { std::ostringstream ss; ss << v; return ss.str(); } // get_option_value implements the various get_option_value_<type> // functions defined later, because only the option value // type changes a template seems a proper solution. template<typename T> T get_option_value(const string& optionName) { T ret = T(); if (options.find(optionName) == options.end()) return ret; std::istringstream ss(options[optionName].currentValue); ss >> ret; return ret; } // Specialization for std::string where instruction 'ss >> ret;' // would erroneusly tokenize a string with spaces. template<> string get_option_value<string>(const string& optionName) { if (options.find(optionName) == options.end()) return string(); return options[optionName].currentValue; } } //// //// Functions //// /// init_uci_options() initializes the UCI options. Currently, the only /// thing this function does is to initialize the default value of the /// "Threads" parameter to the number of available CPU cores. void init_uci_options() { load_defaults(options); // Set optimal value for parameter "Minimum Split Depth" // according to number of available cores. assert(options.find("Threads") != options.end()); assert(options.find("Minimum Split Depth") != options.end()); Option& thr = options["Threads"]; Option& msd = options["Minimum Split Depth"]; thr.defaultValue = thr.currentValue = stringify(cpu_count()); if (cpu_count() >= 8) msd.defaultValue = msd.currentValue = stringify(7); } /// print_uci_options() prints all the UCI options to the standard output, /// in the format defined by the UCI protocol. void print_uci_options() { static const char optionTypeName[][16] = { "spin", "combo", "check", "string", "button" }; // Build up a vector out of the options map and sort it according to idx // field, that is the chronological insertion order in options map. std::vector<Option> vec; for (Options::const_iterator it = options.begin(); it != options.end(); ++it) vec.push_back(it->second); std::sort(vec.begin(), vec.end()); for (std::vector<Option>::const_iterator it = vec.begin(); it != vec.end(); ++it) { std::cout << "\noption name " << it->name << " type " << optionTypeName[it->type]; if (it->type == BUTTON) continue; if (it->type == CHECK) std::cout << " default " << (it->defaultValue == "1" ? "true" : "false"); else std::cout << " default " << it->defaultValue; if (it->type == SPIN) std::cout << " min " << it->minValue << " max " << it->maxValue; else if (it->type == COMBO) for (ComboValues::const_iterator itc = it->comboValues.begin(); itc != it->comboValues.end(); ++itc) std::cout << " var " << *itc; } std::cout << std::endl; } /// get_option_value_bool() returns the current value of a UCI parameter of /// type "check". bool get_option_value_bool(const string& optionName) { return get_option_value<bool>(optionName); } /// get_option_value_int() returns the value of a UCI parameter as an integer. /// Normally, this function will be used for a parameter of type "spin", but /// it could also be used with a "combo" parameter, where all the available /// values are integers. int get_option_value_int(const string& optionName) { return get_option_value<int>(optionName); } /// get_option_value_string() returns the current value of a UCI parameter as /// a string. It is used with parameters of type "combo" and "string". string get_option_value_string(const string& optionName) { return get_option_value<string>(optionName); } /// set_option_value() inserts a new value for a UCI parameter. Note that /// the function does not check that the new value is legal for the given /// parameter: This is assumed to be the responsibility of the GUI. void set_option_value(const string& name, const string& value) { // UCI protocol uses "true" and "false" instead of "1" and "0", so convert // value according to standard C++ convention before to store it. string v(value); if (v == "true") v = "1"; else if (v == "false") v = "0"; if (options.find(name) == options.end()) { std::cout << "No such option: " << name << std::endl; return; } // Normally it's up to the GUI to check for option's limits, // but we could receive the new value directly from the user // by terminal window. So let's check the bounds anyway. Option& opt = options[name]; if (opt.type == CHECK && v != "0" && v != "1") return; else if (opt.type == SPIN) { int val = atoi(v.c_str()); if (val < opt.minValue || val > opt.maxValue) return; } opt.currentValue = v; if (name == "Play Style") update_play_style(); } /// push_button() is used to tell the engine that a UCI parameter of type /// "button" has been selected: void push_button(const string& buttonName) { set_option_value(buttonName, "true"); } /// button_was_pressed() tests whether a UCI parameter of type "button" has /// been selected since the last time the function was called, in this case /// it also resets the button. bool button_was_pressed(const string& buttonName) { if (!get_option_value<bool>(buttonName)) return false; set_option_value(buttonName, "false"); return true; } namespace { // Define constructors of Option class. Option::Option() {} // To allow insertion in a std::map Option::Option(const char* def, OptionType t) : defaultValue(def), currentValue(def), type(t), idx(options.size()), minValue(0), maxValue(0) {} Option::Option(bool def, OptionType t) : defaultValue(stringify(def)), currentValue(stringify(def)), type(t), idx(options.size()), minValue(0), maxValue(0) {} Option::Option(int def, int minv, int maxv) : defaultValue(stringify(def)), currentValue(stringify(def)), type(SPIN), idx(options.size()), minValue(minv), maxValue(maxv) {} void update_play_style() { std::string playStyle = get_option_value_string("Play Style"); std::cout << "New style: " << playStyle << std::endl; if (playStyle == "Passive") { set_option_value("Mobility (Middle Game)", "40"); set_option_value("Mobility (Endgame)", "40"); set_option_value("Space", "0"); set_option_value("Cowardice", "150"); set_option_value("Aggressiveness", "40"); } else if (playStyle == "Solid") { set_option_value("Mobility (Middle Game)", "80"); set_option_value("Mobility (Endgame)", "80"); set_option_value("Space", "70"); set_option_value("Cowardice", "150"); set_option_value("Aggressiveness", "80"); } else if (playStyle == "Active") { set_option_value("Mobility (Middle Game)", "100"); set_option_value("Mobility (Endgame)", "100"); set_option_value("Space", "100"); set_option_value("Cowardice", "100"); set_option_value("Aggressiveness", "100"); } else if (playStyle == "Aggressive") { set_option_value("Mobility (Middle Game)", "120"); set_option_value("Mobility (Endgame)", "120"); set_option_value("Space", "120"); set_option_value("Cowardice", "100"); set_option_value("Aggressiveness", "150"); } else if (playStyle == "Suicidal") { set_option_value("Mobility (Middle Game)", "150"); set_option_value("Mobility (Endgame)", "150"); set_option_value("Space", "150"); set_option_value("Cowardice", "80"); set_option_value("Aggressiveness", "200"); } else if (playStyle == "Random") { std::stringstream ss; ss << (genrand_int32() % 201); std::cout << "mg mobility: " << ss.str() << std::endl; set_option_value("Mobility (Middle Game)", ss.str()); ss.clear(); ss.str(""); ss << (genrand_int32() % 201); std::cout << "eg mobility: " << ss.str() << std::endl; set_option_value("Mobility (Endgame)", ss.str()); ss.clear(); ss.str(""); ss << (genrand_int32() % 201); std::cout << "space: " << ss.str() << std::endl; set_option_value("Space", ss.str()); ss.clear(); ss.str(""); ss << (genrand_int32() % 201); std::cout << "cow: " << ss.str() << std::endl; set_option_value("Cowardice", ss.str()); ss.clear(); ss.str(""); ss << (genrand_int32() % 201); std::cout << "agg: " << ss.str() << std::endl; set_option_value("Aggressiveness", ss.str()); } } }
wireitcollege/stockfishchess-ios
OldEngine/ucioption.cpp
C++
gpl-3.0
13,279
using System; using System.Collections.Generic; using System.ComponentModel.DataAnnotations; using System.Linq; using System.Web; namespace EmployeeForm_In_Api.Models { public class EmployeeData { //public int Id { get; set; } //public string Name { get; set; } //public int DesignationId { get; set; } //public string Email { get; set; } //public Designation Designation { get; set; } [Key] public int EmployeeID { get; set; } public string EmployeeName { get; set; } public int DesignationID { get; set; } public string Email { get; set; } public Designation Designation { get; set; } } }
aamod0611/Playground
WinForms/EmployeeForm In Api(skill names added)/Models/EmployeeData.cs
C#
gpl-3.0
712
<!DOCTYPE html> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=utf-8"> <title>Live input record and playback</title> <style type='text/css'> ul { list-style: none; } #recordingslist audio { display: block; margin-bottom: 10px; } </style> </head> <body> <h1>Recorder.js simple WAV export example</h1> <p>Make sure you are using a recent version of Google Chrome.</p> <p>Also before you enable microphone input either plug in headphones or turn the volume down if you want to avoid ear splitting feedback!</p> <button onclick="startRecording(this);">record</button> <button onclick="stopRecording(this);" disabled>stop</button> <h2>Recordings</h2> <ul id="recordingslist"></ul> <h2>Log</h2> <pre id="log"></pre> <script> function __log(e, data) { log.innerHTML += "\n" + e + " " + (data || ''); } var audio_context; var recorder; function startUserMedia(stream) { var input = audio_context.createMediaStreamSource(stream); __log('Media stream created.'); // Uncomment if you want the audio to feedback directly //input.connect(audio_context.destination); //__log('Input connected to audio context destination.'); recorder = new Recorder(input); __log('Recorder initialised.'); } function startRecording(button) { recorder && recorder.record(); button.disabled = true; button.nextElementSibling.disabled = false; __log('Recording...'); } function stopRecording(button) { recorder && recorder.stop(); button.disabled = true; button.previousElementSibling.disabled = false; __log('Stopped recording.'); // create WAV download link using audio data blob createDownloadLink(); recorder.clear(); } function createDownloadLink() { recorder && recorder.exportWAV(function(blob) { var url = URL.createObjectURL(blob); var li = document.createElement('li'); var au = document.createElement('audio'); var hf = document.createElement('a'); au.controls = true; au.src = url; hf.href = url; hf.download = new Date().toISOString() + '.wav'; hf.innerHTML = hf.download; li.appendChild(au); li.appendChild(hf); recordingslist.appendChild(li); }); } window.onload = function init() { try { // webkit shim window.AudioContext = window.AudioContext || window.webkitAudioContext; navigator.getUserMedia = navigator.getUserMedia || navigator.webkitGetUserMedia; window.URL = window.URL || window.webkitURL; audio_context = new AudioContext; __log('Audio context set up.'); __log('navigator.getUserMedia ' + (navigator.getUserMedia ? 'available.' : 'not present!')); } catch (e) { alert('No web audio support in this browser!'); } navigator.getUserMedia({audio: true}, startUserMedia, function(e) { __log('No live audio input: ' + e); }); }; </script> <script src="../dist/recorder.js"></script> </body> </html>
projectPenni/penni
static/bower_components/Recorderjs/examples/example_simple_exportwav.html
HTML
gpl-3.0
3,063
#--------------------------------------------------------------------- # Function: Install Postfix # Install and configure postfix #--------------------------------------------------------------------- InstallPostfix() { echo -e "Installing postfix... \n" echo -e "Cheking and disabling sendmail...\n" if [ -f /etc/init.d/sendmail ]; then service sendmail stop update-rc.d -f sendmail remove apt-get -y remove sendmail fi echo "postfix postfix/main_mailer_type select Internet Site" | debconf-set-selections echo "postfix postfix/mailname string $CFG_HOSTNAME_FQDN" | debconf-set-selections apt-get -y install postfix postfix-mysql postfix-doc getmail4 > /dev/null 2>&1 sed -i "s/#submission inet n - - - - smtpd/submission inet n - - - - smtpd/" /etc/postfix/master.cf sed -i "s/# -o syslog_name=postfix\/submission/ -o syslog_name=postfix\/submission/" /etc/postfix/master.cf sed -i "s/# -o smtpd_tls_security_level=encrypt/ -o smtpd_tls_security_level=encrypt/" /etc/postfix/master.cf sed -i "s/# -o smtpd_sasl_auth_enable=yes/ -o smtpd_sasl_auth_enable=yes/" /etc/postfix/master.cf sed -i "s/# -o smtpd_client_restrictions=permit_sasl_authenticated,reject/ -o smtpd_client_restrictions=permit_sasl_authenticated,reject/" /etc/postfix/master.cf sed -i "s/#smtps inet n - - - - smtpd/smtps inet n - - - - smtpd/" /etc/postfix/master.cf sed -i "s/# -o syslog_name=postfix\/smtps/ -o syslog_name=postfix\/smtps/" /etc/postfix/master.cf sed -i "s/# -o smtpd_tls_wrappermode=yes/ -o smtpd_tls_wrappermode=yes/" /etc/postfix/master.cf sed -i "s/# -o smtpd_sasl_auth_enable=yes/ -o smtpd_sasl_auth_enable=yes/" /etc/postfix/master.cf sed -i "s/# -o smtpd_client_restrictions=permit_sasl_authenticated,reject/ -o smtpd_client_restrictions=permit_sasl_authenticated,reject/" /etc/postfix/master.cf service postfix restart echo -e "${green}done${NC}\n" }
wicky-info/ispconfig_setup
distros/debian7/install_postfix.sh
Shell
gpl-3.0
2,038
/* -*- c++ -*- */ /* * Copyright 2013,2015 Free Software Foundation, Inc. * * This file is part of GNU Radio * * GNU Radio is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3, or (at your option) * any later version. * * GNU Radio is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with GNU Radio; see the file COPYING. If not, write to * the Free Software Foundation, Inc., 51 Franklin Street, * Boston, MA 02110-1301, USA. */ #ifdef HAVE_CONFIG_H #include <config.h> #endif #include "histogram_sink_f_impl.h" #include <gnuradio/io_signature.h> #include <gnuradio/prefs.h> #include <string.h> #include <volk/volk.h> #include <qwt_symbol.h> namespace gr { namespace qtgui { histogram_sink_f::sptr histogram_sink_f::make(int size, int bins, double xmin, double xmax, const std::string &name, int nconnections, QWidget *parent) { return gnuradio::get_initial_sptr (new histogram_sink_f_impl(size, bins, xmin, xmax, name, nconnections, parent)); } histogram_sink_f_impl::histogram_sink_f_impl(int size, int bins, double xmin, double xmax, const std::string &name, int nconnections, QWidget *parent) : sync_block("histogram_sink_f", io_signature::make(0, nconnections, sizeof(float)), io_signature::make(0, 0, 0)), d_size(size), d_bins(bins), d_xmin(xmin), d_xmax(xmax), d_name(name), d_nconnections(nconnections), d_parent(parent) { // Required now for Qt; argc must be greater than 0 and argv // must have at least one valid character. Must be valid through // life of the qApplication: // http://harmattan-dev.nokia.com/docs/library/html/qt4/qapplication.html d_argc = 1; d_argv = new char; d_argv[0] = '\0'; d_main_gui = NULL; d_index = 0; // setup PDU handling input port message_port_register_in(pmt::mp("in")); set_msg_handler(pmt::mp("in"), boost::bind(&histogram_sink_f_impl::handle_pdus, this, _1)); // +1 for the PDU buffer for(int i = 0; i < d_nconnections+1; i++) { d_residbufs.push_back((double*)volk_malloc(d_size*sizeof(double), volk_get_alignment())); memset(d_residbufs[i], 0, d_size*sizeof(double)); } // Set alignment properties for VOLK const int alignment_multiple = volk_get_alignment() / sizeof(gr_complex); set_alignment(std::max(1,alignment_multiple)); initialize(); } histogram_sink_f_impl::~histogram_sink_f_impl() { if(!d_main_gui->isClosed()) d_main_gui->close(); // d_main_gui is a qwidget destroyed with its parent for(int i = 0; i < d_nconnections+1; i++) { volk_free(d_residbufs[i]); } delete d_argv; } bool histogram_sink_f_impl::check_topology(int ninputs, int noutputs) { return ninputs == d_nconnections; } void histogram_sink_f_impl::initialize() { if(qApp != NULL) { d_qApplication = qApp; } else { #if QT_VERSION >= 0x040500 std::string style = prefs::singleton()->get_string("qtgui", "style", "raster"); QApplication::setGraphicsSystem(QString(style.c_str())); #endif d_qApplication = new QApplication(d_argc, &d_argv); } // If a style sheet is set in the prefs file, enable it here. std::string qssfile = prefs::singleton()->get_string("qtgui","qss",""); if(qssfile.size() > 0) { QString sstext = get_qt_style_sheet(QString(qssfile.c_str())); d_qApplication->setStyleSheet(sstext); } int numplots = (d_nconnections > 0) ? d_nconnections : 1; d_main_gui = new HistogramDisplayForm(numplots, d_parent); d_main_gui->setNumBins(d_bins); d_main_gui->setNPoints(d_size); d_main_gui->setXaxis(d_xmin, d_xmax); if(d_name.size() > 0) set_title(d_name); // initialize update time to 10 times a second set_update_time(0.1); } void histogram_sink_f_impl::exec_() { d_qApplication->exec(); } QWidget* histogram_sink_f_impl::qwidget() { return d_main_gui; } #ifdef ENABLE_PYTHON PyObject* histogram_sink_f_impl::pyqwidget() { PyObject *w = PyLong_FromVoidPtr((void*)d_main_gui); PyObject *retarg = Py_BuildValue("N", w); return retarg; } #else void * histogram_sink_f_impl::pyqwidget() { return NULL; } #endif void histogram_sink_f_impl::set_y_axis(double min, double max) { d_main_gui->setYaxis(min, max); } void histogram_sink_f_impl::set_x_axis(double min, double max) { d_main_gui->setXaxis(min, max); } void histogram_sink_f_impl::set_update_time(double t) { //convert update time to ticks gr::high_res_timer_type tps = gr::high_res_timer_tps(); d_update_time = t * tps; d_main_gui->setUpdateTime(t); d_last_time = 0; } void histogram_sink_f_impl::set_title(const std::string &title) { d_main_gui->setTitle(title.c_str()); } void histogram_sink_f_impl::set_line_label(int which, const std::string &label) { d_main_gui->setLineLabel(which, label.c_str()); } void histogram_sink_f_impl::set_line_color(int which, const std::string &color) { d_main_gui->setLineColor(which, color.c_str()); } void histogram_sink_f_impl::set_line_width(int which, int width) { d_main_gui->setLineWidth(which, width); } void histogram_sink_f_impl::set_line_style(int which, int style) { d_main_gui->setLineStyle(which, (Qt::PenStyle)style); } void histogram_sink_f_impl::set_line_marker(int which, int marker) { d_main_gui->setLineMarker(which, (QwtSymbol::Style)marker); } void histogram_sink_f_impl::set_line_alpha(int which, double alpha) { d_main_gui->setMarkerAlpha(which, (int)(255.0*alpha)); } void histogram_sink_f_impl::set_size(int width, int height) { d_main_gui->resize(QSize(width, height)); } std::string histogram_sink_f_impl::title() { return d_main_gui->title().toStdString(); } std::string histogram_sink_f_impl::line_label(int which) { return d_main_gui->lineLabel(which).toStdString(); } std::string histogram_sink_f_impl::line_color(int which) { return d_main_gui->lineColor(which).toStdString(); } int histogram_sink_f_impl::line_width(int which) { return d_main_gui->lineWidth(which); } int histogram_sink_f_impl::line_style(int which) { return d_main_gui->lineStyle(which); } int histogram_sink_f_impl::line_marker(int which) { return d_main_gui->lineMarker(which); } double histogram_sink_f_impl::line_alpha(int which) { return (double)(d_main_gui->markerAlpha(which))/255.0; } void histogram_sink_f_impl::set_nsamps(const int newsize) { gr::thread::scoped_lock lock(d_setlock); if(newsize != d_size) { // Resize residbuf and replace data for(int i = 0; i < d_nconnections+1; i++) { volk_free(d_residbufs[i]); d_residbufs[i] = (double*)volk_malloc(newsize*sizeof(double), volk_get_alignment()); memset(d_residbufs[i], 0, newsize*sizeof(double)); } // Set new size and reset buffer index // (throws away any currently held data, but who cares?) d_size = newsize; d_index = 0; d_main_gui->setNPoints(d_size); } } void histogram_sink_f_impl::set_bins(const int bins) { gr::thread::scoped_lock lock(d_setlock); d_bins = bins; d_main_gui->setNumBins(d_bins); } int histogram_sink_f_impl::nsamps() const { return d_size; } int histogram_sink_f_impl::bins() const { return d_bins; } void histogram_sink_f_impl::npoints_resize() { int newsize = d_main_gui->getNPoints(); set_nsamps(newsize); } void histogram_sink_f_impl::enable_menu(bool en) { d_main_gui->enableMenu(en); } void histogram_sink_f_impl::enable_grid(bool en) { d_main_gui->setGrid(en); } void histogram_sink_f_impl::enable_autoscale(bool en) { d_main_gui->autoScale(en); } void histogram_sink_f_impl::enable_semilogx(bool en) { d_main_gui->setSemilogx(en); } void histogram_sink_f_impl::enable_semilogy(bool en) { d_main_gui->setSemilogy(en); } void histogram_sink_f_impl::enable_accumulate(bool en) { d_main_gui->setAccumulate(en); } void histogram_sink_f_impl::disable_legend() { d_main_gui->disableLegend(); } void histogram_sink_f_impl::autoscalex() { d_main_gui->autoScaleX(); } void histogram_sink_f_impl::reset() { d_index = 0; } int histogram_sink_f_impl::work(int noutput_items, gr_vector_const_void_star &input_items, gr_vector_void_star &output_items) { int n=0, j=0, idx=0; const float *in = (const float*)input_items[idx]; npoints_resize(); for(int i=0; i < noutput_items; i+=d_size) { unsigned int datasize = noutput_items - i; unsigned int resid = d_size-d_index; idx = 0; // If we have enough input for one full plot, do it if(datasize >= resid) { // Fill up residbufs with d_size number of items for(n = 0; n < d_nconnections; n++) { in = (const float*)input_items[idx++]; volk_32f_convert_64f_u(&d_residbufs[n][d_index], &in[j], resid); } // Update the plot if its time if(gr::high_res_timer_now() - d_last_time > d_update_time) { d_last_time = gr::high_res_timer_now(); d_qApplication->postEvent(d_main_gui, new HistogramUpdateEvent(d_residbufs, d_size)); } d_index = 0; j += resid; } // Otherwise, copy what we received into the residbufs for next time // because we set the output_multiple, this should never need to be called else { for(n = 0; n < d_nconnections; n++) { in = (const float*)input_items[idx++]; volk_32f_convert_64f_u(&d_residbufs[n][d_index], &in[j], datasize); } d_index += datasize; j += datasize; } } return j; } void histogram_sink_f_impl::handle_pdus(pmt::pmt_t msg) { size_t len; pmt::pmt_t dict, samples; // Test to make sure this is either a PDU or a uniform vector of // samples. Get the samples PMT and the dictionary if it's a PDU. // If not, we throw an error and exit. if(pmt::is_pair(msg)) { dict = pmt::car(msg); samples = pmt::cdr(msg); } else if(pmt::is_uniform_vector(msg)) { samples = msg; } else { throw std::runtime_error("time_sink_c: message must be either " "a PDU or a uniform vector of samples."); } len = pmt::length(samples); const float *in; if(pmt::is_f32vector(samples)) { in = (const float*)pmt::f32vector_elements(samples, len); } else { throw std::runtime_error("histogram_sink_f: unknown data type " "of samples; must be float."); } // Plot if we're past the last update time if(gr::high_res_timer_now() - d_last_time > d_update_time) { d_last_time = gr::high_res_timer_now(); npoints_resize(); // Clear the histogram if(!d_main_gui->getAccumulate()) { d_qApplication->postEvent(d_main_gui, new HistogramClearEvent()); // Set to accumulate over length of the current PDU d_qApplication->postEvent(d_main_gui, new HistogramSetAccumulator(true)); } float nplots_f = static_cast<float>(len) / static_cast<float>(d_size); int nplots = static_cast<int>(ceilf(nplots_f)); int idx = 0; for(int n = 0; n < nplots; n++) { int size = std::min(d_size, (int)(len - idx)); volk_32f_convert_64f_u(d_residbufs[d_nconnections], &in[idx], size); d_qApplication->postEvent(d_main_gui, new HistogramUpdateEvent(d_residbufs, size)); idx += size; } if(!d_main_gui->getAccumulate()) { // Turn accumulation off d_qApplication->postEvent(d_main_gui, new HistogramSetAccumulator(false)); } } } } /* namespace qtgui */ } /* namespace gr */
analogdevicesinc/gnuradio
gr-qtgui/lib/histogram_sink_f_impl.cc
C++
gpl-3.0
13,407
----------------------------------------- -- Spell: Blind ----------------------------------------- require("scripts/globals/status"); require("scripts/globals/magic"); require("scripts/globals/msg"); ----------------------------------------- function onMagicCastingCheck(caster,target,spell) return 0; end; function onSpellCast(caster,target,spell) -- Pull base stats. local dINT = (caster:getStat(MOD_INT) - target:getStat(MOD_MND)); --blind uses caster INT vs target MND -- Base power. May need more research. local power = math.floor(dINT * 9/40) + 23; if (power < 5) then power = 5; end if (power > 50) then power = 50; end if (caster:hasStatusEffect(EFFECT_SABOTEUR)) then power = power * 2; end -- Duration, including resistance. Unconfirmed. local duration = 180; local params = {}; params.diff = nil; params.attribute = MOD_INT; params.skillType = 35; params.bonus = 0; params.effect = EFFECT_BLINDNESS; duration = duration * applyResistanceEffect(caster, target, spell, params); if (duration >= 60) then --Do it! if (caster:hasStatusEffect(EFFECT_SABOTEUR)) then duration = duration * 2; end caster:delStatusEffect(EFFECT_SABOTEUR); if (target:addStatusEffect(EFFECT_BLINDNESS,power,0,duration)) then spell:setMsg(msgBasic.MAGIC_ENFEEB_IS); else spell:setMsg(msgBasic.MAGIC_NO_EFFECT); end else spell:setMsg(msgBasic.MAGIC_RESIST); end return EFFECT_BLINDNESS; end;
gedads/Neodynamis
scripts/globals/spells/blind.lua
Lua
gpl-3.0
1,586
// // Copyright(c) 2009 Syntext, Inc. All Rights Reserved. // Contact: [email protected], http://www.syntext.com // // This file is part of Syntext Serna XML Editor. // // COMMERCIAL USAGE // Licensees holding valid Syntext Serna commercial licenses may use this file // in accordance with the Syntext Serna Commercial License Agreement provided // with the software, or, alternatively, in accorance with the terms contained // in a written agreement between you and Syntext, Inc. // // GNU GENERAL PUBLIC LICENSE USAGE // Alternatively, this file may be used under the terms of the GNU General // Public License versions 2.0 or 3.0 as published by the Free Software // Foundation and appearing in the file LICENSE.GPL included in the packaging // of this file. In addition, as a special exception, Syntext, Inc. gives you // certain additional rights, which are described in the Syntext, Inc. GPL // Exception for Syntext Serna Free Edition, included in the file // GPL_EXCEPTION.txt in this package. // // You should have received a copy of appropriate licenses along with this // package. If not, see <http://www.syntext.com/legal/>. If you are unsure // which license is appropriate for your use, please contact the sales // department at [email protected]. // // This file is provided AS IS with NO WARRANTY OF ANY KIND, INCLUDING THE // WARRANTY OF DESIGN, MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. // #ifndef UI_QT_TAB_WIDGET_H_ #define UI_QT_TAB_WIDGET_H_ #include "ui/ui_defs.h" #include "ui/UiProps.h" #include "ui/UiItems.h" #include "ui/UiStackItem.h" #include <QTabWidget> #include <QTabBar> #include <QToolBox> #include <QPointer> #include <QEvent> #include <map> namespace Sui { class QtToolBox : public StackItem { public: QtToolBox(PropertyNode* properties); virtual ~QtToolBox(); virtual String itemClass() const { return TOOL_BOX; } virtual String widgetClass() const { return SIMPLE_WIDGET; } virtual StackWidget* stackWidget() const { return stackWidget_; } protected: StackWidget* stackWidget_; }; //////////////////////////////////////////////////////////////////////// class QtToolWidget : public QToolBox, public StackWidget, protected Common::PropertyNodeWatcher { Q_OBJECT public: QtToolWidget(StackItem*); virtual void insertItem(const Item* item); virtual void removeItem(const Item* item); virtual void setCurrent(Item* item); virtual void setItemVisible(bool isVisible) { setVisible(isVisible); } virtual QWidget* widget(const Item* item) const; public slots: void currentChanged(int idx); private: Item* itemAt(QWidget* page) const; //! Property modifications virtual void propertyChanged(Common::PropertyNode* property); private: typedef std::map<const Item*, QWidget*> ItemMap; ItemMap itemMap_; }; //////////////////////////////////////////////////////////////////////// class QtTabItem : public StackItem { public: QtTabItem(PropertyNode* properties); virtual ~QtTabItem(); virtual String itemClass() const { return TAB_ITEM; } virtual String widgetClass() const { return SIMPLE_WIDGET; } virtual StackWidget* stackWidget() const { return stackWidget_; } protected: StackWidget* stackWidget_; }; //////////////////////////////////////////////////////////////////////// class QtTabWidget : public QTabWidget, public StackWidget, protected Common::PropertyNodeWatcher { Q_OBJECT public: QtTabWidget(StackItem*, Common::PropertyNode* properties); virtual void insertItem(const Item* item); virtual void removeItem(const Item* item); virtual void setCurrent(Item* item); virtual void setItemVisible(bool isVisible) { setVisible(isVisible); } virtual QWidget* widget(const Item* item) const; public slots: void currentChanged(int idx); void showTabContextMenu(const QPoint& pos); protected: virtual void tabRemoved(int); virtual void propertyChanged(Common::PropertyNode* property); virtual void itemPropertyChanged(Common::PropertyNode* property); private: Item* itemAt(int idx) const; }; class QTabContextMenuProvider : public QObject { Q_OBJECT public: QTabContextMenuProvider(QTabBar* tabBar, QObject* parent); signals: void showTabContextMenu(const QPoint&); private: virtual bool eventFilter(QObject* receiver, QEvent* event); QPointer<QTabBar> tabBar_; }; } // namespace Sui #endif // UI_QT_TAB_WIDGET_H
malaterre/serna-free-backup
sfworks/ui/impl/qt/QtTabWidget.h
C
gpl-3.0
4,787
/* ** FAAD2 - Freeware Advanced Audio (AAC) Decoder including SBR and PS decoding ** Copyright (C) 2003-2004 M. Bakker, Ahead Software AG, http://www.nero.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., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. ** ** Any non-GPL usage of this software or parts of this software is strictly ** forbidden. ** ** Commercial non-GPL licensing of this software is possible. ** For more info contact Ahead Software through [email protected]. ** ** $Id: drm_dec.c 29306 2009-05-13 15:22:13Z bircoph $ **/ #include <stdlib.h> #include <stdio.h> #include <string.h> #include <math.h> #include "common.h" #ifdef DRM #include "sbr_dec.h" #include "drm_dec.h" #include "bits.h" /* constants */ #define DECAY_CUTOFF 3 #define DECAY_SLOPE 0.05f /* type definitaions */ typedef const int8_t (*drm_ps_huff_tab)[2]; /* binary search huffman tables */ static const int8_t f_huffman_sa[][2] = { { /*0*/ -15, 1 }, /* index 0: 1 bits: x */ { 2, 3 }, /* index 1: 2 bits: 1x */ { /*7*/ -8, 4 }, /* index 2: 3 bits: 10x */ { 5, 6 }, /* index 3: 3 bits: 11x */ { /*1*/ -14, /*-1*/ -16 }, /* index 4: 4 bits: 101x */ { /*-2*/ -17, 7 }, /* index 5: 4 bits: 110x */ { 8, 9 }, /* index 6: 4 bits: 111x */ { /*2*/ -13, /*-3*/ -18 }, /* index 7: 5 bits: 1101x */ { /*3*/ -12, 10 }, /* index 8: 5 bits: 1110x */ { 11, 12 }, /* index 9: 5 bits: 1111x */ { /*4*/ -11, /*5*/ -10 }, /* index 10: 6 bits: 11101x */ { /*-4*/ -19, /*-5*/ -20 }, /* index 11: 6 bits: 11110x */ { /*6*/ -9, 13 }, /* index 12: 6 bits: 11111x */ { /*-7*/ -22, /*-6*/ -21 } /* index 13: 7 bits: 111111x */ }; static const int8_t t_huffman_sa[][2] = { { /*0*/ -15, 1 }, /* index 0: 1 bits: x */ { 2, 3 }, /* index 1: 2 bits: 1x */ { /*-1*/ -16, /*1*/ -14 }, /* index 2: 3 bits: 10x */ { 4, 5 }, /* index 3: 3 bits: 11x */ { /*-2*/ -17, /*2*/ -13 }, /* index 4: 4 bits: 110x */ { 6, 7 }, /* index 5: 4 bits: 111x */ { /*-3*/ -18, /*3*/ -12 }, /* index 6: 5 bits: 1110x */ { 8, 9 }, /* index 7: 5 bits: 1111x */ { /*-4*/ -19, /*4*/ -11 }, /* index 8: 6 bits: 11110x */ { 10, 11 }, /* index 9: 6 bits: 11111x */ { /*-5*/ -20, /*5*/ -10 }, /* index 10: 7 bits: 111110x */ { /*-6*/ -21, 12 }, /* index 11: 7 bits: 111111x */ { /*-7*/ -22, 13 }, /* index 12: 8 bits: 1111111x */ { /*6*/ -9, /*7*/ -8 } /* index 13: 9 bits: 11111111x */ }; static const int8_t f_huffman_pan[][2] = { { /*0*/ -15, 1 }, /* index 0: 1 bits: x */ { /*-1*/ -16, 2 }, /* index 1: 2 bits: 1x */ { /*1*/ -14, 3 }, /* index 2: 3 bits: 11x */ { 4, 5 }, /* index 3: 4 bits: 111x */ { /*-2*/ -17, /*2*/ -13 }, /* index 4: 5 bits: 1110x */ { 6, 7 }, /* index 5: 5 bits: 1111x */ { /*-3*/ -18, /*3*/ -12 }, /* index 6: 6 bits: 11110x */ { 8, 9 }, /* index 7: 6 bits: 11111x */ { /*-4*/ -19, /*4*/ -11 }, /* index 8: 7 bits: 111110x */ { 10, 11 }, /* index 9: 7 bits: 111111x */ { /*-5*/ -20, /*5*/ -10 }, /* index 10: 8 bits: 1111110x */ { 12, 13 }, /* index 11: 8 bits: 1111111x */ { /*-6*/ -21, /*6*/ -9 }, /* index 12: 9 bits: 11111110x */ { /*-7*/ -22, 14 }, /* index 13: 9 bits: 11111111x */ { /*7*/ -8, 15 }, /* index 14: 10 bits: 111111111x */ { 16, 17 }, /* index 15: 11 bits: 1111111111x */ { /*-8*/ -23, /*8*/ -7 }, /* index 16: 12 bits: 11111111110x */ { 18, 19 }, /* index 17: 12 bits: 11111111111x */ { /*-10*/ -25, 20 }, /* index 18: 13 bits: 111111111110x */ { 21, 22 }, /* index 19: 13 bits: 111111111111x */ { /*-9*/ -24, /*9*/ -6 }, /* index 20: 14 bits: 1111111111101x */ { /*10*/ -5, 23 }, /* index 21: 14 bits: 1111111111110x */ { 24, 25 }, /* index 22: 14 bits: 1111111111111x */ { /*-13*/ -28, /*-11*/ -26 }, /* index 23: 15 bits: 11111111111101x */ { /*11*/ -4, /*13*/ -2 }, /* index 24: 15 bits: 11111111111110x */ { 26, 27 }, /* index 25: 15 bits: 11111111111111x */ { /*-14*/ -29, /*-12*/ -27 }, /* index 26: 16 bits: 111111111111110x */ { /*12*/ -3, /*14*/ -1 } /* index 27: 16 bits: 111111111111111x */ }; static const int8_t t_huffman_pan[][2] = { { /*0*/ -15, 1 }, /* index 0: 1 bits: x */ { /*-1*/ -16, 2 }, /* index 1: 2 bits: 1x */ { /*1*/ -14, 3 }, /* index 2: 3 bits: 11x */ { /*-2*/ -17, 4 }, /* index 3: 4 bits: 111x */ { /*2*/ -13, 5 }, /* index 4: 5 bits: 1111x */ { /*-3*/ -18, 6 }, /* index 5: 6 bits: 11111x */ { /*3*/ -12, 7 }, /* index 6: 7 bits: 111111x */ { /*-4*/ -19, 8 }, /* index 7: 8 bits: 1111111x */ { /*4*/ -11, 9 }, /* index 8: 9 bits: 11111111x */ { 10, 11 }, /* index 9: 10 bits: 111111111x */ { /*-5*/ -20, /*5*/ -10 }, /* index 10: 11 bits: 1111111110x */ { 12, 13 }, /* index 11: 11 bits: 1111111111x */ { /*-6*/ -21, /*6*/ -9 }, /* index 12: 12 bits: 11111111110x */ { 14, 15 }, /* index 13: 12 bits: 11111111111x */ { /*-7*/ -22, /*7*/ -8 }, /* index 14: 13 bits: 111111111110x */ { 16, 17 }, /* index 15: 13 bits: 111111111111x */ { /*-8*/ -23, /*8*/ -7 }, /* index 16: 14 bits: 1111111111110x */ { 18, 19 }, /* index 17: 14 bits: 1111111111111x */ { /*-10*/ -25, /*10*/ -5 }, /* index 18: 15 bits: 11111111111110x */ { 20, 21 }, /* index 19: 15 bits: 11111111111111x */ { /*-9*/ -24, /*9*/ -6 }, /* index 20: 16 bits: 111111111111110x */ { 22, 23 }, /* index 21: 16 bits: 111111111111111x */ { 24, 25 }, /* index 22: 17 bits: 1111111111111110x */ { 26, 27 }, /* index 23: 17 bits: 1111111111111111x */ { /*-14*/ -29, /*-13*/ -28 }, /* index 24: 18 bits: 11111111111111100x */ { /*-12*/ -27, /*-11*/ -26 }, /* index 25: 18 bits: 11111111111111101x */ { /*11*/ -4, /*12*/ -3 }, /* index 26: 18 bits: 11111111111111110x */ { /*13*/ -2, /*14*/ -1 } /* index 27: 18 bits: 11111111111111111x */ }; /* There are 3 classes in the standard but the last 2 are identical */ static const real_t sa_quant[8][2] = { { FRAC_CONST(0.0000), FRAC_CONST(0.0000) }, { FRAC_CONST(0.0501), FRAC_CONST(0.1778) }, { FRAC_CONST(0.0706), FRAC_CONST(0.2818) }, { FRAC_CONST(0.0995), FRAC_CONST(0.4467) }, { FRAC_CONST(0.1399), FRAC_CONST(0.5623) }, { FRAC_CONST(0.1957), FRAC_CONST(0.7079) }, { FRAC_CONST(0.2713), FRAC_CONST(0.8913) }, { FRAC_CONST(0.3699), FRAC_CONST(1.0000) }, }; /* We don't need the actual quantizer values */ #if 0 static const real_t pan_quant[8][5] = { { COEF_CONST(0.0000), COEF_CONST(0.0000), COEF_CONST(0.0000), COEF_CONST(0.0000), COEF_CONST(0.0000) }, { COEF_CONST(0.1661), COEF_CONST(0.1661), COEF_CONST(0.3322), COEF_CONST(0.3322), COEF_CONST(0.3322) }, { COEF_CONST(0.3322), COEF_CONST(0.3322), COEF_CONST(0.6644), COEF_CONST(0.8305), COEF_CONST(0.8305) }, { COEF_CONST(0.4983), COEF_CONST(0.6644), COEF_CONST(0.9966), COEF_CONST(1.4949), COEF_CONST(1.6610) }, { COEF_CONST(0.6644), COEF_CONST(0.9966), COEF_CONST(1.4949), COEF_CONST(2.1593), COEF_CONST(2.4914) }, { COEF_CONST(0.8305), COEF_CONST(1.3288), COEF_CONST(2.1593), COEF_CONST(2.9897), COEF_CONST(3.4880) }, { COEF_CONST(0.9966), COEF_CONST(1.8271), COEF_CONST(2.8236), COEF_CONST(3.8202), COEF_CONST(4.6507) }, { COEF_CONST(1.3288), COEF_CONST(2.3253), COEF_CONST(3.4880), COEF_CONST(4.6507), COEF_CONST(5.8134) }, }; #endif /* 2^(pan_quant[x][y] */ static const real_t pan_pow_2_pos[8][5] = { { REAL_CONST(1.0000000), REAL_CONST(1.0000000), REAL_CONST(1.0000000), REAL_CONST(1.0000000), REAL_CONST(1.0000000) }, { REAL_CONST(1.1220021), REAL_CONST(1.1220021), REAL_CONST(1.2589312), REAL_CONST(1.2589312), REAL_CONST(1.2589312) }, { REAL_CONST(1.2589312), REAL_CONST(1.2589312), REAL_CONST(1.5849090), REAL_CONST(1.7783016), REAL_CONST(1.7783016) }, { REAL_CONST(1.4125481), REAL_CONST(1.5849090), REAL_CONST(1.9952921), REAL_CONST(2.8184461), REAL_CONST(3.1623565) }, { REAL_CONST(1.5849090), REAL_CONST(1.9952922), REAL_CONST(2.8184461), REAL_CONST(4.4669806), REAL_CONST(5.6232337) }, { REAL_CONST(1.7783016), REAL_CONST(2.5119365), REAL_CONST(4.4669806), REAL_CONST(7.9430881), REAL_CONST(11.219994) }, { REAL_CONST(1.9952921), REAL_CONST(3.5482312), REAL_CONST(7.0792671), REAL_CONST(14.125206), REAL_CONST(25.118876) }, { REAL_CONST(2.5119365), REAL_CONST(5.0116998), REAL_CONST(11.219994), REAL_CONST(25.118876), REAL_CONST(56.235140) } }; /* 2^(-pan_quant[x][y] */ static const real_t pan_pow_2_neg[8][5] = { { REAL_CONST(1), REAL_CONST(1), REAL_CONST(1), REAL_CONST(1), REAL_CONST(1) }, { REAL_CONST(0.8912487), REAL_CONST(0.8912487), REAL_CONST(0.7943242), REAL_CONST(0.7943242), REAL_CONST(0.7943242) }, { REAL_CONST(0.7943242), REAL_CONST(0.7943242), REAL_CONST(0.6309511), REAL_CONST(0.5623344), REAL_CONST(0.5623344) }, { REAL_CONST(0.7079405), REAL_CONST(0.6309511), REAL_CONST(0.5011797), REAL_CONST(0.3548054), REAL_CONST(0.3162199) }, { REAL_CONST(0.6309511), REAL_CONST(0.5011797), REAL_CONST(0.3548054), REAL_CONST(0.2238649), REAL_CONST(0.1778336) }, { REAL_CONST(0.5623343), REAL_CONST(0.3980992), REAL_CONST(0.2238649), REAL_CONST(0.1258956), REAL_CONST(0.0891266) }, { REAL_CONST(0.5011797), REAL_CONST(0.2818306), REAL_CONST(0.1412576), REAL_CONST(0.0707954), REAL_CONST(0.0398107) }, { REAL_CONST(0.3980992), REAL_CONST(0.1995331), REAL_CONST(0.0891267), REAL_CONST(0.0398107), REAL_CONST(0.0177825) } }; /* 2^(pan_quant[x][y]/30) */ static const real_t pan_pow_2_30_pos[8][5] = { { COEF_CONST(1), COEF_CONST(1), COEF_CONST(1), COEF_CONST(1), COEF_CONST(1) }, { COEF_CONST(1.003845098), COEF_CONST(1.003845098), COEF_CONST(1.007704982), COEF_CONST(1.007704982), COEF_CONST(1.007704982) }, { COEF_CONST(1.007704982), COEF_CONST(1.007704982), COEF_CONST(1.01546933), COEF_CONST(1.019373909), COEF_CONST(1.019373909) }, { COEF_CONST(1.011579706), COEF_CONST(1.01546933), COEF_CONST(1.023293502), COEF_CONST(1.035142941), COEF_CONST(1.039123167) }, { COEF_CONST(1.01546933), COEF_CONST(1.023293502), COEF_CONST(1.035142941), COEF_CONST(1.051155908), COEF_CONST(1.059252598) }, { COEF_CONST(1.019373909), COEF_CONST(1.03117796), COEF_CONST(1.051155908), COEF_CONST(1.071518432), COEF_CONST(1.0839263) }, { COEF_CONST(1.023293502), COEF_CONST(1.043118698), COEF_CONST(1.067414119), COEF_CONST(1.092277933), COEF_CONST(1.113439626) }, { COEF_CONST(1.03117796), COEF_CONST(1.055195268), COEF_CONST(1.0839263), COEF_CONST(1.113439626), COEF_CONST(1.143756546) } }; /* 2^(-pan_quant[x][y]/30) */ static const real_t pan_pow_2_30_neg[8][5] = { { COEF_CONST(1), COEF_CONST(1), COEF_CONST(1), COEF_CONST(1), COEF_CONST(1) }, { COEF_CONST(0.99616963), COEF_CONST(0.99616963), COEF_CONST(0.992353931), COEF_CONST(0.992353931), COEF_CONST(0.99235393) }, { COEF_CONST(0.992353931), COEF_CONST(0.992353931), COEF_CONST(0.984766325), COEF_CONST(0.980994305), COEF_CONST(0.980994305) }, { COEF_CONST(0.988552848), COEF_CONST(0.984766325), COEF_CONST(0.977236734), COEF_CONST(0.966050157), COEF_CONST(0.962349827) }, { COEF_CONST(0.984766325), COEF_CONST(0.977236734), COEF_CONST(0.966050157), COEF_CONST(0.951333663), COEF_CONST(0.944061881) }, { COEF_CONST(0.980994305), COEF_CONST(0.969764715), COEF_CONST(0.951333663), COEF_CONST(0.933255062), COEF_CONST(0.922571949) }, { COEF_CONST(0.977236734), COEF_CONST(0.958663671), COEF_CONST(0.936843519), COEF_CONST(0.915517901), COEF_CONST(0.898117847) }, { COEF_CONST(0.969764715), COEF_CONST(0.947691892), COEF_CONST(0.922571949), COEF_CONST(0.898117847), COEF_CONST(0.874311936) } }; static const real_t g_decayslope[MAX_SA_BAND] = { FRAC_CONST(1), FRAC_CONST(1), FRAC_CONST(1), FRAC_CONST(0.95),FRAC_CONST(0.9), FRAC_CONST(0.85), FRAC_CONST(0.8), FRAC_CONST(0.75),FRAC_CONST(0.7), FRAC_CONST(0.65),FRAC_CONST(0.6), FRAC_CONST(0.55),FRAC_CONST(0.5), FRAC_CONST(0.45), FRAC_CONST(0.4), FRAC_CONST(0.35),FRAC_CONST(0.3), FRAC_CONST(0.25),FRAC_CONST(0.2), FRAC_CONST(0.15), FRAC_CONST(0.1), FRAC_CONST(0.05),FRAC_CONST(0), FRAC_CONST(0), FRAC_CONST(0), FRAC_CONST(0), FRAC_CONST(0), FRAC_CONST(0), FRAC_CONST(0), FRAC_CONST(0), FRAC_CONST(0), FRAC_CONST(0), FRAC_CONST(0), FRAC_CONST(0), FRAC_CONST(0), FRAC_CONST(0), FRAC_CONST(0), FRAC_CONST(0), FRAC_CONST(0), FRAC_CONST(0), FRAC_CONST(0), FRAC_CONST(0), FRAC_CONST(0), FRAC_CONST(0), FRAC_CONST(0) }; static const real_t sa_sqrt_1_minus[8][2] = { { FRAC_CONST(1), FRAC_CONST(1) }, { FRAC_CONST(0.998744206), FRAC_CONST(0.984066644) }, { FRAC_CONST(0.997504707), FRAC_CONST(0.959473168) }, { FRAC_CONST(0.995037562), FRAC_CONST(0.894683804) }, { FRAC_CONST(0.990165638), FRAC_CONST(0.826933317) }, { FRAC_CONST(0.980663811), FRAC_CONST(0.706312672) }, { FRAC_CONST(0.962494836), FRAC_CONST(0.45341406) }, { FRAC_CONST(0.929071574), FRAC_CONST(0) } }; static const uint8_t sa_freq_scale[9][2] = { { 0, 0}, { 1, 1}, { 2, 2}, { 3, 3}, { 5, 5}, { 7, 7}, {10,10}, {13,13}, {46,23} }; static const uint8_t pan_freq_scale[21] = { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 18, 22, 26, 32, 64 }; static const uint8_t pan_quant_class[20] = { 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 2, 2, 2, 2, 3, 3, 3, 4, 4, 4 }; /* Inverse mapping lookup */ static const uint8_t pan_inv_freq[64] = { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 15, 15, 16, 16, 16, 16, 17, 17, 17, 17, 18, 18, 18, 18, 18, 18, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19 }; static const uint8_t sa_inv_freq[MAX_SA_BAND] = { 0, 1, 2, 3, 3, 4, 4, 5, 5, 5, 6, 6, 6, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7 }; static const real_t filter_coeff[] = { FRAC_CONST(0.65143905754106), FRAC_CONST(0.56471812200776), FRAC_CONST(0.48954165955695) }; static const uint8_t delay_length[][2] = { { 1, 3 }, { 2, 4 }, { 3, 5 } }; static const real_t delay_fraction[] = { FRAC_CONST(0.43), FRAC_CONST(0.75), FRAC_CONST(0.347) }; static const real_t peak_decay[2] = { FRAC_CONST(0.58664621951003), FRAC_CONST(0.76592833836465) }; static const real_t smooth_coeff[2] = { FRAC_CONST(0.6), FRAC_CONST(0.25) }; /* Please note that these are the same tables as in plain PS */ static const complex_t Q_Fract_allpass_Qmf[][3] = { { { FRAC_CONST(0.7804303765), FRAC_CONST(0.6252426505) }, { FRAC_CONST(0.3826834261), FRAC_CONST(0.9238795042) }, { FRAC_CONST(0.8550928831), FRAC_CONST(0.5184748173) } }, { { FRAC_CONST(-0.4399392009), FRAC_CONST(0.8980275393) }, { FRAC_CONST(-0.9238795042), FRAC_CONST(-0.3826834261) }, { FRAC_CONST(-0.0643581524), FRAC_CONST(0.9979268909) } }, { { FRAC_CONST(-0.9723699093), FRAC_CONST(-0.2334454209) }, { FRAC_CONST(0.9238795042), FRAC_CONST(-0.3826834261) }, { FRAC_CONST(-0.9146071672), FRAC_CONST(0.4043435752) } }, { { FRAC_CONST(0.0157073960), FRAC_CONST(-0.9998766184) }, { FRAC_CONST(-0.3826834261), FRAC_CONST(0.9238795042) }, { FRAC_CONST(-0.7814115286), FRAC_CONST(-0.6240159869) } }, { { FRAC_CONST(0.9792228341), FRAC_CONST(-0.2027871907) }, { FRAC_CONST(-0.3826834261), FRAC_CONST(-0.9238795042) }, { FRAC_CONST(0.1920081824), FRAC_CONST(-0.9813933372) } }, { { FRAC_CONST(0.4115142524), FRAC_CONST(0.9114032984) }, { FRAC_CONST(0.9238795042), FRAC_CONST(0.3826834261) }, { FRAC_CONST(0.9589683414), FRAC_CONST(-0.2835132182) } }, { { FRAC_CONST(-0.7996847630), FRAC_CONST(0.6004201174) }, { FRAC_CONST(-0.9238795042), FRAC_CONST(0.3826834261) }, { FRAC_CONST(0.6947838664), FRAC_CONST(0.7192186117) } }, { { FRAC_CONST(-0.7604058385), FRAC_CONST(-0.6494481564) }, { FRAC_CONST(0.3826834261), FRAC_CONST(-0.9238795042) }, { FRAC_CONST(-0.3164770305), FRAC_CONST(0.9486001730) } }, { { FRAC_CONST(0.4679299891), FRAC_CONST(-0.8837655187) }, { FRAC_CONST(0.3826834261), FRAC_CONST(0.9238795042) }, { FRAC_CONST(-0.9874414206), FRAC_CONST(0.1579856575) } }, { { FRAC_CONST(0.9645573497), FRAC_CONST(0.2638732493) }, { FRAC_CONST(-0.9238795042), FRAC_CONST(-0.3826834261) }, { FRAC_CONST(-0.5966450572), FRAC_CONST(-0.8025052547) } }, { { FRAC_CONST(-0.0471066870), FRAC_CONST(0.9988898635) }, { FRAC_CONST(0.9238795042), FRAC_CONST(-0.3826834261) }, { FRAC_CONST(0.4357025325), FRAC_CONST(-0.9000906944) } }, { { FRAC_CONST(-0.9851093888), FRAC_CONST(0.1719288528) }, { FRAC_CONST(-0.3826834261), FRAC_CONST(0.9238795042) }, { FRAC_CONST(0.9995546937), FRAC_CONST(-0.0298405960) } }, { { FRAC_CONST(-0.3826831877), FRAC_CONST(-0.9238796234) }, { FRAC_CONST(-0.3826834261), FRAC_CONST(-0.9238795042) }, { FRAC_CONST(0.4886211455), FRAC_CONST(0.8724960685) } }, { { FRAC_CONST(0.8181498647), FRAC_CONST(-0.5750049949) }, { FRAC_CONST(0.9238795042), FRAC_CONST(0.3826834261) }, { FRAC_CONST(-0.5477093458), FRAC_CONST(0.8366686702) } }, { { FRAC_CONST(0.7396308780), FRAC_CONST(0.6730127335) }, { FRAC_CONST(-0.9238795042), FRAC_CONST(0.3826834261) }, { FRAC_CONST(-0.9951074123), FRAC_CONST(-0.0987988561) } }, { { FRAC_CONST(-0.4954589605), FRAC_CONST(0.8686313629) }, { FRAC_CONST(0.3826834261), FRAC_CONST(-0.9238795042) }, { FRAC_CONST(-0.3725017905), FRAC_CONST(-0.9280315042) } }, { { FRAC_CONST(-0.9557929039), FRAC_CONST(-0.2940406799) }, { FRAC_CONST(0.3826834261), FRAC_CONST(0.9238795042) }, { FRAC_CONST(0.6506417990), FRAC_CONST(-0.7593847513) } }, { { FRAC_CONST(0.0784594864), FRAC_CONST(-0.9969173074) }, { FRAC_CONST(-0.9238795042), FRAC_CONST(-0.3826834261) }, { FRAC_CONST(0.9741733670), FRAC_CONST(0.2258014232) } }, { { FRAC_CONST(0.9900237322), FRAC_CONST(-0.1409008205) }, { FRAC_CONST(0.9238795042), FRAC_CONST(-0.3826834261) }, { FRAC_CONST(0.2502108514), FRAC_CONST(0.9681913853) } }, { { FRAC_CONST(0.3534744382), FRAC_CONST(0.9354441762) }, { FRAC_CONST(-0.3826834261), FRAC_CONST(0.9238795042) }, { FRAC_CONST(-0.7427945137), FRAC_CONST(0.6695194840) } }, { { FRAC_CONST(-0.8358076215), FRAC_CONST(0.5490224361) }, { FRAC_CONST(-0.3826834261), FRAC_CONST(-0.9238795042) }, { FRAC_CONST(-0.9370992780), FRAC_CONST(-0.3490629196) } }, { { FRAC_CONST(-0.7181259394), FRAC_CONST(-0.6959131360) }, { FRAC_CONST(0.9238795042), FRAC_CONST(0.3826834261) }, { FRAC_CONST(-0.1237744763), FRAC_CONST(-0.9923103452) } }, { { FRAC_CONST(0.5224990249), FRAC_CONST(-0.8526399136) }, { FRAC_CONST(-0.9238795042), FRAC_CONST(0.3826834261) }, { FRAC_CONST(0.8226406574), FRAC_CONST(-0.5685616732) } }, { { FRAC_CONST(0.9460852146), FRAC_CONST(0.3239179254) }, { FRAC_CONST(0.3826834261), FRAC_CONST(-0.9238795042) }, { FRAC_CONST(0.8844994903), FRAC_CONST(0.4665412009) } }, { { FRAC_CONST(-0.1097348556), FRAC_CONST(0.9939609170) }, { FRAC_CONST(0.3826834261), FRAC_CONST(0.9238795042) }, { FRAC_CONST(-0.0047125919), FRAC_CONST(0.9999889135) } }, { { FRAC_CONST(-0.9939610362), FRAC_CONST(0.1097337380) }, { FRAC_CONST(-0.9238795042), FRAC_CONST(-0.3826834261) }, { FRAC_CONST(-0.8888573647), FRAC_CONST(0.4581840038) } }, { { FRAC_CONST(-0.3239168525), FRAC_CONST(-0.9460855722) }, { FRAC_CONST(0.9238795042), FRAC_CONST(-0.3826834261) }, { FRAC_CONST(-0.8172453642), FRAC_CONST(-0.5762898922) } }, { { FRAC_CONST(0.8526405096), FRAC_CONST(-0.5224980116) }, { FRAC_CONST(-0.3826834261), FRAC_CONST(0.9238795042) }, { FRAC_CONST(0.1331215799), FRAC_CONST(-0.9910997152) } }, { { FRAC_CONST(0.6959123611), FRAC_CONST(0.7181267142) }, { FRAC_CONST(-0.3826834261), FRAC_CONST(-0.9238795042) }, { FRAC_CONST(0.9403476119), FRAC_CONST(-0.3402152061) } }, { { FRAC_CONST(-0.5490233898), FRAC_CONST(0.8358070254) }, { FRAC_CONST(0.9238795042), FRAC_CONST(0.3826834261) }, { FRAC_CONST(0.7364512086), FRAC_CONST(0.6764906645) } }, { { FRAC_CONST(-0.9354437590), FRAC_CONST(-0.3534754813) }, { FRAC_CONST(-0.9238795042), FRAC_CONST(0.3826834261) }, { FRAC_CONST(-0.2593250275), FRAC_CONST(0.9657900929) } }, { { FRAC_CONST(0.1409019381), FRAC_CONST(-0.9900235534) }, { FRAC_CONST(0.3826834261), FRAC_CONST(-0.9238795042) }, { FRAC_CONST(-0.9762582779), FRAC_CONST(0.2166097313) } }, { { FRAC_CONST(0.9969173670), FRAC_CONST(-0.0784583688) }, { FRAC_CONST(0.3826834261), FRAC_CONST(0.9238795042) }, { FRAC_CONST(-0.6434556246), FRAC_CONST(-0.7654833794) } }, { { FRAC_CONST(0.2940396070), FRAC_CONST(0.9557932615) }, { FRAC_CONST(-0.9238795042), FRAC_CONST(-0.3826834261) }, { FRAC_CONST(0.3812320232), FRAC_CONST(-0.9244794250) } }, { { FRAC_CONST(-0.8686318994), FRAC_CONST(0.4954580069) }, { FRAC_CONST(0.9238795042), FRAC_CONST(-0.3826834261) }, { FRAC_CONST(0.9959943891), FRAC_CONST(-0.0894154981) } }, { { FRAC_CONST(-0.6730118990), FRAC_CONST(-0.7396316528) }, { FRAC_CONST(-0.3826834261), FRAC_CONST(0.9238795042) }, { FRAC_CONST(0.5397993922), FRAC_CONST(0.8417937160) } }, { { FRAC_CONST(0.5750059485), FRAC_CONST(-0.8181492686) }, { FRAC_CONST(-0.3826834261), FRAC_CONST(-0.9238795042) }, { FRAC_CONST(-0.4968227744), FRAC_CONST(0.8678520322) } }, { { FRAC_CONST(0.9238792062), FRAC_CONST(0.3826842010) }, { FRAC_CONST(0.9238795042), FRAC_CONST(0.3826834261) }, { FRAC_CONST(-0.9992290139), FRAC_CONST(-0.0392601527) } }, { { FRAC_CONST(-0.1719299555), FRAC_CONST(0.9851091504) }, { FRAC_CONST(-0.9238795042), FRAC_CONST(0.3826834261) }, { FRAC_CONST(-0.4271997511), FRAC_CONST(-0.9041572809) } }, { { FRAC_CONST(-0.9988899231), FRAC_CONST(0.0471055657) }, { FRAC_CONST(0.3826834261), FRAC_CONST(-0.9238795042) }, { FRAC_CONST(0.6041822433), FRAC_CONST(-0.7968461514) } }, { { FRAC_CONST(-0.2638721764), FRAC_CONST(-0.9645576477) }, { FRAC_CONST(0.3826834261), FRAC_CONST(0.9238795042) }, { FRAC_CONST(0.9859085083), FRAC_CONST(0.1672853529) } }, { { FRAC_CONST(0.8837660551), FRAC_CONST(-0.4679289758) }, { FRAC_CONST(-0.9238795042), FRAC_CONST(-0.3826834261) }, { FRAC_CONST(0.3075223565), FRAC_CONST(0.9515408874) } }, { { FRAC_CONST(0.6494473219), FRAC_CONST(0.7604066133) }, { FRAC_CONST(0.9238795042), FRAC_CONST(-0.3826834261) }, { FRAC_CONST(-0.7015317082), FRAC_CONST(0.7126382589) } }, { { FRAC_CONST(-0.6004210114), FRAC_CONST(0.7996840477) }, { FRAC_CONST(-0.3826834261), FRAC_CONST(0.9238795042) }, { FRAC_CONST(-0.9562535882), FRAC_CONST(-0.2925389707) } }, { { FRAC_CONST(-0.9114028811), FRAC_CONST(-0.4115152657) }, { FRAC_CONST(-0.3826834261), FRAC_CONST(-0.9238795042) }, { FRAC_CONST(-0.1827499419), FRAC_CONST(-0.9831594229) } }, { { FRAC_CONST(0.2027882934), FRAC_CONST(-0.9792225957) }, { FRAC_CONST(0.9238795042), FRAC_CONST(0.3826834261) }, { FRAC_CONST(0.7872582674), FRAC_CONST(-0.6166234016) } }, { { FRAC_CONST(0.9998766780), FRAC_CONST(-0.0157062728) }, { FRAC_CONST(-0.9238795042), FRAC_CONST(0.3826834261) }, { FRAC_CONST(0.9107555747), FRAC_CONST(0.4129458666) } }, { { FRAC_CONST(0.2334443331), FRAC_CONST(0.9723701477) }, { FRAC_CONST(0.3826834261), FRAC_CONST(-0.9238795042) }, { FRAC_CONST(0.0549497530), FRAC_CONST(0.9984891415) } }, { { FRAC_CONST(-0.8980280757), FRAC_CONST(0.4399381876) }, { FRAC_CONST(0.3826834261), FRAC_CONST(0.9238795042) }, { FRAC_CONST(-0.8599416018), FRAC_CONST(0.5103924870) } }, { { FRAC_CONST(-0.6252418160), FRAC_CONST(-0.7804310918) }, { FRAC_CONST(-0.9238795042), FRAC_CONST(-0.3826834261) }, { FRAC_CONST(-0.8501682281), FRAC_CONST(-0.5265110731) } }, { { FRAC_CONST(0.6252435446), FRAC_CONST(-0.7804297209) }, { FRAC_CONST(0.9238795042), FRAC_CONST(-0.3826834261) }, { FRAC_CONST(0.0737608299), FRAC_CONST(-0.9972759485) } }, { { FRAC_CONST(0.8980270624), FRAC_CONST(0.4399402142) }, { FRAC_CONST(-0.3826834261), FRAC_CONST(0.9238795042) }, { FRAC_CONST(0.9183775187), FRAC_CONST(-0.3957053721) } }, { { FRAC_CONST(-0.2334465086), FRAC_CONST(0.9723696709) }, { FRAC_CONST(-0.3826834261), FRAC_CONST(-0.9238795042) }, { FRAC_CONST(0.7754954696), FRAC_CONST(0.6313531399) } }, { { FRAC_CONST(-0.9998766184), FRAC_CONST(-0.0157085191) }, { FRAC_CONST(0.9238795042), FRAC_CONST(0.3826834261) }, { FRAC_CONST(-0.2012493610), FRAC_CONST(0.9795400500) } }, { { FRAC_CONST(-0.2027861029), FRAC_CONST(-0.9792230725) }, { FRAC_CONST(-0.9238795042), FRAC_CONST(0.3826834261) }, { FRAC_CONST(-0.9615978599), FRAC_CONST(0.2744622827) } }, { { FRAC_CONST(0.9114037752), FRAC_CONST(-0.4115132093) }, { FRAC_CONST(0.3826834261), FRAC_CONST(-0.9238795042) }, { FRAC_CONST(-0.6879743338), FRAC_CONST(-0.7257350087) } }, { { FRAC_CONST(0.6004192233), FRAC_CONST(0.7996854186) }, { FRAC_CONST(0.3826834261), FRAC_CONST(0.9238795042) }, { FRAC_CONST(0.3254036009), FRAC_CONST(-0.9455752373) } }, { { FRAC_CONST(-0.6494490504), FRAC_CONST(0.7604051232) }, { FRAC_CONST(-0.9238795042), FRAC_CONST(-0.3826834261) }, { FRAC_CONST(0.9888865948), FRAC_CONST(-0.1486719251) } }, { { FRAC_CONST(-0.8837650418), FRAC_CONST(-0.4679309726) }, { FRAC_CONST(0.9238795042), FRAC_CONST(-0.3826834261) }, { FRAC_CONST(0.5890548825), FRAC_CONST(0.8080930114) } }, { { FRAC_CONST(0.2638743520), FRAC_CONST(-0.9645570517) }, { FRAC_CONST(-0.3826834261), FRAC_CONST(0.9238795042) }, { FRAC_CONST(-0.4441666007), FRAC_CONST(0.8959442377) } }, { { FRAC_CONST(0.9988898039), FRAC_CONST(0.0471078083) }, { FRAC_CONST(-0.3826834261), FRAC_CONST(-0.9238795042) }, { FRAC_CONST(-0.9997915030), FRAC_CONST(0.0204183888) } }, { { FRAC_CONST(0.1719277352), FRAC_CONST(0.9851095676) }, { FRAC_CONST(0.9238795042), FRAC_CONST(0.3826834261) }, { FRAC_CONST(-0.4803760946), FRAC_CONST(-0.8770626187) } }, { { FRAC_CONST(-0.9238800406), FRAC_CONST(0.3826821446) }, { FRAC_CONST(-0.9238795042), FRAC_CONST(0.3826834261) }, { FRAC_CONST(0.5555707216), FRAC_CONST(-0.8314692974) } }, { { FRAC_CONST(-0.5750041008), FRAC_CONST(-0.8181505203) }, { FRAC_CONST(0.3826834261), FRAC_CONST(-0.9238795042) }, { FRAC_CONST(0.9941320419), FRAC_CONST(0.1081734300) } } }; static const complex_t Phi_Fract_Qmf[] = { { FRAC_CONST(0.8181497455), FRAC_CONST(0.5750052333) }, { FRAC_CONST(-0.2638730407), FRAC_CONST(0.9645574093) }, { FRAC_CONST(-0.9969173074), FRAC_CONST(0.0784590989) }, { FRAC_CONST(-0.4115143716), FRAC_CONST(-0.9114032984) }, { FRAC_CONST(0.7181262970), FRAC_CONST(-0.6959127784) }, { FRAC_CONST(0.8980275989), FRAC_CONST(0.4399391711) }, { FRAC_CONST(-0.1097343117), FRAC_CONST(0.9939609766) }, { FRAC_CONST(-0.9723699093), FRAC_CONST(0.2334453613) }, { FRAC_CONST(-0.5490227938), FRAC_CONST(-0.8358073831) }, { FRAC_CONST(0.6004202366), FRAC_CONST(-0.7996846437) }, { FRAC_CONST(0.9557930231), FRAC_CONST(0.2940403223) }, { FRAC_CONST(0.0471064523), FRAC_CONST(0.9988898635) }, { FRAC_CONST(-0.9238795042), FRAC_CONST(0.3826834261) }, { FRAC_CONST(-0.6730124950), FRAC_CONST(-0.7396311164) }, { FRAC_CONST(0.4679298103), FRAC_CONST(-0.8837656379) }, { FRAC_CONST(0.9900236726), FRAC_CONST(0.1409012377) }, { FRAC_CONST(0.2027872950), FRAC_CONST(0.9792228341) }, { FRAC_CONST(-0.8526401520), FRAC_CONST(0.5224985480) }, { FRAC_CONST(-0.7804304361), FRAC_CONST(-0.6252426505) }, { FRAC_CONST(0.3239174187), FRAC_CONST(-0.9460853338) }, { FRAC_CONST(0.9998766184), FRAC_CONST(-0.0157073177) }, { FRAC_CONST(0.3534748554), FRAC_CONST(0.9354440570) }, { FRAC_CONST(-0.7604059577), FRAC_CONST(0.6494480371) }, { FRAC_CONST(-0.8686315417), FRAC_CONST(-0.4954586625) }, { FRAC_CONST(0.1719291061), FRAC_CONST(-0.9851093292) }, { FRAC_CONST(0.9851093292), FRAC_CONST(-0.1719291061) }, { FRAC_CONST(0.4954586625), FRAC_CONST(0.8686315417) }, { FRAC_CONST(-0.6494480371), FRAC_CONST(0.7604059577) }, { FRAC_CONST(-0.9354440570), FRAC_CONST(-0.3534748554) }, { FRAC_CONST(0.0157073177), FRAC_CONST(-0.9998766184) }, { FRAC_CONST(0.9460853338), FRAC_CONST(-0.3239174187) }, { FRAC_CONST(0.6252426505), FRAC_CONST(0.7804304361) }, { FRAC_CONST(-0.5224985480), FRAC_CONST(0.8526401520) }, { FRAC_CONST(-0.9792228341), FRAC_CONST(-0.2027872950) }, { FRAC_CONST(-0.1409012377), FRAC_CONST(-0.9900236726) }, { FRAC_CONST(0.8837656379), FRAC_CONST(-0.4679298103) }, { FRAC_CONST(0.7396311164), FRAC_CONST(0.6730124950) }, { FRAC_CONST(-0.3826834261), FRAC_CONST(0.9238795042) }, { FRAC_CONST(-0.9988898635), FRAC_CONST(-0.0471064523) }, { FRAC_CONST(-0.2940403223), FRAC_CONST(-0.9557930231) }, { FRAC_CONST(0.7996846437), FRAC_CONST(-0.6004202366) }, { FRAC_CONST(0.8358073831), FRAC_CONST(0.5490227938) }, { FRAC_CONST(-0.2334453613), FRAC_CONST(0.9723699093) }, { FRAC_CONST(-0.9939609766), FRAC_CONST(0.1097343117) }, { FRAC_CONST(-0.4399391711), FRAC_CONST(-0.8980275989) }, { FRAC_CONST(0.6959127784), FRAC_CONST(-0.7181262970) }, { FRAC_CONST(0.9114032984), FRAC_CONST(0.4115143716) }, { FRAC_CONST(-0.0784590989), FRAC_CONST(0.9969173074) }, { FRAC_CONST(-0.9645574093), FRAC_CONST(0.2638730407) }, { FRAC_CONST(-0.5750052333), FRAC_CONST(-0.8181497455) }, { FRAC_CONST(0.5750052333), FRAC_CONST(-0.8181497455) }, { FRAC_CONST(0.9645574093), FRAC_CONST(0.2638730407) }, { FRAC_CONST(0.0784590989), FRAC_CONST(0.9969173074) }, { FRAC_CONST(-0.9114032984), FRAC_CONST(0.4115143716) }, { FRAC_CONST(-0.6959127784), FRAC_CONST(-0.7181262970) }, { FRAC_CONST(0.4399391711), FRAC_CONST(-0.8980275989) }, { FRAC_CONST(0.9939609766), FRAC_CONST(0.1097343117) }, { FRAC_CONST(0.2334453613), FRAC_CONST(0.9723699093) }, { FRAC_CONST(-0.8358073831), FRAC_CONST(0.5490227938) }, { FRAC_CONST(-0.7996846437), FRAC_CONST(-0.6004202366) }, { FRAC_CONST(0.2940403223), FRAC_CONST(-0.9557930231) }, { FRAC_CONST(0.9988898635), FRAC_CONST(-0.0471064523) }, { FRAC_CONST(0.3826834261), FRAC_CONST(0.9238795042) }, { FRAC_CONST(-0.7396311164), FRAC_CONST(0.6730124950) } }; /* static function declarations */ static void drm_ps_sa_element(drm_ps_info *ps, bitfile *ld); static void drm_ps_pan_element(drm_ps_info *ps, bitfile *ld); static int8_t huff_dec(bitfile *ld, drm_ps_huff_tab huff); uint16_t drm_ps_data(drm_ps_info *ps, bitfile *ld) { uint16_t bits = (uint16_t)faad_get_processed_bits(ld); ps->drm_ps_data_available = 1; ps->bs_enable_sa = faad_get1bit(ld); ps->bs_enable_pan = faad_get1bit(ld); if (ps->bs_enable_sa) { drm_ps_sa_element(ps, ld); } if (ps->bs_enable_pan) { drm_ps_pan_element(ps, ld); } bits = (uint16_t)faad_get_processed_bits(ld) - bits; return bits; } static void drm_ps_sa_element(drm_ps_info *ps, bitfile *ld) { drm_ps_huff_tab huff; uint8_t band; ps->bs_sa_dt_flag = faad_get1bit(ld); if (ps->bs_sa_dt_flag) { huff = t_huffman_sa; } else { huff = f_huffman_sa; } for (band = 0; band < DRM_NUM_SA_BANDS; band++) { ps->bs_sa_data[band] = huff_dec(ld, huff); } } static void drm_ps_pan_element(drm_ps_info *ps, bitfile *ld) { drm_ps_huff_tab huff; uint8_t band; ps->bs_pan_dt_flag = faad_get1bit(ld); if (ps->bs_pan_dt_flag) { huff = t_huffman_pan; } else { huff = f_huffman_pan; } for (band = 0; band < DRM_NUM_PAN_BANDS; band++) { ps->bs_pan_data[band] = huff_dec(ld, huff); } } /* binary search huffman decoding */ static int8_t huff_dec(bitfile *ld, drm_ps_huff_tab huff) { uint8_t bit; int16_t index = 0; while (index >= 0) { bit = (uint8_t)faad_get1bit(ld); index = huff[index][bit]; } return index + 15; } static int8_t sa_delta_clip(drm_ps_info *ps, int8_t i) { if (i < 0) { /* printf(" SAminclip %d", i); */ ps->sa_decode_error = 1; return 0; } else if (i > 7) { /* printf(" SAmaxclip %d", i); */ ps->sa_decode_error = 1; return 7; } else return i; } static int8_t pan_delta_clip(drm_ps_info *ps, int8_t i) { if (i < -7) { /* printf(" PANminclip %d", i); */ ps->pan_decode_error = 1; return -7; } else if (i > 7) { /* printf(" PANmaxclip %d", i); */ ps->pan_decode_error = 1; return 7; } else return i; } static void drm_ps_delta_decode(drm_ps_info *ps) { uint8_t band; if (ps->bs_enable_sa) { if (ps->bs_sa_dt_flag && !ps->g_last_had_sa) { for (band = 0; band < DRM_NUM_SA_BANDS; band++) { ps->g_prev_sa_index[band] = 0; } } if (ps->bs_sa_dt_flag) { ps->g_sa_index[0] = sa_delta_clip(ps, ps->g_prev_sa_index[0]+ps->bs_sa_data[0]); } else { ps->g_sa_index[0] = sa_delta_clip(ps,ps->bs_sa_data[0]); } for (band = 1; band < DRM_NUM_SA_BANDS; band++) { if (ps->bs_sa_dt_flag) { ps->g_sa_index[band] = sa_delta_clip(ps, ps->g_prev_sa_index[band] + ps->bs_sa_data[band]); } else { ps->g_sa_index[band] = sa_delta_clip(ps, ps->g_sa_index[band-1] + ps->bs_sa_data[band]); } } } /* An error during SA decoding implies PAN data will be undecodable, too */ /* Also, we don't like on/off switching in PS, so we force to last settings */ if (ps->sa_decode_error) { ps->pan_decode_error = 1; ps->bs_enable_pan = ps->g_last_had_pan; ps->bs_enable_sa = ps->g_last_had_sa; } if (ps->bs_enable_sa) { if (ps->sa_decode_error) { for (band = 0; band < DRM_NUM_SA_BANDS; band++) { ps->g_sa_index[band] = ps->g_last_good_sa_index[band]; } } else { for (band = 0; band < DRM_NUM_SA_BANDS; band++) { ps->g_last_good_sa_index[band] = ps->g_sa_index[band]; } } } if (ps->bs_enable_pan) { if (ps->bs_pan_dt_flag && !ps->g_last_had_pan) { /* The DRM PS spec doesn't say anything about this case. (deltacoded in time without a previous frame) AAC PS spec you must tread previous frame as 0, so that's what we try. */ for (band = 0; band < DRM_NUM_PAN_BANDS; band++) { ps->g_prev_pan_index[band] = 0; } } if (ps->bs_pan_dt_flag) { ps->g_pan_index[0] = pan_delta_clip(ps, ps->g_prev_pan_index[0]+ps->bs_pan_data[0]); } else { ps->g_pan_index[0] = pan_delta_clip(ps, ps->bs_pan_data[0]); } for (band = 1; band < DRM_NUM_PAN_BANDS; band++) { if (ps->bs_pan_dt_flag) { ps->g_pan_index[band] = pan_delta_clip(ps, ps->g_prev_pan_index[band] + ps->bs_pan_data[band]); } else { ps->g_pan_index[band] = pan_delta_clip(ps, ps->g_pan_index[band-1] + ps->bs_pan_data[band]); } } if (ps->pan_decode_error) { for (band = 0; band < DRM_NUM_PAN_BANDS; band++) { ps->g_pan_index[band] = ps->g_last_good_pan_index[band]; } } else { for (band = 0; band < DRM_NUM_PAN_BANDS; band++) { ps->g_last_good_pan_index[band] = ps->g_pan_index[band]; } } } } static void drm_calc_sa_side_signal(drm_ps_info *ps, qmf_t X[38][64], uint8_t rateselect) { uint8_t s, b, k; complex_t qfrac, tmp0, tmp, in, R0; real_t peakdiff; real_t nrg; real_t power; real_t transratio; real_t new_delay_slopes[NUM_OF_LINKS]; uint8_t temp_delay_ser[NUM_OF_LINKS]; complex_t Phi_Fract; #ifdef FIXED_POINT uint32_t in_re, in_im; #endif for (b = 0; b < sa_freq_scale[DRM_NUM_SA_BANDS][rateselect]; b++) { /* set delay indices */ for (k = 0; k < NUM_OF_LINKS; k++) temp_delay_ser[k] = ps->delay_buf_index_ser[k]; RE(Phi_Fract) = RE(Phi_Fract_Qmf[b]); IM(Phi_Fract) = IM(Phi_Fract_Qmf[b]); for (s = 0; s < NUM_OF_SUBSAMPLES; s++) { const real_t gamma = REAL_CONST(1.5); const real_t sigma = REAL_CONST(1.5625); RE(in) = QMF_RE(X[s][b]); IM(in) = QMF_IM(X[s][b]); #ifdef FIXED_POINT /* NOTE: all input is scaled by 2^(-5) because of fixed point QMF * meaning that P will be scaled by 2^(-10) compared to floating point version */ in_re = ((abs(RE(in))+(1<<(REAL_BITS-1)))>>REAL_BITS); in_im = ((abs(IM(in))+(1<<(REAL_BITS-1)))>>REAL_BITS); power = in_re*in_re + in_im*in_im; #else power = MUL_R(RE(in),RE(in)) + MUL_R(IM(in),IM(in)); #endif ps->peakdecay_fast[b] = MUL_F(ps->peakdecay_fast[b], peak_decay[rateselect]); if (ps->peakdecay_fast[b] < power) ps->peakdecay_fast[b] = power; peakdiff = ps->prev_peakdiff[b]; peakdiff += MUL_F((ps->peakdecay_fast[b] - power - ps->prev_peakdiff[b]), smooth_coeff[rateselect]); ps->prev_peakdiff[b] = peakdiff; nrg = ps->prev_nrg[b]; nrg += MUL_F((power - ps->prev_nrg[b]), smooth_coeff[rateselect]); ps->prev_nrg[b] = nrg; if (MUL_R(peakdiff, gamma) <= nrg) { transratio = sigma; } else { transratio = MUL_R(DIV_R(nrg, MUL_R(peakdiff, gamma)), sigma); } for (k = 0; k < NUM_OF_LINKS; k++) { new_delay_slopes[k] = MUL_F(g_decayslope[b], filter_coeff[k]); } RE(tmp0) = RE(ps->d_buff[0][b]); IM(tmp0) = IM(ps->d_buff[0][b]); RE(ps->d_buff[0][b]) = RE(ps->d_buff[1][b]); IM(ps->d_buff[0][b]) = IM(ps->d_buff[1][b]); RE(ps->d_buff[1][b]) = RE(in); IM(ps->d_buff[1][b]) = IM(in); ComplexMult(&RE(tmp), &IM(tmp), RE(tmp0), IM(tmp0), RE(Phi_Fract), IM(Phi_Fract)); RE(R0) = RE(tmp); IM(R0) = IM(tmp); for (k = 0; k < NUM_OF_LINKS; k++) { RE(qfrac) = RE(Q_Fract_allpass_Qmf[b][k]); IM(qfrac) = IM(Q_Fract_allpass_Qmf[b][k]); RE(tmp0) = RE(ps->d2_buff[k][temp_delay_ser[k]][b]); IM(tmp0) = IM(ps->d2_buff[k][temp_delay_ser[k]][b]); ComplexMult(&RE(tmp), &IM(tmp), RE(tmp0), IM(tmp0), RE(qfrac), IM(qfrac)); RE(tmp) += -MUL_F(new_delay_slopes[k], RE(R0)); IM(tmp) += -MUL_F(new_delay_slopes[k], IM(R0)); RE(ps->d2_buff[k][temp_delay_ser[k]][b]) = RE(R0) + MUL_F(new_delay_slopes[k], RE(tmp)); IM(ps->d2_buff[k][temp_delay_ser[k]][b]) = IM(R0) + MUL_F(new_delay_slopes[k], IM(tmp)); RE(R0) = RE(tmp); IM(R0) = IM(tmp); } QMF_RE(ps->SA[s][b]) = MUL_R(RE(R0), transratio); QMF_IM(ps->SA[s][b]) = MUL_R(IM(R0), transratio); for (k = 0; k < NUM_OF_LINKS; k++) { if (++temp_delay_ser[k] >= delay_length[k][rateselect]) temp_delay_ser[k] = 0; } } } for (k = 0; k < NUM_OF_LINKS; k++) ps->delay_buf_index_ser[k] = temp_delay_ser[k]; } static void drm_add_ambiance(drm_ps_info *ps, uint8_t rateselect, qmf_t X_left[38][64], qmf_t X_right[38][64]) { uint8_t s, b, ifreq, qclass; real_t sa_map[MAX_SA_BAND], sa_dir_map[MAX_SA_BAND], k_sa_map[MAX_SA_BAND], k_sa_dir_map[MAX_SA_BAND]; real_t new_dir_map, new_sa_map; if (ps->bs_enable_sa) { /* Instead of dequantization and mapping, we use an inverse mapping to look up all the values we need */ for (b = 0; b < sa_freq_scale[DRM_NUM_SA_BANDS][rateselect]; b++) { const real_t inv_f_num_of_subsamples = FRAC_CONST(0.03333333333); ifreq = sa_inv_freq[b]; qclass = (b != 0); sa_map[b] = sa_quant[ps->g_prev_sa_index[ifreq]][qclass]; new_sa_map = sa_quant[ps->g_sa_index[ifreq]][qclass]; k_sa_map[b] = MUL_F(inv_f_num_of_subsamples, (new_sa_map - sa_map[b])); sa_dir_map[b] = sa_sqrt_1_minus[ps->g_prev_sa_index[ifreq]][qclass]; new_dir_map = sa_sqrt_1_minus[ps->g_sa_index[ifreq]][qclass]; k_sa_dir_map[b] = MUL_F(inv_f_num_of_subsamples, (new_dir_map - sa_dir_map[b])); } for (s = 0; s < NUM_OF_SUBSAMPLES; s++) { for (b = 0; b < sa_freq_scale[DRM_NUM_SA_BANDS][rateselect]; b++) { QMF_RE(X_right[s][b]) = MUL_F(QMF_RE(X_left[s][b]), sa_dir_map[b]) - MUL_F(QMF_RE(ps->SA[s][b]), sa_map[b]); QMF_IM(X_right[s][b]) = MUL_F(QMF_IM(X_left[s][b]), sa_dir_map[b]) - MUL_F(QMF_IM(ps->SA[s][b]), sa_map[b]); QMF_RE(X_left[s][b]) = MUL_F(QMF_RE(X_left[s][b]), sa_dir_map[b]) + MUL_F(QMF_RE(ps->SA[s][b]), sa_map[b]); QMF_IM(X_left[s][b]) = MUL_F(QMF_IM(X_left[s][b]), sa_dir_map[b]) + MUL_F(QMF_IM(ps->SA[s][b]), sa_map[b]); sa_map[b] += k_sa_map[b]; sa_dir_map[b] += k_sa_dir_map[b]; } for (b = sa_freq_scale[DRM_NUM_SA_BANDS][rateselect]; b < NUM_OF_QMF_CHANNELS; b++) { QMF_RE(X_right[s][b]) = QMF_RE(X_left[s][b]); QMF_IM(X_right[s][b]) = QMF_IM(X_left[s][b]); } } } else { for (s = 0; s < NUM_OF_SUBSAMPLES; s++) { for (b = 0; b < NUM_OF_QMF_CHANNELS; b++) { QMF_RE(X_right[s][b]) = QMF_RE(X_left[s][b]); QMF_IM(X_right[s][b]) = QMF_IM(X_left[s][b]); } } } } static void drm_add_pan(drm_ps_info *ps, uint8_t rateselect, qmf_t X_left[38][64], qmf_t X_right[38][64]) { uint8_t s, b, qclass, ifreq; real_t tmp, coeff1, coeff2; real_t pan_base[MAX_PAN_BAND]; real_t pan_delta[MAX_PAN_BAND]; qmf_t temp_l, temp_r; if (ps->bs_enable_pan) { for (b = 0; b < NUM_OF_QMF_CHANNELS; b++) { /* Instead of dequantization, 20->64 mapping and 2^G(x,y) we do an inverse mapping 64->20 and look up the 2^G(x,y) values directly */ ifreq = pan_inv_freq[b]; qclass = pan_quant_class[ifreq]; if (ps->g_prev_pan_index[ifreq] >= 0) { pan_base[b] = pan_pow_2_pos[ps->g_prev_pan_index[ifreq]][qclass]; } else { pan_base[b] = pan_pow_2_neg[-ps->g_prev_pan_index[ifreq]][qclass]; } /* 2^((a-b)/30) = 2^(a/30) * 1/(2^(b/30)) */ /* a en b can be negative so we may need to inverse parts */ if (ps->g_pan_index[ifreq] >= 0) { if (ps->g_prev_pan_index[ifreq] >= 0) { pan_delta[b] = MUL_C(pan_pow_2_30_pos[ps->g_pan_index[ifreq]][qclass], pan_pow_2_30_neg[ps->g_prev_pan_index[ifreq]][qclass]); } else { pan_delta[b] = MUL_C(pan_pow_2_30_pos[ps->g_pan_index[ifreq]][qclass], pan_pow_2_30_pos[-ps->g_prev_pan_index[ifreq]][qclass]); } } else { if (ps->g_prev_pan_index[ifreq] >= 0) { pan_delta[b] = MUL_C(pan_pow_2_30_neg[-ps->g_pan_index[ifreq]][qclass], pan_pow_2_30_neg[ps->g_prev_pan_index[ifreq]][qclass]); } else { pan_delta[b] = MUL_C(pan_pow_2_30_neg[-ps->g_pan_index[ifreq]][qclass], pan_pow_2_30_pos[-ps->g_prev_pan_index[ifreq]][qclass]); } } } for (s = 0; s < NUM_OF_SUBSAMPLES; s++) { /* PAN always uses all 64 channels */ for (b = 0; b < NUM_OF_QMF_CHANNELS; b++) { tmp = pan_base[b]; coeff2 = DIV_R(REAL_CONST(2.0), (REAL_CONST(1.0) + tmp)); coeff1 = MUL_R(coeff2, tmp); QMF_RE(temp_l) = QMF_RE(X_left[s][b]); QMF_IM(temp_l) = QMF_IM(X_left[s][b]); QMF_RE(temp_r) = QMF_RE(X_right[s][b]); QMF_IM(temp_r) = QMF_IM(X_right[s][b]); QMF_RE(X_left[s][b]) = MUL_R(QMF_RE(temp_l), coeff1); QMF_IM(X_left[s][b]) = MUL_R(QMF_IM(temp_l), coeff1); QMF_RE(X_right[s][b]) = MUL_R(QMF_RE(temp_r), coeff2); QMF_IM(X_right[s][b]) = MUL_R(QMF_IM(temp_r), coeff2); /* 2^(a+k*b) = 2^a * 2^b * ... * 2^b */ /* ^^^^^^^^^^^^^^^ k times */ pan_base[b] = MUL_C(pan_base[b], pan_delta[b]); } } } } drm_ps_info *drm_ps_init(void) { drm_ps_info *ps = (drm_ps_info*)faad_malloc(sizeof(drm_ps_info)); memset(ps, 0, sizeof(drm_ps_info)); return ps; } void drm_ps_free(drm_ps_info *ps) { faad_free(ps); } /* main DRM PS decoding function */ uint8_t drm_ps_decode(drm_ps_info *ps, uint8_t guess, uint32_t samplerate, qmf_t X_left[38][64], qmf_t X_right[38][64]) { uint8_t rateselect = (samplerate >= 24000); if (ps == NULL) { memcpy(X_right, X_left, sizeof(qmf_t)*30*64); return 0; } if (!ps->drm_ps_data_available && !guess) { memcpy(X_right, X_left, sizeof(qmf_t)*30*64); memset(ps->g_prev_sa_index, 0, sizeof(ps->g_prev_sa_index)); memset(ps->g_prev_pan_index, 0, sizeof(ps->g_prev_pan_index)); return 0; } /* if SBR CRC doesn't match out, we can assume decode errors to start with, and we'll guess what the parameters should be */ if (!guess) { ps->sa_decode_error = 0; ps->pan_decode_error = 0; drm_ps_delta_decode(ps); } else { ps->sa_decode_error = 1; ps->pan_decode_error = 1; /* don't even bother decoding */ } ps->drm_ps_data_available = 0; drm_calc_sa_side_signal(ps, X_left, rateselect); drm_add_ambiance(ps, rateselect, X_left, X_right); if (ps->bs_enable_sa) { ps->g_last_had_sa = 1; memcpy(ps->g_prev_sa_index, ps->g_sa_index, sizeof(int8_t) * DRM_NUM_SA_BANDS); } else { ps->g_last_had_sa = 0; } if (ps->bs_enable_pan) { drm_add_pan(ps, rateselect, X_left, X_right); ps->g_last_had_pan = 1; memcpy(ps->g_prev_pan_index, ps->g_pan_index, sizeof(int8_t) * DRM_NUM_PAN_BANDS); } else { ps->g_last_had_pan = 0; } return 0; } #endif
dr4g0nsr/mplayer-skyviia-8860
mplayer_android/libfaad2/drm_dec.c
C
gpl-3.0
48,595
require 'test_helper' class PluginsTest < Test::Unit::TestCase def setup @plugins = ::Proxy::Plugins.new end class TestPlugin1 < Proxy::Plugin; plugin :plugin_1, "1.0"; default_settings :enabled => true; end class TestPlugin2 < Proxy::Provider; plugin :plugin_2, "1.0"; default_settings :enabled => true; end def test_find_provider @plugins.update([{:name => :plugin_1, :class => TestPlugin1}, {:name => :plugin_2, :class => TestPlugin2}]) assert_equal PluginsTest::TestPlugin2, @plugins.find_provider(:plugin_2) end def test_find_provider_should_raise_exception_if_no_provider_exists assert_raises(::Proxy::PluginProviderNotFound) { @plugins.find_provider(:nonexistent) } end class TestPlugin3 < Proxy::Plugin; plugin :plugin_3, "1.0"; default_settings :enabled => true; end def test_find_provider_should_raise_exception_if_provider_is_of_wrong_class @plugins.update([{:name => :plugin_3, :class => TestPlugin3}]) assert_raises(::Proxy::PluginProviderNotFound) { @plugins.find_provider(:plugin_3) } end end
dLobatog/smart-proxy
test/plugins/plugins_test.rb
Ruby
gpl-3.0
1,058
/* Fontname: -FreeType-Gentium Basic-Medium-R-Normal--27-270-72-72-P-125-ISO10646-1 Copyright: Copyright (c) SIL International, 2003-2008. Capital A Height: 17, '1' Height: 16 Calculated Max Values w=22 h=27 x= 2 y=14 dx=23 dy= 0 ascent=22 len=66 Font Bounding box w=40 h=38 x=-14 y=-9 Calculated Min Values x=-3 y=-6 dx= 0 dy= 0 Pure Font ascent =17 descent=-6 X Font ascent =21 descent=-6 Max Font ascent =22 descent=-6 */ #include "u8g.h" const u8g_fntpgm_uint8_t u8g_font_gdr17r[3380] U8G_FONT_SECTION("u8g_font_gdr17r") = { 0,40,38,242,247,17,4,64,9,46,32,127,250,22,250,21, 250,0,0,0,6,0,0,3,21,21,7,2,255,96,224,224, 224,224,96,96,96,96,96,64,64,64,64,64,0,0,96,224, 224,192,7,9,9,11,2,11,102,230,230,198,198,70,70,70, 70,12,15,30,13,1,2,6,96,6,96,4,64,4,64,12, 192,63,240,8,128,25,128,17,0,255,224,51,0,34,0,34, 0,102,0,68,0,11,20,40,12,0,254,6,0,6,0,15, 128,55,224,102,64,102,0,102,0,118,0,62,0,31,128,7, 192,6,224,6,96,134,96,198,96,230,192,127,192,31,0,6, 0,6,0,17,16,48,19,1,0,56,6,0,108,12,0,198, 24,0,198,24,0,198,48,0,198,96,0,198,192,0,108,192, 0,57,158,0,3,51,0,6,97,128,6,97,128,12,97,128, 24,97,128,48,51,0,32,30,0,17,19,57,18,1,0,3, 192,0,12,224,0,8,96,0,24,96,0,24,96,0,24,192, 0,29,192,0,31,128,0,14,0,0,62,63,128,119,29,0, 103,12,0,195,140,0,193,204,0,193,232,0,192,248,0,96, 120,0,112,222,0,31,7,128,3,9,9,7,2,11,96,224, 224,192,192,64,64,64,64,6,25,25,9,2,252,4,8,24, 48,32,96,96,96,192,192,192,192,192,192,192,192,192,224,96, 96,96,48,24,8,4,6,25,25,9,1,252,128,64,96,48, 24,24,24,24,12,12,12,12,12,12,12,12,12,24,24,24, 48,48,96,64,128,10,12,24,12,1,9,12,0,12,0,140, 0,204,192,119,128,30,0,30,0,119,128,204,192,12,128,12, 0,12,0,10,9,18,11,1,3,12,0,12,0,12,0,12, 0,255,192,12,0,12,0,12,0,12,0,4,7,7,6,1, 252,112,240,48,48,32,96,64,7,1,1,9,1,6,254,3, 4,4,6,2,255,96,224,224,192,11,25,50,13,1,252,0, 96,0,96,0,192,0,192,1,128,1,128,1,128,3,0,3, 0,6,0,6,0,6,0,12,0,12,0,12,0,24,0,24, 0,48,0,48,0,48,0,96,0,96,0,224,0,192,0,192, 0,11,16,32,13,1,0,15,0,49,128,96,192,64,192,64, 224,192,96,192,96,192,96,192,96,192,96,192,96,192,64,96, 64,96,192,49,128,30,0,9,16,32,13,2,0,12,0,60, 0,252,0,12,0,12,0,12,0,12,0,12,0,12,0,12, 0,12,0,12,0,12,0,12,0,12,0,255,128,10,16,32, 13,1,0,15,0,49,128,96,192,96,192,0,192,0,192,1, 128,1,128,3,0,6,0,12,0,28,0,24,0,48,64,96, 64,255,192,10,16,32,13,1,0,30,0,99,0,97,128,193, 128,1,128,3,0,6,0,31,0,3,128,1,192,0,192,0, 192,0,192,1,128,193,128,62,0,11,16,32,13,1,0,1, 128,3,128,7,128,5,128,13,128,25,128,17,128,49,128,97, 128,65,128,255,224,1,128,1,128,1,128,1,128,15,224,10, 16,32,13,1,0,63,192,32,0,32,0,32,0,96,0,96, 0,127,0,67,128,1,192,0,192,0,192,0,192,0,192,1, 128,193,128,62,0,11,16,32,13,1,0,3,128,14,0,24, 0,48,0,96,0,96,0,207,0,241,192,192,224,192,96,192, 96,192,96,96,96,96,64,48,128,31,0,11,16,32,13,1, 0,127,224,64,192,128,192,0,128,1,128,1,128,3,0,3, 0,6,0,6,0,4,0,12,0,12,0,24,0,24,0,48, 0,11,16,32,13,1,0,31,0,113,128,224,192,224,192,224, 192,241,128,63,0,15,128,51,192,96,224,192,96,192,96,192, 96,192,64,96,128,31,0,11,17,34,13,1,255,31,0,49, 128,96,192,192,192,192,96,192,96,192,96,224,96,113,224,30, 96,0,224,0,192,0,192,1,128,3,0,14,0,48,0,3, 14,14,6,2,255,64,224,224,224,0,0,0,0,0,0,96, 224,224,192,4,17,17,6,1,252,32,112,112,112,0,0,0, 0,0,0,112,240,48,48,32,96,64,10,9,18,12,1,3, 0,192,3,192,31,0,120,0,224,0,248,0,30,0,7,192, 0,192,10,5,10,12,1,5,255,192,0,0,0,0,0,0, 255,192,10,9,18,12,1,3,192,0,248,0,30,0,7,192, 1,192,7,128,60,0,240,0,128,0,10,20,40,12,1,255, 31,0,97,128,192,192,192,192,192,192,0,192,1,128,1,128, 3,0,6,0,6,0,12,0,12,0,12,0,8,0,0,0, 12,0,28,0,28,0,24,0,20,22,66,22,1,251,0,252, 0,3,7,0,12,1,192,24,0,192,48,0,96,32,244,96, 97,28,112,67,12,48,194,12,48,198,12,48,198,12,48,198, 12,48,198,12,32,198,12,96,227,12,64,99,60,128,97,199, 0,48,0,0,56,0,0,28,0,64,7,3,128,1,252,0, 16,17,34,16,0,0,0,128,1,128,3,128,3,192,2,192, 6,192,6,96,4,96,12,112,12,48,15,240,24,24,24,24, 16,24,48,12,48,12,248,63,12,17,34,14,1,0,127,128, 176,192,48,96,48,96,48,96,48,64,49,128,63,192,48,224, 48,96,48,48,48,48,48,48,48,48,48,96,48,224,255,128, 12,17,34,14,1,0,7,224,24,112,48,0,32,0,96,0, 64,0,192,0,192,0,192,0,192,0,192,0,192,0,96,0, 96,0,48,16,24,32,15,192,14,17,34,16,1,0,127,128, 176,224,48,48,48,24,48,24,48,12,48,12,48,12,48,12, 48,12,48,12,48,12,48,24,48,24,48,48,48,96,255,128, 12,17,34,13,1,0,255,224,48,32,48,32,48,0,48,0, 48,0,48,0,63,192,48,128,48,0,48,0,48,0,48,0, 48,0,48,16,48,48,255,224,11,17,34,13,1,0,255,224, 48,32,48,32,48,0,48,0,48,0,48,0,63,128,49,0, 48,0,48,0,48,0,48,0,48,0,48,0,48,0,252,0, 14,17,34,16,1,0,3,240,12,56,16,0,32,0,96,0, 64,0,192,0,192,0,192,0,192,252,192,24,192,24,96,24, 96,24,48,24,24,24,7,224,16,17,34,18,1,0,252,63, 48,12,48,12,48,12,48,12,48,12,48,12,48,12,63,252, 48,12,48,12,48,12,48,12,48,12,48,12,48,12,252,63, 6,17,17,8,1,0,252,48,48,48,48,48,48,48,48,48, 48,48,48,48,48,48,252,10,22,44,8,253,251,31,192,3, 0,3,0,3,0,3,0,3,0,3,0,3,0,3,0,3, 0,3,0,3,0,3,0,3,0,3,0,3,0,3,0,3, 0,2,0,6,0,68,0,248,0,15,17,34,16,1,0,252, 252,48,48,48,96,48,192,49,128,51,0,54,0,52,0,62, 0,54,0,51,0,49,128,49,192,48,224,48,112,48,56,252, 30,12,17,34,13,1,0,252,0,48,0,48,0,48,0,48, 0,48,0,48,0,48,0,48,0,48,0,48,0,48,0,48, 0,48,0,48,16,48,48,255,224,20,17,51,22,1,0,240, 1,224,56,1,192,56,3,192,44,2,192,44,6,192,44,6, 192,38,4,192,38,12,192,35,8,192,35,24,192,35,152,192, 33,144,192,33,176,192,32,224,192,32,224,192,32,64,192,248, 67,240,16,17,34,18,1,0,240,63,48,12,56,12,60,12, 52,12,54,12,51,12,51,12,49,140,48,204,48,204,48,108, 48,60,48,60,48,28,48,28,252,12,14,17,34,16,1,0, 7,192,24,96,48,48,96,24,96,24,64,12,192,12,192,12, 192,12,192,12,192,12,192,8,96,24,96,16,48,48,24,96, 15,128,12,17,34,14,1,0,127,128,176,224,48,96,48,48, 48,48,48,48,48,48,48,96,48,192,63,128,48,0,48,0, 48,0,48,0,48,0,48,0,252,0,16,21,42,16,1,252, 7,192,24,96,48,48,96,24,96,24,64,12,192,12,192,12, 192,12,192,12,192,12,192,12,96,24,96,24,48,48,24,96, 15,192,0,192,0,96,0,49,0,14,14,17,34,15,1,0, 127,0,177,192,48,96,48,96,48,96,48,96,48,192,49,192, 63,0,51,0,49,128,49,128,48,192,48,224,48,96,48,112, 252,60,10,17,34,13,2,0,31,0,99,128,193,0,192,0, 224,0,240,0,124,0,126,0,31,128,7,128,1,192,0,192, 0,192,128,192,128,128,193,0,126,0,14,17,34,15,0,0, 255,252,131,4,131,4,3,0,3,0,3,0,3,0,3,0, 3,0,3,0,3,0,3,0,3,0,3,0,3,0,3,0, 15,192,16,17,34,18,1,0,252,63,48,12,48,12,48,12, 48,12,48,12,48,12,48,12,48,12,48,12,48,12,48,12, 48,12,48,24,24,24,12,48,7,224,17,17,51,18,0,0, 252,15,128,48,6,0,24,6,0,24,4,0,24,12,0,12, 12,0,12,8,0,14,24,0,6,24,0,6,16,0,3,48, 0,3,32,0,3,96,0,1,224,0,1,192,0,1,192,0, 0,128,0,22,17,51,23,0,0,252,16,124,48,16,16,48, 56,16,24,56,48,24,56,48,24,108,48,24,108,32,24,76, 32,12,198,96,12,198,96,12,134,96,13,131,64,7,131,64, 7,3,192,7,1,192,7,1,192,6,1,128,16,17,34,17, 0,0,124,63,56,28,24,24,12,48,14,48,7,96,3,192, 3,192,1,192,3,192,3,224,6,112,12,48,12,24,24,28, 56,14,252,63,15,17,34,16,0,0,240,62,56,12,24,24, 28,24,14,48,6,32,7,96,3,192,3,192,1,128,1,128, 1,128,1,128,1,128,1,128,1,128,7,224,12,17,34,14, 1,0,127,240,64,96,64,224,128,192,1,192,3,128,3,0, 7,0,6,0,14,0,28,0,24,0,56,0,48,16,112,16, 224,48,255,240,6,25,25,8,2,252,252,192,192,192,192,192, 192,192,192,192,192,192,192,192,192,192,192,192,192,192,192,192, 192,192,252,11,25,50,13,1,252,128,0,192,0,64,0,96, 0,96,0,48,0,48,0,48,0,24,0,24,0,8,0,12, 0,12,0,6,0,6,0,2,0,3,0,3,0,1,128,1, 128,1,128,0,192,0,192,0,64,0,96,6,25,25,9,1, 252,252,12,12,12,12,12,12,12,12,12,12,12,12,12,12, 12,12,12,12,12,12,12,12,12,252,11,13,26,13,1,7, 6,0,14,0,14,0,15,0,27,0,19,0,17,128,49,128, 33,192,96,192,96,192,64,96,192,64,11,1,2,13,1,253, 255,224,6,6,6,9,0,14,96,224,48,24,8,4,11,12, 24,12,1,0,31,0,97,128,225,128,1,128,1,128,31,128, 121,128,225,128,193,128,193,128,199,128,121,224,13,20,40,14, 0,0,48,0,240,0,48,0,48,0,48,0,48,0,48,0, 48,0,49,224,54,112,56,48,48,56,48,24,48,24,48,24, 48,24,48,16,48,48,56,96,15,128,10,12,24,12,1,0, 15,192,48,192,96,128,64,0,192,0,192,0,192,0,192,0, 192,0,96,64,48,192,31,0,13,20,40,14,1,0,0,96, 1,224,0,96,0,96,0,96,0,96,0,96,0,96,15,224, 48,224,96,96,64,96,192,96,192,96,192,96,192,96,192,96, 96,224,49,120,30,96,10,12,24,12,1,0,15,0,49,128, 96,192,64,192,255,192,192,0,192,0,192,0,224,0,96,64, 48,128,31,0,10,20,40,8,1,0,3,192,12,128,24,0, 16,0,48,0,48,0,48,0,48,0,255,0,48,0,48,0, 48,0,48,0,48,0,48,0,48,0,48,0,48,0,48,0, 254,0,13,18,36,13,0,250,15,24,48,240,32,96,96,96, 96,96,96,96,56,192,31,0,24,0,56,0,63,128,31,240, 48,120,192,24,192,24,192,16,112,96,31,128,14,20,40,15, 1,0,48,0,240,0,48,0,48,0,48,0,48,0,48,0, 48,0,49,224,50,48,52,48,56,48,48,48,48,48,48,48, 48,48,48,48,48,48,48,48,252,252,6,18,18,7,1,0, 48,112,48,0,0,0,48,240,48,48,48,48,48,48,48,48, 48,252,8,24,24,7,253,250,3,7,3,0,0,0,3,15, 3,3,3,3,3,3,3,3,3,3,3,3,2,2,4,248, 13,20,40,14,1,0,48,0,240,0,48,0,48,0,48,0, 48,0,48,0,48,0,49,240,48,192,49,128,51,0,52,0, 60,0,54,0,51,0,49,128,48,192,48,224,248,120,6,20, 20,7,1,0,48,240,48,48,48,48,48,48,48,48,48,48, 48,48,48,48,48,48,48,252,20,12,36,21,1,0,113,195, 128,182,108,192,56,112,192,56,112,192,48,96,192,48,96,192, 48,96,192,48,96,192,48,96,192,48,96,192,48,96,192,253, 251,240,14,12,24,15,1,0,113,224,178,48,52,48,56,48, 48,48,48,48,48,48,48,48,48,48,48,48,48,48,252,252, 12,12,24,14,1,0,15,128,48,192,96,96,64,112,192,48, 192,48,192,48,192,48,224,32,96,96,48,192,31,0,12,18, 36,14,1,250,113,192,182,224,56,96,48,48,48,48,48,48, 48,48,48,48,48,32,48,96,56,64,55,128,48,0,48,0, 48,0,48,0,48,0,252,0,13,18,36,14,1,250,15,32, 48,224,96,96,64,96,192,96,192,96,192,96,192,96,192,96, 96,224,49,96,30,96,0,96,0,96,0,96,0,96,0,96, 1,248,10,12,24,11,1,0,51,192,244,128,56,128,56,0, 48,0,48,0,48,0,48,0,48,0,48,0,48,0,252,0, 8,12,12,10,1,0,62,70,194,224,240,124,30,7,131,131, 198,124,9,17,34,9,0,0,16,0,48,0,48,0,48,0, 48,0,255,128,48,0,48,0,48,0,48,0,48,0,48,0, 48,0,48,0,48,0,49,0,30,128,14,12,24,14,0,0, 48,48,240,240,48,48,48,48,48,48,48,48,48,48,48,48, 48,48,48,112,56,188,31,48,13,12,24,13,0,0,248,120, 48,48,48,32,24,96,24,64,28,64,12,192,12,128,7,128, 7,0,7,0,2,0,19,12,36,19,0,0,248,99,224,48, 96,128,48,96,128,48,241,128,24,177,128,25,177,0,25,153, 0,13,27,0,15,26,0,14,14,0,6,14,0,4,4,0, 13,12,24,14,0,0,252,248,56,96,24,64,12,128,7,128, 7,0,7,128,13,128,8,192,16,96,48,112,248,248,14,18, 36,13,255,250,124,60,24,24,24,16,12,48,12,32,14,32, 6,96,6,64,3,192,3,128,3,128,1,128,1,0,3,0, 2,0,6,0,124,0,240,0,10,12,24,12,1,0,127,192, 65,128,131,128,3,0,6,0,12,0,28,0,24,0,48,0, 112,64,96,64,255,192,6,25,25,9,2,252,4,8,24,48, 48,48,48,24,24,24,24,48,224,56,24,24,24,24,48,48, 48,48,16,24,4,2,27,27,6,2,251,192,192,192,192,192, 192,192,192,192,192,192,192,192,192,192,192,192,192,192,192,192, 192,192,192,192,192,192,6,25,25,9,1,252,128,96,32,48, 48,48,48,96,96,96,96,48,28,48,96,96,96,96,48,48, 48,48,96,64,128,12,4,8,13,1,6,56,48,126,32,143, 192,131,128,255};
sa2blv/canASC
u8gl/u8g/u8g_font_gdr17r.c
C
gpl-3.0
11,147
/* * Copyright 2011 Ytai Ben-Tsvi. All rights reserved. * * * Redistribution and use in source and binary forms, with or without modification, are * permitted provided that the following conditions are met: * * 1. Redistributions of source code must retain the above copyright notice, this list of * conditions and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright notice, this list * of conditions and the following disclaimer in the documentation and/or other materials * provided with the distribution. * * THIS SOFTWARE IS PROVIDED "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 ARSHAN POURSOHI OR * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON * ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * * The views and conclusions contained in the software and documentation are those of the * authors and should not be interpreted as representing official policies, either expressed * or implied. */ package ioio.lib.api; import java.io.Closeable; import java.io.InputStream; import java.io.OutputStream; /** * An interface for controlling a UART module. * <p> * UART is a very common hardware communication protocol, enabling full- duplex, * asynchronous point-to-point data transfer. It typically serves for opening * consoles or as a basis for higher-level protocols, such as MIDI, RS-232 and * RS-485. Uart instances are obtained by calling * {@link ioio.lib.api.IOIO#openUart(ioio.lib.api.DigitalInput.Spec, ioio.lib.api.DigitalOutput.Spec, int, ioio.lib.api.Uart.Parity, ioio.lib.api.Uart.StopBits)}. * <p> * The UART protocol is completely symmetric - there is no "master" and "slave" * at this layer. Each end may send any number of bytes at arbitrary times, * making it very useful for terminals and terminal-controllable devices. * <p> * Working with UART is very intuitive - it just provides a standard InputStream * and/or OutputStream. Optionally, one could create a read-only or write-only * UART instances, by passing null (or INVALID_PIN) for either TX or RX pins. * <p> * The instance is alive since its creation. If the connection with the IOIO * drops at any point, the instance transitions to a disconnected state, which * every attempt to use it (except {@link #close()}) will throw a * {@link ioio.lib.api.exception.ConnectionLostException}. Whenever {@link #close()} is invoked the * instance may no longer be used. Any resources associated with it are freed * and can be reused. * <p> * Typical usage: * * <pre> * Uart uart = ioio.openUart(3, 4, 19200, Parity.NONE, StopBits.ONE); * InputStream in = uart.getInputStream(); * OutputStream out = uart.getOutputStream(); * out.write(new String("Hello").getBytes()); * int i = in.read(); // blocking * ... * uart.close(); // free UART module and pins * </pre> * * @see ioio.lib.api.IOIO#openUart(ioio.lib.api.DigitalInput.Spec, ioio.lib.api.DigitalOutput.Spec, int, ioio.lib.api.Uart.Parity, * ioio.lib.api.Uart.StopBits) */ public interface Uart extends Closeable { /** Parity-bit mode. */ enum Parity { /** No parity. */ NONE, /** Even parity. */ EVEN, /** Odd parity. */ ODD } /** Number of stop-bits. */ enum StopBits { /** One stop bit. */ ONE, /** Two stop bits. */ TWO } /** * Gets the input stream. * * @return An input stream. */ public InputStream getInputStream(); /** * Gets the output stream. * * @return An output stream. */ public OutputStream getOutputStream(); }
Cantal0p3/Networking-Aircasting
src/main/java/ioio/lib/api/Uart.java
Java
gpl-3.0
4,090
/**************************************************************************//** * @file cmsis_gcc.h * @brief CMSIS Cortex-M Core Function/Instruction Header File * @version V5.00 * @date 20. December 2016 ******************************************************************************/ /* * Copyright (c) 2009-2016 ARM Limited. All rights reserved. * * SPDX-License-Identifier: Apache-2.0 * * Licensed under the Apache License, Version 2.0 (the License); you may * not use this file except in compliance with the License. * You may obtain a copy of the License at * * www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an AS IS BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #ifndef __CMSIS_GCC_H #define __CMSIS_GCC_H /* ignore some GCC warnings */ #pragma GCC diagnostic push #pragma GCC diagnostic ignored "-Wsign-conversion" #pragma GCC diagnostic ignored "-Wconversion" #pragma GCC diagnostic ignored "-Wunused-parameter" /* CMSIS compiler specific defines */ #ifndef __ASM #define __ASM __asm #endif #ifndef __INLINE #define __INLINE inline #endif #ifndef __STATIC_INLINE #define __STATIC_INLINE static inline #endif #ifndef __NO_RETURN #define __NO_RETURN __attribute__((noreturn)) #endif #ifndef __USED #define __USED __attribute__((used)) #endif #ifndef __WEAK #define __WEAK __attribute__((weak)) #endif #ifndef __UNALIGNED_UINT32 #pragma GCC diagnostic push #pragma GCC diagnostic ignored "-Wpacked" #pragma GCC diagnostic ignored "-Wattributes" struct __attribute__((packed)) T_UINT32 { uint32_t v; }; #pragma GCC diagnostic pop #define __UNALIGNED_UINT32(x) (((struct T_UINT32 *)(x))->v) #endif #ifndef __ALIGNED #define __ALIGNED(x) __attribute__((aligned(x))) #endif #ifndef __PACKED #define __PACKED __attribute__((packed, aligned(1))) #endif /* ########################### Core Function Access ########################### */ /** \ingroup CMSIS_Core_FunctionInterface \defgroup CMSIS_Core_RegAccFunctions CMSIS Core Register Access Functions @{ */ /** \brief Enable IRQ Interrupts \details Enables IRQ interrupts by clearing the I-bit in the CPSR. Can only be executed in Privileged modes. */ __attribute__((always_inline)) __STATIC_INLINE void __enable_irq(void) { __ASM volatile ("cpsie i" : : : "memory"); } /** \brief Disable IRQ Interrupts \details Disables IRQ interrupts by setting the I-bit in the CPSR. Can only be executed in Privileged modes. */ __attribute__((always_inline)) __STATIC_INLINE void __disable_irq(void) { __ASM volatile ("cpsid i" : : : "memory"); } /** \brief Get Control Register \details Returns the content of the Control Register. \return Control Register value */ __attribute__((always_inline)) __STATIC_INLINE uint32_t __get_CONTROL(void) { uint32_t result; __ASM volatile ("MRS %0, control" : "=r" (result) ); return(result); } #if (defined (__ARM_FEATURE_CMSE ) && (__ARM_FEATURE_CMSE == 3)) /** \brief Get Control Register (non-secure) \details Returns the content of the non-secure Control Register when in secure mode. \return non-secure Control Register value */ __attribute__((always_inline)) __STATIC_INLINE uint32_t __TZ_get_CONTROL_NS(void) { uint32_t result; __ASM volatile ("MRS %0, control_ns" : "=r" (result) ); return(result); } #endif /** \brief Set Control Register \details Writes the given value to the Control Register. \param [in] control Control Register value to set */ __attribute__((always_inline)) __STATIC_INLINE void __set_CONTROL(uint32_t control) { __ASM volatile ("MSR control, %0" : : "r" (control) : "memory"); } #if (defined (__ARM_FEATURE_CMSE ) && (__ARM_FEATURE_CMSE == 3)) /** \brief Set Control Register (non-secure) \details Writes the given value to the non-secure Control Register when in secure state. \param [in] control Control Register value to set */ __attribute__((always_inline)) __STATIC_INLINE void __TZ_set_CONTROL_NS(uint32_t control) { __ASM volatile ("MSR control_ns, %0" : : "r" (control) : "memory"); } #endif /** \brief Get IPSR Register \details Returns the content of the IPSR Register. \return IPSR Register value */ __attribute__((always_inline)) __STATIC_INLINE uint32_t __get_IPSR(void) { uint32_t result; __ASM volatile ("MRS %0, ipsr" : "=r" (result) ); return(result); } /** \brief Get APSR Register \details Returns the content of the APSR Register. \return APSR Register value */ __attribute__((always_inline)) __STATIC_INLINE uint32_t __get_APSR(void) { uint32_t result; __ASM volatile ("MRS %0, apsr" : "=r" (result) ); return(result); } /** \brief Get xPSR Register \details Returns the content of the xPSR Register. \return xPSR Register value */ __attribute__((always_inline)) __STATIC_INLINE uint32_t __get_xPSR(void) { uint32_t result; __ASM volatile ("MRS %0, xpsr" : "=r" (result) ); return(result); } /** \brief Get Process Stack Pointer \details Returns the current value of the Process Stack Pointer (PSP). \return PSP Register value */ __attribute__((always_inline)) __STATIC_INLINE uint32_t __get_PSP(void) { register uint32_t result; __ASM volatile ("MRS %0, psp" : "=r" (result) ); return(result); } #if (defined (__ARM_FEATURE_CMSE ) && (__ARM_FEATURE_CMSE == 3)) /** \brief Get Process Stack Pointer (non-secure) \details Returns the current value of the non-secure Process Stack Pointer (PSP) when in secure state. \return PSP Register value */ __attribute__((always_inline)) __STATIC_INLINE uint32_t __TZ_get_PSP_NS(void) { register uint32_t result; __ASM volatile ("MRS %0, psp_ns" : "=r" (result) ); return(result); } #endif /** \brief Set Process Stack Pointer \details Assigns the given value to the Process Stack Pointer (PSP). \param [in] topOfProcStack Process Stack Pointer value to set */ __attribute__((always_inline)) __STATIC_INLINE void __set_PSP(uint32_t topOfProcStack) { __ASM volatile ("MSR psp, %0" : : "r" (topOfProcStack) : "sp"); } #if (defined (__ARM_FEATURE_CMSE ) && (__ARM_FEATURE_CMSE == 3)) /** \brief Set Process Stack Pointer (non-secure) \details Assigns the given value to the non-secure Process Stack Pointer (PSP) when in secure state. \param [in] topOfProcStack Process Stack Pointer value to set */ __attribute__((always_inline)) __STATIC_INLINE void __TZ_set_PSP_NS(uint32_t topOfProcStack) { __ASM volatile ("MSR psp_ns, %0" : : "r" (topOfProcStack) : "sp"); } #endif /** \brief Get Main Stack Pointer \details Returns the current value of the Main Stack Pointer (MSP). \return MSP Register value */ __attribute__((always_inline)) __STATIC_INLINE uint32_t __get_MSP(void) { register uint32_t result; __ASM volatile ("MRS %0, msp" : "=r" (result) ); return(result); } #if (defined (__ARM_FEATURE_CMSE ) && (__ARM_FEATURE_CMSE == 3)) /** \brief Get Main Stack Pointer (non-secure) \details Returns the current value of the non-secure Main Stack Pointer (MSP) when in secure state. \return MSP Register value */ __attribute__((always_inline)) __STATIC_INLINE uint32_t __TZ_get_MSP_NS(void) { register uint32_t result; __ASM volatile ("MRS %0, msp_ns" : "=r" (result) ); return(result); } #endif /** \brief Set Main Stack Pointer \details Assigns the given value to the Main Stack Pointer (MSP). \param [in] topOfMainStack Main Stack Pointer value to set */ __attribute__((always_inline)) __STATIC_INLINE void __set_MSP(uint32_t topOfMainStack) { __ASM volatile ("MSR msp, %0" : : "r" (topOfMainStack) : "sp"); } #if (defined (__ARM_FEATURE_CMSE ) && (__ARM_FEATURE_CMSE == 3)) /** \brief Set Main Stack Pointer (non-secure) \details Assigns the given value to the non-secure Main Stack Pointer (MSP) when in secure state. \param [in] topOfMainStack Main Stack Pointer value to set */ __attribute__((always_inline)) __STATIC_INLINE void __TZ_set_MSP_NS(uint32_t topOfMainStack) { __ASM volatile ("MSR msp_ns, %0" : : "r" (topOfMainStack) : "sp"); } #endif /** \brief Get Priority Mask \details Returns the current state of the priority mask bit from the Priority Mask Register. \return Priority Mask value */ __attribute__((always_inline)) __STATIC_INLINE uint32_t __get_PRIMASK(void) { uint32_t result; __ASM volatile ("MRS %0, primask" : "=r" (result) ); return(result); } #if (defined (__ARM_FEATURE_CMSE ) && (__ARM_FEATURE_CMSE == 3)) /** \brief Get Priority Mask (non-secure) \details Returns the current state of the non-secure priority mask bit from the Priority Mask Register when in secure state. \return Priority Mask value */ __attribute__((always_inline)) __STATIC_INLINE uint32_t __TZ_get_PRIMASK_NS(void) { uint32_t result; __ASM volatile ("MRS %0, primask_ns" : "=r" (result) ); return(result); } #endif /** \brief Set Priority Mask \details Assigns the given value to the Priority Mask Register. \param [in] priMask Priority Mask */ __attribute__((always_inline)) __STATIC_INLINE void __set_PRIMASK(uint32_t priMask) { __ASM volatile ("MSR primask, %0" : : "r" (priMask) : "memory"); } #if (defined (__ARM_FEATURE_CMSE ) && (__ARM_FEATURE_CMSE == 3)) /** \brief Set Priority Mask (non-secure) \details Assigns the given value to the non-secure Priority Mask Register when in secure state. \param [in] priMask Priority Mask */ __attribute__((always_inline)) __STATIC_INLINE void __TZ_set_PRIMASK_NS(uint32_t priMask) { __ASM volatile ("MSR primask_ns, %0" : : "r" (priMask) : "memory"); } #endif #if ((defined (__ARM_ARCH_7M__ ) && (__ARM_ARCH_7M__ == 1)) || \ (defined (__ARM_ARCH_7EM__ ) && (__ARM_ARCH_7EM__ == 1)) || \ (defined (__ARM_ARCH_8M_MAIN__ ) && (__ARM_ARCH_8M_MAIN__ == 1)) ) /** \brief Enable FIQ \details Enables FIQ interrupts by clearing the F-bit in the CPSR. Can only be executed in Privileged modes. */ __attribute__((always_inline)) __STATIC_INLINE void __enable_fault_irq(void) { __ASM volatile ("cpsie f" : : : "memory"); } /** \brief Disable FIQ \details Disables FIQ interrupts by setting the F-bit in the CPSR. Can only be executed in Privileged modes. */ __attribute__((always_inline)) __STATIC_INLINE void __disable_fault_irq(void) { __ASM volatile ("cpsid f" : : : "memory"); } /** \brief Get Base Priority \details Returns the current value of the Base Priority register. \return Base Priority register value */ __attribute__((always_inline)) __STATIC_INLINE uint32_t __get_BASEPRI(void) { uint32_t result; __ASM volatile ("MRS %0, basepri" : "=r" (result) ); return(result); } #if (defined (__ARM_FEATURE_CMSE ) && (__ARM_FEATURE_CMSE == 3)) /** \brief Get Base Priority (non-secure) \details Returns the current value of the non-secure Base Priority register when in secure state. \return Base Priority register value */ __attribute__((always_inline)) __STATIC_INLINE uint32_t __TZ_get_BASEPRI_NS(void) { uint32_t result; __ASM volatile ("MRS %0, basepri_ns" : "=r" (result) ); return(result); } #endif /** \brief Set Base Priority \details Assigns the given value to the Base Priority register. \param [in] basePri Base Priority value to set */ __attribute__((always_inline)) __STATIC_INLINE void __set_BASEPRI(uint32_t basePri) { __ASM volatile ("MSR basepri, %0" : : "r" (basePri) : "memory"); } #if (defined (__ARM_FEATURE_CMSE ) && (__ARM_FEATURE_CMSE == 3)) /** \brief Set Base Priority (non-secure) \details Assigns the given value to the non-secure Base Priority register when in secure state. \param [in] basePri Base Priority value to set */ __attribute__((always_inline)) __STATIC_INLINE void __TZ_set_BASEPRI_NS(uint32_t basePri) { __ASM volatile ("MSR basepri_ns, %0" : : "r" (basePri) : "memory"); } #endif /** \brief Set Base Priority with condition \details Assigns the given value to the Base Priority register only if BASEPRI masking is disabled, or the new value increases the BASEPRI priority level. \param [in] basePri Base Priority value to set */ __attribute__((always_inline)) __STATIC_INLINE void __set_BASEPRI_MAX(uint32_t basePri) { __ASM volatile ("MSR basepri_max, %0" : : "r" (basePri) : "memory"); } /** \brief Get Fault Mask \details Returns the current value of the Fault Mask register. \return Fault Mask register value */ __attribute__((always_inline)) __STATIC_INLINE uint32_t __get_FAULTMASK(void) { uint32_t result; __ASM volatile ("MRS %0, faultmask" : "=r" (result) ); return(result); } #if (defined (__ARM_FEATURE_CMSE ) && (__ARM_FEATURE_CMSE == 3)) /** \brief Get Fault Mask (non-secure) \details Returns the current value of the non-secure Fault Mask register when in secure state. \return Fault Mask register value */ __attribute__((always_inline)) __STATIC_INLINE uint32_t __TZ_get_FAULTMASK_NS(void) { uint32_t result; __ASM volatile ("MRS %0, faultmask_ns" : "=r" (result) ); return(result); } #endif /** \brief Set Fault Mask \details Assigns the given value to the Fault Mask register. \param [in] faultMask Fault Mask value to set */ __attribute__((always_inline)) __STATIC_INLINE void __set_FAULTMASK(uint32_t faultMask) { __ASM volatile ("MSR faultmask, %0" : : "r" (faultMask) : "memory"); } #if (defined (__ARM_FEATURE_CMSE ) && (__ARM_FEATURE_CMSE == 3)) /** \brief Set Fault Mask (non-secure) \details Assigns the given value to the non-secure Fault Mask register when in secure state. \param [in] faultMask Fault Mask value to set */ __attribute__((always_inline)) __STATIC_INLINE void __TZ_set_FAULTMASK_NS(uint32_t faultMask) { __ASM volatile ("MSR faultmask_ns, %0" : : "r" (faultMask) : "memory"); } #endif #endif /* ((defined (__ARM_ARCH_7M__ ) && (__ARM_ARCH_7M__ == 1)) || \ (defined (__ARM_ARCH_7EM__ ) && (__ARM_ARCH_7EM__ == 1)) || \ (defined (__ARM_ARCH_8M_MAIN__ ) && (__ARM_ARCH_8M_MAIN__ == 1)) ) */ #if ((defined (__ARM_ARCH_8M_MAIN__ ) && (__ARM_ARCH_8M_MAIN__ == 1)) || \ (defined (__ARM_ARCH_8M_BASE__ ) && (__ARM_ARCH_8M_BASE__ == 1)) ) /** \brief Get Process Stack Pointer Limit \details Returns the current value of the Process Stack Pointer Limit (PSPLIM). \return PSPLIM Register value */ __attribute__((always_inline)) __STATIC_INLINE uint32_t __get_PSPLIM(void) { register uint32_t result; __ASM volatile ("MRS %0, psplim" : "=r" (result) ); return(result); } #if ((defined (__ARM_FEATURE_CMSE ) && (__ARM_FEATURE_CMSE == 3)) && \ (defined (__ARM_ARCH_8M_MAIN__) && (__ARM_ARCH_8M_MAIN__ == 1)) ) /** \brief Get Process Stack Pointer Limit (non-secure) \details Returns the current value of the non-secure Process Stack Pointer Limit (PSPLIM) when in secure state. \return PSPLIM Register value */ __attribute__((always_inline)) __STATIC_INLINE uint32_t __TZ_get_PSPLIM_NS(void) { register uint32_t result; __ASM volatile ("MRS %0, psplim_ns" : "=r" (result) ); return(result); } #endif /** \brief Set Process Stack Pointer Limit \details Assigns the given value to the Process Stack Pointer Limit (PSPLIM). \param [in] ProcStackPtrLimit Process Stack Pointer Limit value to set */ __attribute__((always_inline)) __STATIC_INLINE void __set_PSPLIM(uint32_t ProcStackPtrLimit) { __ASM volatile ("MSR psplim, %0" : : "r" (ProcStackPtrLimit)); } #if ((defined (__ARM_FEATURE_CMSE ) && (__ARM_FEATURE_CMSE == 3)) && \ (defined (__ARM_ARCH_8M_MAIN__) && (__ARM_ARCH_8M_MAIN__ == 1)) ) /** \brief Set Process Stack Pointer (non-secure) \details Assigns the given value to the non-secure Process Stack Pointer Limit (PSPLIM) when in secure state. \param [in] ProcStackPtrLimit Process Stack Pointer Limit value to set */ __attribute__((always_inline)) __STATIC_INLINE void __TZ_set_PSPLIM_NS(uint32_t ProcStackPtrLimit) { __ASM volatile ("MSR psplim_ns, %0\n" : : "r" (ProcStackPtrLimit)); } #endif /** \brief Get Main Stack Pointer Limit \details Returns the current value of the Main Stack Pointer Limit (MSPLIM). \return MSPLIM Register value */ __attribute__((always_inline)) __STATIC_INLINE uint32_t __get_MSPLIM(void) { register uint32_t result; __ASM volatile ("MRS %0, msplim" : "=r" (result) ); return(result); } #if ((defined (__ARM_FEATURE_CMSE ) && (__ARM_FEATURE_CMSE == 3)) && \ (defined (__ARM_ARCH_8M_MAIN__) && (__ARM_ARCH_8M_MAIN__ == 1)) ) /** \brief Get Main Stack Pointer Limit (non-secure) \details Returns the current value of the non-secure Main Stack Pointer Limit(MSPLIM) when in secure state. \return MSPLIM Register value */ __attribute__((always_inline)) __STATIC_INLINE uint32_t __TZ_get_MSPLIM_NS(void) { register uint32_t result; __ASM volatile ("MRS %0, msplim_ns" : "=r" (result) ); return(result); } #endif /** \brief Set Main Stack Pointer Limit \details Assigns the given value to the Main Stack Pointer Limit (MSPLIM). \param [in] MainStackPtrLimit Main Stack Pointer Limit value to set */ __attribute__((always_inline)) __STATIC_INLINE void __set_MSPLIM(uint32_t MainStackPtrLimit) { __ASM volatile ("MSR msplim, %0" : : "r" (MainStackPtrLimit)); } #if ((defined (__ARM_FEATURE_CMSE ) && (__ARM_FEATURE_CMSE == 3)) && \ (defined (__ARM_ARCH_8M_MAIN__) && (__ARM_ARCH_8M_MAIN__ == 1)) ) /** \brief Set Main Stack Pointer Limit (non-secure) \details Assigns the given value to the non-secure Main Stack Pointer Limit (MSPLIM) when in secure state. \param [in] MainStackPtrLimit Main Stack Pointer value to set */ __attribute__((always_inline)) __STATIC_INLINE void __TZ_set_MSPLIM_NS(uint32_t MainStackPtrLimit) { __ASM volatile ("MSR msplim_ns, %0" : : "r" (MainStackPtrLimit)); } #endif #endif /* ((defined (__ARM_ARCH_8M_MAIN__ ) && (__ARM_ARCH_8M_MAIN__ == 1)) || \ (defined (__ARM_ARCH_8M_BASE__ ) && (__ARM_ARCH_8M_BASE__ == 1)) ) */ #if ((defined (__ARM_ARCH_7EM__ ) && (__ARM_ARCH_7EM__ == 1)) || \ (defined (__ARM_ARCH_8M_MAIN__ ) && (__ARM_ARCH_8M_MAIN__ == 1)) ) /** \brief Get FPSCR \details Returns the current value of the Floating Point Status/Control register. \return Floating Point Status/Control register value */ __attribute__((always_inline)) __STATIC_INLINE uint32_t __get_FPSCR(void) { #if ((defined (__FPU_PRESENT) && (__FPU_PRESENT == 1U)) && \ (defined (__FPU_USED ) && (__FPU_USED == 1U)) ) uint32_t result; __ASM volatile ("VMRS %0, fpscr" : "=r" (result) ); return(result); #else return(0U); #endif } /** \brief Set FPSCR \details Assigns the given value to the Floating Point Status/Control register. \param [in] fpscr Floating Point Status/Control value to set */ __attribute__((always_inline)) __STATIC_INLINE void __set_FPSCR(uint32_t fpscr) { #if ((defined (__FPU_PRESENT) && (__FPU_PRESENT == 1U)) && \ (defined (__FPU_USED ) && (__FPU_USED == 1U)) ) __ASM volatile ("VMSR fpscr, %0" : : "r" (fpscr) : "vfpcc", "memory"); #else (void)fpscr; #endif } #endif /* ((defined (__ARM_ARCH_7EM__ ) && (__ARM_ARCH_7EM__ == 1)) || \ (defined (__ARM_ARCH_8M_MAIN__ ) && (__ARM_ARCH_8M_MAIN__ == 1)) ) */ /*@} end of CMSIS_Core_RegAccFunctions */ /* ########################## Core Instruction Access ######################### */ /** \defgroup CMSIS_Core_InstructionInterface CMSIS Core Instruction Interface Access to dedicated instructions @{ */ /* Define macros for porting to both thumb1 and thumb2. * For thumb1, use low register (r0-r7), specified by constraint "l" * Otherwise, use general registers, specified by constraint "r" */ #if defined (__thumb__) && !defined (__thumb2__) #define __CMSIS_GCC_OUT_REG(r) "=l" (r) #define __CMSIS_GCC_RW_REG(r) "+l" (r) #define __CMSIS_GCC_USE_REG(r) "l" (r) #else #define __CMSIS_GCC_OUT_REG(r) "=r" (r) #define __CMSIS_GCC_RW_REG(r) "+r" (r) #define __CMSIS_GCC_USE_REG(r) "r" (r) #endif /** \brief No Operation \details No Operation does nothing. This instruction can be used for code alignment purposes. */ //__attribute__((always_inline)) __STATIC_INLINE void __NOP(void) //{ // __ASM volatile ("nop"); //} #define __NOP() __ASM volatile ("nop") /* This implementation generates debug information */ /** \brief Wait For Interrupt \details Wait For Interrupt is a hint instruction that suspends execution until one of a number of events occurs. */ //__attribute__((always_inline)) __STATIC_INLINE void __WFI(void) //{ // __ASM volatile ("wfi"); //} #define __WFI() __ASM volatile ("wfi") /* This implementation generates debug information */ /** \brief Wait For Event \details Wait For Event is a hint instruction that permits the processor to enter a low-power state until one of a number of events occurs. */ //__attribute__((always_inline)) __STATIC_INLINE void __WFE(void) //{ // __ASM volatile ("wfe"); //} #define __WFE() __ASM volatile ("wfe") /* This implementation generates debug information */ /** \brief Send Event \details Send Event is a hint instruction. It causes an event to be signaled to the CPU. */ //__attribute__((always_inline)) __STATIC_INLINE void __SEV(void) //{ // __ASM volatile ("sev"); //} #define __SEV() __ASM volatile ("sev") /* This implementation generates debug information */ /** \brief Instruction Synchronization Barrier \details Instruction Synchronization Barrier flushes the pipeline in the processor, so that all instructions following the ISB are fetched from cache or memory, after the instruction has been completed. */ __attribute__((always_inline)) __STATIC_INLINE void __ISB(void) { __ASM volatile ("isb 0xF":::"memory"); } /** \brief Data Synchronization Barrier \details Acts as a special kind of Data Memory Barrier. It completes when all explicit memory accesses before this instruction complete. */ __attribute__((always_inline)) __STATIC_INLINE void __DSB(void) { __ASM volatile ("dsb 0xF":::"memory"); } /** \brief Data Memory Barrier \details Ensures the apparent order of the explicit memory operations before and after the instruction, without ensuring their completion. */ __attribute__((always_inline)) __STATIC_INLINE void __DMB(void) { __ASM volatile ("dmb 0xF":::"memory"); } /** \brief Reverse byte order (32 bit) \details Reverses the byte order in integer value. \param [in] value Value to reverse \return Reversed value */ __attribute__((always_inline)) __STATIC_INLINE uint32_t __REV(uint32_t value) { #if (__GNUC__ > 4) || (__GNUC__ == 4 && __GNUC_MINOR__ >= 5) return __builtin_bswap32(value); #else uint32_t result; __ASM volatile ("rev %0, %1" : __CMSIS_GCC_OUT_REG (result) : __CMSIS_GCC_USE_REG (value) ); return(result); #endif } /** \brief Reverse byte order (16 bit) \details Reverses the byte order in two unsigned short values. \param [in] value Value to reverse \return Reversed value */ __attribute__((always_inline)) __STATIC_INLINE uint32_t __REV16(uint32_t value) { uint32_t result; __ASM volatile ("rev16 %0, %1" : __CMSIS_GCC_OUT_REG (result) : __CMSIS_GCC_USE_REG (value) ); return(result); } /** \brief Reverse byte order in signed short value \details Reverses the byte order in a signed short value with sign extension to integer. \param [in] value Value to reverse \return Reversed value */ __attribute__((always_inline)) __STATIC_INLINE int32_t __REVSH(int32_t value) { #if (__GNUC__ > 4) || (__GNUC__ == 4 && __GNUC_MINOR__ >= 8) return (short)__builtin_bswap16(value); #else int32_t result; __ASM volatile ("revsh %0, %1" : __CMSIS_GCC_OUT_REG (result) : __CMSIS_GCC_USE_REG (value) ); return(result); #endif } /** \brief Rotate Right in unsigned value (32 bit) \details Rotate Right (immediate) provides the value of the contents of a register rotated by a variable number of bits. \param [in] op1 Value to rotate \param [in] op2 Number of Bits to rotate \return Rotated value */ __attribute__((always_inline)) __STATIC_INLINE uint32_t __ROR(uint32_t op1, uint32_t op2) { return (op1 >> op2) | (op1 << (32U - op2)); } /** \brief Breakpoint \details Causes the processor to enter Debug state. Debug tools can use this to investigate system state when the instruction at a particular address is reached. \param [in] value is ignored by the processor. If required, a debugger can use it to store additional information about the breakpoint. */ #define __BKPT(value) __ASM volatile ("bkpt "#value) /** \brief Reverse bit order of value \details Reverses the bit order of the given value. \param [in] value Value to reverse \return Reversed value */ __attribute__((always_inline)) __STATIC_INLINE uint32_t __RBIT(uint32_t value) { uint32_t result; #if ((defined (__ARM_ARCH_7M__ ) && (__ARM_ARCH_7M__ == 1)) || \ (defined (__ARM_ARCH_7EM__ ) && (__ARM_ARCH_7EM__ == 1)) || \ (defined (__ARM_ARCH_8M_MAIN__ ) && (__ARM_ARCH_8M_MAIN__ == 1)) ) __ASM volatile ("rbit %0, %1" : "=r" (result) : "r" (value) ); #else int32_t s = (4 /*sizeof(v)*/ * 8) - 1; /* extra shift needed at end */ result = value; /* r will be reversed bits of v; first get LSB of v */ for (value >>= 1U; value; value >>= 1U) { result <<= 1U; result |= value & 1U; s--; } result <<= s; /* shift when v's highest bits are zero */ #endif return(result); } /** \brief Count leading zeros \details Counts the number of leading zeros of a data value. \param [in] value Value to count the leading zeros \return number of leading zeros in value */ #define __CLZ __builtin_clz #if ((defined (__ARM_ARCH_7M__ ) && (__ARM_ARCH_7M__ == 1)) || \ (defined (__ARM_ARCH_7EM__ ) && (__ARM_ARCH_7EM__ == 1)) || \ (defined (__ARM_ARCH_8M_MAIN__ ) && (__ARM_ARCH_8M_MAIN__ == 1)) || \ (defined (__ARM_ARCH_8M_BASE__ ) && (__ARM_ARCH_8M_BASE__ == 1)) ) /** \brief LDR Exclusive (8 bit) \details Executes a exclusive LDR instruction for 8 bit value. \param [in] ptr Pointer to data \return value of type uint8_t at (*ptr) */ __attribute__((always_inline)) __STATIC_INLINE uint8_t __LDREXB(volatile uint8_t *addr) { uint32_t result; #if (__GNUC__ > 4) || (__GNUC__ == 4 && __GNUC_MINOR__ >= 8) __ASM volatile ("ldrexb %0, %1" : "=r" (result) : "Q" (*addr) ); #else /* Prior to GCC 4.8, "Q" will be expanded to [rx, #0] which is not accepted by assembler. So has to use following less efficient pattern. */ __ASM volatile ("ldrexb %0, [%1]" : "=r" (result) : "r" (addr) : "memory" ); #endif return ((uint8_t) result); /* Add explicit type cast here */ } /** \brief LDR Exclusive (16 bit) \details Executes a exclusive LDR instruction for 16 bit values. \param [in] ptr Pointer to data \return value of type uint16_t at (*ptr) */ __attribute__((always_inline)) __STATIC_INLINE uint16_t __LDREXH(volatile uint16_t *addr) { uint32_t result; #if (__GNUC__ > 4) || (__GNUC__ == 4 && __GNUC_MINOR__ >= 8) __ASM volatile ("ldrexh %0, %1" : "=r" (result) : "Q" (*addr) ); #else /* Prior to GCC 4.8, "Q" will be expanded to [rx, #0] which is not accepted by assembler. So has to use following less efficient pattern. */ __ASM volatile ("ldrexh %0, [%1]" : "=r" (result) : "r" (addr) : "memory" ); #endif return ((uint16_t) result); /* Add explicit type cast here */ } /** \brief LDR Exclusive (32 bit) \details Executes a exclusive LDR instruction for 32 bit values. \param [in] ptr Pointer to data \return value of type uint32_t at (*ptr) */ __attribute__((always_inline)) __STATIC_INLINE uint32_t __LDREXW(volatile uint32_t *addr) { uint32_t result; __ASM volatile ("ldrex %0, %1" : "=r" (result) : "Q" (*addr) ); return(result); } /** \brief STR Exclusive (8 bit) \details Executes a exclusive STR instruction for 8 bit values. \param [in] value Value to store \param [in] ptr Pointer to location \return 0 Function succeeded \return 1 Function failed */ __attribute__((always_inline)) __STATIC_INLINE uint32_t __STREXB(uint8_t value, volatile uint8_t *addr) { uint32_t result; __ASM volatile ("strexb %0, %2, %1" : "=&r" (result), "=Q" (*addr) : "r" ((uint32_t)value) ); return(result); } /** \brief STR Exclusive (16 bit) \details Executes a exclusive STR instruction for 16 bit values. \param [in] value Value to store \param [in] ptr Pointer to location \return 0 Function succeeded \return 1 Function failed */ __attribute__((always_inline)) __STATIC_INLINE uint32_t __STREXH(uint16_t value, volatile uint16_t *addr) { uint32_t result; __ASM volatile ("strexh %0, %2, %1" : "=&r" (result), "=Q" (*addr) : "r" ((uint32_t)value) ); return(result); } /** \brief STR Exclusive (32 bit) \details Executes a exclusive STR instruction for 32 bit values. \param [in] value Value to store \param [in] ptr Pointer to location \return 0 Function succeeded \return 1 Function failed */ __attribute__((always_inline)) __STATIC_INLINE uint32_t __STREXW(uint32_t value, volatile uint32_t *addr) { uint32_t result; __ASM volatile ("strex %0, %2, %1" : "=&r" (result), "=Q" (*addr) : "r" (value) ); return(result); } /** \brief Remove the exclusive lock \details Removes the exclusive lock which is created by LDREX. */ __attribute__((always_inline)) __STATIC_INLINE void __CLREX(void) { __ASM volatile ("clrex" ::: "memory"); } #endif /* ((defined (__ARM_ARCH_7M__ ) && (__ARM_ARCH_7M__ == 1)) || \ (defined (__ARM_ARCH_7EM__ ) && (__ARM_ARCH_7EM__ == 1)) || \ (defined (__ARM_ARCH_8M_MAIN__ ) && (__ARM_ARCH_8M_MAIN__ == 1)) || \ (defined (__ARM_ARCH_8M_BASE__ ) && (__ARM_ARCH_8M_BASE__ == 1)) ) */ #if ((defined (__ARM_ARCH_7M__ ) && (__ARM_ARCH_7M__ == 1)) || \ (defined (__ARM_ARCH_7EM__ ) && (__ARM_ARCH_7EM__ == 1)) || \ (defined (__ARM_ARCH_8M_MAIN__ ) && (__ARM_ARCH_8M_MAIN__ == 1)) ) /** \brief Signed Saturate \details Saturates a signed value. \param [in] value Value to be saturated \param [in] sat Bit position to saturate to (1..32) \return Saturated value */ #define __SSAT(ARG1,ARG2) \ ({ \ int32_t __RES, __ARG1 = (ARG1); \ __ASM ("ssat %0, %1, %2" : "=r" (__RES) : "I" (ARG2), "r" (__ARG1) ); \ __RES; \ }) /** \brief Unsigned Saturate \details Saturates an unsigned value. \param [in] value Value to be saturated \param [in] sat Bit position to saturate to (0..31) \return Saturated value */ #define __USAT(ARG1,ARG2) \ ({ \ uint32_t __RES, __ARG1 = (ARG1); \ __ASM ("usat %0, %1, %2" : "=r" (__RES) : "I" (ARG2), "r" (__ARG1) ); \ __RES; \ }) /** \brief Rotate Right with Extend (32 bit) \details Moves each bit of a bitstring right by one bit. The carry input is shifted in at the left end of the bitstring. \param [in] value Value to rotate \return Rotated value */ __attribute__((always_inline)) __STATIC_INLINE uint32_t __RRX(uint32_t value) { uint32_t result; __ASM volatile ("rrx %0, %1" : __CMSIS_GCC_OUT_REG (result) : __CMSIS_GCC_USE_REG (value) ); return(result); } /** \brief LDRT Unprivileged (8 bit) \details Executes a Unprivileged LDRT instruction for 8 bit value. \param [in] ptr Pointer to data \return value of type uint8_t at (*ptr) */ __attribute__((always_inline)) __STATIC_INLINE uint8_t __LDRBT(volatile uint8_t *ptr) { uint32_t result; #if (__GNUC__ > 4) || (__GNUC__ == 4 && __GNUC_MINOR__ >= 8) __ASM volatile ("ldrbt %0, %1" : "=r" (result) : "Q" (*ptr) ); #else /* Prior to GCC 4.8, "Q" will be expanded to [rx, #0] which is not accepted by assembler. So has to use following less efficient pattern. */ __ASM volatile ("ldrbt %0, [%1]" : "=r" (result) : "r" (ptr) : "memory" ); #endif return ((uint8_t) result); /* Add explicit type cast here */ } /** \brief LDRT Unprivileged (16 bit) \details Executes a Unprivileged LDRT instruction for 16 bit values. \param [in] ptr Pointer to data \return value of type uint16_t at (*ptr) */ __attribute__((always_inline)) __STATIC_INLINE uint16_t __LDRHT(volatile uint16_t *ptr) { uint32_t result; #if (__GNUC__ > 4) || (__GNUC__ == 4 && __GNUC_MINOR__ >= 8) __ASM volatile ("ldrht %0, %1" : "=r" (result) : "Q" (*ptr) ); #else /* Prior to GCC 4.8, "Q" will be expanded to [rx, #0] which is not accepted by assembler. So has to use following less efficient pattern. */ __ASM volatile ("ldrht %0, [%1]" : "=r" (result) : "r" (ptr) : "memory" ); #endif return ((uint16_t) result); /* Add explicit type cast here */ } /** \brief LDRT Unprivileged (32 bit) \details Executes a Unprivileged LDRT instruction for 32 bit values. \param [in] ptr Pointer to data \return value of type uint32_t at (*ptr) */ __attribute__((always_inline)) __STATIC_INLINE uint32_t __LDRT(volatile uint32_t *ptr) { uint32_t result; __ASM volatile ("ldrt %0, %1" : "=r" (result) : "Q" (*ptr) ); return(result); } /** \brief STRT Unprivileged (8 bit) \details Executes a Unprivileged STRT instruction for 8 bit values. \param [in] value Value to store \param [in] ptr Pointer to location */ __attribute__((always_inline)) __STATIC_INLINE void __STRBT(uint8_t value, volatile uint8_t *ptr) { __ASM volatile ("strbt %1, %0" : "=Q" (*ptr) : "r" ((uint32_t)value) ); } /** \brief STRT Unprivileged (16 bit) \details Executes a Unprivileged STRT instruction for 16 bit values. \param [in] value Value to store \param [in] ptr Pointer to location */ __attribute__((always_inline)) __STATIC_INLINE void __STRHT(uint16_t value, volatile uint16_t *ptr) { __ASM volatile ("strht %1, %0" : "=Q" (*ptr) : "r" ((uint32_t)value) ); } /** \brief STRT Unprivileged (32 bit) \details Executes a Unprivileged STRT instruction for 32 bit values. \param [in] value Value to store \param [in] ptr Pointer to location */ __attribute__((always_inline)) __STATIC_INLINE void __STRT(uint32_t value, volatile uint32_t *ptr) { __ASM volatile ("strt %1, %0" : "=Q" (*ptr) : "r" (value) ); } #endif /* ((defined (__ARM_ARCH_7M__ ) && (__ARM_ARCH_7M__ == 1)) || \ (defined (__ARM_ARCH_7EM__ ) && (__ARM_ARCH_7EM__ == 1)) || \ (defined (__ARM_ARCH_8M_MAIN__ ) && (__ARM_ARCH_8M_MAIN__ == 1)) ) */ #if ((defined (__ARM_ARCH_8M_MAIN__ ) && (__ARM_ARCH_8M_MAIN__ == 1)) || \ (defined (__ARM_ARCH_8M_BASE__ ) && (__ARM_ARCH_8M_BASE__ == 1)) ) /** \brief Load-Acquire (8 bit) \details Executes a LDAB instruction for 8 bit value. \param [in] ptr Pointer to data \return value of type uint8_t at (*ptr) */ __attribute__((always_inline)) __STATIC_INLINE uint8_t __LDAB(volatile uint8_t *ptr) { uint32_t result; __ASM volatile ("ldab %0, %1" : "=r" (result) : "Q" (*ptr) ); return ((uint8_t) result); } /** \brief Load-Acquire (16 bit) \details Executes a LDAH instruction for 16 bit values. \param [in] ptr Pointer to data \return value of type uint16_t at (*ptr) */ __attribute__((always_inline)) __STATIC_INLINE uint16_t __LDAH(volatile uint16_t *ptr) { uint32_t result; __ASM volatile ("ldah %0, %1" : "=r" (result) : "Q" (*ptr) ); return ((uint16_t) result); } /** \brief Load-Acquire (32 bit) \details Executes a LDA instruction for 32 bit values. \param [in] ptr Pointer to data \return value of type uint32_t at (*ptr) */ __attribute__((always_inline)) __STATIC_INLINE uint32_t __LDA(volatile uint32_t *ptr) { uint32_t result; __ASM volatile ("lda %0, %1" : "=r" (result) : "Q" (*ptr) ); return(result); } /** \brief Store-Release (8 bit) \details Executes a STLB instruction for 8 bit values. \param [in] value Value to store \param [in] ptr Pointer to location */ __attribute__((always_inline)) __STATIC_INLINE void __STLB(uint8_t value, volatile uint8_t *ptr) { __ASM volatile ("stlb %1, %0" : "=Q" (*ptr) : "r" ((uint32_t)value) ); } /** \brief Store-Release (16 bit) \details Executes a STLH instruction for 16 bit values. \param [in] value Value to store \param [in] ptr Pointer to location */ __attribute__((always_inline)) __STATIC_INLINE void __STLH(uint16_t value, volatile uint16_t *ptr) { __ASM volatile ("stlh %1, %0" : "=Q" (*ptr) : "r" ((uint32_t)value) ); } /** \brief Store-Release (32 bit) \details Executes a STL instruction for 32 bit values. \param [in] value Value to store \param [in] ptr Pointer to location */ __attribute__((always_inline)) __STATIC_INLINE void __STL(uint32_t value, volatile uint32_t *ptr) { __ASM volatile ("stl %1, %0" : "=Q" (*ptr) : "r" ((uint32_t)value) ); } /** \brief Load-Acquire Exclusive (8 bit) \details Executes a LDAB exclusive instruction for 8 bit value. \param [in] ptr Pointer to data \return value of type uint8_t at (*ptr) */ __attribute__((always_inline)) __STATIC_INLINE uint8_t __LDAEXB(volatile uint8_t *ptr) { uint32_t result; __ASM volatile ("ldaexb %0, %1" : "=r" (result) : "Q" (*ptr) ); return ((uint8_t) result); } /** \brief Load-Acquire Exclusive (16 bit) \details Executes a LDAH exclusive instruction for 16 bit values. \param [in] ptr Pointer to data \return value of type uint16_t at (*ptr) */ __attribute__((always_inline)) __STATIC_INLINE uint16_t __LDAEXH(volatile uint16_t *ptr) { uint32_t result; __ASM volatile ("ldaexh %0, %1" : "=r" (result) : "Q" (*ptr) ); return ((uint16_t) result); } /** \brief Load-Acquire Exclusive (32 bit) \details Executes a LDA exclusive instruction for 32 bit values. \param [in] ptr Pointer to data \return value of type uint32_t at (*ptr) */ __attribute__((always_inline)) __STATIC_INLINE uint32_t __LDAEX(volatile uint32_t *ptr) { uint32_t result; __ASM volatile ("ldaex %0, %1" : "=r" (result) : "Q" (*ptr) ); return(result); } /** \brief Store-Release Exclusive (8 bit) \details Executes a STLB exclusive instruction for 8 bit values. \param [in] value Value to store \param [in] ptr Pointer to location \return 0 Function succeeded \return 1 Function failed */ __attribute__((always_inline)) __STATIC_INLINE uint32_t __STLEXB(uint8_t value, volatile uint8_t *ptr) { uint32_t result; __ASM volatile ("stlexb %0, %2, %1" : "=&r" (result), "=Q" (*ptr) : "r" ((uint32_t)value) ); return(result); } /** \brief Store-Release Exclusive (16 bit) \details Executes a STLH exclusive instruction for 16 bit values. \param [in] value Value to store \param [in] ptr Pointer to location \return 0 Function succeeded \return 1 Function failed */ __attribute__((always_inline)) __STATIC_INLINE uint32_t __STLEXH(uint16_t value, volatile uint16_t *ptr) { uint32_t result; __ASM volatile ("stlexh %0, %2, %1" : "=&r" (result), "=Q" (*ptr) : "r" ((uint32_t)value) ); return(result); } /** \brief Store-Release Exclusive (32 bit) \details Executes a STL exclusive instruction for 32 bit values. \param [in] value Value to store \param [in] ptr Pointer to location \return 0 Function succeeded \return 1 Function failed */ __attribute__((always_inline)) __STATIC_INLINE uint32_t __STLEX(uint32_t value, volatile uint32_t *ptr) { uint32_t result; __ASM volatile ("stlex %0, %2, %1" : "=&r" (result), "=Q" (*ptr) : "r" ((uint32_t)value) ); return(result); } #endif /* ((defined (__ARM_ARCH_8M_MAIN__ ) && (__ARM_ARCH_8M_MAIN__ == 1)) || \ (defined (__ARM_ARCH_8M_BASE__ ) && (__ARM_ARCH_8M_BASE__ == 1)) ) */ /*@}*/ /* end of group CMSIS_Core_InstructionInterface */ /* ################### Compiler specific Intrinsics ########################### */ /** \defgroup CMSIS_SIMD_intrinsics CMSIS SIMD Intrinsics Access to dedicated SIMD instructions @{ */ #if (__ARM_FEATURE_DSP == 1) /* ToDo ARMCLANG: This should be ARCH >= ARMv7-M + SIMD */ __attribute__((always_inline)) __STATIC_INLINE uint32_t __SADD8(uint32_t op1, uint32_t op2) { uint32_t result; __ASM volatile ("sadd8 %0, %1, %2" : "=r" (result) : "r" (op1), "r" (op2) ); return(result); } __attribute__((always_inline)) __STATIC_INLINE uint32_t __QADD8(uint32_t op1, uint32_t op2) { uint32_t result; __ASM volatile ("qadd8 %0, %1, %2" : "=r" (result) : "r" (op1), "r" (op2) ); return(result); } __attribute__((always_inline)) __STATIC_INLINE uint32_t __SHADD8(uint32_t op1, uint32_t op2) { uint32_t result; __ASM volatile ("shadd8 %0, %1, %2" : "=r" (result) : "r" (op1), "r" (op2) ); return(result); } __attribute__((always_inline)) __STATIC_INLINE uint32_t __UADD8(uint32_t op1, uint32_t op2) { uint32_t result; __ASM volatile ("uadd8 %0, %1, %2" : "=r" (result) : "r" (op1), "r" (op2) ); return(result); } __attribute__((always_inline)) __STATIC_INLINE uint32_t __UQADD8(uint32_t op1, uint32_t op2) { uint32_t result; __ASM volatile ("uqadd8 %0, %1, %2" : "=r" (result) : "r" (op1), "r" (op2) ); return(result); } __attribute__((always_inline)) __STATIC_INLINE uint32_t __UHADD8(uint32_t op1, uint32_t op2) { uint32_t result; __ASM volatile ("uhadd8 %0, %1, %2" : "=r" (result) : "r" (op1), "r" (op2) ); return(result); } __attribute__((always_inline)) __STATIC_INLINE uint32_t __SSUB8(uint32_t op1, uint32_t op2) { uint32_t result; __ASM volatile ("ssub8 %0, %1, %2" : "=r" (result) : "r" (op1), "r" (op2) ); return(result); } __attribute__((always_inline)) __STATIC_INLINE uint32_t __QSUB8(uint32_t op1, uint32_t op2) { uint32_t result; __ASM volatile ("qsub8 %0, %1, %2" : "=r" (result) : "r" (op1), "r" (op2) ); return(result); } __attribute__((always_inline)) __STATIC_INLINE uint32_t __SHSUB8(uint32_t op1, uint32_t op2) { uint32_t result; __ASM volatile ("shsub8 %0, %1, %2" : "=r" (result) : "r" (op1), "r" (op2) ); return(result); } __attribute__((always_inline)) __STATIC_INLINE uint32_t __USUB8(uint32_t op1, uint32_t op2) { uint32_t result; __ASM volatile ("usub8 %0, %1, %2" : "=r" (result) : "r" (op1), "r" (op2) ); return(result); } __attribute__((always_inline)) __STATIC_INLINE uint32_t __UQSUB8(uint32_t op1, uint32_t op2) { uint32_t result; __ASM volatile ("uqsub8 %0, %1, %2" : "=r" (result) : "r" (op1), "r" (op2) ); return(result); } __attribute__((always_inline)) __STATIC_INLINE uint32_t __UHSUB8(uint32_t op1, uint32_t op2) { uint32_t result; __ASM volatile ("uhsub8 %0, %1, %2" : "=r" (result) : "r" (op1), "r" (op2) ); return(result); } __attribute__((always_inline)) __STATIC_INLINE uint32_t __SADD16(uint32_t op1, uint32_t op2) { uint32_t result; __ASM volatile ("sadd16 %0, %1, %2" : "=r" (result) : "r" (op1), "r" (op2) ); return(result); } __attribute__((always_inline)) __STATIC_INLINE uint32_t __QADD16(uint32_t op1, uint32_t op2) { uint32_t result; __ASM volatile ("qadd16 %0, %1, %2" : "=r" (result) : "r" (op1), "r" (op2) ); return(result); } __attribute__((always_inline)) __STATIC_INLINE uint32_t __SHADD16(uint32_t op1, uint32_t op2) { uint32_t result; __ASM volatile ("shadd16 %0, %1, %2" : "=r" (result) : "r" (op1), "r" (op2) ); return(result); } __attribute__((always_inline)) __STATIC_INLINE uint32_t __UADD16(uint32_t op1, uint32_t op2) { uint32_t result; __ASM volatile ("uadd16 %0, %1, %2" : "=r" (result) : "r" (op1), "r" (op2) ); return(result); } __attribute__((always_inline)) __STATIC_INLINE uint32_t __UQADD16(uint32_t op1, uint32_t op2) { uint32_t result; __ASM volatile ("uqadd16 %0, %1, %2" : "=r" (result) : "r" (op1), "r" (op2) ); return(result); } __attribute__((always_inline)) __STATIC_INLINE uint32_t __UHADD16(uint32_t op1, uint32_t op2) { uint32_t result; __ASM volatile ("uhadd16 %0, %1, %2" : "=r" (result) : "r" (op1), "r" (op2) ); return(result); } __attribute__((always_inline)) __STATIC_INLINE uint32_t __SSUB16(uint32_t op1, uint32_t op2) { uint32_t result; __ASM volatile ("ssub16 %0, %1, %2" : "=r" (result) : "r" (op1), "r" (op2) ); return(result); } __attribute__((always_inline)) __STATIC_INLINE uint32_t __QSUB16(uint32_t op1, uint32_t op2) { uint32_t result; __ASM volatile ("qsub16 %0, %1, %2" : "=r" (result) : "r" (op1), "r" (op2) ); return(result); } __attribute__((always_inline)) __STATIC_INLINE uint32_t __SHSUB16(uint32_t op1, uint32_t op2) { uint32_t result; __ASM volatile ("shsub16 %0, %1, %2" : "=r" (result) : "r" (op1), "r" (op2) ); return(result); } __attribute__((always_inline)) __STATIC_INLINE uint32_t __USUB16(uint32_t op1, uint32_t op2) { uint32_t result; __ASM volatile ("usub16 %0, %1, %2" : "=r" (result) : "r" (op1), "r" (op2) ); return(result); } __attribute__((always_inline)) __STATIC_INLINE uint32_t __UQSUB16(uint32_t op1, uint32_t op2) { uint32_t result; __ASM volatile ("uqsub16 %0, %1, %2" : "=r" (result) : "r" (op1), "r" (op2) ); return(result); } __attribute__((always_inline)) __STATIC_INLINE uint32_t __UHSUB16(uint32_t op1, uint32_t op2) { uint32_t result; __ASM volatile ("uhsub16 %0, %1, %2" : "=r" (result) : "r" (op1), "r" (op2) ); return(result); } __attribute__((always_inline)) __STATIC_INLINE uint32_t __SASX(uint32_t op1, uint32_t op2) { uint32_t result; __ASM volatile ("sasx %0, %1, %2" : "=r" (result) : "r" (op1), "r" (op2) ); return(result); } __attribute__((always_inline)) __STATIC_INLINE uint32_t __QASX(uint32_t op1, uint32_t op2) { uint32_t result; __ASM volatile ("qasx %0, %1, %2" : "=r" (result) : "r" (op1), "r" (op2) ); return(result); } __attribute__((always_inline)) __STATIC_INLINE uint32_t __SHASX(uint32_t op1, uint32_t op2) { uint32_t result; __ASM volatile ("shasx %0, %1, %2" : "=r" (result) : "r" (op1), "r" (op2) ); return(result); } __attribute__((always_inline)) __STATIC_INLINE uint32_t __UASX(uint32_t op1, uint32_t op2) { uint32_t result; __ASM volatile ("uasx %0, %1, %2" : "=r" (result) : "r" (op1), "r" (op2) ); return(result); } __attribute__((always_inline)) __STATIC_INLINE uint32_t __UQASX(uint32_t op1, uint32_t op2) { uint32_t result; __ASM volatile ("uqasx %0, %1, %2" : "=r" (result) : "r" (op1), "r" (op2) ); return(result); } __attribute__((always_inline)) __STATIC_INLINE uint32_t __UHASX(uint32_t op1, uint32_t op2) { uint32_t result; __ASM volatile ("uhasx %0, %1, %2" : "=r" (result) : "r" (op1), "r" (op2) ); return(result); } __attribute__((always_inline)) __STATIC_INLINE uint32_t __SSAX(uint32_t op1, uint32_t op2) { uint32_t result; __ASM volatile ("ssax %0, %1, %2" : "=r" (result) : "r" (op1), "r" (op2) ); return(result); } __attribute__((always_inline)) __STATIC_INLINE uint32_t __QSAX(uint32_t op1, uint32_t op2) { uint32_t result; __ASM volatile ("qsax %0, %1, %2" : "=r" (result) : "r" (op1), "r" (op2) ); return(result); } __attribute__((always_inline)) __STATIC_INLINE uint32_t __SHSAX(uint32_t op1, uint32_t op2) { uint32_t result; __ASM volatile ("shsax %0, %1, %2" : "=r" (result) : "r" (op1), "r" (op2) ); return(result); } __attribute__((always_inline)) __STATIC_INLINE uint32_t __USAX(uint32_t op1, uint32_t op2) { uint32_t result; __ASM volatile ("usax %0, %1, %2" : "=r" (result) : "r" (op1), "r" (op2) ); return(result); } __attribute__((always_inline)) __STATIC_INLINE uint32_t __UQSAX(uint32_t op1, uint32_t op2) { uint32_t result; __ASM volatile ("uqsax %0, %1, %2" : "=r" (result) : "r" (op1), "r" (op2) ); return(result); } __attribute__((always_inline)) __STATIC_INLINE uint32_t __UHSAX(uint32_t op1, uint32_t op2) { uint32_t result; __ASM volatile ("uhsax %0, %1, %2" : "=r" (result) : "r" (op1), "r" (op2) ); return(result); } __attribute__((always_inline)) __STATIC_INLINE uint32_t __USAD8(uint32_t op1, uint32_t op2) { uint32_t result; __ASM volatile ("usad8 %0, %1, %2" : "=r" (result) : "r" (op1), "r" (op2) ); return(result); } __attribute__((always_inline)) __STATIC_INLINE uint32_t __USADA8(uint32_t op1, uint32_t op2, uint32_t op3) { uint32_t result; __ASM volatile ("usada8 %0, %1, %2, %3" : "=r" (result) : "r" (op1), "r" (op2), "r" (op3) ); return(result); } #define __SSAT16(ARG1,ARG2) \ ({ \ int32_t __RES, __ARG1 = (ARG1); \ __ASM ("ssat16 %0, %1, %2" : "=r" (__RES) : "I" (ARG2), "r" (__ARG1) ); \ __RES; \ }) #define __USAT16(ARG1,ARG2) \ ({ \ uint32_t __RES, __ARG1 = (ARG1); \ __ASM ("usat16 %0, %1, %2" : "=r" (__RES) : "I" (ARG2), "r" (__ARG1) ); \ __RES; \ }) __attribute__((always_inline)) __STATIC_INLINE uint32_t __UXTB16(uint32_t op1) { uint32_t result; __ASM volatile ("uxtb16 %0, %1" : "=r" (result) : "r" (op1)); return(result); } __attribute__((always_inline)) __STATIC_INLINE uint32_t __UXTAB16(uint32_t op1, uint32_t op2) { uint32_t result; __ASM volatile ("uxtab16 %0, %1, %2" : "=r" (result) : "r" (op1), "r" (op2) ); return(result); } __attribute__((always_inline)) __STATIC_INLINE uint32_t __SXTB16(uint32_t op1) { uint32_t result; __ASM volatile ("sxtb16 %0, %1" : "=r" (result) : "r" (op1)); return(result); } __attribute__((always_inline)) __STATIC_INLINE uint32_t __SXTAB16(uint32_t op1, uint32_t op2) { uint32_t result; __ASM volatile ("sxtab16 %0, %1, %2" : "=r" (result) : "r" (op1), "r" (op2) ); return(result); } __attribute__((always_inline)) __STATIC_INLINE uint32_t __SMUAD (uint32_t op1, uint32_t op2) { uint32_t result; __ASM volatile ("smuad %0, %1, %2" : "=r" (result) : "r" (op1), "r" (op2) ); return(result); } __attribute__((always_inline)) __STATIC_INLINE uint32_t __SMUADX (uint32_t op1, uint32_t op2) { uint32_t result; __ASM volatile ("smuadx %0, %1, %2" : "=r" (result) : "r" (op1), "r" (op2) ); return(result); } __attribute__((always_inline)) __STATIC_INLINE uint32_t __SMLAD (uint32_t op1, uint32_t op2, uint32_t op3) { uint32_t result; __ASM volatile ("smlad %0, %1, %2, %3" : "=r" (result) : "r" (op1), "r" (op2), "r" (op3) ); return(result); } __attribute__((always_inline)) __STATIC_INLINE uint32_t __SMLADX (uint32_t op1, uint32_t op2, uint32_t op3) { uint32_t result; __ASM volatile ("smladx %0, %1, %2, %3" : "=r" (result) : "r" (op1), "r" (op2), "r" (op3) ); return(result); } __attribute__((always_inline)) __STATIC_INLINE uint64_t __SMLALD (uint32_t op1, uint32_t op2, uint64_t acc) { union llreg_u{ uint32_t w32[2]; uint64_t w64; } llr; llr.w64 = acc; #ifndef __ARMEB__ /* Little endian */ __ASM volatile ("smlald %0, %1, %2, %3" : "=r" (llr.w32[0]), "=r" (llr.w32[1]): "r" (op1), "r" (op2) , "0" (llr.w32[0]), "1" (llr.w32[1]) ); #else /* Big endian */ __ASM volatile ("smlald %0, %1, %2, %3" : "=r" (llr.w32[1]), "=r" (llr.w32[0]): "r" (op1), "r" (op2) , "0" (llr.w32[1]), "1" (llr.w32[0]) ); #endif return(llr.w64); } __attribute__((always_inline)) __STATIC_INLINE uint64_t __SMLALDX (uint32_t op1, uint32_t op2, uint64_t acc) { union llreg_u{ uint32_t w32[2]; uint64_t w64; } llr; llr.w64 = acc; #ifndef __ARMEB__ /* Little endian */ __ASM volatile ("smlaldx %0, %1, %2, %3" : "=r" (llr.w32[0]), "=r" (llr.w32[1]): "r" (op1), "r" (op2) , "0" (llr.w32[0]), "1" (llr.w32[1]) ); #else /* Big endian */ __ASM volatile ("smlaldx %0, %1, %2, %3" : "=r" (llr.w32[1]), "=r" (llr.w32[0]): "r" (op1), "r" (op2) , "0" (llr.w32[1]), "1" (llr.w32[0]) ); #endif return(llr.w64); } __attribute__((always_inline)) __STATIC_INLINE uint32_t __SMUSD (uint32_t op1, uint32_t op2) { uint32_t result; __ASM volatile ("smusd %0, %1, %2" : "=r" (result) : "r" (op1), "r" (op2) ); return(result); } __attribute__((always_inline)) __STATIC_INLINE uint32_t __SMUSDX (uint32_t op1, uint32_t op2) { uint32_t result; __ASM volatile ("smusdx %0, %1, %2" : "=r" (result) : "r" (op1), "r" (op2) ); return(result); } __attribute__((always_inline)) __STATIC_INLINE uint32_t __SMLSD (uint32_t op1, uint32_t op2, uint32_t op3) { uint32_t result; __ASM volatile ("smlsd %0, %1, %2, %3" : "=r" (result) : "r" (op1), "r" (op2), "r" (op3) ); return(result); } __attribute__((always_inline)) __STATIC_INLINE uint32_t __SMLSDX (uint32_t op1, uint32_t op2, uint32_t op3) { uint32_t result; __ASM volatile ("smlsdx %0, %1, %2, %3" : "=r" (result) : "r" (op1), "r" (op2), "r" (op3) ); return(result); } __attribute__((always_inline)) __STATIC_INLINE uint64_t __SMLSLD (uint32_t op1, uint32_t op2, uint64_t acc) { union llreg_u{ uint32_t w32[2]; uint64_t w64; } llr; llr.w64 = acc; #ifndef __ARMEB__ /* Little endian */ __ASM volatile ("smlsld %0, %1, %2, %3" : "=r" (llr.w32[0]), "=r" (llr.w32[1]): "r" (op1), "r" (op2) , "0" (llr.w32[0]), "1" (llr.w32[1]) ); #else /* Big endian */ __ASM volatile ("smlsld %0, %1, %2, %3" : "=r" (llr.w32[1]), "=r" (llr.w32[0]): "r" (op1), "r" (op2) , "0" (llr.w32[1]), "1" (llr.w32[0]) ); #endif return(llr.w64); } __attribute__((always_inline)) __STATIC_INLINE uint64_t __SMLSLDX (uint32_t op1, uint32_t op2, uint64_t acc) { union llreg_u{ uint32_t w32[2]; uint64_t w64; } llr; llr.w64 = acc; #ifndef __ARMEB__ /* Little endian */ __ASM volatile ("smlsldx %0, %1, %2, %3" : "=r" (llr.w32[0]), "=r" (llr.w32[1]): "r" (op1), "r" (op2) , "0" (llr.w32[0]), "1" (llr.w32[1]) ); #else /* Big endian */ __ASM volatile ("smlsldx %0, %1, %2, %3" : "=r" (llr.w32[1]), "=r" (llr.w32[0]): "r" (op1), "r" (op2) , "0" (llr.w32[1]), "1" (llr.w32[0]) ); #endif return(llr.w64); } __attribute__((always_inline)) __STATIC_INLINE uint32_t __SEL (uint32_t op1, uint32_t op2) { uint32_t result; __ASM volatile ("sel %0, %1, %2" : "=r" (result) : "r" (op1), "r" (op2) ); return(result); } __attribute__((always_inline)) __STATIC_INLINE int32_t __QADD( int32_t op1, int32_t op2) { int32_t result; __ASM volatile ("qadd %0, %1, %2" : "=r" (result) : "r" (op1), "r" (op2) ); return(result); } __attribute__((always_inline)) __STATIC_INLINE int32_t __QSUB( int32_t op1, int32_t op2) { int32_t result; __ASM volatile ("qsub %0, %1, %2" : "=r" (result) : "r" (op1), "r" (op2) ); return(result); } #if 0 #define __PKHBT(ARG1,ARG2,ARG3) \ ({ \ uint32_t __RES, __ARG1 = (ARG1), __ARG2 = (ARG2); \ __ASM ("pkhbt %0, %1, %2, lsl %3" : "=r" (__RES) : "r" (__ARG1), "r" (__ARG2), "I" (ARG3) ); \ __RES; \ }) #define __PKHTB(ARG1,ARG2,ARG3) \ ({ \ uint32_t __RES, __ARG1 = (ARG1), __ARG2 = (ARG2); \ if (ARG3 == 0) \ __ASM ("pkhtb %0, %1, %2" : "=r" (__RES) : "r" (__ARG1), "r" (__ARG2) ); \ else \ __ASM ("pkhtb %0, %1, %2, asr %3" : "=r" (__RES) : "r" (__ARG1), "r" (__ARG2), "I" (ARG3) ); \ __RES; \ }) #endif #define __PKHBT(ARG1,ARG2,ARG3) ( ((((uint32_t)(ARG1)) ) & 0x0000FFFFUL) | \ ((((uint32_t)(ARG2)) << (ARG3)) & 0xFFFF0000UL) ) #define __PKHTB(ARG1,ARG2,ARG3) ( ((((uint32_t)(ARG1)) ) & 0xFFFF0000UL) | \ ((((uint32_t)(ARG2)) >> (ARG3)) & 0x0000FFFFUL) ) __attribute__((always_inline)) __STATIC_INLINE int32_t __SMMLA (int32_t op1, int32_t op2, int32_t op3) { int32_t result; __ASM volatile ("smmla %0, %1, %2, %3" : "=r" (result): "r" (op1), "r" (op2), "r" (op3) ); return(result); } #endif /* (__ARM_FEATURE_DSP == 1) */ /*@} end of group CMSIS_SIMD_intrinsics */ #pragma GCC diagnostic pop #endif /* __CMSIS_GCC_H */
dkmorb/axoloti
CMSIS/Include/cmsis_gcc.h
C
gpl-3.0
57,355
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <!--NewPage--> <HTML> <HEAD> <!-- Generated by javadoc (build 1.6.0_35) on Sat Oct 06 21:59:20 CEST 2012 --> <TITLE> MockitoLogger (Mockito 1.9.5 API) </TITLE> <META NAME="date" CONTENT="2012-10-06"> <LINK REL ="stylesheet" TYPE="text/css" HREF="../../../../stylesheet.css" TITLE="Style"> <SCRIPT type="text/javascript"> function windowTitle() { if (location.href.indexOf('is-external=true') == -1) { parent.document.title="MockitoLogger (Mockito 1.9.5 API)"; } } </SCRIPT> <NOSCRIPT> </NOSCRIPT> </HEAD> <BODY BGCOLOR="white" onload="windowTitle();"> <HR> <!-- ========= START OF TOP NAVBAR ======= --> <A NAME="navbar_top"><!-- --></A> <A HREF="#skip-navbar_top" title="Skip navigation links"></A> <TABLE BORDER="0" WIDTH="100%" CELLPADDING="1" CELLSPACING="0" SUMMARY=""> <TR> <TD COLSPAN=2 BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A NAME="navbar_top_firstrow"><!-- --></A> <TABLE BORDER="0" CELLPADDING="0" CELLSPACING="3" SUMMARY=""> <TR ALIGN="center" VALIGN="top"> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../overview-summary.html"><FONT CLASS="NavBarFont1"><B>Overview</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="package-summary.html"><FONT CLASS="NavBarFont1"><B>Package</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#FFFFFF" CLASS="NavBarCell1Rev"> &nbsp;<FONT CLASS="NavBarFont1Rev"><B>Class</B></FONT>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="class-use/MockitoLogger.html"><FONT CLASS="NavBarFont1"><B>Use</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="package-tree.html"><FONT CLASS="NavBarFont1"><B>Tree</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../deprecated-list.html"><FONT CLASS="NavBarFont1"><B>Deprecated</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../index-all.html"><FONT CLASS="NavBarFont1"><B>Index</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../help-doc.html"><FONT CLASS="NavBarFont1"><B>Help</B></FONT></A>&nbsp;</TD> </TR> </TABLE> </TD> <TD ALIGN="right" VALIGN="top" ROWSPAN=3><EM> <!-- Note there is a weird javadoc task bug if using the double quote char \" that causes an 'illegal package name' error --> <!-- using the beautify plugin for jQuery from https://bitbucket.org/larscorneliussen/beautyofcode/ --> <script type="text/javascript"> var shBaseURL = '../../../../js/sh-2.1.382/'; </script> <script type="text/javascript" src="../../../../js/jquery-1.7.min.js"></script> <script type="text/javascript" src="../../../../js/jquery.beautyOfCode-min.js"></script> <script type="text/javascript"> /* Apply beautification of code */ var usingOldIE = false; if($.browser.msie && parseInt($.browser.version) < 9) usingOldIE = true; if(!usingOldIE) { $.beautyOfCode.init({ theme : 'Eclipse', brushes: ['Java'] }); /* Add name & version to header */ $(function() { $('td.NavBarCell1[colspan=2]').each(function(index, element) { var jqueryTD = $(element); jqueryTD.after( $('<td><em><strong>Mockito 1.9.5 API</strong></em></td>').attr('class','NavBarCell1').attr('id','mockito-version-header') ); jqueryTD.removeAttr('colspan'); }) }) } </script> </EM> </TD> </TR> <TR> <TD BGCOLOR="white" CLASS="NavBarCell2"><FONT SIZE="-2"> &nbsp;<A HREF="../../../../org/mockito/internal/util/MockCreationValidator.html" title="class in org.mockito.internal.util"><B>PREV CLASS</B></A>&nbsp; &nbsp;<A HREF="../../../../org/mockito/internal/util/MockitoSpy.html" title="interface in org.mockito.internal.util"><B>NEXT CLASS</B></A></FONT></TD> <TD BGCOLOR="white" CLASS="NavBarCell2"><FONT SIZE="-2"> <A HREF="../../../../index.html?org/mockito/internal/util/MockitoLogger.html" target="_top"><B>FRAMES</B></A> &nbsp; &nbsp;<A HREF="MockitoLogger.html" target="_top"><B>NO FRAMES</B></A> &nbsp; &nbsp;<SCRIPT type="text/javascript"> <!-- if(window==top) { document.writeln('<A HREF="../../../../allclasses-noframe.html"><B>All Classes</B></A>'); } //--> </SCRIPT> <NOSCRIPT> <A HREF="../../../../allclasses-noframe.html"><B>All Classes</B></A> </NOSCRIPT> </FONT></TD> </TR> <TR> <TD VALIGN="top" CLASS="NavBarCell3"><FONT SIZE="-2"> SUMMARY:&nbsp;NESTED&nbsp;|&nbsp;FIELD&nbsp;|&nbsp;CONSTR&nbsp;|&nbsp;<A HREF="#method_summary">METHOD</A></FONT></TD> <TD VALIGN="top" CLASS="NavBarCell3"><FONT SIZE="-2"> DETAIL:&nbsp;FIELD&nbsp;|&nbsp;CONSTR&nbsp;|&nbsp;<A HREF="#method_detail">METHOD</A></FONT></TD> </TR> </TABLE> <A NAME="skip-navbar_top"></A> <!-- ========= END OF TOP NAVBAR ========= --> <HR> <!-- ======== START OF CLASS DATA ======== --> <H2> <FONT SIZE="-1"> org.mockito.internal.util</FONT> <BR> Interface MockitoLogger</H2> <DL> <DT><B>All Known Implementing Classes:</B> <DD><A HREF="../../../../org/mockito/internal/util/ConsoleMockitoLogger.html" title="class in org.mockito.internal.util">ConsoleMockitoLogger</A>, <A HREF="../../../../org/mockito/internal/util/SimpleMockitoLogger.html" title="class in org.mockito.internal.util">SimpleMockitoLogger</A></DD> </DL> <HR> <DL> <DT><PRE>public interface <B>MockitoLogger</B></DL> </PRE> <P> <HR> <P> <!-- ========== METHOD SUMMARY =========== --> <A NAME="method_summary"><!-- --></A> <TABLE BORDER="1" WIDTH="100%" CELLPADDING="3" CELLSPACING="0" SUMMARY=""> <TR BGCOLOR="#CCCCFF" CLASS="TableHeadingColor"> <TH ALIGN="left" COLSPAN="2"><FONT SIZE="+2"> <B>Method Summary</B></FONT></TH> </TR> <TR BGCOLOR="white" CLASS="TableRowColor"> <TD ALIGN="right" VALIGN="top" WIDTH="1%"><FONT SIZE="-1"> <CODE>&nbsp;void</CODE></FONT></TD> <TD><CODE><B><A HREF="../../../../org/mockito/internal/util/MockitoLogger.html#log(java.lang.Object)">log</A></B>(java.lang.Object&nbsp;what)</CODE> <BR> &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</TD> </TR> </TABLE> &nbsp; <P> <!-- ============ METHOD DETAIL ========== --> <A NAME="method_detail"><!-- --></A> <TABLE BORDER="1" WIDTH="100%" CELLPADDING="3" CELLSPACING="0" SUMMARY=""> <TR BGCOLOR="#CCCCFF" CLASS="TableHeadingColor"> <TH ALIGN="left" COLSPAN="1"><FONT SIZE="+2"> <B>Method Detail</B></FONT></TH> </TR> </TABLE> <A NAME="log(java.lang.Object)"><!-- --></A><H3> log</H3> <PRE> void <B>log</B>(java.lang.Object&nbsp;what)</PRE> <DL> <DD><DL> </DL> </DD> </DL> <!-- ========= END OF CLASS DATA ========= --> <HR> <!-- ======= START OF BOTTOM NAVBAR ====== --> <A NAME="navbar_bottom"><!-- --></A> <A HREF="#skip-navbar_bottom" title="Skip navigation links"></A> <TABLE BORDER="0" WIDTH="100%" CELLPADDING="1" CELLSPACING="0" SUMMARY=""> <TR> <TD COLSPAN=2 BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A NAME="navbar_bottom_firstrow"><!-- --></A> <TABLE BORDER="0" CELLPADDING="0" CELLSPACING="3" SUMMARY=""> <TR ALIGN="center" VALIGN="top"> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../overview-summary.html"><FONT CLASS="NavBarFont1"><B>Overview</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="package-summary.html"><FONT CLASS="NavBarFont1"><B>Package</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#FFFFFF" CLASS="NavBarCell1Rev"> &nbsp;<FONT CLASS="NavBarFont1Rev"><B>Class</B></FONT>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="class-use/MockitoLogger.html"><FONT CLASS="NavBarFont1"><B>Use</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="package-tree.html"><FONT CLASS="NavBarFont1"><B>Tree</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../deprecated-list.html"><FONT CLASS="NavBarFont1"><B>Deprecated</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../index-all.html"><FONT CLASS="NavBarFont1"><B>Index</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../help-doc.html"><FONT CLASS="NavBarFont1"><B>Help</B></FONT></A>&nbsp;</TD> </TR> </TABLE> </TD> <TD ALIGN="right" VALIGN="top" ROWSPAN=3><EM> <!-- Note there is a weird javadoc task bug if using the double quote char \" that causes an 'illegal package name' error --> <!-- using the beautify plugin for jQuery from https://bitbucket.org/larscorneliussen/beautyofcode/ --> <script type="text/javascript"> var shBaseURL = '../../../../js/sh-2.1.382/'; </script> <script type="text/javascript" src="../../../../js/jquery-1.7.min.js"></script> <script type="text/javascript" src="../../../../js/jquery.beautyOfCode-min.js"></script> <script type="text/javascript"> /* Apply beautification of code */ var usingOldIE = false; if($.browser.msie && parseInt($.browser.version) < 9) usingOldIE = true; if(!usingOldIE) { $.beautyOfCode.init({ theme : 'Eclipse', brushes: ['Java'] }); /* Add name & version to header */ $(function() { $('td.NavBarCell1[colspan=2]').each(function(index, element) { var jqueryTD = $(element); jqueryTD.after( $('<td><em><strong>Mockito 1.9.5 API</strong></em></td>').attr('class','NavBarCell1').attr('id','mockito-version-header') ); jqueryTD.removeAttr('colspan'); }) }) } </script> </EM> </TD> </TR> <TR> <TD BGCOLOR="white" CLASS="NavBarCell2"><FONT SIZE="-2"> &nbsp;<A HREF="../../../../org/mockito/internal/util/MockCreationValidator.html" title="class in org.mockito.internal.util"><B>PREV CLASS</B></A>&nbsp; &nbsp;<A HREF="../../../../org/mockito/internal/util/MockitoSpy.html" title="interface in org.mockito.internal.util"><B>NEXT CLASS</B></A></FONT></TD> <TD BGCOLOR="white" CLASS="NavBarCell2"><FONT SIZE="-2"> <A HREF="../../../../index.html?org/mockito/internal/util/MockitoLogger.html" target="_top"><B>FRAMES</B></A> &nbsp; &nbsp;<A HREF="MockitoLogger.html" target="_top"><B>NO FRAMES</B></A> &nbsp; &nbsp;<SCRIPT type="text/javascript"> <!-- if(window==top) { document.writeln('<A HREF="../../../../allclasses-noframe.html"><B>All Classes</B></A>'); } //--> </SCRIPT> <NOSCRIPT> <A HREF="../../../../allclasses-noframe.html"><B>All Classes</B></A> </NOSCRIPT> </FONT></TD> </TR> <TR> <TD VALIGN="top" CLASS="NavBarCell3"><FONT SIZE="-2"> SUMMARY:&nbsp;NESTED&nbsp;|&nbsp;FIELD&nbsp;|&nbsp;CONSTR&nbsp;|&nbsp;<A HREF="#method_summary">METHOD</A></FONT></TD> <TD VALIGN="top" CLASS="NavBarCell3"><FONT SIZE="-2"> DETAIL:&nbsp;FIELD&nbsp;|&nbsp;CONSTR&nbsp;|&nbsp;<A HREF="#method_detail">METHOD</A></FONT></TD> </TR> </TABLE> <A NAME="skip-navbar_bottom"></A> <!-- ======== END OF BOTTOM NAVBAR ======= --> <HR> </BODY> </HTML>
robertsmieja/Gw2InfoViewer
lib/mockito-1.9.5/javadoc/org/mockito/internal/util/MockitoLogger.html
HTML
gpl-3.0
11,531
/* * Crafter Studio Web-content authoring solution * Copyright (C) 2007-2016 Crafter Software Corporation. * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package org.craftercms.studio.api.v1.dal; import java.io.Serializable; public class NavigationOrderSequence implements Serializable { private static final long serialVersionUID = 3646263089226872560L; protected String folderId; protected String site; protected String path; protected double maxCount; public String getFolderId() { return folderId; } public void setFolderId(String folderId) { this.folderId = folderId; } public String getSite() { return site; } public void setSite(String site) { this.site = site; } public String getPath() { return path; } public void setPath(String path) { this.path = path; } public double getMaxCount() { return maxCount; } public void setMaxCount(double maxCount) { this.maxCount = maxCount; } }
dejan-brkic/studio2
src/main/java/org/craftercms/studio/api/v1/dal/NavigationOrderSequence.java
Java
gpl-3.0
1,558
<?php $l['name']='Tasques'; $l['description']='Per favor, introduïu una descripció'; $lang['link_type'][12]=$l['status']='Estat'; $l['statuses']['NEEDS-ACTION']= 'Sol·licitud d\'Acció'; $l['statuses']['ACCEPTED']= 'Acceptada'; $l['statuses']['DECLINED']= 'Rebutjada'; $l['statuses']['TENTATIVE']= 'Temptativa'; $l['statuses']['DELEGATED']= 'Delegat'; $l['statuses']['COMPLETED']= 'Complert'; $l['statuses']['IN-PROCESS']= 'En curs'; $l['scheduled_call']='Trucada agendada per a %s'; $l['import_success']='%s tasques han estat importades'; $l['dueAtdate']='Venç en %s'; $l['list']='Llistat de tasques'; $l['tasklistChanged']="* Llistat de tasques ha canviat de '%s' a '%s'"; $l['statusChanged']="* Estat ha canviat de '%s' a '%s'"; $l['multipleSelected']='Selecció múltiple de llistats de tasques'; $l['incomplete_delete']='No teniu permís per eliminar totes les tasques seleccionades'; $l["task"]= 'Tasca'; $l["noTask"]= 'No hi ha tasques per mostrar'; $l["tasks"]= 'Tasques'; $l["addTask"]= 'Afegir tasca...'; $l["tasklist"]= 'Llistat de tasques'; $l["tasklists"]= 'Llistats de tasques'; $l["showCompletedTasks"]= 'Mostrar tasques completades'; $l["filter"]= 'Filtre'; $l["dueDate"]= 'Data de caducitat'; $l["dueAt"]= 'Caduca'; $l["needsAction"]= 'Cal intervenció'; $l["accepted"]= 'Acceptada'; $l["declined"]= 'Rebutjada'; $l["tentative"]= 'Temptativa'; $l["delegated"]= 'Delegat'; $l["completed"]= 'Complert'; $l["inProcess"]= 'En procés'; $l["repeatEvery"]= 'Repetir cada'; $l["atDays"]= 'Diària'; $l["repeatUntil"]= 'Repetir fins'; $l["repeatForever"]= 'Repetir per sempre'; $l["recurrence"]= 'Repetició'; $l["options"]= 'Opcions'; $l["createLink"]= 'Crear un enllaç'; $l["startsAt"]='Inici'; $l["showInactiveTasks"]='Mostrar tasques inactives'; $l["remindMe"]= 'Recordatori'; $l["scheduleCall"]='Agendar una trucada telefònica'; $l["call"]='Trucada telefònica'; $l["selectIcalendarFile"]='Seleccioneu un arxiu d\'icalendar (*.ics)'; $l["completedAt"]='Completat el'; $l["taskDefaults"]='Configuració per defecte per les tasques'; $l["daysBeforeStart"]='Dies abans de començar'; $l["defaultTasklist"]='Llistat de tasques per defecte'; $l["visibleTasklists"]='Llistat de tasques visibles'; $l["visible"]='Visible'; $l["continueTask"]='Continuar tasca'; $l["categories"]='Categories'; $l["category"]='Categoriay'; $l["selectCategory"]='Seleccionar categoria'; $l["noTasklistSelected"]='Heu de seleccionar almenys 1 llistat de tasques.'; $l["selectAllTasklists"]='Seleccionar tots els llistats de tasques'; $l["globalCategory"]='Categoria global'; $l["showFutureTasks"]='Mostrar tasques futures'; $l["incompleteTasks"]='Tasques incomplertes'; $l["dueInSevenDays"]='Esperats en set dies'; $l["overDue"]='Retrassat'; $l["futureTasks"]='Tasques futures'; $l["all"]='Tot'; $l["active"]='Actiu';
deependhulla/powermail-debian9
files/rootdir/usr/local/src/groupoffice-6.2/groupoffice-6.2-setup-www/modules/tasks/language/ca.php
PHP
gpl-3.0
2,812
/* * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS HEADER. * * Copyright 1997-2007 Sun Microsystems, Inc. All rights reserved. * * The contents of this file are subject to the terms of either the GNU * General Public License Version 2 only ("GPL") or the Common Development * and Distribution License("CDDL") (collectively, the "License"). You * may not use this file except in compliance with the License. You can obtain * a copy of the License at https://glassfish.dev.java.net/public/CDDL+GPL.html * or glassfish/bootstrap/legal/LICENSE.txt. See the License for the specific * language governing permissions and limitations under the License. * * When distributing the software, include this License Header Notice in each * file and include the License file at glassfish/bootstrap/legal/LICENSE.txt. * Sun designates this particular file as subject to the "Classpath" exception * as provided by Sun in the GPL Version 2 section of the License file that * accompanied this code. If applicable, add the following below the License * Header, with the fields enclosed by brackets [] replaced by your own * identifying information: "Portions Copyrighted [year] * [name of copyright owner]" * * Contributor(s): * * If you wish your version of this file to be governed by only the CDDL or * only the GPL Version 2, indicate your decision by adding "[Contributor] * elects to include this software in this distribution under the [CDDL or GPL * Version 2] license." If you don't indicate a single choice of license, a * recipient has the option to distribute your version of this file under * either the CDDL, the GPL Version 2 or to extend the choice of license to * its licensees as provided above. However, if you add GPL Version 2 code * and therefore, elected the GPL Version 2 license, then the option applies * only if the new code is made subject to such option by the copyright * holder. */ package javax.mail.event; /** * This is the Listener interface for MessageCount events. * * @author John Mani */ public interface MessageCountListener extends java.util.EventListener { /** * Invoked when messages are added into a folder. */ public void messagesAdded(MessageCountEvent e); /** * Invoked when messages are removed (expunged) from a folder. */ public void messagesRemoved(MessageCountEvent e); }
arthurzaczek/kolab-android
javamail/javax/mail/event/MessageCountListener.java
Java
gpl-3.0
2,391
/***************************************************************************** ** $Source: /cygdrive/d/Private/_SVNROOT/bluemsx/blueMSX/Src/Arch/ArchText.h,v $ ** ** $Revision: 1.4 $ ** ** $Date: 2008-03-30 18:38:39 $ ** ** More info: http://www.bluemsx.com ** ** Copyright (C) 2003-2006 Daniel Vik ** ** 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., 675 Mass Ave, Cambridge, MA 02139, USA. ** ****************************************************************************** */ #ifndef ARCH_TEXT_H #define ARCH_TEXT_H typedef struct ArchText ArchText; ArchText* archTextCreate(int height, int color, int rightAligned); void archTextDestroy(ArchText* text); void archTextDraw(ArchText* text, void* dcDest, int xDest, int yDest, int width, int height, char* string); #endif
pokebyte/blueberryMSX
Src/Arch/ArchText.h
C
gpl-3.0
1,401
----------------------------------- -- Area: Aht Urhgan Whitegate -- NPC: Door: Kokba Hostel -- Standard Info NPC ----------------------------------- package.loaded["scripts/zones/Aht_Urhgan_Whitegate/TextIDs"] = nil; ----------------------------------- require("scripts/zones/Aht_Urhgan_Whitegate/TextIDs"); ----------------------------------- function onTrade(player,npc,trade) end; function onTrigger(player,npc) --player:startEvent(70); end; function onEventUpdate(player,csid,option) -- printf("CSID: %u",csid); -- printf("RESULT: %u",option); end; function onEventFinish(player,csid,option) -- printf("CSID: %u",csid); -- printf("RESULT: %u",option); end;
Whitechaser/darkstar
scripts/zones/Aht_Urhgan_Whitegate/npcs/_1ee.lua
Lua
gpl-3.0
684
<?php /* * @copyright 2014 Mautic Contributors. All rights reserved * @author Mautic * * @link http://mautic.org * * @license GNU/GPLv3 http://www.gnu.org/licenses/gpl-3.0.html */ namespace Mautic\PointBundle\EventListener; use Mautic\CoreBundle\EventListener\CommonSubscriber; use Mautic\LeadBundle\Entity\PointsChangeLog; use Mautic\LeadBundle\Event\LeadEvent; use Mautic\LeadBundle\Event\LeadMergeEvent; use Mautic\LeadBundle\Event\LeadTimelineEvent; use Mautic\LeadBundle\Event\PointsChangeEvent; use Mautic\LeadBundle\LeadEvents; use Mautic\PointBundle\Model\TriggerModel; /** * Class LeadSubscriber. */ class LeadSubscriber extends CommonSubscriber { /** * @var TriggerModel */ protected $triggerModel; /** * LeadSubscriber constructor. * * @param TriggerModel $triggerModel */ public function __construct(TriggerModel $triggerModel) { $this->triggerModel = $triggerModel; } /** * {@inheritdoc} */ public static function getSubscribedEvents() { return [ LeadEvents::LEAD_POINTS_CHANGE => ['onLeadPointsChange', 0], LeadEvents::TIMELINE_ON_GENERATE => ['onTimelineGenerate', 0], LeadEvents::LEAD_POST_MERGE => ['onLeadMerge', 0], LeadEvents::LEAD_POST_SAVE => ['onLeadSave', -1], ]; } /** * Trigger applicable events for the lead. * * @param PointsChangeEvent $event */ public function onLeadPointsChange(PointsChangeEvent $event) { $this->triggerModel->triggerEvents($event->getLead()); } /** * Handle point triggers for new leads (including 0 point triggers). * * @param LeadEvent $event */ public function onLeadSave(LeadEvent $event) { if ($event->isNew()) { $this->triggerModel->triggerEvents($event->getLead()); } } /** * Compile events for the lead timeline. * * @param LeadTimelineEvent $event */ public function onTimelineGenerate(LeadTimelineEvent $event) { // Set available event types $eventTypeKey = 'point.gained'; $eventTypeName = $this->translator->trans('mautic.point.event.gained'); $event->addEventType($eventTypeKey, $eventTypeName); if (!$event->isApplicable($eventTypeKey)) { return; } $lead = $event->getLead(); /** @var \Mautic\PageBundle\Entity\HitRepository $hitRepository */ $logRepository = $this->em->getRepository('MauticLeadBundle:PointsChangeLog'); $logs = $logRepository->getLeadTimelineEvents($lead->getId(), $event->getQueryOptions()); // Add to counter $event->addToCounter($eventTypeKey, $logs); if (!$event->isEngagementCount()) { // Add the logs to the event array foreach ($logs['results'] as $log) { $event->addEvent( [ 'event' => $eventTypeKey, 'eventLabel' => $log['eventName'].' / '.$log['delta'], 'eventType' => $eventTypeName, 'timestamp' => $log['dateAdded'], 'extra' => [ 'log' => $log, ], 'icon' => 'fa-calculator', ] ); } } } /** * @param LeadMergeEvent $event */ public function onLeadMerge(LeadMergeEvent $event) { $this->em->getRepository('MauticPointBundle:LeadPointLog')->updateLead( $event->getLoser()->getId(), $event->getVictor()->getId() ); $this->em->getRepository('MauticPointBundle:LeadTriggerLog')->updateLead( $event->getLoser()->getId(), $event->getVictor()->getId() ); } }
optimum-web/mautic
app/bundles/PointBundle/EventListener/LeadSubscriber.php
PHP
gpl-3.0
3,952
<?php namespace Neos\Flow\Persistence\Doctrine\Migrations; use Doctrine\Migrations\AbstractMigration; use Doctrine\DBAL\Schema\Schema; /** * Adjust event log table to schema valid table structure */ class Version20150224171108 extends AbstractMigration { /** * @param Schema $schema * @return void */ public function up(Schema $schema): void { $this->abortIf($this->connection->getDatabasePlatform()->getName() != "postgresql"); $this->addSql("ALTER TABLE typo3_neos_eventlog_domain_model_event DROP CONSTRAINT FK_30AB3A75B684C08"); $this->addSql("ALTER TABLE typo3_neos_eventlog_domain_model_event DROP CONSTRAINT typo3_neos_eventlog_domain_model_event_pkey"); $this->addSql("WITH p AS (SELECT DISTINCT uid, persistence_object_identifier FROM typo3_neos_eventlog_domain_model_event) UPDATE typo3_neos_eventlog_domain_model_event SET parentevent = p.uid FROM p WHERE parentevent IS NOT NULL AND p.persistence_object_identifier = parentevent"); $this->addSql("ALTER TABLE typo3_neos_eventlog_domain_model_event ALTER parentevent DROP DEFAULT"); $this->addSql("ALTER TABLE typo3_neos_eventlog_domain_model_event ALTER parentevent TYPE INTEGER USING (parentevent::integer)"); $this->addSql("ALTER TABLE typo3_neos_eventlog_domain_model_event ALTER uid SET NOT NULL"); $this->addSql("ALTER TABLE typo3_neos_eventlog_domain_model_event DROP persistence_object_identifier"); $this->addSql("ALTER TABLE typo3_neos_eventlog_domain_model_event ADD PRIMARY KEY (uid)"); $this->addSql("ALTER TABLE typo3_neos_eventlog_domain_model_event ADD CONSTRAINT FK_30AB3A75B684C08 FOREIGN KEY (parentevent) REFERENCES typo3_neos_eventlog_domain_model_event (uid) NOT DEFERRABLE INITIALLY IMMEDIATE"); } /** * @param Schema $schema * @return void */ public function down(Schema $schema): void { $this->abortIf($this->connection->getDatabasePlatform()->getName() != "postgresql"); $this->addSql("ALTER TABLE typo3_neos_eventlog_domain_model_event DROP CONSTRAINT fk_30ab3a75b684c08"); $this->addSql("ALTER TABLE typo3_neos_eventlog_domain_model_event DROP CONSTRAINT typo3_neos_eventlog_domain_model_event_pkey"); $this->addSql("ALTER TABLE typo3_neos_eventlog_domain_model_event ADD persistence_object_identifier VARCHAR(40) NULL"); $result = $this->connection->executeQuery("SELECT installed_version FROM pg_available_extensions WHERE name = 'uuid-ossp'"); if ($result->fetchColumn() !== null) { $this->addSql("UPDATE typo3_neos_eventlog_domain_model_event SET persistence_object_identifier = uuid_generate_v4()"); } else { $result = $this->connection->executeQuery("SELECT uid FROM typo3_neos_eventlog_domain_model_event"); while ($uid = $result->fetchColumn()) { $this->addSql("UPDATE typo3_neos_eventlog_domain_model_event SET persistence_object_identifier = '" . \Neos\Flow\Utility\Algorithms::generateUUID() . "' WHERE uid = " . $uid); } } $this->addSql("ALTER TABLE typo3_neos_eventlog_domain_model_event ALTER COLUMN persistence_object_identifier SET NOT NULL"); $this->addSql("ALTER TABLE typo3_neos_eventlog_domain_model_event ALTER uid DROP NOT NULL"); $this->addSql("ALTER TABLE typo3_neos_eventlog_domain_model_event ALTER parentevent TYPE VARCHAR(40) USING (parentevent::varchar)"); $this->addSql("ALTER TABLE typo3_neos_eventlog_domain_model_event ALTER parentevent DROP DEFAULT"); $this->addSql("WITH p AS (SELECT DISTINCT uid, persistence_object_identifier FROM typo3_neos_eventlog_domain_model_event) UPDATE typo3_neos_eventlog_domain_model_event SET parentevent = p.persistence_object_identifier FROM p WHERE parentevent IS NOT NULL AND p.uid = parentevent::integer"); $this->addSql("SELECT setval('typo3_neos_eventlog_domain_model_event_uid_seq', (SELECT MAX(uid) FROM typo3_neos_eventlog_domain_model_event)+1);"); $this->addSql("ALTER TABLE typo3_neos_eventlog_domain_model_event ALTER uid SET DEFAULT nextval('typo3_neos_eventlog_domain_model_event_uid_seq')"); $this->addSql("ALTER TABLE typo3_neos_eventlog_domain_model_event ADD PRIMARY KEY (persistence_object_identifier)"); $this->addSql("ALTER TABLE typo3_neos_eventlog_domain_model_event ADD CONSTRAINT fk_30ab3a75b684c08 FOREIGN KEY (parentevent) REFERENCES typo3_neos_eventlog_domain_model_event (persistence_object_identifier) NOT DEFERRABLE INITIALLY IMMEDIATE"); } }
daniellienert/neos-development-collection
Neos.Neos/Migrations/Postgresql/Version20150224171108.php
PHP
gpl-3.0
4,589
package com.ardublock.translator.block; import com.ardublock.translator.Translator; import com.ardublock.translator.block.exception.SocketNullException; import com.ardublock.translator.block.exception.SubroutineNotDeclaredException; public class D7 extends TranslatorBlock { public D7(Long blockId, Translator translator, String codePrefix, String codeSuffix, String label) { super(blockId, translator, codePrefix, codeSuffix, label); } @Override public String toCode() throws SocketNullException { return codePrefix + "7" + codeSuffix; } }
Elecrow-keen/Ardublock
src/main/java/com/ardublock/translator/block/D7.java
Java
gpl-3.0
567
using System; namespace Server.Misc { public class RaceDefinitions { public static void Configure() { /* Here we configure all races. Some notes: * * 1) The first 32 races are reserved for core use. * 2) Race 0x7F is reserved for core use. * 3) Race 0xFF is reserved for core use. * 4) Changing or removing any predefined races may cause server instability. */ RegisterRace(new Human(0, 0)); RegisterRace(new Elf(1, 1)); #region Stygian Abyss RegisterRace(new Gargoyle(2, 2)); #endregion } public static void RegisterRace(Race race) { Race.Races[race.RaceIndex] = race; Race.AllRaces.Add(race); } private class Human : Race { public Human(int raceID, int raceIndex) : base(raceID, raceIndex, "Human", "Humans", 400, 401, 402, 403, Expansion.None) { } public override bool ValidateHair(bool female, int itemID) { if (itemID == 0) return true; if ((female && itemID == 0x2048) || (!female && itemID == 0x2046)) return false; //Buns & Receeding Hair if (itemID >= 0x203B && itemID <= 0x203D) return true; if (itemID >= 0x2044 && itemID <= 0x204A) return true; return false; } public override int RandomHair(bool female) //Random hair doesn't include baldness { switch( Utility.Random(9) ) { case 0: return 0x203B; //Short case 1: return 0x203C; //Long case 2: return 0x203D; //Pony Tail case 3: return 0x2044; //Mohawk case 4: return 0x2045; //Pageboy case 5: return 0x2047; //Afro case 6: return 0x2049; //Pig tails case 7: return 0x204A; //Krisna default: return (female ? 0x2046 : 0x2048); //Buns or Receeding Hair } } public override bool ValidateFacialHair(bool female, int itemID) { if (itemID == 0) return true; if (female) return false; if (itemID >= 0x203E && itemID <= 0x2041) return true; if (itemID >= 0x204B && itemID <= 0x204D) return true; return false; } public override int RandomFacialHair(bool female) { if (female) return 0; int rand = Utility.Random(7); return ((rand < 4) ? 0x203E : 0x2047) + rand; } #region Enhance Client public override bool ValidateFace(bool female, int itemID) { if (itemID.Equals(0)) return false; if (itemID >= 0x3B44 && itemID <= 0x3B4D) return true; return false; } public override int RandomFace(bool female) { switch (Utility.Random(10)) { case 0: return 0x3B44; // face1 case 1: return 0x3B45; // face2 case 2: return 0x3B46; // face3 case 3: return 0x3B47; // face4 case 4: return 0x3B48; // face5 case 5: return 0x3B49; // face6 case 6: return 0x3B4A; // face7 case 7: return 0x3B4B; // face8 case 8: return 0x3B4C; // face9 case 9: return 0x3B4D; // face10 default: return 0x3B44; // face1 } } #endregion public override int ClipSkinHue(int hue) { if (hue < 1002) return 1002; else if (hue > 1058) return 1058; else return hue; } public override int RandomSkinHue() { return Utility.Random(1002, 57) | 0x8000; } public override int ClipHairHue(int hue) { if (hue < 1102) return 1102; else if (hue > 1149) return 1149; else return hue; } public override int RandomHairHue() { return Utility.Random(1102, 48); } #region Enhance Client public override int ClipFaceHue(int hue) { return ClipSkinHue(hue); } public override int RandomFaceHue() { return RandomSkinHue(); } #endregion } private class Elf : Race { private static readonly int[] m_SkinHues = new int[] { 0x0BF, 0x24D, 0x24E, 0x24F, 0x353, 0x361, 0x367, 0x374, 0x375, 0x376, 0x381, 0x382, 0x383, 0x384, 0x385, 0x389, 0x3DE, 0x3E5, 0x3E6, 0x3E8, 0x3E9, 0x430, 0x4A7, 0x4DE, 0x51D, 0x53F, 0x579, 0x76B, 0x76C, 0x76D, 0x835, 0x903 }; private static readonly int[] m_HairHues = new int[] { 0x034, 0x035, 0x036, 0x037, 0x038, 0x039, 0x058, 0x08E, 0x08F, 0x090, 0x091, 0x092, 0x101, 0x159, 0x15A, 0x15B, 0x15C, 0x15D, 0x15E, 0x128, 0x12F, 0x1BD, 0x1E4, 0x1F3, 0x207, 0x211, 0x239, 0x251, 0x26C, 0x2C3, 0x2C9, 0x31D, 0x31E, 0x31F, 0x320, 0x321, 0x322, 0x323, 0x324, 0x325, 0x326, 0x369, 0x386, 0x387, 0x388, 0x389, 0x38A, 0x59D, 0x6B8, 0x725, 0x853 }; public Elf(int raceID, int raceIndex) : base(raceID, raceIndex, "Elf", "Elves", 605, 606, 607, 608, Expansion.ML) { } public override bool ValidateHair(bool female, int itemID) { if (itemID == 0) return true; if ((female && (itemID == 0x2FCD || itemID == 0x2FBF)) || (!female && (itemID == 0x2FCC || itemID == 0x2FD0))) return false; if (itemID >= 0x2FBF && itemID <= 0x2FC2) return true; if (itemID >= 0x2FCC && itemID <= 0x2FD1) return true; return false; } public override int RandomHair(bool female) //Random hair doesn't include baldness { switch( Utility.Random(8) ) { case 0: return 0x2FC0; //Long Feather case 1: return 0x2FC1; //Short case 2: return 0x2FC2; //Mullet case 3: return 0x2FCE; //Knob case 4: return 0x2FCF; //Braided case 5: return 0x2FD1; //Spiked case 6: return (female ? 0x2FCC : 0x2FBF); //Flower or Mid-long default: return (female ? 0x2FD0 : 0x2FCD); //Bun or Long } } public override bool ValidateFacialHair(bool female, int itemID) { return (itemID == 0); } public override int RandomFacialHair(bool female) { return 0; } #region Enhance Client public override bool ValidateFace(bool female, int itemID) { if (itemID.Equals(0)) return false; if (itemID >= 0x3B44 && itemID <= 0x3B4D) return true; return false; } public override int RandomFace(bool female) { switch (Utility.Random(10)) { case 0: return 0x3B44; // face1 case 1: return 0x3B45; // face2 case 2: return 0x3B46; // face3 case 3: return 0x3B47; // face4 case 4: return 0x3B48; // face5 case 5: return 0x3B49; // face6 case 6: return 0x3B4A; // face7 case 7: return 0x3B4B; // face8 case 8: return 0x3B4C; // face9 case 9: return 0x3B4D; // face10 default: return 0x3B44; // face1 } } #endregion public override int ClipSkinHue(int hue) { for (int i = 0; i < m_SkinHues.Length; i++) if (m_SkinHues[i] == hue) return hue; return m_SkinHues[0]; } public override int RandomSkinHue() { return m_SkinHues[Utility.Random(m_SkinHues.Length)] | 0x8000; } public override int ClipHairHue(int hue) { for (int i = 0; i < m_HairHues.Length; i++) if (m_HairHues[i] == hue) return hue; return m_HairHues[0]; } public override int RandomHairHue() { return m_HairHues[Utility.Random(m_HairHues.Length)]; } #region Enhance Client public override int ClipFaceHue(int hue) { return ClipSkinHue(hue); } public override int RandomFaceHue() { return RandomSkinHue(); } #endregion } #region SA private class Gargoyle : Race { public Gargoyle(int raceID, int raceIndex) : base(raceID, raceIndex, "Gargoyle", "Gargoyles", 666, 667, 695, 694, Expansion.SA) { } public override bool ValidateHair(bool female, int itemID) { if (female == false) { return itemID >= 0x4258 && itemID <= 0x425F; } else { return ((itemID == 0x4261 || itemID == 0x4262) || (itemID >= 0x4273 && itemID <= 0x4275) || (itemID == 0x42B0 || itemID == 0x42B1) || (itemID == 0x42AA || itemID == 0x42AB)); } } public override int RandomHair(bool female) { if (Utility.Random(9) == 0) return 0; else if (!female) return 0x4258 + Utility.Random(8); else { switch (Utility.Random(9)) { case 0: return 0x4261; case 1: return 0x4262; case 2: return 0x4273; case 3: return 0x4274; case 4: return 0x4275; case 5: return 0x42B0; case 6: return 0x42B1; case 7: return 0x42AA; case 8: return 0x42AB; } return 0; } } public override bool ValidateFacialHair(bool female, int itemID) { if (female) return false; else return itemID >= 0x42AD && itemID <= 0x42B0; } public override int RandomFacialHair(bool female) { if (female) return 0; else return Utility.RandomList(0, 0x42AD, 0x42AE, 0x42AF, 0x42B0); } // Todo Finish body hues private static readonly int[] m_BodyHues = new int[] { 0x86DB, 0x86DC, 0x86DD, 0x86DE, 0x86DF, 0x86E0, 0x86E1, 0x86E2, 0x86E3, 0x86E4, 0x86E5, 0x86E6 // 0x, 0x, 0x, 0x, // 86E7/86E8/86E9/86EA? // 0x, 0x, 0x, 0x, // 86EB/86EC/86ED/86EE? // 0x86F3, 0x86DB, 0x86DC, 0x86DD }; #region Enhance Client public override bool ValidateFace(bool female, int itemID) { if (itemID.Equals(0)) { return false; //Console.WriteLine("HELP2"); } if (itemID >= 0x5679 && itemID <= 0x567E) { return true; //Console.WriteLine("HELP1"); } return false; } public override int RandomFace(bool female) { switch (Utility.Random(6)) { case 0: return 0x5679; // face1 case 1: return 0x567A; // face2 case 2: return 0x567B; // face3 case 3: return 0x567C; // face4 case 4: return 0x567D; // face5 case 5: return 0x567E; // face6 default: return 0x5679; // face1 } } #endregion public override int ClipSkinHue(int hue) { return hue; // for hue infomation gathering } public override int RandomSkinHue() { return m_BodyHues[Utility.Random(m_BodyHues.Length)] | 0x8000; } private static readonly int[] m_HornHues = new int[] { 0x709, 0x70B, 0x70D, 0x70F, 0x711, 0x763, 0x765, 0x768, 0x76B, 0x6F3, 0x6F1, 0x6EF, 0x6E4, 0x6E2, 0x6E0, 0x709, 0x70B, 0x70D }; public override int ClipHairHue(int hue) { for (int i = 0; i < m_HornHues.Length; i++) if (m_HornHues[i] == hue) return hue; return m_HornHues[0]; } public override int RandomHairHue() { return m_HornHues[Utility.Random(m_HornHues.Length)]; } #region Enhance Client public override int ClipFaceHue(int hue) { return ClipSkinHue(hue); } public override int RandomFaceHue() { return RandomSkinHue(); } #endregion } #endregion } }
LeonG-ZA/JustUO-KR
Scripts/Misc/RaceDefinitions.cs
C#
gpl-3.0
15,625
{% import 'macros/form.html' as form %} {% block package_basic_fields_title %} {{ form.input('title', id='field-title', label=_('Title'), placeholder=_('eg. A descriptive title'), value=data.title, error=errors.title, classes=['control-full', 'control-large'], attrs={'data-module': 'slug-preview-target'}) }} {% endblock %} {% block package_basic_fields_url %} {% set prefix = h.url_for(controller='package', action='read', id='') %} {% set domain = h.url_for(controller='package', action='read', id='', qualified=true) %} {% set domain = domain|replace("http://", "")|replace("https://", "") %} {% set attrs = {'data-module': 'slug-preview-slug', 'data-module-prefix': domain, 'data-module-placeholder': '<dataset>'} %} {{ form.prepend('name', id='field-name', label=_('URL'), prepend=prefix, placeholder=_('eg. my-dataset'), value=data.name, error=errors.name, attrs=attrs, is_required=true) }} {% endblock %} {% block package_basic_fields_custom %}{% endblock %} {% block package_basic_fields_description %} {{ form.markdown('notes', id='field-notes', label=_('Description'), placeholder=_('eg. Some useful notes about the data'), value=data.notes, error=errors.notes) }} {% endblock %} {% block package_basic_fields_tags %} {% set tag_attrs = {'data-module': 'autocomplete', 'data-module-tags': '', 'data-module-source': '/api/2/util/tag/autocomplete?incomplete=?'} %} {{ form.input('tag_string', id='field-tags', label=_('Tags'), placeholder=_('eg. economy, mental health, government'), value=data.tag_string, error=errors.tags, classes=['control-full'], attrs=tag_attrs) }} {% endblock %} {% block package_basic_fields_license %} <div class="control-group"> {% set error = errors.license_id %} <label class="control-label" for="field-license">{{ _("License") }}</label> <div class="controls"> <select id="field-license" name="license_id" data-module="autocomplete"> {% set existing_license_id = data.get('license_id') %} {% for license_id, license_desc in h.license_options(existing_license_id) %} <option value="{{ license_id }}" {% if existing_license_id == license_id %}selected="selected"{% endif %}>{{ license_desc }}</option> {% endfor %} </select> {% if error %}<span class="error-block">{{ error }}</span>{% endif %} <span class="info-block info-inline"> <i class="icon-info-sign"></i> {% trans %} License definitions and additional information can be found at <a href="http://opendefinition.org/licenses/">opendefinition.org</a> {% endtrans %} </span> </div> </div> {% endblock %} {% block package_basic_fields_org %} {# if we have a default group then this wants remembering #} {% if data.group_id %} <input type="hidden" name="groups__0__id" value="{{ data.group_id }}" /> {% endif %} {% set dataset_is_draft = data.get('state', 'draft').startswith('draft') or data.get('state', 'none') == 'none' %} {% set dataset_has_organization = data.owner_org or data.group_id %} {% set organizations_available = h.organizations_available('create_dataset') %} {% set user_is_sysadmin = h.check_access('sysadmin') %} {% set show_organizations_selector = organizations_available %} {% set show_visibility_selector = dataset_has_organization or (organizations_available and (user_is_sysadmin or dataset_is_draft)) %} {% if show_organizations_selector and show_visibility_selector %} <div data-module="dataset-visibility"> {% endif %} {% if show_organizations_selector %} {% set existing_org = data.owner_org or data.group_id %} <div class="control-group"> <label for="field-organizations" class="control-label">{{ _('Organization') }}</label> <div class="controls"> <select id="field-organizations" name="owner_org" data-module="autocomplete"> {% if h.check_config_permission('create_unowned_dataset') %} <option value="" {% if not selected_org and data.id %} selected="selected" {% endif %}>{{ _('No organization') }}</option> {% endif %} {% for organization in organizations_available %} {# get out first org from users list only if there is not an existing org #} {% set selected_org = (existing_org and existing_org == organization.id) or (not existing_org and not data.id and organization.id == organizations_available[0].id) %} <option value="{{ organization.id }}" {% if selected_org %} selected="selected" {% endif %}>{{ organization.display_name }}</option> {% endfor %} </select> </div> </div> {% endif %} {% if show_visibility_selector %} {% block package_metadata_fields_visibility %} <div class="control-group"> <label for="field-private" class="control-label">{{ _('Visibility') }}</label> <div class="controls"> <select id="field-private" name="private"> {% for option in [('True', _('Private')), ('False', _('Public'))] %} <option value="{{ option[0] }}" {% if option[0] == data.private|trim %}selected="selected"{% endif %}>{{ option[1] }}</option> {% endfor %} </select> </div> </div> {% endblock %} {% endif %} {% if show_organizations_selector and show_visibility_selector %} </div> {% endif %} {% if data.id and h.check_access('package_delete', {'id': data.id}) and data.state != 'active' %} <div class="control-group"> <label for="field-state" class="control-label">{{ _('State') }}</label> <div class="controls"> <select id="field-state" name="state"> <option value="active" {% if data.get('state', 'none') == 'active' %} selected="selected" {% endif %}>{{ _('Active') }}</option> <option value="deleted" {% if data.get('state', 'none') == 'deleted' %} selected="selected" {% endif %}>{{ _('Deleted') }}</option> </select> </div> </div> {% endif %} {% endblock %}
eokoe/appcivico-ckan-comovamos
custom/templates/package/snippets/package_basic_fields.html
HTML
gpl-3.0
5,961
using System; using System.IO; namespace GitCommands { public static class FileInfoExtensions { /// <summary> /// Remove all attributes that could cause the file to be read-only /// and restores them later /// </summary> public static void MakeFileTemporaryWritable(string fileName, Action<string> writableAction) { var fileInfo = new FileInfo(fileName); if (!fileInfo.Exists) { // The file doesn't exist yet, no need to make it writable writableAction(fileName); return; } var oldAttributes = fileInfo.Attributes; fileInfo.Attributes = FileAttributes.Normal; writableAction(fileName); fileInfo.Refresh(); if (fileInfo.Exists) { fileInfo.Attributes = oldAttributes; } } } }
jbialobr/gitextensions
GitCommands/FileInfoExtensions.cs
C#
gpl-3.0
947
ARCH=msp:43 MACHINE= SCRIPT_NAME=elf32msp430 OUTPUT_FORMAT="elf32-msp430" MAXPAGESIZE=1 EMBEDDED=yes TEMPLATE_NAME=generic ROM_START=0x8000 ROM_SIZE=0x7fe0 RAM_START=0x0200 RAM_SIZE=1024 STACK=0x600
uhhpctools/openuh
osprey/cygnus/ld/emulparams/msp430x437.sh
Shell
gpl-3.0
201
#region Copyright & License Information /* * Copyright 2007-2016 The OpenRA Developers (see AUTHORS) * This file is part of OpenRA, which is free software. It is made * available to you under the terms of the GNU General Public License * as published by the Free Software Foundation, either version 3 of * the License, or (at your option) any later version. For more * information, see COPYING. */ #endregion using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Text; using OpenRA.FileSystem; using OpenRA.Graphics; using OpenRA.Mods.Common.FileFormats; using OpenRA.Mods.Common.Traits; using OpenRA.Primitives; namespace OpenRA.Mods.Common.UtilityCommands { public abstract class ImportLegacyMapCommand { public readonly int MapSize; public ImportLegacyMapCommand(int mapSize) { MapSize = mapSize; } public ModData ModData; public Map Map; public List<string> Players = new List<string>(); public MapPlayers MapPlayers; bool singlePlayer; int spawnCount; protected bool ValidateArguments(string[] args) { return args.Length >= 2; } protected void Run(Utility utility, string[] args) { // HACK: The engine code assumes that Game.modData is set. Game.ModData = ModData = utility.ModData; var filename = args[1]; using (var stream = File.OpenRead(filename)) { var file = new IniFile(stream); var basic = file.GetSection("Basic"); var player = basic.GetValue("Player", string.Empty); if (!string.IsNullOrEmpty(player)) singlePlayer = !player.StartsWith("Multi"); var mapSection = file.GetSection("Map"); var format = GetMapFormatVersion(basic); ValidateMapFormat(format); // The original game isn't case sensitive, but we are. var tileset = GetTileset(mapSection).ToUpperInvariant(); if (!ModData.DefaultTileSets.ContainsKey(tileset)) throw new InvalidDataException("Unknown tileset {0}".F(tileset)); Map = new Map(ModData, ModData.DefaultTileSets[tileset], MapSize, MapSize) { Title = basic.GetValue("Name", Path.GetFileNameWithoutExtension(filename)), Author = "Westwood Studios", }; Map.RequiresMod = ModData.Manifest.Id; SetBounds(Map, mapSection); ReadPacks(file, filename); ReadTrees(file); LoadVideos(file, "BASIC"); LoadBriefing(file); ReadActors(file); LoadSmudges(file, "SMUDGE"); var waypoints = file.GetSection("Waypoints"); LoadWaypoints(waypoints); // Create default player definitions only if there are no players to import MapPlayers = new MapPlayers(Map.Rules, Players.Count == 0 ? spawnCount : 0); foreach (var p in Players) LoadPlayer(file, p); Map.PlayerDefinitions = MapPlayers.ToMiniYaml(); } Map.FixOpenAreas(); var dest = Path.GetFileNameWithoutExtension(args[1]) + ".oramap"; Map.Save(ZipFile.Create(dest, new Folder("."))); Console.WriteLine(dest + " saved."); } /* * 1=Tiberium Dawn & Sole Survivor * 2=Red Alert (also with Counterstrike installed) * 3=Red Alert (with Aftermath installed) * 4=Tiberian Sun (including Firestorm) & Red Alert 2 (including Yuri's Revenge) */ static int GetMapFormatVersion(IniSection basicSection) { var iniFormat = basicSection.GetValue("NewINIFormat", "0"); var iniFormatVersion = 0; Exts.TryParseIntegerInvariant(iniFormat, out iniFormatVersion); return iniFormatVersion; } public abstract void ValidateMapFormat(int format); void LoadBriefing(IniFile file) { var briefingSection = file.GetSection("Briefing", true); if (briefingSection == null) return; var briefing = new StringBuilder(); foreach (var s in briefingSection) briefing.AppendLine(s.Value); if (briefing.Length == 0) return; var worldNode = Map.RuleDefinitions.Nodes.FirstOrDefault(n => n.Key == "World"); if (worldNode == null) { worldNode = new MiniYamlNode("World", new MiniYaml("", new List<MiniYamlNode>())); Map.RuleDefinitions.Nodes.Add(worldNode); } var missionData = worldNode.Value.Nodes.FirstOrDefault(n => n.Key == "MissionData"); if (missionData == null) { missionData = new MiniYamlNode("MissionData", new MiniYaml("", new List<MiniYamlNode>())); worldNode.Value.Nodes.Add(missionData); } missionData.Value.Nodes.Add(new MiniYamlNode("Briefing", briefing.Replace("\n", " ").ToString())); } static void SetBounds(Map map, IniSection mapSection) { var offsetX = Exts.ParseIntegerInvariant(mapSection.GetValue("X", "0")); var offsetY = Exts.ParseIntegerInvariant(mapSection.GetValue("Y", "0")); var width = Exts.ParseIntegerInvariant(mapSection.GetValue("Width", "0")); var height = Exts.ParseIntegerInvariant(mapSection.GetValue("Height", "0")); var tl = new PPos(offsetX, offsetY); var br = new PPos(offsetX + width - 1, offsetY + height - 1); map.SetBounds(tl, br); } public abstract void ReadPacks(IniFile file, string filename); void LoadVideos(IniFile file, string section) { var videos = new List<MiniYamlNode>(); foreach (var s in file.GetSection(section)) { if (s.Value != "x" && s.Value != "X" && s.Value != "<none>") { switch (s.Key) { case "Intro": videos.Add(new MiniYamlNode("BackgroundVideo", s.Value.ToLower() + ".vqa")); break; case "Brief": videos.Add(new MiniYamlNode("BriefingVideo", s.Value.ToLower() + ".vqa")); break; case "Action": videos.Add(new MiniYamlNode("StartVideo", s.Value.ToLower() + ".vqa")); break; case "Win": videos.Add(new MiniYamlNode("WinVideo", s.Value.ToLower() + ".vqa")); break; case "Lose": videos.Add(new MiniYamlNode("LossVideo", s.Value.ToLower() + ".vqa")); break; } } } if (videos.Any()) { var worldNode = Map.RuleDefinitions.Nodes.FirstOrDefault(n => n.Key == "World"); if (worldNode == null) { worldNode = new MiniYamlNode("World", new MiniYaml("", new List<MiniYamlNode>())); Map.RuleDefinitions.Nodes.Add(worldNode); } var missionData = worldNode.Value.Nodes.FirstOrDefault(n => n.Key == "MissionData"); if (missionData == null) { missionData = new MiniYamlNode("MissionData", new MiniYaml("", new List<MiniYamlNode>())); worldNode.Value.Nodes.Add(missionData); } missionData.Value.Nodes.AddRange(videos); } } public virtual void ReadActors(IniFile file) { LoadActors(file, "STRUCTURES", Players, MapSize, Map); LoadActors(file, "UNITS", Players, MapSize, Map); LoadActors(file, "INFANTRY", Players, MapSize, Map); } public abstract void LoadPlayer(IniFile file, string section); static string Truncate(string s, int maxLength) { return s.Length <= maxLength ? s : s.Substring(0, maxLength); } static string GetTileset(IniSection mapSection) { // NOTE: The original isn't case sensitive, we are. // NOTE: Tileset TEMPERAT exists in every C&C game. return Truncate(mapSection.GetValue("Theater", "TEMPERAT"), 8).ToUpperInvariant(); } static int2 LocationFromMapOffset(int offset, int mapSize) { return new int2(offset % mapSize, offset / mapSize); } void LoadWaypoints(IniSection waypointSection) { var actorCount = Map.ActorDefinitions.Count; var wps = waypointSection .Where(kv => Exts.ParseIntegerInvariant(kv.Value) > 0) .Select(kv => Pair.New(Exts.ParseIntegerInvariant(kv.Key), LocationFromMapOffset(Exts.ParseIntegerInvariant(kv.Value), MapSize))); // Add waypoint actors skipping duplicate entries foreach (var kv in wps.DistinctBy(location => location.Second)) { if (!singlePlayer && kv.First <= 7) { var ar = new ActorReference("mpspawn") { new LocationInit((CPos)kv.Second), new OwnerInit("Neutral") }; Map.ActorDefinitions.Add(new MiniYamlNode("Actor" + actorCount++, ar.Save())); spawnCount++; } else { var ar = new ActorReference("waypoint") { new LocationInit((CPos)kv.Second), new OwnerInit("Neutral") }; SaveWaypoint(kv.First, ar); } } } public virtual void SaveWaypoint(int waypointNumber, ActorReference waypointReference) { var waypointName = "waypoint" + waypointNumber; Map.ActorDefinitions.Add(new MiniYamlNode(waypointName, waypointReference.Save())); } void LoadSmudges(IniFile file, string section) { var scorches = new List<MiniYamlNode>(); var craters = new List<MiniYamlNode>(); foreach (var s in file.GetSection(section, true)) { // loc=type,loc,depth var parts = s.Value.Split(','); var loc = Exts.ParseIntegerInvariant(parts[1]); var type = parts[0].ToLowerInvariant(); var key = "{0},{1}".F(loc % MapSize, loc / MapSize); var value = "{0},{1}".F(type, parts[2]); var node = new MiniYamlNode(key, value); if (type.StartsWith("sc")) scorches.Add(node); else if (type.StartsWith("cr")) craters.Add(node); } var worldNode = Map.RuleDefinitions.Nodes.FirstOrDefault(n => n.Key == "World"); if (worldNode == null) worldNode = new MiniYamlNode("World", new MiniYaml("", new List<MiniYamlNode>())); if (scorches.Any()) { var initialScorches = new MiniYamlNode("InitialSmudges", new MiniYaml("", scorches)); var smudgeLayer = new MiniYamlNode("SmudgeLayer@SCORCH", new MiniYaml("", new List<MiniYamlNode>() { initialScorches })); worldNode.Value.Nodes.Add(smudgeLayer); } if (craters.Any()) { var initialCraters = new MiniYamlNode("InitialSmudges", new MiniYaml("", craters)); var smudgeLayer = new MiniYamlNode("SmudgeLayer@CRATER", new MiniYaml("", new List<MiniYamlNode>() { initialCraters })); worldNode.Value.Nodes.Add(smudgeLayer); } if (worldNode.Value.Nodes.Any() && !Map.RuleDefinitions.Nodes.Contains(worldNode)) Map.RuleDefinitions.Nodes.Add(worldNode); } // TODO: fix this -- will have bitrotted pretty badly. static Dictionary<string, HSLColor> namedColorMapping = new Dictionary<string, HSLColor>() { { "gold", HSLColor.FromRGB(246, 214, 121) }, { "blue", HSLColor.FromRGB(226, 230, 246) }, { "red", HSLColor.FromRGB(255, 20, 0) }, { "neutral", HSLColor.FromRGB(238, 238, 238) }, { "orange", HSLColor.FromRGB(255, 230, 149) }, { "teal", HSLColor.FromRGB(93, 194, 165) }, { "salmon", HSLColor.FromRGB(210, 153, 125) }, { "green", HSLColor.FromRGB(160, 240, 140) }, { "white", HSLColor.FromRGB(255, 255, 255) }, { "black", HSLColor.FromRGB(80, 80, 80) }, }; public static void SetMapPlayers(string section, string faction, string color, IniFile file, List<string> players, MapPlayers mapPlayers) { var pr = new PlayerReference { Name = section, OwnsWorld = section == "Neutral", NonCombatant = section == "Neutral", Faction = faction, Color = namedColorMapping[color] }; var neutral = new[] { "Neutral" }; foreach (var s in file.GetSection(section, true)) { switch (s.Key) { case "Allies": pr.Allies = s.Value.Split(',').Intersect(players).Except(neutral).ToArray(); pr.Enemies = s.Value.Split(',').SymmetricDifference(players).Except(neutral).ToArray(); break; default: Console.WriteLine("Ignoring unknown {0}={1} for player {2}", s.Key, s.Value, pr.Name); break; } } // Overwrite default player definitions if needed if (!mapPlayers.Players.ContainsKey(section)) mapPlayers.Players.Add(section, pr); else mapPlayers.Players[section] = pr; } public virtual CPos ParseActorLocation(string input, int loc) { return new CPos(loc % MapSize, loc / MapSize); } public void LoadActors(IniFile file, string section, List<string> players, int mapSize, Map map) { foreach (var s in file.GetSection(section, true)) { // Structures: num=owner,type,health,location,turret-facing,trigger // Units: num=owner,type,health,location,facing,action,trigger // Infantry: num=owner,type,health,location,subcell,action,facing,trigger try { var parts = s.Value.Split(','); if (parts[0] == "") parts[0] = "Neutral"; if (!players.Contains(parts[0])) players.Add(parts[0]); var loc = Exts.ParseIntegerInvariant(parts[3]); var health = Exts.ParseIntegerInvariant(parts[2]) * 100 / 256; var facing = (section == "INFANTRY") ? Exts.ParseIntegerInvariant(parts[6]) : Exts.ParseIntegerInvariant(parts[4]); var actorType = parts[1].ToLowerInvariant(); var actor = new ActorReference(actorType) { new LocationInit(ParseActorLocation(actorType, loc)), new OwnerInit(parts[0]), }; var initDict = actor.InitDict; if (health != 100) initDict.Add(new HealthInit(health)); if (facing != 0) initDict.Add(new FacingInit(255 - facing)); if (section == "INFANTRY") actor.Add(new SubCellInit(Exts.ParseIntegerInvariant(parts[4]))); var actorCount = map.ActorDefinitions.Count; if (!map.Rules.Actors.ContainsKey(parts[1].ToLowerInvariant())) Console.WriteLine("Ignoring unknown actor type: `{0}`".F(parts[1].ToLowerInvariant())); else map.ActorDefinitions.Add(new MiniYamlNode("Actor" + actorCount++, actor.Save())); } catch (Exception) { Console.WriteLine("Malformed actor definition: `{0}`".F(s)); } } } public abstract string ParseTreeActor(string input); void ReadTrees(IniFile file) { var terrain = file.GetSection("TERRAIN", true); if (terrain == null) return; foreach (var kv in terrain) { var loc = Exts.ParseIntegerInvariant(kv.Key); var treeActor = ParseTreeActor(kv.Value); var ar = new ActorReference(treeActor) { new LocationInit(ParseActorLocation(treeActor, loc)), new OwnerInit("Neutral") }; var actorCount = Map.ActorDefinitions.Count; Map.ActorDefinitions.Add(new MiniYamlNode("Actor" + actorCount++, ar.Save())); } } } }
e1d1s1/OpenRA
OpenRA.Mods.Common/UtilityCommands/ImportLegacyMapCommand.cs
C#
gpl-3.0
14,014
/* * Copyright (c) 2015, Psiphon 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 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. * */ // Package transferstats counts and keeps track of session stats. These are // per-domain bytes transferred and total bytes transferred. package transferstats /* Assumption: The same connection will not be used to access different hostnames (even if, say, those hostnames map to the same server). If this does occur, we will mis-attribute some bytes. Assumption: Enough of the first HTTP will be present in the first Write() call for us to a) recognize that it is HTTP, and b) parse the hostname. - If this turns out to not be generally true we will need to add buffering. */ import ( "net" "sync/atomic" ) // Conn is to be used as an intermediate link in a chain of net.Conn objects. // It inspects requests and responses and derives stats from them. type Conn struct { net.Conn serverID string firstWrite int32 hostnameParsed int32 hostname string regexps *Regexps } // NewConn creates a Conn. serverID can be anything that uniquely // identifies the server; it will be passed to TakeOutStatsForServer() when // retrieving the accumulated stats. func NewConn(nextConn net.Conn, serverID string, regexps *Regexps) *Conn { return &Conn{ Conn: nextConn, serverID: serverID, firstWrite: 1, hostnameParsed: 0, regexps: regexps, } } func (conn *Conn) isRecordingHostBytes() bool { // When there are no regexes, no per-host bytes stats will be // recorded, including no "(OTHER)" category. In this case, it's // expected that there will be no data to send in any status // request. return conn.regexps != nil && len(*conn.regexps) > 0 } // Write is called when requests are being written out through the tunnel to // the remote server. func (conn *Conn) Write(buffer []byte) (n int, err error) { // First pass the data down the chain. n, err = conn.Conn.Write(buffer) // Count stats before we check the error condition. It could happen that the // buffer was partially written and then an error occurred. if n > 0 { // If this is the first request, try to determine the hostname to associate // with this connection. Skip parsing when not recording per-host bytes, as // the hostname isn't used in this case. if conn.isRecordingHostBytes() && atomic.CompareAndSwapInt32(&conn.firstWrite, 1, 0) { hostname, ok := getHostname(buffer) if ok { // Get the hostname value that will be stored in stats by // regexing the real hostname. conn.hostname = regexHostname(hostname, conn.regexps) atomic.StoreInt32(&conn.hostnameParsed, 1) } } recordStat(&statsUpdate{ conn.serverID, conn.hostname, int64(n), 0}, conn.isRecordingHostBytes(), false) } return } // Read is called when responses to requests are being read from the remote server. func (conn *Conn) Read(buffer []byte) (n int, err error) { n, err = conn.Conn.Read(buffer) var hostname string if atomic.LoadInt32(&conn.hostnameParsed) == 1 { hostname = conn.hostname } else { hostname = "" } // Count bytes without checking the error condition. It could happen that the // buffer was partially read and then an error occurred. recordStat(&statsUpdate{ conn.serverID, hostname, 0, int64(n)}, conn.isRecordingHostBytes(), false) return }
Psiphon-Labs/psiphon-tunnel-core
psiphon/transferstats/conn.go
GO
gpl-3.0
3,984
#include "ChannelState.h" bool ChannelState::isIdle() const { return idle; } double ChannelState::getRSSI() const { return rssi; }
PeterDanie/mixim2.3
src/base/phyLayer/ChannelState.cc
C++
gpl-3.0
142
//======================================================================= // Copyright 2007 Aaron Windsor // // Distributed under the Boost Software License, Version 1.0. (See // accompanying file LICENSE_1_0.txt or copy at // http://www.boost.org/LICENSE_1_0.txt) //======================================================================= #include <boost/graph/adjacency_list.hpp> #include <boost/graph/properties.hpp> #include <boost/graph/make_maximal_planar.hpp> #include <boost/graph/boyer_myrvold_planar_test.hpp> #include <boost/property_map/property_map.hpp> #include <boost/property_map/vector_property_map.hpp> #include <boost/test/minimal.hpp> using namespace boost; template <typename Graph> void reset_edge_index(Graph& g) { typename property_map<Graph, edge_index_t>::type index = get(edge_index, g); typename graph_traits<Graph>::edge_iterator ei, ei_end; typename graph_traits<Graph>::edges_size_type cnt = 0; for(tie(ei,ei_end) = edges(g); ei != ei_end; ++ei) put(index, *ei, cnt++); } template <typename Graph> void make_cycle(Graph& g, int size) { typedef typename graph_traits<Graph>::vertex_descriptor vertex_t; vertex_t first_vertex = add_vertex(g); vertex_t prev_vertex = first_vertex; for(int i = 1; i < size; ++i) { vertex_t curr_vertex = add_vertex(g); add_edge(curr_vertex, prev_vertex, g); prev_vertex = curr_vertex; } add_edge(first_vertex, prev_vertex, g); } struct UpdateVertexIndex { template <typename Graph> void update(Graph& g) { typename property_map<Graph, vertex_index_t>::type index = get(vertex_index, g); typename graph_traits<Graph>::vertex_iterator vi, vi_end; typename graph_traits<Graph>::vertices_size_type cnt = 0; for(tie(vi,vi_end) = vertices(g); vi != vi_end; ++vi) put(index, *vi, cnt++); } }; struct NoVertexIndexUpdater { template <typename Graph> void update(Graph&) {} }; template <typename Graph, typename VertexIndexUpdater> void test_cycle(VertexIndexUpdater vertex_index_updater, int size) { Graph g; make_cycle(g, size); vertex_index_updater.update(g); reset_edge_index(g); typedef std::vector< typename graph_traits<Graph>::edge_descriptor > edge_vector_t; typedef std::vector< edge_vector_t > embedding_storage_t; typedef iterator_property_map < typename embedding_storage_t::iterator, typename property_map<Graph, vertex_index_t>::type > embedding_t; embedding_storage_t embedding_storage(num_vertices(g)); embedding_t embedding(embedding_storage.begin(), get(vertex_index, g)); typename graph_traits<Graph>::vertex_iterator vi, vi_end; for(tie(vi,vi_end) = vertices(g); vi != vi_end; ++vi) std::copy(out_edges(*vi,g).first, out_edges(*vi,g).second, std::back_inserter(embedding[*vi])); BOOST_CHECK(boyer_myrvold_planarity_test(g)); make_maximal_planar(g, embedding); reset_edge_index(g); // A graph is maximal planar exactly when it's both // planar and has 3 * num_vertices(g) - 6 edges. BOOST_CHECK(num_edges(g) == 3 * num_vertices(g) - 6); BOOST_CHECK(boyer_myrvold_planarity_test(g)); } int test_main(int, char* []) { typedef adjacency_list <vecS, vecS, undirectedS, property<vertex_index_t, int>, property<edge_index_t, int> > VVgraph_t; typedef adjacency_list <vecS, listS, undirectedS, property<vertex_index_t, int>, property<edge_index_t, int> > VLgraph_t; typedef adjacency_list <listS, vecS, undirectedS, property<vertex_index_t, int>, property<edge_index_t, int> > LVgraph_t; typedef adjacency_list <listS, listS, undirectedS, property<vertex_index_t, int>, property<edge_index_t, int> > LLgraph_t; typedef adjacency_list <setS, setS, undirectedS, property<vertex_index_t, int>, property<edge_index_t, int> > SSgraph_t; test_cycle<VVgraph_t>(NoVertexIndexUpdater(), 10); test_cycle<VVgraph_t>(NoVertexIndexUpdater(), 50); test_cycle<VLgraph_t>(UpdateVertexIndex(), 3); test_cycle<VLgraph_t>(UpdateVertexIndex(), 30); test_cycle<LVgraph_t>(NoVertexIndexUpdater(), 15); test_cycle<LVgraph_t>(NoVertexIndexUpdater(), 45); test_cycle<LLgraph_t>(UpdateVertexIndex(), 8); test_cycle<LLgraph_t>(UpdateVertexIndex(), 19); test_cycle<SSgraph_t>(UpdateVertexIndex(), 13); test_cycle<SSgraph_t>(UpdateVertexIndex(), 20); return 0; }
gorkinovich/DefendersOfMankind
dependencies/boost-1.46.0/libs/graph/test/make_maximal_planar_test.cpp
C++
gpl-3.0
4,469
/* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 4 -*- * vim: set ts=8 sts=4 et sw=4 tw=99: * This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ #ifndef jit_arm_MoveEmitter_arm_h #define jit_arm_MoveEmitter_arm_h #include "jit/MoveResolver.h" #include "jit/IonMacroAssembler.h" namespace js { namespace jit { class CodeGenerator; class MoveEmitterARM { typedef MoveResolver::Move Move; typedef MoveResolver::MoveOperand MoveOperand; bool inCycle_; MacroAssemblerARMCompat &masm; // Original stack push value. uint32_t pushedAtStart_; // These store stack offsets to spill locations, snapshotting // codegen->framePushed_ at the time they were allocated. They are -1 if no // stack space has been allocated for that particular spill. int32_t pushedAtCycle_; int32_t pushedAtSpill_; int32_t pushedAtDoubleSpill_; // These are registers that are available for temporary use. They may be // assigned InvalidReg. If no corresponding spill space has been assigned, // then these registers do not need to be spilled. Register spilledReg_; FloatRegister spilledFloatReg_; void assertDone(); Register tempReg(); FloatRegister tempFloatReg(); Operand cycleSlot() const; Operand spillSlot() const; Operand doubleSpillSlot() const; Operand toOperand(const MoveOperand &operand, bool isFloat) const; void emitMove(const MoveOperand &from, const MoveOperand &to); void emitDoubleMove(const MoveOperand &from, const MoveOperand &to); void breakCycle(const MoveOperand &from, const MoveOperand &to, Move::Kind kind); void completeCycle(const MoveOperand &from, const MoveOperand &to, Move::Kind kind); void emit(const Move &move); public: MoveEmitterARM(MacroAssemblerARMCompat &masm); ~MoveEmitterARM(); void emit(const MoveResolver &moves); void finish(); }; typedef MoveEmitterARM MoveEmitter; } // namespace jit } // namespace js #endif /* jit_arm_MoveEmitter_arm_h */
michath/MetaMonkey
js/src/jit/arm/MoveEmitter-arm.h
C
mpl-2.0
2,181
<!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.16"/> <title>GLFW: Keyboard keys</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" /> <link href="extra.css" rel="stylesheet" type="text/css"/> </head> <body> <div id="top"><!-- do not remove this div, it is closed by doxygen! --> <div id="titlearea"> <div class="glfwheader"> <a href="https://www.glfw.org/" id="glfwhome">GLFW</a> <ul class="glfwnavbar"> <li><a href="https://www.glfw.org/documentation.html">Documentation</a></li> <li><a href="https://www.glfw.org/download.html">Download</a></li> <li><a href="https://www.glfw.org/community.html">Community</a></li> </ul> </div> </div> <!-- end header part --> <!-- Generated by Doxygen 1.8.16 --> <script type="text/javascript"> /* @license magnet:?xt=urn:btih:cf05388f2679ee054f2beb29a391d25f4e673ac3&amp;dn=gpl-2.0.txt GPL-v2 */ var searchBox = new SearchBox("searchBox", "search",false,'Search'); /* @license-end */ </script> <script type="text/javascript" src="menudata.js"></script> <script type="text/javascript" src="menu.js"></script> <script type="text/javascript"> /* @license magnet:?xt=urn:btih:cf05388f2679ee054f2beb29a391d25f4e673ac3&amp;dn=gpl-2.0.txt GPL-v2 */ $(function() { initMenu('',true,false,'search.php','Search'); $(document).ready(function() { init_search(); }); }); /* @license-end */</script> <div id="main-nav"></div> </div><!-- top --> <!-- 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 class="header"> <div class="summary"> <a href="#define-members">Macros</a> </div> <div class="headertitle"> <div class="title">Keyboard keys<div class="ingroups"><a class="el" href="group__input.html">Input reference</a></div></div> </div> </div><!--header--> <div class="contents"> <a name="details" id="details"></a><h2 class="groupheader">Description</h2> <p>See <a class="el" href="input_guide.html#input_key">key input</a> for how these are used.</p> <p>These key codes are inspired by the <em>USB HID Usage Tables v1.12</em> (p. 53-60), but re-arranged to map to 7-bit ASCII for printable keys (function keys are put in the 256+ range).</p> <p>The naming of the key codes follow these rules:</p><ul> <li>The US keyboard layout is used</li> <li>Names of printable alpha-numeric characters are used (e.g. "A", "R", "3", etc.)</li> <li>For non-alphanumeric characters, Unicode:ish names are used (e.g. "COMMA", "LEFT_SQUARE_BRACKET", etc.). Note that some names do not correspond to the Unicode standard (usually for brevity)</li> <li>Keys that lack a clear US mapping are named "WORLD_x"</li> <li>For non-printable keys, custom names are used (e.g. "F4", "BACKSPACE", etc.) </li> </ul> <table class="memberdecls"> <tr class="heading"><td colspan="2"><h2 class="groupheader"><a name="define-members"></a> Macros</h2></td></tr> <tr class="memitem:ga99aacc875b6b27a072552631e13775c7"><td class="memItemLeft" align="right" valign="top">#define&#160;</td><td class="memItemRight" valign="bottom"><a class="el" href="group__keys.html#ga99aacc875b6b27a072552631e13775c7">GLFW_KEY_UNKNOWN</a>&#160;&#160;&#160;-1</td></tr> <tr class="separator:ga99aacc875b6b27a072552631e13775c7"><td class="memSeparator" colspan="2">&#160;</td></tr> <tr class="memitem:gaddb2c23772b97fd7e26e8ee66f1ad014"><td class="memItemLeft" align="right" valign="top">#define&#160;</td><td class="memItemRight" valign="bottom"><a class="el" href="group__keys.html#gaddb2c23772b97fd7e26e8ee66f1ad014">GLFW_KEY_SPACE</a>&#160;&#160;&#160;32</td></tr> <tr class="separator:gaddb2c23772b97fd7e26e8ee66f1ad014"><td class="memSeparator" colspan="2">&#160;</td></tr> <tr class="memitem:ga6059b0b048ba6980b6107fffbd3b4b24"><td class="memItemLeft" align="right" valign="top">#define&#160;</td><td class="memItemRight" valign="bottom"><a class="el" href="group__keys.html#ga6059b0b048ba6980b6107fffbd3b4b24">GLFW_KEY_APOSTROPHE</a>&#160;&#160;&#160;39 /* ' */</td></tr> <tr class="separator:ga6059b0b048ba6980b6107fffbd3b4b24"><td class="memSeparator" colspan="2">&#160;</td></tr> <tr class="memitem:gab3d5d72e59d3055f494627b0a524926c"><td class="memItemLeft" align="right" valign="top">#define&#160;</td><td class="memItemRight" valign="bottom"><a class="el" href="group__keys.html#gab3d5d72e59d3055f494627b0a524926c">GLFW_KEY_COMMA</a>&#160;&#160;&#160;44 /* , */</td></tr> <tr class="separator:gab3d5d72e59d3055f494627b0a524926c"><td class="memSeparator" colspan="2">&#160;</td></tr> <tr class="memitem:gac556b360f7f6fca4b70ba0aecf313fd4"><td class="memItemLeft" align="right" valign="top">#define&#160;</td><td class="memItemRight" valign="bottom"><a class="el" href="group__keys.html#gac556b360f7f6fca4b70ba0aecf313fd4">GLFW_KEY_MINUS</a>&#160;&#160;&#160;45 /* - */</td></tr> <tr class="separator:gac556b360f7f6fca4b70ba0aecf313fd4"><td class="memSeparator" colspan="2">&#160;</td></tr> <tr class="memitem:ga37e296b650eab419fc474ff69033d927"><td class="memItemLeft" align="right" valign="top">#define&#160;</td><td class="memItemRight" valign="bottom"><a class="el" href="group__keys.html#ga37e296b650eab419fc474ff69033d927">GLFW_KEY_PERIOD</a>&#160;&#160;&#160;46 /* . */</td></tr> <tr class="separator:ga37e296b650eab419fc474ff69033d927"><td class="memSeparator" colspan="2">&#160;</td></tr> <tr class="memitem:gadf3d753b2d479148d711de34b83fd0db"><td class="memItemLeft" align="right" valign="top">#define&#160;</td><td class="memItemRight" valign="bottom"><a class="el" href="group__keys.html#gadf3d753b2d479148d711de34b83fd0db">GLFW_KEY_SLASH</a>&#160;&#160;&#160;47 /* / */</td></tr> <tr class="separator:gadf3d753b2d479148d711de34b83fd0db"><td class="memSeparator" colspan="2">&#160;</td></tr> <tr class="memitem:ga50391730e9d7112ad4fd42d0bd1597c1"><td class="memItemLeft" align="right" valign="top">#define&#160;</td><td class="memItemRight" valign="bottom"><a class="el" href="group__keys.html#ga50391730e9d7112ad4fd42d0bd1597c1">GLFW_KEY_0</a>&#160;&#160;&#160;48</td></tr> <tr class="separator:ga50391730e9d7112ad4fd42d0bd1597c1"><td class="memSeparator" colspan="2">&#160;</td></tr> <tr class="memitem:ga05e4cae9ddb8d40cf6d82c8f11f2502f"><td class="memItemLeft" align="right" valign="top">#define&#160;</td><td class="memItemRight" valign="bottom"><a class="el" href="group__keys.html#ga05e4cae9ddb8d40cf6d82c8f11f2502f">GLFW_KEY_1</a>&#160;&#160;&#160;49</td></tr> <tr class="separator:ga05e4cae9ddb8d40cf6d82c8f11f2502f"><td class="memSeparator" colspan="2">&#160;</td></tr> <tr class="memitem:gadc8e66b3a4c4b5c39ad1305cf852863c"><td class="memItemLeft" align="right" valign="top">#define&#160;</td><td class="memItemRight" valign="bottom"><a class="el" href="group__keys.html#gadc8e66b3a4c4b5c39ad1305cf852863c">GLFW_KEY_2</a>&#160;&#160;&#160;50</td></tr> <tr class="separator:gadc8e66b3a4c4b5c39ad1305cf852863c"><td class="memSeparator" colspan="2">&#160;</td></tr> <tr class="memitem:ga812f0273fe1a981e1fa002ae73e92271"><td class="memItemLeft" align="right" valign="top">#define&#160;</td><td class="memItemRight" valign="bottom"><a class="el" href="group__keys.html#ga812f0273fe1a981e1fa002ae73e92271">GLFW_KEY_3</a>&#160;&#160;&#160;51</td></tr> <tr class="separator:ga812f0273fe1a981e1fa002ae73e92271"><td class="memSeparator" colspan="2">&#160;</td></tr> <tr class="memitem:ga9e14b6975a9cc8f66cdd5cb3d3861356"><td class="memItemLeft" align="right" valign="top">#define&#160;</td><td class="memItemRight" valign="bottom"><a class="el" href="group__keys.html#ga9e14b6975a9cc8f66cdd5cb3d3861356">GLFW_KEY_4</a>&#160;&#160;&#160;52</td></tr> <tr class="separator:ga9e14b6975a9cc8f66cdd5cb3d3861356"><td class="memSeparator" colspan="2">&#160;</td></tr> <tr class="memitem:ga4d74ddaa5d4c609993b4d4a15736c924"><td class="memItemLeft" align="right" valign="top">#define&#160;</td><td class="memItemRight" valign="bottom"><a class="el" href="group__keys.html#ga4d74ddaa5d4c609993b4d4a15736c924">GLFW_KEY_5</a>&#160;&#160;&#160;53</td></tr> <tr class="separator:ga4d74ddaa5d4c609993b4d4a15736c924"><td class="memSeparator" colspan="2">&#160;</td></tr> <tr class="memitem:ga9ea4ab80c313a227b14d0a7c6f810b5d"><td class="memItemLeft" align="right" valign="top">#define&#160;</td><td class="memItemRight" valign="bottom"><a class="el" href="group__keys.html#ga9ea4ab80c313a227b14d0a7c6f810b5d">GLFW_KEY_6</a>&#160;&#160;&#160;54</td></tr> <tr class="separator:ga9ea4ab80c313a227b14d0a7c6f810b5d"><td class="memSeparator" colspan="2">&#160;</td></tr> <tr class="memitem:gab79b1cfae7bd630cfc4604c1f263c666"><td class="memItemLeft" align="right" valign="top">#define&#160;</td><td class="memItemRight" valign="bottom"><a class="el" href="group__keys.html#gab79b1cfae7bd630cfc4604c1f263c666">GLFW_KEY_7</a>&#160;&#160;&#160;55</td></tr> <tr class="separator:gab79b1cfae7bd630cfc4604c1f263c666"><td class="memSeparator" colspan="2">&#160;</td></tr> <tr class="memitem:gadeaa109a0f9f5afc94fe4a108e686f6f"><td class="memItemLeft" align="right" valign="top">#define&#160;</td><td class="memItemRight" valign="bottom"><a class="el" href="group__keys.html#gadeaa109a0f9f5afc94fe4a108e686f6f">GLFW_KEY_8</a>&#160;&#160;&#160;56</td></tr> <tr class="separator:gadeaa109a0f9f5afc94fe4a108e686f6f"><td class="memSeparator" colspan="2">&#160;</td></tr> <tr class="memitem:ga2924cb5349ebbf97c8987f3521c44f39"><td class="memItemLeft" align="right" valign="top">#define&#160;</td><td class="memItemRight" valign="bottom"><a class="el" href="group__keys.html#ga2924cb5349ebbf97c8987f3521c44f39">GLFW_KEY_9</a>&#160;&#160;&#160;57</td></tr> <tr class="separator:ga2924cb5349ebbf97c8987f3521c44f39"><td class="memSeparator" colspan="2">&#160;</td></tr> <tr class="memitem:ga84233de9ee5bb3e8788a5aa07d80af7d"><td class="memItemLeft" align="right" valign="top">#define&#160;</td><td class="memItemRight" valign="bottom"><a class="el" href="group__keys.html#ga84233de9ee5bb3e8788a5aa07d80af7d">GLFW_KEY_SEMICOLON</a>&#160;&#160;&#160;59 /* ; */</td></tr> <tr class="separator:ga84233de9ee5bb3e8788a5aa07d80af7d"><td class="memSeparator" colspan="2">&#160;</td></tr> <tr class="memitem:gae1a2de47240d6664423c204bdd91bd17"><td class="memItemLeft" align="right" valign="top">#define&#160;</td><td class="memItemRight" valign="bottom"><a class="el" href="group__keys.html#gae1a2de47240d6664423c204bdd91bd17">GLFW_KEY_EQUAL</a>&#160;&#160;&#160;61 /* = */</td></tr> <tr class="separator:gae1a2de47240d6664423c204bdd91bd17"><td class="memSeparator" colspan="2">&#160;</td></tr> <tr class="memitem:ga03e842608e1ea323370889d33b8f70ff"><td class="memItemLeft" align="right" valign="top">#define&#160;</td><td class="memItemRight" valign="bottom"><a class="el" href="group__keys.html#ga03e842608e1ea323370889d33b8f70ff">GLFW_KEY_A</a>&#160;&#160;&#160;65</td></tr> <tr class="separator:ga03e842608e1ea323370889d33b8f70ff"><td class="memSeparator" colspan="2">&#160;</td></tr> <tr class="memitem:ga8e3fb647ff3aca9e8dbf14fe66332941"><td class="memItemLeft" align="right" valign="top">#define&#160;</td><td class="memItemRight" valign="bottom"><a class="el" href="group__keys.html#ga8e3fb647ff3aca9e8dbf14fe66332941">GLFW_KEY_B</a>&#160;&#160;&#160;66</td></tr> <tr class="separator:ga8e3fb647ff3aca9e8dbf14fe66332941"><td class="memSeparator" colspan="2">&#160;</td></tr> <tr class="memitem:ga00ccf3475d9ee2e679480d540d554669"><td class="memItemLeft" align="right" valign="top">#define&#160;</td><td class="memItemRight" valign="bottom"><a class="el" href="group__keys.html#ga00ccf3475d9ee2e679480d540d554669">GLFW_KEY_C</a>&#160;&#160;&#160;67</td></tr> <tr class="separator:ga00ccf3475d9ee2e679480d540d554669"><td class="memSeparator" colspan="2">&#160;</td></tr> <tr class="memitem:ga011f7cdc9a654da984a2506479606933"><td class="memItemLeft" align="right" valign="top">#define&#160;</td><td class="memItemRight" valign="bottom"><a class="el" href="group__keys.html#ga011f7cdc9a654da984a2506479606933">GLFW_KEY_D</a>&#160;&#160;&#160;68</td></tr> <tr class="separator:ga011f7cdc9a654da984a2506479606933"><td class="memSeparator" colspan="2">&#160;</td></tr> <tr class="memitem:gabf48fcc3afbe69349df432b470c96ef2"><td class="memItemLeft" align="right" valign="top">#define&#160;</td><td class="memItemRight" valign="bottom"><a class="el" href="group__keys.html#gabf48fcc3afbe69349df432b470c96ef2">GLFW_KEY_E</a>&#160;&#160;&#160;69</td></tr> <tr class="separator:gabf48fcc3afbe69349df432b470c96ef2"><td class="memSeparator" colspan="2">&#160;</td></tr> <tr class="memitem:ga5df402e02aca08444240058fd9b42a55"><td class="memItemLeft" align="right" valign="top">#define&#160;</td><td class="memItemRight" valign="bottom"><a class="el" href="group__keys.html#ga5df402e02aca08444240058fd9b42a55">GLFW_KEY_F</a>&#160;&#160;&#160;70</td></tr> <tr class="separator:ga5df402e02aca08444240058fd9b42a55"><td class="memSeparator" colspan="2">&#160;</td></tr> <tr class="memitem:gae74ecddf7cc96104ab23989b1cdab536"><td class="memItemLeft" align="right" valign="top">#define&#160;</td><td class="memItemRight" valign="bottom"><a class="el" href="group__keys.html#gae74ecddf7cc96104ab23989b1cdab536">GLFW_KEY_G</a>&#160;&#160;&#160;71</td></tr> <tr class="separator:gae74ecddf7cc96104ab23989b1cdab536"><td class="memSeparator" colspan="2">&#160;</td></tr> <tr class="memitem:gad4cc98fc8f35f015d9e2fb94bf136076"><td class="memItemLeft" align="right" valign="top">#define&#160;</td><td class="memItemRight" valign="bottom"><a class="el" href="group__keys.html#gad4cc98fc8f35f015d9e2fb94bf136076">GLFW_KEY_H</a>&#160;&#160;&#160;72</td></tr> <tr class="separator:gad4cc98fc8f35f015d9e2fb94bf136076"><td class="memSeparator" colspan="2">&#160;</td></tr> <tr class="memitem:ga274655c8bfe39742684ca393cf8ed093"><td class="memItemLeft" align="right" valign="top">#define&#160;</td><td class="memItemRight" valign="bottom"><a class="el" href="group__keys.html#ga274655c8bfe39742684ca393cf8ed093">GLFW_KEY_I</a>&#160;&#160;&#160;73</td></tr> <tr class="separator:ga274655c8bfe39742684ca393cf8ed093"><td class="memSeparator" colspan="2">&#160;</td></tr> <tr class="memitem:ga65ff2aedb129a3149ad9cb3e4159a75f"><td class="memItemLeft" align="right" valign="top">#define&#160;</td><td class="memItemRight" valign="bottom"><a class="el" href="group__keys.html#ga65ff2aedb129a3149ad9cb3e4159a75f">GLFW_KEY_J</a>&#160;&#160;&#160;74</td></tr> <tr class="separator:ga65ff2aedb129a3149ad9cb3e4159a75f"><td class="memSeparator" colspan="2">&#160;</td></tr> <tr class="memitem:ga4ae8debadf6d2a691badae0b53ea3ba0"><td class="memItemLeft" align="right" valign="top">#define&#160;</td><td class="memItemRight" valign="bottom"><a class="el" href="group__keys.html#ga4ae8debadf6d2a691badae0b53ea3ba0">GLFW_KEY_K</a>&#160;&#160;&#160;75</td></tr> <tr class="separator:ga4ae8debadf6d2a691badae0b53ea3ba0"><td class="memSeparator" colspan="2">&#160;</td></tr> <tr class="memitem:gaaa8b54a13f6b1eed85ac86f82d550db2"><td class="memItemLeft" align="right" valign="top">#define&#160;</td><td class="memItemRight" valign="bottom"><a class="el" href="group__keys.html#gaaa8b54a13f6b1eed85ac86f82d550db2">GLFW_KEY_L</a>&#160;&#160;&#160;76</td></tr> <tr class="separator:gaaa8b54a13f6b1eed85ac86f82d550db2"><td class="memSeparator" colspan="2">&#160;</td></tr> <tr class="memitem:ga4d7f0260c82e4ea3d6ebc7a21d6e3716"><td class="memItemLeft" align="right" valign="top">#define&#160;</td><td class="memItemRight" valign="bottom"><a class="el" href="group__keys.html#ga4d7f0260c82e4ea3d6ebc7a21d6e3716">GLFW_KEY_M</a>&#160;&#160;&#160;77</td></tr> <tr class="separator:ga4d7f0260c82e4ea3d6ebc7a21d6e3716"><td class="memSeparator" colspan="2">&#160;</td></tr> <tr class="memitem:gae00856dfeb5d13aafebf59d44de5cdda"><td class="memItemLeft" align="right" valign="top">#define&#160;</td><td class="memItemRight" valign="bottom"><a class="el" href="group__keys.html#gae00856dfeb5d13aafebf59d44de5cdda">GLFW_KEY_N</a>&#160;&#160;&#160;78</td></tr> <tr class="separator:gae00856dfeb5d13aafebf59d44de5cdda"><td class="memSeparator" colspan="2">&#160;</td></tr> <tr class="memitem:gaecbbb79130df419d58dd7f09a169efe9"><td class="memItemLeft" align="right" valign="top">#define&#160;</td><td class="memItemRight" valign="bottom"><a class="el" href="group__keys.html#gaecbbb79130df419d58dd7f09a169efe9">GLFW_KEY_O</a>&#160;&#160;&#160;79</td></tr> <tr class="separator:gaecbbb79130df419d58dd7f09a169efe9"><td class="memSeparator" colspan="2">&#160;</td></tr> <tr class="memitem:ga8fc15819c1094fb2afa01d84546b33e1"><td class="memItemLeft" align="right" valign="top">#define&#160;</td><td class="memItemRight" valign="bottom"><a class="el" href="group__keys.html#ga8fc15819c1094fb2afa01d84546b33e1">GLFW_KEY_P</a>&#160;&#160;&#160;80</td></tr> <tr class="separator:ga8fc15819c1094fb2afa01d84546b33e1"><td class="memSeparator" colspan="2">&#160;</td></tr> <tr class="memitem:gafdd01e38b120d67cf51e348bb47f3964"><td class="memItemLeft" align="right" valign="top">#define&#160;</td><td class="memItemRight" valign="bottom"><a class="el" href="group__keys.html#gafdd01e38b120d67cf51e348bb47f3964">GLFW_KEY_Q</a>&#160;&#160;&#160;81</td></tr> <tr class="separator:gafdd01e38b120d67cf51e348bb47f3964"><td class="memSeparator" colspan="2">&#160;</td></tr> <tr class="memitem:ga4ce6c70a0c98c50b3fe4ab9a728d4d36"><td class="memItemLeft" align="right" valign="top">#define&#160;</td><td class="memItemRight" valign="bottom"><a class="el" href="group__keys.html#ga4ce6c70a0c98c50b3fe4ab9a728d4d36">GLFW_KEY_R</a>&#160;&#160;&#160;82</td></tr> <tr class="separator:ga4ce6c70a0c98c50b3fe4ab9a728d4d36"><td class="memSeparator" colspan="2">&#160;</td></tr> <tr class="memitem:ga1570e2ccaab036ea82bed66fc1dab2a9"><td class="memItemLeft" align="right" valign="top">#define&#160;</td><td class="memItemRight" valign="bottom"><a class="el" href="group__keys.html#ga1570e2ccaab036ea82bed66fc1dab2a9">GLFW_KEY_S</a>&#160;&#160;&#160;83</td></tr> <tr class="separator:ga1570e2ccaab036ea82bed66fc1dab2a9"><td class="memSeparator" colspan="2">&#160;</td></tr> <tr class="memitem:ga90e0560422ec7a30e7f3f375bc9f37f9"><td class="memItemLeft" align="right" valign="top">#define&#160;</td><td class="memItemRight" valign="bottom"><a class="el" href="group__keys.html#ga90e0560422ec7a30e7f3f375bc9f37f9">GLFW_KEY_T</a>&#160;&#160;&#160;84</td></tr> <tr class="separator:ga90e0560422ec7a30e7f3f375bc9f37f9"><td class="memSeparator" colspan="2">&#160;</td></tr> <tr class="memitem:gacad52f3bf7d378fc0ffa72a76769256d"><td class="memItemLeft" align="right" valign="top">#define&#160;</td><td class="memItemRight" valign="bottom"><a class="el" href="group__keys.html#gacad52f3bf7d378fc0ffa72a76769256d">GLFW_KEY_U</a>&#160;&#160;&#160;85</td></tr> <tr class="separator:gacad52f3bf7d378fc0ffa72a76769256d"><td class="memSeparator" colspan="2">&#160;</td></tr> <tr class="memitem:ga22c7763899ecf7788862e5f90eacce6b"><td class="memItemLeft" align="right" valign="top">#define&#160;</td><td class="memItemRight" valign="bottom"><a class="el" href="group__keys.html#ga22c7763899ecf7788862e5f90eacce6b">GLFW_KEY_V</a>&#160;&#160;&#160;86</td></tr> <tr class="separator:ga22c7763899ecf7788862e5f90eacce6b"><td class="memSeparator" colspan="2">&#160;</td></tr> <tr class="memitem:gaa06a712e6202661fc03da5bdb7b6e545"><td class="memItemLeft" align="right" valign="top">#define&#160;</td><td class="memItemRight" valign="bottom"><a class="el" href="group__keys.html#gaa06a712e6202661fc03da5bdb7b6e545">GLFW_KEY_W</a>&#160;&#160;&#160;87</td></tr> <tr class="separator:gaa06a712e6202661fc03da5bdb7b6e545"><td class="memSeparator" colspan="2">&#160;</td></tr> <tr class="memitem:gac1c42c0bf4192cea713c55598b06b744"><td class="memItemLeft" align="right" valign="top">#define&#160;</td><td class="memItemRight" valign="bottom"><a class="el" href="group__keys.html#gac1c42c0bf4192cea713c55598b06b744">GLFW_KEY_X</a>&#160;&#160;&#160;88</td></tr> <tr class="separator:gac1c42c0bf4192cea713c55598b06b744"><td class="memSeparator" colspan="2">&#160;</td></tr> <tr class="memitem:gafd9f115a549effdf8e372a787c360313"><td class="memItemLeft" align="right" valign="top">#define&#160;</td><td class="memItemRight" valign="bottom"><a class="el" href="group__keys.html#gafd9f115a549effdf8e372a787c360313">GLFW_KEY_Y</a>&#160;&#160;&#160;89</td></tr> <tr class="separator:gafd9f115a549effdf8e372a787c360313"><td class="memSeparator" colspan="2">&#160;</td></tr> <tr class="memitem:gac489e208c26afda8d4938ed88718760a"><td class="memItemLeft" align="right" valign="top">#define&#160;</td><td class="memItemRight" valign="bottom"><a class="el" href="group__keys.html#gac489e208c26afda8d4938ed88718760a">GLFW_KEY_Z</a>&#160;&#160;&#160;90</td></tr> <tr class="separator:gac489e208c26afda8d4938ed88718760a"><td class="memSeparator" colspan="2">&#160;</td></tr> <tr class="memitem:gad1c8d9adac53925276ecb1d592511d8a"><td class="memItemLeft" align="right" valign="top">#define&#160;</td><td class="memItemRight" valign="bottom"><a class="el" href="group__keys.html#gad1c8d9adac53925276ecb1d592511d8a">GLFW_KEY_LEFT_BRACKET</a>&#160;&#160;&#160;91 /* [ */</td></tr> <tr class="separator:gad1c8d9adac53925276ecb1d592511d8a"><td class="memSeparator" colspan="2">&#160;</td></tr> <tr class="memitem:gab8155ea99d1ab27ff56f24f8dc73f8d1"><td class="memItemLeft" align="right" valign="top">#define&#160;</td><td class="memItemRight" valign="bottom"><a class="el" href="group__keys.html#gab8155ea99d1ab27ff56f24f8dc73f8d1">GLFW_KEY_BACKSLASH</a>&#160;&#160;&#160;92 /* \ */</td></tr> <tr class="separator:gab8155ea99d1ab27ff56f24f8dc73f8d1"><td class="memSeparator" colspan="2">&#160;</td></tr> <tr class="memitem:ga86ef225fd6a66404caae71044cdd58d8"><td class="memItemLeft" align="right" valign="top">#define&#160;</td><td class="memItemRight" valign="bottom"><a class="el" href="group__keys.html#ga86ef225fd6a66404caae71044cdd58d8">GLFW_KEY_RIGHT_BRACKET</a>&#160;&#160;&#160;93 /* ] */</td></tr> <tr class="separator:ga86ef225fd6a66404caae71044cdd58d8"><td class="memSeparator" colspan="2">&#160;</td></tr> <tr class="memitem:ga7a3701fb4e2a0b136ff4b568c3c8d668"><td class="memItemLeft" align="right" valign="top">#define&#160;</td><td class="memItemRight" valign="bottom"><a class="el" href="group__keys.html#ga7a3701fb4e2a0b136ff4b568c3c8d668">GLFW_KEY_GRAVE_ACCENT</a>&#160;&#160;&#160;96 /* ` */</td></tr> <tr class="separator:ga7a3701fb4e2a0b136ff4b568c3c8d668"><td class="memSeparator" colspan="2">&#160;</td></tr> <tr class="memitem:gadc78dad3dab76bcd4b5c20114052577a"><td class="memItemLeft" align="right" valign="top">#define&#160;</td><td class="memItemRight" valign="bottom"><a class="el" href="group__keys.html#gadc78dad3dab76bcd4b5c20114052577a">GLFW_KEY_WORLD_1</a>&#160;&#160;&#160;161 /* non-US #1 */</td></tr> <tr class="separator:gadc78dad3dab76bcd4b5c20114052577a"><td class="memSeparator" colspan="2">&#160;</td></tr> <tr class="memitem:ga20494bfebf0bb4fc9503afca18ab2c5e"><td class="memItemLeft" align="right" valign="top">#define&#160;</td><td class="memItemRight" valign="bottom"><a class="el" href="group__keys.html#ga20494bfebf0bb4fc9503afca18ab2c5e">GLFW_KEY_WORLD_2</a>&#160;&#160;&#160;162 /* non-US #2 */</td></tr> <tr class="separator:ga20494bfebf0bb4fc9503afca18ab2c5e"><td class="memSeparator" colspan="2">&#160;</td></tr> <tr class="memitem:gaac6596c350b635c245113b81c2123b93"><td class="memItemLeft" align="right" valign="top">#define&#160;</td><td class="memItemRight" valign="bottom"><a class="el" href="group__keys.html#gaac6596c350b635c245113b81c2123b93">GLFW_KEY_ESCAPE</a>&#160;&#160;&#160;256</td></tr> <tr class="separator:gaac6596c350b635c245113b81c2123b93"><td class="memSeparator" colspan="2">&#160;</td></tr> <tr class="memitem:ga9555a92ecbecdbc1f3435219c571d667"><td class="memItemLeft" align="right" valign="top">#define&#160;</td><td class="memItemRight" valign="bottom"><a class="el" href="group__keys.html#ga9555a92ecbecdbc1f3435219c571d667">GLFW_KEY_ENTER</a>&#160;&#160;&#160;257</td></tr> <tr class="separator:ga9555a92ecbecdbc1f3435219c571d667"><td class="memSeparator" colspan="2">&#160;</td></tr> <tr class="memitem:ga6908a4bda9950a3e2b73f794bbe985df"><td class="memItemLeft" align="right" valign="top">#define&#160;</td><td class="memItemRight" valign="bottom"><a class="el" href="group__keys.html#ga6908a4bda9950a3e2b73f794bbe985df">GLFW_KEY_TAB</a>&#160;&#160;&#160;258</td></tr> <tr class="separator:ga6908a4bda9950a3e2b73f794bbe985df"><td class="memSeparator" colspan="2">&#160;</td></tr> <tr class="memitem:ga6c0df1fe2f156bbd5a98c66d76ff3635"><td class="memItemLeft" align="right" valign="top">#define&#160;</td><td class="memItemRight" valign="bottom"><a class="el" href="group__keys.html#ga6c0df1fe2f156bbd5a98c66d76ff3635">GLFW_KEY_BACKSPACE</a>&#160;&#160;&#160;259</td></tr> <tr class="separator:ga6c0df1fe2f156bbd5a98c66d76ff3635"><td class="memSeparator" colspan="2">&#160;</td></tr> <tr class="memitem:ga373ac7365435d6b0eb1068f470e34f47"><td class="memItemLeft" align="right" valign="top">#define&#160;</td><td class="memItemRight" valign="bottom"><a class="el" href="group__keys.html#ga373ac7365435d6b0eb1068f470e34f47">GLFW_KEY_INSERT</a>&#160;&#160;&#160;260</td></tr> <tr class="separator:ga373ac7365435d6b0eb1068f470e34f47"><td class="memSeparator" colspan="2">&#160;</td></tr> <tr class="memitem:gadb111e4df74b8a715f2c05dad58d2682"><td class="memItemLeft" align="right" valign="top">#define&#160;</td><td class="memItemRight" valign="bottom"><a class="el" href="group__keys.html#gadb111e4df74b8a715f2c05dad58d2682">GLFW_KEY_DELETE</a>&#160;&#160;&#160;261</td></tr> <tr class="separator:gadb111e4df74b8a715f2c05dad58d2682"><td class="memSeparator" colspan="2">&#160;</td></tr> <tr class="memitem:ga06ba07662e8c291a4a84535379ffc7ac"><td class="memItemLeft" align="right" valign="top">#define&#160;</td><td class="memItemRight" valign="bottom"><a class="el" href="group__keys.html#ga06ba07662e8c291a4a84535379ffc7ac">GLFW_KEY_RIGHT</a>&#160;&#160;&#160;262</td></tr> <tr class="separator:ga06ba07662e8c291a4a84535379ffc7ac"><td class="memSeparator" colspan="2">&#160;</td></tr> <tr class="memitem:gae12a010d33c309a67ab9460c51eb2462"><td class="memItemLeft" align="right" valign="top">#define&#160;</td><td class="memItemRight" valign="bottom"><a class="el" href="group__keys.html#gae12a010d33c309a67ab9460c51eb2462">GLFW_KEY_LEFT</a>&#160;&#160;&#160;263</td></tr> <tr class="separator:gae12a010d33c309a67ab9460c51eb2462"><td class="memSeparator" colspan="2">&#160;</td></tr> <tr class="memitem:gae2e3958c71595607416aa7bf082be2f9"><td class="memItemLeft" align="right" valign="top">#define&#160;</td><td class="memItemRight" valign="bottom"><a class="el" href="group__keys.html#gae2e3958c71595607416aa7bf082be2f9">GLFW_KEY_DOWN</a>&#160;&#160;&#160;264</td></tr> <tr class="separator:gae2e3958c71595607416aa7bf082be2f9"><td class="memSeparator" colspan="2">&#160;</td></tr> <tr class="memitem:ga2f3342b194020d3544c67e3506b6f144"><td class="memItemLeft" align="right" valign="top">#define&#160;</td><td class="memItemRight" valign="bottom"><a class="el" href="group__keys.html#ga2f3342b194020d3544c67e3506b6f144">GLFW_KEY_UP</a>&#160;&#160;&#160;265</td></tr> <tr class="separator:ga2f3342b194020d3544c67e3506b6f144"><td class="memSeparator" colspan="2">&#160;</td></tr> <tr class="memitem:ga3ab731f9622f0db280178a5f3cc6d586"><td class="memItemLeft" align="right" valign="top">#define&#160;</td><td class="memItemRight" valign="bottom"><a class="el" href="group__keys.html#ga3ab731f9622f0db280178a5f3cc6d586">GLFW_KEY_PAGE_UP</a>&#160;&#160;&#160;266</td></tr> <tr class="separator:ga3ab731f9622f0db280178a5f3cc6d586"><td class="memSeparator" colspan="2">&#160;</td></tr> <tr class="memitem:gaee0a8fa442001cc2147812f84b59041c"><td class="memItemLeft" align="right" valign="top">#define&#160;</td><td class="memItemRight" valign="bottom"><a class="el" href="group__keys.html#gaee0a8fa442001cc2147812f84b59041c">GLFW_KEY_PAGE_DOWN</a>&#160;&#160;&#160;267</td></tr> <tr class="separator:gaee0a8fa442001cc2147812f84b59041c"><td class="memSeparator" colspan="2">&#160;</td></tr> <tr class="memitem:ga41452c7287195d481e43207318c126a7"><td class="memItemLeft" align="right" valign="top">#define&#160;</td><td class="memItemRight" valign="bottom"><a class="el" href="group__keys.html#ga41452c7287195d481e43207318c126a7">GLFW_KEY_HOME</a>&#160;&#160;&#160;268</td></tr> <tr class="separator:ga41452c7287195d481e43207318c126a7"><td class="memSeparator" colspan="2">&#160;</td></tr> <tr class="memitem:ga86587ea1df19a65978d3e3b8439bedd9"><td class="memItemLeft" align="right" valign="top">#define&#160;</td><td class="memItemRight" valign="bottom"><a class="el" href="group__keys.html#ga86587ea1df19a65978d3e3b8439bedd9">GLFW_KEY_END</a>&#160;&#160;&#160;269</td></tr> <tr class="separator:ga86587ea1df19a65978d3e3b8439bedd9"><td class="memSeparator" colspan="2">&#160;</td></tr> <tr class="memitem:ga92c1d2c9d63485f3d70f94f688d48672"><td class="memItemLeft" align="right" valign="top">#define&#160;</td><td class="memItemRight" valign="bottom"><a class="el" href="group__keys.html#ga92c1d2c9d63485f3d70f94f688d48672">GLFW_KEY_CAPS_LOCK</a>&#160;&#160;&#160;280</td></tr> <tr class="separator:ga92c1d2c9d63485f3d70f94f688d48672"><td class="memSeparator" colspan="2">&#160;</td></tr> <tr class="memitem:gaf622b63b9537f7084c2ab649b8365630"><td class="memItemLeft" align="right" valign="top">#define&#160;</td><td class="memItemRight" valign="bottom"><a class="el" href="group__keys.html#gaf622b63b9537f7084c2ab649b8365630">GLFW_KEY_SCROLL_LOCK</a>&#160;&#160;&#160;281</td></tr> <tr class="separator:gaf622b63b9537f7084c2ab649b8365630"><td class="memSeparator" colspan="2">&#160;</td></tr> <tr class="memitem:ga3946edc362aeff213b2be6304296cf43"><td class="memItemLeft" align="right" valign="top">#define&#160;</td><td class="memItemRight" valign="bottom"><a class="el" href="group__keys.html#ga3946edc362aeff213b2be6304296cf43">GLFW_KEY_NUM_LOCK</a>&#160;&#160;&#160;282</td></tr> <tr class="separator:ga3946edc362aeff213b2be6304296cf43"><td class="memSeparator" colspan="2">&#160;</td></tr> <tr class="memitem:gaf964c2e65e97d0cf785a5636ee8df642"><td class="memItemLeft" align="right" valign="top">#define&#160;</td><td class="memItemRight" valign="bottom"><a class="el" href="group__keys.html#gaf964c2e65e97d0cf785a5636ee8df642">GLFW_KEY_PRINT_SCREEN</a>&#160;&#160;&#160;283</td></tr> <tr class="separator:gaf964c2e65e97d0cf785a5636ee8df642"><td class="memSeparator" colspan="2">&#160;</td></tr> <tr class="memitem:ga8116b9692d87382afb5849b6d8907f18"><td class="memItemLeft" align="right" valign="top">#define&#160;</td><td class="memItemRight" valign="bottom"><a class="el" href="group__keys.html#ga8116b9692d87382afb5849b6d8907f18">GLFW_KEY_PAUSE</a>&#160;&#160;&#160;284</td></tr> <tr class="separator:ga8116b9692d87382afb5849b6d8907f18"><td class="memSeparator" colspan="2">&#160;</td></tr> <tr class="memitem:gafb8d66c573acf22e364049477dcbea30"><td class="memItemLeft" align="right" valign="top">#define&#160;</td><td class="memItemRight" valign="bottom"><a class="el" href="group__keys.html#gafb8d66c573acf22e364049477dcbea30">GLFW_KEY_F1</a>&#160;&#160;&#160;290</td></tr> <tr class="separator:gafb8d66c573acf22e364049477dcbea30"><td class="memSeparator" colspan="2">&#160;</td></tr> <tr class="memitem:ga0900750aff94889b940f5e428c07daee"><td class="memItemLeft" align="right" valign="top">#define&#160;</td><td class="memItemRight" valign="bottom"><a class="el" href="group__keys.html#ga0900750aff94889b940f5e428c07daee">GLFW_KEY_F2</a>&#160;&#160;&#160;291</td></tr> <tr class="separator:ga0900750aff94889b940f5e428c07daee"><td class="memSeparator" colspan="2">&#160;</td></tr> <tr class="memitem:gaed7cd729c0147a551bb8b7bb36c17015"><td class="memItemLeft" align="right" valign="top">#define&#160;</td><td class="memItemRight" valign="bottom"><a class="el" href="group__keys.html#gaed7cd729c0147a551bb8b7bb36c17015">GLFW_KEY_F3</a>&#160;&#160;&#160;292</td></tr> <tr class="separator:gaed7cd729c0147a551bb8b7bb36c17015"><td class="memSeparator" colspan="2">&#160;</td></tr> <tr class="memitem:ga9b61ebd0c63b44b7332fda2c9763eaa6"><td class="memItemLeft" align="right" valign="top">#define&#160;</td><td class="memItemRight" valign="bottom"><a class="el" href="group__keys.html#ga9b61ebd0c63b44b7332fda2c9763eaa6">GLFW_KEY_F4</a>&#160;&#160;&#160;293</td></tr> <tr class="separator:ga9b61ebd0c63b44b7332fda2c9763eaa6"><td class="memSeparator" colspan="2">&#160;</td></tr> <tr class="memitem:gaf258dda9947daa428377938ed577c8c2"><td class="memItemLeft" align="right" valign="top">#define&#160;</td><td class="memItemRight" valign="bottom"><a class="el" href="group__keys.html#gaf258dda9947daa428377938ed577c8c2">GLFW_KEY_F5</a>&#160;&#160;&#160;294</td></tr> <tr class="separator:gaf258dda9947daa428377938ed577c8c2"><td class="memSeparator" colspan="2">&#160;</td></tr> <tr class="memitem:ga6dc2d3f87b9d51ffbbbe2ef0299d8e1d"><td class="memItemLeft" align="right" valign="top">#define&#160;</td><td class="memItemRight" valign="bottom"><a class="el" href="group__keys.html#ga6dc2d3f87b9d51ffbbbe2ef0299d8e1d">GLFW_KEY_F6</a>&#160;&#160;&#160;295</td></tr> <tr class="separator:ga6dc2d3f87b9d51ffbbbe2ef0299d8e1d"><td class="memSeparator" colspan="2">&#160;</td></tr> <tr class="memitem:gacca6ef8a2162c52a0ac1d881e8d9c38a"><td class="memItemLeft" align="right" valign="top">#define&#160;</td><td class="memItemRight" valign="bottom"><a class="el" href="group__keys.html#gacca6ef8a2162c52a0ac1d881e8d9c38a">GLFW_KEY_F7</a>&#160;&#160;&#160;296</td></tr> <tr class="separator:gacca6ef8a2162c52a0ac1d881e8d9c38a"><td class="memSeparator" colspan="2">&#160;</td></tr> <tr class="memitem:gac9d39390336ae14e4a93e295de43c7e8"><td class="memItemLeft" align="right" valign="top">#define&#160;</td><td class="memItemRight" valign="bottom"><a class="el" href="group__keys.html#gac9d39390336ae14e4a93e295de43c7e8">GLFW_KEY_F8</a>&#160;&#160;&#160;297</td></tr> <tr class="separator:gac9d39390336ae14e4a93e295de43c7e8"><td class="memSeparator" colspan="2">&#160;</td></tr> <tr class="memitem:gae40de0de1c9f21cd26c9afa3d7050851"><td class="memItemLeft" align="right" valign="top">#define&#160;</td><td class="memItemRight" valign="bottom"><a class="el" href="group__keys.html#gae40de0de1c9f21cd26c9afa3d7050851">GLFW_KEY_F9</a>&#160;&#160;&#160;298</td></tr> <tr class="separator:gae40de0de1c9f21cd26c9afa3d7050851"><td class="memSeparator" colspan="2">&#160;</td></tr> <tr class="memitem:ga718d11d2f7d57471a2f6a894235995b1"><td class="memItemLeft" align="right" valign="top">#define&#160;</td><td class="memItemRight" valign="bottom"><a class="el" href="group__keys.html#ga718d11d2f7d57471a2f6a894235995b1">GLFW_KEY_F10</a>&#160;&#160;&#160;299</td></tr> <tr class="separator:ga718d11d2f7d57471a2f6a894235995b1"><td class="memSeparator" colspan="2">&#160;</td></tr> <tr class="memitem:ga0bc04b11627e7d69339151e7306b2832"><td class="memItemLeft" align="right" valign="top">#define&#160;</td><td class="memItemRight" valign="bottom"><a class="el" href="group__keys.html#ga0bc04b11627e7d69339151e7306b2832">GLFW_KEY_F11</a>&#160;&#160;&#160;300</td></tr> <tr class="separator:ga0bc04b11627e7d69339151e7306b2832"><td class="memSeparator" colspan="2">&#160;</td></tr> <tr class="memitem:gaf5908fa9b0a906ae03fc2c61ac7aa3e2"><td class="memItemLeft" align="right" valign="top">#define&#160;</td><td class="memItemRight" valign="bottom"><a class="el" href="group__keys.html#gaf5908fa9b0a906ae03fc2c61ac7aa3e2">GLFW_KEY_F12</a>&#160;&#160;&#160;301</td></tr> <tr class="separator:gaf5908fa9b0a906ae03fc2c61ac7aa3e2"><td class="memSeparator" colspan="2">&#160;</td></tr> <tr class="memitem:gad637f4308655e1001bd6ad942bc0fd4b"><td class="memItemLeft" align="right" valign="top">#define&#160;</td><td class="memItemRight" valign="bottom"><a class="el" href="group__keys.html#gad637f4308655e1001bd6ad942bc0fd4b">GLFW_KEY_F13</a>&#160;&#160;&#160;302</td></tr> <tr class="separator:gad637f4308655e1001bd6ad942bc0fd4b"><td class="memSeparator" colspan="2">&#160;</td></tr> <tr class="memitem:gaf14c66cff3396e5bd46e803c035e6c1f"><td class="memItemLeft" align="right" valign="top">#define&#160;</td><td class="memItemRight" valign="bottom"><a class="el" href="group__keys.html#gaf14c66cff3396e5bd46e803c035e6c1f">GLFW_KEY_F14</a>&#160;&#160;&#160;303</td></tr> <tr class="separator:gaf14c66cff3396e5bd46e803c035e6c1f"><td class="memSeparator" colspan="2">&#160;</td></tr> <tr class="memitem:ga7f70970db6e8be1794da8516a6d14058"><td class="memItemLeft" align="right" valign="top">#define&#160;</td><td class="memItemRight" valign="bottom"><a class="el" href="group__keys.html#ga7f70970db6e8be1794da8516a6d14058">GLFW_KEY_F15</a>&#160;&#160;&#160;304</td></tr> <tr class="separator:ga7f70970db6e8be1794da8516a6d14058"><td class="memSeparator" colspan="2">&#160;</td></tr> <tr class="memitem:gaa582dbb1d2ba2050aa1dca0838095b27"><td class="memItemLeft" align="right" valign="top">#define&#160;</td><td class="memItemRight" valign="bottom"><a class="el" href="group__keys.html#gaa582dbb1d2ba2050aa1dca0838095b27">GLFW_KEY_F16</a>&#160;&#160;&#160;305</td></tr> <tr class="separator:gaa582dbb1d2ba2050aa1dca0838095b27"><td class="memSeparator" colspan="2">&#160;</td></tr> <tr class="memitem:ga972ce5c365e2394b36104b0e3125c748"><td class="memItemLeft" align="right" valign="top">#define&#160;</td><td class="memItemRight" valign="bottom"><a class="el" href="group__keys.html#ga972ce5c365e2394b36104b0e3125c748">GLFW_KEY_F17</a>&#160;&#160;&#160;306</td></tr> <tr class="separator:ga972ce5c365e2394b36104b0e3125c748"><td class="memSeparator" colspan="2">&#160;</td></tr> <tr class="memitem:gaebf6391058d5566601e357edc5ea737c"><td class="memItemLeft" align="right" valign="top">#define&#160;</td><td class="memItemRight" valign="bottom"><a class="el" href="group__keys.html#gaebf6391058d5566601e357edc5ea737c">GLFW_KEY_F18</a>&#160;&#160;&#160;307</td></tr> <tr class="separator:gaebf6391058d5566601e357edc5ea737c"><td class="memSeparator" colspan="2">&#160;</td></tr> <tr class="memitem:gaec011d9ba044058cb54529da710e9791"><td class="memItemLeft" align="right" valign="top">#define&#160;</td><td class="memItemRight" valign="bottom"><a class="el" href="group__keys.html#gaec011d9ba044058cb54529da710e9791">GLFW_KEY_F19</a>&#160;&#160;&#160;308</td></tr> <tr class="separator:gaec011d9ba044058cb54529da710e9791"><td class="memSeparator" colspan="2">&#160;</td></tr> <tr class="memitem:ga82b9c721ada04cd5ca8de767da38022f"><td class="memItemLeft" align="right" valign="top">#define&#160;</td><td class="memItemRight" valign="bottom"><a class="el" href="group__keys.html#ga82b9c721ada04cd5ca8de767da38022f">GLFW_KEY_F20</a>&#160;&#160;&#160;309</td></tr> <tr class="separator:ga82b9c721ada04cd5ca8de767da38022f"><td class="memSeparator" colspan="2">&#160;</td></tr> <tr class="memitem:ga356afb14d3440ff2bb378f74f7ebc60f"><td class="memItemLeft" align="right" valign="top">#define&#160;</td><td class="memItemRight" valign="bottom"><a class="el" href="group__keys.html#ga356afb14d3440ff2bb378f74f7ebc60f">GLFW_KEY_F21</a>&#160;&#160;&#160;310</td></tr> <tr class="separator:ga356afb14d3440ff2bb378f74f7ebc60f"><td class="memSeparator" colspan="2">&#160;</td></tr> <tr class="memitem:ga90960bd2a155f2b09675324d3dff1565"><td class="memItemLeft" align="right" valign="top">#define&#160;</td><td class="memItemRight" valign="bottom"><a class="el" href="group__keys.html#ga90960bd2a155f2b09675324d3dff1565">GLFW_KEY_F22</a>&#160;&#160;&#160;311</td></tr> <tr class="separator:ga90960bd2a155f2b09675324d3dff1565"><td class="memSeparator" colspan="2">&#160;</td></tr> <tr class="memitem:ga43c21099aac10952d1be909a8ddee4d5"><td class="memItemLeft" align="right" valign="top">#define&#160;</td><td class="memItemRight" valign="bottom"><a class="el" href="group__keys.html#ga43c21099aac10952d1be909a8ddee4d5">GLFW_KEY_F23</a>&#160;&#160;&#160;312</td></tr> <tr class="separator:ga43c21099aac10952d1be909a8ddee4d5"><td class="memSeparator" colspan="2">&#160;</td></tr> <tr class="memitem:ga8150374677b5bed3043408732152dea2"><td class="memItemLeft" align="right" valign="top">#define&#160;</td><td class="memItemRight" valign="bottom"><a class="el" href="group__keys.html#ga8150374677b5bed3043408732152dea2">GLFW_KEY_F24</a>&#160;&#160;&#160;313</td></tr> <tr class="separator:ga8150374677b5bed3043408732152dea2"><td class="memSeparator" colspan="2">&#160;</td></tr> <tr class="memitem:gaa4bbd93ed73bb4c6ae7d83df880b7199"><td class="memItemLeft" align="right" valign="top">#define&#160;</td><td class="memItemRight" valign="bottom"><a class="el" href="group__keys.html#gaa4bbd93ed73bb4c6ae7d83df880b7199">GLFW_KEY_F25</a>&#160;&#160;&#160;314</td></tr> <tr class="separator:gaa4bbd93ed73bb4c6ae7d83df880b7199"><td class="memSeparator" colspan="2">&#160;</td></tr> <tr class="memitem:ga10515dafc55b71e7683f5b4fedd1c70d"><td class="memItemLeft" align="right" valign="top">#define&#160;</td><td class="memItemRight" valign="bottom"><a class="el" href="group__keys.html#ga10515dafc55b71e7683f5b4fedd1c70d">GLFW_KEY_KP_0</a>&#160;&#160;&#160;320</td></tr> <tr class="separator:ga10515dafc55b71e7683f5b4fedd1c70d"><td class="memSeparator" colspan="2">&#160;</td></tr> <tr class="memitem:gaf3a29a334402c5eaf0b3439edf5587c3"><td class="memItemLeft" align="right" valign="top">#define&#160;</td><td class="memItemRight" valign="bottom"><a class="el" href="group__keys.html#gaf3a29a334402c5eaf0b3439edf5587c3">GLFW_KEY_KP_1</a>&#160;&#160;&#160;321</td></tr> <tr class="separator:gaf3a29a334402c5eaf0b3439edf5587c3"><td class="memSeparator" colspan="2">&#160;</td></tr> <tr class="memitem:gaf82d5a802ab8213c72653d7480c16f13"><td class="memItemLeft" align="right" valign="top">#define&#160;</td><td class="memItemRight" valign="bottom"><a class="el" href="group__keys.html#gaf82d5a802ab8213c72653d7480c16f13">GLFW_KEY_KP_2</a>&#160;&#160;&#160;322</td></tr> <tr class="separator:gaf82d5a802ab8213c72653d7480c16f13"><td class="memSeparator" colspan="2">&#160;</td></tr> <tr class="memitem:ga7e25ff30d56cd512828c1d4ae8d54ef2"><td class="memItemLeft" align="right" valign="top">#define&#160;</td><td class="memItemRight" valign="bottom"><a class="el" href="group__keys.html#ga7e25ff30d56cd512828c1d4ae8d54ef2">GLFW_KEY_KP_3</a>&#160;&#160;&#160;323</td></tr> <tr class="separator:ga7e25ff30d56cd512828c1d4ae8d54ef2"><td class="memSeparator" colspan="2">&#160;</td></tr> <tr class="memitem:gada7ec86778b85e0b4de0beea72234aea"><td class="memItemLeft" align="right" valign="top">#define&#160;</td><td class="memItemRight" valign="bottom"><a class="el" href="group__keys.html#gada7ec86778b85e0b4de0beea72234aea">GLFW_KEY_KP_4</a>&#160;&#160;&#160;324</td></tr> <tr class="separator:gada7ec86778b85e0b4de0beea72234aea"><td class="memSeparator" colspan="2">&#160;</td></tr> <tr class="memitem:ga9a5be274434866c51738cafbb6d26b45"><td class="memItemLeft" align="right" valign="top">#define&#160;</td><td class="memItemRight" valign="bottom"><a class="el" href="group__keys.html#ga9a5be274434866c51738cafbb6d26b45">GLFW_KEY_KP_5</a>&#160;&#160;&#160;325</td></tr> <tr class="separator:ga9a5be274434866c51738cafbb6d26b45"><td class="memSeparator" colspan="2">&#160;</td></tr> <tr class="memitem:gafc141b0f8450519084c01092a3157faa"><td class="memItemLeft" align="right" valign="top">#define&#160;</td><td class="memItemRight" valign="bottom"><a class="el" href="group__keys.html#gafc141b0f8450519084c01092a3157faa">GLFW_KEY_KP_6</a>&#160;&#160;&#160;326</td></tr> <tr class="separator:gafc141b0f8450519084c01092a3157faa"><td class="memSeparator" colspan="2">&#160;</td></tr> <tr class="memitem:ga8882f411f05d04ec77a9563974bbfa53"><td class="memItemLeft" align="right" valign="top">#define&#160;</td><td class="memItemRight" valign="bottom"><a class="el" href="group__keys.html#ga8882f411f05d04ec77a9563974bbfa53">GLFW_KEY_KP_7</a>&#160;&#160;&#160;327</td></tr> <tr class="separator:ga8882f411f05d04ec77a9563974bbfa53"><td class="memSeparator" colspan="2">&#160;</td></tr> <tr class="memitem:gab2ea2e6a12f89d315045af520ac78cec"><td class="memItemLeft" align="right" valign="top">#define&#160;</td><td class="memItemRight" valign="bottom"><a class="el" href="group__keys.html#gab2ea2e6a12f89d315045af520ac78cec">GLFW_KEY_KP_8</a>&#160;&#160;&#160;328</td></tr> <tr class="separator:gab2ea2e6a12f89d315045af520ac78cec"><td class="memSeparator" colspan="2">&#160;</td></tr> <tr class="memitem:gafb21426b630ed4fcc084868699ba74c1"><td class="memItemLeft" align="right" valign="top">#define&#160;</td><td class="memItemRight" valign="bottom"><a class="el" href="group__keys.html#gafb21426b630ed4fcc084868699ba74c1">GLFW_KEY_KP_9</a>&#160;&#160;&#160;329</td></tr> <tr class="separator:gafb21426b630ed4fcc084868699ba74c1"><td class="memSeparator" colspan="2">&#160;</td></tr> <tr class="memitem:ga4e231d968796331a9ea0dbfb98d4005b"><td class="memItemLeft" align="right" valign="top">#define&#160;</td><td class="memItemRight" valign="bottom"><a class="el" href="group__keys.html#ga4e231d968796331a9ea0dbfb98d4005b">GLFW_KEY_KP_DECIMAL</a>&#160;&#160;&#160;330</td></tr> <tr class="separator:ga4e231d968796331a9ea0dbfb98d4005b"><td class="memSeparator" colspan="2">&#160;</td></tr> <tr class="memitem:gabca1733780a273d549129ad0f250d1e5"><td class="memItemLeft" align="right" valign="top">#define&#160;</td><td class="memItemRight" valign="bottom"><a class="el" href="group__keys.html#gabca1733780a273d549129ad0f250d1e5">GLFW_KEY_KP_DIVIDE</a>&#160;&#160;&#160;331</td></tr> <tr class="separator:gabca1733780a273d549129ad0f250d1e5"><td class="memSeparator" colspan="2">&#160;</td></tr> <tr class="memitem:ga9ada267eb0e78ed2ada8701dd24a56ef"><td class="memItemLeft" align="right" valign="top">#define&#160;</td><td class="memItemRight" valign="bottom"><a class="el" href="group__keys.html#ga9ada267eb0e78ed2ada8701dd24a56ef">GLFW_KEY_KP_MULTIPLY</a>&#160;&#160;&#160;332</td></tr> <tr class="separator:ga9ada267eb0e78ed2ada8701dd24a56ef"><td class="memSeparator" colspan="2">&#160;</td></tr> <tr class="memitem:gaa3dbd60782ff93d6082a124bce1fa236"><td class="memItemLeft" align="right" valign="top">#define&#160;</td><td class="memItemRight" valign="bottom"><a class="el" href="group__keys.html#gaa3dbd60782ff93d6082a124bce1fa236">GLFW_KEY_KP_SUBTRACT</a>&#160;&#160;&#160;333</td></tr> <tr class="separator:gaa3dbd60782ff93d6082a124bce1fa236"><td class="memSeparator" colspan="2">&#160;</td></tr> <tr class="memitem:gad09c7c98acc79e89aa6a0a91275becac"><td class="memItemLeft" align="right" valign="top">#define&#160;</td><td class="memItemRight" valign="bottom"><a class="el" href="group__keys.html#gad09c7c98acc79e89aa6a0a91275becac">GLFW_KEY_KP_ADD</a>&#160;&#160;&#160;334</td></tr> <tr class="separator:gad09c7c98acc79e89aa6a0a91275becac"><td class="memSeparator" colspan="2">&#160;</td></tr> <tr class="memitem:ga4f728f8738f2986bd63eedd3d412e8cf"><td class="memItemLeft" align="right" valign="top">#define&#160;</td><td class="memItemRight" valign="bottom"><a class="el" href="group__keys.html#ga4f728f8738f2986bd63eedd3d412e8cf">GLFW_KEY_KP_ENTER</a>&#160;&#160;&#160;335</td></tr> <tr class="separator:ga4f728f8738f2986bd63eedd3d412e8cf"><td class="memSeparator" colspan="2">&#160;</td></tr> <tr class="memitem:gaebdc76d4a808191e6d21b7e4ad2acd97"><td class="memItemLeft" align="right" valign="top">#define&#160;</td><td class="memItemRight" valign="bottom"><a class="el" href="group__keys.html#gaebdc76d4a808191e6d21b7e4ad2acd97">GLFW_KEY_KP_EQUAL</a>&#160;&#160;&#160;336</td></tr> <tr class="separator:gaebdc76d4a808191e6d21b7e4ad2acd97"><td class="memSeparator" colspan="2">&#160;</td></tr> <tr class="memitem:ga8a530a28a65c44ab5d00b759b756d3f6"><td class="memItemLeft" align="right" valign="top">#define&#160;</td><td class="memItemRight" valign="bottom"><a class="el" href="group__keys.html#ga8a530a28a65c44ab5d00b759b756d3f6">GLFW_KEY_LEFT_SHIFT</a>&#160;&#160;&#160;340</td></tr> <tr class="separator:ga8a530a28a65c44ab5d00b759b756d3f6"><td class="memSeparator" colspan="2">&#160;</td></tr> <tr class="memitem:ga9f97b743e81460ac4b2deddecd10a464"><td class="memItemLeft" align="right" valign="top">#define&#160;</td><td class="memItemRight" valign="bottom"><a class="el" href="group__keys.html#ga9f97b743e81460ac4b2deddecd10a464">GLFW_KEY_LEFT_CONTROL</a>&#160;&#160;&#160;341</td></tr> <tr class="separator:ga9f97b743e81460ac4b2deddecd10a464"><td class="memSeparator" colspan="2">&#160;</td></tr> <tr class="memitem:ga7f27dabf63a7789daa31e1c96790219b"><td class="memItemLeft" align="right" valign="top">#define&#160;</td><td class="memItemRight" valign="bottom"><a class="el" href="group__keys.html#ga7f27dabf63a7789daa31e1c96790219b">GLFW_KEY_LEFT_ALT</a>&#160;&#160;&#160;342</td></tr> <tr class="separator:ga7f27dabf63a7789daa31e1c96790219b"><td class="memSeparator" colspan="2">&#160;</td></tr> <tr class="memitem:gafb1207c91997fc295afd1835fbc5641a"><td class="memItemLeft" align="right" valign="top">#define&#160;</td><td class="memItemRight" valign="bottom"><a class="el" href="group__keys.html#gafb1207c91997fc295afd1835fbc5641a">GLFW_KEY_LEFT_SUPER</a>&#160;&#160;&#160;343</td></tr> <tr class="separator:gafb1207c91997fc295afd1835fbc5641a"><td class="memSeparator" colspan="2">&#160;</td></tr> <tr class="memitem:gaffca36b99c9dce1a19cb9befbadce691"><td class="memItemLeft" align="right" valign="top">#define&#160;</td><td class="memItemRight" valign="bottom"><a class="el" href="group__keys.html#gaffca36b99c9dce1a19cb9befbadce691">GLFW_KEY_RIGHT_SHIFT</a>&#160;&#160;&#160;344</td></tr> <tr class="separator:gaffca36b99c9dce1a19cb9befbadce691"><td class="memSeparator" colspan="2">&#160;</td></tr> <tr class="memitem:gad1ca2094b2694e7251d0ab1fd34f8519"><td class="memItemLeft" align="right" valign="top">#define&#160;</td><td class="memItemRight" valign="bottom"><a class="el" href="group__keys.html#gad1ca2094b2694e7251d0ab1fd34f8519">GLFW_KEY_RIGHT_CONTROL</a>&#160;&#160;&#160;345</td></tr> <tr class="separator:gad1ca2094b2694e7251d0ab1fd34f8519"><td class="memSeparator" colspan="2">&#160;</td></tr> <tr class="memitem:ga687b38009131cfdd07a8d05fff8fa446"><td class="memItemLeft" align="right" valign="top">#define&#160;</td><td class="memItemRight" valign="bottom"><a class="el" href="group__keys.html#ga687b38009131cfdd07a8d05fff8fa446">GLFW_KEY_RIGHT_ALT</a>&#160;&#160;&#160;346</td></tr> <tr class="separator:ga687b38009131cfdd07a8d05fff8fa446"><td class="memSeparator" colspan="2">&#160;</td></tr> <tr class="memitem:gad4547a3e8e247594acb60423fe6502db"><td class="memItemLeft" align="right" valign="top">#define&#160;</td><td class="memItemRight" valign="bottom"><a class="el" href="group__keys.html#gad4547a3e8e247594acb60423fe6502db">GLFW_KEY_RIGHT_SUPER</a>&#160;&#160;&#160;347</td></tr> <tr class="separator:gad4547a3e8e247594acb60423fe6502db"><td class="memSeparator" colspan="2">&#160;</td></tr> <tr class="memitem:ga9845be48a745fc232045c9ec174d8820"><td class="memItemLeft" align="right" valign="top">#define&#160;</td><td class="memItemRight" valign="bottom"><a class="el" href="group__keys.html#ga9845be48a745fc232045c9ec174d8820">GLFW_KEY_MENU</a>&#160;&#160;&#160;348</td></tr> <tr class="separator:ga9845be48a745fc232045c9ec174d8820"><td class="memSeparator" colspan="2">&#160;</td></tr> <tr class="memitem:ga442cbaef7bfb9a4ba13594dd7fbf2789"><td class="memItemLeft" align="right" valign="top">#define&#160;</td><td class="memItemRight" valign="bottom"><a class="el" href="group__keys.html#ga442cbaef7bfb9a4ba13594dd7fbf2789">GLFW_KEY_LAST</a>&#160;&#160;&#160;<a class="el" href="group__keys.html#ga9845be48a745fc232045c9ec174d8820">GLFW_KEY_MENU</a></td></tr> <tr class="separator:ga442cbaef7bfb9a4ba13594dd7fbf2789"><td class="memSeparator" colspan="2">&#160;</td></tr> </table> <h2 class="groupheader">Macro Definition Documentation</h2> <a id="ga99aacc875b6b27a072552631e13775c7"></a> <h2 class="memtitle"><span class="permalink"><a href="#ga99aacc875b6b27a072552631e13775c7">&#9670;&nbsp;</a></span>GLFW_KEY_UNKNOWN</h2> <div class="memitem"> <div class="memproto"> <table class="memname"> <tr> <td class="memname">#define GLFW_KEY_UNKNOWN&#160;&#160;&#160;-1</td> </tr> </table> </div><div class="memdoc"> </div> </div> <a id="gaddb2c23772b97fd7e26e8ee66f1ad014"></a> <h2 class="memtitle"><span class="permalink"><a href="#gaddb2c23772b97fd7e26e8ee66f1ad014">&#9670;&nbsp;</a></span>GLFW_KEY_SPACE</h2> <div class="memitem"> <div class="memproto"> <table class="memname"> <tr> <td class="memname">#define GLFW_KEY_SPACE&#160;&#160;&#160;32</td> </tr> </table> </div><div class="memdoc"> </div> </div> <a id="ga6059b0b048ba6980b6107fffbd3b4b24"></a> <h2 class="memtitle"><span class="permalink"><a href="#ga6059b0b048ba6980b6107fffbd3b4b24">&#9670;&nbsp;</a></span>GLFW_KEY_APOSTROPHE</h2> <div class="memitem"> <div class="memproto"> <table class="memname"> <tr> <td class="memname">#define GLFW_KEY_APOSTROPHE&#160;&#160;&#160;39 /* ' */</td> </tr> </table> </div><div class="memdoc"> </div> </div> <a id="gab3d5d72e59d3055f494627b0a524926c"></a> <h2 class="memtitle"><span class="permalink"><a href="#gab3d5d72e59d3055f494627b0a524926c">&#9670;&nbsp;</a></span>GLFW_KEY_COMMA</h2> <div class="memitem"> <div class="memproto"> <table class="memname"> <tr> <td class="memname">#define GLFW_KEY_COMMA&#160;&#160;&#160;44 /* , */</td> </tr> </table> </div><div class="memdoc"> </div> </div> <a id="gac556b360f7f6fca4b70ba0aecf313fd4"></a> <h2 class="memtitle"><span class="permalink"><a href="#gac556b360f7f6fca4b70ba0aecf313fd4">&#9670;&nbsp;</a></span>GLFW_KEY_MINUS</h2> <div class="memitem"> <div class="memproto"> <table class="memname"> <tr> <td class="memname">#define GLFW_KEY_MINUS&#160;&#160;&#160;45 /* - */</td> </tr> </table> </div><div class="memdoc"> </div> </div> <a id="ga37e296b650eab419fc474ff69033d927"></a> <h2 class="memtitle"><span class="permalink"><a href="#ga37e296b650eab419fc474ff69033d927">&#9670;&nbsp;</a></span>GLFW_KEY_PERIOD</h2> <div class="memitem"> <div class="memproto"> <table class="memname"> <tr> <td class="memname">#define GLFW_KEY_PERIOD&#160;&#160;&#160;46 /* . */</td> </tr> </table> </div><div class="memdoc"> </div> </div> <a id="gadf3d753b2d479148d711de34b83fd0db"></a> <h2 class="memtitle"><span class="permalink"><a href="#gadf3d753b2d479148d711de34b83fd0db">&#9670;&nbsp;</a></span>GLFW_KEY_SLASH</h2> <div class="memitem"> <div class="memproto"> <table class="memname"> <tr> <td class="memname">#define GLFW_KEY_SLASH&#160;&#160;&#160;47 /* / */</td> </tr> </table> </div><div class="memdoc"> </div> </div> <a id="ga50391730e9d7112ad4fd42d0bd1597c1"></a> <h2 class="memtitle"><span class="permalink"><a href="#ga50391730e9d7112ad4fd42d0bd1597c1">&#9670;&nbsp;</a></span>GLFW_KEY_0</h2> <div class="memitem"> <div class="memproto"> <table class="memname"> <tr> <td class="memname">#define GLFW_KEY_0&#160;&#160;&#160;48</td> </tr> </table> </div><div class="memdoc"> </div> </div> <a id="ga05e4cae9ddb8d40cf6d82c8f11f2502f"></a> <h2 class="memtitle"><span class="permalink"><a href="#ga05e4cae9ddb8d40cf6d82c8f11f2502f">&#9670;&nbsp;</a></span>GLFW_KEY_1</h2> <div class="memitem"> <div class="memproto"> <table class="memname"> <tr> <td class="memname">#define GLFW_KEY_1&#160;&#160;&#160;49</td> </tr> </table> </div><div class="memdoc"> </div> </div> <a id="gadc8e66b3a4c4b5c39ad1305cf852863c"></a> <h2 class="memtitle"><span class="permalink"><a href="#gadc8e66b3a4c4b5c39ad1305cf852863c">&#9670;&nbsp;</a></span>GLFW_KEY_2</h2> <div class="memitem"> <div class="memproto"> <table class="memname"> <tr> <td class="memname">#define GLFW_KEY_2&#160;&#160;&#160;50</td> </tr> </table> </div><div class="memdoc"> </div> </div> <a id="ga812f0273fe1a981e1fa002ae73e92271"></a> <h2 class="memtitle"><span class="permalink"><a href="#ga812f0273fe1a981e1fa002ae73e92271">&#9670;&nbsp;</a></span>GLFW_KEY_3</h2> <div class="memitem"> <div class="memproto"> <table class="memname"> <tr> <td class="memname">#define GLFW_KEY_3&#160;&#160;&#160;51</td> </tr> </table> </div><div class="memdoc"> </div> </div> <a id="ga9e14b6975a9cc8f66cdd5cb3d3861356"></a> <h2 class="memtitle"><span class="permalink"><a href="#ga9e14b6975a9cc8f66cdd5cb3d3861356">&#9670;&nbsp;</a></span>GLFW_KEY_4</h2> <div class="memitem"> <div class="memproto"> <table class="memname"> <tr> <td class="memname">#define GLFW_KEY_4&#160;&#160;&#160;52</td> </tr> </table> </div><div class="memdoc"> </div> </div> <a id="ga4d74ddaa5d4c609993b4d4a15736c924"></a> <h2 class="memtitle"><span class="permalink"><a href="#ga4d74ddaa5d4c609993b4d4a15736c924">&#9670;&nbsp;</a></span>GLFW_KEY_5</h2> <div class="memitem"> <div class="memproto"> <table class="memname"> <tr> <td class="memname">#define GLFW_KEY_5&#160;&#160;&#160;53</td> </tr> </table> </div><div class="memdoc"> </div> </div> <a id="ga9ea4ab80c313a227b14d0a7c6f810b5d"></a> <h2 class="memtitle"><span class="permalink"><a href="#ga9ea4ab80c313a227b14d0a7c6f810b5d">&#9670;&nbsp;</a></span>GLFW_KEY_6</h2> <div class="memitem"> <div class="memproto"> <table class="memname"> <tr> <td class="memname">#define GLFW_KEY_6&#160;&#160;&#160;54</td> </tr> </table> </div><div class="memdoc"> </div> </div> <a id="gab79b1cfae7bd630cfc4604c1f263c666"></a> <h2 class="memtitle"><span class="permalink"><a href="#gab79b1cfae7bd630cfc4604c1f263c666">&#9670;&nbsp;</a></span>GLFW_KEY_7</h2> <div class="memitem"> <div class="memproto"> <table class="memname"> <tr> <td class="memname">#define GLFW_KEY_7&#160;&#160;&#160;55</td> </tr> </table> </div><div class="memdoc"> </div> </div> <a id="gadeaa109a0f9f5afc94fe4a108e686f6f"></a> <h2 class="memtitle"><span class="permalink"><a href="#gadeaa109a0f9f5afc94fe4a108e686f6f">&#9670;&nbsp;</a></span>GLFW_KEY_8</h2> <div class="memitem"> <div class="memproto"> <table class="memname"> <tr> <td class="memname">#define GLFW_KEY_8&#160;&#160;&#160;56</td> </tr> </table> </div><div class="memdoc"> </div> </div> <a id="ga2924cb5349ebbf97c8987f3521c44f39"></a> <h2 class="memtitle"><span class="permalink"><a href="#ga2924cb5349ebbf97c8987f3521c44f39">&#9670;&nbsp;</a></span>GLFW_KEY_9</h2> <div class="memitem"> <div class="memproto"> <table class="memname"> <tr> <td class="memname">#define GLFW_KEY_9&#160;&#160;&#160;57</td> </tr> </table> </div><div class="memdoc"> </div> </div> <a id="ga84233de9ee5bb3e8788a5aa07d80af7d"></a> <h2 class="memtitle"><span class="permalink"><a href="#ga84233de9ee5bb3e8788a5aa07d80af7d">&#9670;&nbsp;</a></span>GLFW_KEY_SEMICOLON</h2> <div class="memitem"> <div class="memproto"> <table class="memname"> <tr> <td class="memname">#define GLFW_KEY_SEMICOLON&#160;&#160;&#160;59 /* ; */</td> </tr> </table> </div><div class="memdoc"> </div> </div> <a id="gae1a2de47240d6664423c204bdd91bd17"></a> <h2 class="memtitle"><span class="permalink"><a href="#gae1a2de47240d6664423c204bdd91bd17">&#9670;&nbsp;</a></span>GLFW_KEY_EQUAL</h2> <div class="memitem"> <div class="memproto"> <table class="memname"> <tr> <td class="memname">#define GLFW_KEY_EQUAL&#160;&#160;&#160;61 /* = */</td> </tr> </table> </div><div class="memdoc"> </div> </div> <a id="ga03e842608e1ea323370889d33b8f70ff"></a> <h2 class="memtitle"><span class="permalink"><a href="#ga03e842608e1ea323370889d33b8f70ff">&#9670;&nbsp;</a></span>GLFW_KEY_A</h2> <div class="memitem"> <div class="memproto"> <table class="memname"> <tr> <td class="memname">#define GLFW_KEY_A&#160;&#160;&#160;65</td> </tr> </table> </div><div class="memdoc"> </div> </div> <a id="ga8e3fb647ff3aca9e8dbf14fe66332941"></a> <h2 class="memtitle"><span class="permalink"><a href="#ga8e3fb647ff3aca9e8dbf14fe66332941">&#9670;&nbsp;</a></span>GLFW_KEY_B</h2> <div class="memitem"> <div class="memproto"> <table class="memname"> <tr> <td class="memname">#define GLFW_KEY_B&#160;&#160;&#160;66</td> </tr> </table> </div><div class="memdoc"> </div> </div> <a id="ga00ccf3475d9ee2e679480d540d554669"></a> <h2 class="memtitle"><span class="permalink"><a href="#ga00ccf3475d9ee2e679480d540d554669">&#9670;&nbsp;</a></span>GLFW_KEY_C</h2> <div class="memitem"> <div class="memproto"> <table class="memname"> <tr> <td class="memname">#define GLFW_KEY_C&#160;&#160;&#160;67</td> </tr> </table> </div><div class="memdoc"> </div> </div> <a id="ga011f7cdc9a654da984a2506479606933"></a> <h2 class="memtitle"><span class="permalink"><a href="#ga011f7cdc9a654da984a2506479606933">&#9670;&nbsp;</a></span>GLFW_KEY_D</h2> <div class="memitem"> <div class="memproto"> <table class="memname"> <tr> <td class="memname">#define GLFW_KEY_D&#160;&#160;&#160;68</td> </tr> </table> </div><div class="memdoc"> </div> </div> <a id="gabf48fcc3afbe69349df432b470c96ef2"></a> <h2 class="memtitle"><span class="permalink"><a href="#gabf48fcc3afbe69349df432b470c96ef2">&#9670;&nbsp;</a></span>GLFW_KEY_E</h2> <div class="memitem"> <div class="memproto"> <table class="memname"> <tr> <td class="memname">#define GLFW_KEY_E&#160;&#160;&#160;69</td> </tr> </table> </div><div class="memdoc"> </div> </div> <a id="ga5df402e02aca08444240058fd9b42a55"></a> <h2 class="memtitle"><span class="permalink"><a href="#ga5df402e02aca08444240058fd9b42a55">&#9670;&nbsp;</a></span>GLFW_KEY_F</h2> <div class="memitem"> <div class="memproto"> <table class="memname"> <tr> <td class="memname">#define GLFW_KEY_F&#160;&#160;&#160;70</td> </tr> </table> </div><div class="memdoc"> </div> </div> <a id="gae74ecddf7cc96104ab23989b1cdab536"></a> <h2 class="memtitle"><span class="permalink"><a href="#gae74ecddf7cc96104ab23989b1cdab536">&#9670;&nbsp;</a></span>GLFW_KEY_G</h2> <div class="memitem"> <div class="memproto"> <table class="memname"> <tr> <td class="memname">#define GLFW_KEY_G&#160;&#160;&#160;71</td> </tr> </table> </div><div class="memdoc"> </div> </div> <a id="gad4cc98fc8f35f015d9e2fb94bf136076"></a> <h2 class="memtitle"><span class="permalink"><a href="#gad4cc98fc8f35f015d9e2fb94bf136076">&#9670;&nbsp;</a></span>GLFW_KEY_H</h2> <div class="memitem"> <div class="memproto"> <table class="memname"> <tr> <td class="memname">#define GLFW_KEY_H&#160;&#160;&#160;72</td> </tr> </table> </div><div class="memdoc"> </div> </div> <a id="ga274655c8bfe39742684ca393cf8ed093"></a> <h2 class="memtitle"><span class="permalink"><a href="#ga274655c8bfe39742684ca393cf8ed093">&#9670;&nbsp;</a></span>GLFW_KEY_I</h2> <div class="memitem"> <div class="memproto"> <table class="memname"> <tr> <td class="memname">#define GLFW_KEY_I&#160;&#160;&#160;73</td> </tr> </table> </div><div class="memdoc"> </div> </div> <a id="ga65ff2aedb129a3149ad9cb3e4159a75f"></a> <h2 class="memtitle"><span class="permalink"><a href="#ga65ff2aedb129a3149ad9cb3e4159a75f">&#9670;&nbsp;</a></span>GLFW_KEY_J</h2> <div class="memitem"> <div class="memproto"> <table class="memname"> <tr> <td class="memname">#define GLFW_KEY_J&#160;&#160;&#160;74</td> </tr> </table> </div><div class="memdoc"> </div> </div> <a id="ga4ae8debadf6d2a691badae0b53ea3ba0"></a> <h2 class="memtitle"><span class="permalink"><a href="#ga4ae8debadf6d2a691badae0b53ea3ba0">&#9670;&nbsp;</a></span>GLFW_KEY_K</h2> <div class="memitem"> <div class="memproto"> <table class="memname"> <tr> <td class="memname">#define GLFW_KEY_K&#160;&#160;&#160;75</td> </tr> </table> </div><div class="memdoc"> </div> </div> <a id="gaaa8b54a13f6b1eed85ac86f82d550db2"></a> <h2 class="memtitle"><span class="permalink"><a href="#gaaa8b54a13f6b1eed85ac86f82d550db2">&#9670;&nbsp;</a></span>GLFW_KEY_L</h2> <div class="memitem"> <div class="memproto"> <table class="memname"> <tr> <td class="memname">#define GLFW_KEY_L&#160;&#160;&#160;76</td> </tr> </table> </div><div class="memdoc"> </div> </div> <a id="ga4d7f0260c82e4ea3d6ebc7a21d6e3716"></a> <h2 class="memtitle"><span class="permalink"><a href="#ga4d7f0260c82e4ea3d6ebc7a21d6e3716">&#9670;&nbsp;</a></span>GLFW_KEY_M</h2> <div class="memitem"> <div class="memproto"> <table class="memname"> <tr> <td class="memname">#define GLFW_KEY_M&#160;&#160;&#160;77</td> </tr> </table> </div><div class="memdoc"> </div> </div> <a id="gae00856dfeb5d13aafebf59d44de5cdda"></a> <h2 class="memtitle"><span class="permalink"><a href="#gae00856dfeb5d13aafebf59d44de5cdda">&#9670;&nbsp;</a></span>GLFW_KEY_N</h2> <div class="memitem"> <div class="memproto"> <table class="memname"> <tr> <td class="memname">#define GLFW_KEY_N&#160;&#160;&#160;78</td> </tr> </table> </div><div class="memdoc"> </div> </div> <a id="gaecbbb79130df419d58dd7f09a169efe9"></a> <h2 class="memtitle"><span class="permalink"><a href="#gaecbbb79130df419d58dd7f09a169efe9">&#9670;&nbsp;</a></span>GLFW_KEY_O</h2> <div class="memitem"> <div class="memproto"> <table class="memname"> <tr> <td class="memname">#define GLFW_KEY_O&#160;&#160;&#160;79</td> </tr> </table> </div><div class="memdoc"> </div> </div> <a id="ga8fc15819c1094fb2afa01d84546b33e1"></a> <h2 class="memtitle"><span class="permalink"><a href="#ga8fc15819c1094fb2afa01d84546b33e1">&#9670;&nbsp;</a></span>GLFW_KEY_P</h2> <div class="memitem"> <div class="memproto"> <table class="memname"> <tr> <td class="memname">#define GLFW_KEY_P&#160;&#160;&#160;80</td> </tr> </table> </div><div class="memdoc"> </div> </div> <a id="gafdd01e38b120d67cf51e348bb47f3964"></a> <h2 class="memtitle"><span class="permalink"><a href="#gafdd01e38b120d67cf51e348bb47f3964">&#9670;&nbsp;</a></span>GLFW_KEY_Q</h2> <div class="memitem"> <div class="memproto"> <table class="memname"> <tr> <td class="memname">#define GLFW_KEY_Q&#160;&#160;&#160;81</td> </tr> </table> </div><div class="memdoc"> </div> </div> <a id="ga4ce6c70a0c98c50b3fe4ab9a728d4d36"></a> <h2 class="memtitle"><span class="permalink"><a href="#ga4ce6c70a0c98c50b3fe4ab9a728d4d36">&#9670;&nbsp;</a></span>GLFW_KEY_R</h2> <div class="memitem"> <div class="memproto"> <table class="memname"> <tr> <td class="memname">#define GLFW_KEY_R&#160;&#160;&#160;82</td> </tr> </table> </div><div class="memdoc"> </div> </div> <a id="ga1570e2ccaab036ea82bed66fc1dab2a9"></a> <h2 class="memtitle"><span class="permalink"><a href="#ga1570e2ccaab036ea82bed66fc1dab2a9">&#9670;&nbsp;</a></span>GLFW_KEY_S</h2> <div class="memitem"> <div class="memproto"> <table class="memname"> <tr> <td class="memname">#define GLFW_KEY_S&#160;&#160;&#160;83</td> </tr> </table> </div><div class="memdoc"> </div> </div> <a id="ga90e0560422ec7a30e7f3f375bc9f37f9"></a> <h2 class="memtitle"><span class="permalink"><a href="#ga90e0560422ec7a30e7f3f375bc9f37f9">&#9670;&nbsp;</a></span>GLFW_KEY_T</h2> <div class="memitem"> <div class="memproto"> <table class="memname"> <tr> <td class="memname">#define GLFW_KEY_T&#160;&#160;&#160;84</td> </tr> </table> </div><div class="memdoc"> </div> </div> <a id="gacad52f3bf7d378fc0ffa72a76769256d"></a> <h2 class="memtitle"><span class="permalink"><a href="#gacad52f3bf7d378fc0ffa72a76769256d">&#9670;&nbsp;</a></span>GLFW_KEY_U</h2> <div class="memitem"> <div class="memproto"> <table class="memname"> <tr> <td class="memname">#define GLFW_KEY_U&#160;&#160;&#160;85</td> </tr> </table> </div><div class="memdoc"> </div> </div> <a id="ga22c7763899ecf7788862e5f90eacce6b"></a> <h2 class="memtitle"><span class="permalink"><a href="#ga22c7763899ecf7788862e5f90eacce6b">&#9670;&nbsp;</a></span>GLFW_KEY_V</h2> <div class="memitem"> <div class="memproto"> <table class="memname"> <tr> <td class="memname">#define GLFW_KEY_V&#160;&#160;&#160;86</td> </tr> </table> </div><div class="memdoc"> </div> </div> <a id="gaa06a712e6202661fc03da5bdb7b6e545"></a> <h2 class="memtitle"><span class="permalink"><a href="#gaa06a712e6202661fc03da5bdb7b6e545">&#9670;&nbsp;</a></span>GLFW_KEY_W</h2> <div class="memitem"> <div class="memproto"> <table class="memname"> <tr> <td class="memname">#define GLFW_KEY_W&#160;&#160;&#160;87</td> </tr> </table> </div><div class="memdoc"> </div> </div> <a id="gac1c42c0bf4192cea713c55598b06b744"></a> <h2 class="memtitle"><span class="permalink"><a href="#gac1c42c0bf4192cea713c55598b06b744">&#9670;&nbsp;</a></span>GLFW_KEY_X</h2> <div class="memitem"> <div class="memproto"> <table class="memname"> <tr> <td class="memname">#define GLFW_KEY_X&#160;&#160;&#160;88</td> </tr> </table> </div><div class="memdoc"> </div> </div> <a id="gafd9f115a549effdf8e372a787c360313"></a> <h2 class="memtitle"><span class="permalink"><a href="#gafd9f115a549effdf8e372a787c360313">&#9670;&nbsp;</a></span>GLFW_KEY_Y</h2> <div class="memitem"> <div class="memproto"> <table class="memname"> <tr> <td class="memname">#define GLFW_KEY_Y&#160;&#160;&#160;89</td> </tr> </table> </div><div class="memdoc"> </div> </div> <a id="gac489e208c26afda8d4938ed88718760a"></a> <h2 class="memtitle"><span class="permalink"><a href="#gac489e208c26afda8d4938ed88718760a">&#9670;&nbsp;</a></span>GLFW_KEY_Z</h2> <div class="memitem"> <div class="memproto"> <table class="memname"> <tr> <td class="memname">#define GLFW_KEY_Z&#160;&#160;&#160;90</td> </tr> </table> </div><div class="memdoc"> </div> </div> <a id="gad1c8d9adac53925276ecb1d592511d8a"></a> <h2 class="memtitle"><span class="permalink"><a href="#gad1c8d9adac53925276ecb1d592511d8a">&#9670;&nbsp;</a></span>GLFW_KEY_LEFT_BRACKET</h2> <div class="memitem"> <div class="memproto"> <table class="memname"> <tr> <td class="memname">#define GLFW_KEY_LEFT_BRACKET&#160;&#160;&#160;91 /* [ */</td> </tr> </table> </div><div class="memdoc"> </div> </div> <a id="gab8155ea99d1ab27ff56f24f8dc73f8d1"></a> <h2 class="memtitle"><span class="permalink"><a href="#gab8155ea99d1ab27ff56f24f8dc73f8d1">&#9670;&nbsp;</a></span>GLFW_KEY_BACKSLASH</h2> <div class="memitem"> <div class="memproto"> <table class="memname"> <tr> <td class="memname">#define GLFW_KEY_BACKSLASH&#160;&#160;&#160;92 /* \ */</td> </tr> </table> </div><div class="memdoc"> </div> </div> <a id="ga86ef225fd6a66404caae71044cdd58d8"></a> <h2 class="memtitle"><span class="permalink"><a href="#ga86ef225fd6a66404caae71044cdd58d8">&#9670;&nbsp;</a></span>GLFW_KEY_RIGHT_BRACKET</h2> <div class="memitem"> <div class="memproto"> <table class="memname"> <tr> <td class="memname">#define GLFW_KEY_RIGHT_BRACKET&#160;&#160;&#160;93 /* ] */</td> </tr> </table> </div><div class="memdoc"> </div> </div> <a id="ga7a3701fb4e2a0b136ff4b568c3c8d668"></a> <h2 class="memtitle"><span class="permalink"><a href="#ga7a3701fb4e2a0b136ff4b568c3c8d668">&#9670;&nbsp;</a></span>GLFW_KEY_GRAVE_ACCENT</h2> <div class="memitem"> <div class="memproto"> <table class="memname"> <tr> <td class="memname">#define GLFW_KEY_GRAVE_ACCENT&#160;&#160;&#160;96 /* ` */</td> </tr> </table> </div><div class="memdoc"> </div> </div> <a id="gadc78dad3dab76bcd4b5c20114052577a"></a> <h2 class="memtitle"><span class="permalink"><a href="#gadc78dad3dab76bcd4b5c20114052577a">&#9670;&nbsp;</a></span>GLFW_KEY_WORLD_1</h2> <div class="memitem"> <div class="memproto"> <table class="memname"> <tr> <td class="memname">#define GLFW_KEY_WORLD_1&#160;&#160;&#160;161 /* non-US #1 */</td> </tr> </table> </div><div class="memdoc"> </div> </div> <a id="ga20494bfebf0bb4fc9503afca18ab2c5e"></a> <h2 class="memtitle"><span class="permalink"><a href="#ga20494bfebf0bb4fc9503afca18ab2c5e">&#9670;&nbsp;</a></span>GLFW_KEY_WORLD_2</h2> <div class="memitem"> <div class="memproto"> <table class="memname"> <tr> <td class="memname">#define GLFW_KEY_WORLD_2&#160;&#160;&#160;162 /* non-US #2 */</td> </tr> </table> </div><div class="memdoc"> </div> </div> <a id="gaac6596c350b635c245113b81c2123b93"></a> <h2 class="memtitle"><span class="permalink"><a href="#gaac6596c350b635c245113b81c2123b93">&#9670;&nbsp;</a></span>GLFW_KEY_ESCAPE</h2> <div class="memitem"> <div class="memproto"> <table class="memname"> <tr> <td class="memname">#define GLFW_KEY_ESCAPE&#160;&#160;&#160;256</td> </tr> </table> </div><div class="memdoc"> </div> </div> <a id="ga9555a92ecbecdbc1f3435219c571d667"></a> <h2 class="memtitle"><span class="permalink"><a href="#ga9555a92ecbecdbc1f3435219c571d667">&#9670;&nbsp;</a></span>GLFW_KEY_ENTER</h2> <div class="memitem"> <div class="memproto"> <table class="memname"> <tr> <td class="memname">#define GLFW_KEY_ENTER&#160;&#160;&#160;257</td> </tr> </table> </div><div class="memdoc"> </div> </div> <a id="ga6908a4bda9950a3e2b73f794bbe985df"></a> <h2 class="memtitle"><span class="permalink"><a href="#ga6908a4bda9950a3e2b73f794bbe985df">&#9670;&nbsp;</a></span>GLFW_KEY_TAB</h2> <div class="memitem"> <div class="memproto"> <table class="memname"> <tr> <td class="memname">#define GLFW_KEY_TAB&#160;&#160;&#160;258</td> </tr> </table> </div><div class="memdoc"> </div> </div> <a id="ga6c0df1fe2f156bbd5a98c66d76ff3635"></a> <h2 class="memtitle"><span class="permalink"><a href="#ga6c0df1fe2f156bbd5a98c66d76ff3635">&#9670;&nbsp;</a></span>GLFW_KEY_BACKSPACE</h2> <div class="memitem"> <div class="memproto"> <table class="memname"> <tr> <td class="memname">#define GLFW_KEY_BACKSPACE&#160;&#160;&#160;259</td> </tr> </table> </div><div class="memdoc"> </div> </div> <a id="ga373ac7365435d6b0eb1068f470e34f47"></a> <h2 class="memtitle"><span class="permalink"><a href="#ga373ac7365435d6b0eb1068f470e34f47">&#9670;&nbsp;</a></span>GLFW_KEY_INSERT</h2> <div class="memitem"> <div class="memproto"> <table class="memname"> <tr> <td class="memname">#define GLFW_KEY_INSERT&#160;&#160;&#160;260</td> </tr> </table> </div><div class="memdoc"> </div> </div> <a id="gadb111e4df74b8a715f2c05dad58d2682"></a> <h2 class="memtitle"><span class="permalink"><a href="#gadb111e4df74b8a715f2c05dad58d2682">&#9670;&nbsp;</a></span>GLFW_KEY_DELETE</h2> <div class="memitem"> <div class="memproto"> <table class="memname"> <tr> <td class="memname">#define GLFW_KEY_DELETE&#160;&#160;&#160;261</td> </tr> </table> </div><div class="memdoc"> </div> </div> <a id="ga06ba07662e8c291a4a84535379ffc7ac"></a> <h2 class="memtitle"><span class="permalink"><a href="#ga06ba07662e8c291a4a84535379ffc7ac">&#9670;&nbsp;</a></span>GLFW_KEY_RIGHT</h2> <div class="memitem"> <div class="memproto"> <table class="memname"> <tr> <td class="memname">#define GLFW_KEY_RIGHT&#160;&#160;&#160;262</td> </tr> </table> </div><div class="memdoc"> </div> </div> <a id="gae12a010d33c309a67ab9460c51eb2462"></a> <h2 class="memtitle"><span class="permalink"><a href="#gae12a010d33c309a67ab9460c51eb2462">&#9670;&nbsp;</a></span>GLFW_KEY_LEFT</h2> <div class="memitem"> <div class="memproto"> <table class="memname"> <tr> <td class="memname">#define GLFW_KEY_LEFT&#160;&#160;&#160;263</td> </tr> </table> </div><div class="memdoc"> </div> </div> <a id="gae2e3958c71595607416aa7bf082be2f9"></a> <h2 class="memtitle"><span class="permalink"><a href="#gae2e3958c71595607416aa7bf082be2f9">&#9670;&nbsp;</a></span>GLFW_KEY_DOWN</h2> <div class="memitem"> <div class="memproto"> <table class="memname"> <tr> <td class="memname">#define GLFW_KEY_DOWN&#160;&#160;&#160;264</td> </tr> </table> </div><div class="memdoc"> </div> </div> <a id="ga2f3342b194020d3544c67e3506b6f144"></a> <h2 class="memtitle"><span class="permalink"><a href="#ga2f3342b194020d3544c67e3506b6f144">&#9670;&nbsp;</a></span>GLFW_KEY_UP</h2> <div class="memitem"> <div class="memproto"> <table class="memname"> <tr> <td class="memname">#define GLFW_KEY_UP&#160;&#160;&#160;265</td> </tr> </table> </div><div class="memdoc"> </div> </div> <a id="ga3ab731f9622f0db280178a5f3cc6d586"></a> <h2 class="memtitle"><span class="permalink"><a href="#ga3ab731f9622f0db280178a5f3cc6d586">&#9670;&nbsp;</a></span>GLFW_KEY_PAGE_UP</h2> <div class="memitem"> <div class="memproto"> <table class="memname"> <tr> <td class="memname">#define GLFW_KEY_PAGE_UP&#160;&#160;&#160;266</td> </tr> </table> </div><div class="memdoc"> </div> </div> <a id="gaee0a8fa442001cc2147812f84b59041c"></a> <h2 class="memtitle"><span class="permalink"><a href="#gaee0a8fa442001cc2147812f84b59041c">&#9670;&nbsp;</a></span>GLFW_KEY_PAGE_DOWN</h2> <div class="memitem"> <div class="memproto"> <table class="memname"> <tr> <td class="memname">#define GLFW_KEY_PAGE_DOWN&#160;&#160;&#160;267</td> </tr> </table> </div><div class="memdoc"> </div> </div> <a id="ga41452c7287195d481e43207318c126a7"></a> <h2 class="memtitle"><span class="permalink"><a href="#ga41452c7287195d481e43207318c126a7">&#9670;&nbsp;</a></span>GLFW_KEY_HOME</h2> <div class="memitem"> <div class="memproto"> <table class="memname"> <tr> <td class="memname">#define GLFW_KEY_HOME&#160;&#160;&#160;268</td> </tr> </table> </div><div class="memdoc"> </div> </div> <a id="ga86587ea1df19a65978d3e3b8439bedd9"></a> <h2 class="memtitle"><span class="permalink"><a href="#ga86587ea1df19a65978d3e3b8439bedd9">&#9670;&nbsp;</a></span>GLFW_KEY_END</h2> <div class="memitem"> <div class="memproto"> <table class="memname"> <tr> <td class="memname">#define GLFW_KEY_END&#160;&#160;&#160;269</td> </tr> </table> </div><div class="memdoc"> </div> </div> <a id="ga92c1d2c9d63485f3d70f94f688d48672"></a> <h2 class="memtitle"><span class="permalink"><a href="#ga92c1d2c9d63485f3d70f94f688d48672">&#9670;&nbsp;</a></span>GLFW_KEY_CAPS_LOCK</h2> <div class="memitem"> <div class="memproto"> <table class="memname"> <tr> <td class="memname">#define GLFW_KEY_CAPS_LOCK&#160;&#160;&#160;280</td> </tr> </table> </div><div class="memdoc"> </div> </div> <a id="gaf622b63b9537f7084c2ab649b8365630"></a> <h2 class="memtitle"><span class="permalink"><a href="#gaf622b63b9537f7084c2ab649b8365630">&#9670;&nbsp;</a></span>GLFW_KEY_SCROLL_LOCK</h2> <div class="memitem"> <div class="memproto"> <table class="memname"> <tr> <td class="memname">#define GLFW_KEY_SCROLL_LOCK&#160;&#160;&#160;281</td> </tr> </table> </div><div class="memdoc"> </div> </div> <a id="ga3946edc362aeff213b2be6304296cf43"></a> <h2 class="memtitle"><span class="permalink"><a href="#ga3946edc362aeff213b2be6304296cf43">&#9670;&nbsp;</a></span>GLFW_KEY_NUM_LOCK</h2> <div class="memitem"> <div class="memproto"> <table class="memname"> <tr> <td class="memname">#define GLFW_KEY_NUM_LOCK&#160;&#160;&#160;282</td> </tr> </table> </div><div class="memdoc"> </div> </div> <a id="gaf964c2e65e97d0cf785a5636ee8df642"></a> <h2 class="memtitle"><span class="permalink"><a href="#gaf964c2e65e97d0cf785a5636ee8df642">&#9670;&nbsp;</a></span>GLFW_KEY_PRINT_SCREEN</h2> <div class="memitem"> <div class="memproto"> <table class="memname"> <tr> <td class="memname">#define GLFW_KEY_PRINT_SCREEN&#160;&#160;&#160;283</td> </tr> </table> </div><div class="memdoc"> </div> </div> <a id="ga8116b9692d87382afb5849b6d8907f18"></a> <h2 class="memtitle"><span class="permalink"><a href="#ga8116b9692d87382afb5849b6d8907f18">&#9670;&nbsp;</a></span>GLFW_KEY_PAUSE</h2> <div class="memitem"> <div class="memproto"> <table class="memname"> <tr> <td class="memname">#define GLFW_KEY_PAUSE&#160;&#160;&#160;284</td> </tr> </table> </div><div class="memdoc"> </div> </div> <a id="gafb8d66c573acf22e364049477dcbea30"></a> <h2 class="memtitle"><span class="permalink"><a href="#gafb8d66c573acf22e364049477dcbea30">&#9670;&nbsp;</a></span>GLFW_KEY_F1</h2> <div class="memitem"> <div class="memproto"> <table class="memname"> <tr> <td class="memname">#define GLFW_KEY_F1&#160;&#160;&#160;290</td> </tr> </table> </div><div class="memdoc"> </div> </div> <a id="ga0900750aff94889b940f5e428c07daee"></a> <h2 class="memtitle"><span class="permalink"><a href="#ga0900750aff94889b940f5e428c07daee">&#9670;&nbsp;</a></span>GLFW_KEY_F2</h2> <div class="memitem"> <div class="memproto"> <table class="memname"> <tr> <td class="memname">#define GLFW_KEY_F2&#160;&#160;&#160;291</td> </tr> </table> </div><div class="memdoc"> </div> </div> <a id="gaed7cd729c0147a551bb8b7bb36c17015"></a> <h2 class="memtitle"><span class="permalink"><a href="#gaed7cd729c0147a551bb8b7bb36c17015">&#9670;&nbsp;</a></span>GLFW_KEY_F3</h2> <div class="memitem"> <div class="memproto"> <table class="memname"> <tr> <td class="memname">#define GLFW_KEY_F3&#160;&#160;&#160;292</td> </tr> </table> </div><div class="memdoc"> </div> </div> <a id="ga9b61ebd0c63b44b7332fda2c9763eaa6"></a> <h2 class="memtitle"><span class="permalink"><a href="#ga9b61ebd0c63b44b7332fda2c9763eaa6">&#9670;&nbsp;</a></span>GLFW_KEY_F4</h2> <div class="memitem"> <div class="memproto"> <table class="memname"> <tr> <td class="memname">#define GLFW_KEY_F4&#160;&#160;&#160;293</td> </tr> </table> </div><div class="memdoc"> </div> </div> <a id="gaf258dda9947daa428377938ed577c8c2"></a> <h2 class="memtitle"><span class="permalink"><a href="#gaf258dda9947daa428377938ed577c8c2">&#9670;&nbsp;</a></span>GLFW_KEY_F5</h2> <div class="memitem"> <div class="memproto"> <table class="memname"> <tr> <td class="memname">#define GLFW_KEY_F5&#160;&#160;&#160;294</td> </tr> </table> </div><div class="memdoc"> </div> </div> <a id="ga6dc2d3f87b9d51ffbbbe2ef0299d8e1d"></a> <h2 class="memtitle"><span class="permalink"><a href="#ga6dc2d3f87b9d51ffbbbe2ef0299d8e1d">&#9670;&nbsp;</a></span>GLFW_KEY_F6</h2> <div class="memitem"> <div class="memproto"> <table class="memname"> <tr> <td class="memname">#define GLFW_KEY_F6&#160;&#160;&#160;295</td> </tr> </table> </div><div class="memdoc"> </div> </div> <a id="gacca6ef8a2162c52a0ac1d881e8d9c38a"></a> <h2 class="memtitle"><span class="permalink"><a href="#gacca6ef8a2162c52a0ac1d881e8d9c38a">&#9670;&nbsp;</a></span>GLFW_KEY_F7</h2> <div class="memitem"> <div class="memproto"> <table class="memname"> <tr> <td class="memname">#define GLFW_KEY_F7&#160;&#160;&#160;296</td> </tr> </table> </div><div class="memdoc"> </div> </div> <a id="gac9d39390336ae14e4a93e295de43c7e8"></a> <h2 class="memtitle"><span class="permalink"><a href="#gac9d39390336ae14e4a93e295de43c7e8">&#9670;&nbsp;</a></span>GLFW_KEY_F8</h2> <div class="memitem"> <div class="memproto"> <table class="memname"> <tr> <td class="memname">#define GLFW_KEY_F8&#160;&#160;&#160;297</td> </tr> </table> </div><div class="memdoc"> </div> </div> <a id="gae40de0de1c9f21cd26c9afa3d7050851"></a> <h2 class="memtitle"><span class="permalink"><a href="#gae40de0de1c9f21cd26c9afa3d7050851">&#9670;&nbsp;</a></span>GLFW_KEY_F9</h2> <div class="memitem"> <div class="memproto"> <table class="memname"> <tr> <td class="memname">#define GLFW_KEY_F9&#160;&#160;&#160;298</td> </tr> </table> </div><div class="memdoc"> </div> </div> <a id="ga718d11d2f7d57471a2f6a894235995b1"></a> <h2 class="memtitle"><span class="permalink"><a href="#ga718d11d2f7d57471a2f6a894235995b1">&#9670;&nbsp;</a></span>GLFW_KEY_F10</h2> <div class="memitem"> <div class="memproto"> <table class="memname"> <tr> <td class="memname">#define GLFW_KEY_F10&#160;&#160;&#160;299</td> </tr> </table> </div><div class="memdoc"> </div> </div> <a id="ga0bc04b11627e7d69339151e7306b2832"></a> <h2 class="memtitle"><span class="permalink"><a href="#ga0bc04b11627e7d69339151e7306b2832">&#9670;&nbsp;</a></span>GLFW_KEY_F11</h2> <div class="memitem"> <div class="memproto"> <table class="memname"> <tr> <td class="memname">#define GLFW_KEY_F11&#160;&#160;&#160;300</td> </tr> </table> </div><div class="memdoc"> </div> </div> <a id="gaf5908fa9b0a906ae03fc2c61ac7aa3e2"></a> <h2 class="memtitle"><span class="permalink"><a href="#gaf5908fa9b0a906ae03fc2c61ac7aa3e2">&#9670;&nbsp;</a></span>GLFW_KEY_F12</h2> <div class="memitem"> <div class="memproto"> <table class="memname"> <tr> <td class="memname">#define GLFW_KEY_F12&#160;&#160;&#160;301</td> </tr> </table> </div><div class="memdoc"> </div> </div> <a id="gad637f4308655e1001bd6ad942bc0fd4b"></a> <h2 class="memtitle"><span class="permalink"><a href="#gad637f4308655e1001bd6ad942bc0fd4b">&#9670;&nbsp;</a></span>GLFW_KEY_F13</h2> <div class="memitem"> <div class="memproto"> <table class="memname"> <tr> <td class="memname">#define GLFW_KEY_F13&#160;&#160;&#160;302</td> </tr> </table> </div><div class="memdoc"> </div> </div> <a id="gaf14c66cff3396e5bd46e803c035e6c1f"></a> <h2 class="memtitle"><span class="permalink"><a href="#gaf14c66cff3396e5bd46e803c035e6c1f">&#9670;&nbsp;</a></span>GLFW_KEY_F14</h2> <div class="memitem"> <div class="memproto"> <table class="memname"> <tr> <td class="memname">#define GLFW_KEY_F14&#160;&#160;&#160;303</td> </tr> </table> </div><div class="memdoc"> </div> </div> <a id="ga7f70970db6e8be1794da8516a6d14058"></a> <h2 class="memtitle"><span class="permalink"><a href="#ga7f70970db6e8be1794da8516a6d14058">&#9670;&nbsp;</a></span>GLFW_KEY_F15</h2> <div class="memitem"> <div class="memproto"> <table class="memname"> <tr> <td class="memname">#define GLFW_KEY_F15&#160;&#160;&#160;304</td> </tr> </table> </div><div class="memdoc"> </div> </div> <a id="gaa582dbb1d2ba2050aa1dca0838095b27"></a> <h2 class="memtitle"><span class="permalink"><a href="#gaa582dbb1d2ba2050aa1dca0838095b27">&#9670;&nbsp;</a></span>GLFW_KEY_F16</h2> <div class="memitem"> <div class="memproto"> <table class="memname"> <tr> <td class="memname">#define GLFW_KEY_F16&#160;&#160;&#160;305</td> </tr> </table> </div><div class="memdoc"> </div> </div> <a id="ga972ce5c365e2394b36104b0e3125c748"></a> <h2 class="memtitle"><span class="permalink"><a href="#ga972ce5c365e2394b36104b0e3125c748">&#9670;&nbsp;</a></span>GLFW_KEY_F17</h2> <div class="memitem"> <div class="memproto"> <table class="memname"> <tr> <td class="memname">#define GLFW_KEY_F17&#160;&#160;&#160;306</td> </tr> </table> </div><div class="memdoc"> </div> </div> <a id="gaebf6391058d5566601e357edc5ea737c"></a> <h2 class="memtitle"><span class="permalink"><a href="#gaebf6391058d5566601e357edc5ea737c">&#9670;&nbsp;</a></span>GLFW_KEY_F18</h2> <div class="memitem"> <div class="memproto"> <table class="memname"> <tr> <td class="memname">#define GLFW_KEY_F18&#160;&#160;&#160;307</td> </tr> </table> </div><div class="memdoc"> </div> </div> <a id="gaec011d9ba044058cb54529da710e9791"></a> <h2 class="memtitle"><span class="permalink"><a href="#gaec011d9ba044058cb54529da710e9791">&#9670;&nbsp;</a></span>GLFW_KEY_F19</h2> <div class="memitem"> <div class="memproto"> <table class="memname"> <tr> <td class="memname">#define GLFW_KEY_F19&#160;&#160;&#160;308</td> </tr> </table> </div><div class="memdoc"> </div> </div> <a id="ga82b9c721ada04cd5ca8de767da38022f"></a> <h2 class="memtitle"><span class="permalink"><a href="#ga82b9c721ada04cd5ca8de767da38022f">&#9670;&nbsp;</a></span>GLFW_KEY_F20</h2> <div class="memitem"> <div class="memproto"> <table class="memname"> <tr> <td class="memname">#define GLFW_KEY_F20&#160;&#160;&#160;309</td> </tr> </table> </div><div class="memdoc"> </div> </div> <a id="ga356afb14d3440ff2bb378f74f7ebc60f"></a> <h2 class="memtitle"><span class="permalink"><a href="#ga356afb14d3440ff2bb378f74f7ebc60f">&#9670;&nbsp;</a></span>GLFW_KEY_F21</h2> <div class="memitem"> <div class="memproto"> <table class="memname"> <tr> <td class="memname">#define GLFW_KEY_F21&#160;&#160;&#160;310</td> </tr> </table> </div><div class="memdoc"> </div> </div> <a id="ga90960bd2a155f2b09675324d3dff1565"></a> <h2 class="memtitle"><span class="permalink"><a href="#ga90960bd2a155f2b09675324d3dff1565">&#9670;&nbsp;</a></span>GLFW_KEY_F22</h2> <div class="memitem"> <div class="memproto"> <table class="memname"> <tr> <td class="memname">#define GLFW_KEY_F22&#160;&#160;&#160;311</td> </tr> </table> </div><div class="memdoc"> </div> </div> <a id="ga43c21099aac10952d1be909a8ddee4d5"></a> <h2 class="memtitle"><span class="permalink"><a href="#ga43c21099aac10952d1be909a8ddee4d5">&#9670;&nbsp;</a></span>GLFW_KEY_F23</h2> <div class="memitem"> <div class="memproto"> <table class="memname"> <tr> <td class="memname">#define GLFW_KEY_F23&#160;&#160;&#160;312</td> </tr> </table> </div><div class="memdoc"> </div> </div> <a id="ga8150374677b5bed3043408732152dea2"></a> <h2 class="memtitle"><span class="permalink"><a href="#ga8150374677b5bed3043408732152dea2">&#9670;&nbsp;</a></span>GLFW_KEY_F24</h2> <div class="memitem"> <div class="memproto"> <table class="memname"> <tr> <td class="memname">#define GLFW_KEY_F24&#160;&#160;&#160;313</td> </tr> </table> </div><div class="memdoc"> </div> </div> <a id="gaa4bbd93ed73bb4c6ae7d83df880b7199"></a> <h2 class="memtitle"><span class="permalink"><a href="#gaa4bbd93ed73bb4c6ae7d83df880b7199">&#9670;&nbsp;</a></span>GLFW_KEY_F25</h2> <div class="memitem"> <div class="memproto"> <table class="memname"> <tr> <td class="memname">#define GLFW_KEY_F25&#160;&#160;&#160;314</td> </tr> </table> </div><div class="memdoc"> </div> </div> <a id="ga10515dafc55b71e7683f5b4fedd1c70d"></a> <h2 class="memtitle"><span class="permalink"><a href="#ga10515dafc55b71e7683f5b4fedd1c70d">&#9670;&nbsp;</a></span>GLFW_KEY_KP_0</h2> <div class="memitem"> <div class="memproto"> <table class="memname"> <tr> <td class="memname">#define GLFW_KEY_KP_0&#160;&#160;&#160;320</td> </tr> </table> </div><div class="memdoc"> </div> </div> <a id="gaf3a29a334402c5eaf0b3439edf5587c3"></a> <h2 class="memtitle"><span class="permalink"><a href="#gaf3a29a334402c5eaf0b3439edf5587c3">&#9670;&nbsp;</a></span>GLFW_KEY_KP_1</h2> <div class="memitem"> <div class="memproto"> <table class="memname"> <tr> <td class="memname">#define GLFW_KEY_KP_1&#160;&#160;&#160;321</td> </tr> </table> </div><div class="memdoc"> </div> </div> <a id="gaf82d5a802ab8213c72653d7480c16f13"></a> <h2 class="memtitle"><span class="permalink"><a href="#gaf82d5a802ab8213c72653d7480c16f13">&#9670;&nbsp;</a></span>GLFW_KEY_KP_2</h2> <div class="memitem"> <div class="memproto"> <table class="memname"> <tr> <td class="memname">#define GLFW_KEY_KP_2&#160;&#160;&#160;322</td> </tr> </table> </div><div class="memdoc"> </div> </div> <a id="ga7e25ff30d56cd512828c1d4ae8d54ef2"></a> <h2 class="memtitle"><span class="permalink"><a href="#ga7e25ff30d56cd512828c1d4ae8d54ef2">&#9670;&nbsp;</a></span>GLFW_KEY_KP_3</h2> <div class="memitem"> <div class="memproto"> <table class="memname"> <tr> <td class="memname">#define GLFW_KEY_KP_3&#160;&#160;&#160;323</td> </tr> </table> </div><div class="memdoc"> </div> </div> <a id="gada7ec86778b85e0b4de0beea72234aea"></a> <h2 class="memtitle"><span class="permalink"><a href="#gada7ec86778b85e0b4de0beea72234aea">&#9670;&nbsp;</a></span>GLFW_KEY_KP_4</h2> <div class="memitem"> <div class="memproto"> <table class="memname"> <tr> <td class="memname">#define GLFW_KEY_KP_4&#160;&#160;&#160;324</td> </tr> </table> </div><div class="memdoc"> </div> </div> <a id="ga9a5be274434866c51738cafbb6d26b45"></a> <h2 class="memtitle"><span class="permalink"><a href="#ga9a5be274434866c51738cafbb6d26b45">&#9670;&nbsp;</a></span>GLFW_KEY_KP_5</h2> <div class="memitem"> <div class="memproto"> <table class="memname"> <tr> <td class="memname">#define GLFW_KEY_KP_5&#160;&#160;&#160;325</td> </tr> </table> </div><div class="memdoc"> </div> </div> <a id="gafc141b0f8450519084c01092a3157faa"></a> <h2 class="memtitle"><span class="permalink"><a href="#gafc141b0f8450519084c01092a3157faa">&#9670;&nbsp;</a></span>GLFW_KEY_KP_6</h2> <div class="memitem"> <div class="memproto"> <table class="memname"> <tr> <td class="memname">#define GLFW_KEY_KP_6&#160;&#160;&#160;326</td> </tr> </table> </div><div class="memdoc"> </div> </div> <a id="ga8882f411f05d04ec77a9563974bbfa53"></a> <h2 class="memtitle"><span class="permalink"><a href="#ga8882f411f05d04ec77a9563974bbfa53">&#9670;&nbsp;</a></span>GLFW_KEY_KP_7</h2> <div class="memitem"> <div class="memproto"> <table class="memname"> <tr> <td class="memname">#define GLFW_KEY_KP_7&#160;&#160;&#160;327</td> </tr> </table> </div><div class="memdoc"> </div> </div> <a id="gab2ea2e6a12f89d315045af520ac78cec"></a> <h2 class="memtitle"><span class="permalink"><a href="#gab2ea2e6a12f89d315045af520ac78cec">&#9670;&nbsp;</a></span>GLFW_KEY_KP_8</h2> <div class="memitem"> <div class="memproto"> <table class="memname"> <tr> <td class="memname">#define GLFW_KEY_KP_8&#160;&#160;&#160;328</td> </tr> </table> </div><div class="memdoc"> </div> </div> <a id="gafb21426b630ed4fcc084868699ba74c1"></a> <h2 class="memtitle"><span class="permalink"><a href="#gafb21426b630ed4fcc084868699ba74c1">&#9670;&nbsp;</a></span>GLFW_KEY_KP_9</h2> <div class="memitem"> <div class="memproto"> <table class="memname"> <tr> <td class="memname">#define GLFW_KEY_KP_9&#160;&#160;&#160;329</td> </tr> </table> </div><div class="memdoc"> </div> </div> <a id="ga4e231d968796331a9ea0dbfb98d4005b"></a> <h2 class="memtitle"><span class="permalink"><a href="#ga4e231d968796331a9ea0dbfb98d4005b">&#9670;&nbsp;</a></span>GLFW_KEY_KP_DECIMAL</h2> <div class="memitem"> <div class="memproto"> <table class="memname"> <tr> <td class="memname">#define GLFW_KEY_KP_DECIMAL&#160;&#160;&#160;330</td> </tr> </table> </div><div class="memdoc"> </div> </div> <a id="gabca1733780a273d549129ad0f250d1e5"></a> <h2 class="memtitle"><span class="permalink"><a href="#gabca1733780a273d549129ad0f250d1e5">&#9670;&nbsp;</a></span>GLFW_KEY_KP_DIVIDE</h2> <div class="memitem"> <div class="memproto"> <table class="memname"> <tr> <td class="memname">#define GLFW_KEY_KP_DIVIDE&#160;&#160;&#160;331</td> </tr> </table> </div><div class="memdoc"> </div> </div> <a id="ga9ada267eb0e78ed2ada8701dd24a56ef"></a> <h2 class="memtitle"><span class="permalink"><a href="#ga9ada267eb0e78ed2ada8701dd24a56ef">&#9670;&nbsp;</a></span>GLFW_KEY_KP_MULTIPLY</h2> <div class="memitem"> <div class="memproto"> <table class="memname"> <tr> <td class="memname">#define GLFW_KEY_KP_MULTIPLY&#160;&#160;&#160;332</td> </tr> </table> </div><div class="memdoc"> </div> </div> <a id="gaa3dbd60782ff93d6082a124bce1fa236"></a> <h2 class="memtitle"><span class="permalink"><a href="#gaa3dbd60782ff93d6082a124bce1fa236">&#9670;&nbsp;</a></span>GLFW_KEY_KP_SUBTRACT</h2> <div class="memitem"> <div class="memproto"> <table class="memname"> <tr> <td class="memname">#define GLFW_KEY_KP_SUBTRACT&#160;&#160;&#160;333</td> </tr> </table> </div><div class="memdoc"> </div> </div> <a id="gad09c7c98acc79e89aa6a0a91275becac"></a> <h2 class="memtitle"><span class="permalink"><a href="#gad09c7c98acc79e89aa6a0a91275becac">&#9670;&nbsp;</a></span>GLFW_KEY_KP_ADD</h2> <div class="memitem"> <div class="memproto"> <table class="memname"> <tr> <td class="memname">#define GLFW_KEY_KP_ADD&#160;&#160;&#160;334</td> </tr> </table> </div><div class="memdoc"> </div> </div> <a id="ga4f728f8738f2986bd63eedd3d412e8cf"></a> <h2 class="memtitle"><span class="permalink"><a href="#ga4f728f8738f2986bd63eedd3d412e8cf">&#9670;&nbsp;</a></span>GLFW_KEY_KP_ENTER</h2> <div class="memitem"> <div class="memproto"> <table class="memname"> <tr> <td class="memname">#define GLFW_KEY_KP_ENTER&#160;&#160;&#160;335</td> </tr> </table> </div><div class="memdoc"> </div> </div> <a id="gaebdc76d4a808191e6d21b7e4ad2acd97"></a> <h2 class="memtitle"><span class="permalink"><a href="#gaebdc76d4a808191e6d21b7e4ad2acd97">&#9670;&nbsp;</a></span>GLFW_KEY_KP_EQUAL</h2> <div class="memitem"> <div class="memproto"> <table class="memname"> <tr> <td class="memname">#define GLFW_KEY_KP_EQUAL&#160;&#160;&#160;336</td> </tr> </table> </div><div class="memdoc"> </div> </div> <a id="ga8a530a28a65c44ab5d00b759b756d3f6"></a> <h2 class="memtitle"><span class="permalink"><a href="#ga8a530a28a65c44ab5d00b759b756d3f6">&#9670;&nbsp;</a></span>GLFW_KEY_LEFT_SHIFT</h2> <div class="memitem"> <div class="memproto"> <table class="memname"> <tr> <td class="memname">#define GLFW_KEY_LEFT_SHIFT&#160;&#160;&#160;340</td> </tr> </table> </div><div class="memdoc"> </div> </div> <a id="ga9f97b743e81460ac4b2deddecd10a464"></a> <h2 class="memtitle"><span class="permalink"><a href="#ga9f97b743e81460ac4b2deddecd10a464">&#9670;&nbsp;</a></span>GLFW_KEY_LEFT_CONTROL</h2> <div class="memitem"> <div class="memproto"> <table class="memname"> <tr> <td class="memname">#define GLFW_KEY_LEFT_CONTROL&#160;&#160;&#160;341</td> </tr> </table> </div><div class="memdoc"> </div> </div> <a id="ga7f27dabf63a7789daa31e1c96790219b"></a> <h2 class="memtitle"><span class="permalink"><a href="#ga7f27dabf63a7789daa31e1c96790219b">&#9670;&nbsp;</a></span>GLFW_KEY_LEFT_ALT</h2> <div class="memitem"> <div class="memproto"> <table class="memname"> <tr> <td class="memname">#define GLFW_KEY_LEFT_ALT&#160;&#160;&#160;342</td> </tr> </table> </div><div class="memdoc"> </div> </div> <a id="gafb1207c91997fc295afd1835fbc5641a"></a> <h2 class="memtitle"><span class="permalink"><a href="#gafb1207c91997fc295afd1835fbc5641a">&#9670;&nbsp;</a></span>GLFW_KEY_LEFT_SUPER</h2> <div class="memitem"> <div class="memproto"> <table class="memname"> <tr> <td class="memname">#define GLFW_KEY_LEFT_SUPER&#160;&#160;&#160;343</td> </tr> </table> </div><div class="memdoc"> </div> </div> <a id="gaffca36b99c9dce1a19cb9befbadce691"></a> <h2 class="memtitle"><span class="permalink"><a href="#gaffca36b99c9dce1a19cb9befbadce691">&#9670;&nbsp;</a></span>GLFW_KEY_RIGHT_SHIFT</h2> <div class="memitem"> <div class="memproto"> <table class="memname"> <tr> <td class="memname">#define GLFW_KEY_RIGHT_SHIFT&#160;&#160;&#160;344</td> </tr> </table> </div><div class="memdoc"> </div> </div> <a id="gad1ca2094b2694e7251d0ab1fd34f8519"></a> <h2 class="memtitle"><span class="permalink"><a href="#gad1ca2094b2694e7251d0ab1fd34f8519">&#9670;&nbsp;</a></span>GLFW_KEY_RIGHT_CONTROL</h2> <div class="memitem"> <div class="memproto"> <table class="memname"> <tr> <td class="memname">#define GLFW_KEY_RIGHT_CONTROL&#160;&#160;&#160;345</td> </tr> </table> </div><div class="memdoc"> </div> </div> <a id="ga687b38009131cfdd07a8d05fff8fa446"></a> <h2 class="memtitle"><span class="permalink"><a href="#ga687b38009131cfdd07a8d05fff8fa446">&#9670;&nbsp;</a></span>GLFW_KEY_RIGHT_ALT</h2> <div class="memitem"> <div class="memproto"> <table class="memname"> <tr> <td class="memname">#define GLFW_KEY_RIGHT_ALT&#160;&#160;&#160;346</td> </tr> </table> </div><div class="memdoc"> </div> </div> <a id="gad4547a3e8e247594acb60423fe6502db"></a> <h2 class="memtitle"><span class="permalink"><a href="#gad4547a3e8e247594acb60423fe6502db">&#9670;&nbsp;</a></span>GLFW_KEY_RIGHT_SUPER</h2> <div class="memitem"> <div class="memproto"> <table class="memname"> <tr> <td class="memname">#define GLFW_KEY_RIGHT_SUPER&#160;&#160;&#160;347</td> </tr> </table> </div><div class="memdoc"> </div> </div> <a id="ga9845be48a745fc232045c9ec174d8820"></a> <h2 class="memtitle"><span class="permalink"><a href="#ga9845be48a745fc232045c9ec174d8820">&#9670;&nbsp;</a></span>GLFW_KEY_MENU</h2> <div class="memitem"> <div class="memproto"> <table class="memname"> <tr> <td class="memname">#define GLFW_KEY_MENU&#160;&#160;&#160;348</td> </tr> </table> </div><div class="memdoc"> </div> </div> <a id="ga442cbaef7bfb9a4ba13594dd7fbf2789"></a> <h2 class="memtitle"><span class="permalink"><a href="#ga442cbaef7bfb9a4ba13594dd7fbf2789">&#9670;&nbsp;</a></span>GLFW_KEY_LAST</h2> <div class="memitem"> <div class="memproto"> <table class="memname"> <tr> <td class="memname">#define GLFW_KEY_LAST&#160;&#160;&#160;<a class="el" href="group__keys.html#ga9845be48a745fc232045c9ec174d8820">GLFW_KEY_MENU</a></td> </tr> </table> </div><div class="memdoc"> </div> </div> </div><!-- contents --> <address class="footer"> <p> Last update on Mon Jan 20 2020 for GLFW 3.3.2 </p> </address> </body> </html>
tmj-fstate/maszyna
ref/glfw/docs/html/group__keys.html
HTML
mpl-2.0
104,344
#!/usr/bin/env python # This Source Code Form is subject to the terms of the Mozilla Public # License, v. 2.0. If a copy of the MPL was not distributed with this # file, You can obtain one at http://mozilla.org/MPL/2.0/. # Usage: check_source_count.py SEARCH_TERM COUNT ERROR_LOCATION REPLACEMENT [FILES...] # Checks that FILES contains exactly COUNT matches of SEARCH_TERM. If it does # not, an error message is printed, quoting ERROR_LOCATION, which should # probably be the filename and line number of the erroneous call to # check_source_count.py. import sys import os import re search_string = sys.argv[1] expected_count = int(sys.argv[2]) error_location = sys.argv[3] replacement = sys.argv[4] files = sys.argv[5:] details = {} count = 0 for f in files: text = file(f).read() match = re.findall(search_string, text) if match: num = len(match) count += num details[f] = num if count == expected_count: print "TEST-PASS | check_source_count.py %s | %d" % (search_string, expected_count) else: print "TEST-UNEXPECTED-FAIL | check_source_count.py %s | " % (search_string), if count < expected_count: print "There are fewer occurrences of /%s/ than expected. This may mean that you have removed some, but forgotten to account for it %s." % (search_string, error_location) else: print "There are more occurrences of /%s/ than expected. We're trying to prevent an increase in the number of %s's, using %s if possible. If it in unavoidable, you should update the expected count %s." % (search_string, search_string, replacement, error_location) print "Expected: %d; found: %d" % (expected_count, count) for k in sorted(details): print "Found %d occurences in %s" % (details[k],k) sys.exit(-1)
cledoux/cmps530
js/src/config/check_source_count.py
Python
mpl-2.0
1,797
<script> var a = document.createElementNS("http://www.w3.org/1999/xhtml", "audio"); a.mozPreservesPitch = a; </script>
Yukarumya/Yukarum-Redfoxes
dom/media/test/crashtests/844563.html
HTML
mpl-2.0
120
/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ // This file is a Mako template: http://www.makotemplates.org/ use std::ascii::AsciiExt; use std::collections::HashSet; use std::default::Default; use std::fmt; use std::fmt::Debug; use std::hash::{Hash, Hasher}; use std::intrinsics; use std::mem; use std::sync::Arc; use cssparser::{Parser, Color, RGBA, AtRuleParser, DeclarationParser, DeclarationListParser, parse_important, ToCss, TokenSerializationType}; use url::Url; use util::geometry::Au; use util::logical_geometry::{LogicalMargin, PhysicalSide, WritingMode}; use euclid::SideOffsets2D; use euclid::size::Size2D; use fnv::FnvHasher; use string_cache::Atom; use computed_values; use parser::{ParserContext, log_css_error}; use selectors::matching::DeclarationBlock; use stylesheets::Origin; use values::computed::{self, ToComputedValue}; use values::specified::{Length, BorderStyle}; use self::property_bit_field::PropertyBitField; <%! import re def to_rust_ident(name): name = name.replace("-", "_") if name in ["static", "super", "box", "move"]: # Rust keywords name += "_" return name def to_camel_case(ident): return re.sub("_([a-z])", lambda m: m.group(1).upper(), ident.strip("_").capitalize()) class Longhand(object): def __init__(self, name, derived_from=None, custom_cascade=False, experimental=False): self.name = name self.ident = to_rust_ident(name) self.camel_case = to_camel_case(self.ident) self.style_struct = THIS_STYLE_STRUCT self.experimental = ("layout.%s.enabled" % name) if experimental else None self.custom_cascade = custom_cascade if derived_from is None: self.derived_from = None else: self.derived_from = [ to_rust_ident(name) for name in derived_from ] class Shorthand(object): def __init__(self, name, sub_properties, experimental=False): self.name = name self.ident = to_rust_ident(name) self.camel_case = to_camel_case(self.ident) self.derived_from = None self.experimental = ("layout.%s.enabled" % name) if experimental else None self.sub_properties = [LONGHANDS_BY_NAME[s] for s in sub_properties] class StyleStruct(object): def __init__(self, name, inherited): self.name = name self.ident = to_rust_ident(name.lower()) self.longhands = [] self.inherited = inherited STYLE_STRUCTS = [] THIS_STYLE_STRUCT = None LONGHANDS = [] LONGHANDS_BY_NAME = {} DERIVED_LONGHANDS = {} SHORTHANDS = [] def new_style_struct(name, is_inherited): global THIS_STYLE_STRUCT style_struct = StyleStruct(name, is_inherited) STYLE_STRUCTS.append(style_struct) THIS_STYLE_STRUCT = style_struct return "" def switch_to_style_struct(name): global THIS_STYLE_STRUCT for style_struct in STYLE_STRUCTS: if style_struct.name == name: THIS_STYLE_STRUCT = style_struct return "" fail() %> pub mod longhands { use cssparser::Parser; use parser::ParserContext; use values::specified; <%def name="raw_longhand(name, derived_from=None, custom_cascade=False, experimental=False)"> <% if derived_from is not None: derived_from = derived_from.split() property = Longhand(name, derived_from=derived_from, custom_cascade=custom_cascade, experimental=experimental) property.style_struct = THIS_STYLE_STRUCT THIS_STYLE_STRUCT.longhands.append(property) LONGHANDS.append(property) LONGHANDS_BY_NAME[name] = property if derived_from is not None: for name in derived_from: DERIVED_LONGHANDS.setdefault(name, []).append(property) %> pub mod ${property.ident} { #![allow(unused_imports)] % if derived_from is None: use cssparser::Parser; use parser::ParserContext; use properties::{CSSWideKeyword, DeclaredValue, Shorthand}; % endif use properties::longhands; use properties::property_bit_field::PropertyBitField; use properties::{ComputedValues, PropertyDeclaration}; use std::collections::HashMap; use std::sync::Arc; use values::computed::ToComputedValue; use values::{computed, specified}; use string_cache::Atom; ${caller.body()} #[allow(unused_variables)] pub fn cascade_property(declaration: &PropertyDeclaration, style: &mut ComputedValues, inherited_style: &ComputedValues, context: &computed::Context, seen: &mut PropertyBitField, cacheable: &mut bool) { let declared_value = match *declaration { PropertyDeclaration::${property.camel_case}(ref declared_value) => { declared_value } _ => panic!("entered the wrong cascade_property() implementation"), }; % if property.derived_from is None: if seen.get_${property.ident}() { return } seen.set_${property.ident}(); let computed_value = ::properties::substitute_variables_${property.ident}( declared_value, &style.custom_properties, |value| match *value { DeclaredValue::Value(ref specified_value) => { specified_value.to_computed_value(&context) } DeclaredValue::WithVariables { .. } => unreachable!(), DeclaredValue::Initial => get_initial_value(), DeclaredValue::Inherit => { // This is a bit slow, but this is rare so it shouldn't // matter. // // FIXME: is it still? *cacheable = false; inherited_style.${THIS_STYLE_STRUCT.ident} .${property.ident} .clone() } } ); Arc::make_mut(&mut style.${THIS_STYLE_STRUCT.ident}).${property.ident} = computed_value; % if custom_cascade: cascade_property_custom(&computed_value, declaration, style, inherited_style, context, seen, cacheable); % endif % else: // Do not allow stylesheets to set derived properties. % endif } % if derived_from is None: pub fn parse_declared(context: &ParserContext, input: &mut Parser) -> Result<DeclaredValue<SpecifiedValue>, ()> { match input.try(CSSWideKeyword::parse) { Ok(CSSWideKeyword::InheritKeyword) => Ok(DeclaredValue::Inherit), Ok(CSSWideKeyword::InitialKeyword) => Ok(DeclaredValue::Initial), Ok(CSSWideKeyword::UnsetKeyword) => Ok(DeclaredValue::${ "Inherit" if THIS_STYLE_STRUCT.inherited else "Initial"}), Err(()) => { input.look_for_var_functions(); let start = input.position(); let specified = parse_specified(context, input); if specified.is_err() { while let Ok(_) = input.next() {} // Look for var() after the error. } let var = input.seen_var_functions(); if specified.is_err() && var { input.reset(start); let (first_token_type, _) = try!( ::custom_properties::parse_declaration_value(input, &mut None)); return Ok(DeclaredValue::WithVariables { css: input.slice_from(start).to_owned(), first_token_type: first_token_type, base_url: context.base_url.clone(), from_shorthand: Shorthand::None, }) } specified } } } % endif } </%def> <%def name="longhand(name, derived_from=None, custom_cascade=False, experimental=False)"> <%self:raw_longhand name="${name}" derived_from="${derived_from}" custom_cascade="${custom_cascade}" experimental="${experimental}"> ${caller.body()} % if derived_from is None: pub fn parse_specified(context: &ParserContext, input: &mut Parser) -> Result<DeclaredValue<SpecifiedValue>, ()> { parse(context, input).map(DeclaredValue::Value) } % endif </%self:raw_longhand> </%def> <%def name="single_keyword_computed(name, values, custom_cascade=False, experimental=False)"> <%self:longhand name="${name}" custom_cascade="${custom_cascade}" experimental="${experimental}"> pub use self::computed_value::T as SpecifiedValue; ${caller.body()} pub mod computed_value { define_css_keyword_enum! { T: % for value in values.split(): "${value}" => ${to_rust_ident(value)}, % endfor } } #[inline] pub fn get_initial_value() -> computed_value::T { computed_value::T::${to_rust_ident(values.split()[0])} } pub fn parse(_context: &ParserContext, input: &mut Parser) -> Result<SpecifiedValue, ()> { computed_value::T::parse(input) } </%self:longhand> </%def> <%def name="single_keyword(name, values, experimental=False)"> <%self:single_keyword_computed name="${name}" values="${values}" experimental="${experimental}"> use values::computed::ComputedValueAsSpecified; impl ComputedValueAsSpecified for SpecifiedValue {} </%self:single_keyword_computed> </%def> <%def name="predefined_type(name, type, initial_value, parse_method='parse')"> <%self:longhand name="${name}"> #[allow(unused_imports)] use util::geometry::Au; pub type SpecifiedValue = specified::${type}; pub mod computed_value { pub use values::computed::${type} as T; } #[inline] pub fn get_initial_value() -> computed_value::T { ${initial_value} } #[inline] pub fn parse(_context: &ParserContext, input: &mut Parser) -> Result<SpecifiedValue, ()> { specified::${type}::${parse_method}(input) } </%self:longhand> </%def> // CSS 2.1, Section 8 - Box model ${new_style_struct("Margin", is_inherited=False)} % for side in ["top", "right", "bottom", "left"]: ${predefined_type("margin-" + side, "LengthOrPercentageOrAuto", "computed::LengthOrPercentageOrAuto::Length(Au(0))")} % endfor ${new_style_struct("Padding", is_inherited=False)} % for side in ["top", "right", "bottom", "left"]: ${predefined_type("padding-" + side, "LengthOrPercentage", "computed::LengthOrPercentage::Length(Au(0))", "parse_non_negative")} % endfor ${new_style_struct("Border", is_inherited=False)} % for side in ["top", "right", "bottom", "left"]: ${predefined_type("border-%s-color" % side, "CSSColor", "::cssparser::Color::CurrentColor")} % endfor % for side in ["top", "right", "bottom", "left"]: ${predefined_type("border-%s-style" % side, "BorderStyle", "specified::BorderStyle::none")} % endfor % for side in ["top", "right", "bottom", "left"]: <%self:longhand name="border-${side}-width"> use cssparser::ToCss; use std::fmt; use util::geometry::Au; use values::computed::Context; impl ToCss for SpecifiedValue { fn to_css<W>(&self, dest: &mut W) -> fmt::Result where W: fmt::Write { self.0.to_css(dest) } } #[inline] pub fn parse(_context: &ParserContext, input: &mut Parser) -> Result<SpecifiedValue, ()> { specified::parse_border_width(input).map(SpecifiedValue) } #[derive(Clone, PartialEq)] pub struct SpecifiedValue(pub specified::Length); pub mod computed_value { use util::geometry::Au; pub type T = Au; } #[inline] pub fn get_initial_value() -> computed_value::T { Au::from_px(3) // medium } impl ToComputedValue for SpecifiedValue { type ComputedValue = computed_value::T; #[inline] fn to_computed_value(&self, context: &Context) -> computed_value::T { if !context.border_${side}_present { Au(0) } else { self.0.to_computed_value(context) } } } </%self:longhand> % endfor // FIXME(#4126): when gfx supports painting it, make this Size2D<LengthOrPercentage> % for corner in ["top-left", "top-right", "bottom-right", "bottom-left"]: ${predefined_type("border-" + corner + "-radius", "BorderRadiusSize", "computed::BorderRadiusSize::zero()", "parse")} % endfor ${new_style_struct("Outline", is_inherited=False)} // TODO(pcwalton): `invert` ${predefined_type("outline-color", "CSSColor", "::cssparser::Color::CurrentColor")} <%self:longhand name="outline-style"> pub use values::specified::BorderStyle as SpecifiedValue; pub fn get_initial_value() -> SpecifiedValue { SpecifiedValue::none } pub mod computed_value { pub use values::specified::BorderStyle as T; } pub fn parse(_context: &ParserContext, input: &mut Parser) -> Result<SpecifiedValue, ()> { match SpecifiedValue::parse(input) { Ok(SpecifiedValue::hidden) => Err(()), result => result } } </%self:longhand> <%self:longhand name="outline-width"> use cssparser::ToCss; use std::fmt; use util::geometry::Au; use values::computed::Context; impl ToCss for SpecifiedValue { fn to_css<W>(&self, dest: &mut W) -> fmt::Result where W: fmt::Write { self.0.to_css(dest) } } pub fn parse(_context: &ParserContext, input: &mut Parser) -> Result<SpecifiedValue, ()> { specified::parse_border_width(input).map(SpecifiedValue) } #[derive(Clone, PartialEq)] pub struct SpecifiedValue(pub specified::Length); pub mod computed_value { use util::geometry::Au; pub type T = Au; } pub use super::border_top_width::get_initial_value; impl ToComputedValue for SpecifiedValue { type ComputedValue = computed_value::T; #[inline] fn to_computed_value(&self, context: &Context) -> computed_value::T { if !context.outline_style_present { Au(0) } else { self.0.to_computed_value(context) } } } </%self:longhand> ${predefined_type("outline-offset", "Length", "Au(0)")} ${new_style_struct("PositionOffsets", is_inherited=False)} % for side in ["top", "right", "bottom", "left"]: ${predefined_type(side, "LengthOrPercentageOrAuto", "computed::LengthOrPercentageOrAuto::Auto")} % endfor // CSS 2.1, Section 9 - Visual formatting model ${new_style_struct("Box", is_inherited=False)} // TODO(SimonSapin): don't parse `inline-table`, since we don't support it <%self:longhand name="display" custom_cascade="True"> <% values = """inline block inline-block table inline-table table-row-group table-header-group table-footer-group table-row table-column-group table-column table-cell table-caption list-item flex none """.split() experimental_values = set("flex".split()) %> pub use self::computed_value::T as SpecifiedValue; use values::computed::Context; pub mod computed_value { #[allow(non_camel_case_types)] #[derive(Clone, Eq, PartialEq, Copy, Hash, RustcEncodable, Debug, HeapSizeOf)] #[derive(Deserialize, Serialize)] pub enum T { % for value in values: ${to_rust_ident(value)}, % endfor } impl ::cssparser::ToCss for T { fn to_css<W>(&self, dest: &mut W) -> ::std::fmt::Result where W: ::std::fmt::Write { match *self { % for value in values: T::${to_rust_ident(value)} => dest.write_str("${value}"), % endfor } } } } #[inline] pub fn get_initial_value() -> computed_value::T { computed_value::T::${to_rust_ident(values[0])} } pub fn parse(_context: &ParserContext, input: &mut Parser) -> Result<SpecifiedValue, ()> { match_ignore_ascii_case! { try!(input.expect_ident()), % for value in values[:-1]: "${value}" => { % if value in experimental_values: if !::util::prefs::get_pref("layout.${value}.enabled").unwrap_or(false) { return Err(()) } % endif Ok(computed_value::T::${to_rust_ident(value)}) }, % endfor % for value in values[-1:]: "${value}" => { % if value in experimental_values: if !::util::prefs::get_pref("layout.${value}.enabled".unwrap_or(false) { return Err(()) } % endif Ok(computed_value::T::${to_rust_ident(value)}) } % endfor _ => Err(()) } } impl ToComputedValue for SpecifiedValue { type ComputedValue = computed_value::T; #[inline] fn to_computed_value(&self, context: &Context) -> computed_value::T { use self::computed_value::T; // if context.is_root_element && value == list_item { // return block // } if context.positioned || context.floated || context.is_root_element { match *self { T::inline_table => T::table, T::inline | T::inline_block | T::table_row_group | T::table_column | T::table_column_group | T::table_header_group | T::table_footer_group | T::table_row | T::table_cell | T::table_caption => T::block, _ => *self, } } else { *self } } } fn cascade_property_custom(computed_value: &computed_value::T, _declaration: &PropertyDeclaration, style: &mut ComputedValues, _inherited_style: &ComputedValues, context: &computed::Context, _seen: &mut PropertyBitField, _cacheable: &mut bool) { Arc::make_mut(&mut style.box_)._servo_display_for_hypothetical_box = longhands::_servo_display_for_hypothetical_box::derive_from_display( *computed_value, &context); Arc::make_mut(&mut style.inheritedtext)._servo_text_decorations_in_effect = longhands::_servo_text_decorations_in_effect::derive_from_display(*computed_value, &context); } </%self:longhand> ${single_keyword("position", "static absolute relative fixed")} ${single_keyword("float", "none left right")} ${single_keyword("clear", "none left right both")} <%self:longhand name="-servo-display-for-hypothetical-box" derived_from="display"> pub use super::display::{SpecifiedValue, get_initial_value}; pub use super::display::{parse}; pub mod computed_value { pub type T = super::SpecifiedValue; } #[inline] pub fn derive_from_display(_: super::display::computed_value::T, context: &computed::Context) -> computed_value::T { context.display } </%self:longhand> <%self:longhand name="z-index"> use values::computed::ComputedValueAsSpecified; impl ComputedValueAsSpecified for SpecifiedValue {} pub type SpecifiedValue = computed_value::T; pub mod computed_value { use cssparser::ToCss; use std::fmt; #[derive(PartialEq, Clone, Eq, Copy, Debug, HeapSizeOf)] pub enum T { Auto, Number(i32), } impl ToCss for T { fn to_css<W>(&self, dest: &mut W) -> fmt::Result where W: fmt::Write { match *self { T::Auto => dest.write_str("auto"), T::Number(number) => write!(dest, "{}", number), } } } impl T { pub fn number_or_zero(self) -> i32 { match self { T::Auto => 0, T::Number(value) => value, } } } } #[inline] pub fn get_initial_value() -> computed_value::T { computed_value::T::Auto } fn parse(_context: &ParserContext, input: &mut Parser) -> Result<SpecifiedValue, ()> { if input.try(|input| input.expect_ident_matching("auto")).is_ok() { Ok(computed_value::T::Auto) } else { Ok(computed_value::T::Number(try!(input.expect_integer()) as i32)) } } </%self:longhand> ${new_style_struct("InheritedBox", is_inherited=True)} ${single_keyword("direction", "ltr rtl")} // CSS 2.1, Section 10 - Visual formatting model details ${switch_to_style_struct("Box")} ${predefined_type("width", "LengthOrPercentageOrAuto", "computed::LengthOrPercentageOrAuto::Auto", "parse_non_negative")} ${predefined_type("height", "LengthOrPercentageOrAuto", "computed::LengthOrPercentageOrAuto::Auto", "parse_non_negative")} ${predefined_type("min-width", "LengthOrPercentage", "computed::LengthOrPercentage::Length(Au(0))", "parse_non_negative")} ${predefined_type("max-width", "LengthOrPercentageOrNone", "computed::LengthOrPercentageOrNone::None", "parse_non_negative")} ${predefined_type("min-height", "LengthOrPercentage", "computed::LengthOrPercentage::Length(Au(0))", "parse_non_negative")} ${predefined_type("max-height", "LengthOrPercentageOrNone", "computed::LengthOrPercentageOrNone::None", "parse_non_negative")} ${switch_to_style_struct("InheritedBox")} <%self:longhand name="line-height"> use cssparser::ToCss; use std::fmt; use values::CSSFloat; use values::computed::Context; #[derive(Clone, PartialEq, Copy)] pub enum SpecifiedValue { Normal, Length(specified::Length), Number(CSSFloat), Percentage(CSSFloat), } impl ToCss for SpecifiedValue { fn to_css<W>(&self, dest: &mut W) -> fmt::Result where W: fmt::Write { match *self { SpecifiedValue::Normal => dest.write_str("normal"), SpecifiedValue::Length(length) => length.to_css(dest), SpecifiedValue::Number(number) => write!(dest, "{}", number), SpecifiedValue::Percentage(number) => write!(dest, "{}%", number * 100.), } } } /// normal | <number> | <length> | <percentage> pub fn parse(_context: &ParserContext, input: &mut Parser) -> Result<SpecifiedValue, ()> { use cssparser::Token; use std::ascii::AsciiExt; match try!(input.next()) { Token::Number(ref value) if value.value >= 0. => { Ok(SpecifiedValue::Number(value.value)) } Token::Percentage(ref value) if value.unit_value >= 0. => { Ok(SpecifiedValue::Percentage(value.unit_value)) } Token::Dimension(ref value, ref unit) if value.value >= 0. => { specified::Length::parse_dimension(value.value, unit) .map(SpecifiedValue::Length) } Token::Ident(ref value) if value.eq_ignore_ascii_case("normal") => { Ok(SpecifiedValue::Normal) } _ => Err(()), } } pub mod computed_value { use std::fmt; use util::geometry::Au; use values::CSSFloat; #[derive(PartialEq, Copy, Clone, HeapSizeOf)] pub enum T { Normal, Length(Au), Number(CSSFloat), } impl fmt::Debug for T { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { match *self { T::Normal => write!(f, "normal"), T::Length(length) => write!(f, "{:?}%", length), T::Number(number) => write!(f, "{}", number), } } } } impl ToCss for computed_value::T { fn to_css<W>(&self, dest: &mut W) -> fmt::Result where W: fmt::Write { match *self { computed_value::T::Normal => dest.write_str("normal"), computed_value::T::Length(length) => length.to_css(dest), computed_value::T::Number(number) => write!(dest, "{}", number), } } } #[inline] pub fn get_initial_value() -> computed_value::T { computed_value::T::Normal } impl ToComputedValue for SpecifiedValue { type ComputedValue = computed_value::T; #[inline] fn to_computed_value(&self, context: &Context) -> computed_value::T { match *self { SpecifiedValue::Normal => computed_value::T::Normal, SpecifiedValue::Length(value) => { computed_value::T::Length(value.to_computed_value(context)) } SpecifiedValue::Number(value) => computed_value::T::Number(value), SpecifiedValue::Percentage(value) => { let fr = specified::Length::FontRelative(specified::FontRelativeLength::Em(value)); computed_value::T::Length(fr.to_computed_value(context)) } } } } </%self:longhand> ${switch_to_style_struct("Box")} <%self:longhand name="vertical-align"> use cssparser::ToCss; use std::fmt; use values::computed::Context; <% vertical_align_keywords = ( "baseline sub super top text-top middle bottom text-bottom".split()) %> #[allow(non_camel_case_types)] #[derive(Clone, PartialEq, Copy)] pub enum SpecifiedValue { % for keyword in vertical_align_keywords: ${to_rust_ident(keyword)}, % endfor LengthOrPercentage(specified::LengthOrPercentage), } impl ToCss for SpecifiedValue { fn to_css<W>(&self, dest: &mut W) -> fmt::Result where W: fmt::Write { match *self { % for keyword in vertical_align_keywords: SpecifiedValue::${to_rust_ident(keyword)} => dest.write_str("${keyword}"), % endfor SpecifiedValue::LengthOrPercentage(value) => value.to_css(dest), } } } /// baseline | sub | super | top | text-top | middle | bottom | text-bottom /// | <percentage> | <length> pub fn parse(_context: &ParserContext, input: &mut Parser) -> Result<SpecifiedValue, ()> { input.try(specified::LengthOrPercentage::parse) .map(SpecifiedValue::LengthOrPercentage) .or_else(|()| { match_ignore_ascii_case! { try!(input.expect_ident()), % for keyword in vertical_align_keywords[:-1]: "${keyword}" => Ok(SpecifiedValue::${to_rust_ident(keyword)}), % endfor // Hack to work around quirks of macro_rules parsing in match_ignore_ascii_case! % for keyword in vertical_align_keywords[-1:]: "${keyword}" => Ok(SpecifiedValue::${to_rust_ident(keyword)}) % endfor _ => Err(()) } }) } pub mod computed_value { use std::fmt; use util::geometry::Au; use values::{CSSFloat, computed}; #[allow(non_camel_case_types)] #[derive(PartialEq, Copy, Clone, HeapSizeOf)] pub enum T { % for keyword in vertical_align_keywords: ${to_rust_ident(keyword)}, % endfor Length(Au), Percentage(CSSFloat), Calc(computed::Calc), } impl fmt::Debug for T { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { match *self { % for keyword in vertical_align_keywords: T::${to_rust_ident(keyword)} => write!(f, "${keyword}"), % endfor T::Length(length) => write!(f, "{:?}", length), T::Percentage(number) => write!(f, "{}%", number), T::Calc(calc) => write!(f, "{:?}", calc) } } } impl ::cssparser::ToCss for T { fn to_css<W>(&self, dest: &mut W) -> fmt::Result where W: fmt::Write { match *self { % for keyword in vertical_align_keywords: T::${to_rust_ident(keyword)} => dest.write_str("${keyword}"), % endfor T::Length(value) => value.to_css(dest), T::Percentage(percentage) => write!(dest, "{}%", percentage * 100.), T::Calc(calc) => calc.to_css(dest), } } } } #[inline] pub fn get_initial_value() -> computed_value::T { computed_value::T::baseline } impl ToComputedValue for SpecifiedValue { type ComputedValue = computed_value::T; #[inline] fn to_computed_value(&self, context: &Context) -> computed_value::T { match *self { % for keyword in vertical_align_keywords: SpecifiedValue::${to_rust_ident(keyword)} => { computed_value::T::${to_rust_ident(keyword)} } % endfor SpecifiedValue::LengthOrPercentage(value) => { match value.to_computed_value(context) { computed::LengthOrPercentage::Length(value) => computed_value::T::Length(value), computed::LengthOrPercentage::Percentage(value) => computed_value::T::Percentage(value), computed::LengthOrPercentage::Calc(value) => computed_value::T::Calc(value), } } } } } </%self:longhand> // CSS 2.1, Section 11 - Visual effects // FIXME(pcwalton, #2742): Implement scrolling for `scroll` and `auto`. <%self:single_keyword_computed name="overflow-x" values="visible hidden scroll auto"> use values::computed::Context; pub fn compute_with_other_overflow_direction(value: SpecifiedValue, other_direction: SpecifiedValue) -> computed_value::T { // CSS-OVERFLOW 3 states "Otherwise, if one cascaded values is one of the scrolling // values and the other is `visible`, then computed values are the cascaded values with // `visible` changed to `auto`." match (value, other_direction) { (SpecifiedValue::visible, SpecifiedValue::hidden) | (SpecifiedValue::visible, SpecifiedValue::scroll) | (SpecifiedValue::visible, SpecifiedValue::auto) => computed_value::T::auto, _ => value, } } impl ToComputedValue for SpecifiedValue { type ComputedValue = computed_value::T; #[inline] fn to_computed_value(&self, context: &Context) -> computed_value::T { compute_with_other_overflow_direction(*self, context.overflow_y.0) } } </%self:single_keyword_computed> // FIXME(pcwalton, #2742): Implement scrolling for `scroll` and `auto`. <%self:longhand name="overflow-y"> use super::overflow_x; use values::computed::Context; use cssparser::ToCss; use std::fmt; pub use self::computed_value::T as SpecifiedValue; impl ToCss for SpecifiedValue { fn to_css<W>(&self, dest: &mut W) -> fmt::Result where W: fmt::Write { self.0.to_css(dest) } } pub mod computed_value { #[derive(Clone, Copy, PartialEq, HeapSizeOf)] pub struct T(pub super::super::overflow_x::computed_value::T); } impl ToComputedValue for SpecifiedValue { type ComputedValue = computed_value::T; #[inline] fn to_computed_value(&self, context: &Context) -> computed_value::T { let computed_value::T(this) = *self; computed_value::T(overflow_x::compute_with_other_overflow_direction( this, context.overflow_x)) } } pub fn get_initial_value() -> computed_value::T { computed_value::T(overflow_x::get_initial_value()) } pub fn parse(context: &ParserContext, input: &mut Parser) -> Result<SpecifiedValue,()> { overflow_x::parse(context, input).map(SpecifiedValue) } </%self:longhand> ${switch_to_style_struct("InheritedBox")} // TODO: collapse. Well, do tables first. ${single_keyword("visibility", "visible hidden")} // CSS 2.1, Section 12 - Generated content, automatic numbering, and lists ${switch_to_style_struct("Box")} <%self:longhand name="content"> use cssparser::Token; use std::ascii::AsciiExt; use values::computed::ComputedValueAsSpecified; use super::list_style_type; pub use self::computed_value::T as SpecifiedValue; pub use self::computed_value::ContentItem; impl ComputedValueAsSpecified for SpecifiedValue {} pub mod computed_value { use super::super::list_style_type; use cssparser::{self, ToCss}; use std::fmt; #[derive(PartialEq, Eq, Clone, HeapSizeOf)] pub enum ContentItem { /// Literal string content. String(String), /// `counter(name, style)`. Counter(String, list_style_type::computed_value::T), /// `counters(name, separator, style)`. Counters(String, String, list_style_type::computed_value::T), /// `open-quote`. OpenQuote, /// `close-quote`. CloseQuote, /// `no-open-quote`. NoOpenQuote, /// `no-close-quote`. NoCloseQuote, } impl ToCss for ContentItem { fn to_css<W>(&self, dest: &mut W) -> fmt::Result where W: fmt::Write { match *self { ContentItem::String(ref s) => { cssparser::serialize_string(&**s, dest) } ContentItem::Counter(ref s, ref list_style_type) => { try!(dest.write_str("counter(")); try!(cssparser::serialize_identifier(&**s, dest)); try!(dest.write_str(", ")); try!(list_style_type.to_css(dest)); dest.write_str(")") } ContentItem::Counters(ref s, ref separator, ref list_style_type) => { try!(dest.write_str("counter(")); try!(cssparser::serialize_identifier(&**s, dest)); try!(dest.write_str(", ")); try!(cssparser::serialize_string(&**separator, dest)); try!(dest.write_str(", ")); try!(list_style_type.to_css(dest)); dest.write_str(")") } ContentItem::OpenQuote => dest.write_str("open-quote"), ContentItem::CloseQuote => dest.write_str("close-quote"), ContentItem::NoOpenQuote => dest.write_str("no-open-quote"), ContentItem::NoCloseQuote => dest.write_str("no-close-quote"), } } } #[allow(non_camel_case_types)] #[derive(PartialEq, Eq, Clone, HeapSizeOf)] pub enum T { normal, none, Content(Vec<ContentItem>), } impl ToCss for T { fn to_css<W>(&self, dest: &mut W) -> fmt::Result where W: fmt::Write { match *self { T::normal => dest.write_str("normal"), T::none => dest.write_str("none"), T::Content(ref content) => { let mut iter = content.iter(); try!(iter.next().unwrap().to_css(dest)); for c in iter { try!(dest.write_str(" ")); try!(c.to_css(dest)); } Ok(()) } } } } } #[inline] pub fn get_initial_value() -> computed_value::T { computed_value::T::normal } pub fn counter_name_is_illegal(name: &str) -> bool { name.eq_ignore_ascii_case("none") || name.eq_ignore_ascii_case("inherit") || name.eq_ignore_ascii_case("initial") } // normal | none | [ <string> | <counter> | open-quote | close-quote | no-open-quote | // no-close-quote ]+ // TODO: <uri>, attr(<identifier>) pub fn parse(context: &ParserContext, input: &mut Parser) -> Result<SpecifiedValue, ()> { if input.try(|input| input.expect_ident_matching("normal")).is_ok() { return Ok(SpecifiedValue::normal) } if input.try(|input| input.expect_ident_matching("none")).is_ok() { return Ok(SpecifiedValue::none) } let mut content = vec![]; loop { match input.next() { Ok(Token::QuotedString(value)) => { content.push(ContentItem::String(value.into_owned())) } Ok(Token::Function(name)) => { content.push(try!(match_ignore_ascii_case! { name, "counter" => input.parse_nested_block(|input| { let name = try!(input.expect_ident()).into_owned(); let style = input.try(|input| { try!(input.expect_comma()); list_style_type::parse(context, input) }).unwrap_or(list_style_type::computed_value::T::decimal); Ok(ContentItem::Counter(name, style)) }), "counters" => input.parse_nested_block(|input| { let name = try!(input.expect_ident()).into_owned(); try!(input.expect_comma()); let separator = try!(input.expect_string()).into_owned(); let style = input.try(|input| { try!(input.expect_comma()); list_style_type::parse(context, input) }).unwrap_or(list_style_type::computed_value::T::decimal); Ok(ContentItem::Counters(name, separator, style)) }) _ => return Err(()) })); } Ok(Token::Ident(ident)) => { match_ignore_ascii_case! { ident, "open-quote" => content.push(ContentItem::OpenQuote), "close-quote" => content.push(ContentItem::CloseQuote), "no-open-quote" => content.push(ContentItem::NoOpenQuote), "no-close-quote" => content.push(ContentItem::NoCloseQuote) _ => return Err(()) } } Err(_) => break, _ => return Err(()) } } if !content.is_empty() { Ok(SpecifiedValue::Content(content)) } else { Err(()) } } </%self:longhand> ${new_style_struct("List", is_inherited=True)} ${single_keyword("list-style-position", "outside inside")} // TODO(pcwalton): Implement the full set of counter styles per CSS-COUNTER-STYLES [1] 6.1: // // decimal-leading-zero, armenian, upper-armenian, lower-armenian, georgian, lower-roman, // upper-roman // // [1]: http://dev.w3.org/csswg/css-counter-styles/ ${single_keyword("list-style-type", """ disc none circle square decimal arabic-indic bengali cambodian cjk-decimal devanagari gujarati gurmukhi kannada khmer lao malayalam mongolian myanmar oriya persian telugu thai tibetan lower-alpha upper-alpha cjk-earthly-branch cjk-heavenly-stem lower-greek hiragana hiragana-iroha katakana katakana-iroha disclosure-open disclosure-closed """)} <%self:longhand name="list-style-image"> use cssparser::{ToCss, Token}; use std::fmt; use url::Url; use values::computed::Context; #[derive(Clone, PartialEq, Eq)] pub enum SpecifiedValue { None, Url(Url), } impl ToCss for SpecifiedValue { fn to_css<W>(&self, dest: &mut W) -> fmt::Result where W: fmt::Write { match *self { SpecifiedValue::None => dest.write_str("none"), SpecifiedValue::Url(ref url) => { Token::Url(url.to_string().into()).to_css(dest) } } } } pub mod computed_value { use cssparser::{ToCss, Token}; use std::fmt; use url::Url; #[derive(Clone, PartialEq, HeapSizeOf)] pub struct T(pub Option<Url>); impl ToCss for T { fn to_css<W>(&self, dest: &mut W) -> fmt::Result where W: fmt::Write { match self.0 { None => dest.write_str("none"), Some(ref url) => Token::Url(url.to_string().into()).to_css(dest) } } } } impl ToComputedValue for SpecifiedValue { type ComputedValue = computed_value::T; #[inline] fn to_computed_value(&self, _context: &Context) -> computed_value::T { match *self { SpecifiedValue::None => computed_value::T(None), SpecifiedValue::Url(ref url) => computed_value::T(Some(url.clone())), } } } pub fn parse(context: &ParserContext, input: &mut Parser) -> Result<SpecifiedValue, ()> { if input.try(|input| input.expect_ident_matching("none")).is_ok() { Ok(SpecifiedValue::None) } else { Ok(SpecifiedValue::Url(context.parse_url(&*try!(input.expect_url())))) } } #[inline] pub fn get_initial_value() -> computed_value::T { computed_value::T(None) } </%self:longhand> <%self:longhand name="quotes"> use std::borrow::Cow; use std::fmt; use values::computed::ComputedValueAsSpecified; use cssparser::{ToCss, Token}; pub use self::computed_value::T as SpecifiedValue; pub mod computed_value { #[derive(Clone, PartialEq, HeapSizeOf)] pub struct T(pub Vec<(String,String)>); } impl ComputedValueAsSpecified for SpecifiedValue {} impl ToCss for SpecifiedValue { fn to_css<W>(&self, dest: &mut W) -> fmt::Result where W: fmt::Write { let mut first = true; for pair in &self.0 { if !first { try!(dest.write_str(" ")); } first = false; try!(Token::QuotedString(Cow::from(&*pair.0)).to_css(dest)); try!(dest.write_str(" ")); try!(Token::QuotedString(Cow::from(&*pair.1)).to_css(dest)); } Ok(()) } } #[inline] pub fn get_initial_value() -> computed_value::T { computed_value::T(vec![ ("\u{201c}".to_owned(), "\u{201d}".to_owned()), ("\u{2018}".to_owned(), "\u{2019}".to_owned()), ]) } pub fn parse(_: &ParserContext, input: &mut Parser) -> Result<SpecifiedValue,()> { if input.try(|input| input.expect_ident_matching("none")).is_ok() { return Ok(SpecifiedValue(Vec::new())) } let mut quotes = Vec::new(); loop { let first = match input.next() { Ok(Token::QuotedString(value)) => value.into_owned(), Ok(_) => return Err(()), Err(()) => break, }; let second = match input.next() { Ok(Token::QuotedString(value)) => value.into_owned(), _ => return Err(()), }; quotes.push((first, second)) } if !quotes.is_empty() { Ok(SpecifiedValue(quotes)) } else { Err(()) } } </%self:longhand> ${new_style_struct("Counters", is_inherited=False)} <%self:longhand name="counter-increment"> use std::fmt; use super::content; use values::computed::ComputedValueAsSpecified; use cssparser::{ToCss, Token}; use std::borrow::{Cow, ToOwned}; pub use self::computed_value::T as SpecifiedValue; pub mod computed_value { #[derive(Clone, PartialEq, HeapSizeOf)] pub struct T(pub Vec<(String,i32)>); } #[inline] pub fn get_initial_value() -> computed_value::T { computed_value::T(Vec::new()) } impl ComputedValueAsSpecified for SpecifiedValue {} impl ToCss for SpecifiedValue { fn to_css<W>(&self, dest: &mut W) -> fmt::Result where W: fmt::Write { let mut first = true; for pair in &self.0 { if !first { try!(dest.write_str(" ")); } first = false; try!(Token::QuotedString(Cow::from(&*pair.0)).to_css(dest)); try!(write!(dest, " {}", pair.1)); } Ok(()) } } pub fn parse(_: &ParserContext, input: &mut Parser) -> Result<SpecifiedValue,()> { if input.try(|input| input.expect_ident_matching("none")).is_ok() { return Ok(SpecifiedValue(Vec::new())) } let mut counters = Vec::new(); loop { let counter_name = match input.next() { Ok(Token::Ident(ident)) => (*ident).to_owned(), Ok(_) => return Err(()), Err(_) => break, }; if content::counter_name_is_illegal(&counter_name) { return Err(()) } let counter_delta = input.try(|input| input.expect_integer()).unwrap_or(1) as i32; counters.push((counter_name, counter_delta)) } if !counters.is_empty() { Ok(SpecifiedValue(counters)) } else { Err(()) } } </%self:longhand> <%self:longhand name="counter-reset"> pub use super::counter_increment::{SpecifiedValue, computed_value, get_initial_value}; pub use super::counter_increment::{parse}; </%self:longhand> // CSS 2.1, Section 13 - Paged media // CSS 2.1, Section 14 - Colors and Backgrounds ${new_style_struct("Background", is_inherited=False)} ${predefined_type( "background-color", "CSSColor", "::cssparser::Color::RGBA(::cssparser::RGBA { red: 0., green: 0., blue: 0., alpha: 0. }) /* transparent */")} <%self:longhand name="background-image"> use cssparser::ToCss; use std::fmt; use values::computed::Context; use values::specified::Image; pub mod computed_value { use values::computed; #[derive(Clone, PartialEq, HeapSizeOf)] pub struct T(pub Option<computed::Image>); } impl ToCss for computed_value::T { fn to_css<W>(&self, dest: &mut W) -> fmt::Result where W: fmt::Write { match self.0 { None => dest.write_str("none"), Some(computed::Image::Url(ref url)) => ::cssparser::Token::Url(url.to_string().into()).to_css(dest), Some(computed::Image::LinearGradient(ref gradient)) => gradient.to_css(dest) } } } #[derive(Clone, PartialEq)] pub struct SpecifiedValue(pub Option<Image>); impl ToCss for SpecifiedValue { fn to_css<W>(&self, dest: &mut W) -> fmt::Result where W: fmt::Write { match *self { SpecifiedValue(Some(ref image)) => image.to_css(dest), SpecifiedValue(None) => dest.write_str("none"), } } } #[inline] pub fn get_initial_value() -> computed_value::T { computed_value::T(None) } pub fn parse(context: &ParserContext, input: &mut Parser) -> Result<SpecifiedValue, ()> { if input.try(|input| input.expect_ident_matching("none")).is_ok() { Ok(SpecifiedValue(None)) } else { Ok(SpecifiedValue(Some(try!(Image::parse(context, input))))) } } impl ToComputedValue for SpecifiedValue { type ComputedValue = computed_value::T; #[inline] fn to_computed_value(&self, context: &Context) -> computed_value::T { match *self { SpecifiedValue(None) => computed_value::T(None), SpecifiedValue(Some(ref image)) => computed_value::T(Some(image.to_computed_value(context))), } } } </%self:longhand> <%self:longhand name="background-position"> use cssparser::ToCss; use std::fmt; use values::computed::Context; pub mod computed_value { use values::computed::LengthOrPercentage; #[derive(PartialEq, Copy, Clone, Debug, HeapSizeOf)] pub struct T { pub horizontal: LengthOrPercentage, pub vertical: LengthOrPercentage, } } #[derive(Clone, PartialEq, Copy)] pub struct SpecifiedValue { pub horizontal: specified::LengthOrPercentage, pub vertical: specified::LengthOrPercentage, } impl ToCss for SpecifiedValue { fn to_css<W>(&self, dest: &mut W) -> fmt::Result where W: fmt::Write { try!(self.horizontal.to_css(dest)); try!(dest.write_str(" ")); try!(self.vertical.to_css(dest)); Ok(()) } } impl ToCss for computed_value::T { fn to_css<W>(&self, dest: &mut W) -> fmt::Result where W: fmt::Write { try!(self.horizontal.to_css(dest)); try!(dest.write_str(" ")); try!(self.vertical.to_css(dest)); Ok(()) } } impl SpecifiedValue { fn new(first: specified::PositionComponent, second: specified::PositionComponent) -> Result<SpecifiedValue, ()> { let (horiz, vert) = match (category(first), category(second)) { // Don't allow two vertical keywords or two horizontal keywords. (PositionCategory::HorizontalKeyword, PositionCategory::HorizontalKeyword) | (PositionCategory::VerticalKeyword, PositionCategory::VerticalKeyword) => return Err(()), // Swap if both are keywords and vertical precedes horizontal. (PositionCategory::VerticalKeyword, PositionCategory::HorizontalKeyword) | (PositionCategory::VerticalKeyword, PositionCategory::OtherKeyword) | (PositionCategory::OtherKeyword, PositionCategory::HorizontalKeyword) => (second, first), // By default, horizontal is first. _ => (first, second), }; Ok(SpecifiedValue { horizontal: horiz.to_length_or_percentage(), vertical: vert.to_length_or_percentage(), }) } } // Collapse `Position` into a few categories to simplify the above `match` expression. enum PositionCategory { HorizontalKeyword, VerticalKeyword, OtherKeyword, LengthOrPercentage, } fn category(p: specified::PositionComponent) -> PositionCategory { match p { specified::PositionComponent::Left | specified::PositionComponent::Right => PositionCategory::HorizontalKeyword, specified::PositionComponent::Top | specified::PositionComponent::Bottom => PositionCategory::VerticalKeyword, specified::PositionComponent::Center => PositionCategory::OtherKeyword, specified::PositionComponent::Length(_) | specified::PositionComponent::Percentage(_) => PositionCategory::LengthOrPercentage, } } impl ToComputedValue for SpecifiedValue { type ComputedValue = computed_value::T; #[inline] fn to_computed_value(&self, context: &Context) -> computed_value::T { computed_value::T { horizontal: self.horizontal.to_computed_value(context), vertical: self.vertical.to_computed_value(context), } } } #[inline] pub fn get_initial_value() -> computed_value::T { computed_value::T { horizontal: computed::LengthOrPercentage::Percentage(0.0), vertical: computed::LengthOrPercentage::Percentage(0.0), } } pub fn parse(_context: &ParserContext, input: &mut Parser) -> Result<SpecifiedValue, ()> { let first = try!(specified::PositionComponent::parse(input)); let second = input.try(specified::PositionComponent::parse) .unwrap_or(specified::PositionComponent::Center); SpecifiedValue::new(first, second) } </%self:longhand> ${single_keyword("background-repeat", "repeat repeat-x repeat-y no-repeat")} ${single_keyword("background-attachment", "scroll fixed")} ${single_keyword("background-clip", "border-box padding-box content-box")} ${single_keyword("background-origin", "padding-box border-box content-box")} <%self:longhand name="background-size"> use cssparser::{ToCss, Token}; use std::ascii::AsciiExt; use std::fmt; use values::computed::Context; pub mod computed_value { use values::computed::LengthOrPercentageOrAuto; #[derive(PartialEq, Clone, Debug, HeapSizeOf)] pub struct ExplicitSize { pub width: LengthOrPercentageOrAuto, pub height: LengthOrPercentageOrAuto, } #[derive(PartialEq, Clone, Debug, HeapSizeOf)] pub enum T { Explicit(ExplicitSize), Cover, Contain, } } impl ToCss for computed_value::T { fn to_css<W>(&self, dest: &mut W) -> fmt::Result where W: fmt::Write { match *self { computed_value::T::Explicit(ref size) => size.to_css(dest), computed_value::T::Cover => dest.write_str("cover"), computed_value::T::Contain => dest.write_str("contain"), } } } #[derive(Clone, PartialEq, Debug)] pub struct SpecifiedExplicitSize { pub width: specified::LengthOrPercentageOrAuto, pub height: specified::LengthOrPercentageOrAuto, } impl ToCss for SpecifiedExplicitSize { fn to_css<W>(&self, dest: &mut W) -> fmt::Result where W: fmt::Write { try!(self.width.to_css(dest)); try!(dest.write_str(" ")); self.height.to_css(dest) } } impl ToCss for computed_value::ExplicitSize { fn to_css<W>(&self, dest: &mut W) -> fmt::Result where W: fmt::Write { try!(self.width.to_css(dest)); try!(dest.write_str(" ")); self.height.to_css(dest) } } #[derive(Clone, PartialEq, Debug)] pub enum SpecifiedValue { Explicit(SpecifiedExplicitSize), Cover, Contain, } impl ToCss for SpecifiedValue { fn to_css<W>(&self, dest: &mut W) -> fmt::Result where W: fmt::Write { match *self { SpecifiedValue::Explicit(ref size) => size.to_css(dest), SpecifiedValue::Cover => dest.write_str("cover"), SpecifiedValue::Contain => dest.write_str("contain"), } } } impl ToComputedValue for SpecifiedValue { type ComputedValue = computed_value::T; #[inline] fn to_computed_value(&self, context: &computed::Context) -> computed_value::T { match *self { SpecifiedValue::Explicit(ref size) => { computed_value::T::Explicit(computed_value::ExplicitSize { width: size.width.to_computed_value(context), height: size.height.to_computed_value(context), }) } SpecifiedValue::Cover => computed_value::T::Cover, SpecifiedValue::Contain => computed_value::T::Contain, } } } #[inline] pub fn get_initial_value() -> computed_value::T { computed_value::T::Explicit(computed_value::ExplicitSize { width: computed::LengthOrPercentageOrAuto::Auto, height: computed::LengthOrPercentageOrAuto::Auto, }) } pub fn parse(_: &ParserContext, input: &mut Parser) -> Result<SpecifiedValue,()> { let width; if let Ok(value) = input.try(|input| { match input.next() { Err(_) => Err(()), Ok(Token::Ident(ref ident)) if ident.eq_ignore_ascii_case("cover") => { Ok(SpecifiedValue::Cover) } Ok(Token::Ident(ref ident)) if ident.eq_ignore_ascii_case("contain") => { Ok(SpecifiedValue::Contain) } Ok(_) => Err(()), } }) { return Ok(value) } else { width = try!(specified::LengthOrPercentageOrAuto::parse(input)) } let height; if let Ok(value) = input.try(|input| { match input.next() { Err(_) => Ok(specified::LengthOrPercentageOrAuto::Auto), Ok(_) => Err(()), } }) { height = value } else { height = try!(specified::LengthOrPercentageOrAuto::parse(input)); } Ok(SpecifiedValue::Explicit(SpecifiedExplicitSize { width: width, height: height, })) } </%self:longhand> ${new_style_struct("Color", is_inherited=True)} <%self:raw_longhand name="color"> use cssparser::{Color, RGBA}; use values::computed::Context; use values::specified::{CSSColor, CSSRGBA}; impl ToComputedValue for SpecifiedValue { type ComputedValue = computed_value::T; #[inline] fn to_computed_value(&self, _context: &Context) -> computed_value::T { self.parsed } } pub type SpecifiedValue = CSSRGBA; pub mod computed_value { use cssparser; pub type T = cssparser::RGBA; } #[inline] pub fn get_initial_value() -> computed_value::T { RGBA { red: 0., green: 0., blue: 0., alpha: 1. } /* black */ } pub fn parse_specified(_context: &ParserContext, input: &mut Parser) -> Result<DeclaredValue<SpecifiedValue>, ()> { let value = try!(CSSColor::parse(input)); let rgba = match value.parsed { Color::RGBA(rgba) => rgba, Color::CurrentColor => return Ok(DeclaredValue::Inherit) }; Ok(DeclaredValue::Value(CSSRGBA { parsed: rgba, authored: value.authored, })) } </%self:raw_longhand> // CSS 2.1, Section 15 - Fonts ${new_style_struct("Font", is_inherited=True)} <%self:longhand name="font-family"> use self::computed_value::FontFamily; use values::computed::ComputedValueAsSpecified; pub use self::computed_value::T as SpecifiedValue; impl ComputedValueAsSpecified for SpecifiedValue {} pub mod computed_value { use cssparser::ToCss; use std::fmt; use string_cache::Atom; #[derive(PartialEq, Eq, Clone, Hash, HeapSizeOf)] pub enum FontFamily { FamilyName(Atom), // Generic // Serif, // SansSerif, // Cursive, // Fantasy, // Monospace, } impl FontFamily { #[inline] pub fn name(&self) -> &str { match *self { FontFamily::FamilyName(ref name) => name.as_slice(), } } } impl ToCss for FontFamily { fn to_css<W>(&self, dest: &mut W) -> fmt::Result where W: fmt::Write { match *self { FontFamily::FamilyName(ref name) => dest.write_str(name.as_slice()), } } } impl ToCss for T { fn to_css<W>(&self, dest: &mut W) -> fmt::Result where W: fmt::Write { let mut iter = self.0.iter(); try!(iter.next().unwrap().to_css(dest)); for family in iter { try!(dest.write_str(", ")); try!(family.to_css(dest)); } Ok(()) } } #[derive(Clone, PartialEq, Eq, Hash, HeapSizeOf)] pub struct T(pub Vec<FontFamily>); } #[inline] pub fn get_initial_value() -> computed_value::T { computed_value::T(vec![FontFamily::FamilyName(atom!("serif"))]) } /// <family-name># /// <family-name> = <string> | [ <ident>+ ] /// TODO: <generic-family> pub fn parse(_context: &ParserContext, input: &mut Parser) -> Result<SpecifiedValue, ()> { input.parse_comma_separated(parse_one_family).map(SpecifiedValue) } pub fn parse_one_family(input: &mut Parser) -> Result<FontFamily, ()> { if let Ok(value) = input.try(|input| input.expect_string()) { return Ok(FontFamily::FamilyName(Atom::from_slice(&value))) } let first_ident = try!(input.expect_ident()); // match_ignore_ascii_case! { first_ident, // "serif" => return Ok(Serif), // "sans-serif" => return Ok(SansSerif), // "cursive" => return Ok(Cursive), // "fantasy" => return Ok(Fantasy), // "monospace" => return Ok(Monospace) // _ => {} // } let mut value = first_ident.into_owned(); while let Ok(ident) = input.try(|input| input.expect_ident()) { value.push_str(" "); value.push_str(&ident); } Ok(FontFamily::FamilyName(Atom::from_slice(&value))) } </%self:longhand> ${single_keyword("font-style", "normal italic oblique")} ${single_keyword("font-variant", "normal small-caps")} <%self:longhand name="font-weight"> use cssparser::ToCss; use std::fmt; use values::computed::Context; #[derive(Clone, PartialEq, Eq, Copy)] pub enum SpecifiedValue { Bolder, Lighter, % for weight in range(100, 901, 100): Weight${weight}, % endfor } impl ToCss for SpecifiedValue { fn to_css<W>(&self, dest: &mut W) -> fmt::Result where W: fmt::Write { match *self { SpecifiedValue::Bolder => dest.write_str("bolder"), SpecifiedValue::Lighter => dest.write_str("lighter"), % for weight in range(100, 901, 100): SpecifiedValue::Weight${weight} => dest.write_str("${weight}"), % endfor } } } /// normal | bold | bolder | lighter | 100 | 200 | 300 | 400 | 500 | 600 | 700 | 800 | 900 pub fn parse(_context: &ParserContext, input: &mut Parser) -> Result<SpecifiedValue, ()> { input.try(|input| { match_ignore_ascii_case! { try!(input.expect_ident()), "bold" => Ok(SpecifiedValue::Weight700), "normal" => Ok(SpecifiedValue::Weight400), "bolder" => Ok(SpecifiedValue::Bolder), "lighter" => Ok(SpecifiedValue::Lighter) _ => Err(()) } }).or_else(|()| { match try!(input.expect_integer()) { 100 => Ok(SpecifiedValue::Weight100), 200 => Ok(SpecifiedValue::Weight200), 300 => Ok(SpecifiedValue::Weight300), 400 => Ok(SpecifiedValue::Weight400), 500 => Ok(SpecifiedValue::Weight500), 600 => Ok(SpecifiedValue::Weight600), 700 => Ok(SpecifiedValue::Weight700), 800 => Ok(SpecifiedValue::Weight800), 900 => Ok(SpecifiedValue::Weight900), _ => Err(()) } }) } pub mod computed_value { use std::fmt; #[derive(PartialEq, Eq, Copy, Clone, Hash, Deserialize, Serialize, HeapSizeOf)] pub enum T { % for weight in range(100, 901, 100): Weight${weight} = ${weight}, % endfor } impl fmt::Debug for T { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { match *self { % for weight in range(100, 901, 100): T::Weight${weight} => write!(f, "{}", ${weight}), % endfor } } } impl T { #[inline] pub fn is_bold(self) -> bool { match self { T::Weight900 | T::Weight800 | T::Weight700 | T::Weight600 => true, _ => false } } } } impl ToCss for computed_value::T { fn to_css<W>(&self, dest: &mut W) -> fmt::Result where W: fmt::Write { match *self { % for weight in range(100, 901, 100): computed_value::T::Weight${weight} => dest.write_str("${weight}"), % endfor } } } #[inline] pub fn get_initial_value() -> computed_value::T { computed_value::T::Weight400 // normal } impl ToComputedValue for SpecifiedValue { type ComputedValue = computed_value::T; #[inline] fn to_computed_value(&self, context: &Context) -> computed_value::T { match *self { % for weight in range(100, 901, 100): SpecifiedValue::Weight${weight} => computed_value::T::Weight${weight}, % endfor SpecifiedValue::Bolder => match context.inherited_font_weight { computed_value::T::Weight100 => computed_value::T::Weight400, computed_value::T::Weight200 => computed_value::T::Weight400, computed_value::T::Weight300 => computed_value::T::Weight400, computed_value::T::Weight400 => computed_value::T::Weight700, computed_value::T::Weight500 => computed_value::T::Weight700, computed_value::T::Weight600 => computed_value::T::Weight900, computed_value::T::Weight700 => computed_value::T::Weight900, computed_value::T::Weight800 => computed_value::T::Weight900, computed_value::T::Weight900 => computed_value::T::Weight900, }, SpecifiedValue::Lighter => match context.inherited_font_weight { computed_value::T::Weight100 => computed_value::T::Weight100, computed_value::T::Weight200 => computed_value::T::Weight100, computed_value::T::Weight300 => computed_value::T::Weight100, computed_value::T::Weight400 => computed_value::T::Weight100, computed_value::T::Weight500 => computed_value::T::Weight100, computed_value::T::Weight600 => computed_value::T::Weight400, computed_value::T::Weight700 => computed_value::T::Weight400, computed_value::T::Weight800 => computed_value::T::Weight700, computed_value::T::Weight900 => computed_value::T::Weight700, }, } } } </%self:longhand> <%self:longhand name="font-size"> use cssparser::ToCss; use std::fmt; use util::geometry::Au; use values::computed::Context; impl ToCss for SpecifiedValue { fn to_css<W>(&self, dest: &mut W) -> fmt::Result where W: fmt::Write { self.0.to_css(dest) } } #[derive(Clone, PartialEq)] pub struct SpecifiedValue(pub specified::Length); // Percentages are the same as em. pub mod computed_value { use util::geometry::Au; pub type T = Au; } const MEDIUM_PX: i32 = 16; #[inline] pub fn get_initial_value() -> computed_value::T { Au::from_px(MEDIUM_PX) } impl ToComputedValue for SpecifiedValue { type ComputedValue = computed_value::T; #[inline] fn to_computed_value(&self, context: &Context) -> computed_value::T { // We already computed this element's font size; no need to compute it again. return context.font_size } } /// <length> | <percentage> | <absolute-size> | <relative-size> pub fn parse(_context: &ParserContext, input: &mut Parser) -> Result<SpecifiedValue, ()> { input.try(specified::LengthOrPercentage::parse_non_negative) .and_then(|value| match value { specified::LengthOrPercentage::Length(value) => Ok(value), specified::LengthOrPercentage::Percentage(value) => Ok(specified::Length::FontRelative(specified::FontRelativeLength::Em(value.0))), // FIXME(dzbarsky) handle calc for font-size specified::LengthOrPercentage::Calc(_) => Err(()) }) .or_else(|()| { match_ignore_ascii_case! { try!(input.expect_ident()), "xx-small" => Ok(specified::Length::Absolute(Au::from_px(MEDIUM_PX) * 3 / 5)), "x-small" => Ok(specified::Length::Absolute(Au::from_px(MEDIUM_PX) * 3 / 4)), "small" => Ok(specified::Length::Absolute(Au::from_px(MEDIUM_PX) * 8 / 9)), "medium" => Ok(specified::Length::Absolute(Au::from_px(MEDIUM_PX))), "large" => Ok(specified::Length::Absolute(Au::from_px(MEDIUM_PX) * 6 / 5)), "x-large" => Ok(specified::Length::Absolute(Au::from_px(MEDIUM_PX) * 3 / 2)), "xx-large" => Ok(specified::Length::Absolute(Au::from_px(MEDIUM_PX) * 2)), // https://github.com/servo/servo/issues/3423#issuecomment-56321664 "smaller" => Ok(specified::Length::FontRelative(specified::FontRelativeLength::Em(0.85))), "larger" => Ok(specified::Length::FontRelative(specified::FontRelativeLength::Em(1.2))) _ => Err(()) } }) .map(SpecifiedValue) } </%self:longhand> ${single_keyword("font-stretch", "normal ultra-condensed extra-condensed condensed semi-condensed semi-expanded \ expanded extra-expanded ultra-expanded")} // CSS 2.1, Section 16 - Text ${new_style_struct("InheritedText", is_inherited=True)} <%self:longhand name="text-align"> pub use self::computed_value::T as SpecifiedValue; use values::computed::ComputedValueAsSpecified; impl ComputedValueAsSpecified for SpecifiedValue {} pub mod computed_value { macro_rules! define_text_align { ( $( $name: ident ( $string: expr ) => $discriminant: expr, )+ ) => { define_css_keyword_enum! { T: $( $string => $name, )+ } impl T { pub fn to_u32(self) -> u32 { match self { $( T::$name => $discriminant, )+ } } pub fn from_u32(discriminant: u32) -> Option<T> { match discriminant { $( $discriminant => Some(T::$name), )+ _ => None } } } } } define_text_align! { start("start") => 0, end("end") => 1, left("left") => 2, right("right") => 3, center("center") => 4, justify("justify") => 5, servo_center("-servo-center") => 6, } } #[inline] pub fn get_initial_value() -> computed_value::T { computed_value::T::start } pub fn parse(_context: &ParserContext, input: &mut Parser) -> Result<SpecifiedValue, ()> { computed_value::T::parse(input) } </%self:longhand> <%self:longhand name="letter-spacing"> use cssparser::ToCss; use std::fmt; use values::computed::Context; #[derive(Clone, Copy, PartialEq)] pub enum SpecifiedValue { Normal, Specified(specified::Length), } impl ToCss for SpecifiedValue { fn to_css<W>(&self, dest: &mut W) -> fmt::Result where W: fmt::Write { match *self { SpecifiedValue::Normal => dest.write_str("normal"), SpecifiedValue::Specified(l) => l.to_css(dest), } } } pub mod computed_value { use util::geometry::Au; #[derive(Clone, PartialEq, HeapSizeOf)] pub struct T(pub Option<Au>); } impl ToCss for computed_value::T { fn to_css<W>(&self, dest: &mut W) -> fmt::Result where W: fmt::Write { match self.0 { None => dest.write_str("normal"), Some(l) => l.to_css(dest), } } } #[inline] pub fn get_initial_value() -> computed_value::T { computed_value::T(None) } impl ToComputedValue for SpecifiedValue { type ComputedValue = computed_value::T; #[inline] fn to_computed_value(&self, context: &Context) -> computed_value::T { match *self { SpecifiedValue::Normal => computed_value::T(None), SpecifiedValue::Specified(l) => computed_value::T(Some(l.to_computed_value(context))) } } } pub fn parse(_context: &ParserContext, input: &mut Parser) -> Result<SpecifiedValue, ()> { if input.try(|input| input.expect_ident_matching("normal")).is_ok() { Ok(SpecifiedValue::Normal) } else { specified::Length::parse_non_negative(input).map(SpecifiedValue::Specified) } } </%self:longhand> <%self:longhand name="word-spacing"> use cssparser::ToCss; use std::fmt; use values::computed::Context; #[derive(Clone, Copy, PartialEq)] pub enum SpecifiedValue { Normal, Specified(specified::Length), // FIXME(SimonSapin) support percentages } impl ToCss for SpecifiedValue { fn to_css<W>(&self, dest: &mut W) -> fmt::Result where W: fmt::Write { match *self { SpecifiedValue::Normal => dest.write_str("normal"), SpecifiedValue::Specified(l) => l.to_css(dest), } } } pub mod computed_value { use util::geometry::Au; #[derive(Clone, PartialEq, HeapSizeOf)] pub struct T(pub Option<Au>); } impl ToCss for computed_value::T { fn to_css<W>(&self, dest: &mut W) -> fmt::Result where W: fmt::Write { match self.0 { None => dest.write_str("normal"), Some(l) => l.to_css(dest), } } } #[inline] pub fn get_initial_value() -> computed_value::T { computed_value::T(None) } impl ToComputedValue for SpecifiedValue { type ComputedValue = computed_value::T; #[inline] fn to_computed_value(&self, context: &Context) -> computed_value::T { match *self { SpecifiedValue::Normal => computed_value::T(None), SpecifiedValue::Specified(l) => computed_value::T(Some(l.to_computed_value(context))) } } } pub fn parse(_context: &ParserContext, input: &mut Parser) -> Result<SpecifiedValue, ()> { if input.try(|input| input.expect_ident_matching("normal")).is_ok() { Ok(SpecifiedValue::Normal) } else { specified::Length::parse_non_negative(input).map(SpecifiedValue::Specified) } } </%self:longhand> ${predefined_type("text-indent", "LengthOrPercentage", "computed::LengthOrPercentage::Length(Au(0))")} // Also known as "word-wrap" (which is more popular because of IE), but this is the preferred // name per CSS-TEXT 6.2. ${single_keyword("overflow-wrap", "normal break-word")} // TODO(pcwalton): Support `word-break: keep-all` once we have better CJK support. ${single_keyword("word-break", "normal break-all")} ${single_keyword("text-overflow", "clip ellipsis")} // TODO(pcwalton): Support `text-justify: distribute`. ${single_keyword("text-justify", "auto none inter-word")} ${new_style_struct("Text", is_inherited=False)} ${single_keyword("unicode-bidi", "normal embed isolate bidi-override isolate-override plaintext")} <%self:longhand name="text-decoration" custom_cascade="True"> use cssparser::ToCss; use std::fmt; use values::computed::ComputedValueAsSpecified; impl ComputedValueAsSpecified for SpecifiedValue {} #[derive(PartialEq, Eq, Copy, Clone, Debug, HeapSizeOf)] pub struct SpecifiedValue { pub underline: bool, pub overline: bool, pub line_through: bool, // 'blink' is accepted in the parser but ignored. // Just not blinking the text is a conforming implementation per CSS 2.1. } impl ToCss for SpecifiedValue { fn to_css<W>(&self, dest: &mut W) -> fmt::Result where W: fmt::Write { let mut space = false; if self.underline { try!(dest.write_str("underline")); space = true; } if self.overline { if space { try!(dest.write_str(" ")); } try!(dest.write_str("overline")); space = true; } if self.line_through { if space { try!(dest.write_str(" ")); } try!(dest.write_str("line-through")); } Ok(()) } } pub mod computed_value { pub type T = super::SpecifiedValue; #[allow(non_upper_case_globals)] pub const none: T = super::SpecifiedValue { underline: false, overline: false, line_through: false }; } #[inline] pub fn get_initial_value() -> computed_value::T { computed_value::none } /// none | [ underline || overline || line-through || blink ] pub fn parse(_context: &ParserContext, input: &mut Parser) -> Result<SpecifiedValue, ()> { let mut result = SpecifiedValue { underline: false, overline: false, line_through: false, }; if input.try(|input| input.expect_ident_matching("none")).is_ok() { return Ok(result) } let mut blink = false; let mut empty = true; while let Ok(ident) = input.expect_ident() { match_ignore_ascii_case! { ident, "underline" => if result.underline { return Err(()) } else { empty = false; result.underline = true }, "overline" => if result.overline { return Err(()) } else { empty = false; result.overline = true }, "line-through" => if result.line_through { return Err(()) } else { empty = false; result.line_through = true }, "blink" => if blink { return Err(()) } else { empty = false; blink = true } _ => break } } if !empty { Ok(result) } else { Err(()) } } fn cascade_property_custom(computed_value: &computed_value::T, _declaration: &PropertyDeclaration, style: &mut ComputedValues, _inherited_style: &ComputedValues, context: &computed::Context, _seen: &mut PropertyBitField, _cacheable: &mut bool) { Arc::make_mut(&mut style.inheritedtext)._servo_text_decorations_in_effect = longhands::_servo_text_decorations_in_effect::derive_from_text_decoration( *computed_value, &context); } </%self:longhand> ${switch_to_style_struct("InheritedText")} <%self:longhand name="-servo-text-decorations-in-effect" derived_from="display text-decoration"> use cssparser::{RGBA, ToCss}; use std::fmt; use values::computed::ComputedValueAsSpecified; impl ComputedValueAsSpecified for SpecifiedValue {} #[derive(Clone, PartialEq, Copy, Debug, HeapSizeOf)] pub struct SpecifiedValue { pub underline: Option<RGBA>, pub overline: Option<RGBA>, pub line_through: Option<RGBA>, } pub mod computed_value { pub type T = super::SpecifiedValue; } impl ToCss for SpecifiedValue { fn to_css<W>(&self, _: &mut W) -> fmt::Result where W: fmt::Write { // Web compat doesn't matter here. Ok(()) } } #[inline] pub fn get_initial_value() -> computed_value::T { SpecifiedValue { underline: None, overline: None, line_through: None, } } fn maybe(flag: bool, context: &computed::Context) -> Option<RGBA> { if flag { Some(context.color) } else { None } } fn derive(context: &computed::Context) -> computed_value::T { // Start with no declarations if this is a block; otherwise, start with the // declarations in effect and add in the text decorations that this inline specifies. let mut result = match context.display { super::display::computed_value::T::inline => { context.inherited_text_decorations_in_effect } _ => { SpecifiedValue { underline: None, overline: None, line_through: None, } } }; if result.underline.is_none() { result.underline = maybe(context.text_decoration.underline, context) } if result.overline.is_none() { result.overline = maybe(context.text_decoration.overline, context) } if result.line_through.is_none() { result.line_through = maybe(context.text_decoration.line_through, context) } result } #[inline] pub fn derive_from_text_decoration(_: super::text_decoration::computed_value::T, context: &computed::Context) -> computed_value::T { derive(context) } #[inline] pub fn derive_from_display(_: super::display::computed_value::T, context: &computed::Context) -> computed_value::T { derive(context) } </%self:longhand> ${single_keyword("white-space", "normal pre nowrap")} // TODO(pcwalton): `full-width` ${single_keyword("text-transform", "none capitalize uppercase lowercase")} ${single_keyword("text-rendering", "auto optimizespeed optimizelegibility geometricprecision")} // CSS 2.1, Section 17 - Tables ${new_style_struct("Table", is_inherited=False)} ${single_keyword("table-layout", "auto fixed")} ${new_style_struct("InheritedTable", is_inherited=True)} ${single_keyword("border-collapse", "separate collapse")} ${single_keyword("empty-cells", "show hide")} ${single_keyword("caption-side", "top bottom")} <%self:longhand name="border-spacing"> use values::computed::Context; use cssparser::ToCss; use std::fmt; use util::geometry::Au; pub mod computed_value { use util::geometry::Au; #[derive(Clone, Copy, Debug, PartialEq, RustcEncodable, HeapSizeOf)] pub struct T { pub horizontal: Au, pub vertical: Au, } } #[derive(Clone, Debug, PartialEq)] pub struct SpecifiedValue { pub horizontal: specified::Length, pub vertical: specified::Length, } #[inline] pub fn get_initial_value() -> computed_value::T { computed_value::T { horizontal: Au(0), vertical: Au(0), } } impl ToCss for SpecifiedValue { fn to_css<W>(&self, dest: &mut W) -> fmt::Result where W: fmt::Write { try!(self.horizontal.to_css(dest)); try!(dest.write_str(" ")); self.vertical.to_css(dest) } } impl ToCss for computed_value::T { fn to_css<W>(&self, dest: &mut W) -> fmt::Result where W: fmt::Write { try!(self.horizontal.to_css(dest)); try!(dest.write_str(" ")); self.vertical.to_css(dest) } } impl ToComputedValue for SpecifiedValue { type ComputedValue = computed_value::T; #[inline] fn to_computed_value(&self, context: &Context) -> computed_value::T { computed_value::T { horizontal: self.horizontal.to_computed_value(context), vertical: self.vertical.to_computed_value(context), } } } pub fn parse(_: &ParserContext, input: &mut Parser) -> Result<SpecifiedValue,()> { let mut lengths = [ None, None ]; for i in 0..2 { match specified::Length::parse_non_negative(input) { Err(()) => break, Ok(length) => lengths[i] = Some(length), } } if input.next().is_ok() { return Err(()) } match (lengths[0], lengths[1]) { (None, None) => Err(()), (Some(length), None) => { Ok(SpecifiedValue { horizontal: length, vertical: length, }) } (Some(horizontal), Some(vertical)) => { Ok(SpecifiedValue { horizontal: horizontal, vertical: vertical, }) } (None, Some(_)) => panic!("shouldn't happen"), } } </%self:longhand> // CSS 2.1, Section 18 - User interface // CSS Writing Modes Level 3 // http://dev.w3.org/csswg/css-writing-modes/ ${switch_to_style_struct("InheritedBox")} ${single_keyword("writing-mode", "horizontal-tb vertical-rl vertical-lr", experimental=True)} // FIXME(SimonSapin): Add 'mixed' and 'upright' (needs vertical text support) // FIXME(SimonSapin): initial (first) value should be 'mixed', when that's implemented ${single_keyword("text-orientation", "sideways sideways-left sideways-right", experimental=True)} // CSS Basic User Interface Module Level 3 // http://dev.w3.org/csswg/css-ui/ ${switch_to_style_struct("Box")} ${single_keyword("box-sizing", "content-box border-box")} ${new_style_struct("Pointing", is_inherited=True)} <%self:longhand name="cursor"> use util::cursor as util_cursor; pub use self::computed_value::T as SpecifiedValue; use values::computed::ComputedValueAsSpecified; impl ComputedValueAsSpecified for SpecifiedValue {} pub mod computed_value { use cssparser::ToCss; use std::fmt; use util::cursor::Cursor; #[derive(Clone, PartialEq, Eq, Copy, Debug, HeapSizeOf)] pub enum T { AutoCursor, SpecifiedCursor(Cursor), } impl ToCss for T { fn to_css<W>(&self, dest: &mut W) -> fmt::Result where W: fmt::Write { match *self { T::AutoCursor => dest.write_str("auto"), T::SpecifiedCursor(c) => c.to_css(dest), } } } } #[inline] pub fn get_initial_value() -> computed_value::T { computed_value::T::AutoCursor } pub fn parse(_context: &ParserContext, input: &mut Parser) -> Result<SpecifiedValue, ()> { use std::ascii::AsciiExt; let ident = try!(input.expect_ident()); if ident.eq_ignore_ascii_case("auto") { Ok(SpecifiedValue::AutoCursor) } else { util_cursor::Cursor::from_css_keyword(&ident) .map(SpecifiedValue::SpecifiedCursor) } } </%self:longhand> // NB: `pointer-events: auto` (and use of `pointer-events` in anything that isn't SVG, in fact) // is nonstandard, slated for CSS4-UI. // TODO(pcwalton): SVG-only values. ${single_keyword("pointer-events", "auto none")} ${new_style_struct("Column", is_inherited=False)} <%self:longhand name="column-width" experimental="True"> use cssparser::ToCss; use std::fmt; use values::computed::Context; #[derive(Clone, Copy, PartialEq)] pub enum SpecifiedValue { Auto, Specified(specified::Length), } impl ToCss for SpecifiedValue { fn to_css<W>(&self, dest: &mut W) -> fmt::Result where W: fmt::Write { match *self { SpecifiedValue::Auto => dest.write_str("auto"), SpecifiedValue::Specified(l) => l.to_css(dest), } } } pub mod computed_value { use util::geometry::Au; #[derive(Clone, PartialEq, HeapSizeOf)] pub struct T(pub Option<Au>); } impl ToCss for computed_value::T { fn to_css<W>(&self, dest: &mut W) -> fmt::Result where W: fmt::Write { match self.0 { None => dest.write_str("auto"), Some(l) => l.to_css(dest), } } } #[inline] pub fn get_initial_value() -> computed_value::T { computed_value::T(None) } impl ToComputedValue for SpecifiedValue { type ComputedValue = computed_value::T; #[inline] fn to_computed_value(&self, context: &Context) -> computed_value::T { match *self { SpecifiedValue::Auto => computed_value::T(None), SpecifiedValue::Specified(l) => computed_value::T(Some(l.to_computed_value(context))) } } } pub fn parse(_context: &ParserContext, input: &mut Parser) -> Result<SpecifiedValue, ()> { if input.try(|input| input.expect_ident_matching("auto")).is_ok() { Ok(SpecifiedValue::Auto) } else { specified::Length::parse_non_negative(input).map(SpecifiedValue::Specified) } } </%self:longhand> <%self:longhand name="column-count" experimental="True"> use cssparser::ToCss; use std::fmt; use values::computed::Context; #[derive(Clone, Copy, PartialEq)] pub enum SpecifiedValue { Auto, Specified(u32), } impl ToCss for SpecifiedValue { fn to_css<W>(&self, dest: &mut W) -> fmt::Result where W: fmt::Write { match *self { SpecifiedValue::Auto => dest.write_str("auto"), SpecifiedValue::Specified(count) => write!(dest, "{}", count), } } } pub mod computed_value { #[derive(Clone, PartialEq, HeapSizeOf)] pub struct T(pub Option<u32>); } impl ToCss for computed_value::T { fn to_css<W>(&self, dest: &mut W) -> fmt::Result where W: fmt::Write { match self.0 { None => dest.write_str("auto"), Some(count) => write!(dest, "{}", count), } } } #[inline] pub fn get_initial_value() -> computed_value::T { computed_value::T(None) } impl ToComputedValue for SpecifiedValue { type ComputedValue = computed_value::T; #[inline] fn to_computed_value(&self, _context: &Context) -> computed_value::T { match *self { SpecifiedValue::Auto => computed_value::T(None), SpecifiedValue::Specified(count) => computed_value::T(Some(count)) } } } pub fn parse(_context: &ParserContext, input: &mut Parser) -> Result<SpecifiedValue, ()> { if input.try(|input| input.expect_ident_matching("auto")).is_ok() { Ok(SpecifiedValue::Auto) } else { let count = try!(input.expect_integer()); // Zero is invalid if count <= 0 { return Err(()) } Ok(SpecifiedValue::Specified(count as u32)) } } </%self:longhand> <%self:longhand name="column-gap" experimental="True"> use cssparser::ToCss; use std::fmt; use values::computed::Context; #[derive(Clone, Copy, PartialEq)] pub enum SpecifiedValue { Normal, Specified(specified::Length), } impl ToCss for SpecifiedValue { fn to_css<W>(&self, dest: &mut W) -> fmt::Result where W: fmt::Write { match *self { SpecifiedValue::Normal => dest.write_str("normal"), SpecifiedValue::Specified(l) => l.to_css(dest), } } } pub mod computed_value { use util::geometry::Au; #[derive(Clone, PartialEq, HeapSizeOf)] pub struct T(pub Option<Au>); } impl ToCss for computed_value::T { fn to_css<W>(&self, dest: &mut W) -> fmt::Result where W: fmt::Write { match self.0 { None => dest.write_str("normal"), Some(l) => l.to_css(dest), } } } #[inline] pub fn get_initial_value() -> computed_value::T { computed_value::T(None) } impl ToComputedValue for SpecifiedValue { type ComputedValue = computed_value::T; #[inline] fn to_computed_value(&self, context: &Context) -> computed_value::T { match *self { SpecifiedValue::Normal => computed_value::T(None), SpecifiedValue::Specified(l) => computed_value::T(Some(l.to_computed_value(context))) } } } pub fn parse(_context: &ParserContext, input: &mut Parser) -> Result<SpecifiedValue, ()> { if input.try(|input| input.expect_ident_matching("normal")).is_ok() { Ok(SpecifiedValue::Normal) } else { specified::Length::parse_non_negative(input).map(SpecifiedValue::Specified) } } </%self:longhand> // Box-shadow, etc. ${new_style_struct("Effects", is_inherited=False)} <%self:longhand name="opacity"> use cssparser::ToCss; use std::fmt; use values::CSSFloat; use values::computed::Context; impl ToCss for SpecifiedValue { fn to_css<W>(&self, dest: &mut W) -> fmt::Result where W: fmt::Write { self.0.to_css(dest) } } #[derive(Clone, PartialEq)] pub struct SpecifiedValue(pub CSSFloat); pub mod computed_value { use values::CSSFloat; pub type T = CSSFloat; } #[inline] pub fn get_initial_value() -> computed_value::T { 1.0 } impl ToComputedValue for SpecifiedValue { type ComputedValue = computed_value::T; #[inline] fn to_computed_value(&self, _context: &Context) -> computed_value::T { if self.0 < 0.0 { 0.0 } else if self.0 > 1.0 { 1.0 } else { self.0 } } } fn parse(_context: &ParserContext, input: &mut Parser) -> Result<SpecifiedValue, ()> { input.expect_number().map(SpecifiedValue) } </%self:longhand> <%self:longhand name="box-shadow"> use cssparser::{self, ToCss}; use std::fmt; use values::computed::Context; #[derive(Clone, PartialEq)] pub struct SpecifiedValue(Vec<SpecifiedBoxShadow>); #[derive(Clone, PartialEq)] pub struct SpecifiedBoxShadow { pub offset_x: specified::Length, pub offset_y: specified::Length, pub blur_radius: specified::Length, pub spread_radius: specified::Length, pub color: Option<specified::CSSColor>, pub inset: bool, } impl ToCss for SpecifiedValue { fn to_css<W>(&self, dest: &mut W) -> fmt::Result where W: fmt::Write { let mut iter = self.0.iter(); if let Some(shadow) = iter.next() { try!(shadow.to_css(dest)); } else { try!(dest.write_str("none")); return Ok(()) } for shadow in iter { try!(dest.write_str(", ")); try!(shadow.to_css(dest)); } Ok(()) } } impl ToCss for SpecifiedBoxShadow { fn to_css<W>(&self, dest: &mut W) -> fmt::Result where W: fmt::Write { if self.inset { try!(dest.write_str("inset ")); } try!(self.blur_radius.to_css(dest)); try!(dest.write_str(" ")); try!(self.spread_radius.to_css(dest)); try!(dest.write_str(" ")); try!(self.offset_x.to_css(dest)); try!(dest.write_str(" ")); try!(self.offset_y.to_css(dest)); if let Some(ref color) = self.color { try!(dest.write_str(" ")); try!(color.to_css(dest)); } Ok(()) } } pub mod computed_value { use std::fmt; use util::geometry::Au; use values::computed; #[derive(Clone, PartialEq, HeapSizeOf)] pub struct T(pub Vec<BoxShadow>); #[derive(Clone, PartialEq, Copy, HeapSizeOf)] pub struct BoxShadow { pub offset_x: Au, pub offset_y: Au, pub blur_radius: Au, pub spread_radius: Au, pub color: computed::CSSColor, pub inset: bool, } impl fmt::Debug for BoxShadow { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { if self.inset { let _ = write!(f, "inset "); } let _ = write!(f, "{:?} {:?} {:?} {:?} {:?}", self.offset_x, self.offset_y, self.blur_radius, self.spread_radius, self.color); Ok(()) } } } impl ToCss for computed_value::T { fn to_css<W>(&self, dest: &mut W) -> fmt::Result where W: fmt::Write { let mut iter = self.0.iter(); if let Some(shadow) = iter.next() { try!(shadow.to_css(dest)); } else { try!(dest.write_str("none")); return Ok(()) } for shadow in iter { try!(dest.write_str(", ")); try!(shadow.to_css(dest)); } Ok(()) } } impl ToCss for computed_value::BoxShadow { fn to_css<W>(&self, dest: &mut W) -> fmt::Result where W: fmt::Write { if self.inset { try!(dest.write_str("inset ")); } try!(self.blur_radius.to_css(dest)); try!(dest.write_str(" ")); try!(self.spread_radius.to_css(dest)); try!(dest.write_str(" ")); try!(self.offset_x.to_css(dest)); try!(dest.write_str(" ")); try!(self.offset_y.to_css(dest)); try!(dest.write_str(" ")); try!(self.color.to_css(dest)); Ok(()) } } #[inline] pub fn get_initial_value() -> computed_value::T { computed_value::T(Vec::new()) } pub fn parse(_context: &ParserContext, input: &mut Parser) -> Result<SpecifiedValue, ()> { if input.try(|input| input.expect_ident_matching("none")).is_ok() { Ok(SpecifiedValue(Vec::new())) } else { input.parse_comma_separated(parse_one_box_shadow).map(SpecifiedValue) } } impl ToComputedValue for SpecifiedValue { type ComputedValue = computed_value::T; #[inline] fn to_computed_value(&self, context: &Context) -> computed_value::T { computed_value::T(self.0.iter().map(|value| compute_one_box_shadow(value, context)).collect()) } } pub fn compute_one_box_shadow(value: &SpecifiedBoxShadow, context: &computed::Context) -> computed_value::BoxShadow { computed_value::BoxShadow { offset_x: value.offset_x.to_computed_value(context), offset_y: value.offset_y.to_computed_value(context), blur_radius: value.blur_radius.to_computed_value(context), spread_radius: value.spread_radius.to_computed_value(context), color: value.color .as_ref() .map(|color| color.parsed) .unwrap_or(cssparser::Color::CurrentColor), inset: value.inset, } } pub fn parse_one_box_shadow(input: &mut Parser) -> Result<SpecifiedBoxShadow, ()> { use util::geometry::Au; let mut lengths = [specified::Length::Absolute(Au(0)); 4]; let mut lengths_parsed = false; let mut color = None; let mut inset = false; loop { if !inset { if input.try(|input| input.expect_ident_matching("inset")).is_ok() { inset = true; continue } } if !lengths_parsed { if let Ok(value) = input.try(specified::Length::parse) { lengths[0] = value; let mut length_parsed_count = 1; while length_parsed_count < 4 { if let Ok(value) = input.try(specified::Length::parse) { lengths[length_parsed_count] = value } else { break } length_parsed_count += 1; } // The first two lengths must be specified. if length_parsed_count < 2 { return Err(()) } lengths_parsed = true; continue } } if color.is_none() { if let Ok(value) = input.try(specified::CSSColor::parse) { color = Some(value); continue } } break } // Lengths must be specified. if !lengths_parsed { return Err(()) } Ok(SpecifiedBoxShadow { offset_x: lengths[0], offset_y: lengths[1], blur_radius: lengths[2], spread_radius: lengths[3], color: color, inset: inset, }) } </%self:longhand> <%self:longhand name="clip"> use cssparser::ToCss; use std::fmt; // NB: `top` and `left` are 0 if `auto` per CSS 2.1 11.1.2. use values::computed::Context; pub mod computed_value { use util::geometry::Au; #[derive(Clone, PartialEq, Eq, Copy, Debug, HeapSizeOf)] pub struct ClipRect { pub top: Au, pub right: Option<Au>, pub bottom: Option<Au>, pub left: Au, } #[derive(Clone, PartialEq, HeapSizeOf)] pub struct T(pub Option<ClipRect>); } impl ToCss for computed_value::T { fn to_css<W>(&self, dest: &mut W) -> fmt::Result where W: fmt::Write { match self.0 { None => dest.write_str("auto"), Some(rect) => { try!(dest.write_str("rect(")); try!(rect.top.to_css(dest)); try!(dest.write_str(", ")); if let Some(right) = rect.right { try!(right.to_css(dest)); try!(dest.write_str(", ")); } else { try!(dest.write_str("auto, ")); } if let Some(bottom) = rect.bottom { try!(bottom.to_css(dest)); try!(dest.write_str(", ")); } else { try!(dest.write_str("auto, ")); } try!(rect.left.to_css(dest)); try!(dest.write_str(")")); Ok(()) } } } } #[derive(Clone, Debug, PartialEq, Copy)] pub struct SpecifiedClipRect { pub top: specified::Length, pub right: Option<specified::Length>, pub bottom: Option<specified::Length>, pub left: specified::Length, } #[derive(Clone, Debug, PartialEq, Copy)] pub struct SpecifiedValue(Option<SpecifiedClipRect>); impl ToCss for SpecifiedClipRect { fn to_css<W>(&self, dest: &mut W) -> fmt::Result where W: fmt::Write { try!(dest.write_str("rect(")); try!(self.top.to_css(dest)); try!(dest.write_str(", ")); if let Some(right) = self.right { try!(right.to_css(dest)); try!(dest.write_str(", ")); } else { try!(dest.write_str("auto, ")); } if let Some(bottom) = self.bottom { try!(bottom.to_css(dest)); try!(dest.write_str(", ")); } else { try!(dest.write_str("auto, ")); } try!(self.left.to_css(dest)); try!(dest.write_str(")")); Ok(()) } } impl ToCss for SpecifiedValue { fn to_css<W>(&self, dest: &mut W) -> fmt::Result where W: fmt::Write { if let Some(ref rect) = self.0 { rect.to_css(dest) } else { dest.write_str("auto") } } } #[inline] pub fn get_initial_value() -> computed_value::T { computed_value::T(None) } impl ToComputedValue for SpecifiedValue { type ComputedValue = computed_value::T; #[inline] fn to_computed_value(&self, context: &Context) -> computed_value::T { computed_value::T(self.0.map(|value| computed_value::ClipRect { top: value.top.to_computed_value(context), right: value.right.map(|right| right.to_computed_value(context)), bottom: value.bottom.map(|bottom| bottom.to_computed_value(context)), left: value.left.to_computed_value(context), })) } } pub fn parse(_context: &ParserContext, input: &mut Parser) -> Result<SpecifiedValue, ()> { use std::ascii::AsciiExt; use util::geometry::Au; use values::specified::Length; if input.try(|input| input.expect_ident_matching("auto")).is_ok() { return Ok(SpecifiedValue(None)) } if !try!(input.expect_function()).eq_ignore_ascii_case("rect") { return Err(()) } let sides = try!(input.parse_nested_block(|input| { input.parse_comma_separated(|input| { if input.try(|input| input.expect_ident_matching("auto")).is_ok() { Ok(None) } else { Length::parse(input).map(Some) } }) })); if sides.len() == 4 { Ok(SpecifiedValue(Some(SpecifiedClipRect { top: sides[0].unwrap_or(Length::Absolute(Au(0))), right: sides[1], bottom: sides[2], left: sides[3].unwrap_or(Length::Absolute(Au(0))), }))) } else { Err(()) } } </%self:longhand> <%self:longhand name="text-shadow"> use cssparser::{self, ToCss}; use std::fmt; use values::computed::Context; #[derive(Clone, PartialEq)] pub struct SpecifiedValue(Vec<SpecifiedTextShadow>); #[derive(Clone, PartialEq)] pub struct SpecifiedTextShadow { pub offset_x: specified::Length, pub offset_y: specified::Length, pub blur_radius: specified::Length, pub color: Option<specified::CSSColor>, } impl fmt::Debug for SpecifiedTextShadow { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { let _ = write!(f, "{:?} {:?} {:?}", self.offset_x, self.offset_y, self.blur_radius); if let Some(ref color) = self.color { let _ = write!(f, "{:?}", color); } Ok(()) } } pub mod computed_value { use cssparser::Color; use util::geometry::Au; #[derive(Clone, PartialEq, Debug, HeapSizeOf)] pub struct T(pub Vec<TextShadow>); #[derive(Clone, PartialEq, Debug, HeapSizeOf)] pub struct TextShadow { pub offset_x: Au, pub offset_y: Au, pub blur_radius: Au, pub color: Color, } } impl ToCss for computed_value::T { fn to_css<W>(&self, dest: &mut W) -> fmt::Result where W: fmt::Write { let mut iter = self.0.iter(); if let Some(shadow) = iter.next() { try!(shadow.to_css(dest)); } else { try!(dest.write_str("none")); return Ok(()) } for shadow in iter { try!(dest.write_str(", ")); try!(shadow.to_css(dest)); } Ok(()) } } impl ToCss for computed_value::TextShadow { fn to_css<W>(&self, dest: &mut W) -> fmt::Result where W: fmt::Write { try!(self.offset_x.to_css(dest)); try!(dest.write_str(" ")); try!(self.offset_y.to_css(dest)); try!(dest.write_str(" ")); try!(self.blur_radius.to_css(dest)); try!(dest.write_str(" ")); try!(self.color.to_css(dest)); Ok(()) } } impl ToCss for SpecifiedValue { fn to_css<W>(&self, dest: &mut W) -> fmt::Result where W: fmt::Write { let mut iter = self.0.iter(); if let Some(shadow) = iter.next() { try!(shadow.to_css(dest)); } else { try!(dest.write_str("none")); return Ok(()) } for shadow in iter { try!(dest.write_str(", ")); try!(shadow.to_css(dest)); } Ok(()) } } impl ToCss for SpecifiedTextShadow { fn to_css<W>(&self, dest: &mut W) -> fmt::Result where W: fmt::Write { try!(self.offset_x.to_css(dest)); try!(dest.write_str(" ")); try!(self.offset_y.to_css(dest)); try!(dest.write_str(" ")); try!(self.blur_radius.to_css(dest)); if let Some(ref color) = self.color { try!(dest.write_str(" ")); try!(color.to_css(dest)); } Ok(()) } } #[inline] pub fn get_initial_value() -> computed_value::T { computed_value::T(Vec::new()) } pub fn parse(_: &ParserContext, input: &mut Parser) -> Result<SpecifiedValue,()> { if input.try(|input| input.expect_ident_matching("none")).is_ok() { Ok(SpecifiedValue(Vec::new())) } else { input.parse_comma_separated(parse_one_text_shadow).map(SpecifiedValue) } } fn parse_one_text_shadow(input: &mut Parser) -> Result<SpecifiedTextShadow,()> { use util::geometry::Au; let mut lengths = [specified::Length::Absolute(Au(0)); 3]; let mut lengths_parsed = false; let mut color = None; loop { if !lengths_parsed { if let Ok(value) = input.try(specified::Length::parse) { lengths[0] = value; let mut length_parsed_count = 1; while length_parsed_count < 3 { if let Ok(value) = input.try(specified::Length::parse) { lengths[length_parsed_count] = value } else { break } length_parsed_count += 1; } // The first two lengths must be specified. if length_parsed_count < 2 { return Err(()) } lengths_parsed = true; continue } } if color.is_none() { if let Ok(value) = input.try(specified::CSSColor::parse) { color = Some(value); continue } } break } // Lengths must be specified. if !lengths_parsed { return Err(()) } Ok(SpecifiedTextShadow { offset_x: lengths[0], offset_y: lengths[1], blur_radius: lengths[2], color: color, }) } impl ToComputedValue for SpecifiedValue { type ComputedValue = computed_value::T; fn to_computed_value(&self, context: &computed::Context) -> computed_value::T { computed_value::T(self.0.iter().map(|value| { computed_value::TextShadow { offset_x: value.offset_x.to_computed_value(context), offset_y: value.offset_y.to_computed_value(context), blur_radius: value.blur_radius.to_computed_value(context), color: value.color .as_ref() .map(|color| color.parsed) .unwrap_or(cssparser::Color::CurrentColor), } }).collect()) } } </%self:longhand> <%self:longhand name="filter"> //pub use self::computed_value::T as SpecifiedValue; use cssparser::ToCss; use std::fmt; use values::CSSFloat; use values::specified::{Angle, Length}; #[derive(Clone, PartialEq)] pub struct SpecifiedValue(Vec<SpecifiedFilter>); // TODO(pcwalton): `drop-shadow` #[derive(Clone, PartialEq, Debug)] pub enum SpecifiedFilter { Blur(Length), Brightness(CSSFloat), Contrast(CSSFloat), Grayscale(CSSFloat), HueRotate(Angle), Invert(CSSFloat), Opacity(CSSFloat), Saturate(CSSFloat), Sepia(CSSFloat), } pub mod computed_value { use util::geometry::Au; use values::CSSFloat; use values::specified::{Angle}; #[derive(Clone, PartialEq, Debug, HeapSizeOf, Deserialize, Serialize)] pub enum Filter { Blur(Au), Brightness(CSSFloat), Contrast(CSSFloat), Grayscale(CSSFloat), HueRotate(Angle), Invert(CSSFloat), Opacity(CSSFloat), Saturate(CSSFloat), Sepia(CSSFloat), } #[derive(Clone, PartialEq, Debug, HeapSizeOf, Deserialize, Serialize)] pub struct T { pub filters: Vec<Filter> } impl T { /// Creates a new filter pipeline. #[inline] pub fn new(filters: Vec<Filter>) -> T { T { filters: filters, } } /// Adds a new filter to the filter pipeline. #[inline] pub fn push(&mut self, filter: Filter) { self.filters.push(filter) } /// Returns true if this filter pipeline is empty and false otherwise. #[inline] pub fn is_empty(&self) -> bool { self.filters.is_empty() } /// Returns the resulting opacity of this filter pipeline. #[inline] pub fn opacity(&self) -> CSSFloat { let mut opacity = 1.0; for filter in &self.filters { if let Filter::Opacity(ref opacity_value) = *filter { opacity *= *opacity_value } } opacity } } } impl ToCss for computed_value::T { fn to_css<W>(&self, dest: &mut W) -> fmt::Result where W: fmt::Write { let mut iter = self.filters.iter(); if let Some(filter) = iter.next() { try!(filter.to_css(dest)); } else { try!(dest.write_str("none")); return Ok(()) } for filter in iter { try!(dest.write_str(" ")); try!(filter.to_css(dest)); } Ok(()) } } impl ToCss for SpecifiedValue { fn to_css<W>(&self, dest: &mut W) -> fmt::Result where W: fmt::Write { let mut iter = self.0.iter(); if let Some(filter) = iter.next() { try!(filter.to_css(dest)); } else { try!(dest.write_str("none")); return Ok(()) } for filter in iter { try!(dest.write_str(" ")); try!(filter.to_css(dest)); } Ok(()) } } impl ToCss for computed_value::Filter { fn to_css<W>(&self, dest: &mut W) -> fmt::Result where W: fmt::Write { match *self { computed_value::Filter::Blur(value) => { try!(dest.write_str("blur(")); try!(value.to_css(dest)); try!(dest.write_str(")")); } computed_value::Filter::Brightness(value) => try!(write!(dest, "brightness({})", value)), computed_value::Filter::Contrast(value) => try!(write!(dest, "contrast({})", value)), computed_value::Filter::Grayscale(value) => try!(write!(dest, "grayscale({})", value)), computed_value::Filter::HueRotate(value) => { try!(dest.write_str("hue-rotate(")); try!(value.to_css(dest)); try!(dest.write_str(")")); } computed_value::Filter::Invert(value) => try!(write!(dest, "invert({})", value)), computed_value::Filter::Opacity(value) => try!(write!(dest, "opacity({})", value)), computed_value::Filter::Saturate(value) => try!(write!(dest, "saturate({})", value)), computed_value::Filter::Sepia(value) => try!(write!(dest, "sepia({})", value)), } Ok(()) } } impl ToCss for SpecifiedFilter { fn to_css<W>(&self, dest: &mut W) -> fmt::Result where W: fmt::Write { match *self { SpecifiedFilter::Blur(value) => { try!(dest.write_str("blur(")); try!(value.to_css(dest)); try!(dest.write_str(")")); } SpecifiedFilter::Brightness(value) => try!(write!(dest, "brightness({})", value)), SpecifiedFilter::Contrast(value) => try!(write!(dest, "contrast({})", value)), SpecifiedFilter::Grayscale(value) => try!(write!(dest, "grayscale({})", value)), SpecifiedFilter::HueRotate(value) => { try!(dest.write_str("hue-rotate(")); try!(value.to_css(dest)); try!(dest.write_str(")")); } SpecifiedFilter::Invert(value) => try!(write!(dest, "invert({})", value)), SpecifiedFilter::Opacity(value) => try!(write!(dest, "opacity({})", value)), SpecifiedFilter::Saturate(value) => try!(write!(dest, "saturate({})", value)), SpecifiedFilter::Sepia(value) => try!(write!(dest, "sepia({})", value)), } Ok(()) } } #[inline] pub fn get_initial_value() -> computed_value::T { computed_value::T::new(Vec::new()) } pub fn parse(_context: &ParserContext, input: &mut Parser) -> Result<SpecifiedValue, ()> { let mut filters = Vec::new(); if input.try(|input| input.expect_ident_matching("none")).is_ok() { return Ok(SpecifiedValue(filters)) } loop { if let Ok(function_name) = input.try(|input| input.expect_function()) { filters.push(try!(input.parse_nested_block(|input| { match_ignore_ascii_case! { function_name, "blur" => specified::Length::parse_non_negative(input).map(SpecifiedFilter::Blur), "brightness" => parse_factor(input).map(SpecifiedFilter::Brightness), "contrast" => parse_factor(input).map(SpecifiedFilter::Contrast), "grayscale" => parse_factor(input).map(SpecifiedFilter::Grayscale), "hue-rotate" => Angle::parse(input).map(SpecifiedFilter::HueRotate), "invert" => parse_factor(input).map(SpecifiedFilter::Invert), "opacity" => parse_factor(input).map(SpecifiedFilter::Opacity), "saturate" => parse_factor(input).map(SpecifiedFilter::Saturate), "sepia" => parse_factor(input).map(SpecifiedFilter::Sepia) _ => Err(()) } }))); } else if filters.is_empty() { return Err(()) } else { return Ok(SpecifiedValue(filters)) } } } fn parse_factor(input: &mut Parser) -> Result<::values::CSSFloat, ()> { use cssparser::Token; match input.next() { Ok(Token::Number(value)) => Ok(value.value), Ok(Token::Percentage(value)) => Ok(value.unit_value), _ => Err(()) } } impl ToComputedValue for SpecifiedValue { type ComputedValue = computed_value::T; fn to_computed_value(&self, context: &computed::Context) -> computed_value::T { computed_value::T{ filters: self.0.iter().map(|value| { match *value { SpecifiedFilter::Blur(factor) => computed_value::Filter::Blur(factor.to_computed_value(context)), SpecifiedFilter::Brightness(factor) => computed_value::Filter::Brightness(factor), SpecifiedFilter::Contrast(factor) => computed_value::Filter::Contrast(factor), SpecifiedFilter::Grayscale(factor) => computed_value::Filter::Grayscale(factor), SpecifiedFilter::HueRotate(factor) => computed_value::Filter::HueRotate(factor), SpecifiedFilter::Invert(factor) => computed_value::Filter::Invert(factor), SpecifiedFilter::Opacity(factor) => computed_value::Filter::Opacity(factor), SpecifiedFilter::Saturate(factor) => computed_value::Filter::Saturate(factor), SpecifiedFilter::Sepia(factor) => computed_value::Filter::Sepia(factor), } }).collect() } } } </%self:longhand> <%self:longhand name="transform"> use values::CSSFloat; use values::computed::Context; use cssparser::ToCss; use std::fmt; use util::geometry::Au; pub mod computed_value { use values::CSSFloat; use values::computed; #[derive(Clone, Copy, Debug, PartialEq, HeapSizeOf)] pub struct ComputedMatrix { pub m11: CSSFloat, pub m12: CSSFloat, pub m13: CSSFloat, pub m14: CSSFloat, pub m21: CSSFloat, pub m22: CSSFloat, pub m23: CSSFloat, pub m24: CSSFloat, pub m31: CSSFloat, pub m32: CSSFloat, pub m33: CSSFloat, pub m34: CSSFloat, pub m41: CSSFloat, pub m42: CSSFloat, pub m43: CSSFloat, pub m44: CSSFloat, } impl ComputedMatrix { pub fn identity() -> ComputedMatrix { ComputedMatrix { m11: 1.0, m12: 0.0, m13: 0.0, m14: 0.0, m21: 0.0, m22: 1.0, m23: 0.0, m24: 0.0, m31: 0.0, m32: 0.0, m33: 1.0, m34: 0.0, m41: 0.0, m42: 0.0, m43: 0.0, m44: 1.0 } } } #[derive(Clone, Debug, PartialEq, HeapSizeOf)] pub enum ComputedOperation { Matrix(ComputedMatrix), Skew(computed::Angle, computed::Angle), Translate(computed::LengthOrPercentage, computed::LengthOrPercentage, computed::Length), Scale(CSSFloat, CSSFloat, CSSFloat), Rotate(CSSFloat, CSSFloat, CSSFloat, computed::Angle), Perspective(computed::Length), } #[derive(Clone, Debug, PartialEq, HeapSizeOf)] pub struct T(pub Option<Vec<ComputedOperation>>); } pub use self::computed_value::ComputedMatrix as SpecifiedMatrix; fn parse_two_lengths_or_percentages(input: &mut Parser) -> Result<(specified::LengthOrPercentage, specified::LengthOrPercentage),()> { let first = try!(specified::LengthOrPercentage::parse(input)); let second = input.try(|input| { try!(input.expect_comma()); specified::LengthOrPercentage::parse(input) }).unwrap_or(specified::LengthOrPercentage::zero()); Ok((first, second)) } fn parse_two_floats(input: &mut Parser) -> Result<(CSSFloat,CSSFloat),()> { let first = try!(input.expect_number()); let second = input.try(|input| { try!(input.expect_comma()); input.expect_number() }).unwrap_or(first); Ok((first, second)) } fn parse_two_angles(input: &mut Parser) -> Result<(specified::Angle, specified::Angle),()> { let first = try!(specified::Angle::parse(input)); let second = input.try(|input| { try!(input.expect_comma()); specified::Angle::parse(input) }).unwrap_or(specified::Angle(0.0)); Ok((first, second)) } #[derive(Copy, Clone, Debug, PartialEq)] enum TranslateKind { Translate, TranslateX, TranslateY, TranslateZ, Translate3D, } #[derive(Clone, Debug, PartialEq)] enum SpecifiedOperation { Matrix(SpecifiedMatrix), Skew(specified::Angle, specified::Angle), Translate(TranslateKind, specified::LengthOrPercentage, specified::LengthOrPercentage, specified::Length), Scale(CSSFloat, CSSFloat, CSSFloat), Rotate(CSSFloat, CSSFloat, CSSFloat, specified::Angle), Perspective(specified::Length), } impl ToCss for computed_value::T { fn to_css<W>(&self, _: &mut W) -> fmt::Result where W: fmt::Write { // TODO(pcwalton) Ok(()) } } impl ToCss for SpecifiedOperation { fn to_css<W>(&self, dest: &mut W) -> fmt::Result where W: fmt::Write { match *self { // todo(gw): implement serialization for transform // types other than translate. SpecifiedOperation::Matrix(_m) => { Ok(()) } SpecifiedOperation::Skew(_sx, _sy) => { Ok(()) } SpecifiedOperation::Translate(kind, tx, ty, tz) => { match kind { TranslateKind::Translate => { try!(dest.write_str("translate(")); try!(tx.to_css(dest)); try!(dest.write_str(", ")); try!(ty.to_css(dest)); dest.write_str(")") } TranslateKind::TranslateX => { try!(dest.write_str("translateX(")); try!(tx.to_css(dest)); dest.write_str(")") } TranslateKind::TranslateY => { try!(dest.write_str("translateY(")); try!(ty.to_css(dest)); dest.write_str(")") } TranslateKind::TranslateZ => { try!(dest.write_str("translateZ(")); try!(tz.to_css(dest)); dest.write_str(")") } TranslateKind::Translate3D => { try!(dest.write_str("translate3d(")); try!(tx.to_css(dest)); try!(dest.write_str(", ")); try!(ty.to_css(dest)); try!(dest.write_str(", ")); try!(tz.to_css(dest)); dest.write_str(")") } } } SpecifiedOperation::Scale(_sx, _sy, _sz) => { Ok(()) } SpecifiedOperation::Rotate(_ax, _ay, _az, _angle) => { Ok(()) } SpecifiedOperation::Perspective(_p) => { Ok(()) } } } } #[derive(Clone, Debug, PartialEq)] pub struct SpecifiedValue(Vec<SpecifiedOperation>); impl ToCss for SpecifiedValue { fn to_css<W>(&self, dest: &mut W) -> fmt::Result where W: fmt::Write { let mut first = true; for operation in &self.0 { if !first { try!(dest.write_str(" ")); } first = false; try!(operation.to_css(dest)) } Ok(()) } } #[inline] pub fn get_initial_value() -> computed_value::T { computed_value::T(None) } pub fn parse(_: &ParserContext, input: &mut Parser) -> Result<SpecifiedValue,()> { if input.try(|input| input.expect_ident_matching("none")).is_ok() { return Ok(SpecifiedValue(Vec::new())) } let mut result = Vec::new(); loop { let name = match input.expect_function() { Ok(name) => name, Err(_) => break, }; match_ignore_ascii_case! { name, "matrix" => { try!(input.parse_nested_block(|input| { let values = try!(input.parse_comma_separated(|input| { input.expect_number() })); if values.len() != 6 { return Err(()) } result.push(SpecifiedOperation::Matrix( SpecifiedMatrix { m11: values[0], m12: values[1], m13: 0.0, m14: 0.0, m21: values[2], m22: values[3], m23: 0.0, m24: 0.0, m31: 0.0, m32: 0.0, m33: 1.0, m34: 0.0, m41: values[4], m42: values[5], m43: 0.0, m44: 1.0 })); Ok(()) })) }, "matrix3d" => { try!(input.parse_nested_block(|input| { let values = try!(input.parse_comma_separated(|input| { input.expect_number() })); if values.len() != 16 { return Err(()) } result.push(SpecifiedOperation::Matrix( SpecifiedMatrix { m11: values[ 0], m12: values[ 1], m13: values[ 2], m14: values[ 3], m21: values[ 4], m22: values[ 5], m23: values[ 6], m24: values[ 7], m31: values[ 8], m32: values[ 9], m33: values[10], m34: values[11], m41: values[12], m42: values[13], m43: values[14], m44: values[15] })); Ok(()) })) }, "translate" => { try!(input.parse_nested_block(|input| { let (tx, ty) = try!(parse_two_lengths_or_percentages(input)); result.push(SpecifiedOperation::Translate(TranslateKind::Translate, tx, ty, specified::Length::Absolute(Au(0)))); Ok(()) })) }, "translatex" => { try!(input.parse_nested_block(|input| { let tx = try!(specified::LengthOrPercentage::parse(input)); result.push(SpecifiedOperation::Translate( TranslateKind::TranslateX, tx, specified::LengthOrPercentage::zero(), specified::Length::Absolute(Au(0)))); Ok(()) })) }, "translatey" => { try!(input.parse_nested_block(|input| { let ty = try!(specified::LengthOrPercentage::parse(input)); result.push(SpecifiedOperation::Translate( TranslateKind::TranslateY, specified::LengthOrPercentage::zero(), ty, specified::Length::Absolute(Au(0)))); Ok(()) })) }, "translatez" => { try!(input.parse_nested_block(|input| { let tz = try!(specified::Length::parse(input)); result.push(SpecifiedOperation::Translate( TranslateKind::TranslateZ, specified::LengthOrPercentage::zero(), specified::LengthOrPercentage::zero(), tz)); Ok(()) })) }, "translate3d" => { try!(input.parse_nested_block(|input| { let tx = try!(specified::LengthOrPercentage::parse(input)); try!(input.expect_comma()); let ty = try!(specified::LengthOrPercentage::parse(input)); try!(input.expect_comma()); let tz = try!(specified::Length::parse(input)); result.push(SpecifiedOperation::Translate( TranslateKind::Translate3D, tx, ty, tz)); Ok(()) })) }, "scale" => { try!(input.parse_nested_block(|input| { let (sx, sy) = try!(parse_two_floats(input)); result.push(SpecifiedOperation::Scale(sx, sy, 1.0)); Ok(()) })) }, "scalex" => { try!(input.parse_nested_block(|input| { let sx = try!(input.expect_number()); result.push(SpecifiedOperation::Scale(sx, 1.0, 1.0)); Ok(()) })) }, "scaley" => { try!(input.parse_nested_block(|input| { let sy = try!(input.expect_number()); result.push(SpecifiedOperation::Scale(1.0, sy, 1.0)); Ok(()) })) }, "scalez" => { try!(input.parse_nested_block(|input| { let sz = try!(input.expect_number()); result.push(SpecifiedOperation::Scale(1.0, 1.0, sz)); Ok(()) })) }, "scale3d" => { try!(input.parse_nested_block(|input| { let sx = try!(input.expect_number()); try!(input.expect_comma()); let sy = try!(input.expect_number()); try!(input.expect_comma()); let sz = try!(input.expect_number()); result.push(SpecifiedOperation::Scale(sx, sy, sz)); Ok(()) })) }, "rotate" => { try!(input.parse_nested_block(|input| { let theta = try!(specified::Angle::parse(input)); result.push(SpecifiedOperation::Rotate(0.0, 0.0, 1.0, theta)); Ok(()) })) }, "rotatex" => { try!(input.parse_nested_block(|input| { let theta = try!(specified::Angle::parse(input)); result.push(SpecifiedOperation::Rotate(1.0, 0.0, 0.0, theta)); Ok(()) })) }, "rotatey" => { try!(input.parse_nested_block(|input| { let theta = try!(specified::Angle::parse(input)); result.push(SpecifiedOperation::Rotate(0.0, 1.0, 0.0, theta)); Ok(()) })) }, "rotatez" => { try!(input.parse_nested_block(|input| { let theta = try!(specified::Angle::parse(input)); result.push(SpecifiedOperation::Rotate(0.0, 0.0, 1.0, theta)); Ok(()) })) }, "rotate3d" => { try!(input.parse_nested_block(|input| { let ax = try!(input.expect_number()); try!(input.expect_comma()); let ay = try!(input.expect_number()); try!(input.expect_comma()); let az = try!(input.expect_number()); try!(input.expect_comma()); let theta = try!(specified::Angle::parse(input)); // TODO(gw): Check the axis can be normalized!! result.push(SpecifiedOperation::Rotate(ax, ay, az, theta)); Ok(()) })) }, "skew" => { try!(input.parse_nested_block(|input| { let (theta_x, theta_y) = try!(parse_two_angles(input)); result.push(SpecifiedOperation::Skew(theta_x, theta_y)); Ok(()) })) }, "skewx" => { try!(input.parse_nested_block(|input| { let theta_x = try!(specified::Angle::parse(input)); result.push(SpecifiedOperation::Skew(theta_x, specified::Angle(0.0))); Ok(()) })) }, "skewy" => { try!(input.parse_nested_block(|input| { let theta_y = try!(specified::Angle::parse(input)); result.push(SpecifiedOperation::Skew(specified::Angle(0.0), theta_y)); Ok(()) })) }, "perspective" => { try!(input.parse_nested_block(|input| { let d = try!(specified::Length::parse(input)); result.push(SpecifiedOperation::Perspective(d)); Ok(()) })) } _ => return Err(()) } } if !result.is_empty() { Ok(SpecifiedValue(result)) } else { Err(()) } } impl ToComputedValue for SpecifiedValue { type ComputedValue = computed_value::T; #[inline] fn to_computed_value(&self, context: &Context) -> computed_value::T { if self.0.is_empty() { return computed_value::T(None) } let mut result = vec!(); for operation in &self.0 { match *operation { SpecifiedOperation::Matrix(ref matrix) => { result.push(computed_value::ComputedOperation::Matrix(*matrix)); } SpecifiedOperation::Translate(_, ref tx, ref ty, ref tz) => { result.push(computed_value::ComputedOperation::Translate(tx.to_computed_value(context), ty.to_computed_value(context), tz.to_computed_value(context))); } SpecifiedOperation::Scale(sx, sy, sz) => { result.push(computed_value::ComputedOperation::Scale(sx, sy, sz)); } SpecifiedOperation::Rotate(ax, ay, az, theta) => { result.push(computed_value::ComputedOperation::Rotate(ax, ay, az, theta)); } SpecifiedOperation::Skew(theta_x, theta_y) => { result.push(computed_value::ComputedOperation::Skew(theta_x, theta_y)); } SpecifiedOperation::Perspective(d) => { result.push(computed_value::ComputedOperation::Perspective(d.to_computed_value(context))); } }; } computed_value::T(Some(result)) } } </%self:longhand> pub struct OriginParseResult { horizontal: Option<specified::LengthOrPercentage>, vertical: Option<specified::LengthOrPercentage>, depth: Option<specified::Length> } pub fn parse_origin(_: &ParserContext, input: &mut Parser) -> Result<OriginParseResult,()> { use values::specified::{LengthOrPercentage, Percentage}; let (mut horizontal, mut vertical, mut depth) = (None, None, None); loop { if let Err(_) = input.try(|input| { let token = try!(input.expect_ident()); match_ignore_ascii_case! { token, "left" => { if horizontal.is_none() { horizontal = Some(LengthOrPercentage::Percentage(Percentage(0.0))) } else { return Err(()) } }, "center" => { if horizontal.is_none() { horizontal = Some(LengthOrPercentage::Percentage(Percentage(0.5))) } else if vertical.is_none() { vertical = Some(LengthOrPercentage::Percentage(Percentage(0.5))) } else { return Err(()) } }, "right" => { if horizontal.is_none() { horizontal = Some(LengthOrPercentage::Percentage(Percentage(1.0))) } else { return Err(()) } }, "top" => { if vertical.is_none() { vertical = Some(LengthOrPercentage::Percentage(Percentage(0.0))) } else { return Err(()) } }, "bottom" => { if vertical.is_none() { vertical = Some(LengthOrPercentage::Percentage(Percentage(1.0))) } else { return Err(()) } } _ => return Err(()) } Ok(()) }) { match LengthOrPercentage::parse(input) { Ok(value) => { if horizontal.is_none() { horizontal = Some(value); } else if vertical.is_none() { vertical = Some(value); } else if let LengthOrPercentage::Length(length) = value { depth = Some(length); } else { break; } } _ => break, } } } if horizontal.is_some() || vertical.is_some() { Ok(OriginParseResult { horizontal: horizontal, vertical: vertical, depth: depth, }) } else { Err(()) } } ${single_keyword("backface-visibility", "visible hidden")} ${single_keyword("transform-style", "auto flat preserve-3d")} <%self:longhand name="transform-origin"> use values::computed::Context; use values::specified::{Length, LengthOrPercentage, Percentage}; use cssparser::ToCss; use std::fmt; use util::geometry::Au; pub mod computed_value { use values::computed::{Length, LengthOrPercentage}; #[derive(Clone, Copy, Debug, PartialEq, HeapSizeOf)] pub struct T { pub horizontal: LengthOrPercentage, pub vertical: LengthOrPercentage, pub depth: Length, } } #[derive(Clone, Copy, Debug, PartialEq)] pub struct SpecifiedValue { horizontal: LengthOrPercentage, vertical: LengthOrPercentage, depth: Length, } impl ToCss for computed_value::T { fn to_css<W>(&self, dest: &mut W) -> fmt::Result where W: fmt::Write { try!(self.horizontal.to_css(dest)); try!(dest.write_str(" ")); try!(self.vertical.to_css(dest)); try!(dest.write_str(" ")); self.depth.to_css(dest) } } impl ToCss for SpecifiedValue { fn to_css<W>(&self, dest: &mut W) -> fmt::Result where W: fmt::Write { try!(self.horizontal.to_css(dest)); try!(dest.write_str(" ")); try!(self.vertical.to_css(dest)); try!(dest.write_str(" ")); self.depth.to_css(dest) } } #[inline] pub fn get_initial_value() -> computed_value::T { computed_value::T { horizontal: computed::LengthOrPercentage::Percentage(0.5), vertical: computed::LengthOrPercentage::Percentage(0.5), depth: Au(0), } } pub fn parse(context: &ParserContext, input: &mut Parser) -> Result<SpecifiedValue,()> { let result = try!(super::parse_origin(context, input)); Ok(SpecifiedValue { horizontal: result.horizontal.unwrap_or(LengthOrPercentage::Percentage(Percentage(0.5))), vertical: result.vertical.unwrap_or(LengthOrPercentage::Percentage(Percentage(0.5))), depth: result.depth.unwrap_or(Length::Absolute(Au(0))), }) } impl ToComputedValue for SpecifiedValue { type ComputedValue = computed_value::T; #[inline] fn to_computed_value(&self, context: &Context) -> computed_value::T { computed_value::T { horizontal: self.horizontal.to_computed_value(context), vertical: self.vertical.to_computed_value(context), depth: self.depth.to_computed_value(context), } } } </%self:longhand> ${predefined_type("perspective", "LengthOrNone", "computed::LengthOrNone::None")} <%self:longhand name="perspective-origin"> use values::computed::Context; use values::specified::{LengthOrPercentage, Percentage}; use cssparser::ToCss; use std::fmt; pub mod computed_value { use values::computed::LengthOrPercentage; #[derive(Clone, Copy, Debug, PartialEq, HeapSizeOf)] pub struct T { pub horizontal: LengthOrPercentage, pub vertical: LengthOrPercentage, } } impl ToCss for computed_value::T { fn to_css<W>(&self, dest: &mut W) -> fmt::Result where W: fmt::Write { try!(self.horizontal.to_css(dest)); try!(dest.write_str(" ")); self.vertical.to_css(dest) } } #[derive(Clone, Copy, Debug, PartialEq)] pub struct SpecifiedValue { horizontal: LengthOrPercentage, vertical: LengthOrPercentage, } impl ToCss for SpecifiedValue { fn to_css<W>(&self, dest: &mut W) -> fmt::Result where W: fmt::Write { try!(self.horizontal.to_css(dest)); try!(dest.write_str(" ")); self.vertical.to_css(dest) } } #[inline] pub fn get_initial_value() -> computed_value::T { computed_value::T { horizontal: computed::LengthOrPercentage::Percentage(0.5), vertical: computed::LengthOrPercentage::Percentage(0.5), } } pub fn parse(context: &ParserContext, input: &mut Parser) -> Result<SpecifiedValue,()> { let result = try!(super::parse_origin(context, input)); match result.depth { Some(_) => Err(()), None => Ok(SpecifiedValue { horizontal: result.horizontal.unwrap_or(LengthOrPercentage::Percentage(Percentage(0.5))), vertical: result.vertical.unwrap_or(LengthOrPercentage::Percentage(Percentage(0.5))), }) } } impl ToComputedValue for SpecifiedValue { type ComputedValue = computed_value::T; #[inline] fn to_computed_value(&self, context: &Context) -> computed_value::T { computed_value::T { horizontal: self.horizontal.to_computed_value(context), vertical: self.vertical.to_computed_value(context), } } } </%self:longhand> ${single_keyword("mix-blend-mode", """normal multiply screen overlay darken lighten color-dodge color-burn hard-light soft-light difference exclusion hue saturation color luminosity""")} <%self:longhand name="image-rendering"> use values::computed::Context; pub mod computed_value { use cssparser::ToCss; use std::fmt; #[derive(Copy, Clone, Debug, PartialEq, HeapSizeOf, Deserialize, Serialize)] pub enum T { Auto, CrispEdges, Pixelated, } impl ToCss for T { fn to_css<W>(&self, dest: &mut W) -> fmt::Result where W: fmt::Write { match *self { T::Auto => dest.write_str("auto"), T::CrispEdges => dest.write_str("crisp-edges"), T::Pixelated => dest.write_str("pixelated"), } } } } pub type SpecifiedValue = computed_value::T; #[inline] pub fn get_initial_value() -> computed_value::T { computed_value::T::Auto } pub fn parse(_: &ParserContext, input: &mut Parser) -> Result<SpecifiedValue,()> { // According to to CSS-IMAGES-3, `optimizespeed` and `optimizequality` are synonyms for // `auto`. match_ignore_ascii_case! { try!(input.expect_ident()), "auto" => Ok(computed_value::T::Auto), "optimizespeed" => Ok(computed_value::T::Auto), "optimizequality" => Ok(computed_value::T::Auto), "crisp-edges" => Ok(computed_value::T::CrispEdges), "pixelated" => Ok(computed_value::T::Pixelated) _ => Err(()) } } impl ToComputedValue for SpecifiedValue { type ComputedValue = computed_value::T; #[inline] fn to_computed_value(&self, _: &Context) -> computed_value::T { *self } } </%self:longhand> ${new_style_struct("Animation", is_inherited=False)} // TODO(pcwalton): Multiple transitions. <%self:longhand name="transition-duration"> use values::specified::Time; pub use self::computed_value::T as SpecifiedValue; pub use values::specified::Time as SingleSpecifiedValue; pub mod computed_value { use cssparser::ToCss; use std::fmt; use values::computed::{Context, ToComputedValue}; pub use values::computed::Time as SingleComputedValue; #[derive(Clone, PartialEq, HeapSizeOf)] pub struct T(pub Vec<SingleComputedValue>); impl ToComputedValue for T { type ComputedValue = T; #[inline] fn to_computed_value(&self, _: &Context) -> T { (*self).clone() } } impl ToCss for T { fn to_css<W>(&self, dest: &mut W) -> fmt::Result where W: fmt::Write { if self.0.is_empty() { return dest.write_str("none") } for (i, value) in self.0.iter().enumerate() { if i != 0 { try!(dest.write_str(", ")) } try!(value.to_css(dest)) } Ok(()) } } } #[inline] pub fn parse_one(input: &mut Parser) -> Result<SingleSpecifiedValue,()> { Time::parse(input) } #[inline] pub fn get_initial_value() -> computed_value::T { computed_value::T(vec![get_initial_single_value()]) } #[inline] pub fn get_initial_single_value() -> Time { Time(0.0) } pub fn parse(_: &ParserContext, input: &mut Parser) -> Result<SpecifiedValue,()> { Ok(SpecifiedValue(try!(input.parse_comma_separated(parse_one)))) } </%self:longhand> // TODO(pcwalton): Lots more timing functions. // TODO(pcwalton): Multiple transitions. <%self:longhand name="transition-timing-function"> use self::computed_value::{StartEnd, TransitionTimingFunction}; use values::computed::Context; use euclid::point::Point2D; pub use self::computed_value::SingleComputedValue as SingleSpecifiedValue; pub use self::computed_value::T as SpecifiedValue; static EASE: TransitionTimingFunction = TransitionTimingFunction::CubicBezier(Point2D { x: 0.25, y: 0.1, }, Point2D { x: 0.25, y: 1.0, }); static LINEAR: TransitionTimingFunction = TransitionTimingFunction::CubicBezier(Point2D { x: 0.0, y: 0.0, }, Point2D { x: 1.0, y: 1.0, }); static EASE_IN: TransitionTimingFunction = TransitionTimingFunction::CubicBezier(Point2D { x: 0.42, y: 0.0, }, Point2D { x: 1.0, y: 1.0, }); static EASE_OUT: TransitionTimingFunction = TransitionTimingFunction::CubicBezier(Point2D { x: 0.0, y: 0.0, }, Point2D { x: 0.58, y: 1.0, }); static EASE_IN_OUT: TransitionTimingFunction = TransitionTimingFunction::CubicBezier(Point2D { x: 0.42, y: 0.0, }, Point2D { x: 0.58, y: 1.0, }); static STEP_START: TransitionTimingFunction = TransitionTimingFunction::Steps(1, StartEnd::Start); static STEP_END: TransitionTimingFunction = TransitionTimingFunction::Steps(1, StartEnd::End); pub mod computed_value { use cssparser::ToCss; use euclid::point::Point2D; use std::fmt; pub use self::TransitionTimingFunction as SingleComputedValue; #[derive(Copy, Clone, Debug, PartialEq, HeapSizeOf)] pub enum TransitionTimingFunction { CubicBezier(Point2D<f32>, Point2D<f32>), Steps(u32, StartEnd), } impl ToCss for TransitionTimingFunction { fn to_css<W>(&self, dest: &mut W) -> fmt::Result where W: fmt::Write { match *self { TransitionTimingFunction::CubicBezier(p1, p2) => { try!(dest.write_str("cubic-bezier(")); try!(p1.x.to_css(dest)); try!(dest.write_str(", ")); try!(p1.y.to_css(dest)); try!(dest.write_str(", ")); try!(p2.x.to_css(dest)); try!(dest.write_str(", ")); try!(p2.y.to_css(dest)); dest.write_str(")") } TransitionTimingFunction::Steps(steps, start_end) => { try!(dest.write_str("steps(")); try!(steps.to_css(dest)); try!(dest.write_str(", ")); try!(start_end.to_css(dest)); dest.write_str(")") } } } } #[derive(Copy, Clone, Debug, PartialEq, HeapSizeOf)] pub enum StartEnd { Start, End, } impl ToCss for StartEnd { fn to_css<W>(&self, dest: &mut W) -> fmt::Result where W: fmt::Write { match *self { StartEnd::Start => dest.write_str("start"), StartEnd::End => dest.write_str("end"), } } } #[derive(Clone, Debug, PartialEq, HeapSizeOf)] pub struct T(pub Vec<TransitionTimingFunction>); impl ToCss for T { fn to_css<W>(&self, dest: &mut W) -> fmt::Result where W: fmt::Write { if self.0.is_empty() { return dest.write_str("none") } for (i, value) in self.0.iter().enumerate() { if i != 0 { try!(dest.write_str(", ")) } try!(value.to_css(dest)) } Ok(()) } } } impl ToComputedValue for SpecifiedValue { type ComputedValue = computed_value::T; #[inline] fn to_computed_value(&self, _: &Context) -> computed_value::T { (*self).clone() } } #[inline] pub fn get_initial_value() -> computed_value::T { computed_value::T(vec![get_initial_single_value()]) } #[inline] pub fn get_initial_single_value() -> TransitionTimingFunction { EASE } pub fn parse_one(input: &mut Parser) -> Result<SingleSpecifiedValue,()> { if let Ok(function_name) = input.try(|input| input.expect_function()) { return match_ignore_ascii_case! { function_name, "cubic-bezier" => { let (mut p1x, mut p1y, mut p2x, mut p2y) = (0.0, 0.0, 0.0, 0.0); try!(input.parse_nested_block(|input| { p1x = try!(input.expect_number()); try!(input.expect_comma()); p1y = try!(input.expect_number()); try!(input.expect_comma()); p2x = try!(input.expect_number()); try!(input.expect_comma()); p2y = try!(input.expect_number()); Ok(()) })); let (p1, p2) = (Point2D::new(p1x, p1y), Point2D::new(p2x, p2y)); Ok(TransitionTimingFunction::CubicBezier(p1, p2)) }, "steps" => { let (mut step_count, mut start_end) = (0, computed_value::StartEnd::Start); try!(input.parse_nested_block(|input| { step_count = try!(input.expect_integer()); try!(input.expect_comma()); start_end = try!(match_ignore_ascii_case! { try!(input.expect_ident()), "start" => Ok(computed_value::StartEnd::Start), "end" => Ok(computed_value::StartEnd::End) _ => Err(()) }); Ok(()) })); Ok(TransitionTimingFunction::Steps(step_count as u32, start_end)) } _ => Err(()) } } match_ignore_ascii_case! { try!(input.expect_ident()), "ease" => Ok(EASE), "linear" => Ok(LINEAR), "ease-in" => Ok(EASE_IN), "ease-out" => Ok(EASE_OUT), "ease-in-out" => Ok(EASE_IN_OUT), "step-start" => Ok(STEP_START), "step-end" => Ok(STEP_END) _ => Err(()) } } pub fn parse(_: &ParserContext, input: &mut Parser) -> Result<SpecifiedValue,()> { Ok(SpecifiedValue(try!(input.parse_comma_separated(parse_one)))) } </%self:longhand> // TODO(pcwalton): Lots more properties. <%self:longhand name="transition-property"> use self::computed_value::TransitionProperty; use values::computed::Context; pub use self::computed_value::SingleComputedValue as SingleSpecifiedValue; pub use self::computed_value::T as SpecifiedValue; pub mod computed_value { use cssparser::ToCss; use std::fmt; pub use self::TransitionProperty as SingleComputedValue; #[derive(Copy, Clone, Debug, PartialEq, HeapSizeOf)] pub enum TransitionProperty { All, BackgroundColor, BackgroundPosition, BorderBottomColor, BorderBottomWidth, BorderLeftColor, BorderLeftWidth, BorderRightColor, BorderRightWidth, BorderSpacing, BorderTopColor, BorderTopWidth, Bottom, Color, Clip, FontSize, FontWeight, Height, Left, LetterSpacing, LineHeight, MarginBottom, MarginLeft, MarginRight, MarginTop, MaxHeight, MaxWidth, MinHeight, MinWidth, Opacity, OutlineColor, OutlineWidth, PaddingBottom, PaddingLeft, PaddingRight, PaddingTop, Right, TextIndent, TextShadow, Top, Transform, VerticalAlign, Visibility, Width, WordSpacing, ZIndex, } pub static ALL_TRANSITION_PROPERTIES: [TransitionProperty; 45] = [ TransitionProperty::BackgroundColor, TransitionProperty::BackgroundPosition, TransitionProperty::BorderBottomColor, TransitionProperty::BorderBottomWidth, TransitionProperty::BorderLeftColor, TransitionProperty::BorderLeftWidth, TransitionProperty::BorderRightColor, TransitionProperty::BorderRightWidth, TransitionProperty::BorderSpacing, TransitionProperty::BorderTopColor, TransitionProperty::BorderTopWidth, TransitionProperty::Bottom, TransitionProperty::Color, TransitionProperty::Clip, TransitionProperty::FontSize, TransitionProperty::FontWeight, TransitionProperty::Height, TransitionProperty::Left, TransitionProperty::LetterSpacing, TransitionProperty::LineHeight, TransitionProperty::MarginBottom, TransitionProperty::MarginLeft, TransitionProperty::MarginRight, TransitionProperty::MarginTop, TransitionProperty::MaxHeight, TransitionProperty::MaxWidth, TransitionProperty::MinHeight, TransitionProperty::MinWidth, TransitionProperty::Opacity, TransitionProperty::OutlineColor, TransitionProperty::OutlineWidth, TransitionProperty::PaddingBottom, TransitionProperty::PaddingLeft, TransitionProperty::PaddingRight, TransitionProperty::PaddingTop, TransitionProperty::Right, TransitionProperty::TextIndent, TransitionProperty::TextShadow, TransitionProperty::Top, TransitionProperty::Transform, TransitionProperty::VerticalAlign, TransitionProperty::Visibility, TransitionProperty::Width, TransitionProperty::WordSpacing, TransitionProperty::ZIndex, ]; impl ToCss for TransitionProperty { fn to_css<W>(&self, dest: &mut W) -> fmt::Result where W: fmt::Write { match *self { TransitionProperty::All => dest.write_str("all"), TransitionProperty::BackgroundColor => dest.write_str("background-color"), TransitionProperty::BackgroundPosition => dest.write_str("background-position"), TransitionProperty::BorderBottomColor => dest.write_str("border-bottom-color"), TransitionProperty::BorderBottomWidth => dest.write_str("border-bottom-width"), TransitionProperty::BorderLeftColor => dest.write_str("border-left-color"), TransitionProperty::BorderLeftWidth => dest.write_str("border-left-width"), TransitionProperty::BorderRightColor => dest.write_str("border-right-color"), TransitionProperty::BorderRightWidth => dest.write_str("border-right-width"), TransitionProperty::BorderSpacing => dest.write_str("border-spacing"), TransitionProperty::BorderTopColor => dest.write_str("border-top-color"), TransitionProperty::BorderTopWidth => dest.write_str("border-top-width"), TransitionProperty::Bottom => dest.write_str("bottom"), TransitionProperty::Color => dest.write_str("color"), TransitionProperty::Clip => dest.write_str("clip"), TransitionProperty::FontSize => dest.write_str("font-size"), TransitionProperty::FontWeight => dest.write_str("font-weight"), TransitionProperty::Height => dest.write_str("height"), TransitionProperty::Left => dest.write_str("left"), TransitionProperty::LetterSpacing => dest.write_str("letter-spacing"), TransitionProperty::LineHeight => dest.write_str("line-height"), TransitionProperty::MarginBottom => dest.write_str("margin-bottom"), TransitionProperty::MarginLeft => dest.write_str("margin-left"), TransitionProperty::MarginRight => dest.write_str("margin-right"), TransitionProperty::MarginTop => dest.write_str("margin-top"), TransitionProperty::MaxHeight => dest.write_str("max-height"), TransitionProperty::MaxWidth => dest.write_str("max-width"), TransitionProperty::MinHeight => dest.write_str("min-height"), TransitionProperty::MinWidth => dest.write_str("min-width"), TransitionProperty::Opacity => dest.write_str("opacity"), TransitionProperty::OutlineColor => dest.write_str("outline-color"), TransitionProperty::OutlineWidth => dest.write_str("outline-width"), TransitionProperty::PaddingBottom => dest.write_str("padding-bottom"), TransitionProperty::PaddingLeft => dest.write_str("padding-left"), TransitionProperty::PaddingRight => dest.write_str("padding-right"), TransitionProperty::PaddingTop => dest.write_str("padding-top"), TransitionProperty::Right => dest.write_str("right"), TransitionProperty::TextIndent => dest.write_str("text-indent"), TransitionProperty::TextShadow => dest.write_str("text-shadow"), TransitionProperty::Top => dest.write_str("top"), TransitionProperty::Transform => dest.write_str("transform"), TransitionProperty::VerticalAlign => dest.write_str("vertical-align"), TransitionProperty::Visibility => dest.write_str("visibility"), TransitionProperty::Width => dest.write_str("width"), TransitionProperty::WordSpacing => dest.write_str("word-spacing"), TransitionProperty::ZIndex => dest.write_str("z-index"), } } } #[derive(Clone, Debug, PartialEq, HeapSizeOf)] pub struct T(pub Vec<SingleComputedValue>); impl ToCss for T { fn to_css<W>(&self, dest: &mut W) -> fmt::Result where W: fmt::Write { if self.0.is_empty() { return dest.write_str("none") } for (i, value) in self.0.iter().enumerate() { if i != 0 { try!(dest.write_str(", ")) } try!(value.to_css(dest)) } Ok(()) } } } #[inline] pub fn get_initial_value() -> computed_value::T { computed_value::T(Vec::new()) } pub fn parse_one(input: &mut Parser) -> Result<SingleSpecifiedValue,()> { match_ignore_ascii_case! { try!(input.expect_ident()), "all" => Ok(TransitionProperty::All), "background-color" => Ok(TransitionProperty::BackgroundColor), "background-position" => Ok(TransitionProperty::BackgroundPosition), "border-bottom-color" => Ok(TransitionProperty::BorderBottomColor), "border-bottom-width" => Ok(TransitionProperty::BorderBottomWidth), "border-left-color" => Ok(TransitionProperty::BorderLeftColor), "border-left-width" => Ok(TransitionProperty::BorderLeftWidth), "border-right-color" => Ok(TransitionProperty::BorderRightColor), "border-right-width" => Ok(TransitionProperty::BorderRightWidth), "border-spacing" => Ok(TransitionProperty::BorderSpacing), "border-top-color" => Ok(TransitionProperty::BorderTopColor), "border-top-width" => Ok(TransitionProperty::BorderTopWidth), "bottom" => Ok(TransitionProperty::Bottom), "color" => Ok(TransitionProperty::Color), "clip" => Ok(TransitionProperty::Clip), "font-size" => Ok(TransitionProperty::FontSize), "font-weight" => Ok(TransitionProperty::FontWeight), "height" => Ok(TransitionProperty::Height), "left" => Ok(TransitionProperty::Left), "letter-spacing" => Ok(TransitionProperty::LetterSpacing), "line-height" => Ok(TransitionProperty::LineHeight), "margin-bottom" => Ok(TransitionProperty::MarginBottom), "margin-left" => Ok(TransitionProperty::MarginLeft), "margin-right" => Ok(TransitionProperty::MarginRight), "margin-top" => Ok(TransitionProperty::MarginTop), "max-height" => Ok(TransitionProperty::MaxHeight), "max-width" => Ok(TransitionProperty::MaxWidth), "min-height" => Ok(TransitionProperty::MinHeight), "min-width" => Ok(TransitionProperty::MinWidth), "opacity" => Ok(TransitionProperty::Opacity), "outline-color" => Ok(TransitionProperty::OutlineColor), "outline-width" => Ok(TransitionProperty::OutlineWidth), "padding-bottom" => Ok(TransitionProperty::PaddingBottom), "padding-left" => Ok(TransitionProperty::PaddingLeft), "padding-right" => Ok(TransitionProperty::PaddingRight), "padding-top" => Ok(TransitionProperty::PaddingTop), "right" => Ok(TransitionProperty::Right), "text-indent" => Ok(TransitionProperty::TextIndent), "text-shadow" => Ok(TransitionProperty::TextShadow), "top" => Ok(TransitionProperty::Top), "transform" => Ok(TransitionProperty::Transform), "vertical-align" => Ok(TransitionProperty::VerticalAlign), "visibility" => Ok(TransitionProperty::Visibility), "width" => Ok(TransitionProperty::Width), "word-spacing" => Ok(TransitionProperty::WordSpacing), "z-index" => Ok(TransitionProperty::ZIndex) _ => Err(()) } } pub fn parse(_: &ParserContext, input: &mut Parser) -> Result<SpecifiedValue,()> { Ok(SpecifiedValue(try!(input.parse_comma_separated(parse_one)))) } impl ToComputedValue for SpecifiedValue { type ComputedValue = computed_value::T; #[inline] fn to_computed_value(&self, _: &Context) -> computed_value::T { (*self).clone() } } </%self:longhand> <%self:longhand name="transition-delay"> pub use properties::longhands::transition_duration::{SingleSpecifiedValue, SpecifiedValue}; pub use properties::longhands::transition_duration::{computed_value}; pub use properties::longhands::transition_duration::{get_initial_single_value}; pub use properties::longhands::transition_duration::{get_initial_value, parse, parse_one}; </%self:longhand> // CSS Flexible Box Layout Module Level 1 // http://www.w3.org/TR/css3-flexbox/ ${new_style_struct("Flex", is_inherited=False)} // Flex container properties ${single_keyword("flex-direction", "row row-reverse column column-reverse", experimental=True)} } pub mod shorthands { use cssparser::Parser; use parser::ParserContext; use values::specified; <%def name="shorthand(name, sub_properties, experimental=False)"> <% shorthand = Shorthand(name, sub_properties.split(), experimental=experimental) SHORTHANDS.append(shorthand) %> pub mod ${shorthand.ident} { use cssparser::Parser; use parser::ParserContext; use properties::{longhands, PropertyDeclaration, DeclaredValue, Shorthand}; pub struct Longhands { % for sub_property in shorthand.sub_properties: pub ${sub_property.ident}: Option<longhands::${sub_property.ident}::SpecifiedValue>, % endfor } pub fn parse(context: &ParserContext, input: &mut Parser, declarations: &mut Vec<PropertyDeclaration>) -> Result<(), ()> { input.look_for_var_functions(); let start = input.position(); let value = parse_value(context, input); let var = input.seen_var_functions(); if let Ok(value) = value { % for sub_property in shorthand.sub_properties: declarations.push(PropertyDeclaration::${sub_property.camel_case}( match value.${sub_property.ident} { Some(value) => DeclaredValue::Value(value), None => DeclaredValue::Initial, } )); % endfor Ok(()) } else if var { input.reset(start); let (first_token_type, _) = try!( ::custom_properties::parse_declaration_value(input, &mut None)); let css = input.slice_from(start); % for sub_property in shorthand.sub_properties: declarations.push(PropertyDeclaration::${sub_property.camel_case}( DeclaredValue::WithVariables { css: css.to_owned(), first_token_type: first_token_type, base_url: context.base_url.clone(), from_shorthand: Shorthand::${shorthand.camel_case}, } )); % endfor Ok(()) } else { Err(()) } } #[allow(unused_variables)] pub fn parse_value(context: &ParserContext, input: &mut Parser) -> Result<Longhands, ()> { ${caller.body()} } } </%def> fn parse_four_sides<F, T>(input: &mut Parser, parse_one: F) -> Result<(T, T, T, T), ()> where F: Fn(&mut Parser) -> Result<T, ()>, F: Copy, T: Clone { // zero or more than four values is invalid. // one value sets them all // two values set (top, bottom) and (left, right) // three values set top, (left, right) and bottom // four values set them in order let top = try!(parse_one(input)); let right; let bottom; let left; match input.try(parse_one) { Err(()) => { right = top.clone(); bottom = top.clone(); left = top.clone(); } Ok(value) => { right = value; match input.try(parse_one) { Err(()) => { bottom = top.clone(); left = right.clone(); } Ok(value) => { bottom = value; match input.try(parse_one) { Err(()) => { left = right.clone(); } Ok(value) => { left = value; } } } } } } Ok((top, right, bottom, left)) } <%def name="four_sides_shorthand(name, sub_property_pattern, parser_function)"> <%self:shorthand name="${name}" sub_properties="${ ' '.join(sub_property_pattern % side for side in ['top', 'right', 'bottom', 'left'])}"> use super::parse_four_sides; use values::specified; let _unused = context; let (top, right, bottom, left) = try!(parse_four_sides(input, ${parser_function})); Ok(Longhands { % for side in ["top", "right", "bottom", "left"]: ${to_rust_ident(sub_property_pattern % side)}: Some(${side}), % endfor }) </%self:shorthand> </%def> // TODO: other background-* properties <%self:shorthand name="background" sub_properties="background-color background-position background-repeat background-attachment background-image background-size background-origin background-clip"> use properties::longhands::{background_color, background_position, background_repeat, background_attachment}; use properties::longhands::{background_image, background_size, background_origin, background_clip}; let mut color = None; let mut image = None; let mut position = None; let mut repeat = None; let mut size = None; let mut attachment = None; let mut any = false; let mut origin = None; let mut clip = None; loop { if position.is_none() { if let Ok(value) = input.try(|input| background_position::parse(context, input)) { position = Some(value); any = true; // Parse background size, if applicable. size = input.try(|input| { try!(input.expect_delim('/')); background_size::parse(context, input) }).ok(); continue } } if color.is_none() { if let Ok(value) = input.try(|input| background_color::parse(context, input)) { color = Some(value); any = true; continue } } if image.is_none() { if let Ok(value) = input.try(|input| background_image::parse(context, input)) { image = Some(value); any = true; continue } } if repeat.is_none() { if let Ok(value) = input.try(|input| background_repeat::parse(context, input)) { repeat = Some(value); any = true; continue } } if attachment.is_none() { if let Ok(value) = input.try(|input| background_attachment::parse(context, input)) { attachment = Some(value); any = true; continue } } if origin.is_none() { if let Ok(value) = input.try(|input| background_origin::parse(context, input)) { origin = Some(value); any = true; continue } } if clip.is_none() { if let Ok(value) = input.try(|input| background_clip::parse(context, input)) { clip = Some(value); any = true; continue } } break } if any { Ok(Longhands { background_color: color, background_image: image, background_position: position, background_repeat: repeat, background_attachment: attachment, background_size: size, background_origin: origin, background_clip: clip, }) } else { Err(()) } </%self:shorthand> ${four_sides_shorthand("margin", "margin-%s", "specified::LengthOrPercentageOrAuto::parse")} ${four_sides_shorthand("padding", "padding-%s", "specified::LengthOrPercentage::parse")} ${four_sides_shorthand("border-color", "border-%s-color", "specified::CSSColor::parse")} ${four_sides_shorthand("border-style", "border-%s-style", "specified::BorderStyle::parse")} <%self:shorthand name="border-width" sub_properties="${ ' '.join('border-%s-width' % side for side in ['top', 'right', 'bottom', 'left'])}"> use super::parse_four_sides; use values::specified; let _unused = context; let (top, right, bottom, left) = try!(parse_four_sides(input, specified::parse_border_width)); Ok(Longhands { % for side in ["top", "right", "bottom", "left"]: ${to_rust_ident('border-%s-width' % side)}: Some(longhands::${to_rust_ident('border-%s-width' % side)}::SpecifiedValue(${side})), % endfor }) </%self:shorthand> pub fn parse_border(context: &ParserContext, input: &mut Parser) -> Result<(Option<specified::CSSColor>, Option<specified::BorderStyle>, Option<specified::Length>), ()> { use values::specified; let _unused = context; let mut color = None; let mut style = None; let mut width = None; let mut any = false; loop { if color.is_none() { if let Ok(value) = input.try(specified::CSSColor::parse) { color = Some(value); any = true; continue } } if style.is_none() { if let Ok(value) = input.try(specified::BorderStyle::parse) { style = Some(value); any = true; continue } } if width.is_none() { if let Ok(value) = input.try(specified::parse_border_width) { width = Some(value); any = true; continue } } break } if any { Ok((color, style, width)) } else { Err(()) } } % for side in ["top", "right", "bottom", "left"]: <%self:shorthand name="border-${side}" sub_properties="${' '.join( 'border-%s-%s' % (side, prop) for prop in ['color', 'style', 'width'] )}"> let (color, style, width) = try!(super::parse_border(context, input)); Ok(Longhands { border_${side}_color: color, border_${side}_style: style, border_${side}_width: width.map(longhands::${to_rust_ident('border-%s-width' % side)}::SpecifiedValue), }) </%self:shorthand> % endfor <%self:shorthand name="border" sub_properties="${' '.join( 'border-%s-%s' % (side, prop) for side in ['top', 'right', 'bottom', 'left'] for prop in ['color', 'style', 'width'] )}"> let (color, style, width) = try!(super::parse_border(context, input)); Ok(Longhands { % for side in ["top", "right", "bottom", "left"]: border_${side}_color: color.clone(), border_${side}_style: style, border_${side}_width: width.map(longhands::${to_rust_ident('border-%s-width' % side)}::SpecifiedValue), % endfor }) </%self:shorthand> <%self:shorthand name="border-radius" sub_properties="${' '.join( 'border-%s-radius' % (corner) for corner in ['top-left', 'top-right', 'bottom-right', 'bottom-left'] )}"> use util::geometry::Au; use values::specified::{Length, LengthOrPercentage}; use values::specified::BorderRadiusSize; let _ignored = context; fn parse_one_set_of_border_values(mut input: &mut Parser) -> Result<[LengthOrPercentage; 4], ()> { let mut count = 0; let mut values = [LengthOrPercentage::Length(Length::Absolute(Au(0))); 4]; while count < 4 { if let Ok(value) = input.try(LengthOrPercentage::parse) { values[count] = value; count += 1; } else { break } } match count { 1 => Ok([values[0], values[0], values[0], values[0]]), 2 => Ok([values[0], values[1], values[0], values[1]]), 3 => Ok([values[0], values[1], values[2], values[1]]), 4 => Ok([values[0], values[1], values[2], values[3]]), _ => Err(()), } } fn parse_one_set_of_border_radii(mut input: &mut Parser) -> Result<[BorderRadiusSize; 4], ()> { let widths = try!(parse_one_set_of_border_values(input)); let mut heights = widths.clone(); let mut radii_values = [BorderRadiusSize::zero(); 4]; if input.try(|input| input.expect_delim('/')).is_ok() { heights = try!(parse_one_set_of_border_values(input)); } for i in 0..radii_values.len() { radii_values[i] = BorderRadiusSize::new(widths[i], heights[i]); } Ok(radii_values) } let radii = try!(parse_one_set_of_border_radii(input)); Ok(Longhands { border_top_left_radius: Some(radii[0]), border_top_right_radius: Some(radii[1]), border_bottom_right_radius: Some(radii[2]), border_bottom_left_radius: Some(radii[3]), }) </%self:shorthand> <%self:shorthand name="outline" sub_properties="outline-color outline-style outline-width"> use properties::longhands::outline_width; use values::specified; let _unused = context; let mut color = None; let mut style = None; let mut width = None; let mut any = false; loop { if color.is_none() { if let Ok(value) = input.try(specified::CSSColor::parse) { color = Some(value); any = true; continue } } if style.is_none() { if let Ok(value) = input.try(specified::BorderStyle::parse) { style = Some(value); any = true; continue } } if width.is_none() { if let Ok(value) = input.try(|input| outline_width::parse(context, input)) { width = Some(value); any = true; continue } } break } if any { Ok(Longhands { outline_color: color, outline_style: style, outline_width: width, }) } else { Err(()) } </%self:shorthand> <%self:shorthand name="font" sub_properties="font-style font-variant font-weight font-size line-height font-family"> use properties::longhands::{font_style, font_variant, font_weight, font_size, line_height, font_family}; let mut nb_normals = 0; let mut style = None; let mut variant = None; let mut weight = None; let size; loop { // Special-case 'normal' because it is valid in each of // font-style, font-weight and font-variant. // Leaves the values to None, 'normal' is the initial value for each of them. if input.try(|input| input.expect_ident_matching("normal")).is_ok() { nb_normals += 1; continue; } if style.is_none() { if let Ok(value) = input.try(|input| font_style::parse(context, input)) { style = Some(value); continue } } if weight.is_none() { if let Ok(value) = input.try(|input| font_weight::parse(context, input)) { weight = Some(value); continue } } if variant.is_none() { if let Ok(value) = input.try(|input| font_variant::parse(context, input)) { variant = Some(value); continue } } size = Some(try!(font_size::parse(context, input))); break } #[inline] fn count<T>(opt: &Option<T>) -> u8 { if opt.is_some() { 1 } else { 0 } } if size.is_none() || (count(&style) + count(&weight) + count(&variant) + nb_normals) > 3 { return Err(()) } let line_height = if input.try(|input| input.expect_delim('/')).is_ok() { Some(try!(line_height::parse(context, input))) } else { None }; let family = try!(input.parse_comma_separated(font_family::parse_one_family)); Ok(Longhands { font_style: style, font_variant: variant, font_weight: weight, font_size: size, line_height: line_height, font_family: Some(font_family::SpecifiedValue(family)) }) </%self:shorthand> // Per CSS-TEXT 6.2, "for legacy reasons, UAs must treat `word-wrap` as an alternate name for // the `overflow-wrap` property, as if it were a shorthand of `overflow-wrap`." <%self:shorthand name="word-wrap" sub_properties="overflow-wrap"> use properties::longhands::overflow_wrap; Ok(Longhands { overflow_wrap: Some(try!(overflow_wrap::parse(context, input))), }) </%self:shorthand> <%self:shorthand name="list-style" sub_properties="list-style-image list-style-position list-style-type"> use properties::longhands::{list_style_image, list_style_position, list_style_type}; // `none` is ambiguous until we've finished parsing the shorthands, so we count the number // of times we see it. let mut nones = 0u8; let (mut image, mut position, mut list_style_type, mut any) = (None, None, None, false); loop { if input.try(|input| input.expect_ident_matching("none")).is_ok() { nones = nones + 1; if nones > 2 { return Err(()) } any = true; continue } if list_style_type.is_none() { if let Ok(value) = input.try(|input| list_style_type::parse(context, input)) { list_style_type = Some(value); any = true; continue } } if image.is_none() { if let Ok(value) = input.try(|input| list_style_image::parse(context, input)) { image = Some(value); any = true; continue } } if position.is_none() { if let Ok(value) = input.try(|input| list_style_position::parse(context, input)) { position = Some(value); any = true; continue } } break } // If there are two `none`s, then we can't have a type or image; if there is one `none`, // then we can't have both a type *and* an image; if there is no `none` then we're fine as // long as we parsed something. match (any, nones, list_style_type, image) { (true, 2, None, None) => { Ok(Longhands { list_style_position: position, list_style_image: Some(list_style_image::SpecifiedValue::None), list_style_type: Some(list_style_type::SpecifiedValue::none), }) } (true, 1, None, Some(image)) => { Ok(Longhands { list_style_position: position, list_style_image: Some(image), list_style_type: Some(list_style_type::SpecifiedValue::none), }) } (true, 1, Some(list_style_type), None) => { Ok(Longhands { list_style_position: position, list_style_image: Some(list_style_image::SpecifiedValue::None), list_style_type: Some(list_style_type), }) } (true, 1, None, None) => { Ok(Longhands { list_style_position: position, list_style_image: Some(list_style_image::SpecifiedValue::None), list_style_type: Some(list_style_type::SpecifiedValue::none), }) } (true, 0, list_style_type, image) => { Ok(Longhands { list_style_position: position, list_style_image: image, list_style_type: list_style_type, }) } _ => Err(()), } </%self:shorthand> <%self:shorthand name="columns" sub_properties="column-count column-width" experimental="True"> use properties::longhands::{column_count, column_width}; let mut column_count = None; let mut column_width = None; let mut autos = 0; loop { if input.try(|input| input.expect_ident_matching("auto")).is_ok() { // Leave the options to None, 'auto' is the initial value. autos += 1; continue } if column_count.is_none() { if let Ok(value) = input.try(|input| column_count::parse(context, input)) { column_count = Some(value); continue } } if column_width.is_none() { if let Ok(value) = input.try(|input| column_width::parse(context, input)) { column_width = Some(value); continue } } break } let values = autos + column_count.iter().len() + column_width.iter().len(); if values == 0 || values > 2 { Err(()) } else { Ok(Longhands { column_count: column_count, column_width: column_width, }) } </%self:shorthand> <%self:shorthand name="overflow" sub_properties="overflow-x overflow-y"> use properties::longhands::{overflow_x, overflow_y}; let overflow = try!(overflow_x::parse(context, input)); Ok(Longhands { overflow_x: Some(overflow), overflow_y: Some(overflow_y::SpecifiedValue(overflow)), }) </%self:shorthand> <%self:shorthand name="transition" sub_properties="transition-property transition-duration transition-timing-function transition-delay"> use properties::longhands::{transition_delay, transition_duration, transition_property}; use properties::longhands::{transition_timing_function}; struct SingleTransition { transition_property: transition_property::SingleSpecifiedValue, transition_duration: transition_duration::SingleSpecifiedValue, transition_timing_function: transition_timing_function::SingleSpecifiedValue, transition_delay: transition_delay::SingleSpecifiedValue, } fn parse_one_transition(input: &mut Parser) -> Result<SingleTransition,()> { let (mut property, mut duration) = (None, None); let (mut timing_function, mut delay) = (None, None); loop { if property.is_none() { if let Ok(value) = input.try(|input| transition_property::parse_one(input)) { property = Some(value); continue } } if duration.is_none() { if let Ok(value) = input.try(|input| transition_duration::parse_one(input)) { duration = Some(value); continue } } if timing_function.is_none() { if let Ok(value) = input.try(|input| { transition_timing_function::parse_one(input) }) { timing_function = Some(value); continue } } if delay.is_none() { if let Ok(value) = input.try(|input| transition_delay::parse_one(input)) { delay = Some(value); continue; } } break } if let Some(property) = property { Ok(SingleTransition { transition_property: property, transition_duration: duration.unwrap_or(transition_duration::get_initial_single_value()), transition_timing_function: timing_function.unwrap_or( transition_timing_function::get_initial_single_value()), transition_delay: delay.unwrap_or(transition_delay::get_initial_single_value()), }) } else { Err(()) } } if input.try(|input| input.expect_ident_matching("none")).is_ok() { return Ok(Longhands { transition_property: None, transition_duration: None, transition_timing_function: None, transition_delay: None, }) } let results = try!(input.parse_comma_separated(parse_one_transition)); let (mut properties, mut durations) = (Vec::new(), Vec::new()); let (mut timing_functions, mut delays) = (Vec::new(), Vec::new()); for result in results { properties.push(result.transition_property); durations.push(result.transition_duration); timing_functions.push(result.transition_timing_function); delays.push(result.transition_delay); } Ok(Longhands { transition_property: Some(transition_property::SpecifiedValue(properties)), transition_duration: Some(transition_duration::SpecifiedValue(durations)), transition_timing_function: Some(transition_timing_function::SpecifiedValue(timing_functions)), transition_delay: Some(transition_delay::SpecifiedValue(delays)), }) </%self:shorthand> } // TODO(SimonSapin): Convert this to a syntax extension rather than a Mako template. // Maybe submit for inclusion in libstd? mod property_bit_field { pub struct PropertyBitField { storage: [u32; (${len(LONGHANDS)} - 1 + 32) / 32] } impl PropertyBitField { #[inline] pub fn new() -> PropertyBitField { PropertyBitField { storage: [0; (${len(LONGHANDS)} - 1 + 32) / 32] } } #[inline] fn get(&self, bit: usize) -> bool { (self.storage[bit / 32] & (1 << (bit % 32))) != 0 } #[inline] fn set(&mut self, bit: usize) { self.storage[bit / 32] |= 1 << (bit % 32) } % for i, property in enumerate(LONGHANDS): % if property.derived_from is None: #[allow(non_snake_case)] #[inline] pub fn get_${property.ident}(&self) -> bool { self.get(${i}) } #[allow(non_snake_case)] #[inline] pub fn set_${property.ident}(&mut self) { self.set(${i}) } % endif % endfor } } % for property in LONGHANDS: % if property.derived_from is None: fn substitute_variables_${property.ident}<F, R>( value: &DeclaredValue<longhands::${property.ident}::SpecifiedValue>, custom_properties: &Option<Arc<::custom_properties::ComputedValuesMap>>, f: F) -> R where F: FnOnce(&DeclaredValue<longhands::${property.ident}::SpecifiedValue>) -> R { if let DeclaredValue::WithVariables { ref css, first_token_type, ref base_url, from_shorthand } = *value { f(& ::custom_properties::substitute(css, first_token_type, custom_properties) .and_then(|css| { // As of this writing, only the base URL is used for property values: let context = ParserContext::new( ::stylesheets::Origin::Author, base_url); Parser::new(&css).parse_entirely(|input| { match from_shorthand { Shorthand::None => { longhands::${property.ident}::parse_specified(&context, input) } % for shorthand in SHORTHANDS: % if property in shorthand.sub_properties: Shorthand::${shorthand.camel_case} => { shorthands::${shorthand.ident}::parse_value(&context, input) .map(|result| match result.${property.ident} { Some(value) => DeclaredValue::Value(value), None => DeclaredValue::Initial, }) } % endif % endfor _ => unreachable!() } }) }) .unwrap_or( // Invalid at computed-value time. DeclaredValue::${"Inherit" if property.style_struct.inherited else "Initial"} ) ) } else { f(value) } } % endif % endfor /// Declarations are stored in reverse order. /// Overridden declarations are skipped. #[derive(Debug, PartialEq, HeapSizeOf)] pub struct PropertyDeclarationBlock { #[ignore_heap_size_of = "#7038"] pub important: Arc<Vec<PropertyDeclaration>>, #[ignore_heap_size_of = "#7038"] pub normal: Arc<Vec<PropertyDeclaration>>, } pub fn parse_style_attribute(input: &str, base_url: &Url) -> PropertyDeclarationBlock { let context = ParserContext::new(Origin::Author, base_url); parse_property_declaration_list(&context, &mut Parser::new(input)) } pub fn parse_one_declaration(name: &str, input: &str, base_url: &Url) -> Result<Vec<PropertyDeclaration>, ()> { let context = ParserContext::new(Origin::Author, base_url); let mut results = vec![]; match PropertyDeclaration::parse(name, &context, &mut Parser::new(input), &mut results) { PropertyDeclarationParseResult::ValidOrIgnoredDeclaration => Ok(results), _ => Err(()) } } struct PropertyDeclarationParser<'a, 'b: 'a> { context: &'a ParserContext<'b>, } /// Default methods reject all at rules. impl<'a, 'b> AtRuleParser for PropertyDeclarationParser<'a, 'b> { type Prelude = (); type AtRule = (Vec<PropertyDeclaration>, bool); } impl<'a, 'b> DeclarationParser for PropertyDeclarationParser<'a, 'b> { type Declaration = (Vec<PropertyDeclaration>, bool); fn parse_value(&self, name: &str, input: &mut Parser) -> Result<(Vec<PropertyDeclaration>, bool), ()> { let mut results = vec![]; match PropertyDeclaration::parse(name, self.context, input, &mut results) { PropertyDeclarationParseResult::ValidOrIgnoredDeclaration => {} _ => return Err(()) } let important = input.try(parse_important).is_ok(); Ok((results, important)) } } pub fn parse_property_declaration_list(context: &ParserContext, input: &mut Parser) -> PropertyDeclarationBlock { let mut important_declarations = Vec::new(); let mut normal_declarations = Vec::new(); let parser = PropertyDeclarationParser { context: context, }; let mut iter = DeclarationListParser::new(input, parser); while let Some(declaration) = iter.next() { match declaration { Ok((results, important)) => { if important { important_declarations.extend(results); } else { normal_declarations.extend(results); } } Err(range) => { let pos = range.start; let message = format!("Unsupported property declaration: '{}'", iter.input.slice(range)); log_css_error(iter.input, pos, &*message); } } } PropertyDeclarationBlock { important: Arc::new(deduplicate_property_declarations(important_declarations)), normal: Arc::new(deduplicate_property_declarations(normal_declarations)), } } /// Only keep the last declaration for any given property. /// The input is in source order, output in reverse source order. fn deduplicate_property_declarations(declarations: Vec<PropertyDeclaration>) -> Vec<PropertyDeclaration> { let mut deduplicated = vec![]; let mut seen = PropertyBitField::new(); let mut seen_custom = Vec::new(); for declaration in declarations.into_iter().rev() { match declaration { % for property in LONGHANDS: PropertyDeclaration::${property.camel_case}(..) => { % if property.derived_from is None: if seen.get_${property.ident}() { continue } seen.set_${property.ident}() % else: unreachable!(); % endif }, % endfor PropertyDeclaration::Custom(ref name, _) => { if seen_custom.contains(name) { continue } seen_custom.push(name.clone()) } } deduplicated.push(declaration) } deduplicated } #[derive(Copy, Clone, PartialEq, Eq, Debug)] pub enum CSSWideKeyword { InitialKeyword, InheritKeyword, UnsetKeyword, } impl CSSWideKeyword { pub fn parse(input: &mut Parser) -> Result<CSSWideKeyword, ()> { match_ignore_ascii_case! { try!(input.expect_ident()), "initial" => Ok(CSSWideKeyword::InitialKeyword), "inherit" => Ok(CSSWideKeyword::InheritKeyword), "unset" => Ok(CSSWideKeyword::UnsetKeyword) _ => Err(()) } } } #[derive(Clone, Copy, Eq, PartialEq, Debug)] pub enum Shorthand { None, % for property in SHORTHANDS: ${property.camel_case}, % endfor } #[derive(Clone, PartialEq, Eq, Debug)] pub enum DeclaredValue<T> { Value(T), WithVariables { css: String, first_token_type: TokenSerializationType, base_url: Url, from_shorthand: Shorthand }, Initial, Inherit, // There is no Unset variant here. // The 'unset' keyword is represented as either Initial or Inherit, // depending on whether the property is inherited. } impl<T: ToCss> ToCss for DeclaredValue<T> { fn to_css<W>(&self, dest: &mut W) -> fmt::Result where W: fmt::Write { match *self { DeclaredValue::Value(ref inner) => inner.to_css(dest), DeclaredValue::WithVariables { ref css, from_shorthand: Shorthand::None, .. } => { dest.write_str(css) } // https://drafts.csswg.org/css-variables/#variables-in-shorthands DeclaredValue::WithVariables { .. } => Ok(()), DeclaredValue::Initial => dest.write_str("initial"), DeclaredValue::Inherit => dest.write_str("inherit"), } } } #[derive(PartialEq, Clone)] pub enum PropertyDeclaration { % for property in LONGHANDS: ${property.camel_case}(DeclaredValue<longhands::${property.ident}::SpecifiedValue>), % endfor Custom(::custom_properties::Name, DeclaredValue<::custom_properties::SpecifiedValue>), } #[derive(Eq, PartialEq, Copy, Clone)] pub enum PropertyDeclarationParseResult { UnknownProperty, ExperimentalProperty, InvalidValue, ValidOrIgnoredDeclaration, } #[derive(Eq, PartialEq, Clone)] pub enum PropertyDeclarationName { Longhand(&'static str), Custom(::custom_properties::Name), Internal } impl PartialEq<str> for PropertyDeclarationName { fn eq(&self, other: &str) -> bool { match *self { PropertyDeclarationName::Longhand(n) => n == other, PropertyDeclarationName::Custom(ref n) => { ::custom_properties::parse_name(other) == Ok(&**n) } PropertyDeclarationName::Internal => false, } } } impl fmt::Display for PropertyDeclarationName { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { match *self { PropertyDeclarationName::Longhand(n) => f.write_str(n), PropertyDeclarationName::Custom(ref n) => { try!(f.write_str("--")); f.write_str(n) } PropertyDeclarationName::Internal => Ok(()), } } } impl PropertyDeclaration { pub fn name(&self) -> PropertyDeclarationName { match *self { % for property in LONGHANDS: % if property.derived_from is None: PropertyDeclaration::${property.camel_case}(..) => { PropertyDeclarationName::Longhand("${property.name}") } % endif % endfor PropertyDeclaration::Custom(ref name, _) => { PropertyDeclarationName::Custom(name.clone()) } _ => PropertyDeclarationName::Internal, } } pub fn value(&self) -> String { match *self { % for property in LONGHANDS: % if property.derived_from is None: PropertyDeclaration::${property.camel_case}(ref value) => value.to_css_string(), % endif % endfor PropertyDeclaration::Custom(_, ref value) => value.to_css_string(), ref decl => panic!("unsupported property declaration: {}", decl.name()), } } pub fn matches(&self, name: &str) -> bool { match *self { % for property in LONGHANDS: % if property.derived_from is None: PropertyDeclaration::${property.camel_case}(..) => { name.eq_ignore_ascii_case("${property.name}") } % endif % endfor PropertyDeclaration::Custom(ref declaration_name, _) => { ::custom_properties::parse_name(name) == Ok(&**declaration_name) } _ => false, } } pub fn parse(name: &str, context: &ParserContext, input: &mut Parser, result_list: &mut Vec<PropertyDeclaration>) -> PropertyDeclarationParseResult { if let Ok(name) = ::custom_properties::parse_name(name) { let value = match input.try(CSSWideKeyword::parse) { Ok(CSSWideKeyword::UnsetKeyword) | // Custom properties are alawys inherited Ok(CSSWideKeyword::InheritKeyword) => DeclaredValue::Inherit, Ok(CSSWideKeyword::InitialKeyword) => DeclaredValue::Initial, Err(()) => match ::custom_properties::parse(input) { Ok(value) => DeclaredValue::Value(value), Err(()) => return PropertyDeclarationParseResult::InvalidValue, } }; result_list.push(PropertyDeclaration::Custom(Atom::from_slice(name), value)); return PropertyDeclarationParseResult::ValidOrIgnoredDeclaration; } match_ignore_ascii_case! { name, % for property in LONGHANDS: % if property.derived_from is None: "${property.name}" => { % if property.experimental: if !::util::prefs::get_pref("${property.experimental}").unwrap_or(false) { return PropertyDeclarationParseResult::ExperimentalProperty } % endif match longhands::${property.ident}::parse_declared(context, input) { Ok(value) => { result_list.push(PropertyDeclaration::${property.camel_case}(value)); PropertyDeclarationParseResult::ValidOrIgnoredDeclaration }, Err(()) => PropertyDeclarationParseResult::InvalidValue, } }, % else: "${property.name}" => PropertyDeclarationParseResult::UnknownProperty, % endif % endfor % for shorthand in SHORTHANDS: "${shorthand.name}" => { % if shorthand.experimental: if !::util::prefs::get_pref("${shorthand.experimental}").unwrap_or(false) { return PropertyDeclarationParseResult::ExperimentalProperty } % endif match input.try(CSSWideKeyword::parse) { Ok(CSSWideKeyword::InheritKeyword) => { % for sub_property in shorthand.sub_properties: result_list.push( PropertyDeclaration::${sub_property.camel_case}( DeclaredValue::Inherit)); % endfor PropertyDeclarationParseResult::ValidOrIgnoredDeclaration }, Ok(CSSWideKeyword::InitialKeyword) => { % for sub_property in shorthand.sub_properties: result_list.push( PropertyDeclaration::${sub_property.camel_case}( DeclaredValue::Initial)); % endfor PropertyDeclarationParseResult::ValidOrIgnoredDeclaration }, Ok(CSSWideKeyword::UnsetKeyword) => { % for sub_property in shorthand.sub_properties: result_list.push(PropertyDeclaration::${sub_property.camel_case}( DeclaredValue::${"Inherit" if sub_property.style_struct.inherited else "Initial"} )); % endfor PropertyDeclarationParseResult::ValidOrIgnoredDeclaration }, Err(()) => match shorthands::${shorthand.ident}::parse(context, input, result_list) { Ok(()) => PropertyDeclarationParseResult::ValidOrIgnoredDeclaration, Err(()) => PropertyDeclarationParseResult::InvalidValue, } } }, % endfor // Hack to work around quirks of macro_rules parsing in match_ignore_ascii_case! "_nonexistent" => PropertyDeclarationParseResult::UnknownProperty _ => PropertyDeclarationParseResult::UnknownProperty } } } impl Debug for PropertyDeclaration { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { write!(f, "{}: {}", self.name(), self.value()) } } pub mod style_structs { use super::longhands; % for style_struct in STYLE_STRUCTS: #[derive(PartialEq, Clone, HeapSizeOf)] pub struct ${style_struct.name} { % for longhand in style_struct.longhands: pub ${longhand.ident}: longhands::${longhand.ident}::computed_value::T, % endfor % if style_struct.name == "Font": pub hash: u64, % endif } % endfor } #[derive(Clone, HeapSizeOf)] pub struct ComputedValues { % for style_struct in STYLE_STRUCTS: ${style_struct.ident}: Arc<style_structs::${style_struct.name}>, % endfor custom_properties: Option<Arc<::custom_properties::ComputedValuesMap>>, shareable: bool, pub writing_mode: WritingMode, pub root_font_size: Au, } impl ComputedValues { /// Resolves the currentColor keyword. /// Any color value form computed values (except for the 'color' property itself) /// should go through this method. /// /// Usage example: /// let top_color = style.resolve_color(style.Border.border_top_color); #[inline] pub fn resolve_color(&self, color: Color) -> RGBA { match color { Color::RGBA(rgba) => rgba, Color::CurrentColor => self.get_color().color, } } #[inline] pub fn content_inline_size(&self) -> computed::LengthOrPercentageOrAuto { let box_style = self.get_box(); if self.writing_mode.is_vertical() { box_style.height } else { box_style.width } } #[inline] pub fn content_block_size(&self) -> computed::LengthOrPercentageOrAuto { let box_style = self.get_box(); if self.writing_mode.is_vertical() { box_style.width } else { box_style.height } } #[inline] pub fn min_inline_size(&self) -> computed::LengthOrPercentage { let box_style = self.get_box(); if self.writing_mode.is_vertical() { box_style.min_height } else { box_style.min_width } } #[inline] pub fn min_block_size(&self) -> computed::LengthOrPercentage { let box_style = self.get_box(); if self.writing_mode.is_vertical() { box_style.min_width } else { box_style.min_height } } #[inline] pub fn max_inline_size(&self) -> computed::LengthOrPercentageOrNone { let box_style = self.get_box(); if self.writing_mode.is_vertical() { box_style.max_height } else { box_style.max_width } } #[inline] pub fn max_block_size(&self) -> computed::LengthOrPercentageOrNone { let box_style = self.get_box(); if self.writing_mode.is_vertical() { box_style.max_width } else { box_style.max_height } } #[inline] pub fn logical_padding(&self) -> LogicalMargin<computed::LengthOrPercentage> { let padding_style = self.get_padding(); LogicalMargin::from_physical(self.writing_mode, SideOffsets2D::new( padding_style.padding_top, padding_style.padding_right, padding_style.padding_bottom, padding_style.padding_left, )) } #[inline] pub fn logical_border_width(&self) -> LogicalMargin<Au> { let border_style = self.get_border(); LogicalMargin::from_physical(self.writing_mode, SideOffsets2D::new( border_style.border_top_width, border_style.border_right_width, border_style.border_bottom_width, border_style.border_left_width, )) } #[inline] pub fn logical_margin(&self) -> LogicalMargin<computed::LengthOrPercentageOrAuto> { let margin_style = self.get_margin(); LogicalMargin::from_physical(self.writing_mode, SideOffsets2D::new( margin_style.margin_top, margin_style.margin_right, margin_style.margin_bottom, margin_style.margin_left, )) } #[inline] pub fn logical_position(&self) -> LogicalMargin<computed::LengthOrPercentageOrAuto> { // FIXME(SimonSapin): should be the writing mode of the containing block, maybe? let position_style = self.get_positionoffsets(); LogicalMargin::from_physical(self.writing_mode, SideOffsets2D::new( position_style.top, position_style.right, position_style.bottom, position_style.left, )) } #[inline] pub fn is_multicol(&self) -> bool { let style = self.get_column(); style.column_count.0.is_some() || style.column_width.0.is_some() } #[inline] pub fn get_font_arc(&self) -> Arc<style_structs::Font> { self.font.clone() } // http://dev.w3.org/csswg/css-transforms/#grouping-property-values pub fn get_used_transform_style(&self) -> computed_values::transform_style::T { use computed_values::mix_blend_mode; use computed_values::transform_style; let effects = self.get_effects(); // TODO(gw): Add clip-path, isolation, mask-image, mask-border-source when supported. if effects.opacity < 1.0 || !effects.filter.is_empty() || effects.clip.0.is_some() { effects.mix_blend_mode != mix_blend_mode::T::normal || return transform_style::T::flat; } if effects.transform_style == transform_style::T::auto { if effects.transform.0.is_some() { return transform_style::T::flat; } if effects.perspective != computed::LengthOrNone::None { return transform_style::T::flat; } } // Return the computed value if not overridden by the above exceptions effects.transform_style } % for style_struct in STYLE_STRUCTS: #[inline] pub fn get_${style_struct.name.lower()} <'a>(&'a self) -> &'a style_structs::${style_struct.name} { &*self.${style_struct.ident} } #[inline] pub fn mutate_${style_struct.name.lower()} <'a>(&'a mut self) -> &'a mut style_structs::${style_struct.name} { &mut *Arc::make_mut(&mut self.${style_struct.ident}) } % endfor pub fn computed_value_to_string(&self, name: &str) -> Result<String, ()> { match name { % for style_struct in STYLE_STRUCTS: % for longhand in style_struct.longhands: "${longhand.name}" => Ok(self.${style_struct.ident}.${longhand.ident}.to_css_string()), % endfor % endfor _ => { let name = try!(::custom_properties::parse_name(name)); let map = try!(self.custom_properties.as_ref().ok_or(())); let value = try!(map.get(&Atom::from_slice(name)).ok_or(())); Ok(value.to_css_string()) } } } } /// Return a WritingMode bitflags from the relevant CSS properties. pub fn get_writing_mode(inheritedbox_style: &style_structs::InheritedBox) -> WritingMode { use util::logical_geometry; let mut flags = WritingMode::empty(); match inheritedbox_style.direction { computed_values::direction::T::ltr => {}, computed_values::direction::T::rtl => { flags.insert(logical_geometry::FLAG_RTL); }, } match inheritedbox_style.writing_mode { computed_values::writing_mode::T::horizontal_tb => {}, computed_values::writing_mode::T::vertical_rl => { flags.insert(logical_geometry::FLAG_VERTICAL); }, computed_values::writing_mode::T::vertical_lr => { flags.insert(logical_geometry::FLAG_VERTICAL); flags.insert(logical_geometry::FLAG_VERTICAL_LR); }, } match inheritedbox_style.text_orientation { computed_values::text_orientation::T::sideways_right => {}, computed_values::text_orientation::T::sideways_left => { flags.insert(logical_geometry::FLAG_VERTICAL_LR); }, computed_values::text_orientation::T::sideways => { if flags.intersects(logical_geometry::FLAG_VERTICAL_LR) { flags.insert(logical_geometry::FLAG_SIDEWAYS_LEFT); } }, } flags } /// The initial values for all style structs as defined by the specification. lazy_static! { pub static ref INITIAL_VALUES: ComputedValues = ComputedValues { % for style_struct in STYLE_STRUCTS: ${style_struct.ident}: Arc::new(style_structs::${style_struct.name} { % for longhand in style_struct.longhands: ${longhand.ident}: longhands::${longhand.ident}::get_initial_value(), % endfor % if style_struct.name == "Font": hash: 0, % endif }), % endfor custom_properties: None, shareable: true, writing_mode: WritingMode::empty(), root_font_size: longhands::font_size::get_initial_value(), }; } /// Fast path for the function below. Only computes new inherited styles. #[allow(unused_mut)] fn cascade_with_cached_declarations( applicable_declarations: &[DeclarationBlock<Vec<PropertyDeclaration>>], shareable: bool, parent_style: &ComputedValues, cached_style: &ComputedValues, custom_properties: Option<Arc<::custom_properties::ComputedValuesMap>>, context: &computed::Context) -> ComputedValues { % for style_struct in STYLE_STRUCTS: % if style_struct.inherited: let mut style_${style_struct.ident} = parent_style.${style_struct.ident}.clone(); % else: let mut style_${style_struct.ident} = cached_style.${style_struct.ident}.clone(); % endif % endfor let mut seen = PropertyBitField::new(); // Declaration blocks are stored in increasing precedence order, // we want them in decreasing order here. for sub_list in applicable_declarations.iter().rev() { // Declarations are already stored in reverse order. for declaration in sub_list.declarations.iter() { match *declaration { % for style_struct in STYLE_STRUCTS: % for property in style_struct.longhands: % if property.derived_from is None: PropertyDeclaration::${property.camel_case}(ref ${'_' if not style_struct.inherited else ''}declared_value) => { % if style_struct.inherited: if seen.get_${property.ident}() { continue } seen.set_${property.ident}(); let computed_value = substitute_variables_${property.ident}( declared_value, &custom_properties, |value| match *value { DeclaredValue::Value(ref specified_value) => specified_value.to_computed_value(context), DeclaredValue::Initial => longhands::${property.ident}::get_initial_value(), DeclaredValue::Inherit => { // This is a bit slow, but this is rare so it shouldn't // matter. // // FIXME: is it still? parent_style.${style_struct.ident} .${property.ident} .clone() } DeclaredValue::WithVariables { .. } => unreachable!() } ); Arc::make_mut(&mut style_${style_struct.ident}) .${property.ident} = computed_value; % endif % if property.name in DERIVED_LONGHANDS: % if not style_struct.inherited: // Use the cached value. let computed_value = style_${style_struct.ident} .${property.ident}.clone(); % endif % for derived in DERIVED_LONGHANDS[property.name]: Arc::make_mut(&mut style_${derived.style_struct.ident}) .${derived.ident} = longhands::${derived.ident} ::derive_from_${property.ident}( computed_value, context); % endfor % endif } % else: PropertyDeclaration::${property.camel_case}(_) => { // Do not allow stylesheets to set derived properties. } % endif % endfor % endfor PropertyDeclaration::Custom(..) => {} } } } if seen.get_font_style() || seen.get_font_weight() || seen.get_font_stretch() || seen.get_font_family() { compute_font_hash(&mut *Arc::make_mut(&mut style_font)) } ComputedValues { writing_mode: get_writing_mode(&*style_inheritedbox), % for style_struct in STYLE_STRUCTS: ${style_struct.ident}: style_${style_struct.ident}, % endfor custom_properties: custom_properties, shareable: shareable, root_font_size: parent_style.root_font_size, } } type CascadePropertyFn = extern "Rust" fn(declaration: &PropertyDeclaration, style: &mut ComputedValues, inherited_style: &ComputedValues, context: &computed::Context, seen: &mut PropertyBitField, cacheable: &mut bool); // This is a thread-local rather than a lazy static to avoid atomic operations when cascading // properties. thread_local!(static CASCADE_PROPERTY: Vec<Option<CascadePropertyFn>> = { let mut result: Vec<Option<CascadePropertyFn>> = Vec::new(); % for style_struct in STYLE_STRUCTS: % for property in style_struct.longhands: let discriminant; unsafe { let variant = PropertyDeclaration::${property.camel_case}(intrinsics::uninit()); discriminant = intrinsics::discriminant_value(&variant) as usize; mem::forget(variant); } while result.len() < discriminant + 1 { result.push(None) } result[discriminant] = Some(longhands::${property.ident}::cascade_property); % endfor % endfor result }); /// Performs the CSS cascade, computing new styles for an element from its parent style and /// optionally a cached related style. The arguments are: /// /// * `viewport_size`: The size of the initial viewport. /// /// * `applicable_declarations`: The list of CSS rules that matched. /// /// * `shareable`: Whether the `ComputedValues` structure to be constructed should be considered /// shareable. /// /// * `parent_style`: The parent style, if applicable; if `None`, this is the root node. /// /// * `cached_style`: If present, cascading is short-circuited for everything but inherited /// values and these values are used instead. Obviously, you must be careful when supplying /// this that it is safe to only provide inherited declarations. If `parent_style` is `None`, /// this is ignored. /// /// Returns the computed values and a boolean indicating whether the result is cacheable. pub fn cascade(viewport_size: Size2D<Au>, applicable_declarations: &[DeclarationBlock<Vec<PropertyDeclaration>>], shareable: bool, parent_style: Option< &ComputedValues >, cached_style: Option< &ComputedValues >) -> (ComputedValues, bool) { let initial_values = &*INITIAL_VALUES; let (is_root_element, inherited_style) = match parent_style { Some(parent_style) => (false, parent_style), None => (true, initial_values), }; let mut custom_properties = None; let mut seen_custom = HashSet::new(); for sub_list in applicable_declarations.iter().rev() { // Declarations are already stored in reverse order. for declaration in sub_list.declarations.iter() { match *declaration { PropertyDeclaration::Custom(ref name, ref value) => { ::custom_properties::cascade( &mut custom_properties, &inherited_style.custom_properties, &mut seen_custom, name, value) } _ => {} } } } let custom_properties = ::custom_properties::finish_cascade( custom_properties, &inherited_style.custom_properties); let mut context = { let inherited_font_style = inherited_style.get_font(); computed::Context { is_root_element: is_root_element, viewport_size: viewport_size, inherited_font_weight: inherited_font_style.font_weight, inherited_font_size: inherited_font_style.font_size, inherited_text_decorations_in_effect: inherited_style.get_inheritedtext()._servo_text_decorations_in_effect, // To be overridden by applicable declarations: font_size: inherited_font_style.font_size, root_font_size: inherited_style.root_font_size, display: longhands::display::get_initial_value(), color: inherited_style.get_color().color, text_decoration: longhands::text_decoration::get_initial_value(), overflow_x: longhands::overflow_x::get_initial_value(), overflow_y: longhands::overflow_y::get_initial_value(), positioned: false, floated: false, border_top_present: false, border_right_present: false, border_bottom_present: false, border_left_present: false, outline_style_present: false, } }; // This assumes that the computed and specified values have the same Rust type. macro_rules! get_specified( ($style_struct_getter: ident, $property: ident, $declared_value: expr) => { concat_idents!(substitute_variables_, $property)( $declared_value, &custom_properties, |value| match *value { DeclaredValue::Value(specified_value) => specified_value, DeclaredValue::Initial => longhands::$property::get_initial_value(), DeclaredValue::Inherit => { inherited_style.$style_struct_getter().$property.clone() } DeclaredValue::WithVariables { .. } => unreachable!() } ) }; ); // Initialize `context` // Declarations blocks are already stored in increasing precedence order. for sub_list in applicable_declarations { // Declarations are stored in reverse source order, we want them in forward order here. for declaration in sub_list.declarations.iter().rev() { match *declaration { PropertyDeclaration::FontSize(ref value) => { context.font_size = substitute_variables_font_size( value, &custom_properties, |value| match *value { DeclaredValue::Value(ref specified_value) => { match specified_value.0 { Length::FontRelative(value) => { value.to_computed_value(context.inherited_font_size, context.root_font_size) } Length::ServoCharacterWidth(value) => { value.to_computed_value(context.inherited_font_size) } _ => specified_value.0.to_computed_value(&context) } } DeclaredValue::Initial => longhands::font_size::get_initial_value(), DeclaredValue::Inherit => context.inherited_font_size, DeclaredValue::WithVariables { .. } => unreachable!(), } ); } PropertyDeclaration::Color(ref value) => { context.color = substitute_variables_color( value, &custom_properties, |value| match *value { DeclaredValue::Value(ref specified_value) => { specified_value.parsed } DeclaredValue::Initial => longhands::color::get_initial_value(), DeclaredValue::Inherit => inherited_style.get_color().color.clone(), DeclaredValue::WithVariables { .. } => unreachable!(), } ); } PropertyDeclaration::Display(ref value) => { context.display = get_specified!(get_box, display, value); } PropertyDeclaration::Position(ref value) => { context.positioned = match get_specified!(get_box, position, value) { longhands::position::SpecifiedValue::absolute | longhands::position::SpecifiedValue::fixed => true, _ => false, } } PropertyDeclaration::OverflowX(ref value) => { context.overflow_x = get_specified!(get_box, overflow_x, value); } PropertyDeclaration::OverflowY(ref value) => { context.overflow_y = get_specified!(get_box, overflow_y, value); } PropertyDeclaration::Float(ref value) => { context.floated = get_specified!(get_box, float, value) != longhands::float::SpecifiedValue::none; } PropertyDeclaration::TextDecoration(ref value) => { context.text_decoration = get_specified!(get_text, text_decoration, value); } PropertyDeclaration::OutlineStyle(ref value) => { context.outline_style_present = match get_specified!(get_outline, outline_style, value) { BorderStyle::none => false, _ => true, }; } % for side in ["top", "right", "bottom", "left"]: PropertyDeclaration::Border${side.capitalize()}Style(ref value) => { context.border_${side}_present = match get_specified!(get_border, border_${side}_style, value) { BorderStyle::none | BorderStyle::hidden => false, _ => true, }; } % endfor _ => {} } } } match (cached_style, parent_style) { (Some(cached_style), Some(parent_style)) => { return (cascade_with_cached_declarations(applicable_declarations, shareable, parent_style, cached_style, custom_properties, &context), false) } (_, _) => {} } // Set computed values, overwriting earlier declarations for the same property. let mut style = ComputedValues { % for style_struct in STYLE_STRUCTS: ${style_struct.ident}: % if style_struct.inherited: inherited_style % else: initial_values % endif .${style_struct.ident}.clone(), % endfor custom_properties: custom_properties, shareable: shareable, writing_mode: WritingMode::empty(), root_font_size: context.root_font_size, }; let mut cacheable = true; let mut seen = PropertyBitField::new(); // Declaration blocks are stored in increasing precedence order, we want them in decreasing // order here. // // We could (and used to) use a pattern match here, but that bloats this function to over 100K // of compiled code! To improve i-cache behavior, we outline the individual functions and use // virtual dispatch instead. CASCADE_PROPERTY.with(|cascade_property| { for sub_list in applicable_declarations.iter().rev() { // Declarations are already stored in reverse order. for declaration in sub_list.declarations.iter() { if let PropertyDeclaration::Custom(..) = *declaration { continue } let discriminant = unsafe { intrinsics::discriminant_value(declaration) as usize }; (cascade_property[discriminant].unwrap())(declaration, &mut style, inherited_style, &context, &mut seen, &mut cacheable); } } }); // The initial value of border-*-width may be changed at computed value time. { let border = Arc::make_mut(&mut style.border); % for side in ["top", "right", "bottom", "left"]: // Like calling to_computed_value, which wouldn't type check. if !context.border_${side}_present { border.border_${side}_width = Au(0); } % endfor } // The initial value of display may be changed at computed value time. if !seen.get_display() { let box_ = Arc::make_mut(&mut style.box_); box_.display = box_.display.to_computed_value(&context); } // The initial value of outline width may be changed at computed value time. if !context.outline_style_present { let outline = Arc::make_mut(&mut style.outline); outline.outline_width = Au(0); } if is_root_element { context.root_font_size = context.font_size; } if seen.get_font_style() || seen.get_font_weight() || seen.get_font_stretch() || seen.get_font_family() { compute_font_hash(&mut *Arc::make_mut(&mut style.font)) } style.writing_mode = get_writing_mode(&*style.inheritedbox); (style, cacheable) } /// Alters the given style to accommodate replaced content. This is called in flow construction. It /// handles cases like `<div style="position: absolute">foo bar baz</div>` (in which `foo`, `bar`, /// and `baz` must not be absolutely-positioned) and cases like `<sup>Foo</sup>` (in which the /// `vertical-align: top` style of `sup` must not propagate down into `Foo`). /// /// FIXME(#5625, pcwalton): It would probably be cleaner and faster to do this in the cascade. #[inline] pub fn modify_style_for_replaced_content(style: &mut Arc<ComputedValues>) { // Reset `position` to handle cases like `<div style="position: absolute">foo bar baz</div>`. if style.box_.display != longhands::display::computed_value::T::inline { let mut style = Arc::make_mut(style); Arc::make_mut(&mut style.box_).display = longhands::display::computed_value::T::inline; Arc::make_mut(&mut style.box_).position = longhands::position::computed_value::T::static_; } // Reset `vertical-align` to handle cases like `<sup>foo</sup>`. if style.box_.vertical_align != longhands::vertical_align::computed_value::T::baseline { let mut style = Arc::make_mut(style); Arc::make_mut(&mut style.box_).vertical_align = longhands::vertical_align::computed_value::T::baseline } // Reset margins. if style.margin.margin_top != computed::LengthOrPercentageOrAuto::Length(Au(0)) || style.margin.margin_left != computed::LengthOrPercentageOrAuto::Length(Au(0)) || style.margin.margin_bottom != computed::LengthOrPercentageOrAuto::Length(Au(0)) || style.margin.margin_right != computed::LengthOrPercentageOrAuto::Length(Au(0)) { let mut style = Arc::make_mut(style); let margin = Arc::make_mut(&mut style.margin); margin.margin_top = computed::LengthOrPercentageOrAuto::Length(Au(0)); margin.margin_left = computed::LengthOrPercentageOrAuto::Length(Au(0)); margin.margin_bottom = computed::LengthOrPercentageOrAuto::Length(Au(0)); margin.margin_right = computed::LengthOrPercentageOrAuto::Length(Au(0)); } } /// Adjusts borders as appropriate to account for a fragment's status as the first or last fragment /// within the range of an element. /// /// Specifically, this function sets border widths to zero on the sides for which the fragment is /// not outermost. #[inline] pub fn modify_border_style_for_inline_sides(style: &mut Arc<ComputedValues>, is_first_fragment_of_element: bool, is_last_fragment_of_element: bool) { fn modify_side(style: &mut Arc<ComputedValues>, side: PhysicalSide) { let mut style = Arc::make_mut(style); let border = Arc::make_mut(&mut style.border); match side { PhysicalSide::Left => { border.border_left_width = Au(0); border.border_left_style = BorderStyle::none; } PhysicalSide::Right => { border.border_right_width = Au(0); border.border_right_style = BorderStyle::none; } PhysicalSide::Bottom => { border.border_bottom_width = Au(0); border.border_bottom_style = BorderStyle::none; } PhysicalSide::Top => { border.border_top_width = Au(0); border.border_top_style = BorderStyle::none; } } } if !is_first_fragment_of_element { let side = style.writing_mode.inline_start_physical_side(); modify_side(style, side) } if !is_last_fragment_of_element { let side = style.writing_mode.inline_end_physical_side(); modify_side(style, side) } } /// Adjusts the display and position properties as appropriate for an anonymous table object. #[inline] pub fn modify_style_for_anonymous_table_object( style: &mut Arc<ComputedValues>, new_display_value: longhands::display::computed_value::T) { let mut style = Arc::make_mut(style); let box_style = Arc::make_mut(&mut style.box_); box_style.display = new_display_value; box_style.position = longhands::position::computed_value::T::static_; } /// Adjusts the `position` property as necessary for the outer fragment wrapper of an inline-block. #[inline] pub fn modify_style_for_outer_inline_block_fragment(style: &mut Arc<ComputedValues>) { let mut style = Arc::make_mut(style); let box_style = Arc::make_mut(&mut style.box_); box_style.position = longhands::position::computed_value::T::static_ } /// Adjusts the `position` and `padding` properties as necessary to account for text. /// /// Text is never directly relatively positioned; it's always contained within an element that is /// itself relatively positioned. #[inline] pub fn modify_style_for_text(style: &mut Arc<ComputedValues>) { if style.box_.position == longhands::position::computed_value::T::relative { // We leave the `position` property set to `relative` so that we'll still establish a // containing block if needed. But we reset all position offsets to `auto`. let mut style = Arc::make_mut(style); let mut position_offsets = Arc::make_mut(&mut style.positionoffsets); position_offsets.top = computed::LengthOrPercentageOrAuto::Auto; position_offsets.right = computed::LengthOrPercentageOrAuto::Auto; position_offsets.bottom = computed::LengthOrPercentageOrAuto::Auto; position_offsets.left = computed::LengthOrPercentageOrAuto::Auto; } if style.padding.padding_top != computed::LengthOrPercentage::Length(Au(0)) || style.padding.padding_right != computed::LengthOrPercentage::Length(Au(0)) || style.padding.padding_bottom != computed::LengthOrPercentage::Length(Au(0)) || style.padding.padding_left != computed::LengthOrPercentage::Length(Au(0)) { let mut style = Arc::make_mut(style); let mut padding = Arc::make_mut(&mut style.padding); padding.padding_top = computed::LengthOrPercentage::Length(Au(0)); padding.padding_right = computed::LengthOrPercentage::Length(Au(0)); padding.padding_bottom = computed::LengthOrPercentage::Length(Au(0)); padding.padding_left = computed::LengthOrPercentage::Length(Au(0)); } } /// Adjusts the `margin` property as necessary to account for the text of an `input` element. /// /// Margins apply to the `input` element itself, so including them in the text will cause them to /// be double-counted. pub fn modify_style_for_input_text(style: &mut Arc<ComputedValues>) { let mut style = Arc::make_mut(style); let margin_style = Arc::make_mut(&mut style.margin); margin_style.margin_top = computed::LengthOrPercentageOrAuto::Length(Au(0)); margin_style.margin_right = computed::LengthOrPercentageOrAuto::Length(Au(0)); margin_style.margin_bottom = computed::LengthOrPercentageOrAuto::Length(Au(0)); margin_style.margin_left = computed::LengthOrPercentageOrAuto::Length(Au(0)); } /// Adjusts the `clip` property so that an inline absolute hypothetical fragment doesn't clip its /// children. pub fn modify_style_for_inline_absolute_hypothetical_fragment(style: &mut Arc<ComputedValues>) { if style.get_effects().clip.0.is_some() { let mut style = Arc::make_mut(style); let effects_style = Arc::make_mut(&mut style.effects); effects_style.clip.0 = None } } pub fn is_supported_property(property: &str) -> bool { match_ignore_ascii_case! { property, % for property in SHORTHANDS + LONGHANDS[:-1]: "${property.name}" => true, % endfor "${LONGHANDS[-1].name}" => true _ => property.starts_with("--") } } #[macro_export] macro_rules! css_properties_accessors { ($macro_name: ident) => { $macro_name! { % for property in SHORTHANDS + LONGHANDS: % if property.derived_from is None: % if '-' in property.name: [${property.ident.capitalize()}, Set${property.ident.capitalize()}, "${property.name}"], % endif % if property != LONGHANDS[-1]: [${property.camel_case}, Set${property.camel_case}, "${property.name}"], % else: [${property.camel_case}, Set${property.camel_case}, "${property.name}"] % endif % endif % endfor } } } macro_rules! longhand_properties_idents { ($macro_name: ident) => { $macro_name! { % for property in LONGHANDS: ${property.ident} % endfor } } } // Extra space here because < seems to be removed by Mako when immediately followed by &. // ↓ pub fn longhands_from_shorthand(shorthand: &str) -> Option< &'static [&'static str]> { % for property in SHORTHANDS: static ${property.ident.upper()}: &'static [&'static str] = &[ % for sub in property.sub_properties: "${sub.name}", % endfor ]; % endfor match_ignore_ascii_case!{ shorthand, % for property in SHORTHANDS[:-1]: "${property.name}" => Some(${property.ident.upper()}), % endfor % for property in SHORTHANDS[-1:]: "${property.name}" => Some(${property.ident.upper()}) % endfor _ => None } } /// Corresponds to the fields in `gfx::font_template::FontTemplateDescriptor`. fn compute_font_hash(font: &mut style_structs::Font) { let mut hasher: FnvHasher = Default::default(); hasher.write_u16(font.font_weight as u16); font.font_stretch.hash(&mut hasher); font.font_family.hash(&mut hasher); font.hash = hasher.finish() }
GyrosOfWar/servo
components/style/properties.mako.rs
Rust
mpl-2.0
278,613
<!DOCTYPE html> <html> <head> <style> :-moz-submit-invalid { display: none; } </style> </head> <body> <form> <input value='foo' required> <input type='submit'> </form> </body> </html>
Yukarumya/Yukarum-Redfoxes
layout/reftests/css-submit-invalid/input-submit/static-valid.html
HTML
mpl-2.0
226
DEPS = $(go list -f '{{range .TestImports}}{{.}} {{end}}' ./...) ENV = $(shell go env GOPATH) GO_VERSION = $(shell go version) GOLANG_CI_VERSION = v1.19.0 # Look for versions prior to 1.10 which have a different fmt output # and don't lint with gofmt against them. ifneq (,$(findstring go version go1.8, $(GO_VERSION))) FMT= else ifneq (,$(findstring go version go1.9, $(GO_VERSION))) FMT= else FMT=--enable gofmt endif TEST_RESULTS_DIR?=/tmp/test-results test: go test $(TESTARGS) -timeout=60s -race . go test $(TESTARGS) -timeout=60s -tags batchtest -race . integ: test INTEG_TESTS=yes go test $(TESTARGS) -timeout=25s -run=Integ . INTEG_TESTS=yes go test $(TESTARGS) -timeout=25s -tags batchtest -run=Integ . ci.test-norace: gotestsum --format=short-verbose --junitfile $(TEST_RESULTS_DIR)/gotestsum-report-test.xml -- -timeout=60s gotestsum --format=short-verbose --junitfile $(TEST_RESULTS_DIR)/gotestsum-report-test.xml -- -timeout=60s -tags batchtest ci.test: gotestsum --format=short-verbose --junitfile $(TEST_RESULTS_DIR)/gotestsum-report-test.xml -- -timeout=60s -race . gotestsum --format=short-verbose --junitfile $(TEST_RESULTS_DIR)/gotestsum-report-test.xml -- -timeout=60s -race -tags batchtest . ci.integ: ci.test INTEG_TESTS=yes gotestsum --format=short-verbose --junitfile $(TEST_RESULTS_DIR)/gotestsum-report-integ.xml -- -timeout=25s -run=Integ . INTEG_TESTS=yes gotestsum --format=short-verbose --junitfile $(TEST_RESULTS_DIR)/gotestsum-report-integ.xml -- -timeout=25s -run=Integ -tags batchtest . fuzz: go test $(TESTARGS) -timeout=20m ./fuzzy go test $(TESTARGS) -timeout=20m -tags batchtest ./fuzzy deps: go get -t -d -v ./... echo $(DEPS) | xargs -n1 go get -d lint: gofmt -s -w . golangci-lint run -c .golangci-lint.yml $(FMT) . dep-linter: curl -sfL https://install.goreleaser.com/github.com/golangci/golangci-lint.sh | sh -s -- -b $(ENV)/bin $(GOLANG_CI_VERSION) cov: INTEG_TESTS=yes gocov test github.com/hashicorp/raft | gocov-html > /tmp/coverage.html open /tmp/coverage.html .PHONY: test cov integ deps dep-linter lint
scalp42/consul
vendor/github.com/hashicorp/raft/Makefile
Makefile
mpl-2.0
2,093
# # This Source Code Form is subject to the terms of the Mozilla Public License, # v. 2.0. If a copy of the MPL was not distributed with this file, You can # obtain one at http://mozilla.org/MPL/2.0/. # # Copyright (c) 2015 Digi International Inc., All Rights Reserved. # import logging from signals import MONITOR_TOPIC_SIGNAL_MAP from socketio.namespace import BaseNamespace from socketio.sdjango import namespace from views import DevicesList, monitor_setup, monitor_devicecore_setup logger = logging.getLogger(__name__) @namespace('/device') class DeviceDataNamespace(BaseNamespace): def get_initial_acl(self): """ Don't allow any methods until authenticated """ return [] def initialize(self): """ Initialize the namespace for this socket connection. Checks that the request comes from a valid session """ # Create a new set to track monitored devices self.monitored_devices = set() if not self.request.user.is_authenticated(): logger.error( "Attempted to initialize unauthenticated socket connection") self.emit( 'error', "Attempted an unauthenticated socket connection. Do you " + "have a valid session?") return else: # Lift access control restrictions self.lift_acl_restrictions() def on_startmonitoringdevice(self, *args): for device_id in args: if device_id is not None and device_id not in \ self.monitored_devices: # Check that the requested device belongs to this user # If the local list of devices doesn't yet exist, do a device # query. if not self.request.session.get('user_devices', False): DevicesList.as_view()(self.request) if device_id in self.request.session.get('user_devices', []): logger.debug("Kicking/Creating DataPoint Monitor for %s" % device_id) mon = monitor_setup(self.request, device_id) if mon.status_code != 200: # Something went wrong with monitor setup, # return an error logger.error( 'Error while trying to set up monitor for socket') self.emit( 'error', "An error occurred while setting up the monitor " + "for this device.", mon.data) else: logger.debug( "Adding socket reciever for data for device %s" % device_id) # Add receiver for DataPoint events MONITOR_TOPIC_SIGNAL_MAP['DataPoint'][device_id]\ .connect(self.device_data_receiver) # Add receiver for DeviceCore events MONITOR_TOPIC_SIGNAL_MAP['DeviceCore'][device_id]\ .connect(self.device_status_receiver) self.monitored_devices.add(device_id) self.emit('started_monitoring', device_id) else: logger.error( "User %s attempted to start monitoring device %s," + " which is not in their account!" % (self.request.user.username, device_id)) self.emit( 'error', "Permission denied: Attempted to monitor a device " + "not in your account!") return True def on_stopmonitoringdevice(self, *args): for device_id in args: if device_id in self.monitored_devices: logger.debug("Removing socket reciever for data for device %s" % device_id) MONITOR_TOPIC_SIGNAL_MAP['DataPoint'][device_id]\ .disconnect(self.device_data_receiver) MONITOR_TOPIC_SIGNAL_MAP['DeviceCore'][device_id]\ .disconnect(self.device_status_receiver) self.monitored_devices.remove(device_id) self.emit('stopped_monitoring', device_id) return True def on_startmonitoringstatus(self, *args): """ Check for the existence of a DeviceCore monitor for this user """ mon = monitor_devicecore_setup(self.request) if mon.status_code != 200: # Something went wrong with monitor setup, return an error logger.error('Error while trying to set up monitor for socket') self.emit('error', "An error occurred while setting up the monitor for " + "this device.", mon.data) return True def disconnect(self, **kwargs): logger.debug("disconnecting socket & signal recievers") for device_id in self.monitored_devices: MONITOR_TOPIC_SIGNAL_MAP['DataPoint'][device_id]\ .disconnect(self.device_data_receiver) MONITOR_TOPIC_SIGNAL_MAP['DeviceCore'][device_id]\ .disconnect(self.device_status_receiver) self.monitored_devices.clear() super(DeviceDataNamespace, self).disconnect(**kwargs) def device_data_receiver(self, **kwargs): # Validate that we're only sending data this socket is supposed to # monitor if kwargs['device_id'] in self.monitored_devices: self.emit('device_data', kwargs['data']) return True def device_status_receiver(self, **kwargs): # Validate that we're only sending data this socket is supposed to # monitor if kwargs['device_id'] in self.monitored_devices: self.emit('device_status', kwargs['data']) return True
brucetsao/XBeeZigBeeCloudKit
xbgw_dashboard/apps/dashboard/sockets.py
Python
mpl-2.0
6,071
# this file is evaluated during config/environments/{development,production}.rb # # this needs to happen during environment config, rather than in a # config/initializer/*, to allow Rails' full initialization of the cache to # take place, including middleware inserts and such. # # (autoloading is not available yet, so we need to manually require necessary # classes) # require_dependency 'canvas' if CANVAS_RAILS2 # we want this code to run as if it were in an initializer('something', # before: "initialize_cache") {} block, but rails2 doesn't let us do fine # grained initializers. fortunately, this file is loaded during the # load_environments step that comes after the require_frameworks step and # before the initialize_cache step of boot. as long as we force # ActionController::Dispatcher to be loaded (it's already been autoloaded, # but preload_frameworks hasn't run yet), so that its middleware gets set up, # we should be set. ActionController::Dispatcher # instantiate all cache stores and put them back so the instances are # persisted over calls to Canvas.full_cache_store_config. insert # middlewares similarly to Rails' default initialize_cache initializer, but # for each value. cache_stores = Canvas.cache_stores cache_stores.keys.each do |env| cache_stores[env] = ActiveSupport::Cache.lookup_store(cache_stores[env]) if cache_stores[env].respond_to?(:middleware) config.middleware.insert_before("ActionController::Failsafe", cache_stores[env].middleware) end end # now set RAILS_CACHE so that Rails' default initialize_cache is a no-op. silence_warnings { Object.const_set "RAILS_CACHE", cache_stores[Rails.env] } else # just set to the map of configs; switchman will handle the stuff from the # rails2 branch above in an initializer. config.cache_store = Canvas.cache_stores end
arrivu/hoodemo
config/environments/cache_store.rb
Ruby
agpl-3.0
1,864
<?php /** * Zend Framework * * LICENSE * * This source file is subject to the new BSD license that is bundled * with this package in the file LICENSE.txt. * It is also available through the world-wide-web at this URL: * http://framework.zend.com/license/new-bsd * If you did not receive a copy of the license and are unable to * obtain it through the world-wide-web, please send an email * to [email protected] so we can send you a copy immediately. * * @category Zend * @package Zend_Gdata_YouTube * @subpackage UnitTests * @copyright Copyright (c) 2006 Zend Technologies USA Inc. (http://www.zend.com); * @license http://framework.zend.com/license/new-bsd New BSD License */ /** * Test helper */ require_once dirname(dirname(dirname(dirname(__FILE__)))) . DIRECTORY_SEPARATOR . 'TestHelper.php'; require_once 'Zend/Gdata/YouTube/PlaylistListFeed.php'; require_once 'Zend/Gdata/YouTube.php'; /** * @package Zend_Gdata_App * @subpackage UnitTests */ class Zend_Gdata_YouTube_PlaylistListFeedTest extends PHPUnit_Framework_TestCase { public function setUp() { $this->feedText = file_get_contents( 'Zend/Gdata/YouTube/_files/PlaylistListFeedDataSample1.xml', true); $this->feed = new Zend_Gdata_YouTube_PlaylistListFeed(); } private function verifyAllSamplePropertiesAreCorrect ($playlistListEntry) { $this->assertEquals('http://gdata.youtube.com/feeds/users/testuser/playlists', $playlistListEntry->id->text); $this->assertEquals('2007-09-20T20:59:47.530Z', $playlistListEntry->updated->text); $this->assertEquals('http://schemas.google.com/g/2005#kind', $playlistListEntry->category[0]->scheme); $this->assertEquals('http://gdata.youtube.com/schemas/2007#playlistLink', $playlistListEntry->category[0]->term); $this->assertEquals('http://www.youtube.com/img/pic_youtubelogo_123x63.gif', $playlistListEntry->logo->text); $this->assertEquals('text', $playlistListEntry->title->type); $this->assertEquals('testuser\'s Playlists', $playlistListEntry->title->text);; $this->assertEquals('self', $playlistListEntry->getLink('self')->rel); $this->assertEquals('application/atom+xml', $playlistListEntry->getLink('self')->type); $this->assertEquals('http://gdata.youtube.com/feeds/users/testuser/playlists?start-index=1&max-results=25', $playlistListEntry->getLink('self')->href); $this->assertEquals('testuser', $playlistListEntry->author[0]->name->text); $this->assertEquals('http://gdata.youtube.com/feeds/users/testuser', $playlistListEntry->author[0]->uri->text); $this->assertEquals(2, $playlistListEntry->totalResults->text); } public function testEmptyEntryShouldHaveNoExtensionElements() { $this->assertTrue(is_array($this->feed->extensionElements)); $this->assertTrue(count($this->feed->extensionElements) == 0); } public function testEmptyEntryShouldHaveNoExtensionAttributes() { $this->assertTrue(is_array($this->feed->extensionAttributes)); $this->assertTrue(count($this->feed->extensionAttributes) == 0); } public function testSampleEntryShouldHaveNoExtensionElements() { $this->feed->transferFromXML($this->feedText); $this->assertTrue(is_array($this->feed->extensionElements)); $this->assertTrue(count($this->feed->extensionElements) == 0); } public function testSampleEntryShouldHaveNoExtensionAttributes() { $this->feed->transferFromXML($this->feedText); $this->assertTrue(is_array($this->feed->extensionAttributes)); $this->assertTrue(count($this->feed->extensionAttributes) == 0); } public function testEmptyPlaylistListFeedToAndFromStringShouldMatch() { $entryXml = $this->feed->saveXML(); $newPlaylistListFeed = new Zend_Gdata_YouTube_PlaylistListFeed(); $newPlaylistListFeed->transferFromXML($entryXml); $newPlaylistListFeedXml = $newPlaylistListFeed->saveXML(); $this->assertTrue($entryXml == $newPlaylistListFeedXml); } public function testSamplePropertiesAreCorrect () { $this->feed->transferFromXML($this->feedText); $this->verifyAllSamplePropertiesAreCorrect($this->feed); } public function testConvertPlaylistListFeedToAndFromString() { $this->feed->transferFromXML($this->feedText); $entryXml = $this->feed->saveXML(); $newPlaylistListFeed = new Zend_Gdata_YouTube_PlaylistListFeed(); $newPlaylistListFeed->transferFromXML($entryXml); $this->verifyAllSamplePropertiesAreCorrect($newPlaylistListFeed); $newPlaylistListFeedXml = $newPlaylistListFeed->saveXML(); $this->assertEquals($entryXml, $newPlaylistListFeedXml); } }
ftrotter/btg
trunk/ZendGdata-1.7.1+Health/tests/Zend/Gdata/YouTube/PlaylistListFeedTest.php
PHP
agpl-3.0
4,828
/* * Kuali Coeus, a comprehensive research administration system for higher education. * * Copyright 2005-2016 Kuali, Inc. * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as * published by the Free Software Foundation, either version 3 of the * License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package org.kuali.kra.personmasschange.service; import org.kuali.kra.iacuc.IacucProtocol; import org.kuali.kra.personmasschange.bo.PersonMassChange; import java.util.List; /** * Defines the service interface for performing a Person Mass Change on IACUC Protocols. */ public interface IacucProtocolPersonMassChangeService { /** * Returns the IACUC Protocols that would have a Person Mass Change performed on them. * * @param personMassChange the Person Mass Change to be performed * @return the IACUC Protocols that would have a Person Mass Change performed on them */ List<IacucProtocol> getIacucProtocolChangeCandidates(PersonMassChange personMassChange); /** * Performs the Person Mass Change on the IACUC Protocols. * * @param personMassChange the Person Mass Change to be performed * @param iacucProtocolChangeCandidates the IACUC Protocols to perform a Person Mass Change on */ void performPersonMassChange(PersonMassChange personMassChange, List<IacucProtocol> iacucProtocolChangeCandidates); }
mukadder/kc
coeus-impl/src/main/java/org/kuali/kra/personmasschange/service/IacucProtocolPersonMassChangeService.java
Java
agpl-3.0
1,889
/* * Kuali Coeus, a comprehensive research administration system for higher education. * * Copyright 2005-2015 Kuali, Inc. * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as * published by the Free Software Foundation, either version 3 of the * License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package org.kuali.kra.award.paymentreports.paymentschedule; import org.kuali.rice.krad.rules.rule.BusinessRule; /** * This interface defines the rule processing method */ public interface AwardPaymentScheduleRule extends BusinessRule { public static final String PAYMENT_SCHEDULE_ITEMS_LIST_ERROR_KEY = "paymentScheduleItems"; /** * This method is used to validate AwardPaymentSchedule items in an Award * @param awardApprovedEquipmentRuleEvent * @return */ boolean processAwardPaymentScheduleBusinessRules(AwardPaymentScheduleRuleEvent event); /** * * This method is used to validate a new AwardPaymentSchedule to be added to an Award * @param event * @return */ boolean processAddAwardPaymentScheduleBusinessRules(AddAwardPaymentScheduleRuleEvent event); }
sanjupolus/KC6.oLatest
coeus-impl/src/main/java/org/kuali/kra/award/paymentreports/paymentschedule/AwardPaymentScheduleRule.java
Java
agpl-3.0
1,643
from os import listdir from os.path import realpath, dirname, join, isdir from sys import version_info from searx.utils import load_module from collections import defaultdict if version_info[0] == 3: unicode = str answerers_dir = dirname(realpath(__file__)) def load_answerers(): answerers = [] for filename in listdir(answerers_dir): if not isdir(join(answerers_dir, filename)) or filename.startswith('_'): continue module = load_module('answerer.py', join(answerers_dir, filename)) if not hasattr(module, 'keywords') or not isinstance(module.keywords, tuple) or not len(module.keywords): exit(2) answerers.append(module) return answerers def get_answerers_by_keywords(answerers): by_keyword = defaultdict(list) for answerer in answerers: for keyword in answerer.keywords: for keyword in answerer.keywords: by_keyword[keyword].append(answerer.answer) return by_keyword def ask(query): results = [] query_parts = list(filter(None, query.query.split())) if query_parts[0].decode('utf-8') not in answerers_by_keywords: return results for answerer in answerers_by_keywords[query_parts[0].decode('utf-8')]: result = answerer(query) if result: results.append(result) return results answerers = load_answerers() answerers_by_keywords = get_answerers_by_keywords(answerers)
misnyo/searx
searx/answerers/__init__.py
Python
agpl-3.0
1,456
<?php function Q_image_response () { $slots = Q_Response::slots(true); if (isset($slots['data'])) { return; } if (!isset($_REQUEST['hash'])) { throw new Q_Exception_WrongValue(array( 'field' => 'hash', 'range' => "identifier hash" )); } $hash = $_REQUEST['hash']; header ("Content-type: image/png"); $gravatar = isset($_REQUEST['gravatar']) ? $_REQUEST['gravatar'] : Q_Config::get('Users', 'login', 'gravatar', false); $result = Q_Image::avatar( $hash, isset($_REQUEST['size']) ? $_REQUEST['size'] : null, isset($_REQUEST['type']) ? $_REQUEST['type'] : null, $gravatar ); if ($gravatar) { echo $result; } else { imagepng($result); } return false; }
jkokh/Platform
platform/plugins/Q/handlers/Q/file/response.php
PHP
agpl-3.0
703
import _ from 'lodash'; SavedSearchService.$inject = ['api', '$filter', '$q', '$rootScope']; export function SavedSearchService(api, $filter, $q, $rootScope) { var _getAll = function(endPoint, page = 1, items = [], params = null) { return api.query(endPoint, {max_results: 200, page: page}, params) .then((result) => { let pg = page; let merged = items.concat(result._items); if (result._links.next) { pg++; return _getAll(endPoint, pg, merged, params); } return $filter('sortByName')(merged); }); }; this.savedSearches = null; this.savedSearchLookup = null; this.getAllSavedSearches = function(page, items) { var self = this; if (self.savedSearches) { return $q.when(self.savedSearches); } return _getAll('all_saved_searches', page, items) .then((savedSearches) => { self.savedSearches = savedSearches; self.savedSearchLookup = {}; _.each(savedSearches, (item) => { self.savedSearchLookup[item._id] = item; }); return savedSearches; }); }; this.getUserSavedSearches = function(userId, page, items) { return _getAll('saved_searches', page, items, userId); }; this.resetSavedSearches = function() { this.savedSearches = null; this.savedSearchLookup = null; }; // reset cache on update $rootScope.$on('savedsearch:update', angular.bind(this, this.resetSavedSearches)); }
pavlovicnemanja/superdesk-client-core
scripts/apps/search/services/SavedSearchService.ts
TypeScript
agpl-3.0
1,671
DROP VIEW IF EXISTS finance.cost_of_sale_selector_view; CREATE VIEW finance.cost_of_sale_selector_view AS SELECT finance.account_scrud_view.account_id AS cost_of_sale_id, finance.account_scrud_view.account_name AS cost_of_sale_name FROM finance.account_scrud_view WHERE account_master_id IN(SELECT * FROM finance.get_account_master_ids(20400)) ORDER BY account_id;
mixerp3/finance
db/PostgreSQL/2.x/2.0/src/05.selector-views/finance.cost_of_sale_selector_view.sql
SQL
agpl-3.0
380
/* * JBoss, Home of Professional Open Source. * Copyright 2015, Red Hat Middleware LLC, and individual contributors * as indicated by the @author tags. See the copyright.txt file in the * distribution for a full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.wildfly.extension.clustering.singleton; import java.util.EnumSet; import org.jboss.as.clustering.controller.CommonUnaryRequirement; import org.jboss.as.clustering.subsystem.AdditionalInitialization; import org.jboss.as.clustering.subsystem.ClusteringSubsystemTest; import org.junit.runner.RunWith; import org.junit.runners.Parameterized; import org.junit.runners.Parameterized.Parameters; import org.wildfly.clustering.singleton.SingletonCacheRequirement; import org.wildfly.clustering.singleton.SingletonDefaultCacheRequirement; /** * @author Paul Ferraro */ @RunWith(Parameterized.class) public class SingletonSubsystemTestCase extends ClusteringSubsystemTest<SingletonSchema> { @Parameters public static Iterable<SingletonSchema> parameters() { return EnumSet.allOf(SingletonSchema.class); } public SingletonSubsystemTestCase(SingletonSchema schema) { super(SingletonExtension.SUBSYSTEM_NAME, new SingletonExtension(), schema, "subsystem-singleton-%d_%d.xml", "schema/wildfly-singleton_%d_%d.xsd"); } @Override protected org.jboss.as.subsystem.test.AdditionalInitialization createAdditionalInitialization() { return new AdditionalInitialization() .require(CommonUnaryRequirement.OUTBOUND_SOCKET_BINDING, "binding0", "binding1") .require(SingletonDefaultCacheRequirement.SINGLETON_SERVICE_CONFIGURATOR_FACTORY, "singleton-container") .require(SingletonCacheRequirement.SINGLETON_SERVICE_CONFIGURATOR_FACTORY, "singleton-container", "singleton-cache") ; } }
jstourac/wildfly
clustering/singleton/extension/src/test/java/org/wildfly/extension/clustering/singleton/SingletonSubsystemTestCase.java
Java
lgpl-2.1
2,611
/* * Copyright (C) 2019 HAW Hamburg * * This file is subject to the terms and conditions of the GNU Lesser * General Public License v2.1. See the file LICENSE in the top level * directory for more details. */ /** * @{ * * @file * @author José Ignacio Alamos <[email protected]> * * @} */ #include <stdio.h> #include <string.h> #include "net/lora.h" #include "net/gnrc/lorawan.h" #include "net/gnrc/lorawan/region.h" #include "errno.h" #include "net/gnrc/pktbuf.h" #include "random.h" #include "net/lorawan/hdr.h" #define ENABLE_DEBUG (0) #include "debug.h" static gnrc_pktsnip_t *_build_join_req_pkt(uint8_t *appeui, uint8_t *deveui, uint8_t *appkey, uint8_t *dev_nonce) { gnrc_pktsnip_t *pkt = gnrc_pktbuf_add(NULL, NULL, sizeof(lorawan_join_request_t), GNRC_NETTYPE_UNDEF); if (pkt) { lorawan_join_request_t *hdr = (lorawan_join_request_t *) pkt->data; hdr->mt_maj = 0; lorawan_hdr_set_mtype((lorawan_hdr_t *) hdr, MTYPE_JOIN_REQUEST); lorawan_hdr_set_maj((lorawan_hdr_t *) hdr, MAJOR_LRWAN_R1); le_uint64_t l_appeui = *((le_uint64_t *) appeui); le_uint64_t l_deveui = *((le_uint64_t *) deveui); hdr->app_eui = l_appeui; hdr->dev_eui = l_deveui; le_uint16_t l_dev_nonce = *((le_uint16_t *) dev_nonce); hdr->dev_nonce = l_dev_nonce; iolist_t io = { .iol_base = pkt->data, .iol_len = JOIN_REQUEST_SIZE - MIC_SIZE, .iol_next = NULL }; gnrc_lorawan_calculate_join_mic(&io, appkey, &hdr->mic); } return pkt; } static int gnrc_lorawan_send_join_request(gnrc_lorawan_t *mac, uint8_t *deveui, uint8_t *appeui, uint8_t *appkey, uint8_t dr) { netdev_t *dev = gnrc_lorawan_get_netdev(mac); /* Dev Nonce */ uint32_t random_number; dev->driver->get(dev, NETOPT_RANDOM, &random_number, sizeof(random_number)); mac->mlme.dev_nonce[0] = random_number & 0xFF; mac->mlme.dev_nonce[1] = (random_number >> 8) & 0xFF; /* build join request */ gnrc_pktsnip_t *pkt = _build_join_req_pkt(appeui, deveui, appkey, mac->mlme.dev_nonce); if (!pkt) { return -ENOBUFS; } /* We need a random delay for join request. Otherwise there might be * network congestion if a group of nodes start at the same time */ xtimer_usleep(random_uint32() & GNRC_LORAWAN_JOIN_DELAY_U32_MASK); gnrc_lorawan_send_pkt(mac, pkt, dr); mac->mlme.backoff_budget -= mac->toa; gnrc_pktbuf_release(pkt); return GNRC_LORAWAN_REQ_STATUS_DEFERRED; } void gnrc_lorawan_mlme_process_join(gnrc_lorawan_t *mac, gnrc_pktsnip_t *pkt) { int status; if (mac->mlme.activation != MLME_ACTIVATION_NONE) { status = -EBADMSG; goto out; } if (pkt->size != GNRC_LORAWAN_JOIN_ACCEPT_MAX_SIZE - CFLIST_SIZE && pkt->size != GNRC_LORAWAN_JOIN_ACCEPT_MAX_SIZE) { status = -EBADMSG; goto out; } /* Subtract 1 from join accept max size, since the MHDR was already read */ uint8_t out[GNRC_LORAWAN_JOIN_ACCEPT_MAX_SIZE - 1]; uint8_t has_cflist = (pkt->size - 1) >= CFLIST_SIZE; gnrc_lorawan_decrypt_join_accept(mac->appskey, ((uint8_t *) pkt->data) + 1, has_cflist, out); memcpy(((uint8_t *) pkt->data) + 1, out, pkt->size - 1); iolist_t io = { .iol_base = pkt->data, .iol_len = pkt->size - MIC_SIZE, .iol_next = NULL }; le_uint32_t mic; le_uint32_t *expected_mic = (le_uint32_t *) (((uint8_t *) pkt->data) + pkt->size - MIC_SIZE); gnrc_lorawan_calculate_join_mic(&io, mac->appskey, &mic); if (mic.u32 != expected_mic->u32) { DEBUG("gnrc_lorawan_mlme: wrong MIC.\n"); status = -EBADMSG; goto out; } lorawan_join_accept_t *ja_hdr = (lorawan_join_accept_t *) pkt->data; gnrc_lorawan_generate_session_keys(ja_hdr->app_nonce, mac->mlme.dev_nonce, mac->appskey, mac->nwkskey, mac->appskey); le_uint32_t le_nid; le_nid.u32 = 0; memcpy(&le_nid, ja_hdr->net_id, 3); mac->mlme.nid = byteorder_ntohl(byteorder_ltobl(le_nid)); /* Copy devaddr */ memcpy(&mac->dev_addr, ja_hdr->dev_addr, sizeof(mac->dev_addr)); mac->dl_settings = ja_hdr->dl_settings; /* delay 0 maps to 1 second */ mac->rx_delay = ja_hdr->rx_delay ? ja_hdr->rx_delay : 1; gnrc_lorawan_process_cflist(mac, out + sizeof(lorawan_join_accept_t) - 1); mac->mlme.activation = MLME_ACTIVATION_OTAA; status = GNRC_LORAWAN_REQ_STATUS_SUCCESS; out: gnrc_pktbuf_release(pkt); mlme_confirm_t mlme_confirm; mlme_confirm.type = MLME_JOIN; mlme_confirm.status = status; gnrc_lorawan_mlme_confirm(mac, &mlme_confirm); } void gnrc_lorawan_mlme_backoff_expire(gnrc_lorawan_t *mac) { uint8_t counter = mac->mlme.backoff_state & 0x1F; uint8_t state = mac->mlme.backoff_state >> 5; if (counter == 0) { switch (state) { case GNRC_LORAWAN_BACKOFF_STATE_1: counter = GNRC_LORAWAN_BACKOFF_TIME_1; state = GNRC_LORAWAN_BACKOFF_STATE_2; mac->mlme.backoff_budget = GNRC_LORAWAN_BACKOFF_BUDGET_1; break; case GNRC_LORAWAN_BACKOFF_STATE_2: counter = GNRC_LORAWAN_BACKOFF_TIME_2; state = GNRC_LORAWAN_BACKOFF_STATE_3; mac->mlme.backoff_budget = GNRC_LORAWAN_BACKOFF_BUDGET_2; break; case GNRC_LORAWAN_BACKOFF_STATE_3: default: counter = GNRC_LORAWAN_BACKOFF_TIME_3; mac->mlme.backoff_budget = GNRC_LORAWAN_BACKOFF_BUDGET_3; break; } } counter--; mac->mlme.backoff_state = state << 5 | (counter & 0x1F); xtimer_set_msg(&mac->mlme.backoff_timer, GNRC_LORAWAN_BACKOFF_WINDOW_TICK, &mac->mlme.backoff_msg, thread_getpid()); } static void _mlme_set(gnrc_lorawan_t *mac, const mlme_request_t *mlme_request, mlme_confirm_t *mlme_confirm) { mlme_confirm->status = -EINVAL; switch(mlme_request->mib.type) { case MIB_ACTIVATION_METHOD: if(mlme_request->mib.activation != MLME_ACTIVATION_OTAA) { mlme_confirm->status = GNRC_LORAWAN_REQ_STATUS_SUCCESS; mac->mlme.activation = mlme_request->mib.activation; } break; case MIB_DEV_ADDR: mlme_confirm->status = GNRC_LORAWAN_REQ_STATUS_SUCCESS; memcpy(&mac->dev_addr, mlme_request->mib.dev_addr, sizeof(uint32_t)); break; case MIB_RX2_DR: mlme_confirm->status = GNRC_LORAWAN_REQ_STATUS_SUCCESS; gnrc_lorawan_set_rx2_dr(mac, mlme_request->mib.rx2_dr); break; default: break; } } static void _mlme_get(gnrc_lorawan_t *mac, const mlme_request_t *mlme_request, mlme_confirm_t *mlme_confirm) { switch(mlme_request->mib.type) { case MIB_ACTIVATION_METHOD: mlme_confirm->status = GNRC_LORAWAN_REQ_STATUS_SUCCESS; mlme_confirm->mib.activation = mac->mlme.activation; break; case MIB_DEV_ADDR: mlme_confirm->status = GNRC_LORAWAN_REQ_STATUS_SUCCESS; mlme_confirm->mib.dev_addr = &mac->dev_addr; break; default: mlme_confirm->status = -EINVAL; break; } } void gnrc_lorawan_mlme_request(gnrc_lorawan_t *mac, const mlme_request_t *mlme_request, mlme_confirm_t *mlme_confirm) { switch (mlme_request->type) { case MLME_JOIN: if(mac->mlme.activation != MLME_ACTIVATION_NONE) { mlme_confirm->status = -EINVAL; break; } if (!gnrc_lorawan_mac_acquire(mac)) { mlme_confirm->status = -EBUSY; break; } if (mac->mlme.backoff_budget < 0) { mlme_confirm->status = -EDQUOT; break; } memcpy(mac->appskey, mlme_request->join.appkey, LORAMAC_APPKEY_LEN); mlme_confirm->status = gnrc_lorawan_send_join_request(mac, mlme_request->join.deveui, mlme_request->join.appeui, mlme_request->join.appkey, mlme_request->join.dr); break; case MLME_LINK_CHECK: mac->mlme.pending_mlme_opts |= GNRC_LORAWAN_MLME_OPTS_LINK_CHECK_REQ; mlme_confirm->status = GNRC_LORAWAN_REQ_STATUS_DEFERRED; break; case MLME_SET: _mlme_set(mac, mlme_request, mlme_confirm); break; case MLME_GET: _mlme_get(mac, mlme_request, mlme_confirm); break; case MLME_RESET: gnrc_lorawan_reset(mac); mlme_confirm->status = GNRC_LORAWAN_REQ_STATUS_SUCCESS; break; default: break; } } int _fopts_mlme_link_check_req(lorawan_buffer_t *buf) { if (buf) { assert(buf->index + GNRC_LORAWAN_CID_SIZE <= buf->size); buf->data[buf->index++] = GNRC_LORAWAN_CID_LINK_CHECK_ANS; } return GNRC_LORAWAN_CID_SIZE; } static void _mlme_link_check_ans(gnrc_lorawan_t *mac, uint8_t *p) { mlme_confirm_t mlme_confirm; mlme_confirm.link_req.margin = p[1]; mlme_confirm.link_req.num_gateways = p[2]; mlme_confirm.type = MLME_LINK_CHECK; mlme_confirm.status = GNRC_LORAWAN_REQ_STATUS_SUCCESS; gnrc_lorawan_mlme_confirm(mac, &mlme_confirm); mac->mlme.pending_mlme_opts &= ~GNRC_LORAWAN_MLME_OPTS_LINK_CHECK_REQ; } void gnrc_lorawan_process_fopts(gnrc_lorawan_t *mac, uint8_t *fopts, size_t size) { if (!fopts || !size) { return; } uint8_t ret = 0; void (*cb)(gnrc_lorawan_t*, uint8_t *p) = NULL; for(uint8_t pos = 0; pos < size; pos += ret) { switch (fopts[pos]) { case GNRC_LORAWAN_CID_LINK_CHECK_ANS: ret += GNRC_LORAWAN_FOPT_LINK_CHECK_ANS_SIZE; cb = _mlme_link_check_ans; break; default: return; } if(pos + ret > size) { return; } cb(mac, &fopts[pos]); } } uint8_t gnrc_lorawan_build_options(gnrc_lorawan_t *mac, lorawan_buffer_t *buf) { size_t size = 0; if(mac->mlme.pending_mlme_opts & GNRC_LORAWAN_MLME_OPTS_LINK_CHECK_REQ) { size += _fopts_mlme_link_check_req(buf); } return size; } void gnrc_lorawan_mlme_no_rx(gnrc_lorawan_t *mac) { mlme_confirm_t mlme_confirm; mlme_confirm.status = -ETIMEDOUT; if (mac->mlme.activation == MLME_ACTIVATION_NONE) { mlme_confirm.type = MLME_JOIN; gnrc_lorawan_mlme_confirm(mac, &mlme_confirm); } else if (mac->mlme.pending_mlme_opts & GNRC_LORAWAN_MLME_OPTS_LINK_CHECK_REQ) { mlme_confirm.type = MLME_LINK_CHECK; gnrc_lorawan_mlme_confirm(mac, &mlme_confirm); mac->mlme.pending_mlme_opts &= ~GNRC_LORAWAN_MLME_OPTS_LINK_CHECK_REQ; } }
yogo1212/RIOT
sys/net/gnrc/link_layer/lorawan/gnrc_lorawan_mlme.c
C
lgpl-2.1
11,148
<html> <head> <meta charset='utf-8'> <style> .pass { font-weight: bold; color: green; } .fail { font-weight: bold; color: red; } </style> <script> if (window.testRunner) testRunner.dumpAsText(); function SputnikError(message) { this.message = message; } SputnikError.prototype.toString = function () { return 'SputnikError: ' + this.message; }; var sputnikException; function testPrint(msg) { var span = document.createElement("span"); document.getElementById("console").appendChild(span); // insert it first so XHTML knows the namespace span.innerHTML = msg + '<br />'; } function escapeHTML(text) { return text.toString().replace(/&/g, "&amp;").replace(/</g, "&lt;"); } function printTestPassed(msg) { testPrint('<span><span class="pass">PASS</span> ' + escapeHTML(msg) + '</span>'); } function printTestFailed(msg) { testPrint('<span><span class="fail">FAIL</span> ' + escapeHTML(msg) + '</span>'); } function testFailed(msg) { throw new SputnikError(msg); } var successfullyParsed = false; </script> </head> <body> <p>S11.13.2_A4.10_T2.3</p> <div id='console'></div> <script> try { /** * @name: S11.13.2_A4.10_T2.3; * @section: 11.13.2, 11.10.2; * @assertion: The production x ^= y is the same as x = x ^ y; * @description: Type(x) is different from Type(y) and both types vary between Number (primitive or object) and Null; */ //CHECK#1 x = 1; x ^= null; if (x !== 1) { testFailed('#1: x = 1; x ^= null; x === 1. Actual: ' + (x)); } //CHECK#2 x = null; x ^= 1; if (x !== 1) { testFailed('#2: x = null; x ^= 1; x === 1. Actual: ' + (x)); } //CHECK#3 x = new Number(1); x ^= null; if (x !== 1) { testFailed('#3: x = new Number(1); x ^= null; x === 1. Actual: ' + (x)); } //CHECK#4 x = null; x ^= new Number(1); if (x !== 1) { testFailed('#4: x = null; x ^= new Number(1); x === 1. Actual: ' + (x)); } } catch (ex) { sputnikException = ex; } var successfullyParsed = true; </script> <script> if (!successfullyParsed) printTestFailed('successfullyParsed is not set'); else if (sputnikException) printTestFailed(sputnikException); else printTestPassed(""); testPrint('<br /><span class="pass">TEST COMPLETE</span>'); </script> </body> </html>
youfoh/webkit-efl
LayoutTests/sputnik/Conformance/11_Expressions/11.13_Assignment_Operators/11.13.2_Compound_Assignment/S11.13.2_A4.10_T2.3.html
HTML
lgpl-2.1
2,249
############################################################################## # Copyright (c) 2013-2018, Lawrence Livermore National Security, LLC. # Produced at the Lawrence Livermore National Laboratory. # # This file is part of Spack. # Created by Todd Gamblin, [email protected], All rights reserved. # LLNL-CODE-647188 # # For details, see https://github.com/spack/spack # Please also see the NOTICE and LICENSE files for our notice and the LGPL. # # This program is free software; you can redistribute it and/or modify # it under the terms of the GNU Lesser General Public License (as # published by the Free Software Foundation) version 2.1, February 1999. # # 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 terms and # conditions of 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, write to the Free Software # Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA ############################################################################## from spack import * class Tantan(MakefilePackage): """tantan is a tool to mask simple regions (low complexity and short-period tandem repeats) in DNA, RNA, and protein sequences.""" homepage = "http://cbrc3.cbrc.jp/~martin/tantan" url = "http://cbrc3.cbrc.jp/~martin/tantan/tantan-13.zip" version('13', '90a30284a7d0cd04d797527d47bc8bd0') def install(self, spec, prefix): make('prefix={0}'.format(self.prefix), 'install')
krafczyk/spack
var/spack/repos/builtin/packages/tantan/package.py
Python
lgpl-2.1
1,699
/* * Copyright (C) 2018 Gunar Schorcht * * This file is subject to the terms and conditions of the GNU Lesser * General Public License v2.1. See the file LICENSE in the top level * directory for more details. */ /** * @ingroup cpu_esp32 * @{ * * @file * @brief Implementation of the kernel's architecture dependent thread interface * * @author Gunar Schorcht <[email protected]> * * @} */ /* * PLEASE NOTE: Some parts of the code are taken from the FreeRTOS port for * Xtensa processors from Cadence Design Systems. These parts are marked * accordingly. For these parts, the following license is valid: * * Copyright (c) 2003-2015 Cadence Design Systems, Inc. * * Permission is hereby granted, free of charge, to any person obtaining * a copy of this software and associated documentation files (the * "Software"), to deal in the Software without restriction, including * without limitation the rights to use, copy, modify, merge, publish, * distribute, sublicense, and/or sell copies of the Software, and to * permit persons to whom the Software is furnished to do so, subject to * the following conditions: * * The above copyright notice and this permission notice shall be included * in all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. * IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY * CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, * TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE * SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ #define ENABLE_DEBUG (0) #include "debug.h" #include <stdio.h> #include <string.h> #include "board.h" #include "cpu.h" #include "irq.h" #include "log.h" #include "thread.h" #include "sched.h" #include "esp_common.h" #include "irq_arch.h" #include "syscalls.h" #include "tools.h" #include "esp/xtensa_ops.h" #include "rom/ets_sys.h" #include "soc/dport_reg.h" #include "xtensa/xtensa_context.h" /* User exception dispatcher when exiting */ extern void _xt_user_exit(void); /* Switch context to the highest priority ready task without context save */ extern void _frxt_dispatch(void); /* Set an flag indicating that a task switch is required on return from interrupt */ extern void _frxt_setup_switch(void); /* Switch context to the highest priority ready task with context save */ extern void vPortYield(void); extern void vPortYieldFromInt(void); /* forward declarations */ NORETURN void task_exit(void); char* thread_stack_init(thread_task_func_t task_func, void *arg, void *stack_start, int stack_size) { /* Stack layout after task stack initialization * * +------------------------+ * | | TOP * | thread_control_block | * stack_start + stack_size ==> | | top_of_stack+1 * +------------------------+ * top_of_stack ==> | | * | XT_CP_SA | * | (optional) | * | ... | ... * | cpstored | XT_CPSTORED * top_of_stack + 1 - XT_CP_SIZE ==> | cpenable | XT_CPENABLE * (cp_state) +------------------------+ * | | * | XT_STK_FRAME | * | | XT_STK_... * | a2 = arg | XT_STK_A2 * | a1 = sp + XT_STK_FRMSZ | XT_STK_A1 * | a0 = sched_task_exit | XT_STK_A0 * | ps = PS_UM | PS_EXCM | XT_STK_PS * | pc = task_func | XT_STK_PC * sp = top_of_stack + 1 - XT_CP_SIZE ==> | exit = _xt_user_exit | XT_STK_EXIT * - XT_STK_FRMSZ +------------------------+ * | | * | remaining stack space | * | available for data | * stack_start (preallocated var) ==> | | BOTTOM * +------------------------+ * * Initialized stack frame represents the registers as set when the * the task function would have been called. * * Registers in a called function * * pc - PC at the beginning in the function * a0 - return address from the function (return address to caller) * a1 - current stack pointer at the beginning in the function * a2 - first argument of the function */ /* stack is [stack_start+0 ... stack_start+stack_size-1] */ uint8_t *top_of_stack; uint8_t *sp; top_of_stack = (uint8_t*)((uint32_t)stack_start + stack_size-1); /* BEGIN - code from FreeRTOS port for Xtensa from Cadence */ /* Create interrupt stack frame aligned to 16 byte boundary */ sp = (uint8_t*)(((uint32_t)(top_of_stack+1) - XT_STK_FRMSZ - XT_CP_SIZE) & ~0xf); /* Clear whole stack with a known value to assist debugging */ #if !defined(DEVELHELP) && !defined(SCHED_TEST_STACK) /* Unfortunatly, this affects thread_measure_stack_free function */ memset(stack_start, 0, stack_size); #else memset(sp, 0, XT_STK_FRMSZ + XT_CP_SIZE); #endif /* ensure that stack is big enough */ assert (sp > (uint8_t*)stack_start); XtExcFrame* exc_frame = (XtExcFrame*)sp; /* Explicitly initialize certain saved registers for call0 ABI */ exc_frame->pc = (uint32_t)task_func; /* task entry point */ exc_frame->a0 = (uint32_t)task_exit; /* task exit point*/ exc_frame->a1 = (uint32_t)sp + XT_STK_FRMSZ; /* physical top of stack frame */ exc_frame->exit = (uint32_t)_xt_user_exit; /* user exception exit dispatcher */ /* Set initial PS to int level 0, EXCM disabled ('rfe' will enable), user mode. */ /* Also set entry point argument parameter. */ #ifdef __XTENSA_CALL0_ABI__ /* for CALL0 ABI set in parameter a2 to task argument */ exc_frame->ps = PS_UM | PS_EXCM; exc_frame->a2 = (uint32_t)arg; /* parameters for task_func */ #else /* for Windowed Register ABI set PS.CALLINC=01 to handle task entry as call4 return address in a4 and parameter in a6 and */ exc_frame->ps = PS_UM | PS_EXCM | PS_WOE | PS_CALLINC(1); exc_frame->a4 = (uint32_t)task_exit; /* task exit point*/ exc_frame->a6 = (uint32_t)arg; /* parameters for task_func */ #endif #ifdef XT_USE_SWPRI /* Set the initial virtual priority mask value to all 1's. */ exc_frame->vpri = 0xFFFFFFFF; #endif #if XCHAL_CP_NUM > 0 /* Init the coprocessor save area (see xtensa_context.h) */ /* No access to TCB here, so derive indirectly. Stack growth is top to bottom. */ /* p = (uint32_t *) xMPUSettings->coproc_area; */ uint32_t *p; p = (uint32_t *)(((uint32_t) top_of_stack+1 - XT_CP_SIZE)); p[0] = 0; p[1] = 0; p[2] = (((uint32_t) p) + 12 + XCHAL_TOTAL_SA_ALIGN - 1) & -XCHAL_TOTAL_SA_ALIGN; #endif /* END - code from FreeRTOS port for Xtensa from Cadence */ DEBUG("%s start=%p size=%d top=%p sp=%p free=%u\n", __func__, stack_start, stack_size, top_of_stack, sp, sp-(uint8_t*)stack_start); return (char*)sp; } /** * Context switches are realized using software interrupts since interrupt * entry and exit functions are the only way to save and restore complete * context including spilling the register windows to the stack */ void IRAM_ATTR thread_yield_isr(void* arg) { /* clear the interrupt first */ DPORT_WRITE_PERI_REG(DPORT_CPU_INTR_FROM_CPU_0_REG, 0); /* set the context switch flag (indicates that context has to be switched is switch on exit from interrupt in _frxt_int_exit */ _frxt_setup_switch(); } /** * If we are already in an interrupt handler, the function simply sets the * context switch flag, which indicates that the context has to be switched * in the _frxt_int_exit function when exiting the interrupt. Otherwise, we * will generate a software interrupt to force the context switch when * terminating the software interrupt (see thread_yield_isr). */ void thread_yield_higher(void) { /* reset hardware watchdog */ system_wdt_feed(); /* yield next task */ #if defined(ENABLE_DEBUG) && defined(DEVELHELP) if (sched_active_thread) { DEBUG("%u old task %u %s %u\n", system_get_time(), sched_active_thread->pid, sched_active_thread->name, sched_active_thread->sp - sched_active_thread-> stack_start); } #endif if (!irq_is_in()) { /* generate the software interrupt to switch the context */ DPORT_WRITE_PERI_REG(DPORT_CPU_INTR_FROM_CPU_0_REG, DPORT_CPU_INTR_FROM_CPU_0); } else { /* set the context switch flag */ _frxt_setup_switch(); } #if defined(ENABLE_DEBUG) && defined(DEVELHELP) if (sched_active_thread) { DEBUG("%u new task %u %s %u\n", system_get_time(), sched_active_thread->pid, sched_active_thread->name, sched_active_thread->sp - sched_active_thread-> stack_start); } #endif /* * Instruction fetch synchronize: Waits for all previously fetched load, * store, cache, and special register write instructions that affect * instruction fetch to be performed before fetching the next instruction. */ __asm__("isync"); return; } void thread_stack_print(void) { /* Print the current stack to stdout. */ #if defined(DEVELHELP) volatile thread_t* task = thread_get(sched_active_pid); if (task) { char* stack_top = task->stack_start + task->stack_size; int size = stack_top - task->sp; printf("Printing current stack of thread %" PRIkernel_pid "\n", thread_getpid()); esp_hexdump((void*)(task->sp), size >> 2, 'w', 8); } #else NOT_SUPPORTED(); #endif } void thread_print_stack(void) { /* Prints human readable, ps-like thread information for debugging purposes. */ /* because of Xtensa stack structure and call ABI, it is not possible to implement */ NOT_YET_IMPLEMENTED(); return; } #ifdef DEVELHELP extern uint8_t port_IntStack; extern uint8_t port_IntStackTop; void thread_isr_stack_init(void) { /* code from thread.c, please see the copyright notice there */ /* assign each int of the stack the value of it's address */ uintptr_t *stackmax = (uintptr_t *)&port_IntStackTop; uintptr_t *stackp = (uintptr_t *)&port_IntStack; while (stackp < stackmax) { *stackp = (uintptr_t) stackp; stackp++; } } int thread_isr_stack_usage(void) { return &port_IntStackTop - &port_IntStack - thread_measure_stack_free((char*)&port_IntStack); } void *thread_isr_stack_pointer(void) { /* Get the current ISR stack pointer. */ return &port_IntStackTop; } void *thread_isr_stack_start(void) { /* Get the start of the ISR stack. */ return &port_IntStack; } void thread_isr_stack_print(void) { printf("Printing current ISR\n"); esp_hexdump(&port_IntStack, &port_IntStackTop-&port_IntStack, 'w', 8); } #else /* DEVELHELP */ void thread_isr_stack_init(void) {} #endif /* DEVELHELP */ static bool _initial_exit = true; /** * The function is used on task exit to switch to the context to the next * running task. It realizes only the second half of a complete context by * simulating the exit from an interrupt handling where a context switch is * forced. The old context is not saved here since it is no longer needed. */ NORETURN void task_exit(void) { DEBUG("sched_task_exit: ending thread %" PRIkernel_pid "...\n", sched_active_thread ? sched_active_thread->pid : KERNEL_PID_UNDEF); (void) irq_disable(); /* remove old task from scheduling if it is not already done */ if (sched_active_thread) { sched_threads[sched_active_pid] = NULL; sched_num_threads--; sched_set_status((thread_t *)sched_active_thread, STATUS_STOPPED); sched_active_thread = NULL; } /* determine the new running task */ sched_run(); /* set the context switch flag (indicates that context has to be switched is switch on exit from interrupt in _frxt_int_exit */ _frxt_setup_switch(); /* set interrupt nesting level to the right value */ irq_interrupt_nesting++; /* reset windowed registers */ __asm__ volatile ("movi a2, 0\n" "wsr a2, windowstart\n" "wsr a2, windowbase\n" "rsync\n"); /* exit from simulated interrupt to switch to the new context */ __asm__ volatile ("call0 _frxt_int_exit"); /* should not be executed */ UNREACHABLE(); } NORETURN void cpu_switch_context_exit(void) { DEBUG("%s\n", __func__); /* Switch context to the highest priority ready task without context save */ if (_initial_exit) { _initial_exit = false; __asm__ volatile ("call0 _frxt_dispatch"); } else { task_exit(); } UNREACHABLE(); }
lazytech-org/RIOT
cpu/esp32/thread_arch.c
C
lgpl-2.1
14,103
# cerbero - a multi-platform build system for Open Source software # Copyright (C) 2012 Andoni Morales Alastruey <[email protected]> # # This library is free software; you can redistribute it and/or # modify it under the terms of the GNU Library General Public # License as published by the Free Software Foundation; either # version 2 of the License, or (at your option) any later version. # # This library is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU # Library General Public License for more details. # # You should have received a copy of the GNU Library General Public # License along with this library; if not, write to the # Free Software Foundation, Inc., 59 Temple Place - Suite 330, # Boston, MA 02111-1307, USA. __all__ = ['Command', 'register_command', 'run'] from cerbero.errors import FatalError from cerbero.utils import _ from cerbero.utils import messages as m class Command: """Base class for Command objects""" doc = '' name = None def __init__(self, arguments=[]): self.arguments = arguments def run(self, config, args): """The body of the command""" raise NotImplementedError def add_parser(self, subparsers): self.parser = subparsers.add_parser(self.name, help=_(self.doc)) for arg in self.arguments: arg.add_to_parser(self.parser) # dictionary with the list of commands # command_name -> command_instance _commands = {} def register_command(command_class): command = command_class() _commands[command.name] = command def load_commands(subparsers): import os commands_dir = os.path.abspath(os.path.dirname(__file__)) for name in os.listdir(commands_dir): name, extension = os.path.splitext(name) if extension != '.py': continue try: __import__('cerbero.commands.%s' % name) except ImportError as e: m.warning("Error importing command %s:\n %s" % (name, e)) for command in _commands.values(): command.add_parser(subparsers) def run(command, config, args): # if the command hasn't been registered, load a module by the same name if command not in _commands: raise FatalError(_('command not found')) return _commands[command].run(config, args)
nirbheek/cerbero
cerbero/commands/__init__.py
Python
lgpl-2.1
2,418
/** * fsck.c * * Copyright (c) 2013 Samsung Electronics Co., Ltd. * http://www.samsung.com/ * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License version 2 as * published by the Free Software Foundation. */ #include "fsck.h" char *tree_mark; uint32_t tree_mark_size = 256; static inline int f2fs_set_main_bitmap(struct f2fs_sb_info *sbi, u32 blk) { struct f2fs_fsck *fsck = F2FS_FSCK(sbi); return f2fs_set_bit(BLKOFF_FROM_MAIN(sbi, blk), fsck->main_area_bitmap); } static inline int f2fs_test_main_bitmap(struct f2fs_sb_info *sbi, u32 blk) { struct f2fs_fsck *fsck = F2FS_FSCK(sbi); return f2fs_test_bit(BLKOFF_FROM_MAIN(sbi, blk), fsck->main_area_bitmap); } static inline int f2fs_test_sit_bitmap(struct f2fs_sb_info *sbi, u32 blk) { struct f2fs_fsck *fsck = F2FS_FSCK(sbi); return f2fs_test_bit(BLKOFF_FROM_MAIN(sbi, blk), fsck->sit_area_bitmap); } static int add_into_hard_link_list(struct f2fs_sb_info *sbi, u32 nid, u32 link_cnt) { struct f2fs_fsck *fsck = F2FS_FSCK(sbi); struct hard_link_node *node = NULL, *tmp = NULL, *prev = NULL; node = calloc(sizeof(struct hard_link_node), 1); ASSERT(node != NULL); node->nid = nid; node->links = link_cnt; node->next = NULL; if (fsck->hard_link_list_head == NULL) { fsck->hard_link_list_head = node; goto out; } tmp = fsck->hard_link_list_head; /* Find insertion position */ while (tmp && (nid < tmp->nid)) { ASSERT(tmp->nid != nid); prev = tmp; tmp = tmp->next; } if (tmp == fsck->hard_link_list_head) { node->next = tmp; fsck->hard_link_list_head = node; } else { prev->next = node; node->next = tmp; } out: DBG(2, "ino[0x%x] has hard links [0x%x]\n", nid, link_cnt); return 0; } static int find_and_dec_hard_link_list(struct f2fs_sb_info *sbi, u32 nid) { struct f2fs_fsck *fsck = F2FS_FSCK(sbi); struct hard_link_node *node = NULL, *prev = NULL; if (fsck->hard_link_list_head == NULL) return -EINVAL; node = fsck->hard_link_list_head; while (node && (nid < node->nid)) { prev = node; node = node->next; } if (node == NULL || (nid != node->nid)) return -EINVAL; /* Decrease link count */ node->links = node->links - 1; /* if link count becomes one, remove the node */ if (node->links == 1) { if (fsck->hard_link_list_head == node) fsck->hard_link_list_head = node->next; else prev->next = node->next; free(node); } return 0; } static int is_valid_ssa_node_blk(struct f2fs_sb_info *sbi, u32 nid, u32 blk_addr) { int ret = 0; struct f2fs_summary sum_entry; ret = get_sum_entry(sbi, blk_addr, &sum_entry); if (ret != SEG_TYPE_NODE && ret != SEG_TYPE_CUR_NODE) { ASSERT_MSG("Summary footer is not for node segment"); return -EINVAL; } if (le32_to_cpu(sum_entry.nid) != nid) { DBG(0, "nid [0x%x]\n", nid); DBG(0, "target blk_addr [0x%x]\n", blk_addr); DBG(0, "summary blk_addr [0x%x]\n", GET_SUM_BLKADDR(sbi, GET_SEGNO(sbi, blk_addr))); DBG(0, "seg no / offset [0x%x / 0x%x]\n", GET_SEGNO(sbi, blk_addr), OFFSET_IN_SEG(sbi, blk_addr)); DBG(0, "summary_entry.nid [0x%x]\n", le32_to_cpu(sum_entry.nid)); DBG(0, "--> node block's nid [0x%x]\n", nid); ASSERT_MSG("Invalid node seg summary\n"); return -EINVAL; } return 0; } static int is_valid_ssa_data_blk(struct f2fs_sb_info *sbi, u32 blk_addr, u32 parent_nid, u16 idx_in_node, u8 version) { int ret = 0; struct f2fs_summary sum_entry; ret = get_sum_entry(sbi, blk_addr, &sum_entry); if (ret != SEG_TYPE_DATA && ret != SEG_TYPE_CUR_DATA) { ASSERT_MSG("Summary footer is not for data segment"); return -EINVAL; } if (le32_to_cpu(sum_entry.nid) != parent_nid || sum_entry.version != version || le16_to_cpu(sum_entry.ofs_in_node) != idx_in_node) { DBG(0, "summary_entry.nid [0x%x]\n", le32_to_cpu(sum_entry.nid)); DBG(0, "summary_entry.version [0x%x]\n", sum_entry.version); DBG(0, "summary_entry.ofs_in_node [0x%x]\n", le16_to_cpu(sum_entry.ofs_in_node)); DBG(0, "parent nid [0x%x]\n", parent_nid); DBG(0, "version from nat [0x%x]\n", version); DBG(0, "idx in parent node [0x%x]\n", idx_in_node); DBG(0, "Target data block addr [0x%x]\n", blk_addr); ASSERT_MSG("Invalid data seg summary\n"); return -EINVAL; } return 0; } static int sanity_check_nid(struct f2fs_sb_info *sbi, u32 nid, struct f2fs_node *node_blk, enum FILE_TYPE ftype, enum NODE_TYPE ntype, struct node_info *ni) { struct f2fs_fsck *fsck = F2FS_FSCK(sbi); int ret; if (!IS_VALID_NID(sbi, nid)) { ASSERT_MSG("nid is not valid. [0x%x]", nid); return -EINVAL; } get_node_info(sbi, nid, ni); if (ni->blk_addr == NEW_ADDR) { ASSERT_MSG("nid is NEW_ADDR. [0x%x]", nid); return -EINVAL; } if (!IS_VALID_BLK_ADDR(sbi, ni->blk_addr)) { ASSERT_MSG("blkaddres is not valid. [0x%x]", ni->blk_addr); return -EINVAL; } if (is_valid_ssa_node_blk(sbi, nid, ni->blk_addr)) { ASSERT_MSG("summary node block is not valid. [0x%x]", nid); return -EINVAL; } ret = dev_read_block(node_blk, ni->blk_addr); ASSERT(ret >= 0); if (ntype == TYPE_INODE && node_blk->footer.nid != node_blk->footer.ino) { ASSERT_MSG("nid[0x%x] footer.nid[0x%x] footer.ino[0x%x]", nid, le32_to_cpu(node_blk->footer.nid), le32_to_cpu(node_blk->footer.ino)); return -EINVAL; } if (ntype != TYPE_INODE && node_blk->footer.nid == node_blk->footer.ino) { ASSERT_MSG("nid[0x%x] footer.nid[0x%x] footer.ino[0x%x]", nid, le32_to_cpu(node_blk->footer.nid), le32_to_cpu(node_blk->footer.ino)); return -EINVAL; } if (le32_to_cpu(node_blk->footer.nid) != nid) { ASSERT_MSG("nid[0x%x] blk_addr[0x%x] footer.nid[0x%x]", nid, ni->blk_addr, le32_to_cpu(node_blk->footer.nid)); return -EINVAL; } if (ntype == TYPE_XATTR) { u32 flag = le32_to_cpu(node_blk->footer.flag); if ((flag >> OFFSET_BIT_SHIFT) != XATTR_NODE_OFFSET) { ASSERT_MSG("xnid[0x%x] has wrong ofs:[0x%x]", nid, flag); return -EINVAL; } } if ((ntype == TYPE_INODE && ftype == F2FS_FT_DIR) || (ntype == TYPE_XATTR && ftype == F2FS_FT_XATTR)) { /* not included '.' & '..' */ if (f2fs_test_main_bitmap(sbi, ni->blk_addr) != 0) { ASSERT_MSG("Duplicated node blk. nid[0x%x][0x%x]\n", nid, ni->blk_addr); return -EINVAL; } } /* workaround to fix later */ if (ftype != F2FS_FT_ORPHAN || f2fs_test_bit(nid, fsck->nat_area_bitmap) != 0) f2fs_clear_bit(nid, fsck->nat_area_bitmap); else ASSERT_MSG("orphan or xattr nid is duplicated [0x%x]\n", nid); if (f2fs_test_sit_bitmap(sbi, ni->blk_addr) == 0) ASSERT_MSG("SIT bitmap is 0x0. blk_addr[0x%x]", ni->blk_addr); if (f2fs_test_main_bitmap(sbi, ni->blk_addr) == 0) { fsck->chk.valid_blk_cnt++; fsck->chk.valid_node_cnt++; } return 0; } static int fsck_chk_xattr_blk(struct f2fs_sb_info *sbi, u32 ino, u32 x_nid, u32 *blk_cnt) { struct f2fs_node *node_blk = NULL; struct node_info ni; int ret = 0; if (x_nid == 0x0) return 0; node_blk = (struct f2fs_node *)calloc(BLOCK_SZ, 1); ASSERT(node_blk != NULL); /* Sanity check */ if (sanity_check_nid(sbi, x_nid, node_blk, F2FS_FT_XATTR, TYPE_XATTR, &ni)) { ret = -EINVAL; goto out; } *blk_cnt = *blk_cnt + 1; f2fs_set_main_bitmap(sbi, ni.blk_addr); DBG(2, "ino[0x%x] x_nid[0x%x]\n", ino, x_nid); out: free(node_blk); return ret; } int fsck_chk_node_blk(struct f2fs_sb_info *sbi, struct f2fs_inode *inode, u32 nid, enum FILE_TYPE ftype, enum NODE_TYPE ntype, u32 *blk_cnt) { struct node_info ni; struct f2fs_node *node_blk = NULL; node_blk = (struct f2fs_node *)calloc(BLOCK_SZ, 1); ASSERT(node_blk != NULL); if (sanity_check_nid(sbi, nid, node_blk, ftype, ntype, &ni)) goto err; if (ntype == TYPE_INODE) { fsck_chk_inode_blk(sbi, nid, ftype, node_blk, blk_cnt, &ni); } else { f2fs_set_main_bitmap(sbi, ni.blk_addr); switch (ntype) { case TYPE_DIRECT_NODE: fsck_chk_dnode_blk(sbi, inode, nid, ftype, node_blk, blk_cnt, &ni); break; case TYPE_INDIRECT_NODE: fsck_chk_idnode_blk(sbi, inode, ftype, node_blk, blk_cnt); break; case TYPE_DOUBLE_INDIRECT_NODE: fsck_chk_didnode_blk(sbi, inode, ftype, node_blk, blk_cnt); break; default: ASSERT(0); } } free(node_blk); return 0; err: free(node_blk); return -EINVAL; } /* start with valid nid and blkaddr */ void fsck_chk_inode_blk(struct f2fs_sb_info *sbi, u32 nid, enum FILE_TYPE ftype, struct f2fs_node *node_blk, u32 *blk_cnt, struct node_info *ni) { struct f2fs_fsck *fsck = F2FS_FSCK(sbi); u32 child_cnt = 0, child_files = 0; enum NODE_TYPE ntype; u32 i_links = le32_to_cpu(node_blk->i.i_links); u64 i_blocks = le64_to_cpu(node_blk->i.i_blocks); unsigned int idx = 0; int need_fix = 0; int ret; if (f2fs_test_main_bitmap(sbi, ni->blk_addr) == 0) fsck->chk.valid_inode_cnt++; if (ftype == F2FS_FT_DIR) { f2fs_set_main_bitmap(sbi, ni->blk_addr); } else { if (f2fs_test_main_bitmap(sbi, ni->blk_addr) == 0) { f2fs_set_main_bitmap(sbi, ni->blk_addr); if (i_links > 1) { /* First time. Create new hard link node */ add_into_hard_link_list(sbi, nid, i_links); fsck->chk.multi_hard_link_files++; } } else { DBG(3, "[0x%x] has hard links [0x%x]\n", nid, i_links); if (find_and_dec_hard_link_list(sbi, nid)) { ASSERT_MSG("[0x%x] needs more i_links=0x%x", nid, i_links); if (config.fix_on) { node_blk->i.i_links = cpu_to_le32(i_links + 1); need_fix = 1; FIX_MSG("File: 0x%x " "i_links= 0x%x -> 0x%x", nid, i_links, i_links + 1); } goto check; } /* No need to go deep into the node */ return; } } if (fsck_chk_xattr_blk(sbi, nid, le32_to_cpu(node_blk->i.i_xattr_nid), blk_cnt) && config.fix_on) { node_blk->i.i_xattr_nid = 0; need_fix = 1; FIX_MSG("Remove xattr block: 0x%x, x_nid = 0x%x", nid, le32_to_cpu(node_blk->i.i_xattr_nid)); } if (ftype == F2FS_FT_CHRDEV || ftype == F2FS_FT_BLKDEV || ftype == F2FS_FT_FIFO || ftype == F2FS_FT_SOCK) goto check; if((node_blk->i.i_inline & F2FS_INLINE_DATA)) { if (le32_to_cpu(node_blk->i.i_addr[0]) != 0) { /* should fix this bug all the time */ FIX_MSG("inline_data has wrong 0'th block = %x", le32_to_cpu(node_blk->i.i_addr[0])); node_blk->i.i_addr[0] = 0; node_blk->i.i_blocks = cpu_to_le64(*blk_cnt); need_fix = 1; } if (!(node_blk->i.i_inline & F2FS_DATA_EXIST)) { char buf[MAX_INLINE_DATA]; memset(buf, 0, MAX_INLINE_DATA); if (memcmp(buf, &node_blk->i.i_addr[1], MAX_INLINE_DATA)) { FIX_MSG("inline_data has DATA_EXIST"); node_blk->i.i_inline |= F2FS_DATA_EXIST; need_fix = 1; } } DBG(3, "ino[0x%x] has inline data!\n", nid); goto check; } if((node_blk->i.i_inline & F2FS_INLINE_DENTRY)) { DBG(3, "ino[0x%x] has inline dentry!\n", nid); ret = fsck_chk_inline_dentries(sbi, node_blk, &child_cnt, &child_files); if (ret < 0) { /* should fix this bug all the time */ need_fix = 1; } goto check; } /* check data blocks in inode */ for (idx = 0; idx < ADDRS_PER_INODE(&node_blk->i); idx++) { if (le32_to_cpu(node_blk->i.i_addr[idx]) != 0) { ret = fsck_chk_data_blk(sbi, le32_to_cpu(node_blk->i.i_addr[idx]), &child_cnt, &child_files, (i_blocks == *blk_cnt), ftype, nid, idx, ni->version); if (!ret) { *blk_cnt = *blk_cnt + 1; } else if (config.fix_on) { node_blk->i.i_addr[idx] = 0; need_fix = 1; FIX_MSG("[0x%x] i_addr[%d] = 0", nid, idx); } } } /* check node blocks in inode */ for (idx = 0; idx < 5; idx++) { if (idx == 0 || idx == 1) ntype = TYPE_DIRECT_NODE; else if (idx == 2 || idx == 3) ntype = TYPE_INDIRECT_NODE; else if (idx == 4) ntype = TYPE_DOUBLE_INDIRECT_NODE; else ASSERT(0); if (le32_to_cpu(node_blk->i.i_nid[idx]) != 0) { ret = fsck_chk_node_blk(sbi, &node_blk->i, le32_to_cpu(node_blk->i.i_nid[idx]), ftype, ntype, blk_cnt); if (!ret) { *blk_cnt = *blk_cnt + 1; } else if (config.fix_on) { node_blk->i.i_nid[idx] = 0; need_fix = 1; FIX_MSG("[0x%x] i_nid[%d] = 0", nid, idx); } } } check: if (ftype == F2FS_FT_DIR) DBG(1, "Directory Inode: 0x%x [%s] depth: %d has %d files\n\n", le32_to_cpu(node_blk->footer.ino), node_blk->i.i_name, le32_to_cpu(node_blk->i.i_current_depth), child_files); if (ftype == F2FS_FT_ORPHAN) DBG(1, "Orphan Inode: 0x%x [%s] i_blocks: %u\n\n", le32_to_cpu(node_blk->footer.ino), node_blk->i.i_name, (u32)i_blocks); if (i_blocks != *blk_cnt) { ASSERT_MSG("ino: 0x%x has i_blocks: %08"PRIx64", " "but has %u blocks", nid, i_blocks, *blk_cnt); if (config.fix_on) { node_blk->i.i_blocks = cpu_to_le64(*blk_cnt); need_fix = 1; FIX_MSG("[0x%x] i_blocks=0x%08"PRIx64" -> 0x%x", nid, i_blocks, *blk_cnt); } } if (ftype == F2FS_FT_DIR && i_links != child_cnt) { ASSERT_MSG("ino: 0x%x has i_links: %u but real links: %u", nid, i_links, child_cnt); if (config.fix_on) { node_blk->i.i_links = cpu_to_le32(child_cnt); need_fix = 1; FIX_MSG("Dir: 0x%x i_links= 0x%x -> 0x%x", nid, i_links, child_cnt); } } if (ftype == F2FS_FT_ORPHAN && i_links) ASSERT_MSG("ino: 0x%x is orphan inode, but has i_links: %u", nid, i_links); if (need_fix) { ret = dev_write_block(node_blk, ni->blk_addr); ASSERT(ret >= 0); } } int fsck_chk_dnode_blk(struct f2fs_sb_info *sbi, struct f2fs_inode *inode, u32 nid, enum FILE_TYPE ftype, struct f2fs_node *node_blk, u32 *blk_cnt, struct node_info *ni) { int idx, ret; u32 child_cnt = 0, child_files = 0; for (idx = 0; idx < ADDRS_PER_BLOCK; idx++) { if (le32_to_cpu(node_blk->dn.addr[idx]) == 0x0) continue; ret = fsck_chk_data_blk(sbi, le32_to_cpu(node_blk->dn.addr[idx]), &child_cnt, &child_files, le64_to_cpu(inode->i_blocks) == *blk_cnt, ftype, nid, idx, ni->version); if (!ret) *blk_cnt = *blk_cnt + 1; } return 0; } int fsck_chk_idnode_blk(struct f2fs_sb_info *sbi, struct f2fs_inode *inode, enum FILE_TYPE ftype, struct f2fs_node *node_blk, u32 *blk_cnt) { int ret; int i = 0; for (i = 0 ; i < NIDS_PER_BLOCK; i++) { if (le32_to_cpu(node_blk->in.nid[i]) == 0x0) continue; ret = fsck_chk_node_blk(sbi, inode, le32_to_cpu(node_blk->in.nid[i]), ftype, TYPE_DIRECT_NODE, blk_cnt); if (!ret) *blk_cnt = *blk_cnt + 1; else if (ret == -EINVAL) printf("delete in.nid[i] = 0;\n"); } return 0; } int fsck_chk_didnode_blk(struct f2fs_sb_info *sbi, struct f2fs_inode *inode, enum FILE_TYPE ftype, struct f2fs_node *node_blk, u32 *blk_cnt) { int i = 0; int ret = 0; for (i = 0; i < NIDS_PER_BLOCK; i++) { if (le32_to_cpu(node_blk->in.nid[i]) == 0x0) continue; ret = fsck_chk_node_blk(sbi, inode, le32_to_cpu(node_blk->in.nid[i]), ftype, TYPE_INDIRECT_NODE, blk_cnt); if (!ret) *blk_cnt = *blk_cnt + 1; else if (ret == -EINVAL) printf("delete in.nid[i] = 0;\n"); } return 0; } static void print_dentry(__u32 depth, __u8 *name, unsigned long *bitmap, struct f2fs_dir_entry *dentry, int max, int idx, int last_blk) { int last_de = 0; int next_idx = 0; int name_len; unsigned int i; int bit_offset; if (config.dbg_lv != -1) return; name_len = le16_to_cpu(dentry[idx].name_len); next_idx = idx + (name_len + F2FS_SLOT_LEN - 1) / F2FS_SLOT_LEN; bit_offset = find_next_bit(bitmap, max, next_idx); if (bit_offset >= max && last_blk) last_de = 1; if (tree_mark_size <= depth) { tree_mark_size *= 2; tree_mark = realloc(tree_mark, tree_mark_size); } if (last_de) tree_mark[depth] = '`'; else tree_mark[depth] = '|'; if (tree_mark[depth - 1] == '`') tree_mark[depth - 1] = ' '; for (i = 1; i < depth; i++) printf("%c ", tree_mark[i]); printf("%c-- %s 0x%x\n", last_de ? '`' : '|', name, le32_to_cpu(dentry[idx].ino)); } static int __chk_dentries(struct f2fs_sb_info *sbi, u32 *child_cnt, u32* child_files, unsigned long *bitmap, struct f2fs_dir_entry *dentry, __u8 (*filenames)[F2FS_SLOT_LEN], int max, int last_blk) { struct f2fs_fsck *fsck = F2FS_FSCK(sbi); enum FILE_TYPE ftype; int dentries = 0; u32 blk_cnt; u8 *name; u32 hash_code; u16 name_len;; int ret = 0; int fixed = 0; int i; for (i = 0; i < max;) { if (test_bit(i, bitmap) == 0) { i++; continue; } if (!IS_VALID_NID(sbi, le32_to_cpu(dentry[i].ino))) { DBG(1, "Bad dentry 0x%x with invalid NID/ino 0x%x", i, le32_to_cpu(dentry[i].ino)); if (config.fix_on) { FIX_MSG("Clear bad dentry 0x%x with bad ino 0x%x", i, le32_to_cpu(dentry[i].ino)); clear_bit(i, bitmap); i++; fixed = 1; continue; } } ftype = dentry[i].file_type; if ((ftype <= F2FS_FT_UNKNOWN || ftype > F2FS_FT_LAST_FILE_TYPE) && config.fix_on) { DBG(1, "Bad dentry 0x%x with unexpected ftype 0x%x", i, ftype); if (config.fix_on) { FIX_MSG("Clear bad dentry 0x%x with bad ftype 0x%x", i, ftype); clear_bit(i, bitmap); i++; fixed = 1; continue; } } name_len = le16_to_cpu(dentry[i].name_len); name = calloc(name_len + 1, 1); memcpy(name, filenames[i], name_len); hash_code = f2fs_dentry_hash((const unsigned char *)name, name_len); /* fix hash_code made by old buggy code */ if (le32_to_cpu(dentry[i].hash_code) != hash_code) { dentry[i].hash_code = hash_code; fixed = 1; FIX_MSG("hash_code[%d] of %s", i, name); } /* Becareful. 'dentry.file_type' is not imode. */ if (ftype == F2FS_FT_DIR) { *child_cnt = *child_cnt + 1; if ((name[0] == '.' && name_len == 1) || (name[0] == '.' && name[1] == '.' && name_len == 2)) { i++; free(name); continue; } } DBG(1, "[%3u]-[0x%x] name[%s] len[0x%x] ino[0x%x] type[0x%x]\n", fsck->dentry_depth, i, name, name_len, le32_to_cpu(dentry[i].ino), dentry[i].file_type); print_dentry(fsck->dentry_depth, name, bitmap, dentry, max, i, last_blk); blk_cnt = 1; ret = fsck_chk_node_blk(sbi, NULL, le32_to_cpu(dentry[i].ino), ftype, TYPE_INODE, &blk_cnt); if (ret && config.fix_on) { int j; int slots = (name_len + F2FS_SLOT_LEN - 1) / F2FS_SLOT_LEN; for (j = 0; j < slots; j++) clear_bit(i + j, bitmap); FIX_MSG("Unlink [0x%x] - %s len[0x%x], type[0x%x]", le32_to_cpu(dentry[i].ino), name, name_len, dentry[i].file_type); i += slots; free(name); continue; } i += (name_len + F2FS_SLOT_LEN - 1) / F2FS_SLOT_LEN; dentries++; *child_files = *child_files + 1; free(name); } return fixed ? -1 : dentries; } int fsck_chk_inline_dentries(struct f2fs_sb_info *sbi, struct f2fs_node *node_blk, u32 *child_cnt, u32 *child_files) { struct f2fs_fsck *fsck = F2FS_FSCK(sbi); struct f2fs_inline_dentry *de_blk; int dentries; de_blk = inline_data_addr(node_blk); ASSERT(de_blk != NULL); fsck->dentry_depth++; dentries = __chk_dentries(sbi, child_cnt, child_files, (unsigned long *)de_blk->dentry_bitmap, de_blk->dentry, de_blk->filename, NR_INLINE_DENTRY, 1); if (dentries < 0) { DBG(1, "[%3d] Inline Dentry Block Fixed hash_codes\n\n", fsck->dentry_depth); } else { DBG(1, "[%3d] Inline Dentry Block Done : " "dentries:%d in %d slots (len:%d)\n\n", fsck->dentry_depth, dentries, (int)NR_INLINE_DENTRY, F2FS_NAME_LEN); } fsck->dentry_depth--; return dentries; } int fsck_chk_dentry_blk(struct f2fs_sb_info *sbi, u32 blk_addr, u32 *child_cnt, u32 *child_files, int last_blk) { struct f2fs_fsck *fsck = F2FS_FSCK(sbi); struct f2fs_dentry_block *de_blk; int dentries, ret; de_blk = (struct f2fs_dentry_block *)calloc(BLOCK_SZ, 1); ASSERT(de_blk != NULL); ret = dev_read_block(de_blk, blk_addr); ASSERT(ret >= 0); fsck->dentry_depth++; dentries = __chk_dentries(sbi, child_cnt, child_files, (unsigned long *)de_blk->dentry_bitmap, de_blk->dentry, de_blk->filename, NR_DENTRY_IN_BLOCK, last_blk); if (dentries < 0) { ret = dev_write_block(de_blk, blk_addr); ASSERT(ret >= 0); DBG(1, "[%3d] Dentry Block [0x%x] Fixed hash_codes\n\n", fsck->dentry_depth, blk_addr); } else { DBG(1, "[%3d] Dentry Block [0x%x] Done : " "dentries:%d in %d slots (len:%d)\n\n", fsck->dentry_depth, blk_addr, dentries, NR_DENTRY_IN_BLOCK, F2FS_NAME_LEN); } fsck->dentry_depth--; free(de_blk); return 0; } int fsck_chk_data_blk(struct f2fs_sb_info *sbi, u32 blk_addr, u32 *child_cnt, u32 *child_files, int last_blk, enum FILE_TYPE ftype, u32 parent_nid, u16 idx_in_node, u8 ver) { struct f2fs_fsck *fsck = F2FS_FSCK(sbi); /* Is it reserved block? */ if (blk_addr == NEW_ADDR) { fsck->chk.valid_blk_cnt++; return 0; } if (!IS_VALID_BLK_ADDR(sbi, blk_addr)) { ASSERT_MSG("blkaddres is not valid. [0x%x]", blk_addr); return -EINVAL; } if (is_valid_ssa_data_blk(sbi, blk_addr, parent_nid, idx_in_node, ver)) { ASSERT_MSG("summary data block is not valid. [0x%x]", parent_nid); return -EINVAL; } if (f2fs_test_sit_bitmap(sbi, blk_addr) == 0) ASSERT_MSG("SIT bitmap is 0x0. blk_addr[0x%x]", blk_addr); if (f2fs_test_main_bitmap(sbi, blk_addr) != 0) ASSERT_MSG("Duplicated data [0x%x]. pnid[0x%x] idx[0x%x]", blk_addr, parent_nid, idx_in_node); f2fs_set_main_bitmap(sbi, blk_addr); fsck->chk.valid_blk_cnt++; if (ftype == F2FS_FT_DIR) return fsck_chk_dentry_blk(sbi, blk_addr, child_cnt, child_files, last_blk); return 0; } void fsck_chk_orphan_node(struct f2fs_sb_info *sbi) { u32 blk_cnt = 0; block_t start_blk, orphan_blkaddr, i, j; struct f2fs_orphan_block *orphan_blk; struct f2fs_checkpoint *ckpt = F2FS_CKPT(sbi); if (!is_set_ckpt_flags(ckpt, CP_ORPHAN_PRESENT_FLAG)) return; if (config.fix_on) return; start_blk = __start_cp_addr(sbi) + 1 + le32_to_cpu(F2FS_RAW_SUPER(sbi)->cp_payload); orphan_blkaddr = __start_sum_addr(sbi) - 1; orphan_blk = calloc(BLOCK_SZ, 1); for (i = 0; i < orphan_blkaddr; i++) { int ret = dev_read_block(orphan_blk, start_blk + i); ASSERT(ret >= 0); for (j = 0; j < le32_to_cpu(orphan_blk->entry_count); j++) { nid_t ino = le32_to_cpu(orphan_blk->ino[j]); DBG(1, "[%3d] ino [0x%x]\n", i, ino); blk_cnt = 1; fsck_chk_node_blk(sbi, NULL, ino, F2FS_FT_ORPHAN, TYPE_INODE, &blk_cnt); } memset(orphan_blk, 0, BLOCK_SZ); } free(orphan_blk); } void fsck_init(struct f2fs_sb_info *sbi) { struct f2fs_fsck *fsck = F2FS_FSCK(sbi); struct f2fs_sm_info *sm_i = SM_I(sbi); /* * We build three bitmap for main/sit/nat so that may check consistency * of filesystem. * 1. main_area_bitmap will be used to check whether all blocks of main * area is used or not. * 2. nat_area_bitmap has bitmap information of used nid in NAT. * 3. sit_area_bitmap has bitmap information of used main block. * At Last sequence, we compare main_area_bitmap with sit_area_bitmap. */ fsck->nr_main_blks = sm_i->main_segments << sbi->log_blocks_per_seg; fsck->main_area_bitmap_sz = (fsck->nr_main_blks + 7) / 8; fsck->main_area_bitmap = calloc(fsck->main_area_bitmap_sz, 1); ASSERT(fsck->main_area_bitmap != NULL); build_nat_area_bitmap(sbi); build_sit_area_bitmap(sbi); tree_mark = calloc(tree_mark_size, 1); ASSERT(tree_mark != NULL); } static void fix_nat_entries(struct f2fs_sb_info *sbi) { struct f2fs_fsck *fsck = F2FS_FSCK(sbi); u32 i; for (i = 0; i < fsck->nr_nat_entries; i++) if (f2fs_test_bit(i, fsck->nat_area_bitmap) != 0) nullify_nat_entry(sbi, i); } static void fix_checkpoint(struct f2fs_sb_info *sbi) { struct f2fs_fsck *fsck = F2FS_FSCK(sbi); struct f2fs_super_block *raw_sb = sbi->raw_super; struct f2fs_checkpoint *ckp = F2FS_CKPT(sbi); unsigned long long cp_blk_no; u32 i; int ret; u_int32_t crc = 0; ckp->ckpt_flags = cpu_to_le32(CP_UMOUNT_FLAG); ckp->cp_pack_total_block_count = cpu_to_le32(8 + le32_to_cpu(raw_sb->cp_payload)); ckp->cp_pack_start_sum = cpu_to_le32(1 + le32_to_cpu(raw_sb->cp_payload)); ckp->free_segment_count = cpu_to_le32(fsck->chk.free_segs); ckp->valid_block_count = cpu_to_le32(fsck->chk.valid_blk_cnt); ckp->valid_node_count = cpu_to_le32(fsck->chk.valid_node_cnt); ckp->valid_inode_count = cpu_to_le32(fsck->chk.valid_inode_cnt); crc = f2fs_cal_crc32(F2FS_SUPER_MAGIC, ckp, CHECKSUM_OFFSET); *((__le32 *)((unsigned char *)ckp + CHECKSUM_OFFSET)) = cpu_to_le32(crc); cp_blk_no = le32_to_cpu(raw_sb->cp_blkaddr); if (sbi->cur_cp == 2) cp_blk_no += 1 << le32_to_cpu(raw_sb->log_blocks_per_seg); ret = dev_write_block(ckp, cp_blk_no++); ASSERT(ret >= 0); for (i = 0; i < le32_to_cpu(raw_sb->cp_payload); i++) { ret = dev_write_block(((unsigned char *)ckp) + i * F2FS_BLKSIZE, cp_blk_no++); ASSERT(ret >= 0); } for (i = 0; i < NO_CHECK_TYPE; i++) { struct curseg_info *curseg = CURSEG_I(sbi, i); ret = dev_write_block(curseg->sum_blk, cp_blk_no++); ASSERT(ret >= 0); } ret = dev_write_block(ckp, cp_blk_no++); ASSERT(ret >= 0); } int check_curseg_offset(struct f2fs_sb_info *sbi) { int i; for (i = 0; i < NO_CHECK_TYPE; i++) { struct curseg_info *curseg = CURSEG_I(sbi, i); struct seg_entry *se; se = get_seg_entry(sbi, curseg->segno); if (f2fs_test_bit(curseg->next_blkoff, (const char *)se->cur_valid_map) == 1) { ASSERT_MSG("Next block offset is not free, type:%d", i); return -EINVAL; } } return 0; } int fsck_verify(struct f2fs_sb_info *sbi) { unsigned int i = 0; int ret = 0; u32 nr_unref_nid = 0; struct f2fs_fsck *fsck = F2FS_FSCK(sbi); struct hard_link_node *node = NULL; printf("\n"); for (i = 0; i < fsck->nr_nat_entries; i++) { if (f2fs_test_bit(i, fsck->nat_area_bitmap) != 0) { printf("NID[0x%x] is unreachable\n", i); nr_unref_nid++; } } if (fsck->hard_link_list_head != NULL) { node = fsck->hard_link_list_head; while (node) { printf("NID[0x%x] has [0x%x] more unreachable links\n", node->nid, node->links); node = node->next; } config.bug_on = 1; } printf("[FSCK] Unreachable nat entries "); if (nr_unref_nid == 0x0) { printf(" [Ok..] [0x%x]\n", nr_unref_nid); } else { printf(" [Fail] [0x%x]\n", nr_unref_nid); ret = EXIT_ERR_CODE; config.bug_on = 1; } printf("[FSCK] SIT valid block bitmap checking "); if (memcmp(fsck->sit_area_bitmap, fsck->main_area_bitmap, fsck->sit_area_bitmap_sz) == 0x0) { printf("[Ok..]\n"); } else { printf("[Fail]\n"); ret = EXIT_ERR_CODE; config.bug_on = 1; } printf("[FSCK] Hard link checking for regular file "); if (fsck->hard_link_list_head == NULL) { printf(" [Ok..] [0x%x]\n", fsck->chk.multi_hard_link_files); } else { printf(" [Fail] [0x%x]\n", fsck->chk.multi_hard_link_files); ret = EXIT_ERR_CODE; config.bug_on = 1; } printf("[FSCK] valid_block_count matching with CP "); if (sbi->total_valid_block_count == fsck->chk.valid_blk_cnt) { printf(" [Ok..] [0x%x]\n", (u32)fsck->chk.valid_blk_cnt); } else { printf(" [Fail] [0x%x]\n", (u32)fsck->chk.valid_blk_cnt); ret = EXIT_ERR_CODE; config.bug_on = 1; } printf("[FSCK] valid_node_count matcing with CP (de lookup) "); if (sbi->total_valid_node_count == fsck->chk.valid_node_cnt) { printf(" [Ok..] [0x%x]\n", fsck->chk.valid_node_cnt); } else { printf(" [Fail] [0x%x]\n", fsck->chk.valid_node_cnt); ret = EXIT_ERR_CODE; config.bug_on = 1; } printf("[FSCK] valid_node_count matcing with CP (nat lookup) "); if (sbi->total_valid_node_count == fsck->chk.valid_nat_entry_cnt) { printf(" [Ok..] [0x%x]\n", fsck->chk.valid_nat_entry_cnt); } else { printf(" [Fail] [0x%x]\n", fsck->chk.valid_nat_entry_cnt); ret = EXIT_ERR_CODE; config.bug_on = 1; } printf("[FSCK] valid_inode_count matched with CP "); if (sbi->total_valid_inode_count == fsck->chk.valid_inode_cnt) { printf(" [Ok..] [0x%x]\n", fsck->chk.valid_inode_cnt); } else { printf(" [Fail] [0x%x]\n", fsck->chk.valid_inode_cnt); ret = EXIT_ERR_CODE; config.bug_on = 1; } printf("[FSCK] free segment_count matched with CP "); if (le32_to_cpu(F2FS_CKPT(sbi)->free_segment_count) == fsck->chk.sit_free_segs) { printf(" [Ok..] [0x%x]\n", fsck->chk.sit_free_segs); } else { printf(" [Fail] [0x%x]\n", fsck->chk.sit_free_segs); ret = EXIT_ERR_CODE; config.bug_on = 1; } printf("[FSCK] next block offset is free "); if (check_curseg_offset(sbi) == 0) { printf(" [Ok..]\n"); } else { printf(" [Fail]\n"); ret = EXIT_ERR_CODE; config.bug_on = 1; } printf("[FSCK] other corrupted bugs "); if (config.bug_on == 0) { printf(" [Ok..]\n"); } else { printf(" [Fail]\n"); ret = EXIT_ERR_CODE; config.bug_on = 1; } /* fix global metadata */ if (config.bug_on && config.fix_on) { fix_nat_entries(sbi); rewrite_sit_area_bitmap(sbi); fix_checkpoint(sbi); } return ret; } void fsck_free(struct f2fs_sb_info *sbi) { struct f2fs_fsck *fsck = F2FS_FSCK(sbi); if (fsck->main_area_bitmap) free(fsck->main_area_bitmap); if (fsck->nat_area_bitmap) free(fsck->nat_area_bitmap); if (fsck->sit_area_bitmap) free(fsck->sit_area_bitmap); if (tree_mark) free(tree_mark); }
android-ia/platform_external_f2fs-tools
fsck/fsck.c
C
lgpl-2.1
29,313
<!DOCTYPE HTML PUBLIC "-//IETF//DTD HTML//EN"> <html> <head> <script src="../../fast/js/resources/js-test-pre.js"></script> </head> <body> <p id="description"></p> <div id="console"></div> <script src="resources/ie-test-pre.js"></script> <script src="TestCases/15.4.4.15-1-10.js"></script> <script src="resources/ie-test-post.js"></script> <script src="../../fast/js/resources/js-test-post.js"></script> </body> </html>
youfoh/webkit-efl
LayoutTests/ietestcenter/Javascript/15.4.4.15-1-10.html
HTML
lgpl-2.1
420
// --------------------------------------------------------------------- // // Copyright (C) 2010 - 2015 by the deal.II authors // // This file is part of the deal.II library. // // The deal.II library is free software; you can use it, redistribute // it, and/or modify it under the terms of the GNU Lesser General // Public License as published by the Free Software Foundation; either // version 2.1 of the License, or (at your option) any later version. // The full text of the license can be found in the file LICENSE at // the top level of the deal.II distribution. // // --------------------------------------------------------------------- // DataOut::build_patches appeared to have a problem when outputting // data using MappingFEField in combination with high subdivisions // and/or high degree. This turned out to be related to multiple // threads accessing the same global values for local_dof_values and // local_dof_indices, where they should have been accessing thread // local data. Running this test on a version of deal.II without the // fix produces an "exploded" output, where the location of the // vertices are randomly mixed between cells. #include "../tests.h" #include <deal.II/grid/tria.h> #include <deal.II/dofs/dof_handler.h> #include <deal.II/grid/grid_in.h> #include <deal.II/lac/vector.h> #include <deal.II/numerics/data_out.h> #include <deal.II/numerics/vector_tools.h> #include <deal.II/grid/manifold_lib.h> #include <deal.II/fe/fe.h> #include <deal.II/fe/fe_q.h> #include <deal.II/fe/fe_values.h> #include <deal.II/fe/fe_system.h> #include <deal.II/fe/mapping_q.h> #include <deal.II/fe/mapping_q_eulerian.h> #include <deal.II/fe/mapping_fe_field.h> template <int dim, int spacedim> void test(const unsigned int refs, const unsigned int degree, const unsigned int subdivisions) { const unsigned int id = degree+10*refs+100*subdivisions; Triangulation<dim, spacedim> triangulation; FE_Q<dim, spacedim> fe(degree); FESystem<dim, spacedim> fe_euler(FE_Q<dim, spacedim> (degree), spacedim); DoFHandler<dim, spacedim> dof_handler(triangulation); DoFHandler<dim, spacedim> map_dh(triangulation); Vector<double> euler_vec; Vector<double> scal_sol; GridIn<dim, spacedim> grid_in; grid_in.attach_triangulation (triangulation); std::ifstream fname(SOURCE_DIR "/grids/sphere_0.inp"); grid_in.read_ucd (fname); SphericalManifold<dim,spacedim> manifold; triangulation.set_all_manifold_ids(0); triangulation.set_manifold(0, manifold); triangulation.refine_global(refs); dof_handler.distribute_dofs (fe); map_dh.distribute_dofs (fe_euler); euler_vec.reinit (map_dh.n_dofs()); scal_sol.reinit (dof_handler.n_dofs()); scal_sol = 1; VectorTools::get_position_vector(map_dh,euler_vec); MappingFEField<dim, spacedim> mapping(map_dh,euler_vec);; DataOut<dim, DoFHandler<dim, spacedim> > data_out_scal; data_out_scal.attach_dof_handler (dof_handler); data_out_scal.add_data_vector (scal_sol, "scalar_data", DataOut<dim,DoFHandler<dim, spacedim> >::type_dof_data); data_out_scal.build_patches(mapping, subdivisions, DataOut<dim, DoFHandler<dim, spacedim> >::curved_inner_cells); std::string filename_scal = ( "scal_check_"+ Utilities::int_to_string(id) + ".vtu" ); std::ofstream file_scal(filename_scal.c_str()); data_out_scal.write_vtu(file_scal); data_out_scal.write_vtk(deallog.get_file_stream()); std::vector<DataComponentInterpretation::DataComponentInterpretation> data_component_interpretation (spacedim, DataComponentInterpretation::component_is_part_of_vector); DataOut<dim, DoFHandler<dim, spacedim> > data_out_euler; data_out_euler.attach_dof_handler (map_dh); data_out_euler.add_data_vector (euler_vec, "euler_vec", DataOut<dim, DoFHandler<dim, spacedim> >::type_dof_data, data_component_interpretation); data_out_euler.build_patches(mapping, degree, DataOut<dim, DoFHandler<dim, spacedim> >::curved_inner_cells); std::string filename_euler = ( "euler_check_"+ Utilities::int_to_string(id) + ".vtu" ); std::ofstream file_euler(filename_euler.c_str()); data_out_euler.write_vtu(file_euler); data_out_euler.write_vtk(deallog.get_file_stream()); triangulation.set_manifold(0); } int main () { initlog(); test<2,3>(4,3,3); test<2,3>(3,4,4); test<2,3>(2,5,5); test<2,3>(2,3,5); test<2,3>(1,4,6); test<2,3>(0,5,7); return 0; }
kalj/dealii
tests/codim_one/mapping_fe_field_01.cc
C++
lgpl-2.1
4,619
/* * gosthash.h * 21 Apr 1998 Markku-Juhani Saarinen <[email protected]> * * GOST R 34.11-94, Russian Standard Hash Function * header with function prototypes. * * Copyright (c) 1998 SSH Communications Security, Finland * All rights reserved. */ #if defined(ENABLE_GOST) #if !defined(GOSTHASH_H) #define GOSTHASH_H /* State structure */ #include "libdefs.h" typedef struct { mutils_word32 sum[8]; mutils_word32 hash[8]; mutils_word32 len[8]; mutils_word8 partial[32]; mutils_word32 partial_bytes; } GostHashCtx; /* Compute some lookup-tables that are needed by all other functions. */ #if 0 void gosthash_init(void); #endif /* Clear the state of the given context structure. */ void gosthash_reset(GostHashCtx * ctx); /* Mix in len bytes of data for the given buffer. */ void gosthash_update(GostHashCtx * ctx, __const mutils_word8 * buf, mutils_word32 len); /* Compute and save the 32-byte digest. */ void gosthash_final(GostHashCtx * ctx, mutils_word8 * digest); #endif /* GOSTHASH_H */ #endif
cention-nazri/mhash
lib/mhash_gost.h
C
lgpl-2.1
1,087
include ../../../config.mak LDFLAGS= all: luma create_lumas @./create_lumas luma: luma.c # When cross-compiling, use the host OS compiler to build the luma # binary because the files are generated at build time. # Strips the CROSS prefix from the C compiler variable. ifdef CROSS $(subst $(CROSS),,$(CC)) -o $@ luma.c endif create_lumas: depend: distclean: rm -rf PAL NTSC luma clean: rm -f luma install: all install -d $(DESTDIR)$(mltdatadir)/lumas/PAL install -d $(DESTDIR)$(mltdatadir)/lumas/NTSC install -m 644 PAL/* $(DESTDIR)$(mltdatadir)/lumas/PAL install -m 644 NTSC/* $(DESTDIR)$(mltdatadir)/lumas/NTSC
wideioltd/mlt
src/modules/lumas/Makefile
Makefile
lgpl-2.1
630
/**************************************************************************** ** ** Copyright (C) 2013 Digia Plc and/or its subsidiary(-ies). ** Contact: http://www.qt-project.org/legal ** ** This file is part of the tools applications of the Qt Toolkit. ** ** $QT_BEGIN_LICENSE:LGPL$ ** Commercial License Usage ** Licensees holding valid commercial Qt licenses may use this file in ** accordance with the commercial license agreement provided with the ** Software or, alternatively, in accordance with the terms contained in ** a written agreement between you and Digia. For licensing terms and ** conditions see http://qt.digia.com/licensing. For further information ** use the contact form at http://qt.digia.com/contact-us. ** ** GNU Lesser General Public License Usage ** Alternatively, this file may be used under the terms of the GNU Lesser ** General Public License version 2.1 as published by the Free Software ** Foundation and appearing in the file LICENSE.LGPL included in the ** packaging of this file. Please review the following information to ** ensure the GNU Lesser General Public License version 2.1 requirements ** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html. ** ** In addition, as a special exception, Digia gives you certain additional ** rights. These rights are described in the Digia Qt LGPL Exception ** version 1.1, included in the file LGPL_EXCEPTION.txt in this package. ** ** GNU General Public License Usage ** Alternatively, this file may be used under the terms of the GNU ** General Public License version 3.0 as published by the Free Software ** Foundation and appearing in the file LICENSE.GPL included in the ** packaging of this file. Please review the following information to ** ensure the GNU General Public License version 3.0 requirements will be ** met: http://www.gnu.org/copyleft/gpl.html. ** ** ** $QT_END_LICENSE$ ** ****************************************************************************/ #include "commands.h" #include <Pm.h> #include <Pmpolicy.h> #define CLEAN_FAIL(a) {delete appName; \ delete arguments; \ return (a); } int qRemoteLaunch(DWORD, BYTE*, DWORD*, BYTE**, IRAPIStream* stream) { if (!stream) return -1; DWORD bytesRead; int appLength; wchar_t* appName = 0; int argumentsLength; wchar_t* arguments = 0; int timeout = -1; int returnValue = -2; DWORD error = 0; if (S_OK != stream->Read(&appLength, sizeof(appLength), &bytesRead)) CLEAN_FAIL(-2); appName = (wchar_t*) malloc(sizeof(wchar_t)*(appLength + 1)); if (S_OK != stream->Read(appName, sizeof(wchar_t)*appLength, &bytesRead)) CLEAN_FAIL(-2); appName[appLength] = '\0'; if (S_OK != stream->Read(&argumentsLength, sizeof(argumentsLength), &bytesRead)) CLEAN_FAIL(-2); arguments = (wchar_t*) malloc(sizeof(wchar_t)*(argumentsLength + 1)); if (S_OK != stream->Read(arguments, sizeof(wchar_t)*argumentsLength, &bytesRead)) CLEAN_FAIL(-2); arguments[argumentsLength] = '\0'; if (S_OK != stream->Read(&timeout, sizeof(timeout), &bytesRead)) CLEAN_FAIL(-2); bool result = qRemoteExecute(appName, arguments, &returnValue, &error, timeout); if (timeout != 0) { if (S_OK != stream->Write(&returnValue, sizeof(returnValue), &bytesRead)) CLEAN_FAIL(-4); if (S_OK != stream->Write(&error, sizeof(error), &bytesRead)) CLEAN_FAIL(-5); } delete appName; delete arguments; // We need to fail here for the execute, otherwise the calling application will wait // forever for the returnValue. if (!result) return -3; return S_OK; } bool qRemoteExecute(const wchar_t* program, const wchar_t* arguments, int *returnValue, DWORD* error, int timeout) { *error = 0; if (!program) return false; PROCESS_INFORMATION pid; if (!CreateProcess(program, arguments, NULL, NULL, false, 0, NULL, NULL, NULL, &pid)) { *error = GetLastError(); wprintf(L"Could not launch: %s\n", program); return false; } // Timeout is in seconds DWORD waitingTime = (timeout == -1) ? INFINITE : timeout * 1000; if (waitingTime != 0) { DWORD waitStatus = WaitForSingleObject(pid.hProcess, waitingTime); if (waitStatus == WAIT_TIMEOUT) { TerminateProcess(pid.hProcess, 2); return false; } else if (waitStatus == WAIT_OBJECT_0 && returnValue) { *returnValue = 0; DWORD exitCode; if (GetExitCodeProcess(pid.hProcess, &exitCode)) *returnValue = exitCode; } } return true; } /** \brief Reset the device. */ int qRemoteSoftReset(DWORD, BYTE*, DWORD*, BYTE**, IRAPIStream* stream) { //POWER_STATE_ON On state //POWER_STATE_OFF Off state //POWER_STATE_CRITICAL Critical state //POWER_STATE_BOOT Boot state //POWER_STATE_IDLE Idle state //POWER_STATE_SUSPEND Suspend state //POWER_STATE_RESET Reset state DWORD returnValue = SetSystemPowerState(0, POWER_STATE_RESET, POWER_FORCE); return returnValue; } /** \brief Toggle the unattended powermode of the device */ int qRemoteToggleUnattendedPowerMode(DWORD, BYTE*, DWORD*, BYTE**, IRAPIStream* stream) { if (!stream) return -1; DWORD bytesRead; int toggleVal = 0; int returnValue = S_OK; if (S_OK != stream->Read(&toggleVal, sizeof(toggleVal), &bytesRead)) return -2; //PPN_REEVALUATESTATE 0x0001 Reserved. Set dwData to zero (0). //PPN_POWERCHANGE 0x0002 Reserved. Set dwData to zero (0). //PPN_UNATTENDEDMODE 0x0003 Set dwData to TRUE or FALSE. //PPN_SUSPENDKEYPRESSED or //PPN_POWERBUTTONPRESSED 0x0004 Reserved. Set dwData to zero (0). //PPN_SUSPENDKEYRELEASED 0x0005 Reserved. Set dwData to zero (0). //PPN_APPBUTTONPRESSED 0x0006 Reserved. Set dwData to zero (0). //PPN_OEMBASE Greater than or equal to 0x10000 //You can define higher values, such as 0x10001, 0x10002, and so on. // Reserved. Set dwData to zero (0). returnValue = PowerPolicyNotify(PPN_UNATTENDEDMODE, toggleVal); if (S_OK != stream->Write(&returnValue, sizeof(returnValue), &bytesRead)) return -3; else return S_OK; } /** \brief Virtually press the power button of the device */ int qRemotePowerButton(DWORD, BYTE*, DWORD*, BYTE**, IRAPIStream* stream) { if (!stream) return -1; DWORD bytesRead; int toggleVal = 0; int returnValue = S_OK; if (S_OK != stream->Read(&toggleVal, sizeof(toggleVal), &bytesRead)) return -2; //PPN_REEVALUATESTATE 0x0001 Reserved. Set dwData to zero (0). //PPN_POWERCHANGE 0x0002 Reserved. Set dwData to zero (0). //PPN_UNATTENDEDMODE 0x0003 Set dwData to TRUE or FALSE. //PPN_SUSPENDKEYPRESSED or //PPN_POWERBUTTONPRESSED 0x0004 Reserved. Set dwData to zero (0). //PPN_SUSPENDKEYRELEASED 0x0005 Reserved. Set dwData to zero (0). //PPN_APPBUTTONPRESSED 0x0006 Reserved. Set dwData to zero (0). //PPN_OEMBASE Greater than or equal to 0x10000 //You can define higher values, such as 0x10001, 0x10002, and so on. // Reserved. Set dwData to zero (0). returnValue = PowerPolicyNotify(PPN_SUSPENDKEYPRESSED, 0); if (S_OK != stream->Write(&returnValue, sizeof(returnValue), &bytesRead)) return -3; else return S_OK; }
mer-qt/qttools
src/qtestlib/wince/remotelib/commands.cpp
C++
lgpl-2.1
7,474
/* csound_orc_optimizee.c: Copyright (C) 2006 Steven Yi This file is part of Csound. The Csound Library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. Csound is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with Csound; if not, write to the Free Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA */ #include "csoundCore.h" #include "csound_orc.h" static TREE * create_fun_token(CSOUND *csound, TREE *right, char *fname) { TREE *ans; ans = (TREE*)csound->Malloc(csound, sizeof(TREE)); if (UNLIKELY(ans == NULL)) exit(1); ans->type = T_FUNCTION; ans->value = make_token(csound, fname); ans->value->type = T_FUNCTION; ans->left = NULL; ans->right = right; ans->next = NULL; ans->len = 0; ans->markup = NULL; ans->rate = -1; return ans; } static TREE * optimize_ifun(CSOUND *csound, TREE *root) { /* print_tree(csound, "optimize_ifun: before", root); */ switch(root->right->type) { case INTEGER_TOKEN: case NUMBER_TOKEN: /* i(num) -> num */ // FIXME - reinstate optimization after implementing get_type(varname) // case T_IDENT_I: /* i(ivar) -> ivar */ // case T_IDENT_GI: /* i(givar) -> givar */ // case T_IDENT_P: /* i(pN) -> pN */ root = root->right; break; // case T_IDENT_K: /* i(kvar) -> i(kvar) */ // case T_IDENT_GK: /* i(gkvar) -> i(gkvar) */ // break; case T_FUNCTION: /* i(fn(x)) -> fn(i(x)) */ { TREE *funTree = root->right; funTree->right = create_fun_token(csound, funTree->right, "i"); root = funTree; } break; default: /* i(A op B) -> i(A) op i(B) */ if(root->right->left != NULL) root->right->left = create_fun_token(csound, root->right->left, "i"); if(root->right->right != NULL) root->right->right = create_fun_token(csound, root->right->right, "i"); root->right->next = root->next; root = root->right; break; } /* print_tree(csound, "optimize_ifun: after", root); */ return root; } /** Verifies and optimise; constant fold and opcodes and args are correct*/ static TREE * verify_tree1(CSOUND *csound, TREE *root) { TREE *ans, *last; double lval, rval; //csound->Message(csound, "Verifying AST (NEED TO IMPLEMENT)\n"); //print_tree(csound, "Verify", root); if (root->right && root->right->type != T_INSTLIST) { if (root->type == T_OPCODE || root->type == T_OPCODE0) { last = root->right; while (last->next) { /* we optimize the i() functions in the opcode */ if (last->next->type == T_FUNCTION && (strcmp(last->next->value->lexeme, "i") == 0)) { TREE *temp = optimize_ifun(csound, last->next); temp->next = last->next->next; last->next = temp; } last = last->next; } } if (root->right->type == T_FUNCTION && (strcmp(root->right->value->lexeme, "i") == 0)) { /* i() function */ root->right = optimize_ifun(csound, root->right); } last = root->right; while (last->next) { last->next = verify_tree1(csound, last->next); last = last->next; } root->right = verify_tree1(csound, root->right); if (root->left) { if (root->left->type == T_FUNCTION && (strcmp(root->left->value->lexeme, "i") == 0)) { /* i() function */ root->left = optimize_ifun(csound, root->left); } root->left= verify_tree1(csound, root->left); if ((root->left->type == INTEGER_TOKEN || root->left->type == NUMBER_TOKEN) && (root->right->type == INTEGER_TOKEN || root->right->type == NUMBER_TOKEN)) { //print_tree(csound, "numerical case\n", root); lval = (root->left->type == INTEGER_TOKEN ? (double)root->left->value->value : root->left->value->fvalue); rval = (root->right->type == INTEGER_TOKEN ? (double)root->right->value->value : root->right->value->fvalue); ans = root->left; /* **** Something wrong here -- subtraction confuses memory **** */ switch (root->type) { case '+': ans->type = ans->value->type = NUMBER_TOKEN; ans->value->fvalue = lval+rval; ans->value->lexeme = (char*)csound-> ReAlloc(csound, ans->value->lexeme, 24); CS_SPRINTF(ans->value->lexeme, "%f", ans->value->fvalue); ans->next = root->next; //Memory leak!! //csound->Free(csound, root); mfree(csound root->right); return ans; case '-': ans->type = ans->value->type = NUMBER_TOKEN; ans->value->fvalue = lval-rval; ans->value->lexeme = (char*)csound-> ReAlloc(csound, ans->value->lexeme, 24); CS_SPRINTF(ans->value->lexeme, "%f", ans->value->fvalue); ans->next = root->next; //Memory leak!! //csound->Free(csound, root); mfree(csound, root->right); return ans; case '*': ans->type = ans->value->type = NUMBER_TOKEN; ans->value->fvalue = lval*rval; ans->value->lexeme = (char*)csound->ReAlloc(csound, ans->value->lexeme, 24); CS_SPRINTF(ans->value->lexeme, "%f", ans->value->fvalue); ans->next = root->next; //Memory leak!! //csound->Free(csound, root); mfree(csound, root->right); return ans; case '/': ans->type = ans->value->type = NUMBER_TOKEN; ans->value->fvalue = lval/rval; ans->value->lexeme = (char*)csound->ReAlloc(csound, ans->value->lexeme, 24); CS_SPRINTF(ans->value->lexeme, "%f", ans->value->fvalue); ans->next = root->next; //Memory leak!! //csound->Free(csound, root); mfree(csound, root->right); return ans; /* case S_NEQ: */ /* break; */ /* case S_AND: */ /* break; */ /* case S_OR: */ /* break; */ /* case S_LT: */ /* break; */ /* case S_LE: */ /* break; */ /* case S_EQ: */ /* break; */ /* case S_GT: */ /* break; */ /* case S_GE: */ /* break; */ default: break; } } } else if (root->right->type == INTEGER_TOKEN || root->right->type == NUMBER_TOKEN) { switch (root->type) { case S_UMINUS: /*print_tree(csound, "root", root);*/ ans = root->right; ans->value->fvalue = -(ans->type==INTEGER_TOKEN ? (double)ans->value->value : ans->value->fvalue); ans->value->lexeme = (char*)csound->ReAlloc(csound, ans->value->lexeme, 24); CS_SPRINTF(ans->value->lexeme, "%f", ans->value->fvalue); ans->type = ans->value->type = NUMBER_TOKEN; //print_tree(csound, "ans", ans); ans->next = root->next; return ans; default: break; } } } return root; } /* Optimizes tree (expressions, etc.) */ TREE * csound_orc_optimize(CSOUND *csound, TREE *root) { TREE *original=root, *last = NULL; while (root) { TREE *xx = verify_tree1(csound, root); if (xx != root) { xx->next = root->next; if (last) last->next = xx; else original = xx; } last = root; root = root->next; } return original; }
Angeldude/csound
Engine/csound_orc_optimize.c
C
lgpl-2.1
10,052
# Copyright 2013-2021 Lawrence Livermore National Security, LLC and other # Spack Project Developers. See the top-level COPYRIGHT file for details. # # SPDX-License-Identifier: (Apache-2.0 OR MIT) from spack import * class Gengetopt(AutotoolsPackage): """Tool to write command line option parsing code for C programs""" homepage = "https://www.gnu.org/software/gengetopt/gengetopt.html" url = "ftp://ftp.gnu.org/gnu/gengetopt/gengetopt-2.23.tar.xz" maintainers = ['rblake-llnl'] version('2.23', sha256='b941aec9011864978dd7fdeb052b1943535824169d2aa2b0e7eae9ab807584ac') version('2.22.6', sha256='30b05a88604d71ef2a42a2ef26cd26df242b41f5b011ad03083143a31d9b01f7') version('2.22.5', sha256='3b6fb3240352b0eb0c5b8583b58b62cbba58167cef5a7e82fa08a7f968ed2137') version('2.22.4', sha256='4edf6b24ec8085929c86835c51d5bf904052cc671530c15f9314d9b87fe54421') version('2.22.3', sha256='8ce6b3df49cefea97bd522dc054ede2037939978bf23754d5c17311e5a1df3dc') version('2.22.2', sha256='4bf96bea9f80ac85c716cd07f5fe68602db7f380f6dc2d025f17139aa0b56455') version('2.22.1', sha256='e8d1de4f8c102263844886a2f2b57d82c291c1eae6307ea406fb96f29a67c3a7') version('2.22', sha256='b605555e41e9bf7e852a37b051e6a49014e561f21290680e3a60c279488d417e') version('2.21', sha256='355a32310b2fee5e7289d6d6e89eddd13275a7c85a243dc5dd293a6cb5bb047e') version('2.20', sha256='4c8b3b42cecff579f5f9de5ccad47e0849e0245e325a04ff5985c248141af1a4') depends_on('texinfo', type='build') parallel = False def url_for_version(self, version): url = 'ftp://ftp.gnu.org/gnu/gengetopt/gengetopt-{0}.tar.{1}' if version >= Version('2.23'): suffix = 'xz' else: suffix = 'gz' return url.format(version, suffix)
LLNL/spack
var/spack/repos/builtin/packages/gengetopt/package.py
Python
lgpl-2.1
1,793