code
stringlengths
3
1.01M
repo_name
stringlengths
5
116
path
stringlengths
3
311
language
stringclasses
30 values
license
stringclasses
15 values
size
int64
3
1.01M
/* packet-paltalk.c * Routines for Paltalk dissection * Copyright 2005, Tim Hentenaar < tim at hentenaar dot com > * Copyright 2008, Mohammad Ebrahim Mohammadi Panah < mebrahim at gmail dot com > * * Wireshark - Network traffic analyzer * By Gerald Combs <gerald@wireshark.org> * Copyright 1998 Gerald Combs * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ #include "config.h" #include <string.h> #include <glib.h> #include <epan/packet.h> #include "packet-tcp.h" void proto_register_paltalk(void); void proto_reg_handoff_paltalk(void); #define INET_IPV4_ADDRESS_FROM_BYTES(a,b,c,d) g_htonl(((a)<<24) | ((b)<<16) | ((c)<<8) | (d)) /* *network* order */ #define PALTALK_SERVERS_ADDRESS INET_IPV4_ADDRESS_FROM_BYTES(199,106,0,0) /* 199.106.0.0 in *network* order */ #define PALTALK_SERVERS_NETMASK INET_IPV4_ADDRESS_FROM_BYTES(0xFF, 0xFE, 0x00, 0x00) /* /15 in *network* order */ #define PALTALK_HEADER_LENGTH 6 static int proto_paltalk = -1; static int hf_paltalk_pdu_type = -1; static int hf_paltalk_version = -1; static int hf_paltalk_length = -1; static int hf_paltalk_content = -1; static gint ett_paltalk = -1; static guint dissect_paltalk_get_len(packet_info *pinfo _U_, tvbuff_t *tvb, int offset) { return tvb_get_ntohs(tvb, offset + 4) + PALTALK_HEADER_LENGTH; } static int dissect_paltalk_desegmented(tvbuff_t *tvb, packet_info *pinfo, proto_tree *tree, void* data _U_) { proto_item *ti = NULL; proto_tree *pt_tree = NULL; col_set_str(pinfo->cinfo, COL_PROTOCOL, "Paltalk"); col_clear(pinfo->cinfo, COL_INFO); if (tree) /* we are being asked for details */ { ti = proto_tree_add_item(tree, proto_paltalk, tvb, 0, -1, ENC_NA); pt_tree = proto_item_add_subtree(ti, ett_paltalk); proto_tree_add_item(pt_tree, hf_paltalk_pdu_type, tvb, 0, 2, ENC_BIG_ENDIAN); proto_tree_add_item(pt_tree, hf_paltalk_version, tvb, 2, 2, ENC_BIG_ENDIAN); proto_tree_add_item(pt_tree, hf_paltalk_length, tvb, 4, 2, ENC_BIG_ENDIAN); proto_tree_add_item(pt_tree, hf_paltalk_content, tvb, 6, tvb_get_ntohs(tvb, 4), ENC_NA); } return tvb_length(tvb); } static gboolean dissect_paltalk(tvbuff_t *tvb, packet_info *pinfo, proto_tree *tree, void *data) { guint32 src32, dst32; /* Detect if this TCP session is a Paltalk one */ /* TODO: Optimize detection logic if possible */ if ((pinfo->net_src.type != AT_IPv4) || (pinfo->net_dst.type != AT_IPv4) || (pinfo->net_src.len != 4) || (pinfo->net_dst.len != 4) || !pinfo->net_src.data || !pinfo->net_dst.data) return FALSE; memcpy((guint8 *)&src32, pinfo->net_src.data, 4); /* *Network* order */ memcpy((guint8 *)&dst32, pinfo->net_dst.data, 4); /* *Network* order */ if ( ((src32 & PALTALK_SERVERS_NETMASK) != PALTALK_SERVERS_ADDRESS) && ((dst32 & PALTALK_SERVERS_NETMASK) != PALTALK_SERVERS_ADDRESS)) return FALSE; /* Dissect result of desegmented TCP data */ tcp_dissect_pdus(tvb, pinfo, tree, TRUE, PALTALK_HEADER_LENGTH, dissect_paltalk_get_len, dissect_paltalk_desegmented, data); return TRUE; } void proto_register_paltalk(void) { static hf_register_info hf[] = { { &hf_paltalk_pdu_type, { "Packet Type", "paltalk.type", FT_UINT16, BASE_HEX, NULL, 0x00, NULL, HFILL }}, { &hf_paltalk_version, { "Protocol Version", "paltalk.version", FT_INT16, BASE_DEC, NULL, 0x00, NULL, HFILL }}, { &hf_paltalk_length, { "Payload Length", "paltalk.length", FT_INT16, BASE_DEC, NULL, 0x00, NULL, HFILL }}, { &hf_paltalk_content, { "Payload Content", "paltalk.content", FT_BYTES, BASE_NONE, NULL, 0x00, NULL, HFILL }} }; static gint *ett[] = { &ett_paltalk }; proto_paltalk = proto_register_protocol("Paltalk Messenger Protocol", "Paltalk", "paltalk"); proto_register_field_array(proto_paltalk, hf, array_length(hf)); proto_register_subtree_array(ett, array_length(ett)); } void proto_reg_handoff_paltalk(void) { heur_dissector_add("tcp", dissect_paltalk, proto_paltalk); }
jfzazo/wireshark-hwgen
src/epan/dissectors/packet-paltalk.c
C
gpl-2.0
4,631
// op_codes.h, 159 7 // // operation codes for OS services, e.g., FileSys // here are codes covering more than what we need // // op code is put into msg.nums[0] to send // recipient checks, so to know what to do #ifndef _OP_CODES_H_ #define _OP_CODES_H_ // -------------------- General Code ---------------------- #define OK 0 #define NOT_OK -1 #define NOT_USED -1 // -------------------- MODE Related ---------------------- #define ECHO_OFF 77 #define ECHO_ON 88 // ------------------ FileSys Result ---------------------- #define UNKNOWN_OP_CODE -99 #define NOT_FOUND -11 #define NO_MORE_FD -12 // all file descriptors in use #define END_OF_FILE -13 // no more content #define BAD_PARAM -14 // some parameter was invalid #define BUFF_TOO_SMALL -15 // your buffer too small // ------------------ FileSys Service --------------------- #define RDONLY 0 #define WRONLY 1 #define RDWR 2 #define STAT 20 // message passing: // supply filename string (NUL terminated) in message // return file status structure (overwrites the filename string) #define OPEN 21 // message passing: // supply filename (NUL terminated) // supply operation flag such as RDONLY // return file descriptor if successful, -1 if failure #define READ 22 // message passing: // supply file descriptor // supply buffer in a msg // return number of bytes read // return content read in a msg #define CLOSE 23 // message passing: // supply file descriptor #define SEEK 24 // message passing: // supply file descriptor // supply offset (a +/- value) // supply whence (base: head, tail, or the last position) // return absolute offset (head+offset) #endif
danthemanvsqz/Operating_System_Pragramtics_CSUS
159/A/op_codes.h
C
gpl-2.0
1,752
/* * Copyright (C) 2008-2014 TrinityCore <http://www.trinitycore.org/> * Copyright (C) 2005-2009 MaNGOS <http://getmangos.com/> * * This program is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License as published by the * Free Software Foundation; either version 2 of the License, or (at your * option) any later version. * * This program is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for * more details. * * You should have received a copy of the GNU General Public License along * with this program. If not, see <http://www.gnu.org/licenses/>. */ #ifndef TRINITYCORE_PET_H #define TRINITYCORE_PET_H #include "PetDefines.h" #include "TemporarySummon.h" #define PET_FOCUS_REGEN_INTERVAL 4 * IN_MILLISECONDS #define HAPPINESS_LEVEL_SIZE 333000 struct PetSpell { ActiveStates active; PetSpellState state; PetSpellType type; }; typedef std::unordered_map<uint32, PetSpell> PetSpellMap; typedef std::vector<uint32> AutoSpellList; class Player; class Pet : public Guardian { public: explicit Pet(Player* owner, PetType type = MAX_PET_TYPE); virtual ~Pet(); void AddToWorld() override; void RemoveFromWorld() override; void SetDisplayId(uint32 modelId) override; PetType getPetType() const { return m_petType; } void setPetType(PetType type) { m_petType = type; } bool isControlled() const { return getPetType() == SUMMON_PET || getPetType() == HUNTER_PET; } bool isTemporarySummoned() const { return m_duration > 0; } bool IsPermanentPetFor(Player* owner) const; // pet have tab in character windows and set UNIT_FIELD_PETNUMBER bool Create(uint32 guidlow, Map* map, uint32 Entry, uint32 pet_number); bool CreateBaseAtCreature(Creature* creature); bool CreateBaseAtCreatureInfo(CreatureTemplate const* cinfo, Unit* owner); bool CreateBaseAtTamed(CreatureTemplate const* cinfo, Map* map); bool LoadPetFromDB(Player* owner, uint32 petentry = 0, uint32 petnumber = 0, bool current = false); bool IsLoading() const override { return m_loading;} void SavePetToDB(PetSaveMode mode); void Remove(PetSaveMode mode, bool returnreagent = false); static void DeleteFromDB(uint32 guidlow); void setDeathState(DeathState s) override; // overwrite virtual Creature::setDeathState and Unit::setDeathState void Update(uint32 diff) override; // overwrite virtual Creature::Update and Unit::Update uint8 GetPetAutoSpellSize() const override { return m_autospells.size(); } uint32 GetPetAutoSpellOnPos(uint8 pos) const override { if (pos >= m_autospells.size()) return 0; else return m_autospells[pos]; } void GivePetXP(uint32 xp); void GivePetLevel(uint8 level); void SynchronizeLevelWithOwner(); bool HaveInDiet(ItemTemplate const* item) const; uint32 GetCurrentFoodBenefitLevel(uint32 itemlevel) const; void SetDuration(int32 dur) { m_duration = dur; } int32 GetDuration() const { return m_duration; } /* bool UpdateStats(Stats stat); bool UpdateAllStats(); void UpdateResistances(uint32 school); void UpdateArmor(); void UpdateMaxHealth(); void UpdateMaxPower(Powers power); void UpdateAttackPowerAndDamage(bool ranged = false); void UpdateDamagePhysical(WeaponAttackType attType) override; */ void ToggleAutocast(SpellInfo const* spellInfo, bool apply); bool HasSpell(uint32 spell) const override; void LearnPetPassives(); void CastPetAuras(bool current); void CastPetAura(PetAura const* aura); bool IsPetAura(Aura const* aura); void _LoadSpellCooldowns(); void _SaveSpellCooldowns(SQLTransaction& trans); void _LoadAuras(uint32 timediff); void _SaveAuras(SQLTransaction& trans); void _LoadSpells(); void _SaveSpells(SQLTransaction& trans); bool addSpell(uint32 spellId, ActiveStates active = ACT_DECIDE, PetSpellState state = PETSPELL_NEW, PetSpellType type = PETSPELL_NORMAL); bool learnSpell(uint32 spell_id); void learnSpellHighRank(uint32 spellid); void InitLevelupSpellsForLevel(); bool unlearnSpell(uint32 spell_id, bool learn_prev, bool clear_ab = true); bool removeSpell(uint32 spell_id, bool learn_prev, bool clear_ab = true); void CleanupActionBar(); virtual void ProhibitSpellSchool(SpellSchoolMask idSchoolMask, uint32 unTimeMs) override; PetSpellMap m_spells; AutoSpellList m_autospells; void InitPetCreateSpells(); bool resetTalents(); static void resetTalentsForAllPetsOf(Player* owner, Pet* online_pet = nullptr); void InitTalentForLevel(); uint8 GetMaxTalentPointsForLevel(uint8 level); uint8 GetFreeTalentPoints() { return GetByteValue(UNIT_FIELD_BYTES_1, 1); } void SetFreeTalentPoints(uint8 points) { SetByteValue(UNIT_FIELD_BYTES_1, 1, points); } uint32 m_usedTalentCount; uint64 GetAuraUpdateMaskForRaid() const { return m_auraRaidUpdateMask; } void SetAuraUpdateMaskForRaid(uint8 slot) { m_auraRaidUpdateMask |= (uint64(1) << slot); } void ResetAuraUpdateMaskForRaid() { m_auraRaidUpdateMask = 0; } DeclinedName const* GetDeclinedNames() const { return m_declinedname; } bool m_removed; // prevent overwrite pet state in DB at next Pet::Update if pet already removed(saved) Player* GetOwner() const; protected: PetType m_petType; int32 m_duration; // time until unsummon (used mostly for summoned guardians and not used for controlled pets) uint64 m_auraRaidUpdateMask; bool m_loading; uint32 m_regenTimer; DeclinedName *m_declinedname; private: void SaveToDB(uint32, uint8, uint32) override // override of Creature::SaveToDB - must not be called { ASSERT(false); } void DeleteFromDB() override // override of Creature::DeleteFromDB - must not be called { ASSERT(false); } }; #endif
cooler-SAI/TrinityCore434
src/server/game/Entities/Pet/Pet.h
C
gpl-2.0
6,668
<?php /** * Magento * * NOTICE OF LICENSE * * This source file is subject to the Open Software License (OSL 3.0) * that is bundled with this package in the file LICENSE.txt. * It is also available through the world-wide-web at this URL: * http://opensource.org/licenses/osl-3.0.php * If you did not receive a copy of the license and are unable to * obtain it through the world-wide-web, please send an email * to license@magento.com so we can send you a copy immediately. * * DISCLAIMER * * Do not edit or add to this file if you wish to upgrade Magento to newer * versions in the future. If you wish to customize Magento for your * needs please refer to http://www.magento.com for more information. * * @category Mage * @package Mage_ProductAlert * @copyright Copyright (c) 2006-2014 X.commerce, Inc. (http://www.magento.com) * @license http://opensource.org/licenses/osl-3.0.php Open Software License (OSL 3.0) */ /** * ProductAlert Email processor * * @category Mage * @package Mage_ProductAlert * @author Magento Core Team <core@magentocommerce.com> */ class Mage_ProductAlert_Model_Email extends Mage_Core_Model_Abstract { const XML_PATH_EMAIL_PRICE_TEMPLATE = 'catalog/productalert/email_price_template'; const XML_PATH_EMAIL_STOCK_TEMPLATE = 'catalog/productalert/email_stock_template'; const XML_PATH_EMAIL_IDENTITY = 'catalog/productalert/email_identity'; /** * Type * * @var string */ protected $_type = 'price'; /** * Website Model * * @var Mage_Core_Model_Website */ protected $_website; /** * Customer model * * @var Mage_Customer_Model_Customer */ protected $_customer; /** * Products collection where changed price * * @var array */ protected $_priceProducts = array(); /** * Product collection which of back in stock * * @var array */ protected $_stockProducts = array(); /** * Price block * * @var Mage_ProductAlert_Block_Email_Price */ protected $_priceBlock; /** * Stock block * * @var Mage_ProductAlert_Block_Email_Stock */ protected $_stockBlock; /** * Set model type * * @param string $type */ public function setType($type) { $this->_type = $type; } /** * Retrieve model type * * @return string */ public function getType() { return $this->_type; } /** * Set website model * * @param Mage_Core_Model_Website $website * @return Mage_ProductAlert_Model_Email */ public function setWebsite(Mage_Core_Model_Website $website) { $this->_website = $website; return $this; } /** * Set website id * * @param int $websiteId * @return Mage_ProductAlert_Model_Email */ public function setWebsiteId($websiteId) { $this->_website = Mage::app()->getWebsite($websiteId); return $this; } /** * Set customer by id * * @param int $customerId * @return Mage_ProductAlert_Model_Email */ public function setCustomerId($customerId) { $this->_customer = Mage::getModel('customer/customer')->load($customerId); return $this; } /** * Set customer model * * @param Mage_Customer_Model_Customer $customer * @return Mage_ProductAlert_Model_Email */ public function setCustomer(Mage_Customer_Model_Customer $customer) { $this->_customer = $customer; return $this; } /** * Clean data * * @return Mage_ProductAlert_Model_Email */ public function clean() { $this->_customer = null; $this->_priceProducts = array(); $this->_stockProducts = array(); return $this; } /** * Add product (price change) to collection * * @param Mage_Catalog_Model_Product $product * @return Mage_ProductAlert_Model_Email */ public function addPriceProduct(Mage_Catalog_Model_Product $product) { $this->_priceProducts[$product->getId()] = $product; return $this; } /** * Add product (back in stock) to collection * * @param Mage_Catalog_Model_Product $product * @return Mage_ProductAlert_Model_Email */ public function addStockProduct(Mage_Catalog_Model_Product $product) { $this->_stockProducts[$product->getId()] = $product; return $this; } /** * Retrieve price block * * @return Mage_ProductAlert_Block_Email_Price */ protected function _getPriceBlock() { if (is_null($this->_priceBlock)) { $this->_priceBlock = Mage::helper('productalert') ->createBlock('productalert/email_price'); } return $this->_priceBlock; } /** * Retrieve stock block * * @return Mage_ProductAlert_Block_Email_Stock */ protected function _getStockBlock() { if (is_null($this->_stockBlock)) { $this->_stockBlock = Mage::helper('productalert') ->createBlock('productalert/email_stock'); } return $this->_stockBlock; } /** * Send customer email * * @return bool */ public function send() { if (is_null($this->_website) || is_null($this->_customer)) { return false; } if (($this->_type == 'price' && count($this->_priceProducts) == 0) || ($this->_type == 'stock' && count($this->_stockProducts) == 0)) { return false; } if (!$this->_website->getDefaultGroup() || !$this->_website->getDefaultGroup()->getDefaultStore()) { return false; } $store = $this->_website->getDefaultStore(); $storeId = $store->getId(); if ($this->_type == 'price' && !Mage::getStoreConfig(self::XML_PATH_EMAIL_PRICE_TEMPLATE, $storeId)) { return false; } elseif ($this->_type == 'stock' && !Mage::getStoreConfig(self::XML_PATH_EMAIL_STOCK_TEMPLATE, $storeId)) { return false; } if ($this->_type != 'price' && $this->_type != 'stock') { return false; } $appEmulation = Mage::getSingleton('core/app_emulation'); $initialEnvironmentInfo = $appEmulation->startEnvironmentEmulation($storeId); if ($this->_type == 'price') { $this->_getPriceBlock() ->setStore($store) ->reset(); foreach ($this->_priceProducts as $product) { $product->setCustomerGroupId($this->_customer->getGroupId()); $this->_getPriceBlock()->addProduct($product); } $block = $this->_getPriceBlock()->toHtml(); $templateId = Mage::getStoreConfig(self::XML_PATH_EMAIL_PRICE_TEMPLATE, $storeId); } else { $this->_getStockBlock() ->setStore($store) ->reset(); foreach ($this->_stockProducts as $product) { $product->setCustomerGroupId($this->_customer->getGroupId()); $this->_getStockBlock()->addProduct($product); } $block = $this->_getStockBlock()->toHtml(); $templateId = Mage::getStoreConfig(self::XML_PATH_EMAIL_STOCK_TEMPLATE, $storeId); } $appEmulation->stopEnvironmentEmulation($initialEnvironmentInfo); Mage::getModel('core/email_template') ->setDesignConfig(array( 'area' => 'frontend', 'store' => $storeId ))->sendTransactional( $templateId, Mage::getStoreConfig(self::XML_PATH_EMAIL_IDENTITY, $storeId), $this->_customer->getEmail(), $this->_customer->getName(), array( 'customerName' => $this->_customer->getName(), 'alertGrid' => $block ) ); return true; } }
T0MM0R/magento
web/app/code/core/Mage/ProductAlert/Model/Email.php
PHP
gpl-2.0
8,161
/* ** file.cpp ** ** This file is part of mkxp. ** ** Copyright (C) 2013 Jonas Kulla <Nyocurio@gmail.com> ** ** mkxp 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. ** ** mkxp 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 mkxp. If not, see <http://www.gnu.org/licenses/>. */ #include "file.h" #include "debugwriter.h" #include "../binding-util.h" #include <mruby/string.h> #include <mruby/array.h> #include <mruby/class.h> #include <SDL_rwops.h> #include <stdio.h> #include <errno.h> #include <unistd.h> #include <libgen.h> #include <sys/stat.h> #include <vector> extern mrb_value timeFromSecondsInt(mrb_state *mrb, time_t seconds); static void checkValid(mrb_state *mrb, FileImpl *p, int rwMode = FileImpl::ReadWrite) { MrbData *data = getMrbData(mrb); if (p->closed) mrb_raise(mrb, data->exc[IO], "closed stream"); if (!(p->mode & rwMode)) { const char *errorMsg = 0; switch (rwMode) { case FileImpl::Read : errorMsg = "not openend for reading"; break; case FileImpl::Write : errorMsg = "not openend for writing"; break; default: break; } mrb_raise(mrb, data->exc[IO], errorMsg); } } extern const mrb_data_type FileType = { "File", freeInstance<FileImpl> }; static int getOpenMode(const char *mode) { #define STR_CASE(cs, ret) else if (!strcmp(mode, cs)) { return FileImpl:: ret; } if (!strcmp(mode, "r")) return FileImpl::Read; STR_CASE("rb", Read) STR_CASE("r+", ReadWrite) STR_CASE("w", Write) STR_CASE("wb", Write) STR_CASE("w+", ReadWrite) STR_CASE("rw", ReadWrite) STR_CASE("a", Write) STR_CASE("a+", ReadWrite) Debug() << "getOpenMode failed for:" << mode; return 0; } static void handleErrno(mrb_state *mrb) { MrbException exc; const char *msg; mrb_value arg1; #define ENO(_eno, _msg) \ case _eno: { exc = Errno##_eno; msg = _msg; break; } switch (errno) { ENO(EACCES, ""); ENO(EBADF, ""); ENO(EEXIST, ""); ENO(EINVAL, ""); ENO(EMFILE, ""); ENO(ENOMEM, ""); ENO(ERANGE, ""); default: exc = IO; msg = "Unknown Errno: %S"; arg1 = mrb_any_to_s(mrb, mrb_fixnum_value(errno)); } #undef ENO mrb_raisef(mrb, getMrbData(mrb)->exc[exc], msg, arg1); } #define GUARD_ERRNO(stmnt) \ { \ errno = 0; \ { stmnt } \ if (errno != 0) \ handleErrno(mrb); \ } static char * findLastDot(char *str) { char *find = 0; char *ptr = str; /* Dot in front is not considered */ if (*ptr == '.') ptr++; for (; *ptr; ++ptr) { /* Dot in dirpath is not considered */ if (*ptr == '/') { ptr++; if (*ptr == '.') ptr++; } if (*ptr == '.') find = ptr; } return find; } /* File class methods */ MRB_FUNCTION(fileBasename) { mrb_value filename; const char *suffix = 0; mrb_get_args(mrb, "S|z", &filename, &suffix); char *_filename = RSTRING_PTR(filename); char *base = basename(_filename); char *ext = 0; if (suffix) { ext = findLastDot(base); if (ext && !strcmp(ext, suffix)) *ext = '\0'; } mrb_value str = mrb_str_new_cstr(mrb, base); /* Restore param string */ if (ext) *ext = '.'; return str; } MRB_FUNCTION(fileDelete) { mrb_int argc; mrb_value *argv; mrb_get_args(mrb, "*", &argv, &argc); for (int i = 0; i < argc; ++i) { mrb_value &v = argv[i]; if (!mrb_string_p(v)) continue; const char *filename = RSTRING_PTR(v); GUARD_ERRNO( unlink(filename); ) } return mrb_nil_value(); } MRB_FUNCTION(fileDirname) { mrb_value filename; mrb_get_args(mrb, "S", &filename); char *_filename = RSTRING_PTR(filename); char *dir = dirname(_filename); return mrb_str_new_cstr(mrb, dir); } MRB_FUNCTION(fileExpandPath) { const char *path; const char *defDir = 0; mrb_get_args(mrb, "z|z", &path, &defDir); // FIXME No idea how to integrate 'default_dir' right now if (defDir) Debug() << "FIXME: File.expand_path: default_dir not implemented"; char buffer[PATH_MAX]; char *unused = realpath(path, buffer); (void) unused; return mrb_str_new_cstr(mrb, buffer); } MRB_FUNCTION(fileExtname) { mrb_value filename; mrb_get_args(mrb, "S", &filename); char *ext = findLastDot(RSTRING_PTR(filename)); return mrb_str_new_cstr(mrb, ext); } MRB_FUNCTION(fileOpen) { mrb_value path; const char *mode = "r"; mrb_value block = mrb_nil_value(); mrb_get_args(mrb, "S|z&", &path, &mode, &block); /* We manually check errno because we're supplying the * filename on ENOENT */ errno = 0; FILE *f = fopen(RSTRING_PTR(path), mode); if (!f) { if (errno == ENOENT) mrb_raisef(mrb, getMrbData(mrb)->exc[ErrnoENOENT], "No such file or directory - %S", path); else handleErrno(mrb); } SDL_RWops *ops = SDL_RWFromFP(f, SDL_TRUE); FileImpl *p = new FileImpl(ops, getOpenMode(mode)); mrb_value obj = wrapObject(mrb, p, FileType); setProperty(mrb, obj, CSpath, path); if (mrb_type(block) == MRB_TT_PROC) { // FIXME inquire how GC behaviour works here for obj mrb_value ret = mrb_yield(mrb, block, obj); p->close(); return ret; } return obj; } MRB_FUNCTION(fileRename) { const char *from, *to; mrb_get_args(mrb, "zz", &from, &to); GUARD_ERRNO( rename(from, to); ) return mrb_fixnum_value(0); } MRB_FUNCTION(mrbNoop) { MRB_FUN_UNUSED_PARAM; return mrb_nil_value(); } /* File instance methods */ MRB_METHOD(fileClose) { FileImpl *p = getPrivateData<FileImpl>(mrb, self); checkValid(mrb, p); GUARD_ERRNO( p->close(); ) return self; } static void readLine(FILE *f, std::vector<char> &buffer) { buffer.clear(); while (true) { if (feof(f)) break; int c = fgetc(f); if (c == '\n' || c == EOF) break; buffer.push_back(c); } } MRB_METHOD(fileEachLine) { FileImpl *p = getPrivateData<FileImpl>(mrb, self); checkValid(mrb, p, FileImpl::Read); FILE *f = p->fp(); mrb_value block; mrb_get_args(mrb, "&", &block); (void) f; std::vector<char> buffer; mrb_value str = mrb_str_buf_new(mrb, 0); while (feof(f) == 0) { GUARD_ERRNO( readLine(f, buffer); ) if (buffer.empty() && feof(f) != 0) break; size_t lineLen = buffer.size(); mrb_str_resize(mrb, str, lineLen); memcpy(RSTRING_PTR(str), &buffer[0], lineLen); mrb_yield(mrb, block, str); } return self; } MRB_METHOD(fileEachByte) { FileImpl *p = getPrivateData<FileImpl>(mrb, self); checkValid(mrb, p, FileImpl::Read); FILE *f = p->fp(); mrb_value block; mrb_get_args(mrb, "&", &block); GUARD_ERRNO( while (feof(f) == 0) { mrb_int byte = fgetc(f); if (byte == -1) break; mrb_yield(mrb, block, mrb_fixnum_value(byte)); }) return self; } MRB_METHOD(fileIsEof) { FileImpl *p = getPrivateData<FileImpl>(mrb, self); checkValid(mrb, p); FILE *f = p->fp(); bool isEof; GUARD_ERRNO( isEof = feof(f) != 0; ) return mrb_bool_value(isEof); } MRB_METHOD(fileSetPos) { FileImpl *p = getPrivateData<FileImpl>(mrb, self); checkValid(mrb, p); FILE *f = p->fp(); mrb_int pos; mrb_get_args(mrb, "i", &pos); GUARD_ERRNO( fseek(f, pos, SEEK_SET); ) return self; } MRB_METHOD(fileGetPos) { FileImpl *p = getPrivateData<FileImpl>(mrb, self); checkValid(mrb, p); FILE *f = p->fp(); long pos; GUARD_ERRNO( pos = ftell(f); ) return mrb_fixnum_value(pos); } MRB_METHOD(fileRead) { FileImpl *p = getPrivateData<FileImpl>(mrb, self); checkValid(mrb, p, FileImpl::Read); FILE *f = p->fp(); long cur, size; GUARD_ERRNO( cur = ftell(f); ) GUARD_ERRNO( fseek(f, 0, SEEK_END); ) GUARD_ERRNO( size = ftell(f); ) GUARD_ERRNO( fseek(f, cur, SEEK_SET); ) mrb_int length = size - cur; mrb_get_args(mrb, "|i", &length); mrb_value str = mrb_str_new(mrb, 0, 0); mrb_str_resize(mrb, str, length); GUARD_ERRNO( int unused = fread(RSTRING_PTR(str), 1, length, f); (void) unused; ) return str; } // FIXME this function always splits on newline right now, // to make rs fully work, I'll have to use some strrstr magic I guess MRB_METHOD(fileReadLines) { FileImpl *p = getPrivateData<FileImpl>(mrb, self); checkValid(mrb, p, FileImpl::Read); FILE *f = p->fp(); mrb_value arg; mrb_get_args(mrb, "|o", &arg); const char *rs = "\n"; (void) rs; if (mrb->c->ci->argc > 0) { Debug() << "FIXME: File.readlines: rs not implemented"; if (mrb_string_p(arg)) rs = RSTRING_PTR(arg); else if (mrb_nil_p(arg)) rs = "\n"; else mrb_raise(mrb, getMrbData(mrb)->exc[TypeError], "Expected string or nil"); // FIXME add "got <> instead" remark } mrb_value ary = mrb_ary_new(mrb); std::vector<char> buffer; while (feof(f) == 0) { GUARD_ERRNO( readLine(f, buffer); ) if (buffer.empty() && feof(f) != 0) break; mrb_value str = mrb_str_new(mrb, &buffer[0], buffer.size()); mrb_ary_push(mrb, ary, str); } return ary; } MRB_METHOD(fileWrite) { FileImpl *p = getPrivateData<FileImpl>(mrb, self); checkValid(mrb, p, FileImpl::Write); FILE *f = p->fp(); mrb_value str; mrb_get_args(mrb, "S", &str); size_t count; GUARD_ERRNO( count = fwrite(RSTRING_PTR(str), 1, RSTRING_LEN(str), f); ) return mrb_fixnum_value(count); } MRB_METHOD(fileGetPath) { FileImpl *p = getPrivateData<FileImpl>(mrb, self); checkValid(mrb, p); return getProperty(mrb, self, CSpath); } static void getFileStat(mrb_state *mrb, struct stat &fileStat) { const char *filename; mrb_get_args(mrb, "z", &filename); stat(filename, &fileStat); } MRB_METHOD(fileGetMtime) { mrb_value path = getProperty(mrb, self, CSpath); struct stat fileStat; stat(RSTRING_PTR(path), &fileStat); return timeFromSecondsInt(mrb, fileStat.st_mtim.tv_sec); } /* FileTest module functions */ MRB_FUNCTION(fileTestDoesExist) { const char *filename; mrb_get_args(mrb, "z", &filename); int result = access(filename, F_OK); return mrb_bool_value(result == 0); } MRB_FUNCTION(fileTestIsFile) { struct stat fileStat; getFileStat(mrb, fileStat); return mrb_bool_value(S_ISREG(fileStat.st_mode)); } MRB_FUNCTION(fileTestIsDirectory) { struct stat fileStat; getFileStat(mrb, fileStat); return mrb_bool_value(S_ISDIR(fileStat.st_mode)); } MRB_FUNCTION(fileTestSize) { struct stat fileStat; getFileStat(mrb, fileStat); return mrb_fixnum_value(fileStat.st_size); } void fileBindingInit(mrb_state *mrb) { mrb_define_method(mrb, mrb->kernel_module, "open", fileOpen, MRB_ARGS_REQ(1) | MRB_ARGS_OPT(1) | MRB_ARGS_BLOCK()); RClass *klass = defineClass(mrb, "IO"); klass = mrb_define_class(mrb, "File", klass); mrb_define_class_method(mrb, klass, "basename", fileBasename, MRB_ARGS_REQ(1) | MRB_ARGS_OPT(1)); mrb_define_class_method(mrb, klass, "delete", fileDelete, MRB_ARGS_REQ(1) | MRB_ARGS_ANY()); mrb_define_class_method(mrb, klass, "dirname", fileDirname, MRB_ARGS_REQ(1)); mrb_define_class_method(mrb, klass, "expand_path", fileExpandPath, MRB_ARGS_REQ(1) | MRB_ARGS_OPT(1)); mrb_define_class_method(mrb, klass, "extname", fileExtname, MRB_ARGS_REQ(1)); mrb_define_class_method(mrb, klass, "open", fileOpen, MRB_ARGS_REQ(1) | MRB_ARGS_OPT(1) | MRB_ARGS_BLOCK()); mrb_define_class_method(mrb, klass, "rename", fileRename, MRB_ARGS_REQ(2)); /* IO */ mrb_define_method(mrb, klass, "binmode", mrbNoop, MRB_ARGS_NONE()); mrb_define_method(mrb, klass, "close", fileClose, MRB_ARGS_NONE()); mrb_define_method(mrb, klass, "each_line", fileEachLine, MRB_ARGS_BLOCK()); mrb_define_method(mrb, klass, "each_byte", fileEachByte, MRB_ARGS_BLOCK()); mrb_define_method(mrb, klass, "eof?", fileIsEof, MRB_ARGS_NONE()); mrb_define_method(mrb, klass, "pos", fileGetPos, MRB_ARGS_NONE()); mrb_define_method(mrb, klass, "pos=", fileSetPos, MRB_ARGS_REQ(1)); mrb_define_method(mrb, klass, "read", fileRead, MRB_ARGS_OPT(1)); mrb_define_method(mrb, klass, "readlines", fileReadLines, MRB_ARGS_OPT(1)); mrb_define_method(mrb, klass, "write", fileWrite, MRB_ARGS_REQ(1)); /* File */ mrb_define_method(mrb, klass, "mtime", fileGetMtime, MRB_ARGS_NONE()); mrb_define_method(mrb, klass, "path", fileGetPath, MRB_ARGS_NONE()); /* FileTest */ RClass *module = mrb_define_module(mrb, "FileTest"); mrb_define_module_function(mrb, module, "exist?", fileTestDoesExist, MRB_ARGS_REQ(1)); mrb_define_module_function(mrb, module, "directory?", fileTestIsDirectory, MRB_ARGS_REQ(1)); mrb_define_module_function(mrb, module, "file?", fileTestIsFile, MRB_ARGS_REQ(1)); mrb_define_module_function(mrb, module, "size", fileTestSize, MRB_ARGS_REQ(1)); }
Ancurio/mkxp-abs
binding-mruby/mrb-ext/file.cpp
C++
gpl-2.0
12,649
/* * This file is part of the TrinityCore Project. See AUTHORS file for Copyright information * * This program is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License as published by the * Free Software Foundation; either version 2 of the License, or (at your * option) any later version. * * This program is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for * more details. * * You should have received a copy of the GNU General Public License along * with this program. If not, see <http://www.gnu.org/licenses/>. */ #ifndef TRINITY_FOLLOWMOVEMENTGENERATOR_H #define TRINITY_FOLLOWMOVEMENTGENERATOR_H #include "AbstractFollower.h" #include "MovementDefines.h" #include "MovementGenerator.h" #include "Optional.h" #include "Position.h" class PathGenerator; class Unit; #define FOLLOW_RANGE_TOLERANCE 1.0f class FollowMovementGenerator : public MovementGenerator, public AbstractFollower { public: explicit FollowMovementGenerator(Unit* target, float range, ChaseAngle angle); ~FollowMovementGenerator(); void Initialize(Unit*) override; void Reset(Unit*) override; bool Update(Unit*, uint32) override; void Deactivate(Unit*) override; void Finalize(Unit*, bool, bool) override; MovementGeneratorType GetMovementGeneratorType() const override { return FOLLOW_MOTION_TYPE; } void UnitSpeedChanged() override { _lastTargetPosition.reset(); } private: static constexpr uint32 CHECK_INTERVAL = 500; void UpdatePetSpeed(Unit* owner); float const _range; ChaseAngle const _angle; uint32 _checkTimer = CHECK_INTERVAL; std::unique_ptr<PathGenerator> _path; Optional<Position> _lastTargetPosition; }; #endif
funjoker/TrinityCore
src/server/game/Movement/MovementGenerators/FollowMovementGenerator.h
C
gpl-2.0
1,974
/* Copyright (c) 2009-2010, Code Aurora Forum. All rights reserved. * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License version 2 and * only version 2 as published by the Free Software Foundation. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA * 02110-1301, USA. */ /* * Bluetooth Power Switch Module * controls power to external Bluetooth device * with interface to power management device */ #include <linux/init.h> #include <linux/module.h> #include <linux/kernel.h> #include <linux/platform_device.h> #include <linux/rfkill.h> #if defined (CONFIG_MACH_LGE) #include <mach/board_lge.h> static struct bluetooth_platform_data *bt_platform_data = 0; #else /* origin */ static bool previous; static int bluetooth_toggle_radio(void *data, bool blocked) { int ret = 0; int (*power_control)(int enable); power_control = data; if (previous != blocked) ret = (*power_control)(!blocked); if (!ret) previous = blocked; return ret; } #endif /* LGE_CHANGES_S [taekeun1.kim@lge.com] 2010-06-06, for bt */ #if defined (CONFIG_MACH_LGE) static struct rfkill_ops bluetooth_power_rfkill_ops; #else static const struct rfkill_ops bluetooth_power_rfkill_ops = { .set_block = bluetooth_toggle_radio, }; #endif static int bluetooth_power_rfkill_probe(struct platform_device *pdev) { struct rfkill *rfkill; int ret; printk(KERN_ERR "[LG_BTUI] %s : Called bluetooth_power_rfkill_probe",__func__); /* LGE_CHANGES_S [taekeun1.kim@lge.com] 2010-06-06, for bt */ #if defined (CONFIG_MACH_LGE) bluetooth_power_rfkill_ops.set_block = bt_platform_data->bluetooth_toggle_radio; #endif rfkill = rfkill_alloc("bt_power", &pdev->dev, RFKILL_TYPE_BLUETOOTH, &bluetooth_power_rfkill_ops, pdev->dev.platform_data); if (!rfkill) { dev_err(&pdev->dev, "rfkill allocate failed\n"); return -ENOMEM; } /* force Bluetooth off during init to allow for user control */ rfkill_init_sw_state(rfkill, 1); #if !defined (CONFIG_MACH_LGE) previous = 1; #endif ret = rfkill_register(rfkill); if (ret) { dev_err(&pdev->dev, "rfkill register failed=%d\n", ret); rfkill_destroy(rfkill); return ret; } platform_set_drvdata(pdev, rfkill); return 0; } static void bluetooth_power_rfkill_remove(struct platform_device *pdev) { struct rfkill *rfkill; dev_dbg(&pdev->dev, "%s\n", __func__); rfkill = platform_get_drvdata(pdev); if (rfkill) rfkill_unregister(rfkill); rfkill_destroy(rfkill); platform_set_drvdata(pdev, NULL); } static int __devinit bt_power_probe(struct platform_device *pdev) { int ret = 0; dev_dbg(&pdev->dev, "%s\n", __func__); printk(KERN_ERR "[LG_BTUI] %s : Called bt_power_probe",__func__); if (!pdev->dev.platform_data) { dev_err(&pdev->dev, "platform data not initialized\n"); return -ENOSYS; } #if defined (CONFIG_MACH_LGE) bt_platform_data = (struct bluetooth_platform_data *)pdev->dev.platform_data; #endif ret = bluetooth_power_rfkill_probe(pdev); return ret; } static int __devexit bt_power_remove(struct platform_device *pdev) { dev_dbg(&pdev->dev, "%s\n", __func__); bluetooth_power_rfkill_remove(pdev); return 0; } static struct platform_driver bt_power_driver = { .probe = bt_power_probe, .remove = __devexit_p(bt_power_remove), .driver = { .name = "bt_power", .owner = THIS_MODULE, }, }; static int __init bluetooth_power_init(void) { int ret; printk(KERN_ERR "[LG_BTUI] %s : Called bluetooth_power_init",__func__); ret = platform_driver_register(&bt_power_driver); return ret; } static void __exit bluetooth_power_exit(void) { platform_driver_unregister(&bt_power_driver); } MODULE_LICENSE("GPL v2"); MODULE_DESCRIPTION("MSM Bluetooth power control driver"); MODULE_VERSION("1.40"); module_init(bluetooth_power_init); module_exit(bluetooth_power_exit);
mtmichaelson/LG_Spectrum_Kernel
drivers/bluetooth/bluetooth-power.c
C
gpl-2.0
4,254
""" A HTML5 target. """ from targets import _ from html import TYPE import html NAME = _('HTML5 page') EXTENSION = 'html' HEADER = """\ <!DOCTYPE html> <html> <head> <meta charset="%(ENCODING)s"> <title>%(HEADER1)s</title> <meta name="generator" content="http://txt2tags.org"> <link rel="stylesheet" href="%(STYLE)s"> <style> body{background-color:#fff;color:#000;} hr{background-color:#000;border:0;color:#000;} hr.heavy{height:5px;} hr.light{height:1px;} img{border:0;display:block;} img.right{margin:0 0 0 auto;} img.center{border:0;margin:0 auto;} table th,table td{padding:4px;} .center,header{text-align:center;} table.center {margin-left:auto; margin-right:auto;} .right{text-align:right;} .left{text-align:left;} .tableborder,.tableborder td,.tableborder th{border:1px solid #000;} .underline{text-decoration:underline;} </style> </head> <body> <header> <hgroup> <h1>%(HEADER1)s</h1> <h2>%(HEADER2)s</h2> <h3>%(HEADER3)s</h3> </hgroup> </header> <article> """ HEADERCSS = """\ <!DOCTYPE html> <html> <head> <meta charset="%(ENCODING)s"> <title>%(HEADER1)s</title> <meta name="generator" content="http://txt2tags.org"> <link rel="stylesheet" href="%(STYLE)s"> </head> <body> <header> <hgroup> <h1>%(HEADER1)s</h1> <h2>%(HEADER2)s</h2> <h3>%(HEADER3)s</h3> </hgroup> </header> <article> """ TAGS = html.TAGS.copy() for tag in TAGS: TAGS[tag] = TAGS[tag].lower() HTML5TAGS = { 'title1Open' : '<section~A~>\n<h1>\a</h1>' , 'title1Close' : '</section>' , 'title2Open' : '<section~A~>\n<h2>\a</h2>' , 'title2Close' : '</section>' , 'title3Open' : '<section~A~>\n<h3>\a</h3>' , 'title3Close' : '</section>' , 'title4Open' : '<section~A~>\n<h4>\a</h4>' , 'title4Close' : '</section>' , 'title5Open' : '<section~A~>\n<h5>\a</h5>' , 'title5Close' : '</section>' , 'fontBoldOpen' : '<strong>' , 'fontBoldClose' : '</strong>' , 'fontItalicOpen' : '<em>' , 'fontItalicClose' : '</em>' , 'fontUnderlineOpen' : '<span class="underline">', 'fontUnderlineClose' : '</span>' , 'fontStrikeOpen' : '<del>' , 'fontStrikeClose' : '</del>' , 'listItemClose' : '</li>' , 'numlistItemClose' : '</li>' , 'deflistItem2Close' : '</dd>' , 'bar1' : '<hr class="light">' , 'bar2' : '<hr class="heavy">' , 'img' : '<img~a~ src="\a" alt="">' , 'imgEmbed' : '<img~a~ src="\a" alt="">' , '_imgAlignLeft' : ' class="left"' , '_imgAlignCenter' : ' class="center"', '_imgAlignRight' : ' class="right"' , 'tableOpen' : '<table~a~~b~>' , '_tableBorder' : ' class="tableborder"' , '_tableAlignCenter' : ' style="margin-left: auto; margin-right: auto;"', '_tableCellAlignRight' : ' class="right"' , '_tableCellAlignCenter': ' class="center"', 'cssOpen' : '<style>' , 'tocOpen' : '<nav>' , 'tocClose' : '</nav>' , 'EOD' : '</article></body></html>' } TAGS.update(HTML5TAGS) RULES = html.RULES.copy() #Update the rules to use explicit <section> </section> tags HTML5RULES = { 'titleblocks' : 1, } RULES.update(HTML5RULES)
farvardin/txt2tags-test
targets/html5.py
Python
gpl-2.0
3,582
<?php /*--------------------------------------------- * * [raw]..[/raw] * * Protect shortcode content from wpautop and wptexturize * */ function ccs_raw_format( $content ) { $new_content = null; $pattern_full = '{(\[raw\].*?\[/raw\])}is'; $pattern_contents = '{\[raw\](.*?)\[/raw\]}is'; $pieces = preg_split($pattern_full, $content, -1, PREG_SPLIT_DELIM_CAPTURE); foreach ($pieces as $piece) { if (preg_match($pattern_contents, $piece, $matches)) { $new_content .= $matches[1]; } else { $new_content .= wptexturize(wpautop($piece)); } } return $new_content; } remove_filter('the_content', 'wpautop'); remove_filter('the_content', 'wptexturize'); add_filter('the_content', 'ccs_raw_format', 1);
itercommunity/IterCommunity
wp-content/plugins/raw.php
PHP
gpl-2.0
725
<?php /** * Copyright © 2015 Magento. All rights reserved. * See COPYING.txt for license details. */ namespace Magento\GiftMessage\Block\Cart\Item\Renderer\Actions; use Magento\Quote\Model\Quote\Item\AbstractItem; class ItemIdProcessor implements LayoutProcessorInterface { /** * Adds item ID to giftOptionsCartItem configuration and name * * @param array $jsLayout * @param AbstractItem $item * @return array */ public function process($jsLayout, AbstractItem $item) { if (isset($jsLayout['components']['giftOptionsCartItem'])) { if (!isset($jsLayout['components']['giftOptionsCartItem']['config'])) { $jsLayout['components']['giftOptionsCartItem']['config'] = []; } $jsLayout['components']['giftOptionsCartItem']['config']['itemId'] = $item->getId(); $jsLayout['components']['giftOptionsCartItem-' . $item->getId()] = $jsLayout['components']['giftOptionsCartItem']; unset($jsLayout['components']['giftOptionsCartItem']); } return $jsLayout; } }
FPLD/project0
vendor/magento/module-gift-message/Block/Cart/Item/Renderer/Actions/ItemIdProcessor.php
PHP
gpl-2.0
1,117
<?php /** * Copyright © 2015 Magento. All rights reserved. * See COPYING.txt for license details. */ namespace Magento\Framework\View\Element\Message\Renderer; use Magento\Framework\Message\MessageInterface; interface RendererInterface { /** * Renders message * * @param MessageInterface $message * @param array $initializationData * @return string */ public function render(MessageInterface $message, array $initializationData); }
FPLD/project0
vendor/magento/framework/View/Element/Message/Renderer/RendererInterface.php
PHP
gpl-2.0
476
/* * (C) Copyright 2010-2012 * NVIDIA Corporation <www.nvidia.com> * * SPDX-License-Identifier: GPL-2.0+ */ #ifndef __TEGRA_COMMON_POST_H #define __TEGRA_COMMON_POST_H #ifndef CONFIG_SPL_BUILD #define BOOT_TARGET_DEVICES(func) \ func(MMC, mmc, 1) \ func(MMC, mmc, 0) \ func(USB, usb, 0) \ func(PXE, pxe, na) \ func(DHCP, dhcp, na) #include <config_distro_bootcmd.h> #else #define BOOTENV #endif #ifdef CONFIG_TEGRA_KEYBOARD #define STDIN_KBD_KBC ",tegra-kbc" #else #define STDIN_KBD_KBC "" #endif #ifdef CONFIG_USB_KEYBOARD #define STDIN_KBD_USB ",usbkbd" #define CONFIG_SYS_USB_EVENT_POLL #define CONFIG_PREBOOT "usb start" #else #define STDIN_KBD_USB "" #endif #ifdef CONFIG_VIDEO_TEGRA #define STDOUT_LCD ",lcd" #else #define STDOUT_LCD "" #endif #define TEGRA_DEVICE_SETTINGS \ "stdin=serial" STDIN_KBD_KBC STDIN_KBD_USB "\0" \ "stdout=serial" STDOUT_LCD "\0" \ "stderr=serial" STDOUT_LCD "\0" \ "" #ifndef BOARD_EXTRA_ENV_SETTINGS #define BOARD_EXTRA_ENV_SETTINGS #endif #define CONFIG_EXTRA_ENV_SETTINGS \ TEGRA_DEVICE_SETTINGS \ MEM_LAYOUT_ENV_SETTINGS \ "fdt_high=ffffffff\0" \ "initrd_high=ffffffff\0" \ BOOTENV \ BOARD_EXTRA_ENV_SETTINGS #if defined(CONFIG_TEGRA20_SFLASH) || defined(CONFIG_TEGRA20_SLINK) || defined(CONFIG_TEGRA114_SPI) #define CONFIG_FDT_SPI #endif /* overrides for SPL build here */ #ifdef CONFIG_SPL_BUILD #define CONFIG_SKIP_LOWLEVEL_INIT /* remove devicetree support */ #ifdef CONFIG_OF_CONTROL #endif /* remove I2C support */ #ifdef CONFIG_SYS_I2C_TEGRA #undef CONFIG_SYS_I2C_TEGRA #endif #ifdef CONFIG_CMD_I2C #undef CONFIG_CMD_I2C #endif /* remove MMC support */ #ifdef CONFIG_MMC #undef CONFIG_MMC #endif #ifdef CONFIG_GENERIC_MMC #undef CONFIG_GENERIC_MMC #endif #ifdef CONFIG_TEGRA_MMC #undef CONFIG_TEGRA_MMC #endif #ifdef CONFIG_CMD_MMC #undef CONFIG_CMD_MMC #endif /* remove partitions/filesystems */ #ifdef CONFIG_DOS_PARTITION #undef CONFIG_DOS_PARTITION #endif #ifdef CONFIG_EFI_PARTITION #undef CONFIG_EFI_PARTITION #endif #ifdef CONFIG_CMD_FS_GENERIC #undef CONFIG_CMD_FS_GENERIC #endif #ifdef CONFIG_CMD_EXT4 #undef CONFIG_CMD_EXT4 #endif #ifdef CONFIG_CMD_EXT2 #undef CONFIG_CMD_EXT2 #endif #ifdef CONFIG_CMD_FAT #undef CONFIG_CMD_FAT #endif #ifdef CONFIG_FS_EXT4 #undef CONFIG_FS_EXT4 #endif #ifdef CONFIG_FS_FAT #undef CONFIG_FS_FAT #endif /* remove USB */ #ifdef CONFIG_USB_EHCI #undef CONFIG_USB_EHCI #endif #ifdef CONFIG_USB_EHCI_TEGRA #undef CONFIG_USB_EHCI_TEGRA #endif #ifdef CONFIG_USB_STORAGE #undef CONFIG_USB_STORAGE #endif #ifdef CONFIG_CMD_USB #undef CONFIG_CMD_USB #endif /* remove part command support */ #ifdef CONFIG_PARTITION_UUIDS #undef CONFIG_PARTITION_UUIDS #endif #ifdef CONFIG_CMD_PART #undef CONFIG_CMD_PART #endif #endif /* CONFIG_SPL_BUILD */ #endif /* __TEGRA_COMMON_POST_H */
dingguanliang/uboot2014formicro2440
u-boot-2014.10/include/configs/tegra-common-post.h
C
gpl-2.0
2,797
//===-- BranchFolding.cpp - Fold machine code branch instructions ---------===// // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// // // This pass forwards branches to unconditional branches to make them branch // directly to the target block. This pass often results in dead MBB's, which // it then removes. // // Note that this pass must be run after register allocation, it cannot handle // SSA form. // //===----------------------------------------------------------------------===// #include "BranchFolding.h" #include "llvm/ADT/STLExtras.h" #include "llvm/ADT/SmallSet.h" #include "llvm/ADT/Statistic.h" #include "llvm/CodeGen/MachineBlockFrequencyInfo.h" #include "llvm/CodeGen/MachineBranchProbabilityInfo.h" #include "llvm/CodeGen/MachineFunctionPass.h" #include "llvm/CodeGen/MachineJumpTableInfo.h" #include "llvm/CodeGen/MachineMemOperand.h" #include "llvm/CodeGen/MachineModuleInfo.h" #include "llvm/CodeGen/MachineRegisterInfo.h" #include "llvm/CodeGen/Passes.h" #include "llvm/CodeGen/RegisterScavenging.h" #include "llvm/IR/Function.h" #include "llvm/Support/CommandLine.h" #include "llvm/Support/Debug.h" #include "llvm/Support/ErrorHandling.h" #include "llvm/Support/raw_ostream.h" #include "llvm/Target/TargetInstrInfo.h" #include "llvm/Target/TargetRegisterInfo.h" #include "llvm/Target/TargetSubtargetInfo.h" #include <algorithm> using namespace llvm; #define DEBUG_TYPE "branchfolding" STATISTIC(NumDeadBlocks, "Number of dead blocks removed"); STATISTIC(NumBranchOpts, "Number of branches optimized"); STATISTIC(NumTailMerge , "Number of block tails merged"); STATISTIC(NumHoist , "Number of times common instructions are hoisted"); static cl::opt<cl::boolOrDefault> FlagEnableTailMerge("enable-tail-merge", cl::init(cl::BOU_UNSET), cl::Hidden); // Throttle for huge numbers of predecessors (compile speed problems) static cl::opt<unsigned> TailMergeThreshold("tail-merge-threshold", cl::desc("Max number of predecessors to consider tail merging"), cl::init(150), cl::Hidden); // Heuristic for tail merging (and, inversely, tail duplication). // TODO: This should be replaced with a target query. static cl::opt<unsigned> TailMergeSize("tail-merge-size", cl::desc("Min number of instructions to consider tail merging"), cl::init(3), cl::Hidden); namespace { /// BranchFolderPass - Wrap branch folder in a machine function pass. class BranchFolderPass : public MachineFunctionPass { public: static char ID; explicit BranchFolderPass(): MachineFunctionPass(ID) {} bool runOnMachineFunction(MachineFunction &MF) override; void getAnalysisUsage(AnalysisUsage &AU) const override { AU.addRequired<MachineBlockFrequencyInfo>(); AU.addRequired<MachineBranchProbabilityInfo>(); AU.addRequired<TargetPassConfig>(); MachineFunctionPass::getAnalysisUsage(AU); } }; } char BranchFolderPass::ID = 0; char &llvm::BranchFolderPassID = BranchFolderPass::ID; INITIALIZE_PASS(BranchFolderPass, "branch-folder", "Control Flow Optimizer", false, false) bool BranchFolderPass::runOnMachineFunction(MachineFunction &MF) { if (skipOptnoneFunction(*MF.getFunction())) return false; TargetPassConfig *PassConfig = &getAnalysis<TargetPassConfig>(); // TailMerge can create jump into if branches that make CFG irreducible for // HW that requires structurized CFG. bool EnableTailMerge = !MF.getTarget().requiresStructuredCFG() && PassConfig->getEnableTailMerge(); BranchFolder Folder(EnableTailMerge, /*CommonHoist=*/true, getAnalysis<MachineBlockFrequencyInfo>(), getAnalysis<MachineBranchProbabilityInfo>()); return Folder.OptimizeFunction(MF, MF.getSubtarget().getInstrInfo(), MF.getSubtarget().getRegisterInfo(), getAnalysisIfAvailable<MachineModuleInfo>()); } BranchFolder::BranchFolder(bool defaultEnableTailMerge, bool CommonHoist, const MachineBlockFrequencyInfo &FreqInfo, const MachineBranchProbabilityInfo &ProbInfo) : EnableHoistCommonCode(CommonHoist), MBBFreqInfo(FreqInfo), MBPI(ProbInfo) { switch (FlagEnableTailMerge) { case cl::BOU_UNSET: EnableTailMerge = defaultEnableTailMerge; break; case cl::BOU_TRUE: EnableTailMerge = true; break; case cl::BOU_FALSE: EnableTailMerge = false; break; } } /// RemoveDeadBlock - Remove the specified dead machine basic block from the /// function, updating the CFG. void BranchFolder::RemoveDeadBlock(MachineBasicBlock *MBB) { assert(MBB->pred_empty() && "MBB must be dead!"); DEBUG(dbgs() << "\nRemoving MBB: " << *MBB); MachineFunction *MF = MBB->getParent(); // drop all successors. while (!MBB->succ_empty()) MBB->removeSuccessor(MBB->succ_end()-1); // Avoid matching if this pointer gets reused. TriedMerging.erase(MBB); // Remove the block. MF->erase(MBB); } /// OptimizeImpDefsBlock - If a basic block is just a bunch of implicit_def /// followed by terminators, and if the implicitly defined registers are not /// used by the terminators, remove those implicit_def's. e.g. /// BB1: /// r0 = implicit_def /// r1 = implicit_def /// br /// This block can be optimized away later if the implicit instructions are /// removed. bool BranchFolder::OptimizeImpDefsBlock(MachineBasicBlock *MBB) { SmallSet<unsigned, 4> ImpDefRegs; MachineBasicBlock::iterator I = MBB->begin(); while (I != MBB->end()) { if (!I->isImplicitDef()) break; unsigned Reg = I->getOperand(0).getReg(); for (MCSubRegIterator SubRegs(Reg, TRI, /*IncludeSelf=*/true); SubRegs.isValid(); ++SubRegs) ImpDefRegs.insert(*SubRegs); ++I; } if (ImpDefRegs.empty()) return false; MachineBasicBlock::iterator FirstTerm = I; while (I != MBB->end()) { if (!TII->isUnpredicatedTerminator(I)) return false; // See if it uses any of the implicitly defined registers. for (unsigned i = 0, e = I->getNumOperands(); i != e; ++i) { MachineOperand &MO = I->getOperand(i); if (!MO.isReg() || !MO.isUse()) continue; unsigned Reg = MO.getReg(); if (ImpDefRegs.count(Reg)) return false; } ++I; } I = MBB->begin(); while (I != FirstTerm) { MachineInstr *ImpDefMI = &*I; ++I; MBB->erase(ImpDefMI); } return true; } /// OptimizeFunction - Perhaps branch folding, tail merging and other /// CFG optimizations on the given function. bool BranchFolder::OptimizeFunction(MachineFunction &MF, const TargetInstrInfo *tii, const TargetRegisterInfo *tri, MachineModuleInfo *mmi) { if (!tii) return false; TriedMerging.clear(); TII = tii; TRI = tri; MMI = mmi; RS = nullptr; // Use a RegScavenger to help update liveness when required. MachineRegisterInfo &MRI = MF.getRegInfo(); if (MRI.tracksLiveness() && TRI->trackLivenessAfterRegAlloc(MF)) RS = new RegScavenger(); else MRI.invalidateLiveness(); // Fix CFG. The later algorithms expect it to be right. bool MadeChange = false; for (MachineFunction::iterator I = MF.begin(), E = MF.end(); I != E; I++) { MachineBasicBlock *MBB = I, *TBB = nullptr, *FBB = nullptr; SmallVector<MachineOperand, 4> Cond; if (!TII->AnalyzeBranch(*MBB, TBB, FBB, Cond, true)) MadeChange |= MBB->CorrectExtraCFGEdges(TBB, FBB, !Cond.empty()); MadeChange |= OptimizeImpDefsBlock(MBB); } bool MadeChangeThisIteration = true; while (MadeChangeThisIteration) { MadeChangeThisIteration = TailMergeBlocks(MF); MadeChangeThisIteration |= OptimizeBranches(MF); if (EnableHoistCommonCode) MadeChangeThisIteration |= HoistCommonCode(MF); MadeChange |= MadeChangeThisIteration; } // See if any jump tables have become dead as the code generator // did its thing. MachineJumpTableInfo *JTI = MF.getJumpTableInfo(); if (!JTI) { delete RS; return MadeChange; } // Walk the function to find jump tables that are live. BitVector JTIsLive(JTI->getJumpTables().size()); for (MachineFunction::iterator BB = MF.begin(), E = MF.end(); BB != E; ++BB) { for (MachineBasicBlock::iterator I = BB->begin(), E = BB->end(); I != E; ++I) for (unsigned op = 0, e = I->getNumOperands(); op != e; ++op) { MachineOperand &Op = I->getOperand(op); if (!Op.isJTI()) continue; // Remember that this JT is live. JTIsLive.set(Op.getIndex()); } } // Finally, remove dead jump tables. This happens when the // indirect jump was unreachable (and thus deleted). for (unsigned i = 0, e = JTIsLive.size(); i != e; ++i) if (!JTIsLive.test(i)) { JTI->RemoveJumpTable(i); MadeChange = true; } delete RS; return MadeChange; } //===----------------------------------------------------------------------===// // Tail Merging of Blocks //===----------------------------------------------------------------------===// /// HashMachineInstr - Compute a hash value for MI and its operands. static unsigned HashMachineInstr(const MachineInstr *MI) { unsigned Hash = MI->getOpcode(); for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) { const MachineOperand &Op = MI->getOperand(i); // Merge in bits from the operand if easy. We can't use MachineOperand's // hash_code here because it's not deterministic and we sort by hash value // later. unsigned OperandHash = 0; switch (Op.getType()) { case MachineOperand::MO_Register: OperandHash = Op.getReg(); break; case MachineOperand::MO_Immediate: OperandHash = Op.getImm(); break; case MachineOperand::MO_MachineBasicBlock: OperandHash = Op.getMBB()->getNumber(); break; case MachineOperand::MO_FrameIndex: case MachineOperand::MO_ConstantPoolIndex: case MachineOperand::MO_JumpTableIndex: OperandHash = Op.getIndex(); break; case MachineOperand::MO_GlobalAddress: case MachineOperand::MO_ExternalSymbol: // Global address / external symbol are too hard, don't bother, but do // pull in the offset. OperandHash = Op.getOffset(); break; default: break; } Hash += ((OperandHash << 3) | Op.getType()) << (i & 31); } return Hash; } /// HashEndOfMBB - Hash the last instruction in the MBB. static unsigned HashEndOfMBB(const MachineBasicBlock *MBB) { MachineBasicBlock::const_iterator I = MBB->getLastNonDebugInstr(); if (I == MBB->end()) return 0; return HashMachineInstr(I); } /// ComputeCommonTailLength - Given two machine basic blocks, compute the number /// of instructions they actually have in common together at their end. Return /// iterators for the first shared instruction in each block. static unsigned ComputeCommonTailLength(MachineBasicBlock *MBB1, MachineBasicBlock *MBB2, MachineBasicBlock::iterator &I1, MachineBasicBlock::iterator &I2) { I1 = MBB1->end(); I2 = MBB2->end(); unsigned TailLen = 0; while (I1 != MBB1->begin() && I2 != MBB2->begin()) { --I1; --I2; // Skip debugging pseudos; necessary to avoid changing the code. while (I1->isDebugValue()) { if (I1==MBB1->begin()) { while (I2->isDebugValue()) { if (I2==MBB2->begin()) // I1==DBG at begin; I2==DBG at begin return TailLen; --I2; } ++I2; // I1==DBG at begin; I2==non-DBG, or first of DBGs not at begin return TailLen; } --I1; } // I1==first (untested) non-DBG preceding known match while (I2->isDebugValue()) { if (I2==MBB2->begin()) { ++I1; // I1==non-DBG, or first of DBGs not at begin; I2==DBG at begin return TailLen; } --I2; } // I1, I2==first (untested) non-DBGs preceding known match if (!I1->isIdenticalTo(I2) || // FIXME: This check is dubious. It's used to get around a problem where // people incorrectly expect inline asm directives to remain in the same // relative order. This is untenable because normal compiler // optimizations (like this one) may reorder and/or merge these // directives. I1->isInlineAsm()) { ++I1; ++I2; break; } ++TailLen; } // Back past possible debugging pseudos at beginning of block. This matters // when one block differs from the other only by whether debugging pseudos // are present at the beginning. (This way, the various checks later for // I1==MBB1->begin() work as expected.) if (I1 == MBB1->begin() && I2 != MBB2->begin()) { --I2; while (I2->isDebugValue()) { if (I2 == MBB2->begin()) return TailLen; --I2; } ++I2; } if (I2 == MBB2->begin() && I1 != MBB1->begin()) { --I1; while (I1->isDebugValue()) { if (I1 == MBB1->begin()) return TailLen; --I1; } ++I1; } return TailLen; } void BranchFolder::MaintainLiveIns(MachineBasicBlock *CurMBB, MachineBasicBlock *NewMBB) { if (RS) { RS->enterBasicBlock(CurMBB); if (!CurMBB->empty()) RS->forward(std::prev(CurMBB->end())); for (unsigned int i = 1, e = TRI->getNumRegs(); i != e; i++) if (RS->isRegUsed(i, false)) NewMBB->addLiveIn(i); } } /// ReplaceTailWithBranchTo - Delete the instruction OldInst and everything /// after it, replacing it with an unconditional branch to NewDest. void BranchFolder::ReplaceTailWithBranchTo(MachineBasicBlock::iterator OldInst, MachineBasicBlock *NewDest) { MachineBasicBlock *CurMBB = OldInst->getParent(); TII->ReplaceTailWithBranchTo(OldInst, NewDest); // For targets that use the register scavenger, we must maintain LiveIns. MaintainLiveIns(CurMBB, NewDest); ++NumTailMerge; } /// SplitMBBAt - Given a machine basic block and an iterator into it, split the /// MBB so that the part before the iterator falls into the part starting at the /// iterator. This returns the new MBB. MachineBasicBlock *BranchFolder::SplitMBBAt(MachineBasicBlock &CurMBB, MachineBasicBlock::iterator BBI1, const BasicBlock *BB) { if (!TII->isLegalToSplitMBBAt(CurMBB, BBI1)) return nullptr; MachineFunction &MF = *CurMBB.getParent(); // Create the fall-through block. MachineFunction::iterator MBBI = &CurMBB; MachineBasicBlock *NewMBB =MF.CreateMachineBasicBlock(BB); CurMBB.getParent()->insert(++MBBI, NewMBB); // Move all the successors of this block to the specified block. NewMBB->transferSuccessors(&CurMBB); // Add an edge from CurMBB to NewMBB for the fall-through. CurMBB.addSuccessor(NewMBB); // Splice the code over. NewMBB->splice(NewMBB->end(), &CurMBB, BBI1, CurMBB.end()); // NewMBB inherits CurMBB's block frequency. MBBFreqInfo.setBlockFreq(NewMBB, MBBFreqInfo.getBlockFreq(&CurMBB)); // For targets that use the register scavenger, we must maintain LiveIns. MaintainLiveIns(&CurMBB, NewMBB); return NewMBB; } /// EstimateRuntime - Make a rough estimate for how long it will take to run /// the specified code. static unsigned EstimateRuntime(MachineBasicBlock::iterator I, MachineBasicBlock::iterator E) { unsigned Time = 0; for (; I != E; ++I) { if (I->isDebugValue()) continue; if (I->isCall()) Time += 10; else if (I->mayLoad() || I->mayStore()) Time += 2; else ++Time; } return Time; } // CurMBB needs to add an unconditional branch to SuccMBB (we removed these // branches temporarily for tail merging). In the case where CurMBB ends // with a conditional branch to the next block, optimize by reversing the // test and conditionally branching to SuccMBB instead. static void FixTail(MachineBasicBlock *CurMBB, MachineBasicBlock *SuccBB, const TargetInstrInfo *TII) { MachineFunction *MF = CurMBB->getParent(); MachineFunction::iterator I = std::next(MachineFunction::iterator(CurMBB)); MachineBasicBlock *TBB = nullptr, *FBB = nullptr; SmallVector<MachineOperand, 4> Cond; DebugLoc dl; // FIXME: this is nowhere if (I != MF->end() && !TII->AnalyzeBranch(*CurMBB, TBB, FBB, Cond, true)) { MachineBasicBlock *NextBB = I; if (TBB == NextBB && !Cond.empty() && !FBB) { if (!TII->ReverseBranchCondition(Cond)) { TII->RemoveBranch(*CurMBB); TII->InsertBranch(*CurMBB, SuccBB, nullptr, Cond, dl); return; } } } TII->InsertBranch(*CurMBB, SuccBB, nullptr, SmallVector<MachineOperand, 0>(), dl); } bool BranchFolder::MergePotentialsElt::operator<(const MergePotentialsElt &o) const { if (getHash() < o.getHash()) return true; if (getHash() > o.getHash()) return false; if (getBlock()->getNumber() < o.getBlock()->getNumber()) return true; if (getBlock()->getNumber() > o.getBlock()->getNumber()) return false; // _GLIBCXX_DEBUG checks strict weak ordering, which involves comparing // an object with itself. #ifndef _GLIBCXX_DEBUG llvm_unreachable("Predecessor appears twice"); #else return false; #endif } BlockFrequency BranchFolder::MBFIWrapper::getBlockFreq(const MachineBasicBlock *MBB) const { auto I = MergedBBFreq.find(MBB); if (I != MergedBBFreq.end()) return I->second; return MBFI.getBlockFreq(MBB); } void BranchFolder::MBFIWrapper::setBlockFreq(const MachineBasicBlock *MBB, BlockFrequency F) { MergedBBFreq[MBB] = F; } /// CountTerminators - Count the number of terminators in the given /// block and set I to the position of the first non-terminator, if there /// is one, or MBB->end() otherwise. static unsigned CountTerminators(MachineBasicBlock *MBB, MachineBasicBlock::iterator &I) { I = MBB->end(); unsigned NumTerms = 0; for (;;) { if (I == MBB->begin()) { I = MBB->end(); break; } --I; if (!I->isTerminator()) break; ++NumTerms; } return NumTerms; } /// ProfitableToMerge - Check if two machine basic blocks have a common tail /// and decide if it would be profitable to merge those tails. Return the /// length of the common tail and iterators to the first common instruction /// in each block. static bool ProfitableToMerge(MachineBasicBlock *MBB1, MachineBasicBlock *MBB2, unsigned minCommonTailLength, unsigned &CommonTailLen, MachineBasicBlock::iterator &I1, MachineBasicBlock::iterator &I2, MachineBasicBlock *SuccBB, MachineBasicBlock *PredBB) { CommonTailLen = ComputeCommonTailLength(MBB1, MBB2, I1, I2); if (CommonTailLen == 0) return false; DEBUG(dbgs() << "Common tail length of BB#" << MBB1->getNumber() << " and BB#" << MBB2->getNumber() << " is " << CommonTailLen << '\n'); // It's almost always profitable to merge any number of non-terminator // instructions with the block that falls through into the common successor. if (MBB1 == PredBB || MBB2 == PredBB) { MachineBasicBlock::iterator I; unsigned NumTerms = CountTerminators(MBB1 == PredBB ? MBB2 : MBB1, I); if (CommonTailLen > NumTerms) return true; } // If one of the blocks can be completely merged and happens to be in // a position where the other could fall through into it, merge any number // of instructions, because it can be done without a branch. // TODO: If the blocks are not adjacent, move one of them so that they are? if (MBB1->isLayoutSuccessor(MBB2) && I2 == MBB2->begin()) return true; if (MBB2->isLayoutSuccessor(MBB1) && I1 == MBB1->begin()) return true; // If both blocks have an unconditional branch temporarily stripped out, // count that as an additional common instruction for the following // heuristics. unsigned EffectiveTailLen = CommonTailLen; if (SuccBB && MBB1 != PredBB && MBB2 != PredBB && !MBB1->back().isBarrier() && !MBB2->back().isBarrier()) ++EffectiveTailLen; // Check if the common tail is long enough to be worthwhile. if (EffectiveTailLen >= minCommonTailLength) return true; // If we are optimizing for code size, 2 instructions in common is enough if // we don't have to split a block. At worst we will be introducing 1 new // branch instruction, which is likely to be smaller than the 2 // instructions that would be deleted in the merge. MachineFunction *MF = MBB1->getParent(); if (EffectiveTailLen >= 2 && MF->getFunction()->hasFnAttribute(Attribute::OptimizeForSize) && (I1 == MBB1->begin() || I2 == MBB2->begin())) return true; return false; } /// ComputeSameTails - Look through all the blocks in MergePotentials that have /// hash CurHash (guaranteed to match the last element). Build the vector /// SameTails of all those that have the (same) largest number of instructions /// in common of any pair of these blocks. SameTails entries contain an /// iterator into MergePotentials (from which the MachineBasicBlock can be /// found) and a MachineBasicBlock::iterator into that MBB indicating the /// instruction where the matching code sequence begins. /// Order of elements in SameTails is the reverse of the order in which /// those blocks appear in MergePotentials (where they are not necessarily /// consecutive). unsigned BranchFolder::ComputeSameTails(unsigned CurHash, unsigned minCommonTailLength, MachineBasicBlock *SuccBB, MachineBasicBlock *PredBB) { unsigned maxCommonTailLength = 0U; SameTails.clear(); MachineBasicBlock::iterator TrialBBI1, TrialBBI2; MPIterator HighestMPIter = std::prev(MergePotentials.end()); for (MPIterator CurMPIter = std::prev(MergePotentials.end()), B = MergePotentials.begin(); CurMPIter != B && CurMPIter->getHash() == CurHash; --CurMPIter) { for (MPIterator I = std::prev(CurMPIter); I->getHash() == CurHash; --I) { unsigned CommonTailLen; if (ProfitableToMerge(CurMPIter->getBlock(), I->getBlock(), minCommonTailLength, CommonTailLen, TrialBBI1, TrialBBI2, SuccBB, PredBB)) { if (CommonTailLen > maxCommonTailLength) { SameTails.clear(); maxCommonTailLength = CommonTailLen; HighestMPIter = CurMPIter; SameTails.push_back(SameTailElt(CurMPIter, TrialBBI1)); } if (HighestMPIter == CurMPIter && CommonTailLen == maxCommonTailLength) SameTails.push_back(SameTailElt(I, TrialBBI2)); } if (I == B) break; } } return maxCommonTailLength; } /// RemoveBlocksWithHash - Remove all blocks with hash CurHash from /// MergePotentials, restoring branches at ends of blocks as appropriate. void BranchFolder::RemoveBlocksWithHash(unsigned CurHash, MachineBasicBlock *SuccBB, MachineBasicBlock *PredBB) { MPIterator CurMPIter, B; for (CurMPIter = std::prev(MergePotentials.end()), B = MergePotentials.begin(); CurMPIter->getHash() == CurHash; --CurMPIter) { // Put the unconditional branch back, if we need one. MachineBasicBlock *CurMBB = CurMPIter->getBlock(); if (SuccBB && CurMBB != PredBB) FixTail(CurMBB, SuccBB, TII); if (CurMPIter == B) break; } if (CurMPIter->getHash() != CurHash) CurMPIter++; MergePotentials.erase(CurMPIter, MergePotentials.end()); } /// CreateCommonTailOnlyBlock - None of the blocks to be tail-merged consist /// only of the common tail. Create a block that does by splitting one. bool BranchFolder::CreateCommonTailOnlyBlock(MachineBasicBlock *&PredBB, MachineBasicBlock *SuccBB, unsigned maxCommonTailLength, unsigned &commonTailIndex) { commonTailIndex = 0; unsigned TimeEstimate = ~0U; for (unsigned i = 0, e = SameTails.size(); i != e; ++i) { // Use PredBB if possible; that doesn't require a new branch. if (SameTails[i].getBlock() == PredBB) { commonTailIndex = i; break; } // Otherwise, make a (fairly bogus) choice based on estimate of // how long it will take the various blocks to execute. unsigned t = EstimateRuntime(SameTails[i].getBlock()->begin(), SameTails[i].getTailStartPos()); if (t <= TimeEstimate) { TimeEstimate = t; commonTailIndex = i; } } MachineBasicBlock::iterator BBI = SameTails[commonTailIndex].getTailStartPos(); MachineBasicBlock *MBB = SameTails[commonTailIndex].getBlock(); // If the common tail includes any debug info we will take it pretty // randomly from one of the inputs. Might be better to remove it? DEBUG(dbgs() << "\nSplitting BB#" << MBB->getNumber() << ", size " << maxCommonTailLength); // If the split block unconditionally falls-thru to SuccBB, it will be // merged. In control flow terms it should then take SuccBB's name. e.g. If // SuccBB is an inner loop, the common tail is still part of the inner loop. const BasicBlock *BB = (SuccBB && MBB->succ_size() == 1) ? SuccBB->getBasicBlock() : MBB->getBasicBlock(); MachineBasicBlock *newMBB = SplitMBBAt(*MBB, BBI, BB); if (!newMBB) { DEBUG(dbgs() << "... failed!"); return false; } SameTails[commonTailIndex].setBlock(newMBB); SameTails[commonTailIndex].setTailStartPos(newMBB->begin()); // If we split PredBB, newMBB is the new predecessor. if (PredBB == MBB) PredBB = newMBB; return true; } static bool hasIdenticalMMOs(const MachineInstr *MI1, const MachineInstr *MI2) { auto I1 = MI1->memoperands_begin(), E1 = MI1->memoperands_end(); auto I2 = MI2->memoperands_begin(), E2 = MI2->memoperands_end(); if ((E1 - I1) != (E2 - I2)) return false; for (; I1 != E1; ++I1, ++I2) { if (**I1 != **I2) return false; } return true; } static void removeMMOsFromMemoryOperations(MachineBasicBlock::iterator MBBIStartPos, MachineBasicBlock &MBBCommon) { // Remove MMOs from memory operations in the common block // when they do not match the ones from the block being tail-merged. // This ensures later passes conservatively compute dependencies. MachineBasicBlock *MBB = MBBIStartPos->getParent(); // Note CommonTailLen does not necessarily matches the size of // the common BB nor all its instructions because of debug // instructions differences. unsigned CommonTailLen = 0; for (auto E = MBB->end(); MBBIStartPos != E; ++MBBIStartPos) ++CommonTailLen; MachineBasicBlock::reverse_iterator MBBI = MBB->rbegin(); MachineBasicBlock::reverse_iterator MBBIE = MBB->rend(); MachineBasicBlock::reverse_iterator MBBICommon = MBBCommon.rbegin(); MachineBasicBlock::reverse_iterator MBBIECommon = MBBCommon.rend(); while (CommonTailLen--) { assert(MBBI != MBBIE && "Reached BB end within common tail length!"); (void)MBBIE; if (MBBI->isDebugValue()) { ++MBBI; continue; } while ((MBBICommon != MBBIECommon) && MBBICommon->isDebugValue()) ++MBBICommon; assert(MBBICommon != MBBIECommon && "Reached BB end within common tail length!"); assert(MBBICommon->isIdenticalTo(&*MBBI) && "Expected matching MIIs!"); if (MBBICommon->mayLoad() || MBBICommon->mayStore()) if (!hasIdenticalMMOs(&*MBBI, &*MBBICommon)) MBBICommon->clearMemRefs(); ++MBBI; ++MBBICommon; } } // See if any of the blocks in MergePotentials (which all have a common single // successor, or all have no successor) can be tail-merged. If there is a // successor, any blocks in MergePotentials that are not tail-merged and // are not immediately before Succ must have an unconditional branch to // Succ added (but the predecessor/successor lists need no adjustment). // The lone predecessor of Succ that falls through into Succ, // if any, is given in PredBB. bool BranchFolder::TryTailMergeBlocks(MachineBasicBlock *SuccBB, MachineBasicBlock *PredBB) { bool MadeChange = false; // Except for the special cases below, tail-merge if there are at least // this many instructions in common. unsigned minCommonTailLength = TailMergeSize; DEBUG(dbgs() << "\nTryTailMergeBlocks: "; for (unsigned i = 0, e = MergePotentials.size(); i != e; ++i) dbgs() << "BB#" << MergePotentials[i].getBlock()->getNumber() << (i == e-1 ? "" : ", "); dbgs() << "\n"; if (SuccBB) { dbgs() << " with successor BB#" << SuccBB->getNumber() << '\n'; if (PredBB) dbgs() << " which has fall-through from BB#" << PredBB->getNumber() << "\n"; } dbgs() << "Looking for common tails of at least " << minCommonTailLength << " instruction" << (minCommonTailLength == 1 ? "" : "s") << '\n'; ); // Sort by hash value so that blocks with identical end sequences sort // together. array_pod_sort(MergePotentials.begin(), MergePotentials.end()); // Walk through equivalence sets looking for actual exact matches. while (MergePotentials.size() > 1) { unsigned CurHash = MergePotentials.back().getHash(); // Build SameTails, identifying the set of blocks with this hash code // and with the maximum number of instructions in common. unsigned maxCommonTailLength = ComputeSameTails(CurHash, minCommonTailLength, SuccBB, PredBB); // If we didn't find any pair that has at least minCommonTailLength // instructions in common, remove all blocks with this hash code and retry. if (SameTails.empty()) { RemoveBlocksWithHash(CurHash, SuccBB, PredBB); continue; } // If one of the blocks is the entire common tail (and not the entry // block, which we can't jump to), we can treat all blocks with this same // tail at once. Use PredBB if that is one of the possibilities, as that // will not introduce any extra branches. MachineBasicBlock *EntryBB = MergePotentials.begin()->getBlock()-> getParent()->begin(); unsigned commonTailIndex = SameTails.size(); // If there are two blocks, check to see if one can be made to fall through // into the other. if (SameTails.size() == 2 && SameTails[0].getBlock()->isLayoutSuccessor(SameTails[1].getBlock()) && SameTails[1].tailIsWholeBlock()) commonTailIndex = 1; else if (SameTails.size() == 2 && SameTails[1].getBlock()->isLayoutSuccessor( SameTails[0].getBlock()) && SameTails[0].tailIsWholeBlock()) commonTailIndex = 0; else { // Otherwise just pick one, favoring the fall-through predecessor if // there is one. for (unsigned i = 0, e = SameTails.size(); i != e; ++i) { MachineBasicBlock *MBB = SameTails[i].getBlock(); if (MBB == EntryBB && SameTails[i].tailIsWholeBlock()) continue; if (MBB == PredBB) { commonTailIndex = i; break; } if (SameTails[i].tailIsWholeBlock()) commonTailIndex = i; } } if (commonTailIndex == SameTails.size() || (SameTails[commonTailIndex].getBlock() == PredBB && !SameTails[commonTailIndex].tailIsWholeBlock())) { // None of the blocks consist entirely of the common tail. // Split a block so that one does. if (!CreateCommonTailOnlyBlock(PredBB, SuccBB, maxCommonTailLength, commonTailIndex)) { RemoveBlocksWithHash(CurHash, SuccBB, PredBB); continue; } } MachineBasicBlock *MBB = SameTails[commonTailIndex].getBlock(); // Recompute commont tail MBB's edge weights and block frequency. setCommonTailEdgeWeights(*MBB); // MBB is common tail. Adjust all other BB's to jump to this one. // Traversal must be forwards so erases work. DEBUG(dbgs() << "\nUsing common tail in BB#" << MBB->getNumber() << " for "); for (unsigned int i=0, e = SameTails.size(); i != e; ++i) { if (commonTailIndex == i) continue; DEBUG(dbgs() << "BB#" << SameTails[i].getBlock()->getNumber() << (i == e-1 ? "" : ", ")); // Remove MMOs from memory operations as needed. removeMMOsFromMemoryOperations(SameTails[i].getTailStartPos(), *MBB); // Hack the end off BB i, making it jump to BB commonTailIndex instead. ReplaceTailWithBranchTo(SameTails[i].getTailStartPos(), MBB); // BB i is no longer a predecessor of SuccBB; remove it from the worklist. MergePotentials.erase(SameTails[i].getMPIter()); } DEBUG(dbgs() << "\n"); // We leave commonTailIndex in the worklist in case there are other blocks // that match it with a smaller number of instructions. MadeChange = true; } return MadeChange; } bool BranchFolder::TailMergeBlocks(MachineFunction &MF) { bool MadeChange = false; if (!EnableTailMerge) return MadeChange; // First find blocks with no successors. MergePotentials.clear(); for (MachineFunction::iterator I = MF.begin(), E = MF.end(); I != E && MergePotentials.size() < TailMergeThreshold; ++I) { if (TriedMerging.count(I)) continue; if (I->succ_empty()) MergePotentials.push_back(MergePotentialsElt(HashEndOfMBB(I), I)); } // If this is a large problem, avoid visiting the same basic blocks // multiple times. if (MergePotentials.size() == TailMergeThreshold) for (unsigned i = 0, e = MergePotentials.size(); i != e; ++i) TriedMerging.insert(MergePotentials[i].getBlock()); // See if we can do any tail merging on those. if (MergePotentials.size() >= 2) MadeChange |= TryTailMergeBlocks(nullptr, nullptr); // Look at blocks (IBB) with multiple predecessors (PBB). // We change each predecessor to a canonical form, by // (1) temporarily removing any unconditional branch from the predecessor // to IBB, and // (2) alter conditional branches so they branch to the other block // not IBB; this may require adding back an unconditional branch to IBB // later, where there wasn't one coming in. E.g. // Bcc IBB // fallthrough to QBB // here becomes // Bncc QBB // with a conceptual B to IBB after that, which never actually exists. // With those changes, we see whether the predecessors' tails match, // and merge them if so. We change things out of canonical form and // back to the way they were later in the process. (OptimizeBranches // would undo some of this, but we can't use it, because we'd get into // a compile-time infinite loop repeatedly doing and undoing the same // transformations.) for (MachineFunction::iterator I = std::next(MF.begin()), E = MF.end(); I != E; ++I) { if (I->pred_size() < 2) continue; SmallPtrSet<MachineBasicBlock *, 8> UniquePreds; MachineBasicBlock *IBB = I; MachineBasicBlock *PredBB = std::prev(I); MergePotentials.clear(); for (MachineBasicBlock::pred_iterator P = I->pred_begin(), E2 = I->pred_end(); P != E2 && MergePotentials.size() < TailMergeThreshold; ++P) { MachineBasicBlock *PBB = *P; if (TriedMerging.count(PBB)) continue; // Skip blocks that loop to themselves, can't tail merge these. if (PBB == IBB) continue; // Visit each predecessor only once. if (!UniquePreds.insert(PBB).second) continue; // Skip blocks which may jump to a landing pad. Can't tail merge these. if (PBB->getLandingPadSuccessor()) continue; MachineBasicBlock *TBB = nullptr, *FBB = nullptr; SmallVector<MachineOperand, 4> Cond; if (!TII->AnalyzeBranch(*PBB, TBB, FBB, Cond, true)) { // Failing case: IBB is the target of a cbr, and we cannot reverse the // branch. SmallVector<MachineOperand, 4> NewCond(Cond); if (!Cond.empty() && TBB == IBB) { if (TII->ReverseBranchCondition(NewCond)) continue; // This is the QBB case described above if (!FBB) FBB = std::next(MachineFunction::iterator(PBB)); } // Failing case: the only way IBB can be reached from PBB is via // exception handling. Happens for landing pads. Would be nice to have // a bit in the edge so we didn't have to do all this. if (IBB->isLandingPad()) { MachineFunction::iterator IP = PBB; IP++; MachineBasicBlock *PredNextBB = nullptr; if (IP != MF.end()) PredNextBB = IP; if (!TBB) { if (IBB != PredNextBB) // fallthrough continue; } else if (FBB) { if (TBB != IBB && FBB != IBB) // cbr then ubr continue; } else if (Cond.empty()) { if (TBB != IBB) // ubr continue; } else { if (TBB != IBB && IBB != PredNextBB) // cbr continue; } } // Remove the unconditional branch at the end, if any. if (TBB && (Cond.empty() || FBB)) { DebugLoc dl; // FIXME: this is nowhere TII->RemoveBranch(*PBB); if (!Cond.empty()) // reinsert conditional branch only, for now TII->InsertBranch(*PBB, (TBB == IBB) ? FBB : TBB, nullptr, NewCond, dl); } MergePotentials.push_back(MergePotentialsElt(HashEndOfMBB(PBB), *P)); } } // If this is a large problem, avoid visiting the same basic blocks multiple // times. if (MergePotentials.size() == TailMergeThreshold) for (unsigned i = 0, e = MergePotentials.size(); i != e; ++i) TriedMerging.insert(MergePotentials[i].getBlock()); if (MergePotentials.size() >= 2) MadeChange |= TryTailMergeBlocks(IBB, PredBB); // Reinsert an unconditional branch if needed. The 1 below can occur as a // result of removing blocks in TryTailMergeBlocks. PredBB = std::prev(I); // this may have been changed in TryTailMergeBlocks if (MergePotentials.size() == 1 && MergePotentials.begin()->getBlock() != PredBB) FixTail(MergePotentials.begin()->getBlock(), IBB, TII); } return MadeChange; } void BranchFolder::setCommonTailEdgeWeights(MachineBasicBlock &TailMBB) { SmallVector<BlockFrequency, 2> EdgeFreqLs(TailMBB.succ_size()); BlockFrequency AccumulatedMBBFreq; // Aggregate edge frequency of successor edge j: // edgeFreq(j) = sum (freq(bb) * edgeProb(bb, j)), // where bb is a basic block that is in SameTails. for (const auto &Src : SameTails) { const MachineBasicBlock *SrcMBB = Src.getBlock(); BlockFrequency BlockFreq = MBBFreqInfo.getBlockFreq(SrcMBB); AccumulatedMBBFreq += BlockFreq; // It is not necessary to recompute edge weights if TailBB has less than two // successors. if (TailMBB.succ_size() <= 1) continue; auto EdgeFreq = EdgeFreqLs.begin(); for (auto SuccI = TailMBB.succ_begin(), SuccE = TailMBB.succ_end(); SuccI != SuccE; ++SuccI, ++EdgeFreq) *EdgeFreq += BlockFreq * MBPI.getEdgeProbability(SrcMBB, *SuccI); } MBBFreqInfo.setBlockFreq(&TailMBB, AccumulatedMBBFreq); if (TailMBB.succ_size() <= 1) return; auto MaxEdgeFreq = *std::max_element(EdgeFreqLs.begin(), EdgeFreqLs.end()); uint64_t Scale = MaxEdgeFreq.getFrequency() / UINT32_MAX + 1; auto EdgeFreq = EdgeFreqLs.begin(); for (auto SuccI = TailMBB.succ_begin(), SuccE = TailMBB.succ_end(); SuccI != SuccE; ++SuccI, ++EdgeFreq) TailMBB.setSuccWeight(SuccI, EdgeFreq->getFrequency() / Scale); } //===----------------------------------------------------------------------===// // Branch Optimization //===----------------------------------------------------------------------===// bool BranchFolder::OptimizeBranches(MachineFunction &MF) { bool MadeChange = false; // Make sure blocks are numbered in order MF.RenumberBlocks(); for (MachineFunction::iterator I = std::next(MF.begin()), E = MF.end(); I != E; ) { MachineBasicBlock *MBB = I++; MadeChange |= OptimizeBlock(MBB); // If it is dead, remove it. if (MBB->pred_empty()) { RemoveDeadBlock(MBB); MadeChange = true; ++NumDeadBlocks; } } return MadeChange; } // Blocks should be considered empty if they contain only debug info; // else the debug info would affect codegen. static bool IsEmptyBlock(MachineBasicBlock *MBB) { return MBB->getFirstNonDebugInstr() == MBB->end(); } // Blocks with only debug info and branches should be considered the same // as blocks with only branches. static bool IsBranchOnlyBlock(MachineBasicBlock *MBB) { MachineBasicBlock::iterator I = MBB->getFirstNonDebugInstr(); assert(I != MBB->end() && "empty block!"); return I->isBranch(); } /// IsBetterFallthrough - Return true if it would be clearly better to /// fall-through to MBB1 than to fall through into MBB2. This has to return /// a strict ordering, returning true for both (MBB1,MBB2) and (MBB2,MBB1) will /// result in infinite loops. static bool IsBetterFallthrough(MachineBasicBlock *MBB1, MachineBasicBlock *MBB2) { // Right now, we use a simple heuristic. If MBB2 ends with a call, and // MBB1 doesn't, we prefer to fall through into MBB1. This allows us to // optimize branches that branch to either a return block or an assert block // into a fallthrough to the return. MachineBasicBlock::iterator MBB1I = MBB1->getLastNonDebugInstr(); MachineBasicBlock::iterator MBB2I = MBB2->getLastNonDebugInstr(); if (MBB1I == MBB1->end() || MBB2I == MBB2->end()) return false; // If there is a clear successor ordering we make sure that one block // will fall through to the next if (MBB1->isSuccessor(MBB2)) return true; if (MBB2->isSuccessor(MBB1)) return false; return MBB2I->isCall() && !MBB1I->isCall(); } /// getBranchDebugLoc - Find and return, if any, the DebugLoc of the branch /// instructions on the block. static DebugLoc getBranchDebugLoc(MachineBasicBlock &MBB) { MachineBasicBlock::iterator I = MBB.getLastNonDebugInstr(); if (I != MBB.end() && I->isBranch()) return I->getDebugLoc(); return DebugLoc(); } /// OptimizeBlock - Analyze and optimize control flow related to the specified /// block. This is never called on the entry block. bool BranchFolder::OptimizeBlock(MachineBasicBlock *MBB) { bool MadeChange = false; MachineFunction &MF = *MBB->getParent(); ReoptimizeBlock: MachineFunction::iterator FallThrough = MBB; ++FallThrough; // If this block is empty, make everyone use its fall-through, not the block // explicitly. Landing pads should not do this since the landing-pad table // points to this block. Blocks with their addresses taken shouldn't be // optimized away. if (IsEmptyBlock(MBB) && !MBB->isLandingPad() && !MBB->hasAddressTaken()) { // Dead block? Leave for cleanup later. if (MBB->pred_empty()) return MadeChange; if (FallThrough == MF.end()) { // TODO: Simplify preds to not branch here if possible! } else if (FallThrough->isLandingPad()) { // Don't rewrite to a landing pad fallthough. That could lead to the case // where a BB jumps to more than one landing pad. // TODO: Is it ever worth rewriting predecessors which don't already // jump to a landing pad, and so can safely jump to the fallthrough? } else { // Rewrite all predecessors of the old block to go to the fallthrough // instead. while (!MBB->pred_empty()) { MachineBasicBlock *Pred = *(MBB->pred_end()-1); Pred->ReplaceUsesOfBlockWith(MBB, FallThrough); } // If MBB was the target of a jump table, update jump tables to go to the // fallthrough instead. if (MachineJumpTableInfo *MJTI = MF.getJumpTableInfo()) MJTI->ReplaceMBBInJumpTables(MBB, FallThrough); MadeChange = true; } return MadeChange; } // Check to see if we can simplify the terminator of the block before this // one. MachineBasicBlock &PrevBB = *std::prev(MachineFunction::iterator(MBB)); MachineBasicBlock *PriorTBB = nullptr, *PriorFBB = nullptr; SmallVector<MachineOperand, 4> PriorCond; bool PriorUnAnalyzable = TII->AnalyzeBranch(PrevBB, PriorTBB, PriorFBB, PriorCond, true); if (!PriorUnAnalyzable) { // If the CFG for the prior block has extra edges, remove them. MadeChange |= PrevBB.CorrectExtraCFGEdges(PriorTBB, PriorFBB, !PriorCond.empty()); // If the previous branch is conditional and both conditions go to the same // destination, remove the branch, replacing it with an unconditional one or // a fall-through. if (PriorTBB && PriorTBB == PriorFBB) { DebugLoc dl = getBranchDebugLoc(PrevBB); TII->RemoveBranch(PrevBB); PriorCond.clear(); if (PriorTBB != MBB) TII->InsertBranch(PrevBB, PriorTBB, nullptr, PriorCond, dl); MadeChange = true; ++NumBranchOpts; goto ReoptimizeBlock; } // If the previous block unconditionally falls through to this block and // this block has no other predecessors, move the contents of this block // into the prior block. This doesn't usually happen when SimplifyCFG // has been used, but it can happen if tail merging splits a fall-through // predecessor of a block. // This has to check PrevBB->succ_size() because EH edges are ignored by // AnalyzeBranch. if (PriorCond.empty() && !PriorTBB && MBB->pred_size() == 1 && PrevBB.succ_size() == 1 && !MBB->hasAddressTaken() && !MBB->isLandingPad()) { DEBUG(dbgs() << "\nMerging into block: " << PrevBB << "From MBB: " << *MBB); // Remove redundant DBG_VALUEs first. if (PrevBB.begin() != PrevBB.end()) { MachineBasicBlock::iterator PrevBBIter = PrevBB.end(); --PrevBBIter; MachineBasicBlock::iterator MBBIter = MBB->begin(); // Check if DBG_VALUE at the end of PrevBB is identical to the // DBG_VALUE at the beginning of MBB. while (PrevBBIter != PrevBB.begin() && MBBIter != MBB->end() && PrevBBIter->isDebugValue() && MBBIter->isDebugValue()) { if (!MBBIter->isIdenticalTo(PrevBBIter)) break; MachineInstr *DuplicateDbg = MBBIter; ++MBBIter; -- PrevBBIter; DuplicateDbg->eraseFromParent(); } } PrevBB.splice(PrevBB.end(), MBB, MBB->begin(), MBB->end()); PrevBB.removeSuccessor(PrevBB.succ_begin()); assert(PrevBB.succ_empty()); PrevBB.transferSuccessors(MBB); MadeChange = true; return MadeChange; } // If the previous branch *only* branches to *this* block (conditional or // not) remove the branch. if (PriorTBB == MBB && !PriorFBB) { TII->RemoveBranch(PrevBB); MadeChange = true; ++NumBranchOpts; goto ReoptimizeBlock; } // If the prior block branches somewhere else on the condition and here if // the condition is false, remove the uncond second branch. if (PriorFBB == MBB) { DebugLoc dl = getBranchDebugLoc(PrevBB); TII->RemoveBranch(PrevBB); TII->InsertBranch(PrevBB, PriorTBB, nullptr, PriorCond, dl); MadeChange = true; ++NumBranchOpts; goto ReoptimizeBlock; } // If the prior block branches here on true and somewhere else on false, and // if the branch condition is reversible, reverse the branch to create a // fall-through. if (PriorTBB == MBB) { SmallVector<MachineOperand, 4> NewPriorCond(PriorCond); if (!TII->ReverseBranchCondition(NewPriorCond)) { DebugLoc dl = getBranchDebugLoc(PrevBB); TII->RemoveBranch(PrevBB); TII->InsertBranch(PrevBB, PriorFBB, nullptr, NewPriorCond, dl); MadeChange = true; ++NumBranchOpts; goto ReoptimizeBlock; } } // If this block has no successors (e.g. it is a return block or ends with // a call to a no-return function like abort or __cxa_throw) and if the pred // falls through into this block, and if it would otherwise fall through // into the block after this, move this block to the end of the function. // // We consider it more likely that execution will stay in the function (e.g. // due to loops) than it is to exit it. This asserts in loops etc, moving // the assert condition out of the loop body. if (MBB->succ_empty() && !PriorCond.empty() && !PriorFBB && MachineFunction::iterator(PriorTBB) == FallThrough && !MBB->canFallThrough()) { bool DoTransform = true; // We have to be careful that the succs of PredBB aren't both no-successor // blocks. If neither have successors and if PredBB is the second from // last block in the function, we'd just keep swapping the two blocks for // last. Only do the swap if one is clearly better to fall through than // the other. if (FallThrough == --MF.end() && !IsBetterFallthrough(PriorTBB, MBB)) DoTransform = false; if (DoTransform) { // Reverse the branch so we will fall through on the previous true cond. SmallVector<MachineOperand, 4> NewPriorCond(PriorCond); if (!TII->ReverseBranchCondition(NewPriorCond)) { DEBUG(dbgs() << "\nMoving MBB: " << *MBB << "To make fallthrough to: " << *PriorTBB << "\n"); DebugLoc dl = getBranchDebugLoc(PrevBB); TII->RemoveBranch(PrevBB); TII->InsertBranch(PrevBB, MBB, nullptr, NewPriorCond, dl); // Move this block to the end of the function. MBB->moveAfter(--MF.end()); MadeChange = true; ++NumBranchOpts; return MadeChange; } } } } // Analyze the branch in the current block. MachineBasicBlock *CurTBB = nullptr, *CurFBB = nullptr; SmallVector<MachineOperand, 4> CurCond; bool CurUnAnalyzable= TII->AnalyzeBranch(*MBB, CurTBB, CurFBB, CurCond, true); if (!CurUnAnalyzable) { // If the CFG for the prior block has extra edges, remove them. MadeChange |= MBB->CorrectExtraCFGEdges(CurTBB, CurFBB, !CurCond.empty()); // If this is a two-way branch, and the FBB branches to this block, reverse // the condition so the single-basic-block loop is faster. Instead of: // Loop: xxx; jcc Out; jmp Loop // we want: // Loop: xxx; jncc Loop; jmp Out if (CurTBB && CurFBB && CurFBB == MBB && CurTBB != MBB) { SmallVector<MachineOperand, 4> NewCond(CurCond); if (!TII->ReverseBranchCondition(NewCond)) { DebugLoc dl = getBranchDebugLoc(*MBB); TII->RemoveBranch(*MBB); TII->InsertBranch(*MBB, CurFBB, CurTBB, NewCond, dl); MadeChange = true; ++NumBranchOpts; goto ReoptimizeBlock; } } // If this branch is the only thing in its block, see if we can forward // other blocks across it. if (CurTBB && CurCond.empty() && !CurFBB && IsBranchOnlyBlock(MBB) && CurTBB != MBB && !MBB->hasAddressTaken()) { DebugLoc dl = getBranchDebugLoc(*MBB); // This block may contain just an unconditional branch. Because there can // be 'non-branch terminators' in the block, try removing the branch and // then seeing if the block is empty. TII->RemoveBranch(*MBB); // If the only things remaining in the block are debug info, remove these // as well, so this will behave the same as an empty block in non-debug // mode. if (IsEmptyBlock(MBB)) { // Make the block empty, losing the debug info (we could probably // improve this in some cases.) MBB->erase(MBB->begin(), MBB->end()); } // If this block is just an unconditional branch to CurTBB, we can // usually completely eliminate the block. The only case we cannot // completely eliminate the block is when the block before this one // falls through into MBB and we can't understand the prior block's branch // condition. if (MBB->empty()) { bool PredHasNoFallThrough = !PrevBB.canFallThrough(); if (PredHasNoFallThrough || !PriorUnAnalyzable || !PrevBB.isSuccessor(MBB)) { // If the prior block falls through into us, turn it into an // explicit branch to us to make updates simpler. if (!PredHasNoFallThrough && PrevBB.isSuccessor(MBB) && PriorTBB != MBB && PriorFBB != MBB) { if (!PriorTBB) { assert(PriorCond.empty() && !PriorFBB && "Bad branch analysis"); PriorTBB = MBB; } else { assert(!PriorFBB && "Machine CFG out of date!"); PriorFBB = MBB; } DebugLoc pdl = getBranchDebugLoc(PrevBB); TII->RemoveBranch(PrevBB); TII->InsertBranch(PrevBB, PriorTBB, PriorFBB, PriorCond, pdl); } // Iterate through all the predecessors, revectoring each in-turn. size_t PI = 0; bool DidChange = false; bool HasBranchToSelf = false; while(PI != MBB->pred_size()) { MachineBasicBlock *PMBB = *(MBB->pred_begin() + PI); if (PMBB == MBB) { // If this block has an uncond branch to itself, leave it. ++PI; HasBranchToSelf = true; } else { DidChange = true; PMBB->ReplaceUsesOfBlockWith(MBB, CurTBB); // If this change resulted in PMBB ending in a conditional // branch where both conditions go to the same destination, // change this to an unconditional branch (and fix the CFG). MachineBasicBlock *NewCurTBB = nullptr, *NewCurFBB = nullptr; SmallVector<MachineOperand, 4> NewCurCond; bool NewCurUnAnalyzable = TII->AnalyzeBranch(*PMBB, NewCurTBB, NewCurFBB, NewCurCond, true); if (!NewCurUnAnalyzable && NewCurTBB && NewCurTBB == NewCurFBB) { DebugLoc pdl = getBranchDebugLoc(*PMBB); TII->RemoveBranch(*PMBB); NewCurCond.clear(); TII->InsertBranch(*PMBB, NewCurTBB, nullptr, NewCurCond, pdl); MadeChange = true; ++NumBranchOpts; PMBB->CorrectExtraCFGEdges(NewCurTBB, nullptr, false); } } } // Change any jumptables to go to the new MBB. if (MachineJumpTableInfo *MJTI = MF.getJumpTableInfo()) MJTI->ReplaceMBBInJumpTables(MBB, CurTBB); if (DidChange) { ++NumBranchOpts; MadeChange = true; if (!HasBranchToSelf) return MadeChange; } } } // Add the branch back if the block is more than just an uncond branch. TII->InsertBranch(*MBB, CurTBB, nullptr, CurCond, dl); } } // If the prior block doesn't fall through into this block, and if this // block doesn't fall through into some other block, see if we can find a // place to move this block where a fall-through will happen. if (!PrevBB.canFallThrough()) { // Now we know that there was no fall-through into this block, check to // see if it has a fall-through into its successor. bool CurFallsThru = MBB->canFallThrough(); if (!MBB->isLandingPad()) { // Check all the predecessors of this block. If one of them has no fall // throughs, move this block right after it. for (MachineBasicBlock::pred_iterator PI = MBB->pred_begin(), E = MBB->pred_end(); PI != E; ++PI) { // Analyze the branch at the end of the pred. MachineBasicBlock *PredBB = *PI; MachineFunction::iterator PredFallthrough = PredBB; ++PredFallthrough; MachineBasicBlock *PredTBB = nullptr, *PredFBB = nullptr; SmallVector<MachineOperand, 4> PredCond; if (PredBB != MBB && !PredBB->canFallThrough() && !TII->AnalyzeBranch(*PredBB, PredTBB, PredFBB, PredCond, true) && (!CurFallsThru || !CurTBB || !CurFBB) && (!CurFallsThru || MBB->getNumber() >= PredBB->getNumber())) { // If the current block doesn't fall through, just move it. // If the current block can fall through and does not end with a // conditional branch, we need to append an unconditional jump to // the (current) next block. To avoid a possible compile-time // infinite loop, move blocks only backward in this case. // Also, if there are already 2 branches here, we cannot add a third; // this means we have the case // Bcc next // B elsewhere // next: if (CurFallsThru) { MachineBasicBlock *NextBB = std::next(MachineFunction::iterator(MBB)); CurCond.clear(); TII->InsertBranch(*MBB, NextBB, nullptr, CurCond, DebugLoc()); } MBB->moveAfter(PredBB); MadeChange = true; goto ReoptimizeBlock; } } } if (!CurFallsThru) { // Check all successors to see if we can move this block before it. for (MachineBasicBlock::succ_iterator SI = MBB->succ_begin(), E = MBB->succ_end(); SI != E; ++SI) { // Analyze the branch at the end of the block before the succ. MachineBasicBlock *SuccBB = *SI; MachineFunction::iterator SuccPrev = SuccBB; --SuccPrev; // If this block doesn't already fall-through to that successor, and if // the succ doesn't already have a block that can fall through into it, // and if the successor isn't an EH destination, we can arrange for the // fallthrough to happen. if (SuccBB != MBB && &*SuccPrev != MBB && !SuccPrev->canFallThrough() && !CurUnAnalyzable && !SuccBB->isLandingPad()) { MBB->moveBefore(SuccBB); MadeChange = true; goto ReoptimizeBlock; } } // Okay, there is no really great place to put this block. If, however, // the block before this one would be a fall-through if this block were // removed, move this block to the end of the function. MachineBasicBlock *PrevTBB = nullptr, *PrevFBB = nullptr; SmallVector<MachineOperand, 4> PrevCond; if (FallThrough != MF.end() && !TII->AnalyzeBranch(PrevBB, PrevTBB, PrevFBB, PrevCond, true) && PrevBB.isSuccessor(FallThrough)) { MBB->moveAfter(--MF.end()); MadeChange = true; return MadeChange; } } } return MadeChange; } //===----------------------------------------------------------------------===// // Hoist Common Code //===----------------------------------------------------------------------===// /// HoistCommonCode - Hoist common instruction sequences at the start of basic /// blocks to their common predecessor. bool BranchFolder::HoistCommonCode(MachineFunction &MF) { bool MadeChange = false; for (MachineFunction::iterator I = MF.begin(), E = MF.end(); I != E; ) { MachineBasicBlock *MBB = I++; MadeChange |= HoistCommonCodeInSuccs(MBB); } return MadeChange; } /// findFalseBlock - BB has a fallthrough. Find its 'false' successor given /// its 'true' successor. static MachineBasicBlock *findFalseBlock(MachineBasicBlock *BB, MachineBasicBlock *TrueBB) { for (MachineBasicBlock::succ_iterator SI = BB->succ_begin(), E = BB->succ_end(); SI != E; ++SI) { MachineBasicBlock *SuccBB = *SI; if (SuccBB != TrueBB) return SuccBB; } return nullptr; } /// findHoistingInsertPosAndDeps - Find the location to move common instructions /// in successors to. The location is usually just before the terminator, /// however if the terminator is a conditional branch and its previous /// instruction is the flag setting instruction, the previous instruction is /// the preferred location. This function also gathers uses and defs of the /// instructions from the insertion point to the end of the block. The data is /// used by HoistCommonCodeInSuccs to ensure safety. static MachineBasicBlock::iterator findHoistingInsertPosAndDeps(MachineBasicBlock *MBB, const TargetInstrInfo *TII, const TargetRegisterInfo *TRI, SmallSet<unsigned,4> &Uses, SmallSet<unsigned,4> &Defs) { MachineBasicBlock::iterator Loc = MBB->getFirstTerminator(); if (!TII->isUnpredicatedTerminator(Loc)) return MBB->end(); for (unsigned i = 0, e = Loc->getNumOperands(); i != e; ++i) { const MachineOperand &MO = Loc->getOperand(i); if (!MO.isReg()) continue; unsigned Reg = MO.getReg(); if (!Reg) continue; if (MO.isUse()) { for (MCRegAliasIterator AI(Reg, TRI, true); AI.isValid(); ++AI) Uses.insert(*AI); } else { if (!MO.isDead()) // Don't try to hoist code in the rare case the terminator defines a // register that is later used. return MBB->end(); // If the terminator defines a register, make sure we don't hoist // the instruction whose def might be clobbered by the terminator. for (MCRegAliasIterator AI(Reg, TRI, true); AI.isValid(); ++AI) Defs.insert(*AI); } } if (Uses.empty()) return Loc; if (Loc == MBB->begin()) return MBB->end(); // The terminator is probably a conditional branch, try not to separate the // branch from condition setting instruction. MachineBasicBlock::iterator PI = Loc; --PI; while (PI != MBB->begin() && PI->isDebugValue()) --PI; bool IsDef = false; for (unsigned i = 0, e = PI->getNumOperands(); !IsDef && i != e; ++i) { const MachineOperand &MO = PI->getOperand(i); // If PI has a regmask operand, it is probably a call. Separate away. if (MO.isRegMask()) return Loc; if (!MO.isReg() || MO.isUse()) continue; unsigned Reg = MO.getReg(); if (!Reg) continue; if (Uses.count(Reg)) IsDef = true; } if (!IsDef) // The condition setting instruction is not just before the conditional // branch. return Loc; // Be conservative, don't insert instruction above something that may have // side-effects. And since it's potentially bad to separate flag setting // instruction from the conditional branch, just abort the optimization // completely. // Also avoid moving code above predicated instruction since it's hard to // reason about register liveness with predicated instruction. bool DontMoveAcrossStore = true; if (!PI->isSafeToMove(nullptr, DontMoveAcrossStore) || TII->isPredicated(PI)) return MBB->end(); // Find out what registers are live. Note this routine is ignoring other live // registers which are only used by instructions in successor blocks. for (unsigned i = 0, e = PI->getNumOperands(); i != e; ++i) { const MachineOperand &MO = PI->getOperand(i); if (!MO.isReg()) continue; unsigned Reg = MO.getReg(); if (!Reg) continue; if (MO.isUse()) { for (MCRegAliasIterator AI(Reg, TRI, true); AI.isValid(); ++AI) Uses.insert(*AI); } else { if (Uses.erase(Reg)) { for (MCSubRegIterator SubRegs(Reg, TRI); SubRegs.isValid(); ++SubRegs) Uses.erase(*SubRegs); // Use sub-registers to be conservative } for (MCRegAliasIterator AI(Reg, TRI, true); AI.isValid(); ++AI) Defs.insert(*AI); } } return PI; } /// HoistCommonCodeInSuccs - If the successors of MBB has common instruction /// sequence at the start of the function, move the instructions before MBB /// terminator if it's legal. bool BranchFolder::HoistCommonCodeInSuccs(MachineBasicBlock *MBB) { MachineBasicBlock *TBB = nullptr, *FBB = nullptr; SmallVector<MachineOperand, 4> Cond; if (TII->AnalyzeBranch(*MBB, TBB, FBB, Cond, true) || !TBB || Cond.empty()) return false; if (!FBB) FBB = findFalseBlock(MBB, TBB); if (!FBB) // Malformed bcc? True and false blocks are the same? return false; // Restrict the optimization to cases where MBB is the only predecessor, // it is an obvious win. if (TBB->pred_size() > 1 || FBB->pred_size() > 1) return false; // Find a suitable position to hoist the common instructions to. Also figure // out which registers are used or defined by instructions from the insertion // point to the end of the block. SmallSet<unsigned, 4> Uses, Defs; MachineBasicBlock::iterator Loc = findHoistingInsertPosAndDeps(MBB, TII, TRI, Uses, Defs); if (Loc == MBB->end()) return false; bool HasDups = false; SmallVector<unsigned, 4> LocalDefs; SmallSet<unsigned, 4> LocalDefsSet; MachineBasicBlock::iterator TIB = TBB->begin(); MachineBasicBlock::iterator FIB = FBB->begin(); MachineBasicBlock::iterator TIE = TBB->end(); MachineBasicBlock::iterator FIE = FBB->end(); while (TIB != TIE && FIB != FIE) { // Skip dbg_value instructions. These do not count. if (TIB->isDebugValue()) { while (TIB != TIE && TIB->isDebugValue()) ++TIB; if (TIB == TIE) break; } if (FIB->isDebugValue()) { while (FIB != FIE && FIB->isDebugValue()) ++FIB; if (FIB == FIE) break; } if (!TIB->isIdenticalTo(FIB, MachineInstr::CheckKillDead)) break; if (TII->isPredicated(TIB)) // Hard to reason about register liveness with predicated instruction. break; bool IsSafe = true; for (unsigned i = 0, e = TIB->getNumOperands(); i != e; ++i) { MachineOperand &MO = TIB->getOperand(i); // Don't attempt to hoist instructions with register masks. if (MO.isRegMask()) { IsSafe = false; break; } if (!MO.isReg()) continue; unsigned Reg = MO.getReg(); if (!Reg) continue; if (MO.isDef()) { if (Uses.count(Reg)) { // Avoid clobbering a register that's used by the instruction at // the point of insertion. IsSafe = false; break; } if (Defs.count(Reg) && !MO.isDead()) { // Don't hoist the instruction if the def would be clobber by the // instruction at the point insertion. FIXME: This is overly // conservative. It should be possible to hoist the instructions // in BB2 in the following example: // BB1: // r1, eflag = op1 r2, r3 // brcc eflag // // BB2: // r1 = op2, ... // = op3, r1<kill> IsSafe = false; break; } } else if (!LocalDefsSet.count(Reg)) { if (Defs.count(Reg)) { // Use is defined by the instruction at the point of insertion. IsSafe = false; break; } if (MO.isKill() && Uses.count(Reg)) // Kills a register that's read by the instruction at the point of // insertion. Remove the kill marker. MO.setIsKill(false); } } if (!IsSafe) break; bool DontMoveAcrossStore = true; if (!TIB->isSafeToMove(nullptr, DontMoveAcrossStore)) break; // Remove kills from LocalDefsSet, these registers had short live ranges. for (unsigned i = 0, e = TIB->getNumOperands(); i != e; ++i) { MachineOperand &MO = TIB->getOperand(i); if (!MO.isReg() || !MO.isUse() || !MO.isKill()) continue; unsigned Reg = MO.getReg(); if (!Reg || !LocalDefsSet.count(Reg)) continue; for (MCRegAliasIterator AI(Reg, TRI, true); AI.isValid(); ++AI) LocalDefsSet.erase(*AI); } // Track local defs so we can update liveins. for (unsigned i = 0, e = TIB->getNumOperands(); i != e; ++i) { MachineOperand &MO = TIB->getOperand(i); if (!MO.isReg() || !MO.isDef() || MO.isDead()) continue; unsigned Reg = MO.getReg(); if (!Reg) continue; LocalDefs.push_back(Reg); for (MCRegAliasIterator AI(Reg, TRI, true); AI.isValid(); ++AI) LocalDefsSet.insert(*AI); } HasDups = true; ++TIB; ++FIB; } if (!HasDups) return false; MBB->splice(Loc, TBB, TBB->begin(), TIB); FBB->erase(FBB->begin(), FIB); // Update livein's. for (unsigned i = 0, e = LocalDefs.size(); i != e; ++i) { unsigned Def = LocalDefs[i]; if (LocalDefsSet.count(Def)) { TBB->addLiveIn(Def); FBB->addLiveIn(Def); } } ++NumHoist; return true; }
rutgers-apl/Atomicity-Violation-Detector
tdebug-llvm/llvm/lib/CodeGen/BranchFolding.cpp
C++
gpl-2.0
70,187
// Copyright (C) 2011,2012 GlavSoft LLC. // All rights reserved. // //------------------------------------------------------------------------- // This file is part of the TightVNC software. Please visit our Web site: // // http://www.tightvnc.com/ // // This program is free software; you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation; either version 2 of the License, or // (at your option) any later version. // // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU General Public License along // with this program; if not, write to the Free Software Foundation, Inc., // 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. //------------------------------------------------------------------------- // #include "PointerPosDecoder.h" PointerPosDecoder::PointerPosDecoder(LogWriter *logWriter) : PseudoDecoder(logWriter) { m_encoding = PseudoEncDefs::POINTER_POS; } PointerPosDecoder::~PointerPosDecoder() { }
Lacon-Computer/LC-RemoteHelp
viewer-core/PointerPosDecoder.cpp
C++
gpl-2.0
1,282
<?php /** * JEvents Component for Joomla 1.5.x * * @version $Id: view.html.php 3155 2012-01-05 12:01:16Z geraintedwards $ * @package JEvents * @copyright Copyright (C) 2008-2015 GWE Systems Ltd * @license GNU/GPLv2, see http://www.gnu.org/licenses/gpl-2.0.html * @link http://www.jevents.net */ // Check to ensure this file is included in Joomla! defined('_JEXEC') or die(); /** * HTML View class for the component frontend * * @static */ class flatViewICalevent extends JEventsflatView { function detail($tpl = null) { JEVHelper::componentStylesheet($this); $document = JFactory::getDocument(); // TODO do this properly //$document->setTitle(JText::_( 'BROWSER_TITLE' )); $params = JComponentHelper::getParams(JEV_COM_COMPONENT); //$this->assign("introduction", $params->get("intro","")); $this->data = $this->datamodel->getEventData( $this->evid, $this->jevtype, $this->year, $this->month, $this->day, $this->uid ); // Dynamic pathway if (isset($this->data['row'])){ $pathway = JFactory::getApplication()->getPathway(); $pathway->addItem($this->data['row']->title() ,""); // Set date in view for use in navigation icons $this->year = $this->data['row']->yup(); $this->month = $this->data['row']->mup(); $this->day = $this->data['row']->dup(); // seth month and year to be used by mini-calendar if needed if (!JRequest::getVar("month",0)) JRequest::setVar("month",$this->month); if (!JRequest::getVar("year",0)) JRequest::setVar("year",$this->year); } } }
githubupttik/upttik
components/com_jevents/views/flat/icalevent/view.html.php
PHP
gpl-2.0
1,562
#! /usr/bin/env bash $XGETTEXT *.cpp -o $podir/randrmonitor.pot
falbrechtskirchinger/kde-workspace
kcontrol/randr/module/Messages.sh
Shell
gpl-2.0
64
// $Id: ajax_view.js,v 1.13 2008/12/02 18:35:50 merlinofchaos Exp $ /** * @file ajaxView.js * * Handles AJAX fetching of views, including filter submission and response. */ Drupal.Views.Ajax = Drupal.Views.Ajax || {}; /** * An ajax responder that accepts a packet of JSON data and acts appropriately. * * The following fields control behavior. * - 'display': Display the associated data in the view area. */ Drupal.Views.Ajax.ajaxViewResponse = function(target, response) { if (response.debug) { alert(response.debug); } var $view = $(target); // Check the 'display' for data. if (response.status && response.display) { var $newView = $(response.display); $view.replaceWith($newView); $view = $newView; Drupal.attachBehaviors($view.parent()); } if (response.messages) { // Show any messages (but first remove old ones, if there are any). $view.find('.views-messages').remove().end().prepend(response.messages); } }; /** * Ajax behavior for views. */ Drupal.behaviors.ViewsAjaxView = function() { var ajax_path = Drupal.settings.views.ajax_path; // If there are multiple views this might've ended up showing up multiple times. if (ajax_path.constructor.toString().indexOf("Array") != -1) { ajax_path = ajax_path[0]; } if (Drupal.settings && Drupal.settings.views && Drupal.settings.views.ajaxViews) { $.each(Drupal.settings.views.ajaxViews, function(i, settings) { var view = '.view-dom-id-' + settings.view_dom_id; if (!$(view).size()) { // Backward compatibility: if 'views-view.tpl.php' is old and doesn't // contain the 'view-dom-id-#' class, we fall back to the old way of // locating the view: view = '.view-id-' + settings.view_name + '.view-display-id-' + settings.view_display_id; } // Process exposed filter forms. $('form#views-exposed-form-' + settings.view_name.replace(/_/g, '-') + '-' + settings.view_display_id.replace(/_/g, '-')) .filter(':not(.views-processed)') .each(function () { // remove 'q' from the form; it's there for clean URLs // so that it submits to the right place with regular submit // but this method is submitting elsewhere. $('input[name=q]', this).remove(); var form = this; // ajaxSubmit doesn't accept a data argument, so we have to // pass additional fields this way. $.each(settings, function(key, setting) { $(form).append('<input type="hidden" name="'+ key + '" value="'+ setting +'"/>'); }); }) .addClass('views-processed') .submit(function () { $('input[@type=submit]', this).after('<span class="views-throbbing">&nbsp</span>'); var object = this; $(this).ajaxSubmit({ url: ajax_path, type: 'GET', success: function(response) { // Call all callbacks. if (response.__callbacks) { $.each(response.__callbacks, function(i, callback) { eval(callback)(view, response); }); $('.views-throbbing', object).remove(); } }, error: function() { alert(Drupal.t("An error occurred at @path.", {'@path': ajax_path})); $('.views-throbbing', object).remove(); }, dataType: 'json' }); return false; }); $(view).filter(':not(.views-processed)').each(function() { var target = this; $(this) .addClass('views-processed') // Process pager links. .find('ul.pager > li > a') .each(function () { var viewData = Drupal.Views.parseQueryString($(this).attr('href')); if (!viewData['view_name']) { $.each(settings, function (key, setting) { viewData[key] = setting; }); } $(this) .click(function () { $(this).addClass('views-throbbing'); $.ajax({ url: ajax_path, type: 'GET', data: viewData, success: function(response) { $(this).removeClass('views-throbbing'); // Call all callbacks. if (response.__callbacks) { $.each(response.__callbacks, function(i, callback) { eval(callback)(target, response); }); } }, error: function() { $(this).removeClass('views-throbbing'); alert(Drupal.t("An error occurred at @path.", {'@path': ajax_path})); }, dataType: 'json' }); return false; }); }) .end() // Process tablesort links. .find('th.views-field a') .each(function () { var viewData = Drupal.Views.parseQueryString($(this).attr('href')); $.each(settings, function (key, setting) { viewData[key] = setting; }); $(this) .click(function () { $(this).addClass('views-throbbing'); $.ajax({ url: ajax_path, type: 'GET', data: viewData, success: function(response) { $(this).removeClass('views-throbbing'); // Call all callbacks. if (response.__callbacks) { $.each(response.__callbacks, function(i, callback) { eval(callback)(target, response); }); } }, error: function() { $(this).removeClass('views-throbbing'); alert(Drupal.t("An error occurred at @path.", {'@path': ajax_path})); }, dataType: 'json' }); return false; }); }); // .each 'th.views-field a' }); // $view.filter().each }); // .each Drupal.settings.views.ajaxViews } // if };
pblasone/Lagervarer
sites/all/modules/views/js/ajax_view.js
JavaScript
gpl-2.0
6,006
/* * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public * License v2 as published by the Free Software Foundation. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * General Public License for more details. * * You should have received a copy of the GNU General Public * License along with this program; if not, write to the * Free Software Foundation, Inc., 59 Temple Place - Suite 330, * Boston, MA 021110-1307, USA. */ #include <sys/stat.h> #include <sys/ioctl.h> #include <sys/types.h> #include <sys/xattr.h> #include <fcntl.h> #include <unistd.h> #include "ctree.h" #include "commands.h" #include "utils.h" #include "props.h" #define XATTR_BTRFS_PREFIX "btrfs." #define XATTR_BTRFS_PREFIX_LEN (sizeof(XATTR_BTRFS_PREFIX) - 1) /* * Defined as synonyms in attr/xattr.h */ #ifndef ENOATTR #define ENOATTR ENODATA #endif static int prop_read_only(enum prop_object_type type, const char *object, const char *name, const char *value) { int ret = 0; int fd = -1; u64 flags = 0; fd = open(object, O_RDONLY); if (fd < 0) { ret = -errno; error("failed to open %s: %s", object, strerror(-ret)); goto out; } ret = ioctl(fd, BTRFS_IOC_SUBVOL_GETFLAGS, &flags); if (ret < 0) { ret = -errno; error("failed to get flags for %s: %s", object, strerror(-ret)); goto out; } if (!value) { if (flags & BTRFS_SUBVOL_RDONLY) fprintf(stdout, "ro=true\n"); else fprintf(stdout, "ro=false\n"); ret = 0; goto out; } if (!strcmp(value, "true")) { flags |= BTRFS_SUBVOL_RDONLY; } else if (!strcmp(value, "false")) { flags = flags & ~BTRFS_SUBVOL_RDONLY; } else { ret = -EINVAL; error("invalid value for property: %s", value); goto out; } ret = ioctl(fd, BTRFS_IOC_SUBVOL_SETFLAGS, &flags); if (ret < 0) { ret = -errno; error("failed to set flags for %s: %s", object, strerror(-ret)); goto out; } out: if (fd != -1) close(fd); return ret; } static int prop_label(enum prop_object_type type, const char *object, const char *name, const char *value) { int ret; if (value) { ret = set_label((char *) object, (char *) value); } else { char label[BTRFS_LABEL_SIZE]; ret = get_label((char *) object, label); if (!ret) fprintf(stdout, "label=%s\n", label); } return ret; } static int prop_compression(enum prop_object_type type, const char *object, const char *name, const char *value) { int ret; ssize_t sret; int fd = -1; DIR *dirstream = NULL; char *buf = NULL; char *xattr_name = NULL; int open_flags = value ? O_RDWR : O_RDONLY; fd = open_file_or_dir3(object, &dirstream, open_flags); if (fd == -1) { ret = -errno; error("failed to open %s: %s", object, strerror(-ret)); goto out; } xattr_name = malloc(XATTR_BTRFS_PREFIX_LEN + strlen(name) + 1); if (!xattr_name) { ret = -ENOMEM; goto out; } memcpy(xattr_name, XATTR_BTRFS_PREFIX, XATTR_BTRFS_PREFIX_LEN); memcpy(xattr_name + XATTR_BTRFS_PREFIX_LEN, name, strlen(name)); xattr_name[XATTR_BTRFS_PREFIX_LEN + strlen(name)] = '\0'; if (value) sret = fsetxattr(fd, xattr_name, value, strlen(value), 0); else sret = fgetxattr(fd, xattr_name, NULL, 0); if (sret < 0) { ret = -errno; if (ret != -ENOATTR) error("failed to %s compression for %s: %s", value ? "set" : "get", object, strerror(-ret)); else ret = 0; goto out; } if (!value) { size_t len = sret; buf = malloc(len); if (!buf) { ret = -ENOMEM; goto out; } sret = fgetxattr(fd, xattr_name, buf, len); if (sret < 0) { ret = -errno; error("failed to get compression for %s: %s", object, strerror(-ret)); goto out; } fprintf(stdout, "compression=%.*s\n", (int)len, buf); } ret = 0; out: free(xattr_name); free(buf); if (fd >= 0) close_file_or_dir(fd, dirstream); return ret; } const struct prop_handler prop_handlers[] = { {"ro", "Set/get read-only flag of subvolume.", 0, prop_object_subvol, prop_read_only}, {"label", "Set/get label of device.", 0, prop_object_dev | prop_object_root, prop_label}, {"compression", "Set/get compression for a file or directory", 0, prop_object_inode, prop_compression}, {NULL, NULL, 0, 0, NULL} };
rot13/btrfs-progs
props.c
C
gpl-2.0
4,427
#adminmenu #toplevel_page_wps_overview_page div.wp-menu-image { background: url("../images/icon.png") no-repeat scroll center center rgba(0, 0, 0, 0) !important; } #adminmenu #toplevel_page_wps_overview_page div.wp-menu-image:before { content: ""; }
xoyoc/xoyocNET
wp-content/plugins/wp-statistics/assets/css/admin-old.css
CSS
gpl-2.0
270
/** \file vp_api_lib_cfg.h * vp_api_lib_cfg.h * * This file contains the default options for various libraries. In general * the default options are same as top level API default options. However * VP-API provides a mechanism to define default options that is different * compared to top level default options. This file provides such a mechanism. * * Copyright (c) 2010, Zarlink Semiconductor, Inc. * * $Revision: 1.1 $ * $LastChangedDate: 2010-02-12 16:40:10 -0600 (Fri, 12 Feb 2010) $ */ #ifndef VP_API_LIB_CFG_H #define VP_API_LIB_CFG_H /****************************************************************************** * Library Specific default options * *****************************************************************************/ /* The following section provides mechanisms to define default options for * individual VTD families that is different compared to VP-API top level * default settins. * * NOTE: Users are free to change individual library's default settings as long * as it is not needed by the API and the VTD understands it. */ #ifdef VP_CC_VCP_SERIES /* Default Event Masks for VCP */ /* First, define the events that VCP does not understand or not needed */ #define VCP_EVCAT_FAULT_NOT_NEEDED \ (VP_DEV_EVID_EVQ_OFL_FLT | /* VCP does not understand */ \ VP_DEV_EVID_WDT_FLT) /* VCP does not understand */ /* Second, define the events that are specially needed for the VCP API */ #define VCP_EVCAT_FAULT_NEEDED (~0x0000) /* Third, Define the composite events */ #define VCP_OPTION_DEFAULT_FAULT_EVENT_MASK \ ((VP_OPTION_DEFAULT_FAULT_EVENT_MASK | /* Top level API default */ \ VCP_EVCAT_FAULT_NOT_NEEDED) & /* Events not needed for VCP*/ \ VCP_EVCAT_FAULT_NEEDED) /* Events needed for VCP */ /* First, define the events that VCP does not understand or not needed */ #define VCP_EVCAT_SIGNALLING_NOT_NEEDED \ (VP_LINE_EVID_US_TONE_DETECT | /* VCP does not understand */ \ VP_LINE_EVID_DS_TONE_DETECT | /* VCP does not understand */ \ VP_DEV_EVID_SEQUENCER) /* VCP does not understand */ /* Second, define the events that are specially needed for the VCP API */ #define VCP_EVCAT_SIGNALLING_NEEDED (~0x0000) /* Third, Define the composite events */ #define VCP_OPTION_DEFAULT_SIGNALING_EVENT_MASK \ ((VP_OPTION_DEFAULT_SIGNALING_EVENT_MASK | /* Top level API default */ \ VCP_EVCAT_SIGNALLING_NOT_NEEDED) & /* Events not needed for VCP*/ \ VCP_EVCAT_SIGNALLING_NEEDED) /* Events needed for VCP */ /* First, define the events that VCP does not understand or not needed */ #define VCP_EVCAT_RESPONSE_NOT_NEEDED \ (VP_DEV_EVID_DEV_INIT_CMP ) /* VCP does not understand */ /* Second, define the events that are specially needed for the VCP API */ #define VCP_EVCAT_RESPONSE_NEEDED (~0x0000) /* Third, Define the composite events */ #define VCP_OPTION_DEFAULT_RESPONSE_EVENT_MASK \ ((VP_OPTION_DEFAULT_RESPONSE_EVENT_MASK | /* Top level API default */ \ VCP_EVCAT_RESPONSE_NOT_NEEDED) & /* Events not needed for VCP*/ \ VCP_EVCAT_RESPONSE_NEEDED) /* Events needed for VCP */ #define VCP_OPTION_DEFAULT_FXO_EVENT_MASK (0xffff)/* VCP does not * understand */ #define VCP_OPTION_DEFAULT_PACKET_EVENT_MASK (0xffff)/* VCP does not * understand */ #endif /* VP_CC_VCP_SERIES */ #ifdef VP_CC_VCP2_SERIES /* Default option settings for VCP2: These are the default values applied at * VpInitDevice() and/or VpInitLine(). If your application uses more than one * type of device (VTD) and you with to specify VCP2-specific defaults that * differ from the defaults specified in vp_api_cfg.h, do so here. */ #include "vcp2_api.h" /* VCP2-specific default event masks: */ #define VCP2_DEFAULT_MASK_FAULT (VP_OPTION_DEFAULT_FAULT_EVENT_MASK | VCP2_INVALID_FAULT_EVENTS) #define VCP2_DEFAULT_MASK_SIGNALING (VP_OPTION_DEFAULT_SIGNALING_EVENT_MASK | VCP2_INVALID_SIGNALING_EVENTS) #define VCP2_DEFAULT_MASK_RESPONSE (VP_OPTION_DEFAULT_RESPONSE_EVENT_MASK | VCP2_INVALID_RESPONSE_EVENTS) #define VCP2_DEFAULT_MASK_TEST (VP_OPTION_DEFAULT_TEST_EVENT_MASK | VCP2_INVALID_TEST_EVENTS) #define VCP2_DEFAULT_MASK_PROCESS (VP_OPTION_DEFAULT_PROCESS_EVENT_MASK | VCP2_INVALID_PROCESS_EVENTS) #define VCP2_DEFAULT_MASK_FXO (VP_OPTION_DEFAULT_FXO_EVENT_MASK | VCP2_INVALID_FXO_EVENTS) #define VCP2_DEFAULT_MASK_PACKET (VP_OPTION_DEFAULT_PACKET_EVENT_MASK | VCP2_INVALID_PACKET_EVENTS) #endif #endif /* VP_API_LIB_CFG_H */
ysleu/RTL8685
uClinux-dist/linux-2.6.x/rtk_voip-single_cpu/voip_drivers/zarlink/api_lib-2.16.1/includes/vp_api_lib_cfg.h
C
gpl-2.0
4,737
// license:BSD-3-Clause // copyright-holders:Mike Coates, Couriersud /*************************************************************************** Century CVS System MAIN BOARD: FLAG LOW | FLAG HIGH ------------------------------------+----------------------------------- 1C00-1FFF SYSTEM RAM | SYSTEM RAM | | 1800-1BFF ATTRIBUTE RAM 32X28 | SCREEN RAM 32X28 1700 2636 1 | CHARACTER RAM 1 256BYTES OF 1K* 1600 2636 2 | CHARACTER RAM 2 256BYTES OF 1K* 1500 2636 3 | CHARACTER RAM 3 256BYTES OF 1K* 1400 BULLET RAM | PALETTE RAM 16BYTES | | 0000-13FF PROGRAM ROM'S | PROGRAM ROM'S * Note the upper two address lines are latched using an I/O read. The I/O map only has space for 128 character bit maps The CPU CANNOT read the character PROMs ------ CVS I/O MAP ----------- ADR14 ADR13 | READ | WRITE ------------+-------------------------------------------+----------------------------- 1 0 | COLLISION RESET | D0 = STARS ON | | D1 = SHADE BRIGHTER TO RIGHT | | D2 = SCREEN ROTATE read/write | | D3 = SHADE BRIGHTER TO LEFT Data | | D4 = LAMP 1 (CN1 1) | | D5 = LAMP 2 (CN1 2) | | D6 = SHADE BRIGHTER TO BOTTOM | | D7 = SHADE BRIGHTER TO TOP ------------+-------------------------------------------+------------------------------ X 1 | A0-2: 0 STROBE CN2 1 | VERTICAL SCROLL OFFSET | 1 STROBE CN2 11 | | 2 STROBE CN2 2 | | 3 STROBE CN2 3 | | 4 STROBE CN2 4 | | 5 STROBE CN2 12 | | 6 STROBE DIP SW3 | | 7 STROBE DIP SW2 | | | read/write | A4-5: CHARACTER PROM/RAM SELECTION MODE | extended | There are 256 characters in total. The | | higher ones can be user defined in RAM. | | The split between PROM and RAM characters | | is variable. | | ROM RAM | | A4 A5 MODE CHARACTERS CHARACTERS | | 0 0 0 224 (0-223) 32 (224-255)| | 0 1 1 192 (0-191) 64 (192-255)| | 1 0 2 256 (0-255) 0 | | 1 1 3 128 (0-127) 128 (128-255)| | | | | | A6-7: SELECT CHARACTER RAM's | | UPPER ADDRESS BITS A8-9 | | (see memory map) | ------------+-------------------------------------------+------------------------------- 0 0 | COLLISION DATA BYTE: | SOUND CONTROL PORT | D0 = OBJECT 1 AND 2 | | D1 = OBJECT 2 AND 3 | read/write | D2 = OBJECT 1 AND 3 | control | D3 = ANY OBJECT AND BULLET | | D4 = OBJECT 1 AND CP1 OR CP2 | | D5 = OBJECT 2 AND CP1 OR CP2 | | D6 = OBJECT 3 AND CP1 OR CP2 | | D7 = BULLET AND CP1 OR CP2 | ------------+-------------------------------------------+------------------------------- Driver by Mike Coates Hardware Info Malcolm & Darren Additional work 2009 Couriersud Todo & FIXME: - the board most probably has discrete circuits. The 393Hz tone used for shots (superbike) and collisions (8ball) is just a guess. ***************************************************************************/ #include "emu.h" #include "cpu/s2650/s2650.h" #include "includes/cvs.h" /* Turn to 1 so all inputs are always available (this shall only be a debug feature) */ #define CVS_SHOW_ALL_INPUTS 0 #define VERBOSE 0 #define LOG(x) do { if (VERBOSE) logerror x; } while (0) /************************************* * * Multiplexed memory access * *************************************/ WRITE_LINE_MEMBER(cvs_state::write_s2650_flag) { m_s2650_flag = state; } READ8_MEMBER(cvs_state::cvs_video_or_color_ram_r) { if (m_s2650_flag) return m_video_ram[offset]; else return m_color_ram[offset]; } WRITE8_MEMBER(cvs_state::cvs_video_or_color_ram_w) { if (m_s2650_flag) m_video_ram[offset] = data; else m_color_ram[offset] = data; } READ8_MEMBER(cvs_state::cvs_bullet_ram_or_palette_r) { if (m_s2650_flag) return m_palette_ram[offset & 0x0f]; else return m_bullet_ram[offset]; } WRITE8_MEMBER(cvs_state::cvs_bullet_ram_or_palette_w) { if (m_s2650_flag) m_palette_ram[offset & 0x0f] = data; else m_bullet_ram[offset] = data; } READ8_MEMBER(cvs_state::cvs_s2636_0_or_character_ram_r) { if (m_s2650_flag) return m_character_ram[(0 * 0x800) | 0x400 | m_character_ram_page_start | offset]; else return m_s2636_0->read_data(space, offset); } WRITE8_MEMBER(cvs_state::cvs_s2636_0_or_character_ram_w) { if (m_s2650_flag) { offset |= (0 * 0x800) | 0x400 | m_character_ram_page_start; m_character_ram[offset] = data; m_gfxdecode->gfx(1)->mark_dirty((offset / 8) % 256); } else m_s2636_0->write_data(space, offset, data); } READ8_MEMBER(cvs_state::cvs_s2636_1_or_character_ram_r) { if (m_s2650_flag) return m_character_ram[(1 * 0x800) | 0x400 | m_character_ram_page_start | offset]; else return m_s2636_1->read_data(space, offset); } WRITE8_MEMBER(cvs_state::cvs_s2636_1_or_character_ram_w) { if (m_s2650_flag) { offset |= (1 * 0x800) | 0x400 | m_character_ram_page_start; m_character_ram[offset] = data; m_gfxdecode->gfx(1)->mark_dirty((offset / 8) % 256); } else m_s2636_1->write_data(space, offset, data); } READ8_MEMBER(cvs_state::cvs_s2636_2_or_character_ram_r) { if (m_s2650_flag) return m_character_ram[(2 * 0x800) | 0x400 | m_character_ram_page_start | offset]; else return m_s2636_2->read_data(space, offset); } WRITE8_MEMBER(cvs_state::cvs_s2636_2_or_character_ram_w) { if (m_s2650_flag) { offset |= (2 * 0x800) | 0x400 | m_character_ram_page_start; m_character_ram[offset] = data; m_gfxdecode->gfx(1)->mark_dirty((offset / 8) % 256); } else m_s2636_2->write_data(space, offset, data); } /************************************* * * Interrupt generation * *************************************/ INTERRUPT_GEN_MEMBER(cvs_state::cvs_main_cpu_interrupt) { device.execute().set_input_line_vector(0, 0x03); generic_pulse_irq_line(device.execute(), 0, 1); cvs_scroll_stars(); } static void cvs_slave_cpu_interrupt( cpu_device *cpu, int state ) { cpu->set_input_line_vector(0, 0x03); //cpu->set_input_line(0, state ? ASSERT_LINE : CLEAR_LINE); cpu->set_input_line(0, state ? HOLD_LINE : CLEAR_LINE); } /************************************* * * Input port access * *************************************/ READ8_MEMBER(cvs_state::cvs_input_r) { UINT8 ret = 0; /* the upper 4 bits of the address is used to select the character banking attributes */ m_character_banking_mode = (offset >> 4) & 0x03; m_character_ram_page_start = (offset << 2) & 0x300; /* the lower 4 (or 3?) bits select the port to read */ switch (offset & 0x0f) /* might be 0x07 */ { case 0x00: ret = ioport("IN0")->read(); break; case 0x02: ret = ioport("IN1")->read(); break; case 0x03: ret = ioport("IN2")->read(); break; case 0x04: ret = ioport("IN3")->read(); break; case 0x06: ret = ioport("DSW3")->read(); break; case 0x07: ret = ioport("DSW2")->read(); break; default: logerror("%04x : CVS: Reading unmapped input port 0x%02x\n", space.device().safe_pc(), offset & 0x0f); break; } return ret; } /************************************* * * Timing * *************************************/ #if 0 READ8_MEMBER(cvs_state::cvs_393hz_clock_r) { return m_cvs_393hz_clock ? 0x80 : 0; } #endif READ8_MEMBER(cvs_state::tms_clock_r) { return m_tms5110->romclk_hack_r(space, 0) ? 0x80 : 0; } TIMER_CALLBACK_MEMBER(cvs_state::cvs_393hz_timer_cb) { m_cvs_393hz_clock = !m_cvs_393hz_clock; /* quasar.c games use this timer but have no dac3! */ if (m_dac3 != nullptr) { if (m_dac3_state[2]) m_dac3->write_unsigned8(m_cvs_393hz_clock * 0xff); } } void cvs_state::start_393hz_timer() { m_cvs_393hz_timer = machine().scheduler().timer_alloc(timer_expired_delegate(FUNC(cvs_state::cvs_393hz_timer_cb),this)); m_cvs_393hz_timer->adjust(attotime::from_hz(30*393), 0, attotime::from_hz(30*393)); } /************************************* * * 4-bit DAC * *************************************/ WRITE8_MEMBER(cvs_state::cvs_4_bit_dac_data_w) { UINT8 dac_value; static int old_data[4] = {0,0,0,0}; if (data != old_data[offset]) { LOG(("4BIT: %02x %02x\n", offset, data)); old_data[offset] = data; } m_cvs_4_bit_dac_data[offset] = data >> 7; /* merge into D0-D3 */ dac_value = (m_cvs_4_bit_dac_data[0] << 0) | (m_cvs_4_bit_dac_data[1] << 1) | (m_cvs_4_bit_dac_data[2] << 2) | (m_cvs_4_bit_dac_data[3] << 3); /* scale up to a full byte and output */ m_dac2->write_unsigned8((dac_value << 4) | dac_value); } WRITE8_MEMBER(cvs_state::cvs_unknown_w) { /* offset 2 is used in 8ball * offset 0 is used in spacefrt * offset 3 is used in darkwar * * offset 1 is not used (no trace in disassembly) */ if (data != m_dac3_state[offset]) { if (offset != 2) popmessage("Unknown: %02x %02x\n", offset, data); m_dac3_state[offset] = data; } } /************************************* * * Speech hardware * *************************************/ WRITE8_MEMBER(cvs_state::cvs_speech_rom_address_lo_w) { /* assuming that d0-d2 are cleared here */ m_speech_rom_bit_address = (m_speech_rom_bit_address & 0xf800) | (data << 3); LOG(("%04x : CVS: Speech Lo %02x Address = %04x\n", space.device().safe_pc(), data, m_speech_rom_bit_address >> 3)); } WRITE8_MEMBER(cvs_state::cvs_speech_rom_address_hi_w) { m_speech_rom_bit_address = (m_speech_rom_bit_address & 0x07ff) | (data << 11); LOG(("%04x : CVS: Speech Hi %02x Address = %04x\n", space.device().safe_pc(), data, m_speech_rom_bit_address >> 3)); } READ8_MEMBER(cvs_state::cvs_speech_command_r) { /* FIXME: this was by observation on board ??? * -bit 7 is TMS status (active LO) */ return ((m_tms5110->ctl_r(space, 0) ^ 1) << 7) | (soundlatch_byte_r(space, 0) & 0x7f); } WRITE8_MEMBER(cvs_state::cvs_tms5110_ctl_w) { UINT8 ctl; /* * offset 0: CS ? */ m_tms5110_ctl_data[offset] = (~data >> 7) & 0x01; ctl = 0 | /* CTL1 */ (m_tms5110_ctl_data[1] << 1) | /* CTL2 */ (m_tms5110_ctl_data[2] << 2) | /* CTL4 */ (m_tms5110_ctl_data[1] << 3); /* CTL8 */ LOG(("CVS: Speech CTL = %04x %02x %02x\n", ctl, offset, data)); m_tms5110->ctl_w(space, 0, ctl); } WRITE8_MEMBER(cvs_state::cvs_tms5110_pdc_w) { UINT8 out = ((~data) >> 7) & 1; LOG(("CVS: Speech PDC = %02x %02x\n", offset, out)); m_tms5110->pdc_w(out); } READ_LINE_MEMBER(cvs_state::speech_rom_read_bit) { int bit; UINT8 *ROM = memregion("speechdata")->base(); /* before reading the bit, clamp the address to the region length */ m_speech_rom_bit_address &= ((memregion("speechdata")->bytes() * 8) - 1); bit = BIT(ROM[m_speech_rom_bit_address >> 3], m_speech_rom_bit_address & 0x07); /* prepare for next bit */ m_speech_rom_bit_address++; return bit; } /************************************* * * Inter-CPU communications * *************************************/ WRITE8_MEMBER(cvs_state::audio_command_w) { LOG(("data %02x\n", data)); /* cause interrupt on audio CPU if bit 7 set */ soundlatch_byte_w(space, 0, data); cvs_slave_cpu_interrupt(m_audiocpu, data & 0x80 ? 1 : 0); } /************************************* * * Main CPU memory/IO handlers * *************************************/ static ADDRESS_MAP_START( cvs_main_cpu_map, AS_PROGRAM, 8, cvs_state ) ADDRESS_MAP_GLOBAL_MASK(0x7fff) AM_RANGE(0x0000, 0x13ff) AM_ROM AM_RANGE(0x1400, 0x14ff) AM_MIRROR(0x6000) AM_READWRITE(cvs_bullet_ram_or_palette_r, cvs_bullet_ram_or_palette_w) AM_SHARE("bullet_ram") AM_RANGE(0x1500, 0x15ff) AM_MIRROR(0x6000) AM_READWRITE(cvs_s2636_2_or_character_ram_r, cvs_s2636_2_or_character_ram_w) AM_RANGE(0x1600, 0x16ff) AM_MIRROR(0x6000) AM_READWRITE(cvs_s2636_1_or_character_ram_r, cvs_s2636_1_or_character_ram_w) AM_RANGE(0x1700, 0x17ff) AM_MIRROR(0x6000) AM_READWRITE(cvs_s2636_0_or_character_ram_r, cvs_s2636_0_or_character_ram_w) AM_RANGE(0x1800, 0x1bff) AM_MIRROR(0x6000) AM_READWRITE(cvs_video_or_color_ram_r, cvs_video_or_color_ram_w) AM_SHARE("video_ram") AM_RANGE(0x1c00, 0x1fff) AM_MIRROR(0x6000) AM_RAM AM_RANGE(0x2000, 0x33ff) AM_ROM AM_RANGE(0x4000, 0x53ff) AM_ROM AM_RANGE(0x6000, 0x73ff) AM_ROM ADDRESS_MAP_END static ADDRESS_MAP_START( cvs_main_cpu_io_map, AS_IO, 8, cvs_state ) AM_RANGE(0x00, 0xff) AM_READ(cvs_input_r) AM_WRITE(cvs_scroll_w) AM_RANGE(S2650_DATA_PORT, S2650_DATA_PORT) AM_READWRITE(cvs_collision_clear, cvs_video_fx_w) AM_RANGE(S2650_CTRL_PORT, S2650_CTRL_PORT) AM_READ(cvs_collision_r) AM_WRITE(audio_command_w) AM_RANGE(S2650_SENSE_PORT, S2650_SENSE_PORT) AM_READ_PORT("SENSE") ADDRESS_MAP_END /************************************* * * DAC driving CPU memory/IO handlers * *************************************/ static ADDRESS_MAP_START( cvs_dac_cpu_map, AS_PROGRAM, 8, cvs_state ) ADDRESS_MAP_GLOBAL_MASK(0x7fff) AM_RANGE(0x0000, 0x0fff) AM_ROM AM_RANGE(0x1000, 0x107f) AM_RAM AM_RANGE(0x1800, 0x1800) AM_READ(soundlatch_byte_r) AM_RANGE(0x1840, 0x1840) AM_DEVWRITE("dac1", dac_device, write_unsigned8) AM_RANGE(0x1880, 0x1883) AM_WRITE(cvs_4_bit_dac_data_w) AM_SHARE("4bit_dac") AM_RANGE(0x1884, 0x1887) AM_WRITE(cvs_unknown_w) AM_SHARE("dac3_state") /* ???? not connected to anything */ ADDRESS_MAP_END static ADDRESS_MAP_START( cvs_dac_cpu_io_map, AS_IO, 8, cvs_state ) /* doesn't look like it is used at all */ //AM_RANGE(S2650_SENSE_PORT, S2650_SENSE_PORT) AM_READ(cvs_393hz_clock_r) ADDRESS_MAP_END /************************************* * * Speech driving CPU memory/IO handlers * *************************************/ static ADDRESS_MAP_START( cvs_speech_cpu_map, AS_PROGRAM, 8, cvs_state ) ADDRESS_MAP_GLOBAL_MASK(0x7fff) AM_RANGE(0x0000, 0x07ff) AM_ROM AM_RANGE(0x1d00, 0x1d00) AM_WRITE(cvs_speech_rom_address_lo_w) AM_RANGE(0x1d40, 0x1d40) AM_WRITE(cvs_speech_rom_address_hi_w) AM_RANGE(0x1d80, 0x1d80) AM_READ(cvs_speech_command_r) AM_RANGE(0x1ddc, 0x1dde) AM_WRITE(cvs_tms5110_ctl_w) AM_SHARE("tms5110_ctl") AM_RANGE(0x1ddf, 0x1ddf) AM_WRITE(cvs_tms5110_pdc_w) ADDRESS_MAP_END static ADDRESS_MAP_START( cvs_speech_cpu_io_map, AS_IO, 8, cvs_state ) /* romclk is much more probable, 393 Hz results in timing issues */ // AM_RANGE(S2650_SENSE_PORT, S2650_SENSE_PORT) AM_READ(cvs_393hz_clock_r) AM_RANGE(S2650_SENSE_PORT, S2650_SENSE_PORT) AM_READ(tms_clock_r) ADDRESS_MAP_END /************************************* * * Standard CVS port definitions * *************************************/ static INPUT_PORTS_START( cvs ) PORT_START("IN0") /* Matrix 0 */ PORT_BIT( 0x01, IP_ACTIVE_LOW, IPT_START1 ) PORT_BIT( 0x02, IP_ACTIVE_LOW, IPT_START2 ) PORT_BIT( 0x04, IP_ACTIVE_LOW, IPT_COIN2 ) PORT_BIT( 0x08, IP_ACTIVE_LOW, IPT_COIN1 ) PORT_BIT( 0x10, IP_ACTIVE_LOW, IPT_BUTTON1 ) PORT_COCKTAIL /* "Red button" */ PORT_BIT( 0x20, IP_ACTIVE_LOW, IPT_BUTTON1 ) /* "Red button" */ PORT_BIT( 0x40, IP_ACTIVE_LOW, IPT_UNKNOWN ) PORT_BIT( 0x80, IP_ACTIVE_LOW, IPT_UNKNOWN ) PORT_START("IN1") PORT_BIT( 0x01, IP_ACTIVE_LOW, IPT_BUTTON2 ) PORT_COCKTAIL /* "Green button" */ PORT_BIT( 0x02, IP_ACTIVE_LOW, IPT_BUTTON2 ) /* "Green button" */ PORT_BIT( 0x04, IP_ACTIVE_LOW, IPT_JOYSTICK_RIGHT ) PORT_COCKTAIL PORT_BIT( 0x08, IP_ACTIVE_LOW, IPT_JOYSTICK_LEFT ) PORT_COCKTAIL PORT_BIT( 0x10, IP_ACTIVE_LOW, IPT_JOYSTICK_RIGHT ) PORT_BIT( 0x20, IP_ACTIVE_LOW, IPT_JOYSTICK_LEFT ) PORT_BIT( 0x40, IP_ACTIVE_LOW, IPT_UNKNOWN ) PORT_BIT( 0x80, IP_ACTIVE_LOW, IPT_UNKNOWN ) PORT_START("IN2") PORT_BIT( 0x01, IP_ACTIVE_LOW, IPT_SERVICE1 ) /* not sure it's SERVICE1 : it uses "Coin B" coinage and doesn't say "CREDIT" */ PORT_BIT( 0xfe, IP_ACTIVE_LOW, IPT_UNKNOWN ) PORT_START("IN3") PORT_BIT( 0x01, IP_ACTIVE_LOW, IPT_UNKNOWN ) PORT_BIT( 0x02, IP_ACTIVE_LOW, IPT_UNKNOWN ) PORT_BIT( 0x04, IP_ACTIVE_LOW, IPT_JOYSTICK_UP ) PORT_COCKTAIL PORT_BIT( 0x08, IP_ACTIVE_LOW, IPT_JOYSTICK_DOWN ) PORT_COCKTAIL PORT_BIT( 0x10, IP_ACTIVE_LOW, IPT_JOYSTICK_UP ) PORT_BIT( 0x20, IP_ACTIVE_LOW, IPT_JOYSTICK_DOWN ) PORT_BIT( 0x40, IP_ACTIVE_LOW, IPT_UNKNOWN ) PORT_BIT( 0x80, IP_ACTIVE_LOW, IPT_UNKNOWN ) PORT_START("DSW3") PORT_DIPUNUSED( 0x01, IP_ACTIVE_HIGH ) /* can't tell if it's ACTIVE_HIGH or ACTIVE_LOW */ PORT_DIPUNUSED( 0x02, IP_ACTIVE_HIGH ) /* can't tell if it's ACTIVE_HIGH or ACTIVE_LOW */ PORT_DIPUNUSED( 0x04, IP_ACTIVE_HIGH ) /* can't tell if it's ACTIVE_HIGH or ACTIVE_LOW */ PORT_DIPUNUSED( 0x08, IP_ACTIVE_HIGH ) /* can't tell if it's ACTIVE_HIGH or ACTIVE_LOW */ PORT_DIPNAME( 0x10, 0x00, DEF_STR( Cabinet ) ) PORT_DIPSETTING( 0x00, DEF_STR( Upright ) ) PORT_DIPSETTING( 0x10, DEF_STR( Cocktail ) ) PORT_DIPUNUSED( 0x20, IP_ACTIVE_HIGH ) /* can't tell if it's ACTIVE_HIGH or ACTIVE_LOW */ PORT_START("DSW2") PORT_DIPNAME( 0x03, 0x00, DEF_STR( Coin_A ) ) PORT_DIPSETTING( 0x03, DEF_STR( 4C_1C ) ) PORT_DIPSETTING( 0x01, DEF_STR( 3C_1C ) ) PORT_DIPSETTING( 0x02, DEF_STR( 2C_1C ) ) PORT_DIPSETTING( 0x00, DEF_STR( 1C_1C ) ) PORT_DIPNAME( 0x0c, 0x0c, DEF_STR( Coin_B ) ) PORT_DIPSETTING( 0x0c, DEF_STR( 1C_2C ) ) PORT_DIPSETTING( 0x04, DEF_STR( 1C_3C ) ) PORT_DIPSETTING( 0x08, DEF_STR( 1C_4C ) ) PORT_DIPSETTING( 0x00, DEF_STR( 1C_5C ) ) PORT_DIPNAME( 0x10, 0x00, DEF_STR( Lives ) ) PORT_DIPSETTING( 0x00, "3" ) PORT_DIPSETTING( 0x10, "5" ) PORT_DIPUNUSED( 0x20, IP_ACTIVE_HIGH ) /* can't tell if it's ACTIVE_HIGH or ACTIVE_LOW */ PORT_START("SENSE") PORT_BIT( 0x80, IP_ACTIVE_HIGH, IPT_CUSTOM ) PORT_VBLANK("screen") INPUT_PORTS_END static INPUT_PORTS_START( cvs_registration ) PORT_INCLUDE(cvs) PORT_MODIFY("DSW3") PORT_DIPNAME( 0x01, 0x01, "Registration" ) /* can't tell what shall be the default value */ PORT_DIPSETTING( 0x00, DEF_STR( Off ) ) PORT_DIPSETTING( 0x01, DEF_STR( On ) ) PORT_DIPNAME( 0x02, 0x02, "Registration Length" ) /* can't tell what shall be the default value */ PORT_DIPSETTING( 0x02, "3" ) PORT_DIPSETTING( 0x00, "10" ) /* bits 2 and 3 determine bonus life settings but they might change from game to game - they are sometimes unused */ PORT_MODIFY("DSW2") /* Told to be "Meter Pulses" but I don't know what this means */ PORT_DIPNAME( 0x20, 0x00, DEF_STR( Unknown ) ) /* has an effect when COIN2 is pressed (when COIN1 is pressed, value always 1 */ PORT_DIPSETTING( 0x00, "2" ) PORT_DIPSETTING( 0x20, "5" ) INPUT_PORTS_END /************************************* * * Games port definitions * *************************************/ static INPUT_PORTS_START( cosmos ) PORT_INCLUDE(cvs) #if !CVS_SHOW_ALL_INPUTS PORT_MODIFY("IN2") PORT_BIT( 0x01, IP_ACTIVE_LOW, IPT_UNUSED ) /* IPT_SERVICE1 */ PORT_MODIFY("IN3") PORT_BIT( 0x04, IP_ACTIVE_LOW, IPT_UNUSED ) /* IPT_JOYSTICK_UP PORT_COCKTAIL */ PORT_BIT( 0x08, IP_ACTIVE_LOW, IPT_UNUSED ) /* IPT_JOYSTICK_DOWN PORT_COCKTAIL */ PORT_BIT( 0x10, IP_ACTIVE_LOW, IPT_UNUSED ) /* IPT_JOYSTICK_UP */ PORT_BIT( 0x20, IP_ACTIVE_LOW, IPT_UNUSED ) /* IPT_JOYSTICK_DOWN */ #endif PORT_MODIFY("DSW3") /* DSW3 bits 0 and 1 stored at 0x7d55 (0, 2, 1, 3) - code at 0x66f3 - not read back */ PORT_DIPNAME( 0x0c, 0x0c, DEF_STR( Bonus_Life ) ) PORT_DIPSETTING( 0x0c, "10k only" ) /* displays "10000" */ PORT_DIPSETTING( 0x08, "20k only" ) /* displays "20000" */ PORT_DIPSETTING( 0x04, "30k only" ) /* displays "30000" */ PORT_DIPSETTING( 0x00, "40k only" ) /* displays "40000" */ INPUT_PORTS_END static INPUT_PORTS_START( darkwar ) PORT_INCLUDE(cvs) #if !CVS_SHOW_ALL_INPUTS PORT_MODIFY("IN1") PORT_BIT( 0x01, IP_ACTIVE_LOW, IPT_UNUSED ) /* IPT_BUTTON2 PORT_COCKTAIL */ PORT_BIT( 0x02, IP_ACTIVE_LOW, IPT_UNUSED ) /* IPT_BUTTON2 */ PORT_MODIFY("IN2") PORT_BIT( 0x01, IP_ACTIVE_LOW, IPT_UNUSED ) /* IPT_SERVICE1 */ PORT_MODIFY("IN3") PORT_BIT( 0x04, IP_ACTIVE_LOW, IPT_UNUSED ) /* IPT_JOYSTICK_UP PORT_COCKTAIL */ PORT_BIT( 0x08, IP_ACTIVE_LOW, IPT_UNUSED ) /* IPT_JOYSTICK_DOWN PORT_COCKTAIL */ PORT_BIT( 0x10, IP_ACTIVE_LOW, IPT_UNUSED ) /* IPT_JOYSTICK_UP */ PORT_BIT( 0x20, IP_ACTIVE_LOW, IPT_UNUSED ) /* IPT_JOYSTICK_DOWN */ #endif /* DSW3 bits 0 to 3 are not read */ INPUT_PORTS_END static INPUT_PORTS_START( spacefrt ) PORT_INCLUDE(cvs) #if !CVS_SHOW_ALL_INPUTS PORT_MODIFY("IN2") PORT_BIT( 0x01, IP_ACTIVE_LOW, IPT_UNUSED ) /* IPT_SERVICE1 */ PORT_MODIFY("IN3") PORT_BIT( 0x04, IP_ACTIVE_LOW, IPT_UNUSED ) /* IPT_JOYSTICK_UP PORT_COCKTAIL */ PORT_BIT( 0x08, IP_ACTIVE_LOW, IPT_UNUSED ) /* IPT_JOYSTICK_DOWN PORT_COCKTAIL */ PORT_BIT( 0x10, IP_ACTIVE_LOW, IPT_UNUSED ) /* IPT_JOYSTICK_UP */ PORT_BIT( 0x20, IP_ACTIVE_LOW, IPT_UNUSED ) /* IPT_JOYSTICK_DOWN */ #endif PORT_MODIFY("DSW3") /* DSW3 bits 0 and 1 stored at 0x7d3f (0, 2, 1, 3) - code at 0x6895 - not read back */ PORT_DIPNAME( 0x0c, 0x0c, DEF_STR( Bonus_Life ) ) PORT_DIPSETTING( 0x0c, "100k only" ) /* displays "50000" */ PORT_DIPSETTING( 0x08, "150k only" ) /* displays "110000" */ PORT_DIPSETTING( 0x04, "200k only" ) /* displays "200000" */ PORT_DIPSETTING( 0x00, DEF_STR( None ) ) /* displays "200000" */ INPUT_PORTS_END static INPUT_PORTS_START( 8ball ) PORT_INCLUDE(cvs_registration) #if !CVS_SHOW_ALL_INPUTS PORT_MODIFY("IN1") PORT_BIT( 0x01, IP_ACTIVE_LOW, IPT_UNUSED ) /* IPT_BUTTON2 PORT_COCKTAIL */ PORT_BIT( 0x02, IP_ACTIVE_LOW, IPT_UNUSED ) /* IPT_BUTTON2 */ #endif PORT_MODIFY("DSW3") PORT_DIPNAME( 0x0c, 0x0c, DEF_STR( Bonus_Life ) ) PORT_DIPSETTING( 0x0c, "10k only" ) /* displays "10000" */ PORT_DIPSETTING( 0x08, "20k only" ) /* displays "20000" */ PORT_DIPSETTING( 0x04, "40k only" ) /* displays "80000" */ PORT_DIPSETTING( 0x00, "80k only" ) /* displays "80000" */ PORT_DIPNAME( 0x20, 0x00, "Colors" ) /* stored at 0x1ed4 - code at 0x0847 ('8ball') or 0x08af ('8ball1') */ PORT_DIPSETTING( 0x00, "Palette 1" ) /* table at 0x0781 ('8ball') or 0x07e9 ('8ball1') - 16 bytes */ PORT_DIPSETTING( 0x20, "Palette 2" ) /* table at 0x0791 ('8ball') or 0x07f9 ('8ball1') - 16 bytes */ /* DSW2 bit 5 stored at 0x1d93 - code at 0x0858 ('8ball') or 0x08c0 ('8ball1') - read back code at 0x0073 */ INPUT_PORTS_END static INPUT_PORTS_START( logger ) PORT_INCLUDE(cvs_registration) #if !CVS_SHOW_ALL_INPUTS PORT_MODIFY("IN1") PORT_BIT( 0x01, IP_ACTIVE_LOW, IPT_UNUSED ) /* IPT_BUTTON2 PORT_COCKTAIL */ PORT_BIT( 0x02, IP_ACTIVE_LOW, IPT_UNUSED ) /* IPT_BUTTON2 */ #endif PORT_MODIFY("DSW3") PORT_DIPNAME( 0x0c, 0x0c, DEF_STR( Bonus_Life ) ) PORT_DIPSETTING( 0x0c, "10k only" ) /* displays "10000" */ PORT_DIPSETTING( 0x08, "20k only" ) /* displays "20000" */ PORT_DIPSETTING( 0x04, "40k only" ) /* displays "40000" */ PORT_DIPSETTING( 0x00, "80k only" ) /* displays "80000" */ /* DSW3 bit 5 stored at 0x7dc8 - code at 0x6eb6 - not read back */ /* DSW2 bit 5 stored at 0x7da1 - code at 0x6ec7 - read back code at 0x0073 */ INPUT_PORTS_END static INPUT_PORTS_START( dazzler ) PORT_INCLUDE(cvs_registration) #if !CVS_SHOW_ALL_INPUTS PORT_MODIFY("IN1") PORT_BIT( 0x01, IP_ACTIVE_LOW, IPT_UNUSED ) /* IPT_BUTTON2 PORT_COCKTAIL */ PORT_BIT( 0x02, IP_ACTIVE_LOW, IPT_UNUSED ) /* IPT_BUTTON2 */ #endif PORT_MODIFY("DSW3") PORT_DIPNAME( 0x0c, 0x0c, DEF_STR( Bonus_Life ) ) PORT_DIPSETTING( 0x0c, "10k only" ) /* displays "10000" */ PORT_DIPSETTING( 0x04, "20k only" ) /* displays "20000" */ PORT_DIPSETTING( 0x08, "40k only" ) /* displays "40000" */ PORT_DIPSETTING( 0x00, "80k only" ) /* displays "80000" */ /* DSW2 bit 5 stored at 0x7d9c - code at 0x6b51 - read back code at 0x0099 */ INPUT_PORTS_END static INPUT_PORTS_START( wallst ) PORT_INCLUDE(cvs_registration) #if !CVS_SHOW_ALL_INPUTS PORT_MODIFY("IN1") PORT_BIT( 0x01, IP_ACTIVE_LOW, IPT_UNUSED ) /* IPT_BUTTON2 PORT_COCKTAIL */ PORT_BIT( 0x02, IP_ACTIVE_LOW, IPT_UNUSED ) /* IPT_BUTTON2 */ #endif PORT_MODIFY("DSW3") PORT_DIPNAME( 0x0c, 0x0c, DEF_STR( Bonus_Life ) ) PORT_DIPSETTING( 0x0c, "10k only" ) /* displays "10000" */ PORT_DIPSETTING( 0x04, "20k only" ) /* displays "20000" */ PORT_DIPSETTING( 0x08, "40k only" ) /* displays "40000" */ PORT_DIPSETTING( 0x00, "80k only" ) /* displays "80000" */ /* DSW2 bit 5 stored at 0x1e95 - code at 0x1232 - read back code at 0x6054 */ INPUT_PORTS_END static INPUT_PORTS_START( radarzon ) PORT_INCLUDE(cvs_registration) #if !CVS_SHOW_ALL_INPUTS PORT_MODIFY("IN1") PORT_BIT( 0x01, IP_ACTIVE_LOW, IPT_UNUSED ) /* IPT_BUTTON2 PORT_COCKTAIL */ PORT_BIT( 0x02, IP_ACTIVE_LOW, IPT_UNUSED ) /* IPT_BUTTON2 */ #endif PORT_MODIFY("DSW3") PORT_DIPNAME( 0x0c, 0x0c, DEF_STR( Bonus_Life ) ) PORT_DIPSETTING( 0x0c, "100k only" ) /* displays "100000" */ PORT_DIPSETTING( 0x04, "200k only" ) /* displays "200000" */ PORT_DIPSETTING( 0x08, "400k only" ) /* displays "400000" */ PORT_DIPSETTING( 0x00, "800k only" ) /* displays "800000" */ /* DSW2 bit 5 stored at 0x3d6e - code at 0x22aa - read back code at 0x00e4 */ INPUT_PORTS_END static INPUT_PORTS_START( goldbug ) PORT_INCLUDE(cvs_registration) #if !CVS_SHOW_ALL_INPUTS PORT_MODIFY("IN1") PORT_BIT( 0x01, IP_ACTIVE_LOW, IPT_UNUSED ) /* IPT_BUTTON2 PORT_COCKTAIL */ PORT_BIT( 0x02, IP_ACTIVE_LOW, IPT_UNUSED ) /* IPT_BUTTON2 */ #endif PORT_MODIFY("DSW3") PORT_DIPNAME( 0x0c, 0x0c, DEF_STR( Bonus_Life ) ) PORT_DIPSETTING( 0x0c, "100k only" ) /* displays "100000" */ PORT_DIPSETTING( 0x04, "200k only" ) /* displays "200000" */ PORT_DIPSETTING( 0x08, "400k only" ) /* displays "400000" */ PORT_DIPSETTING( 0x00, "800k only" ) /* displays "800000" */ /* DSW2 bit 5 stored at 0x3d89 - code at 0x3377 - read back code at 0x6054 */ INPUT_PORTS_END static INPUT_PORTS_START( diggerc ) PORT_INCLUDE(cvs_registration) #if !CVS_SHOW_ALL_INPUTS PORT_MODIFY("IN1") PORT_BIT( 0x01, IP_ACTIVE_LOW, IPT_UNUSED ) /* IPT_BUTTON2 PORT_COCKTAIL */ PORT_BIT( 0x02, IP_ACTIVE_LOW, IPT_UNUSED ) /* IPT_BUTTON2 */ #endif PORT_MODIFY("DSW3") PORT_DIPNAME( 0x0c, 0x0c, DEF_STR( Bonus_Life ) ) PORT_DIPSETTING( 0x0c, "50k only" ) /* displays "50000" */ PORT_DIPSETTING( 0x04, "100k only" ) /* displays "100000" */ PORT_DIPSETTING( 0x08, "150k only" ) /* displays "150000" */ PORT_DIPSETTING( 0x00, "200k only" ) /* displays "200000" */ /* DSW2 bit 5 stored at 0x3db3 - code at 0x22ad - read back code at 0x00e4 */ INPUT_PORTS_END static INPUT_PORTS_START( heartatk ) PORT_INCLUDE(cvs_registration) /* DSW3 bits 2 and 3 stored at 0x1c61 (0, 2, 1, 3) - code at 0x0c52 read back code at 0x2197 but untested value : bonus life always at 100000 */ /* DSW2 bit 5 stored at 0x1e76 - code at 0x0c5c - read back code at 0x00e4 */ INPUT_PORTS_END static INPUT_PORTS_START( hunchbak ) PORT_INCLUDE(cvs_registration) #if !CVS_SHOW_ALL_INPUTS PORT_MODIFY("IN1") PORT_BIT( 0x01, IP_ACTIVE_LOW, IPT_UNUSED ) /* IPT_BUTTON2 PORT_COCKTAIL */ PORT_BIT( 0x02, IP_ACTIVE_LOW, IPT_UNUSED ) /* IPT_BUTTON2 */ PORT_MODIFY("IN3") PORT_BIT( 0x04, IP_ACTIVE_LOW, IPT_UNUSED ) /* IPT_JOYSTICK_UP PORT_COCKTAIL */ PORT_BIT( 0x08, IP_ACTIVE_LOW, IPT_UNUSED ) /* IPT_JOYSTICK_DOWN PORT_COCKTAIL */ PORT_BIT( 0x10, IP_ACTIVE_LOW, IPT_UNUSED ) /* IPT_JOYSTICK_UP */ PORT_BIT( 0x20, IP_ACTIVE_LOW, IPT_UNUSED ) /* IPT_JOYSTICK_DOWN */ #endif PORT_MODIFY("DSW3") PORT_DIPNAME( 0x0c, 0x0c, DEF_STR( Bonus_Life ) ) PORT_DIPSETTING( 0x0c, "10k only" ) /* displays "10000" */ PORT_DIPSETTING( 0x04, "20k only" ) /* displays "20000" */ PORT_DIPSETTING( 0x08, "40k only" ) /* displays "40000" */ PORT_DIPSETTING( 0x00, "80k only" ) /* displays "80000" */ /* hunchbak : DSW2 bit 5 stored at 0x5e97 - code at 0x516c - read back code at 0x6054 */ /* hunchbaka : DSW2 bit 5 stored at 0x1e97 - code at 0x0c0c - read back code at 0x6054 */ INPUT_PORTS_END static INPUT_PORTS_START( superbik ) PORT_INCLUDE(cvs_registration) /* DSW3 bits 2 and 3 are not read : bonus life alaways at 5000 */ /* DSW2 bit 5 stored at 0x1e79 - code at 0x060f - read back code at 0x25bf */ INPUT_PORTS_END static INPUT_PORTS_START( raiders ) PORT_INCLUDE(cvs_registration) /* DSW3 bits 2 and 3 are not read : bonus life alaways at 100000 */ PORT_MODIFY("DSW2") PORT_DIPUNUSED( 0x10, IP_ACTIVE_HIGH ) /* always 4 lives - table at 0x4218 - 2 bytes */ /* DSW2 bit 5 stored at 0x1e79 - code at 0x1307 - read back code at 0x251d */ INPUT_PORTS_END static INPUT_PORTS_START( hero ) PORT_INCLUDE(cvs_registration) #if !CVS_SHOW_ALL_INPUTS PORT_MODIFY("IN1") PORT_BIT( 0x01, IP_ACTIVE_LOW, IPT_UNUSED ) /* IPT_BUTTON2 PORT_COCKTAIL */ PORT_BIT( 0x02, IP_ACTIVE_LOW, IPT_UNUSED ) /* IPT_BUTTON2 */ #endif /* DSW3 bits 2 and 3 are not read : bonus life alaways at 150000 */ PORT_MODIFY("DSW2") PORT_DIPUNUSED( 0x10, IP_ACTIVE_HIGH ) /* always 3 lives - table at 0x4ebb - 2 bytes */ /* DSW2 bit 5 stored at 0x1e99 - code at 0x0fdd - read back code at 0x0352 */ INPUT_PORTS_END static INPUT_PORTS_START( huncholy ) PORT_INCLUDE(cvs_registration) #if !CVS_SHOW_ALL_INPUTS PORT_MODIFY("IN1") PORT_BIT( 0x01, IP_ACTIVE_LOW, IPT_UNUSED ) /* IPT_BUTTON2 PORT_COCKTAIL */ PORT_BIT( 0x02, IP_ACTIVE_LOW, IPT_UNUSED ) /* IPT_BUTTON2 */ #endif /* DSW3 bits 2 and 3 are not read : bonus life alaways at 20000 */ PORT_MODIFY("DSW2") PORT_DIPUNUSED( 0x10, IP_ACTIVE_HIGH ) /* always 3 lives - table at 0x4531 - 2 bytes */ /* DSW2 bit 5 stored at 0x1e7c - code at 0x067d - read back code at 0x2f95 */ INPUT_PORTS_END /************************************* * * Graphics definitions * *************************************/ static const gfx_layout charlayout = { 8,8, /* 8*8 characters */ 256, /* 256 characters */ 3, /* 3 bits per pixel */ { 0, 0x800*8, 0x1000*8 }, /* the bitplanes are separated */ { 0, 1, 2, 3, 4, 5, 6, 7 }, { 0*8, 1*8, 2*8, 3*8, 4*8, 5*8, 6*8, 7*8 }, 8*8 /* every char takes 8 consecutive bytes */ }; static GFXDECODE_START( cvs ) GFXDECODE_ENTRY( "gfx1", 0x0000, charlayout, 0, 256+4 ) GFXDECODE_ENTRY( nullptr, 0x0000, charlayout, 0, 256+4 ) GFXDECODE_END /************************************* * * Machine driver * *************************************/ MACHINE_START_MEMBER(cvs_state,cvs) { /* allocate memory */ if (m_gfxdecode->gfx(1) != nullptr) m_gfxdecode->gfx(1)->set_source(m_character_ram); start_393hz_timer(); /* register state save */ save_item(NAME(m_color_ram)); save_item(NAME(m_palette_ram)); save_item(NAME(m_character_ram)); save_item(NAME(m_character_banking_mode)); save_item(NAME(m_character_ram_page_start)); save_item(NAME(m_speech_rom_bit_address)); save_item(NAME(m_s2650_flag)); save_item(NAME(m_cvs_393hz_clock)); save_item(NAME(m_collision_register)); save_item(NAME(m_total_stars)); save_item(NAME(m_stars_on)); save_item(NAME(m_scroll_reg)); save_item(NAME(m_stars_scroll)); } MACHINE_RESET_MEMBER(cvs_state,cvs) { m_character_banking_mode = 0; m_character_ram_page_start = 0; m_speech_rom_bit_address = 0; m_cvs_393hz_clock = 0; m_collision_register = 0; m_stars_on = 0; m_scroll_reg = 0; m_stars_scroll = 0; } static MACHINE_CONFIG_START( cvs, cvs_state ) /* basic machine hardware */ MCFG_CPU_ADD("maincpu", S2650, XTAL_14_31818MHz/16) MCFG_CPU_PROGRAM_MAP(cvs_main_cpu_map) MCFG_CPU_IO_MAP(cvs_main_cpu_io_map) MCFG_CPU_VBLANK_INT_DRIVER("screen", cvs_state, cvs_main_cpu_interrupt) MCFG_S2650_FLAG_HANDLER(WRITELINE(cvs_state, write_s2650_flag)) MCFG_CPU_ADD("audiocpu", S2650, XTAL_14_31818MHz/16) MCFG_CPU_PROGRAM_MAP(cvs_dac_cpu_map) MCFG_CPU_IO_MAP(cvs_dac_cpu_io_map) MCFG_CPU_ADD("speechcpu", S2650, XTAL_14_31818MHz/16) MCFG_CPU_PROGRAM_MAP(cvs_speech_cpu_map) MCFG_CPU_IO_MAP(cvs_speech_cpu_io_map) MCFG_MACHINE_START_OVERRIDE(cvs_state,cvs) MCFG_MACHINE_RESET_OVERRIDE(cvs_state,cvs) /* video hardware */ MCFG_VIDEO_START_OVERRIDE(cvs_state,cvs) MCFG_GFXDECODE_ADD("gfxdecode", "palette", cvs) MCFG_PALETTE_ADD("palette", (256+4)*8+8+1) MCFG_PALETTE_INDIRECT_ENTRIES(16) MCFG_PALETTE_INIT_OWNER(cvs_state,cvs) MCFG_SCREEN_ADD("screen", RASTER) MCFG_SCREEN_VIDEO_ATTRIBUTES(VIDEO_ALWAYS_UPDATE) MCFG_SCREEN_SIZE(32*8, 32*8) MCFG_SCREEN_VISIBLE_AREA(0*8, 30*8-1, 1*8, 32*8-1) MCFG_SCREEN_REFRESH_RATE(60) MCFG_SCREEN_VBLANK_TIME(ATTOSECONDS_IN_USEC(1000)) MCFG_SCREEN_UPDATE_DRIVER(cvs_state, screen_update_cvs) MCFG_SCREEN_PALETTE("palette") MCFG_DEVICE_ADD("s2636_0", S2636, 0) MCFG_S2636_OFFSETS(CVS_S2636_Y_OFFSET, CVS_S2636_X_OFFSET) MCFG_DEVICE_ADD("s2636_1", S2636, 0) MCFG_S2636_OFFSETS(CVS_S2636_Y_OFFSET, CVS_S2636_X_OFFSET) MCFG_DEVICE_ADD("s2636_2", S2636, 0) MCFG_S2636_OFFSETS(CVS_S2636_Y_OFFSET, CVS_S2636_X_OFFSET) /* audio hardware */ MCFG_SPEAKER_STANDARD_MONO("mono") MCFG_DAC_ADD("dac1") MCFG_SOUND_ROUTE(ALL_OUTPUTS, "mono", 1.0) //MCFG_DAC_ADD("dac1a") //MCFG_SOUND_ROUTE(ALL_OUTPUTS, "mono", 1.0) MCFG_DAC_ADD("dac2") MCFG_SOUND_ROUTE(ALL_OUTPUTS, "mono", 1.0) MCFG_DAC_ADD("dac3") MCFG_SOUND_ROUTE(ALL_OUTPUTS, "mono", 1.0) MCFG_SOUND_ADD("tms", TMS5100, XTAL_640kHz) MCFG_TMS5110_DATA_CB(READLINE(cvs_state, speech_rom_read_bit)) MCFG_SOUND_ROUTE(ALL_OUTPUTS, "mono", 1.0) MACHINE_CONFIG_END /************************************* * * ROM definitions * *************************************/ #define CVS_COMMON_ROMS \ ROM_REGION( 0x8000, "speechcpu", 0 ) \ ROM_LOAD( "5b.bin", 0x0000, 0x0800, CRC(f055a624) SHA1(5dfe89d7271092e665cdd5cd59d15a2b70f92f43) ) \ \ ROM_REGION( 0x0820, "proms", 0 ) \ ROM_LOAD( "82s185.10h", 0x0000, 0x0800, CRC(c205bca6) SHA1(ec9bd220e75f7b067ede6139763ef8aca0fb7a29) ) \ ROM_LOAD( "82s123.10k", 0x0800, 0x0020, CRC(b5221cec) SHA1(71d9830b33b1a8140b0fe1a2ba8024ba8e6e48e0) ) #define CVS_ROM_REGION_SPEECH_DATA(name, len, hash) \ ROM_REGION( 0x1000, "speechdata", 0 ) \ ROM_LOAD( name, 0x0000, len, hash ) #define ROM_LOAD_STAGGERED(name, offs, hash) \ ROM_LOAD( name, 0x0000 + offs, 0x0400, hash ) \ ROM_CONTINUE( 0x2000 + offs, 0x0400 ) \ ROM_CONTINUE( 0x4000 + offs, 0x0400 ) \ ROM_CONTINUE( 0x6000 + offs, 0x0400 ) ROM_START( huncholy ) ROM_REGION( 0x8000, "maincpu", 0 ) ROM_LOAD_STAGGERED( "ho-gp1.bin", 0x0000, CRC(4f17cda7) SHA1(ae6fe495c723042c6e060d4ada50aaef1019d5eb) ) ROM_LOAD_STAGGERED( "ho-gp2.bin", 0x0400, CRC(70fa52c7) SHA1(179813fdc204870d72c0bfa8cd5dbf277e1f67c4) ) ROM_LOAD_STAGGERED( "ho-gp3.bin", 0x0800, CRC(931934b1) SHA1(08fe5ad3459862246e9ea845abab4e01e1dbd62d) ) ROM_LOAD_STAGGERED( "ho-gp4.bin", 0x0c00, CRC(af5cd501) SHA1(9a79b173aa41a82faa9f19210d3e18bfa6c593fa) ) ROM_LOAD_STAGGERED( "ho-gp5.bin", 0x1000, CRC(658e8974) SHA1(30d0ada1cce99a842bad8f5a58630bc1b7048b03) ) ROM_REGION( 0x8000, "audiocpu", 0 ) ROM_LOAD( "ho-sdp1.bin", 0x0000, 0x1000, CRC(3efb3ffd) SHA1(be4807c8b4fe23f2247aa3b6ac02285bee1a0520) ) CVS_ROM_REGION_SPEECH_DATA( "ho-sp1.bin", 0x1000, CRC(3fd39b1e) SHA1(f5d0b2cfaeda994762403f039a6f7933c5525234) ) ROM_REGION( 0x1800, "gfx1", 0 ) ROM_LOAD( "ho-cp1.bin", 0x0000, 0x0800, CRC(c6c73d46) SHA1(63aba92f77105fedf46337b591b074020bec05d0) ) ROM_LOAD( "ho-cp2.bin", 0x0800, 0x0800, CRC(e596371c) SHA1(93a0d0ccdf830ae72d070b03b7e2222f4a737ead) ) ROM_LOAD( "ho-cp3.bin", 0x1000, 0x0800, CRC(11fae1cf) SHA1(5ceabfb1ff1a6f76d1649512f57d7151f5258ecb) ) CVS_COMMON_ROMS ROM_END ROM_START( darkwar ) ROM_REGION( 0x8000, "maincpu", 0 ) ROM_LOAD_STAGGERED( "dw-gp1.bin", 0x0000, CRC(f10ccf24) SHA1(f694a9016fc935798e5342598e4fd60fbdbc2829) ) ROM_LOAD_STAGGERED( "dw-gp2.bin", 0x0400, CRC(b77d0483) SHA1(47d126b9ceaf07267c9078a342a860295320b01c) ) ROM_LOAD_STAGGERED( "dw-gp3.bin", 0x0800, CRC(c01c3281) SHA1(3c272f424f8a35d08b58f203718b579c1abbe63f) ) ROM_LOAD_STAGGERED( "dw-gp4.bin", 0x0c00, CRC(0b0bffaf) SHA1(48db78d86dc249fb4d7d93b79b2ac269a0c6698e) ) ROM_LOAD_STAGGERED( "dw-gp5.bin", 0x1000, CRC(7fdbcaff) SHA1(db80d0d8690105ca72df359c1dc1a43952709111) ) ROM_REGION( 0x8000, "audiocpu", 0 ) ROM_LOAD( "dw-sdp1.bin", 0x0000, 0x0800, CRC(b385b669) SHA1(79621d3fb3eb4ea6fa8a733faa6f21edeacae186) ) CVS_ROM_REGION_SPEECH_DATA( "dw-sp1.bin", 0x1000, CRC(ce815074) SHA1(105f24fb776131b30e35488cca29954298559518) ) ROM_REGION( 0x1800, "gfx1", 0 ) ROM_LOAD( "dw-cp1.bin", 0x0000, 0x0800, CRC(7a0f9f3e) SHA1(0aa787923fbb614f15016d99c03093a59a0bfb88) ) ROM_LOAD( "dw-cp2.bin", 0x0800, 0x0800, CRC(232e5120) SHA1(76e4d6d17e8108306761604bd56d6269bfc431e1) ) ROM_LOAD( "dw-cp3.bin", 0x1000, 0x0800, CRC(573e0a17) SHA1(9c7991eac625b287bafb6cf722ffb405a9627e09) ) CVS_COMMON_ROMS ROM_END ROM_START( 8ball ) ROM_REGION( 0x8000, "maincpu", 0 ) ROM_LOAD_STAGGERED( "8b-gp1.bin", 0x0000, CRC(1b4fb37f) SHA1(df6dd2766a3b70eec0bde0ae1932b35abdab3735) ) ROM_LOAD_STAGGERED( "8b-gp2.bin", 0x0400, CRC(f193cdb5) SHA1(54fd1a10c1b9da0f9c4d190f95acc11b3c6e7907) ) ROM_LOAD_STAGGERED( "8b-gp3.bin", 0x0800, CRC(191989bf) SHA1(dea129a4ed06aac453ab1fbbfae14d8048ef270d) ) ROM_LOAD_STAGGERED( "8b-gp4.bin", 0x0c00, CRC(9c64519e) SHA1(9a5cad7ccf8f1f289da9a6de0edd4e6d4f0b12fb) ) ROM_LOAD_STAGGERED( "8b-gp5.bin", 0x1000, CRC(c50d0f9d) SHA1(31b6ea6282fec96d9d2fb74129a215d10f12cc9b) ) ROM_REGION( 0x8000, "audiocpu", 0 ) ROM_LOAD( "8b-sdp1.bin", 0x0000, 0x1000, CRC(a571daf4) SHA1(0db5b95db9da27216bbfa8fff84491a7755f9f1a) ) CVS_ROM_REGION_SPEECH_DATA( "8b-sp1.bin", 0x0800, CRC(1ee167f3) SHA1(40c876a60832456a27108252ba0b9963f9fe70b0) ) ROM_REGION( 0x1800, "gfx1", 0 ) ROM_LOAD( "8b-cp1.bin", 0x0000, 0x0800, CRC(c1f68754) SHA1(481c8e3dc35300f779b7925fa8a54320688dac54) ) ROM_LOAD( "8b-cp2.bin", 0x0800, 0x0800, CRC(6ec1d711) SHA1(768df8e621a7b110a963c93402ee01b1c9009286) ) ROM_LOAD( "8b-cp3.bin", 0x1000, 0x0800, CRC(4a9afce4) SHA1(187e5106aa2d0bdebf6ec9f2b7c2c2f67d47d221) ) CVS_COMMON_ROMS ROM_END ROM_START( 8ball1 ) ROM_REGION( 0x8000, "maincpu", 0 ) ROM_LOAD_STAGGERED( "8a-gp1.bin", 0x0000, CRC(b5d3b763) SHA1(23a01bcbd536ba7f773934ea9dedc7dd9f698100) ) ROM_LOAD_STAGGERED( "8a-gp2.bin", 0x0400, CRC(5e4aa61a) SHA1(aefa79b4c63d1ac5cb000f2c7c5d06e85d58a547) ) ROM_LOAD_STAGGERED( "8a-gp3.bin", 0x0800, CRC(3dc272fe) SHA1(303184f7c3557be91d6b8e62a9685080444a78c5) ) ROM_LOAD_STAGGERED( "8a-gp4.bin", 0x0c00, CRC(33afedbf) SHA1(857c743fd81fbd439c204b6adb251db68465cfc3) ) ROM_LOAD_STAGGERED( "8a-gp5.bin", 0x1000, CRC(b8b3f373) SHA1(e808db4dcac6d8a454e20b561bb4f3a3bb9c6200) ) ROM_REGION( 0x8000, "audiocpu", 0 ) ROM_LOAD( "8b-sdp1.bin", 0x0000, 0x1000, CRC(a571daf4) SHA1(0db5b95db9da27216bbfa8fff84491a7755f9f1a) ) CVS_ROM_REGION_SPEECH_DATA( "8b-sp1.bin", 0x0800, CRC(1ee167f3) SHA1(40c876a60832456a27108252ba0b9963f9fe70b0) ) ROM_REGION( 0x1800, "gfx1", 0 ) ROM_LOAD( "8a-cp1.bin", 0x0000, 0x0800, CRC(d9b36c16) SHA1(dbb496102fa2344f19b5d9a3eecdb29c433e4c08) ) ROM_LOAD( "8a-cp2.bin", 0x0800, 0x0800, CRC(6f66f0ff) SHA1(1e91474973356e97f89b4d9093565747a8331f50) ) ROM_LOAD( "8a-cp3.bin", 0x1000, 0x0800, CRC(baee8b17) SHA1(9f86f1d5903aeead17cc75dac8a2b892bb375dad) ) CVS_COMMON_ROMS ROM_END ROM_START( hunchbak ) // actual ROM label has "Century Elect. Ltd. (c)1981", and some label has HB/HB2 handwritten ROM_REGION( 0x8000, "maincpu", 0 ) ROM_LOAD_STAGGERED( "hb-gp1.bin", 0x0000, CRC(af801d54) SHA1(68e31561e98f7e2caa337dd764941d08f075b559) ) ROM_LOAD_STAGGERED( "hb-gp2.bin", 0x0400, CRC(b448cc8e) SHA1(ed94f662c0e08a3a0aca073fbec29ae1fbd0328e) ) ROM_LOAD_STAGGERED( "hb-gp3.bin", 0x0800, CRC(57c6ea7b) SHA1(8c3ba01ab1917a8c24180ed1c0011dbfed36d406) ) ROM_LOAD_STAGGERED( "hb-gp4.bin", 0x0c00, CRC(7f91287b) SHA1(9383d885c142417de73879905cbce272ba9514c7) ) ROM_LOAD_STAGGERED( "hb-gp5.bin", 0x1000, CRC(1dd5755c) SHA1(b1e158d52bd9a238e3e32ed3024e495df2292dcb) ) ROM_REGION( 0x8000, "audiocpu", 0 ) ROM_LOAD( "6c.sdp1", 0x0000, 0x1000, CRC(f9ba2854) SHA1(d041198e2e8b8c3e668bd1610310f8d25c5b1119) ) CVS_ROM_REGION_SPEECH_DATA( "8a.sp1", 0x0800, CRC(ed1cd201) SHA1(6cc3842dda1bfddc06ffb436c55d14276286bd67) ) ROM_REGION( 0x1800, "gfx1", 0 ) ROM_LOAD( "11a.cp1", 0x0000, 0x0800, CRC(f256b047) SHA1(02d79882bad37ffdd58ef478e2658a1369c32ebc) ) ROM_LOAD( "10a.cp2", 0x0800, 0x0800, CRC(b870c64f) SHA1(ce4f8de87568782ce02bba754edff85df7f5c393) ) ROM_LOAD( "9a.cp3", 0x1000, 0x0800, CRC(9a7dab88) SHA1(cd39a9d4f982a7f49c478db1408d7e07335f2ddc) ) CVS_COMMON_ROMS ROM_END ROM_START( hunchbaka ) ROM_REGION( 0x8000, "maincpu", 0 ) ROM_LOAD_STAGGERED( "1b.gp1", 0x0000, CRC(c816860b) SHA1(1109639645496d4644564d21c816b8baf8c84cf7) ) ROM_LOAD_STAGGERED( "2a.gp2", 0x0400, CRC(cab1e524) SHA1(c3fd7ac9ce5893fd2602a15ad0f6e3267a4ca122) ) ROM_LOAD_STAGGERED( "3a.gp3", 0x0800, CRC(b2adcfeb) SHA1(3090e2c6b945857c1e48dea395015a05c6165cd9) ) ROM_LOAD_STAGGERED( "4c.gp4", 0x0c00, CRC(229a8b71) SHA1(ea3815eb69d4927da356eada0add8382735feb48) ) ROM_LOAD_STAGGERED( "5a.gp5", 0x1000, CRC(cb4f0313) SHA1(1ef63cbe62e7a54d45e0afbc398c9d9b601e6403) ) ROM_REGION( 0x8000, "audiocpu", 0 ) ROM_LOAD( "6c.sdp1", 0x0000, 0x1000, CRC(f9ba2854) SHA1(d041198e2e8b8c3e668bd1610310f8d25c5b1119) ) CVS_ROM_REGION_SPEECH_DATA( "8a.sp1", 0x0800, CRC(ed1cd201) SHA1(6cc3842dda1bfddc06ffb436c55d14276286bd67) ) ROM_REGION( 0x1800, "gfx1", 0 ) ROM_LOAD( "11a.cp1", 0x0000, 0x0800, CRC(f256b047) SHA1(02d79882bad37ffdd58ef478e2658a1369c32ebc) ) ROM_LOAD( "10a.cp2", 0x0800, 0x0800, CRC(b870c64f) SHA1(ce4f8de87568782ce02bba754edff85df7f5c393) ) ROM_LOAD( "9a.cp3", 0x1000, 0x0800, CRC(9a7dab88) SHA1(cd39a9d4f982a7f49c478db1408d7e07335f2ddc) ) CVS_COMMON_ROMS ROM_END ROM_START( wallst ) ROM_REGION( 0x8000, "maincpu", 0 ) ROM_LOAD_STAGGERED( "ws-gp1.bin", 0x0000, CRC(bdac81b6) SHA1(6ce865d8902e815742a9ecf10d6f9495f376dede) ) ROM_LOAD_STAGGERED( "ws-gp2.bin", 0x0400, CRC(9ca67cdd) SHA1(575a4d8d037d2a3c07a8f49d93c7cf6781349ec1) ) ROM_LOAD_STAGGERED( "ws-gp3.bin", 0x0800, CRC(c2f407f2) SHA1(8208064fd0138a6ccacf03275b8d28793245bfd9) ) ROM_LOAD_STAGGERED( "ws-gp4.bin", 0x0c00, CRC(1e4b2fe1) SHA1(28eda70cc9cf619452729092e68734ab1a5dc7fb) ) ROM_LOAD_STAGGERED( "ws-gp5.bin", 0x1000, CRC(eec7bfd0) SHA1(6485e9e2e1624118e38892e74f80431820fd9672) ) ROM_REGION( 0x8000, "audiocpu", 0 ) ROM_LOAD( "ws-sdp1.bin", 0x0000, 0x1000, CRC(faed2ac0) SHA1(c2c48e24a560d918531e5c17fb109d68bdec850f) ) CVS_ROM_REGION_SPEECH_DATA( "ws-sp1.bin", 0x0800, CRC(84b72637) SHA1(9c5834320f39545403839fb7088c37177a6c8861) ) ROM_REGION( 0x1800, "gfx1", 0 ) ROM_LOAD( "ws-cp1.bin", 0x0000, 0x0800, CRC(5aca11df) SHA1(5ef815b5b09445515ff8b958c4ea29f1a221cee1) ) ROM_LOAD( "ws-cp2.bin", 0x0800, 0x0800, CRC(ca530d85) SHA1(e5a78667c3583d06d8387848323b11e4a91091ec) ) ROM_LOAD( "ws-cp3.bin", 0x1000, 0x0800, CRC(1e0225d6) SHA1(410795046c64c24de6711b167315308808b54291) ) CVS_COMMON_ROMS ROM_END ROM_START( dazzler ) ROM_REGION( 0x8000, "maincpu", 0 ) ROM_LOAD_STAGGERED( "dz-gp1.bin", 0x0000, CRC(2c5d75de) SHA1(d121de662e95f2fc362e367cef57e5e70bafd197) ) ROM_LOAD_STAGGERED( "dz-gp2.bin", 0x0400, CRC(d0db80d6) SHA1(ca57d3a1d516e0afd750a8f05ae51d4ddee60ca0) ) ROM_LOAD_STAGGERED( "dz-gp3.bin", 0x0800, CRC(d5f07796) SHA1(110bb0e1613db3634513e8456770dd9d43ad7d34) ) ROM_LOAD_STAGGERED( "dz-gp4.bin", 0x0c00, CRC(84e41a46) SHA1(a1c1fd9ecacf3357f5c7916cf05dc0b79e975137) ) ROM_LOAD_STAGGERED( "dz-gp5.bin", 0x1000, CRC(2ae59c41) SHA1(a17e9535409e9e91c41f26a3543f44f20c1b07a5) ) ROM_REGION( 0x8000, "audiocpu", 0 ) ROM_LOAD( "dz-sdp1.bin", 0x0000, 0x1000, CRC(89847352) SHA1(54037a4d95958c4c3383467d7f4c2c9416b2eb4a) ) CVS_ROM_REGION_SPEECH_DATA( "dz-sp1.bin", 0x0800, CRC(25da1fc1) SHA1(c14717ec3399ce7dc47a9d42c8ac8f585db770e9) ) ROM_REGION( 0x1800, "gfx1", 0 ) ROM_LOAD( "dz-cp1.bin", 0x0000, 0x0800, CRC(0a8a9034) SHA1(9df3d4f387bd5ce3d3580ba678aeda1b65634ac2) ) ROM_LOAD( "dz-cp2.bin", 0x0800, 0x0800, CRC(3868dd82) SHA1(844584c5a80fb8f1797b4aa4e22024e75726293d) ) ROM_LOAD( "dz-cp3.bin", 0x1000, 0x0800, CRC(755d9ed2) SHA1(a7165a1d12a5a81d8bb941d8ad073e2097c90beb) ) CVS_COMMON_ROMS ROM_END ROM_START( radarzon ) ROM_REGION( 0x8000, "maincpu", 0 ) ROM_LOAD_STAGGERED( "rd-gp1.bin", 0x0000, CRC(775786ba) SHA1(5ad0f4e774821a7ed73615118ea42132d3b5424b) ) ROM_LOAD_STAGGERED( "rd-gp2.bin", 0x0400, CRC(9f6be426) SHA1(24b6cf3d826f3aec0e928881f259a5bc6229232b) ) ROM_LOAD_STAGGERED( "rd-gp3.bin", 0x0800, CRC(61d11b29) SHA1(fe321c1c912b93bbb098d591e5c4ed0b5b72c88e) ) ROM_LOAD_STAGGERED( "rd-gp4.bin", 0x0c00, CRC(2fbc778c) SHA1(e45ba08156cf03a1c4a1bdfb8569476d0eb05847) ) ROM_LOAD_STAGGERED( "rd-gp5.bin", 0x1000, CRC(692a99d5) SHA1(122ae802914cb9a41713536f9030cd9377cf3468) ) ROM_REGION( 0x8000, "audiocpu", 0 ) ROM_LOAD( "rd-sdp1.bin", 0x0000, 0x0800, CRC(cd5aea6d) SHA1(f7545b87e71e3108c0dec24a4e91620d006e0602) ) CVS_ROM_REGION_SPEECH_DATA( "rd-sp1.bin", 0x0800, CRC(43b17734) SHA1(59960f0c48ed24cedb4b4655f97f6f1fdac4445e) ) ROM_REGION( 0x1800, "gfx1", 0 ) ROM_LOAD( "rd-cp1.bin", 0x0000, 0x0800, CRC(ed601677) SHA1(efe2b6033f319603ee80ed4ba66d3b3607537b13) ) ROM_LOAD( "rd-cp2.bin", 0x0800, 0x0800, CRC(35e317ff) SHA1(458550b431ec66006e2966d86a2286905c0495ed) ) ROM_LOAD( "rd-cp3.bin", 0x1000, 0x0800, CRC(90f2c43f) SHA1(406215217f6f20c1a78f31b2ae3c0a97391e3371) ) CVS_COMMON_ROMS ROM_END ROM_START( radarzon1 ) ROM_REGION( 0x8000, "maincpu", 0 ) ROM_LOAD_STAGGERED( "r1-gp1.bin", 0x0000, CRC(7c73c21f) SHA1(1113025ea16cfcc500b9624a031f3d25290db163) ) ROM_LOAD_STAGGERED( "r1-gp2.bin", 0x0400, CRC(dedbd2ce) SHA1(ef80bf1b4a9561ad7f54e795c78e72664abf0501) ) ROM_LOAD_STAGGERED( "r1-gp3.bin", 0x0800, CRC(966a49e7) SHA1(6c769ac12fbfb65184131f1ab16240e422125c04) ) ROM_LOAD_STAGGERED( "r1-gp4.bin", 0x0c00, CRC(f3175bee) SHA1(f4927eea856ae56b1854263666a48e2cfb3ab60d) ) ROM_LOAD_STAGGERED( "r1-gp5.bin", 0x1000, CRC(7484927b) SHA1(89a67baa91075d2777f2ecd1667ed79175ad57ca) ) ROM_REGION( 0x8000, "audiocpu", 0 ) ROM_LOAD( "rd-sdp1.bin", 0x0000, 0x0800, CRC(cd5aea6d) SHA1(f7545b87e71e3108c0dec24a4e91620d006e0602) ) CVS_ROM_REGION_SPEECH_DATA( "rd-sp1.bin", 0x0800, CRC(43b17734) SHA1(59960f0c48ed24cedb4b4655f97f6f1fdac4445e) ) ROM_REGION( 0x1800, "gfx1", 0 ) ROM_LOAD( "rd-cp1.bin", 0x0000, 0x0800, CRC(ed601677) SHA1(efe2b6033f319603ee80ed4ba66d3b3607537b13) ) ROM_LOAD( "rd-cp2.bin", 0x0800, 0x0800, CRC(35e317ff) SHA1(458550b431ec66006e2966d86a2286905c0495ed) ) ROM_LOAD( "rd-cp3.bin", 0x1000, 0x0800, CRC(90f2c43f) SHA1(406215217f6f20c1a78f31b2ae3c0a97391e3371) ) CVS_COMMON_ROMS ROM_END ROM_START( radarzont ) ROM_REGION( 0x8000, "maincpu", 0 ) ROM_LOAD_STAGGERED( "rt-gp1.bin", 0x0000, CRC(43573974) SHA1(854fe7022e9bdd94bb119c014156e9ffdb6682fa) ) ROM_LOAD_STAGGERED( "rt-gp2.bin", 0x0400, CRC(257a11ce) SHA1(ca7f9260d9879ebce202f83a41838cb6dc9a6480) ) ROM_LOAD_STAGGERED( "rt-gp3.bin", 0x0800, CRC(e00f3552) SHA1(156765809e4016527039e3d5cc1c320cfce06834) ) ROM_LOAD_STAGGERED( "rt-gp4.bin", 0x0c00, CRC(d1e824ac) SHA1(f996813f02d32ddcde7f394740bdb3444eacda76) ) ROM_LOAD_STAGGERED( "rt-gp5.bin", 0x1000, CRC(bc770af8) SHA1(79599b5f2f4d692986862076be1d487b45783c00) ) ROM_REGION( 0x8000, "audiocpu", 0 ) ROM_LOAD( "rd-sdp1.bin", 0x0000, 0x0800, CRC(cd5aea6d) SHA1(f7545b87e71e3108c0dec24a4e91620d006e0602) ) CVS_ROM_REGION_SPEECH_DATA( "rd-sp1.bin", 0x0800, CRC(43b17734) SHA1(59960f0c48ed24cedb4b4655f97f6f1fdac4445e) ) ROM_REGION( 0x1800, "gfx1", 0 ) ROM_LOAD( "rd-cp1.bin", 0x0000, 0x0800, CRC(ed601677) SHA1(efe2b6033f319603ee80ed4ba66d3b3607537b13) ) ROM_LOAD( "rd-cp2.bin", 0x0800, 0x0800, CRC(35e317ff) SHA1(458550b431ec66006e2966d86a2286905c0495ed) ) ROM_LOAD( "rd-cp3.bin", 0x1000, 0x0800, CRC(90f2c43f) SHA1(406215217f6f20c1a78f31b2ae3c0a97391e3371) ) CVS_COMMON_ROMS ROM_END ROM_START( outline ) ROM_REGION( 0x8000, "maincpu", 0 ) ROM_LOAD_STAGGERED( "rt-gp1.bin", 0x0000, CRC(43573974) SHA1(854fe7022e9bdd94bb119c014156e9ffdb6682fa) ) ROM_LOAD_STAGGERED( "rt-gp2.bin", 0x0400, CRC(257a11ce) SHA1(ca7f9260d9879ebce202f83a41838cb6dc9a6480) ) ROM_LOAD_STAGGERED( "ot-gp3.bin", 0x0800, CRC(699489e1) SHA1(d4b21c294254ee0a451c29ac91028582a52f5ba3) ) ROM_LOAD_STAGGERED( "ot-gp4.bin", 0x0c00, CRC(c94aca17) SHA1(ea4ab93c52fee37afc7033b4b2acddcdce308f6b) ) ROM_LOAD_STAGGERED( "ot-gp5.bin", 0x1000, CRC(154712f4) SHA1(90f69e30e1c1d2348d6644406d83d2b2bcfe8171) ) ROM_REGION( 0x8000, "audiocpu", 0 ) ROM_LOAD( "ot-sdp1.bin", 0x0000, 0x0800, CRC(739066a9) SHA1(7b3ba8a163d341931bc0385c298d2061fa75e644) ) CVS_ROM_REGION_SPEECH_DATA( "ot-sp1.bin", 0x1000, CRC(fa21422a) SHA1(a75d13455c65e5a77db02fc87f0c112e329d0d6d) ) ROM_REGION( 0x1800, "gfx1", 0 ) ROM_LOAD( "rd-cp1.bin", 0x0000, 0x0800, CRC(ed601677) SHA1(efe2b6033f319603ee80ed4ba66d3b3607537b13) ) ROM_LOAD( "rd-cp2.bin", 0x0800, 0x0800, CRC(35e317ff) SHA1(458550b431ec66006e2966d86a2286905c0495ed) ) ROM_LOAD( "rd-cp3.bin", 0x1000, 0x0800, CRC(90f2c43f) SHA1(406215217f6f20c1a78f31b2ae3c0a97391e3371) ) CVS_COMMON_ROMS ROM_END ROM_START( goldbug ) ROM_REGION( 0x8000, "maincpu", 0 ) ROM_LOAD_STAGGERED( "gb-gp1.bin", 0x0000, CRC(8deb7761) SHA1(35f27fb6b5e3f76ddaf2c074b3391931e679df6e) ) ROM_LOAD_STAGGERED( "gb-gp2.bin", 0x0400, CRC(135036c1) SHA1(9868eae2486687772bf0bf71b82e461a882ae1ab) ) ROM_LOAD_STAGGERED( "gb-gp3.bin", 0x0800, CRC(d48b1090) SHA1(b3cbfeb4fc2bf1bbe0befab793fcc5e7e6ff804c) ) ROM_LOAD_STAGGERED( "gb-gp4.bin", 0x0c00, CRC(c8053205) SHA1(7f814b059f6b9c62e8a83c1753da5e8780b09411) ) ROM_LOAD_STAGGERED( "gb-gp5.bin", 0x1000, CRC(eca17472) SHA1(25c4ca59b4c96a22bc42b41adbf3cc33373cf85e) ) ROM_REGION( 0x8000, "audiocpu", 0 ) ROM_LOAD( "gb-sdp1.bin", 0x0000, 0x1000, CRC(c8a4b39d) SHA1(29fffaa12639f3b19db818ad374d09fbf9c7fb98) ) CVS_ROM_REGION_SPEECH_DATA( "gb-sp1.bin", 0x0800, CRC(5d0205c3) SHA1(578937058d56e5c9fba8a2204ddbb59a6d23dec7) ) ROM_REGION( 0x1800, "gfx1", 0 ) ROM_LOAD( "gb-cp1.bin", 0x0000, 0x0800, CRC(80e1ad5a) SHA1(0a577b0faffd9d6807c39175ce213f017a5cc7f8) ) ROM_LOAD( "gb-cp2.bin", 0x0800, 0x0800, CRC(0a288b29) SHA1(0c6471a3517805a5c873857ff21ca94dfe91c24e) ) ROM_LOAD( "gb-cp3.bin", 0x1000, 0x0800, CRC(e5bcf8cf) SHA1(7f53b8ee6f87e6c8761d2200e8194a7d16d8c7ac) ) CVS_COMMON_ROMS ROM_END ROM_START( diggerc ) ROM_REGION( 0x8000, "maincpu", 0 ) ROM_LOAD_STAGGERED( "dig-gp1.bin", 0x0000, CRC(6a67662f) SHA1(70e9814259c1fbaf195004e1d8ce0ab1125d62d0) ) ROM_LOAD_STAGGERED( "dig-gp2.bin", 0x0400, CRC(aa9f93b5) SHA1(e118ecb9160b7ba4a81b75b6cca56c0f01a9a3af) ) ROM_LOAD_STAGGERED( "dig-gp3.bin", 0x0800, CRC(4aa4c87c) SHA1(bcbe291e2ca060ecc623702cba1f4189dfa9c105) ) ROM_LOAD_STAGGERED( "dig-gp4.bin", 0x0c00, CRC(127e6520) SHA1(a4f1813a297616b7f864e235f40a432881fe252b) ) ROM_LOAD_STAGGERED( "dig-gp5.bin", 0x1000, CRC(76786827) SHA1(43e33c47a42878a58d72051c1edeccf944db4a17) ) ROM_REGION( 0x8000, "audiocpu", 0 ) ROM_LOAD( "dig-sdp1.bin", 0x0000, 0x1000, CRC(f82e51f0) SHA1(52903c19cdf7754894cbae57a16533579737b3d5) ) CVS_ROM_REGION_SPEECH_DATA( "dig-sp1.bin", 0x0800, CRC(db526ee1) SHA1(afe319e64350b0c54b72394294a6369c885fdb7f) ) ROM_REGION( 0x1800, "gfx1", 0 ) ROM_LOAD( "dig-cp1.bin", 0x0000, 0x0800, CRC(ca30fb97) SHA1(148f3a6f20b1f256a73e7a1992262116d77cc0a8) ) ROM_LOAD( "dig-cp2.bin", 0x0800, 0x0800, CRC(bed2334c) SHA1(c93902d01174e13fb9265194e5e44f67b38c5970) ) ROM_LOAD( "dig-cp3.bin", 0x1000, 0x0800, CRC(46db9b65) SHA1(1c655b4611ab182b6e4a3cdd3ef930e0d4dad0d9) ) CVS_COMMON_ROMS ROM_END ROM_START( superbik ) ROM_REGION( 0x8000, "maincpu", 0 ) ROM_LOAD_STAGGERED( "sb-gp1.bin", 0x0000, CRC(f0209700) SHA1(7843e8ebcbecb93814863ddd135f5acb0d481043) ) ROM_LOAD_STAGGERED( "sb-gp2.bin", 0x0400, CRC(1956d687) SHA1(00e261c5b1e1414b45661310c47daeceb3d5f4bf) ) ROM_LOAD_STAGGERED( "sb-gp3.bin", 0x0800, CRC(ceb27b75) SHA1(56fecc72746113a6611c18663d1b9e0e2daf57b4) ) ROM_LOAD_STAGGERED( "sb-gp4.bin", 0x0c00, CRC(430b70b3) SHA1(207c4939331c1561d145cbee0538da072aa51f5b) ) ROM_LOAD_STAGGERED( "sb-gp5.bin", 0x1000, CRC(013615a3) SHA1(1795a4dcc98255ad185503a99f48b7bacb5edc9d) ) ROM_REGION( 0x8000, "audiocpu", 0 ) ROM_LOAD( "sb-sdp1.bin", 0x0000, 0x0800, CRC(e977c090) SHA1(24bd4165434c745c1514d49cc90bcb621fb3a0f8) ) CVS_ROM_REGION_SPEECH_DATA( "sb-sp1.bin", 0x0800, CRC(0aeb9ccd) SHA1(e7123eed21e4e758bbe1cebfd5aad44a5de45c27) ) ROM_REGION( 0x1800, "gfx1", 0 ) ROM_LOAD( "sb-cp1.bin", 0x0000, 0x0800, CRC(03ba7760) SHA1(4ed252e2c4ec7cea2199524f7c35a1dc7c44f8d8) ) ROM_LOAD( "sb-cp2.bin", 0x0800, 0x0800, CRC(04de69f2) SHA1(3ef3b3c159d47230622b6cc45baad8737bd93a90) ) ROM_LOAD( "sb-cp3.bin", 0x1000, 0x0800, CRC(bb7d0b9a) SHA1(94c72d6961204be9cab351ac854ac9c69b51e79a) ) CVS_COMMON_ROMS ROM_END ROM_START( hero ) ROM_REGION( 0x8000, "maincpu", 0 ) ROM_LOAD_STAGGERED( "hr-gp1.bin", 0x0000, CRC(82f39788) SHA1(44217dc2312d10fceeb35adf3999cd6f240b60be) ) ROM_LOAD_STAGGERED( "hr-gp2.bin", 0x0400, CRC(79607812) SHA1(eaab829a2f5bcb8ec92c3f4122cffae31a4a77cb) ) ROM_LOAD_STAGGERED( "hr-gp3.bin", 0x0800, CRC(2902715c) SHA1(cf63f72681d1dcbdabdf7673ad8f61b5969e4bd1) ) ROM_LOAD_STAGGERED( "hr-gp4.bin", 0x0c00, CRC(696d2f8e) SHA1(73dd57f0f84e37ae707a89e17253aa3dd0c8b48b) ) ROM_LOAD_STAGGERED( "hr-gp5.bin", 0x1000, CRC(936a4ba6) SHA1(86cddcfafbd93dcdad3a1f26e280ceb96f779ab0) ) ROM_REGION( 0x8000, "audiocpu", 0 ) ROM_LOAD( "hr-sdp1.bin", 0x0000, 0x0800, CRC(c34ecf79) SHA1(07c96283410b1e7401140094db95800708cf310f) ) CVS_ROM_REGION_SPEECH_DATA( "hr-sp1.bin", 0x0800, CRC(a5c33cb1) SHA1(447ffb193b0dc4985bae5d8c214a893afd08664b) ) ROM_REGION( 0x1800, "gfx1", 0 ) ROM_LOAD( "hr-cp1.bin", 0x0000, 0x0800, CRC(2d201496) SHA1(f195aa1b231a0e1752c7da824a10321f0527f8c9) ) ROM_LOAD( "hr-cp2.bin", 0x0800, 0x0800, CRC(21b61fe3) SHA1(31882003f0557ffc4ec38ae6ee07b5d294b4162c) ) ROM_LOAD( "hr-cp3.bin", 0x1000, 0x0800, CRC(9c8e3f9e) SHA1(9d949a4d12b45da12b434677670b2b109568564a) ) CVS_COMMON_ROMS ROM_END ROM_START( logger ) // actual ROM label has "Century Elect. Ltd. (c)1981", and LOG3 is handwritten ROM_REGION( 0x8000, "maincpu", 0 ) ROM_LOAD_STAGGERED( "1clog3.gp1", 0x0000, CRC(0022b9ed) SHA1(4b94d2663f802a8140e8eae1b66ee78fdfa654f5) ) ROM_LOAD_STAGGERED( "2clog3.gp2", 0x0400, CRC(23c5c8dc) SHA1(37fb6a62cb798d96de20078fe4a3af74a2be0e66) ) ROM_LOAD_STAGGERED( "3clog3.gp3", 0x0800, CRC(f9288f74) SHA1(8bb588194186fc0e0c2d61ed2746542c978ebb76) ) ROM_LOAD_STAGGERED( "4clog3.gp4", 0x0c00, CRC(e52ef7bf) SHA1(df5509b6847d6b9520a9d83b15083546898a981e) ) ROM_LOAD_STAGGERED( "5clog3.gp5", 0x1000, CRC(4ee04359) SHA1(a592d4b280ac0ad5f06d68a7809092548261f123) ) ROM_REGION( 0x8000, "audiocpu", 0 ) ROM_LOAD( "6clog3.sdp1", 0x0000, 0x1000, CRC(5af8da17) SHA1(357f02cdf38c6659aca51fa0a8534542fc29623c) ) CVS_ROM_REGION_SPEECH_DATA( "8clog3.sp1", 0x0800, CRC(74f67815) SHA1(6a26a16c27a7e4d58b611e5127115005a60cff91) ) ROM_REGION( 0x1800, "gfx1", 0 ) ROM_LOAD( "11clog3.cp1", 0x0000, 0x0800, CRC(e4ede80e) SHA1(62f2bc78106a057b6a8420d40421908df609bf29) ) ROM_LOAD( "10clog3.cp2", 0x0800, 0x0800, CRC(d3de8e5b) SHA1(f95320e001869c42e51195d9cc11e4f2555e153f) ) ROM_LOAD( "9clog3.cp3", 0x1000, 0x0800, CRC(9b8d1031) SHA1(87ef12aeae80cc0f240dead651c6222848f8dccc) ) CVS_COMMON_ROMS ROM_END ROM_START( cosmos ) ROM_REGION( 0x8000, "maincpu", 0 ) ROM_LOAD_STAGGERED( "cs-gp1.bin", 0x0000, CRC(7eb96ddf) SHA1(f7456ee1ace03ab98c4e8128d375464122c4df01) ) ROM_LOAD_STAGGERED( "cs-gp2.bin", 0x0400, CRC(6975a8f7) SHA1(13192d4eedd843c0c1d7e5c54a3086f71b09fbcb) ) ROM_LOAD_STAGGERED( "cs-gp3.bin", 0x0800, CRC(76904b13) SHA1(de219999e4a1b72142e71ea707b6250f4732ccb3) ) ROM_LOAD_STAGGERED( "cs-gp4.bin", 0x0c00, CRC(bdc89719) SHA1(668267d0b05990ff83a9e38a62950d3d725a53b3) ) ROM_LOAD_STAGGERED( "cs-gp5.bin", 0x1000, CRC(94be44ea) SHA1(e496ea79d177c6d2d79d59f7d45c86b547469c6f) ) ROM_REGION( 0x8000, "audiocpu", 0 ) ROM_LOAD( "cs-sdp1.bin", 0x0000, 0x0800, CRC(b385b669) SHA1(79621d3fb3eb4ea6fa8a733faa6f21edeacae186) ) CVS_ROM_REGION_SPEECH_DATA( "cs-sp1.bin", 0x1000, CRC(3c7fe86d) SHA1(9ae0b63b231a7092820650a196cde60588bc6b58) ) ROM_REGION( 0x1800, "gfx1", 0 ) ROM_LOAD( "cs-cp1.bin", 0x0000, 0x0800, CRC(6a48c898) SHA1(c27f7bcdb2fe042ec52d1b9b4b9a4e47c288862d) ) ROM_LOAD( "cs-cp2.bin", 0x0800, 0x0800, CRC(db0dfd8c) SHA1(f2b0dd43f0e514fdae54e4066606187f45b98e38) ) ROM_LOAD( "cs-cp3.bin", 0x1000, 0x0800, CRC(01eee875) SHA1(6c41d716b5795f085229d855518862fb85f395a4) ) CVS_COMMON_ROMS ROM_END ROM_START( heartatk ) ROM_REGION( 0x8000, "maincpu", 0 ) ROM_LOAD_STAGGERED( "ha-gp1.bin", 0x0000, CRC(e8297c23) SHA1(e79ae7e99f904afe90b43a54df7b0e257d65ac0b) ) ROM_LOAD_STAGGERED( "ha-gp2.bin", 0x0400, CRC(f7632afc) SHA1(ebfc6e12c8b5078e8c448aa25d9de9d39c0baa5e) ) ROM_LOAD_STAGGERED( "ha-gp3.bin", 0x0800, CRC(a9ce3c6a) SHA1(86ddb27c1c132f3cf5ad4268ea9a458e0da23677) ) ROM_LOAD_STAGGERED( "ha-gp4.bin", 0x0c00, CRC(090f30a9) SHA1(acd6b0c7358bf4664d0de668853076326e82fd04) ) ROM_LOAD_STAGGERED( "ha-gp5.bin", 0x1000, CRC(163b3d2d) SHA1(275275b54533e0ce2df6d189619be05a99c68b6d) ) ROM_REGION( 0x8000, "audiocpu", 0 ) ROM_LOAD( "ha-sdp1.bin", 0x0000, 0x1000, CRC(b9c466a0) SHA1(f28c21a15cf6d52123ed7feac4eea2a42ea5e93d) ) CVS_ROM_REGION_SPEECH_DATA( "ha-sp1.bin", 0x1000, CRC(fa21422a) SHA1(a75d13455c65e5a77db02fc87f0c112e329d0d6d) ) ROM_REGION( 0x1800, "gfx1", 0 ) ROM_LOAD( "ha-cp1.bin", 0x0000, 0x0800, CRC(2d0f6d13) SHA1(55e45eaf1bf24a7a78a2f34ffc0d99a4c191d138) ) ROM_LOAD( "ha-cp2.bin", 0x0800, 0x0800, CRC(7f5671bd) SHA1(7f4ae92a96c5a847c113f6f7e8d67d3e5ee0bcb0) ) ROM_LOAD( "ha-cp3.bin", 0x1000, 0x0800, CRC(35b05ab4) SHA1(f336eb0c674c3d52e84be0f37b70953cce6112dc) ) CVS_COMMON_ROMS ROM_END ROM_START( spacefrt ) ROM_REGION( 0x8000, "maincpu", 0 ) ROM_LOAD_STAGGERED( "sf-gp1.bin", 0x0000, CRC(1158fc3a) SHA1(c1f470324b6ec65c3061f78a6ff8620154f20c09) ) ROM_LOAD_STAGGERED( "sf-gp2.bin", 0x0400, CRC(8b4e1582) SHA1(5b92082d67f32197c0c61ddd8e1e3feb742195f4) ) ROM_LOAD_STAGGERED( "sf-gp3.bin", 0x0800, CRC(48f05102) SHA1(72d40cdd0bbc4cfeb6ddf550de0dafc61270d382) ) ROM_LOAD_STAGGERED( "sf-gp4.bin", 0x0c00, CRC(c5b14631) SHA1(360bed649185a090f7c96adadd7f045ef574865a) ) ROM_LOAD_STAGGERED( "sf-gp5.bin", 0x1000, CRC(d7eca1b6) SHA1(8444e61827f0153d04c4f9c08416e7ab753d6918) ) ROM_REGION( 0x8000, "audiocpu", 0 ) ROM_LOAD( "sf-sdp1.bin", 0x0000, 0x0800, CRC(339a327f) SHA1(940887cd4660e37537fd9b57aa1ec3a4717ea0cf) ) CVS_ROM_REGION_SPEECH_DATA( "sf-sp1.bin", 0x1000, CRC(c5628d30) SHA1(d29a5852a1762cbd5f3eba29ae2bf49b3a26f894) ) ROM_REGION( 0x1800, "gfx1", 0 ) ROM_LOAD( "sf-cp1.bin", 0x0000, 0x0800, CRC(da194a68) SHA1(4215267e91644cf1e1f32f898bc9562bfba711f3) ) ROM_LOAD( "sf-cp2.bin", 0x0800, 0x0800, CRC(b96977c7) SHA1(8f0fab044f16787bce83562e2b22d962d0a2c209) ) ROM_LOAD( "sf-cp3.bin", 0x1000, 0x0800, CRC(f5d67b9a) SHA1(a492b41c53b1f28ac5f70969e5f06afa948c1a7d) ) CVS_COMMON_ROMS ROM_END ROM_START( raiders ) ROM_REGION( 0x8000, "maincpu", 0 ) ROM_LOAD_STAGGERED( "raid4-5a.bin", 0x0000, CRC(1a92a5aa) SHA1(7f6dbbc0ac5ee2ba3efb3a9120cbee89c659b712) ) ROM_LOAD_STAGGERED( "raid4-4b.bin", 0x0400, CRC(da69e4b9) SHA1(8a2c4130a5db2cd7dbadb220440bb94ed4513bca) ) ROM_LOAD_STAGGERED( "raid4-3b.bin", 0x0800, CRC(ca794f92) SHA1(f281d88ffc6b7a84f9bcabc06eed99b8ae045eec) ) ROM_LOAD_STAGGERED( "raid4-2c.bin", 0x0c00, CRC(9de2c085) SHA1(be6157904afd0dc6ef8d97ec01a9557021ac8f3a) ) ROM_LOAD_STAGGERED( "raid4-1a.bin", 0x1000, CRC(f4db83ed) SHA1(7d519dc628c93f153ccede85e3cf77c012430f38) ) ROM_REGION( 0x8000, "audiocpu", 0 ) ROM_LOAD( "raidr1-6.bin", 0x0000, 0x0800, CRC(6f827e49) SHA1(4fb272616b60fcd468ed4074b94125e30aa46fd3) ) CVS_ROM_REGION_SPEECH_DATA( "raidr1-8.bin", 0x0800, CRC(b6b90d2e) SHA1(a966fa208b72aec358b7fb277e603e47b6984aa7) ) ROM_REGION( 0x1800, "gfx1", 0 ) ROM_LOAD( "raid4-11.bin", 0x0000, 0x0800, CRC(5eb7143b) SHA1(a19e803c15593b37ae2e61789f6e16f319620a37) ) ROM_LOAD( "raid4-10.bin", 0x0800, 0x0800, CRC(391948a4) SHA1(7e20ad4f7e5bf7ad5dcb08ba6475313e2b8b1f03) ) ROM_LOAD( "raid4-9b.bin", 0x1000, 0x0800, CRC(fecfde80) SHA1(23ea63080b8292fb00a743743cdff1a7ad0a8c6d) ) CVS_COMMON_ROMS ROM_END ROM_START( raidersr3 ) ROM_REGION( 0x8000, "maincpu", 0 ) ROM_LOAD_STAGGERED( "raid3gp5.bin", 0x0000, CRC(e169b71c) SHA1(4e8cc8ee3032ab5a7cfc1caba83f01d6a062d0ae) ) ROM_LOAD_STAGGERED( "raid3gp4.bin", 0x0400, CRC(9bf717ca) SHA1(7109232b7f72a325538fe6d25b8ef55747d1948d) ) ROM_LOAD_STAGGERED( "raid3gp3.bin", 0x0800, CRC(ac304782) SHA1(01597c2808d8e33bf9f6510fa9d7a5520eebf179) ) ROM_LOAD_STAGGERED( "raid3gp2.bin", 0x0c00, CRC(1c0fd350) SHA1(df7e64ad77755da4abdc66b08c470dff018d4592) ) ROM_LOAD_STAGGERED( "raid3gp1.bin", 0x1000, CRC(5ea24ebf) SHA1(96f9b1f26d8f35a1505cf4d45e5d960a9bb8fb74) ) ROM_REGION( 0x8000, "audiocpu", 0 ) ROM_LOAD( "raidr1-6.bin", 0x0000, 0x0800, CRC(6f827e49) SHA1(4fb272616b60fcd468ed4074b94125e30aa46fd3) ) CVS_ROM_REGION_SPEECH_DATA( "raidr1-8.bin", 0x0800, CRC(b6b90d2e) SHA1(a966fa208b72aec358b7fb277e603e47b6984aa7) ) ROM_REGION( 0x1800, "gfx1", 0 ) ROM_LOAD( "raid4-11.bin", 0x0000, 0x0800, CRC(5eb7143b) SHA1(a19e803c15593b37ae2e61789f6e16f319620a37) ) ROM_LOAD( "raid4-10.bin", 0x0800, 0x0800, CRC(391948a4) SHA1(7e20ad4f7e5bf7ad5dcb08ba6475313e2b8b1f03) ) ROM_LOAD( "raid4-9b.bin", 0x1000, 0x0800, CRC(fecfde80) SHA1(23ea63080b8292fb00a743743cdff1a7ad0a8c6d) ) CVS_COMMON_ROMS ROM_END /************************************* * * Game specific initalization * *************************************/ DRIVER_INIT_MEMBER(cvs_state,huncholy) { UINT8 *ROM = memregion("maincpu")->base(); /* patch out protection */ ROM[0x0082] = 0xc0; ROM[0x0083] = 0xc0; ROM[0x0084] = 0xc0; ROM[0x00b7] = 0xc0; ROM[0x00b8] = 0xc0; ROM[0x00b9] = 0xc0; ROM[0x00d9] = 0xc0; ROM[0x00da] = 0xc0; ROM[0x00db] = 0xc0; ROM[0x4456] = 0xc0; ROM[0x4457] = 0xc0; ROM[0x4458] = 0xc0; } DRIVER_INIT_MEMBER(cvs_state,hunchbaka) { UINT8 *ROM = memregion("maincpu")->base(); offs_t offs; /* data lines D2 and D5 swapped */ for (offs = 0; offs < 0x7400; offs++) ROM[offs] = BITSWAP8(ROM[offs],7,6,2,4,3,5,1,0); } DRIVER_INIT_MEMBER(cvs_state,superbik) { UINT8 *ROM = memregion("maincpu")->base(); /* patch out protection */ ROM[0x0079] = 0xc0; ROM[0x007a] = 0xc0; ROM[0x007b] = 0xc0; ROM[0x0081] = 0xc0; ROM[0x0082] = 0xc0; ROM[0x0083] = 0xc0; ROM[0x00b6] = 0xc0; ROM[0x00b7] = 0xc0; ROM[0x00b8] = 0xc0; ROM[0x0168] = 0xc0; ROM[0x0169] = 0xc0; ROM[0x016a] = 0xc0; /* and speed up the protection check */ ROM[0x0099] = 0xc0; ROM[0x009a] = 0xc0; ROM[0x009b] = 0xc0; ROM[0x00bb] = 0xc0; ROM[0x00bc] = 0xc0; ROM[0x00bd] = 0xc0; } DRIVER_INIT_MEMBER(cvs_state,hero) { UINT8 *ROM = memregion("maincpu")->base(); /* patch out protection */ ROM[0x0087] = 0xc0; ROM[0x0088] = 0xc0; ROM[0x0aa1] = 0xc0; ROM[0x0aa2] = 0xc0; ROM[0x0aa3] = 0xc0; ROM[0x0aaf] = 0xc0; ROM[0x0ab0] = 0xc0; ROM[0x0ab1] = 0xc0; ROM[0x0abd] = 0xc0; ROM[0x0abe] = 0xc0; ROM[0x0abf] = 0xc0; ROM[0x4de0] = 0xc0; ROM[0x4de1] = 0xc0; ROM[0x4de2] = 0xc0; } DRIVER_INIT_MEMBER(cvs_state,raiders) { UINT8 *ROM = memregion("maincpu")->base(); offs_t offs; /* data lines D1 and D6 swapped */ for (offs = 0; offs < 0x7400; offs++) ROM[offs] = BITSWAP8(ROM[offs],7,1,5,4,3,2,6,0); /* patch out protection */ ROM[0x010a] = 0xc0; ROM[0x010b] = 0xc0; ROM[0x010c] = 0xc0; } /************************************* * * Game drivers * *************************************/ GAME( 1981, cosmos, 0, cvs, cosmos, driver_device, 0, ROT90, "Century Electronics", "Cosmos", MACHINE_NO_COCKTAIL | MACHINE_IMPERFECT_SOUND | MACHINE_SUPPORTS_SAVE ) GAME( 1981, darkwar, 0, cvs, darkwar, driver_device, 0, ROT90, "Century Electronics", "Dark Warrior", MACHINE_NO_COCKTAIL | MACHINE_IMPERFECT_SOUND | MACHINE_SUPPORTS_SAVE ) GAME( 1981, spacefrt, 0, cvs, spacefrt, driver_device, 0, ROT90, "Century Electronics", "Space Fortress (CVS)", MACHINE_NO_COCKTAIL | MACHINE_IMPERFECT_SOUND | MACHINE_SUPPORTS_SAVE ) GAME( 1982, 8ball, 0, cvs, 8ball, driver_device, 0, ROT90, "Century Electronics", "Video Eight Ball", MACHINE_NO_COCKTAIL | MACHINE_IMPERFECT_SOUND | MACHINE_SUPPORTS_SAVE ) GAME( 1982, 8ball1, 8ball, cvs, 8ball, driver_device, 0, ROT90, "Century Electronics", "Video Eight Ball (Rev.1)", MACHINE_NO_COCKTAIL | MACHINE_IMPERFECT_SOUND | MACHINE_SUPPORTS_SAVE ) GAME( 1982, logger, 0, cvs, logger, driver_device, 0, ROT90, "Century Electronics", "Logger", MACHINE_NO_COCKTAIL | MACHINE_IMPERFECT_SOUND | MACHINE_SUPPORTS_SAVE ) GAME( 1982, dazzler, 0, cvs, dazzler, driver_device, 0, ROT90, "Century Electronics", "Dazzler", MACHINE_NO_COCKTAIL | MACHINE_IMPERFECT_SOUND | MACHINE_SUPPORTS_SAVE ) GAME( 1982, wallst, 0, cvs, wallst, driver_device, 0, ROT90, "Century Electronics", "Wall Street", MACHINE_NO_COCKTAIL | MACHINE_IMPERFECT_SOUND | MACHINE_SUPPORTS_SAVE ) GAME( 1982, radarzon, 0, cvs, radarzon, driver_device, 0, ROT90, "Century Electronics", "Radar Zone", MACHINE_NO_COCKTAIL | MACHINE_IMPERFECT_SOUND | MACHINE_SUPPORTS_SAVE ) GAME( 1982, radarzon1, radarzon, cvs, radarzon, driver_device, 0, ROT90, "Century Electronics", "Radar Zone (Rev.1)", MACHINE_NO_COCKTAIL | MACHINE_IMPERFECT_SOUND | MACHINE_SUPPORTS_SAVE ) GAME( 1982, radarzont, radarzon, cvs, radarzon, driver_device, 0, ROT90, "Century Electronics (Tuni Electro Service Inc)", "Radar Zone (Tuni)", MACHINE_NO_COCKTAIL | MACHINE_IMPERFECT_SOUND | MACHINE_SUPPORTS_SAVE ) GAME( 1982, outline, radarzon, cvs, radarzon, driver_device, 0, ROT90, "Century Electronics", "Outline", MACHINE_NO_COCKTAIL | MACHINE_IMPERFECT_SOUND | MACHINE_SUPPORTS_SAVE ) GAME( 1982, goldbug, 0, cvs, goldbug, driver_device, 0, ROT90, "Century Electronics", "Gold Bug", MACHINE_NO_COCKTAIL | MACHINE_IMPERFECT_SOUND | MACHINE_SUPPORTS_SAVE ) GAME( 1982, diggerc, 0, cvs, diggerc, driver_device, 0, ROT90, "Century Electronics", "Digger (CVS)", MACHINE_NO_COCKTAIL | MACHINE_IMPERFECT_SOUND | MACHINE_SUPPORTS_SAVE ) GAME( 1983, heartatk, 0, cvs, heartatk, driver_device, 0, ROT90, "Century Electronics", "Heart Attack", MACHINE_NO_COCKTAIL | MACHINE_IMPERFECT_SOUND | MACHINE_SUPPORTS_SAVE ) GAME( 1983, hunchbak, 0, cvs, hunchbak, driver_device, 0, ROT90, "Century Electronics", "Hunchback (set 1)", MACHINE_NO_COCKTAIL | MACHINE_IMPERFECT_SOUND | MACHINE_SUPPORTS_SAVE ) GAME( 1983, hunchbaka, hunchbak, cvs, hunchbak, cvs_state, hunchbaka, ROT90, "Century Electronics", "Hunchback (set 2)", MACHINE_NO_COCKTAIL | MACHINE_IMPERFECT_SOUND | MACHINE_SUPPORTS_SAVE ) GAME( 1983, superbik, 0, cvs, superbik, cvs_state, superbik, ROT90, "Century Electronics", "Superbike", MACHINE_NO_COCKTAIL | MACHINE_IMPERFECT_SOUND | MACHINE_SUPPORTS_SAVE ) GAME( 1983, raiders, 0, cvs, raiders, cvs_state, raiders, ROT90, "Century Electronics", "Raiders", MACHINE_NO_COCKTAIL | MACHINE_IMPERFECT_SOUND | MACHINE_SUPPORTS_SAVE ) GAME( 1983, raidersr3, raiders, cvs, raiders, cvs_state, raiders, ROT90, "Century Electronics", "Raiders (Rev.3)", MACHINE_NO_COCKTAIL | MACHINE_IMPERFECT_SOUND | MACHINE_SUPPORTS_SAVE ) GAME( 1984, hero, 0, cvs, hero, cvs_state, hero, ROT90, "Century Electronics / Seatongrove Ltd", "Hero", MACHINE_NO_COCKTAIL | MACHINE_IMPERFECT_SOUND | MACHINE_SUPPORTS_SAVE ) // (C) 1984 CVS on titlescreen, (C) 1983 Seatongrove on highscore screen GAME( 1984, huncholy, 0, cvs, huncholy, cvs_state, huncholy, ROT90, "Century Electronics / Seatongrove Ltd", "Hunchback Olympic", MACHINE_NO_COCKTAIL | MACHINE_IMPERFECT_SOUND | MACHINE_SUPPORTS_SAVE )
sum2012/mame
src/mame/drivers/cvs.cpp
C++
gpl-2.0
70,600
/* * Packet matching code. * * Copyright (C) 1999 Paul `Rusty' Russell & Michael J. Neuling * Copyright (C) 2000-2002 Netfilter core team <coreteam@netfilter.org> * * 19 Jan 2002 Harald Welte <laforge@gnumonks.org> * - increase module usage count as soon as we have rules inside * a table * 06 Jun 2002 Andras Kis-Szabo <kisza@sch.bme.hu> * - new extension header parser code */ #include <linux/config.h> #include <linux/skbuff.h> #include <linux/kmod.h> #include <linux/vmalloc.h> #include <linux/netdevice.h> #include <linux/module.h> #include <linux/tcp.h> #include <linux/udp.h> #include <linux/icmpv6.h> #include <net/ip.h> #include <asm/uaccess.h> #include <asm/semaphore.h> #include <linux/proc_fs.h> #include <linux/netfilter_ipv6/ip6_tables.h> #define IPV6_HDR_LEN (sizeof(struct ipv6hdr)) #define IPV6_OPTHDR_LEN (sizeof(struct ipv6_opt_hdr)) /*#define DEBUG_IP_FIREWALL*/ /*#define DEBUG_ALLOW_ALL*/ /* Useful for remote debugging */ /*#define DEBUG_IP_FIREWALL_USER*/ #ifdef DEBUG_IP_FIREWALL #define dprintf(format, args...) printk(format , ## args) #else #define dprintf(format, args...) #endif #ifdef DEBUG_IP_FIREWALL_USER #define duprintf(format, args...) printk(format , ## args) #else #define duprintf(format, args...) #endif #ifdef CONFIG_NETFILTER_DEBUG #define IP_NF_ASSERT(x) \ do { \ if (!(x)) \ printk("IP_NF_ASSERT: %s:%s:%u\n", \ __FUNCTION__, __FILE__, __LINE__); \ } while(0) #else #define IP_NF_ASSERT(x) #endif #define SMP_ALIGN(x) (((x) + SMP_CACHE_BYTES-1) & ~(SMP_CACHE_BYTES-1)) /* Mutex protects lists (only traversed in user context). */ static DECLARE_MUTEX(ip6t_mutex); /* Must have mutex */ #define ASSERT_READ_LOCK(x) IP_NF_ASSERT(down_trylock(&ip6t_mutex) != 0) #define ASSERT_WRITE_LOCK(x) IP_NF_ASSERT(down_trylock(&ip6t_mutex) != 0) #include <linux/netfilter_ipv4/lockhelp.h> #include <linux/netfilter_ipv4/listhelp.h> #if 0 /* All the better to debug you with... */ #define static #define inline #endif /* Locking is simple: we assume at worst case there will be one packet in user context and one from bottom halves (or soft irq if Alexey's softnet patch was applied). We keep a set of rules for each CPU, so we can avoid write-locking them; doing a readlock_bh() stops packets coming through if we're in user context. To be cache friendly on SMP, we arrange them like so: [ n-entries ] ... cache-align padding ... [ n-entries ] Hence the start of any table is given by get_table() below. */ /* The table itself */ struct ip6t_table_info { /* Size per table */ unsigned int size; /* Number of entries: FIXME. --RR */ unsigned int number; /* Initial number of entries. Needed for module usage count */ unsigned int initial_entries; /* Entry points and underflows */ unsigned int hook_entry[NF_IP6_NUMHOOKS]; unsigned int underflow[NF_IP6_NUMHOOKS]; /* ip6t_entry tables: one per CPU */ char entries[0] ____cacheline_aligned; }; static LIST_HEAD(ip6t_target); static LIST_HEAD(ip6t_match); static LIST_HEAD(ip6t_tables); #define ADD_COUNTER(c,b,p) do { (c).bcnt += (b); (c).pcnt += (p); } while(0) #ifdef CONFIG_SMP #define TABLE_OFFSET(t,p) (SMP_ALIGN((t)->size)*(p)) #else #define TABLE_OFFSET(t,p) 0 #endif #if 0 #define down(x) do { printk("DOWN:%u:" #x "\n", __LINE__); down(x); } while(0) #define down_interruptible(x) ({ int __r; printk("DOWNi:%u:" #x "\n", __LINE__); __r = down_interruptible(x); if (__r != 0) printk("ABORT-DOWNi:%u\n", __LINE__); __r; }) #define up(x) do { printk("UP:%u:" #x "\n", __LINE__); up(x); } while(0) #endif static int ip6_masked_addrcmp(struct in6_addr addr1, struct in6_addr mask, struct in6_addr addr2) { int i; for( i = 0; i < 16; i++){ if((addr1.s6_addr[i] & mask.s6_addr[i]) != (addr2.s6_addr[i] & mask.s6_addr[i])) return 1; } return 0; } /* Check for an extension */ int ip6t_ext_hdr(u8 nexthdr) { return ( (nexthdr == IPPROTO_HOPOPTS) || (nexthdr == IPPROTO_ROUTING) || (nexthdr == IPPROTO_FRAGMENT) || (nexthdr == IPPROTO_ESP) || (nexthdr == IPPROTO_AH) || (nexthdr == IPPROTO_NONE) || (nexthdr == IPPROTO_DSTOPTS) ); } /* Returns whether matches rule or not. */ static inline int ip6_packet_match(const struct sk_buff *skb, const struct ipv6hdr *ipv6, const char *indev, const char *outdev, const struct ip6t_ip6 *ip6info, int isfrag) { size_t i; unsigned long ret; #define FWINV(bool,invflg) ((bool) ^ !!(ip6info->invflags & invflg)) if (FWINV(ip6_masked_addrcmp(ipv6->saddr,ip6info->smsk,ip6info->src), IP6T_INV_SRCIP) || FWINV(ip6_masked_addrcmp(ipv6->daddr,ip6info->dmsk,ip6info->dst), IP6T_INV_DSTIP)) { dprintf("Source or dest mismatch.\n"); /* dprintf("SRC: %u. Mask: %u. Target: %u.%s\n", ip->saddr, ipinfo->smsk.s_addr, ipinfo->src.s_addr, ipinfo->invflags & IP6T_INV_SRCIP ? " (INV)" : ""); dprintf("DST: %u. Mask: %u. Target: %u.%s\n", ip->daddr, ipinfo->dmsk.s_addr, ipinfo->dst.s_addr, ipinfo->invflags & IP6T_INV_DSTIP ? " (INV)" : "");*/ return 0; } /* Look for ifname matches; this should unroll nicely. */ for (i = 0, ret = 0; i < IFNAMSIZ/sizeof(unsigned long); i++) { ret |= (((const unsigned long *)indev)[i] ^ ((const unsigned long *)ip6info->iniface)[i]) & ((const unsigned long *)ip6info->iniface_mask)[i]; } if (FWINV(ret != 0, IP6T_INV_VIA_IN)) { dprintf("VIA in mismatch (%s vs %s).%s\n", indev, ip6info->iniface, ip6info->invflags&IP6T_INV_VIA_IN ?" (INV)":""); return 0; } for (i = 0, ret = 0; i < IFNAMSIZ/sizeof(unsigned long); i++) { ret |= (((const unsigned long *)outdev)[i] ^ ((const unsigned long *)ip6info->outiface)[i]) & ((const unsigned long *)ip6info->outiface_mask)[i]; } if (FWINV(ret != 0, IP6T_INV_VIA_OUT)) { dprintf("VIA out mismatch (%s vs %s).%s\n", outdev, ip6info->outiface, ip6info->invflags&IP6T_INV_VIA_OUT ?" (INV)":""); return 0; } /* ... might want to do something with class and flowlabel here ... */ /* look for the desired protocol header */ if((ip6info->flags & IP6T_F_PROTO)) { u_int8_t currenthdr = ipv6->nexthdr; struct ipv6_opt_hdr *hdrptr; u_int16_t ptr; /* Header offset in skb */ u_int16_t hdrlen; /* Header */ ptr = IPV6_HDR_LEN; while (ip6t_ext_hdr(currenthdr)) { /* Is there enough space for the next ext header? */ if (skb->len - ptr < IPV6_OPTHDR_LEN) return 0; /* NONE or ESP: there isn't protocol part */ /* If we want to count these packets in '-p all', * we will change the return 0 to 1*/ if ((currenthdr == IPPROTO_NONE) || (currenthdr == IPPROTO_ESP)) return 0; hdrptr = (struct ipv6_opt_hdr *)(skb->data + ptr); /* Size calculation */ if (currenthdr == IPPROTO_FRAGMENT) { hdrlen = 8; } else if (currenthdr == IPPROTO_AH) hdrlen = (hdrptr->hdrlen+2)<<2; else hdrlen = ipv6_optlen(hdrptr); currenthdr = hdrptr->nexthdr; ptr += hdrlen; /* ptr is too large */ if ( ptr > skb->len ) return 0; } /* currenthdr contains the protocol header */ dprintf("Packet protocol %hi ?= %s%hi.\n", currenthdr, ip6info->invflags & IP6T_INV_PROTO ? "!":"", ip6info->proto); if (ip6info->proto == currenthdr) { if(ip6info->invflags & IP6T_INV_PROTO) { return 0; } return 1; } /* We need match for the '-p all', too! */ if ((ip6info->proto != 0) && !(ip6info->invflags & IP6T_INV_PROTO)) return 0; } return 1; } /* should be ip6 safe */ static inline int ip6_checkentry(const struct ip6t_ip6 *ipv6) { if (ipv6->flags & ~IP6T_F_MASK) { duprintf("Unknown flag bits set: %08X\n", ipv6->flags & ~IP6T_F_MASK); return 0; } if (ipv6->invflags & ~IP6T_INV_MASK) { duprintf("Unknown invflag bits set: %08X\n", ipv6->invflags & ~IP6T_INV_MASK); return 0; } return 1; } static unsigned int ip6t_error(struct sk_buff **pskb, unsigned int hooknum, const struct net_device *in, const struct net_device *out, const void *targinfo, void *userinfo) { if (net_ratelimit()) printk("ip6_tables: error: `%s'\n", (char *)targinfo); return NF_DROP; } static inline int do_match(struct ip6t_entry_match *m, const struct sk_buff *skb, const struct net_device *in, const struct net_device *out, int offset, const void *hdr, u_int16_t datalen, int *hotdrop) { /* Stop iteration if it doesn't match */ if (!m->u.kernel.match->match(skb, in, out, m->data, offset, hdr, datalen, hotdrop)) return 1; else return 0; } static inline struct ip6t_entry * get_entry(void *base, unsigned int offset) { return (struct ip6t_entry *)(base + offset); } /* Returns one of the generic firewall policies, like NF_ACCEPT. */ unsigned int ip6t_do_table(struct sk_buff **pskb, unsigned int hook, const struct net_device *in, const struct net_device *out, struct ip6t_table *table, void *userdata) { static const char nulldevname[IFNAMSIZ] = { 0 }; u_int16_t offset = 0; struct ipv6hdr *ipv6; void *protohdr; u_int16_t datalen; int hotdrop = 0; /* Initializing verdict to NF_DROP keeps gcc happy. */ unsigned int verdict = NF_DROP; const char *indev, *outdev; void *table_base; struct ip6t_entry *e, *back; /* Initialization */ ipv6 = (*pskb)->nh.ipv6h; protohdr = (u_int32_t *)((char *)ipv6 + IPV6_HDR_LEN); datalen = (*pskb)->len - IPV6_HDR_LEN; indev = in ? in->name : nulldevname; outdev = out ? out->name : nulldevname; /* We handle fragments by dealing with the first fragment as * if it was a normal packet. All other fragments are treated * normally, except that they will NEVER match rules that ask * things we don't know, ie. tcp syn flag or ports). If the * rule is also a fragment-specific rule, non-fragments won't * match it. */ read_lock_bh(&table->lock); IP_NF_ASSERT(table->valid_hooks & (1 << hook)); table_base = (void *)table->private->entries + TABLE_OFFSET(table->private, cpu_number_map(smp_processor_id())); e = get_entry(table_base, table->private->hook_entry[hook]); #ifdef CONFIG_NETFILTER_DEBUG /* Check noone else using our table */ if (((struct ip6t_entry *)table_base)->comefrom != 0xdead57ac && ((struct ip6t_entry *)table_base)->comefrom != 0xeeeeeeec) { printk("ASSERT: CPU #%u, %s comefrom(%p) = %X\n", smp_processor_id(), table->name, &((struct ip6t_entry *)table_base)->comefrom, ((struct ip6t_entry *)table_base)->comefrom); } ((struct ip6t_entry *)table_base)->comefrom = 0x57acc001; #endif /* For return from builtin chain */ back = get_entry(table_base, table->private->underflow[hook]); do { IP_NF_ASSERT(e); IP_NF_ASSERT(back); (*pskb)->nfcache |= e->nfcache; if (ip6_packet_match(*pskb, ipv6, indev, outdev, &e->ipv6, offset)) { struct ip6t_entry_target *t; if (IP6T_MATCH_ITERATE(e, do_match, *pskb, in, out, offset, protohdr, datalen, &hotdrop) != 0) goto no_match; ADD_COUNTER(e->counters, ntohs(ipv6->payload_len) + IPV6_HDR_LEN, 1); t = ip6t_get_target(e); IP_NF_ASSERT(t->u.kernel.target); /* Standard target? */ if (!t->u.kernel.target->target) { int v; v = ((struct ip6t_standard_target *)t)->verdict; if (v < 0) { /* Pop from stack? */ if (v != IP6T_RETURN) { verdict = (unsigned)(-v) - 1; break; } e = back; back = get_entry(table_base, back->comefrom); continue; } if (table_base + v != (void *)e + e->next_offset) { /* Save old back ptr in next entry */ struct ip6t_entry *next = (void *)e + e->next_offset; next->comefrom = (void *)back - table_base; /* set back pointer to next entry */ back = next; } e = get_entry(table_base, v); } else { /* Targets which reenter must return abs. verdicts */ #ifdef CONFIG_NETFILTER_DEBUG ((struct ip6t_entry *)table_base)->comefrom = 0xeeeeeeec; #endif verdict = t->u.kernel.target->target(pskb, hook, in, out, t->data, userdata); #ifdef CONFIG_NETFILTER_DEBUG if (((struct ip6t_entry *)table_base)->comefrom != 0xeeeeeeec && verdict == IP6T_CONTINUE) { printk("Target %s reentered!\n", t->u.kernel.target->name); verdict = NF_DROP; } ((struct ip6t_entry *)table_base)->comefrom = 0x57acc001; #endif /* Target might have changed stuff. */ ipv6 = (*pskb)->nh.ipv6h; protohdr = (u_int32_t *)((void *)ipv6 + IPV6_HDR_LEN); datalen = (*pskb)->len - IPV6_HDR_LEN; if (verdict == IP6T_CONTINUE) e = (void *)e + e->next_offset; else /* Verdict */ break; } } else { no_match: e = (void *)e + e->next_offset; } } while (!hotdrop); #ifdef CONFIG_NETFILTER_DEBUG ((struct ip6t_entry *)table_base)->comefrom = 0xdead57ac; #endif read_unlock_bh(&table->lock); #ifdef DEBUG_ALLOW_ALL return NF_ACCEPT; #else if (hotdrop) return NF_DROP; else return verdict; #endif } /* If it succeeds, returns element and locks mutex */ static inline void * find_inlist_lock_noload(struct list_head *head, const char *name, int *error, struct semaphore *mutex) { void *ret; #if 1 duprintf("find_inlist: searching for `%s' in %s.\n", name, head == &ip6t_target ? "ip6t_target" : head == &ip6t_match ? "ip6t_match" : head == &ip6t_tables ? "ip6t_tables" : "UNKNOWN"); #endif *error = down_interruptible(mutex); if (*error != 0) return NULL; ret = list_named_find(head, name); if (!ret) { *error = -ENOENT; up(mutex); } return ret; } #ifndef CONFIG_KMOD #define find_inlist_lock(h,n,p,e,m) find_inlist_lock_noload((h),(n),(e),(m)) #else static void * find_inlist_lock(struct list_head *head, const char *name, const char *prefix, int *error, struct semaphore *mutex) { void *ret; ret = find_inlist_lock_noload(head, name, error, mutex); if (!ret) { char modulename[IP6T_FUNCTION_MAXNAMELEN + strlen(prefix) + 1]; strcpy(modulename, prefix); strcat(modulename, name); duprintf("find_inlist: loading `%s'.\n", modulename); request_module(modulename); ret = find_inlist_lock_noload(head, name, error, mutex); } return ret; } #endif static inline struct ip6t_table * find_table_lock(const char *name, int *error, struct semaphore *mutex) { return find_inlist_lock(&ip6t_tables, name, "ip6table_", error, mutex); } static inline struct ip6t_match * find_match_lock(const char *name, int *error, struct semaphore *mutex) { return find_inlist_lock(&ip6t_match, name, "ip6t_", error, mutex); } static inline struct ip6t_target * find_target_lock(const char *name, int *error, struct semaphore *mutex) { return find_inlist_lock(&ip6t_target, name, "ip6t_", error, mutex); } /* All zeroes == unconditional rule. */ static inline int unconditional(const struct ip6t_ip6 *ipv6) { unsigned int i; for (i = 0; i < sizeof(*ipv6); i++) if (((char *)ipv6)[i]) break; return (i == sizeof(*ipv6)); } /* Figures out from what hook each rule can be called: returns 0 if there are loops. Puts hook bitmask in comefrom. */ static int mark_source_chains(struct ip6t_table_info *newinfo, unsigned int valid_hooks) { unsigned int hook; /* No recursion; use packet counter to save back ptrs (reset to 0 as we leave), and comefrom to save source hook bitmask */ for (hook = 0; hook < NF_IP6_NUMHOOKS; hook++) { unsigned int pos = newinfo->hook_entry[hook]; struct ip6t_entry *e = (struct ip6t_entry *)(newinfo->entries + pos); if (!(valid_hooks & (1 << hook))) continue; /* Set initial back pointer. */ e->counters.pcnt = pos; for (;;) { struct ip6t_standard_target *t = (void *)ip6t_get_target(e); if (e->comefrom & (1 << NF_IP6_NUMHOOKS)) { printk("iptables: loop hook %u pos %u %08X.\n", hook, pos, e->comefrom); return 0; } e->comefrom |= ((1 << hook) | (1 << NF_IP6_NUMHOOKS)); /* Unconditional return/END. */ if (e->target_offset == sizeof(struct ip6t_entry) && (strcmp(t->target.u.user.name, IP6T_STANDARD_TARGET) == 0) && t->verdict < 0 && unconditional(&e->ipv6)) { unsigned int oldpos, size; /* Return: backtrack through the last big jump. */ do { e->comefrom ^= (1<<NF_IP6_NUMHOOKS); #ifdef DEBUG_IP_FIREWALL_USER if (e->comefrom & (1 << NF_IP6_NUMHOOKS)) { duprintf("Back unset " "on hook %u " "rule %u\n", hook, pos); } #endif oldpos = pos; pos = e->counters.pcnt; e->counters.pcnt = 0; /* We're at the start. */ if (pos == oldpos) goto next; e = (struct ip6t_entry *) (newinfo->entries + pos); } while (oldpos == pos + e->next_offset); /* Move along one */ size = e->next_offset; e = (struct ip6t_entry *) (newinfo->entries + pos + size); e->counters.pcnt = pos; pos += size; } else { int newpos = t->verdict; if (strcmp(t->target.u.user.name, IP6T_STANDARD_TARGET) == 0 && newpos >= 0) { /* This a jump; chase it. */ duprintf("Jump rule %u -> %u\n", pos, newpos); } else { /* ... this is a fallthru */ newpos = pos + e->next_offset; } e = (struct ip6t_entry *) (newinfo->entries + newpos); e->counters.pcnt = pos; pos = newpos; } } next: duprintf("Finished chain %u\n", hook); } return 1; } static inline int cleanup_match(struct ip6t_entry_match *m, unsigned int *i) { if (i && (*i)-- == 0) return 1; if (m->u.kernel.match->destroy) m->u.kernel.match->destroy(m->data, m->u.match_size - sizeof(*m)); if (m->u.kernel.match->me) __MOD_DEC_USE_COUNT(m->u.kernel.match->me); return 0; } static inline int standard_check(const struct ip6t_entry_target *t, unsigned int max_offset) { struct ip6t_standard_target *targ = (void *)t; /* Check standard info. */ if (t->u.target_size != IP6T_ALIGN(sizeof(struct ip6t_standard_target))) { duprintf("standard_check: target size %u != %u\n", t->u.target_size, IP6T_ALIGN(sizeof(struct ip6t_standard_target))); return 0; } if (targ->verdict >= 0 && targ->verdict > max_offset - sizeof(struct ip6t_entry)) { duprintf("ip6t_standard_check: bad verdict (%i)\n", targ->verdict); return 0; } if (targ->verdict < -NF_MAX_VERDICT - 1) { duprintf("ip6t_standard_check: bad negative verdict (%i)\n", targ->verdict); return 0; } return 1; } static inline int check_match(struct ip6t_entry_match *m, const char *name, const struct ip6t_ip6 *ipv6, unsigned int hookmask, unsigned int *i) { int ret; struct ip6t_match *match; match = find_match_lock(m->u.user.name, &ret, &ip6t_mutex); if (!match) { // duprintf("check_match: `%s' not found\n", m->u.name); return ret; } if (match->me) __MOD_INC_USE_COUNT(match->me); m->u.kernel.match = match; up(&ip6t_mutex); if (m->u.kernel.match->checkentry && !m->u.kernel.match->checkentry(name, ipv6, m->data, m->u.match_size - sizeof(*m), hookmask)) { if (m->u.kernel.match->me) __MOD_DEC_USE_COUNT(m->u.kernel.match->me); duprintf("ip_tables: check failed for `%s'.\n", m->u.kernel.match->name); return -EINVAL; } (*i)++; return 0; } static struct ip6t_target ip6t_standard_target; static inline int check_entry(struct ip6t_entry *e, const char *name, unsigned int size, unsigned int *i) { struct ip6t_entry_target *t; struct ip6t_target *target; int ret; unsigned int j; if (!ip6_checkentry(&e->ipv6)) { duprintf("ip_tables: ip check failed %p %s.\n", e, name); return -EINVAL; } j = 0; ret = IP6T_MATCH_ITERATE(e, check_match, name, &e->ipv6, e->comefrom, &j); if (ret != 0) goto cleanup_matches; t = ip6t_get_target(e); target = find_target_lock(t->u.user.name, &ret, &ip6t_mutex); if (!target) { duprintf("check_entry: `%s' not found\n", t->u.user.name); goto cleanup_matches; } if (target->me) __MOD_INC_USE_COUNT(target->me); t->u.kernel.target = target; up(&ip6t_mutex); if (t->u.kernel.target == &ip6t_standard_target) { if (!standard_check(t, size)) { ret = -EINVAL; goto cleanup_matches; } } else if (t->u.kernel.target->checkentry && !t->u.kernel.target->checkentry(name, e, t->data, t->u.target_size - sizeof(*t), e->comefrom)) { if (t->u.kernel.target->me) __MOD_DEC_USE_COUNT(t->u.kernel.target->me); duprintf("ip_tables: check failed for `%s'.\n", t->u.kernel.target->name); ret = -EINVAL; goto cleanup_matches; } (*i)++; return 0; cleanup_matches: IP6T_MATCH_ITERATE(e, cleanup_match, &j); return ret; } static inline int check_entry_size_and_hooks(struct ip6t_entry *e, struct ip6t_table_info *newinfo, unsigned char *base, unsigned char *limit, const unsigned int *hook_entries, const unsigned int *underflows, unsigned int *i) { unsigned int h; if ((unsigned long)e % __alignof__(struct ip6t_entry) != 0 || (unsigned char *)e + sizeof(struct ip6t_entry) >= limit) { duprintf("Bad offset %p\n", e); return -EINVAL; } if (e->next_offset < sizeof(struct ip6t_entry) + sizeof(struct ip6t_entry_target)) { duprintf("checking: element %p size %u\n", e, e->next_offset); return -EINVAL; } /* Check hooks & underflows */ for (h = 0; h < NF_IP6_NUMHOOKS; h++) { if ((unsigned char *)e - base == hook_entries[h]) newinfo->hook_entry[h] = hook_entries[h]; if ((unsigned char *)e - base == underflows[h]) newinfo->underflow[h] = underflows[h]; } /* FIXME: underflows must be unconditional, standard verdicts < 0 (not IP6T_RETURN). --RR */ /* Clear counters and comefrom */ e->counters = ((struct ip6t_counters) { 0, 0 }); e->comefrom = 0; (*i)++; return 0; } static inline int cleanup_entry(struct ip6t_entry *e, unsigned int *i) { struct ip6t_entry_target *t; if (i && (*i)-- == 0) return 1; /* Cleanup all matches */ IP6T_MATCH_ITERATE(e, cleanup_match, NULL); t = ip6t_get_target(e); if (t->u.kernel.target->destroy) t->u.kernel.target->destroy(t->data, t->u.target_size - sizeof(*t)); if (t->u.kernel.target->me) __MOD_DEC_USE_COUNT(t->u.kernel.target->me); return 0; } /* Checks and translates the user-supplied table segment (held in newinfo) */ static int translate_table(const char *name, unsigned int valid_hooks, struct ip6t_table_info *newinfo, unsigned int size, unsigned int number, const unsigned int *hook_entries, const unsigned int *underflows) { unsigned int i; int ret; newinfo->size = size; newinfo->number = number; /* Init all hooks to impossible value. */ for (i = 0; i < NF_IP6_NUMHOOKS; i++) { newinfo->hook_entry[i] = 0xFFFFFFFF; newinfo->underflow[i] = 0xFFFFFFFF; } duprintf("translate_table: size %u\n", newinfo->size); i = 0; /* Walk through entries, checking offsets. */ ret = IP6T_ENTRY_ITERATE(newinfo->entries, newinfo->size, check_entry_size_and_hooks, newinfo, newinfo->entries, newinfo->entries + size, hook_entries, underflows, &i); if (ret != 0) return ret; if (i != number) { duprintf("translate_table: %u not %u entries\n", i, number); return -EINVAL; } /* Check hooks all assigned */ for (i = 0; i < NF_IP6_NUMHOOKS; i++) { /* Only hooks which are valid */ if (!(valid_hooks & (1 << i))) continue; if (newinfo->hook_entry[i] == 0xFFFFFFFF) { duprintf("Invalid hook entry %u %u\n", i, hook_entries[i]); return -EINVAL; } if (newinfo->underflow[i] == 0xFFFFFFFF) { duprintf("Invalid underflow %u %u\n", i, underflows[i]); return -EINVAL; } } if (!mark_source_chains(newinfo, valid_hooks)) return -ELOOP; /* Finally, each sanity check must pass */ i = 0; ret = IP6T_ENTRY_ITERATE(newinfo->entries, newinfo->size, check_entry, name, size, &i); if (ret != 0) { IP6T_ENTRY_ITERATE(newinfo->entries, newinfo->size, cleanup_entry, &i); return ret; } /* And one copy for every other CPU */ for (i = 1; i < smp_num_cpus; i++) { memcpy(newinfo->entries + SMP_ALIGN(newinfo->size)*i, newinfo->entries, SMP_ALIGN(newinfo->size)); } return ret; } static struct ip6t_table_info * replace_table(struct ip6t_table *table, unsigned int num_counters, struct ip6t_table_info *newinfo, int *error) { struct ip6t_table_info *oldinfo; #ifdef CONFIG_NETFILTER_DEBUG { struct ip6t_entry *table_base; unsigned int i; for (i = 0; i < smp_num_cpus; i++) { table_base = (void *)newinfo->entries + TABLE_OFFSET(newinfo, i); table_base->comefrom = 0xdead57ac; } } #endif /* Do the substitution. */ write_lock_bh(&table->lock); /* Check inside lock: is the old number correct? */ if (num_counters != table->private->number) { duprintf("num_counters != table->private->number (%u/%u)\n", num_counters, table->private->number); write_unlock_bh(&table->lock); *error = -EAGAIN; return NULL; } oldinfo = table->private; table->private = newinfo; newinfo->initial_entries = oldinfo->initial_entries; write_unlock_bh(&table->lock); return oldinfo; } /* Gets counters. */ static inline int add_entry_to_counter(const struct ip6t_entry *e, struct ip6t_counters total[], unsigned int *i) { ADD_COUNTER(total[*i], e->counters.bcnt, e->counters.pcnt); (*i)++; return 0; } static void get_counters(const struct ip6t_table_info *t, struct ip6t_counters counters[]) { unsigned int cpu; unsigned int i; for (cpu = 0; cpu < smp_num_cpus; cpu++) { i = 0; IP6T_ENTRY_ITERATE(t->entries + TABLE_OFFSET(t, cpu), t->size, add_entry_to_counter, counters, &i); } } static int copy_entries_to_user(unsigned int total_size, struct ip6t_table *table, void *userptr) { unsigned int off, num, countersize; struct ip6t_entry *e; struct ip6t_counters *counters; int ret = 0; /* We need atomic snapshot of counters: rest doesn't change (other than comefrom, which userspace doesn't care about). */ countersize = sizeof(struct ip6t_counters) * table->private->number; counters = vmalloc(countersize); if (counters == NULL) return -ENOMEM; /* First, sum counters... */ memset(counters, 0, countersize); write_lock_bh(&table->lock); get_counters(table->private, counters); write_unlock_bh(&table->lock); /* ... then copy entire thing from CPU 0... */ if (copy_to_user(userptr, table->private->entries, total_size) != 0) { ret = -EFAULT; goto free_counters; } /* FIXME: use iterator macros --RR */ /* ... then go back and fix counters and names */ for (off = 0, num = 0; off < total_size; off += e->next_offset, num++){ unsigned int i; struct ip6t_entry_match *m; struct ip6t_entry_target *t; e = (struct ip6t_entry *)(table->private->entries + off); if (copy_to_user(userptr + off + offsetof(struct ip6t_entry, counters), &counters[num], sizeof(counters[num])) != 0) { ret = -EFAULT; goto free_counters; } for (i = sizeof(struct ip6t_entry); i < e->target_offset; i += m->u.match_size) { m = (void *)e + i; if (copy_to_user(userptr + off + i + offsetof(struct ip6t_entry_match, u.user.name), m->u.kernel.match->name, strlen(m->u.kernel.match->name)+1) != 0) { ret = -EFAULT; goto free_counters; } } t = ip6t_get_target(e); if (copy_to_user(userptr + off + e->target_offset + offsetof(struct ip6t_entry_target, u.user.name), t->u.kernel.target->name, strlen(t->u.kernel.target->name)+1) != 0) { ret = -EFAULT; goto free_counters; } } free_counters: vfree(counters); return ret; } static int get_entries(const struct ip6t_get_entries *entries, struct ip6t_get_entries *uptr) { int ret; struct ip6t_table *t; t = find_table_lock(entries->name, &ret, &ip6t_mutex); if (t) { duprintf("t->private->number = %u\n", t->private->number); if (entries->size == t->private->size) ret = copy_entries_to_user(t->private->size, t, uptr->entrytable); else { duprintf("get_entries: I've got %u not %u!\n", t->private->size, entries->size); ret = -EINVAL; } up(&ip6t_mutex); } else duprintf("get_entries: Can't find %s!\n", entries->name); return ret; } static int do_replace(void *user, unsigned int len) { int ret; struct ip6t_replace tmp; struct ip6t_table *t; struct ip6t_table_info *newinfo, *oldinfo; struct ip6t_counters *counters; if (copy_from_user(&tmp, user, sizeof(tmp)) != 0) return -EFAULT; /* Pedantry: prevent them from hitting BUG() in vmalloc.c --RR */ if ((SMP_ALIGN(tmp.size) >> PAGE_SHIFT) + 2 > num_physpages) return -ENOMEM; newinfo = vmalloc(sizeof(struct ip6t_table_info) + SMP_ALIGN(tmp.size) * smp_num_cpus); if (!newinfo) return -ENOMEM; if (copy_from_user(newinfo->entries, user + sizeof(tmp), tmp.size) != 0) { ret = -EFAULT; goto free_newinfo; } counters = vmalloc(tmp.num_counters * sizeof(struct ip6t_counters)); if (!counters) { ret = -ENOMEM; goto free_newinfo; } memset(counters, 0, tmp.num_counters * sizeof(struct ip6t_counters)); ret = translate_table(tmp.name, tmp.valid_hooks, newinfo, tmp.size, tmp.num_entries, tmp.hook_entry, tmp.underflow); if (ret != 0) goto free_newinfo_counters; duprintf("ip_tables: Translated table\n"); t = find_table_lock(tmp.name, &ret, &ip6t_mutex); if (!t) goto free_newinfo_counters_untrans; /* You lied! */ if (tmp.valid_hooks != t->valid_hooks) { duprintf("Valid hook crap: %08X vs %08X\n", tmp.valid_hooks, t->valid_hooks); ret = -EINVAL; goto free_newinfo_counters_untrans_unlock; } oldinfo = replace_table(t, tmp.num_counters, newinfo, &ret); if (!oldinfo) goto free_newinfo_counters_untrans_unlock; /* Update module usage count based on number of rules */ duprintf("do_replace: oldnum=%u, initnum=%u, newnum=%u\n", oldinfo->number, oldinfo->initial_entries, newinfo->number); if (t->me && (oldinfo->number <= oldinfo->initial_entries) && (newinfo->number > oldinfo->initial_entries)) __MOD_INC_USE_COUNT(t->me); else if (t->me && (oldinfo->number > oldinfo->initial_entries) && (newinfo->number <= oldinfo->initial_entries)) __MOD_DEC_USE_COUNT(t->me); /* Get the old counters. */ get_counters(oldinfo, counters); /* Decrease module usage counts and free resource */ IP6T_ENTRY_ITERATE(oldinfo->entries, oldinfo->size, cleanup_entry,NULL); vfree(oldinfo); /* Silent error: too late now. */ copy_to_user(tmp.counters, counters, sizeof(struct ip6t_counters) * tmp.num_counters); vfree(counters); up(&ip6t_mutex); return 0; free_newinfo_counters_untrans_unlock: up(&ip6t_mutex); free_newinfo_counters_untrans: IP6T_ENTRY_ITERATE(newinfo->entries, newinfo->size, cleanup_entry,NULL); free_newinfo_counters: vfree(counters); free_newinfo: vfree(newinfo); return ret; } /* We're lazy, and add to the first CPU; overflow works its fey magic * and everything is OK. */ static inline int add_counter_to_entry(struct ip6t_entry *e, const struct ip6t_counters addme[], unsigned int *i) { #if 0 duprintf("add_counter: Entry %u %lu/%lu + %lu/%lu\n", *i, (long unsigned int)e->counters.pcnt, (long unsigned int)e->counters.bcnt, (long unsigned int)addme[*i].pcnt, (long unsigned int)addme[*i].bcnt); #endif ADD_COUNTER(e->counters, addme[*i].bcnt, addme[*i].pcnt); (*i)++; return 0; } static int do_add_counters(void *user, unsigned int len) { unsigned int i; struct ip6t_counters_info tmp, *paddc; struct ip6t_table *t; int ret; if (copy_from_user(&tmp, user, sizeof(tmp)) != 0) return -EFAULT; if (len != sizeof(tmp) + tmp.num_counters*sizeof(struct ip6t_counters)) return -EINVAL; paddc = vmalloc(len); if (!paddc) return -ENOMEM; if (copy_from_user(paddc, user, len) != 0) { ret = -EFAULT; goto free; } t = find_table_lock(tmp.name, &ret, &ip6t_mutex); if (!t) goto free; write_lock_bh(&t->lock); if (t->private->number != paddc->num_counters) { ret = -EINVAL; goto unlock_up_free; } i = 0; IP6T_ENTRY_ITERATE(t->private->entries, t->private->size, add_counter_to_entry, paddc->counters, &i); unlock_up_free: write_unlock_bh(&t->lock); up(&ip6t_mutex); free: vfree(paddc); return ret; } static int do_ip6t_set_ctl(struct sock *sk, int cmd, void *user, unsigned int len) { int ret; if (!capable(CAP_NET_ADMIN)) return -EPERM; switch (cmd) { case IP6T_SO_SET_REPLACE: ret = do_replace(user, len); break; case IP6T_SO_SET_ADD_COUNTERS: ret = do_add_counters(user, len); break; default: duprintf("do_ip6t_set_ctl: unknown request %i\n", cmd); ret = -EINVAL; } return ret; } static int do_ip6t_get_ctl(struct sock *sk, int cmd, void *user, int *len) { int ret; if (!capable(CAP_NET_ADMIN)) return -EPERM; switch (cmd) { case IP6T_SO_GET_INFO: { char name[IP6T_TABLE_MAXNAMELEN]; struct ip6t_table *t; if (*len != sizeof(struct ip6t_getinfo)) { duprintf("length %u != %u\n", *len, sizeof(struct ip6t_getinfo)); ret = -EINVAL; break; } if (copy_from_user(name, user, sizeof(name)) != 0) { ret = -EFAULT; break; } name[IP6T_TABLE_MAXNAMELEN-1] = '\0'; t = find_table_lock(name, &ret, &ip6t_mutex); if (t) { struct ip6t_getinfo info; info.valid_hooks = t->valid_hooks; memcpy(info.hook_entry, t->private->hook_entry, sizeof(info.hook_entry)); memcpy(info.underflow, t->private->underflow, sizeof(info.underflow)); info.num_entries = t->private->number; info.size = t->private->size; strcpy(info.name, name); if (copy_to_user(user, &info, *len) != 0) ret = -EFAULT; else ret = 0; up(&ip6t_mutex); } } break; case IP6T_SO_GET_ENTRIES: { struct ip6t_get_entries get; if (*len < sizeof(get)) { duprintf("get_entries: %u < %u\n", *len, sizeof(get)); ret = -EINVAL; } else if (copy_from_user(&get, user, sizeof(get)) != 0) { ret = -EFAULT; } else if (*len != sizeof(struct ip6t_get_entries) + get.size) { duprintf("get_entries: %u != %u\n", *len, sizeof(struct ip6t_get_entries) + get.size); ret = -EINVAL; } else ret = get_entries(&get, user); break; } default: duprintf("do_ip6t_get_ctl: unknown request %i\n", cmd); ret = -EINVAL; } return ret; } /* Registration hooks for targets. */ int ip6t_register_target(struct ip6t_target *target) { int ret; MOD_INC_USE_COUNT; ret = down_interruptible(&ip6t_mutex); if (ret != 0) { MOD_DEC_USE_COUNT; return ret; } if (!list_named_insert(&ip6t_target, target)) { duprintf("ip6t_register_target: `%s' already in list!\n", target->name); ret = -EINVAL; MOD_DEC_USE_COUNT; } up(&ip6t_mutex); return ret; } void ip6t_unregister_target(struct ip6t_target *target) { down(&ip6t_mutex); LIST_DELETE(&ip6t_target, target); up(&ip6t_mutex); MOD_DEC_USE_COUNT; } int ip6t_register_match(struct ip6t_match *match) { int ret; MOD_INC_USE_COUNT; ret = down_interruptible(&ip6t_mutex); if (ret != 0) { MOD_DEC_USE_COUNT; return ret; } if (!list_named_insert(&ip6t_match, match)) { duprintf("ip6t_register_match: `%s' already in list!\n", match->name); MOD_DEC_USE_COUNT; ret = -EINVAL; } up(&ip6t_mutex); return ret; } void ip6t_unregister_match(struct ip6t_match *match) { down(&ip6t_mutex); LIST_DELETE(&ip6t_match, match); up(&ip6t_mutex); MOD_DEC_USE_COUNT; } int ip6t_register_table(struct ip6t_table *table) { int ret; struct ip6t_table_info *newinfo; static struct ip6t_table_info bootstrap = { 0, 0, 0, { 0 }, { 0 }, { } }; MOD_INC_USE_COUNT; newinfo = vmalloc(sizeof(struct ip6t_table_info) + SMP_ALIGN(table->table->size) * smp_num_cpus); if (!newinfo) { ret = -ENOMEM; MOD_DEC_USE_COUNT; return ret; } memcpy(newinfo->entries, table->table->entries, table->table->size); ret = translate_table(table->name, table->valid_hooks, newinfo, table->table->size, table->table->num_entries, table->table->hook_entry, table->table->underflow); if (ret != 0) { vfree(newinfo); MOD_DEC_USE_COUNT; return ret; } ret = down_interruptible(&ip6t_mutex); if (ret != 0) { vfree(newinfo); MOD_DEC_USE_COUNT; return ret; } /* Don't autoload: we'd eat our tail... */ if (list_named_find(&ip6t_tables, table->name)) { ret = -EEXIST; goto free_unlock; } /* Simplifies replace_table code. */ table->private = &bootstrap; if (!replace_table(table, 0, newinfo, &ret)) goto free_unlock; duprintf("table->private->number = %u\n", table->private->number); /* save number of initial entries */ table->private->initial_entries = table->private->number; table->lock = RW_LOCK_UNLOCKED; list_prepend(&ip6t_tables, table); unlock: up(&ip6t_mutex); return ret; free_unlock: vfree(newinfo); MOD_DEC_USE_COUNT; goto unlock; } void ip6t_unregister_table(struct ip6t_table *table) { down(&ip6t_mutex); LIST_DELETE(&ip6t_tables, table); up(&ip6t_mutex); /* Decrease module usage counts and free resources */ IP6T_ENTRY_ITERATE(table->private->entries, table->private->size, cleanup_entry, NULL); vfree(table->private); MOD_DEC_USE_COUNT; } /* Returns 1 if the port is matched by the range, 0 otherwise */ static inline int port_match(u_int16_t min, u_int16_t max, u_int16_t port, int invert) { int ret; ret = (port >= min && port <= max) ^ invert; return ret; } static int tcp_find_option(u_int8_t option, const struct tcphdr *tcp, u_int16_t datalen, int invert, int *hotdrop) { unsigned int i = sizeof(struct tcphdr); const u_int8_t *opt = (u_int8_t *)tcp; duprintf("tcp_match: finding option\n"); /* If we don't have the whole header, drop packet. */ if (tcp->doff * 4 > datalen) { *hotdrop = 1; return 0; } while (i < tcp->doff * 4) { if (opt[i] == option) return !invert; if (opt[i] < 2) i++; else i += opt[i+1]?:1; } return invert; } static int tcp_match(const struct sk_buff *skb, const struct net_device *in, const struct net_device *out, const void *matchinfo, int offset, const void *hdr, u_int16_t datalen, int *hotdrop) { const struct tcphdr *tcp = hdr; const struct ip6t_tcp *tcpinfo = matchinfo; /* To quote Alan: Don't allow a fragment of TCP 8 bytes in. Nobody normal causes this. Its a cracker trying to break in by doing a flag overwrite to pass the direction checks. */ if (offset == 1) { duprintf("Dropping evil TCP offset=1 frag.\n"); *hotdrop = 1; return 0; } else if (offset == 0 && datalen < sizeof(struct tcphdr)) { /* We've been asked to examine this packet, and we can't. Hence, no choice but to drop. */ duprintf("Dropping evil TCP offset=0 tinygram.\n"); *hotdrop = 1; return 0; } /* FIXME: Try tcp doff >> packet len against various stacks --RR */ #define FWINVTCP(bool,invflg) ((bool) ^ !!(tcpinfo->invflags & invflg)) /* Must not be a fragment. */ return !offset && port_match(tcpinfo->spts[0], tcpinfo->spts[1], ntohs(tcp->source), !!(tcpinfo->invflags & IP6T_TCP_INV_SRCPT)) && port_match(tcpinfo->dpts[0], tcpinfo->dpts[1], ntohs(tcp->dest), !!(tcpinfo->invflags & IP6T_TCP_INV_DSTPT)) && FWINVTCP((((unsigned char *)tcp)[13] & tcpinfo->flg_mask) == tcpinfo->flg_cmp, IP6T_TCP_INV_FLAGS) && (!tcpinfo->option || tcp_find_option(tcpinfo->option, tcp, datalen, tcpinfo->invflags & IP6T_TCP_INV_OPTION, hotdrop)); } /* Called when user tries to insert an entry of this type. */ static int tcp_checkentry(const char *tablename, const struct ip6t_ip6 *ipv6, void *matchinfo, unsigned int matchsize, unsigned int hook_mask) { const struct ip6t_tcp *tcpinfo = matchinfo; /* Must specify proto == TCP, and no unknown invflags */ return ipv6->proto == IPPROTO_TCP && !(ipv6->invflags & IP6T_INV_PROTO) && matchsize == IP6T_ALIGN(sizeof(struct ip6t_tcp)) && !(tcpinfo->invflags & ~IP6T_TCP_INV_MASK); } static int udp_match(const struct sk_buff *skb, const struct net_device *in, const struct net_device *out, const void *matchinfo, int offset, const void *hdr, u_int16_t datalen, int *hotdrop) { const struct udphdr *udp = hdr; const struct ip6t_udp *udpinfo = matchinfo; if (offset == 0 && datalen < sizeof(struct udphdr)) { /* We've been asked to examine this packet, and we can't. Hence, no choice but to drop. */ duprintf("Dropping evil UDP tinygram.\n"); *hotdrop = 1; return 0; } /* Must not be a fragment. */ return !offset && port_match(udpinfo->spts[0], udpinfo->spts[1], ntohs(udp->source), !!(udpinfo->invflags & IP6T_UDP_INV_SRCPT)) && port_match(udpinfo->dpts[0], udpinfo->dpts[1], ntohs(udp->dest), !!(udpinfo->invflags & IP6T_UDP_INV_DSTPT)); } /* Called when user tries to insert an entry of this type. */ static int udp_checkentry(const char *tablename, const struct ip6t_ip6 *ipv6, void *matchinfo, unsigned int matchinfosize, unsigned int hook_mask) { const struct ip6t_udp *udpinfo = matchinfo; /* Must specify proto == UDP, and no unknown invflags */ if (ipv6->proto != IPPROTO_UDP || (ipv6->invflags & IP6T_INV_PROTO)) { duprintf("ip6t_udp: Protocol %u != %u\n", ipv6->proto, IPPROTO_UDP); return 0; } if (matchinfosize != IP6T_ALIGN(sizeof(struct ip6t_udp))) { duprintf("ip6t_udp: matchsize %u != %u\n", matchinfosize, IP6T_ALIGN(sizeof(struct ip6t_udp))); return 0; } if (udpinfo->invflags & ~IP6T_UDP_INV_MASK) { duprintf("ip6t_udp: unknown flags %X\n", udpinfo->invflags); return 0; } return 1; } /* Returns 1 if the type and code is matched by the range, 0 otherwise */ static inline int icmp6_type_code_match(u_int8_t test_type, u_int8_t min_code, u_int8_t max_code, u_int8_t type, u_int8_t code, int invert) { return (type == test_type && code >= min_code && code <= max_code) ^ invert; } static int icmp6_match(const struct sk_buff *skb, const struct net_device *in, const struct net_device *out, const void *matchinfo, int offset, const void *hdr, u_int16_t datalen, int *hotdrop) { const struct icmp6hdr *icmp = hdr; const struct ip6t_icmp *icmpinfo = matchinfo; if (offset == 0 && datalen < 2) { /* We've been asked to examine this packet, and we can't. Hence, no choice but to drop. */ duprintf("Dropping evil ICMP tinygram.\n"); *hotdrop = 1; return 0; } /* Must not be a fragment. */ return !offset && icmp6_type_code_match(icmpinfo->type, icmpinfo->code[0], icmpinfo->code[1], icmp->icmp6_type, icmp->icmp6_code, !!(icmpinfo->invflags&IP6T_ICMP_INV)); } /* Called when user tries to insert an entry of this type. */ static int icmp6_checkentry(const char *tablename, const struct ip6t_ip6 *ipv6, void *matchinfo, unsigned int matchsize, unsigned int hook_mask) { const struct ip6t_icmp *icmpinfo = matchinfo; /* Must specify proto == ICMP, and no unknown invflags */ return ipv6->proto == IPPROTO_ICMPV6 && !(ipv6->invflags & IP6T_INV_PROTO) && matchsize == IP6T_ALIGN(sizeof(struct ip6t_icmp)) && !(icmpinfo->invflags & ~IP6T_ICMP_INV); } /* The built-in targets: standard (NULL) and error. */ static struct ip6t_target ip6t_standard_target = { { NULL, NULL }, IP6T_STANDARD_TARGET, NULL, NULL, NULL }; static struct ip6t_target ip6t_error_target = { { NULL, NULL }, IP6T_ERROR_TARGET, ip6t_error, NULL, NULL }; static struct nf_sockopt_ops ip6t_sockopts = { { NULL, NULL }, PF_INET6, IP6T_BASE_CTL, IP6T_SO_SET_MAX+1, do_ip6t_set_ctl, IP6T_BASE_CTL, IP6T_SO_GET_MAX+1, do_ip6t_get_ctl, 0, NULL }; static struct ip6t_match tcp_matchstruct = { { NULL, NULL }, "tcp", &tcp_match, &tcp_checkentry, NULL }; static struct ip6t_match udp_matchstruct = { { NULL, NULL }, "udp", &udp_match, &udp_checkentry, NULL }; static struct ip6t_match icmp6_matchstruct = { { NULL, NULL }, "icmp6", &icmp6_match, &icmp6_checkentry, NULL }; #ifdef CONFIG_PROC_FS static inline int print_name(const char *i, off_t start_offset, char *buffer, int length, off_t *pos, unsigned int *count) { if ((*count)++ >= start_offset) { unsigned int namelen; namelen = sprintf(buffer + *pos, "%s\n", i + sizeof(struct list_head)); if (*pos + namelen > length) { /* Stop iterating */ return 1; } *pos += namelen; } return 0; } static int ip6t_get_tables(char *buffer, char **start, off_t offset, int length) { off_t pos = 0; unsigned int count = 0; if (down_interruptible(&ip6t_mutex) != 0) return 0; LIST_FIND(&ip6t_tables, print_name, char *, offset, buffer, length, &pos, &count); up(&ip6t_mutex); /* `start' hack - see fs/proc/generic.c line ~105 */ *start=(char *)((unsigned long)count-offset); return pos; } static int ip6t_get_targets(char *buffer, char **start, off_t offset, int length) { off_t pos = 0; unsigned int count = 0; if (down_interruptible(&ip6t_mutex) != 0) return 0; LIST_FIND(&ip6t_target, print_name, char *, offset, buffer, length, &pos, &count); up(&ip6t_mutex); *start = (char *)((unsigned long)count - offset); return pos; } static int ip6t_get_matches(char *buffer, char **start, off_t offset, int length) { off_t pos = 0; unsigned int count = 0; if (down_interruptible(&ip6t_mutex) != 0) return 0; LIST_FIND(&ip6t_match, print_name, char *, offset, buffer, length, &pos, &count); up(&ip6t_mutex); *start = (char *)((unsigned long)count - offset); return pos; } static struct { char *name; get_info_t *get_info; } ip6t_proc_entry[] = { { "ip6_tables_names", ip6t_get_tables }, { "ip6_tables_targets", ip6t_get_targets }, { "ip6_tables_matches", ip6t_get_matches }, { NULL, NULL} }; #endif /*CONFIG_PROC_FS*/ static int __init init(void) { int ret; /* Noone else will be downing sem now, so we won't sleep */ down(&ip6t_mutex); list_append(&ip6t_target, &ip6t_standard_target); list_append(&ip6t_target, &ip6t_error_target); list_append(&ip6t_match, &tcp_matchstruct); list_append(&ip6t_match, &udp_matchstruct); list_append(&ip6t_match, &icmp6_matchstruct); up(&ip6t_mutex); /* Register setsockopt */ ret = nf_register_sockopt(&ip6t_sockopts); if (ret < 0) { duprintf("Unable to register sockopts.\n"); return ret; } #ifdef CONFIG_PROC_FS { struct proc_dir_entry *proc; int i; for (i = 0; ip6t_proc_entry[i].name; i++) { proc = proc_net_create(ip6t_proc_entry[i].name, 0, ip6t_proc_entry[i].get_info); if (!proc) { while (--i >= 0) proc_net_remove(ip6t_proc_entry[i].name); nf_unregister_sockopt(&ip6t_sockopts); return -ENOMEM; } proc->owner = THIS_MODULE; } } #endif printk("ip6_tables: (C) 2000-2002 Netfilter core team\n"); return 0; } static void __exit fini(void) { nf_unregister_sockopt(&ip6t_sockopts); #ifdef CONFIG_PROC_FS { int i; for (i = 0; ip6t_proc_entry[i].name; i++) proc_net_remove(ip6t_proc_entry[i].name); } #endif } EXPORT_SYMBOL(ip6t_register_table); EXPORT_SYMBOL(ip6t_unregister_table); EXPORT_SYMBOL(ip6t_do_table); EXPORT_SYMBOL(ip6t_register_match); EXPORT_SYMBOL(ip6t_unregister_match); EXPORT_SYMBOL(ip6t_register_target); EXPORT_SYMBOL(ip6t_unregister_target); EXPORT_SYMBOL(ip6t_ext_hdr); module_init(init); module_exit(fini); MODULE_LICENSE("GPL");
dduval/kernel-rhel3
net/ipv6/netfilter/ip6_tables.c
C
gpl-2.0
48,029
/***************************************************************************** * effects.c : Effects for the visualization system ***************************************************************************** * Copyright (C) 2002-2009 VLC authors and VideoLAN * $Id$ * * Authors: Clément Stenac <zorglub@via.ecp.fr> * Adrien Maglo <magsoft@videolan.org> * * 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; either version 2.1 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 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., 51 Franklin Street, Fifth Floor, Boston MA 02110-1301, USA. *****************************************************************************/ /***************************************************************************** * Preamble *****************************************************************************/ #ifdef HAVE_CONFIG_H # include "config.h" #endif #include <vlc_common.h> #include <vlc_vout.h> #include <vlc_aout.h> #include "visual.h" #include <math.h> #include "fft.h" #include "window.h" #define PEAK_SPEED 1 #define BAR_DECREASE_SPEED 5 #define GRAD_ANGLE_MIN 0.2 #define GRAD_ANGLE_MAX 0.5 #define GRAD_INCR 0.01 /***************************************************************************** * dummy_Run *****************************************************************************/ static int dummy_Run( visual_effect_t * p_effect, vlc_object_t *p_aout, const block_t * p_buffer , picture_t * p_picture) { VLC_UNUSED(p_effect); VLC_UNUSED(p_aout); VLC_UNUSED(p_buffer); VLC_UNUSED(p_picture); return 0; } static void dummy_Free( void *data ) { VLC_UNUSED(data); } /***************************************************************************** * spectrum_Run: spectrum analyser *****************************************************************************/ typedef struct spectrum_data { int *peaks; int *prev_heights; unsigned i_prev_nb_samples; int16_t *p_prev_s16_buff; window_param wind_param; } spectrum_data; static int spectrum_Run(visual_effect_t * p_effect, vlc_object_t *p_aout, const block_t * p_buffer , picture_t * p_picture) { spectrum_data *p_data = p_effect->p_data; float p_output[FFT_BUFFER_SIZE]; /* Raw FFT Result */ int *height; /* Bar heights */ int *peaks; /* Peaks */ int *prev_heights; /* Previous bar heights */ int i_80_bands; /* number of bands : 80 if true else 20 */ int i_nb_bands; /* number of bands : 80 or 20 */ int i_band_width; /* width of bands */ int i_start; /* first band horizontal position */ int i_peak; /* Should we draw peaks ? */ /* Horizontal scale for 20-band equalizer */ const int xscale1[]={0,1,2,3,4,5,6,7,8,11,15,20,27, 36,47,62,82,107,141,184,255}; /* Horizontal scale for 80-band equalizer */ const int xscale2[] = {0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18, 19,20,21,22,23,24,25,26,27,28,29,30,31,32,33,34, 35,36,37,38,39,40,41,42,43,44,45,46,47,48,49,50,51, 52,53,54,55,56,57,58,59,61,63,67,72,77,82,87,93,99,105, 110,115,121,130,141,152,163,174,185,200,255}; const int *xscale; fft_state *p_state; /* internal FFT data */ DEFINE_WIND_CONTEXT( wind_ctx ); /* internal window data */ int i , j , y , k; int i_line; int16_t p_dest[FFT_BUFFER_SIZE]; /* Adapted FFT result */ int16_t p_buffer1[FFT_BUFFER_SIZE]; /* Buffer on which we perform the FFT (first channel) */ float *p_buffl = /* Original buffer */ (float*)p_buffer->p_buffer; int16_t *p_buffs; /* int16_t converted buffer */ int16_t *p_s16_buff; /* int16_t converted buffer */ if (!p_buffer->i_nb_samples) { msg_Err(p_aout, "no samples yet"); return -1; } /* Create p_data if needed */ if( !p_data ) { p_effect->p_data = p_data = malloc( sizeof( spectrum_data ) ); if( !p_data ) return -1; p_data->peaks = calloc( 80, sizeof(int) ); p_data->prev_heights = calloc( 80, sizeof(int) ); p_data->i_prev_nb_samples = 0; p_data->p_prev_s16_buff = NULL; window_get_param( p_aout, &p_data->wind_param ); } peaks = (int *)p_data->peaks; prev_heights = (int *)p_data->prev_heights; /* Allocate the buffer only if the number of samples change */ if( p_buffer->i_nb_samples != p_data->i_prev_nb_samples ) { free( p_data->p_prev_s16_buff ); p_data->p_prev_s16_buff = malloc( p_buffer->i_nb_samples * p_effect->i_nb_chans * sizeof(int16_t)); p_data->i_prev_nb_samples = p_buffer->i_nb_samples; if( !p_data->p_prev_s16_buff ) return -1; } p_buffs = p_s16_buff = p_data->p_prev_s16_buff; i_80_bands = var_InheritInteger( p_aout, "visual-80-bands" ); i_peak = var_InheritInteger( p_aout, "visual-peaks" ); if( i_80_bands != 0) { xscale = xscale2; i_nb_bands = 80; } else { xscale = xscale1; i_nb_bands = 20; } height = malloc( i_nb_bands * sizeof(int) ); if( !height ) { return -1; } /* Convert the buffer to int16_t */ /* Pasted from float32tos16.c */ for (i = p_buffer->i_nb_samples * p_effect->i_nb_chans; i--; ) { union { float f; int32_t i; } u; u.f = *p_buffl + 384.0; if(u.i > 0x43c07fff ) * p_buffs = 32767; else if ( u.i < 0x43bf8000 ) *p_buffs = -32768; else *p_buffs = u.i - 0x43c00000; p_buffl++ ; p_buffs++ ; } p_state = visual_fft_init(); if( !p_state) { free( height ); msg_Err(p_aout,"unable to initialize FFT transform"); return -1; } if( !window_init( FFT_BUFFER_SIZE, &p_data->wind_param, &wind_ctx ) ) { fft_close( p_state ); free( height ); msg_Err(p_aout,"unable to initialize FFT window"); return -1; } p_buffs = p_s16_buff; for ( i = 0 ; i < FFT_BUFFER_SIZE ; i++) { p_output[i] = 0; p_buffer1[i] = *p_buffs; p_buffs += p_effect->i_nb_chans; if( p_buffs >= &p_s16_buff[p_buffer->i_nb_samples * p_effect->i_nb_chans] ) p_buffs = p_s16_buff; } window_scale_in_place( p_buffer1, &wind_ctx ); fft_perform( p_buffer1, p_output, p_state); for( i = 0; i< FFT_BUFFER_SIZE ; i++ ) p_dest[i] = p_output[i] * ( 2 ^ 16 ) / ( ( FFT_BUFFER_SIZE / 2 * 32768 ) ^ 2 ); /* Compute the horizontal position of the first band */ i_band_width = floor( p_effect->i_width / i_nb_bands); i_start = ( p_effect->i_width - i_band_width * i_nb_bands ) / 2; for ( i = 0 ; i < i_nb_bands ;i++) { /* We search the maximum on one scale */ for( j = xscale[i], y = 0; j< xscale[ i + 1 ]; j++ ) { if ( p_dest[j] > y ) y = p_dest[j]; } /* Calculate the height of the bar */ if( y != 0 ) { height[i] = log( y ) * 30; if( height[i] > 380 ) height[i] = 380; } else height[ i ] = 0; /* Draw the bar now */ if( height[i] > peaks[i] ) { peaks[i] = height[i]; } else if( peaks[i] > 0 ) { peaks[i] -= PEAK_SPEED; if( peaks[i] < height[i] ) { peaks[i] = height[i]; } if( peaks[i] < 0 ) { peaks[i] = 0; } } /* Decrease the bars if needed */ if( height[i] <= prev_heights[i] - BAR_DECREASE_SPEED ) { height[i] = prev_heights[i]; height[i] -= BAR_DECREASE_SPEED; } prev_heights[i] = height[i]; if( peaks[i] > 0 && i_peak ) { if( peaks[i] >= p_effect->i_height ) peaks[i] = p_effect->i_height - 2; i_line = peaks[i]; for( j = 0; j < i_band_width - 1; j++ ) { for( k = 0; k < 3; k ++ ) { /* Draw the peak */ *(p_picture->p[0].p_pixels + ( p_effect->i_height - i_line -1 -k ) * p_picture->p[0].i_pitch + ( i_start + i_band_width*i + j ) ) = 0xff; *(p_picture->p[1].p_pixels + ( ( p_effect->i_height - i_line ) / 2 - 1 -k/2 ) * p_picture->p[1].i_pitch + ( ( i_start + i_band_width * i + j ) /2 ) ) = 0x00; if( i_line + k - 0x0f > 0 ) { if ( i_line + k - 0x0f < 0xff ) *(p_picture->p[2].p_pixels + ( ( p_effect->i_height - i_line ) / 2 - 1 -k/2 ) * p_picture->p[2].i_pitch + ( ( i_start + i_band_width * i + j ) /2 ) ) = ( i_line + k ) - 0x0f; else *(p_picture->p[2].p_pixels + ( ( p_effect->i_height - i_line ) / 2 - 1 -k/2 ) * p_picture->p[2].i_pitch + ( ( i_start + i_band_width * i + j ) /2 ) ) = 0xff; } else { *(p_picture->p[2].p_pixels + ( ( p_effect->i_height - i_line ) / 2 - 1 -k/2 ) * p_picture->p[2].i_pitch + ( ( i_start + i_band_width * i + j ) /2 ) ) = 0x10 ; } } } } if(height[i] > p_effect->i_height) height[i] = floor(p_effect->i_height ); for( i_line = 0; i_line < height[i]; i_line++ ) { for( j = 0 ; j < i_band_width - 1; j++) { *(p_picture->p[0].p_pixels + (p_effect->i_height - i_line - 1) * p_picture->p[0].i_pitch + ( i_start + i_band_width*i + j ) ) = 0xff; *(p_picture->p[1].p_pixels + ( ( p_effect->i_height - i_line ) / 2 - 1) * p_picture->p[1].i_pitch + ( ( i_start + i_band_width * i + j ) /2 ) ) = 0x00; if( i_line - 0x0f > 0 ) { if( i_line - 0x0f < 0xff ) *(p_picture->p[2].p_pixels + ( ( p_effect->i_height - i_line ) / 2 - 1) * p_picture->p[2].i_pitch + ( ( i_start + i_band_width * i + j ) /2 ) ) = i_line - 0x0f; else *(p_picture->p[2].p_pixels + ( ( p_effect->i_height - i_line ) / 2 - 1) * p_picture->p[2].i_pitch + ( ( i_start + i_band_width * i + j ) /2 ) ) = 0xff; } else { *(p_picture->p[2].p_pixels + ( ( p_effect->i_height - i_line ) / 2 - 1) * p_picture->p[2].i_pitch + ( ( i_start + i_band_width * i + j ) /2 ) ) = 0x10; } } } } window_close( &wind_ctx ); fft_close( p_state ); free( height ); return 0; } static void spectrum_Free( void *data ) { spectrum_data *p_data = data; if( p_data != NULL ) { free( p_data->peaks ); free( p_data->prev_heights ); free( p_data->p_prev_s16_buff ); free( p_data ); } } /***************************************************************************** * spectrometer_Run: derivative spectrum analysis *****************************************************************************/ typedef struct { int *peaks; unsigned i_prev_nb_samples; int16_t *p_prev_s16_buff; window_param wind_param; } spectrometer_data; static int spectrometer_Run(visual_effect_t * p_effect, vlc_object_t *p_aout, const block_t * p_buffer , picture_t * p_picture) { #define Y(R,G,B) ((uint8_t)( (R * .299) + (G * .587) + (B * .114) )) #define U(R,G,B) ((uint8_t)( (R * -.169) + (G * -.332) + (B * .500) + 128 )) #define V(R,G,B) ((uint8_t)( (R * .500) + (G * -.419) + (B * -.0813) + 128 )) float p_output[FFT_BUFFER_SIZE]; /* Raw FFT Result */ int *height; /* Bar heights */ int *peaks; /* Peaks */ int i_80_bands; /* number of bands : 80 if true else 20 */ int i_nb_bands; /* number of bands : 80 or 20 */ int i_band_width; /* width of bands */ int i_separ; /* Should we let blanks ? */ int i_amp; /* Vertical amplification */ int i_peak; /* Should we draw peaks ? */ int i_original; /* original spectrum graphic routine */ int i_rad; /* radius of circle of base of bands */ int i_sections; /* sections of spectranalysis */ int i_extra_width; /* extra width on peak */ int i_peak_height; /* height of peak */ int c; /* sentinel container of total spectral sections */ double band_sep_angle; /* angled separation between beginning of each band */ double section_sep_angle;/* " " ' " ' " " spectrum section */ int max_band_length; /* try not to go out of screen */ int i_show_base; /* Should we draw base of circle ? */ int i_show_bands; /* Should we draw bands ? */ //int i_invert_bands; /* do the bands point inward ? */ double a; /* for various misc angle situations in radians */ int x,y,xx,yy; /* various misc x/y */ char color1; /* V slide on a YUV color cube */ //char color2; /* U slide.. ? color2 fade color ? */ /* Horizontal scale for 20-band equalizer */ const int xscale1[]={0,1,2,3,4,5,6,7,8,11,15,20,27, 36,47,62,82,107,141,184,255}; /* Horizontal scale for 80-band equalizer */ const int xscale2[] = {0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18, 19,20,21,22,23,24,25,26,27,28,29,30,31,32,33,34, 35,36,37,38,39,40,41,42,43,44,45,46,47,48,49,50,51, 52,53,54,55,56,57,58,59,61,63,67,72,77,82,87,93,99,105, 110,115,121,130,141,152,163,174,185,200,255}; const int *xscale; const double y_scale = 3.60673760222; /* (log 256) */ fft_state *p_state; /* internal FFT data */ DEFINE_WIND_CONTEXT( wind_ctx ); /* internal window data */ int i , j , k; int i_line = 0; int16_t p_dest[FFT_BUFFER_SIZE]; /* Adapted FFT result */ int16_t p_buffer1[FFT_BUFFER_SIZE]; /* Buffer on which we perform the FFT (first channel) */ float *p_buffl = /* Original buffer */ (float*)p_buffer->p_buffer; int16_t *p_buffs; /* int16_t converted buffer */ int16_t *p_s16_buff; /* int16_t converted buffer */ if (!p_buffer->i_nb_samples) { msg_Err(p_aout, "no samples yet"); return -1; } /* Create the data struct if needed */ spectrometer_data *p_data = p_effect->p_data; if( !p_data ) { p_data = malloc( sizeof(spectrometer_data) ); if( !p_data ) return -1; p_data->peaks = calloc( 80, sizeof(int) ); if( !p_data->peaks ) { free( p_data ); return -1; } p_data->i_prev_nb_samples = 0; p_data->p_prev_s16_buff = NULL; window_get_param( p_aout, &p_data->wind_param ); p_effect->p_data = (void*)p_data; } peaks = p_data->peaks; /* Allocate the buffer only if the number of samples change */ if( p_buffer->i_nb_samples != p_data->i_prev_nb_samples ) { free( p_data->p_prev_s16_buff ); p_data->p_prev_s16_buff = malloc( p_buffer->i_nb_samples * p_effect->i_nb_chans * sizeof(int16_t)); p_data->i_prev_nb_samples = p_buffer->i_nb_samples; if( !p_data->p_prev_s16_buff ) return -1; } p_buffs = p_s16_buff = p_data->p_prev_s16_buff; i_original = var_InheritInteger( p_aout, "spect-show-original" ); i_80_bands = var_InheritInteger( p_aout, "spect-80-bands" ); i_separ = var_InheritInteger( p_aout, "spect-separ" ); i_amp = var_InheritInteger( p_aout, "spect-amp" ); i_peak = var_InheritInteger( p_aout, "spect-show-peaks" ); i_show_base = var_InheritInteger( p_aout, "spect-show-base" ); i_show_bands = var_InheritInteger( p_aout, "spect-show-bands" ); i_rad = var_InheritInteger( p_aout, "spect-radius" ); i_sections = var_InheritInteger( p_aout, "spect-sections" ); i_extra_width = var_InheritInteger( p_aout, "spect-peak-width" ); i_peak_height = var_InheritInteger( p_aout, "spect-peak-height" ); color1 = var_InheritInteger( p_aout, "spect-color" ); if( i_80_bands != 0) { xscale = xscale2; i_nb_bands = 80; } else { xscale = xscale1; i_nb_bands = 20; } height = malloc( i_nb_bands * sizeof(int) ); if( !height) return -1; /* Convert the buffer to int16_t */ /* Pasted from float32tos16.c */ for (i = p_buffer->i_nb_samples * p_effect->i_nb_chans; i--; ) { union { float f; int32_t i; } u; u.f = *p_buffl + 384.0; if(u.i > 0x43c07fff ) * p_buffs = 32767; else if ( u.i < 0x43bf8000 ) *p_buffs = -32768; else *p_buffs = u.i - 0x43c00000; p_buffl++ ; p_buffs++ ; } p_state = visual_fft_init(); if( !p_state) { msg_Err(p_aout,"unable to initialize FFT transform"); free( height ); return -1; } if( !window_init( FFT_BUFFER_SIZE, &p_data->wind_param, &wind_ctx ) ) { fft_close( p_state ); free( height ); msg_Err(p_aout,"unable to initialize FFT window"); return -1; } p_buffs = p_s16_buff; for ( i = 0 ; i < FFT_BUFFER_SIZE; i++) { p_output[i] = 0; p_buffer1[i] = *p_buffs; p_buffs += p_effect->i_nb_chans; if( p_buffs >= &p_s16_buff[p_buffer->i_nb_samples * p_effect->i_nb_chans] ) p_buffs = p_s16_buff; } window_scale_in_place( p_buffer1, &wind_ctx ); fft_perform( p_buffer1, p_output, p_state); for(i = 0; i < FFT_BUFFER_SIZE; i++) { int sqrti = sqrt(p_output[i]); p_dest[i] = sqrti >> 8; } i_nb_bands *= i_sections; for ( i = 0 ; i< i_nb_bands/i_sections ;i++) { /* We search the maximum on one scale */ for( j = xscale[i] , y=0 ; j< xscale[ i + 1 ] ; j++ ) { if ( p_dest[j] > y ) y = p_dest[j]; } /* Calculate the height of the bar */ y >>=7;/* remove some noise */ if( y != 0) { int logy = log(y); height[i] = logy * y_scale; if(height[i] > 150) height[i] = 150; } else { height[i] = 0 ; } /* Draw the bar now */ i_band_width = floor( p_effect->i_width / (i_nb_bands/i_sections)) ; if( i_amp * height[i] > peaks[i]) { peaks[i] = i_amp * height[i]; } else if (peaks[i] > 0 ) { peaks[i] -= PEAK_SPEED; if( peaks[i] < i_amp * height[i] ) { peaks[i] = i_amp * height[i]; } if( peaks[i] < 0 ) { peaks[i] = 0; } } if( i_original != 0 ) { if( peaks[i] > 0 && i_peak ) { if( peaks[i] >= p_effect->i_height ) peaks[i] = p_effect->i_height - 2; i_line = peaks[i]; for( j = 0 ; j< i_band_width - i_separ; j++) { for( k = 0 ; k< 3 ; k ++) { //* Draw the peak *(p_picture->p[0].p_pixels + (p_effect->i_height - i_line -1 -k ) * p_picture->p[0].i_pitch + (i_band_width*i +j) ) = 0xff; *(p_picture->p[1].p_pixels + ( ( p_effect->i_height - i_line ) / 2 -1 -k/2 ) * p_picture->p[1].i_pitch + ( ( i_band_width * i + j ) /2 ) ) = 0x00; if( 0x04 * (i_line + k ) - 0x0f > 0 ) { if ( 0x04 * (i_line + k ) -0x0f < 0xff) *(p_picture->p[2].p_pixels + ( ( p_effect->i_height - i_line ) / 2 - 1 -k/2 ) * p_picture->p[2].i_pitch + ( ( i_band_width * i + j ) /2 ) ) = ( 0x04 * ( i_line + k ) ) -0x0f ; else *(p_picture->p[2].p_pixels + ( ( p_effect->i_height - i_line ) / 2 - 1 -k/2 ) * p_picture->p[2].i_pitch + ( ( i_band_width * i + j ) /2 ) ) = 0xff; } else { *(p_picture->p[2].p_pixels + ( ( p_effect->i_height - i_line ) / 2 - 1 -k/2 ) * p_picture->p[2].i_pitch + ( ( i_band_width * i + j ) /2 ) ) = 0x10 ; } } } } if(height[i] * i_amp > p_effect->i_height) height[i] = floor(p_effect->i_height / i_amp ); for(i_line = 0 ; i_line < i_amp * height[i]; i_line ++ ) { for( j = 0 ; j< i_band_width - i_separ ; j++) { *(p_picture->p[0].p_pixels + (p_effect->i_height - i_line -1) * p_picture->p[0].i_pitch + (i_band_width*i +j) ) = 0xff; *(p_picture->p[1].p_pixels + ( ( p_effect->i_height - i_line ) / 2 -1) * p_picture->p[1].i_pitch + ( ( i_band_width * i + j ) /2 ) ) = 0x00; if( 0x04 * i_line - 0x0f > 0 ) { if( 0x04 * i_line - 0x0f < 0xff ) *(p_picture->p[2].p_pixels + ( ( p_effect->i_height - i_line ) / 2 - 1) * p_picture->p[2].i_pitch + ( ( i_band_width * i + j ) /2 ) ) = ( 0x04 * i_line) -0x0f ; else *(p_picture->p[2].p_pixels + ( ( p_effect->i_height - i_line ) / 2 - 1) * p_picture->p[2].i_pitch + ( ( i_band_width * i + j ) /2 ) ) = 0xff; } else { *(p_picture->p[2].p_pixels + ( ( p_effect->i_height - i_line ) / 2 - 1) * p_picture->p[2].i_pitch + ( ( i_band_width * i + j ) /2 ) ) = 0x10 ; } } } } } band_sep_angle = 360.0 / i_nb_bands; section_sep_angle = 360.0 / i_sections; if( i_peak_height < 1 ) i_peak_height = 1; max_band_length = p_effect->i_height / 2 - ( i_rad + i_peak_height + 1 ); i_band_width = floor( 360 / i_nb_bands - i_separ ); if( i_band_width < 1 ) i_band_width = 1; for( c = 0 ; c < i_sections ; c++ ) for( i = 0 ; i < (i_nb_bands / i_sections) ; i++ ) { /* DO A PEAK */ if( peaks[i] > 0 && i_peak ) { if( peaks[i] >= p_effect->i_height ) peaks[i] = p_effect->i_height - 2; i_line = peaks[i]; /* circular line pattern(so color blend is more visible) */ for( j = 0 ; j < i_peak_height ; j++ ) { //x = p_picture->p[0].i_pitch / 2; x = p_effect->i_width / 2; y = p_effect->i_height / 2; xx = x; yy = y; for( k = 0 ; k < (i_band_width + i_extra_width) ; k++ ) { x = xx; y = yy; a = ( (i+1) * band_sep_angle + section_sep_angle * (c+1) + k ) * 3.141592 / 180.0; x += (double)( cos(a) * (double)( i_line + j + i_rad ) ); y += (double)( -sin(a) * (double)( i_line + j + i_rad ) ); *(p_picture->p[0].p_pixels + x + y * p_picture->p[0].i_pitch ) = 255;/* Y(R,G,B); */ x /= 2; y /= 2; *(p_picture->p[1].p_pixels + x + y * p_picture->p[1].i_pitch ) = 0;/* U(R,G,B); */ if( 0x04 * (i_line + k ) - 0x0f > 0 ) { if ( 0x04 * (i_line + k ) -0x0f < 0xff) *(p_picture->p[2].p_pixels + x + y * p_picture->p[2].i_pitch ) = ( 0x04 * ( i_line + k ) ) -(color1-1);/* -V(R,G,B); */ else *(p_picture->p[2].p_pixels + x + y * p_picture->p[2].i_pitch ) = 255;/* V(R,G,B); */ } else { *(p_picture->p[2].p_pixels + x + y * p_picture->p[2].i_pitch ) = color1;/* V(R,G,B); */ } } } } if( (height[i] * i_amp) > p_effect->i_height ) height[i] = floor( p_effect->i_height / i_amp ); /* DO BASE OF BAND (mostly makes a circle) */ if( i_show_base != 0 ) { //x = p_picture->p[0].i_pitch / 2; x = p_effect->i_width / 2; y = p_effect->i_height / 2; a = ( (i+1) * band_sep_angle + section_sep_angle * (c+1) ) * 3.141592 / 180.0; x += (double)( cos(a) * (double)i_rad );/* newb-forceful casting */ y += (double)( -sin(a) * (double)i_rad ); *(p_picture->p[0].p_pixels + x + y * p_picture->p[0].i_pitch ) = 255;/* Y(R,G,B); */ x /= 2; y /= 2; *(p_picture->p[1].p_pixels + x + y * p_picture->p[1].i_pitch ) = 0;/* U(R,G,B); */ if( 0x04 * i_line - 0x0f > 0 ) { if( 0x04 * i_line -0x0f < 0xff) *(p_picture->p[2].p_pixels + x + y * p_picture->p[2].i_pitch ) = ( 0x04 * i_line) -(color1-1);/* -V(R,G,B); */ else *(p_picture->p[2].p_pixels + x + y * p_picture->p[2].i_pitch ) = 255;/* V(R,G,B); */ } else { *(p_picture->p[2].p_pixels + x + y * p_picture->p[2].i_pitch ) = color1;/* V(R,G,B); */ } } /* DO A BAND */ if( i_show_bands != 0 ) for( j = 0 ; j < i_band_width ; j++ ) { x = p_effect->i_width / 2; y = p_effect->i_height / 2; xx = x; yy = y; a = ( (i+1) * band_sep_angle + section_sep_angle * (c+1) + j ) * 3.141592/180.0; for( k = (i_rad+1) ; k < max_band_length ; k++ ) { if( (k-i_rad) > height[i] ) break;/* uhh.. */ x = xx; y = yy; x += (double)( cos(a) * (double)k );/* newbed! */ y += (double)( -sin(a) * (double)k ); *(p_picture->p[0].p_pixels + x + y * p_picture->p[0].i_pitch ) = 255; x /= 2; y /= 2; *(p_picture->p[1].p_pixels + x + y * p_picture->p[1].i_pitch ) = 0; if( 0x04 * i_line - 0x0f > 0 ) { if ( 0x04 * i_line -0x0f < 0xff) *(p_picture->p[2].p_pixels + x + y * p_picture->p[2].i_pitch ) = ( 0x04 * i_line) -(color1-1); else *(p_picture->p[2].p_pixels + x + y * p_picture->p[2].i_pitch ) = 255; } else { *(p_picture->p[2].p_pixels + x + y * p_picture->p[2].i_pitch ) = color1; } } } } window_close( &wind_ctx ); fft_close( p_state ); free( height ); return 0; } static void spectrometer_Free( void *data ) { spectrometer_data *p_data = data; if( p_data != NULL ) { free( p_data->peaks ); free( p_data->p_prev_s16_buff ); free( p_data ); } } /***************************************************************************** * scope_Run: scope effect *****************************************************************************/ static int scope_Run(visual_effect_t * p_effect, vlc_object_t *p_aout, const block_t * p_buffer , picture_t * p_picture) { VLC_UNUSED(p_aout); int i_index; float *p_sample ; uint8_t *ppp_area[2][3]; for( i_index = 0 ; i_index < 2 ; i_index++ ) { for( int j = 0 ; j < 3 ; j++ ) { ppp_area[i_index][j] = p_picture->p[j].p_pixels + (i_index * 2 + 1) * p_picture->p[j].i_lines / 4 * p_picture->p[j].i_pitch; } } for( i_index = 0, p_sample = (float *)p_buffer->p_buffer; i_index < __MIN( p_effect->i_width, (int)p_buffer->i_nb_samples ); i_index++ ) { int8_t i_value; /* Left channel */ i_value = p_sample[p_effect->i_idx_left] * 127; *(ppp_area[0][0] + p_picture->p[0].i_pitch * i_index / p_effect->i_width + p_picture->p[0].i_lines * i_value / 512 * p_picture->p[0].i_pitch) = 0xbf; *(ppp_area[0][1] + p_picture->p[1].i_pitch * i_index / p_effect->i_width + p_picture->p[1].i_lines * i_value / 512 * p_picture->p[1].i_pitch) = 0xff; /* Right channel */ i_value = p_sample[p_effect->i_idx_right] * 127; *(ppp_area[1][0] + p_picture->p[0].i_pitch * i_index / p_effect->i_width + p_picture->p[0].i_lines * i_value / 512 * p_picture->p[0].i_pitch) = 0x9f; *(ppp_area[1][2] + p_picture->p[2].i_pitch * i_index / p_effect->i_width + p_picture->p[2].i_lines * i_value / 512 * p_picture->p[2].i_pitch) = 0xdd; p_sample += p_effect->i_nb_chans; } return 0; } /***************************************************************************** * vuMeter_Run: vu meter effect *****************************************************************************/ static int vuMeter_Run(visual_effect_t * p_effect, vlc_object_t *p_aout, const block_t * p_buffer , picture_t * p_picture) { VLC_UNUSED(p_aout); float i_value_l = 0; float i_value_r = 0; /* Compute the peak values */ for ( unsigned i = 0 ; i < p_buffer->i_nb_samples; i++ ) { const float *p_sample = (float *)p_buffer->p_buffer; float ch; ch = p_sample[p_effect->i_idx_left] * 256; if (ch > i_value_l) i_value_l = ch; ch = p_sample[p_effect->i_idx_right] * 256; if (ch > i_value_r) i_value_r = ch; p_sample += p_effect->i_nb_chans; } i_value_l = abs(i_value_l); i_value_r = abs(i_value_r); /* Stay under maximum value admited */ if ( i_value_l > 200 * M_PI_2 ) i_value_l = 200 * M_PI_2; if ( i_value_r > 200 * M_PI_2 ) i_value_r = 200 * M_PI_2; float *i_value; if( !p_effect->p_data ) { /* Allocate memory to save hand positions */ p_effect->p_data = malloc( 2 * sizeof(float) ); i_value = p_effect->p_data; i_value[0] = i_value_l; i_value[1] = i_value_r; } else { /* Make the hands go down slowly if the current values are slower than the previous */ i_value = p_effect->p_data; if ( i_value_l > i_value[0] - 6 ) i_value[0] = i_value_l; else i_value[0] = i_value[0] - 6; if ( i_value_r > i_value[1] - 6 ) i_value[1] = i_value_r; else i_value[1] = i_value[1] - 6; } int x, y; float teta; float teta_grad; int start_x = p_effect->i_width / 2 - 120; /* i_width.min = 532 (visual.c) */ for ( int j = 0; j < 2; j++ ) { /* Draw the two scales */ int k = 0; teta_grad = GRAD_ANGLE_MIN; for ( teta = -M_PI_4; teta <= M_PI_4; teta = teta + 0.003 ) { for ( unsigned i = 140; i <= 150; i++ ) { y = i * cos(teta) + 20; x = i * sin(teta) + start_x + 240 * j; /* Compute the last color for the gradation */ if (teta >= teta_grad + GRAD_INCR && teta_grad <= GRAD_ANGLE_MAX) { teta_grad = teta_grad + GRAD_INCR; k = k + 5; } *(p_picture->p[0].p_pixels + (p_picture->p[0].i_lines - y - 1 ) * p_picture->p[0].i_pitch + x ) = 0x45; *(p_picture->p[1].p_pixels + (p_picture->p[1].i_lines - y / 2 - 1 ) * p_picture->p[1].i_pitch + x / 2 ) = 0x0; *(p_picture->p[2].p_pixels + (p_picture->p[2].i_lines - y / 2 - 1 ) * p_picture->p[2].i_pitch + x / 2 ) = 0x4D + k; } } /* Draw the two hands */ teta = (float)i_value[j] / 200 - M_PI_4; for ( int i = 0; i <= 150; i++ ) { y = i * cos(teta) + 20; x = i * sin(teta) + start_x + 240 * j; *(p_picture->p[0].p_pixels + (p_picture->p[0].i_lines - y - 1 ) * p_picture->p[0].i_pitch + x ) = 0xAD; *(p_picture->p[1].p_pixels + (p_picture->p[1].i_lines - y / 2 - 1 ) * p_picture->p[1].i_pitch + x / 2 ) = 0xFC; *(p_picture->p[2].p_pixels + (p_picture->p[2].i_lines - y / 2 - 1 ) * p_picture->p[2].i_pitch + x / 2 ) = 0xAC; } /* Draw the hand bases */ for ( teta = -M_PI_2; teta <= M_PI_2 + 0.01; teta = teta + 0.003 ) { for ( int i = 0; i < 10; i++ ) { y = i * cos(teta) + 20; x = i * sin(teta) + start_x + 240 * j; *(p_picture->p[0].p_pixels + (p_picture->p[0].i_lines - y - 1 ) * p_picture->p[0].i_pitch + x ) = 0xFF; *(p_picture->p[1].p_pixels + (p_picture->p[1].i_lines - y / 2 - 1 ) * p_picture->p[1].i_pitch + x / 2 ) = 0x80; *(p_picture->p[2].p_pixels + (p_picture->p[2].i_lines - y / 2 - 1 ) * p_picture->p[2].i_pitch + x / 2 ) = 0x80; } } } return 0; } /* Table of effects */ const struct visual_cb_t effectv[] = { { "scope", scope_Run, dummy_Free }, { "vuMeter", vuMeter_Run, dummy_Free }, { "spectrum", spectrum_Run, spectrum_Free }, { "spectrometer", spectrometer_Run, spectrometer_Free }, { "dummy", dummy_Run, dummy_Free }, }; const unsigned effectc = sizeof (effectv) / sizeof (effectv[0]);
vaughamhong/vlc
modules/visualization/visual/effects.c
C
gpl-2.0
37,924
<?php /* WPFront User Role Editor Plugin Copyright (C) 2014, WPFront.com Website: wpfront.com Contact: syam@wpfront.com WPFront User Role Editor Plugin is distributed under the GNU General Public License, Version 3, June 2007. Copyright (C) 2007 Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110, USA 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. */ if (!defined('ABSPATH')) { exit(); } if (!class_exists('WPFront_User_Role_Editor_Add_Remove_Capability')) { /** * Add or Remove Capability * * @author Syam Mohan <syam@wpfront.com> * @copyright 2014 WPFront.com */ class WPFront_User_Role_Editor_Add_Remove_Capability extends WPFront_User_Role_Editor_Controller_Base { const MENU_SLUG = 'wpfront-user-role-editor-add-remove-capability'; private $action; private $capability; private $roles_type; private $roles; private $message; public function add_remove_capability() { if (!$this->can_edit()) { $this->main->permission_denied(); return; } $this->action = 'add'; $this->capability = ''; $this->roles_type = 'all'; $this->roles = array(); $this->message = NULL; if (!empty($_POST['add-remove-capability'])) { $this->main->verify_nonce(); $this->action = $_POST['action_type']; $this->capability = trim($_POST['capability']); if (empty($this->capability)) $this->capability = NULL; $this->roles_type = $_POST['roles_type']; if ($this->roles_type === 'selected' && !empty($_POST['selected-roles'])) $this->roles = $_POST['selected-roles']; if (!empty($this->capability)) { $roles = array(); switch ($this->roles_type) { case 'all': global $wp_roles; $roles = $wp_roles->role_names; break; case 'selected': $roles = $this->roles; break; } $func = NULL; switch ($this->action) { case 'add': $func = 'add_cap'; if (!isset($roles[self::ADMINISTRATOR_ROLE_KEY])) { $roles[self::ADMINISTRATOR_ROLE_KEY] = TRUE; } break; case 'remove': $func = 'remove_cap'; if ($this->roles_type === 'all') { $roles[self::ADMINISTRATOR_ROLE_KEY] = TRUE; } else { unset($roles[self::ADMINISTRATOR_ROLE_KEY]); } break; } foreach ($roles as $key => $value) { $role = get_role($key); if (!empty($role)) { $role->$func($this->capability); } } $this->message = $this->__('Roles updated.'); } } include($this->main->pluginDIR() . 'templates/add-remove-capability.php'); } private function get_roles() { global $wp_roles; $roles = $wp_roles->role_names; unset($roles[self::ADMINISTRATOR_ROLE_KEY]); return $roles; } protected function add_help_tab() { return array( array( 'id' => 'overview', 'title' => $this->__('Overview'), 'content' => '<p>' . $this->__('This screen allows you to add a capability to roles or remove a capability from roles within your site.') . '</p>' ), array( 'id' => 'action', 'title' => $this->__('Action'), 'content' => '<p>' . $this->__('Select "Add Capability" to add a capability to roles.') . '</p>' . '<p>' . $this->__('Select "Remove Capability" to remove a capability from roles.') . '</p>' ), array( 'id' => 'capability', 'title' => $this->__('Capability'), 'content' => '<p>' . $this->__('Use the Capability field to name the capability to be added or removed.') . '</p>' ), array( 'id' => 'roles', 'title' => $this->__('Roles'), 'content' => '<p><strong>' . $this->__('All Roles') . '</strong>: '. $this->__('Select "All Roles", if you want the current action to be applied to all roles within your site.') . '</p>' . '<p><strong>' . $this->__('Selected Roles') . '</strong>: '. $this->__('Select "Selected Roles", if you want to individually select the roles. When this option is selected, "Administrator" role is included by default on "Add Capability" action and excluded by default on "Remove Capability" action.') . '</p>' ) ); } protected function set_help_sidebar() { return array( array( $this->__('Documentation on Add/Remove Capability'), 'add-remove-capability/' ) ); } } }
MujeresdelasAmericas/Sitio
wp-content/plugins/wpfront-user-role-editor/classes/class-wpfront-user-role-editor-add-remove-capability.php
PHP
gpl-2.0
6,778
/* * arizona.h - Wolfson Arizona class device shared support * * Copyright 2012 Wolfson Microelectronics plc * * Author: Mark Brown <broonie@opensource.wolfsonmicro.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. */ #ifndef _ASOC_ARIZONA_H #define _ASOC_ARIZONA_H #include <linux/completion.h> #include <sound/soc.h> #include "wm_adsp.h" #define ARIZONA_CLK_SYSCLK 1 #define ARIZONA_CLK_ASYNCCLK 2 #define ARIZONA_CLK_OPCLK 3 #define ARIZONA_CLK_ASYNC_OPCLK 4 #define ARIZONA_CLK_SYSCLK_2 5 #define ARIZONA_CLK_SYSCLK_3 6 #define ARIZONA_CLK_ASYNCCLK_2 7 #define ARIZONA_CLK_DSPCLK 8 #define ARIZONA_CLK_SRC_MCLK1 0x0 #define ARIZONA_CLK_SRC_MCLK2 0x1 #define ARIZONA_CLK_SRC_FLL1 0x4 #define ARIZONA_CLK_SRC_FLL2 0x5 #define ARIZONA_CLK_SRC_FLL3 0x6 #define ARIZONA_CLK_SRC_AIF1BCLK 0x8 #define ARIZONA_CLK_SRC_AIF2BCLK 0x9 #define ARIZONA_CLK_SRC_AIF3BCLK 0xa #define ARIZONA_CLK_SRC_AIF4BCLK 0xb #define ARIZONA_FLL_SRC_NONE -1 #define ARIZONA_FLL_SRC_MCLK1 0 #define ARIZONA_FLL_SRC_MCLK2 1 #define ARIZONA_FLL_SRC_SLIMCLK 3 #define ARIZONA_FLL_SRC_FLL1 4 #define ARIZONA_FLL_SRC_FLL2 5 #define ARIZONA_FLL_SRC_AIF1BCLK 8 #define ARIZONA_FLL_SRC_AIF2BCLK 9 #define ARIZONA_FLL_SRC_AIF3BCLK 10 #define ARIZONA_FLL_SRC_AIF4BCLK 11 #define ARIZONA_FLL_SRC_AIF1LRCLK 12 #define ARIZONA_FLL_SRC_AIF2LRCLK 13 #define ARIZONA_FLL_SRC_AIF3LRCLK 14 #define ARIZONA_FLL_SRC_AIF4LRCLK 15 #define ARIZONA_MIXER_VOL_MASK 0x00FE #define ARIZONA_MIXER_VOL_SHIFT 1 #define ARIZONA_MIXER_VOL_WIDTH 7 #define ARIZONA_CLK_6MHZ 0 #define ARIZONA_CLK_12MHZ 1 #define ARIZONA_CLK_24MHZ 2 #define ARIZONA_CLK_49MHZ 3 #define ARIZONA_CLK_73MHZ 4 #define CLEARWATER_CLK_98MHZ 4 #define ARIZONA_CLK_98MHZ 5 #define ARIZONA_CLK_147MHZ 6 #define CLEARWATER_DSP_CLK_9MHZ 0 #define CLEARWATER_DSP_CLK_18MHZ 1 #define CLEARWATER_DSP_CLK_36MHZ 2 #define CLEARWATER_DSP_CLK_73MHZ 3 #define CLEARWATER_DSP_CLK_147MHZ 4 #define ARIZONA_MAX_DAI 11 #define ARIZONA_MAX_ADSP 7 struct arizona; struct wm_adsp; struct arizona_jd_state; struct arizona_dai_priv { int clk; }; struct arizona_priv { struct wm_adsp adsp[ARIZONA_MAX_ADSP]; struct arizona *arizona; int sysclk; int asyncclk; int dspclk; struct arizona_dai_priv dai[ARIZONA_MAX_DAI]; int num_inputs; unsigned int in_pending; unsigned int out_up_pending; unsigned int out_up_delay; unsigned int out_down_pending; unsigned int out_down_delay; bool edre_stereo_disable; }; #define ARIZONA_NUM_MIXER_INPUTS 134 #define ARIZONA_V2_NUM_MIXER_INPUTS 138 extern const unsigned int arizona_mixer_tlv[]; extern const char * const arizona_mixer_texts[ARIZONA_NUM_MIXER_INPUTS]; extern unsigned int arizona_mixer_values[ARIZONA_NUM_MIXER_INPUTS]; extern const char * const arizona_v2_mixer_texts[ARIZONA_V2_NUM_MIXER_INPUTS]; extern unsigned int arizona_v2_mixer_values[ARIZONA_V2_NUM_MIXER_INPUTS]; #define ARIZONA_GAINMUX_CONTROLS(name, base) \ SOC_SINGLE_RANGE_TLV(name " Input Volume", base + 1, \ ARIZONA_MIXER_VOL_SHIFT, 0x20, 0x50, 0, \ arizona_mixer_tlv) #define ARIZONA_MIXER_CONTROLS(name, base) \ SOC_SINGLE_RANGE_TLV(name " Input 1 Volume", base + 1, \ ARIZONA_MIXER_VOL_SHIFT, 0x20, 0x50, 0, \ arizona_mixer_tlv), \ SOC_SINGLE_RANGE_TLV(name " Input 2 Volume", base + 3, \ ARIZONA_MIXER_VOL_SHIFT, 0x20, 0x50, 0, \ arizona_mixer_tlv), \ SOC_SINGLE_RANGE_TLV(name " Input 3 Volume", base + 5, \ ARIZONA_MIXER_VOL_SHIFT, 0x20, 0x50, 0, \ arizona_mixer_tlv), \ SOC_SINGLE_RANGE_TLV(name " Input 4 Volume", base + 7, \ ARIZONA_MIXER_VOL_SHIFT, 0x20, 0x50, 0, \ arizona_mixer_tlv) #define ARIZONA_MUX_ENUM_DECL(name, reg) \ SOC_VALUE_ENUM_SINGLE_DECL(name, reg, 0, 0xff, \ arizona_mixer_texts, arizona_mixer_values) #define ARIZONA_MUX_CTL_DECL(xname) \ const struct snd_kcontrol_new xname##_mux = { \ .iface = SNDRV_CTL_ELEM_IFACE_MIXER, .name = "Route", \ .info = snd_soc_info_enum_double, \ .get = snd_soc_dapm_get_enum_virt, \ .put = arizona_mux_put, \ .private_value = (unsigned long)&xname##_enum } #define ARIZONA_MUX_ENUMS(name, base_reg) \ static ARIZONA_MUX_ENUM_DECL(name##_enum, base_reg); \ static ARIZONA_MUX_CTL_DECL(name) #define ARIZONA_MIXER_ENUMS(name, base_reg) \ ARIZONA_MUX_ENUMS(name##_in1, base_reg); \ ARIZONA_MUX_ENUMS(name##_in2, base_reg + 2); \ ARIZONA_MUX_ENUMS(name##_in3, base_reg + 4); \ ARIZONA_MUX_ENUMS(name##_in4, base_reg + 6) #define ARIZONA_DSP_AUX_ENUMS(name, base_reg) \ ARIZONA_MUX_ENUMS(name##_aux1, base_reg); \ ARIZONA_MUX_ENUMS(name##_aux2, base_reg + 8); \ ARIZONA_MUX_ENUMS(name##_aux3, base_reg + 16); \ ARIZONA_MUX_ENUMS(name##_aux4, base_reg + 24); \ ARIZONA_MUX_ENUMS(name##_aux5, base_reg + 32); \ ARIZONA_MUX_ENUMS(name##_aux6, base_reg + 40) #define CLEARWATER_MUX_ENUM_DECL(name, reg) \ SOC_VALUE_ENUM_SINGLE_DECL(name, reg, 0, 0xff, \ arizona_v2_mixer_texts, arizona_v2_mixer_values) #define CLEARWATER_MUX_ENUMS(name, base_reg) \ static CLEARWATER_MUX_ENUM_DECL(name##_enum, base_reg); \ static ARIZONA_MUX_CTL_DECL(name) #define CLEARWATER_MIXER_ENUMS(name, base_reg) \ CLEARWATER_MUX_ENUMS(name##_in1, base_reg); \ CLEARWATER_MUX_ENUMS(name##_in2, base_reg + 2); \ CLEARWATER_MUX_ENUMS(name##_in3, base_reg + 4); \ CLEARWATER_MUX_ENUMS(name##_in4, base_reg + 6) #define CLEARWATER_DSP_AUX_ENUMS(name, base_reg) \ CLEARWATER_MUX_ENUMS(name##_aux1, base_reg); \ CLEARWATER_MUX_ENUMS(name##_aux2, base_reg + 8); \ CLEARWATER_MUX_ENUMS(name##_aux3, base_reg + 16); \ CLEARWATER_MUX_ENUMS(name##_aux4, base_reg + 24); \ CLEARWATER_MUX_ENUMS(name##_aux5, base_reg + 32); \ CLEARWATER_MUX_ENUMS(name##_aux6, base_reg + 40) #define ARIZONA_MUX(wname, wctrl) \ { .id = snd_soc_dapm_value_mux, .name = wname, .reg = SND_SOC_NOPM, \ .shift = 0, .invert = 0, .kcontrol_news = wctrl, \ .num_kcontrols = 1, .event = arizona_mux_event, \ .event_flags = SND_SOC_DAPM_POST_PMU | SND_SOC_DAPM_PRE_PMD } #define ARIZONA_MUX_WIDGETS(name, name_str) \ ARIZONA_MUX(name_str " Input", &name##_mux) #define ARIZONA_MIXER_WIDGETS(name, name_str) \ ARIZONA_MUX(name_str " Input 1", &name##_in1_mux), \ ARIZONA_MUX(name_str " Input 2", &name##_in2_mux), \ ARIZONA_MUX(name_str " Input 3", &name##_in3_mux), \ ARIZONA_MUX(name_str " Input 4", &name##_in4_mux), \ SND_SOC_DAPM_MIXER(name_str " Mixer", SND_SOC_NOPM, 0, 0, NULL, 0) #define ARIZONA_DSP_WIDGETS(name, name_str) \ ARIZONA_MIXER_WIDGETS(name##L, name_str "L"), \ ARIZONA_MIXER_WIDGETS(name##R, name_str "R"), \ ARIZONA_MUX(name_str " Aux 1", &name##_aux1_mux), \ ARIZONA_MUX(name_str " Aux 2", &name##_aux2_mux), \ ARIZONA_MUX(name_str " Aux 3", &name##_aux3_mux), \ ARIZONA_MUX(name_str " Aux 4", &name##_aux4_mux), \ ARIZONA_MUX(name_str " Aux 5", &name##_aux5_mux), \ ARIZONA_MUX(name_str " Aux 6", &name##_aux6_mux) #define ARIZONA_MUX_ROUTES(widget, name) \ { widget, NULL, name " Input" }, \ ARIZONA_MIXER_INPUT_ROUTES(name " Input") #define ARIZONA_MIXER_ROUTES(widget, name) \ { widget, NULL, name " Mixer" }, \ { name " Mixer", NULL, name " Input 1" }, \ { name " Mixer", NULL, name " Input 2" }, \ { name " Mixer", NULL, name " Input 3" }, \ { name " Mixer", NULL, name " Input 4" }, \ ARIZONA_MIXER_INPUT_ROUTES(name " Input 1"), \ ARIZONA_MIXER_INPUT_ROUTES(name " Input 2"), \ ARIZONA_MIXER_INPUT_ROUTES(name " Input 3"), \ ARIZONA_MIXER_INPUT_ROUTES(name " Input 4") #define ARIZONA_DSP_ROUTES(name) \ { name, NULL, name " Preloader"}, \ { name " Preloader", NULL, name " Aux 1" }, \ { name " Preloader", NULL, name " Aux 2" }, \ { name " Preloader", NULL, name " Aux 3" }, \ { name " Preloader", NULL, name " Aux 4" }, \ { name " Preloader", NULL, name " Aux 5" }, \ { name " Preloader", NULL, name " Aux 6" }, \ ARIZONA_MIXER_INPUT_ROUTES(name " Aux 1"), \ ARIZONA_MIXER_INPUT_ROUTES(name " Aux 2"), \ ARIZONA_MIXER_INPUT_ROUTES(name " Aux 3"), \ ARIZONA_MIXER_INPUT_ROUTES(name " Aux 4"), \ ARIZONA_MIXER_INPUT_ROUTES(name " Aux 5"), \ ARIZONA_MIXER_INPUT_ROUTES(name " Aux 6"), \ ARIZONA_MIXER_ROUTES(name " Preloader", name "L"), \ ARIZONA_MIXER_ROUTES(name " Preloader", name "R") #define ARIZONA_SAMPLE_RATE_CONTROL(name, domain) \ SOC_VALUE_ENUM(name, arizona_sample_rate[(domain) - 2]) #define ARIZONA_SAMPLE_RATE_CONTROL_DVFS(name, domain) \ SOC_VALUE_ENUM_EXT(name, arizona_sample_rate[(domain) - 2], \ snd_soc_get_value_enum_double, \ arizona_put_sample_rate_enum) #define ARIZONA_EQ_CONTROL(xname, xbase) \ { .iface = SNDRV_CTL_ELEM_IFACE_MIXER, .name = xname, \ .info = snd_soc_bytes_info, .get = snd_soc_bytes_get, \ .put = arizona_eq_coeff_put, .private_value = \ ((unsigned long)&(struct soc_bytes) \ {.base = xbase, .num_regs = 20, \ .mask = ~ARIZONA_EQ1_B1_MODE }) } #define CLEARWATER_OSR_ENUM_SIZE 5 #define ARIZONA_RATE_ENUM_SIZE 5 #define ARIZONA_SYNC_RATE_ENUM_SIZE 3 #define ARIZONA_ASYNC_RATE_ENUM_SIZE 2 #define ARIZONA_SAMPLE_RATE_ENUM_SIZE 14 #define ARIZONA_ANC_INPUT_ENUM_SIZE 19 #define WM8280_ANC_INPUT_ENUM_SIZE 13 #define CLEARWATER_ANC_INPUT_ENUM_SIZE 19 extern const char * const arizona_rate_text[ARIZONA_RATE_ENUM_SIZE]; extern const unsigned int arizona_rate_val[ARIZONA_RATE_ENUM_SIZE]; extern const char * const arizona_sample_rate_text[ARIZONA_SAMPLE_RATE_ENUM_SIZE]; extern const unsigned int arizona_sample_rate_val[ARIZONA_SAMPLE_RATE_ENUM_SIZE]; extern const struct soc_enum arizona_sample_rate[]; extern const struct soc_enum arizona_isrc_fsl[]; extern const struct soc_enum arizona_isrc_fsh[]; extern const struct soc_enum arizona_asrc_rate1; extern const struct soc_enum clearwater_asrc1_rate[]; extern const struct soc_enum clearwater_asrc2_rate[]; extern const struct soc_enum arizona_input_rate; extern const struct soc_enum arizona_output_rate; extern const struct soc_enum arizona_fx_rate; extern const struct soc_enum arizona_spdif_rate; extern const struct soc_enum arizona_in_vi_ramp; extern const struct soc_enum arizona_in_vd_ramp; extern const struct soc_enum arizona_out_vi_ramp; extern const struct soc_enum arizona_out_vd_ramp; extern const struct soc_enum arizona_lhpf1_mode; extern const struct soc_enum arizona_lhpf2_mode; extern const struct soc_enum arizona_lhpf3_mode; extern const struct soc_enum arizona_lhpf4_mode; extern const struct soc_enum arizona_ng_hold; extern const struct soc_enum arizona_in_hpf_cut_enum; extern const struct soc_enum arizona_in_dmic_osr[]; extern const struct soc_enum clearwater_in_dmic_osr[]; extern const struct soc_enum arizona_anc_input_src[]; extern const struct soc_enum clearwater_anc_input_src[]; extern const struct soc_enum arizona_output_anc_src[]; extern const struct soc_enum clearwater_output_anc_src_defs[]; extern const struct soc_enum arizona_ip_mode[]; extern int arizona_ip_mode_put(struct snd_kcontrol *kcontrol, struct snd_ctl_elem_value *ucontrol); extern int arizona_put_anc_input(struct snd_kcontrol *kcontrol, struct snd_ctl_elem_value *ucontrol); extern int arizona_in_ev(struct snd_soc_dapm_widget *w, struct snd_kcontrol *kcontrol, int event); extern int arizona_out_ev(struct snd_soc_dapm_widget *w, struct snd_kcontrol *kcontrol, int event); extern int arizona_hp_ev(struct snd_soc_dapm_widget *w, struct snd_kcontrol *kcontrol, int event); extern int florida_hp_ev(struct snd_soc_dapm_widget *w, struct snd_kcontrol *kcontrol, int event); extern int clearwater_hp_ev(struct snd_soc_dapm_widget *w, struct snd_kcontrol *kcontrol, int event); extern int arizona_anc_ev(struct snd_soc_dapm_widget *w, struct snd_kcontrol *kcontrol, int event); extern int arizona_mux_put(struct snd_kcontrol *kcontrol, struct snd_ctl_elem_value *ucontrol); extern int arizona_mux_event(struct snd_soc_dapm_widget *w, struct snd_kcontrol *kcontrol, int event); extern int arizona_put_sample_rate_enum(struct snd_kcontrol *kcontrol, struct snd_ctl_elem_value *ucontrol); extern int arizona_eq_coeff_put(struct snd_kcontrol *kcontrol, struct snd_ctl_elem_value *ucontrol); extern int arizona_set_sysclk(struct snd_soc_codec *codec, int clk_id, int source, unsigned int freq, int dir); extern int arizona_cache_and_clear_sources(struct arizona *arizona, const int *sources, unsigned int *cache, int lim); extern int arizona_restore_sources(struct arizona *arizona, const int *sources, unsigned int *cache, int lim); extern int clearwater_edre_stereo_get(struct snd_kcontrol *kcontrol, struct snd_ctl_elem_value *ucontrol); extern int clearwater_edre_stereo_put(struct snd_kcontrol *kcontrol, struct snd_ctl_elem_value *ucontrol); extern void clearwater_spin_sysclk(struct arizona *arizona); extern const struct snd_soc_dai_ops arizona_dai_ops; extern const struct snd_soc_dai_ops arizona_simple_dai_ops; #define ARIZONA_FLL_NAME_LEN 20 struct arizona_fll { struct arizona *arizona; int id; unsigned int base; unsigned int vco_mult; struct completion ok; unsigned int fvco; int min_outdiv; int max_outdiv; int outdiv; unsigned int fout; int sync_src; unsigned int sync_freq; int ref_src; unsigned int ref_freq; char lock_name[ARIZONA_FLL_NAME_LEN]; char clock_ok_name[ARIZONA_FLL_NAME_LEN]; }; extern int arizona_init_fll(struct arizona *arizona, int id, int base, int lock_irq, int ok_irq, struct arizona_fll *fll); extern int arizona_set_fll_refclk(struct arizona_fll *fll, int source, unsigned int Fref, unsigned int Fout); extern int arizona_set_fll(struct arizona_fll *fll, int source, unsigned int Fref, unsigned int Fout); extern int arizona_init_spk(struct snd_soc_codec *codec); extern int arizona_init_gpio(struct snd_soc_codec *codec); extern int arizona_init_mono(struct snd_soc_codec *codec); extern int arizona_init_input(struct snd_soc_codec *codec); extern int arizona_adsp_power_ev(struct snd_soc_dapm_widget *w, struct snd_kcontrol *kcontrol, int event); extern int arizona_init_dai(struct arizona_priv *priv, int dai); int arizona_set_output_mode(struct snd_soc_codec *codec, int output, bool diff); extern int arizona_set_hpdet_cb(struct snd_soc_codec *codec, void (*hpdet_cb)(unsigned int measurement)); extern int arizona_set_micd_cb(struct snd_soc_codec *codec, void (*micd_cb)(bool mic)); extern int arizona_set_ez2ctrl_cb(struct snd_soc_codec *codec, void (*ez2ctrl_trigger)(void)); extern int arizona_set_custom_jd(struct snd_soc_codec *codec, const struct arizona_jd_state *custom_jd); extern int florida_put_dre(struct snd_kcontrol *kcontrol, struct snd_ctl_elem_value *ucontrol); extern int clearwater_put_dre(struct snd_kcontrol *kcontrol, struct snd_ctl_elem_value *ucontrol); extern int arizona_put_out4_edre(struct snd_kcontrol *kcontrol, struct snd_ctl_elem_value *ucontrol); extern struct regmap *arizona_get_regmap_dsp(struct snd_soc_codec *codec); extern struct arizona_extcon_info * arizona_get_extcon_info(struct snd_soc_codec *codec); extern int arizona_enable_force_bypass(struct snd_soc_codec *codec); extern int arizona_disable_force_bypass(struct snd_soc_codec *codec); #endif
The-Sickness/S6-MM
sound/soc/codecs/arizona.h
C
gpl-2.0
15,581
/* Support routines for the intrinsic power (**) operator. Copyright (C) 2004-2021 Free Software Foundation, Inc. Contributed by Paul Brook This file is part of the GNU Fortran 95 runtime library (libgfortran). Libgfortran 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. Libgfortran 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. Under Section 7 of GPL version 3, you are granted additional permissions described in the GCC Runtime Library Exception, version 3.1, as published by the Free Software Foundation. You should have received a copy of the GNU General Public License and a copy of the GCC Runtime Library Exception along with this program; see the files COPYING3 and COPYING.RUNTIME respectively. If not, see <http://www.gnu.org/licenses/>. */ #include "libgfortran.h" /* Use Binary Method to calculate the powi. This is not an optimal but a simple and reasonable arithmetic. See section 4.6.3, "Evaluation of Powers" of Donald E. Knuth, "Seminumerical Algorithms", Vol. 2, "The Art of Computer Programming", 3rd Edition, 1998. */ #if defined (HAVE_GFC_COMPLEX_10) && defined (HAVE_GFC_INTEGER_4) GFC_COMPLEX_10 pow_c10_i4 (GFC_COMPLEX_10 a, GFC_INTEGER_4 b); export_proto(pow_c10_i4); GFC_COMPLEX_10 pow_c10_i4 (GFC_COMPLEX_10 a, GFC_INTEGER_4 b) { GFC_COMPLEX_10 pow, x; GFC_INTEGER_4 n; GFC_UINTEGER_4 u; n = b; x = a; pow = 1; if (n != 0) { if (n < 0) { u = -n; x = pow / x; } else { u = n; } for (;;) { if (u & 1) pow *= x; u >>= 1; if (u) x *= x; else break; } } return pow; } #endif
Gurgel100/gcc
libgfortran/generated/pow_c10_i4.c
C
gpl-2.0
1,971
<?php /** * @package Joomla.UnitTest * @subpackage Form * * @copyright Copyright (C) 2005 - 2017 Open Source Matters, Inc. All rights reserved. * @license GNU General Public License version 2 or later; see LICENSE */ /** * Test class for JFormFieldHeadertag. * * @package Joomla.UnitTest * @subpackage Form * @since 3.1 */ class JFormFieldHeadertagTest extends PHPUnit_Framework_TestCase { /** * Tests the getInput method. * * @return void * * @since 3.1 */ public function testGetInput() { $field = new JFormFieldHeadertag; $field->setup( new SimpleXMLElement('<field name="headertag" type="headertag" label="Header Tag" description="Header Tag listing" />'), 'value' ); $this->assertContains( '<option value="h3">h3</option>', $field->input, 'The getInput method should return an option with the header tags, verify H3 tag is in list.' ); } }
muhakh/joomla-cms
tests/unit/suites/libraries/cms/form/field/JFormFieldHeadertagTest.php
PHP
gpl-2.0
925
'use strict'; Object.defineProperty(exports, "__esModule", { value: true }); exports.getCellMetadata = getCellMetadata; var _initCellMetadata = require('./initCellMetadata'); var _initCellMetadata2 = _interopRequireDefault(_initCellMetadata); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } // Default cell sizes and offsets for use in below tests function getCellMetadata() { var cellSizes = [10, // 0: 0..0 (min) 20, // 1: 0..10 15, // 2: 0..30 10, // 3: 5..45 15, // 4: 20..55 30, // 5: 50..70 20, // 6: 70..100 10, // 7: 80..110 30 // 8: 110..110 (max) ]; return (0, _initCellMetadata2.default)({ cellCount: cellSizes.length, size: function size(_ref) { var index = _ref.index; return cellSizes[index]; } }); }
Alex-Shilman/Drupal8Node
node_modules/react-virtualized/dist/commonjs/utils/TestHelper.js
JavaScript
gpl-2.0
818
/* * Copyright (c) 1996, 2014, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License version 2 only, as * published by the Free Software Foundation. Oracle designates this * particular file as subject to the "Classpath" exception as provided * by Oracle in the LICENSE file that accompanied this code. * * This code is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License * version 2 for more details (a copy is included in the LICENSE file that * accompanied this code). * * You should have received a copy of the GNU General Public License version * 2 along with this work; if not, write to the Free Software Foundation, * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. * * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA * or visit www.oracle.com if you need additional information or have any * questions. */ #include "awt_Menu.h" #include "awt_MenuBar.h" #include "awt_Frame.h" #include <java_awt_Menu.h> #include <sun_awt_windows_WMenuPeer.h> #include <java_awt_MenuBar.h> #include <sun_awt_windows_WMenuBarPeer.h> /* IMPORTANT! Read the README.JNI file for notes on JNI converted AWT code. */ /************************************************************************ * AwtMenuItem fields */ jmethodID AwtMenu::countItemsMID; jmethodID AwtMenu::getItemMID; /************************************************************************ * AwtMenuItem methods */ AwtMenu::AwtMenu() { m_hMenu = NULL; } AwtMenu::~AwtMenu() { } void AwtMenu::Dispose() { if (m_hMenu != NULL) { /* * Don't verify -- may not be a valid anymore if its window * was disposed of first. */ ::DestroyMenu(m_hMenu); m_hMenu = NULL; } AwtMenuItem::Dispose(); } LPCTSTR AwtMenu::GetClassName() { return TEXT("SunAwtMenu"); } /* Create a new AwtMenu object and menu. */ AwtMenu* AwtMenu::Create(jobject self, AwtMenu* parentMenu) { JNIEnv *env = (JNIEnv *)JNU_GetEnv(jvm, JNI_VERSION_1_2); jobject target = NULL; AwtMenu* menu = NULL; try { if (env->EnsureLocalCapacity(1) < 0) { return NULL; } target = env->GetObjectField(self, AwtObject::targetID); JNI_CHECK_NULL_GOTO(target, "null target", done); menu = new AwtMenu(); SetLastError(0); HMENU hMenu = ::CreateMenu(); // fix for 5088782 if (!CheckMenuCreation(env, self, hMenu)) { env->DeleteLocalRef(target); return NULL; } menu->SetHMenu(hMenu); menu->LinkObjects(env, self); menu->SetMenuContainer(parentMenu); if (parentMenu != NULL) { parentMenu->AddItem(menu); } } catch (...) { env->DeleteLocalRef(target); throw; } done: if (target != NULL) { env->DeleteLocalRef(target); } return menu; } void AwtMenu::UpdateLayout() { UpdateLayout(GetHMenu()); RedrawMenuBar(); } void AwtMenu::UpdateLayout(const HMENU hmenu) { const int nMenuItemCount = ::GetMenuItemCount(hmenu); static MENUITEMINFO mii; for (int idx = 0; idx < nMenuItemCount; ++idx) { memset(&mii, 0, sizeof(mii)); mii.cbSize = sizeof(mii); mii.fMask = MIIM_CHECKMARKS | MIIM_DATA | MIIM_ID | MIIM_STATE | MIIM_SUBMENU | MIIM_TYPE; if (::GetMenuItemInfo(hmenu, idx, TRUE, &mii)) { VERIFY(::RemoveMenu(hmenu, idx, MF_BYPOSITION)); VERIFY(::InsertMenuItem(hmenu, idx, TRUE, &mii)); if (mii.hSubMenu != NULL) { UpdateLayout(mii.hSubMenu); } } } } void AwtMenu::UpdateContainerLayout() { AwtMenu* menu = GetMenuContainer(); if (menu != NULL) { menu->UpdateLayout(); } else { UpdateLayout(); } } AwtMenuBar* AwtMenu::GetMenuBar() { return (GetMenuContainer() == NULL) ? NULL : GetMenuContainer()->GetMenuBar(); } HWND AwtMenu::GetOwnerHWnd() { return (GetMenuContainer() == NULL) ? NULL : GetMenuContainer()->GetOwnerHWnd(); } void AwtMenu::AddSeparator() { VERIFY(::AppendMenu(GetHMenu(), MF_SEPARATOR, 0, 0)); } void AwtMenu::AddItem(AwtMenuItem* item) { JNIEnv *env = (JNIEnv *)JNU_GetEnv(jvm, JNI_VERSION_1_2); if (env->EnsureLocalCapacity(2) < 0) { return; } if (item->IsSeparator()) { AddSeparator(); } else { /* jitem is a java.awt.MenuItem */ jobject jitem = item->GetTarget(env); jboolean enabled = (jboolean)env->GetBooleanField(jitem, AwtMenuItem::enabledID); UINT flags = MF_STRING | (enabled ? MF_ENABLED : MF_GRAYED); flags |= MF_OWNERDRAW; LPCTSTR itemInfo = (LPCTSTR) this; if (_tcscmp(item->GetClassName(), TEXT("SunAwtMenu")) == 0) { flags |= MF_POPUP; itemInfo = (LPCTSTR) item; } VERIFY(::AppendMenu(GetHMenu(), flags, item->GetID(), itemInfo)); if (GetRTL()) { MENUITEMINFO mif; memset(&mif, 0, sizeof(MENUITEMINFO)); mif.cbSize = sizeof(MENUITEMINFO); mif.fMask = MIIM_TYPE; ::GetMenuItemInfo(GetHMenu(), item->GetID(), FALSE, &mif); mif.fType |= MFT_RIGHTJUSTIFY | MFT_RIGHTORDER; ::SetMenuItemInfo(GetHMenu(), item->GetID(), FALSE, &mif); } env->DeleteLocalRef(jitem); } } void AwtMenu::DeleteItem(UINT index) { VERIFY(::RemoveMenu(GetHMenu(), index, MF_BYPOSITION)); } void AwtMenu::SendDrawItem(AwtMenuItem* awtMenuItem, DRAWITEMSTRUCT& drawInfo) { awtMenuItem->DrawItem(drawInfo); } void AwtMenu::SendMeasureItem(AwtMenuItem* awtMenuItem, HDC hDC, MEASUREITEMSTRUCT& measureInfo) { awtMenuItem->MeasureItem(hDC, measureInfo); } int AwtMenu::CountItem(jobject target) { JNIEnv *env = (JNIEnv *)JNU_GetEnv(jvm, JNI_VERSION_1_2); jint nCount = env->CallIntMethod(target, AwtMenu::countItemsMID); DASSERT(!safe_ExceptionOccurred(env)); return nCount; } AwtMenuItem* AwtMenu::GetItem(jobject target, jint index) { JNIEnv *env = (JNIEnv *)JNU_GetEnv(jvm, JNI_VERSION_1_2); if (env->EnsureLocalCapacity(2) < 0) { return NULL; } jobject menuItem = env->CallObjectMethod(target, AwtMenu::getItemMID, index); if (!menuItem) return NULL; // menu item was removed concurrently DASSERT(!safe_ExceptionOccurred(env)); jobject wMenuItemPeer = GetPeerForTarget(env, menuItem); PDATA pData; AwtMenuItem* awtMenuItem = NULL; JNI_CHECK_PEER_GOTO(wMenuItemPeer, done); awtMenuItem = (AwtMenuItem*)pData; done: env->DeleteLocalRef(menuItem); env->DeleteLocalRef(wMenuItemPeer); return awtMenuItem; } void AwtMenu::DrawItems(DRAWITEMSTRUCT& drawInfo) { JNIEnv *env = (JNIEnv *)JNU_GetEnv(jvm, JNI_VERSION_1_2); if (env->EnsureLocalCapacity(1) < 0) { return; } /* target is a java.awt.Menu */ jobject target = GetTarget(env); if(!target || env->ExceptionCheck()) return; int nCount = CountItem(target); for (int i = 0; i < nCount && !env->ExceptionCheck(); i++) { AwtMenuItem* awtMenuItem = GetItem(target, i); if (awtMenuItem != NULL) { SendDrawItem(awtMenuItem, drawInfo); } } env->DeleteLocalRef(target); } void AwtMenu::DrawItem(DRAWITEMSTRUCT& drawInfo) { DASSERT(drawInfo.CtlType == ODT_MENU); if (drawInfo.itemID == GetID()) { DrawSelf(drawInfo); return; } DrawItems(drawInfo); } void AwtMenu::MeasureItems(HDC hDC, MEASUREITEMSTRUCT& measureInfo) { JNIEnv *env = (JNIEnv *)JNU_GetEnv(jvm, JNI_VERSION_1_2); if (env->EnsureLocalCapacity(1) < 0) { return; } /* target is a java.awt.Menu */ jobject target = GetTarget(env); if(!target || env->ExceptionCheck()) return; int nCount = CountItem(target); for (int i = 0; i < nCount && !env->ExceptionCheck(); i++) { AwtMenuItem* awtMenuItem = GetItem(target, i); if (awtMenuItem != NULL) { SendMeasureItem(awtMenuItem, hDC, measureInfo); } } env->DeleteLocalRef(target); } void AwtMenu::MeasureItem(HDC hDC, MEASUREITEMSTRUCT& measureInfo) { DASSERT(measureInfo.CtlType == ODT_MENU); if (measureInfo.itemID == GetID()) { MeasureSelf(hDC, measureInfo); return; } MeasureItems(hDC, measureInfo); } BOOL AwtMenu::IsTopMenu() { return (GetMenuBar() == GetMenuContainer()); } LRESULT AwtMenu::WinThreadExecProc(ExecuteArgs * args) { switch( args->cmdId ) { case MENU_ADDSEPARATOR: this->AddSeparator(); break; case MENU_DELITEM: this->DeleteItem(static_cast<UINT>(args->param1)); break; default: AwtMenuItem::WinThreadExecProc(args); break; } return 0L; } /************************************************************************ * WMenuPeer native methods */ extern "C" { JNIEXPORT void JNICALL Java_java_awt_Menu_initIDs(JNIEnv *env, jclass cls) { TRY; AwtMenu::countItemsMID = env->GetMethodID(cls, "countItemsImpl", "()I"); DASSERT(AwtMenu::countItemsMID != NULL); CHECK_NULL(AwtMenu::countItemsMID); AwtMenu::getItemMID = env->GetMethodID(cls, "getItemImpl", "(I)Ljava/awt/MenuItem;"); DASSERT(AwtMenu::getItemMID != NULL); CATCH_BAD_ALLOC; } } /* extern "C" */ /************************************************************************ * WMenuPeer native methods */ extern "C" { /* * Class: sun_awt_windows_WMenuPeer * Method: addSeparator * Signature: ()V */ JNIEXPORT void JNICALL Java_sun_awt_windows_WMenuPeer_addSeparator(JNIEnv *env, jobject self) { TRY; PDATA pData; JNI_CHECK_PEER_RETURN(self); AwtObject::WinThreadExec(self, AwtMenu::MENU_ADDSEPARATOR); CATCH_BAD_ALLOC; } /* * Class: sun_awt_windows_WMenuPeer * Method: delItem * Signature: (I)V */ JNIEXPORT void JNICALL Java_sun_awt_windows_WMenuPeer_delItem(JNIEnv *env, jobject self, jint index) { TRY; PDATA pData; JNI_CHECK_PEER_RETURN(self); AwtObject::WinThreadExec(self, AwtMenu::MENU_DELITEM, index); CATCH_BAD_ALLOC; } /* * Class: sun_awt_windows_WMenuPeer * Method: createMenu * Signature: (Lsun/awt/windows/WMenuBarPeer;)V */ JNIEXPORT void JNICALL Java_sun_awt_windows_WMenuPeer_createMenu(JNIEnv *env, jobject self, jobject menuBar) { TRY; PDATA pData; JNI_CHECK_PEER_RETURN(menuBar); AwtMenuBar* awtMenuBar = (AwtMenuBar *)pData; AwtToolkit::CreateComponent(self, awtMenuBar, (AwtToolkit::ComponentFactory)AwtMenu::Create,FALSE); JNI_CHECK_PEER_CREATION_RETURN(self); CATCH_BAD_ALLOC; } /* * Class: sun_awt_windows_WMenuPeer * Method: createSubMenu * Signature: (Lsun/awt/windows/WMenuPeer;)V */ JNIEXPORT void JNICALL Java_sun_awt_windows_WMenuPeer_createSubMenu(JNIEnv *env, jobject self, jobject menu) { TRY; PDATA pData; JNI_CHECK_PEER_RETURN(menu); AwtMenu* awtMenu = (AwtMenu *)pData; AwtToolkit::CreateComponent(self, awtMenu, (AwtToolkit::ComponentFactory)AwtMenu::Create,FALSE); JNI_CHECK_PEER_CREATION_RETURN(self); CATCH_BAD_ALLOC; } } /* extern "C" */
FauxFaux/jdk9-jdk
src/java.desktop/windows/native/libawt/windows/awt_Menu.cpp
C++
gpl-2.0
11,965
/*lint --e{537,713,732,752}*/ #ifdef __KERNEL__ #include <linux/platform_device.h> #include <soc_interrupts_app.h> #elif defined(__VXWORKS__) #include <string.h> #include <soc_interrupts_mdm.h> //#include <bsp_uart.h> #endif #include <osl_module.h> #include <bsp_memmap.h> #include <bsp_om.h> #include <bsp_ipc.h> #include <bsp_hardtimer.h> #include <bsp_dpm.h> #include "ipc_balong.h" #ifdef __cplusplus extern "C" { #endif void bsp_ipc_debug_show(void); extern s32 bsp_ipc_test_init(void); #ifdef __KERNEL__ #define IPC_INT INT_LVL_IPCM2APP0 #define IPC_SEM INT_LVL_IPCM2APP1 #elif defined(__VXWORKS__) #define IPC_INT INT_LVL_IPCM2MDM0 #define IPC_SEM INT_LVL_IPCM2MDM1 #endif static struct ipc_control ipc_ctrl; static struct ipc_debug_s ipc_debug = {0}; #define IPC_CHECK_PARA(para,max) \ do {\ if (para >= max)\ {\ bsp_trace(BSP_LOG_LEVEL_ERROR,BSP_MODU_IPC,"[%s]Wrong para , line:%d,para = %d\n",__FUNCTION__, __LINE__,para); \ return ERROR; \ } \ } while (0) s32 bsp_ipc_int_enable (IPC_INT_LEV_E ulLvl) { u32 u32IntMask = 0; unsigned long flags=0; IPC_CHECK_PARA(ulLvl,IPC_INT_BUTTOM); /*дÖÐ¶ÏÆÁ±Î¼Ä´æÆ÷*/ spin_lock_irqsave(&ipc_ctrl.lock,flags); u32IntMask = readl(ipc_ctrl.ipc_base + BSP_IPC_CPU_INT_MASK(ipc_ctrl.core_num)); u32IntMask |= (u32)1 << ulLvl; writel(u32IntMask,ipc_ctrl.ipc_base+BSP_IPC_CPU_INT_MASK(ipc_ctrl.core_num)); spin_unlock_irqrestore(&ipc_ctrl.lock,flags); return OK; } s32 bsp_ipc_int_disable(IPC_INT_LEV_E ulLvl) { u32 u32IntMask = 0; unsigned long flags=0; IPC_CHECK_PARA(ulLvl,IPC_INT_BUTTOM); /*дÖÐ¶ÏÆÁ±Î¼Ä´æÆ÷*/ spin_lock_irqsave(&ipc_ctrl.lock,flags); u32IntMask = readl(ipc_ctrl.ipc_base + BSP_IPC_CPU_INT_MASK(ipc_ctrl.core_num)); u32IntMask = u32IntMask & (~((u32)1 << ulLvl)); writel(u32IntMask, ipc_ctrl.ipc_base + BSP_IPC_CPU_INT_MASK(ipc_ctrl.core_num)); spin_unlock_irqrestore(&ipc_ctrl.lock,flags); return OK; } s32 bsp_ipc_int_connect(IPC_INT_LEV_E ulLvl, voidfuncptr routine, u32 parameter) { unsigned long flags=0; IPC_CHECK_PARA(ulLvl,IPC_INT_BUTTOM); spin_lock_irqsave(&ipc_ctrl.lock,flags); ipc_ctrl.ipc_int_table[ulLvl].routine = routine; ipc_ctrl.ipc_int_table[ulLvl].arg = parameter; spin_unlock_irqrestore(&ipc_ctrl.lock,flags); return OK; } s32 bsp_ipc_int_disconnect(IPC_INT_LEV_E ulLvl,voidfuncptr routine, u32 parameter) { unsigned long flags = 0; IPC_CHECK_PARA(ulLvl,IPC_INT_BUTTOM); spin_lock_irqsave(&ipc_ctrl.lock,flags); ipc_ctrl.ipc_int_table[ulLvl].routine = NULL; ipc_ctrl.ipc_int_table[ulLvl].arg = 0; spin_unlock_irqrestore(&ipc_ctrl.lock,flags); return OK; } OSL_IRQ_FUNC(static irqreturn_t,ipc_int_handler,irq,dev_id) { u32 i = 0; u32 u32IntStat = 0,begin = 0,end = 0; u32 u32Date = 0x1; u32 u32BitValue = 0; u32IntStat=readl(ipc_ctrl.ipc_base + BSP_IPC_CPU_INT_STAT(ipc_ctrl.core_num)); /*ÇåÖжÏ*/ writel(u32IntStat,ipc_ctrl.ipc_base + BSP_IPC_CPU_INT_CLR(ipc_ctrl.core_num)); /* ±éÀú32¸öÖÐ¶Ï */ for (i = 0; i < INTSRC_NUM; i++) { if(0!=i) { u32Date <<= 1; } u32BitValue = u32IntStat & u32Date; /* Èç¹ûÓÐÖÐ¶Ï ,Ôòµ÷ÓöÔÓ¦Öжϴ¦Àíº¯Êý */ if (0 != u32BitValue) { /*µ÷ÓÃ×¢²áµÄÖжϴ¦Àíº¯Êý*/ if (NULL != ipc_ctrl.ipc_int_table[i].routine) { begin = bsp_get_slice_value(); ipc_ctrl.ipc_int_table[i].routine(ipc_ctrl.ipc_int_table[i].arg); end = bsp_get_slice_value(); ipc_debug.u32IntTimeDelta[i] = get_timer_slice_delta(begin,end); } else { bsp_trace(BSP_LOG_LEVEL_ERROR,BSP_MODU_IPC,"BSP_DRV_IpcIntHandler:No IntConnect,ERROR!.int num =%d\n",i); } ipc_debug.u32IntHandleTimes[i]++; } } return IRQ_HANDLED; } s32 bsp_ipc_int_send(IPC_INT_CORE_E enDstCore, IPC_INT_LEV_E ulLvl) { unsigned long flags = 0; IPC_CHECK_PARA(ulLvl,IPC_INT_BUTTOM); IPC_CHECK_PARA(enDstCore,IPC_CORE_BUTTOM); /*дԭʼÖжϼĴæÆ÷,²úÉúÖжÏ*/ spin_lock_irqsave(&ipc_ctrl.lock,flags); writel((u32)1 << ulLvl,ipc_ctrl.ipc_base + BSP_IPC_CPU_RAW_INT(enDstCore)); #ifdef CONFIG_P531_DRX_IPC switch(ulLvl) { case IPC_INT_DICC_RELDATA: case IPC_ACPU_INT_SRC_CCPU_MSG: case IPC_ACPU_INT_SRC_CCPU_NVIM: case IPC_INT_DICC_USRDATA: case IPC_ACPU_INT_SRC_ICC: case IPC_ACPU_INT_SRC_ICC_PRIVATE: case IPC_ACPU_SRC_CCPU_DUMP: writel(1<<IPC_MCU_INT_SRC_CCPU_DRX,ipc_ctrl.ipc_base + BSP_IPC_CPU_RAW_INT(IPC_CORE_MCORE)); break; default: break; } #endif spin_unlock_irqrestore(&ipc_ctrl.lock,flags); ipc_debug.u32RecvIntCore = enDstCore; ipc_debug.u32IntSendTimes[enDstCore][ulLvl]++; return OK; } static void mask_int(u32 u32SignalNum) { u32 u32IntMask = 0; unsigned long flags=0; spin_lock_irqsave(&ipc_ctrl.lock,flags); u32IntMask = readl(ipc_ctrl.ipc_base + BSP_IPC_SEM_INT_MASK(ipc_ctrl.core_num)); u32IntMask = u32IntMask & (~((u32)1 << u32SignalNum)); writel(u32IntMask,ipc_ctrl.ipc_base + BSP_IPC_SEM_INT_MASK(ipc_ctrl.core_num)); spin_unlock_irqrestore(&ipc_ctrl.lock,flags); } s32 bsp_ipc_sem_create(u32 u32SignalNum) { IPC_CHECK_PARA(u32SignalNum,IPC_SEM_BUTTOM); if(true != ipc_ctrl.sem_exist[u32SignalNum])/*±ÜÃâͬһ¸öÐźÅÁ¿ÔÚûÓÐɾ³ýµÄÇé¿öÏ´´½¨¶à´Î*/ { osl_sem_init(SEM_EMPTY,&(ipc_ctrl.sem_ipc_task[u32SignalNum])); ipc_ctrl.sem_exist[u32SignalNum] = true; return OK; } else { return OK; } } s32 bsp_ipc_sem_delete(u32 u32SignalNum) { IPC_CHECK_PARA(u32SignalNum,IPC_SEM_BUTTOM); if(false == ipc_ctrl.sem_exist[u32SignalNum] ) { bsp_trace(BSP_LOG_LEVEL_ERROR,BSP_MODU_IPC,"semphore not exists,may be deleted already.\n"); return ERROR; } else { if (osl_sema_delete(&(ipc_ctrl.sem_ipc_task[u32SignalNum]))) { bsp_trace(BSP_LOG_LEVEL_ERROR,BSP_MODU_IPC,"Delete semphore failed.\n"); return ERROR; } ipc_ctrl.sem_exist[u32SignalNum] = false; return OK; } } s32 bsp_ipc_sem_take(u32 u32SignalNum,s32 s32timeout) { u32 u32IntMask = 0,ret = 0; /*²ÎÊý¼ì²é*/ IPC_CHECK_PARA(u32SignalNum,IPC_SEM_BUTTOM); /*½«ÉêÇëµÄÐźÅÁ¿¶ÔÓ¦µÄÊÍ·ÅÖжÏÇåÁã*/ writel((u32)1<<u32SignalNum, ipc_ctrl.ipc_base+BSP_IPC_SEM_INT_CLR(ipc_ctrl.core_num)); ret = readl(ipc_ctrl.ipc_base + BSP_IPC_HS_CTRL(ipc_ctrl.core_num, u32SignalNum)); if(0 == ret) { mask_int(u32SignalNum); ipc_debug.u32SemTakeTimes[u32SignalNum]++; ipc_debug.u32SemId = u32SignalNum; return OK; } else { if(false == ipc_ctrl.sem_exist[u32SignalNum]) { bsp_trace(BSP_LOG_LEVEL_ERROR,BSP_MODU_IPC,"need call ipc_sem_create to create this sem before call ipc_sem_take!\n"); return ERROR; } if(0 != s32timeout) { /*ʹÄÜÐźÅÁ¿ÊÍ·ÅÖжÏ*/ u32IntMask = readl(ipc_ctrl.ipc_base + BSP_IPC_SEM_INT_MASK(ipc_ctrl.core_num)); u32IntMask = u32IntMask | ((u32)1 << u32SignalNum); writel(u32IntMask,ipc_ctrl.ipc_base + BSP_IPC_SEM_INT_MASK(ipc_ctrl.core_num)); if (OK != osl_sem_downtimeout(&(ipc_ctrl.sem_ipc_task[u32SignalNum]), s32timeout)) { mask_int(u32SignalNum); bsp_trace(BSP_LOG_LEVEL_ERROR,BSP_MODU_IPC,"semTake timeout!\n"); ipc_debug.u32SemTakeFailTimes[u32SignalNum]++; return ERROR; } else { mask_int(u32SignalNum); ipc_debug.u32SemTakeTimes[u32SignalNum]++; ipc_debug.u32SemId = u32SignalNum; return OK; } } else { return ERROR; } } } s32 bsp_ipc_sem_give(u32 u32SignalNum) { IPC_CHECK_PARA(u32SignalNum,IPC_SEM_BUTTOM); ipc_debug.u32SemGiveTimes[u32SignalNum]++; /*ÏòÐźÅÁ¿ÇëÇó¼Ä´æÆ÷д0*/ writel(0,ipc_ctrl.ipc_base + BSP_IPC_HS_CTRL(ipc_ctrl.core_num, u32SignalNum)); return OK; } static s32 ffSLsb(s32 args) { s32 num = 0; s32 s32ImpVal = args; if(0 == args) { return 0; } for(;;) { num++; if (0x1 == (s32ImpVal & 0x1)) { break; } s32ImpVal = (s32)((u32)s32ImpVal >> 1); } return num; } /***************************************************************************** * º¯ Êý Ãû : ipc_sem_int_handler * * ¹¦ÄÜÃèÊö : ÐźÅÁ¿ÊÍ·ÅÖжϴ¦Àíº¯Êý * * ÊäÈë²ÎÊý : ÎÞ * Êä³ö²ÎÊý : ÎÞ * * ·µ »Ø Öµ : ÎÞ * * Ð޸ļǼ : 2013Äê1ÔÂ9ÈÕ lixiaojie *****************************************************************************/ OSL_IRQ_FUNC(static irqreturn_t,ipc_sem_int_handler,irq,dev_id) { u32 u32IntStat = 0,u32HsCtrl=0,u32SNum=0, i = 32; u32IntStat = readl(ipc_ctrl.ipc_base+BSP_IPC_SEM_INT_STAT(ipc_ctrl.core_num)); u32SNum = ffSLsb(u32IntStat); if( u32SNum != 0) { do { /*Èç¹ûÓÐÐźÅÁ¿ÊÍ·ÅÖжϣ¬Çå³ý¸ÃÖжÏ*/ writel((u32)1<<--u32SNum, ipc_ctrl.ipc_base+BSP_IPC_SEM_INT_CLR(ipc_ctrl.core_num)); u32HsCtrl = readl(ipc_ctrl.ipc_base + BSP_IPC_HS_CTRL(ipc_ctrl.core_num, u32SNum)); if (0 == u32HsCtrl) { osl_sem_up(&(ipc_ctrl.sem_ipc_task[u32SNum])); } else { ipc_debug.u32SemTakeFailTimes[u32SNum]++; } u32IntStat = readl(ipc_ctrl.ipc_base+BSP_IPC_SEM_INT_STAT(ipc_ctrl.core_num)); u32SNum = ffSLsb(u32IntStat); i--; }while((u32SNum != 0) && (i > 0)); } else { return IRQ_NONE; } return IRQ_HANDLED; } s32 bsp_ipc_spin_lock(u32 u32SignalNum) { u32 u32HsCtrl = 0; IPC_CHECK_PARA(u32SignalNum,IPC_SEM_BUTTOM); for(;;) { u32HsCtrl = readl(ipc_ctrl.ipc_base + BSP_IPC_HS_CTRL(ipc_ctrl.core_num, u32SignalNum)); if (0 == u32HsCtrl) { ipc_debug.u32SemTakeTimes[u32SignalNum]++; ipc_debug.u32SemId = u32SignalNum; break; } } return OK; } s32 bsp_ipc_spin_unlock (u32 u32SignalNum) { IPC_CHECK_PARA(u32SignalNum,IPC_SEM_BUTTOM); writel(0,ipc_ctrl.ipc_base + BSP_IPC_HS_CTRL(ipc_ctrl.core_num, u32SignalNum)); return OK; } static s32 ipc_suspend_late(struct dpm_device *dev) { u32 i = 0,ret = 0; for(i=0;i<32;i++) { ret = readl(ipc_ctrl.ipc_base + BSP_IPC_HS_STAT(ipc_ctrl.core_num,i)); if(ret==0x9) { //printksync("ipc signum id = %d is occupied\n",i); return ERROR; } } return OK; } struct dpm_device ipc_dpm = { .device_name = "ipc dpm", .suspend_late = ipc_suspend_late, }; void bsp_ipc_init(void) { s32 ret = 0,i = 0; ipc_ctrl.core_num = IPC_CORE_CCORE; for(i = 0;i< INTSRC_NUM;i++ ) { ipc_ctrl.sem_exist[i] = false; } #ifdef CONFIG_CCORE_PM ret = bsp_device_pm_add(&ipc_dpm); if(ret) { bsp_trace(BSP_LOG_LEVEL_ERROR,BSP_MODU_IPC,"ipc init fail\n"); return; } #endif memset((void*)(ipc_ctrl.ipc_int_table),0x0,sizeof(struct ipc_entry) *INTSRC_NUM); ipc_ctrl.ipc_base = HI_IPCM_REGBASE_ADDR_VIRT; writel(0x0,ipc_ctrl.ipc_base + BSP_IPC_CPU_INT_MASK(ipc_ctrl.core_num)); writel(0x0,ipc_ctrl.ipc_base + BSP_IPC_SEM_INT_MASK(ipc_ctrl.core_num)); spin_lock_init(&ipc_ctrl.lock); ret = request_irq(IPC_INT,(irq_handler_t) ipc_int_handler, 0, "ipc_irq",(void*) NULL); if (ret ) { bsp_trace(BSP_LOG_LEVEL_ERROR,BSP_MODU_IPC,"ipc int handler error,init failed\n"); return; } ret = request_irq(IPC_SEM, (irq_handler_t) ipc_sem_int_handler, 0, "ipc_sem",(void*) NULL); if (ret ) { bsp_trace(BSP_LOG_LEVEL_ERROR,BSP_MODU_IPC,"ipc sem handler error,init failed\n"); return; } #ifdef ENABLE_TEST_CODE ret = bsp_ipc_test_init(); if (ret ) { bsp_trace(BSP_LOG_LEVEL_ERROR,BSP_MODU_IPC,"bsp_ipc_test_init failed\n"); return; } #endif bsp_trace(BSP_LOG_LEVEL_ERROR,BSP_MODU_IPC,"ipc init success\n"); return; } void bsp_ipc_debug_show(void) { u32 i = 0; bsp_trace(BSP_LOG_LEVEL_ERROR,BSP_MODU_IPC,"\nµ±Ç°Õ¼ÓõÄÐźÅÁ¿IDΪ : \t%d\n", ipc_debug.u32SemId); bsp_trace(BSP_LOG_LEVEL_ERROR,BSP_MODU_IPC,"µ±Ç°½ÓÊÕÖжϵÄCore IDΪ : \t%d\n", ipc_debug.u32RecvIntCore); for(i = 0; i < INTSRC_NUM; i++) { bsp_trace(BSP_LOG_LEVEL_ERROR,BSP_MODU_IPC,"ÐźÅÁ¿%d»ñÈ¡´ÎÊý : \t%d\n", i,ipc_debug.u32SemTakeTimes[i]); bsp_trace(BSP_LOG_LEVEL_ERROR,BSP_MODU_IPC,"ÐźÅÁ¿%dÊÍ·Å´ÎÊý : \t%d\n", i,ipc_debug.u32SemGiveTimes[i]); bsp_trace(BSP_LOG_LEVEL_ERROR,BSP_MODU_IPC,"%dºÅÖжϽÓÊյĴÎÊýΪ : \t%d\n",i, ipc_debug.u32IntHandleTimes[i]); bsp_trace(BSP_LOG_LEVEL_ERROR,BSP_MODU_IPC,"%dºÅÖжϴ¦Àíº¯ÊýÖ´ÐÐʱ¼äΪ : \t%d us\n",i, ipc_debug.u32IntTimeDelta[i]*1000000/HI_TCXO_CLK); } } void bsp_int_send_info(void) { u32 i = 0,j = 0; for(i = 0;i <IPC_CORE_BUTTOM;i++) { for(j=0;j<IPC_INT_BUTTOM;j++) { bsp_trace(BSP_LOG_LEVEL_ERROR,BSP_MODU_IPC,"ÍùºË%d·¢ËÍÖжÏ%dµÄ´ÎÊýΪ: \t%d\n",i,j, ipc_debug.u32IntSendTimes[i][j]); } } } #ifdef __cplusplus } #endif
gabry3795/android_kernel_huawei_mt7_l09
drivers/vendor/hisi/modem/drv/ccore/drivers/ipc/ipc_balong.c
C
gpl-2.0
12,731
/* Copyright 2019 MechMerlin <mechmerlin@gmail.com> * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ #include "v3.h" #include "indicator_leds.h" enum BACKLIGHT_AREAS { BACKLIGHT_ALPHAS = 0b00000010, BACKLIGHT_MODNUM = 0b00001000 }; void backlight_set(uint8_t level) { switch(level) { case 0: PORTB |= BACKLIGHT_ALPHAS; PORTB |= BACKLIGHT_MODNUM; break; case 1: PORTB &= ~BACKLIGHT_ALPHAS; PORTB |= BACKLIGHT_MODNUM; break; case 2: PORTB |= BACKLIGHT_ALPHAS; PORTB &= ~BACKLIGHT_MODNUM; break; case 3: PORTB &= ~BACKLIGHT_ALPHAS; PORTB &= ~BACKLIGHT_MODNUM; break; } } // Port from backlight_update_state void led_set_kb(uint8_t usb_led) { bool status[8] = { IS_HOST_LED_ON(USB_LED_SCROLL_LOCK), /* LED 3 */ IS_HOST_LED_ON(USB_LED_CAPS_LOCK), /* LED 2 */ IS_HOST_LED_ON(USB_LED_NUM_LOCK), /* LED 1 */ layer_state & (1<<2), /* LED 6 */ layer_state & (1<<1), /* LED 5 */ layer_state & (1<<0) ? 0: 1, /* LED 4 */ layer_state & (1<<5), /* LED 8 */ layer_state & (1<<4) /* LED 7 */ }; indicator_leds_set(status); } bool process_record_kb(uint16_t keycode, keyrecord_t *record) { return process_record_user(keycode, record); }
chancegrissom/qmk_firmware
keyboards/duck/orion/v3/v3.c
C
gpl-2.0
1,967
class CfgVehicles { class Man; class CAManBase: Man { class ACE_SelfActions { class ACE_Equipment { class GVAR(adjustZero) { // Updates the zero reference displayName = "$STR_ACE_Scopes_AdjustZero"; condition = QUOTE([ACE_player] call FUNC(canAdjustZero)); statement = QUOTE([ACE_player] call FUNC(adjustZero)); showDisabled = 0; priority = 0.2; //icon = QUOTE(PATHTOF(UI\...)); // TODO exceptions[] = {"notOnMap", "isNotInside"}; }; }; }; }; };
Dimaslg/ACE3
addons/scopes/CfgVehicles.hpp
C++
gpl-2.0
690
/* This testcase is part of GDB, the GNU debugger. Copyright 2008-2020 Free Software Foundation, Inc. This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see <http://www.gnu.org/licenses/>. */ #include <unistd.h> #include <stdlib.h> #include <sys/wait.h> void marker1 (void) { } void marker2 (void) { } int status = -1; int main (void) { marker1 (); if (!fork ()) _exit (123); else waitpid (-1, &status, 0); marker2 (); return 0; }
mattstock/binutils-bexkat1
gdb/testsuite/gdb.reverse/waitpid-reverse.c
C
gpl-2.0
1,015
package org.freeplane.core.util; import java.io.File; import java.util.Arrays; import java.util.Collections; import java.util.List; import org.apache.commons.lang.StringUtils; public class ConfigurationUtils { private static final String CONFIG_LIST_VALUE_SEPARATOR_STRICT = File.pathSeparator + File.pathSeparator; private static final String CONFIG_LIST_VALUE_SEPARATOR_ONE_OR_MORE = File.pathSeparator + '+'; /** if not requireTwo one pathseparator suffices otherwise two are required. */ public static List<String> decodeListValue(final String value, boolean requireTwo) { if (value.length() == 0) return Collections.emptyList(); final String sep = requireTwo ? CONFIG_LIST_VALUE_SEPARATOR_STRICT : CONFIG_LIST_VALUE_SEPARATOR_ONE_OR_MORE; // -1: don't discard trailing empty strings return Arrays.asList(value.split("\\s*" + sep + "\\s*", -1)); } /** if not requireTwo one pathseparator suffices otherwise two are required. */ public static String encodeListValue(final List<String> list, boolean requireTwo) { return StringUtils.join(list.iterator(), requireTwo ? CONFIG_LIST_VALUE_SEPARATOR_STRICT : CONFIG_LIST_VALUE_SEPARATOR_ONE_OR_MORE); } public static File getLocalizedFile(final File[] baseDirs, final String document, final String languageCode) { final int extPosition = document.lastIndexOf('.'); final String localizedDocument; if (extPosition != -1) { localizedDocument = document.substring(0, extPosition) + "_" + languageCode + document.substring(extPosition); } else{ localizedDocument = document; } for(File baseDir : baseDirs){ if(baseDir != null){ final File localFile = new File(baseDir, localizedDocument); if (localFile.canRead()) { return localFile; } final File file = new File(baseDir, document); if (file.canRead()) { return file; } } } return null; } }
fnatter/freeplane-debian-dev
freeplane/src/main/java/org/freeplane/core/util/ConfigurationUtils.java
Java
gpl-2.0
1,999
/* * Copyright (C) 2007-2009 Geometer Plus <contact@geometerplus.com> * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA * 02110-1301, USA. */ package org.geometerplus.fbreader.formats.txt; import java.io.File; import java.io.IOException; import java.io.InputStream; import org.geometerplus.fbreader.bookmodel.BookModel; import org.geometerplus.fbreader.formats.FormatPlugin; import org.geometerplus.fbreader.library.Book; import org.geometerplus.zlibrary.core.filesystem.ZLFile; import org.geometerplus.zlibrary.core.image.ZLImage; public class TxtPlugin extends FormatPlugin { //Override public boolean acceptsFile(ZLFile file) { return "txt".equalsIgnoreCase(file.getExtension()); } public boolean readDescription(BookModel model) { int enc = new SinoDetect().detectEncoding(new File(model.Book.File.getPath())); // System.out.println("encoding is ======"+enc); InputStream stream = null; try { stream = model.Book.File.getInputStream(); if (stream.available() <= 0) { return false; } //Here, we are supposed to set language and encoder model.Book.setEncoding(SinoDetect.nicename[enc]); detectEncodingAndLanguage(model.Book, stream); } catch (IOException e) { e.printStackTrace(); } finally { try { stream.close(); } catch (IOException e) { // ignore } } /* if (description.getEncoding() == null || description.getEncoding().equals("")) { return false; } */ return true; } //Override public boolean readModel(BookModel model) { File mfile = new File(model.Book.File.getPath()); if(mfile.length() == 0) return false; readDescription(model); return new TxtReader(model).readBook(); } //Override public ZLImage readCover(Book book) { // TODO Auto-generated method stub return null; } //Override public boolean readMetaInfo(Book book) { // TODO Auto-generated method stub return true; } }
giannoug/android_device_jxd_s7300b
packages/PicturePlayer/src/org/geometerplus/fbreader/formats/txt/TxtPlugin.java
Java
gpl-2.0
2,743
/* * mmap support for qemu * * Copyright (c) 2003 Fabrice Bellard * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, see <http://www.gnu.org/licenses/>. */ #include <stdlib.h> #include <stdio.h> #include <stdarg.h> #include <string.h> #include <unistd.h> #include <errno.h> #include <sys/types.h> #include <sys/stat.h> #include <sys/mman.h> #include <linux/mman.h> #include <linux/unistd.h> #include "qemu.h" #include "qemu-common.h" //#define DEBUG_MMAP #if defined(CONFIG_USE_NPTL) pthread_mutex_t mmap_mutex = PTHREAD_MUTEX_INITIALIZER; static int __thread mmap_lock_count; void mmap_lock(void) { if (mmap_lock_count++ == 0) { pthread_mutex_lock(&mmap_mutex); } } void mmap_unlock(void) { if (--mmap_lock_count == 0) { pthread_mutex_unlock(&mmap_mutex); } } /* Grab lock to make sure things are in a consistent state after fork(). */ void mmap_fork_start(void) { if (mmap_lock_count) abort(); pthread_mutex_lock(&mmap_mutex); } void mmap_fork_end(int child) { if (child) pthread_mutex_init(&mmap_mutex, NULL); else pthread_mutex_unlock(&mmap_mutex); } #else /* We aren't threadsafe to start with, so no need to worry about locking. */ void mmap_lock(void) { } void mmap_unlock(void) { } #endif void *qemu_vmalloc(size_t size) { void *p; unsigned long addr; mmap_lock(); /* Use map and mark the pages as used. */ p = mmap(NULL, size, PROT_READ | PROT_WRITE, MAP_PRIVATE | MAP_ANONYMOUS, -1, 0); addr = (unsigned long)p; if (addr == (target_ulong) addr) { /* Allocated region overlaps guest address space. This may recurse. */ page_set_flags(addr & TARGET_PAGE_MASK, TARGET_PAGE_ALIGN(addr + size), PAGE_RESERVED); } mmap_unlock(); return p; } void *qemu_malloc(size_t size) { char * p; size += 16; p = qemu_vmalloc(size); *(size_t *)p = size; return p + 16; } /* We use map, which is always zero initialized. */ void * qemu_mallocz(size_t size) { return qemu_malloc(size); } void qemu_free(void *ptr) { /* FIXME: We should unmark the reserved pages here. However this gets complicated when one target page spans multiple host pages, so we don't bother. */ size_t *p; p = (size_t *)((char *)ptr - 16); munmap(p, *p); } void *qemu_realloc(void *ptr, size_t size) { size_t old_size, copy; void *new_ptr; if (!ptr) return qemu_malloc(size); old_size = *(size_t *)((char *)ptr - 16); copy = old_size < size ? old_size : size; new_ptr = qemu_malloc(size); memcpy(new_ptr, ptr, copy); qemu_free(ptr); return new_ptr; } /* NOTE: all the constants are the HOST ones, but addresses are target. */ int target_mprotect(abi_ulong start, abi_ulong len, int prot) { abi_ulong end, host_start, host_end, addr; int prot1, ret; #ifdef DEBUG_MMAP printf("mprotect: start=0x" TARGET_ABI_FMT_lx "len=0x" TARGET_ABI_FMT_lx " prot=%c%c%c\n", start, len, prot & PROT_READ ? 'r' : '-', prot & PROT_WRITE ? 'w' : '-', prot & PROT_EXEC ? 'x' : '-'); #endif if ((start & ~TARGET_PAGE_MASK) != 0) return -EINVAL; len = TARGET_PAGE_ALIGN(len); end = start + len; if (end < start) return -EINVAL; prot &= PROT_READ | PROT_WRITE | PROT_EXEC; if (len == 0) return 0; mmap_lock(); host_start = start & qemu_host_page_mask; host_end = HOST_PAGE_ALIGN(end); if (start > host_start) { /* handle host page containing start */ prot1 = prot; for(addr = host_start; addr < start; addr += TARGET_PAGE_SIZE) { prot1 |= page_get_flags(addr); } if (host_end == host_start + qemu_host_page_size) { for(addr = end; addr < host_end; addr += TARGET_PAGE_SIZE) { prot1 |= page_get_flags(addr); } end = host_end; } ret = mprotect(g2h(host_start), qemu_host_page_size, prot1 & PAGE_BITS); if (ret != 0) goto error; host_start += qemu_host_page_size; } if (end < host_end) { prot1 = prot; for(addr = end; addr < host_end; addr += TARGET_PAGE_SIZE) { prot1 |= page_get_flags(addr); } ret = mprotect(g2h(host_end - qemu_host_page_size), qemu_host_page_size, prot1 & PAGE_BITS); if (ret != 0) goto error; host_end -= qemu_host_page_size; } /* handle the pages in the middle */ if (host_start < host_end) { ret = mprotect(g2h(host_start), host_end - host_start, prot); if (ret != 0) goto error; } page_set_flags(start, start + len, prot | PAGE_VALID); mmap_unlock(); return 0; error: mmap_unlock(); return ret; } /* map an incomplete host page */ static int mmap_frag(abi_ulong real_start, abi_ulong start, abi_ulong end, int prot, int flags, int fd, abi_ulong offset) { abi_ulong real_end, addr; void *host_start; int prot1, prot_new; real_end = real_start + qemu_host_page_size; host_start = g2h(real_start); /* get the protection of the target pages outside the mapping */ prot1 = 0; for(addr = real_start; addr < real_end; addr++) { if (addr < start || addr >= end) prot1 |= page_get_flags(addr); } if (prot1 == 0) { /* no page was there, so we allocate one */ void *p = mmap(host_start, qemu_host_page_size, prot, flags | MAP_ANONYMOUS, -1, 0); if (p == MAP_FAILED) return -1; prot1 = prot; } prot1 &= PAGE_BITS; prot_new = prot | prot1; if (!(flags & MAP_ANONYMOUS)) { /* msync() won't work here, so we return an error if write is possible while it is a shared mapping */ if ((flags & MAP_TYPE) == MAP_SHARED && (prot & PROT_WRITE)) return -EINVAL; /* adjust protection to be able to read */ if (!(prot1 & PROT_WRITE)) mprotect(host_start, qemu_host_page_size, prot1 | PROT_WRITE); /* read the corresponding file data */ pread(fd, g2h(start), end - start, offset); /* put final protection */ if (prot_new != (prot1 | PROT_WRITE)) mprotect(host_start, qemu_host_page_size, prot_new); } else { /* just update the protection */ if (prot_new != prot1) { mprotect(host_start, qemu_host_page_size, prot_new); } } return 0; } #if defined(__CYGWIN__) /* Cygwin doesn't have a whole lot of address space. */ static abi_ulong mmap_next_start = 0x18000000; #else static abi_ulong mmap_next_start = 0x40000000; #endif unsigned long last_brk; /* find a free memory area of size 'size'. The search starts at 'start'. If 'start' == 0, then a default start address is used. Return -1 if error. */ /* page_init() marks pages used by the host as reserved to be sure not to use them. */ abi_ulong mmap_find_vma(abi_ulong start, abi_ulong size) { abi_ulong addr, addr1, addr_start; int prot; unsigned long new_brk; new_brk = (unsigned long)sbrk(0); if (last_brk && last_brk < new_brk && last_brk == (target_ulong)last_brk) { /* This is a hack to catch the host allocating memory with brk(). If it uses mmap then we loose. FIXME: We really want to avoid the host allocating memory in the first place, and maybe leave some slack to avoid switching to mmap. */ page_set_flags(last_brk & TARGET_PAGE_MASK, TARGET_PAGE_ALIGN(new_brk), PAGE_RESERVED); } last_brk = new_brk; size = HOST_PAGE_ALIGN(size); start = start & qemu_host_page_mask; addr = start; if (addr == 0) addr = mmap_next_start; addr_start = addr; for(;;) { prot = 0; for(addr1 = addr; addr1 < (addr + size); addr1 += TARGET_PAGE_SIZE) { prot |= page_get_flags(addr1); } if (prot == 0) break; addr += qemu_host_page_size; /* we found nothing */ if (addr == addr_start) return (abi_ulong)-1; } if (start == 0) mmap_next_start = addr + size; return addr; } /* NOTE: all the constants are the HOST ones */ abi_long target_mmap(abi_ulong start, abi_ulong len, int prot, int flags, int fd, abi_ulong offset) { abi_ulong ret, end, real_start, real_end, retaddr, host_offset, host_len; unsigned long host_start; mmap_lock(); #ifdef DEBUG_MMAP { printf("mmap: start=0x" TARGET_ABI_FMT_lx " len=0x" TARGET_ABI_FMT_lx " prot=%c%c%c flags=", start, len, prot & PROT_READ ? 'r' : '-', prot & PROT_WRITE ? 'w' : '-', prot & PROT_EXEC ? 'x' : '-'); if (flags & MAP_FIXED) printf("MAP_FIXED "); if (flags & MAP_ANONYMOUS) printf("MAP_ANON "); switch(flags & MAP_TYPE) { case MAP_PRIVATE: printf("MAP_PRIVATE "); break; case MAP_SHARED: printf("MAP_SHARED "); break; default: printf("[MAP_TYPE=0x%x] ", flags & MAP_TYPE); break; } printf("fd=%d offset=" TARGET_ABI_FMT_lx "\n", fd, offset); } #endif if (offset & ~TARGET_PAGE_MASK) { errno = EINVAL; goto fail; } len = TARGET_PAGE_ALIGN(len); if (len == 0) goto the_end; real_start = start & qemu_host_page_mask; /* When mapping files into a memory area larger than the file, accesses to pages beyond the file size will cause a SIGBUS. For example, if mmaping a file of 100 bytes on a host with 4K pages emulating a target with 8K pages, the target expects to be able to access the first 8K. But the host will trap us on any access beyond 4K. When emulating a target with a larger page-size than the hosts, we may need to truncate file maps at EOF and add extra anonymous pages up to the targets page boundary. */ if ((qemu_real_host_page_size < TARGET_PAGE_SIZE) && !(flags & MAP_ANONYMOUS)) { struct stat sb; if (fstat (fd, &sb) == -1) goto fail; /* Are we trying to create a map beyond EOF?. */ if (offset + len > sb.st_size) { /* If so, truncate the file map at eof aligned with the hosts real pagesize. Additional anonymous maps will be created beyond EOF. */ len = (sb.st_size - offset); len += qemu_real_host_page_size - 1; len &= ~(qemu_real_host_page_size - 1); } } if (!(flags & MAP_FIXED)) { abi_ulong mmap_start; void *p; host_offset = offset & qemu_host_page_mask; host_len = len + offset - host_offset; host_len = HOST_PAGE_ALIGN(host_len); mmap_start = mmap_find_vma(real_start, host_len); if (mmap_start == (abi_ulong)-1) { errno = ENOMEM; goto fail; } /* Note: we prefer to control the mapping address. It is especially important if qemu_host_page_size > qemu_real_host_page_size */ p = mmap(g2h(mmap_start), host_len, prot, flags | MAP_FIXED | MAP_ANONYMOUS, -1, 0); if (p == MAP_FAILED) goto fail; /* update start so that it points to the file position at 'offset' */ host_start = (unsigned long)p; if (!(flags & MAP_ANONYMOUS)) { p = mmap(g2h(mmap_start), len, prot, flags | MAP_FIXED, fd, host_offset); host_start += offset - host_offset; } start = h2g(host_start); } else { int flg; target_ulong addr; if (start & ~TARGET_PAGE_MASK) { errno = EINVAL; goto fail; } end = start + len; real_end = HOST_PAGE_ALIGN(end); /* * Test if requested memory area fits target address space * It can fail only on 64-bit host with 32-bit target. * On any other target/host host mmap() handles this error correctly. */ if ((unsigned long)start + len - 1 > (abi_ulong) -1) { errno = EINVAL; goto fail; } for(addr = real_start; addr < real_end; addr += TARGET_PAGE_SIZE) { flg = page_get_flags(addr); if (flg & PAGE_RESERVED) { errno = ENXIO; goto fail; } } /* worst case: we cannot map the file because the offset is not aligned, so we read it */ if (!(flags & MAP_ANONYMOUS) && (offset & ~qemu_host_page_mask) != (start & ~qemu_host_page_mask)) { /* msync() won't work here, so we return an error if write is possible while it is a shared mapping */ if ((flags & MAP_TYPE) == MAP_SHARED && (prot & PROT_WRITE)) { errno = EINVAL; goto fail; } retaddr = target_mmap(start, len, prot | PROT_WRITE, MAP_FIXED | MAP_PRIVATE | MAP_ANONYMOUS, -1, 0); if (retaddr == -1) goto fail; pread(fd, g2h(start), len, offset); if (!(prot & PROT_WRITE)) { ret = target_mprotect(start, len, prot); if (ret != 0) { start = ret; goto the_end; } } goto the_end; } /* handle the start of the mapping */ if (start > real_start) { if (real_end == real_start + qemu_host_page_size) { /* one single host page */ ret = mmap_frag(real_start, start, end, prot, flags, fd, offset); if (ret == -1) goto fail; goto the_end1; } ret = mmap_frag(real_start, start, real_start + qemu_host_page_size, prot, flags, fd, offset); if (ret == -1) goto fail; real_start += qemu_host_page_size; } /* handle the end of the mapping */ if (end < real_end) { ret = mmap_frag(real_end - qemu_host_page_size, real_end - qemu_host_page_size, real_end, prot, flags, fd, offset + real_end - qemu_host_page_size - start); if (ret == -1) goto fail; real_end -= qemu_host_page_size; } /* map the middle (easier) */ if (real_start < real_end) { void *p; unsigned long offset1; if (flags & MAP_ANONYMOUS) offset1 = 0; else offset1 = offset + real_start - start; p = mmap(g2h(real_start), real_end - real_start, prot, flags, fd, offset1); if (p == MAP_FAILED) goto fail; } } the_end1: page_set_flags(start, start + len, prot | PAGE_VALID); the_end: #ifdef DEBUG_MMAP printf("ret=0x" TARGET_ABI_FMT_lx "\n", start); page_dump(stdout); printf("\n"); #endif mmap_unlock(); return start; fail: mmap_unlock(); return -1; } int target_munmap(abi_ulong start, abi_ulong len) { abi_ulong end, real_start, real_end, addr; int prot, ret; #ifdef DEBUG_MMAP printf("munmap: start=0x" TARGET_ABI_FMT_lx " len=0x" TARGET_ABI_FMT_lx "\n", start, len); #endif if (start & ~TARGET_PAGE_MASK) return -EINVAL; len = TARGET_PAGE_ALIGN(len); if (len == 0) return -EINVAL; mmap_lock(); end = start + len; real_start = start & qemu_host_page_mask; real_end = HOST_PAGE_ALIGN(end); if (start > real_start) { /* handle host page containing start */ prot = 0; for(addr = real_start; addr < start; addr += TARGET_PAGE_SIZE) { prot |= page_get_flags(addr); } if (real_end == real_start + qemu_host_page_size) { for(addr = end; addr < real_end; addr += TARGET_PAGE_SIZE) { prot |= page_get_flags(addr); } end = real_end; } if (prot != 0) real_start += qemu_host_page_size; } if (end < real_end) { prot = 0; for(addr = end; addr < real_end; addr += TARGET_PAGE_SIZE) { prot |= page_get_flags(addr); } if (prot != 0) real_end -= qemu_host_page_size; } ret = 0; /* unmap what we can */ if (real_start < real_end) { ret = munmap(g2h(real_start), real_end - real_start); } if (ret == 0) page_set_flags(start, start + len, 0); mmap_unlock(); return ret; } abi_long target_mremap(abi_ulong old_addr, abi_ulong old_size, abi_ulong new_size, unsigned long flags, abi_ulong new_addr) { int prot; void *host_addr; mmap_lock(); if (flags & MREMAP_FIXED) host_addr = (void *) syscall(__NR_mremap, g2h(old_addr), old_size, new_size, flags, new_addr); else if (flags & MREMAP_MAYMOVE) { abi_ulong mmap_start; mmap_start = mmap_find_vma(0, new_size); if (mmap_start == -1) { errno = ENOMEM; host_addr = MAP_FAILED; } else host_addr = (void *) syscall(__NR_mremap, g2h(old_addr), old_size, new_size, flags | MREMAP_FIXED, g2h(mmap_start)); } else { host_addr = mremap(g2h(old_addr), old_size, new_size, flags); /* Check if address fits target address space */ if ((unsigned long)host_addr + new_size > (abi_ulong)-1) { /* Revert mremap() changes */ host_addr = mremap(g2h(old_addr), new_size, old_size, flags); errno = ENOMEM; host_addr = MAP_FAILED; } } if (host_addr == MAP_FAILED) { new_addr = -1; } else { new_addr = h2g(host_addr); prot = page_get_flags(old_addr); page_set_flags(old_addr, old_addr + old_size, 0); page_set_flags(new_addr, new_addr + new_size, prot | PAGE_VALID); } mmap_unlock(); return new_addr; } int target_msync(abi_ulong start, abi_ulong len, int flags) { abi_ulong end; if (start & ~TARGET_PAGE_MASK) return -EINVAL; len = TARGET_PAGE_ALIGN(len); end = start + len; if (end < start) return -EINVAL; if (end == start) return 0; start &= qemu_host_page_mask; return msync(g2h(start), end - start, flags); }
bulotus/bulotus-qemu-at91sam9263ek
linux-user/mmap.c
C
gpl-2.0
19,863
<!DOCTYPE html> <html> <head> <title>Smart Rendering</title> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"/> <meta http-equiv="X-UA-Compatible" content="IE=edge"/> <link rel="stylesheet" type="text/css" href="../../../codebase/dhtmlx.css"/> <script src="../../../codebase/dhtmlx.js"></script> <script> var myGrid; function doOnLoad(){ myGrid = new dhtmlXGridObject('gridbox'); myGrid.setImagePath("../../../codebase/imgs/"); myGrid.setHeader("Order,Index,Request info"); myGrid.setInitWidths("50,275,*"); myGrid.setColAlign("right,left,left"); myGrid.setColTypes("ed,ed,ed"); myGrid.setColSorting("na,na,na"); myGrid.init(); myGrid.enableSmartRendering(true,50); myGrid.loadXML("php/dynload.php"); } </script> </head> <body onload="doOnLoad()"> <h1>Smart Rendering</h1> <p> To increase grid performance working with very large amoung of data you can enable <strong>Smart Rendering</strong> mode with dynamical loading of rows from server (already loaded rows remain on client side). <br> To achieve this you should add the following javascript command: <br> <em>yourGrid.enableSmartRendering(mode,count);</em> <br><br> - and make your server side output records based on incomming parameters: <br> <div>posStart -the first row in portion</div> <div>count - number of rows to return</div> <div id="gridbox" style="width:600px;height:250px;background-color:white;"></div> </body> </html>
o-unity/lanio
old/dhtmlx/samples/dhtmlxGrid/14_loading_big_datasets/03_grid_dyn.html
HTML
gpl-2.0
1,504
/* Copyright (c) 2011-2012, The Linux Foundation. All rights reserved. * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License version 2 and * only version 2 as published by the Free Software Foundation. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. */ #include <linux/init.h> #include <linux/module.h> #include <linux/fs.h> #include <linux/slab.h> #include <linux/miscdevice.h> #include <linux/spinlock.h> #include <linux/uaccess.h> #include <linux/io.h> #include <linux/irq.h> #include <linux/interrupt.h> #include <linux/sched.h> #include <linux/wait.h> #include <linux/poll.h> #include <mach/msm_iomap.h> #include <linux/fsm_dfe_hh.h> /* */ #define HH_ADDR_MASK 0x000ffffc #define HH_OFFSET_VALID(offset) (((offset) & ~HH_ADDR_MASK) == 0) #define HH_REG_IOADDR(offset) ((uint8_t *) MSM_HH_BASE + (offset)) #define HH_MAKE_OFFSET(blk, adr) (((blk)&0x1F)<<15|((adr)&0x1FFF)<<2) #define HH_REG_SCPN_IREQ_MASK HH_REG_IOADDR(HH_MAKE_OFFSET(5, 0x12)) #define HH_REG_SCPN_IREQ_FLAG HH_REG_IOADDR(HH_MAKE_OFFSET(5, 0x13)) /* */ #define HH_IRQ_FIFO_SIZE 64 #define HH_IRQ_FIFO_EMPTY(pdev) ((pdev)->irq_fifo_head == \ (pdev)->irq_fifo_tail) #define HH_IRQ_FIFO_FULL(pdev) ((((pdev)->irq_fifo_tail + 1) % \ HH_IRQ_FIFO_SIZE) == \ (pdev)->irq_fifo_head) static struct hh_dev_node_info { spinlock_t hh_lock; char irq_fifo[HH_IRQ_FIFO_SIZE]; unsigned int irq_fifo_head, irq_fifo_tail; wait_queue_head_t wq; } hh_dev_info; /* */ struct hh_dev_file_info { /* */ unsigned int *parray; unsigned int array_num; struct dfe_command_entry *pcmd; unsigned int cmd_num; }; /* */ static int hh_open(struct inode *inode, struct file *file) { struct hh_dev_file_info *pdfi; /* */ pdfi = kmalloc(sizeof(*pdfi), GFP_KERNEL); if (pdfi == NULL) return -ENOMEM; file->private_data = pdfi; /* */ pdfi->parray = NULL; pdfi->array_num = 0; pdfi->pcmd = NULL; pdfi->cmd_num = 0; return 0; } static int hh_release(struct inode *inode, struct file *file) { struct hh_dev_file_info *pdfi; pdfi = (struct hh_dev_file_info *) file->private_data; kfree(pdfi->parray); pdfi->parray = NULL; pdfi->array_num = 0; kfree(pdfi->pcmd); pdfi->pcmd = NULL; pdfi->cmd_num = 0; kfree(file->private_data); file->private_data = NULL; return 0; } static ssize_t hh_read(struct file *filp, char __user *buf, size_t count, loff_t *f_pos) { signed char irq = -1; unsigned long irq_flags; do { spin_lock_irqsave(&hh_dev_info.hh_lock, irq_flags); if (!HH_IRQ_FIFO_EMPTY(&hh_dev_info)) { irq = hh_dev_info.irq_fifo[hh_dev_info.irq_fifo_head]; if (++hh_dev_info.irq_fifo_head == HH_IRQ_FIFO_SIZE) hh_dev_info.irq_fifo_head = 0; } spin_unlock_irqrestore(&hh_dev_info.hh_lock, irq_flags); if (irq < 0) if (wait_event_interruptible(hh_dev_info.wq, !HH_IRQ_FIFO_EMPTY(&hh_dev_info)) < 0) break; } while (irq < 0); if (irq < 0) { /* */ return 0; } else { put_user(irq, buf); return 1; } return 0; } static ssize_t hh_write(struct file *file, const char __user *buffer, size_t count, loff_t *ppos) { return 0; } static long hh_ioctl(struct file *file, unsigned int cmd, unsigned long arg) { unsigned int __user *argp = (unsigned int __user *) arg; struct hh_dev_file_info *pdfi = (struct hh_dev_file_info *) file->private_data; switch (cmd) { case DFE_IOCTL_READ_REGISTER: { unsigned int offset, value; if (get_user(offset, argp)) return -EFAULT; if (!HH_OFFSET_VALID(offset)) return -EINVAL; value = __raw_readl(HH_REG_IOADDR(offset)); if (put_user(value, argp)) return -EFAULT; } break; case DFE_IOCTL_WRITE_REGISTER: { struct dfe_write_register_param param; if (copy_from_user(&param, argp, sizeof param)) return -EFAULT; if (!HH_OFFSET_VALID(param.offset)) return -EINVAL; __raw_writel(param.value, HH_REG_IOADDR(param.offset)); } break; case DFE_IOCTL_WRITE_REGISTER_WITH_MASK: { struct dfe_write_register_mask_param param; unsigned int value; unsigned long irq_flags; if (copy_from_user(&param, argp, sizeof param)) return -EFAULT; if (!HH_OFFSET_VALID(param.offset)) return -EINVAL; spin_lock_irqsave(&hh_dev_info.hh_lock, irq_flags); value = __raw_readl(HH_REG_IOADDR(param.offset)); value &= ~param.mask; value |= param.value & param.mask; __raw_writel(value, HH_REG_IOADDR(param.offset)); spin_unlock_irqrestore(&hh_dev_info.hh_lock, irq_flags); } break; case DFE_IOCTL_READ_REGISTER_ARRAY: case DFE_IOCTL_WRITE_REGISTER_ARRAY: { struct dfe_read_write_array_param param; unsigned int req_sz; unsigned long irq_flags; unsigned int i; void *addr; if (copy_from_user(&param, argp, sizeof param)) return -EFAULT; if (!HH_OFFSET_VALID(param.offset)) return -EINVAL; if (param.num == 0) break; req_sz = sizeof(unsigned int) * param.num; if (pdfi->array_num < param.num) { void *pmem; pmem = kmalloc(req_sz, GFP_KERNEL); if (pmem == NULL) return -ENOMEM; pdfi->parray = (unsigned int *) pmem; pdfi->array_num = param.num; } if (cmd == DFE_IOCTL_WRITE_REGISTER_ARRAY) if (copy_from_user(pdfi->parray, param.pArray, req_sz)) return -EFAULT; addr = HH_REG_IOADDR(param.offset); spin_lock_irqsave(&hh_dev_info.hh_lock, irq_flags); for (i = 0; i < param.num; ++i, addr += 4) { if (cmd == DFE_IOCTL_READ_REGISTER_ARRAY) pdfi->parray[i] = __raw_readl(addr); else __raw_writel(pdfi->parray[i], addr); } spin_unlock_irqrestore(&hh_dev_info.hh_lock, irq_flags); if (cmd == DFE_IOCTL_READ_REGISTER_ARRAY) if (copy_to_user(pdfi->parray, param.pArray, req_sz)) return -EFAULT; } break; case DFE_IOCTL_COMMAND: { struct dfe_command_param param; unsigned int req_sz; unsigned long irq_flags; unsigned int i, value; struct dfe_command_entry *pcmd; void *addr; if (copy_from_user(&param, argp, sizeof param)) return -EFAULT; if (param.num == 0) break; req_sz = sizeof(struct dfe_command_entry) * param.num; if (pdfi->cmd_num < param.num) { void *pmem; pmem = kmalloc(req_sz, GFP_KERNEL); if (pmem == NULL) return -ENOMEM; pdfi->pcmd = (struct dfe_command_entry *) pmem; pdfi->cmd_num = param.num; } if (copy_from_user(pdfi->pcmd, param.pEntry, req_sz)) return -EFAULT; pcmd = pdfi->pcmd; spin_lock_irqsave(&hh_dev_info.hh_lock, irq_flags); for (i = 0; i < param.num; ++i, ++pcmd) { if (!HH_OFFSET_VALID(pcmd->offset)) return -EINVAL; addr = HH_REG_IOADDR(pcmd->offset); switch (pcmd->code) { case DFE_IOCTL_COMMAND_CODE_WRITE: __raw_writel(pcmd->value, addr); break; case DFE_IOCTL_COMMAND_CODE_WRITE_WITH_MASK: value = __raw_readl(addr); value &= ~pcmd->mask; value |= pcmd->value & pcmd->mask; __raw_writel(value, addr); break; } } spin_unlock_irqrestore(&hh_dev_info.hh_lock, irq_flags); } break; default: return -EINVAL; } return 0; } static unsigned int hh_poll(struct file *filp, struct poll_table_struct *wait) { unsigned mask = 0; if (!HH_IRQ_FIFO_EMPTY(&hh_dev_info)) mask |= POLLIN; if (mask == 0) { poll_wait(filp, &hh_dev_info.wq, wait); if (!HH_IRQ_FIFO_EMPTY(&hh_dev_info)) mask |= POLLIN; } return mask; } static const struct file_operations hh_fops = { .owner = THIS_MODULE, .open = hh_open, .release = hh_release, .read = hh_read, .write = hh_write, .unlocked_ioctl = hh_ioctl, .poll = hh_poll, }; /* */ static irqreturn_t hh_irq_handler(int irq, void *data) { unsigned int irq_enable, irq_flag, irq_mask; int i; irq_enable = __raw_readl(HH_REG_SCPN_IREQ_MASK); irq_flag = __raw_readl(HH_REG_SCPN_IREQ_FLAG); irq_flag &= irq_enable; /* */ irq_enable &= ~irq_flag; __raw_writel(irq_enable, HH_REG_SCPN_IREQ_MASK); /* */ spin_lock(&hh_dev_info.hh_lock); for (i = 0, irq_mask = 1; i < 32; ++i, irq_mask <<= 1) { if (HH_IRQ_FIFO_FULL(&hh_dev_info)) break; if (irq_flag & irq_mask) { hh_dev_info.irq_fifo[hh_dev_info.irq_fifo_tail] = \ (char) i; if (++hh_dev_info.irq_fifo_tail == HH_IRQ_FIFO_SIZE) hh_dev_info.irq_fifo_tail = 0; } } spin_unlock(&hh_dev_info.hh_lock); /* */ wake_up_interruptible(&hh_dev_info.wq); return IRQ_HANDLED; } /* */ static struct miscdevice hh_misc_dev = { .minor = MISC_DYNAMIC_MINOR, .name = DFE_HH_DEVICE_NAME, .fops = &hh_fops, }; static int __init hh_init(void) { int ret; /* */ spin_lock_init(&hh_dev_info.hh_lock); /* */ hh_dev_info.irq_fifo_head = 0; hh_dev_info.irq_fifo_tail = 0; ret = request_irq(INT_HH_SUPSS_IRQ, hh_irq_handler, IRQF_TRIGGER_RISING, "hh_dev", 0); if (ret < 0) { pr_err("Cannot register HH interrupt handler.\n"); return ret; } /* */ init_waitqueue_head(&hh_dev_info.wq); return misc_register(&hh_misc_dev); } static void __exit hh_exit(void) { misc_deregister(&hh_misc_dev); free_irq(INT_HH_SUPSS_IRQ, 0); } MODULE_LICENSE("GPL v2"); MODULE_AUTHOR("Rohit Vaswani <rvaswani@codeaurora.org>"); MODULE_DESCRIPTION("Qualcomm Hammerhead Digital Front End driver"); MODULE_VERSION("1.0"); module_init(hh_init); module_exit(hh_exit);
TeamLGOG/android_kernel_lge_d800
arch/arm/mach-msm/dfe-fsm9xxx.c
C
gpl-2.0
9,910
<?php /** * WP-Members Admin Functions * * Functions to manage administration. * * This file is part of the WP-Members plugin by Chad Butler * You can find out more about this plugin at http://rocketgeek.com * Copyright (c) 2006-2013 Chad Butler (email : plugins@butlerblog.com) * WP-Members(tm) is a trademark of butlerblog.com * * @package WordPress * @subpackage WP-Members * @author Chad Butler * @copyright 2006-2013 */ /** File Includes */ include_once( 'dialogs.php' ); //include_once( 'users.php' ); // currently included in the main plugin file //include_once( 'user-profile.php' ); // currently included in the main plugin file /** Actions and Filters */ add_action( 'wpmem_admin_do_tab', 'wpmem_admin_do_tab', 10, 2 ); add_action( 'wp_ajax_wpmem_a_field_reorder', 'wpmem_a_do_field_reorder' ); add_filter( 'plugin_action_links', 'wpmem_admin_plugin_links', 10, 2 ); /** * Calls the function to reorder fields * * @since 2.8.0 * * @uses wpmem_a_field_reorder */ function wpmem_a_do_field_reorder(){ include_once( 'tab-fields.php' ); wpmem_a_field_reorder(); } /** * filter to add link to settings from plugin panel * * @since 2.4 * * @param array $links * @param string $file * @static string $wpmem_plugin * @return array $links */ function wpmem_admin_plugin_links( $links, $file ) { static $wpmem_plugin; if( !$wpmem_plugin ) $wpmem_plugin = plugin_basename( 'wp-members/wp-members.php' ); if( $file == $wpmem_plugin ) { $settings_link = '<a href="options-general.php?page=wpmem-settings">' . __( 'Settings' ) . '</a>'; $links = array_merge( array( $settings_link ), $links ); } return $links; } /** * Loads the admin javascript and css files * * @since 2.5.1 * * @uses wp_enqueue_script * @uses wp_enqueue_style */ function wpmem_load_admin_js() { // queue up admin ajax and styles wp_enqueue_script( 'wpmem-admin-js', WPMEM_DIR . '/js/admin.js', '', WPMEM_VERSION ); wp_enqueue_style ( 'wpmem-admin-css', WPMEM_DIR . '/css/admin.css', '', WPMEM_VERSION ); } /** * Creates the captcha tab * * @since 2.8 * * @param string $tab * @return */ function wpmem_a_captcha_tab( $tab ) { include_once( 'tab-captcha.php' ); return ( $tab == 'captcha' ) ? wpmem_a_build_captcha_options() : false ; } /** * Adds the captcha tab * * @since 2.8 * * @param array $tabs The array of tabs for the admin panel * @return array The updated array of tabs for the admin panel */ function wpmem_add_captcha_tab( $tabs ) { return array_merge( $tabs, array( 'captcha' => 'Captcha' ) ); } /** * Primary admin function * * @since 2.1 * * @uses do_action wpmem_admin_do_tab */ function wpmem_admin() { $did_update = ( isset( $_POST['wpmem_admin_a'] ) ) ? wpmem_admin_action( $_POST['wpmem_admin_a'] ) : false; $wpmem_settings = get_option( 'wpmembers_settings' ); if( $wpmem_settings[6] ) { add_filter( 'wpmem_admin_tabs', 'wpmem_add_captcha_tab' ); add_action( 'wpmem_admin_do_tab', 'wpmem_a_captcha_tab', 1, 1 ); } ?> <div class="wrap"> <?php screen_icon( 'options-general' ); ?> <!--<h2>WP-Members <?php _e('Settings', 'wp-members'); ?></h2>--> <?php $tab = ( isset( $_GET['tab'] ) ) ? $_GET['tab'] : 'options'; wpmem_admin_tabs( $tab ); wpmem_a_do_warnings( $did_update, $wpmem_settings ); do_action( 'wpmem_admin_do_tab', $tab, $wpmem_settings ); ?> </div><!-- .wrap --><?php return; } /** * Displays the content for default tabs * * @since 2.8 * * @param string $tab The tab that we are on and displaying * @param array $wpmem_settings The array of plugin settings */ function wpmem_admin_do_tab( $tab, $wpmem_settings ) { switch ( $tab ) { case 'options' : include_once( 'tab-options.php' ); wpmem_a_build_options( $wpmem_settings ); break; case 'fields' : include_once( 'tab-fields.php' ); wpmem_a_build_fields(); break; case 'dialogs' : include_once( 'tab-dialogs.php' ); wpmem_a_build_dialogs(); break; case 'emails' : include_once( 'tab-emails.php' ); wpmem_a_build_emails( $wpmem_settings ); break; } } /** * Assemble the tabs for the admin panel * * @since 2.8 * * @uses apply_filters Calls wpmem_admin_tabs * * @param string $current The tab that we are on */ function wpmem_admin_tabs( $current = 'options' ) { $tabs = array( 'options' => 'WP-Members ' . __( 'Options', 'wp-members' ), 'fields' => __( 'Fields', 'wp-members' ), 'dialogs' => __( 'Dialogs', 'wp-members' ), 'emails' => __( 'Emails', 'wp-members' ) ); $tabs = apply_filters( 'wpmem_admin_tabs', $tabs ); $links = array(); foreach( $tabs as $tab => $name ) { $class = ( $tab == $current ) ? 'nav-tab nav-tab-active' : 'nav-tab'; $links[] = '<a class="' . $class . '" href="?page=wpmem-settings&amp;tab=' . $tab . '">' . $name . '</a>'; } echo '<h2 class="nav-tab-wrapper">'; foreach( $links as $link ) echo $link; echo '</h2>'; } /** * Handles the various update actions for the default tabs * * @since 2.8 * * @param string $action The action that is being done */ function wpmem_admin_action( $action ) { switch( $action ) { case( 'update_settings' ): include_once( 'tab-options.php' ); $did_update = wpmem_update_options(); break; case( 'update_fields' ): case( 'add_field' ): case( 'edit_field' ): include_once( 'tab-fields.php' ); $did_update = wpmem_update_fields( $action ); break; case( 'update_dialogs' ): include_once( 'tab-dialogs.php' ); $did_update = wpmem_update_dialogs(); break; case( 'update_emails' ): include_once( 'tab-emails.php' ); $did_update = wpmem_update_emails(); break; case( 'update_captcha' ): include_once( 'tab-captcha.php' ); $did_update = wpmem_update_captcha(); break; } return $did_update; } ?>
beetleskin/klimotion
wp-content/plugins/wp-members/admin/admin.php
PHP
gpl-2.0
6,072
/* * linux/ipc/sem.c * Copyright (C) 1992 Krishna Balasubramanian * Copyright (C) 1995 Eric Schenk, Bruno Haible * * IMPLEMENTATION NOTES ON CODE REWRITE (Eric Schenk, January 1995): * This code underwent a massive rewrite in order to solve some problems * with the original code. In particular the original code failed to * wake up processes that were waiting for semval to go to 0 if the * value went to 0 and was then incremented rapidly enough. In solving * this problem I have also modified the implementation so that it * processes pending operations in a FIFO manner, thus give a guarantee * that processes waiting for a lock on the semaphore won't starve * unless another locking process fails to unlock. * In addition the following two changes in behavior have been introduced: * - The original implementation of semop returned the value * last semaphore element examined on success. This does not * match the manual page specifications, and effectively * allows the user to read the semaphore even if they do not * have read permissions. The implementation now returns 0 * on success as stated in the manual page. * - There is some confusion over whether the set of undo adjustments * to be performed at exit should be done in an atomic manner. * That is, if we are attempting to decrement the semval should we queue * up and wait until we can do so legally? * The original implementation attempted to do this. * The current implementation does not do so. This is because I don't * think it is the right thing (TM) to do, and because I couldn't * see a clean way to get the old behavior with the new design. * The POSIX standard and SVID should be consulted to determine * what behavior is mandated. * * Further notes on refinement (Christoph Rohland, December 1998): * - The POSIX standard says, that the undo adjustments simply should * redo. So the current implementation is o.K. * - The previous code had two flaws: * 1) It actively gave the semaphore to the next waiting process * sleeping on the semaphore. Since this process did not have the * cpu this led to many unnecessary context switches and bad * performance. Now we only check which process should be able to * get the semaphore and if this process wants to reduce some * semaphore value we simply wake it up without doing the * operation. So it has to try to get it later. Thus e.g. the * running process may reacquire the semaphore during the current * time slice. If it only waits for zero or increases the semaphore, * we do the operation in advance and wake it up. * 2) It did not wake up all zero waiting processes. We try to do * better but only get the semops right which only wait for zero or * increase. If there are decrement operations in the operations * array we do the same as before. * * With the incarnation of O(1) scheduler, it becomes unnecessary to perform * check/retry algorithm for waking up blocked processes as the new scheduler * is better at handling thread switch than the old one. * * /proc/sysvipc/sem support (c) 1999 Dragos Acostachioaie <dragos@iname.com> * * SMP-threaded, sysctl's added * (c) 1999 Manfred Spraul <manfred@colorfullife.com> * Enforced range limit on SEM_UNDO * (c) 2001 Red Hat Inc * Lockless wakeup * (c) 2003 Manfred Spraul <manfred@colorfullife.com> * * support for audit of ipc object properties and permission changes * Dustin Kirkland <dustin.kirkland@us.ibm.com> * * namespaces support * OpenVZ, SWsoft Inc. * Pavel Emelianov <xemul@openvz.org> */ #include <linux/slab.h> #include <linux/spinlock.h> #include <linux/init.h> #include <linux/proc_fs.h> #include <linux/time.h> #include <linux/security.h> #include <linux/syscalls.h> #include <linux/audit.h> #include <linux/capability.h> #include <linux/seq_file.h> #include <linux/rwsem.h> #include <linux/nsproxy.h> #include <linux/ipc_namespace.h> #include <asm/uaccess.h> #include "util.h" #define sem_ids(ns) ((ns)->ids[IPC_SEM_IDS]) #define sem_unlock(sma) ipc_unlock(&(sma)->sem_perm) #define sem_checkid(sma, semid) ipc_checkid(&sma->sem_perm, semid) static int newary(struct ipc_namespace *, struct ipc_params *); static void freeary(struct ipc_namespace *, struct kern_ipc_perm *); #ifdef CONFIG_PROC_FS static int sysvipc_sem_proc_show(struct seq_file *s, void *it); #endif #define SEMMSL_FAST 256 /* 512 bytes on stack */ #define SEMOPM_FAST 64 /* ~ 372 bytes on stack */ /* * linked list protection: * sem_undo.id_next, * sem_array.sem_pending{,last}, * sem_array.sem_undo: sem_lock() for read/write * sem_undo.proc_next: only "current" is allowed to read/write that field. * */ #define sc_semmsl sem_ctls[0] #define sc_semmns sem_ctls[1] #define sc_semopm sem_ctls[2] #define sc_semmni sem_ctls[3] void sem_init_ns(struct ipc_namespace *ns) { ns->sc_semmsl = SEMMSL; ns->sc_semmns = SEMMNS; ns->sc_semopm = SEMOPM; ns->sc_semmni = SEMMNI; ns->used_sems = 0; ipc_init_ids(&ns->ids[IPC_SEM_IDS]); } #ifdef CONFIG_IPC_NS void sem_exit_ns(struct ipc_namespace *ns) { free_ipcs(ns, &sem_ids(ns), freeary); idr_destroy(&ns->ids[IPC_SEM_IDS].ipcs_idr); } #endif void __init sem_init (void) { sem_init_ns(&init_ipc_ns); ipc_init_proc_interface("sysvipc/sem", " key semid perms nsems uid gid cuid cgid otime ctime\n", IPC_SEM_IDS, sysvipc_sem_proc_show); } /* * sem_lock_(check_) routines are called in the paths where the rw_mutex * is not held. */ static inline struct sem_array *sem_lock(struct ipc_namespace *ns, int id) { struct kern_ipc_perm *ipcp = ipc_lock(&sem_ids(ns), id); if (IS_ERR(ipcp)) return (struct sem_array *)ipcp; return container_of(ipcp, struct sem_array, sem_perm); } static inline struct sem_array *sem_lock_check(struct ipc_namespace *ns, int id) { struct kern_ipc_perm *ipcp = ipc_lock_check(&sem_ids(ns), id); if (IS_ERR(ipcp)) return (struct sem_array *)ipcp; return container_of(ipcp, struct sem_array, sem_perm); } static inline void sem_lock_and_putref(struct sem_array *sma) { ipc_lock_by_ptr(&sma->sem_perm); ipc_rcu_putref(sma); } static inline void sem_getref_and_unlock(struct sem_array *sma) { ipc_rcu_getref(sma); ipc_unlock(&(sma)->sem_perm); } static inline void sem_putref(struct sem_array *sma) { ipc_lock_by_ptr(&sma->sem_perm); ipc_rcu_putref(sma); ipc_unlock(&(sma)->sem_perm); } static inline void sem_rmid(struct ipc_namespace *ns, struct sem_array *s) { ipc_rmid(&sem_ids(ns), &s->sem_perm); } /* * Lockless wakeup algorithm: * Without the check/retry algorithm a lockless wakeup is possible: * - queue.status is initialized to -EINTR before blocking. * - wakeup is performed by * * unlinking the queue entry from sma->sem_pending * * setting queue.status to IN_WAKEUP * This is the notification for the blocked thread that a * result value is imminent. * * call wake_up_process * * set queue.status to the final value. * - the previously blocked thread checks queue.status: * * if it's IN_WAKEUP, then it must wait until the value changes * * if it's not -EINTR, then the operation was completed by * update_queue. semtimedop can return queue.status without * performing any operation on the sem array. * * otherwise it must acquire the spinlock and check what's up. * * The two-stage algorithm is necessary to protect against the following * races: * - if queue.status is set after wake_up_process, then the woken up idle * thread could race forward and try (and fail) to acquire sma->lock * before update_queue had a chance to set queue.status * - if queue.status is written before wake_up_process and if the * blocked process is woken up by a signal between writing * queue.status and the wake_up_process, then the woken up * process could return from semtimedop and die by calling * sys_exit before wake_up_process is called. Then wake_up_process * will oops, because the task structure is already invalid. * (yes, this happened on s390 with sysv msg). * */ #define IN_WAKEUP 1 /** * newary - Create a new semaphore set * @ns: namespace * @params: ptr to the structure that contains key, semflg and nsems * * Called with sem_ids.rw_mutex held (as a writer) */ static int newary(struct ipc_namespace *ns, struct ipc_params *params) { int id; int retval; struct sem_array *sma; int size; key_t key = params->key; int nsems = params->u.nsems; int semflg = params->flg; if (!nsems) return -EINVAL; if (ns->used_sems + nsems > ns->sc_semmns) return -ENOSPC; size = sizeof (*sma) + nsems * sizeof (struct sem); sma = ipc_rcu_alloc(size); if (!sma) { return -ENOMEM; } memset (sma, 0, size); sma->sem_perm.mode = (semflg & S_IRWXUGO); sma->sem_perm.key = key; sma->sem_perm.security = NULL; retval = security_sem_alloc(sma); if (retval) { ipc_rcu_putref(sma); return retval; } sma->sem_base = (struct sem *) &sma[1]; INIT_LIST_HEAD(&sma->sem_pending); INIT_LIST_HEAD(&sma->list_id); sma->sem_nsems = nsems; sma->sem_ctime = get_seconds(); id = ipc_addid(&sem_ids(ns), &sma->sem_perm, ns->sc_semmni); if (id < 0) { security_sem_free(sma); ipc_rcu_putref(sma); return id; } ns->used_sems += nsems; sem_unlock(sma); return sma->sem_perm.id; } /* * Called with sem_ids.rw_mutex and ipcp locked. */ static inline int sem_security(struct kern_ipc_perm *ipcp, int semflg) { struct sem_array *sma; sma = container_of(ipcp, struct sem_array, sem_perm); return security_sem_associate(sma, semflg); } /* * Called with sem_ids.rw_mutex and ipcp locked. */ static inline int sem_more_checks(struct kern_ipc_perm *ipcp, struct ipc_params *params) { struct sem_array *sma; sma = container_of(ipcp, struct sem_array, sem_perm); if (params->u.nsems > sma->sem_nsems) return -EINVAL; return 0; } SYSCALL_DEFINE3(semget, key_t, key, int, nsems, int, semflg) { struct ipc_namespace *ns; struct ipc_ops sem_ops; struct ipc_params sem_params; ns = current->nsproxy->ipc_ns; if (nsems < 0 || nsems > ns->sc_semmsl) return -EINVAL; sem_ops.getnew = newary; sem_ops.associate = sem_security; sem_ops.more_checks = sem_more_checks; sem_params.key = key; sem_params.flg = semflg; sem_params.u.nsems = nsems; return ipcget(ns, &sem_ids(ns), &sem_ops, &sem_params); } /* * Determine whether a sequence of semaphore operations would succeed * all at once. Return 0 if yes, 1 if need to sleep, else return error code. */ static int try_atomic_semop (struct sem_array * sma, struct sembuf * sops, int nsops, struct sem_undo *un, int pid) { int result, sem_op; struct sembuf *sop; struct sem * curr; for (sop = sops; sop < sops + nsops; sop++) { curr = sma->sem_base + sop->sem_num; sem_op = sop->sem_op; result = curr->semval; if (!sem_op && result) goto would_block; result += sem_op; if (result < 0) goto would_block; if (result > SEMVMX) goto out_of_range; if (sop->sem_flg & SEM_UNDO) { int undo = un->semadj[sop->sem_num] - sem_op; /* * Exceeding the undo range is an error. */ if (undo < (-SEMAEM - 1) || undo > SEMAEM) goto out_of_range; } curr->semval = result; } sop--; while (sop >= sops) { sma->sem_base[sop->sem_num].sempid = pid; if (sop->sem_flg & SEM_UNDO) un->semadj[sop->sem_num] -= sop->sem_op; sop--; } sma->sem_otime = get_seconds(); return 0; out_of_range: result = -ERANGE; goto undo; would_block: if (sop->sem_flg & IPC_NOWAIT) result = -EAGAIN; else result = 1; undo: sop--; while (sop >= sops) { sma->sem_base[sop->sem_num].semval -= sop->sem_op; sop--; } return result; } /* Go through the pending queue for the indicated semaphore * looking for tasks that can be completed. */ static void update_queue (struct sem_array * sma) { int error; struct sem_queue * q; q = list_entry(sma->sem_pending.next, struct sem_queue, list); while (&q->list != &sma->sem_pending) { error = try_atomic_semop(sma, q->sops, q->nsops, q->undo, q->pid); /* Does q->sleeper still need to sleep? */ if (error <= 0) { struct sem_queue *n; /* * Continue scanning. The next operation * that must be checked depends on the type of the * completed operation: * - if the operation modified the array, then * restart from the head of the queue and * check for threads that might be waiting * for semaphore values to become 0. * - if the operation didn't modify the array, * then just continue. * The order of list_del() and reading ->next * is crucial: In the former case, the list_del() * must be done first [because we might be the * first entry in ->sem_pending], in the latter * case the list_del() must be done last * [because the list is invalid after the list_del()] */ if (q->alter) { list_del(&q->list); n = list_entry(sma->sem_pending.next, struct sem_queue, list); } else { n = list_entry(q->list.next, struct sem_queue, list); list_del(&q->list); } /* wake up the waiting thread */ q->status = IN_WAKEUP; wake_up_process(q->sleeper); /* hands-off: q will disappear immediately after * writing q->status. */ smp_wmb(); q->status = error; q = n; } else { q = list_entry(q->list.next, struct sem_queue, list); } } } /* The following counts are associated to each semaphore: * semncnt number of tasks waiting on semval being nonzero * semzcnt number of tasks waiting on semval being zero * This model assumes that a task waits on exactly one semaphore. * Since semaphore operations are to be performed atomically, tasks actually * wait on a whole sequence of semaphores simultaneously. * The counts we return here are a rough approximation, but still * warrant that semncnt+semzcnt>0 if the task is on the pending queue. */ static int count_semncnt (struct sem_array * sma, ushort semnum) { int semncnt; struct sem_queue * q; semncnt = 0; list_for_each_entry(q, &sma->sem_pending, list) { struct sembuf * sops = q->sops; int nsops = q->nsops; int i; for (i = 0; i < nsops; i++) if (sops[i].sem_num == semnum && (sops[i].sem_op < 0) && !(sops[i].sem_flg & IPC_NOWAIT)) semncnt++; } return semncnt; } static int count_semzcnt (struct sem_array * sma, ushort semnum) { int semzcnt; struct sem_queue * q; semzcnt = 0; list_for_each_entry(q, &sma->sem_pending, list) { struct sembuf * sops = q->sops; int nsops = q->nsops; int i; for (i = 0; i < nsops; i++) if (sops[i].sem_num == semnum && (sops[i].sem_op == 0) && !(sops[i].sem_flg & IPC_NOWAIT)) semzcnt++; } return semzcnt; } static void free_un(struct rcu_head *head) { struct sem_undo *un = container_of(head, struct sem_undo, rcu); kfree(un); } /* Free a semaphore set. freeary() is called with sem_ids.rw_mutex locked * as a writer and the spinlock for this semaphore set hold. sem_ids.rw_mutex * remains locked on exit. */ static void freeary(struct ipc_namespace *ns, struct kern_ipc_perm *ipcp) { struct sem_undo *un, *tu; struct sem_queue *q, *tq; struct sem_array *sma = container_of(ipcp, struct sem_array, sem_perm); /* Free the existing undo structures for this semaphore set. */ assert_spin_locked(&sma->sem_perm.lock); list_for_each_entry_safe(un, tu, &sma->list_id, list_id) { list_del(&un->list_id); spin_lock(&un->ulp->lock); un->semid = -1; list_del_rcu(&un->list_proc); spin_unlock(&un->ulp->lock); call_rcu(&un->rcu, free_un); } /* Wake up all pending processes and let them fail with EIDRM. */ list_for_each_entry_safe(q, tq, &sma->sem_pending, list) { list_del(&q->list); q->status = IN_WAKEUP; wake_up_process(q->sleeper); /* doesn't sleep */ smp_wmb(); q->status = -EIDRM; /* hands-off q */ } /* Remove the semaphore set from the IDR */ sem_rmid(ns, sma); sem_unlock(sma); ns->used_sems -= sma->sem_nsems; security_sem_free(sma); ipc_rcu_putref(sma); } static unsigned long copy_semid_to_user(void __user *buf, struct semid64_ds *in, int version) { switch(version) { case IPC_64: return copy_to_user(buf, in, sizeof(*in)); case IPC_OLD: { struct semid_ds out; memset(&out, 0, sizeof(out)); ipc64_perm_to_ipc_perm(&in->sem_perm, &out.sem_perm); out.sem_otime = in->sem_otime; out.sem_ctime = in->sem_ctime; out.sem_nsems = in->sem_nsems; return copy_to_user(buf, &out, sizeof(out)); } default: return -EINVAL; } } static int semctl_nolock(struct ipc_namespace *ns, int semid, int cmd, int version, union semun arg) { int err = -EINVAL; struct sem_array *sma; switch(cmd) { case IPC_INFO: case SEM_INFO: { struct seminfo seminfo; int max_id; err = security_sem_semctl(NULL, cmd); if (err) return err; memset(&seminfo,0,sizeof(seminfo)); seminfo.semmni = ns->sc_semmni; seminfo.semmns = ns->sc_semmns; seminfo.semmsl = ns->sc_semmsl; seminfo.semopm = ns->sc_semopm; seminfo.semvmx = SEMVMX; seminfo.semmnu = SEMMNU; seminfo.semmap = SEMMAP; seminfo.semume = SEMUME; down_read(&sem_ids(ns).rw_mutex); if (cmd == SEM_INFO) { seminfo.semusz = sem_ids(ns).in_use; seminfo.semaem = ns->used_sems; } else { seminfo.semusz = SEMUSZ; seminfo.semaem = SEMAEM; } max_id = ipc_get_maxid(&sem_ids(ns)); up_read(&sem_ids(ns).rw_mutex); if (copy_to_user (arg.__buf, &seminfo, sizeof(struct seminfo))) return -EFAULT; return (max_id < 0) ? 0: max_id; } case IPC_STAT: case SEM_STAT: { struct semid64_ds tbuf; int id; if (cmd == SEM_STAT) { sma = sem_lock(ns, semid); if (IS_ERR(sma)) return PTR_ERR(sma); id = sma->sem_perm.id; } else { sma = sem_lock_check(ns, semid); if (IS_ERR(sma)) return PTR_ERR(sma); id = 0; } err = -EACCES; if (ipcperms (&sma->sem_perm, S_IRUGO)) goto out_unlock; err = security_sem_semctl(sma, cmd); if (err) goto out_unlock; memset(&tbuf, 0, sizeof(tbuf)); kernel_to_ipc64_perm(&sma->sem_perm, &tbuf.sem_perm); tbuf.sem_otime = sma->sem_otime; tbuf.sem_ctime = sma->sem_ctime; tbuf.sem_nsems = sma->sem_nsems; sem_unlock(sma); if (copy_semid_to_user (arg.buf, &tbuf, version)) return -EFAULT; return id; } default: return -EINVAL; } return err; out_unlock: sem_unlock(sma); return err; } static int semctl_main(struct ipc_namespace *ns, int semid, int semnum, int cmd, int version, union semun arg) { struct sem_array *sma; struct sem* curr; int err; ushort fast_sem_io[SEMMSL_FAST]; ushort* sem_io = fast_sem_io; int nsems; sma = sem_lock_check(ns, semid); if (IS_ERR(sma)) return PTR_ERR(sma); nsems = sma->sem_nsems; err = -EACCES; if (ipcperms (&sma->sem_perm, (cmd==SETVAL||cmd==SETALL)?S_IWUGO:S_IRUGO)) goto out_unlock; err = security_sem_semctl(sma, cmd); if (err) goto out_unlock; err = -EACCES; switch (cmd) { case GETALL: { ushort __user *array = arg.array; int i; if(nsems > SEMMSL_FAST) { sem_getref_and_unlock(sma); sem_io = ipc_alloc(sizeof(ushort)*nsems); if(sem_io == NULL) { sem_putref(sma); return -ENOMEM; } sem_lock_and_putref(sma); if (sma->sem_perm.deleted) { sem_unlock(sma); err = -EIDRM; goto out_free; } } for (i = 0; i < sma->sem_nsems; i++) sem_io[i] = sma->sem_base[i].semval; sem_unlock(sma); err = 0; if(copy_to_user(array, sem_io, nsems*sizeof(ushort))) err = -EFAULT; goto out_free; } case SETALL: { int i; struct sem_undo *un; sem_getref_and_unlock(sma); if(nsems > SEMMSL_FAST) { sem_io = ipc_alloc(sizeof(ushort)*nsems); if(sem_io == NULL) { sem_putref(sma); return -ENOMEM; } } if (copy_from_user (sem_io, arg.array, nsems*sizeof(ushort))) { sem_putref(sma); err = -EFAULT; goto out_free; } for (i = 0; i < nsems; i++) { if (sem_io[i] > SEMVMX) { sem_putref(sma); err = -ERANGE; goto out_free; } } sem_lock_and_putref(sma); if (sma->sem_perm.deleted) { sem_unlock(sma); err = -EIDRM; goto out_free; } for (i = 0; i < nsems; i++) sma->sem_base[i].semval = sem_io[i]; assert_spin_locked(&sma->sem_perm.lock); list_for_each_entry(un, &sma->list_id, list_id) { for (i = 0; i < nsems; i++) un->semadj[i] = 0; } sma->sem_ctime = get_seconds(); /* maybe some queued-up processes were waiting for this */ update_queue(sma); err = 0; goto out_unlock; } /* GETVAL, GETPID, GETNCTN, GETZCNT, SETVAL: fall-through */ } err = -EINVAL; if(semnum < 0 || semnum >= nsems) goto out_unlock; curr = &sma->sem_base[semnum]; switch (cmd) { case GETVAL: err = curr->semval; goto out_unlock; case GETPID: err = curr->sempid; goto out_unlock; case GETNCNT: err = count_semncnt(sma,semnum); goto out_unlock; case GETZCNT: err = count_semzcnt(sma,semnum); goto out_unlock; case SETVAL: { int val = arg.val; struct sem_undo *un; err = -ERANGE; if (val > SEMVMX || val < 0) goto out_unlock; assert_spin_locked(&sma->sem_perm.lock); list_for_each_entry(un, &sma->list_id, list_id) un->semadj[semnum] = 0; curr->semval = val; curr->sempid = task_tgid_vnr(current); sma->sem_ctime = get_seconds(); /* maybe some queued-up processes were waiting for this */ update_queue(sma); err = 0; goto out_unlock; } } out_unlock: sem_unlock(sma); out_free: if(sem_io != fast_sem_io) ipc_free(sem_io, sizeof(ushort)*nsems); return err; } static inline unsigned long copy_semid_from_user(struct semid64_ds *out, void __user *buf, int version) { switch(version) { case IPC_64: if (copy_from_user(out, buf, sizeof(*out))) return -EFAULT; return 0; case IPC_OLD: { struct semid_ds tbuf_old; if(copy_from_user(&tbuf_old, buf, sizeof(tbuf_old))) return -EFAULT; out->sem_perm.uid = tbuf_old.sem_perm.uid; out->sem_perm.gid = tbuf_old.sem_perm.gid; out->sem_perm.mode = tbuf_old.sem_perm.mode; return 0; } default: return -EINVAL; } } /* * This function handles some semctl commands which require the rw_mutex * to be held in write mode. * NOTE: no locks must be held, the rw_mutex is taken inside this function. */ static int semctl_down(struct ipc_namespace *ns, int semid, int cmd, int version, union semun arg) { struct sem_array *sma; int err; struct semid64_ds semid64; struct kern_ipc_perm *ipcp; if(cmd == IPC_SET) { if (copy_semid_from_user(&semid64, arg.buf, version)) return -EFAULT; } ipcp = ipcctl_pre_down(&sem_ids(ns), semid, cmd, &semid64.sem_perm, 0); if (IS_ERR(ipcp)) return PTR_ERR(ipcp); sma = container_of(ipcp, struct sem_array, sem_perm); err = security_sem_semctl(sma, cmd); if (err) goto out_unlock; switch(cmd){ case IPC_RMID: freeary(ns, ipcp); goto out_up; case IPC_SET: ipc_update_perm(&semid64.sem_perm, ipcp); sma->sem_ctime = get_seconds(); break; default: err = -EINVAL; } out_unlock: sem_unlock(sma); out_up: up_write(&sem_ids(ns).rw_mutex); return err; } SYSCALL_DEFINE(semctl)(int semid, int semnum, int cmd, union semun arg) { int err = -EINVAL; int version; struct ipc_namespace *ns; if (semid < 0) return -EINVAL; version = ipc_parse_version(&cmd); ns = current->nsproxy->ipc_ns; switch(cmd) { case IPC_INFO: case SEM_INFO: case IPC_STAT: case SEM_STAT: err = semctl_nolock(ns, semid, cmd, version, arg); return err; case GETALL: case GETVAL: case GETPID: case GETNCNT: case GETZCNT: case SETVAL: case SETALL: err = semctl_main(ns,semid,semnum,cmd,version,arg); return err; case IPC_RMID: case IPC_SET: err = semctl_down(ns, semid, cmd, version, arg); return err; default: return -EINVAL; } } #ifdef CONFIG_HAVE_SYSCALL_WRAPPERS asmlinkage long SyS_semctl(int semid, int semnum, int cmd, union semun arg) { return SYSC_semctl((int) semid, (int) semnum, (int) cmd, arg); } SYSCALL_ALIAS(sys_semctl, SyS_semctl); #endif /* If the task doesn't already have a undo_list, then allocate one * here. We guarantee there is only one thread using this undo list, * and current is THE ONE * * If this allocation and assignment succeeds, but later * portions of this code fail, there is no need to free the sem_undo_list. * Just let it stay associated with the task, and it'll be freed later * at exit time. * * This can block, so callers must hold no locks. */ static inline int get_undo_list(struct sem_undo_list **undo_listp) { struct sem_undo_list *undo_list; undo_list = current->sysvsem.undo_list; if (!undo_list) { undo_list = kzalloc(sizeof(*undo_list), GFP_KERNEL); if (undo_list == NULL) return -ENOMEM; spin_lock_init(&undo_list->lock); atomic_set(&undo_list->refcnt, 1); INIT_LIST_HEAD(&undo_list->list_proc); current->sysvsem.undo_list = undo_list; } *undo_listp = undo_list; return 0; } static struct sem_undo *lookup_undo(struct sem_undo_list *ulp, int semid) { struct sem_undo *walk; list_for_each_entry_rcu(walk, &ulp->list_proc, list_proc) { if (walk->semid == semid) return walk; } return NULL; } /** * find_alloc_undo - Lookup (and if not present create) undo array * @ns: namespace * @semid: semaphore array id * * The function looks up (and if not present creates) the undo structure. * The size of the undo structure depends on the size of the semaphore * array, thus the alloc path is not that straightforward. * Lifetime-rules: sem_undo is rcu-protected, on success, the function * performs a rcu_read_lock(). */ static struct sem_undo *find_alloc_undo(struct ipc_namespace *ns, int semid) { struct sem_array *sma; struct sem_undo_list *ulp; struct sem_undo *un, *new; int nsems; int error; error = get_undo_list(&ulp); if (error) return ERR_PTR(error); rcu_read_lock(); spin_lock(&ulp->lock); un = lookup_undo(ulp, semid); spin_unlock(&ulp->lock); if (likely(un!=NULL)) goto out; rcu_read_unlock(); /* no undo structure around - allocate one. */ /* step 1: figure out the size of the semaphore array */ sma = sem_lock_check(ns, semid); if (IS_ERR(sma)) return ERR_PTR(PTR_ERR(sma)); nsems = sma->sem_nsems; sem_getref_and_unlock(sma); /* step 2: allocate new undo structure */ new = kzalloc(sizeof(struct sem_undo) + sizeof(short)*nsems, GFP_KERNEL); if (!new) { sem_putref(sma); return ERR_PTR(-ENOMEM); } /* step 3: Acquire the lock on semaphore array */ sem_lock_and_putref(sma); if (sma->sem_perm.deleted) { sem_unlock(sma); kfree(new); un = ERR_PTR(-EIDRM); goto out; } spin_lock(&ulp->lock); /* * step 4: check for races: did someone else allocate the undo struct? */ un = lookup_undo(ulp, semid); if (un) { kfree(new); goto success; } /* step 5: initialize & link new undo structure */ new->semadj = (short *) &new[1]; new->ulp = ulp; new->semid = semid; assert_spin_locked(&ulp->lock); list_add_rcu(&new->list_proc, &ulp->list_proc); assert_spin_locked(&sma->sem_perm.lock); list_add(&new->list_id, &sma->list_id); un = new; success: spin_unlock(&ulp->lock); rcu_read_lock(); sem_unlock(sma); out: return un; } SYSCALL_DEFINE4(semtimedop, int, semid, struct sembuf __user *, tsops, unsigned, nsops, const struct timespec __user *, timeout) { int error = -EINVAL; struct sem_array *sma; struct sembuf fast_sops[SEMOPM_FAST]; struct sembuf* sops = fast_sops, *sop; struct sem_undo *un; int undos = 0, alter = 0, max; struct sem_queue queue; unsigned long jiffies_left = 0; struct ipc_namespace *ns; ns = current->nsproxy->ipc_ns; if (nsops < 1 || semid < 0) return -EINVAL; if (nsops > ns->sc_semopm) return -E2BIG; if(nsops > SEMOPM_FAST) { sops = kmalloc(sizeof(*sops)*nsops,GFP_KERNEL); if(sops==NULL) return -ENOMEM; } if (copy_from_user (sops, tsops, nsops * sizeof(*tsops))) { error=-EFAULT; goto out_free; } if (timeout) { struct timespec _timeout; if (copy_from_user(&_timeout, timeout, sizeof(*timeout))) { error = -EFAULT; goto out_free; } if (_timeout.tv_sec < 0 || _timeout.tv_nsec < 0 || _timeout.tv_nsec >= 1000000000L) { error = -EINVAL; goto out_free; } jiffies_left = timespec_to_jiffies(&_timeout); } max = 0; for (sop = sops; sop < sops + nsops; sop++) { if (sop->sem_num >= max) max = sop->sem_num; if (sop->sem_flg & SEM_UNDO) undos = 1; if (sop->sem_op != 0) alter = 1; } if (undos) { un = find_alloc_undo(ns, semid); if (IS_ERR(un)) { error = PTR_ERR(un); goto out_free; } } else un = NULL; sma = sem_lock_check(ns, semid); if (IS_ERR(sma)) { if (un) rcu_read_unlock(); error = PTR_ERR(sma); goto out_free; } /* * semid identifiers are not unique - find_alloc_undo may have * allocated an undo structure, it was invalidated by an RMID * and now a new array with received the same id. Check and fail. * This case can be detected checking un->semid. The existance of * "un" itself is guaranteed by rcu. */ error = -EIDRM; if (un) { if (un->semid == -1) { rcu_read_unlock(); goto out_unlock_free; } else { /* * rcu lock can be released, "un" cannot disappear: * - sem_lock is acquired, thus IPC_RMID is * impossible. * - exit_sem is impossible, it always operates on * current (or a dead task). */ rcu_read_unlock(); } } error = -EFBIG; if (max >= sma->sem_nsems) goto out_unlock_free; error = -EACCES; if (ipcperms(&sma->sem_perm, alter ? S_IWUGO : S_IRUGO)) goto out_unlock_free; error = security_sem_semop(sma, sops, nsops, alter); if (error) goto out_unlock_free; error = try_atomic_semop (sma, sops, nsops, un, task_tgid_vnr(current)); if (error <= 0) { if (alter && error == 0) update_queue (sma); goto out_unlock_free; } /* We need to sleep on this operation, so we put the current * task into the pending queue and go to sleep. */ queue.sops = sops; queue.nsops = nsops; queue.undo = un; queue.pid = task_tgid_vnr(current); queue.alter = alter; if (alter) list_add_tail(&queue.list, &sma->sem_pending); else list_add(&queue.list, &sma->sem_pending); queue.status = -EINTR; queue.sleeper = current; current->state = TASK_INTERRUPTIBLE; sem_unlock(sma); if (timeout) jiffies_left = schedule_timeout(jiffies_left); else schedule(); error = queue.status; while(unlikely(error == IN_WAKEUP)) { cpu_relax(); error = queue.status; } if (error != -EINTR) { /* fast path: update_queue already obtained all requested * resources */ goto out_free; } sma = sem_lock(ns, semid); if (IS_ERR(sma)) { error = -EIDRM; goto out_free; } /* * If queue.status != -EINTR we are woken up by another process */ error = queue.status; if (error != -EINTR) { goto out_unlock_free; } /* * If an interrupt occurred we have to clean up the queue */ if (timeout && jiffies_left == 0) error = -EAGAIN; list_del(&queue.list); out_unlock_free: sem_unlock(sma); out_free: if(sops != fast_sops) kfree(sops); return error; } SYSCALL_DEFINE3(semop, int, semid, struct sembuf __user *, tsops, unsigned, nsops) { return sys_semtimedop(semid, tsops, nsops, NULL); } /* If CLONE_SYSVSEM is set, establish sharing of SEM_UNDO state between * parent and child tasks. */ int copy_semundo(unsigned long clone_flags, struct task_struct *tsk) { struct sem_undo_list *undo_list; int error; if (clone_flags & CLONE_SYSVSEM) { error = get_undo_list(&undo_list); if (error) return error; atomic_inc(&undo_list->refcnt); tsk->sysvsem.undo_list = undo_list; } else tsk->sysvsem.undo_list = NULL; return 0; } /* * add semadj values to semaphores, free undo structures. * undo structures are not freed when semaphore arrays are destroyed * so some of them may be out of date. * IMPLEMENTATION NOTE: There is some confusion over whether the * set of adjustments that needs to be done should be done in an atomic * manner or not. That is, if we are attempting to decrement the semval * should we queue up and wait until we can do so legally? * The original implementation attempted to do this (queue and wait). * The current implementation does not do so. The POSIX standard * and SVID should be consulted to determine what behavior is mandated. */ void exit_sem(struct task_struct *tsk) { struct sem_undo_list *ulp; ulp = tsk->sysvsem.undo_list; if (!ulp) return; tsk->sysvsem.undo_list = NULL; if (!atomic_dec_and_test(&ulp->refcnt)) return; for (;;) { struct sem_array *sma; struct sem_undo *un; int semid; int i; rcu_read_lock(); un = list_entry_rcu(ulp->list_proc.next, struct sem_undo, list_proc); if (&un->list_proc == &ulp->list_proc) { /* * We must wait for freeary() before freeing this ulp, * in case we raced with last sem_undo. There is a small * possibility where we exit while freeary() didn't * finish unlocking sem_undo_list. */ spin_unlock_wait(&ulp->lock); rcu_read_unlock(); break; } spin_lock(&ulp->lock); semid = un->semid; spin_unlock(&ulp->lock); rcu_read_unlock(); /* exit_sem raced with IPC_RMID, nothing to do */ if (semid == -1) continue; sma = sem_lock_check(tsk->nsproxy->ipc_ns, semid); /* exit_sem raced with IPC_RMID, nothing to do */ if (IS_ERR(sma)) continue; un = lookup_undo(ulp, semid); if (un == NULL) { /* exit_sem raced with IPC_RMID+semget() that created * exactly the same semid. Nothing to do. */ sem_unlock(sma); continue; } /* remove un from the linked lists */ assert_spin_locked(&sma->sem_perm.lock); list_del(&un->list_id); spin_lock(&ulp->lock); list_del_rcu(&un->list_proc); spin_unlock(&ulp->lock); /* perform adjustments registered in un */ for (i = 0; i < sma->sem_nsems; i++) { struct sem * semaphore = &sma->sem_base[i]; if (un->semadj[i]) { semaphore->semval += un->semadj[i]; /* * Range checks of the new semaphore value, * not defined by sus: * - Some unices ignore the undo entirely * (e.g. HP UX 11i 11.22, Tru64 V5.1) * - some cap the value (e.g. FreeBSD caps * at 0, but doesn't enforce SEMVMX) * * Linux caps the semaphore value, both at 0 * and at SEMVMX. * * Manfred <manfred@colorfullife.com> */ if (semaphore->semval < 0) semaphore->semval = 0; if (semaphore->semval > SEMVMX) semaphore->semval = SEMVMX; semaphore->sempid = task_tgid_vnr(current); } } sma->sem_otime = get_seconds(); /* maybe some queued-up processes were waiting for this */ update_queue(sma); sem_unlock(sma); call_rcu(&un->rcu, free_un); } kfree(ulp); } #ifdef CONFIG_PROC_FS static int sysvipc_sem_proc_show(struct seq_file *s, void *it) { struct sem_array *sma = it; return seq_printf(s, "%10d %10d %4o %10lu %5u %5u %5u %5u %10lu %10lu\n", sma->sem_perm.key, sma->sem_perm.id, sma->sem_perm.mode, sma->sem_nsems, sma->sem_perm.uid, sma->sem_perm.gid, sma->sem_perm.cuid, sma->sem_perm.cgid, sma->sem_otime, sma->sem_ctime); } #endif
matachi/linux-2.6.32.y
ipc/sem.c
C
gpl-2.0
35,191
<?php /** * Piwik - Open source web analytics * * @link http://piwik.org * @license http://www.gnu.org/licenses/gpl-3.0.html GPL v3 or later * */ namespace Piwik\Plugins\Overlay; class Overlay extends \Piwik\Plugin { public function getInformation() { $suffix = ' Note: Requires the Transitions plugin enabled.'; $info = parent::getInformation(); $info['description'] .= ' ' . $suffix; return $info; } /** * @see Piwik\Plugin::getListHooksRegistered */ function getListHooksRegistered() { return array( 'AssetManager.getJavaScriptFiles' => 'getJsFiles', 'Translate.getClientSideTranslationKeys' => 'getClientSideTranslationKeys' ); } /** * Returns required Js Files * @param $jsFiles */ public function getJsFiles(&$jsFiles) { $jsFiles[] = 'plugins/Overlay/javascripts/rowaction.js'; $jsFiles[] = 'plugins/Overlay/javascripts/Overlay_Helper.js'; } public function getClientSideTranslationKeys(&$translationKeys) { $translationKeys[] = 'General_OverlayRowActionTooltipTitle'; $translationKeys[] = 'General_OverlayRowActionTooltip'; } }
agiza/vs-port
piwik/plugins/Overlay/Overlay.php
PHP
gpl-2.0
1,239
// -*- C++ -*- // Copyright (C) 2005-2021 Free Software Foundation, Inc. // // This file is part of the GNU ISO C++ Library. This library is free // software; you can redistribute it and/or modify it under the terms // of the GNU General Public License as published by the Free Software // Foundation; either version 3, or (at your option) any later // version. // This library is distributed in the hope that it will be useful, but // WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU // General Public License for more details. // You should have received a copy of the GNU General Public License // along with this library; see the file COPYING3. If not see // <http://www.gnu.org/licenses/>. // Copyright (C) 2004 Ami Tavory and Vladimir Dreizin, IBM-HRL. // Permission to use, copy, modify, sell, and distribute this software // is hereby granted without fee, provided that the above copyright // notice appears in all copies, and that both that copyright notice // and this permission notice appear in supporting documentation. None // of the above authors, nor IBM Haifa Research Laboratories, make any // representation about the suitability of this software for any // purpose. It is provided "as is" without express or implied // warranty. /** * @file sample_variance.hpp * Contains a function for calculating a sample variance */ #ifndef PB_DS_SAMPLE_VAR_HPP #define PB_DS_SAMPLE_VAR_HPP #include <list> #include <numeric> #include <math.h> #include <iterator> namespace __gnu_pbds { namespace test { namespace detail { #define PB_DS_VTYPE typename std::iterator_traits<It>::value_type template<typename It> PB_DS_VTYPE sample_variance(It b, It e, PB_DS_VTYPE sm) { PB_DS_VTYPE ss = 0; size_t num_res = 0; while (b != e) { const PB_DS_VTYPE d =* b - sm; ss += d* d; ++num_res; ++b; } if (num_res == 1) return 0; return ::sqrt(ss / (num_res - 1)); } #undef PB_DS_VTYPE } // namespace detail } // namespace test } // namespace __gnu_pbds #endif
Gurgel100/gcc
libstdc++-v3/testsuite/util/statistic/sample_variance.hpp
C++
gpl-2.0
2,138
.size 8000 .text@100 jp lbegin .data@143 80 .text@150 lbegin: xor a, a ldff(26), a ld a, 80 ldff(26), a ld a, 77 ldff(24), a ld a, 11 ldff(25), a ld a, 00 ldff(11), a ld a, 80 ldff(12), a ld a, c0 ldff(13), a ld a, 87 ldff(14), a ld b, 71 lwaitpos: dec b jrnz lwaitpos ld a, 80 lmodulate: xor a, 40 ldff(12), a ld b, a ld a, 80 ldff(14), a ld a, b ld b, 20 lwaitperiod: dec b jrnz lwaitperiod jr lmodulate
Ben10do/gambatte
test/hwtests/sound/ch1_duty0_pattern_pos7_dmg08_cgb04c_outaudio1.asm
Assembly
gpl-2.0
442
\hypertarget{classedu_1_1kit_1_1trufflehog_1_1model_1_1configdata_1_1_notification_view_model}{}\section{edu.\+kit.\+trufflehog.\+model.\+configdata.\+Notification\+View\+Model Class Reference} \label{classedu_1_1kit_1_1trufflehog_1_1model_1_1configdata_1_1_notification_view_model}\index{edu.\+kit.\+trufflehog.\+model.\+configdata.\+Notification\+View\+Model@{edu.\+kit.\+trufflehog.\+model.\+configdata.\+Notification\+View\+Model}} Inherits \hyperlink{classedu_1_1kit_1_1trufflehog_1_1model_1_1configdata_1_1_config_data_model}{edu.\+kit.\+trufflehog.\+model.\+configdata.\+Config\+Data\+Model}. \subsection*{Additional Inherited Members} \subsection{Detailed Description} The \hyperlink{classedu_1_1kit_1_1trufflehog_1_1model_1_1configdata_1_1_notification_view_model}{Notification\+View\+Model} contains the config data for the notification view. That means it contains the labels and any other information relevant to displaying the notification view. The notification view is where notification that occurred in Truffle\+Hog are shown. So if for example a node is suddenly marked as illegal because it was on a blacklist, this would show up in the notification view.
TruffleHogProject/TruffleHog
doc/doxygen/design_latex/classedu_1_1kit_1_1trufflehog_1_1model_1_1configdata_1_1_notification_view_model.tex
TeX
gpl-2.0
1,182
#.rst: # FindBoost # --------- # # Find Boost include dirs and libraries # # Use this module by invoking find_package with the form:: # # find_package(Boost # [version] [EXACT] # Minimum or EXACT version e.g. 1.36.0 # [REQUIRED] # Fail with error if Boost is not found # [COMPONENTS <libs>...] # Boost libraries by their canonical name # ) # e.g. "date_time" for "libboost_date_time" # # This module finds headers and requested component libraries OR a CMake # package configuration file provided by a "Boost CMake" build. For the # latter case skip to the "Boost CMake" section below. For the former # case results are reported in variables:: # # Boost_FOUND - True if headers and requested libraries were found # Boost_INCLUDE_DIRS - Boost include directories # Boost_LIBRARY_DIRS - Link directories for Boost libraries # Boost_LIBRARIES - Boost component libraries to be linked # Boost_<C>_FOUND - True if component <C> was found (<C> is upper-case) # Boost_<C>_LIBRARY - Libraries to link for component <C> (may include # target_link_libraries debug/optimized keywords) # Boost_VERSION - BOOST_VERSION value from boost/version.hpp # Boost_LIB_VERSION - Version string appended to library filenames # Boost_MAJOR_VERSION - Boost major version number (X in X.y.z) # Boost_MINOR_VERSION - Boost minor version number (Y in x.Y.z) # Boost_SUBMINOR_VERSION - Boost subminor version number (Z in x.y.Z) # Boost_LIB_DIAGNOSTIC_DEFINITIONS (Windows) # - Pass to add_definitions() to have diagnostic # information about Boost's automatic linking # displayed during compilation # # This module reads hints about search locations from variables:: # # BOOST_ROOT - Preferred installation prefix # (or BOOSTROOT) # BOOST_INCLUDEDIR - Preferred include directory e.g. <prefix>/include # BOOST_LIBRARYDIR - Preferred library directory e.g. <prefix>/lib # Boost_NO_SYSTEM_PATHS - Set to ON to disable searching in locations not # specified by these hint variables. Default is OFF. # Boost_ADDITIONAL_VERSIONS # - List of Boost versions not known to this module # (Boost install locations may contain the version) # # and saves search results persistently in CMake cache entries:: # # Boost_INCLUDE_DIR - Directory containing Boost headers # Boost_LIBRARY_DIR - Directory containing Boost libraries # Boost_<C>_LIBRARY_DEBUG - Component <C> library debug variant # Boost_<C>_LIBRARY_RELEASE - Component <C> library release variant # # Users may set these hints or results as cache entries. Projects # should not read these entries directly but instead use the above # result variables. Note that some hint names start in upper-case # "BOOST". One may specify these as environment variables if they are # not specified as CMake variables or cache entries. # # This module first searches for the Boost header files using the above # hint variables (excluding BOOST_LIBRARYDIR) and saves the result in # Boost_INCLUDE_DIR. Then it searches for requested component libraries # using the above hints (excluding BOOST_INCLUDEDIR and # Boost_ADDITIONAL_VERSIONS), "lib" directories near Boost_INCLUDE_DIR, # and the library name configuration settings below. It saves the # library directory in Boost_LIBRARY_DIR and individual library # locations in Boost_<C>_LIBRARY_DEBUG and Boost_<C>_LIBRARY_RELEASE. # When one changes settings used by previous searches in the same build # tree (excluding environment variables) this module discards previous # search results affected by the changes and searches again. # # Boost libraries come in many variants encoded in their file name. # Users or projects may tell this module which variant to find by # setting variables:: # # Boost_USE_MULTITHREADED - Set to OFF to use the non-multithreaded # libraries ('mt' tag). Default is ON. # Boost_USE_STATIC_LIBS - Set to ON to force the use of the static # libraries. Default is OFF. # Boost_USE_STATIC_RUNTIME - Set to ON or OFF to specify whether to use # libraries linked statically to the C++ runtime # ('s' tag). Default is platform dependent. # Boost_USE_DEBUG_RUNTIME - Set to ON or OFF to specify whether to use # libraries linked to the MS debug C++ runtime # ('g' tag). Default is ON. # Boost_USE_DEBUG_PYTHON - Set to ON to use libraries compiled with a # debug Python build ('y' tag). Default is OFF. # Boost_USE_STLPORT - Set to ON to use libraries compiled with # STLPort ('p' tag). Default is OFF. # Boost_USE_STLPORT_DEPRECATED_NATIVE_IOSTREAMS # - Set to ON to use libraries compiled with # STLPort deprecated "native iostreams" # ('n' tag). Default is OFF. # Boost_COMPILER - Set to the compiler-specific library suffix # (e.g. "-gcc43"). Default is auto-computed # for the C++ compiler in use. # Boost_THREADAPI - Suffix for "thread" component library name, # such as "pthread" or "win32". Names with # and without this suffix will both be tried. # Boost_NAMESPACE - Alternate namespace used to build boost with # e.g. if set to "myboost", will search for # myboost_thread instead of boost_thread. # # Other variables one may set to control this module are:: # # Boost_DEBUG - Set to ON to enable debug output from FindBoost. # Please enable this before filing any bug report. # Boost_DETAILED_FAILURE_MSG # - Set to ON to add detailed information to the # failure message even when the REQUIRED option # is not given to the find_package call. # Boost_REALPATH - Set to ON to resolve symlinks for discovered # libraries to assist with packaging. For example, # the "system" component library may be resolved to # "/usr/lib/libboost_system.so.1.42.0" instead of # "/usr/lib/libboost_system.so". This does not # affect linking and should not be enabled unless # the user needs this information. # # On Visual Studio and Borland compilers Boost headers request automatic # linking to corresponding libraries. This requires matching libraries # to be linked explicitly or available in the link library search path. # In this case setting Boost_USE_STATIC_LIBS to OFF may not achieve # dynamic linking. Boost automatic linking typically requests static # libraries with a few exceptions (such as Boost.Python). Use:: # # add_definitions(${Boost_LIB_DIAGNOSTIC_DEFINITIONS}) # # to ask Boost to report information about automatic linking requests. # # Example to find Boost headers only:: # # find_package(Boost 1.36.0) # if(Boost_FOUND) # include_directories(${Boost_INCLUDE_DIRS}) # add_executable(foo foo.cc) # endif() # # Example to find Boost headers and some *static* libraries:: # # set(Boost_USE_STATIC_LIBS ON) # only find static libs # set(Boost_USE_MULTITHREADED ON) # set(Boost_USE_STATIC_RUNTIME OFF) # find_package(Boost 1.36.0 COMPONENTS date_time filesystem system ...) # if(Boost_FOUND) # include_directories(${Boost_INCLUDE_DIRS}) # add_executable(foo foo.cc) # target_link_libraries(foo ${Boost_LIBRARIES}) # endif() # # Boost CMake # ^^^^^^^^^^^ # # If Boost was built using the boost-cmake project it provides a package # configuration file for use with find_package's Config mode. This # module looks for the package configuration file called # BoostConfig.cmake or boost-config.cmake and stores the result in cache # entry "Boost_DIR". If found, the package configuration file is loaded # and this module returns with no further action. See documentation of # the Boost CMake package configuration for details on what it provides. # # Set Boost_NO_BOOST_CMAKE to ON to disable the search for boost-cmake. #============================================================================= # Copyright 2006-2012 Kitware, Inc. # Copyright 2006-2008 Andreas Schneider <mail@cynapses.org> # Copyright 2007 Wengo # Copyright 2007 Mike Jackson # Copyright 2008 Andreas Pakulat <apaku@gmx.de> # Copyright 2008-2012 Philip Lowman <philip@yhbt.com> # # Distributed under the OSI-approved BSD License (the "License"); # see accompanying file Copyright.txt for details. # # This software is distributed WITHOUT ANY WARRANTY; without even the # implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. # See the License for more information. #============================================================================= # (To distribute this file outside of CMake, substitute the full # License text for the above reference.) #------------------------------------------------------------------------------- # Before we go searching, check whether boost-cmake is available, unless the # user specifically asked NOT to search for boost-cmake. # # If Boost_DIR is set, this behaves as any find_package call would. If not, # it looks at BOOST_ROOT and BOOSTROOT to find Boost. # if (NOT Boost_NO_BOOST_CMAKE) # If Boost_DIR is not set, look for BOOSTROOT and BOOST_ROOT as alternatives, # since these are more conventional for Boost. if ("$ENV{Boost_DIR}" STREQUAL "") if (NOT "$ENV{BOOST_ROOT}" STREQUAL "") set(ENV{Boost_DIR} $ENV{BOOST_ROOT}) elseif (NOT "$ENV{BOOSTROOT}" STREQUAL "") set(ENV{Boost_DIR} $ENV{BOOSTROOT}) endif() endif() # Do the same find_package call but look specifically for the CMake version. # Note that args are passed in the Boost_FIND_xxxxx variables, so there is no # need to delegate them to this find_package call. find_package(Boost QUIET NO_MODULE) mark_as_advanced(Boost_DIR) # If we found boost-cmake, then we're done. Print out what we found. # Otherwise let the rest of the module try to find it. if (Boost_FOUND) message("Boost ${Boost_FIND_VERSION} found.") if (Boost_FIND_COMPONENTS) message("Found Boost components:") message(" ${Boost_FIND_COMPONENTS}") endif() return() endif() endif() #------------------------------------------------------------------------------- # FindBoost functions & macros # ############################################ # # Check the existence of the libraries. # ############################################ # This macro was taken directly from the FindQt4.cmake file that is included # with the CMake distribution. This is NOT my work. All work was done by the # original authors of the FindQt4.cmake file. Only minor modifications were # made to remove references to Qt and make this file more generally applicable # And ELSE/ENDIF pairs were removed for readability. ######################################################################### macro(_Boost_ADJUST_LIB_VARS basename) if(Boost_INCLUDE_DIR ) if(Boost_${basename}_LIBRARY_DEBUG AND Boost_${basename}_LIBRARY_RELEASE) # if the generator supports configuration types then set # optimized and debug libraries, or if the CMAKE_BUILD_TYPE has a value if(CMAKE_CONFIGURATION_TYPES OR CMAKE_BUILD_TYPE) set(Boost_${basename}_LIBRARY optimized ${Boost_${basename}_LIBRARY_RELEASE} debug ${Boost_${basename}_LIBRARY_DEBUG}) else() # if there are no configuration types and CMAKE_BUILD_TYPE has no value # then just use the release libraries set(Boost_${basename}_LIBRARY ${Boost_${basename}_LIBRARY_RELEASE} ) endif() # FIXME: This probably should be set for both cases set(Boost_${basename}_LIBRARIES optimized ${Boost_${basename}_LIBRARY_RELEASE} debug ${Boost_${basename}_LIBRARY_DEBUG}) endif() # if only the release version was found, set the debug variable also to the release version if(Boost_${basename}_LIBRARY_RELEASE AND NOT Boost_${basename}_LIBRARY_DEBUG) set(Boost_${basename}_LIBRARY_DEBUG ${Boost_${basename}_LIBRARY_RELEASE}) set(Boost_${basename}_LIBRARY ${Boost_${basename}_LIBRARY_RELEASE}) set(Boost_${basename}_LIBRARIES ${Boost_${basename}_LIBRARY_RELEASE}) endif() # if only the debug version was found, set the release variable also to the debug version if(Boost_${basename}_LIBRARY_DEBUG AND NOT Boost_${basename}_LIBRARY_RELEASE) set(Boost_${basename}_LIBRARY_RELEASE ${Boost_${basename}_LIBRARY_DEBUG}) set(Boost_${basename}_LIBRARY ${Boost_${basename}_LIBRARY_DEBUG}) set(Boost_${basename}_LIBRARIES ${Boost_${basename}_LIBRARY_DEBUG}) endif() # If the debug & release library ends up being the same, omit the keywords if(${Boost_${basename}_LIBRARY_RELEASE} STREQUAL ${Boost_${basename}_LIBRARY_DEBUG}) set(Boost_${basename}_LIBRARY ${Boost_${basename}_LIBRARY_RELEASE} ) set(Boost_${basename}_LIBRARIES ${Boost_${basename}_LIBRARY_RELEASE} ) endif() if(Boost_${basename}_LIBRARY) set(Boost_${basename}_FOUND ON) endif() endif() # Make variables changeable to the advanced user mark_as_advanced( Boost_${basename}_LIBRARY_RELEASE Boost_${basename}_LIBRARY_DEBUG ) endmacro() macro(_Boost_CHANGE_DETECT changed_var) set(${changed_var} 0) foreach(v ${ARGN}) if(DEFINED _Boost_COMPONENTS_SEARCHED) if(${v}) if(_${v}_LAST) string(COMPARE NOTEQUAL "${${v}}" "${_${v}_LAST}" _${v}_CHANGED) else() set(_${v}_CHANGED 1) endif() elseif(_${v}_LAST) set(_${v}_CHANGED 1) endif() if(_${v}_CHANGED) set(${changed_var} 1) endif() else() set(_${v}_CHANGED 0) endif() endforeach() endmacro() macro(_Boost_FIND_LIBRARY var) find_library(${var} ${ARGN}) if(${var}) # If this is the first library found then save Boost_LIBRARY_DIR. if(NOT Boost_LIBRARY_DIR) get_filename_component(_dir "${${var}}" PATH) set(Boost_LIBRARY_DIR "${_dir}" CACHE PATH "Boost library directory" FORCE) endif() elseif(_Boost_FIND_LIBRARY_HINTS_FOR_COMPONENT) # Try component-specific hints but do not save Boost_LIBRARY_DIR. find_library(${var} HINTS ${_Boost_FIND_LIBRARY_HINTS_FOR_COMPONENT} ${ARGN}) endif() # If Boost_LIBRARY_DIR is known then search only there. if(Boost_LIBRARY_DIR) set(_boost_LIBRARY_SEARCH_DIRS ${Boost_LIBRARY_DIR} NO_DEFAULT_PATH NO_CMAKE_FIND_ROOT_PATH) endif() endmacro() #------------------------------------------------------------------------------- # # Runs compiler with "-dumpversion" and parses major/minor # version with a regex. # function(_Boost_COMPILER_DUMPVERSION _OUTPUT_VERSION) exec_program(${CMAKE_CXX_COMPILER} ARGS ${CMAKE_CXX_COMPILER_ARG1} -dumpversion OUTPUT_VARIABLE _boost_COMPILER_VERSION ) string(REGEX REPLACE "([0-9])\\.([0-9])(\\.[0-9])?" "\\1\\2" _boost_COMPILER_VERSION ${_boost_COMPILER_VERSION}) set(${_OUTPUT_VERSION} ${_boost_COMPILER_VERSION} PARENT_SCOPE) endfunction() # # Take a list of libraries with "thread" in it # and prepend duplicates with "thread_${Boost_THREADAPI}" # at the front of the list # function(_Boost_PREPEND_LIST_WITH_THREADAPI _output) set(_orig_libnames ${ARGN}) string(REPLACE "thread" "thread_${Boost_THREADAPI}" _threadapi_libnames "${_orig_libnames}") set(${_output} ${_threadapi_libnames} ${_orig_libnames} PARENT_SCOPE) endfunction() # # If a library is found, replace its cache entry with its REALPATH # function(_Boost_SWAP_WITH_REALPATH _library _docstring) if(${_library}) get_filename_component(_boost_filepathreal ${${_library}} REALPATH) unset(${_library} CACHE) set(${_library} ${_boost_filepathreal} CACHE FILEPATH "${_docstring}") endif() endfunction() function(_Boost_CHECK_SPELLING _var) if(${_var}) string(TOUPPER ${_var} _var_UC) message(FATAL_ERROR "ERROR: ${_var} is not the correct spelling. The proper spelling is ${_var_UC}.") endif() endfunction() # Guesses Boost's compiler prefix used in built library names # Returns the guess by setting the variable pointed to by _ret function(_Boost_GUESS_COMPILER_PREFIX _ret) if(CMAKE_CXX_COMPILER_ID STREQUAL "Intel" OR CMAKE_CXX_COMPILER MATCHES "icl" OR CMAKE_CXX_COMPILER MATCHES "icpc") if(WIN32) set (_boost_COMPILER "-iw") else() set (_boost_COMPILER "-il") endif() elseif("x${CMAKE_CXX_COMPILER_ID}" STREQUAL "xMSVC") if (NOT CMAKE_CXX_COMPILER_VERSION VERSION_LESS 19.10) set(_boost_COMPILER "-vc141;-vc140") elseif (NOT CMAKE_CXX_COMPILER_VERSION VERSION_LESS 19) set(_boost_COMPILER "-vc140") elseif(NOT CMAKE_CXX_COMPILER_VERSION VERSION_LESS 18) set(_boost_COMPILER "-vc120") elseif(NOT CMAKE_CXX_COMPILER_VERSION VERSION_LESS 17) set(_boost_COMPILER "-vc110") elseif(NOT CMAKE_CXX_COMPILER_VERSION VERSION_LESS 16) set(_boost_COMPILER "-vc100") elseif(NOT CMAKE_CXX_COMPILER_VERSION VERSION_LESS 15) set(_boost_COMPILER "-vc90") elseif(NOT CMAKE_CXX_COMPILER_VERSION VERSION_LESS 14) set(_boost_COMPILER "-vc80") elseif(NOT CMAKE_CXX_COMPILER_VERSION VERSION_LESS 13.10) set(_boost_COMPILER "-vc71") elseif(NOT CMAKE_CXX_COMPILER_VERSION VERSION_LESS 13) # Good luck! set(_boost_COMPILER "-vc7") # yes, this is correct else() # VS 6.0 Good luck! set(_boost_COMPILER "-vc6") # yes, this is correct endif() elseif (BORLAND) set(_boost_COMPILER "-bcb") elseif(CMAKE_CXX_COMPILER_ID STREQUAL "SunPro") set(_boost_COMPILER "-sw") elseif (MINGW) if(${Boost_MAJOR_VERSION}.${Boost_MINOR_VERSION} VERSION_LESS 1.34) set(_boost_COMPILER "-mgw") # no GCC version encoding prior to 1.34 else() _Boost_COMPILER_DUMPVERSION(_boost_COMPILER_VERSION) set(_boost_COMPILER "-mgw${_boost_COMPILER_VERSION}") endif() elseif (UNIX) if (CMAKE_COMPILER_IS_GNUCXX) if(${Boost_MAJOR_VERSION}.${Boost_MINOR_VERSION} VERSION_LESS 1.34) set(_boost_COMPILER "-gcc") # no GCC version encoding prior to 1.34 else() _Boost_COMPILER_DUMPVERSION(_boost_COMPILER_VERSION) # Determine which version of GCC we have. if(APPLE) if(Boost_MINOR_VERSION) if(${Boost_MINOR_VERSION} GREATER 35) # In Boost 1.36.0 and newer, the mangled compiler name used # on Mac OS X/Darwin is "xgcc". set(_boost_COMPILER "-xgcc${_boost_COMPILER_VERSION}") else() # In Boost <= 1.35.0, there is no mangled compiler name for # the Mac OS X/Darwin version of GCC. set(_boost_COMPILER "") endif() else() # We don't know the Boost version, so assume it's # pre-1.36.0. set(_boost_COMPILER "") endif() else() set(_boost_COMPILER "-gcc${_boost_COMPILER_VERSION}") endif() endif() endif () else() # TODO at least Boost_DEBUG here? set(_boost_COMPILER "") endif() set(${_ret} ${_boost_COMPILER} PARENT_SCOPE) endfunction() # # End functions/macros # #------------------------------------------------------------------------------- #------------------------------------------------------------------------------- # main. #------------------------------------------------------------------------------- if(NOT DEFINED Boost_USE_MULTITHREADED) set(Boost_USE_MULTITHREADED TRUE) endif() if(NOT DEFINED Boost_USE_DEBUG_RUNTIME) set(Boost_USE_DEBUG_RUNTIME TRUE) endif() # Check the version of Boost against the requested version. if(Boost_FIND_VERSION AND NOT Boost_FIND_VERSION_MINOR) message(SEND_ERROR "When requesting a specific version of Boost, you must provide at least the major and minor version numbers, e.g., 1.34") endif() if(Boost_FIND_VERSION_EXACT) # The version may appear in a directory with or without the patch # level, even when the patch level is non-zero. set(_boost_TEST_VERSIONS "${Boost_FIND_VERSION_MAJOR}.${Boost_FIND_VERSION_MINOR}.${Boost_FIND_VERSION_PATCH}" "${Boost_FIND_VERSION_MAJOR}.${Boost_FIND_VERSION_MINOR}") else() # The user has not requested an exact version. Among known # versions, find those that are acceptable to the user request. set(_Boost_KNOWN_VERSIONS ${Boost_ADDITIONAL_VERSIONS} "1.65.1" "1.65.0" "1.65" "1.64.0" "1.64" "1.63.0" "1.63" "1.62.0" "1.62" "1.61.0" "1.61" "1.60.0" "1.60" "1.59.0" "1.59" "1.58.0" "1.58" "1.57.0" "1.57" "1.56.0" "1.56" "1.55.0" "1.55" "1.54.0" "1.54" "1.53.0" "1.53" "1.52.0" "1.52" "1.51.0" "1.51" "1.50.0" "1.50" "1.49.0" "1.49" "1.48.0" "1.48" "1.47.0" "1.47" "1.46.1" "1.46.0" "1.46" "1.45.0" "1.45" "1.44.0" "1.44" "1.43.0" "1.43" "1.42.0" "1.42" "1.41.0" "1.41" "1.40.0" "1.40" "1.39.0" "1.39" "1.38.0" "1.38" "1.37.0" "1.37" "1.36.1" "1.36.0" "1.36" "1.35.1" "1.35.0" "1.35" "1.34.1" "1.34.0" "1.34" "1.33.1" "1.33.0" "1.33") set(_boost_TEST_VERSIONS) if(Boost_FIND_VERSION) set(_Boost_FIND_VERSION_SHORT "${Boost_FIND_VERSION_MAJOR}.${Boost_FIND_VERSION_MINOR}") # Select acceptable versions. foreach(version ${_Boost_KNOWN_VERSIONS}) if(NOT "${version}" VERSION_LESS "${Boost_FIND_VERSION}") # This version is high enough. list(APPEND _boost_TEST_VERSIONS "${version}") elseif("${version}.99" VERSION_EQUAL "${_Boost_FIND_VERSION_SHORT}.99") # This version is a short-form for the requested version with # the patch level dropped. list(APPEND _boost_TEST_VERSIONS "${version}") endif() endforeach() else() # Any version is acceptable. set(_boost_TEST_VERSIONS "${_Boost_KNOWN_VERSIONS}") endif() endif() # The reason that we failed to find Boost. This will be set to a # user-friendly message when we fail to find some necessary piece of # Boost. set(Boost_ERROR_REASON) if(Boost_DEBUG) # Output some of their choices message(STATUS "[ ${CMAKE_CURRENT_LIST_FILE}:${CMAKE_CURRENT_LIST_LINE} ] " "_boost_TEST_VERSIONS = ${_boost_TEST_VERSIONS}") message(STATUS "[ ${CMAKE_CURRENT_LIST_FILE}:${CMAKE_CURRENT_LIST_LINE} ] " "Boost_USE_MULTITHREADED = ${Boost_USE_MULTITHREADED}") message(STATUS "[ ${CMAKE_CURRENT_LIST_FILE}:${CMAKE_CURRENT_LIST_LINE} ] " "Boost_USE_STATIC_LIBS = ${Boost_USE_STATIC_LIBS}") message(STATUS "[ ${CMAKE_CURRENT_LIST_FILE}:${CMAKE_CURRENT_LIST_LINE} ] " "Boost_USE_STATIC_RUNTIME = ${Boost_USE_STATIC_RUNTIME}") message(STATUS "[ ${CMAKE_CURRENT_LIST_FILE}:${CMAKE_CURRENT_LIST_LINE} ] " "Boost_ADDITIONAL_VERSIONS = ${Boost_ADDITIONAL_VERSIONS}") message(STATUS "[ ${CMAKE_CURRENT_LIST_FILE}:${CMAKE_CURRENT_LIST_LINE} ] " "Boost_NO_SYSTEM_PATHS = ${Boost_NO_SYSTEM_PATHS}") endif() if(WIN32) # In windows, automatic linking is performed, so you do not have # to specify the libraries. If you are linking to a dynamic # runtime, then you can choose to link to either a static or a # dynamic Boost library, the default is to do a static link. You # can alter this for a specific library "whatever" by defining # BOOST_WHATEVER_DYN_LINK to force Boost library "whatever" to be # linked dynamically. Alternatively you can force all Boost # libraries to dynamic link by defining BOOST_ALL_DYN_LINK. # This feature can be disabled for Boost library "whatever" by # defining BOOST_WHATEVER_NO_LIB, or for all of Boost by defining # BOOST_ALL_NO_LIB. # If you want to observe which libraries are being linked against # then defining BOOST_LIB_DIAGNOSTIC will cause the auto-linking # code to emit a #pragma message each time a library is selected # for linking. set(Boost_LIB_DIAGNOSTIC_DEFINITIONS "-DBOOST_LIB_DIAGNOSTIC") endif() _Boost_CHECK_SPELLING(Boost_ROOT) _Boost_CHECK_SPELLING(Boost_LIBRARYDIR) _Boost_CHECK_SPELLING(Boost_INCLUDEDIR) # Collect environment variable inputs as hints. Do not consider changes. foreach(v BOOSTROOT BOOST_ROOT BOOST_INCLUDEDIR BOOST_LIBRARYDIR) set(_env $ENV{${v}}) if(_env) file(TO_CMAKE_PATH "${_env}" _ENV_${v}) else() set(_ENV_${v} "") endif() endforeach() if(NOT _ENV_BOOST_ROOT AND _ENV_BOOSTROOT) set(_ENV_BOOST_ROOT "${_ENV_BOOSTROOT}") endif() # Collect inputs and cached results. Detect changes since the last run. if(NOT BOOST_ROOT AND BOOSTROOT) set(BOOST_ROOT "${BOOSTROOT}") endif() set(_Boost_VARS_DIR BOOST_ROOT Boost_NO_SYSTEM_PATHS ) if(Boost_DEBUG) message(STATUS "[ ${CMAKE_CURRENT_LIST_FILE}:${CMAKE_CURRENT_LIST_LINE} ] " "Declared as CMake or Environmental Variables:") message(STATUS "[ ${CMAKE_CURRENT_LIST_FILE}:${CMAKE_CURRENT_LIST_LINE} ] " " BOOST_ROOT = ${BOOST_ROOT}") message(STATUS "[ ${CMAKE_CURRENT_LIST_FILE}:${CMAKE_CURRENT_LIST_LINE} ] " " BOOST_INCLUDEDIR = ${BOOST_INCLUDEDIR}") message(STATUS "[ ${CMAKE_CURRENT_LIST_FILE}:${CMAKE_CURRENT_LIST_LINE} ] " " BOOST_LIBRARYDIR = ${BOOST_LIBRARYDIR}") message(STATUS "[ ${CMAKE_CURRENT_LIST_FILE}:${CMAKE_CURRENT_LIST_LINE} ] " "_boost_TEST_VERSIONS = ${_boost_TEST_VERSIONS}") endif() # ------------------------------------------------------------------------ # Search for Boost include DIR # ------------------------------------------------------------------------ set(_Boost_VARS_INC BOOST_INCLUDEDIR Boost_INCLUDE_DIR Boost_ADDITIONAL_VERSIONS) _Boost_CHANGE_DETECT(_Boost_CHANGE_INCDIR ${_Boost_VARS_DIR} ${_Boost_VARS_INC}) # Clear Boost_INCLUDE_DIR if it did not change but other input affecting the # location did. We will find a new one based on the new inputs. if(_Boost_CHANGE_INCDIR AND NOT _Boost_INCLUDE_DIR_CHANGED) unset(Boost_INCLUDE_DIR CACHE) endif() if(NOT Boost_INCLUDE_DIR) set(_boost_INCLUDE_SEARCH_DIRS "") if(BOOST_INCLUDEDIR) list(APPEND _boost_INCLUDE_SEARCH_DIRS ${BOOST_INCLUDEDIR}) elseif(_ENV_BOOST_INCLUDEDIR) list(APPEND _boost_INCLUDE_SEARCH_DIRS ${_ENV_BOOST_INCLUDEDIR}) endif() if( BOOST_ROOT ) list(APPEND _boost_INCLUDE_SEARCH_DIRS ${BOOST_ROOT}/include ${BOOST_ROOT}) elseif( _ENV_BOOST_ROOT ) list(APPEND _boost_INCLUDE_SEARCH_DIRS ${_ENV_BOOST_ROOT}/include ${_ENV_BOOST_ROOT}) endif() if( Boost_NO_SYSTEM_PATHS) list(APPEND _boost_INCLUDE_SEARCH_DIRS NO_CMAKE_SYSTEM_PATH) else() list(APPEND _boost_INCLUDE_SEARCH_DIRS PATHS C:/boost/include C:/boost /sw/local/include /usr/local/include/boost /usr/include/boost ) endif() # Try to find Boost by stepping backwards through the Boost versions # we know about. # Build a list of path suffixes for each version. set(_boost_PATH_SUFFIXES) foreach(_boost_VER ${_boost_TEST_VERSIONS}) # Add in a path suffix, based on the required version, ideally # we could read this from version.hpp, but for that to work we'd # need to know the include dir already set(_boost_BOOSTIFIED_VERSION) # Transform 1.35 => 1_35 and 1.36.0 => 1_36_0 if(_boost_VER MATCHES "([0-9]+)\\.([0-9]+)\\.([0-9]+)") set(_boost_BOOSTIFIED_VERSION "${CMAKE_MATCH_1}_${CMAKE_MATCH_2}_${CMAKE_MATCH_3}") elseif(_boost_VER MATCHES "([0-9]+)\\.([0-9]+)") set(_boost_BOOSTIFIED_VERSION "${CMAKE_MATCH_1}_${CMAKE_MATCH_2}") endif() list(APPEND _boost_PATH_SUFFIXES "boost-${_boost_BOOSTIFIED_VERSION}" "boost_${_boost_BOOSTIFIED_VERSION}" "boost/boost-${_boost_BOOSTIFIED_VERSION}" "boost/boost_${_boost_BOOSTIFIED_VERSION}" ) endforeach() if(Boost_DEBUG) message(STATUS "[ ${CMAKE_CURRENT_LIST_FILE}:${CMAKE_CURRENT_LIST_LINE} ] " "Include debugging info:") message(STATUS "[ ${CMAKE_CURRENT_LIST_FILE}:${CMAKE_CURRENT_LIST_LINE} ] " " _boost_INCLUDE_SEARCH_DIRS = ${_boost_INCLUDE_SEARCH_DIRS}") message(STATUS "[ ${CMAKE_CURRENT_LIST_FILE}:${CMAKE_CURRENT_LIST_LINE} ] " " _boost_PATH_SUFFIXES = ${_boost_PATH_SUFFIXES}") endif() # Look for a standard boost header file. find_path(Boost_INCLUDE_DIR NAMES boost/config.hpp HINTS ${_boost_INCLUDE_SEARCH_DIRS} PATH_SUFFIXES ${_boost_PATH_SUFFIXES} ) endif() # ------------------------------------------------------------------------ # Extract version information from version.hpp # ------------------------------------------------------------------------ # Set Boost_FOUND based only on header location and version. # It will be updated below for component libraries. if(Boost_INCLUDE_DIR) if(Boost_DEBUG) message(STATUS "[ ${CMAKE_CURRENT_LIST_FILE}:${CMAKE_CURRENT_LIST_LINE} ] " "location of version.hpp: ${Boost_INCLUDE_DIR}/boost/version.hpp") endif() # Extract Boost_VERSION and Boost_LIB_VERSION from version.hpp set(Boost_VERSION 0) set(Boost_LIB_VERSION "") file(STRINGS "${Boost_INCLUDE_DIR}/boost/version.hpp" _boost_VERSION_HPP_CONTENTS REGEX "#define BOOST_(LIB_)?VERSION ") set(_Boost_VERSION_REGEX "([0-9]+)") set(_Boost_LIB_VERSION_REGEX "\"([0-9_]+)\"") foreach(v VERSION LIB_VERSION) if("${_boost_VERSION_HPP_CONTENTS}" MATCHES "#define BOOST_${v} ${_Boost_${v}_REGEX}") set(Boost_${v} "${CMAKE_MATCH_1}") endif() endforeach() unset(_boost_VERSION_HPP_CONTENTS) math(EXPR Boost_MAJOR_VERSION "${Boost_VERSION} / 100000") math(EXPR Boost_MINOR_VERSION "${Boost_VERSION} / 100 % 1000") math(EXPR Boost_SUBMINOR_VERSION "${Boost_VERSION} % 100") set(Boost_ERROR_REASON "${Boost_ERROR_REASON}Boost version: ${Boost_MAJOR_VERSION}.${Boost_MINOR_VERSION}.${Boost_SUBMINOR_VERSION}\nBoost include path: ${Boost_INCLUDE_DIR}") if(Boost_DEBUG) message(STATUS "[ ${CMAKE_CURRENT_LIST_FILE}:${CMAKE_CURRENT_LIST_LINE} ] " "version.hpp reveals boost " "${Boost_MAJOR_VERSION}.${Boost_MINOR_VERSION}.${Boost_SUBMINOR_VERSION}") endif() if(Boost_FIND_VERSION) # Set Boost_FOUND based on requested version. set(_Boost_VERSION "${Boost_MAJOR_VERSION}.${Boost_MINOR_VERSION}.${Boost_SUBMINOR_VERSION}") if("${_Boost_VERSION}" VERSION_LESS "${Boost_FIND_VERSION}") set(Boost_FOUND 0) set(_Boost_VERSION_AGE "old") elseif(Boost_FIND_VERSION_EXACT AND NOT "${_Boost_VERSION}" VERSION_EQUAL "${Boost_FIND_VERSION}") set(Boost_FOUND 0) set(_Boost_VERSION_AGE "new") else() set(Boost_FOUND 1) endif() if(NOT Boost_FOUND) # State that we found a version of Boost that is too new or too old. set(Boost_ERROR_REASON "${Boost_ERROR_REASON}\nDetected version of Boost is too ${_Boost_VERSION_AGE}. Requested version was ${Boost_FIND_VERSION_MAJOR}.${Boost_FIND_VERSION_MINOR}") if (Boost_FIND_VERSION_PATCH) set(Boost_ERROR_REASON "${Boost_ERROR_REASON}.${Boost_FIND_VERSION_PATCH}") endif () if (NOT Boost_FIND_VERSION_EXACT) set(Boost_ERROR_REASON "${Boost_ERROR_REASON} (or newer)") endif () set(Boost_ERROR_REASON "${Boost_ERROR_REASON}.") endif () else() # Caller will accept any Boost version. set(Boost_FOUND 1) endif() else() set(Boost_FOUND 0) set(Boost_ERROR_REASON "${Boost_ERROR_REASON}Unable to find the Boost header files. Please set BOOST_ROOT to the root directory containing Boost or BOOST_INCLUDEDIR to the directory containing Boost's headers.") endif() # ------------------------------------------------------------------------ # Prefix initialization # ------------------------------------------------------------------------ set(Boost_LIB_PREFIX "") if ( WIN32 AND Boost_USE_STATIC_LIBS AND NOT CYGWIN) set(Boost_LIB_PREFIX "lib") endif() if ( NOT Boost_NAMESPACE ) set(Boost_NAMESPACE "boost") endif() # ------------------------------------------------------------------------ # Suffix initialization and compiler suffix detection. # ------------------------------------------------------------------------ set(_Boost_VARS_NAME Boost_NAMESPACE Boost_COMPILER Boost_THREADAPI Boost_USE_DEBUG_PYTHON Boost_USE_MULTITHREADED Boost_USE_STATIC_LIBS Boost_USE_STATIC_RUNTIME Boost_USE_STLPORT Boost_USE_STLPORT_DEPRECATED_NATIVE_IOSTREAMS ) _Boost_CHANGE_DETECT(_Boost_CHANGE_LIBNAME ${_Boost_VARS_NAME}) # Setting some more suffixes for the library if (Boost_COMPILER) set(_boost_COMPILER ${Boost_COMPILER}) if(Boost_DEBUG) message(STATUS "[ ${CMAKE_CURRENT_LIST_FILE}:${CMAKE_CURRENT_LIST_LINE} ] " "using user-specified Boost_COMPILER = ${_boost_COMPILER}") endif() else() # Attempt to guess the compiler suffix # NOTE: this is not perfect yet, if you experience any issues # please report them and use the Boost_COMPILER variable # to work around the problems. _Boost_GUESS_COMPILER_PREFIX(_boost_COMPILER) if(Boost_DEBUG) message(STATUS "[ ${CMAKE_CURRENT_LIST_FILE}:${CMAKE_CURRENT_LIST_LINE} ] " "guessed _boost_COMPILER = ${_boost_COMPILER}") endif() endif() set (_boost_MULTITHREADED "-mt") if( NOT Boost_USE_MULTITHREADED ) set (_boost_MULTITHREADED "") endif() if(Boost_DEBUG) message(STATUS "[ ${CMAKE_CURRENT_LIST_FILE}:${CMAKE_CURRENT_LIST_LINE} ] " "_boost_MULTITHREADED = ${_boost_MULTITHREADED}") endif() #====================== # Systematically build up the Boost ABI tag # http://boost.org/doc/libs/1_41_0/more/getting_started/windows.html#library-naming set( _boost_RELEASE_ABI_TAG "-") set( _boost_DEBUG_ABI_TAG "-") # Key Use this library when: # s linking statically to the C++ standard library and # compiler runtime support libraries. if(Boost_USE_STATIC_RUNTIME) set( _boost_RELEASE_ABI_TAG "${_boost_RELEASE_ABI_TAG}s") set( _boost_DEBUG_ABI_TAG "${_boost_DEBUG_ABI_TAG}s") endif() # g using debug versions of the standard and runtime # support libraries if(WIN32 AND Boost_USE_DEBUG_RUNTIME) if(MSVC OR "${CMAKE_CXX_COMPILER}" MATCHES "icl" OR "${CMAKE_CXX_COMPILER}" MATCHES "icpc") set(_boost_DEBUG_ABI_TAG "${_boost_DEBUG_ABI_TAG}g") endif() endif() # y using special debug build of python if(Boost_USE_DEBUG_PYTHON) set(_boost_DEBUG_ABI_TAG "${_boost_DEBUG_ABI_TAG}y") endif() # d using a debug version of your code set(_boost_DEBUG_ABI_TAG "${_boost_DEBUG_ABI_TAG}d") # p using the STLport standard library rather than the # default one supplied with your compiler if(Boost_USE_STLPORT) set( _boost_RELEASE_ABI_TAG "${_boost_RELEASE_ABI_TAG}p") set( _boost_DEBUG_ABI_TAG "${_boost_DEBUG_ABI_TAG}p") endif() # n using the STLport deprecated "native iostreams" feature if(Boost_USE_STLPORT_DEPRECATED_NATIVE_IOSTREAMS) set( _boost_RELEASE_ABI_TAG "${_boost_RELEASE_ABI_TAG}n") set( _boost_DEBUG_ABI_TAG "${_boost_DEBUG_ABI_TAG}n") endif() if(Boost_DEBUG) message(STATUS "[ ${CMAKE_CURRENT_LIST_FILE}:${CMAKE_CURRENT_LIST_LINE} ] " "_boost_RELEASE_ABI_TAG = ${_boost_RELEASE_ABI_TAG}") message(STATUS "[ ${CMAKE_CURRENT_LIST_FILE}:${CMAKE_CURRENT_LIST_LINE} ] " "_boost_DEBUG_ABI_TAG = ${_boost_DEBUG_ABI_TAG}") endif() # ------------------------------------------------------------------------ # Begin finding boost libraries # ------------------------------------------------------------------------ set(_Boost_VARS_LIB BOOST_LIBRARYDIR Boost_LIBRARY_DIR) _Boost_CHANGE_DETECT(_Boost_CHANGE_LIBDIR ${_Boost_VARS_DIR} ${_Boost_VARS_LIB} Boost_INCLUDE_DIR) # Clear Boost_LIBRARY_DIR if it did not change but other input affecting the # location did. We will find a new one based on the new inputs. if(_Boost_CHANGE_LIBDIR AND NOT _Boost_LIBRARY_DIR_CHANGED) unset(Boost_LIBRARY_DIR CACHE) endif() if(Boost_LIBRARY_DIR) set(_boost_LIBRARY_SEARCH_DIRS ${Boost_LIBRARY_DIR} NO_DEFAULT_PATH NO_CMAKE_FIND_ROOT_PATH) else() set(_boost_LIBRARY_SEARCH_DIRS "") if(BOOST_LIBRARYDIR) list(APPEND _boost_LIBRARY_SEARCH_DIRS ${BOOST_LIBRARYDIR}) elseif(_ENV_BOOST_LIBRARYDIR) list(APPEND _boost_LIBRARY_SEARCH_DIRS ${_ENV_BOOST_LIBRARYDIR}) endif() if(BOOST_ROOT) list(APPEND _boost_LIBRARY_SEARCH_DIRS ${BOOST_ROOT}/lib ${BOOST_ROOT}/stage/lib) elseif(_ENV_BOOST_ROOT) list(APPEND _boost_LIBRARY_SEARCH_DIRS ${_ENV_BOOST_ROOT}/lib ${_ENV_BOOST_ROOT}/stage/lib) endif() list(APPEND _boost_LIBRARY_SEARCH_DIRS ${Boost_INCLUDE_DIR}/lib ${Boost_INCLUDE_DIR}/../lib ${Boost_INCLUDE_DIR}/stage/lib ) if( Boost_NO_SYSTEM_PATHS ) list(APPEND _boost_LIBRARY_SEARCH_DIRS NO_CMAKE_SYSTEM_PATH) else() list(APPEND _boost_LIBRARY_SEARCH_DIRS PATHS C:/boost/lib C:/boost /sw/local/lib ) endif() endif() if(Boost_DEBUG) message(STATUS "[ ${CMAKE_CURRENT_LIST_FILE}:${CMAKE_CURRENT_LIST_LINE} ] " "_boost_LIBRARY_SEARCH_DIRS = ${_boost_LIBRARY_SEARCH_DIRS}") endif() # Support preference of static libs by adjusting CMAKE_FIND_LIBRARY_SUFFIXES if( Boost_USE_STATIC_LIBS ) set( _boost_ORIG_CMAKE_FIND_LIBRARY_SUFFIXES ${CMAKE_FIND_LIBRARY_SUFFIXES}) if(WIN32) set(CMAKE_FIND_LIBRARY_SUFFIXES .lib .a ${CMAKE_FIND_LIBRARY_SUFFIXES}) else() set(CMAKE_FIND_LIBRARY_SUFFIXES .a ) endif() endif() # We want to use the tag inline below without risking double dashes if(_boost_RELEASE_ABI_TAG) if(${_boost_RELEASE_ABI_TAG} STREQUAL "-") set(_boost_RELEASE_ABI_TAG "") endif() endif() if(_boost_DEBUG_ABI_TAG) if(${_boost_DEBUG_ABI_TAG} STREQUAL "-") set(_boost_DEBUG_ABI_TAG "") endif() endif() # The previous behavior of FindBoost when Boost_USE_STATIC_LIBS was enabled # on WIN32 was to: # 1. Search for static libs compiled against a SHARED C++ standard runtime library (use if found) # 2. Search for static libs compiled against a STATIC C++ standard runtime library (use if found) # We maintain this behavior since changing it could break people's builds. # To disable the ambiguous behavior, the user need only # set Boost_USE_STATIC_RUNTIME either ON or OFF. set(_boost_STATIC_RUNTIME_WORKAROUND false) if(WIN32 AND Boost_USE_STATIC_LIBS) if(NOT DEFINED Boost_USE_STATIC_RUNTIME) set(_boost_STATIC_RUNTIME_WORKAROUND true) endif() endif() # On versions < 1.35, remove the System library from the considered list # since it wasn't added until 1.35. if(Boost_VERSION AND Boost_FIND_COMPONENTS) if(Boost_VERSION LESS 103500) list(REMOVE_ITEM Boost_FIND_COMPONENTS system) endif() endif() # If the user changed any of our control inputs flush previous results. if(_Boost_CHANGE_LIBDIR OR _Boost_CHANGE_LIBNAME) foreach(COMPONENT ${_Boost_COMPONENTS_SEARCHED}) string(TOUPPER ${COMPONENT} UPPERCOMPONENT) foreach(c DEBUG RELEASE) set(_var Boost_${UPPERCOMPONENT}_LIBRARY_${c}) unset(${_var} CACHE) set(${_var} "${_var}-NOTFOUND") endforeach() endforeach() set(_Boost_COMPONENTS_SEARCHED "") endif() foreach(COMPONENT ${Boost_FIND_COMPONENTS}) string(TOUPPER ${COMPONENT} UPPERCOMPONENT) set( _boost_docstring_release "Boost ${COMPONENT} library (release)") set( _boost_docstring_debug "Boost ${COMPONENT} library (debug)") # Compute component-specific hints. set(_Boost_FIND_LIBRARY_HINTS_FOR_COMPONENT "") if(${COMPONENT} STREQUAL "mpi" OR ${COMPONENT} STREQUAL "mpi_python" OR ${COMPONENT} STREQUAL "graph_parallel") foreach(lib ${MPI_CXX_LIBRARIES} ${MPI_C_LIBRARIES}) if(IS_ABSOLUTE "${lib}") get_filename_component(libdir "${lib}" PATH) string(REPLACE "\\" "/" libdir "${libdir}") list(APPEND _Boost_FIND_LIBRARY_HINTS_FOR_COMPONENT ${libdir}) endif() endforeach() endif() # Consolidate and report component-specific hints. if(_Boost_FIND_LIBRARY_HINTS_FOR_COMPONENT) list(REMOVE_DUPLICATES _Boost_FIND_LIBRARY_HINTS_FOR_COMPONENT) if(Boost_DEBUG) message(STATUS "[ ${CMAKE_CURRENT_LIST_FILE}:${CMAKE_CURRENT_LIST_LINE} ] " "Component-specific library search paths for ${COMPONENT}: " "${_Boost_FIND_LIBRARY_HINTS_FOR_COMPONENT}") endif() endif() # # Find RELEASE libraries # unset(_boost_RELEASE_NAMES) foreach(compiler IN LISTS _boost_COMPILER) list(APPEND _boost_RELEASE_NAMES ${Boost_LIB_PREFIX}${Boost_NAMESPACE}_${COMPONENT}${compiler}${_boost_MULTITHREADED}${_boost_RELEASE_ABI_TAG}-${Boost_LIB_VERSION} ${Boost_LIB_PREFIX}${Boost_NAMESPACE}_${COMPONENT}${compiler}${_boost_MULTITHREADED}${_boost_RELEASE_ABI_TAG} ) endforeach() list(APPEND _boost_RELEASE_NAMES ${Boost_LIB_PREFIX}${Boost_NAMESPACE}_${COMPONENT}${_boost_MULTITHREADED}${_boost_RELEASE_ABI_TAG}-${Boost_LIB_VERSION} ${Boost_LIB_PREFIX}${Boost_NAMESPACE}_${COMPONENT}${_boost_MULTITHREADED}${_boost_RELEASE_ABI_TAG} ${Boost_LIB_PREFIX}${Boost_NAMESPACE}_${COMPONENT} ) if(_boost_STATIC_RUNTIME_WORKAROUND) set(_boost_RELEASE_STATIC_ABI_TAG "-s${_boost_RELEASE_ABI_TAG}") foreach(compiler IN LISTS _boost_COMPILER) list(APPEND _boost_RELEASE_NAMES ${Boost_LIB_PREFIX}${Boost_NAMESPACE}_${COMPONENT}${compiler}${_boost_MULTITHREADED}${_boost_RELEASE_STATIC_ABI_TAG}-${Boost_LIB_VERSION} ${Boost_LIB_PREFIX}${Boost_NAMESPACE}_${COMPONENT}${compiler}${_boost_MULTITHREADED}${_boost_RELEASE_STATIC_ABI_TAG} ) endforeach() list( APPEND _boost_RELEASE_NAMES ${Boost_LIB_PREFIX}${Boost_NAMESPACE}_${COMPONENT}${_boost_MULTITHREADED}${_boost_RELEASE_STATIC_ABI_TAG}-${Boost_LIB_VERSION} ${Boost_LIB_PREFIX}${Boost_NAMESPACE}_${COMPONENT}${_boost_MULTITHREADED}${_boost_RELEASE_STATIC_ABI_TAG} ) endif() if(Boost_THREADAPI AND ${COMPONENT} STREQUAL "thread") _Boost_PREPEND_LIST_WITH_THREADAPI(_boost_RELEASE_NAMES ${_boost_RELEASE_NAMES}) endif() if(Boost_DEBUG) message(STATUS "[ ${CMAKE_CURRENT_LIST_FILE}:${CMAKE_CURRENT_LIST_LINE} ] " "Searching for ${UPPERCOMPONENT}_LIBRARY_RELEASE: ${_boost_RELEASE_NAMES}") endif() # Avoid passing backslashes to _Boost_FIND_LIBRARY due to macro re-parsing. string(REPLACE "\\" "/" _boost_LIBRARY_SEARCH_DIRS_tmp "${_boost_LIBRARY_SEARCH_DIRS}") _Boost_FIND_LIBRARY(Boost_${UPPERCOMPONENT}_LIBRARY_RELEASE NAMES ${_boost_RELEASE_NAMES} HINTS ${_boost_LIBRARY_SEARCH_DIRS_tmp} NAMES_PER_DIR DOC "${_boost_docstring_release}" ) # # Find DEBUG libraries # unset(_boost_DEBUG_NAMES) foreach(compiler IN LISTS _boost_COMPILER) list(APPEND _boost_DEBUG_NAMES ${Boost_LIB_PREFIX}${Boost_NAMESPACE}_${COMPONENT}${compiler}${_boost_MULTITHREADED}${_boost_DEBUG_ABI_TAG}-${Boost_LIB_VERSION} ${Boost_LIB_PREFIX}${Boost_NAMESPACE}_${COMPONENT}${compiler}${_boost_MULTITHREADED}${_boost_DEBUG_ABI_TAG} ) endforeach() list(APPEND ${Boost_LIB_PREFIX}${Boost_NAMESPACE}_${COMPONENT}${_boost_MULTITHREADED}${_boost_DEBUG_ABI_TAG}-${Boost_LIB_VERSION} ${Boost_LIB_PREFIX}${Boost_NAMESPACE}_${COMPONENT}${_boost_MULTITHREADED}${_boost_DEBUG_ABI_TAG} ${Boost_LIB_PREFIX}${Boost_NAMESPACE}_${COMPONENT}${_boost_MULTITHREADED} ${Boost_LIB_PREFIX}${Boost_NAMESPACE}_${COMPONENT} ) if(_boost_STATIC_RUNTIME_WORKAROUND) set(_boost_DEBUG_STATIC_ABI_TAG "-s${_boost_DEBUG_ABI_TAG}") foreach(compiler IN LISTS _boost_COMPILER) list(APPEND _boost_DEBUG_NAMES ${Boost_LIB_PREFIX}${Boost_NAMESPACE}_${COMPONENT}${compiler}${_boost_MULTITHREADED}${_boost_DEBUG_STATIC_ABI_TAG}-${Boost_LIB_VERSION} ${Boost_LIB_PREFIX}${Boost_NAMESPACE}_${COMPONENT}${compiler}${_boost_MULTITHREADED}${_boost_DEBUG_STATIC_ABI_TAG} ) endforeach() list(APPEND _boost_DEBUG_NAMES ${Boost_LIB_PREFIX}${Boost_NAMESPACE}_${COMPONENT}${_boost_MULTITHREADED}${_boost_DEBUG_STATIC_ABI_TAG}-${Boost_LIB_VERSION} ${Boost_LIB_PREFIX}${Boost_NAMESPACE}_${COMPONENT}${_boost_MULTITHREADED}${_boost_DEBUG_STATIC_ABI_TAG} ) endif() if(Boost_THREADAPI AND ${COMPONENT} STREQUAL "thread") _Boost_PREPEND_LIST_WITH_THREADAPI(_boost_DEBUG_NAMES ${_boost_DEBUG_NAMES}) endif() if(Boost_DEBUG) message(STATUS "[ ${CMAKE_CURRENT_LIST_FILE}:${CMAKE_CURRENT_LIST_LINE} ] " "Searching for ${UPPERCOMPONENT}_LIBRARY_DEBUG: ${_boost_DEBUG_NAMES}") endif() # Avoid passing backslashes to _Boost_FIND_LIBRARY due to macro re-parsing. string(REPLACE "\\" "/" _boost_LIBRARY_SEARCH_DIRS_tmp "${_boost_LIBRARY_SEARCH_DIRS}") _Boost_FIND_LIBRARY(Boost_${UPPERCOMPONENT}_LIBRARY_DEBUG NAMES ${_boost_DEBUG_NAMES} HINTS ${_boost_LIBRARY_SEARCH_DIRS_tmp} NAMES_PER_DIR DOC "${_boost_docstring_debug}" ) if(Boost_REALPATH) _Boost_SWAP_WITH_REALPATH(Boost_${UPPERCOMPONENT}_LIBRARY_RELEASE "${_boost_docstring_release}") _Boost_SWAP_WITH_REALPATH(Boost_${UPPERCOMPONENT}_LIBRARY_DEBUG "${_boost_docstring_debug}" ) endif() _Boost_ADJUST_LIB_VARS(${UPPERCOMPONENT}) endforeach() # Restore the original find library ordering if( Boost_USE_STATIC_LIBS ) set(CMAKE_FIND_LIBRARY_SUFFIXES ${_boost_ORIG_CMAKE_FIND_LIBRARY_SUFFIXES}) endif() # ------------------------------------------------------------------------ # End finding boost libraries # ------------------------------------------------------------------------ set(Boost_INCLUDE_DIRS ${Boost_INCLUDE_DIR}) set(Boost_LIBRARY_DIRS ${Boost_LIBRARY_DIR}) # The above setting of Boost_FOUND was based only on the header files. # Update it for the requested component libraries. if(Boost_FOUND) # The headers were found. Check for requested component libs. set(_boost_CHECKED_COMPONENT FALSE) set(_Boost_MISSING_COMPONENTS "") foreach(COMPONENT ${Boost_FIND_COMPONENTS}) string(TOUPPER ${COMPONENT} COMPONENT) set(_boost_CHECKED_COMPONENT TRUE) if(NOT Boost_${COMPONENT}_FOUND) string(TOLOWER ${COMPONENT} COMPONENT) list(APPEND _Boost_MISSING_COMPONENTS ${COMPONENT}) endif() endforeach() if(Boost_DEBUG) message(STATUS "[ ${CMAKE_CURRENT_LIST_FILE}:${CMAKE_CURRENT_LIST_LINE} ] Boost_FOUND = ${Boost_FOUND}") endif() if (_Boost_MISSING_COMPONENTS) set(Boost_FOUND 0) # We were unable to find some libraries, so generate a sensible # error message that lists the libraries we were unable to find. set(Boost_ERROR_REASON "${Boost_ERROR_REASON}\nCould not find the following") if(Boost_USE_STATIC_LIBS) set(Boost_ERROR_REASON "${Boost_ERROR_REASON} static") endif() set(Boost_ERROR_REASON "${Boost_ERROR_REASON} Boost libraries:\n") foreach(COMPONENT ${_Boost_MISSING_COMPONENTS}) set(Boost_ERROR_REASON "${Boost_ERROR_REASON} ${Boost_NAMESPACE}_${COMPONENT}\n") endforeach() list(LENGTH Boost_FIND_COMPONENTS Boost_NUM_COMPONENTS_WANTED) list(LENGTH _Boost_MISSING_COMPONENTS Boost_NUM_MISSING_COMPONENTS) if (${Boost_NUM_COMPONENTS_WANTED} EQUAL ${Boost_NUM_MISSING_COMPONENTS}) set(Boost_ERROR_REASON "${Boost_ERROR_REASON}No Boost libraries were found. You may need to set BOOST_LIBRARYDIR to the directory containing Boost libraries or BOOST_ROOT to the location of Boost. If you still have problems search on forum for TCE00020.") else () set(Boost_ERROR_REASON "${Boost_ERROR_REASON}Some (but not all) of the required Boost libraries were found. You may need to install these additional Boost libraries. Alternatively, set BOOST_LIBRARYDIR to the directory containing Boost libraries or BOOST_ROOT to the location of Boost. If you still have problems search on forum for TCE00021.") endif () endif () if( NOT Boost_LIBRARY_DIRS AND NOT _boost_CHECKED_COMPONENT ) # Compatibility Code for backwards compatibility with CMake # 2.4's FindBoost module. # Look for the boost library path. # Note that the user may not have installed any libraries # so it is quite possible the Boost_LIBRARY_DIRS may not exist. set(_boost_LIB_DIR ${Boost_INCLUDE_DIR}) if("${_boost_LIB_DIR}" MATCHES "boost-[0-9]+") get_filename_component(_boost_LIB_DIR ${_boost_LIB_DIR} PATH) endif() if("${_boost_LIB_DIR}" MATCHES "/include$") # Strip off the trailing "/include" in the path. get_filename_component(_boost_LIB_DIR ${_boost_LIB_DIR} PATH) endif() if(EXISTS "${_boost_LIB_DIR}/lib") set(_boost_LIB_DIR ${_boost_LIB_DIR}/lib) else() if(EXISTS "${_boost_LIB_DIR}/stage/lib") set(_boost_LIB_DIR ${_boost_LIB_DIR}/stage/lib) else() set(_boost_LIB_DIR "") endif() endif() if(_boost_LIB_DIR AND EXISTS "${_boost_LIB_DIR}") set(Boost_LIBRARY_DIRS ${_boost_LIB_DIR}) endif() endif() else() # Boost headers were not found so no components were found. foreach(COMPONENT ${Boost_FIND_COMPONENTS}) string(TOUPPER ${COMPONENT} UPPERCOMPONENT) set(Boost_${UPPERCOMPONENT}_FOUND 0) endforeach() endif() # ------------------------------------------------------------------------ # Notification to end user about what was found # ------------------------------------------------------------------------ set(Boost_LIBRARIES "") if(Boost_FOUND) if(NOT Boost_FIND_QUIETLY) message(STATUS "Boost version: ${Boost_MAJOR_VERSION}.${Boost_MINOR_VERSION}.${Boost_SUBMINOR_VERSION}") if(Boost_FIND_COMPONENTS) message(STATUS "Found the following Boost libraries:") endif() endif() foreach( COMPONENT ${Boost_FIND_COMPONENTS} ) string( TOUPPER ${COMPONENT} UPPERCOMPONENT ) if( Boost_${UPPERCOMPONENT}_FOUND ) if(NOT Boost_FIND_QUIETLY) message (STATUS " ${COMPONENT}") endif() list(APPEND Boost_LIBRARIES ${Boost_${UPPERCOMPONENT}_LIBRARY}) endif() endforeach() else() if(Boost_FIND_REQUIRED) message(SEND_ERROR "Unable to find the requested Boost libraries.\n${Boost_ERROR_REASON}") else() if(NOT Boost_FIND_QUIETLY) # we opt not to automatically output Boost_ERROR_REASON here as # it could be quite lengthy and somewhat imposing in its requests # Since Boost is not always a required dependency we'll leave this # up to the end-user. if(Boost_DEBUG OR Boost_DETAILED_FAILURE_MSG) message(STATUS "Could NOT find Boost\n${Boost_ERROR_REASON}") else() message(STATUS "Could NOT find Boost") endif() endif() endif() endif() # Configure display of cache entries in GUI. foreach(v BOOSTROOT BOOST_ROOT ${_Boost_VARS_INC} ${_Boost_VARS_LIB}) get_property(_type CACHE ${v} PROPERTY TYPE) if(_type) set_property(CACHE ${v} PROPERTY ADVANCED 1) if("x${_type}" STREQUAL "xUNINITIALIZED") if("x${v}" STREQUAL "xBoost_ADDITIONAL_VERSIONS") set_property(CACHE ${v} PROPERTY TYPE STRING) else() set_property(CACHE ${v} PROPERTY TYPE PATH) endif() endif() endif() endforeach() # Record last used values of input variables so we can # detect on the next run if the user changed them. foreach(v ${_Boost_VARS_INC} ${_Boost_VARS_LIB} ${_Boost_VARS_DIR} ${_Boost_VARS_NAME} ) if(DEFINED ${v}) set(_${v}_LAST "${${v}}" CACHE INTERNAL "Last used ${v} value.") else() unset(_${v}_LAST CACHE) endif() endforeach() # Maintain a persistent list of components requested anywhere since # the last flush. set(_Boost_COMPONENTS_SEARCHED "${_Boost_COMPONENTS_SEARCHED}") list(APPEND _Boost_COMPONENTS_SEARCHED ${Boost_FIND_COMPONENTS}) list(REMOVE_DUPLICATES _Boost_COMPONENTS_SEARCHED) list(SORT _Boost_COMPONENTS_SEARCHED) set(_Boost_COMPONENTS_SEARCHED "${_Boost_COMPONENTS_SEARCHED}" CACHE INTERNAL "Components requested for this build tree.")
jtongzhi/TrinityCore
cmake/macros/FindBoost.cmake
CMake
gpl-2.0
52,512
## -*- perl -*- ## ## redland.pod - redland Unix manual page ## ## $Id$ ## ## Copyright (C) 2002-2006, David Beckett http://purl.org/net/dajobe/ ## Copyright (C) 2002-2004, University of Bristol, UK http://www.bristol.ac.uk/ ## ## This package is Free Software and part of Redland http://librdf.org/ ## ## It is licensed under the following three licenses as alternatives: ## 1. GNU Lesser General Public License (LGPL) V2.1 or any newer version ## 2. GNU General Public License (GPL) V2 or any newer version ## 3. Apache License, V2.0 or any newer version ## ## You may not use this file except in compliance with at least one of ## the above three licenses. ## ## See LICENSE.html or LICENSE.txt at the top of this package for the ## complete terms and further detail along with the license texts for ## the licenses in COPYING.LIB, COPYING and LICENSE-2.0.txt respectively. ## ## =pod =head1 NAME Redland Resource Description Framework (RDF) Library =head1 VERSION REDLAND_VERSION_STRING =head1 SYNOPSIS #include <redland.h> =head1 DESCRIPTION B<redland> is a library providing support for the Resource Description Framework (RDF) written in ANSI C with APIs in several other languages. This manual page lists most of the redland public API functions but does not claim to be a complete summary of the entire API. For the complete API with full details of the function interface, see the HTML API documentation either on the Redland web site at L<http://librdf.org/> or with the software release in the docs/api directory. =head1 FUNCTIONS The functions defined by B<redland> are all defined with the C<librdf_> prefix =head2 class world =over 4 =item librdf_world* B<librdf_new_world>(I<void>) =item void B<librdf_free_world>(librdf_world* I<world>) =item void B<librdf_world_open>(librdf_world* I<world>) =item void B<librdf_world_set_error>(librdf_world* I<world>, void* I<user_data>, void (*I<error_fn>)(void* I<user_data>, const char* I<msg>, ...)) =item void B<librdf_world_set_warning>(librdf_world* I<world>, void* I<user_data>, void (*I<warning_fn>)(void* I<user_data>, const char* I<msg>, ...)) =item void B<librdf_world_set_digest>(librdf_world*, const char* I<name>) =item void B<librdf_world_set_uris_hash>(librdf_world* I<world>, librdf_hash* I<uris_hash>) =item const char* B<librdf_world_get_feature>(librdf_world* I<world>, librdf_uri* I<feature>) =item int B<librdf_world_set_feature>(librdf_world* I<world>, librdf_uri* I<feature>, const char* I<value>) =back =head2 class iterator =over 4 =item librdf_iterator* B<librdf_new_iterator>(librdf_world* I<world>, void* I<context>, int (*I<is_end>)(void*), void* (*I<get_next>)(void*), void (*I<finished>)(void*)) =item void B<librdf_free_iterator>(librdf_iterator*) =item int B<librdf_iterator_end>(librdf_iterator* I<iterator>) =item int B<librdf_iterator_finished>(librdf_iterator* I<iterator>) =item int B<librdf_iterator_next>(librdf_iterator* I<iterator>) =item void* B<librdf_iterator_get_object>(librdf_iterator* I<iterator>) =item void* B<librdf_iterator_get_context>(librdf_iterator* I<iterator>) =item void* B<librdf_iterator_get_key>(librdf_iterator* I<iterator>) =item void* B<librdf_iterator_get_value>(librdf_iterator* I<iterator>) =item int B<librdf_iterator_add_map>(librdf_iterator* I<iterator>, void* (*I<fn>)(void* I<context>, void* I<item>), void* I<context>) =item void* B<librdf_iterator_map_remove_duplicate_nodes>(void* I<item>, void* I<user_data>) =back =head2 class digest =over 4 =item void B<librdf_digest_register_factory>(librdf_world* I<world>, const char* I<name>, void (*I<factory>) (librdf_digest_factory*)) =item librdf_digest_factory* B<librdf_get_digest_factory>(librdf_world* I<world>, const char* I<name>) =item librdf_digest* B<librdf_new_digest>(librdf_world* I<world>, char* I<name>) =item librdf_digest* B<librdf_new_digest_from_factory>(librdf_world* I<world>, librdf_digest_factory* I<factory>) =item void B<librdf_free_digest>(librdf_digest* I<digest>) =item void B<librdf_digest_init>(librdf_digest* I<digest>) =item void B<librdf_digest_update>(librdf_digest* I<digest>, unsigned char* I<buf>, size_t I<length>) =item void B<librdf_digest_final>(librdf_digest* I<digest>) =item void* B<librdf_digest_get_digest>(librdf_digest* I<digest>) =item char* B<librdf_digest_to_string>(librdf_digest* I<digest>) =item void B<librdf_digest_print>(librdf_digest* I<digest>, FILE* I<fh>) =back =head2 class uri =over 4 =item librdf_uri* B<librdf_new_uri>(librdf_world* I<world>, const unsigned char * I<string>) =item librdf_uri* B<librdf_new_uri_from_uri>(librdf_uri* I<uri>) =item librdf_uri* B<librdf_new_uri_from_uri_local_name>(librdf_uri* I<uri>, const unsigned char* I<local_name>) =item void B<librdf_free_uri>(librdf_uri* I<uri>) =item unsigned char* B<librdf_uri_as_string>(librdf_uri* I<uri>) =item unsigned char* B<librdf_uri_as_counted_string>(librdf_uri* I<uri>, size_t* I<len_p>) =item librdf_digest* B<librdf_uri_get_digest>(librdf_uri* I<uri>) =item void librdf_uri_print>(librdf_uri* I<uri>, FILE* I<fh>) =item unsigned char* B<librdf_uri_to_string>(librdf_uri* I<uri>) =item unsigned char* B<librdf_uri_to_counted_string>(librdf_uri* I<uri>, size_t* I<len_p>) =item int B<librdf_uri_equals>(librdf_uri* I<first_uri>, librdf_uri* I<second_uri>) =item int B<librdf_uri_is_file_uri>(librdf_uri* I<uri>) =item const char* B<librdf_uri_to_filename>(librdf_uri* I<uri>) =item librdf_uri* B<librdf_new_uri_normalised_to_base>(const unsigned char* I<uri_string>, librdf_uri* I<source_uri>, librdf_uri* I<base_uri>) =item librdf_uri* B<librdf_new_uri_relative_to_base>(librdf_uri* I<base_uri>, const unsigned char* I<uri_string>) =item librdf_uri* B<librdf_new_uri_from_filename>(librdf_world* I<world>, const char* I<filename>) =back =head2 class node =over 4 =item librdf_node* B<librdf_new_node>(librdf_world* I<world>) =item librdf_node* B<librdf_new_node_from_uri_string>(librdf_world* I<world>, const char* I<string>) =item librdf_node* B<librdf_new_node_from_uri>(librdf_world* I<world>, librdf_uri* I<uri>) =item librdf_node* B<librdf_new_node_from_uri_local_name>(librdf_world* I<world>, librdf_uri* I<uri>, const char* I<local_name>) =item librdf_node* B<librdf_new_node_from_normalised_uri_string>(librdf_world* I<world>, const char* I<uri_string>, librdf_uri* I<source_uri>, librdf_uri* I<base_uri>) =item librdf_node* B<librdf_new_node_from_literal>(librdf_world* I<world>, const char* I<string>, const char* I<xml_language>, int I<xml_space>, int I<is_wf_xml>) =item librdf_node* B<librdf_new_node_from_typed_literal>(librdf_world* I<world>, const unsigned char* I<string>, const char* I<xml_language>, librdf_uri* I<datatype_uri>) =item librdf_node* B<librdf_new_node_from_blank_identifier>(librdf_world* I<world>, const unsigned char* I<identifier>) =item librdf_node* B<librdf_new_node_from_node>(librdf_node* I<node>) =item void B<librdf_node_init>(librdf_world* I<world>, librdf_node* I<node>) =item void B<librdf_free_node>(librdf_node* I<r>) =item librdf_uri* B<librdf_node_get_uri>(librdf_node* I<node>) =item librdf_node_type B<librdf_node_get_type>(librdf_node* I<node>) =item unsigned char* B<librdf_node_get_literal_value>(librdf_node* I<node>) =item unsigned char* B<librdf_node_get_literal_value_as_counted_string>(librdf_node* I<node>, size_t* I<len_p>) =item char* B<librdf_node_get_literal_value_as_latin1>(librdf_node* I<node>) =item char* B<librdf_node_get_literal_value_language>(librdf_node* I<node>) =item int B<librdf_node_get_literal_value_is_wf_xml>(librdf_node* I<node>) =item librdf_uri* B<librdf_node_get_literal_value_datatype_uri>(librdf_node* I<node>) =item int B<librdf_node_get_li_ordinal>(librdf_node* I<node>) =item unsigned char* B<librdf_node_get_blank_identifier>(librdf_node* I<node>) =item int B<librdf_node_is_resource>(librdf_node* I<node>) =item int B<librdf_node_is_literal>(librdf_node* I<node>) =item int B<librdf_node_is_blank>(librdf_node* I<node>) =item librdf_digest* B<librdf_node_get_digest>(librdf_node* I<node>) =item size_t B<librdf_node_encode>(librdf_node* I<node>, unsigned char* I<buffer>, size_t I<length>) =item size_t B<librdf_node_decode>(librdf_node* I<node>, unsigned char* I<buffer>, size_t I<length>) =item unsigned char* B<librdf_node_to_string>(librdf_node* I<node>) =item unsigned char* B<librdf_node_to_counted_string>(librdf_node* I<node>, size_t* I<len_p>) =item void B<librdf_node_print>(librdf_node* I<node>, FILE* I<fh>) =item int B<librdf_node_equals>(librdf_node* I<first_node>, librdf_node* I<second_node>) =back =head2 class concepts The library provides macros for all of the RDF and RDFS concepts - nodes and URIs. For example, C<LIBRDF_MS_Alt> for the librdf_node for the rdf:Alt concept and C<LIBRDF_MS_Alt_URI> for the librdf_uri for the URI reference of rdf:Alt. C<LIBRDF_URI_RDF_MS> and C<LIBRDF_URI_RDF_SCHEMA> provide the librdf_uri objects for the RDF and RDFS namespace URIs. They must be copied using B<librdf_new_uri_from_uri> to be shared correctly. =over 4 =item void B<librdf_get_concept_by_name>(librdf_world* I<world>, int I<is_ms>, const char* I<name>, librdf_uri **I<uri_p>, librdf_node **I<node_p>) =back =head2 class statement =over 4 =item librdf_statement* B<librdf_new_statement>(librdf_world* I<world>) =item librdf_statement* B<librdf_new_statement_from_statement>(librdf_statement* I<statement>) =item librdf_statement* B<librdf_new_statement_from_nodes>(librdf_world* I<world>, librdf_node* I<subject>, librdf_node* I<predicate>, librdf_node* I<object>) =item void B<librdf_statement_init>(librdf_world* I<world>, librdf_statement* I<statement>) =item void B<librdf_statement_clear>(librdf_statement* I<statement>) =item void B<librdf_free_statement>(librdf_statement* I<statement>) =item librdf_node* B<librdf_statement_get_subject>(librdf_statement* I<statement>) =item void B<librdf_statement_set_subject>(librdf_statement* I<statement>, librdf_node* I<subject>) =item librdf_node* B<librdf_statement_get_predicate>(librdf_statement* I<statement>) =item void B<librdf_statement_set_predicate>(librdf_statement* I<statement>, librdf_node* I<predicate>) =item librdf_node* B<librdf_statement_get_object>(librdf_statement* I<statement>) =item void B<librdf_statement_set_object>(librdf_statement* I<statement>, librdf_node* I<object>) =item int B<librdf_statement_is_complete>(librdf_statement* I<statement>) =item char* B<librdf_statement_to_string>(librdf_statement* I<statement>) =item void B<librdf_statement_print>(librdf_statement* I<statement>, FILE* I<fh>) =item int B<librdf_statement_equals>(librdf_statement* I<statement1>, librdf_statement* I<statement2>) =item int B<librdf_statement_match>(librdf_statement* I<statement>, librdf_statement* I<partial_statement>) =item size_t B<librdf_statement_encode>(librdf_statement* I<statement>, unsigned char* I<buffer>, size_t I<length>) =item size_t B<librdf_statement_encode_parts>(librdf_statement* I<statement>, unsigned char* I<buffer>, size_t I<length>, librdf_statement_part I<fields>) =item size_t B<librdf_statement_decode>(librdf_statement* I<statement>, unsigned char* I<buffer>, size_t I<length>) =item size_t B<librdf_statement_decode_parts>(librdf_statement* I<statement>, librdf_node** I<context_node>, unsigned char* I<buffer>, size_t I<length>) =back =head2 class model =over 4 =item librdf_model* B<librdf_new_model>(librdf_world* I<world>, librdf_storage* I<storage>, char* I<options_string>) =item librdf_model* B<librdf_new_model_with_options>(librdf_world* I<world>, librdf_storage* I<storage>, librdf_hash* I<options>) =item librdf_model* B<librdf_new_model_from_model>(librdf_model* I<model>) =item void B<librdf_free_model>(librdf_model* I<model>) =item int B<librdf_model_size>(librdf_model* I<model>) =item int B<librdf_model_add>(librdf_model* I<model>, librdf_node* I<subject>, librdf_node* I<predicate>, librdf_node* I<object>) =item int B<librdf_model_add_string_literal_statement>(librdf_model* I<model>, librdf_node* I<subject>, librdf_node* I<predicate>, char* I<string>, char* I<xml_language>, int I<xml_space>, int I<is_wf_xml>) =item int B<librdf_model_add_typed_literal_statement>(librdf_model* I<model>, librdf_node* I<subject>, librdf_node* I<predicate>, const unsigned char* I<string>, char* I<xml_language>, librdf_uri* I<datatype_uri>) =item int B<librdf_model_add_statement>(librdf_model* I<model>, librdf_statement* I<statement>) =item int B<librdf_model_add_statements>(librdf_model* I<model>, librdf_stream* I<statement_stream>) =item int B<librdf_model_remove_statement>(librdf_model* I<model>, librdf_statement* I<statement>) =item int B<librdf_model_contains_statement>(librdf_model* I<model>, librdf_statement* I<statement>) =item int B<librdf_model_has_arc_in>(librdf_model* I<model>, librdf_node* I<node>, librdf_node* I<property>) =item int B<librdf_model_has_arc_out>(librdf_model* I<model>, librdf_node* I<node>, librdf_node* I<property>) =item librdf_stream* B<librdf_model_as_stream>(librdf_model* I<model>) =item librdf_stream* B<librdf_model_find_statements>(librdf_model* I<model>, librdf_statement* I<statement>) =item librdf_stream* B<librdf_model_find_statements_in_context>(librdf_model* I<model>, librdf_statement* I<statement>, librdf_node* I<context_node>) =item librdf_stream* B<librdf_model_find_statements_with_options>(librdf_model* I<model>, librdf_statement* I<statement>, librdf_node* I<context_node>, librdf_hash* I<options>) =item librdf_iterator* B<librdf_model_get_contexts>(librdf_model* I<model>) =item librdf_iterator* B<librdf_model_get_sources>(librdf_model* I<model>, librdf_node* I<arc>, librdf_node* I<target>) =item librdf_iterator* B<librdf_model_get_arcs>(librdf_model* I<model>, librdf_node* I<source>, librdf_node* I<target>) =item librdf_iterator* B<librdf_model_get_targets>(librdf_model* I<model>, librdf_node* I<source>, librdf_node* I<arc>) =item librdf_node* B<librdf_model_get_source>(librdf_model* I<model>, librdf_node* I<arc>, librdf_node* I<target>) =item librdf_node* B<librdf_model_get_arc>(librdf_model* I<model>, librdf_node* I<source>, librdf_node* I<target>) =item librdf_node* B<librdf_model_get_target>(librdf_model* I<model>, librdf_node* I<source>, librdf_node* I<arc>) =item librdf_iterator* B<librdf_model_get_arcs_in>(librdf_model* I<model>, librdf_node* I<node>) =item librdf_iterator* B<librdf_model_get_arcs_out>(librdf_model* I<model>, librdf_node* I<node>) =item int B<librdf_model_add_submodel>(librdf_model* I<model>, librdf_model* I<sub_model>) =item int B<librdf_model_remove_submodel>(librdf_model* I<model>, librdf_model* I<sub_model>) =item void B<librdf_model_print>(librdf_model* I<model>, FILE* I<fh>) =item int B<librdf_model_context_add_statement>(librdf_model* I<model>, librdf_node* I<context>, librdf_statement* I<statement>) =item int B<librdf_model_context_add_statements>(librdf_model* I<model>, librdf_node* I<context>, librdf_stream* I<stream>) =item int B<librdf_model_context_remove_statement>(librdf_model* I<model>, librdf_node* I<context>, librdf_statement* I<statement>) =item int B<librdf_model_context_remove_statements>(librdf_model* I<model>, librdf_node* I<context>) =item librdf_stream* B<librdf_model_context_as_stream>(librdf_model* I<model>, librdf_node* I<context>) =item librdf_stream* B<librdf_model_query>(librdf_model* I<model>, librdf_query* I<query>) =item librdf_stream* B<librdf_model_query_string>(librdf_model* I<model>, const char* I<name>, librdf_uri* I<uri>, const unsigned char* I<query_string>) =item void B<librdf_model_sync>(librdf_model* I<model>) =item librdf_storage* B<librdf_model_get_storage>(librdf_model* I<model>) =item librdf_node* B<librdf_model_get_feature>(librdf_model* I<model>, librdf_uri* I<feature>) =item int B<librdf_model_set_feature>(librdf_model* I<model>, librdf_uri* I<feature>, librdf_node* I<value>) =back =head2 class storage =over 4 =item void B<librdf_storage_register_factory>(const char* I<name>, void (*I<factory>) (librdf_storage_factory*)) =item librdf_storage* B<librdf_new_storage>(librdf_world* I<world>, char* I<storage_name>, char* I<name>, char* I<options_string>) =item librdf_storage* B<librdf_new_storage_with_options>(librdf_world* I<world>, char* I<storage_name>, char* I<name>, librdf_hash* I<options>) =item librdf_storage* B<librdf_new_storage_from_storage>(librdf_storage* I<old_storage>) =item librdf_storage* B<librdf_new_storage_from_factory>(librdf_world* I<world>, librdf_storage_factory* I<factory>, char* I<name>, librdf_hash* I<options>) =item void B<librdf_free_storage>(librdf_storage* I<storage>) =item int B<librdf_storage_open>(librdf_storage* I<storage>, librdf_model* I<model>) =item int B<librdf_storage_close>(librdf_storage* I<storage>) =item int B<librdf_storage_get>(librdf_storage* I<storage>, void* I<key>, size_t I<key_len>, void **I<value>, size_t* I<value_len>, unsigned int I<flags>) =item int B<librdf_storage_size>(librdf_storage* I<storage>) =item int B<librdf_storage_add_statement>(librdf_storage* I<storage>, librdf_statement* I<statement>) =item int B<librdf_storage_add_statements>(librdf_storage* I<storage>, librdf_stream* I<statement_stream>) =item int B<librdf_storage_remove_statement>(librdf_storage* I<storage>, librdf_statement* I<statement>) =item int B<librdf_storage_contains_statement>(librdf_storage* I<storage>, librdf_statement* I<statement>) =item librdf_stream* B<librdf_storage_serialise>(librdf_storage* I<storage>) =item librdf_stream* B<librdf_storage_find_statements>(librdf_storage* I<storage>, librdf_statement* I<statement>) =item librdf_iterator* B<librdf_storage_get_sources>(librdf_storage* I<storage>, librdf_node* I<arc>, librdf_node* I<target>) =item librdf_iterator* B<librdf_storage_get_arcs>(librdf_storage* I<storage>, librdf_node* I<source>, librdf_node* I<target>) =item librdf_iterator* B<librdf_storage_get_targets>(librdf_storage* I<storage>, librdf_node* I<source>, librdf_node* I<arc>) =item librdf_iterator* B<librdf_storage_get_arcs_in>(librdf_storage* I<storage>, librdf_node* I<node>) =item librdf_iterator* B<librdf_storage_get_arcs_out>(librdf_storage* I<storage>, librdf_node* I<node>) =item int B<librdf_storage_has_arc_in>(librdf_storage* I<storage>, librdf_node* I<node>, librdf_node* I<property>) =item int B<librdf_storage_has_arc_out>(librdf_storage* I<storage>, librdf_node* I<node>, librdf_node* I<property>) =item int B<librdf_storage_context_add_statement>(librdf_storage* I<storage>, librdf_node* I<context>, librdf_statement* I<statement>) =item int B<librdf_storage_context_add_statements>(librdf_storage* I<storage>, librdf_node* I<context>, librdf_stream* I<stream>) =item int B<librdf_storage_context_remove_statement>(librdf_storage* I<storage>, librdf_node* I<context>, librdf_statement* I<statement>) =item int B<librdf_storage_context_remove_statements>(librdf_storage* I<storage>, librdf_node* I<context>) =item librdf_stream* B<librdf_storage_context_as_stream>(librdf_storage* I<storage>, librdf_node* I<context>) =item int B<librdf_storage_supports_query>(librdf_storage* I<storage>, librdf_query* I<query>) =item librdf_stream* B<librdf_storage_query>(librdf_storage* I<storage>, librdf_query* I<query>) =item void B<librdf_storage_sync>(librdf_storage* I<storage>) =back =head2 class parser =over 4 =item void B<librdf_parser_register_factory>(librdf_world* I<world>, const char* I<name>, const char* I<mime_type>, const char* I<uri_string>, void (*I<factory>) (librdf_parser_factory*)) =item librdf_parser* B<librdf_new_parser>(librdf_world* I<world>, const char* I<name>, const char* I<mime_type>, librdf_uri* I<type_uri>) =item librdf_parser* B<librdf_new_parser_from_factory>(librdf_world* I<world>, librdf_parser_factory* I<factory>) =item void B<librdf_free_parser>(librdf_parser* I<parser>) =item librdf_stream* B<librdf_parser_parse_as_stream>(librdf_parser* I<parser>, librdf_uri* I<uri>, librdf_uri* I<base_uri>) =item int B<librdf_parser_parse_into_model>(librdf_parser* I<parser>, librdf_uri* I<uri>, librdf_uri* I<base_uri>, librdf_model* I<model>) =item librdf_stream* B<librdf_parser_parse_string_as_stream>(librdf_parser* I<parser>, const unsigned char* I<string>, librdf_uri* I<base_uri>) =item int librdf_parser_parse_string_into_model(librdf_parser* I<parser>, const unsigned char* I<string>, librdf_uri* I<base_uri>, librdf_model* I<model>) =item void B<librdf_parser_set_error>(librdf_parser* I<parser>, void* I<user_data>, void (*I<error_fn>)(void* I<user_data>, const char* I<msg>, ...)) =item void B<librdf_parser_set_warning>(librdf_parser* I<parser>, void* I<user_data>, void (*I<warning_fn>)(void* I<user_data>, const char* I<msg>, ...)) =item librdf_node* B<librdf_parser_get_feature>(librdf_parser* I<parser>, librdf_uri* I<feature>) =item int B<librdf_parser_set_feature>(librdf_parser* I<parser>, librdf_uri* I<feature>, librdf_node* I<value>) =back =head2 class serializer =over 4 =item librdf_serializer* librdf_new_serializer(librdf_world* I<world>, const char *I<name>, const char *I<mime_type>, librdf_uri *I<type_uri>) =item librdf_serializer* librdf_new_serializer_from_factory(librdf_world* I<world>, librdf_serializer_factory *I<factory>) =item void librdf_free_serializer(librdf_serializer *I<serializer>) =item int librdf_serializer_serialize_model(librdf_serializer* I<serializer>, FILE* I<handle>, librdf_uri* I<base_uri>, librdf_model* I<model>) =item int librdf_serializer_serialize_model_to_file(librdf_serializer* I<serializer>, const char *I<name>, librdf_uri* I<base_uri>, librdf_model* I<model>) =item void librdf_serializer_set_error(librdf_serializer* I<serializer>, void *I<user_data>, void (*I<error_fn>)(void *user_data, const char *msg, ...)) =item void librdf_serializer_set_warning(librdf_serializer* I<serializer>, void *I<user_data>, void (*I<warning_fn>)(void *user_data, const char *msg, ...)) =item librdf_node* librdf_serializer_get_feature(librdf_serializer* I<serializer>, librdf_uri* I<feature>) =item int librdf_serializer_set_feature(librdf_serializer* I<serializer>, librdf_uri* I<feature>, librdf_node* I<value>)b =item int librdf_serializer_set_namespace(librdf_serializer* I<serializer>, librdf_uri* I<uri>, const char* I<prefix>) =back =head2 class stream =over 4 =item librdf_stream* B<librdf_new_stream>(librdf_world* I<world>, void* I<context>, int (*I<end_of_stream>)(void*), librdf_statement* (*I<next_statement>)(void*), void (*I<finished>)(void*)) =item librdf_stream* B<librdf_new_stream_from_node_iterator>(librdf_iterator* I<iterator>, librdf_statement* I<statement>, librdf_statement_part I<field>) =item void B<librdf_free_stream>(librdf_stream* I<stream>) =item int B<librdf_stream_end>(librdf_stream* I<stream>) =item int B<librdf_stream_next>(librdf_stream* I<stream>) =item librdf_statement* B<librdf_stream_get_object>(librdf_stream* I<stream>) =item void* B<librdf_stream_get_context>(librdf_stream* I<stream>) =item void B<librdf_stream_set_map>(librdf_stream* I<stream>, librdf_statement* (*I<map>)(void* I<context>, librdf_statement* I<statement>), void* I<map_context>) =item void B<librdf_stream_print>(librdf_stream* I<stream>, FILE* I<fh>) =back =head1 EXAMPLES #include <redland.h> librdf_storage *storage; librdf_model* model; librdf_statement* statement; librdf_world* world world=librdf_new_world(); librdf_world_open(world); storage=librdf_new_storage(world, "hashes", "test", "hash-type='bdb',dir='.'"); model=librdf_new_model(world, storage, NULL); statement=librdf_new_statement_from_nodes(world, librdf_new_node_from_uri_string(world, "http://purl.org/net/dajobe/"), librdf_new_node_from_uri_string(world, "http://purl.org/dc/elements/1.1/creator"), librdf_new_node_from_literal(world, "Dave Beckett", NULL, 0)); librdf_model_add_statement(model, statement); librdf_free_statement(statement); librdf_model_print(model, stdout); librdf_free_model(model); librdf_free_storage(storage); librdf_free_world(world); =head1 SEE ALSO libraptor(3), libxml(4). =head1 HISTORY The B<redland> RDF library was created by Dave Beckett in June 2000. =head1 AUTHOR Dave Beckett L<http://purl.org/net/dajobe/>, =cut
Distrotech/librdf
docs/redland.pod
Perl
gpl-2.0
24,353
<!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_19) on Wed Dec 29 21:55:10 EST 2010 --> <TITLE> context.apps.demos.accelerometer </TITLE> <META NAME="date" CONTENT="2010-12-29"> <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="context.apps.demos.accelerometer"; } } </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="#FFFFFF" CLASS="NavBarCell1Rev"> &nbsp;<FONT CLASS="NavBarFont1Rev"><B>Package</B></FONT>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <FONT CLASS="NavBarFont1">Class</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> </EM> </TD> </TR> <TR> <TD BGCOLOR="white" CLASS="NavBarCell2"><FONT SIZE="-2"> &nbsp;<A HREF="../../../../context/apps/demos/package-summary.html"><B>PREV PACKAGE</B></A>&nbsp; &nbsp;<A HREF="../../../../context/apps/demos/helloroom/package-summary.html"><B>NEXT PACKAGE</B></A></FONT></TD> <TD BGCOLOR="white" CLASS="NavBarCell2"><FONT SIZE="-2"> <A HREF="../../../../index.html?context/apps/demos/accelerometer/package-summary.html" target="_top"><B>FRAMES</B></A> &nbsp; &nbsp;<A HREF="package-summary.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> <H2> Package context.apps.demos.accelerometer </H2> <map id="APIVIZ" name="APIVIZ"> <area shape="rect" id="node1" href="AccelerometerApplication.html" title="AccelerometerApplication" alt="" coords="275,539,445,567"/> <area shape="rect" id="node2" href="AccelerometerDataConverter.html" title="AccelerometerDataConverter" alt="" coords="32,402,219,430"/> <area shape="rect" id="node3" href="AccelerometerEnactor.html" title="AccelerometerEnactor" alt="" coords="285,342,435,370"/> <area shape="rect" id="node4" href="AccelerometerGenerator.html" title="AccelerometerGenerator" alt="" coords="279,273,441,301"/> <area shape="rect" id="node5" href="AccelerometerModel.html" title="AccelerometerModel" alt="" coords="55,213,196,241"/> <area shape="rect" id="node6" href="AccelerometerWidget.html" title="AccelerometerWidget" alt="" coords="287,153,433,181"/> <area shape="rect" id="node7" href="../../../arch/enactor/ClassifierEnactor.html" title="ClassifierEnactor (context.arch.enactor)" alt="" coords="51,333,200,379"/> <area shape="rect" id="node8" href="../../../arch/widget/ClassifierWidget.html" title="ClassifierWidget (context.arch.widget)" alt="" coords="55,144,196,189"/> <area shape="rect" id="node9" href="../../../arch/enactor/Generator.html" title="Generator (context.arch.enactor)" alt="" coords="51,264,200,309"/> <area shape="rect" id="node10" title="JFrame (javax.swing)" alt="" coords="77,453,173,499"/> <area shape="rect" id="node11" href="MotionPresenter.html" title="MotionPresenter" alt="" coords="301,83,419,111"/> <area shape="rect" id="node12" href="MotionWidget.html" title="MotionWidget" alt="" coords="309,14,411,42"/> <area shape="rect" id="node13" href="../../../arch/intelligibility/presenters/TypePanelPresenter.html" title="TypePanelPresenter (context.arch.intelligibility.presenters)" alt="" coords="7,75,244,120"/> <area shape="rect" id="node14" href="../../../arch/widget/Widget.html" title="Widget (context.arch.widget)" alt="" coords="55,5,196,51"/> <area shape="rect" id="node15" href="../../../arch/enactor/EnactorListener.html" title="&#171;interface&#187; EnactorListener (context.arch.enactor)" alt="" coords="51,522,200,585"/> <area shape="rect" id="node16" href="../../../arch/intelligibility/query/QueryListener.html" title="&#171;interface&#187; QueryListener (context.arch.intelligibility.query)" alt="" coords="21,607,229,670"/> </map> <CENTER><IMG SRC="package-summary.png" USEMAP="#APIVIZ" BORDER="0"></CENTER> <BR> <TABLE BORDER="1" WIDTH="100%" CELLPADDING="3" CELLSPACING="0" SUMMARY=""> <TR BGCOLOR="#CCCCFF" CLASS="TableHeadingColor"> <TH ALIGN="left" COLSPAN="2"><FONT SIZE="+2"> <B>Class Summary</B></FONT></TH> </TR> <TR BGCOLOR="white" CLASS="TableRowColor"> <TD WIDTH="15%"><B><A HREF="../../../../context/apps/demos/accelerometer/AccelerometerApplication.html" title="class in context.apps.demos.accelerometer">AccelerometerApplication</A></B></TD> <TD> Main class for running the Mobile Phone Activity Recognition application.</TD> </TR> <TR BGCOLOR="white" CLASS="TableRowColor"> <TD WIDTH="15%"><B><A HREF="../../../../context/apps/demos/accelerometer/AccelerometerDataConverter.html" title="class in context.apps.demos.accelerometer">AccelerometerDataConverter</A></B></TD> <TD>Original Hashtable storage is of the model; counts of attributes at certain values.</TD> </TR> <TR BGCOLOR="white" CLASS="TableRowColor"> <TD WIDTH="15%"><B><A HREF="../../../../context/apps/demos/accelerometer/AccelerometerEnactor.html" title="class in context.apps.demos.accelerometer">AccelerometerEnactor</A></B></TD> <TD>&nbsp;</TD> </TR> <TR BGCOLOR="white" CLASS="TableRowColor"> <TD WIDTH="15%"><B><A HREF="../../../../context/apps/demos/accelerometer/AccelerometerGenerator.html" title="class in context.apps.demos.accelerometer">AccelerometerGenerator</A></B></TD> <TD>&nbsp;</TD> </TR> <TR BGCOLOR="white" CLASS="TableRowColor"> <TD WIDTH="15%"><B><A HREF="../../../../context/apps/demos/accelerometer/AccelerometerModel.html" title="class in context.apps.demos.accelerometer">AccelerometerModel</A></B></TD> <TD>&nbsp;</TD> </TR> <TR BGCOLOR="white" CLASS="TableRowColor"> <TD WIDTH="15%"><B><A HREF="../../../../context/apps/demos/accelerometer/AccelerometerWidget.html" title="class in context.apps.demos.accelerometer">AccelerometerWidget</A></B></TD> <TD>&nbsp;</TD> </TR> <TR BGCOLOR="white" CLASS="TableRowColor"> <TD WIDTH="15%"><B><A HREF="../../../../context/apps/demos/accelerometer/MotionPresenter.html" title="class in context.apps.demos.accelerometer">MotionPresenter</A></B></TD> <TD>&nbsp;</TD> </TR> <TR BGCOLOR="white" CLASS="TableRowColor"> <TD WIDTH="15%"><B><A HREF="../../../../context/apps/demos/accelerometer/MotionWidget.html" title="class in context.apps.demos.accelerometer">MotionWidget</A></B></TD> <TD>&nbsp;</TD> </TR> </TABLE> &nbsp; <P> <DL> </DL> <HR> <!-- ======= START OF BOTTOM NAVBAR ====== --> <A NAME="navbar_bottom"><!-- --></A> <A HREF="#skip-navbar_bottom" title="Skip navigation links"></A> <TABLE BORDER="0" WIDTH="100%" CELLPADDING="1" CELLSPACING="0" SUMMARY=""> <TR> <TD COLSPAN=2 BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A NAME="navbar_bottom_firstrow"><!-- --></A> <TABLE BORDER="0" CELLPADDING="0" CELLSPACING="3" SUMMARY=""> <TR ALIGN="center" VALIGN="top"> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../overview-summary.html"><FONT CLASS="NavBarFont1"><B>Overview</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#FFFFFF" CLASS="NavBarCell1Rev"> &nbsp;<FONT CLASS="NavBarFont1Rev"><B>Package</B></FONT>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <FONT CLASS="NavBarFont1">Class</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> </EM> </TD> </TR> <TR> <TD BGCOLOR="white" CLASS="NavBarCell2"><FONT SIZE="-2"> &nbsp;<A HREF="../../../../context/apps/demos/package-summary.html"><B>PREV PACKAGE</B></A>&nbsp; &nbsp;<A HREF="../../../../context/apps/demos/helloroom/package-summary.html"><B>NEXT PACKAGE</B></A></FONT></TD> <TD BGCOLOR="white" CLASS="NavBarCell2"><FONT SIZE="-2"> <A HREF="../../../../index.html?context/apps/demos/accelerometer/package-summary.html" target="_top"><B>FRAMES</B></A> &nbsp; &nbsp;<A HREF="package-summary.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> </BODY> </HTML>
MaryVin/contexttoolkit
docs/apidoc/context/apps/demos/accelerometer/package-summary.html
HTML
gpl-3.0
10,531
/* * Copyright (c) 2002-2008 LWJGL Project * 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 of 'LWJGL' 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. */ package org.lwjgl.opengl; import org.lwjgl.util.generator.Reuse; import org.lwjgl.util.generator.opengl.GLenum; import org.lwjgl.util.generator.opengl.GLuint; public interface EXT_texture_array { /** * Accepted by the &lt;target&gt; parameter of TexParameteri, TexParameteriv, * TexParameterf, TexParameterfv, and BindTexture: */ int GL_TEXTURE_1D_ARRAY_EXT = 0x8C18; int GL_TEXTURE_2D_ARRAY_EXT = 0x8C1A; /** * Accepted by the &lt;target&gt; parameter of TexImage3D, TexSubImage3D, * CopyTexSubImage3D, CompressedTexImage3D, and CompressedTexSubImage3D: */ int GL_PROXY_TEXTURE_2D_ARRAY_EXT = 0x8C1B; /** * Accepted by the &lt;target&gt; parameter of TexImage2D, TexSubImage2D, * CopyTexImage2D, CopyTexSubImage2D, CompressedTexImage2D, and * CompressedTexSubImage2D: */ int GL_PROXY_TEXTURE_1D_ARRAY_EXT = 0x8C19; /** * Accepted by the &lt;pname&gt; parameter of GetBooleanv, GetDoublev, GetIntegerv * and GetFloatv: */ int GL_TEXTURE_BINDING_1D_ARRAY_EXT = 0x8C1C; int GL_TEXTURE_BINDING_2D_ARRAY_EXT = 0x8C1D; int GL_MAX_ARRAY_TEXTURE_LAYERS_EXT = 0x88FF; /** * Accepted by the &lt;param&gt; parameter of TexParameterf, TexParameteri, * TexParameterfv, and TexParameteriv when the &lt;pname&gt; parameter is * TEXTURE_COMPARE_MODE_ARB: */ int GL_COMPARE_REF_DEPTH_TO_TEXTURE_EXT = 0x884E; /** * Accepted by the &lt;pname&gt; parameter of * GetFramebufferAttachmentParameterivEXT: */ int GL_FRAMEBUFFER_ATTACHMENT_TEXTURE_LAYER_EXT = 0x8CD4; /** Returned by the &lt;type&gt; parameter of GetActiveUniform: */ int GL_SAMPLER_1D_ARRAY_EXT = 0x8DC0; int GL_SAMPLER_2D_ARRAY_EXT = 0x8DC1; int GL_SAMPLER_1D_ARRAY_SHADOW_EXT = 0x8DC3; int GL_SAMPLER_2D_ARRAY_SHADOW_EXT = 0x8DC4; @Reuse("EXTGeometryShader4") void glFramebufferTextureLayerEXT(@GLenum int target, @GLenum int attachment, @GLuint int texture, int level, int layer); }
kevinwang/minecarft
lwjgl-source-2.8.2/src/templates/org/lwjgl/opengl/EXT_texture_array.java
Java
gpl-3.0
3,473
<?php $L['Password_Title'] = 'Password policies'; $L['Password_Description'] = 'Change password policies'; $L['Password_Tags'] = 'strong password policy policies expiration age'; $L['Users_label'] = 'Strong password policy for Users'; $L['Admin_label'] = 'Strong password policy for Admin'; $L['PassExpires_label'] = 'Password Expiration for Users'; $L['Maximum password age (${0})'] = 'The Maximum Password Age (${0})'; $L['Minimum password age (${0})'] = 'The Minimum Password Age (${0})'; $L['Number of days to sent a warning (${0})'] = 'The number of days before sending a reminder (${0})';
DavidePrincipi/nethserver-sssd
root/usr/share/nethesis/NethServer/Language/en/NethServer_Module_Password.php
PHP
gpl-3.0
595
/**************************************************************************** ** ** Copyright (C) 2016 The Qt Company Ltd. ** Contact: https://www.qt.io/licensing/ ** ** This file is part of the QtQuick module of the Qt Toolkit. ** ** $QT_BEGIN_LICENSE:LGPL$ ** Commercial License Usage ** Licensees holding valid commercial Qt licenses may use this file in ** accordance with the commercial license agreement provided with the ** Software or, alternatively, in accordance with the terms contained in ** a written agreement between you and The Qt Company. For licensing terms ** and conditions see https://www.qt.io/terms-conditions. For further ** information use the contact form at https://www.qt.io/contact-us. ** ** GNU Lesser General Public License Usage ** Alternatively, this file may be used under the terms of the GNU Lesser ** General Public License version 3 as published by the Free Software ** Foundation and appearing in the file LICENSE.LGPL3 included in the ** packaging of this file. Please review the following information to ** ensure the GNU Lesser General Public License version 3 requirements ** will be met: https://www.gnu.org/licenses/lgpl-3.0.html. ** ** GNU General Public License Usage ** Alternatively, this file may be used under the terms of the GNU ** General Public License version 2.0 or (at your option) the GNU General ** Public license version 3 or any later version approved by the KDE Free ** Qt Foundation. The licenses are as published by the Free Software ** Foundation and appearing in the file LICENSE.GPL2 and LICENSE.GPL3 ** included in the packaging of this file. Please review the following ** information to ensure the GNU General Public License requirements will ** be met: https://www.gnu.org/licenses/gpl-2.0.html and ** https://www.gnu.org/licenses/gpl-3.0.html. ** ** $QT_END_LICENSE$ ** ****************************************************************************/ #ifndef QQUICKRECTANGLE_P_P_H #define QQUICKRECTANGLE_P_P_H // // W A R N I N G // ------------- // // This file is not part of the Qt API. It exists purely as an // implementation detail. This header file may change from version to // version without notice, or even be removed. // // We mean it. // #include "qquickitem_p.h" #include <QtCore/qmetaobject.h> QT_BEGIN_NAMESPACE class QQuickGradient; class QQuickRectangle; class QQuickRectanglePrivate : public QQuickItemPrivate { Q_DECLARE_PUBLIC(QQuickRectangle) public: QQuickRectanglePrivate() : color(Qt::white), gradient(0), pen(0), radius(0) { } ~QQuickRectanglePrivate() { delete pen; } QColor color; QQuickGradient *gradient; QQuickPen *pen; qreal radius; static int doUpdateSlotIdx; QQuickPen *getPen() { if (!pen) { Q_Q(QQuickRectangle); pen = new QQuickPen; static int penChangedSignalIdx = -1; if (penChangedSignalIdx < 0) penChangedSignalIdx = QMetaMethod::fromSignal(&QQuickPen::penChanged).methodIndex(); if (doUpdateSlotIdx < 0) doUpdateSlotIdx = QQuickRectangle::staticMetaObject.indexOfSlot("doUpdate()"); QMetaObject::connect(pen, penChangedSignalIdx, q, doUpdateSlotIdx); } return pen; } }; QT_END_NAMESPACE #endif // QQUICKRECTANGLE_P_P_H
geminy/aidear
oss/qt/qt-everywhere-opensource-src-5.9.0/qtdeclarative/src/quick/items/qquickrectangle_p_p.h
C
gpl-3.0
3,343
/*---------------------------------------------------------------------------*\ ========= | \\ / F ield | OpenFOAM: The Open Source CFD Toolbox \\ / O peration | \\ / A nd | Copyright (C) 2013-2015 OpenFOAM Foundation \\/ M anipulation | ------------------------------------------------------------------------------- License This file is part of OpenFOAM. OpenFOAM 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. OpenFOAM 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 OpenFOAM. If not, see <http://www.gnu.org/licenses/>. \*---------------------------------------------------------------------------*/ #include "IATE.H" #include "IATEsource.H" #include "fvmDdt.H" #include "fvmDiv.H" #include "fvmSup.H" #include "fvcDdt.H" #include "fvcDiv.H" #include "fvcAverage.H" #include "fvOptionList.H" #include "mathematicalConstants.H" #include "fundamentalConstants.H" #include "addToRunTimeSelectionTable.H" // * * * * * * * * * * * * * * Static Data Members * * * * * * * * * * * * * // namespace Foam { namespace diameterModels { defineTypeNameAndDebug(IATE, 0); addToRunTimeSelectionTable ( diameterModel, IATE, dictionary ); } } // * * * * * * * * * * * * * * * * Constructors * * * * * * * * * * * * * * // Foam::diameterModels::IATE::IATE ( const dictionary& diameterProperties, const phaseModel& phase ) : diameterModel(diameterProperties, phase), kappai_ ( IOobject ( IOobject::groupName("kappai", phase.name()), phase_.time().timeName(), phase_.mesh(), IOobject::MUST_READ, IOobject::AUTO_WRITE ), phase_.mesh() ), dMax_("dMax", dimLength, diameterProperties_), dMin_("dMin", dimLength, diameterProperties_), residualAlpha_ ( "residualAlpha", dimless, diameterProperties_ ), d_ ( IOobject ( IOobject::groupName("d", phase.name()), phase_.time().timeName(), phase_.mesh(), IOobject::NO_READ, IOobject::AUTO_WRITE ), dsm() ), sources_ ( diameterProperties_.lookup("sources"), IATEsource::iNew(*this) ) {} // * * * * * * * * * * * * * * * * Destructor * * * * * * * * * * * * * * * // Foam::diameterModels::IATE::~IATE() {} // * * * * * * * * * * * * * * * Member Functions * * * * * * * * * * * * * // Foam::tmp<Foam::volScalarField> Foam::diameterModels::IATE::dsm() const { return max(6/max(kappai_, 6/dMax_), dMin_); } // Placeholder for the nucleation/condensation model // Foam::tmp<Foam::volScalarField> Foam::diameterModels::IATE::Rph() const // { // const volScalarField& T = phase_thermo().T(); // const volScalarField& p = phase_.p(); // // scalar A, B, C, sigma, vm, Rph; // // volScalarField ps(1e5*pow(10, A - B/(T + C))); // volScalarField Dbc // ( // 4*sigma*vm/(constant::physicoChemical::k*T*log(p/ps)) // ); // // return constant::mathematical::pi*sqr(Dbc)*Rph; // } void Foam::diameterModels::IATE::correct() { // Initialise the accumulated source term to the dilatation effect volScalarField R ( ( (1.0/3.0) /max ( fvc::average(phase_ + phase_.oldTime()), residualAlpha_ ) ) *(fvc::ddt(phase_) + fvc::div(phase_.alphaPhi())) ); // Accumulate the run-time selectable sources forAll(sources_, j) { R -= sources_[j].R(); } // const_cast needed because the operators and functions of fvOptions // are currently non-const. fv::optionList& fvOptions = const_cast<fv::optionList&> ( phase_.mesh().lookupObject<fv::optionList>("fvOptions") ); // Construct the interfacial curvature equation fvScalarMatrix kappaiEqn ( fvm::ddt(kappai_) + fvm::div(phase_.phi(), kappai_) - fvm::Sp(fvc::div(phase_.phi()), kappai_) == - fvm::SuSp(R, kappai_) //+ Rph() // Omit the nucleation/condensation term + fvOptions(kappai_) ); kappaiEqn.relax(); fvOptions.constrain(kappaiEqn); kappaiEqn.solve(); // Update the Sauter-mean diameter d_ = dsm(); } bool Foam::diameterModels::IATE::read(const dictionary& phaseProperties) { diameterModel::read(phaseProperties); diameterProperties_.lookup("dMax") >> dMax_; diameterProperties_.lookup("dMin") >> dMin_; // Re-create all the sources updating number, type and coefficients PtrList<IATEsource> ( diameterProperties_.lookup("sources"), IATEsource::iNew(*this) ).transfer(sources_); return true; } // ************************************************************************* //
OpenFOAM/OpenFOAM-3.0.x
applications/solvers/multiphase/reactingEulerFoam/reactingTwoPhaseEulerFoam/twoPhaseSystem/diameterModels/IATE/IATE.C
C++
gpl-3.0
5,373
using SmartStore.Web.Framework.Mvc; namespace SmartStore.Web.Models.Common { public partial class MenuModel : ModelBase { public bool BlogEnabled { get; set; } public bool RecentlyAddedProductsEnabled { get; set; } public bool ForumEnabled { get; set; } public bool AllowPrivateMessages { get; set; } public int UnreadPrivateMessages { get; set; } public bool IsAuthenticated { get; set; } public bool DisplayAdminLink { get; set; } public bool IsCustomerImpersonated { get; set; } public string CustomerEmailUsername { get; set; } } }
sashabuka/smartshop
src/Presentation/SmartStore.Web/Models/Common/MenuModel.cs
C#
gpl-3.0
625
import unittest from circular_buffer import ( CircularBuffer, BufferFullException, BufferEmptyException ) class CircularBufferTest(unittest.TestCase): def test_read_empty_buffer(self): buf = CircularBuffer(1) with self.assertRaises(BufferEmptyException): buf.read() def test_write_and_read_back_one_item(self): buf = CircularBuffer(1) buf.write('1') self.assertEqual('1', buf.read()) with self.assertRaises(BufferEmptyException): buf.read() def test_write_and_read_back_multiple_items(self): buf = CircularBuffer(2) buf.write('1') buf.write('2') self.assertEqual('1', buf.read()) self.assertEqual('2', buf.read()) with self.assertRaises(BufferEmptyException): buf.read() def test_clearing_buffer(self): buf = CircularBuffer(3) for c in '123': buf.write(c) buf.clear() with self.assertRaises(BufferEmptyException): buf.read() buf.write('1') buf.write('2') self.assertEqual('1', buf.read()) buf.write('3') self.assertEqual('2', buf.read()) def test_alternate_write_and_read(self): buf = CircularBuffer(2) buf.write('1') self.assertEqual('1', buf.read()) buf.write('2') self.assertEqual('2', buf.read()) def test_read_back_oldest_item(self): buf = CircularBuffer(3) buf.write('1') buf.write('2') buf.read() buf.write('3') buf.read() self.assertEqual('3', buf.read()) def test_write_full_buffer(self): buf = CircularBuffer(2) buf.write('1') buf.write('2') with self.assertRaises(BufferFullException): buf.write('A') def test_overwrite_full_buffer(self): buf = CircularBuffer(2) buf.write('1') buf.write('2') buf.overwrite('A') self.assertEqual('2', buf.read()) self.assertEqual('A', buf.read()) with self.assertRaises(BufferEmptyException): buf.read() def test_overwrite_non_full_buffer(self): buf = CircularBuffer(2) buf.overwrite('1') buf.overwrite('2') self.assertEqual('1', buf.read()) self.assertEqual('2', buf.read()) with self.assertRaises(BufferEmptyException): buf.read() def test_alternate_read_and_overwrite(self): buf = CircularBuffer(5) for c in '123': buf.write(c) buf.read() buf.read() buf.write('4') buf.read() for c in '5678': buf.write(c) buf.overwrite('A') buf.overwrite('B') self.assertEqual('6', buf.read()) self.assertEqual('7', buf.read()) self.assertEqual('8', buf.read()) self.assertEqual('A', buf.read()) self.assertEqual('B', buf.read()) with self.assertRaises(BufferEmptyException): buf.read() if __name__ == '__main__': unittest.main()
GregMilway/Exercism
python/circular-buffer/circular_buffer_test.py
Python
gpl-3.0
3,084
# 由 product_owner 組員40223131所寫的考試報告 協同考試流程的規劃: 1.了解齒輪和嚙合程式 2.每個組員建立一個齒輪之齒數表單 3.每個組員輸入齒輪表單時,各組員的齒輪都能嚙合(總共七顆齒輪) 4.寫新得報告,交給組員05號,做統整並將資料 pandoc 產生pdf 與 html
40223102/2015cd_midterm
product_owner.md
Markdown
gpl-3.0
344
<?php /* * This file is part of Phraseanet * * (c) 2005-2016 Alchemy * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ use Alchemy\Phrasea\Model\Entities\User; class eventsmanager_notify_feed extends eventsmanager_notifyAbstract { /** * * @return string */ public function icon_url() { return '/assets/common/images/icons/rss16.png'; } /** * * @param Array $datas * @param boolean $unread * @return Array */ public function datas(array $data, $unread) { $entry = $this->app['repo.feed-entries']->find($data['entry_id']); if (null === $entry) { return []; } $ret = [ 'text' => $this->app->trans('%user% has published %title%', ['%user%' => $entry->getAuthorName(), '%title%' => '<a href="/lightbox/feeds/entry/' . $entry->getId() . '/" target="_blank">' . $entry->getTitle() . '</a>']) , 'class' => ($unread == 1 ? 'reload_baskets' : '') ]; return $ret; } /** * * @return string */ public function get_name() { return $this->app->trans('Feeds'); } /** * * @return string */ public function get_description() { return $this->app->trans('Receive notification when a publication is available'); } /** * @param integer $usr_id The id of the user to check * * @return boolean */ public function is_available(User $user) { return true; } }
aztech-dev/Phraseanet
lib/classes/eventsmanager/notify/feed.php
PHP
gpl-3.0
1,621
// Copyright (C) 2013 Patryk Nadrowski // Heavily based on the OpenGL driver implemented by Nikolaus Gebhardt // OpenGL ES driver implemented by Christian Stehno and first OpenGL ES 2.0 // driver implemented by Amundis. // This file is part of the "Irrlicht Engine". // For conditions of distribution and use, see copyright notice in Irrlicht.h #ifndef __C_OGLES2_SL_MATERIAL_RENDERER_H_INCLUDED__ #define __C_OGLES2_SL_MATERIAL_RENDERER_H_INCLUDED__ #include "IrrCompileConfig.h" #ifdef _IRR_COMPILE_WITH_OGLES2_ #if defined(_IRR_COMPILE_WITH_IPHONE_DEVICE_) #include <OpenGLES/ES2/gl.h> #include <OpenGLES/ES2/glext.h> #else #include <GLES2/gl2.h> #include <EGL/eglplatform.h> #endif #include "EMaterialTypes.h" #include "EVertexAttributes.h" #include "IMaterialRenderer.h" #include "IMaterialRendererServices.h" #include "IGPUProgrammingServices.h" #include "IShaderConstantSetCallBack.h" #include "irrArray.h" #include "irrString.h" namespace irr { namespace video { class COGLES2Driver; //! Class for using GLSL shaders with OpenGL ES 2.0 //! Please note: This renderer implements its own IMaterialRendererServices class COGLES2MaterialRenderer : public IMaterialRenderer, public IMaterialRendererServices { public: //! Constructor COGLES2MaterialRenderer( COGLES2Driver* driver, s32& outMaterialTypeNr, const c8* vertexShaderProgram = 0, const c8* pixelShaderProgram = 0, IShaderConstantSetCallBack* callback = 0, E_MATERIAL_TYPE baseMaterial = EMT_SOLID, s32 userData = 0); //! Destructor virtual ~COGLES2MaterialRenderer(); GLuint getProgram() const; virtual void OnSetMaterial(const SMaterial& material, const SMaterial& lastMaterial, bool resetAllRenderstates, IMaterialRendererServices* services); virtual bool OnRender(IMaterialRendererServices* service, E_VERTEX_TYPE vtxtype); virtual void OnUnsetMaterial(); //! Returns if the material is transparent. virtual bool isTransparent() const; // implementations for the render services virtual void setBasicRenderStates(const SMaterial& material, const SMaterial& lastMaterial, bool resetAllRenderstates); virtual s32 getVertexShaderConstantID(const c8* name); virtual s32 getPixelShaderConstantID(const c8* name); virtual void setVertexShaderConstant(const f32* data, s32 startRegister, s32 constantAmount=1); virtual void setPixelShaderConstant(const f32* data, s32 startRegister, s32 constantAmount=1); virtual bool setVertexShaderConstant(s32 index, const f32* floats, int count); virtual bool setVertexShaderConstant(s32 index, const s32* ints, int count); virtual bool setPixelShaderConstant(s32 index, const f32* floats, int count); virtual bool setPixelShaderConstant(s32 index, const s32* ints, int count); virtual IVideoDriver* getVideoDriver(); protected: //! constructor only for use by derived classes who want to //! create a fall back material for example. COGLES2MaterialRenderer(COGLES2Driver* driver, IShaderConstantSetCallBack* callback = 0, E_MATERIAL_TYPE baseMaterial = EMT_SOLID, s32 userData = 0); void init(s32& outMaterialTypeNr, const c8* vertexShaderProgram, const c8* pixelShaderProgram, bool addMaterial = true); bool createShader(GLenum shaderType, const char* shader); bool linkProgram(); COGLES2Driver* Driver; IShaderConstantSetCallBack* CallBack; bool Alpha; bool Blending; bool FixedBlending; struct SUniformInfo { core::stringc name; GLenum type; GLint location; }; GLuint Program; core::array<SUniformInfo> UniformInfo; s32 UserData; }; } // end namespace video } // end namespace irr #endif // compile with OpenGL ES 2.0 #endif // if included
nado/stk-code
lib/irrlicht/source/Irrlicht/COGLES2MaterialRenderer.h
C
gpl-3.0
3,768
// Copyright (c) 2018 Dr. Colin Hirsch and Daniel Frey // Please see LICENSE for license or visit https://github.com/taocpp/PEGTL/ #ifndef TAO_PEGTL_INTERNAL_THREE_HPP #define TAO_PEGTL_INTERNAL_THREE_HPP #include <utility> #include "../config.hpp" #include "bump_help.hpp" #include "result_on_found.hpp" #include "skip_control.hpp" #include "../analysis/generic.hpp" namespace tao { namespace TAO_PEGTL_NAMESPACE { namespace internal { template< char C > struct three { using analyze_t = analysis::generic< analysis::rule_type::ANY >; template< typename Input > static bool match( Input& in ) noexcept( noexcept( in.size( 3 ) ) ) { if( in.size( 3 ) >= 3 ) { if( ( in.peek_char( 0 ) == C ) && ( in.peek_char( 1 ) == C ) && ( in.peek_char( 2 ) == C ) ) { bump_help< result_on_found::SUCCESS, Input, char, C >( in, 3 ); return true; } } return false; } }; template< char C > struct skip_control< three< C > > : std::true_type { }; } // namespace internal } // namespace TAO_PEGTL_NAMESPACE } // namespace tao #endif
Tsung-Wei/OpenTimer
ot/parser-spef/pegtl/pegtl/internal/three.hpp
C++
gpl-3.0
1,311
<?php /* Copyright (C) 2001-2004 Rodolphe Quiedeville <rodolphe@quiedeville.org> * Copyright (C) 2004-2008 Laurent Destailleur <eldy@users.sourceforge.net> * Copyright (C) 2005-2009 Regis Houssin <regis.houssin@capnetworks.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 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/>. */ /** * \file htdocs/product/stock/liste.php * \ingroup stock * \brief Page liste des stocks */ require '../../main.inc.php'; require_once DOL_DOCUMENT_ROOT.'/product/stock/class/entrepot.class.php'; $langs->load("stocks"); // Security check $result=restrictedArea($user,'stock'); $sref=GETPOST("sref");; $snom=GETPOST("snom"); $sall=GETPOST("sall"); $sortfield = GETPOST("sortfield"); $sortorder = GETPOST("sortorder"); if (! $sortfield) $sortfield="e.label"; if (! $sortorder) $sortorder="ASC"; $page = $_GET["page"]; if ($page < 0) $page = 0; $limit = $conf->liste_limit; $offset = $limit * $page; $sql = "SELECT e.rowid, e.label as ref, e.statut, e.lieu, e.address, e.zip, e.town, e.fk_pays"; $sql.= " FROM ".MAIN_DB_PREFIX."entrepot as e"; $sql.= " WHERE e.entity = ".$conf->entity; if ($sref) { $sql.= " AND e.label like '%".$db->escape($sref)."%'"; } if ($sall) { $sql.= " AND (e.description like '%".$db->escape($sall)."%' OR e.lieu like '%".$db->escape($sall)."%' OR e.address like '%".$db->escape($sall)."%' OR e.town like '%".$db->escape($sall)."%')"; } $sql.= $db->order($sortfield,$sortorder); $sql.= $db->plimit($limit+1, $offset); $result = $db->query($sql); if ($result) { $num = $db->num_rows($result); $i = 0; $help_url='EN:Module_Stocks_En|FR:Module_Stock|ES:M&oacute;dulo_Stocks'; llxHeader("",$langs->trans("ListOfWarehouses"),$help_url); print_barre_liste($langs->trans("ListOfWarehouses"), $page, "liste.php", "", $sortfield, $sortorder,'',$num); print '<table class="noborder" width="100%">'; print "<tr class=\"liste_titre\">"; print_liste_field_titre($langs->trans("Ref"),"liste.php", "e.label","","","",$sortfield,$sortorder); print_liste_field_titre($langs->trans("LocationSummary"),"liste.php", "e.lieu","","","",$sortfield,$sortorder); print_liste_field_titre($langs->trans("Status"),"liste.php", "e.statut",'','','align="right"',$sortfield,$sortorder); print "</tr>\n"; if ($num) { $entrepot=new Entrepot($db); $var=True; while ($i < min($num,$limit)) { $objp = $db->fetch_object($result); $var=!$var; print "<tr ".$bc[$var].">"; print '<td><a href="fiche.php?id='.$objp->rowid.'">'.img_object($langs->trans("ShowWarehouse"),'stock').' '.$objp->ref.'</a></td>'; print '<td>'.$objp->lieu.'</td>'; print '<td align="right">'.$entrepot->LibStatut($objp->statut,5).'</td>'; print "</tr>\n"; $i++; } } $db->free($result); print "</table>"; } else { dol_print_error($db); } $db->close(); llxFooter();
Agile-Team/fran
htdocs/product/stock/liste.php
PHP
gpl-3.0
3,429
# Copyright 2012 Google Inc. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # 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. """Commands for interacting with Google Compute Engine firewalls.""" import socket from google.apputils import appcommands import gflags as flags from gcutil_lib import command_base from gcutil_lib import gcutil_errors from gcutil_lib import utils FLAGS = flags.FLAGS class FirewallCommand(command_base.GoogleComputeCommand): """Base command for working with the firewalls collection.""" print_spec = command_base.ResourcePrintSpec( summary=['name', 'network'], field_mappings=( ('name', 'name'), ('description', 'description'), ('network', 'network'), ('source-ips', 'sourceRanges'), ('source-tags', 'sourceTags'), ('target-tags', 'targetTags')), detail=( ('name', 'name'), ('description', 'description'), ('creation-time', 'creationTimestamp'), ('network', 'network'), ('source-ips', 'sourceRanges'), ('source-tags', 'sourceTags'), ('target-tags', 'targetTags')), sort_by='name') resource_collection_name = 'firewalls' def __init__(self, name, flag_values): super(FirewallCommand, self).__init__(name, flag_values) def GetDetailRow(self, result): """Returns an associative list of items for display in a detail table. Args: result: A dict returned by the server. Returns: A list. """ data = [] # Add the rules for allowed in result.get('allowed', []): as_string = str(allowed['IPProtocol']) if allowed.get('ports'): as_string += ': %s' % ', '.join(allowed['ports']) data.append(('allowed', as_string)) return data class FirewallRules(object): """Class representing the list of a firewall's rules. This class is only used for parsing a firewall from command-line flags, for printing the firewall, we simply dump the JSON. """ @staticmethod def ParsePortSpecs(port_spec_strings): """Parse the port-specification portion of firewall rules. This takes the value of the 'allowed' flag and builds the corresponding firewall rules, excluding the 'source' fields. Args: port_spec_strings: A list of strings specifying the port-specific components of a firewall rule. These are of the form "(<protocol>)?(:<port>('-'<port>)?)?" Returns: A list of dict values containing a protocol string and a list of port range strings. This is a substructure of the firewall rule dictionaries, which additionally contain a 'source' field. Raises: ValueError: If any of the input strings are malformed. """ def _AddToPortSpecs(protocol, port_string, port_specs): """Ensure the specified rule for this protocol allows the given port(s). If there is no port_string specified it implies all ports are allowed, and whatever is in the port_specs map for that protocol get clobbered. This method also makes sure that any protocol entry without a ports member does not get further restricted. Args: protocol: The protocol under which the given port range is allowed. port_string: The string specification of what ports are allowed. port_specs: The mapping from protocols to firewall rules. """ port_spec_entry = port_specs.setdefault(protocol, {'IPProtocol': str(protocol), 'ports': []}) if 'ports' in port_spec_entry: # We only handle the 'then' case because in the other case the # existing entry already allows all ports. if not port_string: # A missing 'ports' field indicates all ports are allowed. port_spec_entry.pop('ports') else: port_spec_entry['ports'].append(port_string) port_specs = {} for port_spec_string in port_spec_strings: protocol = None port_string = None parts = port_spec_string.split(':') if len(parts) > 2: raise ValueError('Invalid allowed entry: %s' % port_spec_string) elif len(parts) == 2: if parts[0]: protocol = utils.ParseProtocol(parts[0]) port_string = utils.ReplacePortNames(parts[1]) else: protocol = utils.ParseProtocol(parts[0]) if protocol: _AddToPortSpecs(protocol, port_string, port_specs) else: # Add entries for both UPD and TCP _AddToPortSpecs(socket.getprotobyname('tcp'), port_string, port_specs) _AddToPortSpecs(socket.getprotobyname('udp'), port_string, port_specs) return port_specs.values() def __init__(self, allowed, allowed_ip_sources): self.port_specs = FirewallRules.ParsePortSpecs(allowed) self.source_ranges = allowed_ip_sources self.source_tags = [] self.target_tags = [] def SetTags(self, source_tags, target_tags): self.source_tags = sorted(set(source_tags)) self.target_tags = sorted(set(target_tags)) def AddToFirewall(self, firewall): if self.source_ranges: firewall['sourceRanges'] = self.source_ranges if self.source_tags: firewall['sourceTags'] = self.source_tags if self.target_tags: firewall['targetTags'] = self.target_tags firewall['allowed'] = self.port_specs class AddFirewall(FirewallCommand): """Create a new firewall rule to allow incoming traffic to a network.""" positional_args = '<firewall-name>' def __init__(self, name, flag_values): super(AddFirewall, self).__init__(name, flag_values) flags.DEFINE_string('description', '', 'An optional Firewall description.', flag_values=flag_values) flags.DEFINE_string('network', 'default', 'Specifies which network this firewall applies to.', flag_values=flag_values) flags.DEFINE_list('allowed', None, '[Required] Specifies a list of allowed ports for this ' 'firewall. Each entry must be a combination of the ' 'protocol and the port or port range in the following ' 'form: \'<protocol>:<port>-<port>\' or ' '\'<protocol>:<port>\'. To specify multiple ports, ' 'protocols, or ranges, provide them as comma' '-separated entries. For example: ' '\'--allowed=tcp:ssh,udp:5000-6000,tcp:80,icmp\'.', flag_values=flag_values) flags.DEFINE_list('allowed_ip_sources', [], 'Specifies a list of IP addresses that are allowed ' 'to talk to instances within the network, through the ' '<protocols>:<ports> described by the \'--allowed\' ' 'flag. If no IP or tag sources are listed, all sources ' 'will be allowed.', flag_values=flag_values) flags.DEFINE_list('allowed_tag_sources', [], 'Specifies a list of instance tags that are allowed to ' 'talk to instances within the network, through the ' '<protocols>:<ports> described by the \'--allowed\' ' 'flag. If specifying multiple tags, provide them as ' 'comma-separated entries. For example, ' '\'--allowed_tag_sources=www,database,frontend\'. ' 'If no tag or ip sources are listed, all sources will ' 'be allowed.', flag_values=flag_values) flags.DEFINE_list('target_tags', [], 'Specifies a set of tagged instances that this ' 'firewall applies to. To specify multiple tags, ' 'provide them as comma-separated entries. If no tags ' 'are listed, this firewall applies to all instances in ' 'the network.', flag_values=flag_values) def Handle(self, firewall_name): """Add the specified firewall. Args: firewall_name: The name of the firewall to add. Returns: The result of inserting the firewall. Raises: gcutil_errors.CommandError: If the passed flag values cannot be interpreted. """ if not self._flags.allowed: raise gcutil_errors.CommandError( 'You must specify at least one rule through --allowed.') firewall_context = self._context_parser.ParseContextOrPrompt('firewalls', firewall_name) firewall_resource = { 'kind': self._GetResourceApiKind('firewall'), 'name': firewall_context['firewall'], 'description': self._flags.description, } if self._flags.network is not None: firewall_resource['network'] = self._context_parser.NormalizeOrPrompt( 'networks', self._flags.network) if (not self._flags.allowed_ip_sources and not self._flags.allowed_tag_sources): self._flags.allowed_ip_sources.append('0.0.0.0/0') try: firewall_rules = FirewallRules(self._flags.allowed, self._flags.allowed_ip_sources) firewall_rules.SetTags(self._flags.allowed_tag_sources, self._flags.target_tags) firewall_rules.AddToFirewall(firewall_resource) firewall_request = self.api.firewalls.insert( project=firewall_context['project'], body=firewall_resource) return firewall_request.execute() except ValueError, e: raise gcutil_errors.CommandError(e) class GetFirewall(FirewallCommand): """Get a firewall.""" positional_args = '<firewall-name>' def __init__(self, name, flag_values): super(GetFirewall, self).__init__(name, flag_values) def Handle(self, firewall_name): """Get the specified firewall. Args: firewall_name: The name of the firewall to get. Returns: The result of getting the firewall. """ firewall_context = self._context_parser.ParseContextOrPrompt('firewalls', firewall_name) firewall_request = self.api.firewalls.get( project=firewall_context['project'], firewall=firewall_context['firewall']) return firewall_request.execute() class DeleteFirewall(FirewallCommand): """Delete one or more firewall rules. Specify multiple firewalls as multiple arguments. The firewalls will be deleted in parallel. """ positional_args = '<firewall-name-1> ... <firewall-name-n>' safety_prompt = 'Delete firewall' def __init__(self, name, flag_values): super(DeleteFirewall, self).__init__(name, flag_values) def Handle(self, *firewall_names): """Delete the specified firewall. Args: *firewall_names: The names of the firewalls to delete. Returns: Tuple (results, exceptions) - results of deleting the firewalls. """ requests = [] for name in firewall_names: firewall_context = self._context_parser.ParseContextOrPrompt('firewalls', name) requests.append(self.api.firewalls.delete( project=firewall_context['project'], firewall=firewall_context['firewall'])) results, exceptions = self.ExecuteRequests(requests) return (self.MakeListResult(results, 'operationList'), exceptions) class ListFirewalls(FirewallCommand, command_base.GoogleComputeListCommand): """List the firewall rules for a project.""" def ListFunc(self): """Returns the function for listing firewalls.""" return self.api.firewalls.list def AddCommands(): appcommands.AddCmd('addfirewall', AddFirewall) appcommands.AddCmd('getfirewall', GetFirewall) appcommands.AddCmd('deletefirewall', DeleteFirewall) appcommands.AddCmd('listfirewalls', ListFirewalls)
harshilasu/LinkurApp
y/google-cloud-sdk/platform/gcutil/lib/google_compute_engine/gcutil_lib/firewall_cmds.py
Python
gpl-3.0
12,747
/** * Marlin 3D Printer Firmware * Copyright (C) 2017 MarlinFirmware [https://github.com/MarlinFirmware/Marlin] * * Based on Sprinter and grbl. * Copyright (C) 2011 Camiel Gubbels / Erik van der Zalm * * 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/>. * */ /** * Anet V1.0 board pin assignments */ /** * Rev B 16 JUN 2017 * * 1) no longer uses Sanguino files to define some of the pins * 2) added pointers to useable Arduino IDE extensions * */ /** * The standard Arduino IDE extension (board manager) for this board * is located at https://github.com/SkyNet3D/anet-board. * * Installation instructions are on that page. * * After copying the files to the appropriate location, restart Arduino and * you'll see "Anet V1.0" and "Anet V1.0 (Optiboot)" in the boards list. * * "Anet V1.0" uses the bootloader that was installed on the board when * it shipped from the factory. * * "Anet V1.0 (Optiboot)" frees up another 3K of FLASH. You'll need to burn * a new bootloader to the board to be able to automatically download a * compiled image. * */ /** * Another usable Arduino IDE extension (board manager) can be found at * https://github.com/Lauszus/Sanguino * * This extension has been tested on Arduino 1.6.12 & 1.8.0 * * Here's the JSON path: * https://raw.githubusercontent.com/Lauszus/Sanguino/master/package_lauszus_sanguino_index.json * * When installing select 1.0.2 * * Installation instructions can be found at https://learn.sparkfun.com/pages/CustomBoardsArduino * Just use the above JSON URL instead of Sparkfun's JSON. * * Once installed select the Sanguino board and then select the CPU. * */ /** * To burn a new bootloader: * * 1. Connect your programmer to the board. * 2. In the Arduino IDE select the board and then select the programmer. * 3. In the Arduino IDE click on "burn bootloader". Don't worry about the "verify failed at 1F000" error message. * 4. The programmer is no longer needed. Remove it. */ /** * Additional info: * * Anet Schematics - https://github.com/ralf-e/ANET-3D-Board-V1.0 * Wiring RRDFG Smart Controller - http://www.thingiverse.com/thing:2103748 * SkyNet3D Anet software development - https://github.com/SkyNet3D/Marlin/ * Anet Users / Skynet SW on Facebook - https://www.facebook.com/skynet3ddevelopment/ * * Many thanks to Hans Raaf (@oderwat) for developing the Anet-specific software and supporting the Anet community. */ #ifndef __AVR_ATmega1284P__ #error "Oops! Make sure you have 'Anet V1.0', 'Anet V1.0 (Optiboot)' or 'Sanguino' selected from the 'Tools -> Boards' menu." #endif #ifndef BOARD_NAME #define BOARD_NAME "Anet" #endif #define LARGE_FLASH true // // Limit Switches // #define X_STOP_PIN 18 #define Y_STOP_PIN 19 #define Z_STOP_PIN 20 // // Steppers // #define X_STEP_PIN 15 #define X_DIR_PIN 21 #define X_ENABLE_PIN 14 #define Y_STEP_PIN 22 #define Y_DIR_PIN 23 #define Y_ENABLE_PIN 14 #define Z_STEP_PIN 3 #define Z_DIR_PIN 2 #define Z_ENABLE_PIN 26 #define E0_STEP_PIN 1 #define E0_DIR_PIN 0 #define E0_ENABLE_PIN 14 // // Temperature Sensors // #define TEMP_0_PIN 7 // Analog Input (pin 33 extruder) #define TEMP_BED_PIN 6 // Analog Input (pin 34 bed) // // Heaters / Fans // #define HEATER_0_PIN 13 // (extruder) #define HEATER_BED_PIN 12 // (bed) #define FAN_PIN 4 // // Misc. Functions // #define SDSS 31 #define LED_PIN -1 /** * LCD / Controller * * Only the following displays are supported: * ANET_KEYPAD_LCD * ANET_FULL_GRAPHICS_LCD * REPRAP_DISCOUNT_FULL_GRAPHIC_SMART_CONTROLLER */ #if ENABLED(ULTRA_LCD) && ENABLED(NEWPANEL) #define LCD_SDSS 28 #if ENABLED(ADC_KEYPAD) #define SERVO0_PIN 27 // free for BLTouch/3D-Touch #define LCD_PINS_RS 28 #define LCD_PINS_ENABLE 29 #define LCD_PINS_D4 10 #define LCD_PINS_D5 11 #define LCD_PINS_D6 16 #define LCD_PINS_D7 17 #define BTN_EN1 -1 #define BTN_EN2 -1 #define BTN_ENC -1 #define ADC_KEYPAD_PIN 1 #elif ENABLED(REPRAP_DISCOUNT_FULL_GRAPHIC_SMART_CONTROLLER) || ENABLED(ANET_FULL_GRAPHICS_LCD) // Pin definitions for the Anet A6 Full Graphics display and the RepRapDiscount Full Graphics // display using an adapter board // https://go.aisler.net/benlye/anet-lcd-adapter/pcb // See below for alternative pin definitions for use with https://www.thingiverse.com/thing:2103748 #define SERVO0_PIN 29 // free for BLTouch/3D-Touch #define BEEPER_PIN 17 #define LCD_PINS_RS 27 #define LCD_PINS_ENABLE 28 #define LCD_PINS_D4 30 #define BTN_EN1 11 #define BTN_EN2 10 #define BTN_ENC 16 #define ST7920_DELAY_1 DELAY_0_NOP #define ST7920_DELAY_2 DELAY_1_NOP #define ST7920_DELAY_3 DELAY_2_NOP #define STD_ENCODER_PULSES_PER_STEP 4 #define STD_ENCODER_STEPS_PER_MENU_ITEM 1 #endif #else #define SERVO0_PIN 27 #endif // ULTRA_LCD && NEWPANEL /** * ==================================================================== * =============== Alternative RepRapDiscount Wiring ================== * ==================================================================== * * An alternative wiring scheme for the RepRapDiscount Full Graphics Display is * published by oderwat on Thingiverse at https://www.thingiverse.com/thing:2103748. * * Using that adapter requires changing the pin definition as follows: * #define SERVO0_PIN 27 // free for BLTouch/3D-Touch * #define BEEPER_PIN 28 * #define LCD_PINS_RS 30 * #define LCD_PINS_ENABLE 29 * #define LCD_PINS_D4 17 * * The BLTouch pin becomes LCD:3 */ /** * ==================================================================== * ===================== LCD PINOUTS ================================== * ==================================================================== * * Anet V1.0 controller | ANET_KEYPAD_LCD | ANET_FULL_ | RepRapDiscount Full | Thingiverse RepRap wiring * physical logical alt | | GRAPHICS_LCD | Graphics Display Wiring | http://www.thingiverse * pin pin functions | | | | .com/thing:2103748 *------------------------------------------------------------------------------------------------------------------------ * ANET-J3.1 8 *** | N/A | J3_TX *** | | * ANET-J3.2 9 *** | N/A | J3_RX *** | | * ANET-J3.3 6 MISO | N/A | MISO *** | EXP2.1 MISO | EXP2.1 MISO * ANET-J3.4 +5V | N/A | +5V | | * ANET-J3.5 7 SCK | N/A | SCK *** | EXP2.2 SCK | EXP2.2 SCK * ANET-J3.6 5 MOSI | N/A | MOSI *** | EXP2.6 MOSI | EXP2.6 MOSI * ANET-J3.7 !RESET | N/A | button | EXP2.8 panel button | EXP2.8 panel button * ANET-J3.8 GND | N/A | GND | EXP2.9 GND | EXP2.9 GND * ANET-J3.9 4 Don't use | N/A | N/C | | * ANET-J3.10 +3.3V | N/A | +3.3V *** | | * | | | | * | | | | * ANET-LCD.1 GND | GND | GND | EXP1.9 GND | EXP1.9 GND * ANET-LCD.2 +5V | +5V | +5V | EXP1.10 +5V | EXP1.10 +5V * ANET-LCD.3 27 A4 | N/C * | LCD_PINS_RS | EXP1.4 LCD_PINS_RS | EXP2.4 SDSS or N/C * * ANET-LCD.4 10 | LCD_PINS_D4 | BTN_EN2 | EXP2.3 BTN_EN2 | EXP2.3 BTN_EN2 * ANET-LCD.5 28 A3 | LCD_PINS_RS | LCD_PINS_ENABLE | EXP1.3 LCD_PINS_ENABLE | EXP1.1 BEEPER_PIN * ANET-LCD.6 11 | LCD_PINS_D5 | BTN_EN1 | EXP2.5 BTN_EN1 | EXP2.5 BTN_EN1 * ANET-LCD.7 29 A2 | LCD_PINS_ENABLE | N/C * | EXP2.4 SDSS or N/C * | EXP1.3 LCD_PINS_ENABLE * ANET-LCD.8 16 SCL | LCD_PINS_D6 | BTN_ENC | EXP1.2 BTN_ENC | EXP1.2 BTN_ENC * ANET-LCD.9 30 A1 | ADC_KEYPAD_PIN ** | LCD_PINS_D4 | EXP1.5 LCD_PINS_D4 | EXP1.4 LCD_PINS_RS * ANET-LCD.10 17 SDA | LCD_PINS_D7 | BEEPER_PIN | EXP1.1 BEEPER_PIN | EXP1.5 LCD_PINS_D4 * * N/C * - if not connected to the LCD can be used for BLTouch servo input * ** - analog pin -WITHOUT a pullup * *** - only connected to something if the Bluetooth module is populated */ /** * REPRAP_DISCOUNT_FULL_GRAPHIC_SMART_CONTROLLER * physical pin function * EXP1.1 BEEPER * EXP1.2 BTN_ENC * EXP1.3 LCD_PINS_ENABLE * EXP1.4 LCD_PINS_RS * EXP1.5 LCD_PINS_D4 * EXP1.6 LCD_PINS_D5 (not used) * EXP1.7 LCD_PINS_D6 (not used) * EXP1.8 LCD_PINS_D7 (not used) * EXP1.9 GND * EXP1.10 VCC * * * EXP2.1 MISO * EXP2.2 SCK * EXP2.3 BTN_EN2 * EXP2.4 SDSS * EXP2.5 BTN_EN1 * EXP2.6 MOSI * EXP2.7 SD_DETECT_PIN * EXP2.8 button * EXP2.9 GND * EXP2.10 NC */
rob-4x4/MarlinTarantula
Marlin/src/pins/pins_ANET_10.h
C
gpl-3.0
10,691
from unittest import TestCase class Test(TestCase): pass
egcodes/haberbus
aristotle/tests/test_util.py
Python
gpl-3.0
63
/*==LICENSE==* CyanWorlds.com Engine - MMOG client, server and tools Copyright (C) 2011 Cyan Worlds, Inc. This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see <http://www.gnu.org/licenses/>. Additional permissions under GNU GPL version 3 section 7 If you modify this Program, or any covered work, by linking or combining it with any of RAD Game Tools Bink SDK, Autodesk 3ds Max SDK, NVIDIA PhysX SDK, Microsoft DirectX SDK, OpenSSL library, Independent JPEG Group JPEG library, Microsoft Windows Media SDK, or Apple QuickTime SDK (or a modified version of those libraries), containing parts covered by the terms of the Bink SDK EULA, 3ds Max EULA, PhysX SDK EULA, DirectX SDK EULA, OpenSSL and SSLeay licenses, IJG JPEG Library README, Windows Media SDK EULA, or QuickTime SDK EULA, the licensors of this Program grant you additional permission to convey the resulting work. Corresponding Source for a non-source form of such a combination shall include the source code for the parts of OpenSSL and IJG JPEG Library used as well as that of the covered work. You can contact Cyan Worlds, Inc. by email legal@cyan.com or by snail mail at: Cyan Worlds, Inc. 14617 N Newport Hwy Mead, WA 99021 *==LICENSE==*/ #ifndef plMultiModifier_inc #define plMultiModifier_inc #include "plModifier.h" #include "hsBitVector.h" #include "pnNetCommon/plSynchedValue.h" #include "hsTemplates.h" class plSceneObject; class plMultiModMsg; class plMultiModifier : public plModifier { protected: hsTArray<plSceneObject*> fTargets; hsBitVector fFlags; public: plMultiModifier(); virtual ~plMultiModifier(); CLASSNAME_REGISTER( plMultiModifier ); GETINTERFACE_ANY( plMultiModifier, plModifier ); virtual bool IEval(double secs, float del, uint32_t dirty) = 0; virtual void Read(hsStream* stream, hsResMgr* mgr); virtual void Write(hsStream* stream, hsResMgr* mgr); virtual int GetNumTargets() const { return fTargets.Count(); } virtual plSceneObject* GetTarget(int w) const { hsAssert(w < GetNumTargets(), "Bad target"); return fTargets[w]; } virtual void AddTarget(plSceneObject* so) {fTargets.Append(so);} virtual void RemoveTarget(plSceneObject* so); bool HasFlag(int f) const { return fFlags.IsBitSet(f); } plMultiModifier& SetFlag(int f) { fFlags.SetBit(f); return *this; } }; #endif // plMultiModifier_inc
cwalther/Plasma-nobink
Sources/Plasma/NucleusLib/pnModifier/plMultiModifier.h
C
gpl-3.0
2,924
/** * Copyright (C) 2011 Whisper Systems * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package org.thoughtcrime.securesms.mms; import java.io.IOException; import org.thoughtcrime.securesms.R; import ws.com.google.android.mms.pdu.PduPart; import android.content.ContentResolver; import android.content.Context; import android.database.Cursor; import android.graphics.Bitmap; import android.graphics.BitmapFactory; import android.net.Uri; import android.provider.MediaStore; import android.util.Log; public class VideoSlide extends Slide { public VideoSlide(Context context, PduPart part) { super(context, part); } public VideoSlide(Context context, Uri uri) throws IOException, MediaTooLargeException { super(context, constructPartFromUri(context, uri)); } @Override public Bitmap getThumbnail() { return BitmapFactory.decodeResource(context.getResources(), R.drawable.ic_launcher_video_player); } @Override public boolean hasImage() { return true; } @Override public boolean hasVideo() { return true; } private static PduPart constructPartFromUri(Context context, Uri uri) throws IOException, MediaTooLargeException { PduPart part = new PduPart(); ContentResolver resolver = context.getContentResolver(); Cursor cursor = null; try { cursor = resolver.query(uri, new String[] {MediaStore.Video.Media.MIME_TYPE}, null, null, null); if (cursor != null && cursor.moveToFirst()) { Log.w("VideoSlide", "Setting mime type: " + cursor.getString(0)); part.setContentType(cursor.getString(0).getBytes()); } } finally { if (cursor != null) cursor.close(); } if (getMediaSize(context, uri) > MAX_MESSAGE_SIZE) throw new MediaTooLargeException("Video exceeds maximum message size."); part.setDataUri(uri); part.setContentId((System.currentTimeMillis()+"").getBytes()); part.setName(("Video" + System.currentTimeMillis()).getBytes()); return part; } }
ioerror/TextSecure
src/org/thoughtcrime/securesms/mms/VideoSlide.java
Java
gpl-3.0
2,646
/* Ring definitions. */ #define qr(a_type) \ struct { \ a_type *qre_next; \ a_type *qre_prev; \ } /* Ring functions. */ #define qr_new(a_qr, a_field) do { \ (a_qr)->a_field.qre_next = (a_qr); \ (a_qr)->a_field.qre_prev = (a_qr); \ } while (0) #define qr_next(a_qr, a_field) ((a_qr)->a_field.qre_next) #define qr_prev(a_qr, a_field) ((a_qr)->a_field.qre_prev) #define qr_before_insert(a_qrelm, a_qr, a_field) do { \ (a_qr)->a_field.qre_prev = (a_qrelm)->a_field.qre_prev; \ (a_qr)->a_field.qre_next = (a_qrelm); \ (a_qr)->a_field.qre_prev->a_field.qre_next = (a_qr); \ (a_qrelm)->a_field.qre_prev = (a_qr); \ } while (0) #define qr_after_insert(a_qrelm, a_qr, a_field) \ do \ { \ (a_qr)->a_field.qre_next = (a_qrelm)->a_field.qre_next; \ (a_qr)->a_field.qre_prev = (a_qrelm); \ (a_qr)->a_field.qre_next->a_field.qre_prev = (a_qr); \ (a_qrelm)->a_field.qre_next = (a_qr); \ } while (0) #define qr_meld(a_qr_a, a_qr_b, a_field) do { \ void *t; \ (a_qr_a)->a_field.qre_prev->a_field.qre_next = (a_qr_b); \ (a_qr_b)->a_field.qre_prev->a_field.qre_next = (a_qr_a); \ t = (a_qr_a)->a_field.qre_prev; \ (a_qr_a)->a_field.qre_prev = (a_qr_b)->a_field.qre_prev; \ (a_qr_b)->a_field.qre_prev = t; \ } while (0) /* qr_meld() and qr_split() are functionally equivalent, so there's no need to * have two copies of the code. */ #define qr_split(a_qr_a, a_qr_b, a_field) \ qr_meld((a_qr_a), (a_qr_b), a_field) #define qr_remove(a_qr, a_field) do { \ (a_qr)->a_field.qre_prev->a_field.qre_next \ = (a_qr)->a_field.qre_next; \ (a_qr)->a_field.qre_next->a_field.qre_prev \ = (a_qr)->a_field.qre_prev; \ (a_qr)->a_field.qre_next = (a_qr); \ (a_qr)->a_field.qre_prev = (a_qr); \ } while (0) #define qr_foreach(var, a_qr, a_field) \ for ((var) = (a_qr); \ (var) != NULL; \ (var) = (((var)->a_field.qre_next != (a_qr)) \ ? (var)->a_field.qre_next : NULL)) #define qr_reverse_foreach(var, a_qr, a_field) \ for ((var) = ((a_qr) != NULL) ? qr_prev(a_qr, a_field) : NULL; \ (var) != NULL; \ (var) = (((var) != (a_qr)) \ ? (var)->a_field.qre_prev : NULL))
Kiddinglife/gecoengine
thirdparty/jemalloc/include/jemalloc/internal/qr.h
C
gpl-3.0
2,322
# Text Field Allows for the input of text. Can be a single line or multiple lines. Typically used to accept user input within a form. ## Variants ### Default @@include('TextField.html') ### Multiline @@include('TextField.Multiline.html') ### Placeholder text @@include('TextField.Placeholder.html') ### Underlined @@include('TextField.Underlined.html') ## Using this component 1. Confirm that you have references to Fabric's CSS on your page: ``` <head> <link rel="stylesheet" href="fabric.min.css"> <link rel="stylesheet" href="fabric.components.min.css"> </head> ``` 2. Copy the HTML from one of the samples above into your page. 3. Update the `.ms-Label` to contain your label text. ## Dependencies This component has a dependency on the Label component.
hualiansheng/PlessPP
spike/officeAddIn/slideChangerPowerPointOfficeAddIn/bower_components/office-ui-fabric/src/components/TextField/TextField.md
Markdown
gpl-3.0
797
/* * Meran - MERAN UNLP is a ILS (Integrated Library System) wich provides Catalog, * Circulation and User's Management. It's written in Perl, and uses Apache2 * Web-Server, MySQL database and Sphinx 2 indexing. * Copyright (C) 2009-2013 Grupo de desarrollo de Meran CeSPI-UNLP * * This file is part of Meran. * * Meran 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. * * Meran 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 Meran. If not, see <http://www.gnu.org/licenses/>. */ function a(a){return a==1?2:17}
Desarrollo-CeSPI/meran
dev-plugins/node64/lib/node_modules/uglify-js/test/unit/compress/expected/ifreturn.js
JavaScript
gpl-3.0
980
/** * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.opencloudengine.flamingo2.model.rest; import java.io.Serializable; import java.sql.Timestamp; import java.util.Date; import java.util.Map; /** * Workflow Execution History Domain Object. * * @author Edward KIM * @since 0.1 */ public class WorkflowHistory implements Serializable { /** * Serialization UID */ private static final long serialVersionUID = 1; private long id; private String workflowId; private long jobId; private String jobStringId; private String workflowName; private String workflowXml; private String currentAction; private String jobName; private String variable; private Date startDate; private String startDateSimple; private Date endDate; private String endDateSimple; private long elapsed; private String cause; private int currentStep; private int totalStep; private String exception; private State status; private String username; private String jobType; private String logPath; private String sf_parentIdentifier; private String sf_rootIdentifier; private int sf_depth; private String sf_taskId; public WorkflowHistory() { } public WorkflowHistory(long id) { this.id = id; } public long getId() { return id; } public void setId(long id) { this.id = id; } public String getWorkflowId() { return workflowId; } public void setWorkflowId(String workflowId) { this.workflowId = workflowId; } public long getJobId() { return jobId; } public void setJobId(long jobId) { this.jobId = jobId; } public String getJobStringId() { return jobStringId; } public void setJobStringId(String jobStringId) { this.jobStringId = jobStringId; } public String getWorkflowName() { return workflowName; } public void setWorkflowName(String workflowName) { this.workflowName = workflowName; } public String getWorkflowXml() { return workflowXml; } public void setWorkflowXml(String workflowXml) { this.workflowXml = workflowXml; } public String getCurrentAction() { return currentAction; } public void setCurrentAction(String currentAction) { this.currentAction = currentAction; } public String getJobName() { return jobName; } public void setJobName(String jobName) { this.jobName = jobName; } public String getVariable() { return variable; } public void setVariable(String variable) { this.variable = variable; } public Date getStartDate() { return startDate; } public void setStartDate(Date startDate) { this.startDate = startDate; } public String getStartDateSimple() { return startDateSimple; } public void setStartDateSimple(String startDateSimple) { this.startDateSimple = startDateSimple; } public Date getEndDate() { return endDate; } public void setEndDate(Date endDate) { this.endDate = endDate; } public String getEndDateSimple() { return endDateSimple; } public void setEndDateSimple(String endDateSimple) { this.endDateSimple = endDateSimple; } public long getElapsed() { return elapsed; } public void setElapsed(long elapsed) { this.elapsed = elapsed; } public String getCause() { return cause; } public void setCause(String cause) { this.cause = cause; } public int getCurrentStep() { return currentStep; } public void setCurrentStep(int currentStep) { this.currentStep = currentStep; } public int getTotalStep() { return totalStep; } public void setTotalStep(int totalStep) { this.totalStep = totalStep; } public String getException() { return exception; } public void setException(String exception) { this.exception = exception; } public State getStatus() { return status; } public void setStatus(State status) { this.status = status; } public String getUsername() { return username; } public void setUsername(String username) { this.username = username; } public String getJobType() { return jobType; } public void setJobType(String jobType) { this.jobType = jobType; } public String getLogPath() { return logPath; } public void setLogPath(String logPath) { this.logPath = logPath; } public String getSf_parentIdentifier() { return sf_parentIdentifier; } public void setSf_parentIdentifier(String sf_parentIdentifier) { this.sf_parentIdentifier = sf_parentIdentifier; } public String getSf_rootIdentifier() { return sf_rootIdentifier; } public void setSf_rootIdentifier(String sf_rootIdentifier) { this.sf_rootIdentifier = sf_rootIdentifier; } public int getSf_depth() { return sf_depth; } public void setSf_depth(int sf_depth) { this.sf_depth = sf_depth; } public String getSf_taskId() { return sf_taskId; } public void setSf_taskId(String sf_taskId) { this.sf_taskId = sf_taskId; } @Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; WorkflowHistory that = (WorkflowHistory) o; if (id != that.id) return false; return true; } @Override public int hashCode() { return (int) (id ^ (id >>> 32)); } @Override public String toString() { return "WorkflowHistory{" + "id=" + id + ", workflowId='" + workflowId + '\'' + ", jobId=" + jobId + ", jobStringId='" + jobStringId + '\'' + ", workflowName='" + workflowName + '\'' + ", workflowXml='" + workflowXml + '\'' + ", currentAction='" + currentAction + '\'' + ", jobName='" + jobName + '\'' + ", variable='" + variable + '\'' + ", startDate=" + startDate + ", startDateSimple='" + startDateSimple + '\'' + ", endDate=" + endDate + ", endDateSimple='" + endDateSimple + '\'' + ", elapsed=" + elapsed + ", cause='" + cause + '\'' + ", currentStep=" + currentStep + ", totalStep=" + totalStep + ", exception='" + exception + '\'' + ", status=" + status + ", username='" + username + '\'' + ", jobType='" + jobType + '\'' + ", logPath='" + logPath + '\'' + ", sf_parentIdentifier='" + sf_parentIdentifier + '\'' + ", sf_rootIdentifier='" + sf_rootIdentifier + '\'' + ", sf_depth=" + sf_depth + ", sf_taskId='" + sf_taskId + '\'' + '}'; } }
chiwanpark/flamingo2
flamingo2-common/src/main/java/org/opencloudengine/flamingo2/model/rest/WorkflowHistory.java
Java
gpl-3.0
8,095
/*---------------------------------------------------------------------------*\ ========= | \\ / F ield | OpenFOAM: The Open Source CFD Toolbox \\ / O peration | \\ / A nd | Copyright (C) 2011-2013 OpenFOAM Foundation \\/ M anipulation | ------------------------------------------------------------------------------- License This file is part of OpenFOAM. OpenFOAM 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. OpenFOAM 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 OpenFOAM. If not, see <http://www.gnu.org/licenses/>. Application engineFoam Description Solver for cold-flow in internal combustion engines. \*---------------------------------------------------------------------------*/ #include "fvCFD.H" #include "engineTime.H" #include "engineMesh.H" #include "psiThermo.H" #include "turbulenceModel.H" #include "OFstream.H" #include "fvIOoptionList.H" #include "pimpleControl.H" // * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * // int main(int argc, char *argv[]) { #include "setRootCase.H" #include "createEngineTime.H" #include "createEngineMesh.H" #include "createFields.H" #include "createFvOptions.H" #include "initContinuityErrs.H" #include "readEngineTimeControls.H" #include "compressibleCourantNo.H" #include "setInitialDeltaT.H" #include "startSummary.H" pimpleControl pimple(mesh); // * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * // Info<< "\nStarting time loop\n" << endl; while (runTime.run()) { #include "readEngineTimeControls.H" #include "compressibleCourantNo.H" #include "setDeltaT.H" runTime++; Info<< "Crank angle = " << runTime.theta() << " CA-deg" << endl; mesh.move(); #include "rhoEqn.H" // --- Pressure-velocity PIMPLE corrector loop while (pimple.loop()) { #include "UEqn.H" // --- Pressure corrector loop while (pimple.correct()) { #include "EEqn.H" #include "pEqn.H" } if (pimple.turbCorr()) { turbulence->correct(); } } runTime.write(); #include "logSummary.H" Info<< "ExecutionTime = " << runTime.elapsedCpuTime() << " s" << " ClockTime = " << runTime.elapsedClockTime() << " s" << nl << endl; } Info<< "End\n" << endl; return 0; } // ************************************************************************* //
firelab/OpenFOAM-2.2.x
applications/solvers/combustion/coldEngineFoam/coldEngineFoam.C
C++
gpl-3.0
3,154
<!-- patTemplate:tmpl name="content" --> <script language="javascript" type="text/javascript"> var xpopup; function centangin_semua(varname, start_num, end_num) { var obj = document.getElementById('cek_all'); if(obj.checked == false) { for(i=start_num;i<=end_num;i++) { document.getElementById(varname + i).checked = false; } } else { for(i=start_num;i<=end_num;i++) { document.getElementById(varname + i).checked = true; } } } function show_checkbox (varname, start_num, end_num) { //show check_all checkbox document.getElementById('cek_all').style.display=''; //document.getElementById('btnHapus').type="button"; } function konfirmasi_delete(varname, start_num, end_num) { //var idDelete = document.getElementById('id_delete').value; for(i=start_num;i<=end_num;i++) { if(document.getElementById(varname + i).checked == true) { //document.getElementById('form_list').submit(); document.getElementById('btnHapus').type="submit"; //document.getElementById('btnHapus').click(); document.formaneh.onSubmit(); return true; } } alert('Please check at least 1 data'); return false; } function konfirmasi_update(varname, start_num, end_num) { //var idDelete = document.getElementById('id_delete').value; for(i=start_num;i<=end_num;i++) { if(document.getElementById(varname + i).checked == true) { //document.getElementById('form_list').submit(); document.formaneh.action = '{URL_UPDATE}'; document.getElementById('btnUpdate').type="submit"; //document.getElementById('btnHapus').click(); document.formaneh.onSubmit(); return true; } } alert('Please check at least 1 data'); return false; } document.onload = show_checkbox('gaji_pegawai_id_','{FIRST_NUMBER}','{LAST_NUMBER}'); function bukaPopupUnitkerja(xurl) { showPopup(xurl,'List of Work Unit',500, 500); } function resetFormIni() { if(document.getElementById('unitkerja')) document.getElementById('unitkerja').value=''; if(document.getElementById('unitkerja_label')) document.getElementById('unitkerja_label').innerHTML=''; } /*function coba(){ document.formaneh.action = '{URL_UPDATE}'; //alert(document.formaneh.action); document.getElementById('btnUpdate').type="submit"; document.formaneh.onSubmit(); }*/ </script> <!-- onclick="konfirmasi_delete('gaji_pegawai_id_','{FIRST_NUMBER}','{LAST_NUMBER}', '{URL_DELETE}')" --> <br /> <h1>EMPLOYEE SALARY</h1> <br /> <form method="POST" action="{URL_SEARCH}" class="dataquest xhr_simple_form dest_subcontent-element" id="filterbox"> <table> <tr> <th colspan="3"><h2><strong>Search Data</strong></h2></th> </tr> <tr> <th width="30%">Employee Number/Name</th> <td><input type="text" name="nip_nama" value="{NIP_NAMA}" size="30" /></td> </tr> <tr> <th>Work Unit</th> <td><!--<input type="text" name="satkerja_label" id="satkerja_label" value="{SATKERJA_LABEL}" size="40" readonly="readonly" />--> <input type="text" name="satkerja_label" id="satkerja_label" value="{SATKERJA_LABEL}" readonly="readonly" /> <input type="hidden" name="satkerja" id="satkerja" value="{SATKERJA}" />&nbsp; <input type="button" name="but_unitkerja" onclick="bukaPopupUnitkerja('{URL_POPUP_UNITKERJA}')" value=" ... " /></td> </tr> <tr> <th>Payment Status</th> <td><!-- patTemplate:gtfwrendermodule module="combobox" submodule="combobox" action="view" name="jenis" / --></td> </tr> <tr> <th>Period</th> <td><!-- patTemplate:gtfwrendermodule module="combobox" submodule="combobox" action="view" name="periode_bulan" / --> <!-- patTemplate:gtfwrendermodule module="combobox" submodule="combobox" action="view" name="periode_tahun" / --></td> </tr> <tr> <th>&nbsp;</th> <td colspan='3'> <input type="submit" name="btncari" value=" Search &raquo;" class="buttonSubmit"/> <input name="btnReset" value=" Reset " class="buttonSubmit" type="reset" onclick="resetFormIni()"> </td> </tr> </table> </form> <br /> <!-- patTemplate:tmpl name="warning_box" visibility="hidden" --> <div class="{CLASS_PESAN}"> {ISI_PESAN} </div> <br /> <!-- /patTemplate:tmpl --> <form method="POST" action="{URL_DELETE}" name="formaneh" class="xhr_simple_form dest_subcontent-element" id="form_list"> <div class="pageBar"> <!-- patTemplate:gtfwrendermodule module="paging" submodule="paging" action="view" name="paging_top" / --> <div class="toolbar"> <!-- <a class="xhr dest_subcontent-element" href="{URL_BUAT_TRANSAKSI}" title="Buat Transaksi" tabindex="2"><img src="images/button-tindaklanjuti.gif" alt="Buat Transaksi"> Buat Transaksi </a>--> <a class="xhr dest_subcontent-element" href="{URL_IMPORT}" title="Import Data" tabindex="3"><img src="images/button-print.gif" alt="Import Data"> Import</a> <a class="xhr dest_subcontent-element" href="{URL_REKAP}" title="Salary Rekap Data" tabindex="4"><img src="images/button-tindaklanjuti.gif" alt="Salary Rekap Data"> Salary Rekap Data</a> <input type="button" id="btnUpdate" name="btnUpdate" value="Payment" class="inputButton" onclick="konfirmasi_update('gaji_pegawai_id_','{FIRST_NUMBER}','{LAST_NUMBER}')" /> <input type="button" id="btnHapus" name="btnHapus" value="Delete" class="inputButton" onclick="konfirmasi_delete('gaji_pegawai_id_','{FIRST_NUMBER}','{LAST_NUMBER}')" /> </div> </div> <table class="table-common" width="800px"> <tr> <th width="5" rowspan="2">No</th> <th width="5" rowspan="2"><input type="checkbox" style="display:none" name="cek_all" id="cek_all" value="ALL" onclick="centangin_semua('gaji_pegawai_id_','{FIRST_NUMBER}','{LAST_NUMBER}');" /></th> <th width="130px" rowspan="2">Action</th> <th rowspan="2">Employee Number</th> <th rowspan="2">Name</th> <th rowspan="2" width="120px">Address</th> <th width="80px" rowspan="2">Gross Income (Rp)</th> <th colspan="2">Period</th> <th width="35px" rowspan="2">Active</th> <th width="35px" rowspan="2">Payment Status</th> </tr> <tr> <th>Month</th> <th>Year</th> </tr> <!-- patTemplate:tmpl name="data_gaji_pegawai" type="condition" conditionvar="GAJIPEGAWAI_EMPTY" --> <!-- patTemplate:sub condition="YES" --> <tr><td colspan="11" align="center"><em>-- Data not found --</em></td></tr> <!-- /patTemplate:sub --> <!-- patTemplate:sub condition="NO" --> <!-- patTemplate:tmpl name="data_gaji_pegawai_item" --> <tr class="{GAJIPEGAWAI_CLASS_NAME}"> <td align="center">{GAJIPEGAWAI_NUMBER}</td> <td align="center"> <input type="checkbox" name="id[]" id="gaji_pegawai_id_{GAJIPEGAWAI_NUMBER}" value="{GAJIPEGAWAI_ID}" /><input type="hidden" name="name[{GAJIPEGAWAI_ID}]" value="{GAJIPEGAWAI_NAMA}" /></td> <td class="links" align="center"> <a class="xhr dest_subcontent-element" href="{GAJIPEGAWAI_URL_EDIT}" title="Update"><img src="images/button-edit.gif" alt="Update"/></a> <a class="xhr dest_subcontent-element" href="{GAJIPEGAWAI_URL_DETIL}" title="Detail"><img src="images/button-detail.gif" alt="Detail"/></a> <a class="xhr dest_subcontent-element" href="{GAJIPEGAWAI_URL_HISTORY}" title="History"><img src="images/button-bukubuka.gif" alt="History"/></a> <a class="xhr dest_subcontent-element" href="{GAJIPEGAWAI_URL_PAYROL}" title="Payroll"><img src="images/msg_new.gif" alt="Payroll"/></a> <input type="hidden" name="periode[]" value="{GAJIPEGAWAI_TAHUN_BULAN}" /> <input type="hidden" name="idGaji[]" value="{GAJIPEGAWAI_IDGAJI}" /> </td> <td align="center">{GAJIPEGAWAI_NIP}</td> <td>{GAJIPEGAWAI_NAMA}</td> <td>{GAJIPEGAWAI_ALAMAT}</td> <td style="text-align:right;">{GAJIPEGAWAI_GAJI}</td> <td style="text-align:right;">{GAJIPEGAWAI_PERIODE_BULAN}</td> <td style="text-align:right;">{GAJIPEGAWAI_PERIODE_TAHUN}</td> <td style="text-align:right;">{GAJIPEGAWAI_IS_AKTIF}</td> <td style="text-align:right;">{GAJIPEGAWAI_STATUS}</td> </tr> <!-- /patTemplate:tmpl --> <!-- /patTemplate:sub --> <!-- /patTemplate:tmpl --> </table> </form> <br /> <table class="table-common" width="300px"> <tr class="table-common-even1"> <td style="width:150px"><b>Total Active Employees</b></td><td style="text-align:right;">{TOTAL_PEGAWAI_AKTIF} orang</td> </tr> <tr class="table-common-even1"> <td style="width:150px"><b>Total Salary (1 period)</b></td><td style="text-align:right;">Rp. {TOTAL}</td> </tr> <!--<tr class="table-common-even1"> <td><b>Total Keseluruhan (1 period)</b></td><td style="text-align:right;">Rp. {TOTAL_SELURUH}</td> </tr>--> </table> <!-- /patTemplate:tmpl -->
4n6g4/gtsdm
malra/fo/module/gaji_pegawai/template_eng/view_gaji_pegawai.html
HTML
gpl-3.0
9,385
/* Copyright 2010 David Fritz, Brian Gordon, Wira Mulia 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 plptool.mods; import plptool.Constants; import plptool.PLPSimBusModule; import plptool.Msg; /** * PLP Button Interrupt module. * * @see PLPSimBusModule * @author wira */ public class Button extends PLPSimBusModule { private boolean pressed; private plptool.PLPSimCore sim; private long bit; private long mask; public Button(long bit, long mask, plptool.PLPSimCore sim) { super(-1, -1, true); pressed = false; this.sim = sim; this.bit = bit; this.mask = mask; } public int eval() { if(!enabled) return Constants.PLP_OK; if(pressed) { sim.setIRQ(bit); } else sim.maskIRQ(mask); return Constants.PLP_OK; } public void setPressedState(boolean s) { pressed = s; } public int gui_eval(Object x) { return Constants.PLP_OK; } public String introduce() { return "Interrupt Button"; } @Override public void reset() { // nothing, read only module } @Override public String toString() { return "Interrupt Button"; } }
Progressive-Learning-Platform/progressive-learning-platform
reference/sw/PLPTool/src/plptool/mods/Button.java
Java
gpl-3.0
1,873
/*************************************************************************** * _ _ ____ _ * Project ___| | | | _ \| | * / __| | | | |_) | | * | (__| |_| | _ <| |___ * \___|\___/|_| \_\_____| * * Copyright (C) 1998 - 2016, Daniel Stenberg, <daniel@haxx.se>, 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.haxx.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. * ***************************************************************************/ #include "tool_setup.h" #include "tool_panykey.h" #include "tool_help.h" #include "tool_libinfo.h" #include "tool_version.h" #include "memdebug.h" /* keep this as LAST include */ #ifdef MSDOS # define USE_WATT32 #endif /* * A few of these source lines are >80 columns wide, but that's only because * breaking the strings narrower makes this chunk look even worse! * * Starting with 7.18.0, this list of command line options is sorted based * on the long option name. It is not done automatically, although a command * line like the following can help out: * * curl --help | cut -c5- | grep "^-" | sort */ static const char *const helptext[] = { "Usage: curl [options...] <url>", "Options: (H) means HTTP/HTTPS only, (F) means FTP only", " --anyauth Pick \"any\" authentication method (H)", " -a, --append Append to target file when uploading (F/SFTP)", " --basic Use HTTP Basic Authentication (H)", " --cacert FILE CA certificate to verify peer against (SSL)", " --capath DIR CA directory to verify peer against (SSL)", " -E, --cert CERT[:PASSWD] Client certificate file and password (SSL)", " --cert-status Verify the status of the server certificate (SSL)", " --cert-type TYPE Certificate file type (DER/PEM/ENG) (SSL)", " --ciphers LIST SSL ciphers to use (SSL)", " --compressed Request compressed response (using deflate or gzip)", " -K, --config FILE Read config from FILE", " --connect-timeout SECONDS Maximum time allowed for connection", " --connect-to HOST1:PORT1:HOST2:PORT2 Connect to host (network level)", " -C, --continue-at OFFSET Resumed transfer OFFSET", " -b, --cookie STRING/FILE Read cookies from STRING/FILE (H)", " -c, --cookie-jar FILE Write cookies to FILE after operation (H)", " --create-dirs Create necessary local directory hierarchy", " --crlf Convert LF to CRLF in upload", " --crlfile FILE Get a CRL list in PEM format from the given file", " -d, --data DATA HTTP POST data (H)", " --data-raw DATA HTTP POST data, '@' allowed (H)", " --data-ascii DATA HTTP POST ASCII data (H)", " --data-binary DATA HTTP POST binary data (H)", " --data-urlencode DATA HTTP POST data url encoded (H)", " --delegation STRING GSS-API delegation permission", " --digest Use HTTP Digest Authentication (H)", " --disable-eprt Inhibit using EPRT or LPRT (F)", " --disable-epsv Inhibit using EPSV (F)", " --dns-servers DNS server addrs to use: 1.1.1.1;2.2.2.2", " --dns-interface Interface to use for DNS requests", " --dns-ipv4-addr IPv4 address to use for DNS requests, dot notation", " --dns-ipv6-addr IPv6 address to use for DNS requests, dot notation", " -D, --dump-header FILE Write the received headers to FILE", " --egd-file FILE EGD socket path for random data (SSL)", " --engine ENGINE Crypto engine (use \"--engine list\" for list) (SSL)", #ifdef USE_ENVIRONMENT " --environment Write results to environment variables (RISC OS)", #endif " --expect100-timeout SECONDS How long to wait for 100-continue (H)", " -f, --fail Fail silently (no output at all) on HTTP errors (H)", " --fail-early Fail on first transfer error, do not continue", " --false-start Enable TLS False Start.", " -F, --form CONTENT Specify HTTP multipart POST data (H)", " --form-string STRING Specify HTTP multipart POST data (H)", " --ftp-account DATA Account data string (F)", " --ftp-alternative-to-user COMMAND " "String to replace \"USER [name]\" (F)", " --ftp-create-dirs Create the remote dirs if not present (F)", " --ftp-method [MULTICWD/NOCWD/SINGLECWD] Control CWD usage (F)", " --ftp-pasv Use PASV/EPSV instead of PORT (F)", " -P, --ftp-port ADR Use PORT with given address instead of PASV (F)", " --ftp-skip-pasv-ip Skip the IP address for PASV (F)\n" " --ftp-pret Send PRET before PASV (for drftpd) (F)", " --ftp-ssl-ccc Send CCC after authenticating (F)", " --ftp-ssl-ccc-mode ACTIVE/PASSIVE Set CCC mode (F)", " --ftp-ssl-control Require SSL/TLS for FTP login, " "clear for transfer (F)", " -G, --get Send the -d data with a HTTP GET (H)", " -g, --globoff Disable URL sequences and ranges using {} and []", " -H, --header LINE Pass custom header LINE to server (H)", " -I, --head Show document info only", " -h, --help This help text", " --hostpubmd5 MD5 " "Hex-encoded MD5 string of the host public key. (SSH)", " -0, --http1.0 Use HTTP 1.0 (H)", " --http1.1 Use HTTP 1.1 (H)", " --http2 Use HTTP 2 (H)", " --http2-prior-knowledge Use HTTP 2 without HTTP/1.1 Upgrade (H)", " --ignore-content-length Ignore the HTTP Content-Length header", " -i, --include Include protocol headers in the output (H/F)", " -k, --insecure Allow connections to SSL sites without certs (H)", " --interface INTERFACE Use network INTERFACE (or address)", " -4, --ipv4 Resolve name to IPv4 address", " -6, --ipv6 Resolve name to IPv6 address", " -j, --junk-session-cookies Ignore session cookies read from file (H)", " --keepalive-time SECONDS Wait SECONDS between keepalive probes", " --key KEY Private key file name (SSL/SSH)", " --key-type TYPE Private key file type (DER/PEM/ENG) (SSL)", " --krb LEVEL Enable Kerberos with security LEVEL (F)", #ifndef CURL_DISABLE_LIBCURL_OPTION " --libcurl FILE Dump libcurl equivalent code of this command line", #endif " --limit-rate RATE Limit transfer speed to RATE", " -l, --list-only List only mode (F/POP3)", " --local-port RANGE Force use of RANGE for local port numbers", " -L, --location Follow redirects (H)", " --location-trusted " "Like '--location', and send auth to other hosts (H)", " --login-options OPTIONS Server login options (IMAP, POP3, SMTP)", " -M, --manual Display the full manual", " --mail-from FROM Mail from this address (SMTP)", " --mail-rcpt TO Mail to this/these addresses (SMTP)", " --mail-auth AUTH Originator address of the original email (SMTP)", " --max-filesize BYTES Maximum file size to download (H/F)", " --max-redirs NUM Maximum number of redirects allowed (H)", " -m, --max-time SECONDS Maximum time allowed for the transfer", " --metalink Process given URLs as metalink XML file", " --negotiate Use HTTP Negotiate (SPNEGO) authentication (H)", " -n, --netrc Must read .netrc for user name and password", " --netrc-optional Use either .netrc or URL; overrides -n", " --netrc-file FILE Specify FILE for netrc", " -:, --next " "Allows the following URL to use a separate set of options", " --no-alpn Disable the ALPN TLS extension (H)", " -N, --no-buffer Disable buffering of the output stream", " --no-keepalive Disable keepalive use on the connection", " --no-npn Disable the NPN TLS extension (H)", " --no-sessionid Disable SSL session-ID reusing (SSL)", " --noproxy List of hosts which do not use proxy", " --ntlm Use HTTP NTLM authentication (H)", " --ntlm-wb Use HTTP NTLM authentication with winbind (H)", " --oauth2-bearer TOKEN OAuth 2 Bearer Token (IMAP, POP3, SMTP)", " -o, --output FILE Write to FILE instead of stdout", " --pass PASS Pass phrase for the private key (SSL/SSH)", " --path-as-is Do not squash .. sequences in URL path", " --pinnedpubkey FILE/HASHES Public key to verify peer against (SSL)", " --post301 " "Do not switch to GET after following a 301 redirect (H)", " --post302 " "Do not switch to GET after following a 302 redirect (H)", " --post303 " "Do not switch to GET after following a 303 redirect (H)", " --preproxy [PROTOCOL://]HOST[:PORT] Proxy before HTTP(S) proxy", " -#, --progress-bar Display transfer progress as a progress bar", " --proto PROTOCOLS Enable/disable PROTOCOLS", " --proto-default PROTOCOL Use PROTOCOL for any URL missing a scheme", " --proto-redir PROTOCOLS Enable/disable PROTOCOLS on redirect", " -x, --proxy [PROTOCOL://]HOST[:PORT] Use proxy on given port", " --proxy-anyauth Pick \"any\" proxy authentication method (H)", " --proxy-basic Use Basic authentication on the proxy (H)", " --proxy-digest Use Digest authentication on the proxy (H)", " --proxy-cacert FILE " "CA certificate to verify peer against for proxy (SSL)", " --proxy-capath DIR " "CA directory to verify peer against for proxy (SSL)", " --proxy-cert CERT[:PASSWD] " "Client certificate file and password for proxy (SSL)", " --proxy-cert-type TYPE " "Certificate file type (DER/PEM/ENG) for proxy (SSL)", " --proxy-ciphers LIST SSL ciphers to use for proxy (SSL)", " --proxy-crlfile FILE " "Get a CRL list in PEM format from the given file for proxy", " --proxy-insecure " "Allow connections to SSL sites without certs for proxy (H)", " --proxy-key KEY Private key file name for proxy (SSL)", " --proxy-key-type TYPE " "Private key file type for proxy (DER/PEM/ENG) (SSL)", " --proxy-negotiate " "Use HTTP Negotiate (SPNEGO) authentication on the proxy (H)", " --proxy-ntlm Use NTLM authentication on the proxy (H)", " --proxy-header LINE Pass custom header LINE to proxy (H)", " --proxy-pass PASS Pass phrase for the private key for proxy (SSL)", " --proxy-ssl-allow-beast " "Allow security flaw to improve interop for proxy (SSL)", " --proxy-tlsv1 Use TLSv1 for proxy (SSL)", " --proxy-tlsuser USER TLS username for proxy", " --proxy-tlspassword STRING TLS password for proxy", " --proxy-tlsauthtype STRING " "TLS authentication type for proxy (default SRP)", " --proxy-service-name NAME SPNEGO proxy service name", " --service-name NAME SPNEGO service name", " -U, --proxy-user USER[:PASSWORD] Proxy user and password", " --proxy1.0 HOST[:PORT] Use HTTP/1.0 proxy on given port", " -p, --proxytunnel Operate through a HTTP proxy tunnel (using CONNECT)", " --pubkey KEY Public key file name (SSH)", " -Q, --quote CMD Send command(s) to server before transfer (F/SFTP)", " --random-file FILE File for reading random data from (SSL)", " -r, --range RANGE Retrieve only the bytes within RANGE", " --raw Do HTTP \"raw\"; no transfer decoding (H)", " -e, --referer Referer URL (H)", " -J, --remote-header-name Use the header-provided filename (H)", " -O, --remote-name Write output to a file named as the remote file", " --remote-name-all Use the remote file name for all URLs", " -R, --remote-time Set the remote file's time on the local output", " -X, --request COMMAND Specify request command to use", " --resolve HOST:PORT:ADDRESS Force resolve of HOST:PORT to ADDRESS", " --retry NUM " "Retry request NUM times if transient problems occur", " --retry-connrefused Retry on connection refused (use with --retry)", " --retry-delay SECONDS Wait SECONDS between retries", " --retry-max-time SECONDS Retry only within this period", " --sasl-ir Enable initial response in SASL authentication", " -S, --show-error " "Show error. With -s, make curl show errors when they occur", " -s, --silent Silent mode (don't output anything)", " --socks4 HOST[:PORT] SOCKS4 proxy on given host + port", " --socks4a HOST[:PORT] SOCKS4a proxy on given host + port", " --socks5 HOST[:PORT] SOCKS5 proxy on given host + port", " --socks5-hostname HOST[:PORT] " "SOCKS5 proxy, pass host name to proxy", " --socks5-gssapi-service NAME SOCKS5 proxy service name for GSS-API", " --socks5-gssapi-nec Compatibility with NEC SOCKS5 server", " -Y, --speed-limit RATE " "Stop transfers below RATE for 'speed-time' secs", " -y, --speed-time SECONDS " "Trigger 'speed-limit' abort after SECONDS (default: 30)", " --ssl Try SSL/TLS (FTP, IMAP, POP3, SMTP)", " --ssl-reqd Require SSL/TLS (FTP, IMAP, POP3, SMTP)", " -2, --sslv2 Use SSLv2 (SSL)", " -3, --sslv3 Use SSLv3 (SSL)", " --ssl-allow-beast Allow security flaw to improve interop (SSL)", " --ssl-no-revoke Disable cert revocation checks (WinSSL)", " --stderr FILE Where to redirect stderr (use \"-\" for stdout)", " --suppress-connect-headers Suppress proxy CONNECT response headers", " --tcp-nodelay Use the TCP_NODELAY option", " --tcp-fastopen Use TCP Fast Open", " -t, --telnet-option OPT=VAL Set telnet option", " --tftp-blksize VALUE Set TFTP BLKSIZE option (must be >512)", " --tftp-no-options Do not send TFTP options requests", " -z, --time-cond TIME Transfer based on a time condition", " -1, --tlsv1 Use >= TLSv1 (SSL)", " --tlsv1.0 Use TLSv1.0 (SSL)", " --tlsv1.1 Use TLSv1.1 (SSL)", " --tlsv1.2 Use TLSv1.2 (SSL)", " --tlsv1.3 Use TLSv1.3 (SSL)", " --tls-max VERSION Use TLS up to VERSION (SSL)", " --trace FILE Write a debug trace to FILE", " --trace-ascii FILE Like --trace, but without hex output", " --trace-time Add time stamps to trace/verbose output", " --tr-encoding Request compressed transfer encoding (H)", " -T, --upload-file FILE Transfer FILE to destination", " --url URL URL to work with", " -B, --use-ascii Use ASCII/text transfer", " -u, --user USER[:PASSWORD] Server user and password", " --tlsuser USER TLS username", " --tlspassword STRING TLS password", " --tlsauthtype STRING TLS authentication type (default: SRP)", " --unix-socket PATH Connect through this Unix domain socket", " --abstract-unix-socket PATH Connect to an abstract Unix domain socket", " -A, --user-agent STRING Send User-Agent STRING to server (H)", " -v, --verbose Make the operation more talkative", " -V, --version Show version number and quit", #ifdef USE_WATT32 " --wdebug Turn on Watt-32 debugging", #endif " -w, --write-out FORMAT Use output FORMAT after completion", " --xattr Store metadata in extended file attributes", " -q, --disable Disable .curlrc (must be first parameter)", NULL }; #ifdef NETWARE # define PRINT_LINES_PAUSE 23 #endif #ifdef __SYMBIAN32__ # define PRINT_LINES_PAUSE 16 #endif struct feat { const char *name; int bitmask; }; static const struct feat feats[] = { {"AsynchDNS", CURL_VERSION_ASYNCHDNS}, {"Debug", CURL_VERSION_DEBUG}, {"TrackMemory", CURL_VERSION_CURLDEBUG}, {"IDN", CURL_VERSION_IDN}, {"IPv6", CURL_VERSION_IPV6}, {"Largefile", CURL_VERSION_LARGEFILE}, {"SSPI", CURL_VERSION_SSPI}, {"GSS-API", CURL_VERSION_GSSAPI}, {"Kerberos", CURL_VERSION_KERBEROS5}, {"SPNEGO", CURL_VERSION_SPNEGO}, {"NTLM", CURL_VERSION_NTLM}, {"NTLM_WB", CURL_VERSION_NTLM_WB}, {"SSL", CURL_VERSION_SSL}, {"libz", CURL_VERSION_LIBZ}, {"CharConv", CURL_VERSION_CONV}, {"TLS-SRP", CURL_VERSION_TLSAUTH_SRP}, {"HTTP2", CURL_VERSION_HTTP2}, {"UnixSockets", CURL_VERSION_UNIX_SOCKETS}, {"HTTPS-proxy", CURL_VERSION_HTTPS_PROXY} }; void tool_help(void) { int i; for(i = 0; helptext[i]; i++) { puts(helptext[i]); #ifdef PRINT_LINES_PAUSE if(i && ((i % PRINT_LINES_PAUSE) == 0)) tool_pressanykey(); #endif } } void tool_version_info(void) { const char *const *proto; printf(CURL_ID "%s\n", curl_version()); if(curlinfo->protocols) { printf("Protocols: "); for(proto = curlinfo->protocols; *proto; ++proto) { printf("%s ", *proto); } puts(""); /* newline */ } if(curlinfo->features) { unsigned int i; printf("Features: "); for(i = 0; i < sizeof(feats)/sizeof(feats[0]); i++) { if(curlinfo->features & feats[i].bitmask) printf("%s ", feats[i].name); } #ifdef USE_METALINK printf("Metalink "); #endif #ifdef USE_LIBPSL printf("PSL "); #endif puts(""); /* newline */ } } void tool_list_engines(CURL *curl) { struct curl_slist *engines = NULL; /* Get the list of engines */ curl_easy_getinfo(curl, CURLINFO_SSL_ENGINES, &engines); puts("Build-time engines:"); if(engines) { for(; engines; engines = engines->next) printf(" %s\n", engines->data); } else { puts(" <none>"); } /* Cleanup the list of engines */ curl_slist_free_all(engines); }
Necktrox/mtasa-blue
vendor/curl/src/tool_help.c
C
gpl-3.0
18,072
/* Copyright (c) 2004 Eric B. Weddington Copyright (c) 2005,2006 Anatoly Sokolov 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 of the copyright holders nor the names of contributors may be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED 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. */ /* avr/iom6490.h - definitions for ATmega6490 */ #ifndef _AVR_IOM6490_H_ #define _AVR_IOM6490_H_ 1 /* This file should only be included from <avr/io.h>, never directly. */ #ifndef _AVR_IO_H_ # error "Include <avr/io.h> instead of this file." #endif #ifndef _AVR_IOXXX_H_ # define _AVR_IOXXX_H_ "iom6490.h" #else # error "Attempt to include more than one <avr/ioXXX.h> file." #endif /* Registers and associated bit numbers */ #define PINA _SFR_IO8(0x00) #define PINA7 7 #define PINA6 6 #define PINA5 5 #define PINA4 4 #define PINA3 3 #define PINA2 2 #define PINA1 1 #define PINA0 0 #define DDRA _SFR_IO8(0x01) #define DDA7 7 #define DDA6 6 #define DDA5 5 #define DDA4 4 #define DDA3 3 #define DDA2 2 #define DDA1 1 #define DDA0 0 #define PORTA _SFR_IO8(0x02) #define PA7 7 #define PA6 6 #define PA5 5 #define PA4 4 #define PA3 3 #define PA2 2 #define PA1 1 #define PA0 0 #define PINB _SFR_IO8(0x03) #define PINB7 7 #define PINB6 6 #define PINB5 5 #define PINB4 4 #define PINB3 3 #define PINB2 2 #define PINB1 1 #define PINB0 0 #define DDRB _SFR_IO8(0x04) #define DDB7 7 #define DDB6 6 #define DDB5 5 #define DDB4 4 #define DDB3 3 #define DDB2 2 #define DDB1 1 #define DDB0 0 #define PORTB _SFR_IO8(0x05) #define PB7 7 #define PB6 6 #define PB5 5 #define PB4 4 #define PB3 3 #define PB2 2 #define PB1 1 #define PB0 0 #define PINC _SFR_IO8(0x06) #define PINC7 7 #define PINC6 6 #define PINC5 5 #define PINC4 4 #define PINC3 3 #define PINC2 2 #define PINC1 1 #define PINC0 0 #define DDRC _SFR_IO8(0x07) #define DDC7 7 #define DDC6 6 #define DDC5 5 #define DDC4 4 #define DDC3 3 #define DDC2 2 #define DDC1 1 #define DDC0 0 #define PORTC _SFR_IO8(0x08) #define PC7 7 #define PC6 6 #define PC5 5 #define PC4 4 #define PC3 3 #define PC2 2 #define PC1 1 #define PC0 0 #define PIND _SFR_IO8(0x09) #define PIND7 7 #define PIND6 6 #define PIND5 5 #define PIND4 4 #define PIND3 3 #define PIND2 2 #define PIND1 1 #define PIND0 0 #define DDRD _SFR_IO8(0x0A) #define DDD7 7 #define DDD6 6 #define DDD5 5 #define DDD4 4 #define DDD3 3 #define DDD2 2 #define DDD1 1 #define DDD0 0 #define PORTD _SFR_IO8(0x0B) #define PD7 7 #define PD6 6 #define PD5 5 #define PD4 4 #define PD3 3 #define PD2 2 #define PD1 1 #define PD0 0 #define PINE _SFR_IO8(0x0C) #define PINE7 7 #define PINE6 6 #define PINE5 5 #define PINE4 4 #define PINE3 3 #define PINE2 2 #define PINE1 1 #define PINE0 0 #define DDRE _SFR_IO8(0x0D) #define DDE7 7 #define DDE6 6 #define DDE5 5 #define DDE4 4 #define DDE3 3 #define DDE2 2 #define DDE1 1 #define DDE0 0 #define PORTE _SFR_IO8(0x0E) #define PE7 7 #define PE6 6 #define PE5 5 #define PE4 4 #define PE3 3 #define PE2 2 #define PE1 1 #define PE0 0 #define PINF _SFR_IO8(0x0F) #define PINF7 7 #define PINF6 6 #define PINF5 5 #define PINF4 4 #define PINF3 3 #define PINF2 2 #define PINF1 1 #define PINF0 0 #define DDRF _SFR_IO8(0x10) #define DDF7 7 #define DDF6 6 #define DDF5 5 #define DDF4 4 #define DDF3 3 #define DDF2 2 #define DDF1 1 #define DDF0 0 #define PORTF _SFR_IO8(0x11) #define PF7 7 #define PF6 6 #define PF5 5 #define PF4 4 #define PF3 3 #define PF2 2 #define PF1 1 #define PF0 0 #define PING _SFR_IO8(0x12) #define PING5 5 #define PING4 4 #define PING3 3 #define PING2 2 #define PING1 1 #define PING0 0 #define DDRG _SFR_IO8(0x13) #define DDG4 4 #define DDG3 3 #define DDG2 2 #define DDG1 1 #define DDG0 0 #define PORTG _SFR_IO8(0x14) #define PG4 4 #define PG3 3 #define PG2 2 #define PG1 1 #define PG0 0 #define TIFR0 _SFR_IO8(0x15) #define TOV0 0 #define OCF0A 1 #define TIFR1 _SFR_IO8(0x16) #define TOV1 0 #define OCF1A 1 #define OCF1B 2 #define ICF1 5 #define TIFR2 _SFR_IO8(0x17) #define TOV2 0 #define OCF2A 1 /* Reserved [0x18..0x1B] */ #define EIFR _SFR_IO8(0x1C) #define INTF0 0 #define PCIF0 4 #define PCIF1 5 #define PCIF2 6 #define PCIF3 7 #define EIMSK _SFR_IO8(0x1D) #define INT0 0 #define PCIE0 4 #define PCIE1 5 #define PCIE2 6 #define PCIE3 7 #define GPIOR0 _SFR_IO8(0x1E) #define EECR _SFR_IO8(0x1F) #define EERIE 3 #define EEMWE 2 #define EEWE 1 #define EERE 0 #define EEDR _SFR_IO8(0X20) /* Combine EEARL and EEARH */ #define EEAR _SFR_IO16(0x21) #define EEARL _SFR_IO8(0x21) #define EEARH _SFR_IO8(0X22) /* 6-char sequence denoting where to find the EEPROM registers in memory space. Adresses denoted in hex syntax with uppercase letters. Used by the EEPROM subroutines. First two letters: EECR address. Second two letters: EEDR address. Last two letters: EEAR address. */ #define __EEPROM_REG_LOCATIONS__ 1F2021 #define GTCCR _SFR_IO8(0x23) #define PSR10 0 #define PSR2 1 #define TSM 7 #define TCCR0A _SFR_IO8(0x24) #define CS00 0 #define CS01 1 #define CS02 2 #define WGM01 3 #define COM0A0 4 #define COM0A1 5 #define WGM00 6 #define FOC0A 7 /* Reserved [0x25] */ #define TCNT0 _SFR_IO8(0X26) #define OCR0A _SFR_IO8(0X27) /* Reserved [0x28..0x29] */ #define GPIOR1 _SFR_IO8(0x2A) #define GPIOR2 _SFR_IO8(0x2B) #define SPCR _SFR_IO8(0x2C) #define SPR0 0 #define SPR1 1 #define CPHA 2 #define CPOL 3 #define MSTR 4 #define DORD 5 #define SPE 6 #define SPIE 7 #define SPSR _SFR_IO8(0x2D) #define SPI2X 0 #define WCOL 6 #define SPIF 7 #define SPDR _SFR_IO8(0X2E) /* Reserved [0x2F] */ #define ACSR _SFR_IO8(0x30) #define ACIS0 0 #define ACIS1 1 #define ACIC 2 #define ACIE 3 #define ACI 4 #define ACO 5 #define ACBG 6 #define ACD 7 #define OCDR _SFR_IO8(0x31) #define OCDR0 0 #define OCDR1 1 #define OCDR2 2 #define OCDR3 3 #define OCDR4 4 #define OCDR5 5 #define OCDR6 6 #define OCDR7 7 #define IDRD 7 /* Reserved [0x32] */ #define SMCR _SFR_IO8(0x33) #define SE 0 #define SM0 1 #define SM1 2 #define SM2 3 #define MCUSR _SFR_IO8(0x34) #define PORF 0 #define EXTRF 1 #define BORF 2 #define WDRF 3 #define JTRF 4 #define MCUCR _SFR_IO8(0X35) #define IVCE 0 #define IVSEL 1 #define PUD 4 #define JTD 7 /* Reserved [0x36] */ #define SPMCSR _SFR_IO8(0x37) #define SPMEN 0 #define PGERS 1 #define PGWRT 2 #define BLBSET 3 #define RWWSRE 4 #define RWWSB 6 #define SPMIE 7 /* Reserved [0x38..0x3C] */ /* SP [0x3D..0x3E] */ /* SREG [0x3F] */ #define WDTCR _SFR_MEM8(0x60) #define WDP0 0 #define WDP1 1 #define WDP2 2 #define WDE 3 #define WDCE 4 #define CLKPR _SFR_MEM8(0x61) #define CLKPS0 0 #define CLKPS1 1 #define CLKPS2 2 #define CLKPS3 3 #define CLKPCE 7 /* Reserved [0x62..0x63] */ #define PRR _SFR_MEM8(0x64) #define PRADC 0 #define PRUSART0 1 #define PRSPI 2 #define PRTIM1 3 #define PRLCD 4 /* Reserved [0x65] */ #define OSCCAL _SFR_MEM8(0x66) /* Reserved [0x67..0x68] */ #define EICRA _SFR_MEM8(0x69) #define ISC00 0 #define ISC01 1 /* Reserved [0x6A] */ #define PCMSK0 _SFR_MEM8(0x6B) #define PCINT0 0 #define PCINT1 1 #define PCINT2 2 #define PCINT3 3 #define PCINT4 4 #define PCINT5 5 #define PCINT6 6 #define PCINT7 7 #define PCMSK1 _SFR_MEM8(0x6C) #define PCINT8 0 #define PCINT9 1 #define PCINT10 2 #define PCINT11 3 #define PCINT12 4 #define PCINT13 5 #define PCINT14 6 #define PCINT15 7 #define PCMSK2 _SFR_MEM8(0x6D) #define PCINT16 0 #define PCINT17 1 #define PCINT18 2 #define PCINT19 3 #define PCINT20 4 #define PCINT21 5 #define PCINT22 6 #define PCINT23 7 #define TIMSK0 _SFR_MEM8(0x6E) #define TOIE0 0 #define OCIE0A 1 #define TIMSK1 _SFR_MEM8(0x6F) #define TOIE1 0 #define OCIE1A 1 #define OCIE1B 2 #define ICIE1 5 #define TIMSK2 _SFR_MEM8(0x70) #define TOIE2 0 #define OCIE2A 1 /* Reserved [0x71..0x72] */ #define PCMSK3 _SFR_MEM8(0x73) #define PCINT24 0 #define PCINT25 1 #define PCINT26 2 #define PCINT27 3 #define PCINT28 4 #define PCINT29 5 #define PCINT30 6 /* Reserved [0x74..0x77] */ /* Combine ADCL and ADCH */ #ifndef __ASSEMBLER__ #define ADC _SFR_MEM16(0x78) #endif #define ADCW _SFR_MEM16(0x78) #define ADCL _SFR_MEM8(0x78) #define ADCH _SFR_MEM8(0x79) #define ADCSRA _SFR_MEM8(0x7A) #define ADPS0 0 #define ADPS1 1 #define ADPS2 2 #define ADIE 3 #define ADIF 4 #define ADATE 5 #define ADSC 6 #define ADEN 7 #define ADCSRB _SFR_MEM8(0x7B) #define ADTS0 0 #define ADTS1 1 #define ADTS2 2 #define ACME 6 #define ADMUX _SFR_MEM8(0x7C) #define MUX0 0 #define MUX1 1 #define MUX2 2 #define MUX3 3 #define MUX4 4 #define ADLAR 5 #define REFS0 6 #define REFS1 7 /* Reserved [0x7D] */ #define DIDR0 _SFR_MEM8(0x7E) #define ADC0D 0 #define ADC1D 1 #define ADC2D 2 #define ADC3D 3 #define ADC4D 4 #define ADC5D 5 #define ADC6D 6 #define ADC7D 7 #define DIDR1 _SFR_MEM8(0x7F) #define AIN0D 0 #define AIN1D 1 #define TCCR1A _SFR_MEM8(0X80) #define WGM10 0 #define WGM11 1 #define COM1B0 4 #define COM1B1 5 #define COM1A0 6 #define COM1A1 7 #define TCCR1B _SFR_MEM8(0X81) #define CS10 0 #define CS11 1 #define CS12 2 #define WGM12 3 #define WGM13 4 #define ICES1 6 #define ICNC1 7 #define TCCR1C _SFR_MEM8(0x82) #define FOC1B 6 #define FOC1A 7 /* Reserved [0x83] */ /* Combine TCNT1L and TCNT1H */ #define TCNT1 _SFR_MEM16(0x84) #define TCNT1L _SFR_MEM8(0x84) #define TCNT1H _SFR_MEM8(0x85) /* Combine ICR1L and ICR1H */ #define ICR1 _SFR_MEM16(0x86) #define ICR1L _SFR_MEM8(0x86) #define ICR1H _SFR_MEM8(0x87) /* Combine OCR1AL and OCR1AH */ #define OCR1A _SFR_MEM16(0x88) #define OCR1AL _SFR_MEM8(0x88) #define OCR1AH _SFR_MEM8(0x89) /* Combine OCR1BL and OCR1BH */ #define OCR1B _SFR_MEM16(0x8A) #define OCR1BL _SFR_MEM8(0x8A) #define OCR1BH _SFR_MEM8(0x8B) /* Reserved [0x8C..0xAF] */ #define TCCR2A _SFR_MEM8(0xB0) #define CS20 0 #define CS21 1 #define CS22 2 #define WGM21 3 #define COM2A0 4 #define COM2A1 5 #define WGM20 6 #define FOC2A 7 /* Reserved [0xB1] */ #define TCNT2 _SFR_MEM8(0xB2) #define OCR2A _SFR_MEM8(0xB3) /* Reserved [0xB4..0xB5] */ #define ASSR _SFR_MEM8(0xB6) #define TCR2UB 0 #define OCR2UB 1 #define TCN2UB 2 #define AS2 3 #define EXCLK 4 /* Reserved [0xB7] */ #define USICR _SFR_MEM8(0xB8) #define USITC 0 #define USICLK 1 #define USICS0 2 #define USICS1 3 #define USIWM0 4 #define USIWM1 5 #define USIOIE 6 #define USISIE 7 #define USISR _SFR_MEM8(0xB9) #define USICNT0 0 #define USICNT1 1 #define USICNT2 2 #define USICNT3 3 #define USIDC 4 #define USIPF 5 #define USIOIF 6 #define USISIF 7 #define USIDR _SFR_MEM8(0xBA) /* Reserved [0xBB..0xBF] */ #define UCSR0A _SFR_MEM8(0xC0) #define MPCM0 0 #define U2X0 1 #define UPE0 2 #define DOR0 3 #define FE0 4 #define UDRE0 5 #define TXC0 6 #define RXC0 7 #define UCSR0B _SFR_MEM8(0XC1) #define TXB80 0 #define RXB80 1 #define UCSZ02 2 #define TXEN0 3 #define RXEN0 4 #define UDRIE0 5 #define TXCIE0 6 #define RXCIE0 7 #define UCSR0C _SFR_MEM8(0xC2) #define UCPOL0 0 #define UCSZ00 1 #define UCSZ01 2 #define USBS0 3 #define UPM00 4 #define UPM01 5 #define UMSEL0 6 /* Reserved [0xC3] */ /* Combine UBRR0L and UBRR0H */ #define UBRR0 _SFR_MEM16(0xC4) #define UBRR0L _SFR_MEM8(0xC4) #define UBRR0H _SFR_MEM8(0xC5) #define UDR0 _SFR_MEM8(0XC6) /* Reserved [0xC7..0xD7] */ #define PINH _SFR_MEM8(0xD8) #define PINH7 7 #define PINH6 6 #define PINH5 5 #define PINH4 4 #define PINH3 3 #define PINH2 2 #define PINH1 1 #define PINH0 0 #define DDRH _SFR_MEM8(0xD9) #define DDH7 7 #define DDH6 6 #define DDH5 5 #define DDH4 4 #define DDH3 3 #define DDH2 2 #define DDH1 1 #define DDH0 0 #define PORTH _SFR_MEM8(0xDA) #define PH7 7 #define PH6 6 #define PH5 5 #define PH4 4 #define PH3 3 #define PH2 2 #define PH1 1 #define PH0 0 #define PINJ _SFR_MEM8(0xDB) #define PINJ6 6 #define PINJ5 5 #define PINJ4 4 #define PINJ3 3 #define PINJ2 2 #define PINJ1 1 #define PINJ0 0 #define DDRJ _SFR_MEM8(0xDC) #define DDJ6 6 #define DDJ5 5 #define DDJ4 4 #define DDJ3 3 #define DDJ2 2 #define DDJ1 1 #define DDJ0 0 #define PORTJ _SFR_MEM8(0xDD) #define PJ6 6 #define PJ5 5 #define PJ4 4 #define PJ3 3 #define PJ2 2 #define PJ1 1 #define PJ0 0 /* Reserved [0xDE..0xE3] */ #define LCDCRA _SFR_MEM8(0XE4) #define LCDBL 0 #define LCDIE 3 #define LCDIF 4 #define LCDAB 6 #define LCDEN 7 #define LCDCRB _SFR_MEM8(0XE5) #define LCDPM0 0 #define LCDPM1 1 #define LCDPM2 2 #define LCDPM3 3 #define LCDMUX0 4 #define LCDMUX1 5 #define LCD2B 6 #define LCDCS 7 #define LCDFRR _SFR_MEM8(0XE6) #define LCDCD0 0 #define LCDCD1 1 #define LCDCD2 2 #define LCDPS0 4 #define LCDPS1 5 #define LCDPS2 6 #define LCDCCR _SFR_MEM8(0XE7) #define LCDCC0 0 #define LCDCC1 1 #define LCDCC2 2 #define LCDCC3 3 #define LCDDC0 5 #define LCDDC1 6 #define LCDDC2 7 /* Reserved [0xE8..0xEB] */ #define LCDDR00 _SFR_MEM8(0XEC) #define SEG000 0 #define SEG001 1 #define SEG002 2 #define SEG003 3 #define SEG004 4 #define SEG005 5 #define SEG006 6 #define SEG007 7 #define LCDDR01 _SFR_MEM8(0XED) #define SEG008 0 #define SEG009 1 #define SEG010 2 #define SEG011 3 #define SEG012 4 #define SEG013 5 #define SEG014 6 #define SEG015 7 #define LCDDR02 _SFR_MEM8(0XEE) #define SEG016 0 #define SEG017 1 #define SEG018 2 #define SEG019 3 #define SEG020 4 #define SEG021 5 #define SEG022 6 #define SEG023 7 #define LCDDR03 _SFR_MEM8(0XEF) #define SEG024 0 #define SEG025 1 #define SEG026 2 #define SEG027 3 #define SEG028 4 #define SEG029 5 #define SEG030 6 #define SEG031 7 #define LCDDR04 _SFR_MEM8(0XF0) #define SEG032 0 #define SEG033 1 #define SEG034 2 #define SEG035 3 #define SEG036 4 #define SEG037 5 #define SEG038 6 #define SEG039 7 #define LCDDR05 _SFR_MEM8(0XF1) #define SEG100 0 #define SEG101 1 #define SEG102 2 #define SEG103 3 #define SEG104 4 #define SEG105 5 #define SEG106 6 #define SEG107 7 #define LCDDR06 _SFR_MEM8(0XF2) #define SEG108 0 #define SEG109 1 #define SEG110 2 #define SEG111 3 #define SEG112 4 #define SEG113 5 #define SEG114 6 #define SEG115 7 #define LCDDR07 _SFR_MEM8(0XF3) #define SEG116 0 #define SEG117 1 #define SEG118 2 #define SEG119 3 #define SEG120 4 #define SEG121 5 #define SEG122 6 #define SEG123 7 #define LCDDR08 _SFR_MEM8(0XF4) #define SEG124 0 #define SEG125 1 #define SEG126 2 #define SEG127 3 #define SEG128 4 #define SEG129 5 #define SEG130 6 #define SEG131 7 #define LCDDR09 _SFR_MEM8(0XF5) #define SEG132 0 #define SEG133 1 #define SEG134 2 #define SEG135 3 #define SEG136 4 #define SEG137 5 #define SEG138 6 #define SEG139 7 #define LCDDR10 _SFR_MEM8(0XF6) #define SEG200 0 #define SEG201 1 #define SEG202 2 #define SEG203 3 #define SEG204 4 #define SEG205 5 #define SEG206 6 #define SEG207 7 #define LCDDR11 _SFR_MEM8(0XF7) #define SEG208 0 #define SEG209 1 #define SEG210 2 #define SEG211 3 #define SEG212 4 #define SEG213 5 #define SEG214 6 #define SEG215 7 #define LCDDR12 _SFR_MEM8(0XF8) #define SEG216 0 #define SEG217 1 #define SEG218 2 #define SEG219 3 #define SEG220 4 #define SEG221 5 #define SEG222 6 #define SEG223 7 #define LCDDR13 _SFR_MEM8(0XF9) #define SEG224 0 #define SEG225 1 #define SEG226 2 #define SEG227 3 #define SEG228 4 #define SEG229 5 #define SEG230 6 #define SEG231 7 #define LCDDR14 _SFR_MEM8(0XFA) #define SEG232 0 #define SEG233 1 #define SEG234 2 #define SEG235 3 #define SEG236 4 #define SEG237 5 #define SEG238 6 #define SEG239 7 #define LCDDR15 _SFR_MEM8(0XFB) #define SEG300 0 #define SEG301 1 #define SEG302 2 #define SEG303 3 #define SEG304 4 #define SEG305 5 #define SEG306 6 #define SEG307 7 #define LCDDR16 _SFR_MEM8(0XFC) #define SEG308 0 #define SEG309 1 #define SEG310 2 #define SEG311 3 #define SEG312 4 #define SEG313 5 #define SEG314 6 #define SEG315 7 #define LCDDR17 _SFR_MEM8(0XFD) #define SEG316 0 #define SEG217 1 #define SEG318 2 #define SEG319 3 #define SEG320 4 #define SEG321 5 #define SEG322 6 #define SEG323 7 #define LCDDR18 _SFR_MEM8(0XFE) #define SEG324 0 #define SEG325 1 #define SEG326 2 #define SEG327 3 #define SEG328 4 #define SEG329 5 #define SEG330 6 #define SEG331 7 #define LCDDR19 _SFR_MEM8(0XFF) #define SEG332 0 #define SEG333 1 #define SEG334 2 #define SEG335 3 #define SEG336 4 #define SEG337 5 #define SEG338 6 #define SEG339 7 /* Interrupt vectors */ /* Vector 0 is the reset vector */ /* External Interrupt Request 0 */ #define INT0_vect_num 1 #define INT0_vect _VECTOR(1) #define SIG_INTERRUPT0 _VECTOR(1) /* Pin Change Interrupt Request 0 */ #define PCINT0_vect_num 2 #define PCINT0_vect _VECTOR(2) #define SIG_PIN_CHANGE0 _VECTOR(2) /* Pin Change Interrupt Request 1 */ #define PCINT1_vect_num 3 #define PCINT1_vect _VECTOR(3) #define SIG_PIN_CHANGE1 _VECTOR(3) /* Timer/Counter2 Compare Match */ #define TIMER2_COMP_vect_num 4 #define TIMER2_COMP_vect _VECTOR(4) #define SIG_OUTPUT_COMPARE2 _VECTOR(4) /* Timer/Counter2 Overflow */ #define TIMER2_OVF_vect_num 5 #define TIMER2_OVF_vect _VECTOR(5) #define SIG_OVERFLOW2 _VECTOR(5) /* Timer/Counter1 Capture Event */ #define TIMER1_CAPT_vect_num 6 #define TIMER1_CAPT_vect _VECTOR(6) #define SIG_INPUT_CAPTURE1 _VECTOR(6) /* Timer/Counter1 Compare Match A */ #define TIMER1_COMPA_vect_num 7 #define TIMER1_COMPA_vect _VECTOR(7) #define SIG_OUTPUT_COMPARE1A _VECTOR(7) /* Timer/Counter Compare Match B */ #define TIMER1_COMPB_vect_num 8 #define TIMER1_COMPB_vect _VECTOR(8) #define SIG_OUTPUT_COMPARE1B _VECTOR(8) /* Timer/Counter1 Overflow */ #define TIMER1_OVF_vect_num 9 #define TIMER1_OVF_vect _VECTOR(9) #define SIG_OVERFLOW1 _VECTOR(9) /* Timer/Counter0 Compare Match */ #define TIMER0_COMP_vect_num 10 #define TIMER0_COMP_vect _VECTOR(10) #define SIG_OUTPUT_COMPARE0 _VECTOR(10) /* Timer/Counter0 Overflow */ #define TIMER0_OVF_vect_num 11 #define TIMER0_OVF_vect _VECTOR(11) #define SIG_OVERFLOW0 _VECTOR(11) /* SPI Serial Transfer Complete */ #define SPI_STC_vect_num 12 #define SPI_STC_vect _VECTOR(12) #define SIG_SPI _VECTOR(12) /* USART, Rx Complete */ #define USART_RX_vect_num 13 #define USART_RX_vect _VECTOR(13) #define SIG_UART_RECV _VECTOR(13) /* USART Data register Empty */ #define USART_UDRE_vect_num 14 #define USART_UDRE_vect _VECTOR(14) #define SIG_UART_DATA _VECTOR(14) /* USART0, Tx Complete */ #define USART0_TX_vect_num 15 #define USART0_TX_vect _VECTOR(15) #define SIG_UART_TRANS _VECTOR(15) /* USI Start Condition */ #define USI_START_vect_num 16 #define USI_START_vect _VECTOR(16) #define SIG_USI_START _VECTOR(16) /* USI Overflow */ #define USI_OVERFLOW_vect_num 17 #define USI_OVERFLOW_vect _VECTOR(17) #define SIG_USI_OVERFLOW _VECTOR(17) /* Analog Comparator */ #define ANALOG_COMP_vect_num 18 #define ANALOG_COMP_vect _VECTOR(18) #define SIG_COMPARATOR _VECTOR(18) /* ADC Conversion Complete */ #define ADC_vect_num 19 #define ADC_vect _VECTOR(19) #define SIG_ADC _VECTOR(19) /* EEPROM Ready */ #define EE_READY_vect_num 20 #define EE_READY_vect _VECTOR(20) #define SIG_EEPROM_READY _VECTOR(20) /* Store Program Memory Read */ #define SPM_READY_vect_num 21 #define SPM_READY_vect _VECTOR(21) #define SIG_SPM_READY _VECTOR(21) /* LCD Start of Frame */ #define LCD_vect_num 22 #define LCD_vect _VECTOR(22) #define SIG_LCD _VECTOR(22) /* Pin Change Interrupt Request 2 */ #define PCINT2_vect_num 23 #define PCINT2_vect _VECTOR(23) #define SIG_PIN_CHANGE2 _VECTOR(23) /* Pin Change Interrupt Request 3 */ #define PCINT3_vect_num 24 #define PCINT3_vect _VECTOR(24) #define SIG_PIN_CHANGE3 _VECTOR(24) #define _VECTORS_SIZE 100 /* Constants */ #define SPM_PAGESIZE 256 #define RAMEND 0x10FF #define XRAMEND RAMEND #define E2END 0x7FF #define E2PAGESIZE 8 #define FLASHEND 0xFFFF /* Fuses */ #define FUSE_MEMORY_SIZE 3 /* Low Fuse Byte */ #define FUSE_CKSEL0 (unsigned char)~_BV(0) #define FUSE_CKSEL1 (unsigned char)~_BV(1) #define FUSE_CKSEL2 (unsigned char)~_BV(2) #define FUSE_CKSEL3 (unsigned char)~_BV(3) #define FUSE_SUT0 (unsigned char)~_BV(4) #define FUSE_SUT1 (unsigned char)~_BV(5) #define FUSE_CKOUT (unsigned char)~_BV(6) #define FUSE_CKDIV8 (unsigned char)~_BV(7) #define LFUSE_DEFAULT (FUSE_CKSEL0 & FUSE_CKSEL2 & FUSE_CKSEL3 & FUSE_SUT0 & FUSE_CKDIV8) /* High Fuse Byte */ #define FUSE_BOOTRST (unsigned char)~_BV(0) #define FUSE_BOOTSZ0 (unsigned char)~_BV(1) #define FUSE_BOOTSZ1 (unsigned char)~_BV(2) #define FUSE_EESAVE (unsigned char)~_BV(3) #define FUSE_WDTON (unsigned char)~_BV(4) #define FUSE_SPIEN (unsigned char)~_BV(5) #define FUSE_JTAGEN (unsigned char)~_BV(6) #define FUSE_OCDEN (unsigned char)~_BV(7) #define HFUSE_DEFAULT (FUSE_BOOTSZ0 & FUSE_BOOTSZ1 & FUSE_SPIEN & FUSE_JTAGEN) /* Extended Fuse Byte */ #define FUSE_RSTDISBL (unsigned char)~_BV(0) #define FUSE_BODLEVEL0 (unsigned char)~_BV(1) #define FUSE_BODLEVEL1 (unsigned char)~_BV(2) #define EFUSE_DEFAULT (0xFF) /* Lock Bits */ #define __LOCK_BITS_EXIST #define __BOOT_LOCK_BITS_0_EXIST #define __BOOT_LOCK_BITS_1_EXIST /* Signature */ #define SIGNATURE_0 0x1E #define SIGNATURE_1 0x96 #define SIGNATURE_2 0x04 #endif /* _AVR_IOM6490_H_ */
synnema/rgbcontopH
hex_for_testing/usr_lib_avr__backup/include/avr/iom6490.h
C
gpl-3.0
23,635
/* Lowercase mapping for UTF-16 strings (locale dependent). Copyright (C) 2009-2013 Free Software Foundation, Inc. Written by Bruno Haible <bruno@clisp.org>, 2009. 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; 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 Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this program. If not, see <http://www.gnu.org/licenses/>. */ #include <config.h> /* Specification. */ #include "unicase.h" #include <stddef.h> #include "unicasemap.h" #include "special-casing.h" uint16_t * u16_tolower (const uint16_t *s, size_t n, const char *iso639_language, uninorm_t nf, uint16_t *resultbuf, size_t *lengthp) { return u16_casemap (s, n, unicase_empty_prefix_context, unicase_empty_suffix_context, iso639_language, uc_tolower, offsetof (struct special_casing_rule, lower[0]), nf, resultbuf, lengthp); }
Distrotech/libunistring
lib/unicase/u16-tolower.c
C
gpl-3.0
1,443
// Pingus - A free Lemmings clone // Copyright (C) 2002 Ingo Ruhnke <grumbel@gmx.de> // // This program is free software: you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any later version. // // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU General Public License // along with this program. If not, see <http://www.gnu.org/licenses/>. #include "pingus/string_format.hpp" #include <sstream> #include "engine/display/font.hpp" #include "util/utf8.hpp" std::string StringFormat::break_line (const std::string& text_, int width, const Font& font) { std::string text = text_; UTF8::iterator beg(text); float line_width = 0; std::ostringstream out; UTF8::iterator it(text); while(it.next()) { std::string word = UTF8::substr(beg, it+1); float word_width = font.get_width(word); if (UTF8::is_linebreak_character(*it)) { if ((line_width + word_width) > width) { out << "\n" << word; line_width = word_width; } else { out << word; line_width += word_width; } beg = it+1; } else if (*it == '\n') { line_width = 0; } } std::string word = UTF8::substr(beg, UTF8::iterator(text, text.end())); float word_width = font.get_width(word); if ((line_width + word_width) > width) { out << "\n" << word; } else { out << word; } return out.str(); } /* EOF */
xarnze/pingus
src/pingus/string_format.cpp
C++
gpl-3.0
1,831
#!/bin/bash -x apt-get -y update apt-get install -y vim libffi-dev libssl-dev python-dev python-pip python-virtualenv
rcherrueau/enos
tests/functionnal/tests/packaging/scripts/install_deps.sh
Shell
gpl-3.0
120
#!/usr/bin/python # -*- coding: utf-8 -*- # Copyright (C) 2010-2011 # Drakmail < drakmail@gmail.com > # NomerUNO < uno.kms@gmail.com > # Platon Peacel☮ve <platonny@ngs.ru> # Elec.Lomy.RU <Elec.Lomy.RU@gmail.com> # ADcomp <david.madbox@gmail.com> # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # You should have received a copy of the GNU General Public License # along with this program. If not, see <http://www.gnu.org/licenses/>. import os from Queue import Queue from subprocess import Popen from debug import logINFO devnull = open(os.path.devnull, 'w') q = None def start(): global q q = Queue() def stop(): while not q.empty(): q.get() q.task_done() q.join() def check_programs(): programs = [] while not q.empty(): program = q.get() if program.poll() == None: programs.append(program) q.task_done() for program in programs: q.put(program) return True def launch_command(cmd): try: p = Popen(cmd, stdout = devnull, stderr = devnull ) q.put(p) except OSError, e: logINFO("unable to execute a command: %s : %s" % (repr(cmd), repr(e) ))
tectronics/snapfly
src/launcher.py
Python
gpl-3.0
1,632
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd"> <html xmlns="http://www.w3.org/1999/xhtml" dir="{S_CONTENT_DIRECTION}" lang="{S_USER_LANG}" xml:lang="{S_USER_LANG}"> <head> <meta http-equiv="content-type" content="text/html; charset={S_CONTENT_ENCODING}" /> <meta http-equiv="content-style-type" content="text/css" /> <meta http-equiv="content-language" content="{S_USER_LANG}" /> <meta http-equiv="imagetoolbar" content="no" /> <meta name="resource-type" content="document" /> <meta name="distribution" content="global" /> <meta name="copyright" content="2000, 2002, 2005, 2007 phpBB Group" /> <meta name="keywords" content="" /> <meta name="description" content="" /> <meta name="robots" content="noindex" /> {META} <title>{SITENAME} &bull; {PAGE_TITLE}</title> <link href="{T_THEME_PATH}/print.css" rel="stylesheet" type="text/css" /> </head> <body id="phpbb"> <div id="wrap"> <a id="top" name="top" accesskey="t"></a> <div id="page-header"> <h1>{SITENAME}</h1> <p>{SITE_DESCRIPTION}<br /><a href="{U_FORUM}">{U_FORUM}</a></p> <h2>{TOPIC_TITLE}</h2> <p><a href="{U_TOPIC}">{U_TOPIC}</a></p> </div> <div id="page-body"> <div class="page-number">{PAGE_NUMBER}</div> <!-- BEGIN postrow --> <div class="post"> <h3>{postrow.POST_SUBJECT}</h3> <div class="date">{postrow.MINI_POST_IMG}{L_POSTED}: <strong>{postrow.POST_DATE}</strong></div> <div class="author">{L_POST_BY_AUTHOR} <strong>{postrow.POST_AUTHOR}</strong></div> <div class="content">{postrow.MESSAGE}</div> </div> <hr /> <!-- END postrow --> </div> <!-- We request you retain the full copyright notice below including the link to www.phpbb.com. This not only gives respect to the large amount of time given freely by the developers but also helps build interest, traffic and use of phpBB3. If you (honestly) cannot retain the full copyright we ask you at least leave in place the "Powered by phpBB" line, with "phpBB" linked to www.phpbb.com. If you refuse to include even this then support on our forums may be affected. The phpBB Group : 2006 //--> <div id="page-footer"> <div class="page-number">{S_TIMEZONE}<br />{PAGE_NUMBER}</div> <div class="copyright">Powered by phpBB &copy; 2000, 2002, 2005, 2007 phpBB Group<br />http://www.phpbb.com/</div> </div> </div> </body> </html>
RolePlayGateway/roleplaygateway
styles/prosilver/template/viewtopic_print.html
HTML
gpl-3.0
2,368
/* * Copyright 2011-2019 Arx Libertatis Team (see the AUTHORS file) * * This file is part of Arx Libertatis. * * Arx Libertatis 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. * * Arx Libertatis 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 Arx Libertatis. If not, see <http://www.gnu.org/licenses/>. */ #ifndef ARX_GAME_SPELL_CHEAT_H #define ARX_GAME_SPELL_CHEAT_H enum CheatRune { CheatRune_AAM, CheatRune_COMUNICATUM, CheatRune_KAOM, CheatRune_MEGA, CheatRune_SPACIUM, CheatRune_STREGUM, CheatRune_U, CheatRune_W, CheatRune_S, CheatRune_P, CheatRune_M, CheatRune_A, CheatRune_X, CheatRune_26, CheatRune_O, CheatRune_R, CheatRune_F, CheatRune_Passwall, CheatRune_ChangeSkin, CheatRune_None = 255 }; void handleCheatRuneDetection(CheatRune rune); extern long BH_MODE; extern long passwall; extern long cur_mx; extern long cur_pom; extern long cur_rf; extern long cur_mr; extern long sp_arm; extern long cur_mega; extern long sp_wep; extern short uw_mode; extern long sp_max; void CheatDrawText(); void CheatReset(); void CheatDetectionReset(); void CheckMr(); #endif // ARX_GAME_SPELL_CHEAT_H
Dimoks/ArxLibertatis_fork
src/game/spell/Cheat.h
C
gpl-3.0
1,594
#!/usr/bin/python # # Copyright (c) 2016 Matt Davis, <mdavis@ansible.com> # Chris Houseknecht, <house@redhat.com> # # This file is part of Ansible # # Ansible 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. # # Ansible 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 Ansible. If not, see <http://www.gnu.org/licenses/>. # DOCUMENTATION = ''' --- module: azure_rm_publicipaddress version_added: "2.1" short_description: Manage Azure Public IP Addresses. description: - Create, update and delete a Public IP address. Allows setting and updating the address allocation method and domain name label. Use the azure_rm_networkinterface module to associate a Public IP with a network interface. options: resource_group: description: - Name of resource group with which the Public IP is associated. required: true allocation_method: description: - Control whether the assigned Public IP remains permanently assigned to the object. If not set to 'Static', the IP address my changed anytime an associated virtual machine is power cycled. choices: - Dynamic - Static default: Dynamic required: false domain_name_label: description: - The customizable portion of the FQDN assigned to public IP address. This is an explicit setting. If no value is provided, any existing value will be removed on an existing public IP. aliases: - domain_name_label required: false default: null name: description: - Name of the Public IP. required: true state: description: - Assert the state of the Public IP. Use 'present' to create or update a and 'absent' to delete. default: present choices: - absent - present required: false location: description: - Valid azure location. Defaults to location of the resource group. default: resource_group location required: false extends_documentation_fragment: - azure - azure_tags author: - "Chris Houseknecht (@chouseknecht)" - "Matt Davis (@nitzmahone)" ''' EXAMPLES = ''' - name: Create a public ip address azure_rm_publicipaddress: resource_group: testing name: my_public_ip allocation_method: Static domain_name: foobar - name: Delete public ip azure_rm_publicipaddress: resource_group: testing name: my_public_ip state: absent ''' RETURN = ''' state: description: Facts about the current state of the object. returned: always type: dict sample:{ "dns_settings": {}, "etag": "W/\"a5e56955-12df-445a-bda4-dc129d22c12f\"", "idle_timeout_in_minutes": 4, "ip_address": "52.160.103.93", "location": "westus", "name": "publicip002", "provisioning_state": "Succeeded", "public_ip_allocation_method": "Static", "tags": {}, "type": "Microsoft.Network/publicIPAddresses" } ''' from ansible.module_utils.basic import * from ansible.module_utils.azure_rm_common import * try: from msrestazure.azure_exceptions import CloudError from azure.mgmt.network.models import PublicIPAddress, PublicIPAddressDnsSettings except ImportError: # This is handled in azure_rm_common pass NAME_PATTERN = re.compile(r"^[a-z][a-z0-9-]{1,61}[a-z0-9]$") def pip_to_dict(pip): result = dict( name=pip.name, type=pip.type, location=pip.location, tags=pip.tags, public_ip_allocation_method=pip.public_ip_allocation_method.value, dns_settings=dict(), ip_address=pip.ip_address, idle_timeout_in_minutes=pip.idle_timeout_in_minutes, provisioning_state=pip.provisioning_state, etag=pip.etag ) if pip.dns_settings: result['dns_settings']['domain_name_label'] = pip.dns_settings.domain_name_label result['dns_settings']['fqdn'] = pip.dns_settings.fqdn result['dns_settings']['reverse_fqdn'] = pip.dns_settings.reverse_fqdn return result class AzureRMPublicIPAddress(AzureRMModuleBase): def __init__(self): self.module_arg_spec = dict( resource_group=dict(type='str', required=True), name=dict(type='str', required=True), state=dict(type='str', default='present', choices=['present', 'absent']), location=dict(type='str'), allocation_method=dict(type='str', default='Dynamic', choices=['Dynamic', 'Static']), domain_name=dict(type='str', aliases=['domain_name_label']), ) self.resource_group = None self.name = None self.location = None self.state = None self.tags = None self.allocation_method = None self.domain_name = None self.results = dict( changed=False, state=dict() ) super(AzureRMPublicIPAddress, self).__init__(derived_arg_spec=self.module_arg_spec, supports_check_mode=True) def exec_module(self, **kwargs): for key in self.module_arg_spec.keys() + ['tags']: setattr(self, key, kwargs[key]) results = dict() changed = False pip = None resource_group = self.get_resource_group(self.resource_group) if not self.location: # Set default location self.location = resource_group.location if not NAME_PATTERN.match(self.name): self.fail("Parameter error: name must begin with a letter or number, end with a letter or number " "and contain at least one number.") try: self.log("Fetch public ip {0}".format(self.name)) pip = self.network_client.public_ip_addresses.get(self.resource_group, self.name) self.check_provisioning_state(pip, self.state) self.log("PIP {0} exists".format(self.name)) if self.state == 'present': results = pip_to_dict(pip) if self.domain_name != results['dns_settings'].get('domain_name_label'): self.log('CHANGED: domain_name_label') changed = True results['dns_settings']['domain_name_label'] =self.domain_name if self.allocation_method != results['public_ip_allocation_method']: self.log("CHANGED: allocation_method") changed = True results['public_ip_allocation_method'] = self.allocation_method update_tags, results['tags'] = self.update_tags(results['tags']) if update_tags: changed = True elif self.state == 'absent': self.log("CHANGED: public ip {0} exists but requested state is 'absent'".format(self.name)) changed = True except CloudError: self.log('Public ip {0} does not exist'.format(self.name)) if self.state == 'present': self.log("CHANGED: pip {0} does not exist but requested state is 'present'".format(self.name)) changed = True self.results['state'] = results self.results['changed'] = changed if self.check_mode: return results if changed: if self.state == 'present': if not pip: self.log("Create new Public IP {0}".format(self.name)) pip = PublicIPAddress( location=self.location, public_ip_allocation_method=self.allocation_method, ) if self.tags: pip.tags = self.tags if self.domain_name: pip.dns_settings = PublicIPAddressDnsSettings( domain_name_label=self.domain_name ) else: self.log("Update Public IP {0}".format(self.name)) pip = PublicIPAddress( location=results['location'], public_ip_allocation_method=results['public_ip_allocation_method'], tags=results['tags'] ) if self.domain_name: pip.dns_settings = PublicIPAddressDnsSettings( domain_name_label=self.domain_name ) self.results['state'] = self.create_or_update_pip(pip) elif self.state == 'absent': self.log('Delete public ip {0}'.format(self.name)) self.delete_pip() return self.results def create_or_update_pip(self, pip): try: poller = self.network_client.public_ip_addresses.create_or_update(self.resource_group, self.name, pip) pip = self.get_poller_result(poller) except Exception as exc: self.fail("Error creating or updating {0} - {1}".format(self.name, str(exc))) return pip_to_dict(pip) def delete_pip(self): try: poller = self.network_client.public_ip_addresses.delete(self.resource_group, self.name) self.get_poller_result(poller) except Exception as exc: self.fail("Error deleting {0} - {1}".format(self.name, str(exc))) # Delete returns nada. If we get here, assume that all is well. self.results['state']['status'] = 'Deleted' return True def main(): AzureRMPublicIPAddress() if __name__ == '__main__': main()
hlieberman/ansible-modules-core
cloud/azure/azure_rm_publicipaddress.py
Python
gpl-3.0
10,272
#include "config.h" #include "util.hh" #include "local-store.hh" #include "globals.hh" #include <cstdlib> #include <sys/types.h> #include <sys/stat.h> #include <unistd.h> #include <errno.h> #include <stdio.h> namespace nix { static void makeWritable(const Path & path) { struct stat st; if (lstat(path.c_str(), &st)) throw SysError(format("getting attributes of path `%1%'") % path); if (chmod(path.c_str(), st.st_mode | S_IWUSR) == -1) throw SysError(format("changing writability of `%1%'") % path); } struct MakeReadOnly { Path path; MakeReadOnly(const Path & path) : path(path) { } ~MakeReadOnly() { try { /* This will make the path read-only. */ if (path != "") canonicaliseTimestampAndPermissions(path); } catch (...) { ignoreException(); } } }; LocalStore::InodeHash LocalStore::loadInodeHash() { printMsg(lvlDebug, "loading hash inodes in memory"); InodeHash inodeHash; AutoCloseDir dir = opendir(linksDir.c_str()); if (!dir) throw SysError(format("opening directory `%1%'") % linksDir); struct dirent * dirent; while (errno = 0, dirent = readdir(dir)) { /* sic */ checkInterrupt(); // We don't care if we hit non-hash files, anything goes inodeHash.insert(dirent->d_ino); } if (errno) throw SysError(format("reading directory `%1%'") % linksDir); printMsg(lvlTalkative, format("loaded %1% hash inodes") % inodeHash.size()); return inodeHash; } Strings LocalStore::readDirectoryIgnoringInodes(const Path & path, const InodeHash & inodeHash) { Strings names; AutoCloseDir dir = opendir(path.c_str()); if (!dir) throw SysError(format("opening directory `%1%'") % path); struct dirent * dirent; while (errno = 0, dirent = readdir(dir)) { /* sic */ checkInterrupt(); if (inodeHash.count(dirent->d_ino)) { printMsg(lvlDebug, format("`%1%' is already linked") % dirent->d_name); continue; } string name = dirent->d_name; if (name == "." || name == "..") continue; names.push_back(name); } if (errno) throw SysError(format("reading directory `%1%'") % path); return names; } void LocalStore::optimisePath_(OptimiseStats & stats, const Path & path, InodeHash & inodeHash) { checkInterrupt(); struct stat st; if (lstat(path.c_str(), &st)) throw SysError(format("getting attributes of path `%1%'") % path); if (S_ISDIR(st.st_mode)) { Strings names = readDirectoryIgnoringInodes(path, inodeHash); foreach (Strings::iterator, i, names) optimisePath_(stats, path + "/" + *i, inodeHash); return; } /* We can hard link regular files and maybe symlinks. */ if (!S_ISREG(st.st_mode) #if CAN_LINK_SYMLINK && !S_ISLNK(st.st_mode) #endif ) return; /* Sometimes SNAFUs can cause files in the Nix store to be modified, in particular when running programs as root under NixOS (example: $fontconfig/var/cache being modified). Skip those files. FIXME: check the modification time. */ if (S_ISREG(st.st_mode) && (st.st_mode & S_IWUSR)) { printMsg(lvlError, format("skipping suspicious writable file `%1%'") % path); return; } /* This can still happen on top-level files. */ if (st.st_nlink > 1 && inodeHash.count(st.st_ino)) { printMsg(lvlDebug, format("`%1%' is already linked, with %2% other file(s).") % path % (st.st_nlink - 2)); return; } /* Hash the file. Note that hashPath() returns the hash over the NAR serialisation, which includes the execute bit on the file. Thus, executable and non-executable files with the same contents *won't* be linked (which is good because otherwise the permissions would be screwed up). Also note that if `path' is a symlink, then we're hashing the contents of the symlink (i.e. the result of readlink()), not the contents of the target (which may not even exist). */ Hash hash = hashPath(htSHA256, path).first; printMsg(lvlDebug, format("`%1%' has hash `%2%'") % path % printHash(hash)); /* Check if this is a known hash. */ Path linkPath = linksDir + "/" + printHash32(hash); retry: if (!pathExists(linkPath)) { /* Nope, create a hard link in the links directory. */ if (link(path.c_str(), linkPath.c_str()) == 0) { inodeHash.insert(st.st_ino); return; } if (errno != EEXIST) throw SysError(format("cannot link `%1%' to `%2%'") % linkPath % path); /* Fall through if another process created ‘linkPath’ before we did. */ } /* Yes! We've seen a file with the same contents. Replace the current file with a hard link to that file. */ struct stat stLink; if (lstat(linkPath.c_str(), &stLink)) throw SysError(format("getting attributes of path `%1%'") % linkPath); if (st.st_ino == stLink.st_ino) { printMsg(lvlDebug, format("`%1%' is already linked to `%2%'") % path % linkPath); return; } if (st.st_size != stLink.st_size) { printMsg(lvlError, format("removing corrupted link ‘%1%’") % linkPath); unlink(linkPath.c_str()); goto retry; } printMsg(lvlTalkative, format("linking ‘%1%’ to ‘%2%’") % path % linkPath); /* Make the containing directory writable, but only if it's not the store itself (we don't want or need to mess with its permissions). */ bool mustToggle = !isStorePath(path); if (mustToggle) makeWritable(dirOf(path)); /* When we're done, make the directory read-only again and reset its timestamp back to 0. */ MakeReadOnly makeReadOnly(mustToggle ? dirOf(path) : ""); Path tempLink = (format("%1%/.tmp-link-%2%-%3%") % settings.nixStore % getpid() % rand()).str(); if (link(linkPath.c_str(), tempLink.c_str()) == -1) { if (errno == EMLINK) { /* Too many links to the same file (>= 32000 on most file systems). This is likely to happen with empty files. Just shrug and ignore. */ if (st.st_size) printMsg(lvlInfo, format("`%1%' has maximum number of links") % linkPath); return; } throw SysError(format("cannot link `%1%' to `%2%'") % tempLink % linkPath); } /* Atomically replace the old file with the new hard link. */ if (rename(tempLink.c_str(), path.c_str()) == -1) { if (unlink(tempLink.c_str()) == -1) printMsg(lvlError, format("unable to unlink `%1%'") % tempLink); if (errno == EMLINK) { /* Some filesystems generate too many links on the rename, rather than on the original link. (Probably it temporarily increases the st_nlink field before decreasing it again.) */ if (st.st_size) printMsg(lvlInfo, format("`%1%' has maximum number of links") % linkPath); return; } throw SysError(format("cannot rename `%1%' to `%2%'") % tempLink % path); } stats.filesLinked++; stats.bytesFreed += st.st_size; stats.blocksFreed += st.st_blocks; } void LocalStore::optimiseStore(OptimiseStats & stats) { PathSet paths = queryAllValidPaths(); InodeHash inodeHash = loadInodeHash(); foreach (PathSet::iterator, i, paths) { addTempRoot(*i); if (!isValidPath(*i)) continue; /* path was GC'ed, probably */ startNest(nest, lvlChatty, format("hashing files in `%1%'") % *i); optimisePath_(stats, *i, inodeHash); } } static string showBytes(unsigned long long bytes) { return (format("%.2f MiB") % (bytes / (1024.0 * 1024.0))).str(); } void LocalStore::optimiseStore() { OptimiseStats stats; optimiseStore(stats); printMsg(lvlError, format("%1% freed by hard-linking %2% files") % showBytes(stats.bytesFreed) % stats.filesLinked); } void LocalStore::optimisePath(const Path & path) { OptimiseStats stats; InodeHash inodeHash; if (settings.autoOptimiseStore) optimisePath_(stats, path, inodeHash); } }
genenetwork/guix
nix/libstore/optimise-store.cc
C++
gpl-3.0
8,322
<!DOCTYPE HTML> <html lang="en"> <head> <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> <title>ArduPilot Firmware Download</title> <!--CSS --> <link href="css/main.css" rel="stylesheet" type="text/css" /> </head> <body> <div id="main"> <a href="https://firmware.ardupilot.org/"> <div id="logo"> </div> </a> <h2>ArduPilot Firmware builds</h2> These firmware builds are automatically generated by the <a href="https://autotest.ardupilot.org">ArduPilot autotest system</a>.<p> <h2>License</h2> 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.<p> 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.<p> For details see <a href="http://www.gnu.org/licenses/gpl.html">http://www.gnu.org/licenses/gpl.html</a> <h2>Safety</h2> Operating a powered vehicle of any kind can be a lot of fun. However, nothing will ruin your day at the park more quickly than an accident or running afoul of the law. Since we want you to have a great experience, please make sure that you do all of the following: <ul> <li><b>Operate within all local laws and regulations</b>. For example, in the United States, current regulations require you to operate most UAVs under 400 foot above ground level, within line of site, and away from obstructions and populated areas. Since these regulations vary from place to place, even within the same country, ensure that you understand what you need to do to stay compliant.</li> <li><b>Never operate the vehicle or software in a way that could be dangerous to you, other people, or property</b>. Propellers, while rotating, could easily cut you; if a UAV fell on a person or object, it could cause a lot of pain and damage; a UAV caught in power lines could cause an outage for many people. As Ben Franklin said, "An ounce of prevention is worth a pound of cure."</li> <li><b>Always keep in mind that software and hardware failures happen</b>. Although we design our products to minimize such issues, you should always operate with the understanding that a failure could occur at any point of time and without warning. As such, you should take the appropriate precautions to minimize danger in case of failure.</li> <li><b>Never use the software or hardware for manned vehicles</b>. The software and hardware we provide is only for use in unmanned vehicles.</li> </ul> <h2>Firmwares</h2> <a href="Plane"><img src="images/plane.png" width="80" alt="Plane">Plane</a> - for fixed wing aircraft<p> <a href="Copter"><img src="images/copter.png" width="80" alt="Copter">Copter</a> - for multicopters and traditional helicopters<p> <a href="Rover"><img src="images/rover.png" width="80" alt="Rover">Rover</a> - for land vehicles and boats<p> <a href="Sub"><img src="images/sub.png" width="80" alt="Sub">Sub</a> - for ROVs and underwater vehicles<p> <a href="AntennaTracker"><img src="images/antenna-tracker.png" width="80" alt="AntennaTracker">Antenna Tracker</a> - for antenna tracking of ArduPilot vehicles<p> <a href="Tools/MissionPlanner"><img src="images/planner.png" width="80" alt="MissionPlanner">MissionPlanner</a> - Mission Planner tool<p> <a href="Tools/APMPlanner"><img src="images/ap_rc.png" width="80" alt="APM Planner 2.0">APM Planner 2.0</a> - APM Planner 2.0 tool<p> <a href="SiK"><img src="images/3DR_Radio.jpg" width="80" alt="Radio">SiK</a> - 3DR Radio Firmware<p> <a href="Tools"><img src="images/tools.png" width="80" alt="Tools">Tools</a> - Build and development tools<p> <a href="devbuild"><img src="images/tools.png" width="80" alt="Tools">DevBuild</a> - Developer builds<p> <a href="http://github.com/ArduPilot/companion"><img src="images/companion.png" width="78" alt="Companion">Companion</a> - Companion Computer example code <a href="Companion">and Images</a></p><p> <a href="AP_Periph"><img src="images/tools.png" width="80" alt="AP_Periph">AP_Periph</a> - UAVCAN Peripheral Firmware<p> <h2>Types of firmware available</h2> To choose a firmware to download you need to choose: <ul> <li>The type of board that you have</li> <li>Whether you want the stable, beta or latest version of the firmware</li> <li>Whether you want a HIL (hardware in the loop) image</li> </ul> The meanings of the versions are <ul> <li><b>stable</b> - this is the version recommended for new users. It has had the most testing</li> <li><b>beta</b> - this is the firmware to choose if you want to be part of beta testing of new versions prior to release as a stable version. Note that during some development times the beta release will be the same as the stable release</li> <li><b>latest</b> - this is the latest version from our <a href="http://github.com/ArduPilot">git source code repository</a>. This version is only for developers. The code may have unknown bugs and extreme care should be taken by anyone using it</li> </ul> For each vehicle type a firmware image is available for each type of autopilot board supported by that vehicle type <h2>Load your firmware using Mission Planner</h2> <ul> <li>You can load the <b>stable</b> version of the firmware by selecting the appropriate icon for your airframe from the Firmware Tab.</li> <li>You can load the <b>beta</b> version of the firmware by selecting the "BETA firmware" button in the bottom right corner of the screen and then the appropriate icon.</li> <li>You can load the <b>latest</b> version of the firmware by downloading a firmware image from one of the links and selecting the "Load custom firmware" button in the bottom right corner of the screen.</li> </ul> <h2>Loading firmware on Linux or MacOS</h2> To load a firmware on a Linux or MacOS machine you will need to use the <a href="https://raw.github.com/ArduPilot/ardupilot/master/Tools/scripts/uploader.py">uploader.py</a> python script. You can run it like this: <pre> python Tools/scripts/uploader.py --port /dev/ttyACM0 build/Pixracer/bin/arducopter.apj </pre> After starting the script, press the reset button on your device to make it enter bootloader mode. <h2>Building the firmware yourself</h2> To build the firmware yourself please see the <a href="http://dev.ardupilot.com">ArduPilot development site</a>. </div> </body> </html>
fhedberg/ardupilot
Tools/autotest/web-firmware/index.html
HTML
gpl-3.0
6,649
const { Cc, Ci } = require("chrome"); const { storage } = require("sdk/simple-storage"); const userStorage = require("./userStorage"); userStorage.init(); // Hack: import main first to trigger correct order of dependency resolution const main = require("./main"); const utils = require('./utils'); const { Policy } = require("./contentPolicy"); let preloadText = "@@||sgizmo.co^$third-party\n"+ "@@||www.logos.co.uk^$third-party\n"+ "@@||www.fuseservice.com^$third-party\n"+ "@@||piclens.co.uk^$third-party\n"; exports.testPreloads = function(assert) { main.main(); storage.preloads = {}; userStorage.syncPreloads(preloadText); assert.equal(Object.keys(storage.preloads).length, 4, "test sync preloads"); let goodDomains = [ "https://sgizmo.co", "http://www.sgizmo.co/abc?query=1#foobar", "http://www.logos.co.uk/foobar", "https://abc.piclens.co.uk", "http://foo.bar.piclens.co.uk", "https://maps.api.test.www.fuseservice.com" ]; let badDomains = [ "http://google.com", "https://cdn.logos.co.uk", "http://cdn.logos.co", "https://adswww.fuseservice.com", "http://fuseservice.com", "https://sgizmo.co.uk", "https://lens.co.uk/abcdef" ]; goodDomains.forEach(function(element, index, array) { assert.ok(Policy._isPreloadedWhitelistRequest(utils.makeURI(element)), "test that " + element + " is whitelisted"); }); badDomains.forEach(function(element, index, array) { assert.ok(!Policy._isPreloadedWhitelistRequest(utils.makeURI(element)), "test that " + element + " is NOT whitelisted"); }); main.clearData(true, true); main.onUnload("disabled"); }; require("sdk/test").run(exports);
SwartzCr/privacybadgerfirefox
test/test-preloads.js
JavaScript
gpl-3.0
1,935
/************ * * This file is part of a tool for producing 3D content in the PRC format. * Copyright (C) 2008 Orest Shardt <shardtor (at) gmail dot com> * * 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, 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 Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. * *************/ #ifndef __O_PRC_FILE_H #define __O_PRC_FILE_H #include <iostream> #include <fstream> #include <vector> #include <map> #include <set> #include <list> #include <stack> #include <string> #include <string.h> #ifdef HAVE_CONFIG_H #include "config.h" #endif #include "PRC.h" #include "PRCbitStream.h" #include "writePRC.h" class oPRCFile; class PRCFileStructure; #define EQFLD(fld) fld==c.fld #define COMPFLD(fld) \ if(fld != c.fld) \ return (fld < c.fld); struct RGBAColour { RGBAColour(double r=0.0, double g=0.0, double b=0.0, double a=1.0) : R(r), G(g), B(b), A(a) {} double R,G,B,A; void Set(double r, double g, double b, double a=1.0) { R = r; G = g; B = b; A = a; } bool operator==(const RGBAColour &c) const { return (EQFLD(R) && EQFLD(G) && EQFLD(B) && EQFLD(A)); } bool operator!=(const RGBAColour &c) const { return !(EQFLD(R) && EQFLD(G) && EQFLD(B) && EQFLD(A)); } bool operator<(const RGBAColour &c) const { COMPFLD(R) COMPFLD(G) COMPFLD(B) COMPFLD(A) return false; } friend RGBAColour operator * (const RGBAColour& a, const double d) { return RGBAColour(a.R*d,a.G*d,a.B*d,a.A*d); } friend RGBAColour operator * (const double d, const RGBAColour& a) { return RGBAColour(a.R*d,a.G*d,a.B*d,a.A*d); } }; typedef std::map<RGBAColour,uint32_t> PRCcolourMap; struct RGBAColourWidth { RGBAColourWidth(double r=0.0, double g=0.0, double b=0.0, double a=1.0, double w=1.0) : R(r), G(g), B(b), A(a), W(w) {} double R,G,B,A,W; bool operator==(const RGBAColourWidth &c) const { return (EQFLD(R) && EQFLD(G) && EQFLD(B) && EQFLD(A) && EQFLD(W)); } bool operator!=(const RGBAColourWidth &c) const { return !(EQFLD(R) && EQFLD(G) && EQFLD(B) && EQFLD(A) && EQFLD(W)); } bool operator<(const RGBAColourWidth &c) const { COMPFLD(R) COMPFLD(G) COMPFLD(B) COMPFLD(A) COMPFLD(W) return false; } }; typedef std::map<RGBAColourWidth,uint32_t> PRCcolourwidthMap; struct PRCmaterial { PRCmaterial() : alpha(1.0),shininess(1.0),width(1.0) {} PRCmaterial(const RGBAColour &a, const RGBAColour &d, const RGBAColour &e, const RGBAColour &s, double p, double h, double w=1.0) : ambient(a), diffuse(d), emissive(e), specular(s), alpha(p), shininess(h), width(w) {} RGBAColour ambient,diffuse,emissive,specular; double alpha,shininess,width; bool operator==(const PRCmaterial &c) const { return (EQFLD(ambient) && EQFLD(diffuse) && EQFLD(emissive) && EQFLD(specular) && EQFLD(alpha) && EQFLD(shininess) && EQFLD(width)); } bool operator<(const PRCmaterial &c) const { COMPFLD(ambient) COMPFLD(diffuse) COMPFLD(emissive) COMPFLD(specular) COMPFLD(alpha) COMPFLD(shininess) COMPFLD(width) return false; } }; typedef std::map<PRCmaterial,uint32_t> PRCmaterialMap; #undef EQFLD #undef COMPFLD struct PRCtexture { PRCtexture() : data(NULL), format(KEPRCPicture_BITMAP_RGBA_BYTE), width(0), height(0), size(0), mapping(0), components(PRC_TEXTURE_MAPPING_COMPONENTS_RGBA), function(KEPRCTextureFunction_Modulate), wrapping_mode_S(KEPRCTextureWrappingMode_Repeat), wrapping_mode_T(KEPRCTextureWrappingMode_Repeat) {} const uint8_t* data; EPRCPictureDataFormat format; /* KEPRCPicture_PNG KEPRCPicture_JPG KEPRCPicture_BITMAP_RGB_BYTE KEPRCPicture_BITMAP_RGBA_BYTE KEPRCPicture_BITMAP_GREY_BYTE KEPRCPicture_BITMAP_GREYA_BYTE */ uint32_t width; // may be omitted for PNG and JPEG uint32_t height; // too uint32_t size; uint32_t mapping; /* PRC_TEXTURE_MAPPING_DIFFUSE PRC_TEXTURE_MAPPING_BUMP PRC_TEXTURE_MAPPING_OPACITY PRC_TEXTURE_MAPPING_SPHERICAL_REFLECTION */ uint8_t components; /* PRC_TEXTURE_MAPPING_COMPONENTS_RED PRC_TEXTURE_MAPPING_COMPONENTS_GREEN PRC_TEXTURE_MAPPING_COMPONENTS_BLUE PRC_TEXTURE_MAPPING_COMPONENTS_RGB PRC_TEXTURE_MAPPING_COMPONENTS_ALPHA PRC_TEXTURE_MAPPING_COMPONENTS_RGBA */ EPRCTextureFunction function; /* enum EPRCTextureFunction { // Defines how to paint a texture on the surface being rendered. KEPRCTextureFunction_Unknown, // Let the application choose. KEPRCTextureFunction_Modulate, // Combine lighting with texturing. This is the default value. KEPRCTextureFunction_Replace, // Replace the object color with texture color data. KEPRCTextureFunction_Blend, // Reserved for future use. KEPRCTextureFunction_Decal // Reserved for future use. }; */ EPRCTextureWrappingMode wrapping_mode_S; EPRCTextureWrappingMode wrapping_mode_T; /* enum EPRCTextureWrappingMode { // Defines repeating and clamping texture modes. KEPRCTextureWrappingMode_Unknown, // Let the application choose. KEPRCTextureWrappingMode_Repeat, // Display the repeated texture on the surface. KEPRCTextureWrappingMode_ClampToBorder, // Clamp the texture to the border. Display the surface color along the texture limits. KEPRCTextureWrappingMode_Clamp, // Reserved for future use. KEPRCTextureWrappingMode_ClampToEdge, // Reserved for future use. KEPRCTextureWrappingMode_MirroredRepeat // Reserved for future use. }; */ }; /* struct PRCmaterial { PRCmaterial() : alpha(1.0),shininess(1.0), picture_data(NULL), picture_format(KEPRCPicture_BITMAP_RGB_BYTE), picture_width(0), picture_height(0), picture_size(0), picture_replace(false), picture_repeat(false) {} PRCmaterial(const RGBAColour &a, const RGBAColour &d, const RGBAColour &e, const RGBAColour &s, double p, double h, const uint8_t* pic=NULL, EPRCPictureDataFormat picf=KEPRCPicture_BITMAP_RGB_BYTE, uint32_t picw=0, uint32_t pich=0, uint32_t pics=0, bool picreplace=false, bool picrepeat=false) : ambient(a), diffuse(d), emissive(e), specular(s), alpha(p), shininess(h), picture_data(pic), picture_format(picf), picture_width(picw), picture_height(pich), picture_size(pics), picture_replace(picreplace), picture_repeat(picrepeat) { if(picture_size==0) { if (picture_format==KEPRCPicture_BITMAP_RGB_BYTE) picture_size = picture_width*picture_height*3; if (picture_format==KEPRCPicture_BITMAP_RGBA_BYTE) picture_size = picture_width*picture_height*4; if (picture_format==KEPRCPicture_BITMAP_GREY_BYTE) picture_size = picture_width*picture_height*1; if (picture_format==KEPRCPicture_BITMAP_GREYA_BYTE) picture_size = picture_width*picture_height*2; } } RGBAColour ambient,diffuse,emissive,specular; double alpha,shininess; const uint8_t* picture_data; EPRCPictureDataFormat picture_format; uint32_t picture_width; uint32_t picture_height; uint32_t picture_size; bool picture_replace; // replace material color with texture color? if false - just modify bool picture_repeat; // repeat texture? if false - clamp to edge bool operator==(const PRCmaterial &m) const { return (ambient==m.ambient && diffuse==m.diffuse && emissive==m.emissive && specular==m.specular && alpha==m.alpha && shininess==m.shininess && picture_replace==m.picture_replace && picture_repeat==m.picture_repeat && picture_format==m.picture_format && picture_width==m.picture_width && picture_height==m.picture_height && picture_size==m.picture_size && (picture_data==m.picture_data || memcmp(picture_data,m.picture_data,picture_size)==0) ); } bool operator<(const PRCmaterial &m) const { if(ambient!=m.ambient) return (ambient<m.ambient); if(diffuse!=m.diffuse) return (diffuse<m.diffuse); if(emissive!=m.emissive) return (emissive<m.emissive); if(specular!=m.specular) return (specular<m.specular); if(alpha!=m.alpha) return (alpha<m.alpha); if(shininess!=m.shininess) return (shininess<m.shininess); if(picture_replace!=m.picture_replace) return (picture_replace<m.picture_replace); if(picture_repeat!=m.picture_repeat) return (picture_repeat<m.picture_repeat); if(picture_format!=m.picture_format) return (picture_format<m.picture_format); if(picture_width!=m.picture_width) return (picture_width<m.picture_width); if(picture_height!=m.picture_height) return (picture_height<m.picture_height); if(picture_size!=m.picture_size) return (picture_size<m.picture_size); if(picture_data!=m.picture_data) return (memcmp(picture_data,m.picture_data,picture_size)<0); return false; } }; typedef std::map<PRCmaterial,uint32_t> PRCmaterialMap; */ struct PRCtessrectangle // rectangle { PRCVector3d vertices[4]; uint32_t style; }; typedef std::vector<PRCtessrectangle> PRCtessrectangleList; struct PRCtessquad // rectangle { PRCVector3d vertices[4]; RGBAColour colours[4]; }; typedef std::vector<PRCtessquad> PRCtessquadList; /* struct PRCtesstriangle // textured triangle { PRCtesstriangle() : style(m1) {} PRCVector3d vertices[3]; // PRCVector3d normals[3]; // RGBAColour colors[3]; PRCVector2d texcoords[3]; uint32_t style; }; typedef std::vector<PRCtesstriangle> PRCtesstriangleList; */ struct PRCtessline // polyline { std::vector<PRCVector3d> point; PRCRgbColor color; }; typedef std::list<PRCtessline> PRCtesslineList; typedef std::map<double, PRCtesslineList> PRCtesslineMap; struct PRCface { PRCface() : transform(NULL), face(NULL) {} uint32_t style; bool transparent; PRCGeneralTransformation3d* transform; PRCFace* face; }; typedef std::vector <PRCface> PRCfaceList; struct PRCcompface { PRCcompface() : face(NULL) {} uint32_t style; bool transparent; PRCCompressedFace* face; }; typedef std::vector <PRCcompface> PRCcompfaceList; struct PRCwire { PRCwire() : style(m1), transform(NULL), curve(NULL) {} uint32_t style; PRCGeneralTransformation3d* transform; PRCCurve* curve; }; typedef std::vector <PRCwire> PRCwireList; typedef std::map <uint32_t,std::vector<PRCVector3d> > PRCpointsetMap; class PRCoptions { public: double compression; double granularity; bool closed; // render the surface as one-sided; may yield faster rendering bool tess; // use tessellated mesh to store straight patches bool do_break; // bool no_break; // do not render transparent patches as one-faced nodes double crease_angle; // crease angle for meshes PRCoptions(double compression=0.0, double granularity=0.0, bool closed=false, bool tess=false, bool do_break=true, bool no_break=false, double crease_angle=25.8419) : compression(compression), granularity(granularity), closed(closed), tess(tess), do_break(do_break), no_break(no_break), crease_angle(crease_angle) {} }; class PRCgroup { public: PRCgroup() : product_occurrence(NULL), parent_product_occurrence(NULL), part_definition(NULL), parent_part_definition(NULL), transform(NULL) {} PRCgroup(const std::string& name) : product_occurrence(NULL), parent_product_occurrence(NULL), part_definition(NULL), parent_part_definition(NULL), transform(NULL), name(name) {} PRCProductOccurrence *product_occurrence, *parent_product_occurrence; PRCPartDefinition *part_definition, *parent_part_definition; PRCfaceList faces; PRCcompfaceList compfaces; PRCtessrectangleList rectangles; // PRCtesstriangleList triangles; PRCtessquadList quads; PRCtesslineMap lines; PRCwireList wires; PRCpointsetMap points; std::vector<PRCPointSet*> pointsets; std::vector<PRCPolyBrepModel*> polymodels; std::vector<PRCPolyWire*> polywires; PRCGeneralTransformation3d* transform; std::string name; PRCoptions options; }; void makeFileUUID(PRCUniqueId&); void makeAppUUID(PRCUniqueId&); class PRCStartHeader { public: uint32_t minimal_version_for_read; // PRCVersion uint32_t authoring_version; // PRCVersion PRCUniqueId file_structure_uuid; PRCUniqueId application_uuid; // should be 0 PRCStartHeader() : minimal_version_for_read(PRCVersion), authoring_version(PRCVersion) {} void serializeStartHeader(std::ostream&) const; void serializeUncompressedFiles(std::ostream&) const; PRCUncompressedFileList uncompressed_files; uint32_t getStartHeaderSize() const; uint32_t getUncompressedFilesSize() const; }; class PRCFileStructure : public PRCStartHeader { public: uint32_t number_of_referenced_file_structures; double tessellation_chord_height_ratio; double tessellation_angle_degree; std::string default_font_family_name; PRCRgbColorList colors; PRCRgbColorMap colorMap; PRCPictureList pictures; PRCPictureMap pictureMap; PRCUncompressedFileMap uncompressedfileMap; PRCTextureDefinitionList texture_definitions; PRCTextureDefinitionMap texturedefinitionMap; PRCMaterialList materials; PRCMaterialGenericMap materialgenericMap; PRCTextureApplicationMap textureapplicationMap; PRCStyleList styles; PRCStyleMap styleMap; PRCCoordinateSystemList reference_coordinate_systems; std::vector<PRCFontKeysSameFont> font_keys_of_font; PRCPartDefinitionList part_definitions; PRCProductOccurrenceList product_occurrences; // PRCMarkupList markups; // PRCAnnotationItemList annotation_entities; double unit; PRCTopoContextList contexts; PRCTessList tessellations; uint32_t sizes[6]; uint8_t *globals_data; PRCbitStream globals_out; // order matters: PRCbitStream must be initialized last uint8_t *tree_data; PRCbitStream tree_out; uint8_t *tessellations_data; PRCbitStream tessellations_out; uint8_t *geometry_data; PRCbitStream geometry_out; uint8_t *extraGeometry_data; PRCbitStream extraGeometry_out; ~PRCFileStructure () { for(PRCUncompressedFileList::iterator it=uncompressed_files.begin(); it!=uncompressed_files.end(); ++it) delete *it; for(PRCPictureList::iterator it=pictures.begin(); it!=pictures.end(); ++it) delete *it; for(PRCTextureDefinitionList::iterator it=texture_definitions.begin(); it!=texture_definitions.end(); ++it) delete *it; for(PRCMaterialList::iterator it=materials.begin(); it!=materials.end(); ++it) delete *it; for(PRCStyleList::iterator it=styles.begin(); it!=styles.end(); ++it) delete *it; for(PRCTopoContextList::iterator it=contexts.begin(); it!=contexts.end(); ++it) delete *it; for(PRCTessList::iterator it=tessellations.begin(); it!=tessellations.end(); ++it) delete *it; for(PRCPartDefinitionList::iterator it=part_definitions.begin(); it!=part_definitions.end(); ++it) delete *it; for(PRCProductOccurrenceList::iterator it=product_occurrences.begin(); it!=product_occurrences.end(); ++it) delete *it; for(PRCCoordinateSystemList::iterator it=reference_coordinate_systems.begin(); it!=reference_coordinate_systems.end(); it++) delete *it; free(globals_data); free(tree_data); free(tessellations_data); free(geometry_data); free(extraGeometry_data); } PRCFileStructure() : number_of_referenced_file_structures(0), tessellation_chord_height_ratio(2000.0),tessellation_angle_degree(40.0), default_font_family_name(""), unit(1), globals_data(NULL),globals_out(globals_data,0), tree_data(NULL),tree_out(tree_data,0), tessellations_data(NULL),tessellations_out(tessellations_data,0), geometry_data(NULL),geometry_out(geometry_data,0), extraGeometry_data(NULL),extraGeometry_out(extraGeometry_data,0) {} void write(std::ostream&); void prepare(); uint32_t getSize(); void serializeFileStructureGlobals(PRCbitStream&); void serializeFileStructureTree(PRCbitStream&); void serializeFileStructureTessellation(PRCbitStream&); void serializeFileStructureGeometry(PRCbitStream&); void serializeFileStructureExtraGeometry(PRCbitStream&); uint32_t addPicture(EPRCPictureDataFormat format, uint32_t size, const uint8_t *picture, uint32_t width=0, uint32_t height=0, std::string name=""); #define ADD_ADDUNIQ( prctype ) \ uint32_t add##prctype( PRC##prctype*& p##prctype ); \ uint32_t add##prctype##Unique( PRC##prctype*& p##prctype); ADD_ADDUNIQ( UncompressedFile ) ADD_ADDUNIQ( Picture ) ADD_ADDUNIQ( TextureDefinition ) ADD_ADDUNIQ( TextureApplication ) ADD_ADDUNIQ( MaterialGeneric ) ADD_ADDUNIQ( Style ) #undef ADD_ADDUNIQ uint32_t addRgbColor(double r, double g, double b); uint32_t addRgbColorUnique(double r, double g, double b); uint32_t addPartDefinition(PRCPartDefinition*& pPartDefinition); uint32_t addProductOccurrence(PRCProductOccurrence*& pProductOccurrence); uint32_t addTopoContext(PRCTopoContext*& pTopoContext); uint32_t getTopoContext(PRCTopoContext*& pTopoContext); uint32_t add3DTess(PRC3DTess*& p3DTess); uint32_t add3DWireTess(PRC3DWireTess*& p3DWireTess); /* uint32_t addMarkupTess(PRCMarkupTess*& pMarkupTess); uint32_t addMarkup(PRCMarkup*& pMarkup); uint32_t addAnnotationItem(PRCAnnotationItem*& pAnnotationItem); */ uint32_t addCoordinateSystem(PRCCoordinateSystem*& pCoordinateSystem); uint32_t addCoordinateSystemUnique(PRCCoordinateSystem*& pCoordinateSystem); }; class PRCFileStructureInformation { public: PRCUniqueId UUID; uint32_t reserved; // 0 uint32_t number_of_offsets; uint32_t *offsets; void write(std::ostream&); uint32_t getSize(); }; class PRCHeader : public PRCStartHeader { public : uint32_t number_of_file_structures; PRCFileStructureInformation *fileStructureInformation; uint32_t model_file_offset; uint32_t file_size; // not documented void write(std::ostream&); uint32_t getSize(); }; typedef std::map <PRCGeneralTransformation3d,uint32_t> PRCtransformMap; class oPRCFile { public: oPRCFile(std::ostream &os, double u=1, uint32_t n=1) : number_of_file_structures(n), fileStructures(new PRCFileStructure*[n]), unit(u), modelFile_data(NULL),modelFile_out(modelFile_data,0), fout(NULL),output(os) { for(uint32_t i = 0; i < number_of_file_structures; ++i) { fileStructures[i] = new PRCFileStructure(); fileStructures[i]->minimal_version_for_read = PRCVersion; fileStructures[i]->authoring_version = PRCVersion; makeFileUUID(fileStructures[i]->file_structure_uuid); makeAppUUID(fileStructures[i]->application_uuid); fileStructures[i]->unit = u; } groups.push(PRCgroup()); PRCgroup &group = groups.top(); group.name="root"; group.transform = NULL; group.product_occurrence = new PRCProductOccurrence(group.name); group.parent_product_occurrence = NULL; group.part_definition = new PRCPartDefinition; group.parent_part_definition = NULL; } oPRCFile(const std::string &name, double u=1, uint32_t n=1) : number_of_file_structures(n), fileStructures(new PRCFileStructure*[n]), unit(u), modelFile_data(NULL),modelFile_out(modelFile_data,0), fout(new std::ofstream(name.c_str(), std::ios::out|std::ios::binary|std::ios::trunc)), output(*fout) { for(uint32_t i = 0; i < number_of_file_structures; ++i) { fileStructures[i] = new PRCFileStructure(); fileStructures[i]->minimal_version_for_read = PRCVersion; fileStructures[i]->authoring_version = PRCVersion; makeFileUUID(fileStructures[i]->file_structure_uuid); makeAppUUID(fileStructures[i]->application_uuid); fileStructures[i]->unit = u; } groups.push(PRCgroup()); PRCgroup &group = groups.top(); group.name="root"; group.transform = NULL; group.product_occurrence = new PRCProductOccurrence(group.name); group.parent_product_occurrence = NULL; group.part_definition = new PRCPartDefinition; group.parent_part_definition = NULL; } ~oPRCFile() { for(uint32_t i = 0; i < number_of_file_structures; ++i) delete fileStructures[i]; delete[] fileStructures; if(fout != NULL) delete fout; free(modelFile_data); } void begingroup(const char *name, const PRCoptions *options=NULL, const double* t=NULL); void endgroup(); std::string lastgroupname; std::vector<std::string> lastgroupnames; std::string calculate_unique_name(const ContentPRCBase *prc_entity,const ContentPRCBase *prc_occurence); bool finish(); uint32_t getSize(); const uint32_t number_of_file_structures; PRCFileStructure **fileStructures; PRCHeader header; PRCUnit unit; uint8_t *modelFile_data; PRCbitStream modelFile_out; // order matters: PRCbitStream must be initialized last PRCmaterialMap materialMap; PRCcolourMap colourMap; PRCcolourwidthMap colourwidthMap; PRCgroup rootGroup; PRCtransformMap transformMap; std::stack<PRCgroup> groups; PRCgroup& findGroup(); void doGroup(PRCgroup& group); uint32_t addColour(const RGBAColour &colour); uint32_t addColourWidth(const RGBAColour &colour, double width); uint32_t addLineMaterial(const RGBAColour& c, double width) { return addColourWidth(c,width); } uint32_t addMaterial(const PRCmaterial &material); uint32_t addTexturedMaterial(const PRCmaterial &material, uint32_t n=0, const PRCtexture* const* tt=NULL); uint32_t addTransform(PRCGeneralTransformation3d*& transform); uint32_t addTransform(const double* t); uint32_t addTransform(const double origin[3], const double x_axis[3], const double y_axis[3], double scale); void addPoint(const double P[3], const RGBAColour &c, double w=1.0); void addPoint(double x, double y, double z, const RGBAColour &c, double w); void addPoints(uint32_t n, const double P[][3], const RGBAColour &c, double w=1.0); void addPoints(uint32_t n, const double P[][3], uint32_t style_index); void addLines(uint32_t nP, const double P[][3], uint32_t nI, const uint32_t PI[], const RGBAColour& c, double w, bool segment_color, uint32_t nC, const RGBAColour C[], uint32_t nCI, const uint32_t CI[]); uint32_t createLines(uint32_t nP, const double P[][3], uint32_t nI, const uint32_t PI[], bool segment_color, uint32_t nC, const RGBAColour C[], uint32_t nCI, const uint32_t CI[]); uint32_t createSegments(uint32_t nP, const double P[][3], uint32_t nI, const uint32_t PI[][2], bool segment_color, uint32_t nC, const RGBAColour C[], const uint32_t CI[][2]); void addTriangles(uint32_t nP, const double P[][3], uint32_t nI, const uint32_t PI[][3], const PRCmaterial& m, uint32_t nN, const double N[][3], const uint32_t NI[][3], uint32_t nT, const double T[][2], const uint32_t TI[][3], uint32_t nC, const RGBAColour C[], const uint32_t CI[][3], uint32_t nM, const PRCmaterial M[], const uint32_t MI[], double ca); uint32_t createTriangleMesh(uint32_t nP, const double P[][3], uint32_t nI, const uint32_t PI[][3], uint32_t style_index, uint32_t nN, const double N[][3], const uint32_t NI[][3], uint32_t nT, const double T[][2], const uint32_t TI[][3], uint32_t nC, const RGBAColour C[], const uint32_t CI[][3], uint32_t nS, const uint32_t S[], const uint32_t SI[], double ca); uint32_t createTriangleMesh(uint32_t nP, const double P[][3], uint32_t nI, const uint32_t PI[][3], const PRCmaterial& m, uint32_t nN, const double N[][3], const uint32_t NI[][3], uint32_t nT, const double T[][2], const uint32_t TI[][3], uint32_t nC, const RGBAColour C[], const uint32_t CI[][3], uint32_t nM, const PRCmaterial M[], const uint32_t MI[], double ca) { const uint32_t style = addMaterial(m); if(M!=NULL && nM>0) { uint32_t* const styles = new uint32_t[nM]; for(uint32_t i=0; i<nM; i++) styles[i]=addMaterial(M[i]); const uint32_t meshid = createTriangleMesh(nP, P, nI, PI, style, nN, N, NI, nT, T, TI, nC, C, CI, nM, styles, MI, ca); delete[] styles; return meshid; } else return createTriangleMesh(nP, P, nI, PI, style, nN, N, NI, nT, T, TI, nC, C, CI, 0, NULL, NULL, ca); } void addQuads(uint32_t nP, const double P[][3], uint32_t nI, const uint32_t PI[][4], const PRCmaterial& m, uint32_t nN, const double N[][3], const uint32_t NI[][4], uint32_t nT, const double T[][2], const uint32_t TI[][4], uint32_t nC, const RGBAColour C[], const uint32_t CI[][4], uint32_t nM, const PRCmaterial M[], const uint32_t MI[], double ca); uint32_t createQuadMesh(uint32_t nP, const double P[][3], uint32_t nI, const uint32_t PI[][4], uint32_t style_index, uint32_t nN, const double N[][3], const uint32_t NI[][4], uint32_t nT, const double T[][2], const uint32_t TI[][4], uint32_t nC, const RGBAColour C[], const uint32_t CI[][4], uint32_t nS, const uint32_t S[], const uint32_t SI[], double ca); uint32_t createQuadMesh(uint32_t nP, const double P[][3], uint32_t nI, const uint32_t PI[][4], const PRCmaterial& m, uint32_t nN, const double N[][3], const uint32_t NI[][4], uint32_t nT, const double T[][2], const uint32_t TI[][4], uint32_t nC, const RGBAColour C[], const uint32_t CI[][4], uint32_t nM, const PRCmaterial M[], const uint32_t MI[], double ca) { const uint32_t style = addMaterial(m); if(M!=NULL && nM>0) { uint32_t* const styles = new uint32_t[nM]; for(uint32_t i=0; i<nM; i++) styles[i]=addMaterial(M[i]); const uint32_t meshid = createQuadMesh(nP, P, nI, PI, style, nN, N, NI, nT, T, TI, nC, C, CI, nM, styles, MI, ca); delete[] styles; return meshid; } else return createQuadMesh(nP, P, nI, PI, style, nN, N, NI, nT, T, TI, nC, C, CI, 0, NULL, NULL, ca); } #define PRCTRANSFORM const double origin[3]=NULL, const double x_axis[3]=NULL, const double y_axis[3]=NULL, double scale=1, const double* t=NULL #define PRCCARTRANSFORM const double origin[3], const double x_axis[3], const double y_axis[3], double scale #define PRCGENTRANSFORM const double* t=NULL #define PRCNOMATERIALINDEX m1 void useMesh(uint32_t tess_index, uint32_t style_index, PRCGENTRANSFORM); void useMesh(uint32_t tess_index, const PRCmaterial& m, PRCGENTRANSFORM) { useMesh(tess_index,addMaterial(m),t); } void useMesh(uint32_t tess_index, uint32_t style_index, PRCCARTRANSFORM); void useMesh(uint32_t tess_index, const PRCmaterial& m, PRCCARTRANSFORM) { useMesh(tess_index,addMaterial(m),origin, x_axis, y_axis, scale); } void useLines(uint32_t tess_index, uint32_t style_index, PRCGENTRANSFORM); void useLines(uint32_t tess_index, const RGBAColour& c, double w, PRCGENTRANSFORM) { useLines(tess_index, addLineMaterial(c,w), t); } void useLines(uint32_t tess_index, uint32_t style_index, PRCCARTRANSFORM); void useLines(uint32_t tess_index, const RGBAColour& c, double w, PRCCARTRANSFORM) { useLines(tess_index,addLineMaterial(c,w),origin, x_axis, y_axis, scale); } // void addTriangle(const double P[][3], const double T[][2], uint32_t style_index); void addLine(uint32_t n, const double P[][3], const RGBAColour &c, double w=1.0); void addSegment(const double P1[3], const double P2[3], const RGBAColour &c, double w=1.0); void addBezierCurve(uint32_t n, const double cP[][3], const RGBAColour &c); void addCurve(uint32_t d, uint32_t n, const double cP[][3], const double *k, const RGBAColour &c, const double w[]); void addQuad(const double P[][3], const RGBAColour C[]); void addRectangle(const double P[][3], const PRCmaterial &m); void addPatch(const double cP[][3], const PRCmaterial &m); void addSurface(uint32_t dU, uint32_t dV, uint32_t nU, uint32_t nV, const double cP[][3], const double *kU, const double *kV, const PRCmaterial &m, const double w[]); void addTube(uint32_t n, const double cP[][3], const double oP[][3], bool straight, const PRCmaterial& m, PRCTRANSFORM); void addHemisphere(double radius, const PRCmaterial& m, PRCTRANSFORM); void addSphere(double radius, const PRCmaterial& m, PRCTRANSFORM); void addDisk(double radius, const PRCmaterial& m, PRCTRANSFORM); void addCylinder(double radius, double height, const PRCmaterial& m, PRCTRANSFORM); void addCone(double radius, double height, const PRCmaterial& m, PRCTRANSFORM); void addTorus(double major_radius, double minor_radius, double angle1, double angle2, const PRCmaterial& m, PRCTRANSFORM); #undef PRCTRANSFORM #undef PRCCARTRANSFORM #undef PRCGENTRANSFORM uint32_t addPicture(EPRCPictureDataFormat format, uint32_t size, const uint8_t *picture, uint32_t width=0, uint32_t height=0, std::string name="", uint32_t fileStructure=0) { return fileStructures[fileStructure]->addPicture(format, size, picture, width, height, name); } #define ADD_ADDUNIQ( prctype ) \ uint32_t add##prctype(PRC##prctype*& p##prctype, uint32_t fileStructure=0) \ { return fileStructures[fileStructure]->add##prctype( p##prctype ); } \ uint32_t add##prctype##Unique(PRC##prctype*& p##prctype, uint32_t fileStructure=0) \ { return fileStructures[fileStructure]->add##prctype##Unique(p##prctype); } ADD_ADDUNIQ( TextureDefinition ) ADD_ADDUNIQ( TextureApplication ) ADD_ADDUNIQ( MaterialGeneric ) ADD_ADDUNIQ( Style ) #undef ADD_ADDUNIQ uint32_t addRgbColor(double r, double g, double b, uint32_t fileStructure=0) { return fileStructures[fileStructure]->addRgbColor(r, g, b); } uint32_t addRgbColorUnique(double r, double g, double b, uint32_t fileStructure=0) { return fileStructures[fileStructure]->addRgbColorUnique(r, g, b); } uint32_t addPartDefinition(PRCPartDefinition*& pPartDefinition, uint32_t fileStructure=0) { return fileStructures[fileStructure]->addPartDefinition(pPartDefinition); } uint32_t addProductOccurrence(PRCProductOccurrence*& pProductOccurrence, uint32_t fileStructure=0) { return fileStructures[fileStructure]->addProductOccurrence(pProductOccurrence); } uint32_t addTopoContext(PRCTopoContext*& pTopoContext, uint32_t fileStructure=0) { return fileStructures[fileStructure]->addTopoContext(pTopoContext); } uint32_t getTopoContext(PRCTopoContext*& pTopoContext, uint32_t fileStructure=0) { return fileStructures[fileStructure]->getTopoContext(pTopoContext); } uint32_t add3DTess(PRC3DTess*& p3DTess, uint32_t fileStructure=0) { return fileStructures[fileStructure]->add3DTess(p3DTess); } uint32_t add3DWireTess(PRC3DWireTess*& p3DWireTess, uint32_t fileStructure=0) { return fileStructures[fileStructure]->add3DWireTess(p3DWireTess); } /* uint32_t addMarkupTess(PRCMarkupTess*& pMarkupTess, uint32_t fileStructure=0) { return fileStructures[fileStructure]->addMarkupTess(pMarkupTess); } uint32_t addMarkup(PRCMarkup*& pMarkup, uint32_t fileStructure=0) { return fileStructures[fileStructure]->addMarkup(pMarkup); } uint32_t addAnnotationItem(PRCAnnotationItem*& pAnnotationItem, uint32_t fileStructure=0) { return fileStructures[fileStructure]->addAnnotationItem(pAnnotationItem); } */ uint32_t addCoordinateSystem(PRCCoordinateSystem*& pCoordinateSystem, uint32_t fileStructure=0) { return fileStructures[fileStructure]->addCoordinateSystem(pCoordinateSystem); } uint32_t addCoordinateSystemUnique(PRCCoordinateSystem*& pCoordinateSystem, uint32_t fileStructure=0) { return fileStructures[fileStructure]->addCoordinateSystemUnique(pCoordinateSystem); } private: void serializeModelFileData(PRCbitStream&); std::ofstream *fout; std::ostream &output; }; #endif // __O_PRC_FILE_H
nealkruis/kiva
vendor/mathgl-2.3.5.1/src/prc/oPRCFile.h
C
gpl-3.0
34,173
<div class="row"> <div class="col-xs-6"> <table class="table"> <tr> <td>%last_topics%</td> </tr> $topiclist </table> </div> <div class="col-xs-6"> <table class="table"> <tr> <td>%last_posts%</td> </tr> $postlist </table> </div> </div>
kevinwiede/webspell-nerv
templates/profile_lastposts.html
HTML
gpl-3.0
388
#include "GCS_Plane.h" #include "Plane.h" bool GCS_Plane::cli_enabled() const { #if CLI_ENABLED == ENABLED return plane.g.cli_enabled; #else return false; #endif } AP_HAL::BetterStream* GCS_Plane::cliSerial() { return plane.cliSerial; } void GCS_Plane::send_airspeed_calibration(const Vector3f &vg) { for (uint8_t i=0; i<num_gcs(); i++) { if (_chan[i].initialised) { if (HAVE_PAYLOAD_SPACE((mavlink_channel_t)i, AIRSPEED_AUTOCAL)) { plane.airspeed.log_mavlink_send((mavlink_channel_t)i, vg); } } } }
cast051/ardupilot_cast
ArduPlane/GCS_Plane.cpp
C++
gpl-3.0
579
<?php /* Phoronix Test Suite URLs: http://www.phoronix.com, http://www.phoronix-test-suite.com/ Copyright (C) 2013 - 2015, Phoronix Media Copyright (C) 2013 - 2015, Michael Larabel 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/>. */ if(!is_file('phoromatic-export-viewer-config.php')) { echo '<p>You must first configure the <em>phoromatic-export-viewer-config.php.config</em> file and rename it to <em>phoromatic-export-viewer-config.php</em> within this directory.</p>'; return; } require('phoromatic-export-viewer-config.php'); if(!is_file(PATH_TO_PHORONIX_TEST_SUITE . 'pts-core/pts-core.php')) { echo '<p>You must first set the <em>PATH_TO_PHORONIX_TEST_SUITE</em> define within the <em>phoromatic-export-viewer-config.php</em> file.</p>'; return; } if(!is_file(PATH_TO_EXPORTED_PHOROMATIC_DATA . 'export-index.json')) { echo '<p>You must first set the <em>PATH_TO_EXPORTED_PHOROMATIC_DATA</em> define within the <em>phoromatic-export-viewer-config.php</em> file. No <em>export-index.json</em> found.</p>'; return; } define('PHOROMATIC_EXPORT_VIEWER', true); define('PTS_MODE', 'LIB'); define('PTS_AUTO_LOAD_OBJECTS', true); require(PATH_TO_PHORONIX_TEST_SUITE . 'pts-core/pts-core.php'); pts_define_directories(); set_time_limit(0); ini_set('memory_limit','2048M'); error_reporting(E_ALL); $export_index_json = file_get_contents(PATH_TO_EXPORTED_PHOROMATIC_DATA . 'export-index.json'); $export_index_json = json_decode($export_index_json, true); if(!isset($export_index_json['phoromatic']) || empty($export_index_json['phoromatic'])) { echo '<p>Error decoding the Phoromatic export JSON file.</p>'; return; } if(strpos($_SERVER['REQUEST_URI'], '?') === false && isset($_SERVER['QUERY_STRING'])) { $_SERVER['REQUEST_URI'] .= '?' . $_SERVER['QUERY_STRING']; } $URI = substr($_SERVER['REQUEST_URI'], strpos($_SERVER['REQUEST_URI'], '?') + 1); $PATH = explode('/', $URI); $REQUESTED = str_replace('.', null, array_shift($PATH)); if(empty($REQUESTED) || !isset($export_index_json['phoromatic'][$REQUESTED])) { $keys = array_keys($export_index_json['phoromatic']); $REQUESTED = array_shift($keys); $title = PHOROMATIC_VIEWER_TITLE; $meta_desc = 'Phoronix Test Suite\'s open-source Phoromatic result viewer for automated performance benchmark results.'; } else { $title = $export_index_json['phoromatic'][$REQUESTED]['title']; $meta_desc = substr($export_index_json['phoromatic'][$REQUESTED]['description'], 0, (strpos($export_index_json['phoromatic'][$REQUESTED]['description'], '. ') + 1)); } $tracker = &$export_index_json['phoromatic'][$REQUESTED]; $length = count($tracker['triggers']); ?> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html> <head> <title>Phoronix Test Suite Phoromatic - Benchmark Viewer - <?php echo $title; ?></title> <link href="phoromatic-export-viewer.css" rel="stylesheet" type="text/css" /> <meta name="keywords" content="Linux benchmarks, open-source benchmarks, benchmark viewer, Phoronix Test Suite, Phoromatic, Phoromatic viewer" /> <meta name="Description" content="<?php echo $meta_desc; ?>" /> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8" /> </head> <body> <div id="top_list"> <ul> <li><?php echo PHOROMATIC_VIEWER_TITLE ?></li> <?php foreach($export_index_json['phoromatic'] as &$schedule) { if($schedule['id'] === $REQUESTED) { echo '<li id="alt"><a href="?' . $schedule['id'] . '">' . $schedule['title'] . '</a></li>'; } else { echo '<li><a href="?' . $schedule['id'] . '">' . $schedule['title'] . '</a></li>'; } } ?> </ul> </div> <hr /> <h1><?php echo $tracker['title'] ?></h1> <p id="phoromatic_descriptor"><?php echo $tracker['description'] ?></p> <div id="config_option_line"> <form action="<?php $_SERVER['REQUEST_URI']; ?>" name="update_result_view" method="post"> Show Results For The Past <select name="view_results_limit" id="view_results_limit"> <?php foreach(array(14 => 'Two Weeks', 21 => 'Three Weeks', 30 => 'One Month', 60 => 'Two Months', 90 => 'Three Months', 120 => 'Four Months', 180 => 'Six Months', 270 => 'Nine Months', 365 => 'One Year') as $days => $st) { if($days > $length) { break; } echo '<option value="' . $days . '" ' . (isset($_POST['view_results_limit']) && $_POST['view_results_limit'] == $days ? 'selected="selected"' : null) . ' >' . $st . '</option>'; } echo '<option value="' . count($tracker['triggers']) . '">All Results</option>'; ?> </select> Days. <input type="checkbox" name="normalize_results" value="1" <?php echo (isset($_POST['normalize_results']) && $_POST['normalize_results'] == 1 ? 'checked="checked"' : null); ?> /> Normalize Results? <input type="submit" value="Refresh Results"> </form> </div> <blockquote> <?php if(isset($welcome_msg) && !empty($welcome_msg)) { echo '<p>' . str_replace(PHP_EOL, '<br />', $welcome_msg) . '</p><hr />'; } ?> <p>This service is powered by the <a href="http://www.phoronix-test-suite.com/">Phoronix Test Suite</a>'s built-in <a href="http://www.phoromatic.com/">Phoromatic</a> test orchestration and centralized performance management software. The tests are hosted by <a href="http://openbenchmarking.org/">OpenBenchmarking.org</a>. The public code is <a href="http://github.com/phoronix-test-suite/phoronix-test-suite/">hosted on GitHub</a>.</p> <p><a href="http://www.phoronix-test-suite.com/"><img src="images/pts.png" /></a> &nbsp; &nbsp; &nbsp; <a href="http://www.phoromatic.com/"><img src="images/phoromatic.png" /></a> &nbsp; &nbsp; &nbsp; <a href="http://openbenchmarking.org/"><img src="images/ob.png" /></a></p></blockquote> <?php ini_set('memory_limit', '4G'); if(isset($_POST['view_results_limit']) && is_numeric($_POST['view_results_limit']) && $_POST['view_results_limit'] > 7) { $cut_duration = $_POST['view_results_limit']; } else { $cut_duration = 30; } $result_files = array(); $triggers = array_splice($tracker['triggers'], 0, $cut_duration); foreach($triggers as $trigger) { $results_for_trigger = glob(PATH_TO_EXPORTED_PHOROMATIC_DATA . '/' . $REQUESTED . '/' . $trigger . '/*/composite.xml'); if($results_for_trigger == false) continue; foreach($results_for_trigger as $composite_xml) { // Add to result file $system_name = basename(dirname($composite_xml)) . ': ' . $trigger; array_push($result_files, new pts_result_merge_select($composite_xml, null, $system_name)); } } $attributes = array(); $result_file = new pts_result_file(null, true); $result_file->merge($result_files); $extra_attributes = array('reverse_result_buffer' => true, 'force_simple_keys' => true, 'force_line_graph_compact' => true, 'force_tracking_line_graph' => true); if(isset($_POST['normalize_results']) && $_POST['normalize_results']) { $extra_attributes['normalize_result_buffer'] = true; } $intent = null; //$table = new pts_ResultFileTable($result_file, $intent); //echo '<p style="text-align: center; overflow: auto;" class="result_object">' . pts_render::render_graph_inline_embed($table, $result_file, $extra_attributes) . '</p>'; echo '<div id="pts_results_area">'; foreach($result_file->get_result_objects((isset($_POST['show_only_changed_results']) ? 'ONLY_CHANGED_RESULTS' : -1), true) as $i => $result_object) { if(stripos($result_object->get_arguments_description(), 'frame time') !== false) continue; echo '<h2><a name="r-' . $i . '"></a>' . $result_object->test_profile->get_title() . '</h2>'; //echo '<h3>' . $result_object->get_arguments_description() . '</h3>'; echo '<p class="result_object">'; echo pts_render::render_graph_inline_embed($result_object, $result_file, $extra_attributes); echo '</p>'; unset($result_object); flush(); } echo '</div>'; //$table = new pts_ResultFileSystemsTable($result_file); echo '<p style="text-align: center; overflow: auto;" class="result_object">' . pts_render::render_graph_inline_embed($table, $result_file, $extra_attributes) . '</p>'; ?> <p id="footer"><em><?php echo pts_title(true); ?></em><br />Phoronix Test Suite, Phoromatic, and OpenBenchmarking.org are copyright &copy; 2004 - 2015 by Phoronix Media.<br />The Phoronix Test Suite / Phoromatic is open-source under the GNU GPL.<br />For more information, visit <a href="http://www.phoronix-test-suite.com/">Phoronix-Test-Suite.com</a> or contact <a href="http://www.phoronix-media.com/">Phoronix Media</a>.</p> </body> </html>
Jeni4/phoronix-test-suite
pts-core/phoromatic/export-public-viewer/index.php
PHP
gpl-3.0
8,933
/**CFile**************************************************************** FileName [abcResub.c] SystemName [ABC: Logic synthesis and verification system.] PackageName [Network and node package.] Synopsis [Resubstitution manager.] Author [Alan Mishchenko] Affiliation [UC Berkeley] Date [Ver. 1.0. Started - June 20, 2005.] Revision [$Id: abcResub.c,v 1.00 2005/06/20 00:00:00 alanmi Exp $] ***********************************************************************/ #include "base/abc/abc.h" #include "bool/dec/dec.h" ABC_NAMESPACE_IMPL_START //////////////////////////////////////////////////////////////////////// /// DECLARATIONS /// //////////////////////////////////////////////////////////////////////// #define ABC_RS_DIV1_MAX 150 // the max number of divisors to consider #define ABC_RS_DIV2_MAX 500 // the max number of pair-wise divisors to consider typedef struct Abc_ManRes_t_ Abc_ManRes_t; struct Abc_ManRes_t_ { // paramers int nLeavesMax; // the max number of leaves in the cone int nDivsMax; // the max number of divisors in the cone // representation of the cone Abc_Obj_t * pRoot; // the root of the cone int nLeaves; // the number of leaves int nDivs; // the number of all divisor (including leaves) int nMffc; // the size of MFFC int nLastGain; // the gain the number of nodes Vec_Ptr_t * vDivs; // the divisors // representation of the simulation info int nBits; // the number of simulation bits int nWords; // the number of unsigneds for siminfo Vec_Ptr_t * vSims; // simulation info unsigned * pInfo; // pointer to simulation info // observability don't-cares unsigned * pCareSet; // internal divisor storage Vec_Ptr_t * vDivs1UP; // the single-node unate divisors Vec_Ptr_t * vDivs1UN; // the single-node unate divisors Vec_Ptr_t * vDivs1B; // the single-node binate divisors Vec_Ptr_t * vDivs2UP0; // the double-node unate divisors Vec_Ptr_t * vDivs2UP1; // the double-node unate divisors Vec_Ptr_t * vDivs2UN0; // the double-node unate divisors Vec_Ptr_t * vDivs2UN1; // the double-node unate divisors // other data Vec_Ptr_t * vTemp; // temporary array of nodes // runtime statistics abctime timeCut; abctime timeTruth; abctime timeRes; abctime timeDiv; abctime timeMffc; abctime timeSim; abctime timeRes1; abctime timeResD; abctime timeRes2; abctime timeRes3; abctime timeNtk; abctime timeTotal; // improvement statistics int nUsedNodeC; int nUsedNode0; int nUsedNode1Or; int nUsedNode1And; int nUsedNode2Or; int nUsedNode2And; int nUsedNode2OrAnd; int nUsedNode2AndOr; int nUsedNode3OrAnd; int nUsedNode3AndOr; int nUsedNodeTotal; int nTotalDivs; int nTotalLeaves; int nTotalGain; int nNodesBeg; int nNodesEnd; }; // external procedures static Abc_ManRes_t* Abc_ManResubStart( int nLeavesMax, int nDivsMax ); static void Abc_ManResubStop( Abc_ManRes_t * p ); static Dec_Graph_t * Abc_ManResubEval( Abc_ManRes_t * p, Abc_Obj_t * pRoot, Vec_Ptr_t * vLeaves, int nSteps, int fUpdateLevel, int fVerbose ); static void Abc_ManResubCleanup( Abc_ManRes_t * p ); static void Abc_ManResubPrint( Abc_ManRes_t * p ); // other procedures static int Abc_ManResubCollectDivs( Abc_ManRes_t * p, Abc_Obj_t * pRoot, Vec_Ptr_t * vLeaves, int Required ); static void Abc_ManResubSimulate( Vec_Ptr_t * vDivs, int nLeaves, Vec_Ptr_t * vSims, int nLeavesMax, int nWords ); static void Abc_ManResubPrintDivs( Abc_ManRes_t * p, Abc_Obj_t * pRoot, Vec_Ptr_t * vLeaves ); static void Abc_ManResubDivsS( Abc_ManRes_t * p, int Required ); static void Abc_ManResubDivsD( Abc_ManRes_t * p, int Required ); static Dec_Graph_t * Abc_ManResubQuit( Abc_ManRes_t * p ); static Dec_Graph_t * Abc_ManResubDivs0( Abc_ManRes_t * p ); static Dec_Graph_t * Abc_ManResubDivs1( Abc_ManRes_t * p, int Required ); static Dec_Graph_t * Abc_ManResubDivs12( Abc_ManRes_t * p, int Required ); static Dec_Graph_t * Abc_ManResubDivs2( Abc_ManRes_t * p, int Required ); static Dec_Graph_t * Abc_ManResubDivs3( Abc_ManRes_t * p, int Required ); static Vec_Ptr_t * Abc_CutFactorLarge( Abc_Obj_t * pNode, int nLeavesMax ); static int Abc_CutVolumeCheck( Abc_Obj_t * pNode, Vec_Ptr_t * vLeaves ); extern abctime s_ResubTime; //////////////////////////////////////////////////////////////////////// /// FUNCTION DEFINITIONS /// //////////////////////////////////////////////////////////////////////// /**Function************************************************************* Synopsis [Performs incremental resynthesis of the AIG.] Description [] SideEffects [] SeeAlso [] ***********************************************************************/ int Abc_NtkResubstitute( Abc_Ntk_t * pNtk, int nCutMax, int nStepsMax, int nLevelsOdc, int fUpdateLevel, int fVerbose, int fVeryVerbose ) { extern void Dec_GraphUpdateNetwork( Abc_Obj_t * pRoot, Dec_Graph_t * pGraph, int fUpdateLevel, int nGain ); ProgressBar * pProgress; Abc_ManRes_t * pManRes; Abc_ManCut_t * pManCut; Odc_Man_t * pManOdc = NULL; Dec_Graph_t * pFForm; Vec_Ptr_t * vLeaves; Abc_Obj_t * pNode; abctime clk, clkStart = Abc_Clock(); int i, nNodes; assert( Abc_NtkIsStrash(pNtk) ); // cleanup the AIG Abc_AigCleanup((Abc_Aig_t *)pNtk->pManFunc); // start the managers pManCut = Abc_NtkManCutStart( nCutMax, 100000, 100000, 100000 ); pManRes = Abc_ManResubStart( nCutMax, ABC_RS_DIV1_MAX ); if ( nLevelsOdc > 0 ) pManOdc = Abc_NtkDontCareAlloc( nCutMax, nLevelsOdc, fVerbose, fVeryVerbose ); // compute the reverse levels if level update is requested if ( fUpdateLevel ) Abc_NtkStartReverseLevels( pNtk, 0 ); if ( Abc_NtkLatchNum(pNtk) ) { Abc_NtkForEachLatch(pNtk, pNode, i) pNode->pNext = (Abc_Obj_t *)pNode->pData; } // resynthesize each node once pManRes->nNodesBeg = Abc_NtkNodeNum(pNtk); nNodes = Abc_NtkObjNumMax(pNtk); pProgress = Extra_ProgressBarStart( stdout, nNodes ); Abc_NtkForEachNode( pNtk, pNode, i ) { Extra_ProgressBarUpdate( pProgress, i, NULL ); // skip the constant node // if ( Abc_NodeIsConst(pNode) ) // continue; // skip persistant nodes if ( Abc_NodeIsPersistant(pNode) ) continue; // skip the nodes with many fanouts if ( Abc_ObjFanoutNum(pNode) > 1000 ) continue; // stop if all nodes have been tried once if ( i >= nNodes ) break; // compute a reconvergence-driven cut clk = Abc_Clock(); vLeaves = Abc_NodeFindCut( pManCut, pNode, 0 ); // vLeaves = Abc_CutFactorLarge( pNode, nCutMax ); pManRes->timeCut += Abc_Clock() - clk; /* if ( fVerbose && vLeaves ) printf( "Node %6d : Leaves = %3d. Volume = %3d.\n", pNode->Id, Vec_PtrSize(vLeaves), Abc_CutVolumeCheck(pNode, vLeaves) ); if ( vLeaves == NULL ) continue; */ // get the don't-cares if ( pManOdc ) { clk = Abc_Clock(); Abc_NtkDontCareClear( pManOdc ); Abc_NtkDontCareCompute( pManOdc, pNode, vLeaves, pManRes->pCareSet ); pManRes->timeTruth += Abc_Clock() - clk; } // evaluate this cut clk = Abc_Clock(); pFForm = Abc_ManResubEval( pManRes, pNode, vLeaves, nStepsMax, fUpdateLevel, fVerbose ); // Vec_PtrFree( vLeaves ); // Abc_ManResubCleanup( pManRes ); pManRes->timeRes += Abc_Clock() - clk; if ( pFForm == NULL ) continue; pManRes->nTotalGain += pManRes->nLastGain; /* if ( pManRes->nLeaves == 4 && pManRes->nMffc == 2 && pManRes->nLastGain == 1 ) { printf( "%6d : L = %2d. V = %2d. Mffc = %2d. Divs = %3d. Up = %3d. Un = %3d. B = %3d.\n", pNode->Id, pManRes->nLeaves, Abc_CutVolumeCheck(pNode, vLeaves), pManRes->nMffc, pManRes->nDivs, pManRes->vDivs1UP->nSize, pManRes->vDivs1UN->nSize, pManRes->vDivs1B->nSize ); Abc_ManResubPrintDivs( pManRes, pNode, vLeaves ); } */ // acceptable replacement found, update the graph clk = Abc_Clock(); Dec_GraphUpdateNetwork( pNode, pFForm, fUpdateLevel, pManRes->nLastGain ); pManRes->timeNtk += Abc_Clock() - clk; Dec_GraphFree( pFForm ); } Extra_ProgressBarStop( pProgress ); pManRes->timeTotal = Abc_Clock() - clkStart; pManRes->nNodesEnd = Abc_NtkNodeNum(pNtk); // print statistics if ( fVerbose ) Abc_ManResubPrint( pManRes ); // delete the managers Abc_ManResubStop( pManRes ); Abc_NtkManCutStop( pManCut ); if ( pManOdc ) Abc_NtkDontCareFree( pManOdc ); // clean the data field Abc_NtkForEachObj( pNtk, pNode, i ) pNode->pData = NULL; if ( Abc_NtkLatchNum(pNtk) ) { Abc_NtkForEachLatch(pNtk, pNode, i) pNode->pData = pNode->pNext, pNode->pNext = NULL; } // put the nodes into the DFS order and reassign their IDs Abc_NtkReassignIds( pNtk ); // Abc_AigCheckFaninOrder( pNtk->pManFunc ); // fix the levels if ( fUpdateLevel ) Abc_NtkStopReverseLevels( pNtk ); else Abc_NtkLevel( pNtk ); // check if ( !Abc_NtkCheck( pNtk ) ) { printf( "Abc_NtkRefactor: The network check has failed.\n" ); return 0; } s_ResubTime = Abc_Clock() - clkStart; return 1; } /**Function************************************************************* Synopsis [] Description [] SideEffects [] SeeAlso [] ***********************************************************************/ Abc_ManRes_t * Abc_ManResubStart( int nLeavesMax, int nDivsMax ) { Abc_ManRes_t * p; unsigned * pData; int i, k; assert( sizeof(unsigned) == 4 ); p = ABC_ALLOC( Abc_ManRes_t, 1 ); memset( p, 0, sizeof(Abc_ManRes_t) ); p->nLeavesMax = nLeavesMax; p->nDivsMax = nDivsMax; p->vDivs = Vec_PtrAlloc( p->nDivsMax ); // allocate simulation info p->nBits = (1 << p->nLeavesMax); p->nWords = (p->nBits <= 32)? 1 : (p->nBits / 32); p->pInfo = ABC_ALLOC( unsigned, p->nWords * (p->nDivsMax + 1) ); memset( p->pInfo, 0, sizeof(unsigned) * p->nWords * p->nLeavesMax ); p->vSims = Vec_PtrAlloc( p->nDivsMax ); for ( i = 0; i < p->nDivsMax; i++ ) Vec_PtrPush( p->vSims, p->pInfo + i * p->nWords ); // assign the care set p->pCareSet = p->pInfo + p->nDivsMax * p->nWords; Abc_InfoFill( p->pCareSet, p->nWords ); // set elementary truth tables for ( k = 0; k < p->nLeavesMax; k++ ) { pData = (unsigned *)p->vSims->pArray[k]; for ( i = 0; i < p->nBits; i++ ) if ( i & (1 << k) ) pData[i>>5] |= (1 << (i&31)); } // create the remaining divisors p->vDivs1UP = Vec_PtrAlloc( p->nDivsMax ); p->vDivs1UN = Vec_PtrAlloc( p->nDivsMax ); p->vDivs1B = Vec_PtrAlloc( p->nDivsMax ); p->vDivs2UP0 = Vec_PtrAlloc( p->nDivsMax ); p->vDivs2UP1 = Vec_PtrAlloc( p->nDivsMax ); p->vDivs2UN0 = Vec_PtrAlloc( p->nDivsMax ); p->vDivs2UN1 = Vec_PtrAlloc( p->nDivsMax ); p->vTemp = Vec_PtrAlloc( p->nDivsMax ); return p; } /**Function************************************************************* Synopsis [] Description [] SideEffects [] SeeAlso [] ***********************************************************************/ void Abc_ManResubStop( Abc_ManRes_t * p ) { Vec_PtrFree( p->vDivs ); Vec_PtrFree( p->vSims ); Vec_PtrFree( p->vDivs1UP ); Vec_PtrFree( p->vDivs1UN ); Vec_PtrFree( p->vDivs1B ); Vec_PtrFree( p->vDivs2UP0 ); Vec_PtrFree( p->vDivs2UP1 ); Vec_PtrFree( p->vDivs2UN0 ); Vec_PtrFree( p->vDivs2UN1 ); Vec_PtrFree( p->vTemp ); ABC_FREE( p->pInfo ); ABC_FREE( p ); } /**Function************************************************************* Synopsis [] Description [] SideEffects [] SeeAlso [] ***********************************************************************/ void Abc_ManResubPrint( Abc_ManRes_t * p ) { printf( "Used constants = %6d. ", p->nUsedNodeC ); ABC_PRT( "Cuts ", p->timeCut ); printf( "Used replacements = %6d. ", p->nUsedNode0 ); ABC_PRT( "Resub ", p->timeRes ); printf( "Used single ORs = %6d. ", p->nUsedNode1Or ); ABC_PRT( " Div ", p->timeDiv ); printf( "Used single ANDs = %6d. ", p->nUsedNode1And ); ABC_PRT( " Mffc ", p->timeMffc ); printf( "Used double ORs = %6d. ", p->nUsedNode2Or ); ABC_PRT( " Sim ", p->timeSim ); printf( "Used double ANDs = %6d. ", p->nUsedNode2And ); ABC_PRT( " 1 ", p->timeRes1 ); printf( "Used OR-AND = %6d. ", p->nUsedNode2OrAnd ); ABC_PRT( " D ", p->timeResD ); printf( "Used AND-OR = %6d. ", p->nUsedNode2AndOr ); ABC_PRT( " 2 ", p->timeRes2 ); printf( "Used OR-2ANDs = %6d. ", p->nUsedNode3OrAnd ); ABC_PRT( "Truth ", p->timeTruth ); //ABC_PRT( " 3 ", p->timeRes3 ); printf( "Used AND-2ORs = %6d. ", p->nUsedNode3AndOr ); ABC_PRT( "AIG ", p->timeNtk ); printf( "TOTAL = %6d. ", p->nUsedNodeC + p->nUsedNode0 + p->nUsedNode1Or + p->nUsedNode1And + p->nUsedNode2Or + p->nUsedNode2And + p->nUsedNode2OrAnd + p->nUsedNode2AndOr + p->nUsedNode3OrAnd + p->nUsedNode3AndOr ); ABC_PRT( "TOTAL ", p->timeTotal ); printf( "Total leaves = %8d.\n", p->nTotalLeaves ); printf( "Total divisors = %8d.\n", p->nTotalDivs ); // printf( "Total gain = %8d.\n", p->nTotalGain ); printf( "Gain = %8d. (%6.2f %%).\n", p->nNodesBeg-p->nNodesEnd, 100.0*(p->nNodesBeg-p->nNodesEnd)/p->nNodesBeg ); } /**Function************************************************************* Synopsis [] Description [] SideEffects [] SeeAlso [] ***********************************************************************/ void Abc_ManResubCollectDivs_rec( Abc_Obj_t * pNode, Vec_Ptr_t * vInternal ) { // skip visited nodes if ( Abc_NodeIsTravIdCurrent(pNode) ) return; Abc_NodeSetTravIdCurrent(pNode); // collect the fanins Abc_ManResubCollectDivs_rec( Abc_ObjFanin0(pNode), vInternal ); Abc_ManResubCollectDivs_rec( Abc_ObjFanin1(pNode), vInternal ); // collect the internal node if ( pNode->fMarkA == 0 ) Vec_PtrPush( vInternal, pNode ); } /**Function************************************************************* Synopsis [] Description [] SideEffects [] SeeAlso [] ***********************************************************************/ int Abc_ManResubCollectDivs( Abc_ManRes_t * p, Abc_Obj_t * pRoot, Vec_Ptr_t * vLeaves, int Required ) { Abc_Obj_t * pNode, * pFanout; int i, k, Limit, Counter; Vec_PtrClear( p->vDivs1UP ); Vec_PtrClear( p->vDivs1UN ); Vec_PtrClear( p->vDivs1B ); // add the leaves of the cuts to the divisors Vec_PtrClear( p->vDivs ); Abc_NtkIncrementTravId( pRoot->pNtk ); Vec_PtrForEachEntry( Abc_Obj_t *, vLeaves, pNode, i ) { Vec_PtrPush( p->vDivs, pNode ); Abc_NodeSetTravIdCurrent( pNode ); } // mark nodes in the MFFC Vec_PtrForEachEntry( Abc_Obj_t *, p->vTemp, pNode, i ) pNode->fMarkA = 1; // collect the cone (without MFFC) Abc_ManResubCollectDivs_rec( pRoot, p->vDivs ); // unmark the current MFFC Vec_PtrForEachEntry( Abc_Obj_t *, p->vTemp, pNode, i ) pNode->fMarkA = 0; // check if the number of divisors is not exceeded if ( Vec_PtrSize(p->vDivs) - Vec_PtrSize(vLeaves) + Vec_PtrSize(p->vTemp) >= Vec_PtrSize(p->vSims) - p->nLeavesMax ) return 0; // get the number of divisors to collect Limit = Vec_PtrSize(p->vSims) - p->nLeavesMax - (Vec_PtrSize(p->vDivs) - Vec_PtrSize(vLeaves) + Vec_PtrSize(p->vTemp)); // explore the fanouts, which are not in the MFFC Counter = 0; Vec_PtrForEachEntry( Abc_Obj_t *, p->vDivs, pNode, i ) { if ( Abc_ObjFanoutNum(pNode) > 100 ) { // printf( "%d ", Abc_ObjFanoutNum(pNode) ); continue; } // if the fanout has both fanins in the set, add it Abc_ObjForEachFanout( pNode, pFanout, k ) { if ( Abc_NodeIsTravIdCurrent(pFanout) || Abc_ObjIsCo(pFanout) || (int)pFanout->Level > Required ) continue; if ( Abc_NodeIsTravIdCurrent(Abc_ObjFanin0(pFanout)) && Abc_NodeIsTravIdCurrent(Abc_ObjFanin1(pFanout)) ) { if ( Abc_ObjFanin0(pFanout) == pRoot || Abc_ObjFanin1(pFanout) == pRoot ) continue; Vec_PtrPush( p->vDivs, pFanout ); Abc_NodeSetTravIdCurrent( pFanout ); // quit computing divisors if there is too many of them if ( ++Counter == Limit ) goto Quits; } } } Quits : // get the number of divisors p->nDivs = Vec_PtrSize(p->vDivs); // add the nodes in the MFFC Vec_PtrForEachEntry( Abc_Obj_t *, p->vTemp, pNode, i ) Vec_PtrPush( p->vDivs, pNode ); assert( pRoot == Vec_PtrEntryLast(p->vDivs) ); assert( Vec_PtrSize(p->vDivs) - Vec_PtrSize(vLeaves) <= Vec_PtrSize(p->vSims) - p->nLeavesMax ); return 1; } /**Function************************************************************* Synopsis [] Description [] SideEffects [] SeeAlso [] ***********************************************************************/ void Abc_ManResubPrintDivs( Abc_ManRes_t * p, Abc_Obj_t * pRoot, Vec_Ptr_t * vLeaves ) { Abc_Obj_t * pFanin, * pNode; int i, k; // print the nodes Vec_PtrForEachEntry( Abc_Obj_t *, p->vDivs, pNode, i ) { if ( i < Vec_PtrSize(vLeaves) ) { printf( "%6d : %c\n", pNode->Id, 'a'+i ); continue; } printf( "%6d : %2d = ", pNode->Id, i ); // find the first fanin Vec_PtrForEachEntry( Abc_Obj_t *, p->vDivs, pFanin, k ) if ( Abc_ObjFanin0(pNode) == pFanin ) break; if ( k < Vec_PtrSize(vLeaves) ) printf( "%c", 'a' + k ); else printf( "%d", k ); printf( "%s ", Abc_ObjFaninC0(pNode)? "\'" : "" ); // find the second fanin Vec_PtrForEachEntry( Abc_Obj_t *, p->vDivs, pFanin, k ) if ( Abc_ObjFanin1(pNode) == pFanin ) break; if ( k < Vec_PtrSize(vLeaves) ) printf( "%c", 'a' + k ); else printf( "%d", k ); printf( "%s ", Abc_ObjFaninC1(pNode)? "\'" : "" ); if ( pNode == pRoot ) printf( " root" ); printf( "\n" ); } printf( "\n" ); } /**Function************************************************************* Synopsis [Performs simulation.] Description [] SideEffects [] SeeAlso [] ***********************************************************************/ void Abc_ManResubSimulate( Vec_Ptr_t * vDivs, int nLeaves, Vec_Ptr_t * vSims, int nLeavesMax, int nWords ) { Abc_Obj_t * pObj; unsigned * puData0, * puData1, * puData; int i, k; assert( Vec_PtrSize(vDivs) - nLeaves <= Vec_PtrSize(vSims) - nLeavesMax ); // simulate Vec_PtrForEachEntry( Abc_Obj_t *, vDivs, pObj, i ) { if ( i < nLeaves ) { // initialize the leaf pObj->pData = Vec_PtrEntry( vSims, i ); continue; } // set storage for the node's simulation info pObj->pData = Vec_PtrEntry( vSims, i - nLeaves + nLeavesMax ); // get pointer to the simulation info puData = (unsigned *)pObj->pData; puData0 = (unsigned *)Abc_ObjFanin0(pObj)->pData; puData1 = (unsigned *)Abc_ObjFanin1(pObj)->pData; // simulate if ( Abc_ObjFaninC0(pObj) && Abc_ObjFaninC1(pObj) ) for ( k = 0; k < nWords; k++ ) puData[k] = ~puData0[k] & ~puData1[k]; else if ( Abc_ObjFaninC0(pObj) ) for ( k = 0; k < nWords; k++ ) puData[k] = ~puData0[k] & puData1[k]; else if ( Abc_ObjFaninC1(pObj) ) for ( k = 0; k < nWords; k++ ) puData[k] = puData0[k] & ~puData1[k]; else for ( k = 0; k < nWords; k++ ) puData[k] = puData0[k] & puData1[k]; } // normalize Vec_PtrForEachEntry( Abc_Obj_t *, vDivs, pObj, i ) { puData = (unsigned *)pObj->pData; pObj->fPhase = (puData[0] & 1); if ( pObj->fPhase ) for ( k = 0; k < nWords; k++ ) puData[k] = ~puData[k]; } } /**Function************************************************************* Synopsis [] Description [] SideEffects [] SeeAlso [] ***********************************************************************/ Dec_Graph_t * Abc_ManResubQuit0( Abc_Obj_t * pRoot, Abc_Obj_t * pObj ) { Dec_Graph_t * pGraph; Dec_Edge_t eRoot; pGraph = Dec_GraphCreate( 1 ); Dec_GraphNode( pGraph, 0 )->pFunc = pObj; eRoot = Dec_EdgeCreate( 0, pObj->fPhase ); Dec_GraphSetRoot( pGraph, eRoot ); if ( pRoot->fPhase ) Dec_GraphComplement( pGraph ); return pGraph; } /**Function************************************************************* Synopsis [] Description [] SideEffects [] SeeAlso [] ***********************************************************************/ Dec_Graph_t * Abc_ManResubQuit1( Abc_Obj_t * pRoot, Abc_Obj_t * pObj0, Abc_Obj_t * pObj1, int fOrGate ) { Dec_Graph_t * pGraph; Dec_Edge_t eRoot, eNode0, eNode1; assert( pObj0 != pObj1 ); assert( !Abc_ObjIsComplement(pObj0) ); assert( !Abc_ObjIsComplement(pObj1) ); pGraph = Dec_GraphCreate( 2 ); Dec_GraphNode( pGraph, 0 )->pFunc = pObj0; Dec_GraphNode( pGraph, 1 )->pFunc = pObj1; eNode0 = Dec_EdgeCreate( 0, pObj0->fPhase ); eNode1 = Dec_EdgeCreate( 1, pObj1->fPhase ); if ( fOrGate ) eRoot = Dec_GraphAddNodeOr( pGraph, eNode0, eNode1 ); else eRoot = Dec_GraphAddNodeAnd( pGraph, eNode0, eNode1 ); Dec_GraphSetRoot( pGraph, eRoot ); if ( pRoot->fPhase ) Dec_GraphComplement( pGraph ); return pGraph; } /**Function************************************************************* Synopsis [] Description [] SideEffects [] SeeAlso [] ***********************************************************************/ Dec_Graph_t * Abc_ManResubQuit21( Abc_Obj_t * pRoot, Abc_Obj_t * pObj0, Abc_Obj_t * pObj1, Abc_Obj_t * pObj2, int fOrGate ) { Dec_Graph_t * pGraph; Dec_Edge_t eRoot, eNode0, eNode1, eNode2; assert( pObj0 != pObj1 ); assert( !Abc_ObjIsComplement(pObj0) ); assert( !Abc_ObjIsComplement(pObj1) ); assert( !Abc_ObjIsComplement(pObj2) ); pGraph = Dec_GraphCreate( 3 ); Dec_GraphNode( pGraph, 0 )->pFunc = pObj0; Dec_GraphNode( pGraph, 1 )->pFunc = pObj1; Dec_GraphNode( pGraph, 2 )->pFunc = pObj2; eNode0 = Dec_EdgeCreate( 0, pObj0->fPhase ); eNode1 = Dec_EdgeCreate( 1, pObj1->fPhase ); eNode2 = Dec_EdgeCreate( 2, pObj2->fPhase ); if ( fOrGate ) { eRoot = Dec_GraphAddNodeOr( pGraph, eNode0, eNode1 ); eRoot = Dec_GraphAddNodeOr( pGraph, eNode2, eRoot ); } else { eRoot = Dec_GraphAddNodeAnd( pGraph, eNode0, eNode1 ); eRoot = Dec_GraphAddNodeAnd( pGraph, eNode2, eRoot ); } Dec_GraphSetRoot( pGraph, eRoot ); if ( pRoot->fPhase ) Dec_GraphComplement( pGraph ); return pGraph; } /**Function************************************************************* Synopsis [] Description [] SideEffects [] SeeAlso [] ***********************************************************************/ Dec_Graph_t * Abc_ManResubQuit2( Abc_Obj_t * pRoot, Abc_Obj_t * pObj0, Abc_Obj_t * pObj1, Abc_Obj_t * pObj2, int fOrGate ) { Dec_Graph_t * pGraph; Dec_Edge_t eRoot, ePrev, eNode0, eNode1, eNode2; assert( pObj0 != pObj1 ); assert( pObj0 != pObj2 ); assert( pObj1 != pObj2 ); assert( !Abc_ObjIsComplement(pObj0) ); pGraph = Dec_GraphCreate( 3 ); Dec_GraphNode( pGraph, 0 )->pFunc = Abc_ObjRegular(pObj0); Dec_GraphNode( pGraph, 1 )->pFunc = Abc_ObjRegular(pObj1); Dec_GraphNode( pGraph, 2 )->pFunc = Abc_ObjRegular(pObj2); eNode0 = Dec_EdgeCreate( 0, Abc_ObjRegular(pObj0)->fPhase ); if ( Abc_ObjIsComplement(pObj1) && Abc_ObjIsComplement(pObj2) ) { eNode1 = Dec_EdgeCreate( 1, Abc_ObjRegular(pObj1)->fPhase ); eNode2 = Dec_EdgeCreate( 2, Abc_ObjRegular(pObj2)->fPhase ); ePrev = Dec_GraphAddNodeOr( pGraph, eNode1, eNode2 ); } else { eNode1 = Dec_EdgeCreate( 1, Abc_ObjRegular(pObj1)->fPhase ^ Abc_ObjIsComplement(pObj1) ); eNode2 = Dec_EdgeCreate( 2, Abc_ObjRegular(pObj2)->fPhase ^ Abc_ObjIsComplement(pObj2) ); ePrev = Dec_GraphAddNodeAnd( pGraph, eNode1, eNode2 ); } if ( fOrGate ) eRoot = Dec_GraphAddNodeOr( pGraph, eNode0, ePrev ); else eRoot = Dec_GraphAddNodeAnd( pGraph, eNode0, ePrev ); Dec_GraphSetRoot( pGraph, eRoot ); if ( pRoot->fPhase ) Dec_GraphComplement( pGraph ); return pGraph; } /**Function************************************************************* Synopsis [] Description [] SideEffects [] SeeAlso [] ***********************************************************************/ Dec_Graph_t * Abc_ManResubQuit3( Abc_Obj_t * pRoot, Abc_Obj_t * pObj0, Abc_Obj_t * pObj1, Abc_Obj_t * pObj2, Abc_Obj_t * pObj3, int fOrGate ) { Dec_Graph_t * pGraph; Dec_Edge_t eRoot, ePrev0, ePrev1, eNode0, eNode1, eNode2, eNode3; assert( pObj0 != pObj1 ); assert( pObj2 != pObj3 ); pGraph = Dec_GraphCreate( 4 ); Dec_GraphNode( pGraph, 0 )->pFunc = Abc_ObjRegular(pObj0); Dec_GraphNode( pGraph, 1 )->pFunc = Abc_ObjRegular(pObj1); Dec_GraphNode( pGraph, 2 )->pFunc = Abc_ObjRegular(pObj2); Dec_GraphNode( pGraph, 3 )->pFunc = Abc_ObjRegular(pObj3); if ( Abc_ObjIsComplement(pObj0) && Abc_ObjIsComplement(pObj1) ) { eNode0 = Dec_EdgeCreate( 0, Abc_ObjRegular(pObj0)->fPhase ); eNode1 = Dec_EdgeCreate( 1, Abc_ObjRegular(pObj1)->fPhase ); ePrev0 = Dec_GraphAddNodeOr( pGraph, eNode0, eNode1 ); if ( Abc_ObjIsComplement(pObj2) && Abc_ObjIsComplement(pObj3) ) { eNode2 = Dec_EdgeCreate( 2, Abc_ObjRegular(pObj2)->fPhase ); eNode3 = Dec_EdgeCreate( 3, Abc_ObjRegular(pObj3)->fPhase ); ePrev1 = Dec_GraphAddNodeOr( pGraph, eNode2, eNode3 ); } else { eNode2 = Dec_EdgeCreate( 2, Abc_ObjRegular(pObj2)->fPhase ^ Abc_ObjIsComplement(pObj2) ); eNode3 = Dec_EdgeCreate( 3, Abc_ObjRegular(pObj3)->fPhase ^ Abc_ObjIsComplement(pObj3) ); ePrev1 = Dec_GraphAddNodeAnd( pGraph, eNode2, eNode3 ); } } else { eNode0 = Dec_EdgeCreate( 0, Abc_ObjRegular(pObj0)->fPhase ^ Abc_ObjIsComplement(pObj0) ); eNode1 = Dec_EdgeCreate( 1, Abc_ObjRegular(pObj1)->fPhase ^ Abc_ObjIsComplement(pObj1) ); ePrev0 = Dec_GraphAddNodeAnd( pGraph, eNode0, eNode1 ); if ( Abc_ObjIsComplement(pObj2) && Abc_ObjIsComplement(pObj3) ) { eNode2 = Dec_EdgeCreate( 2, Abc_ObjRegular(pObj2)->fPhase ); eNode3 = Dec_EdgeCreate( 3, Abc_ObjRegular(pObj3)->fPhase ); ePrev1 = Dec_GraphAddNodeOr( pGraph, eNode2, eNode3 ); } else { eNode2 = Dec_EdgeCreate( 2, Abc_ObjRegular(pObj2)->fPhase ^ Abc_ObjIsComplement(pObj2) ); eNode3 = Dec_EdgeCreate( 3, Abc_ObjRegular(pObj3)->fPhase ^ Abc_ObjIsComplement(pObj3) ); ePrev1 = Dec_GraphAddNodeAnd( pGraph, eNode2, eNode3 ); } } if ( fOrGate ) eRoot = Dec_GraphAddNodeOr( pGraph, ePrev0, ePrev1 ); else eRoot = Dec_GraphAddNodeAnd( pGraph, ePrev0, ePrev1 ); Dec_GraphSetRoot( pGraph, eRoot ); if ( pRoot->fPhase ) Dec_GraphComplement( pGraph ); return pGraph; } /**Function************************************************************* Synopsis [Derives single-node unate/binate divisors.] Description [] SideEffects [] SeeAlso [] ***********************************************************************/ void Abc_ManResubDivsS( Abc_ManRes_t * p, int Required ) { Abc_Obj_t * pObj; unsigned * puData, * puDataR; int i, w; Vec_PtrClear( p->vDivs1UP ); Vec_PtrClear( p->vDivs1UN ); Vec_PtrClear( p->vDivs1B ); puDataR = (unsigned *)p->pRoot->pData; Vec_PtrForEachEntryStop( Abc_Obj_t *, p->vDivs, pObj, i, p->nDivs ) { if ( (int)pObj->Level > Required - 1 ) continue; puData = (unsigned *)pObj->pData; // check positive containment for ( w = 0; w < p->nWords; w++ ) // if ( puData[w] & ~puDataR[w] ) if ( puData[w] & ~puDataR[w] & p->pCareSet[w] ) // care set break; if ( w == p->nWords ) { Vec_PtrPush( p->vDivs1UP, pObj ); continue; } // check negative containment for ( w = 0; w < p->nWords; w++ ) // if ( ~puData[w] & puDataR[w] ) if ( ~puData[w] & puDataR[w] & p->pCareSet[w] ) // care set break; if ( w == p->nWords ) { Vec_PtrPush( p->vDivs1UN, pObj ); continue; } // add the node to binates Vec_PtrPush( p->vDivs1B, pObj ); } } /**Function************************************************************* Synopsis [Derives double-node unate/binate divisors.] Description [] SideEffects [] SeeAlso [] ***********************************************************************/ void Abc_ManResubDivsD( Abc_ManRes_t * p, int Required ) { Abc_Obj_t * pObj0, * pObj1; unsigned * puData0, * puData1, * puDataR; int i, k, w; Vec_PtrClear( p->vDivs2UP0 ); Vec_PtrClear( p->vDivs2UP1 ); Vec_PtrClear( p->vDivs2UN0 ); Vec_PtrClear( p->vDivs2UN1 ); puDataR = (unsigned *)p->pRoot->pData; Vec_PtrForEachEntry( Abc_Obj_t *, p->vDivs1B, pObj0, i ) { if ( (int)pObj0->Level > Required - 2 ) continue; puData0 = (unsigned *)pObj0->pData; Vec_PtrForEachEntryStart( Abc_Obj_t *, p->vDivs1B, pObj1, k, i + 1 ) { if ( (int)pObj1->Level > Required - 2 ) continue; puData1 = (unsigned *)pObj1->pData; if ( Vec_PtrSize(p->vDivs2UP0) < ABC_RS_DIV2_MAX ) { // get positive unate divisors for ( w = 0; w < p->nWords; w++ ) // if ( (puData0[w] & puData1[w]) & ~puDataR[w] ) if ( (puData0[w] & puData1[w]) & ~puDataR[w] & p->pCareSet[w] ) // care set break; if ( w == p->nWords ) { Vec_PtrPush( p->vDivs2UP0, pObj0 ); Vec_PtrPush( p->vDivs2UP1, pObj1 ); } for ( w = 0; w < p->nWords; w++ ) // if ( (~puData0[w] & puData1[w]) & ~puDataR[w] ) if ( (~puData0[w] & puData1[w]) & ~puDataR[w] & p->pCareSet[w] ) // care set break; if ( w == p->nWords ) { Vec_PtrPush( p->vDivs2UP0, Abc_ObjNot(pObj0) ); Vec_PtrPush( p->vDivs2UP1, pObj1 ); } for ( w = 0; w < p->nWords; w++ ) // if ( (puData0[w] & ~puData1[w]) & ~puDataR[w] ) if ( (puData0[w] & ~puData1[w]) & ~puDataR[w] & p->pCareSet[w] ) // care set break; if ( w == p->nWords ) { Vec_PtrPush( p->vDivs2UP0, pObj0 ); Vec_PtrPush( p->vDivs2UP1, Abc_ObjNot(pObj1) ); } for ( w = 0; w < p->nWords; w++ ) // if ( (puData0[w] | puData1[w]) & ~puDataR[w] ) if ( (puData0[w] | puData1[w]) & ~puDataR[w] & p->pCareSet[w] ) // care set break; if ( w == p->nWords ) { Vec_PtrPush( p->vDivs2UP0, Abc_ObjNot(pObj0) ); Vec_PtrPush( p->vDivs2UP1, Abc_ObjNot(pObj1) ); } } if ( Vec_PtrSize(p->vDivs2UN0) < ABC_RS_DIV2_MAX ) { // get negative unate divisors for ( w = 0; w < p->nWords; w++ ) // if ( ~(puData0[w] & puData1[w]) & puDataR[w] ) if ( ~(puData0[w] & puData1[w]) & puDataR[w] & p->pCareSet[w] ) // care set break; if ( w == p->nWords ) { Vec_PtrPush( p->vDivs2UN0, pObj0 ); Vec_PtrPush( p->vDivs2UN1, pObj1 ); } for ( w = 0; w < p->nWords; w++ ) // if ( ~(~puData0[w] & puData1[w]) & puDataR[w] ) if ( ~(~puData0[w] & puData1[w]) & puDataR[w] & p->pCareSet[w] ) // care set break; if ( w == p->nWords ) { Vec_PtrPush( p->vDivs2UN0, Abc_ObjNot(pObj0) ); Vec_PtrPush( p->vDivs2UN1, pObj1 ); } for ( w = 0; w < p->nWords; w++ ) // if ( ~(puData0[w] & ~puData1[w]) & puDataR[w] ) if ( ~(puData0[w] & ~puData1[w]) & puDataR[w] & p->pCareSet[w] ) // care set break; if ( w == p->nWords ) { Vec_PtrPush( p->vDivs2UN0, pObj0 ); Vec_PtrPush( p->vDivs2UN1, Abc_ObjNot(pObj1) ); } for ( w = 0; w < p->nWords; w++ ) // if ( ~(puData0[w] | puData1[w]) & puDataR[w] ) if ( ~(puData0[w] | puData1[w]) & puDataR[w] & p->pCareSet[w] ) // care set break; if ( w == p->nWords ) { Vec_PtrPush( p->vDivs2UN0, Abc_ObjNot(pObj0) ); Vec_PtrPush( p->vDivs2UN1, Abc_ObjNot(pObj1) ); } } } } // printf( "%d %d ", Vec_PtrSize(p->vDivs2UP0), Vec_PtrSize(p->vDivs2UN0) ); } /**Function************************************************************* Synopsis [] Description [] SideEffects [] SeeAlso [] ***********************************************************************/ Dec_Graph_t * Abc_ManResubQuit( Abc_ManRes_t * p ) { Dec_Graph_t * pGraph; unsigned * upData; int w; upData = (unsigned *)p->pRoot->pData; for ( w = 0; w < p->nWords; w++ ) // if ( upData[w] ) if ( upData[w] & p->pCareSet[w] ) // care set break; if ( w != p->nWords ) return NULL; // get constant node graph if ( p->pRoot->fPhase ) pGraph = Dec_GraphCreateConst1(); else pGraph = Dec_GraphCreateConst0(); return pGraph; } /**Function************************************************************* Synopsis [] Description [] SideEffects [] SeeAlso [] ***********************************************************************/ Dec_Graph_t * Abc_ManResubDivs0( Abc_ManRes_t * p ) { Abc_Obj_t * pObj; unsigned * puData, * puDataR; int i, w; puDataR = (unsigned *)p->pRoot->pData; Vec_PtrForEachEntryStop( Abc_Obj_t *, p->vDivs, pObj, i, p->nDivs ) { puData = (unsigned *)pObj->pData; for ( w = 0; w < p->nWords; w++ ) // if ( puData[w] != puDataR[w] ) if ( (puData[w] ^ puDataR[w]) & p->pCareSet[w] ) // care set break; if ( w == p->nWords ) return Abc_ManResubQuit0( p->pRoot, pObj ); } return NULL; } /**Function************************************************************* Synopsis [] Description [] SideEffects [] SeeAlso [] ***********************************************************************/ Dec_Graph_t * Abc_ManResubDivs1( Abc_ManRes_t * p, int Required ) { Abc_Obj_t * pObj0, * pObj1; unsigned * puData0, * puData1, * puDataR; int i, k, w; puDataR = (unsigned *)p->pRoot->pData; // check positive unate divisors Vec_PtrForEachEntry( Abc_Obj_t *, p->vDivs1UP, pObj0, i ) { puData0 = (unsigned *)pObj0->pData; Vec_PtrForEachEntryStart( Abc_Obj_t *, p->vDivs1UP, pObj1, k, i + 1 ) { puData1 = (unsigned *)pObj1->pData; for ( w = 0; w < p->nWords; w++ ) // if ( (puData0[w] | puData1[w]) != puDataR[w] ) if ( ((puData0[w] | puData1[w]) ^ puDataR[w]) & p->pCareSet[w] ) // care set break; if ( w == p->nWords ) { p->nUsedNode1Or++; return Abc_ManResubQuit1( p->pRoot, pObj0, pObj1, 1 ); } } } // check negative unate divisors Vec_PtrForEachEntry( Abc_Obj_t *, p->vDivs1UN, pObj0, i ) { puData0 = (unsigned *)pObj0->pData; Vec_PtrForEachEntryStart( Abc_Obj_t *, p->vDivs1UN, pObj1, k, i + 1 ) { puData1 = (unsigned *)pObj1->pData; for ( w = 0; w < p->nWords; w++ ) // if ( (puData0[w] & puData1[w]) != puDataR[w] ) if ( ((puData0[w] & puData1[w]) ^ puDataR[w]) & p->pCareSet[w] ) // care set break; if ( w == p->nWords ) { p->nUsedNode1And++; return Abc_ManResubQuit1( p->pRoot, pObj0, pObj1, 0 ); } } } return NULL; } /**Function************************************************************* Synopsis [] Description [] SideEffects [] SeeAlso [] ***********************************************************************/ Dec_Graph_t * Abc_ManResubDivs12( Abc_ManRes_t * p, int Required ) { Abc_Obj_t * pObj0, * pObj1, * pObj2, * pObjMax, * pObjMin0 = NULL, * pObjMin1 = NULL; unsigned * puData0, * puData1, * puData2, * puDataR; int i, k, j, w, LevelMax; puDataR = (unsigned *)p->pRoot->pData; // check positive unate divisors Vec_PtrForEachEntry( Abc_Obj_t *, p->vDivs1UP, pObj0, i ) { puData0 = (unsigned *)pObj0->pData; Vec_PtrForEachEntryStart( Abc_Obj_t *, p->vDivs1UP, pObj1, k, i + 1 ) { puData1 = (unsigned *)pObj1->pData; Vec_PtrForEachEntryStart( Abc_Obj_t *, p->vDivs1UP, pObj2, j, k + 1 ) { puData2 = (unsigned *)pObj2->pData; for ( w = 0; w < p->nWords; w++ ) // if ( (puData0[w] | puData1[w] | puData2[w]) != puDataR[w] ) if ( ((puData0[w] | puData1[w] | puData2[w]) ^ puDataR[w]) & p->pCareSet[w] ) // care set break; if ( w == p->nWords ) { LevelMax = Abc_MaxInt( pObj0->Level, Abc_MaxInt(pObj1->Level, pObj2->Level) ); assert( LevelMax <= Required - 1 ); pObjMax = NULL; if ( (int)pObj0->Level == LevelMax ) pObjMax = pObj0, pObjMin0 = pObj1, pObjMin1 = pObj2; if ( (int)pObj1->Level == LevelMax ) { if ( pObjMax ) continue; pObjMax = pObj1, pObjMin0 = pObj0, pObjMin1 = pObj2; } if ( (int)pObj2->Level == LevelMax ) { if ( pObjMax ) continue; pObjMax = pObj2, pObjMin0 = pObj0, pObjMin1 = pObj1; } p->nUsedNode2Or++; assert(pObjMin0); assert(pObjMin1); return Abc_ManResubQuit21( p->pRoot, pObjMin0, pObjMin1, pObjMax, 1 ); } } } } // check negative unate divisors Vec_PtrForEachEntry( Abc_Obj_t *, p->vDivs1UN, pObj0, i ) { puData0 = (unsigned *)pObj0->pData; Vec_PtrForEachEntryStart( Abc_Obj_t *, p->vDivs1UN, pObj1, k, i + 1 ) { puData1 = (unsigned *)pObj1->pData; Vec_PtrForEachEntryStart( Abc_Obj_t *, p->vDivs1UN, pObj2, j, k + 1 ) { puData2 = (unsigned *)pObj2->pData; for ( w = 0; w < p->nWords; w++ ) // if ( (puData0[w] & puData1[w] & puData2[w]) != puDataR[w] ) if ( ((puData0[w] & puData1[w] & puData2[w]) ^ puDataR[w]) & p->pCareSet[w] ) // care set break; if ( w == p->nWords ) { LevelMax = Abc_MaxInt( pObj0->Level, Abc_MaxInt(pObj1->Level, pObj2->Level) ); assert( LevelMax <= Required - 1 ); pObjMax = NULL; if ( (int)pObj0->Level == LevelMax ) pObjMax = pObj0, pObjMin0 = pObj1, pObjMin1 = pObj2; if ( (int)pObj1->Level == LevelMax ) { if ( pObjMax ) continue; pObjMax = pObj1, pObjMin0 = pObj0, pObjMin1 = pObj2; } if ( (int)pObj2->Level == LevelMax ) { if ( pObjMax ) continue; pObjMax = pObj2, pObjMin0 = pObj0, pObjMin1 = pObj1; } p->nUsedNode2And++; assert(pObjMin0); assert(pObjMin1); return Abc_ManResubQuit21( p->pRoot, pObjMin0, pObjMin1, pObjMax, 0 ); } } } } return NULL; } /**Function************************************************************* Synopsis [] Description [] SideEffects [] SeeAlso [] ***********************************************************************/ Dec_Graph_t * Abc_ManResubDivs2( Abc_ManRes_t * p, int Required ) { Abc_Obj_t * pObj0, * pObj1, * pObj2; unsigned * puData0, * puData1, * puData2, * puDataR; int i, k, w; puDataR = (unsigned *)p->pRoot->pData; // check positive unate divisors Vec_PtrForEachEntry( Abc_Obj_t *, p->vDivs1UP, pObj0, i ) { puData0 = (unsigned *)pObj0->pData; Vec_PtrForEachEntry( Abc_Obj_t *, p->vDivs2UP0, pObj1, k ) { pObj2 = (Abc_Obj_t *)Vec_PtrEntry( p->vDivs2UP1, k ); puData1 = (unsigned *)Abc_ObjRegular(pObj1)->pData; puData2 = (unsigned *)Abc_ObjRegular(pObj2)->pData; if ( Abc_ObjIsComplement(pObj1) && Abc_ObjIsComplement(pObj2) ) { for ( w = 0; w < p->nWords; w++ ) // if ( (puData0[w] | (puData1[w] | puData2[w])) != puDataR[w] ) if ( ((puData0[w] | (puData1[w] | puData2[w])) ^ puDataR[w]) & p->pCareSet[w] ) // care set break; } else if ( Abc_ObjIsComplement(pObj1) ) { for ( w = 0; w < p->nWords; w++ ) // if ( (puData0[w] | (~puData1[w] & puData2[w])) != puDataR[w] ) if ( ((puData0[w] | (~puData1[w] & puData2[w])) ^ puDataR[w]) & p->pCareSet[w] ) // care set break; } else if ( Abc_ObjIsComplement(pObj2) ) { for ( w = 0; w < p->nWords; w++ ) // if ( (puData0[w] | (puData1[w] & ~puData2[w])) != puDataR[w] ) if ( ((puData0[w] | (puData1[w] & ~puData2[w])) ^ puDataR[w]) & p->pCareSet[w] ) // care set break; } else { for ( w = 0; w < p->nWords; w++ ) // if ( (puData0[w] | (puData1[w] & puData2[w])) != puDataR[w] ) if ( ((puData0[w] | (puData1[w] & puData2[w])) ^ puDataR[w]) & p->pCareSet[w] ) // care set break; } if ( w == p->nWords ) { p->nUsedNode2OrAnd++; return Abc_ManResubQuit2( p->pRoot, pObj0, pObj1, pObj2, 1 ); } } } // check negative unate divisors Vec_PtrForEachEntry( Abc_Obj_t *, p->vDivs1UN, pObj0, i ) { puData0 = (unsigned *)pObj0->pData; Vec_PtrForEachEntry( Abc_Obj_t *, p->vDivs2UN0, pObj1, k ) { pObj2 = (Abc_Obj_t *)Vec_PtrEntry( p->vDivs2UN1, k ); puData1 = (unsigned *)Abc_ObjRegular(pObj1)->pData; puData2 = (unsigned *)Abc_ObjRegular(pObj2)->pData; if ( Abc_ObjIsComplement(pObj1) && Abc_ObjIsComplement(pObj2) ) { for ( w = 0; w < p->nWords; w++ ) // if ( (puData0[w] & (puData1[w] | puData2[w])) != puDataR[w] ) if ( ((puData0[w] & (puData1[w] | puData2[w])) ^ puDataR[w]) & p->pCareSet[w] ) // care set break; } else if ( Abc_ObjIsComplement(pObj1) ) { for ( w = 0; w < p->nWords; w++ ) // if ( (puData0[w] & (~puData1[w] & puData2[w])) != puDataR[w] ) if ( ((puData0[w] & (~puData1[w] & puData2[w])) ^ puDataR[w]) & p->pCareSet[w] ) // care set break; } else if ( Abc_ObjIsComplement(pObj2) ) { for ( w = 0; w < p->nWords; w++ ) // if ( (puData0[w] & (puData1[w] & ~puData2[w])) != puDataR[w] ) if ( ((puData0[w] & (puData1[w] & ~puData2[w])) ^ puDataR[w]) & p->pCareSet[w] ) // care set break; } else { for ( w = 0; w < p->nWords; w++ ) // if ( (puData0[w] & (puData1[w] & puData2[w])) != puDataR[w] ) if ( ((puData0[w] & (puData1[w] & puData2[w])) ^ puDataR[w]) & p->pCareSet[w] ) // care set break; } if ( w == p->nWords ) { p->nUsedNode2AndOr++; return Abc_ManResubQuit2( p->pRoot, pObj0, pObj1, pObj2, 0 ); } } } return NULL; } /**Function************************************************************* Synopsis [] Description [] SideEffects [] SeeAlso [] ***********************************************************************/ Dec_Graph_t * Abc_ManResubDivs3( Abc_ManRes_t * p, int Required ) { Abc_Obj_t * pObj0, * pObj1, * pObj2, * pObj3; unsigned * puData0, * puData1, * puData2, * puData3, * puDataR; int i, k, w = 0, Flag; puDataR = (unsigned *)p->pRoot->pData; // check positive unate divisors Vec_PtrForEachEntry( Abc_Obj_t *, p->vDivs2UP0, pObj0, i ) { pObj1 = (Abc_Obj_t *)Vec_PtrEntry( p->vDivs2UP1, i ); puData0 = (unsigned *)Abc_ObjRegular(pObj0)->pData; puData1 = (unsigned *)Abc_ObjRegular(pObj1)->pData; Flag = (Abc_ObjIsComplement(pObj0) << 3) | (Abc_ObjIsComplement(pObj1) << 2); Vec_PtrForEachEntryStart( Abc_Obj_t *, p->vDivs2UP0, pObj2, k, i + 1 ) { pObj3 = (Abc_Obj_t *)Vec_PtrEntry( p->vDivs2UP1, k ); puData2 = (unsigned *)Abc_ObjRegular(pObj2)->pData; puData3 = (unsigned *)Abc_ObjRegular(pObj3)->pData; Flag = (Flag & 12) | ((int)Abc_ObjIsComplement(pObj2) << 1) | (int)Abc_ObjIsComplement(pObj3); assert( Flag < 16 ); switch( Flag ) { case 0: // 0000 for ( w = 0; w < p->nWords; w++ ) // if ( ((puData0[w] & puData1[w]) | (puData2[w] & puData3[w])) != puDataR[w] ) if ( (((puData0[w] & puData1[w]) | (puData2[w] & puData3[w])) ^ puDataR[w]) & p->pCareSet[w] ) // care set break; break; case 1: // 0001 for ( w = 0; w < p->nWords; w++ ) // if ( ((puData0[w] & puData1[w]) | (puData2[w] & ~puData3[w])) != puDataR[w] ) if ( (((puData0[w] & puData1[w]) | (puData2[w] & ~puData3[w])) ^ puDataR[w]) & p->pCareSet[w] ) // care set break; break; case 2: // 0010 for ( w = 0; w < p->nWords; w++ ) // if ( ((puData0[w] & puData1[w]) | (~puData2[w] & puData3[w])) != puDataR[w] ) if ( (((puData0[w] & puData1[w]) | (~puData2[w] & puData3[w])) ^ puDataR[w]) & p->pCareSet[w] ) // care set break; break; case 3: // 0011 for ( w = 0; w < p->nWords; w++ ) // if ( ((puData0[w] & puData1[w]) | (puData2[w] | puData3[w])) != puDataR[w] ) if ( (((puData0[w] & puData1[w]) | (puData2[w] | puData3[w])) ^ puDataR[w]) & p->pCareSet[w] ) // care set break; break; case 4: // 0100 for ( w = 0; w < p->nWords; w++ ) // if ( ((puData0[w] & ~puData1[w]) | (puData2[w] & puData3[w])) != puDataR[w] ) if ( (((puData0[w] & ~puData1[w]) | (puData2[w] & puData3[w])) ^ puDataR[w]) & p->pCareSet[w] ) // care set break; break; case 5: // 0101 for ( w = 0; w < p->nWords; w++ ) // if ( ((puData0[w] & ~puData1[w]) | (puData2[w] & ~puData3[w])) != puDataR[w] ) if ( (((puData0[w] & ~puData1[w]) | (puData2[w] & ~puData3[w])) ^ puDataR[w]) & p->pCareSet[w] ) // care set break; break; case 6: // 0110 for ( w = 0; w < p->nWords; w++ ) // if ( ((puData0[w] & ~puData1[w]) | (~puData2[w] & puData3[w])) != puDataR[w] ) if ( (((puData0[w] & ~puData1[w]) | (~puData2[w] & puData3[w])) ^ puDataR[w]) & p->pCareSet[w] ) // care set break; break; case 7: // 0111 for ( w = 0; w < p->nWords; w++ ) // if ( ((puData0[w] & ~puData1[w]) | (puData2[w] | puData3[w])) != puDataR[w] ) if ( (((puData0[w] & ~puData1[w]) | (puData2[w] | puData3[w])) ^ puDataR[w]) & p->pCareSet[w] ) // care set break; break; case 8: // 1000 for ( w = 0; w < p->nWords; w++ ) // if ( ((~puData0[w] & puData1[w]) | (puData2[w] & puData3[w])) != puDataR[w] ) if ( (((~puData0[w] & puData1[w]) | (puData2[w] & puData3[w])) ^ puDataR[w]) & p->pCareSet[w] ) // care set break; break; case 9: // 1001 for ( w = 0; w < p->nWords; w++ ) // if ( ((~puData0[w] & puData1[w]) | (puData2[w] & ~puData3[w])) != puDataR[w] ) if ( (((~puData0[w] & puData1[w]) | (puData2[w] & ~puData3[w])) ^ puDataR[w]) & p->pCareSet[w] ) // care set break; break; case 10: // 1010 for ( w = 0; w < p->nWords; w++ ) // if ( ((~puData0[w] & puData1[w]) | (~puData2[w] & puData3[w])) != puDataR[w] ) if ( (((~puData0[w] & puData1[w]) | (~puData2[w] & puData3[w])) ^ puDataR[w]) & p->pCareSet[w] ) // care set break; break; case 11: // 1011 for ( w = 0; w < p->nWords; w++ ) // if ( ((~puData0[w] & puData1[w]) | (puData2[w] | puData3[w])) != puDataR[w] ) if ( (((~puData0[w] & puData1[w]) | (puData2[w] | puData3[w])) ^ puDataR[w]) & p->pCareSet[w] ) // care set break; break; case 12: // 1100 for ( w = 0; w < p->nWords; w++ ) // if ( ((puData0[w] | puData1[w]) | (puData2[w] & puData3[w])) != puDataR[w] ) if ( (((puData0[w] | puData1[w]) | (puData2[w] & puData3[w])) ^ puDataR[w]) & p->pCareSet[w] ) // care set break; break; case 13: // 1101 for ( w = 0; w < p->nWords; w++ ) // if ( ((puData0[w] | puData1[w]) | (puData2[w] & ~puData3[w])) != puDataR[w] ) if ( (((puData0[w] | puData1[w]) | (puData2[w] & ~puData3[w])) ^ puDataR[w]) & p->pCareSet[w] ) break; break; case 14: // 1110 for ( w = 0; w < p->nWords; w++ ) // if ( ((puData0[w] | puData1[w]) | (~puData2[w] & puData3[w])) != puDataR[w] ) if ( (((puData0[w] | puData1[w]) | (~puData2[w] & puData3[w])) ^ puDataR[w]) & p->pCareSet[w] ) break; break; case 15: // 1111 for ( w = 0; w < p->nWords; w++ ) // if ( ((puData0[w] | puData1[w]) | (puData2[w] | puData3[w])) != puDataR[w] ) if ( (((puData0[w] | puData1[w]) | (puData2[w] | puData3[w])) ^ puDataR[w]) & p->pCareSet[w] ) break; break; } if ( w == p->nWords ) { p->nUsedNode3OrAnd++; return Abc_ManResubQuit3( p->pRoot, pObj0, pObj1, pObj2, pObj3, 1 ); } } } /* // check negative unate divisors Vec_PtrForEachEntry( Abc_Obj_t *, p->vDivs2UN0, pObj0, i ) { pObj1 = Vec_PtrEntry( p->vDivs2UN1, i ); puData0 = Abc_ObjRegular(pObj0)->pData; puData1 = Abc_ObjRegular(pObj1)->pData; Flag = (Abc_ObjIsComplement(pObj0) << 3) | (Abc_ObjIsComplement(pObj1) << 2); Vec_PtrForEachEntryStart( Abc_Obj_t *, p->vDivs2UN0, pObj2, k, i + 1 ) { pObj3 = Vec_PtrEntry( p->vDivs2UN1, k ); puData2 = Abc_ObjRegular(pObj2)->pData; puData3 = Abc_ObjRegular(pObj3)->pData; Flag = (Flag & 12) | (Abc_ObjIsComplement(pObj2) << 1) | Abc_ObjIsComplement(pObj3); assert( Flag < 16 ); switch( Flag ) { case 0: // 0000 for ( w = 0; w < p->nWords; w++ ) if ( ((puData0[w] & puData1[w]) & (puData2[w] & puData3[w])) != puDataR[w] ) break; break; case 1: // 0001 for ( w = 0; w < p->nWords; w++ ) if ( ((puData0[w] & puData1[w]) & (puData2[w] & ~puData3[w])) != puDataR[w] ) break; break; case 2: // 0010 for ( w = 0; w < p->nWords; w++ ) if ( ((puData0[w] & puData1[w]) & (~puData2[w] & puData3[w])) != puDataR[w] ) break; break; case 3: // 0011 for ( w = 0; w < p->nWords; w++ ) if ( ((puData0[w] & puData1[w]) & (puData2[w] | puData3[w])) != puDataR[w] ) break; break; case 4: // 0100 for ( w = 0; w < p->nWords; w++ ) if ( ((puData0[w] & ~puData1[w]) & (puData2[w] & puData3[w])) != puDataR[w] ) break; break; case 5: // 0101 for ( w = 0; w < p->nWords; w++ ) if ( ((puData0[w] & ~puData1[w]) & (puData2[w] & ~puData3[w])) != puDataR[w] ) break; break; case 6: // 0110 for ( w = 0; w < p->nWords; w++ ) if ( ((puData0[w] & ~puData1[w]) & (~puData2[w] & puData3[w])) != puDataR[w] ) break; break; case 7: // 0111 for ( w = 0; w < p->nWords; w++ ) if ( ((puData0[w] & ~puData1[w]) & (puData2[w] | puData3[w])) != puDataR[w] ) break; break; case 8: // 1000 for ( w = 0; w < p->nWords; w++ ) if ( ((~puData0[w] & puData1[w]) & (puData2[w] & puData3[w])) != puDataR[w] ) break; break; case 9: // 1001 for ( w = 0; w < p->nWords; w++ ) if ( ((~puData0[w] & puData1[w]) & (puData2[w] & ~puData3[w])) != puDataR[w] ) break; break; case 10: // 1010 for ( w = 0; w < p->nWords; w++ ) if ( ((~puData0[w] & puData1[w]) & (~puData2[w] & puData3[w])) != puDataR[w] ) break; break; case 11: // 1011 for ( w = 0; w < p->nWords; w++ ) if ( ((~puData0[w] & puData1[w]) & (puData2[w] | puData3[w])) != puDataR[w] ) break; break; case 12: // 1100 for ( w = 0; w < p->nWords; w++ ) if ( ((puData0[w] | puData1[w]) & (puData2[w] & puData3[w])) != puDataR[w] ) break; break; case 13: // 1101 for ( w = 0; w < p->nWords; w++ ) if ( ((puData0[w] | puData1[w]) & (puData2[w] & ~puData3[w])) != puDataR[w] ) break; break; case 14: // 1110 for ( w = 0; w < p->nWords; w++ ) if ( ((puData0[w] | puData1[w]) & (~puData2[w] & puData3[w])) != puDataR[w] ) break; break; case 15: // 1111 for ( w = 0; w < p->nWords; w++ ) if ( ((puData0[w] | puData1[w]) & (puData2[w] | puData3[w])) != puDataR[w] ) break; break; } if ( w == p->nWords ) { p->nUsedNode3AndOr++; return Abc_ManResubQuit3( p->pRoot, pObj0, pObj1, pObj2, pObj3, 0 ); } } } */ return NULL; } /**Function************************************************************* Synopsis [] Description [] SideEffects [] SeeAlso [] ***********************************************************************/ void Abc_ManResubCleanup( Abc_ManRes_t * p ) { Abc_Obj_t * pObj; int i; Vec_PtrForEachEntry( Abc_Obj_t *, p->vDivs, pObj, i ) pObj->pData = NULL; Vec_PtrClear( p->vDivs ); p->pRoot = NULL; } /**Function************************************************************* Synopsis [Evaluates resubstution of one cut.] Description [Returns the graph to add if any.] SideEffects [] SeeAlso [] ***********************************************************************/ Dec_Graph_t * Abc_ManResubEval( Abc_ManRes_t * p, Abc_Obj_t * pRoot, Vec_Ptr_t * vLeaves, int nSteps, int fUpdateLevel, int fVerbose ) { extern int Abc_NodeMffcInside( Abc_Obj_t * pNode, Vec_Ptr_t * vLeaves, Vec_Ptr_t * vInside ); Dec_Graph_t * pGraph; int Required; abctime clk; Required = fUpdateLevel? Abc_ObjRequiredLevel(pRoot) : ABC_INFINITY; assert( nSteps >= 0 ); assert( nSteps <= 3 ); p->pRoot = pRoot; p->nLeaves = Vec_PtrSize(vLeaves); p->nLastGain = -1; // collect the MFFC clk = Abc_Clock(); p->nMffc = Abc_NodeMffcInside( pRoot, vLeaves, p->vTemp ); p->timeMffc += Abc_Clock() - clk; assert( p->nMffc > 0 ); // collect the divisor nodes clk = Abc_Clock(); if ( !Abc_ManResubCollectDivs( p, pRoot, vLeaves, Required ) ) return NULL; p->timeDiv += Abc_Clock() - clk; p->nTotalDivs += p->nDivs; p->nTotalLeaves += p->nLeaves; // simulate the nodes clk = Abc_Clock(); Abc_ManResubSimulate( p->vDivs, p->nLeaves, p->vSims, p->nLeavesMax, p->nWords ); p->timeSim += Abc_Clock() - clk; clk = Abc_Clock(); // consider constants if ( (pGraph = Abc_ManResubQuit( p )) ) { p->nUsedNodeC++; p->nLastGain = p->nMffc; return pGraph; } // consider equal nodes if ( (pGraph = Abc_ManResubDivs0( p )) ) { p->timeRes1 += Abc_Clock() - clk; p->nUsedNode0++; p->nLastGain = p->nMffc; return pGraph; } if ( nSteps == 0 || p->nMffc == 1 ) { p->timeRes1 += Abc_Clock() - clk; return NULL; } // get the one level divisors Abc_ManResubDivsS( p, Required ); // consider one node if ( (pGraph = Abc_ManResubDivs1( p, Required )) ) { p->timeRes1 += Abc_Clock() - clk; p->nLastGain = p->nMffc - 1; return pGraph; } p->timeRes1 += Abc_Clock() - clk; if ( nSteps == 1 || p->nMffc == 2 ) return NULL; clk = Abc_Clock(); // consider triples if ( (pGraph = Abc_ManResubDivs12( p, Required )) ) { p->timeRes2 += Abc_Clock() - clk; p->nLastGain = p->nMffc - 2; return pGraph; } p->timeRes2 += Abc_Clock() - clk; // get the two level divisors clk = Abc_Clock(); Abc_ManResubDivsD( p, Required ); p->timeResD += Abc_Clock() - clk; // consider two nodes clk = Abc_Clock(); if ( (pGraph = Abc_ManResubDivs2( p, Required )) ) { p->timeRes2 += Abc_Clock() - clk; p->nLastGain = p->nMffc - 2; return pGraph; } p->timeRes2 += Abc_Clock() - clk; if ( nSteps == 2 || p->nMffc == 3 ) return NULL; // consider two nodes clk = Abc_Clock(); if ( (pGraph = Abc_ManResubDivs3( p, Required )) ) { p->timeRes3 += Abc_Clock() - clk; p->nLastGain = p->nMffc - 3; return pGraph; } p->timeRes3 += Abc_Clock() - clk; if ( nSteps == 3 || p->nLeavesMax == 4 ) return NULL; return NULL; } /**Function************************************************************* Synopsis [Computes the volume and checks if the cut is feasible.] Description [] SideEffects [] SeeAlso [] ***********************************************************************/ int Abc_CutVolumeCheck_rec( Abc_Obj_t * pObj ) { // quit if the node is visited (or if it is a leaf) if ( Abc_NodeIsTravIdCurrent(pObj) ) return 0; Abc_NodeSetTravIdCurrent(pObj); // report the error if ( Abc_ObjIsCi(pObj) ) printf( "Abc_CutVolumeCheck() ERROR: The set of nodes is not a cut!\n" ); // count the number of nodes in the leaves return 1 + Abc_CutVolumeCheck_rec( Abc_ObjFanin0(pObj) ) + Abc_CutVolumeCheck_rec( Abc_ObjFanin1(pObj) ); } /**Function************************************************************* Synopsis [Computes the volume and checks if the cut is feasible.] Description [] SideEffects [] SeeAlso [] ***********************************************************************/ int Abc_CutVolumeCheck( Abc_Obj_t * pNode, Vec_Ptr_t * vLeaves ) { Abc_Obj_t * pObj; int i; // mark the leaves Abc_NtkIncrementTravId( pNode->pNtk ); Vec_PtrForEachEntry( Abc_Obj_t *, vLeaves, pObj, i ) Abc_NodeSetTravIdCurrent( pObj ); // traverse the nodes starting from the given one and count them return Abc_CutVolumeCheck_rec( pNode ); } /**Function************************************************************* Synopsis [Computes the factor cut of the node.] Description [] SideEffects [] SeeAlso [] ***********************************************************************/ void Abc_CutFactor_rec( Abc_Obj_t * pObj, Vec_Ptr_t * vLeaves ) { if ( pObj->fMarkA ) return; if ( Abc_ObjIsCi(pObj) || (Abc_ObjFanoutNum(pObj) > 1 && !Abc_NodeIsMuxControlType(pObj)) ) { Vec_PtrPush( vLeaves, pObj ); pObj->fMarkA = 1; return; } Abc_CutFactor_rec( Abc_ObjFanin0(pObj), vLeaves ); Abc_CutFactor_rec( Abc_ObjFanin1(pObj), vLeaves ); } /**Function************************************************************* Synopsis [Computes the factor cut of the node.] Description [Factor-cut is the cut at a node in terms of factor-nodes. Factor-nodes are roots of the node trees (MUXes/EXORs are counted as single nodes). Factor-cut is unique for the given node.] SideEffects [] SeeAlso [] ***********************************************************************/ Vec_Ptr_t * Abc_CutFactor( Abc_Obj_t * pNode ) { Vec_Ptr_t * vLeaves; Abc_Obj_t * pObj; int i; assert( !Abc_ObjIsCi(pNode) ); vLeaves = Vec_PtrAlloc( 10 ); Abc_CutFactor_rec( Abc_ObjFanin0(pNode), vLeaves ); Abc_CutFactor_rec( Abc_ObjFanin1(pNode), vLeaves ); Vec_PtrForEachEntry( Abc_Obj_t *, vLeaves, pObj, i ) pObj->fMarkA = 0; return vLeaves; } /**Function************************************************************* Synopsis [Cut computation.] Description [This cut computation works as follows: It starts with the factor cut at the node. If the factor-cut is large, quit. It supports the set of leaves of the cut under construction and labels all nodes in the cut under construction, including the leaves. It computes the factor-cuts of the leaves and checks if it is easible to add any of them. If it is, it randomly chooses one feasible and continues.] SideEffects [] SeeAlso [] ***********************************************************************/ Vec_Ptr_t * Abc_CutFactorLarge( Abc_Obj_t * pNode, int nLeavesMax ) { Vec_Ptr_t * vLeaves, * vFactors, * vFact, * vNext; Vec_Int_t * vFeasible; Abc_Obj_t * pLeaf, * pTemp; int i, k, Counter, RandLeaf; int BestCut, BestShare; assert( Abc_ObjIsNode(pNode) ); // get one factor-cut vLeaves = Abc_CutFactor( pNode ); if ( Vec_PtrSize(vLeaves) > nLeavesMax ) { Vec_PtrFree(vLeaves); return NULL; } if ( Vec_PtrSize(vLeaves) == nLeavesMax ) return vLeaves; // initialize the factor cuts for the leaves vFactors = Vec_PtrAlloc( nLeavesMax ); Abc_NtkIncrementTravId( pNode->pNtk ); Vec_PtrForEachEntry( Abc_Obj_t *, vLeaves, pLeaf, i ) { Abc_NodeSetTravIdCurrent( pLeaf ); if ( Abc_ObjIsCi(pLeaf) ) Vec_PtrPush( vFactors, NULL ); else Vec_PtrPush( vFactors, Abc_CutFactor(pLeaf) ); } // construct larger factor cuts vFeasible = Vec_IntAlloc( nLeavesMax ); while ( 1 ) { BestCut = -1, BestShare = -1; // find the next feasible cut to add Vec_IntClear( vFeasible ); Vec_PtrForEachEntry( Vec_Ptr_t *, vFactors, vFact, i ) { if ( vFact == NULL ) continue; // count the number of unmarked leaves of this factor cut Counter = 0; Vec_PtrForEachEntry( Abc_Obj_t *, vFact, pTemp, k ) Counter += !Abc_NodeIsTravIdCurrent(pTemp); // if the number of new leaves is smaller than the diff, it is feasible if ( Counter <= nLeavesMax - Vec_PtrSize(vLeaves) + 1 ) { Vec_IntPush( vFeasible, i ); if ( BestCut == -1 || BestShare < Vec_PtrSize(vFact) - Counter ) BestCut = i, BestShare = Vec_PtrSize(vFact) - Counter; } } // quit if there is no feasible factor cuts if ( Vec_IntSize(vFeasible) == 0 ) break; // randomly choose one leaf and get its factor cut // RandLeaf = Vec_IntEntry( vFeasible, rand() % Vec_IntSize(vFeasible) ); // choose the cut that has most sharing with the other cuts RandLeaf = BestCut; pLeaf = (Abc_Obj_t *)Vec_PtrEntry( vLeaves, RandLeaf ); vNext = (Vec_Ptr_t *)Vec_PtrEntry( vFactors, RandLeaf ); // unmark this leaf Abc_NodeSetTravIdPrevious( pLeaf ); // remove this cut from the leaves and factor cuts for ( i = RandLeaf; i < Vec_PtrSize(vLeaves)-1; i++ ) { Vec_PtrWriteEntry( vLeaves, i, Vec_PtrEntry(vLeaves, i+1) ); Vec_PtrWriteEntry( vFactors, i, Vec_PtrEntry(vFactors,i+1) ); } Vec_PtrShrink( vLeaves, Vec_PtrSize(vLeaves) -1 ); Vec_PtrShrink( vFactors, Vec_PtrSize(vFactors)-1 ); // add new leaves, compute their factor cuts Vec_PtrForEachEntry( Abc_Obj_t *, vNext, pLeaf, i ) { if ( Abc_NodeIsTravIdCurrent(pLeaf) ) continue; Abc_NodeSetTravIdCurrent( pLeaf ); Vec_PtrPush( vLeaves, pLeaf ); if ( Abc_ObjIsCi(pLeaf) ) Vec_PtrPush( vFactors, NULL ); else Vec_PtrPush( vFactors, Abc_CutFactor(pLeaf) ); } Vec_PtrFree( vNext ); assert( Vec_PtrSize(vLeaves) <= nLeavesMax ); if ( Vec_PtrSize(vLeaves) == nLeavesMax ) break; } // remove temporary storage Vec_PtrForEachEntry( Vec_Ptr_t *, vFactors, vFact, i ) if ( vFact ) Vec_PtrFree( vFact ); Vec_PtrFree( vFactors ); Vec_IntFree( vFeasible ); return vLeaves; } //////////////////////////////////////////////////////////////////////// /// END OF FILE /// //////////////////////////////////////////////////////////////////////// ABC_NAMESPACE_IMPL_END
Kinghsy/Approxiamate-Logic-Synthesis
lib/abc/src/base/abci/abcResub.c
C
gpl-3.0
71,823
/**CFile**************************************************************** FileName [resStrash.c] SystemName [ABC: Logic synthesis and verification system.] PackageName [Resynthesis package.] Synopsis [Structural hashing of the nodes in the window.] Author [Alan Mishchenko] Affiliation [UC Berkeley] Date [Ver. 1.0. Started - January 15, 2007.] Revision [$Id: resStrash.c,v 1.00 2007/01/15 00:00:00 alanmi Exp $] ***********************************************************************/ #include "base/abc/abc.h" #include "resInt.h" ABC_NAMESPACE_IMPL_START //////////////////////////////////////////////////////////////////////// /// DECLARATIONS /// //////////////////////////////////////////////////////////////////////// extern Abc_Obj_t * Abc_ConvertAigToAig( Abc_Ntk_t * pAig, Abc_Obj_t * pObjOld ); //////////////////////////////////////////////////////////////////////// /// FUNCTION DEFINITIONS /// //////////////////////////////////////////////////////////////////////// /**Function************************************************************* Synopsis [Structurally hashes the given window.] Description [The first PO is the observability condition. The second is the node's function. The remaining POs are the candidate divisors.] SideEffects [] SeeAlso [] ***********************************************************************/ Abc_Ntk_t * Res_WndStrash( Res_Win_t * p ) { Vec_Ptr_t * vPairs; Abc_Ntk_t * pAig; Abc_Obj_t * pObj, * pMiter; int i; assert( Abc_NtkHasAig(p->pNode->pNtk) ); // Abc_NtkCleanCopy( p->pNode->pNtk ); // create the network pAig = Abc_NtkAlloc( ABC_NTK_STRASH, ABC_FUNC_AIG, 1 ); pAig->pName = Extra_UtilStrsav( "window" ); // create the inputs Vec_PtrForEachEntry( Abc_Obj_t *, p->vLeaves, pObj, i ) pObj->pCopy = Abc_NtkCreatePi( pAig ); Vec_PtrForEachEntry( Abc_Obj_t *, p->vBranches, pObj, i ) pObj->pCopy = Abc_NtkCreatePi( pAig ); // go through the nodes in the topological order Vec_PtrForEachEntry( Abc_Obj_t *, p->vNodes, pObj, i ) { pObj->pCopy = Abc_ConvertAigToAig( pAig, pObj ); if ( pObj == p->pNode ) pObj->pCopy = Abc_ObjNot( pObj->pCopy ); } // collect the POs vPairs = Vec_PtrAlloc( 2 * Vec_PtrSize(p->vRoots) ); Vec_PtrForEachEntry( Abc_Obj_t *, p->vRoots, pObj, i ) { Vec_PtrPush( vPairs, pObj->pCopy ); Vec_PtrPush( vPairs, NULL ); } // mark the TFO of the node Abc_NtkIncrementTravId( p->pNode->pNtk ); Res_WinSweepLeafTfo_rec( p->pNode, (int)p->pNode->Level + p->nWinTfoMax ); // update strashing of the node p->pNode->pCopy = Abc_ObjNot( p->pNode->pCopy ); Abc_NodeSetTravIdPrevious( p->pNode ); // redo strashing in the TFO Vec_PtrForEachEntry( Abc_Obj_t *, p->vNodes, pObj, i ) { if ( Abc_NodeIsTravIdCurrent(pObj) ) pObj->pCopy = Abc_ConvertAigToAig( pAig, pObj ); } // collect the POs Vec_PtrForEachEntry( Abc_Obj_t *, p->vRoots, pObj, i ) Vec_PtrWriteEntry( vPairs, 2 * i + 1, pObj->pCopy ); // add the miter pMiter = Abc_AigMiter( (Abc_Aig_t *)pAig->pManFunc, vPairs, 0 ); Abc_ObjAddFanin( Abc_NtkCreatePo(pAig), pMiter ); Vec_PtrFree( vPairs ); // add the node Abc_ObjAddFanin( Abc_NtkCreatePo(pAig), p->pNode->pCopy ); // add the fanins Abc_ObjForEachFanin( p->pNode, pObj, i ) Abc_ObjAddFanin( Abc_NtkCreatePo(pAig), pObj->pCopy ); // add the divisors Vec_PtrForEachEntry( Abc_Obj_t *, p->vDivs, pObj, i ) Abc_ObjAddFanin( Abc_NtkCreatePo(pAig), pObj->pCopy ); // add the names Abc_NtkAddDummyPiNames( pAig ); Abc_NtkAddDummyPoNames( pAig ); // check the resulting network if ( !Abc_NtkCheck( pAig ) ) fprintf( stdout, "Res_WndStrash(): Network check has failed.\n" ); return pAig; } //////////////////////////////////////////////////////////////////////// /// END OF FILE /// //////////////////////////////////////////////////////////////////////// ABC_NAMESPACE_IMPL_END
Kinghsy/490_core
lib/abc/src/opt/res/resStrash.c
C
gpl-3.0
4,297
using SiteServer.CMS.WeiXin.WeiXinMP.CommonAPIs; using SiteServer.CMS.WeiXin.WeiXinMP.Entities.JsonResult; namespace SiteServer.CMS.WeiXin.WeiXinMP.AdvancedAPIs.Groups { /// <summary> /// 用户组接口 /// </summary> public static class Groups { /// <summary> /// 创建分组 /// </summary> /// <returns></returns> public static CreateGroupResult Create(string accessToken, string name) { var urlFormat = "https://api.weixin.qq.com/cgi-bin/groups/create?access_token={0}"; var data = new { group = new { name = name } }; return CommonJsonSend.Send<CreateGroupResult>(accessToken, urlFormat, data); } /// <summary> /// 发送文本信息 /// </summary> /// <param name="accessToken"></param> /// <returns></returns> public static GroupsJson Get(string accessToken) { var url = $"https://api.weixin.qq.com/cgi-bin/groups/get?access_token={accessToken}"; return HttpUtility.Get.GetJson<GroupsJson>(url); } /// <summary> /// 获取用户分组 /// </summary> /// <param name="accessToken"></param> /// <param name="openId"></param> /// <returns></returns> public static GetGroupIdResult GetId(string accessToken, string openId) { var urlFormat = "https://api.weixin.qq.com/cgi-bin/groups/getid?access_token={0}"; var data = new { openid = openId }; return CommonJsonSend.Send<GetGroupIdResult>(accessToken, urlFormat, data); } /// <summary> /// 创建分组 /// </summary> /// <param name="accessToken"></param> /// <param name="id"></param> /// <param name="name">分组名字(30个字符以内)</param> /// <returns></returns> public static WxJsonResult Update(string accessToken, int id, string name) { var urlFormat = "https://api.weixin.qq.com/cgi-bin/groups/update?access_token={0}"; var data = new { group = new { id = id, name = name } }; return CommonJsonSend.Send(accessToken, urlFormat, data); } /// <summary> /// 移动用户分组 /// </summary> /// <param name="accessToken"></param> /// <param name="openId"></param> /// <param name="toGroupId"></param> /// <returns></returns> public static WxJsonResult MemberUpdate(string accessToken, string openId, int toGroupId) { var urlFormat = "https://api.weixin.qq.com/cgi-bin/groups/members/update?access_token={0}"; var data = new { openid = openId, to_groupid = toGroupId }; return CommonJsonSend.Send(accessToken, urlFormat, data); } } }
ColgateKas/cms
source/SiteServer.CMS/WeiXin/WeiXinMP/AdvancedAPIs/Groups/Groups.cs
C#
gpl-3.0
3,125
<?php class ModelShippingkex extends Model { function getQuote($address) { $this->load->language('shipping/kex'); $query = $this->db->query("SELECT * FROM " . DB_PREFIX . "zone_to_geo_zone WHERE geo_zone_id = '" . (int)$this->config->get('kex_geo_zone_id') . "' AND country_id = '" . (int)$address['country_id'] . "' AND (zone_id = '" . (int)$address['zone_id'] . "' OR zone_id = '0')"); if (!$this->config->get('kex_geo_zone_id')) { $status = true; } elseif ($query->num_rows) { $status = true; } else { $status = false; } $method_data = array(); if ($status) { $cost = 0; $weight = $this->cart->getWeight(); $rates = explode(',', $this->config->get('kex_rate')); foreach ($rates as $rate) { $data = explode(':', $rate); if ($data[0] >= $weight) { if (isset($data[1])) { $cost = $data[1]; } break; } } $quote_data = array(); if ((float)$cost) { $quote_data['kex'] = array( 'code' => 'kex.kex', 'title' => $this->language->get('text_title') . ' (' . $this->language->get('text_weight') . ' ' . $this->weight->format($weight, $this->config->get('config_weight_class_id')) . ')', 'cost' => $cost, 'tax_class_id' => $this->config->get('kex_tax_class_id'), 'text' => $this->currency->format($this->tax->calculate($cost, $this->config->get('kex_tax_class_id'), $this->config->get('config_tax'))) ); $method_data = array( 'code' => 'kex', 'title' => $this->language->get('text_title'), 'quote' => $quote_data, 'sort_order' => $this->config->get('kex_sort_order'), 'error' => false ); } } return $method_data; } } ?>ition - status false $status = false; } else { $status = true; break; } } } elseif (strpos($result['description'], '!') !== false) { // If "Geozone Description" has a ! in it, then exclude by keyword $match = 0; $filters = explode(',', str_replace('!', '', $result['description'])); foreach($filters as $filter) { if (stripos($address[$keyword], trim($filter)) === false) { //if the value doesn't match - status true $status = true; } elseif (stripos($address[$keyword], trim($filter)) > 0) { //if the value doesn't match at the first position - status false $status = true; } else { $status = false; break; } } } } }// if ($status) { $inRange = false; $cost = 0; // set the unit of calculation to $value (weight, subtotal, or itemcount) if ($this->config->get($this->name . '_' . $result['geo_zone_id'] . '_method') == 'itemcount'){ $value = 0; foreach ($this->cart->getProducts() as $product) { if ($product['shipping']) { //$value++; $value += $product['quantity']; } } //$value = $this->cart->countProducts(); // this doesn't take into account products with shipping set to NO } elseif ($this->config->get($this->name . '_' . $result['geo_zone_id'] . '_method') == 'subtotal'){ $value = $this->cart->getSubtotal(); } else { // default to weight-based $value = $this->cart->getWeight(); } // set the operator based on whether its incremental or decremental if ($this->config->get($this->name . '_' . $result['geo_zone_id'] . '_calc') == 'dec') { $op = '>='; $sort_method = 'dec'; } else { //default to inc $op = '<='; $sort_method = 'inc'; } $rates = explode(',', $this->config->get($this->name . '_' . $result['geo_zone_id'] . '_cost')); if ($sort_method == 'dec') { rsort($rates, SORT_NUMERIC); } foreach ($rates as $rate) { $array = explode(':', $rate); if (!empty($array) && isset($array[0]) && isset($array[1]) && $array[0] != '' && @(string)$array[1] != '') { if (eval("return($value $op $array[0]);")) { $cost = @$array[1]; if (strpos($cost, '%')) { $cost = trim($cost, '%'); $cost = $this->cart->getSubtotal() * ($cost/100); } $inRange = true; break; } } } if ($inRange == true) { $quote_data[$this->name . '_' . $result['geo_zone_id']] = array( 'id' => $this->name . '.' . $this->name . '_' . $result['geo_zone_id'], //v14x 'code' => $this->name . '.' . $this->name . '_' . $result['geo_zone_id'], //v15x //'code' => 'kurier', 'title' => $this->language->get('text_title'), 'cost' => $cost, 'tax_class_id' => $this->config->get($this->name . '_tax_class_id'), 'text' => $this->currency->format($this->tax->calculate($cost, $this->config->get($this->name . '_tax_class_id'), $this->config->get('config_tax'))) ); } } } $method_data = array(); if ($quote_data) { $method_data = array( 'id' => $this->name, //v14x 'code' => $this->name, //v15x 'title' => $this->language->get('text_title'), 'quote' => $quote_data, 'sort_order' => $this->config->get($this->name . '_sort_order'), 'error' => FALSE ); } return $method_data; } } ?>
miechuliv/dinocars
catalog/model/shipping/KEX.php
PHP
gpl-3.0
5,367
/* =========================================================================== Copyright (c) 2010-2015 Darkstar Dev Teams This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see http://www.gnu.org/licenses/ This file is part of DarkStar-server source code. =========================================================================== */ #include "../common/showmsg.h" #include "../common/timer.h" #include "packets/treasure_find_item.h" #include "packets/treasure_lot_item.h" #include "utils/charutils.h" #include "utils/itemutils.h" #include "treasure_pool.h" #include "recast_container.h" #include "item_container.h" static constexpr duration treasure_checktime = 3s; static constexpr duration treasure_livetime = 5min; /************************************************************************ * * * Инициализация TreasurePool * * * ************************************************************************/ CTreasurePool::CTreasurePool(TREASUREPOOLTYPE PoolType) { m_count = 0; m_TreasurePoolType = PoolType; for (uint8 i = 0; i < TREASUREPOOL_SIZE; ++i) { m_PoolItems[i].ID = 0; m_PoolItems[i].SlotID = i; } members.reserve(PoolType); } /************************************************************************ * * * Узнаем текущий тип контейнера * * * ************************************************************************/ TREASUREPOOLTYPE CTreasurePool::GetPoolType() { return m_TreasurePoolType; } /************************************************************************ * * * * * * ************************************************************************/ void CTreasurePool::AddMember(CCharEntity* PChar) { DSP_DEBUG_BREAK_IF(PChar == nullptr); DSP_DEBUG_BREAK_IF(PChar->PTreasurePool != this); members.push_back(PChar); if (m_TreasurePoolType == TREASUREPOOL_SOLO && members.size() > 1) { m_TreasurePoolType = TREASUREPOOL_PARTY; }else if (m_TreasurePoolType == TREASUREPOOL_PARTY && members.size() > 6) { m_TreasurePoolType = TREASUREPOOL_ALLIANCE; } } /************************************************************************ * * * * * * ************************************************************************/ void CTreasurePool::DelMember(CCharEntity* PChar) { DSP_DEBUG_BREAK_IF(PChar == nullptr); DSP_DEBUG_BREAK_IF(PChar->PTreasurePool != this); //if(m_TreasurePoolType != TREASUREPOOL_ZONE){ //Zone drops e.g. Dynamis DO NOT remove previous lot info. Everything else does. // ^ TODO: verify what happens when a winner leaves zone for( int i=0; i<10; i++){ if(m_PoolItems[i].Lotters.size()>0){ for(int j=0; j<m_PoolItems[i].Lotters.size(); j++){ //remove their lot info if(PChar->id == m_PoolItems[i].Lotters[j].member->id){ m_PoolItems[i].Lotters.erase(m_PoolItems[i].Lotters.begin()+j); } } } } //} for (uint32 i = 0; i < members.size(); ++i) { if (PChar == members.at(i)) { PChar->PTreasurePool = nullptr; members.erase(members.begin()+i); break; } } if ((m_TreasurePoolType == TREASUREPOOL_PARTY || m_TreasurePoolType == TREASUREPOOL_ALLIANCE) && members.size() == 1) m_TreasurePoolType = TREASUREPOOL_SOLO; if (m_TreasurePoolType != TREASUREPOOL_ZONE && members.empty()) { delete this; return; } } /************************************************************************ * * * Добавляем предмет в хранилище * * * ************************************************************************/ uint8 CTreasurePool::AddItem(uint16 ItemID, CBaseEntity* PEntity) { uint8 SlotID; uint8 FreeSlotID = -1; time_point oldest = time_point::min(); switch (ItemID) { case 1126: //beastmen seal case 1127: //kindred seal case 2955: //kindred crest case 2956: //high kindred crest for (uint32 i = 0; i < members.size(); ++i) { members[i]->PRecastContainer->Add(RECAST_LOOT, 1, 300); //300 = 5 min cooldown } break; } for (SlotID = 0; SlotID < 10; ++SlotID) { if (m_PoolItems[SlotID].ID == 0) { FreeSlotID = SlotID; break; } } if (FreeSlotID > TREASUREPOOL_SIZE) { //find the oldest non-rare and non-ex item for (SlotID = 0; SlotID < 10; ++SlotID) { CItem* PItem = itemutils::GetItemPointer(m_PoolItems[SlotID].ID); if (!(PItem->getFlag() & (ITEM_FLAG_RARE | ITEM_FLAG_EX)) && m_PoolItems[SlotID].TimeStamp > oldest) { FreeSlotID = SlotID; oldest = m_PoolItems[SlotID].TimeStamp; } } if (FreeSlotID > TREASUREPOOL_SIZE) { //find the oldest non-ex item for (SlotID = 0; SlotID < 10; ++SlotID) { CItem* PItem = itemutils::GetItemPointer(m_PoolItems[SlotID].ID); if (!(PItem->getFlag() & (ITEM_FLAG_EX)) && m_PoolItems[SlotID].TimeStamp > oldest) { FreeSlotID = SlotID; oldest = m_PoolItems[SlotID].TimeStamp; } } if (FreeSlotID > TREASUREPOOL_SIZE) { //find the oldest item for (SlotID = 0; SlotID < 10; ++SlotID) { if (m_PoolItems[SlotID].TimeStamp > oldest) { FreeSlotID = SlotID; oldest = m_PoolItems[SlotID].TimeStamp; } } if (FreeSlotID > TREASUREPOOL_SIZE) { //default fallback FreeSlotID = 0; } } } } if (SlotID == 10) { m_PoolItems[FreeSlotID].TimeStamp = get_server_start_time(); CheckTreasureItem(server_clock::now(), FreeSlotID); } m_count++; m_PoolItems[FreeSlotID].ID = ItemID; m_PoolItems[FreeSlotID].TimeStamp = server_clock::now() - treasure_checktime; for (uint32 i = 0; i < members.size(); ++i) { members[i]->pushPacket(new CTreasureFindItemPacket(&m_PoolItems[FreeSlotID], PEntity)); } if (m_TreasurePoolType == TREASUREPOOL_SOLO) { CheckTreasureItem(server_clock::now(), FreeSlotID); } return m_count; } /************************************************************************ * * * * * * ************************************************************************/ void CTreasurePool::UpdatePool(CCharEntity* PChar) { DSP_DEBUG_BREAK_IF(PChar == nullptr); DSP_DEBUG_BREAK_IF(PChar->PTreasurePool != this); if (PChar->status != STATUS_DISAPPEAR) { for (uint8 i = 0; i < TREASUREPOOL_SIZE; ++i) { PChar->pushPacket(new CTreasureFindItemPacket(&m_PoolItems[i], nullptr)); } } } /************************************************************************ * * * Персонаж отказывается/голосует за предмет в хранилище * * * ************************************************************************/ void CTreasurePool::LotItem(CCharEntity* PChar, uint8 SlotID, uint16 Lot) { DSP_DEBUG_BREAK_IF(PChar == nullptr); DSP_DEBUG_BREAK_IF(PChar->PTreasurePool != this); if (SlotID >= TREASUREPOOL_SIZE) return; LotInfo li; li.lot = Lot; li.member = PChar; m_PoolItems[SlotID].Lotters.push_back(li); //Player lots Item for XXX message for (uint32 i = 0; i < members.size(); ++i) { members[i]->pushPacket(new CTreasureLotItemPacket(PChar,SlotID,Lot)); } //if all lotters have lotted, evaluate immediately. if(m_PoolItems[SlotID].Lotters.size() == members.size()){ CheckTreasureItem(m_Tick,SlotID); } } void CTreasurePool::PassItem(CCharEntity* PChar, uint8 SlotID) { DSP_DEBUG_BREAK_IF(PChar == nullptr); DSP_DEBUG_BREAK_IF(PChar->PTreasurePool != this); if (SlotID >= TREASUREPOOL_SIZE) return; LotInfo li; li.lot = 0; li.member = PChar; bool hasLottedBefore = false; // if this member has lotted on this item previously, set their lot to 0. for(int i=0; i<m_PoolItems[SlotID].Lotters.size();i++){ if(m_PoolItems[SlotID].Lotters[i].member->id == PChar->id){ m_PoolItems[SlotID].Lotters[i].lot = 0; hasLottedBefore = true; break; } } if(!hasLottedBefore){ m_PoolItems[SlotID].Lotters.push_back(li); } uint16 PassedLot = 65535; // passed mask is FF FF //Player lots Item for XXX message for (uint32 i = 0; i < members.size(); ++i) { members[i]->pushPacket(new CTreasureLotItemPacket(PChar,SlotID,PassedLot)); } //if all lotters have lotted, evaluate immediately. if(m_PoolItems[SlotID].Lotters.size() == members.size()){ CheckTreasureItem(m_Tick,SlotID); } } bool CTreasurePool::HasLottedItem(CCharEntity* PChar, uint8 SlotID) { std::vector<LotInfo> lotters = m_PoolItems[SlotID].Lotters; for(int i=0; i<lotters.size(); i++){ if(lotters[i].member->id == PChar->id){ return true; } } return false; } bool CTreasurePool::HasPassedItem(CCharEntity* PChar, uint8 SlotID) { std::vector<LotInfo> lotters = m_PoolItems[SlotID].Lotters; for(int i=0; i<lotters.size(); i++){ if(lotters[i].member->id == PChar->id){ return lotters[i].lot == 0; } } return false; } /************************************************************************ * * * * * * ************************************************************************/ void CTreasurePool::CheckItems(time_point tick) { if (m_count != 0) { if ((tick - m_Tick > treasure_checktime)) { for (uint8 i = 0; i < TREASUREPOOL_SIZE; ++i) { CheckTreasureItem(tick, i); } m_Tick = tick; } } } /************************************************************************ * * * * * * ************************************************************************/ void CTreasurePool::CheckTreasureItem(time_point tick, uint8 SlotID) { if (m_PoolItems[SlotID].ID == 0) return; if ((tick - m_PoolItems[SlotID].TimeStamp) > treasure_livetime || (m_TreasurePoolType == TREASUREPOOL_SOLO && members[0]->getStorage(LOC_INVENTORY)->GetFreeSlotsCount() != 0) || m_PoolItems[SlotID].Lotters.size() == members.size()) { if (!m_PoolItems[SlotID].Lotters.empty()) { //give item to highest lotter LotInfo highestInfo; highestInfo.lot = 0; highestInfo.member = nullptr; for(uint8 i = 0; i < m_PoolItems[SlotID].Lotters.size(); i++){ LotInfo curInfo = m_PoolItems[SlotID].Lotters[i]; if(curInfo.lot > highestInfo.lot){ highestInfo = curInfo; } } //sanity check if(highestInfo.member != nullptr && highestInfo.lot!=0){ if(highestInfo.member->getStorage(LOC_INVENTORY)->GetFreeSlotsCount() != 0){ //add item as they have room! if (charutils::AddItem(highestInfo.member, LOC_INVENTORY, m_PoolItems[SlotID].ID, 1, true) != ERROR_SLOTID) { TreasureWon(highestInfo.member, SlotID); } else { TreasureError(highestInfo.member, SlotID); } } else{ //drop the item TreasureLost(SlotID); } } else{ //no one has lotted on this item, give to random member who hasnt passed // std::vector<LotInfo> tempLots; for (uint8 i = 0; i < members.size(); ++i) { bool hasPassed = false; for(uint8 j = 0; j < m_PoolItems[SlotID].Lotters.size(); j++){ if(m_PoolItems[SlotID].Lotters[j].member->id == members[i]->id){ hasPassed = true; break; } } if (charutils::HasItem(members[i], m_PoolItems[SlotID].ID) && itemutils::GetItem(m_PoolItems[SlotID].ID)->getFlag() & ITEM_FLAG_RARE) continue; if (members[i]->getStorage(LOC_INVENTORY)->GetFreeSlotsCount() != 0 && !hasPassed) { LotInfo templi; templi.member = members[i]; templi.lot = 1; tempLots.push_back(templi); } } if(tempLots.size()==0){ TreasureLost(SlotID); } else{ //select random member from this pool to give item to CCharEntity* PChar = tempLots.at(dsprand::GetRandomNumber(tempLots.size())).member; if (charutils::AddItem(PChar, LOC_INVENTORY, m_PoolItems[SlotID].ID, 1, true) != ERROR_SLOTID) { TreasureWon(PChar, SlotID); } else { TreasureError(PChar, SlotID); } tempLots.clear(); return; } } } else { for (uint8 i = 0; i < members.size(); ++i) { if (members[i]->getStorage(LOC_INVENTORY)->GetFreeSlotsCount() != 0) { LotInfo lot = { 0, members[i] }; m_PoolItems[SlotID].Lotters.push_back(lot); } } if (!m_PoolItems[SlotID].Lotters.empty()) { CCharEntity* PChar = m_PoolItems[SlotID].Lotters.at(dsprand::GetRandomNumber(m_PoolItems[SlotID].Lotters.size())).member; if (charutils::AddItem(PChar, LOC_INVENTORY, m_PoolItems[SlotID].ID, 1, true) != ERROR_SLOTID) { TreasureWon(PChar, SlotID); } else { TreasureError(PChar, SlotID); } return; } TreasureLost(SlotID); } } } /************************************************************************ * * * * * * ************************************************************************/ void CTreasurePool::TreasureWon(CCharEntity* winner, uint8 SlotID) { DSP_DEBUG_BREAK_IF(winner == nullptr); DSP_DEBUG_BREAK_IF(winner->PTreasurePool != this); DSP_DEBUG_BREAK_IF(m_PoolItems[SlotID].ID == 0); m_PoolItems[SlotID].TimeStamp = get_server_start_time(); for (uint32 i = 0; i < members.size(); ++i) { members[i]->pushPacket(new CTreasureLotItemPacket(winner, SlotID, 0, ITEMLOT_WIN)); } m_count--; m_PoolItems[SlotID].ID = 0; m_PoolItems[SlotID].Lotters.clear(); } /************************************************************************ * * * * * * ************************************************************************/ void CTreasurePool::TreasureError(CCharEntity* winner, uint8 SlotID) { DSP_DEBUG_BREAK_IF(winner == nullptr); DSP_DEBUG_BREAK_IF(winner->PTreasurePool != this); DSP_DEBUG_BREAK_IF(m_PoolItems[SlotID].ID == 0); m_PoolItems[SlotID].TimeStamp = get_server_start_time(); for (uint32 i = 0; i < members.size(); ++i) { members[i]->pushPacket(new CTreasureLotItemPacket(winner, SlotID, -1, ITEMLOT_WINERROR)); } m_count--; m_PoolItems[SlotID].ID = 0; m_PoolItems[SlotID].Lotters.clear(); } /************************************************************************ * * * * * * ************************************************************************/ void CTreasurePool::TreasureLost(uint8 SlotID) { DSP_DEBUG_BREAK_IF(m_PoolItems[SlotID].ID == 0); m_PoolItems[SlotID].TimeStamp = get_server_start_time(); for (uint32 i = 0; i < members.size(); ++i) { members[i]->pushPacket(new CTreasureLotItemPacket(SlotID, ITEMLOT_WINERROR)); } m_count--; m_PoolItems[SlotID].ID = 0; m_PoolItems[SlotID].Lotters.clear(); } /************************************************************************ * * * * * * ************************************************************************/ bool CTreasurePool::CanAddSeal() { for (uint32 i = 0; i < members.size(); ++i) if (members[i]->PRecastContainer->Has(RECAST_LOOT, 1)) return false; return true; }
AdamGagorik/darkstar
src/map/treasure_pool.cpp
C++
gpl-3.0
18,412
function uriescape { escaped=`echo "$1" | sed 's/ /%20/g; s/\*/\\*/g; s/{/\\\{/g; s/}/\\\}/g; s/\?/%3f/g; s/&/%38/g; s/+/%2b/g; s/"/\\"/g; s/\[/\\\[/g; s/\]/\\\]/g'` } function postescape { escaped=`echo "$1" | sed 's/ /%20/g; s/\*/\\*/g; s/\?/%3f/g; s/&/%38/g; s/+/%2b/g;'` } # usage: sparql $endpoint $query function sparql { uriescape "$2"; echo "Query: $2" echo curl -s -H "Accept: text/plain" "$1/sparql/?query=$escaped" curl -s -H "Accept: text/plain" "$1/sparql/?query=$escaped" } # usage: update $endpoint $update function update { postescape "$2" echo "Update: $2" curl -s -d "update=$escaped" "$1/update/" } # usage: put $endpoint $file $mime-type $model function put { uriescape $4; curl -s -T "$2" -H "Content-Type: $3" "$1/data/?graph=$escaped" | sed 's/ v[.0-9a-z-]*/ [VERSION]/' } # usage: put-old $endpoint $file $mime-type $model function put-old { uriescape $4; curl -s -T "$2" -H "Content-Type: $3" "$1/data/$escaped" | sed 's/ v[.0-9a-z-]*/ [VERSION]/' } # usage: post $endpoint $data $mime-type $model function post { uriescape "$3"; emime=$escaped uriescape "$4"; egraph=$escaped; uriescape "$2" curl -s -H 'Accept: text/plain' -d "mime-type=$emime" -d "graph=$egraph" -d "data=$escaped" "$1/data/" | sed 's/ v[.0-9a-z-]*/ [VERSION]/' } # usage: delete $endpoint $model function delete { uriescape $2; curl -s -X 'DELETE' $1/data/?graph=$escaped | sed 's/ v[.0-9a-z-]*/ [VERSION]/' } # usage: delete-old $endpoint $model function delete-old { uriescape $2; curl -s -X 'DELETE' $1/data/$escaped | sed 's/ v[.0-9a-z-]*/ [VERSION]/' }
szarnyasg/4store
tests/load/sparql.sh
Shell
gpl-3.0
1,606
/* ______ ___ ___ * /\ _ \ /\_ \ /\_ \ * \ \ \L\ \\//\ \ \//\ \ __ __ _ __ ___ * \ \ __ \ \ \ \ \ \ \ /'__`\ /'_ `\/\`'__\/ __`\ * \ \ \/\ \ \_\ \_ \_\ \_/\ __//\ \L\ \ \ \//\ \L\ \ * \ \_\ \_\/\____\/\____\ \____\ \____ \ \_\\ \____/ * \/_/\/_/\/____/\/____/\/____/\/___L\ \/_/ \/___/ * /\____/ * \_/__/ * * Bitmap stretching functions for the i386. * * By Shawn Hargreaves. * * See readme.txt for copyright information. */ #include <stdlib.h> #include <stdio.h> #include <stddef.h> #include <string.h> #include <limits.h> #include "allegro.h" #include "allegro/internal/aintern.h" #include "opcodes.h" #ifdef ALLEGRO_UNIX #include "allegro/platform/aintunix.h" /* for _unix_get_page_size */ #endif #ifdef ALLEGRO_WINDOWS #include "winalleg.h" /* For VirtualProtect */ #endif /* ifdef ALLEGRO_WINDOWS */ #ifdef ALLEGRO_HAVE_MPROTECT #include <sys/types.h> #include <sys/mman.h> #endif /* ifdef ALLEGRO_HAVE_MPROTECT */ /* helper macro for generating stretchers in each color depth */ #define DECLARE_STRETCHER(sz, mask, scale) \ { \ int x, x2; \ int c; \ \ if (sxd == itofix(1)) { /* easy case for 1 -> 1 scaling */ \ if (masked) { \ for (c=0; c<dest_width; c++) { \ COMPILER_LODS##sz(); \ COMPILER_MASKED_STOS##sz(mask); \ } \ } \ else { \ COMPILER_MOV_ECX(dest_width); \ COMPILER_REP_MOVS##sz(); \ } \ } \ else if (sxd > itofix(1)) { /* big -> little scaling */ \ for (x=0; x<dest_width; x++) { \ COMPILER_LODS##sz(); \ if (masked) { \ COMPILER_MASKED_STOS##sz(mask); \ } \ else { \ COMPILER_STOS##sz(); \ } \ x2 = (sx >> 16) + 1; \ sx += sxd; \ x2 = (sx >> 16) - x2; \ if (x2*scale > 1) { \ COMPILER_ADD_ESI(x2*scale); \ } \ else if (x2*scale == 1) { \ COMPILER_INC_ESI(); \ } \ } \ } \ else { /* little -> big scaling */ \ x2 = sx >> 16; \ COMPILER_LODS##sz(); \ for (x=0; x<dest_width; x++) { \ if (masked) { \ COMPILER_MASKED_STOS##sz(mask); \ } \ else { \ COMPILER_STOS##sz(); \ } \ sx += sxd; \ if ((sx >> 16) > x2) { \ COMPILER_LODS##sz(); \ x2++; \ } \ } \ } \ } /* make_stretcher_256: * Helper for constructing a 256 color stretcher routine. */ static int make_stretcher_256(int compiler_pos, fixed sx, fixed sxd, int dest_width, int masked) { #ifdef ALLEGRO_COLOR8 DECLARE_STRETCHER(B, mask, 1); #endif return compiler_pos; } /* make_stretcher_15: * Helper for constructing a 15 bit stretcher routine. */ static int make_stretcher_15(int compiler_pos, fixed sx, fixed sxd, int dest_width, int masked) { #ifdef ALLEGRO_COLOR16 DECLARE_STRETCHER(W, MASK_COLOR_15, 2); #endif return compiler_pos; } /* make_stretcher_16: * Helper for constructing a 16 bit stretcher routine. */ static int make_stretcher_16(int compiler_pos, fixed sx, fixed sxd, int dest_width, int masked) { #ifdef ALLEGRO_COLOR16 DECLARE_STRETCHER(W, MASK_COLOR_16, 2); #endif return compiler_pos; } /* make_stretcher_24: * Helper for constructing a 24 bit stretcher routine. */ static int make_stretcher_24(int compiler_pos, fixed sx, fixed sxd, int dest_width, int masked) { #ifdef ALLEGRO_COLOR24 DECLARE_STRETCHER(L2, MASK_COLOR_24, 3); #endif return compiler_pos; } /* make_stretcher_32: * Helper for constructing a 32 bit stretcher routine. */ static int make_stretcher_32(int compiler_pos, fixed sx, fixed sxd, int dest_width, int masked) { #ifdef ALLEGRO_COLOR32 DECLARE_STRETCHER(L, MASK_COLOR_32, 4); #endif return compiler_pos; } /* make_stretcher: * Helper function for stretch_blit(). Builds a machine code stretching * routine in the scratch memory area. */ static int make_stretcher(int compiler_pos, fixed sx, fixed sxd, int dest_width, int masked, int color_depth) { if (dest_width > 0) { switch (color_depth) { case 8: return make_stretcher_256(compiler_pos, sx, sxd, dest_width, masked); case 15: return make_stretcher_15(compiler_pos, sx, sxd, dest_width, masked); case 16: return make_stretcher_16(compiler_pos, sx, sxd, dest_width, masked); case 24: return make_stretcher_24(compiler_pos, sx, sxd, dest_width, masked); case 32: return make_stretcher_32(compiler_pos, sx, sxd, dest_width, masked); } } return compiler_pos; } /* cache of previously constructed stretcher functions */ typedef struct STRETCHER_INFO { fixed sx; fixed sxd; short dest_width; char depth; char flags; int lru; void *exec; /* xr_ mapping in the mmap case, normally both in one. */ int size; #ifdef ALLEGRO_USE_MMAP_GEN_CODE_BUF void *rw; /* _rw mapping for the mmap case. */ int fd; /* mapping backing fd for the mmap case. */ #endif } STRETCHER_INFO; #define NUM_STRETCHERS 8 static STRETCHER_INFO stretcher_info[NUM_STRETCHERS]; static int stretcher_count = 0; static int stretcher_virgin = TRUE; /* free_stretchers: * Clean up atexit. */ static void free_stretchers(void) { int i; for (i=0; i<NUM_STRETCHERS; i++) if (stretcher_info[i].exec != NULL) { #ifdef ALLEGRO_USE_MMAP_GEN_CODE_BUF munmap(stretcher_info[i].exec, stretcher_info[i].size); munmap(stretcher_info[i].rw, stretcher_info[i].size); close(stretcher_info[i].fd); #else _AL_FREE(stretcher_info[i].exec); #endif } _remove_exit_func(free_stretchers); stretcher_virgin = TRUE; } /* do_stretch_blit: * Like blit(), except it can scale images so the source and destination * rectangles don't need to be the same size. This routine doesn't do as * much safety checking as the regular blit: in particular you must take * care not to copy from areas outside the source bitmap, and you cannot * blit between overlapping regions, ie. you must use different bitmaps for * the source and the destination. This function can draw onto both linear * and mode-X bitmaps. * * This routine does some very dodgy stuff. It dynamically generates a * chunk of machine code to scale a line of the bitmap, and then calls this. * I just _had_ to use self modifying code _somewhere_ in Allegro :-) */ static void do_stretch_blit(BITMAP *source, BITMAP *dest, int source_x, int source_y, int source_width, int source_height, int dest_x, int dest_y, int dest_width, int dest_height, int masked) { #ifdef ALLEGRO_WINDOWS DWORD old_protect; #endif /* ifdef ALLEGRO_WINDOWS */ #ifndef ALLEGRO_USE_MMAP_GEN_CODE_BUF void *prev_scratch_mem; int prev_scratch_mem_size; #endif fixed sx, sy, sxd, syd; int compiler_pos = 0; int best, best_lru; char flags; int i; /* vtable hook; not called if dest is a memory surface */ if (source->vtable->do_stretch_blit && !is_memory_bitmap(dest)) { source->vtable->do_stretch_blit(source, dest, source_x, source_y, source_width, source_height, dest_x, dest_y, dest_width, dest_height, masked); return; } /* trivial reject for zero sizes */ if ((source_width <= 0) || (source_height <= 0) || (dest_width <= 0) || (dest_height <= 0)) return; /* make sure all allocated memory is freed atexit */ if (stretcher_virgin) { stretcher_virgin = FALSE; memset(stretcher_info, 0, sizeof(stretcher_info)); _add_exit_func(free_stretchers, "free_stretchers"); } /* convert to fixed point */ sx = itofix(source_x); sy = itofix(source_y); /* calculate delta values */ sxd = itofix(source_width) / dest_width; syd = itofix(source_height) / dest_height; /* clip? */ if (dest->clip) { while (dest_x < dest->cl) { dest_x++; dest_width--; sx += sxd; } while (dest_y < dest->ct) { dest_y++; dest_height--; sy += syd; } if (dest_x+dest_width > dest->cr) dest_width = dest->cr - dest_x; if (dest_y+dest_height > dest->cb) dest_height = dest->cb - dest_y; if ((dest_width <= 0) || (dest_height <= 0)) return; } /* compensate for a problem where the first column or row can get * an extra pixel than it should do for little -> big scaling, due * to fixed point number representation imprecisions */ if (sxd < itofix(1)) sx += (sxd >> 1); if (syd < itofix(1)) sy += (syd >> 1); /* search the cache */ stretcher_count++; if (stretcher_count <= 0) { stretcher_count = 1; for (i=0; i<NUM_STRETCHERS; i++) stretcher_info[i].lru = 0; } if (is_linear_bitmap(dest)) flags = masked; else flags = masked | 2 | ((dest_x&3)<<2); best = 0; best_lru = INT_MAX; for (i=0; i<NUM_STRETCHERS; i++) { if ((stretcher_info[i].sx == sx) && (stretcher_info[i].sxd == sxd) && (stretcher_info[i].dest_width == dest_width) && (stretcher_info[i].depth == dest->vtable->color_depth) && (stretcher_info[i].flags == flags)) { /* use a previously generated routine */ if (stretcher_info[i].flags & 2) dest_x >>= 2; _do_stretch(source, dest, stretcher_info[i].exec, sx>>16, sy, syd, dest_x, dest_y, dest_height, dest->vtable->color_depth); stretcher_info[i].lru = stretcher_count; return; } else { /* decide which cached routine to discard */ if (stretcher_info[i].lru < best_lru) { best = i; best_lru = stretcher_info[i].lru; } } } #ifdef ALLEGRO_USE_MMAP_GEN_CODE_BUF _exec_map = stretcher_info[best].exec; _rw_map = stretcher_info[best].rw; _map_size = stretcher_info[best].size; _map_fd = stretcher_info[best].fd; #else prev_scratch_mem = _scratch_mem; prev_scratch_mem_size = _scratch_mem_size; _scratch_mem = stretcher_info[best].exec; _scratch_mem_size = stretcher_info[best].size; #endif if (is_linear_bitmap(dest)) { /* build a simple linear stretcher */ compiler_pos = make_stretcher(0, sx, sxd, dest_width, masked, dest->vtable->color_depth); } #ifdef ALLEGRO_GFX_HAS_VGA else { int plane, d; /* build four stretchers, one for each mode-X plane */ for (plane=0; plane<4; plane++) { COMPILER_PUSH_ESI(); COMPILER_PUSH_EDI(); COMPILER_MOV_EAX((0x100<<((dest_x+plane)&3))|2); COMPILER_MOV_EDX(0x3C4); COMPILER_OUTW(); compiler_pos = make_stretcher(compiler_pos, sx+sxd*plane, sxd<<2, (dest_width-plane+3)>>2, masked, 8); COMPILER_POP_EDI(); COMPILER_POP_ESI(); if (((dest_x+plane) & 3) == 3) { COMPILER_INC_EDI(); } d = ((sx+sxd*(plane+1))>>16) - ((sx+sxd*plane)>>16); if (d > 0) { COMPILER_ADD_ESI(d); } } dest_x >>= 2; } #endif /* ifdef ALLEGRO_GFX_HAS_VGA */ COMPILER_RET(); /* Play nice with executable memory protection: VirtualProtect on Windows, * mprotect on UNIX based systems. */ #ifdef ALLEGRO_WINDOWS VirtualProtect(_scratch_mem, _scratch_mem_size, PAGE_EXECUTE_READWRITE, &old_protect); #elif defined(ALLEGRO_HAVE_MPROTECT) && !defined(ALLEGRO_USE_MMAP_GEN_CODE_BUF) { char *p = (char *)((uintptr_t)_scratch_mem & ~(_unix_get_page_size() - 1ul)); if (mprotect(p, _scratch_mem_size + ((char *)_scratch_mem - p), PROT_EXEC|PROT_READ|PROT_WRITE)) perror("allegro-error: mprotect failed during stretched blit!"); } #endif /* store it in the cache */ stretcher_info[best].sx = sx; stretcher_info[best].sxd = sxd; stretcher_info[best].dest_width = dest_width; stretcher_info[best].depth = dest->vtable->color_depth; stretcher_info[best].flags = flags; stretcher_info[best].lru = stretcher_count; #ifdef ALLEGRO_USE_MMAP_GEN_CODE_BUF stretcher_info[best].exec = _exec_map; stretcher_info[best].rw = _rw_map; stretcher_info[best].size = _map_size; stretcher_info[best].fd = _map_fd; #else stretcher_info[best].exec = _scratch_mem; stretcher_info[best].size = _scratch_mem_size; _scratch_mem = prev_scratch_mem; _scratch_mem_size = prev_scratch_mem_size; #endif /* and call the stretcher */ _do_stretch(source, dest, stretcher_info[best].exec, sx>>16, sy, syd, dest_x, dest_y, dest_height, dest->vtable->color_depth); } /* stretch_blit: * Opaque bitmap scaling function. */ void stretch_blit(BITMAP *s, BITMAP *d, int s_x, int s_y, int s_w, int s_h, int d_x, int d_y, int d_w, int d_h) { do_stretch_blit(s, d, s_x, s_y, s_w, s_h, d_x, d_y, d_w, d_h, 0); } /* masked_stretch_blit: * Masked bitmap scaling function. */ void masked_stretch_blit(BITMAP *s, BITMAP *d, int s_x, int s_y, int s_w, int s_h, int d_x, int d_y, int d_w, int d_h) { do_stretch_blit(s, d, s_x, s_y, s_w, s_h, d_x, d_y, d_w, d_h, 1); } /* stretch_sprite: * Masked version of stretch_blit(). */ void stretch_sprite(BITMAP *bmp, BITMAP *sprite, int x, int y, int w, int h) { do_stretch_blit(sprite, bmp, 0, 0, sprite->w, sprite->h, x, y, w, h, 1); }
gwx/ZeldaClassic
allegro/src/i386/istretch.c
C
gpl-3.0
15,930
<?xml version="1.0" encoding="UTF-8" standalone="no"?> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8" /> <title>Deleting Entity Objects</title> <link rel="stylesheet" href="gettingStarted.css" type="text/css" /> <meta name="generator" content="DocBook XSL Stylesheets V1.73.2" /> <link rel="start" href="index.html" title="Getting Started with Berkeley DB" /> <link rel="up" href="persist_access.html" title="Chapter 5. Saving and Retrieving Objects" /> <link rel="prev" href="dpl_entityjoin.html" title="Join Cursors" /> <link rel="next" href="dpl_replace.html" title="Replacing Entity Objects" /> </head> <body> <div xmlns="" class="navheader"> <div class="libver"> <p>Library Version 12.1.6.1</p> </div> <table width="100%" summary="Navigation header"> <tr> <th colspan="3" align="center">Deleting Entity Objects</th> </tr> <tr> <td width="20%" align="left"><a accesskey="p" href="dpl_entityjoin.html">Prev</a> </td> <th width="60%" align="center">Chapter 5. Saving and Retrieving Objects</th> <td width="20%" align="right"> <a accesskey="n" href="dpl_replace.html">Next</a></td> </tr> </table> <hr /> </div> <div class="sect1" lang="en" xml:lang="en"> <div class="titlepage"> <div> <div> <h2 class="title" style="clear: both"><a id="dpl_delete"></a>Deleting Entity Objects</h2> </div> </div> </div> <p> The simplest way to remove an object from your entity store is to delete it by its primary index. For example, using the <code class="classname">SimpleDA</code> class that we created earlier in this document (see <a class="xref" href="simpleda.html" title="SimpleDA.class">SimpleDA.class</a>), you can delete the <code class="classname">SimpleEntityClass</code> object with a primary key of <code class="literal">keyone</code> as follows: </p> <pre class="programlisting">sda.pIdx.delete("keyone");</pre> <p> You can also delete objects by their secondary keys. When you do this, all objects related to the secondary key are deleted, unless the key is a foreign object. </p> <p> For example, the following deletes all <code class="classname">SimpleEntityClass</code> with a secondary key of <code class="literal">skeyone</code>: </p> <pre class="programlisting">sda.sIdx.delete("skeyone");</pre> <p> You can delete any single object by positioning a cursor to that object and then calling the cursor's <code class="methodname">delete()</code> method. </p> <pre class="programlisting">PrimaryIndex&lt;String,SimpleEntityClass&gt; pi = store.getPrimaryIndex(String.class, SimpleEntityClass.class); SecondaryIndex&lt;String,String,SimpleEntityClass&gt; si = store.getSecondaryIndex(pi, String.class, "sKey"); EntityCursor&lt;SimpleEntityClass&gt; sec_cursor = si.subIndex("skeyone").entities(); try { SimpleEntityClass sec; Iterator&lt;SimpleEntityClass&gt; i = sec_cursor.iterator(); while (sec = i.nextDup() != null) { if (sec.getSKey() == "some value") { i.delete(); } } // Always make sure the cursor is closed when we are done with it. } finally { sec_cursor.close(); } </pre> <p> Finally, if you are indexing by foreign key, then the results of deleting the key is determined by the foreign key constraint that you have set for the index. See <a class="xref" href="dplindexcreate.html#foreignkey" title="Foreign Key Constraints">Foreign Key Constraints</a> for more information. </p> </div> <div class="navfooter"> <hr /> <table width="100%" summary="Navigation footer"> <tr> <td width="40%" align="left"><a accesskey="p" href="dpl_entityjoin.html">Prev</a> </td> <td width="20%" align="center"> <a accesskey="u" href="persist_access.html">Up</a> </td> <td width="40%" align="right"> <a accesskey="n" href="dpl_replace.html">Next</a></td> </tr> <tr> <td width="40%" align="left" valign="top">Join Cursors </td> <td width="20%" align="center"> <a accesskey="h" href="index.html">Home</a> </td> <td width="40%" align="right" valign="top"> Replacing Entity Objects</td> </tr> </table> </div> </body> </html>
apavlo/h-store
third_party/cpp/berkeleydb/docs/gsg/JAVA/dpl_delete.html
HTML
gpl-3.0
5,028
#region Copyright & License Information /* * Copyright 2007-2015 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. For more information, * see COPYING. */ #endregion using System.Collections.Generic; using System.Drawing; using System.Linq; using OpenRA.Effects; using OpenRA.Graphics; using OpenRA.Orders; using OpenRA.Primitives; using OpenRA.Traits; namespace OpenRA.Widgets { public class WorldInteractionControllerWidget : Widget { protected readonly World World; readonly WorldRenderer worldRenderer; int2? dragStart, dragEnd; int2 lastMousePosition; [ObjectCreator.UseCtor] public WorldInteractionControllerWidget(World world, WorldRenderer worldRenderer) { this.World = world; this.worldRenderer = worldRenderer; } public override void Draw() { if (!IsDragging) { // Render actors under the mouse pointer foreach (var u in SelectActorsInBoxWithDeadzone(World, lastMousePosition, lastMousePosition)) worldRenderer.DrawRollover(u); return; } // Render actors in the dragbox var selbox = SelectionBox; Game.Renderer.WorldLineRenderer.DrawRect(selbox.Value.First.ToFloat2(), selbox.Value.Second.ToFloat2(), Color.White); foreach (var u in SelectActorsInBoxWithDeadzone(World, selbox.Value.First, selbox.Value.Second)) worldRenderer.DrawRollover(u); } public override bool HandleMouseInput(MouseInput mi) { var xy = worldRenderer.Viewport.ViewToWorldPx(mi.Location); var useClassicMouseStyle = Game.Settings.Game.UseClassicMouseStyle; var hasBox = SelectionBox != null; var multiClick = mi.MultiTapCount >= 2; if (mi.Button == MouseButton.Left && mi.Event == MouseInputEvent.Down) { if (!TakeMouseFocus(mi)) return false; dragStart = xy; // Place buildings, use support powers, and other non-unit things if (!(World.OrderGenerator is UnitOrderGenerator)) { ApplyOrders(World, mi); dragStart = dragEnd = null; YieldMouseFocus(mi); lastMousePosition = xy; return true; } } if (mi.Button == MouseButton.Left && mi.Event == MouseInputEvent.Move && dragStart.HasValue) dragEnd = xy; if (mi.Button == MouseButton.Left && mi.Event == MouseInputEvent.Up) { if (World.OrderGenerator is UnitOrderGenerator) { if (useClassicMouseStyle && HasMouseFocus) { if (!hasBox && World.Selection.Actors.Any() && !multiClick) { if (!(World.ScreenMap.ActorsAt(xy).Where(x => x.HasTrait<Selectable>() && (x.Owner.IsAlliedWith(World.RenderPlayer) || !World.FogObscures(x))).Any() && !mi.Modifiers.HasModifier(Modifiers.Ctrl) && !mi.Modifiers.HasModifier(Modifiers.Alt) && UnitOrderGenerator.InputOverridesSelection(World, xy, mi))) { // Order units instead of selecting ApplyOrders(World, mi); dragStart = dragEnd = null; YieldMouseFocus(mi); lastMousePosition = xy; return true; } } } if (multiClick) { var unit = World.ScreenMap.ActorsAt(xy) .WithHighestSelectionPriority(); if (unit != null && unit.Owner == (World.RenderPlayer ?? World.LocalPlayer)) { var s = unit.TraitOrDefault<Selectable>(); if (s != null) { // Select actors on the screen that have the same selection class as the actor under the mouse cursor var newSelection = SelectActorsOnScreen(World, worldRenderer, new HashSet<string> { s.Class }, unit.Owner); World.Selection.Combine(World, newSelection, true, false); } } } else if (dragStart.HasValue) { // Select actors in the dragbox var newSelection = SelectActorsInBoxWithDeadzone(World, dragStart.Value, xy); World.Selection.Combine(World, newSelection, mi.Modifiers.HasModifier(Modifiers.Shift), dragStart == xy); } } dragStart = dragEnd = null; YieldMouseFocus(mi); } if (mi.Button == MouseButton.Right && mi.Event == MouseInputEvent.Down) { // Don't do anything while selecting if (!hasBox) { if (useClassicMouseStyle) World.Selection.Clear(); ApplyOrders(World, mi); } } lastMousePosition = xy; return true; } bool IsDragging { get { return dragStart.HasValue && dragEnd.HasValue && (dragStart.Value - dragEnd.Value).Length > Game.Settings.Game.SelectionDeadzone; } } public Pair<int2, int2>? SelectionBox { get { if (!IsDragging) return null; return Pair.New(dragStart.Value, dragEnd.Value); } } void ApplyOrders(World world, MouseInput mi) { if (world.OrderGenerator == null) return; var cell = worldRenderer.Viewport.ViewToWorld(mi.Location); var orders = world.OrderGenerator.Order(world, cell, mi).ToArray(); world.PlayVoiceForOrders(orders); var flashed = false; foreach (var order in orders) { var o = order; if (o == null) continue; if (!flashed && !o.SuppressVisualFeedback) { if (o.TargetActor != null) { world.AddFrameEndTask(w => w.Add(new FlashTarget(o.TargetActor))); flashed = true; } else if (o.TargetLocation != CPos.Zero) { var pos = world.Map.CenterOfCell(cell); world.AddFrameEndTask(w => w.Add(new SpriteEffect(pos, world, "moveflsh", "moveflash"))); flashed = true; } } world.IssueOrder(o); } } public override string GetCursor(int2 screenPos) { return Sync.CheckSyncUnchanged(World, () => { // Always show an arrow while selecting if (SelectionBox != null) return null; var cell = worldRenderer.Viewport.ViewToWorld(screenPos); var mi = new MouseInput { Location = screenPos, Button = Game.Settings.Game.MouseButtonPreference.Action, Modifiers = Game.GetModifierKeys() }; return World.OrderGenerator.GetCursor(World, cell, mi); }); } public override bool HandleKeyPress(KeyInput e) { var player = World.RenderPlayer ?? World.LocalPlayer; if (e.Event == KeyInputEvent.Down) { var key = Hotkey.FromKeyInput(e); if (key == Game.Settings.Keys.PauseKey && World.LocalPlayer != null) // Disable pausing for spectators World.SetPauseState(!World.Paused); else if (key == Game.Settings.Keys.SelectAllUnitsKey) { // Select actors on the screen which belong to the current player var ownUnitsOnScreen = SelectActorsOnScreen(World, worldRenderer, null, player).SubsetWithHighestSelectionPriority(); World.Selection.Combine(World, ownUnitsOnScreen, false, false); } else if (key == Game.Settings.Keys.SelectUnitsByTypeKey) { // Get all the selected actors' selection classes var selectedClasses = World.Selection.Actors .Where(x => x.Owner == player) .Select(a => a.Trait<Selectable>().Class) .ToHashSet(); // Select actors on the screen that have the same selection class as one of the already selected actors var newSelection = SelectActorsOnScreen(World, worldRenderer, selectedClasses, player).ToList(); // Check if selecting actors on the screen has selected new units if (newSelection.Count() > World.Selection.Actors.Count()) Game.Debug("Selected across screen"); else { // Select actors in the world that have the same selection class as one of the already selected actors newSelection = SelectActorsInWorld(World, selectedClasses, player).ToList(); Game.Debug("Selected across map"); } World.Selection.Combine(World, newSelection, true, false); } else if (key == Game.Settings.Keys.ToggleStatusBarsKey) return ToggleStatusBars(); else if (key == Game.Settings.Keys.TogglePixelDoubleKey) return TogglePixelDouble(); } return false; } static IEnumerable<Actor> SelectActorsOnScreen(World world, WorldRenderer wr, IEnumerable<string> selectionClasses, Player player) { return SelectActorsByOwnerAndSelectionClass(world.ScreenMap.ActorsInBox(wr.Viewport.TopLeft, wr.Viewport.BottomRight), player, selectionClasses); } static IEnumerable<Actor> SelectActorsInWorld(World world, IEnumerable<string> selectionClasses, Player player) { return SelectActorsByOwnerAndSelectionClass(world.ActorMap.ActorsInWorld(), player, selectionClasses); } static IEnumerable<Actor> SelectActorsByOwnerAndSelectionClass(IEnumerable<Actor> actors, Player owner, IEnumerable<string> selectionClasses) { return actors.Where(a => { if (a.Owner != owner) return false; var s = a.TraitOrDefault<Selectable>(); // selectionClasses == null means that units, that meet all other criteria, get selected return s != null && (selectionClasses == null || selectionClasses.Contains(s.Class)); }); } static IEnumerable<Actor> SelectActorsInBoxWithDeadzone(World world, int2 a, int2 b) { // For dragboxes that are too small, shrink the dragbox to a single point (point b) if ((a - b).Length <= Game.Settings.Game.SelectionDeadzone) a = b; return world.ScreenMap.ActorsInBox(a, b) .Where(x => x.HasTrait<Selectable>() && (x.Owner.IsAlliedWith(world.RenderPlayer) || !world.FogObscures(x))) .SubsetWithHighestSelectionPriority(); } bool ToggleStatusBars() { Game.Settings.Game.AlwaysShowStatusBars ^= true; return true; } bool TogglePixelDouble() { Game.Settings.Graphics.PixelDouble ^= true; worldRenderer.Viewport.Zoom = Game.Settings.Graphics.PixelDouble ? 2 : 1; return true; } } }
DrMelon/OpenRA
OpenRA.Game/Widgets/WorldInteractionControllerWidget.cs
C#
gpl-3.0
9,697
// Copyright 2015 The Cockroach Authors. // // 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. See the AUTHORS file // for names of contributors. // // Author: Spencer Kimball (spencer.kimball@gmail.com) package storage import ( "math" "testing" "github.com/cockroachdb/cockroach/config" "github.com/cockroachdb/cockroach/gossip" "github.com/cockroachdb/cockroach/proto" "github.com/cockroachdb/cockroach/storage/engine" "github.com/cockroachdb/cockroach/util/leaktest" gogoproto "github.com/gogo/protobuf/proto" ) var config1, config2 gogoproto.Message // TestSplitQueueShouldQueue verifies shouldQueue method correctly // combines splits in accounting and zone configs with the size of // the range. func TestSplitQueueShouldQueue(t *testing.T) { defer leaktest.AfterTest(t) tc := testContext{} tc.Start(t) defer tc.Stop() // Set accounting and zone configs. acctMap, err := config.NewPrefixConfigMap([]*config.PrefixConfig{ {proto.KeyMin, nil, config1}, {proto.Key("/dbA"), nil, config2}, }) if err != nil { t.Fatal(err) } if err := tc.gossip.AddInfo(gossip.KeyConfigAccounting, acctMap, 0); err != nil { t.Fatal(err) } zoneMap, err := config.NewPrefixConfigMap([]*config.PrefixConfig{ {proto.KeyMin, nil, &config.ZoneConfig{RangeMaxBytes: 64 << 20}}, {proto.Key("/dbB"), nil, &config.ZoneConfig{RangeMaxBytes: 64 << 20}}, }) if err != nil { t.Fatal(err) } if err := tc.gossip.AddInfo(gossip.KeyConfigZone, zoneMap, 0); err != nil { t.Fatal(err) } testCases := []struct { start, end proto.Key bytes int64 shouldQ bool priority float64 }{ // No intersection, no bytes. {proto.KeyMin, proto.Key("/"), 0, false, 0}, // Intersection in accounting, no bytes. {proto.Key("/"), proto.Key("/dbA1"), 0, true, 1}, // Intersection in zone, no bytes. {proto.Key("/dbA"), proto.Key("/dbC"), 0, true, 1}, // Multiple intersections, no bytes. {proto.KeyMin, proto.KeyMax, 0, true, 1}, // No intersection, max bytes. {proto.KeyMin, proto.Key("/"), 64 << 20, false, 0}, // No intersection, max bytes+1. {proto.KeyMin, proto.Key("/"), 64<<20 + 1, true, 1}, // No intersection, max bytes * 2. {proto.KeyMin, proto.Key("/"), 64 << 21, true, 2}, // Intersection, max bytes +1. {proto.KeyMin, proto.KeyMax, 64<<20 + 1, true, 2}, } splitQ := newSplitQueue(nil, tc.gossip) for i, test := range testCases { if err := tc.rng.stats.SetMVCCStats(tc.rng.rm.Engine(), engine.MVCCStats{KeyBytes: test.bytes}); err != nil { t.Fatal(err) } copy := *tc.rng.Desc() copy.StartKey = test.start copy.EndKey = test.end if err := tc.rng.setDesc(&copy); err != nil { t.Fatal(err) } shouldQ, priority := splitQ.shouldQueue(proto.ZeroTimestamp, tc.rng) if shouldQ != test.shouldQ { t.Errorf("%d: should queue expected %t; got %t", i, test.shouldQ, shouldQ) } if math.Abs(priority-test.priority) > 0.00001 { t.Errorf("%d: priority expected %f; got %f", i, test.priority, priority) } } } //// // NOTE: tests which actually verify processing of the split queue are // in client_split_test.go, which is in a different test package in // order to allow for distributed transactions with a proper client.
elkingtoncode/LampDB
storage/split_queue_test.go
GO
gpl-3.0
3,707
<?php /** * Fetching and processing of interface messages. * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License along * with this program; if not, write to the Free Software Foundation, Inc., * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. * http://www.gnu.org/copyleft/gpl.html * * @file * @author Niklas Laxström */ /** * The Message class provides methods which fulfil two basic services: * - fetching interface messages * - processing messages into a variety of formats * * First implemented with MediaWiki 1.17, the Message class is intended to * replace the old wfMsg* functions that over time grew unusable. * @see https://www.mediawiki.org/wiki/Manual:Messages_API for equivalences * between old and new functions. * * You should use the wfMessage() global function which acts as a wrapper for * the Message class. The wrapper let you pass parameters as arguments. * * The most basic usage cases would be: * * @code * // Initialize a Message object using the 'some_key' message key * $message = wfMessage( 'some_key' ); * * // Using two parameters those values are strings 'value1' and 'value2': * $message = wfMessage( 'some_key', * 'value1', 'value2' * ); * @endcode * * @section message_global_fn Global function wrapper: * * Since wfMessage() returns a Message instance, you can chain its call with * a method. Some of them return a Message instance too so you can chain them. * You will find below several examples of wfMessage() usage. * * Fetching a message text for interface message: * * @code * $button = Xml::button( * wfMessage( 'submit' )->text() * ); * @endcode * * A Message instance can be passed parameters after it has been constructed, * use the params() method to do so: * * @code * wfMessage( 'welcome-to' ) * ->params( $wgSitename ) * ->text(); * @endcode * * {{GRAMMAR}} and friends work correctly: * * @code * wfMessage( 'are-friends', * $user, $friend * ); * wfMessage( 'bad-message' ) * ->rawParams( '<script>...</script>' ) * ->escaped(); * @endcode * * @section message_language Changing language: * * Messages can be requested in a different language or in whatever current * content language is being used. The methods are: * - Message->inContentLanguage() * - Message->inLanguage() * * Sometimes the message text ends up in the database, so content language is * needed: * * @code * wfMessage( 'file-log', * $user, $filename * )->inContentLanguage()->text(); * @endcode * * Checking whether a message exists: * * @code * wfMessage( 'mysterious-message' )->exists() * // returns a boolean whether the 'mysterious-message' key exist. * @endcode * * If you want to use a different language: * * @code * $userLanguage = $user->getOption( 'language' ); * wfMessage( 'email-header' ) * ->inLanguage( $userLanguage ) * ->plain(); * @endcode * * @note You can parse the text only in the content or interface languages * * @section message_compare_old Comparison with old wfMsg* functions: * * Use full parsing: * * @code * // old style: * wfMsgExt( 'key', [ 'parseinline' ], 'apple' ); * // new style: * wfMessage( 'key', 'apple' )->parse(); * @endcode * * Parseinline is used because it is more useful when pre-building HTML. * In normal use it is better to use OutputPage::(add|wrap)WikiMsg. * * Places where HTML cannot be used. {{-transformation is done. * @code * // old style: * wfMsgExt( 'key', [ 'parsemag' ], 'apple', 'pear' ); * // new style: * wfMessage( 'key', 'apple', 'pear' )->text(); * @endcode * * Shortcut for escaping the message too, similar to wfMsgHTML(), but * parameters are not replaced after escaping by default. * @code * $escaped = wfMessage( 'key' ) * ->rawParams( 'apple' ) * ->escaped(); * @endcode * * @section message_appendix Appendix: * * @todo * - test, can we have tests? * - this documentation needs to be extended * * @see https://www.mediawiki.org/wiki/WfMessage() * @see https://www.mediawiki.org/wiki/New_messages_API * @see https://www.mediawiki.org/wiki/Localisation * * @since 1.17 */ class Message implements MessageSpecifier, Serializable { /** * In which language to get this message. True, which is the default, * means the current user language, false content language. * * @var bool */ protected $interface = true; /** * In which language to get this message. Overrides the $interface setting. * * @var Language|bool Explicit language object, or false for user language */ protected $language = false; /** * @var string The message key. If $keysToTry has more than one element, * this may change to one of the keys to try when fetching the message text. */ protected $key; /** * @var string[] List of keys to try when fetching the message. */ protected $keysToTry; /** * @var array List of parameters which will be substituted into the message. */ protected $parameters = []; /** * Format for the message. * Supported formats are: * * text (transform) * * escaped (transform+htmlspecialchars) * * block-parse * * parse (default) * * plain * * @var string */ protected $format = 'parse'; /** * @var bool Whether database can be used. */ protected $useDatabase = true; /** * @var Title Title object to use as context. */ protected $title = null; /** * @var Content Content object representing the message. */ protected $content = null; /** * @var string */ protected $message; /** * @since 1.17 * @param string|string[]|MessageSpecifier $key Message key, or array of * message keys to try and use the first non-empty message for, or a * MessageSpecifier to copy from. * @param array $params Message parameters. * @param Language $language [optional] Language to use (defaults to current user language). * @throws InvalidArgumentException */ public function __construct( $key, $params = [], Language $language = null ) { if ( $key instanceof MessageSpecifier ) { if ( $params ) { throw new InvalidArgumentException( '$params must be empty if $key is a MessageSpecifier' ); } $params = $key->getParams(); $key = $key->getKey(); } if ( !is_string( $key ) && !is_array( $key ) ) { throw new InvalidArgumentException( '$key must be a string or an array' ); } $this->keysToTry = (array)$key; if ( empty( $this->keysToTry ) ) { throw new InvalidArgumentException( '$key must not be an empty list' ); } $this->key = reset( $this->keysToTry ); $this->parameters = array_values( $params ); // User language is only resolved in getLanguage(). This helps preserve the // semantic intent of "user language" across serialize() and unserialize(). $this->language = $language ?: false; } /** * @see Serializable::serialize() * @since 1.26 * @return string */ public function serialize() { return serialize( [ 'interface' => $this->interface, 'language' => $this->language ? $this->language->getCode() : false, 'key' => $this->key, 'keysToTry' => $this->keysToTry, 'parameters' => $this->parameters, 'format' => $this->format, 'useDatabase' => $this->useDatabase, 'title' => $this->title, ] ); } /** * @see Serializable::unserialize() * @since 1.26 * @param string $serialized */ public function unserialize( $serialized ) { $data = unserialize( $serialized ); $this->interface = $data['interface']; $this->key = $data['key']; $this->keysToTry = $data['keysToTry']; $this->parameters = $data['parameters']; $this->format = $data['format']; $this->useDatabase = $data['useDatabase']; $this->language = $data['language'] ? Language::factory( $data['language'] ) : false; $this->title = $data['title']; } /** * @since 1.24 * * @return bool True if this is a multi-key message, that is, if the key provided to the * constructor was a fallback list of keys to try. */ public function isMultiKey() { return count( $this->keysToTry ) > 1; } /** * @since 1.24 * * @return string[] The list of keys to try when fetching the message text, * in order of preference. */ public function getKeysToTry() { return $this->keysToTry; } /** * Returns the message key. * * If a list of multiple possible keys was supplied to the constructor, this method may * return any of these keys. After the message has been fetched, this method will return * the key that was actually used to fetch the message. * * @since 1.21 * * @return string */ public function getKey() { return $this->key; } /** * Returns the message parameters. * * @since 1.21 * * @return array */ public function getParams() { return $this->parameters; } /** * Returns the message format. * * @since 1.21 * * @return string */ public function getFormat() { return $this->format; } /** * Returns the Language of the Message. * * @since 1.23 * * @return Language */ public function getLanguage() { // Defaults to false which means current user language return $this->language ?: RequestContext::getMain()->getLanguage(); } /** * Factory function that is just wrapper for the real constructor. It is * intended to be used instead of the real constructor, because it allows * chaining method calls, while new objects don't. * * @since 1.17 * * @param string|string[]|MessageSpecifier $key * @param mixed $param,... Parameters as strings. * * @return Message */ public static function newFromKey( $key /*...*/ ) { $params = func_get_args(); array_shift( $params ); return new self( $key, $params ); } /** * Transform a MessageSpecifier or a primitive value used interchangeably with * specifiers (a message key string, or a key + params array) into a proper Message. * * Also accepts a MessageSpecifier inside an array: that's not considered a valid format * but is an easy error to make due to how StatusValue stores messages internally. * Further array elements are ignored in that case. * * @param string|array|MessageSpecifier $value * @return Message * @throws InvalidArgumentException * @since 1.27 */ public static function newFromSpecifier( $value ) { $params = []; if ( is_array( $value ) ) { $params = $value; $value = array_shift( $params ); } if ( $value instanceof Message ) { // Message, RawMessage, ApiMessage, etc $message = clone( $value ); } elseif ( $value instanceof MessageSpecifier ) { $message = new Message( $value ); } elseif ( is_string( $value ) ) { $message = new Message( $value, $params ); } else { throw new InvalidArgumentException( __METHOD__ . ': invalid argument type ' . gettype( $value ) ); } return $message; } /** * Factory function accepting multiple message keys and returning a message instance * for the first message which is non-empty. If all messages are empty then an * instance of the first message key is returned. * * @since 1.18 * * @param string|string[] $keys,... Message keys, or first argument as an array of all the * message keys. * * @return Message */ public static function newFallbackSequence( /*...*/ ) { $keys = func_get_args(); if ( func_num_args() == 1 ) { if ( is_array( $keys[0] ) ) { // Allow an array to be passed as the first argument instead $keys = array_values( $keys[0] ); } else { // Optimize a single string to not need special fallback handling $keys = $keys[0]; } } return new self( $keys ); } /** * Get a title object for a mediawiki message, where it can be found in the mediawiki namespace. * The title will be for the current language, if the message key is in * $wgForceUIMsgAsContentMsg it will be append with the language code (except content * language), because Message::inContentLanguage will also return in user language. * * @see $wgForceUIMsgAsContentMsg * @return Title * @since 1.26 */ public function getTitle() { global $wgContLang, $wgForceUIMsgAsContentMsg; $title = $this->key; if ( !$this->language->equals( $wgContLang ) && in_array( $this->key, (array)$wgForceUIMsgAsContentMsg ) ) { $code = $this->language->getCode(); $title .= '/' . $code; } return Title::makeTitle( NS_MEDIAWIKI, $wgContLang->ucfirst( strtr( $title, ' ', '_' ) ) ); } /** * Adds parameters to the parameter list of this message. * * @since 1.17 * * @param mixed ... Parameters as strings, or a single argument that is * an array of strings. * * @return Message $this */ public function params( /*...*/ ) { $args = func_get_args(); if ( isset( $args[0] ) && is_array( $args[0] ) ) { $args = $args[0]; } $args_values = array_values( $args ); $this->parameters = array_merge( $this->parameters, $args_values ); return $this; } /** * Add parameters that are substituted after parsing or escaping. * In other words the parsing process cannot access the contents * of this type of parameter, and you need to make sure it is * sanitized beforehand. The parser will see "$n", instead. * * @since 1.17 * * @param mixed $params,... Raw parameters as strings, or a single argument that is * an array of raw parameters. * * @return Message $this */ public function rawParams( /*...*/ ) { $params = func_get_args(); if ( isset( $params[0] ) && is_array( $params[0] ) ) { $params = $params[0]; } foreach ( $params as $param ) { $this->parameters[] = self::rawParam( $param ); } return $this; } /** * Add parameters that are numeric and will be passed through * Language::formatNum before substitution * * @since 1.18 * * @param mixed $param,... Numeric parameters, or a single argument that is * an array of numeric parameters. * * @return Message $this */ public function numParams( /*...*/ ) { $params = func_get_args(); if ( isset( $params[0] ) && is_array( $params[0] ) ) { $params = $params[0]; } foreach ( $params as $param ) { $this->parameters[] = self::numParam( $param ); } return $this; } /** * Add parameters that are durations of time and will be passed through * Language::formatDuration before substitution * * @since 1.22 * * @param int|int[] $param,... Duration parameters, or a single argument that is * an array of duration parameters. * * @return Message $this */ public function durationParams( /*...*/ ) { $params = func_get_args(); if ( isset( $params[0] ) && is_array( $params[0] ) ) { $params = $params[0]; } foreach ( $params as $param ) { $this->parameters[] = self::durationParam( $param ); } return $this; } /** * Add parameters that are expiration times and will be passed through * Language::formatExpiry before substitution * * @since 1.22 * * @param string|string[] $param,... Expiry parameters, or a single argument that is * an array of expiry parameters. * * @return Message $this */ public function expiryParams( /*...*/ ) { $params = func_get_args(); if ( isset( $params[0] ) && is_array( $params[0] ) ) { $params = $params[0]; } foreach ( $params as $param ) { $this->parameters[] = self::expiryParam( $param ); } return $this; } /** * Add parameters that are time periods and will be passed through * Language::formatTimePeriod before substitution * * @since 1.22 * * @param int|int[] $param,... Time period parameters, or a single argument that is * an array of time period parameters. * * @return Message $this */ public function timeperiodParams( /*...*/ ) { $params = func_get_args(); if ( isset( $params[0] ) && is_array( $params[0] ) ) { $params = $params[0]; } foreach ( $params as $param ) { $this->parameters[] = self::timeperiodParam( $param ); } return $this; } /** * Add parameters that are file sizes and will be passed through * Language::formatSize before substitution * * @since 1.22 * * @param int|int[] $param,... Size parameters, or a single argument that is * an array of size parameters. * * @return Message $this */ public function sizeParams( /*...*/ ) { $params = func_get_args(); if ( isset( $params[0] ) && is_array( $params[0] ) ) { $params = $params[0]; } foreach ( $params as $param ) { $this->parameters[] = self::sizeParam( $param ); } return $this; } /** * Add parameters that are bitrates and will be passed through * Language::formatBitrate before substitution * * @since 1.22 * * @param int|int[] $param,... Bit rate parameters, or a single argument that is * an array of bit rate parameters. * * @return Message $this */ public function bitrateParams( /*...*/ ) { $params = func_get_args(); if ( isset( $params[0] ) && is_array( $params[0] ) ) { $params = $params[0]; } foreach ( $params as $param ) { $this->parameters[] = self::bitrateParam( $param ); } return $this; } /** * Add parameters that are plaintext and will be passed through without * the content being evaluated. Plaintext parameters are not valid as * arguments to parser functions. This differs from self::rawParams in * that the Message class handles escaping to match the output format. * * @since 1.25 * * @param string|string[] $param,... plaintext parameters, or a single argument that is * an array of plaintext parameters. * * @return Message $this */ public function plaintextParams( /*...*/ ) { $params = func_get_args(); if ( isset( $params[0] ) && is_array( $params[0] ) ) { $params = $params[0]; } foreach ( $params as $param ) { $this->parameters[] = self::plaintextParam( $param ); } return $this; } /** * Set the language and the title from a context object * * @since 1.19 * * @param IContextSource $context * * @return Message $this */ public function setContext( IContextSource $context ) { $this->inLanguage( $context->getLanguage() ); $this->title( $context->getTitle() ); $this->interface = true; return $this; } /** * Request the message in any language that is supported. * * As a side effect interface message status is unconditionally * turned off. * * @since 1.17 * @param Language|string $lang Language code or Language object. * @return Message $this * @throws MWException */ public function inLanguage( $lang ) { if ( $lang instanceof Language ) { $this->language = $lang; } elseif ( is_string( $lang ) ) { if ( !$this->language instanceof Language || $this->language->getCode() != $lang ) { $this->language = Language::factory( $lang ); } } elseif ( $lang instanceof StubUserLang ) { $this->language = false; } else { $type = gettype( $lang ); throw new MWException( __METHOD__ . " must be " . "passed a String or Language object; $type given" ); } $this->message = null; $this->interface = false; return $this; } /** * Request the message in the wiki's content language, * unless it is disabled for this message. * * @since 1.17 * @see $wgForceUIMsgAsContentMsg * * @return Message $this */ public function inContentLanguage() { global $wgForceUIMsgAsContentMsg; if ( in_array( $this->key, (array)$wgForceUIMsgAsContentMsg ) ) { return $this; } global $wgContLang; $this->inLanguage( $wgContLang ); return $this; } /** * Allows manipulating the interface message flag directly. * Can be used to restore the flag after setting a language. * * @since 1.20 * * @param bool $interface * * @return Message $this */ public function setInterfaceMessageFlag( $interface ) { $this->interface = (bool)$interface; return $this; } /** * Enable or disable database use. * * @since 1.17 * * @param bool $useDatabase * * @return Message $this */ public function useDatabase( $useDatabase ) { $this->useDatabase = (bool)$useDatabase; return $this; } /** * Set the Title object to use as context when transforming the message * * @since 1.18 * * @param Title $title * * @return Message $this */ public function title( $title ) { $this->title = $title; return $this; } /** * Returns the message as a Content object. * * @return Content */ public function content() { if ( !$this->content ) { $this->content = new MessageContent( $this ); } return $this->content; } /** * Returns the message parsed from wikitext to HTML. * * @since 1.17 * * @return string HTML */ public function toString() { $string = $this->fetchMessage(); if ( $string === false ) { // Err on the side of safety, ensure that the output // is always html safe in the event the message key is // missing, since in that case its highly likely the // message key is user-controlled. // '⧼' is used instead of '<' to side-step any // double-escaping issues. return '⧼' . htmlspecialchars( $this->key ) . '⧽'; } # Replace $* with a list of parameters for &uselang=qqx. if ( strpos( $string, '$*' ) !== false ) { $paramlist = ''; if ( $this->parameters !== [] ) { $paramlist = ': $' . implode( ', $', range( 1, count( $this->parameters ) ) ); } $string = str_replace( '$*', $paramlist, $string ); } # Replace parameters before text parsing $string = $this->replaceParameters( $string, 'before' ); # Maybe transform using the full parser if ( $this->format === 'parse' ) { $string = $this->parseText( $string ); $string = Parser::stripOuterParagraph( $string ); } elseif ( $this->format === 'block-parse' ) { $string = $this->parseText( $string ); } elseif ( $this->format === 'text' ) { $string = $this->transformText( $string ); } elseif ( $this->format === 'escaped' ) { $string = $this->transformText( $string ); $string = htmlspecialchars( $string, ENT_QUOTES, 'UTF-8', false ); } # Raw parameter replacement $string = $this->replaceParameters( $string, 'after' ); return $string; } /** * Magic method implementation of the above (for PHP >= 5.2.0), so we can do, eg: * $foo = new Message( $key ); * $string = "<abbr>$foo</abbr>"; * * @since 1.18 * * @return string */ public function __toString() { if ( $this->format !== 'parse' ) { $ex = new LogicException( __METHOD__ . ' using implicit format: ' . $this->format ); \MediaWiki\Logger\LoggerFactory::getInstance( 'message-format' )->warning( $ex->getMessage(), [ 'exception' => $ex, 'format' => $this->format, 'key' => $this->key ] ); } // PHP doesn't allow __toString to throw exceptions and will // trigger a fatal error if it does. So, catch any exceptions. try { return $this->toString(); } catch ( Exception $ex ) { try { trigger_error( "Exception caught in " . __METHOD__ . " (message " . $this->key . "): " . $ex, E_USER_WARNING ); } catch ( Exception $ex ) { // Doh! Cause a fatal error after all? } if ( $this->format === 'plain' || $this->format === 'text' ) { return '<' . $this->key . '>'; } return '&lt;' . htmlspecialchars( $this->key ) . '&gt;'; } } /** * Fully parse the text from wikitext to HTML. * * @since 1.17 * * @return string Parsed HTML. */ public function parse() { $this->format = 'parse'; return $this->toString(); } /** * Returns the message text. {{-transformation is done. * * @since 1.17 * * @return string Unescaped message text. */ public function text() { $this->format = 'text'; return $this->toString(); } /** * Returns the message text as-is, only parameters are substituted. * * @since 1.17 * * @return string Unescaped untransformed message text. */ public function plain() { $this->format = 'plain'; return $this->toString(); } /** * Returns the parsed message text which is always surrounded by a block element. * * @since 1.17 * * @return string HTML */ public function parseAsBlock() { $this->format = 'block-parse'; return $this->toString(); } /** * Returns the message text. {{-transformation is done and the result * is escaped excluding any raw parameters. * * @since 1.17 * * @return string Escaped message text. */ public function escaped() { $this->format = 'escaped'; return $this->toString(); } /** * Check whether a message key has been defined currently. * * @since 1.17 * * @return bool */ public function exists() { return $this->fetchMessage() !== false; } /** * Check whether a message does not exist, or is an empty string * * @since 1.18 * @todo FIXME: Merge with isDisabled()? * * @return bool */ public function isBlank() { $message = $this->fetchMessage(); return $message === false || $message === ''; } /** * Check whether a message does not exist, is an empty string, or is "-". * * @since 1.18 * * @return bool */ public function isDisabled() { $message = $this->fetchMessage(); return $message === false || $message === '' || $message === '-'; } /** * @since 1.17 * * @param mixed $raw * * @return array Array with a single "raw" key. */ public static function rawParam( $raw ) { return [ 'raw' => $raw ]; } /** * @since 1.18 * * @param mixed $num * * @return array Array with a single "num" key. */ public static function numParam( $num ) { return [ 'num' => $num ]; } /** * @since 1.22 * * @param int $duration * * @return int[] Array with a single "duration" key. */ public static function durationParam( $duration ) { return [ 'duration' => $duration ]; } /** * @since 1.22 * * @param string $expiry * * @return string[] Array with a single "expiry" key. */ public static function expiryParam( $expiry ) { return [ 'expiry' => $expiry ]; } /** * @since 1.22 * * @param number $period * * @return number[] Array with a single "period" key. */ public static function timeperiodParam( $period ) { return [ 'period' => $period ]; } /** * @since 1.22 * * @param int $size * * @return int[] Array with a single "size" key. */ public static function sizeParam( $size ) { return [ 'size' => $size ]; } /** * @since 1.22 * * @param int $bitrate * * @return int[] Array with a single "bitrate" key. */ public static function bitrateParam( $bitrate ) { return [ 'bitrate' => $bitrate ]; } /** * @since 1.25 * * @param string $plaintext * * @return string[] Array with a single "plaintext" key. */ public static function plaintextParam( $plaintext ) { return [ 'plaintext' => $plaintext ]; } /** * Substitutes any parameters into the message text. * * @since 1.17 * * @param string $message The message text. * @param string $type Either "before" or "after". * * @return string */ protected function replaceParameters( $message, $type = 'before' ) { $replacementKeys = []; foreach ( $this->parameters as $n => $param ) { list( $paramType, $value ) = $this->extractParam( $param ); if ( $type === $paramType ) { $replacementKeys['$' . ( $n + 1 )] = $value; } } $message = strtr( $message, $replacementKeys ); return $message; } /** * Extracts the parameter type and preprocessed the value if needed. * * @since 1.18 * * @param mixed $param Parameter as defined in this class. * * @return array Array with the parameter type (either "before" or "after") and the value. */ protected function extractParam( $param ) { if ( is_array( $param ) ) { if ( isset( $param['raw'] ) ) { return [ 'after', $param['raw'] ]; } elseif ( isset( $param['num'] ) ) { // Replace number params always in before step for now. // No support for combined raw and num params return [ 'before', $this->getLanguage()->formatNum( $param['num'] ) ]; } elseif ( isset( $param['duration'] ) ) { return [ 'before', $this->getLanguage()->formatDuration( $param['duration'] ) ]; } elseif ( isset( $param['expiry'] ) ) { return [ 'before', $this->getLanguage()->formatExpiry( $param['expiry'] ) ]; } elseif ( isset( $param['period'] ) ) { return [ 'before', $this->getLanguage()->formatTimePeriod( $param['period'] ) ]; } elseif ( isset( $param['size'] ) ) { return [ 'before', $this->getLanguage()->formatSize( $param['size'] ) ]; } elseif ( isset( $param['bitrate'] ) ) { return [ 'before', $this->getLanguage()->formatBitrate( $param['bitrate'] ) ]; } elseif ( isset( $param['plaintext'] ) ) { return [ 'after', $this->formatPlaintext( $param['plaintext'] ) ]; } else { $warning = 'Invalid parameter for message "' . $this->getKey() . '": ' . htmlspecialchars( serialize( $param ) ); trigger_error( $warning, E_USER_WARNING ); $e = new Exception; wfDebugLog( 'Bug58676', $warning . "\n" . $e->getTraceAsString() ); return [ 'before', '[INVALID]' ]; } } elseif ( $param instanceof Message ) { // Message objects should not be before parameters because // then they'll get double escaped. If the message needs to be // escaped, it'll happen right here when we call toString(). return [ 'after', $param->toString() ]; } else { return [ 'before', $param ]; } } /** * Wrapper for what ever method we use to parse wikitext. * * @since 1.17 * * @param string $string Wikitext message contents. * * @return string Wikitext parsed into HTML. */ protected function parseText( $string ) { $out = MessageCache::singleton()->parse( $string, $this->title, /*linestart*/true, $this->interface, $this->getLanguage() ); return $out instanceof ParserOutput ? $out->getText() : $out; } /** * Wrapper for what ever method we use to {{-transform wikitext. * * @since 1.17 * * @param string $string Wikitext message contents. * * @return string Wikitext with {{-constructs replaced with their values. */ protected function transformText( $string ) { return MessageCache::singleton()->transform( $string, $this->interface, $this->getLanguage(), $this->title ); } /** * Wrapper for what ever method we use to get message contents. * * @since 1.17 * * @return string * @throws MWException If message key array is empty. */ protected function fetchMessage() { if ( $this->message === null ) { $cache = MessageCache::singleton(); foreach ( $this->keysToTry as $key ) { $message = $cache->get( $key, $this->useDatabase, $this->getLanguage() ); if ( $message !== false && $message !== '' ) { break; } } // NOTE: The constructor makes sure keysToTry isn't empty, // so we know that $key and $message are initialized. $this->key = $key; $this->message = $message; } return $this->message; } /** * Formats a message parameter wrapped with 'plaintext'. Ensures that * the entire string is displayed unchanged when displayed in the output * format. * * @since 1.25 * * @param string $plaintext String to ensure plaintext output of * * @return string Input plaintext encoded for output to $this->format */ protected function formatPlaintext( $plaintext ) { switch ( $this->format ) { case 'text': case 'plain': return $plaintext; case 'parse': case 'block-parse': case 'escaped': default: return htmlspecialchars( $plaintext, ENT_QUOTES ); } } } /** * Variant of the Message class. * * Rather than treating the message key as a lookup * value (which is passed to the MessageCache and * translated as necessary), a RawMessage key is * treated as the actual message. * * All other functionality (parsing, escaping, etc.) * is preserved. * * @since 1.21 */ class RawMessage extends Message { /** * Call the parent constructor, then store the key as * the message. * * @see Message::__construct * * @param string $text Message to use. * @param array $params Parameters for the message. * * @throws InvalidArgumentException */ public function __construct( $text, $params = [] ) { if ( !is_string( $text ) ) { throw new InvalidArgumentException( '$text must be a string' ); } parent::__construct( $text, $params ); // The key is the message. $this->message = $text; } /** * Fetch the message (in this case, the key). * * @return string */ public function fetchMessage() { // Just in case the message is unset somewhere. if ( $this->message === null ) { $this->message = $this->key; } return $this->message; } }
Electro-Light/ElectroLight-WebSite
wiki/includes/Message.php
PHP
gpl-3.0
33,273
import processing.core.*; import processing.data.*; import processing.event.*; import processing.opengl.*; import processing.serial.Serial; import controlP5.*; import java.io.File; import java.lang.*; import javax.swing.SwingUtilities; import javax.swing.JFileChooser; import javax.swing.filechooser.FileFilter; import javax.swing.JOptionPane; import java.io.PrintWriter; import java.io.InputStream; import java.io.OutputStream; import java.io.FileOutputStream; import java.io.FileInputStream; import java.util.*; import java.io.FileNotFoundException; import java.text.DecimalFormat; import java.util.HashMap; import java.util.ArrayList; import java.io.File; import java.io.BufferedReader; import java.io.PrintWriter; import java.io.InputStream; import java.io.OutputStream; import java.io.IOException; public class MW_OSD_GUI extends PApplet { /* MultiWii NG OSD ... 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 any later version. see http://www.gnu.org/licenses/ This work is based on the following open source work :- Rush OSD Development GUI https://code.google.com/p/rush-osd-development/ And to a lesser extent code from the following :- Rushduino http://code.google.com/p/rushduino-osd/ Minim OSD https://code.google.com/p/arducam-osd/wiki/minimosd Its base is taken from "Rush OSD Development" R370 All credit and full acknowledgement to the incredible work and hours from the many developers, contributors and testers that have helped along the way. Jean Gabriel Maurice. He started the revolution. He was the first.... */ // serial library // controlP5 library // for efficient String concatemation // required for swing and EDT // Saving dialogue // for our configuration file filter "*.mwi" // for message dialogue //import java.io.BufferedReader; //added new imports to support proccessing 2.0b7 String MW_OSD_GUI_Version = "MWOSD R1.3 - NextGeneration"; int MW_OSD_EEPROM_Version = 6; int GPS_numSatPosition = 0; int GPS_directionToHomePosition = 1; int GPS_distanceToHomePosition = 2; int speedPosition = 3; int GPS_angleToHomePosition = 4; int MwGPSAltPosition = 5; int sensorPosition = 6; int MwHeadingPosition = 7; int MwHeadingGraphPosition = 8; int MwAltitudePosition = 9; int MwClimbRatePosition = 10; int CurrentThrottlePosition = 11; int flyTimePosition = 12; int onTimePosition = 13; int motorArmedPosition = 14; int MwGPSLatPosition = 15; int MwGPSLonPosition = 16; int MwGPSLatPositionTop = 17; int MwGPSLonPositionTop = 18; int rssiPosition = 19; int temperaturePosition = 20; int voltagePosition = 21; int vidvoltagePosition = 22; int amperagePosition = 23; int pMeterSumPosition = 24; int horizonPosition = 25; int SideBarPosition =26; int SideBarScrollPosition = 27; int callSignPosition = 28; int debugPosition = 29; int gimbalPosition = 30; int GPS_timePosition = 31; int SportPosition = 32; int ModePosition = 33; int MapModePosition = 34; int MapCenterPosition = 35; int APstatusPosition = 36; int MSP_sendOrder =0; PImage img_Clear,GUIBackground,OSDBackground,DONATEimage,RadioPot; int readcounter=0; // ScreenType---------- NTSC = 0, PAL = 1 --------------------------------- int ScreenType = 0; int TIMEBASE_X1 = 50; int TIMEBASE = TIMEBASE_X1; int LINE = 30; int LINE01 = 0; int LINE02 = 30; int LINE03 = 60; int LINE04 = 90; int LINE05 = 120; int LINE06 = 150; int LINE07 = 180; int LINE08 = 210; int LINE09 = 240; int LINE10 = 270; int LINE11 = 300; int LINE12 = 330; int LINE13 = 360; int LINE14 = 390; int LINE15 = 420; int LINE16 = 450; int TestLine = 300; int TOPSHIFT = 0; int DisplayWindowX = 681; //500; int DisplayWindowY = 5; //5; int WindowAdjX = -0; //15 int WindowAdjY = -0; int WindowShrinkX = 8; int WindowShrinkY = 48; //image(OSDBackground,DisplayWindowX+WindowAdjX, DisplayWindowY+WindowAdjY, 469-WindowShrinkX, 300-WindowShrinkY); //529-WindowShrinkX, 360-WindowShrinkY); int currentCol = 0; int currentRow = 0; //Boolean SimulateMW = true; int S16_AMPMAX = 0; //16bit from 8 EEPROM values ControlP5 controlP5; ControlP5 SmallcontrolP5; ControlP5 ScontrolP5; ControlP5 FontGroupcontrolP5; ControlP5 GroupcontrolP5; Textlabel txtlblWhichcom,txtlblWhichbaud,txtmessage; Textlabel txtlblLayoutTxt,txtlblLayoutEnTxt, txtlblLayoutHudTxt; Textlabel txtlblLayoutTxt2,txtlblLayoutEnTxt2, txtlblLayoutHudTxt2; ListBox commListbox,baudListbox; //char serialBuffer[] = new char[128]; // this hold the imcoming string from serial O string //String TestString = ""; ///String SendCommand = ""; boolean PortRead = false; boolean PortWrite = false; int PortReadtimer = 0; int ReadConfig = 0; int ReadMillis = 0; int WriteConfig = 0; int WriteMillis = 0; int linktimer = 0; ControlGroup messageBox; Textlabel MessageText; int LEWvisible=0; // XML config variables int DISPLAY_STATE; int hudsavailable=8; int hudoptions; int hudnamelength; int[][] hudenable; String[] hudpositiontext; int xmlloaded=0; XML xml; int[][] CONFIGHUD; int[][] CONFIGHUDEN; String[] CONFIGHUDTEXT; String[] CONFIGHUDNAME; int eeaddressGUI=0; int eedataGUI=0; int eeaddressOSD=0; int eedataOSD=0; int ReadConfigMSPMillis=0; int WriteConfigMSPMillis=0; // XML config editorvariables int hudeditposition=0; int[] SimPosn; int[][] ConfigLayout; int[] EElookuptable= new int[512]; //int[] readcheck; int readerror=0; // Int variables String OSname = System.getProperty("os.name"); String LoadPercent = ""; String CallSign = ""; String Title; int Passthroughcomm; int init_com = 0; int commListMax = 0; int whichKey = -1; // Variable to hold keystoke values int inByte = -1; // Incoming serial data int[] serialInArray = new int[3]; // Where we'll put what we receive int[] debug = new int[4]; String progresstxt=""; int xcolor=20; int serialCount = 0; // A count of how many bytes we receive int ConfigEEPROM = -1; int ConfigVALUE = -1; int windowsX = 1041; int windowsY =578; //995; //573; //int windowsX = 1200; int windowsY =800; //995; //573; int xGraph = 10; int yGraph = 35; int xObj = 520; int yObj = 293; //900,450 int xCompass = 920; int yCompass = 341; //760,336 int xLevelObj = 920; int yLevelObj = 80; //760,80 int xParam = 120; int yParam = 5; int xRC = 690; int yRC = 10; //850,10 int xMot = 690; int yMot = 155; //850,155 int xButton = 845; int yButton = 231; //685,222 int xBox = 415; int yBox = 10; //int xGPS = 853; int yGPS = 438; //693,438 int XSim = DisplayWindowX+WindowAdjX+10; int YSim = 305-WindowShrinkY + 95; //DisplayWindowX+WindowAdjX, DisplayWindowY+WindowAdjY, 360-WindowShrinkX, 288-WindowShrinkY); // Box locations ------------------------------------------------------------------------- int Col1Width = 180; int Col2Width = 200; int Col3Width = 165; int XEEPROM = 120; int YEEPROM = 5; //hidden do not remove int XBoard = 120; int YBoard = 5; int XRSSI = 120; int YRSSI = 317; int XVREF = 120; int YVREF = 444; int XVolts = 120; int YVolts = 5; int XAmps = 120; int YAmps = 190; int XVVolts = 120; int YVVolts = 114; int XTemp = 510; int YTemp = 268; int XCS = 120; int YCS = 486; int XGPS = 510; int YGPS = 5; int XCOMPASS = 510; int YCOMPASS = 98; //int XGPS = 305; int YGPS = 5; int XTIME = 510; int YTIME = 190; //int XTIME = 510; int YTIME = 5; int XHUD = 305; int YHUD = 240; int XDisplay = 305; int YDisplay = 114; //48; int XSPORT = 810; int YSPORT = 357; int XOther = 305; int YOther = 5; //48; //int XOther = 305; int YOther = 150; //48; int XPortStat = 5; int YPortStat = 20; int XDebug = 5; int YDebug = 271; int XFONTTOOLS = 5; int YFONTTOOLS = 395; int XOSD_CONTROLS = 5; int YOSD_CONTROLS = 485; int XSAVE_LOAD = 5; int YSAVE_LOAD = 328; int XMESSAGE = 500; int YMESSAGE = 200; int XLINKS = 690; int YLINKS = 275; int XControlBox= 5; int YControlBox = 450; //389 int XRCSim = XSim; int YRCSim = 30; String FontFileName = "data/default.mcm"; int BaudRate = 115200; //File FontFile; int activeTab = 1; int xx=0; int YLocation = 0; int Roll = 0; int Pitch = 0; int confmillis = 1000; int csmillis = 1000; int confCheck = 0; int resmillis = 5000; int resCheck = 1; int OnTimer = 0; int FlyTimer = 0; float SimItem0= 0; int Armed = 0; int Showback = 1; int del = 0; int armedangle=0; int oldwpmillis; int wpno; // int variables // For Heading char[] headGraph={ 0x1a,0x1d,0x1c,0x1d,0x19,0x1d,0x1c,0x1d,0x1b,0x1d,0x1c,0x1d,0x18,0x1d,0x1c,0x1d,0x1a,0x1d,0x1c,0x1d,0x19,0x1d,0x1c,0x1d,0x1b}; static int MwHeading=0; char MwHeadingUnitAdd=0xbd; String[] ConfigNames = { "EEPROM Loaded", "RSSI Min", "RSSI Max", "RSSI Alarm", "Display RSSI", "Use FC RSSI", "Use PWM", "Display Voltage", "Voltage Alarm", "Battery Cells", "Voltage Adjust", "Use FC main voltage", "Display Amps", "Use FC amperage", "Display mAh", "Use Virtual Sensor", "Amps Adjust", "Display Video Voltage", "Voltage Adjust", "Use FC video voltage", "x100 mAh Alarm", "Amp Alarm", "Display GPS", " - GPS Coords", " - Coords on Top", " - GPS Altitude", "Display Angle to Home", "Display Heading", " - Heading 360", "Units", "Video Signal", "Display Throttle Position", "Display Horizon Bar", "Display Side Bars", "Display Battery Status", "Reset Stats After Arm", " - Map mode", "Enable ADC 5v ref", "Use BoxNames", "Display Flight Mode", "Display CallSign", "Display GPS time", "Time Zone +/-", "Time Zone offset", "Debug", " - SB Scrolling", "Display Gimbal", "Display Vario", "Display BARO ALT", "Display Compass", " - HB Elevation", "Display Timer", " - FM sensors", " - SB direction", "Zero Adjust", "Amperage 16L", "Amperage 16H", "HUD layout", "HUD layout - OSD SW", "x100 Distance alarm", "x10 Altitude alarm", "Speed alarm", "Timer alarm", "S_CS0", "S_CS1", "S_CS2", "S_CS3", "S_CS4", "S_CS5", "S_CS6", "S_CS7", "S_CS8", "S_CS9", }; String[] ConfigHelp = { "EEPROM Loaded", "RSSI Min", "RSSI Max", "RSSI Alarm", "Display RSSI", "Use MWii", "Use PWM", "Display Voltage", "Voltage Alarm", "Battery Cells", "Voltage Adjust", "Use MWii", "Display Amps", "Use MWii", "Display mAh", "Use Virtual Sensor", "Amps Adjust", "Display Video Voltage", "Voltage Adjust", "Use MWii", "mAh Alarm", "Amp Alarm", "Display GPS", " - GPS Coords", " - Coords on Top", " - GPS Altitude", "Display Angle to Home", "Display Heading", " - Heading 360", "Units", "Video Signal", "Display Throttle Position", "Display Horizon Bar", "Display Side Bars", "Display Battery Status", "Reset Stats After Arm", "Enable Map mode", "Enable ADC 5v ref", "Use BoxNames", "Display Flight Mode", "Display CallSign", "Display GPS time", "Time Zone +/-", "Time Zone offset", "Debug", " - SB Scrolling", "Display Gimbal", "Display Vario", "Display BARO ALT", "Display Compass", " - HB Elevation", "Display Timer", " - FM sensors", " - SB direction", "Zero Adjust", "Amperage 16L", "Amperage 16H", "HUD layout", "HUD layout - OSD SW", "Distance alarm", "Altitude alarm", "Speed alarm", "Timer alarm", "S_CS0", "S_CS1", "S_CS2", "S_CS3", "S_CS4", "S_CS5", "S_CS6", "S_CS7", "S_CS8", "S_CS9", }; static int CHECKBOXITEMS=0; int CONFIGITEMS=ConfigNames.length; static int SIMITEMS=6; // System.out.println("MSP: "); int[] ConfigRanges = { 1, // used for check 0 255, // S_RSSIMIN 1 255, // S_RSSIMAX 2 100, // S_RSSI_ALARM 3 1, // S_DISPLAYRSSI 4 1, // S_MWRSSI 5 1, // S_PWMRSSI 6 1, // S_DISPLAYVOLTAGE 7 255, // S_VOLTAGEMIN 8 6, // S_BATCELLS 9 255, // S_DIVIDERRATIO 10 1, // S_MAINVOLTAGE_VBAT 11 1, // S_AMPERAGE, 12 1, // S_MWAMPERAGE, 12a 1, // S_AMPER_HOUR, 13 1, // S_AMPERAGE_VIRTUAL, 1023, // S_AMPDIVIDERRATIO, // note this is 8>>16 bit EPROM var 1, // S_VIDVOLTAGE 14 255, // S_VIDDIVIDERRATIO 15 1, // S_VIDVOLTAGE_VBAT 16 10000, // S_AMPER_HOUR_ALARM 17 255, // S_AMPERAGE_ALARM 18 //1, // S_BOARDTYPE 19 1, // S_DISPLAYGPS 20 1, // S_COORDINATES 21 1, // S_GPSCOORDTOP 22 1, // S_GPSALTITUDE 23 1, // S_ANGLETOHOME 24 1, // S_SHOWHEADING 25 1, // S_HEADING360 26 1, // S_UNITSYSTEM 27 1, // S_SCREENTYPE 28 1, // S_THROTTLEPOSITION 29 1, // S_DISPLAY_HORIZON_BR 30 1, // S_WITHDECORATION 31 1, // S_SHOWBATLEVELEVOLUTION 32 1, // S_RESETSTATISTICS 33 4, // S_MAPMODE 34 //map mode 1, // S_VREFERENCE, 1, // S_USE_BOXNAMES 35 1, // S_MODEICON 36 1, // call sign 37 1, // GPStime 37a 1, // GPSTZ +/- 37b 13, // GPSTZ 37c //60, // GPSDS 37d 1, // Debug 37e 1, // S_SCROLLING 37f 1, // S_GIMBAL 37g 1, // S_VARO 37h 1, // SHOW BAROALT 38h 1, // SHOW COMPASS 39h 1, // SHOW HORIZON ELEVATION 40h 1, // S_TIMER 41h 1, // S_MODESENSOR 42h 1, //S_SIDEBARTOPS 43h 1023, // S_AMPMIN, 255, // S_AMPMAXL, 3, // S_AMPMAXH, 7, // S_HUD, 7, // S_HUDOSDSW, 255, //S_DISTANCE_ALARM, 255, //S_ALTITUDE_ALARM, 255, //S_SPEED_ALARM, 255, //S_TIMER_ALARM, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, }; String[] SimNames= { "Armed:", "Acro/Stable:", "Bar Mode:", "Mag Mode:", "GPS Home:", "GPS Hold:", "Sim 6:", "Sim 7:", "Sim 8:", "Sim 9:", "Sim 10:" }; int[] SimRanges = { 1, 1, 1, 1, 1, 1, 1, 255, 1, 1, 1}; PFont font8,font9,font10,font11,font12,font15; //Colors-------------------------------------------------------------------------------------------------------------------- int yellow_ = color(200, 200, 20), green_ = color(30, 120, 30), red_ = color(120, 30, 30), blue_ = color(50, 50, 100), grey_ = color(30, 30, 30), switches_ = color(30, 140, 30), font_ = color(50, 50, 50), clear_ = color(0, 0, 0), donateback_ = color(180, 100, 0), donatefront_ = color(50, 50, 255), osdcontr_ = color(50, 50, 50) ; //Colors-------------------------------------------------------------------------------------------------------------------- // textarea ------------------------------------------------------------------------------------------------------------- Textarea myTextarea; //Println console; // textlabels ------------------------------------------------------------------------------------------------------------- Textlabel txtlblconfItem[] = new Textlabel[CONFIGITEMS] ; Textlabel txtlblSimItem[] = new Textlabel[SIMITEMS] ; Textlabel FileUploadText, TXText, RXText; // textlabels ------------------------------------------------------------------------------------------------------------- // Buttons------------------------------------------------------------------------------------------------------------------ Button buttonIMPORT,buttonSAVE,buttonREAD,buttonRESET,buttonWRITE,buttonRESTART, buttonGPSTIMELINK, buttonSPORTLINK; Button buttonLUP, buttonLDOWN, buttonLLEFT, buttonLRIGHT, buttonLPOSUP, buttonLPOSDOWN; Button buttonLHUDUP,buttonLPOSHUDDOWN,buttonLPOSEN, buttonLSET, buttonLADD, buttonLSAVE, buttonLCANCEL; Button buttonLEW; Button buttonGUIDELINK, buttonFAQLINK, buttonCALIBLINK, buttonSUPPORTLINK, buttonDONATELINK; // Buttons------------------------------------------------------------------------------------------------------------------ // Toggles------------------------------------------------------------------------------------------------------------------ Toggle toggleConfItem[] = new Toggle[CONFIGITEMS] ; // Toggles------------------------------------------------------------------------------------------------------------------ // checkboxes------------------------------------------------------------------------------------------------------------------ CheckBox checkboxConfItem[] = new CheckBox[CONFIGITEMS]; // Toggles------------------------------------------------------------------------------------------------------------------ RadioButton RadioButtonConfItem[] = new RadioButton[CONFIGITEMS] ; RadioButton R_PortStat; // number boxes-------------------------------------------------------------------------------------------------------------- Numberbox confItem[] = new Numberbox[CONFIGITEMS] ; int readcheck[] = new int[CONFIGITEMS] ; //Numberbox SimItem[] = new Numberbox[SIMITEMS] ; // number boxes-------------------------------------------------------------------------------------------------------------- Group MGUploadF, LEW, G_LINKS, G_MESSAGE, SAVE_LOAD, OSD_CONTROLS, G_EEPROM, G_RSSI, G_Voltage, G_Amperage, G_VVoltage, G_Alarms, G_Debug, G_Board, G_GPS, G_Other, G_CallSign, G_PortStatus, G_TIME, G_VREF, G_HUD, G_COMPASS, G_DISPLAY, G_SPORT, G_INFO ; // Timers -------------------------------------------------------------------------------------------------------------------- //ControlTimer OnTimer,FlyTimer; public controlP5.Controller hideLabel(controlP5.Controller c) { c.setLabel(""); c.setLabelVisible(false); return c; } public void setup() { size(windowsX,windowsY); // LoadConfig(); // xml = loadXML("HUDLAYOUT.xml"); xml = loadXML("hudlayout.xml"); // xml = loadXML(dataPath("hudlayout.xml")); initxml(); //Map<Settings, String> table = new EnumMap<Settings>(Settings.class); OnTimer = millis(); frameRate(30); OSDBackground = loadImage("OSD_def.jpg"); GUIBackground = loadImage("GUI_def.jpg"); DONATEimage = loadImage("DON_def.png"); //RadioPot = loadImage("MWImage.jpg"); //PGraphics icon = createGraphics(16, 16, P3D); //icon.beginDraw(); //icon.beginShape(); //icon.texture(RadioPot); //icon.endShape(); //icon.endDraw(); //frame.setIconImage(icon.image); font8 = createFont("Arial bold",8,false); font9 = createFont("Arial bold",10,false); font10 = createFont("Arial bold",11,false); font11 = createFont("Arial bold",11,false); font12 = createFont("Arial bold",12,false); font15 = createFont("Arial bold",15,false); controlP5 = new ControlP5(this); // initialize the GUI controls controlP5.setControlFont(font10); //controlP5.setAutoDraw(false); SmallcontrolP5 = new ControlP5(this); // initialize the GUI controls SmallcontrolP5.setControlFont(font9); //SmallcontrolP5.setAutoDraw(false); ScontrolP5 = new ControlP5(this); // initialize the GUI controls ScontrolP5.setControlFont(font10); //ScontrolP5.setAutoDraw(false); //FontGroupcontrolP5.setAutoDraw(false); GroupcontrolP5 = new ControlP5(this); // initialize the GUI controls GroupcontrolP5.setControlFont(font10); //GroupcontrolP5.setColorForeground(color(30,255)); //GroupcontrolP5.setColorBackground(color(30,255)); //GroupcontrolP5.setColorLabel(color(0, 110, 220)); //GroupcontrolP5.setColorValue(0xffff88ff); //GroupcontrolP5.setColorActive(color(30,255)); //GroupcontrolP5.setAutoDraw(false); FontGroupcontrolP5 = new ControlP5(this); // initialize the GUI controls FontGroupcontrolP5.setControlFont(font10); SetupGroups(); myTextarea = controlP5.addTextarea("txt") .setPosition(DisplayWindowX+WindowAdjX+10+10, DisplayWindowY+WindowAdjY+10) .setSize(325, 228) .setFont(createFont("", 12)) .setLineHeight(14) .setColor(color(255)) // .setColorBackground(red_) ; // console = controlP5.addConsole(myTextarea);// // BAUD RATE / COM PORT SELECTION --------------------------------------- baudListbox = controlP5.addListBox("portBaudList",5,116,110,260); // make a listbox and populate it with the available comm ports baudListbox.setItemHeight(15); baudListbox.setBarHeight(15); baudListbox.captionLabel().set("BAUD"); baudListbox.setColorBackground(red_); baudListbox.addItem("115200",0); baudListbox.addItem("57600",1); baudListbox.addItem("38400",2); baudListbox.addItem("19200",3); // baudListbox.setValue(1); baudListbox.close(); txtlblWhichbaud = controlP5.addTextlabel("txtlblWhichbaud","Baud rate: "+str(BaudRate),5,37).setGroup(G_PortStatus); // textlabel(name,text,x,y) // COM PORT SELECTION --------------------------------------- commListbox = controlP5.addListBox("portComList",5,99,110,260); // make a listbox and populate it with the available comm ports commListbox.setItemHeight(15); commListbox.setBarHeight(15); commListbox.captionLabel().set("COM SETTINGS"); commListbox.setColorBackground(red_); for(int i=0;i<Serial.list().length;i++) { String pn = shortifyPortName(Serial.list()[i], 13); if (pn.length() >0 ) commListbox.addItem(pn,i); // addItem(name,value) commListMax = i; } commListbox.addItem("Close Comm",++commListMax); // addItem(name,value) //commListbox.addItem("Pass Thru Comm",commListMax+1); // addItem(name,value) txtlblWhichcom = controlP5.addTextlabel("txtlblWhichcom","No Port Selected",5,22).setGroup(G_PortStatus); // textlabel(name,text,x,y) txtmessage = controlP5.addTextlabel("txtmessage","",3,295); // textdebug // BUTTONS SELECTION --------------------------------------- buttonSAVE = controlP5.addButton("bSAVE",1,20,5,60,16); buttonSAVE.setLabel(" SAVE").setGroup(SAVE_LOAD).setColorBackground(osdcontr_); buttonIMPORT = controlP5.addButton("bIMPORT",1,20,25,60,16); buttonIMPORT.setLabel(" LOAD").setGroup(SAVE_LOAD).setColorBackground(osdcontr_); buttonREAD = controlP5.addButton("READEEMSP",1,20,5,60,16);buttonREAD.setColorBackground(osdcontr_).setGroup(OSD_CONTROLS).setLabel(" READ"); buttonWRITE = controlP5.addButton("WRITEEEMSP",1,20,25,60,16);buttonWRITE.setColorBackground(osdcontr_).setGroup(OSD_CONTROLS).setLabel(" WRITE"); buttonRESET = controlP5.addButton("DEFAULT",1,20,45,60,16);buttonRESET.setColorBackground(osdcontr_).setGroup(OSD_CONTROLS).setLabel(" DEFAULT"); buttonRESTART = controlP5.addButton("RESTART",1,20,65,60,16);buttonRESTART.setColorBackground(osdcontr_).setGroup(OSD_CONTROLS).setLabel(" RESTART"); buttonLEW = controlP5.addButton("LEW",1,10,10,92,16);buttonLEW.setColorBackground(osdcontr_).setGroup(G_LINKS).setLabel("Layout Editor"); // EEPROM---------------------------------------------------------------- CreateItem(GetSetting("S_CHECK_"), 5, 0, G_EEPROM); CreateItem(GetSetting("S_AMPMAXL"), 5, 0, G_EEPROM); CreateItem(GetSetting("S_AMPMAXH"), 5, 0, G_EEPROM); CreateItem(GetSetting("S_USE_BOXNAMES"), 5,0, G_EEPROM); CreateItem(GetSetting("S_GPSCOORDTOP"), 5,0, G_EEPROM); // RSSI --------------------------------------------------------------------------- CreateItem(GetSetting("S_DISPLAYRSSI"), 5, 0, G_RSSI); CreateItem(GetSetting("S_MWRSSI"), 5,1*17, G_RSSI); CreateItem(GetSetting("S_PWMRSSI"), 5,2*17, G_RSSI); CreateItem(GetSetting("S_RSSIMIN"), 5, 3*17, G_RSSI); CreateItem(GetSetting("S_RSSIMAX"), 5,4*17, G_RSSI); CreateItem(GetSetting("S_RSSI_ALARM"), 5,5*17, G_RSSI); // Voltage ------------------------------------------------------------------------ CreateItem(GetSetting("S_DISPLAYVOLTAGE"), 5,0, G_Voltage); CreateItem(GetSetting("S_MAINVOLTAGE_VBAT"), 5,1*17, G_Voltage); CreateItem(GetSetting("S_DIVIDERRATIO"), 5,2*17, G_Voltage); CreateItem(GetSetting("S_BATCELLS"), 5,3*17, G_Voltage); CreateItem(GetSetting("S_VOLTAGEMIN"), 5,4*17, G_Voltage); confItem[GetSetting("S_VOLTAGEMIN")].setDecimalPrecision(1); confItem[GetSetting("S_VOLTAGEMIN")].setMultiplier(0.1f); // Amperage ------------------------------------------------------------------------ CreateItem(GetSetting("S_AMPERAGE"), 5,0, G_Amperage); CreateItem(GetSetting("S_AMPER_HOUR"), 5,1*17, G_Amperage); CreateItem(GetSetting("S_AMPERAGE_VIRTUAL"), 5,2*17, G_Amperage); CreateItem(GetSetting("S_MWAMPERAGE"), 5,3*17, G_Amperage); CreateItem(GetSetting("S_AMPDIVIDERRATIO"), 5,4*17, G_Amperage); CreateItem(GetSetting("S_AMPMIN"), 5, 5*17, G_Amperage); CreateItem(GetSetting("S_AMPER_HOUR_ALARM"), 5,6*17, G_Amperage); CreateItem(GetSetting("S_AMPERAGE_ALARM"), 5,7*17, G_Amperage); // Video Voltage ------------------------------------------------------------------------ CreateItem(GetSetting("S_VIDVOLTAGE"), 5,0, G_VVoltage); CreateItem(GetSetting("S_VIDVOLTAGE_VBAT"), 5,1*17, G_VVoltage); CreateItem(GetSetting("S_VIDDIVIDERRATIO"), 5,2*17, G_VVoltage); // Temperature -------------------------------------------------------------------- //CreateItem(GetSetting("S_DISPLAYTEMPERATURE"), 5,0, G_Alarms); //CreateItem(GetSetting("S_AMPERAGE_ALARM"), 5,1*17, G_Alarms); // Debug -------------------------------------------------------------------- CreateItem(GetSetting("S_DEBUG"), 5,0, G_Debug); // Board --------------------------------------------------------------------------- //CreateItem(GetSetting("S_BOARDTYPE"), 5,0, G_Board); //BuildRadioButton(GetSetting("S_BOARDTYPE"), 5,0, G_Board, "Rush","Minim"); // GPS ---------------------------------------------------------------------------- CreateItem(GetSetting("S_DISPLAYGPS"), 5,0, G_GPS); CreateItem(GetSetting("S_COORDINATES"), 5,1*17, G_GPS); CreateItem(GetSetting("S_GPSALTITUDE"), 5,2*17, G_GPS); CreateItem(GetSetting("S_MAPMODE"), 5,3*17, G_GPS); // HUD ---------------------------------------------------------------------------- CreateItem(GetSetting("S_HUD"), 5,0*17, G_HUD); CreateItem(GetSetting("S_HUDOSDSW"), 5,1*17, G_HUD); CreateItem(GetSetting("S_DISPLAY_HORIZON_BR"), 5,2*17, G_HUD); CreateItem(GetSetting("S_HORIZON_ELEVATION"), 5,3*17, G_HUD); CreateItem(GetSetting("S_WITHDECORATION"), 5,4*17, G_HUD); CreateItem(GetSetting("S_SCROLLING"), 5,5*17, G_HUD); CreateItem(GetSetting("S_SIDEBARTOPS"), 5,6*17, G_HUD); // VREF ---------------------------------------------------------------------------- CreateItem(GetSetting("S_VREFERENCE"), 5,0*17, G_VREF); // Compass --------------------------------------------------------------------------- CreateItem(GetSetting("S_COMPASS"), 5,0*17, G_COMPASS); CreateItem(GetSetting("S_SHOWHEADING"), 5,1*17, G_COMPASS); CreateItem(GetSetting("S_HEADING360"), 5,2*17, G_COMPASS); CreateItem(GetSetting("S_ANGLETOHOME"), 5,3*17, G_COMPASS); // Other --------------------------------------------------------------------------- CreateItem(GetSetting("S_UNITSYSTEM"), 5,0, G_Other); BuildRadioButton(GetSetting("S_UNITSYSTEM"), 5,0, G_Other, "Metric","Imperial"); CreateItem(GetSetting("S_VIDEOSIGNALTYPE"), 5,1*17, G_Other); BuildRadioButton(GetSetting("S_VIDEOSIGNALTYPE"), 5,1*17, G_Other, "NTSC","PAL"); CreateItem(GetSetting("S_THROTTLEPOSITION"), 5,2*17, G_Other); CreateItem(GetSetting("S_SHOWBATLEVELEVOLUTION"), 5,3*17, G_Other); CreateItem(GetSetting("S_RESETSTATISTICS"), 5,4*17, G_Other); // Display --------------------------------------------------------------------------- CreateItem(GetSetting("S_MODEICON"), 5,0*17, G_DISPLAY); CreateItem(GetSetting("S_MODESENSOR"), 5,1*17, G_DISPLAY); CreateItem(GetSetting("S_GIMBAL"), 5,2*17, G_DISPLAY); CreateItem(GetSetting("S_VARIO"), 5,3*17, G_DISPLAY); CreateItem(GetSetting("S_BAROALT"), 5,4*17, G_DISPLAY); CreateItem(GetSetting("S_TIMER"), 5,5*17, G_DISPLAY); // TIME ---------------------------------------------------------------------------- CreateItem(GetSetting("S_GPSTIME"), 5,0*17, G_TIME); CreateItem(GetSetting("S_GPSTZ"), 5,1*17, G_TIME); confItem[GetSetting("S_GPSTZ")].setMultiplier(0.5f);//30min increments, kathmandu would require 15min, it can use DST confItem[GetSetting("S_GPSTZ")].setDecimalPrecision(1); CreateItem(GetSetting("S_GPSTZAHEAD"), 5,2*17, G_TIME); // LINKS ---------------------------------------------------------------------------- buttonGUIDELINK = controlP5.addButton("GUIDELINK",1,110,10,80,16); buttonGUIDELINK.setCaptionLabel("User Guide").setGroup(G_LINKS); buttonFAQLINK = controlP5.addButton("FAQLINK",1,110,30,80,16); buttonFAQLINK.setCaptionLabel("FAQ").setGroup(G_LINKS); buttonCALIBLINK = controlP5.addButton("CALIBLINK",1,110,50,80,16); buttonCALIBLINK.setCaptionLabel("Calibration").setGroup(G_LINKS); buttonSUPPORTLINK = controlP5.addButton("SUPPORTLINK",1,110,70,80,16); buttonSUPPORTLINK.setCaptionLabel("Support").setGroup(G_LINKS); buttonGPSTIMELINK = controlP5.addButton("GPSTIMELINK",1,200,10,125,16); buttonGPSTIMELINK.setCaptionLabel("GPS Requirements").setGroup(G_LINKS); buttonSPORTLINK = controlP5.addButton("SPORTLINK",1,200,30,125,16); buttonSPORTLINK.setCaptionLabel("FRSKY Requirements").setGroup(G_LINKS); buttonDONATELINK = controlP5.addButton("DONATELINK",1,XLINKS+30,YLINKS+217, 80, 20).setVisible(false); // image(DONATEimage,XLINKS+20,YLINKS+207, 100, 40); // ALARMS ---------------------------------------------------------------------------- CreateItem(GetSetting("S_DISTANCE_ALARM"), 5,0*17, G_Alarms); CreateItem(GetSetting("S_ALTITUDE_ALARM"), 5,1*17, G_Alarms); CreateItem(GetSetting("S_SPEED_ALARM"), 5,2*17, G_Alarms); CreateItem(GetSetting("S_TIMER_ALARM"), 5,3*17, G_Alarms); // SPORT ---------------------------------------------------------------------------- // Call Sign --------------------------------------------------------------------------- CreateItem(GetSetting("S_DISPLAY_CS"), 5,0, G_CallSign); controlP5.addTextfield("CallSign") .setPosition(5,1*17) .setSize(105,15) .setFont(font10) .setAutoClear(false) .setLabel(" ") .setGroup(G_CallSign); ; controlP5.addTextlabel("TXTCallSign","",120,1*17) .setGroup(G_CallSign); CreateCS(GetSetting("S_CS0"), 0,0, G_CallSign); CreateCS(GetSetting("S_CS1"), 0,0, G_CallSign); CreateCS(GetSetting("S_CS2"), 0,0, G_CallSign); CreateCS(GetSetting("S_CS3"), 0,0, G_CallSign); CreateCS(GetSetting("S_CS4"), 0,0, G_CallSign); CreateCS(GetSetting("S_CS5"), 0,0, G_CallSign); CreateCS(GetSetting("S_CS6"), 0,0, G_CallSign); CreateCS(GetSetting("S_CS7"), 0,0, G_CallSign); CreateCS(GetSetting("S_CS8"), 0,0, G_CallSign); CreateCS(GetSetting("S_CS9"), 0,0, G_CallSign); for(int i=0;i<CONFIGITEMS;i++) { if (ConfigRanges[i] == 0) { toggleConfItem[i].hide(); confItem[i].hide(); } if (ConfigRanges[i] > 1) { try{ toggleConfItem[i].hide(); }catch(Exception e) { }finally { } } if (ConfigRanges[i] == 1){ confItem[i].hide(); } } //byte[] inBuf = new byte[256]; for (int txTimes = 0; txTimes<255; txTimes++) { inBuf[txTimes] = 0; } BuildToolHelp(); Font_Editor_setup(); SimSetup(); img_Clear = LoadFont(FontFileName); //toggleMSP_Data = true; CloseMode = 0; LoadConfig(); } public controlP5.Controller hideCheckbox(controlP5.Controller c) { c.hide(); //c.setLabelVisible(false); return c; } public controlP5.Controller CheckboxVisable(controlP5.Controller c) { c.isVisible(); //c.setLabelVisible(false); return c; } public void BuildRadioButton(int ItemIndex, int XLoction, int YLocation,Group inGroup, String Cap1, String Cap2){ RadioButtonConfItem[ItemIndex] = controlP5.addRadioButton("RadioButton"+ItemIndex) .setPosition(XLoction,YLocation+3) .setSize(10,10) .setNoneSelectedAllowed(false) //.setColorBackground(color(120)) //.setColorActive(color(255)) // .setColorLabel(color(255)) .setItemsPerRow(2) .setSpacingColumn(PApplet.parseInt(textWidth(Cap1))+10) .addItem("First"+ItemIndex,0) .addItem("Second"+ItemIndex,1) .toUpperCase(false) //.hideLabels() ; RadioButtonConfItem[ItemIndex].setGroup(inGroup); RadioButtonConfItem[ItemIndex].getItem(0).setCaptionLabel(Cap1); RadioButtonConfItem[ItemIndex].getItem(1).setCaptionLabel(Cap2 + " " + ConfigNames[ItemIndex]); toggleConfItem[ItemIndex].hide(); txtlblconfItem[ItemIndex].hide(); } public void CreateCS(int ItemIndex, int XLoction, int YLocation, Group inGroup){ //numberbox confItem[ItemIndex] = (controlP5.Numberbox) hideLabel(controlP5.addNumberbox("configItem"+ItemIndex,0,XLoction,YLocation,35,14)); confItem[ItemIndex].setMin(0); confItem[ItemIndex].setMax(255); confItem[ItemIndex].setDecimalPrecision(0); confItem[ItemIndex].setGroup(inGroup); confItem[ItemIndex].hide(); toggleConfItem[ItemIndex] = (controlP5.Toggle) hideLabel(controlP5.addToggle("toggleValue"+ItemIndex)); toggleConfItem[ItemIndex].hide(); } public void CreateItem(int ItemIndex, int XLoction, int YLocation, Group inGroup){ //numberbox confItem[ItemIndex] = (controlP5.Numberbox) hideLabel(controlP5.addNumberbox("configItem"+ItemIndex,0,XLoction,YLocation,35,14)); confItem[ItemIndex].setColorBackground(red_); confItem[ItemIndex].setMin(0); confItem[ItemIndex].setDirection(Controller.VERTICAL); confItem[ItemIndex].setMax(ConfigRanges[ItemIndex]); confItem[ItemIndex].setDecimalPrecision(0); confItem[ItemIndex].setGroup(inGroup); //confItem[ItemIndex].setMultiplier(10); //Toggle toggleConfItem[ItemIndex] = (controlP5.Toggle) hideLabel(controlP5.addToggle("toggleValue"+ItemIndex)); toggleConfItem[ItemIndex].setPosition(XLoction,YLocation+3); toggleConfItem[ItemIndex].setSize(35,10); toggleConfItem[ItemIndex].setMode(ControlP5.SWITCH); toggleConfItem[ItemIndex].setGroup(inGroup); //TextLabel txtlblconfItem[ItemIndex] = controlP5.addTextlabel("txtlblconfItem"+ItemIndex,ConfigNames[ItemIndex],XLoction+40,YLocation); txtlblconfItem[ItemIndex].setGroup(inGroup); //controlP5.getTooltip().register("txtlblconfItem"+ItemIndex,ConfigHelp[ItemIndex]); } public void BuildToolHelp(){ controlP5.getTooltip().setDelay(100); } public void MakePorts(){ if (PortWrite){ TXText.setColorValue(color(255,10,0)); } else { TXText.setColorValue(color(100,10,0)); } if (PortRead){ PortReadtimer=50+millis(); PortRead=false; } if (PortReadtimer>millis()) { PortRead=false; RXText.setColorValue(color(0,240,0)); } else { RXText.setColorValue(color(0,100,0)); } } public void draw() { // Initial setup time=millis(); progresstxt=""; if (commListbox.isOpen()) baudListbox.close(); else baudListbox.open(); // Process and outstanding Read or Write EEPROM requests if((millis()>ReadConfigMSPMillis)&(millis()>WriteConfigMSPMillis)&(init_com==1)) SimControlToggle.setValue(1); if (millis()<ReadConfigMSPMillis){ if (init_com==1){ READconfigMSP(); toggleMSP_Data = true; int progress=100*eeaddressGUI/CONFIGITEMS; progresstxt="Read: "+progress+"%"; } } if (millis()<WriteConfigMSPMillis){ if (init_com==1){ WRITEconfigMSP(); toggleMSP_Data = true; int progress=100*eeaddressGUI/(CONFIGITEMS + (hudoptions*2*2)); progresstxt="Write: "+progress+"%"; } } txtmessage.setValue(progresstxt); // Layout editor txtlblLayoutTxt.setValue(" : "+ CONFIGHUDTEXT[hudeditposition]); int hudid=0; if (toggleModeItems[9].getValue()>0) hudid = PApplet.parseInt(confItem[GetSetting("S_HUDOSDSW")].value()); else hudid = PApplet.parseInt(confItem[GetSetting("S_HUD")].value()); txtlblLayoutHudTxt.setValue(" : "+hudid); LEW.setLabel("Layout Editor for profile: "+hudid+" - "+CONFIGHUDNAME[hudid]); if (CONFIGHUDEN[hudid][hudeditposition]>0) txtlblLayoutEnTxt.setValue(" : Enabled"); else txtlblLayoutEnTxt.setValue(" : Disabled"); // Colour switches when enabled...... coloriseswitches(); if ((init_com==1) && (toggleMSP_Data == true)) { MWData_Com(); if (!FontMode) PortRead = false; MakePorts(); } else { PortRead = false; MakePorts(); } if ((SendSim ==1) && (ClosePort == false)) { if (!FontMode&&(ReadConfig==0)&&(WriteConfig==0)) { if (init_com==1) { if (ClosePort) return; if (SimControlToggle.getValue()==0) return; if (init_com==1)SendCommand(MSP_ATTITUDE); if (init_com==1)SendCommand(MSP_RC); if (init_com==1)SendCommand(MSP_STATUS); MSP_sendOrder++; switch(MSP_sendOrder) { case 1: if (init_com==1)SendCommand(MSP_BOXNAMES); if (init_com==1)SendCommand(MSP_BOXIDS); if (init_com==1)SendCommand(MSP_IDENT); break; case 2: if (init_com==1)SendCommand(MSP_ANALOG); if (init_com==1)SendCommand(MSP_COMP_GPS); break; case 3: if (init_com==1)SendCommand(MSP_ATTITUDE); break; case 4: if (init_com==1)SendCommand(MSP_RAW_GPS); break; case 5: if (init_com==1)SendCommand(MSP_ALTITUDE); //PortWrite = !PortWrite; break; case 6: if (init_com==1)SendCommand(MSP_CELLS); break; case 7: if ((init_com==1)&&(toggleMSP_Data == false)) SendCommand(MSP_BOXNAMES); break; case 8: if ((init_com==1)&&(toggleMSP_Data == false)) SendCommand(MSP_BOXIDS); break; case 9: if (init_com==1)SendCommand(MSP_NAV_STATUS); break; case 10: if (init_com==1)SendCommand(MSP_DEBUG); break; case 11: if (init_com==1)SendCommand(MSP_PID); MSP_sendOrder=0; break; } PortWrite = !PortWrite; // toggle TX LED every other } } // End !FontMode } else { if (!FontMode) PortWrite = false; } if ((FontMode) && (time-time2 >100)) { SendChar(); } MakePorts(); background(80); // ------------------------------------------------------------------------ // Draw background control boxes // ------------------------------------------------------------------------ image(GUIBackground,0, 0, windowsX, windowsY); if (LEWvisible==0){ image(DONATEimage,XLINKS+20,YLINKS+207, 100, 40); } strokeWeight(3);stroke(0); rectMode(CORNERS); image(OSDBackground,DisplayWindowX+WindowAdjX+10, DisplayWindowY+WindowAdjY, 354-WindowShrinkX, 300-WindowShrinkY); //529-WindowShrinkX, 360-WindowShrinkY); //################################################################################################################################################################################ // Display //################################################################################################################################################################################ for(int i = 0; i < (hudoptions); i++){ ConfigLayout[0][i]=CONFIGHUD[PApplet.parseInt(confItem[GetSetting("S_HUD")].value())][i]; ConfigLayout[1][i]=CONFIGHUD[PApplet.parseInt(confItem[GetSetting("S_HUDOSDSW")].value())][i]; int minimalscreen=0; if (toggleModeItems[9].getValue()>0) minimalscreen=1 ; if (minimalscreen==1){ SimPosn[i]=ConfigLayout[1][i]; } else { SimPosn[i]=ConfigLayout[0][i]; } if (SimPosn[i]<0x4000){ SimPosn[i]=0x3FF; } else{ SimPosn[i]=SimPosn[i]&0x3FF; } } if (PApplet.parseInt(confItem[GetSetting("S_DISPLAYRSSI")].value()) > 0) ShowRSSI(); if(confItem[GetSetting("S_DISPLAY_HORIZON_BR")].value() > 0) displayHorizon(PApplet.parseInt(MW_Pitch_Roll.arrayValue()[0])*10,PApplet.parseInt(MW_Pitch_Roll.arrayValue()[1])*10*-1); SimulateTimer(); CalcAlt_Vario(); ShowCurrentThrottlePosition(); if (PApplet.parseInt(confItem[GetSetting("S_DISPLAYRSSI")].value()) > 0) ShowRSSI(); if (PApplet.parseInt(confItem[GetSetting("S_DISPLAYVOLTAGE")].value()) > 0) ShowVolts(sVBat); ShowVideoVolts(sVBat); displaySensors(); displayMode(); ShowAmps(); ShowAltitude(); ShowCallsign(); ShownAngletohome(); ShowAmperage(); ShowVario(); ShowTemp(); ShowUTC(); displayHeadingGraph(); displayHeading(); ShowDebug(); ShowSideBarArrows(); ShowAPstatus(); if(confItem[GetSetting("S_DISPLAYGPS")].value() > 0) { ShowGPSAltitude(); ShowDistance(); ShowLatLon(); ShowSats(); ShowSpeed(); ShowDirection(); } ShowMapMode(); MatchConfigs(); MakePorts(); ShowSPort(); if ((ClosePort ==true)&& (PortWrite == false)){ //&& (init_com==1) ClosePort(); } //println("Display in text area"); } public int GetSetting(String test){ int TheSetting = 0; for (int i=0; i<Settings.values().length; i++) if (Settings.valueOf(test) == Settings.values()[i]){ TheSetting = Settings.values()[i].ordinal(); } return TheSetting; } public void ShowSimBackground(float[] a) { Showback = PApplet.parseInt(a[0]); } //void SimulateMultiWii(float[] a) { //} public void BuildCallSign(){ String CallSText = ""; for (int i=0; i<10; i++){ //confItem[GetSetting("S_CS0")+i].setValue(0); if (PApplet.parseInt(confItem[GetSetting("S_CS0")+i].getValue())>0){ CallSText+=PApplet.parseChar(PApplet.parseInt(confItem[GetSetting("S_CS0")+i].getValue())); } } controlP5.get(Textfield.class,"CallSign").setText(CallSText); } public void CheckCallSign() { // automatically receives results from controller input String CallSText = controlP5.get(Textfield.class,"CallSign").getText().toUpperCase(); controlP5.get(Textfield.class,"CallSign").setText(CallSText); //if (CallSText.length() >0){ if (CallSText.length() >10){ controlP5.get(Textfield.class,"CallSign").setText(CallSText.substring(0, 10)); CallSText = controlP5.get(Textfield.class,"CallSign").getText(); } for (int i=0; i<10; i++){ confItem[GetSetting("S_CS0")+i].setValue(0); } for (int i=0; i<CallSText.length(); i++){ confItem[(GetSetting("S_CS0"))+i].setValue(PApplet.parseInt(CallSText.charAt(i))); //println(int(CallSText.charAt(0))); //println(controlP5.get(Textfield.class,"CallSign").getText()); } //} } public void MatchConfigs(){ for(int i=0;i<CONFIGITEMS;i++) { try{ if (RadioButtonConfItem[i].isVisible()){ confItem[i].setValue(PApplet.parseInt(RadioButtonConfItem[i].getValue())); } }catch(Exception e) {}finally {} if (toggleConfItem[i].isVisible()){ if (PApplet.parseInt(toggleConfItem[i].getValue())== 1){ confItem[i].setValue(1); } else{ confItem[i].setValue(0); } } if (ConfigRanges[i] == 0) { toggleConfItem[i].hide(); //RadioButtonConfItem[i].hide(); confItem[i].hide(); } if (ConfigRanges[i] > 1) { toggleConfItem[i].hide(); } if (ConfigRanges[i] == 1){ confItem[i].hide(); } } // turn on FlyTimer---- if ((toggleModeItems[0].getValue() == 0) && (SimItem0 < 1)){ Armed = 1; FlyTimer = millis(); } // turn off FlyTimer---- if ((toggleModeItems[0].getValue() == 1 ) && (SimItem0 == 1)){ FlyTimer = 0; } } // controls comport list click public void controlEvent(ControlEvent theEvent) { try{ if (theEvent.isGroup()) if (theEvent.name()=="portComList") InitSerial(theEvent.group().value()); // initialize the serial port selected }catch(Exception e){ System.out.println("error with Port"); } if (theEvent.name()=="CallSign"){ CheckCallSign(); } if (theEvent.name()=="portBaudList"){ // BaudRate=200; if (init_com==1) ClosePort(); if (PApplet.parseInt(theEvent.group().value()) ==3) BaudRate=19200; else if (PApplet.parseInt(theEvent.group().value()) ==2) BaudRate=38400; else if (PApplet.parseInt(theEvent.group().value()) ==1) BaudRate=57600; else BaudRate=115200; // BaudRate=int(theEvent.group().value()); txtlblWhichbaud.setValue("Baud rate: "+str(BaudRate)); updateConfig(); baudListbox.close(); commListbox.open(); } try{ //for (int i=0;i<col.length;i++) { if ((theEvent.getController().getName().substring(0, 7).equals("CharPix")) && (theEvent.getController().isMousePressed())) { //println("Got a pixel " + theEvent.controller().id()); int ColorCheck = PApplet.parseInt(theEvent.getController().value()); curPixel = theEvent.controller().id(); } if ((theEvent.getController().getName().substring(0, 7).equals("CharMap")) && (theEvent.getController().isMousePressed())) { curChar = theEvent.controller().id(); //println("Got a Char " + theEvent.controller().id()); } } catch(ClassCastException e){} catch(StringIndexOutOfBoundsException se){} } public void mapchar(int address, int screenAddress){ int placeX = (screenAddress % 30) * 12; int placeY = (screenAddress / 30) * 18; blend(img_Clear, 0,address*18, 12, 18, placeX+DisplayWindowX, placeY+DisplayWindowY, 12, 18, BLEND); } public void makeText(String inString, int inStartAddress ){ for (int i = 0; i < inString.length(); i++){ mapchar(PApplet.parseInt(inString.charAt(i)), inStartAddress +i); } } public void displaySensors() { // mapchar(0xa0,sensorPosition[0]); // mapchar(0xa2,sensorPosition[0]+1); // mapchar(0xa1,sensorPosition[0]+2); /* if(MwSensorPresent&ACCELEROMETER) mapchar("0xa0",sensorPosition[0]); else ; if(MwSensorPresent&BAROMETER) screenBuffer[1]=0xa2; else screenBuffer[1]=' '; if(MwSensorPresent&MAGNETOMETER) screenBuffer[2]=0xa1; else screenBuffer[2]=' '; if(MwSensorPresent&GPSSENSOR) screenBuffer[3]=0xa3; else screenBuffer[3]=' '; screenBuffer[4]=0; MAX7456_WriteString(screenBuffer,sensorPosition[videoSignalType][screenType]); */ } /////////////////////////////////////////////////////////////////////////////////////////////////////////////////// BEGIN FILE OPS////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// public void bLUP() { int i = 0; if (toggleModeItems[9].getValue()>0) i = PApplet.parseInt(confItem[GetSetting("S_HUDOSDSW")].value()); else i = PApplet.parseInt(confItem[GetSetting("S_HUD")].value()); int ii = CONFIGHUD[i][hudeditposition]&0x1FF; ii-=30; ii=constrain(ii,0,419); println(ii); CONFIGHUD[i][hudeditposition]&=0xFE00; CONFIGHUD[i][hudeditposition]|=ii; } public void bLDOWN() { int i = 0; if (toggleModeItems[9].getValue()>0) i = PApplet.parseInt(confItem[GetSetting("S_HUDOSDSW")].value()); else i = PApplet.parseInt(confItem[GetSetting("S_HUD")].value()); int ii = CONFIGHUD[i][hudeditposition]&0x1FF; ii+=30; ii=constrain(ii,0,419); println(ii); CONFIGHUD[i][hudeditposition]&=0xFE00; CONFIGHUD[i][hudeditposition]|=ii; // CONFIGHUD[i][hudeditposition]+=30; } public void bLLEFT() { int i = 0; if (toggleModeItems[9].getValue()>0) i = PApplet.parseInt(confItem[GetSetting("S_HUDOSDSW")].value()); else i = PApplet.parseInt(confItem[GetSetting("S_HUD")].value()); int ii = CONFIGHUD[i][hudeditposition]&0x1FF; ii-=1; ii=constrain(ii,0,419); println(ii); CONFIGHUD[i][hudeditposition]&=0xFE00; CONFIGHUD[i][hudeditposition]|=ii; } public void bLRIGHT() { int i = 0; if (toggleModeItems[9].getValue()>0) i = PApplet.parseInt(confItem[GetSetting("S_HUDOSDSW")].value()); else i = PApplet.parseInt(confItem[GetSetting("S_HUD")].value()); int ii = CONFIGHUD[i][hudeditposition]&0x1FF; ii+=1; ii=constrain(ii,0,419); println(ii); CONFIGHUD[i][hudeditposition]&=0xFE00; CONFIGHUD[i][hudeditposition]|=ii; } public void bPOSLUP() { hudeditposition--; hudeditposition= constrain(hudeditposition,0,hudoptions-1); } public void bPOSLDOWN() { hudeditposition++; hudeditposition= constrain(hudeditposition,0,hudoptions-1); } public void bPOSLEN() { int i = 0; if (toggleModeItems[9].getValue()>0) i = PApplet.parseInt(confItem[GetSetting("S_HUDOSDSW")].value()); else i = PApplet.parseInt(confItem[GetSetting("S_HUD")].value()); if (CONFIGHUDEN[i][hudeditposition]>0){ CONFIGHUDEN[i][hudeditposition]=0; CONFIGHUD[i][hudeditposition]&=0x3FF; } else{ CONFIGHUDEN[i][hudeditposition]=1; CONFIGHUD[i][hudeditposition]|=0xC000; } } public void bLSAVE() { xmlsavelayout(); } public void bLCANCEL() { Lock_All_Controls(false); LEW.hide(); LEWvisible=0; G_LINKS.show(); initxml(); if (init_com==1) READconfigMSP_init(); } public void bLSET() { setset(); } public void bLADD() { addchild(); } public void bHUDLUP() { int hudid=0; if (toggleModeItems[9].getValue()>0) hudid = PApplet.parseInt(confItem[GetSetting("S_HUDOSDSW")].value()); else hudid = PApplet.parseInt(confItem[GetSetting("S_HUD")].value()); hudid--; hudid= constrain(hudid,0,hudsavailable-1); confItem[GetSetting("S_HUD")].setValue(hudid); confItem[GetSetting("S_HUDOSDSW")].setValue(hudid); } public void bHUDLDOWN() { int hudid=0; if (toggleModeItems[9].getValue()>0) hudid = PApplet.parseInt(confItem[GetSetting("S_HUDOSDSW")].value()); else hudid = PApplet.parseInt(confItem[GetSetting("S_HUD")].value()); hudid++; hudid= constrain(hudid,0,hudsavailable-1); confItem[GetSetting("S_HUD")].setValue(hudid); confItem[GetSetting("S_HUDOSDSW")].setValue(hudid); } //save the content of the model to a file public void bSAVE() { updateModel(); SwingUtilities.invokeLater(new Runnable(){ public void run() { final JFileChooser fc = new JFileChooser(dataPath("")) { private static final long serialVersionUID = 7919427933588163126L; public void approveSelection() { File f = getSelectedFile(); if (f.exists() && getDialogType() == SAVE_DIALOG) { int result = JOptionPane.showConfirmDialog(this, "The file exists, overwrite?", "Existing file", JOptionPane.YES_NO_CANCEL_OPTION); switch (result) { case JOptionPane.YES_OPTION: super.approveSelection(); return; case JOptionPane.CANCEL_OPTION: cancelSelection(); return; default: return; } } super.approveSelection(); } }; fc.setDialogType(JFileChooser.SAVE_DIALOG); fc.setFileFilter(new MwiFileFilter()); int returnVal = fc.showSaveDialog(null); if (returnVal == JFileChooser.APPROVE_OPTION) { File file = fc.getSelectedFile(); String filePath = file.getPath(); if(!filePath.toLowerCase().endsWith(".osd")){ file = new File(filePath + ".osd"); } FileOutputStream out =null; String error = null; try{ out = new FileOutputStream(file) ; MWI.conf.storeToXML(out, "MWOSD Configuration File " + new Date().toString()); JOptionPane.showMessageDialog(null,new StringBuffer().append("configuration saved : ").append(file.toURI()) ); }catch(FileNotFoundException e){ error = e.getCause().toString(); }catch( IOException ioe){ /*failed to write the file*/ ioe.printStackTrace(); error = ioe.getCause().toString(); }finally{ if (out!=null){ try{ out.close(); }catch( IOException ioe){/*failed to close the file*/error = ioe.getCause().toString();} } if (error !=null){ JOptionPane.showMessageDialog(null, new StringBuffer().append("error : ").append(error) ); } } } } } ); } public void updateModel(){ for(int j=0;j<ConfigNames.length;j++) { MWI.setProperty(ConfigNames[j],String.valueOf(confItem[j].value())); } } public void updateView(){ for(int j=0; j<ConfigNames.length; j++) { //confItem[j].setValue(int(MWI.getProperty(ConfigNames[j]))); if(j >= CONFIGITEMS) return; int value = PApplet.parseInt(MWI.getProperty(ConfigNames[j])); confItem[j].setValue(value); if (j == CONFIGITEMS-1){ //buttonWRITE.setColorBackground(green_); } if (value >0){ toggleConfItem[j].setValue(1); } else { toggleConfItem[j].setValue(0); } try{ switch(value) { case(0): RadioButtonConfItem[j].activate(0); break; case(1): RadioButtonConfItem[j].activate(1); break; } } catch(Exception e) {}finally {} } BuildCallSign(); } public class MwiFileFilter extends FileFilter { public boolean accept(File f) { if(f != null) { if(f.isDirectory()) { return true; } String extension = getExtension(f); if("osd".equals(extension)) { return true; } } return false; } public String getExtension(File f) { if(f != null) { String filename = f.getName(); int i = filename.lastIndexOf('.'); if(i>0 && i<filename.length()-1) { return filename.substring(i+1).toLowerCase(); } } return null; } public String getDescription() { return "*.osd MWOSD configuration file"; } } // import the content of a file into the model public void bIMPORT(){ SwingUtilities.invokeLater(new Runnable(){ public void run(){ final JFileChooser fc = new JFileChooser(dataPath("")); fc.setDialogType(JFileChooser.SAVE_DIALOG); fc.setFileFilter(new MwiFileFilter()); int returnVal = fc.showOpenDialog(null); if (returnVal == JFileChooser.APPROVE_OPTION) { File file = fc.getSelectedFile(); FileInputStream in = null; boolean completed = false; String error = null; try{ in = new FileInputStream(file) ; MWI.conf.loadFromXML(in); JOptionPane.showMessageDialog(null,new StringBuffer().append("configuration loaded : ").append(file.toURI()) ); completed = true; }catch(FileNotFoundException e){ error = e.getCause().toString(); }catch( IOException ioe){/*failed to read the file*/ ioe.printStackTrace(); error = ioe.getCause().toString(); }finally{ if (!completed){ // MWI.conf.clear(); // or we can set the properties with view values, sort of 'nothing happens' updateModel(); } updateView(); if (in!=null){ try{ in.close(); }catch( IOException ioe){/*failed to close the file*/} } if (error !=null){ JOptionPane.showMessageDialog(null, new StringBuffer().append("error : ").append(error) ); } } } } } ); } // our model static class MWI { private static Properties conf = new Properties(); public static void setProperty(String key ,String value ){ conf.setProperty( key,value ); } public static String getProperty(String key ){ return conf.getProperty( key,"0"); } public static void clear( ){ conf= null; // help gc conf = new Properties(); } } public void updateConfig(){ String error = null; FileOutputStream out =null; // ConfigClass.setProperty("StartFontFile",FontFileName); ConfigClass.setProperty("BaudRate",str(BaudRate)); ConfigClass.setProperty("Title",Title); ConfigClass.setProperty("Passthroughcomm",str(Passthroughcomm)); File file = new File(dataPath("gui.cfg")); try{ out = new FileOutputStream(file) ; ConfigClass.conf.storeToXML(out, "MW_OSD GUI Configuration File " + new Date().toString()); }catch(FileNotFoundException e){ error = e.getCause().toString(); }catch( IOException ioe){ /*failed to write the file*/ ioe.printStackTrace(); error = ioe.getCause().toString(); }finally{ if (out!=null){ try{ out.close(); }catch( IOException ioe){/*failed to close the file*/error = ioe.getCause().toString();} } if (error !=null){ JOptionPane.showMessageDialog(null, new StringBuffer().append("error : ").append(error) ); } } } public void LoadConfig(){ String error = null; FileInputStream in =null; BaudRate=0; try{ in = new FileInputStream(dataPath("gui.cfg")); } catch(FileNotFoundException e){ //System.out.println("Configuration Failed- Creating Default"); BaudRate = 115200; Title = MW_OSD_GUI_Version; Passthroughcomm = 0; updateConfig(); } catch( IOException ioe){ /*failed to write the file*/ ioe.printStackTrace(); error = ioe.getCause().toString(); }//finally{ if (in!=null){ try{ ConfigClass.conf.loadFromXML(in); BaudRate =PApplet.parseInt(ConfigClass.getProperty("BaudRate")); Title =ConfigClass.getProperty("Title"); Passthroughcomm = PApplet.parseInt(ConfigClass.getProperty("Passthroughcomm")); img_Clear = LoadFont(FontFileName); in.close(); } catch( IOException ioe){ /*failed to close the file*/error = ioe.getCause().toString();} } if (error !=null){ JOptionPane.showMessageDialog(null, new StringBuffer().append("error : ").append(error) ); } txtlblWhichbaud.setValue("Baud rate: "+str(BaudRate)); frame.setTitle(Title); if (Passthroughcomm !=0){ commListbox.addItem("Pass Thru Comm",commListMax+1); } } // our configuration static class ConfigClass { private static Properties conf = new Properties(); public static void setProperty(String key ,String value ){ conf.setProperty( key,value ); } public static String getProperty(String key ){ return conf.getProperty( key,"0"); } public static void clear( ){ conf= null; // help gc conf = new Properties(); } } public void mouseReleased() { mouseDown = false; mouseUp = true; if (curPixel>-1)changePixel(curPixel); if (curChar>-1)GetChar(curChar); ControlLock(); } public void mousePressed() { mouseDown = true; mouseUp = false; } public boolean mouseDown() { return mouseDown; } public boolean mouseUp() { return mouseUp; } public void SketchUploader(){ String ArduioLocal = ConfigClass.getProperty("ArduinoLocation"); if (ArduioLocal == "0"){ try { SwingUtilities.invokeAndWait(new Runnable(){ public void run(){ JFileChooser fc = new JFileChooser(); fc.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY); fc.setDialogType(JFileChooser.SAVE_DIALOG); fc.setDialogTitle("Select Arduino Folder"); //fc.setFileFilter(new FontFileFilter()); //fc.setCurrentDirectory(); int returnVal = fc.showOpenDialog(null); if (returnVal == JFileChooser.APPROVE_OPTION) { File ArduioFile = fc.getSelectedFile(); String ArduioLocal = ArduioFile.getPath(); ConfigClass.setProperty("ArduinoLocation",ArduioLocal); updateConfig(); String error = null; } } } ); } catch (Exception e) { } } toggleMSP_Data = false; //delay(1000); InitSerial(200.00f); updateConfig(); //if (init_com==1){ //init_com=0; //g_serial.stop(); //} super.exit(); } public void GPSTIMELINK(){ link("https://code.google.com/p/multiwii-osd/wiki/GPSTime"); } public void SPORTLINK(){ link("https://code.google.com/p/multiwii-osd/wiki/Frsky_SPort"); } public void CODELINK(){ link("https://code.google.com/p/multiwii-osd/"); } public void FAQLINK(){ link("https://code.google.com/p/multiwii-osd/wiki/FAQ"); } public void GUIDELINK(){ link("https://code.google.com/p/multiwii-osd/wiki/User_Guide"); } public void SUPPORTLINK(){ link("http://fpvlab.com/forums/showthread.php?34250-MWOSD-for-MULTIWII-NAZE32-BASEFLIGHT-HARIKIRI"); } public void DONATELINK(){ link("https://www.paypal.com/cgi-bin/webscr?cmd=_donations&business=EBS76N8F426G2&lc=GB&item_name=MW%2dOSD&item_number=R1%2e3&currency_code=GBP&bn=PP%2dDonationsBF%3abtn_donate_SM%2egif%3aNonHosted"); } public void CALIBLINK(){ link("https://code.google.com/p/multiwii-osd/wiki/Calibration"); } public void initxml(){ int value; int enabled; int hud; int hudindex; int xx; String text; String hudname; XML[] xmlhudconfig = xml.getChildren("CONFIG"); hudsavailable = xmlhudconfig[0].getInt("value"); XML[] xmlhuddescription = xml.getChildren("DESCRIPTION"); hudoptions = xmlhuddescription.length; XML[] xmlhudname = xml.getChildren("HUDNAME"); hudnamelength = xmlhudname.length; XML[] allhudoptions = xml.getChildren("LAYOUT"); // hudoptions = allhudoptions.length/hudsavailable; CONFIGHUD= new int[hudsavailable][hudoptions]; CONFIGHUDEN= new int[hudsavailable][hudoptions]; CONFIGHUDTEXT= new String[hudoptions]; CONFIGHUDNAME= new String[hudnamelength]; for (int i = 0; i < hudoptions; i++) { text = xmlhuddescription[i].getString("desc"); CONFIGHUDTEXT[i] = text; } for (int i = 0; i < hudnamelength; i++) { text = xmlhudname[i].getString("hudname"); CONFIGHUDNAME[i] = text; } for (int i = 0; i < allhudoptions.length; i++) { value = allhudoptions[i].getInt("value"); enabled = allhudoptions[i].getInt("enabled"); hud = allhudoptions[i].getInt("hud"); hudindex = i%hudoptions; if (enabled == 1) DISPLAY_STATE=0xC000; else DISPLAY_STATE=0x0000; CONFIGHUD[hud][hudindex] = value | DISPLAY_STATE; CONFIGHUDEN[hud][hudindex] = enabled; } SimPosn = new int[hudoptions]; ConfigLayout= new int[4][hudoptions]; ConfigRanges[GetSetting("S_HUD")] = hudsavailable-1; ConfigRanges[GetSetting("S_HUDOSDSW")] = hudsavailable-1; } public void xmlsavelayout(){ XML[] allhudoptions = xml.getChildren("LAYOUT"); int i=0; for (int hud = 0; hud < hudsavailable; hud++) { for (int hudindex = 0; hudindex < hudoptions; hudindex++) { allhudoptions[i].setInt("enabled",CONFIGHUDEN[hud][hudindex]); allhudoptions[i].setInt("value",CONFIGHUD[hud][hudindex]&0x3FF); i++; } } saveXML(xml, dataPath("hudlayout.xml")); initxml(); confItem[GetSetting("S_HUD")].setMax(ConfigRanges[GetSetting("S_HUD")]); confItem[GetSetting("S_HUDOSDSW")].setMax(ConfigRanges[GetSetting("S_HUDOSDSW")]); if (init_com==1) READconfigMSP_init(); } public void setset(){ toggleConfItem[GetSetting("S_DISPLAYRSSI")].setValue(1); toggleConfItem[GetSetting("S_DISPLAYVOLTAGE")].setValue(1); toggleConfItem[GetSetting("S_AMPERAGE")].setValue(1); toggleConfItem[GetSetting("S_AMPER_HOUR")].setValue(1); toggleConfItem[GetSetting("S_VIDVOLTAGE")].setValue(1); toggleConfItem[GetSetting("S_DISPLAYGPS")].setValue(1); toggleConfItem[GetSetting("S_COORDINATES")].setValue(1); toggleConfItem[GetSetting("S_GPSCOORDTOP")].setValue(1); toggleConfItem[GetSetting("S_GPSALTITUDE")].setValue(1); toggleConfItem[GetSetting("S_DISPLAY_HORIZON_BR")].setValue(1); toggleConfItem[GetSetting("S_HORIZON_ELEVATION")].setValue(1); toggleConfItem[GetSetting("S_WITHDECORATION")].setValue(1); toggleConfItem[GetSetting("S_SCROLLING")].setValue(1); toggleConfItem[GetSetting("S_SIDEBARTOPS")].setValue(1); toggleConfItem[GetSetting("S_COMPASS")].setValue(1); toggleConfItem[GetSetting("S_SHOWHEADING")].setValue(1); toggleConfItem[GetSetting("S_ANGLETOHOME")].setValue(1); toggleConfItem[GetSetting("S_COORDINATES")].setValue(1); toggleConfItem[GetSetting("S_THROTTLEPOSITION")].setValue(1); toggleConfItem[GetSetting("S_MODEICON")].setValue(1); toggleConfItem[GetSetting("S_MODESENSOR")].setValue(1); toggleConfItem[GetSetting("S_GIMBAL")].setValue(1); toggleConfItem[GetSetting("S_VARIO")].setValue(1); toggleConfItem[GetSetting("S_BAROALT")].setValue(1); toggleConfItem[GetSetting("S_TIMER")].setValue(1); toggleConfItem[GetSetting("S_GPSTIME")].setValue(1); toggleConfItem[GetSetting("S_DISPLAY_CS")].setValue(1); confItem[GetSetting("S_MAPMODE")].setValue(1); } public void addchild(){ int hudid=0; if (toggleModeItems[9].getValue()>0) hudid = PApplet.parseInt(confItem[GetSetting("S_HUDOSDSW")].value()); else hudid = PApplet.parseInt(confItem[GetSetting("S_HUD")].value()); for (int hudindex = 0; hudindex < hudoptions; hudindex++) { XML newChild = xml.addChild("LAYOUT"); newChild.setString("desc",CONFIGHUDTEXT[hudindex]); newChild.setInt("enabled",CONFIGHUDEN[hudid][hudindex]); newChild.setInt("hud",hudsavailable); newChild.setInt("value",CONFIGHUD[hudid][hudindex]&0x3FF); } XML[] xmlhudconfig = xml.getChildren("CONFIG"); xmlhudconfig[0].setInt("value",hudsavailable+1); XML newChild = xml.addChild("HUDNAME"); newChild.setString("hudname","Custom HUD "+hudsavailable); saveXML(xml, dataPath("hudlayout.xml")); initxml(); confItem[GetSetting("S_HUD")].setMax(ConfigRanges[GetSetting("S_HUD")]); confItem[GetSetting("S_HUDOSDSW")].setMax(ConfigRanges[GetSetting("S_HUDOSDSW")]); confItem[GetSetting("S_HUD")].setValue(hudsavailable-1); confItem[GetSetting("S_HUDOSDSW")].setValue(hudsavailable-1); } public void coloriseswitches(){ for(int i=0;i<CONFIGITEMS;i++) { if (toggleConfItem[i].getValue()==1) toggleConfItem[i].setColorActive(switches_); else toggleConfItem[i].setColorActive(red_); } if (SimControlToggle.getValue()==1) SimControlToggle.setColorActive(switches_); else SimControlToggle.setColorActive(red_); } public void LEW(){ // Lock_All_Controls(true); G_LINKS.hide(); LEW.show(); LEWvisible=1; // Lock_All_Controls(true); } public void READEEMSP(){ READconfigMSP_init(); } public void WRITEEEMSP(){ WRITEconfigMSP_init(); } public void mouseClicked(){ if ((mouseX>=(XLINKS+20)) && (mouseX<=(XLINKS+20+100)) && (mouseY>=(YLINKS+207)) && (mouseY<=(YLINKS+207+30))) DONATELINK(); } PImage FullFont; public boolean FontChanged = false; public boolean mouseDown = false; public boolean mouseUp = true; PImage PreviewChar; PImage[] CharImages = new PImage[256]; int row = 0; int gap = 5; int gapE = 1; int curPixel = -1; int curChar = -1; int editChar = -1; boolean mouseSet = false; int gray = color(120); int white = color(255); int black = color(0); // screen locations int XFullFont = 25; int YFullFont = 25; int XcharEdit = 5; int YcharEdit = 5; int PreviewX = 60; int PreviewY = 275; Bang CharBang[] = new Bang[256] ; Bang CharPixelsBang[] = new Bang[216] ; Bang PreviewCharBang; Textlabel CharTopLabel[] = new Textlabel[16] ; Textlabel CharSideLabel[] = new Textlabel[16] ; Textlabel LabelCurChar; Group FG,FGFull,FGCharEdit, FGPreview; Button buttonSendFile,buttonBrowseFile,buttonEditFont,buttonFClose,buttonFSave; public void Font_Editor_setup() { for (int i=0; i<256; i++) { CharImages[i] = createImage(12, 18, ARGB); } FG = FontGroupcontrolP5.addGroup("FG") .setPosition(150,50) .setWidth(680) .setBarHeight(12) .activateEvent(true) .setBackgroundColor(color(200,255)) .setBackgroundHeight(450) .setLabel("Font Editor") .setMoveable(true) .disableCollapse() .hide(); ; FGFull = FontGroupcontrolP5.addGroup("FGFull") .setPosition(20,20) .setWidth( 16*(12+gap)+ 25) .setBarHeight(12) .activateEvent(true) .hideBar() .setBackgroundColor(color(0,255)) .setBackgroundHeight(16*(18+gap)+35) .setLabel("Character List") .setMoveable(true) .setGroup(FG); ; FGCharEdit = FontGroupcontrolP5.addGroup("FGCharEdit") .setPosition(350,20) .setWidth( 12*(10+gapE)+ 33) .setBarHeight(12) .activateEvent(true) .hideBar() .setBackgroundColor(color(180,255)) .setBackgroundHeight(18*(10+gapE)+120) .setMoveable(true) .setGroup(FG); ; // RawFont = LoadFont("MW_OSD.mcm"); for (int i=0; i<256; i++) { int boxX = XFullFont+(i % 16) * (12+gap); int boxY = YFullFont + (i / 16) * (18+gap); CharBang[i] = FontGroupcontrolP5.addBang("CharMap"+i) .setPosition(boxX, boxY) .setSize(12, 18) .setLabel("") .setId(i) .setImages(CharImages[i], CharImages[i], CharImages[i], CharImages[i]) .setGroup(FGFull); ; } String[] CharRows = {"0","1","2","3","4","5","6","7","8","9","A","B","C","D","E","F"}; for (int i=0; i<16; i++) { int boxX = XFullFont-15; int boxY = YFullFont + i * (18+gap); CharSideLabel[i] = FontGroupcontrolP5.addTextlabel("charlabside" +i,CharRows[i],boxX ,boxY ) .setGroup(FGFull) .setColor(white); ; } for (int i=0; i<16; i++) { int boxX = XFullFont + i * (12+gap); int boxY = YFullFont-15; CharTopLabel[i] =FontGroupcontrolP5.addTextlabel("charlabtop" +i,CharRows[i],boxX ,boxY ) .setGroup(FGFull) .setColor(white); ; } for (int i=0; i<216; i++) { int boxX = XcharEdit+(i % 12) * (12+gapE); int boxY = YcharEdit + (i / 12) * (12+gapE); CharPixelsBang[i] = FontGroupcontrolP5.addBang("CharPix"+i) .setPosition(boxX, boxY) .setSize(12, 12) .setLabel("") .setId(i) .setColorBackground(gray) .setColorForeground(gray) .setValue(0) .setGroup(FGCharEdit) ; } LabelCurChar = FontGroupcontrolP5.addTextlabel("LabelCurChar","No Index Set" ,XcharEdit+ 10,YcharEdit + 18*(12+gapE)+5) .setColor(white) .setGroup(FGCharEdit); PreviewCharBang = FontGroupcontrolP5.addBang("PreviewCharBang") .setPosition(FGCharEdit.getWidth() / 2 -6, PreviewY) .setSize(12, 18) .setLabel("") //.setId(i) .setImages(PreviewChar, PreviewChar, PreviewChar, PreviewChar) .setGroup(FGCharEdit); ; buttonFSave = FontGroupcontrolP5.addButton("FSave",1,FGCharEdit.getWidth()-55, FGCharEdit.getBackgroundHeight()-25,45,18);//buttonFClose.setColorBackground(red_); buttonFSave.getCaptionLabel() .setFont(font12) .toUpperCase(false) .setText("SAVE"); buttonFSave.setGroup(FGCharEdit); buttonFClose = FontGroupcontrolP5.addButton("FCLOSE",1,680- 55 ,10,45,18);buttonFClose.setColorBackground(red_); buttonFClose.getCaptionLabel() .setFont(font12) .toUpperCase(false) .setText("CLOSE"); buttonFClose.setGroup(FG); MGUploadF = controlP5.addGroup("MGUploadF") .setPosition(XFONTTOOLS,YFONTTOOLS) .setWidth(110) .setBarHeight(15) .activateEvent(true) .setBackgroundColor(color(30,255)) .setBackgroundHeight(70) .setLabel(" Font Tools") .disableCollapse(); //.close() ; FileUploadText = controlP5.addTextlabel("FileUploadText","",10,5) .setGroup(MGUploadF) .setColorBackground(font_); buttonEditFont = controlP5.addButton("EditFont",1,20,45,60,16) .setColorBackground(font_) .setGroup(MGUploadF); buttonEditFont.getCaptionLabel() .setText("Edit Font"); buttonSendFile = controlP5.addButton("FONT_UPLOAD",1,20,25,60,16) .setColorBackground(font_) .setGroup(MGUploadF); buttonSendFile.getCaptionLabel() .setText("UPLOAD"); buttonBrowseFile = controlP5.addButton("Browse",1,20,5,60,16) .setColorBackground(font_) .setGroup(MGUploadF); buttonBrowseFile.getCaptionLabel() .setText(" SELECT") ; buttonSendFile.getCaptionLabel() .toUpperCase(false) .setText(" UPLOAD"); } public void Send(){ //sendFontFile(); //g_serial.clear(); //CreateFontFile(); } public void MakePreviewChar(){ PImage PreviewChar = createImage(12, 18, ARGB); PreviewChar.loadPixels(); for(int byteNo = 0; byteNo < 216; byteNo++) { switch(PApplet.parseInt(CharPixelsBang[byteNo].value())) { case 0: PreviewChar.pixels[byteNo] = gray; //CharImages[charNo].pixels[CharIndex] = gray; break; case 1: PreviewChar.pixels[byteNo] = black; //CharImages[charNo].pixels[CharIndex] = black; break; case 2: PreviewChar.pixels[byteNo] = white; //CharImages[charNo].pixels[CharIndex] = white; break; } } PreviewChar.updatePixels(); PreviewCharBang.setImages(PreviewChar, PreviewChar, PreviewChar, PreviewChar); } public void FSave(){ UpdateChar(); CreateFontFile(); } public void FCLOSE(){ Lock_All_Controls(false); FG.hide(); } public void EditFont(){ Lock_All_Controls(true); //setLock(ScontrolP5.getController("MwHeading"),true); FG.show(); Lock_All_Controls(true); } public void changePixel(int id){ if ((mouseUp) && (id > -1)){ int curColor = PApplet.parseInt(CharPixelsBang[id].value()); switch(curColor) { case 0: CharPixelsBang[id].setColorForeground(black); CharPixelsBang[id].setValue(1); FontChanged = true; //println("0"); break; case 1: CharPixelsBang[id].setColorForeground(white); CharPixelsBang[id].setValue(2); FontChanged = true; //println("1"); break; case 2: CharPixelsBang[id].setColorForeground(gray); CharPixelsBang[id].setValue(0); FontChanged = true; //println("2"); break; } } curPixel = -1; MakePreviewChar(); } public void GetChar(int id){ if ((mouseUp) && (id > -1)){ for(int byteNo = 0; byteNo < 216; byteNo++) { CharPixelsBang[byteNo].setColorForeground(gray); CharPixelsBang[byteNo].setValue(0); } for(int byteNo = 0; byteNo < 216; byteNo++) { switch(CharImages[id].pixels[byteNo]) { case 0xFF000000: CharPixelsBang[byteNo].setColorForeground(black); CharPixelsBang[byteNo].setValue(1); break; case 0xFFFFFFFF: CharPixelsBang[byteNo].setColorForeground(white); CharPixelsBang[byteNo].setValue(2); break; default: CharPixelsBang[byteNo].setColorForeground(gray); CharPixelsBang[byteNo].setValue(0); break; } } LabelCurChar.setValue(str(id)); LabelCurChar.setColorBackground(0); MakePreviewChar(); editChar = id; //LabelCurChar.update(); curChar = -1; } } public void UpdateChar(){ int changechar = Integer.parseInt(LabelCurChar.getStringValue()); CharImages[changechar].loadPixels(); for(int byteNo = 0; byteNo < 216; byteNo++) { switch(PApplet.parseInt(CharPixelsBang[byteNo].value())) { case 0: CharImages[changechar].pixels[byteNo] = gray; //CharImages[charNo].pixels[CharIndex] = gray; break; case 1: CharImages[changechar].pixels[byteNo] = black; //CharImages[charNo].pixels[CharIndex] = black; break; case 2: CharImages[changechar].pixels[byteNo] = white; //CharImages[charNo].pixels[CharIndex] = white; break; } } CharImages[changechar].updatePixels(); CharBang[changechar].setImages(CharImages[changechar], CharImages[changechar], CharImages[changechar], CharImages[changechar]); } public void setLock(Controller theController, boolean theValue) { theController.setLock(theValue); } public void Lock_All_Controls(boolean theLock){ //System.out.println(controlP5.getControllerList()); ControllerInterface[] sctrl = ScontrolP5.getControllerList(); for(int i=0; i<sctrl.length; ++i) { try{ setLock(ScontrolP5.getController(sctrl[i].getName()),theLock); }catch (NullPointerException e){} } ControllerInterface[] ctrl5 = controlP5.getControllerList(); for(int i=0; i<ctrl5.length; ++i) { try{ setLock(controlP5.getController(ctrl5[i].getName()),theLock); }catch (NullPointerException e){} } } public void Browse(){ SwingUtilities.invokeLater(new Runnable(){ public void run(){ final JFileChooser fc = new JFileChooser(dataPath("")); fc.setDialogType(JFileChooser.SAVE_DIALOG); fc.setFileFilter(new FontFileFilter()); //fc.setCurrentDirectory(); int returnVal = fc.showOpenDialog(null); if (returnVal == JFileChooser.APPROVE_OPTION) { File FontFile = fc.getSelectedFile(); FileInputStream in = null; boolean completed = false; String error = null; try{ in = new FileInputStream(FontFile) ; FontFileName = FontFile.getPath(); img_Clear = LoadFont(FontFileName); updateConfig(); JOptionPane.showMessageDialog(null,new StringBuffer().append("Font File loaded : ").append(FontFile.toURI()) ); completed = true; }catch(FileNotFoundException e){ error = e.getCause().toString(); }catch( IOException ioe){/*failed to read the file*/ ioe.printStackTrace(); error = ioe.getCause().toString(); }finally{ if (!completed){ // MWI.conf.clear(); // or we can set the properties with view values, sort of 'nothing happens' //updateModel(); } //updateView(); if (in!=null){ try{ in.close(); }catch( IOException ioe){/*failed to close the file*/} } if (error !=null){ JOptionPane.showMessageDialog(null, new StringBuffer().append("error : ").append(error) ); } } } } } ); } public class FontFileFilter extends FileFilter { public boolean accept(File f) { if(f != null) { if(f.isDirectory()) { return true; } String extension = getExtension(f); if("mcm".equals(extension)) { return true; } } return false; } public String getExtension(File f) { if(f != null) { String filename = f.getName(); int i = filename.lastIndexOf('.'); if(i>0 && i<filename.length()-1) { return filename.substring(i+1).toLowerCase(); } } return null; } public String getDescription() { return "*.mcm Font File"; } } public void SetupGroups(){ //G_EEPROM, //G_RSSI, // G_Voltage, //G_Amperage, // G_VVoltage, // G_Temperature, // G_GPS, // G_Other //.setColorForeground(color(30,255)) //.setColorBackground(color(30,255)) //.setColorLabel(color(0, 110, 220)) //.setColorValue(0xffff88ff) //.setColorActive(color(30,255)) G_PortStatus = FontGroupcontrolP5.addGroup("G_PortStatus") .setPosition(XPortStat,YPortStat) .setWidth(110) .setColorForeground(color(30,255)) .setColorBackground(color(30,255)) .setColorLabel(color(0, 110, 220)) .setBarHeight(15) .setBackgroundColor(color(30,255)) .setColorActive(red_) .setBackgroundHeight(60) .setLabel(" Port Status") .disableCollapse() ; TXText = FontGroupcontrolP5.addTextlabel("TXText","TX",65,5) .setColorValue(red_) .setGroup("G_PortStatus"); RXText = FontGroupcontrolP5.addTextlabel("RXText","RX",15,5) .setColorValue(green_) .setGroup("G_PortStatus"); OSD_CONTROLS = controlP5.addGroup("OSD_CONTROLS") .setPosition(XOSD_CONTROLS,YOSD_CONTROLS) .setWidth(110) .setBarHeight(15) .activateEvent(true) .setBackgroundColor(color(30,255)) .setBackgroundHeight(90) .setLabel(" OSD CONTROLS") .disableCollapse(); //.close() ; SAVE_LOAD = controlP5.addGroup("SAVE_LOAD") .setPosition(XSAVE_LOAD,YSAVE_LOAD) .setWidth(110) .setBarHeight(15) .activateEvent(true) .setBackgroundColor(color(30,255)) .setBackgroundHeight(47) .setLabel(" SETTINGS") .disableCollapse(); //.close() ; G_LINKS = controlP5.addGroup("G_LINKS") .setPosition(XLINKS,YLINKS) .setWidth(345) .setBarHeight(15) .activateEvent(true) .setBackgroundColor(color(30,255)) .setBackgroundHeight(104) .setLabel("LINKS") //.hide() .disableCollapse() ; G_EEPROM = GroupcontrolP5.addGroup("G_EEPROM") .setPosition(XEEPROM,YEEPROM+15) .setWidth(Col1Width) .setBarHeight(15) .setBackgroundColor(color(30,255)) .setColorForeground(color(30,255)) .setColorActive(red_) .setBackgroundHeight((1*17) +5) .setLabel("EEPROM") //.setGroup(SG) .disableCollapse() ; G_EEPROM.captionLabel() .toUpperCase(false) .align(controlP5.CENTER,controlP5.CENTER) ; G_EEPROM.hide(); G_RSSI = GroupcontrolP5.addGroup("G_RSSI") .setPosition(XRSSI,YRSSI+49) .setWidth(Col1Width) .setColorForeground(color(30,255)) .setColorBackground(color(30,255)) .setColorLabel(color(0, 110, 220)) .setBarHeight(15) .setBackgroundColor(color(30,255)) .setColorActive(red_) .setBackgroundHeight((6*17) +5) .setLabel("RSSI") //.setGroup(SG) .disableCollapse() ; G_RSSI.captionLabel() .toUpperCase(false) .align(controlP5.CENTER,controlP5.CENTER) ; // G_RSSI.setColorBackground(color(30,255)); G_Voltage = GroupcontrolP5.addGroup("G_Voltage") .setPosition(XVolts,YVolts+15) .setWidth(Col1Width) .setColorForeground(color(30,255)) .setColorBackground(color(30,255)) .setColorLabel(color(0, 110, 220)) .setBarHeight(15) .setBackgroundColor(color(30,255)) .setColorActive(red_) .setBackgroundHeight((5*17) +5) .setLabel("Main Voltage") //.setGroup(SG) .disableCollapse() ; G_Voltage.captionLabel() .toUpperCase(false) .align(controlP5.CENTER,controlP5.CENTER) ; G_Amperage = GroupcontrolP5.addGroup("G_Amperage") .setPosition(XAmps,YAmps+15) .setWidth(Col1Width) .setBarHeight(15) .setColorForeground(color(30,255)) .setColorBackground(color(30,255)) .setColorLabel(color(0, 110, 220)) .setBarHeight(15) .setBackgroundColor(color(30,255)) .setColorActive(red_) .setBackgroundHeight((8*17) +5) .setLabel("Amperage") //.setGroup(SG) .disableCollapse() ; G_Amperage.captionLabel() .toUpperCase(false) .align(controlP5.CENTER,controlP5.CENTER) ; G_VVoltage = GroupcontrolP5.addGroup("G_VVoltage") .setPosition(XVVolts,YVVolts+15) .setWidth(Col1Width) .setBarHeight(15) .setColorForeground(color(30,255)) .setColorBackground(color(30,255)) .setColorLabel(color(0, 110, 220)) .setBarHeight(15) .setBackgroundColor(color(30,255)) .setColorActive(red_) .setBackgroundHeight((3*17) +5) .setLabel("Video Voltage") //.setGroup(SG) .disableCollapse() ; G_VVoltage.captionLabel() .toUpperCase(false) .align(controlP5.CENTER,controlP5.CENTER) ; G_Alarms = GroupcontrolP5.addGroup("G_Alarms") .setPosition(XTemp,YTemp+13) .setWidth(Col3Width+10) .setBarHeight(15) .setColorForeground(color(30,255)) .setColorBackground(color(30,255)) .setColorLabel(color(0, 110, 220)) .setBarHeight(15) .setBackgroundColor(color(30,255)) .setColorActive(red_) .setBackgroundHeight((4*17) +5) .setLabel("Alarms") //.setGroup(SG) .disableCollapse() ; G_Alarms.captionLabel() .toUpperCase(false) .align(controlP5.CENTER,controlP5.CENTER) ; G_GPS = GroupcontrolP5.addGroup("G_GPS") .setPosition(XGPS,YGPS+16) .setWidth(Col3Width+10) .setBarHeight(16) .setColorForeground(color(30,255)) .setColorBackground(color(30,255)) .setColorLabel(color(0, 110, 220)) .setBarHeight(16) .setBackgroundColor(color(30,255)) .setColorActive(red_) .setBackgroundHeight((4*17) +5) .setLabel("GPS Settings") //.setGroup(SG) .disableCollapse() ; G_GPS.captionLabel() .toUpperCase(false) .align(controlP5.CENTER,controlP5.CENTER) ; G_Board= GroupcontrolP5.addGroup("G_Board") .hide() .setPosition(XBoard,YBoard+15) .setWidth(Col1Width) .setBarHeight(15) .setColorForeground(color(30,255)) .setColorBackground(color(30,255)) .setColorLabel(color(0, 110, 220)) .setBarHeight(15) .setBackgroundColor(color(30,255)) .setColorActive(red_) .setBackgroundHeight((1*17) +5) .setLabel("Board Type") //.setGroup(SG) .disableCollapse(); G_Board.captionLabel() .toUpperCase(false) .align(controlP5.CENTER,controlP5.CENTER) ; G_CallSign = GroupcontrolP5.addGroup("G_CallSign") .setPosition(XCS,YCS+49) .setWidth(Col1Width) .setBarHeight(15) .setColorForeground(color(30,255)) .setColorBackground(color(30,255)) .setColorLabel(color(0, 110, 220)) .setBarHeight(15) .setBackgroundColor(color(30,255)) .setColorActive(red_) .setBackgroundHeight((2*17) +5) .setLabel("Call Sign") //.setGroup(SG) .disableCollapse(); G_CallSign.captionLabel() .toUpperCase(false) .align(controlP5.CENTER,controlP5.CENTER) ; G_Other = GroupcontrolP5.addGroup("G_Other") .setPosition(XOther,YOther+15) .setWidth(Col2Width) .setBarHeight(15) .setColorForeground(color(30,255)) .setColorBackground(color(30,255)) .setColorLabel(color(0, 110, 220)) .setBarHeight(15) .setBackgroundColor(color(30,3255)) .setColorActive(red_) .setBackgroundHeight((5*17) +5) .setLabel("Other") //.setGroup(SG) .disableCollapse() ; G_Other.captionLabel() .toUpperCase(false) .align(controlP5.CENTER,controlP5.CENTER) ; G_DISPLAY = GroupcontrolP5.addGroup("G_DISPLAY") .setPosition(XDisplay,YDisplay+15) .setWidth(Col2Width) .setBarHeight(15) .setColorForeground(color(30,255)) .setColorBackground(color(30,255)) .setColorLabel(color(0, 110, 220)) .setBarHeight(15) .setBackgroundColor(color(30,3255)) .setColorActive(red_) .setBackgroundHeight((6*17) +5) .setLabel("Display") //.setGroup(SG) .disableCollapse() ; G_DISPLAY.captionLabel() .toUpperCase(false) .align(controlP5.CENTER,controlP5.CENTER) ; G_HUD = GroupcontrolP5.addGroup("G_HUD") .setPosition(XHUD,YHUD+15) .setWidth(Col2Width) .setBarHeight(15) .setColorForeground(color(30,255)) .setColorBackground(color(30,255)) .setColorLabel(color(0, 110, 220)) .setBarHeight(15) .setBackgroundColor(color(30,3255)) .setColorActive(red_) .setBackgroundHeight((7*17) +5) .setLabel("HUD") //.setGroup(G_LINKS) .disableCollapse() ; G_HUD.captionLabel() .toUpperCase(false) .align(controlP5.CENTER,controlP5.CENTER) ; G_COMPASS = GroupcontrolP5.addGroup("G_COMPASS") .setPosition(XCOMPASS,YCOMPASS+15) .setWidth(Col3Width+10) .setBarHeight(15) .setColorForeground(color(30,255)) .setColorBackground(color(30,255)) .setColorLabel(color(0, 110, 220)) .setBarHeight(15) .setBackgroundColor(color(30,3255)) .setColorActive(red_) .setBackgroundHeight((4*17) +5) .setLabel("Compass") //.setGroup(SG) .disableCollapse() ; G_COMPASS.captionLabel() .toUpperCase(false) .align(controlP5.CENTER,controlP5.CENTER) ; G_VREF = GroupcontrolP5.addGroup("G_VREF") .setPosition(XVREF,YVREF+49) .setWidth(Col1Width) .setBarHeight(15) .setColorForeground(color(30,255)) .setColorBackground(color(30,255)) .setColorLabel(color(0, 110, 220)) .setBarHeight(15) .setBackgroundColor(color(30,3255)) .setColorActive(red_) .setBackgroundHeight((1*17) +5) .setLabel("Reference Voltage") //.setGroup(SG) .disableCollapse() ; G_VREF.captionLabel() .toUpperCase(false) .align(controlP5.CENTER,controlP5.CENTER) ; G_TIME = GroupcontrolP5.addGroup("G_TIME") .setPosition(XTIME,YTIME+16) .setWidth(Col3Width+10) .setBarHeight(15) .setColorForeground(color(30,255)) .setColorBackground(color(30,255)) .setColorLabel(color(0, 110, 220)) .setBarHeight(16) .setBackgroundColor(color(30,255)) .setColorActive(red_) .setBackgroundHeight((3*17) +5) .setLabel("Time Settings") //.setGroup(SG) .disableCollapse() ; G_TIME.captionLabel() .toUpperCase(false) .align(controlP5.CENTER,controlP5.CENTER) ; G_INFO = GroupcontrolP5.addGroup("G_INFO") .setPosition(windowsX/2,windowsY/2) .setWidth(Col3Width+10) .setColorForeground(yellow_) // .setColorBackground(blue_) .setColorLabel(color(0, 110, 220)) .setBarHeight(0) .setBackgroundColor(blue_) .setColorActive(red_) .setBackgroundHeight((3*17) +5) .setLabel("") .hide() //.setGroup(SG) .disableCollapse() ; G_TIME.captionLabel() .toUpperCase(false) .align(controlP5.CENTER,controlP5.CENTER) ; /* G_SPORT = GroupcontrolP5.addGroup("G_SPORT") .setPosition(XSPORT,YSPORT) .setWidth(Col3Width+10) .setBarHeight(15) .setColorForeground(color(30,255)) .setColorBackground(color(30,255)) .setColorLabel(color(0, 110, 220)) .setBarHeight(16) .setBackgroundColor(color(30,255)) .setColorActive(red_) .setBackgroundHeight((1*17) +5) .setLabel("FrSky S.Port Data in OSD") //.setGroup(SG) .disableCollapse() ; G_SPORT.captionLabel() .toUpperCase(false) .align(controlP5.CENTER,controlP5.CENTER) ; */ G_Debug = GroupcontrolP5.addGroup("G_Debug") // .setPosition(5,250) .setPosition(693,541) .setWidth(130) .setBarHeight(15) .activateEvent(true) .disableCollapse() .setBackgroundColor(color(30,255)) .setColorActive(red_) .setBackgroundHeight(33) .setLabel("Debug") // .setGroup(SG) ; G_Debug.captionLabel() .toUpperCase(false) .align(controlP5.CENTER,controlP5.CENTER) ; } public boolean toggleRead = false, toggleMSP_Data = true, toggleReset = false, toggleCalibAcc = false, toggleCalibMag = false, toggleWrite = false, toggleSpekBind = false, toggleSetSetting = false; Serial g_serial; // The serial port float LastPort = 0; int time,time1,time2,time3,time4,time5; boolean ClosePort = false; boolean PortIsWriting = false; boolean FontMode = false; int FontCounter = 0; //int cindex = 0; int CloseMode = 0; /******************************* Multiwii Serial Protocol **********************/ //String boxnames[] = { // names for dynamic generation of config GUI //"ANGLE;", //"HORIZON;", //"BARO;", //"MAG;", //"ARM;", //"LLIGHTS;", //"GPS HOME;", // "GPS HOLD;", // "OSD SW;", //}; String boxnames[] = { // names for dynamic generation of config GUI "ARM;", "ANGLE;", "HORIZON;", "BARO;", "MAG;", "CAMSTAB;", "GPS HOME;", "GPS HOLD;", "MISSION;", "OSD SW;" }; String strBoxNames = join(boxnames,""); //int modebits = 0; private static final String MSP_HEADER = "$M<"; private static final int MSP_IDENT =100, MSP_STATUS =101, MSP_RAW_IMU =102, MSP_SERVO =103, MSP_MOTOR =104, MSP_RC =105, MSP_RAW_GPS =106, MSP_COMP_GPS =107, MSP_ATTITUDE =108, MSP_ALTITUDE =109, MSP_ANALOG =110, MSP_RC_TUNING =111, MSP_PID =112, MSP_BOX =113, MSP_MISC =114, MSP_MOTOR_PINS =115, MSP_BOXNAMES =116, MSP_PIDNAMES =117, MSP_BOXIDS =119, MSP_RSSI =120, MSP_NAV_STATUS =121, MSP_CELLS =130, MSP_SET_RAW_RC =200, MSP_SET_RAW_GPS =201, MSP_SET_PID =202, MSP_SET_BOX =203, MSP_SET_RC_TUNING =204, MSP_ACC_CALIBRATION =205, MSP_MAG_CALIBRATION =206, MSP_SET_MISC =207, MSP_RESET_CONF =208, MSP_SELECT_SETTING =210, MSP_SPEK_BIND =240, MSP_PASSTHRU_SERIAL =244, MSP_EEPROM_WRITE =250, MSP_DEBUGMSG =253, MSP_DEBUG =254; private static final int MSP_OSD =220; // Subcommands private static final int OSD_NULL =0, OSD_READ_CMD =1, OSD_WRITE_CMD =2, OSD_GET_FONT =3, OSD_SERIAL_SPEED =4, OSD_RESET =5, OSD_DEFAULT =6, OSD_WRITE_CMD_EE =8, OSD_READ_CMD_EE =9; // initialize the serial port selected in the listBox public void InitSerial(float portValue) { if (portValue < commListMax) { if(init_com == 0){ try{ String portPos = Serial.list()[PApplet.parseInt(portValue)]; txtlblWhichcom.setValue("COM = " + shortifyPortName(portPos, 8)); g_serial = new Serial(this, portPos, BaudRate); LastPort = portValue; init_com=1; toggleMSP_Data = true; ClosePort = false; buttonREAD.setColorBackground(green_); buttonRESET.setColorBackground(green_); commListbox.setColorBackground(green_); buttonRESTART.setColorBackground(green_); g_serial.buffer(512); txtmessage.setText(""); // delay(1500); SendCommand(MSP_IDENT); SendCommand(MSP_STATUS); eeaddressGUI=0; ReadConfigMSPMillis=20000+millis(); READconfigMSP_init(); } catch (Exception e) { // null pointer or serial port dead noLoop(); JOptionPane.showConfirmDialog(null,"Error Opening Port It may be in Use", "Port Error", JOptionPane.PLAIN_MESSAGE,JOptionPane.WARNING_MESSAGE); loop(); System.out.println("OpenPort error " + e); } //+((int)(cmd&0xFF))+": "+(checksum&0xFF)+" expected, got "+(int)(c&0xFF)); } } else if(portValue > commListMax && init_com == 1){ if (Passthroughcomm==1) { System.out.println("Serial Port Pass Through Starting" ); SendCommand(MSP_PASSTHRU_SERIAL); delay(1000); SendCommand(MSP_IDENT); SendCommand(MSP_STATUS); READconfigMSP_init(); } } else { if(init_com == 1){ // System.out.println("Begin Port Down " ); txtlblWhichcom.setValue("Comm Closed"); //g_serial.clear(); toggleMSP_Data = false; ClosePort = true; init_com=0; } } SimControlToggle.setValue(0); } public void ClosePort(){ init_com=0; g_serial.clear(); g_serial.stop(); //System.out.println("Port Turned Off " ); init_com=0; commListbox.setColorBackground(red_); buttonREAD.setColorBackground(osdcontr_); buttonRESET.setColorBackground(osdcontr_); buttonWRITE.setColorBackground(osdcontr_); buttonRESTART.setColorBackground(osdcontr_); if (CloseMode > 0){ InitSerial(LastPort); CloseMode = 0; } } public void SetConfigItem(int index, int value) { if(index >= CONFIGITEMS) return; if(index == GetSetting("S_VOLTAGEMIN"))confItem[index].setValue(PApplet.parseFloat(value)/10);//preserve decimal else if(index == GetSetting("S_GPSTZ"))confItem[index].setValue(PApplet.parseFloat(value)/10);//preserve decimal, maybe can go elsewhere - haydent else confItem[index].setValue(value); if (index == CONFIGITEMS-1) buttonWRITE.setColorBackground(green_); if (value >0){ toggleConfItem[index].setValue(1); } else{ toggleConfItem[index].setValue(0); } try{ switch(value) { case(0): RadioButtonConfItem[index].activate(0); break; case(1): RadioButtonConfItem[index].activate(1); break; } } catch(Exception e) { }finally { } BuildCallSign(); } public void PORTCLOSE(){ toggleMSP_Data = false; CloseMode = 0; InitSerial(200.00f); } public void BounceSerial(){ toggleMSP_Data = false; CloseMode = 1; InitSerial(200.00f); } public void RESTART(){ toggleMSP_Data = true; for (int txTimes = 0; txTimes<3; txTimes++) { headSerialReply(MSP_OSD, 1); serialize8(OSD_RESET); tailSerialReply(); delay(100); } toggleMSP_Data = false; READconfigMSP_init(); // READinit(); // eeaddressGUI=0; // ReadConfigMSPMillis=20000+millis(); } public void WRITEinit(){ WriteConfig=20; ReadConfig=1; SimControlToggle.setValue(0); readerror=1; CheckCallSign(); S16_AMPMAX = PApplet.parseInt(confItem[GetSetting("S_AMPDIVIDERRATIO")].value()); confItem[GetSetting("S_AMPMAXL")].setValue(PApplet.parseInt(confItem[GetSetting("S_AMPDIVIDERRATIO")].value())&0xFF); // for 8>>16 bit EEPROM confItem[GetSetting("S_AMPMAXH")].setValue(PApplet.parseInt(confItem[GetSetting("S_AMPDIVIDERRATIO")].value())>>8); for(int i = 0; i < CONFIGITEMS; i++){ readcheck[i]=PApplet.parseInt(confItem[i].value()); } readcheck[GetSetting("S_AMPDIVIDERRATIO")]=0; } public void WRITEconfig(){ readerror=1; SimControlToggle.setValue(0); CheckCallSign(); PortWrite = true; MakePorts(); toggleMSP_Data = true; p = 0; inBuf[0] = OSD_WRITE_CMD; g_serial.clear(); for(int ii = 1; ii < CONFIGITEMS; ii++){ if (ii != GetSetting("S_AMPDIVIDERRATIO")); SetConfigItem(ii,readcheck[ii]); } for (int txTimes = 0; txTimes<1; txTimes++) { headSerialReply(MSP_OSD, CONFIGITEMS + (hudoptions*2*2) +1); serialize8(OSD_WRITE_CMD); for(int i = 0; i < CONFIGITEMS; i++){ if(i == GetSetting("S_VOLTAGEMIN")){ serialize8(PApplet.parseInt(confItem[i].value()*10));//preserve decimal } else if(i == GetSetting("S_GPSTZ")){ serialize8(PApplet.parseInt(confItem[i].value()*10));//preserve decimal, maybe can go elsewhere - haydent } else if(i == GetSetting("S_AMPDIVIDERRATIO")){ serialize8(0); } else{ serialize8(PApplet.parseInt(confItem[i].value())); } } int clayout=PApplet.parseInt(confItem[GetSetting("S_HUD")].value()); for(int i = 0; i < (hudoptions); i++){ serialize8(PApplet.parseInt(ConfigLayout[0][i]&0xFF)); serialize8(PApplet.parseInt(ConfigLayout[0][i]>>8)); } for(int i = 0; i < (hudoptions); i++){ serialize8(PApplet.parseInt(ConfigLayout[1][i]&0xFF)); serialize8(PApplet.parseInt(ConfigLayout[1][i]>>8)); } tailSerialReply(); } toggleMSP_Data = false; g_serial.clear(); PortWrite = false; } public void FONT_UPLOAD(){ if (init_com==0){ noLoop(); JOptionPane.showConfirmDialog(null,"Please Select a Port", "Not Connected", JOptionPane.PLAIN_MESSAGE,JOptionPane.WARNING_MESSAGE); loop(); }else { SimControlToggle.setValue(0); // System.out.println("FONT_UPLOAD"); //toggleMSP_Data = true; FontMode = true; PortWrite = true; MakePorts(); FontCounter = 0; txtmessage.setText(" Please Wait"); p = 0; inBuf[0] = OSD_GET_FONT; //for (int txTimes = 0; txTimes<2; txTimes++) { headSerialReply(MSP_OSD, 5); serialize8(OSD_GET_FONT); serialize16(7456); // safety code serialize8(0); // first char serialize8(255); // last char tailSerialReply(); //} } } public void SendChar(){ time2=time; PortWrite = !PortWrite; // toggle PortWrite to flash TX if (PortWrite) txtmessage.setText("Please wait...."); else txtmessage.setText(""); MakePorts(); // System.out.println("Sent Char "+FontCounter); buttonSendFile.getCaptionLabel().setText(" " +nf(FontCounter, 3)+"/256"); headSerialReply(MSP_OSD, 56); serialize8(OSD_GET_FONT); for(int i = 0; i < 54; i++){ serialize8(PApplet.parseInt(raw_font[FontCounter][i])); } serialize8(FontCounter); tailSerialReply(); if (FontCounter <255){ FontCounter++; }else{ g_serial.clear(); PortWrite = false; FontMode = false; // System.out.println("Finished Uploading Font"); buttonSendFile.getCaptionLabel().setText(" Upload"); txtmessage.setText(""); READconfigMSP_init(); // READinit(); ReadConfig=100; RESTART(); } } public void DEFAULT(){ if (init_com==1){ // toggleConfItem[0].setValue(0); noLoop(); int Reset_result = JOptionPane.showConfirmDialog(this,"Are you sure you wish to set OSD to DEFAULT values?", "RESET OSD MEMORY",JOptionPane.WARNING_MESSAGE,JOptionPane.YES_NO_CANCEL_OPTION); loop(); switch (Reset_result) { case JOptionPane.YES_OPTION: toggleMSP_Data = true; for (int txTimes = 0; txTimes<3; txTimes++) { headSerialReply(MSP_OSD, 1); serialize8(OSD_DEFAULT); tailSerialReply(); delay(100); } toggleMSP_Data = false; // READinit(); READconfigMSP_init(); // delay(2000); ReadConfig=100; return; case JOptionPane.CANCEL_OPTION: // SimControlToggle.setValue(1); return; default: // SimControlToggle.setValue(1); return; } }else { noLoop(); JOptionPane.showConfirmDialog(null,"Please Select a Port", "Not Connected", JOptionPane.PLAIN_MESSAGE,JOptionPane.WARNING_MESSAGE); loop(); } } public void SendCommand(int cmd){ //int icmd = (int)(cmd&0xFF); switch(cmd) { case MSP_STATUS: PortIsWriting = true; Send_timer+=1; headSerialReply(MSP_STATUS, 11); serialize16(Send_timer); serialize16(0); serialize16(1|1<<1|1<<2|1<<3|0<<4); int modebits = 0; int BitCounter = 1; if(toggleModeItems[0].getValue()> 0) modebits |=1<<0; if(toggleModeItems[1].getValue()> 0) modebits |=1<<1; if(toggleModeItems[2].getValue()> 0) modebits |=1<<2; if(toggleModeItems[3].getValue()> 0) modebits |=1<<3; if(toggleModeItems[4].getValue()> 0) modebits |=1<<5; if(toggleModeItems[5].getValue()> 0) modebits |=1<<8; if(toggleModeItems[6].getValue()> 0) modebits |=1<<10; if(toggleModeItems[7].getValue()> 0) modebits |=1<<11; if(toggleModeItems[8].getValue()> 0) modebits |=1<<20; if(toggleModeItems[9].getValue()> 0) modebits |=1<<19; // if(toggleModeItems[8].getValue()> 0) modebits |=1<<16; //Also send LLIGHTS when OSD enabled - for testing // if(toggleModeItems[5].getValue()> 0) modebits |=1<<12; //Also send PASS when CAMSTAB enabled - for testing serialize32(modebits); serialize8(0); // current setting tailSerialReply(); PortIsWriting = false; break; case MSP_RC: PortIsWriting = true; headSerialReply(MSP_RC, 14); serialize16(PApplet.parseInt(Pitch_Roll.arrayValue()[0])); serialize16(PApplet.parseInt(Pitch_Roll.arrayValue()[1])); serialize16(PApplet.parseInt(Throttle_Yaw.arrayValue()[0])); serialize16(PApplet.parseInt(Throttle_Yaw.arrayValue()[1])); for (int i=5; i<8; i++) { serialize16(1500); } tailSerialReply(); PortIsWriting = false; break; case MSP_IDENT: PortIsWriting = true; headSerialReply(MSP_IDENT, 7); serialize8(101); // multiwii version serialize8(0); // type of multicopter serialize8(0); // MultiWii Serial Protocol Version serialize32(0); // "capability" tailSerialReply(); PortIsWriting = false; break; case MSP_PASSTHRU_SERIAL: PortIsWriting = true; serialize8('$'); serialize8('M'); serialize8('<');//this is the important bit outChecksum = 0; // start calculating a new checksum serialize8(1); serialize8(MSP_PASSTHRU_SERIAL); serialize8(0); tailSerialReply(); PortIsWriting = false; break; case MSP_CELLS: PortIsWriting = true; headSerialReply(MSP_CELLS, 12); if (SFRSKY.arrayValue()[0]<1) break; if (PApplet.parseInt(confItem[GetSetting("S_BATCELLS")].value()) <1) break; int cellvolt= (PApplet.parseInt(sVBat * 100))/PApplet.parseInt(confItem[GetSetting("S_BATCELLS")].value()); for (int i=0; i<6; i++) { if (i < PApplet.parseInt(confItem[GetSetting("S_BATCELLS")].value())) { serialize16(cellvolt); } else { serialize16(0); } } tailSerialReply(); PortIsWriting = false; break; case MSP_BOXNAMES: PortIsWriting = true; headSerialReply(MSP_BOXNAMES,strBoxNames.length()); serializeNames(strBoxNames.length()); tailSerialReply(); PortIsWriting = false; break; case MSP_BOXIDS: PortIsWriting = true; headSerialReply(MSP_BOXIDS,23); for (int i=0; i<23; i++) { serialize8(i); } tailSerialReply(); PortIsWriting = false; break; case MSP_ATTITUDE: PortIsWriting = true; headSerialReply(MSP_ATTITUDE, 8); serialize16(PApplet.parseInt(MW_Pitch_Roll.arrayValue()[0])*10); serialize16(PApplet.parseInt(MW_Pitch_Roll.arrayValue()[1])*10); serialize16(MwHeading); serialize16(0); tailSerialReply(); PortIsWriting = false; break; case MSP_DEBUG: PortIsWriting = true; headSerialReply(MSP_DEBUG, 8); //for (int i = 0; i < 4; i++) { // debug[i]++; //} serialize16(debug[0]); serialize16(debug[1]); serialize16(debug[2]); serialize16(debug[3]); tailSerialReply(); PortIsWriting = false; break; case MSP_PID: int PIDITEMS = 10; PortIsWriting = true; headSerialReply(MSP_PID, 10*3); for(int i=0; i<PIDITEMS; i++) { for(int ii=0; ii<3; ii++) { int pidval=PApplet.parseInt(i*10)+ii; serialize8(pidval); } } tailSerialReply(); PortIsWriting = false; break; case MSP_ANALOG: PortIsWriting = true; headSerialReply(MSP_ANALOG, 5); serialize8(PApplet.parseInt(sVBat * 10)); serialize16(0); serialize16(PApplet.parseInt(sMRSSI)); tailSerialReply(); PortIsWriting = false; break; case MSP_NAV_STATUS: PortIsWriting = true; headSerialReply(MSP_NAV_STATUS, 7); if (millis()>oldwpmillis+1500){ oldwpmillis=millis(); wpno++; if (wpno>15) wpno=0; } serialize8(0); serialize8(0); serialize8(0); serialize8(wpno); serialize8(0); serialize8(0); serialize8(0); tailSerialReply(); PortIsWriting = false; break; case MSP_RAW_GPS: // We have: GPS_fix(0-2), GPS_numSat(0-15), GPS_coord[LAT & LON](signed, in 1/10 000 000 degres), GPS_altitude(signed, in meters) and GPS_speed(in cm/s) headSerialReply(MSP_RAW_GPS,16); serialize8(PApplet.parseInt(SGPS_FIX.arrayValue()[0])); serialize8(PApplet.parseInt(SGPS_numSat.value())); serialize32(430948610); serialize32(-718897060); serialize16(PApplet.parseInt(SGPS_altitude.value()/100)); serialize16(PApplet.parseInt(SGPS_speed.value())); serialize16(MwHeading*10); break; case MSP_COMP_GPS: if(confItem[GetSetting("S_GPSTIME")].value()>0) headSerialReply(MSP_COMP_GPS,9); else headSerialReply(MSP_COMP_GPS,5); serialize16(PApplet.parseInt(SGPS_distanceToHome.value())); int GPSheading = PApplet.parseInt(SGPSHeadHome.value()); if(GPSheading < 0) GPSheading += 360; serialize16(GPSheading); serialize8(0); if(confItem[GetSetting("S_GPSTIME")].value()>0) { int osdtime=hour()*3600+minute()*60+second(); osdtime = osdtime*1000; serialize32(osdtime); } break; case MSP_ALTITUDE: headSerialReply(MSP_ALTITUDE, 6); serialize32(PApplet.parseInt(sAltitude) *100); serialize16(PApplet.parseInt(sVario) *10); break; } tailSerialReply(); } // coded by Eberhard Rensch // Truncates a long port name for better (readable) display in the GUI public String shortifyPortName(String portName, int maxlen) { String shortName = portName; if(shortName.startsWith("/dev/")) shortName = shortName.substring(5); if(shortName.startsWith("tty.")) shortName = shortName.substring(4); // get rid of leading tty. part of device name if(portName.length()>maxlen) shortName = shortName.substring(0,(maxlen-1)/2) + "~" +shortName.substring(shortName.length()-(maxlen-(maxlen-1)/2)); if(shortName.startsWith("cu.")) shortName = "";// only collect the corresponding tty. devices return shortName; } public static final int IDLE = 0, HEADER_START = 1, HEADER_M = 2, HEADER_ARROW = 3, HEADER_SIZE = 4, HEADER_CMD = 5, HEADER_ERR = 6; private static final String MSP_SIM_HEADER = "$M>"; int c_state = IDLE; boolean err_rcvd = false; byte checksum=0; byte cmd = 0; int offset=0, dataSize=0; byte[] inBuf = new byte[256]; int Send_timer = 1; int p=0; public int read32() {return (inBuf[p++]&0xff) + ((inBuf[p++]&0xff)<<8) + ((inBuf[p++]&0xff)<<16) + ((inBuf[p++]&0xff)<<24); } public int read16() {return (inBuf[p++]&0xff) + ((inBuf[p++])<<8); } public int read8() {return inBuf[p++]&0xff;} int outChecksum; public void serialize8(int val) { if (init_com==1) { //if(str(val)!=null){ try{ g_serial.write(val); outChecksum ^= val; } catch(java.lang.Throwable t) { System.out.println( t.getClass().getName() ); //this'll tell you what class has been thrown t.printStackTrace(); //get a stack trace } //} } } public void serialize16(int a) { if (str(a)!=null ){ serialize8((a ) & 0xFF); serialize8((a>>8) & 0xFF); } } public void serialize32(int a) { if (str(a)!=null ){ serialize8((a ) & 0xFF); serialize8((a>> 8) & 0xFF); serialize8((a>>16) & 0xFF); serialize8((a>>24) & 0xFF); } } public void serializeNames(int s) { //for (PGM_P c = s; pgm_read_byte(c); c++) { // serialize8(pgm_read_byte(c)); //} for (int c = 0; c < strBoxNames.length(); c++) { serialize8(strBoxNames.charAt(c)); } } public void headSerialResponse(int requestMSP, Boolean err, int s) { //if (FontMode)DelayTimer(1); serialize8('$'); serialize8('M'); serialize8(err ? '!' : '>'); outChecksum = 0; // start calculating a new checksum serialize8(s); serialize8(requestMSP); } public void headSerialReply(int requestMSP, int s) { if ((str(requestMSP) !=null) && (str(s)!=null)){ headSerialResponse(requestMSP, false, s); } } //void headSerialError(int requestMSP, int s) { // headSerialResponse(requestMSP, true, s); //} public void tailSerialReply() { if (outChecksum > 0) serialize8(outChecksum); } public void DelayTimer(int ms){ int time = millis(); while(millis()-time < ms); } public void evaluateCommand(byte cmd, int size) { if ((init_com==0) || (toggleMSP_Data == false)){ return; } PortRead = true; MakePorts(); int icmd = PApplet.parseInt(cmd&0xFF); if (icmd !=MSP_OSD)return; //System.out.println("Not Valid Command"); //System.out.println("evaluateCommand"); time2=time; //int[] requests = {MSP_STATUS, MSP_RAW_IMU, MSP_SERVO, MSP_MOTOR, MSP_RC, MSP_RAW_GPS, MSP_COMP_GPS, MSP_ALTITUDE, MSP_BAT, MSP_DEBUGMSG, MSP_DEBUG}; switch(icmd) { case MSP_OSD: int cmd_internal = read8(); PortRead = true; MakePorts(); if(cmd_internal == OSD_NULL) { } if(cmd_internal == OSD_READ_CMD_EE) { // response to a read / write request // System.out.print(" "+size+" "); if(size == 2) { // confirmed write request received eeaddressOSD=read8(); eeaddressOSD=eeaddressOSD+read8(); if (eeaddressOSD>=eeaddressGUI){ // update base address eeaddressGUI=eeaddressOSD; } if (eeaddressGUI>(CONFIGITEMS + (hudoptions*2*2))){ // hit end address // if (eeaddressGUI>=(CONFIGITEMS)){ // hit end address config only WriteConfigMSPMillis=0; } } else{ // confirmed write request received for(int i=0; i<10; i++) { eeaddressOSD=read8(); eeaddressOSD=eeaddressOSD+read8(); eedataOSD=read8(); if (eeaddressOSD<CONFIGITEMS){ SetConfigItem(eeaddressOSD, eedataOSD); } if (eeaddressOSD==GetSetting("S_AMPMAXH")){ // 16 bit value amps manipulation now received all data S16_AMPMAX=(PApplet.parseInt(confItem[GetSetting("S_AMPMAXH")].value())<<8)+ PApplet.parseInt(confItem[GetSetting("S_AMPMAXL")].value()); SetConfigItem(GetSetting("S_AMPDIVIDERRATIO"), (int) S16_AMPMAX); } if (eeaddressOSD==eeaddressGUI){ // update base address eeaddressGUI++; } } // if (eeaddressGUI>(CONFIGITEMS + (hudoptions*2*2))){ // hit end address if (eeaddressGUI>=(CONFIGITEMS)){ // hit end address config only ReadConfigMSPMillis=0; } } } if(cmd_internal == OSD_READ_CMD) { if(size == 1) { } else { // debug[1]++; confCheck=0; readerror=0; readcounter++; for(int i = 0; i < CONFIGITEMS; i++){ int xx = read8(); if (i==0){ confCheck=xx; } if (i==GetSetting("S_AMPDIVIDERRATIO")){ xx=0; } if (i>0){ if (WriteConfig>0){ if ((xx!=readcheck[i])){ readerror=1; } } } if (confCheck>0){ SetConfigItem(i, xx); } } if (readerror==0){ WriteConfig=0; ReadConfig=0; } if (MW_OSD_EEPROM_Version!=confCheck){ noLoop(); JOptionPane.showConfirmDialog(null,"GUI version does not match OSD version - a different version is required.", "Version Mismatch Warning", JOptionPane.PLAIN_MESSAGE,JOptionPane.WARNING_MESSAGE); loop(); } S16_AMPMAX=(PApplet.parseInt(confItem[GetSetting("S_AMPMAXH")].value())<<8)+ PApplet.parseInt(confItem[GetSetting("S_AMPMAXL")].value()); // for 8>>16 bit EEPROM SetConfigItem(GetSetting("S_AMPDIVIDERRATIO"), (int) S16_AMPMAX); // Send a NULL reply //headSerialReply(MSP_OSD, 1); //serialize8(OSD_NULL); if (FontMode == false){ toggleMSP_Data = false; g_serial.clear(); } } } if(cmd_internal == OSD_GET_FONT) { if( size == 1) { //headSerialReply(MSP_OSD, 5); //serialize8(OSD_GET_FONT); //serialize16(7456); // safety code //serialize8(0); // first char //serialize8(255); // last char // tailSerialReply(); } if(size == 3) { //txtmessage.setText(" Please Wait"); // PortRead = true; //PortWrite = true; //int cindex = read16(); //if((cindex&0xffff) == 0xffff) { // End! //FontCounter = 255; // headSerialReply(MSP_OSD, 1); // serialize8(OSD_NULL); // tailSerialReply(); // toggleMSP_Data = false; // g_serial.clear(); // PortRead = false; // PortWrite = false; //FontMode = false; // System.out.println("End marker "+cindex); // buttonSendFile.getCaptionLabel().setText(" Upload"); // txtmessage.setText(""); //InitSerial(200.00); // RESTART(); // g_serial.clear(); // g_serial.stop(); // g_serial = new Serial(this, Serial.list()[int(LastPort)], 115200); // READ(); //} //else { //PortWrite = true; //MakePorts(); //headSerialReply(MSP_OSD, 56); //serialize8(OSD_GET_FONT); // for(int i = 0; i < 54; i++){ //serialize8(int(raw_font[cindex][i])); //} //serialize8(cindex); //tailSerialReply(); // // XXX Fake errors to force retransmission // if(int(random(3)) == 0) { // System.out.println("Messed char "+cindex); // outChecksum ^= int(random(1,256)); // } // else // // End fake errors code //System.out.println("Sent Char "+cindex); //buttonSendFile.getCaptionLabel().setText(" " +nf(cindex, 3)+"/256"); //} } } break; } } public void MWData_Com() { if ((toggleMSP_Data == false) ||(init_com==0)) return; int i,aa; float val,inter,a,b,h; int c = 0; //System.out.println("MWData_Com"); while (g_serial.available()>0 && (toggleMSP_Data == true)) { try{ c = (g_serial.read()); if (str(c) == null)return; PortRead = true; MakePorts(); if (c_state == IDLE) { c_state = (c=='$') ? HEADER_START : IDLE; } else if (c_state == HEADER_START) { c_state = (c=='M') ? HEADER_M : IDLE; } else if (c_state == HEADER_M) { if (c == '<') { c_state = HEADER_ARROW; } else if (c == '!') { c_state = HEADER_ERR; } else { c_state = IDLE; } } else if (c_state == HEADER_ARROW || c_state == HEADER_ERR) { /* is this an error message? */ err_rcvd = (c_state == HEADER_ERR); /* now we are expecting the payload size */ dataSize = (c&0xFF); /* reset index variables */ p = 0; offset = 0; checksum = 0; checksum ^= (c&0xFF); /* the command is to follow */ c_state = HEADER_SIZE; } else if (c_state == HEADER_SIZE) { cmd = (byte)(c&0xFF); checksum ^= (c&0xFF); c_state = HEADER_CMD; } else if (c_state == HEADER_CMD && offset < dataSize) { checksum ^= (c&0xFF); inBuf[offset++] = (byte)(c&0xFF); } else if (c_state == HEADER_CMD && offset >= dataSize) { /* compare calculated and transferred checksum */ if ((checksum&0xFF) == (c&0xFF)) { if (err_rcvd) { //System.err.println("Copter did not understand request type "+c); } else { /* we got a valid response packet, evaluate it */ try{ if ((init_com==1) && (toggleMSP_Data == true)) { evaluateCommand(cmd, (int)dataSize); //System.out.println("CMD: "+cmd); PortRead = false; } else{ // System.out.println("port is off "); } } catch (Exception e) { // null pointer or serial port dead System.out.println("write error " + e); } } } else { System.out.println("invalid checksum for command "+((int)(cmd&0xFF))+": "+(checksum&0xFF)+" expected, got "+(int)(c&0xFF)); System.out.print("<"+(cmd&0xFF)+" "+(dataSize&0xFF)+"> {"); for (i=0; i<dataSize; i++) { if (i!=0) { System.err.print(' '); } System.out.print((inBuf[i] & 0xFF)); } System.out.println("} ["+c+"]"); System.out.println(new String(inBuf, 0, dataSize)); } c_state = IDLE; } } catch(java.lang.Throwable t) { System.out.println( t.getClass().getName() ); //this'll tell you what class has been thrown t.printStackTrace(); //get a stack trace } } } public void READconfigMSP_init(){ // println("Console test print"); SimControlToggle.setValue(0); ReadConfigMSPMillis=1000+millis(); eeaddressGUI=0; } public void READconfigMSP(){ toggleMSP_Data = true; inBuf[0] = OSD_WRITE_CMD; for (int txTimes = 0; txTimes<1; txTimes++) { headSerialReply(MSP_OSD, 4); serialize8(OSD_READ_CMD_EE); int tmpeeadd = eeaddressGUI&0xFF; serialize8(tmpeeadd); tmpeeadd = eeaddressGUI>>8; serialize8(tmpeeadd); serialize8(99); tailSerialReply(); } // toggleMSP_Data = false; //??????????????????? ReadConfigMSPMillis=1000+millis(); } public void WRITEconfigMSP_init(){ eeaddressGUI=0; CheckCallSign(); EElookuptableReSet(); WriteConfigMSPMillis=1000+millis(); } public void WRITEconfigMSP(){ SimControlToggle.setValue(0); toggleMSP_Data = true; inBuf[0] = OSD_WRITE_CMD; for (int txTimes = 0; txTimes<1; txTimes++) { headSerialReply(MSP_OSD, 1 + (3*10)); serialize8(OSD_WRITE_CMD_EE); for(int i=0; i<10; i++) { int tmpeeadd = (i+eeaddressGUI)&0xFF; serialize8(tmpeeadd); tmpeeadd = (i+eeaddressGUI)>>8; serialize8(tmpeeadd); serialize8(EElookuptable[i+eeaddressGUI]); // System.out.println(eeaddressGUI+i+":"+EElookuptable[i+eeaddressGUI]); } tailSerialReply(); } // toggleMSP_Data = false; //??????????????????? WriteConfigMSPMillis=1000+millis(); } public void EElookuptableReSet(){ // preparing for a write confItem[GetSetting("S_AMPMAXL")].setValue(PApplet.parseInt(confItem[GetSetting("S_AMPDIVIDERRATIO")].value())&0xFF); // for 8>>16 bit EEPROM confItem[GetSetting("S_AMPMAXH")].setValue(PApplet.parseInt(confItem[GetSetting("S_AMPDIVIDERRATIO")].value())>>8); for(int i = 0; i < CONFIGITEMS; i++){ if(i == GetSetting("S_VOLTAGEMIN")){ EElookuptable[i]=PApplet.parseInt(confItem[i].value()*10); } else if(i == GetSetting("S_GPSTZ")){ EElookuptable[i]=PApplet.parseInt(confItem[i].value()*10); } else if(i == GetSetting("S_AMPDIVIDERRATIO")){ EElookuptable[i]=0; } else{ EElookuptable[i]=PApplet.parseInt(confItem[i].value()); } } // for(int i = 0; i < (hudoptions); i++){ // ConfigLayout[0][i]=CONFIGHUD[int(confItem[GetSetting("S_HUD")].value())][i]; // ConfigLayout[1][i]=CONFIGHUD[int(confItem[GetSetting("S_HUDOSDSW")].value())][i]; // } int EElookuptableaddress=CONFIGITEMS; for(int i = 0; i < (hudoptions); i++){ EElookuptable[EElookuptableaddress]=PApplet.parseInt(ConfigLayout[0][i]&0xFF); EElookuptableaddress++; EElookuptable[EElookuptableaddress]=PApplet.parseInt(ConfigLayout[0][i]>>8); EElookuptableaddress++; } for(int i = 0; i < (hudoptions); i++){ EElookuptable[EElookuptableaddress]=PApplet.parseInt(ConfigLayout[1][i]&0xFF); EElookuptableaddress++; EElookuptable[EElookuptableaddress]=PApplet.parseInt(ConfigLayout[1][i]>>8); EElookuptableaddress++; } } public void EElookuptableSync(){ // Sync settings with EE table } float sAltitude = 0; float sVario = 0; float sVBat = 0; float sMRSSI = 0; int mode_armed = 0; int mode_stable = 0; int mode_horizon = 0; int mode_baro = 0; int mode_mag = 0; int mode_gpshome = 0; int mode_gpshold = 0; int mode_gpsmission = 0; int mode_gpsland = 0; int mode_llights = 0; int mode_camstab = 0; int mode_osd_switch = 0; int SendSim = 0; boolean[] keys = new boolean[526]; boolean armed = false; Group SG,SGControlBox,SGModes,SGAtitude,SGRadio,SGSensors1,SGGPS,SGFRSKY; // Checkboxs CheckBox checkboxSimItem[] = new CheckBox[SIMITEMS] ; CheckBox ShowSimBackground, UnlockControls, SGPS_FIX,SFRSKY; //Toggles Toggle toggleModeItems[] = new Toggle[boxnames.length] ; Toggle SimControlToggle; // Toggle HudOptionEnabled; // Slider2d- Slider2D Pitch_Roll, Throttle_Yaw,MW_Pitch_Roll; //Sliders --- Slider s_Altitude,s_Vario,s_VBat,s_MRSSI; Textlabel txtlblModeItems[] = new Textlabel[boxnames.length] ; Textlabel SimControlText; // Knobs---- Knob HeadingKnob,SGPSHeadHome; Numberbox SGPS_numSat, SGPS_altitude, SGPS_speed, SGPS_ground_course,SGPS_distanceToHome,SGPS_directionToHome,SGPS_update; //GPS_distanceToHome=read16(); //GPS_directionToHome=read16(); //GPS_update=read8(); //CheckBox checkboxModeItems[] = new CheckBox[boxnames.length] ; DecimalFormat OnePlaceDecimal = new DecimalFormat("0.0"); DecimalFormat TwoPlaceDecimal = new DecimalFormat("0.00"); public void LayoutEditorSetup(){ // Group LEW; LEW = FontGroupcontrolP5.addGroup("LEW") .setPosition(XLINKS,YLINKS) .setWidth(345) .setBarHeight(15) .activateEvent(true) .setBackgroundColor(color(30,255)) .setBackgroundHeight(103) .setLabel("Layout Editor") .setMoveable(true) .disableCollapse() .hide() ; LEW.captionLabel() .toUpperCase(false); // buttonLPOSUP = controlP5.addButton("bPOSLUP",1,10,35,12,19) buttonLPOSUP = controlP5.addButton("bPOSLUP",1,10,10,12,19) .setLabel("-") .setColorBackground(blue_) .setColorCaptionLabel(yellow_) .setGroup(LEW); // buttonLPOSDOWN = controlP5.addButton("bPOSLDOWN",1,23,35,12,19) buttonLPOSDOWN = controlP5.addButton("bPOSLDOWN",1,23,10,12,19) .setLabel("+") .setColorBackground(blue_) .setColorCaptionLabel(yellow_) .setGroup(LEW); // txtlblLayoutTxt = controlP5.addTextlabel("txtlblLayoutTxt","blah",37,35) txtlblLayoutTxt = controlP5.addTextlabel("txtlblLayoutTxt","blah",70,10) .setGroup(LEW); txtlblLayoutTxt2 = controlP5.addTextlabel("txtlblLayoutTxt2","Text",37,10) .setGroup(LEW); // buttonLPOSEN = controlP5.addButton("bPOSLEN",1,23,60,12,19) buttonLPOSEN = controlP5.addButton("bPOSLEN",1,23,35,12,19) .setLabel("*") .setColorBackground(blue_) .setColorCaptionLabel(yellow_) .setGroup(LEW); // txtlblLayoutEnTxt = controlP5.addTextlabel("txtlblLayoutEnTxt","-",37,60) txtlblLayoutEnTxt = controlP5.addTextlabel("txtlblLayoutEnTxt","-",70,35) .setGroup(LEW); txtlblLayoutEnTxt2 = controlP5.addTextlabel("txtlblLayoutEnTxt2","Status",37,35) .setGroup(LEW); // buttonLPOSUP = controlP5.addButton("bHUDLUP",1,10,10,12,19) buttonLPOSUP = controlP5.addButton("bHUDLUP",1,10,60,12,19) .setLabel("-") .setColorBackground(blue_) .setColorCaptionLabel(yellow_) .setGroup(LEW); // buttonLPOSDOWN = controlP5.addButton("bHUDLDOWN",1,23,10,12,19) buttonLPOSDOWN = controlP5.addButton("bHUDLDOWN",1,23,60,12,19) .setLabel("+") .setColorBackground(blue_) .setColorCaptionLabel(yellow_) .setGroup(LEW); // txtlblLayoutHudTxt = controlP5.addTextlabel("txtlblLayoutHudTxt","-",37,10) txtlblLayoutHudTxt = controlP5.addTextlabel("txtlblLayoutHudTxt","-",70,60) .setGroup(LEW); txtlblLayoutHudTxt2 = controlP5.addTextlabel("txtlblLayoutHudTxt2","HUD",37,60) .setGroup(LEW); buttonLUP = controlP5.addButton("bLUP",1,195,10,40,19) .setLabel(" UP") .setColorBackground(blue_) .setColorCaptionLabel(yellow_) .setGroup(LEW); buttonLDOWN = controlP5.addButton("bLDOWN",1,195,60,40,19) .setLabel("DOWN") .setColorBackground(blue_) .setColorCaptionLabel(yellow_) .setGroup(LEW); buttonLLEFT = controlP5.addButton("bLLEFT",1,170,35,40,19) .setLabel(" LEFT") .setColorBackground(blue_) .setColorCaptionLabel(yellow_) .setGroup(LEW); buttonLRIGHT = controlP5.addButton("bLRIGHT",1,220,35,40,19) .setLabel("RIGHT") .setColorBackground(blue_) .setColorCaptionLabel(yellow_) .setGroup(LEW); buttonLSET = controlP5.addButton("bLSET",1,270,9,65,16) .setLabel("Switches") .setColorBackground(blue_) .setColorCaptionLabel(yellow_) .setGroup(LEW); buttonLADD = controlP5.addButton("bLADD",1,270,28,65,16) .setLabel(" ADD") .setColorBackground(blue_) .setColorCaptionLabel(yellow_) .setGroup(LEW); buttonLSAVE = controlP5.addButton("bLSAVE",1,270,47,65,16) .setLabel(" SAVE") .setColorBackground(blue_) .setColorCaptionLabel(yellow_) .setGroup(LEW); buttonLCANCEL = controlP5.addButton("bLCANCEL",1,270,66,65,16) .setLabel(" EXIT") .setColorBackground(blue_) .setColorCaptionLabel(yellow_) .setGroup(LEW); } public void SimSetup(){ LayoutEditorSetup(); LinksSetup() ; SG = ScontrolP5.addGroup("SG") .setPosition(305,YSim + 44) .setWidth(733) .setBarHeight(13) .activateEvent(true) .disableCollapse() // .setBackgroundColor(color(0,255)) .setBackgroundHeight(192) .setLabel("Simulator") .setMoveable(true); ; SGModes = ScontrolP5.addGroup("SGModes") .setPosition(632,18) .setWidth(100) .setBarHeight(15) .activateEvent(true) .disableCollapse() .setBackgroundColor(color(30,255)) .setBackgroundHeight((boxnames.length*17) + 9) .setLabel("Modes") .setGroup(SG) .disableCollapse() //.close() ; SGAtitude = ScontrolP5.addGroup("SGAtitude") .setPosition(525,18) .setWidth(100) .setBarHeight(15) .activateEvent(true) .disableCollapse() .setBackgroundColor(color(30,255)) .setBackgroundHeight(162) .setLabel("Angle/Heading") .setGroup(SG) //.close() ; SGRadio = ScontrolP5.addGroup("SGRadio") .setPosition(388,18) .setWidth(130) .setBarHeight(15) .activateEvent(true) .disableCollapse() .setBackgroundColor(color(30,255)) .setBackgroundHeight(62) .setLabel("Radio") .setGroup(SG) //.close() ; SGSensors1 = ScontrolP5.addGroup("SGSensors1") .setPosition(0,18) .setWidth(175) .setBarHeight(15) .activateEvent(true) .disableCollapse() .setBackgroundColor(color(30,255)) .setBackgroundHeight(110) .setLabel("Sensors 1") .setGroup(SG) //.close() ; SGGPS = ScontrolP5.addGroup("SGGPS") .setPosition(182,18) .setWidth(200) .setBarHeight(15) .activateEvent(true) .disableCollapse() .setBackgroundColor(color(30,255)) .setBackgroundHeight(110) .setLabel("GPS") .setGroup(SG) //.close() ; SGFRSKY = ScontrolP5.addGroup("SGFRSKY") .setPosition(182,145) .setWidth(200) .setBarHeight(15) .activateEvent(true) .disableCollapse() .setBackgroundColor(color(30,255)) .setBackgroundHeight(33) .setLabel("FRSKY") .setGroup(SG) //.close() ; SGControlBox = ScontrolP5.addGroup("SGControlBox") .setPosition(0,145) .setWidth(175) .setBarHeight(15) .activateEvent(true) .disableCollapse() .setBackgroundColor(color(30,255)) .setBackgroundHeight(33) .setLabel("Simulator Control") .setGroup(SG) //.close() ; SimControlToggle = (controlP5.Toggle) hideLabel(controlP5.addToggle("SendSim")); SimControlToggle.setPosition(5,5); SimControlToggle.setSize(35,10); SimControlToggle.setMode(ControlP5.SWITCH); SimControlToggle.setGroup(SGControlBox); SimControlToggle.setValue(0); SimControlText = controlP5.addTextlabel("SimControlText","Simulate on OSD",45,3); SimControlText.setGroup(SGControlBox); SFRSKY = ScontrolP5.addCheckBox("SFRSKY",5,5); SFRSKY.setColorBackground(color(120)); SFRSKY.setColorActive(color(255)); SFRSKY.addItem("Simulate FRSKY cells",1); SFRSKY.setGroup(SGFRSKY); // SFRSKY.activate(0); SGPS_FIX = ScontrolP5.addCheckBox("GPS_FIX",5,5); SGPS_FIX.setColorBackground(color(120)); SGPS_FIX.setColorActive(color(255)); SGPS_FIX.addItem("GPS Fix",1); //GPSLock.hideLabels(); SGPS_FIX.setGroup(SGGPS); SGPS_FIX.activate(0); SGPS_numSat = ScontrolP5.addNumberbox("SGPS_numSat",0,5,20,40,14); SGPS_numSat.setLabel("Sats"); //SGPS_numSat.setColorBackground(red_); SGPS_numSat.setMin(0); SGPS_numSat.setDirection(Controller.HORIZONTAL); SGPS_numSat.setMax(15); SGPS_numSat.setDecimalPrecision(0); SGPS_numSat.setGroup(SGGPS); SGPS_numSat.setValue(10); ScontrolP5.getController("SGPS_numSat").getCaptionLabel() .align(ControlP5.LEFT, ControlP5.RIGHT_OUTSIDE).setPaddingX(45); SGPS_altitude = ScontrolP5.addNumberbox("SGPS_altitude",0,5,40,40,14); SGPS_altitude.setLabel("Alt-cm"); //SGPS_numSat.setColorBackground(red_); SGPS_altitude.setMin(0); SGPS_altitude.setDirection(Controller.HORIZONTAL); SGPS_altitude.setMax(100000); SGPS_altitude.setDecimalPrecision(0); SGPS_altitude.setGroup(SGGPS); SGPS_altitude.setValue(10000); ScontrolP5.getController("SGPS_altitude").getCaptionLabel() .align(ControlP5.LEFT, ControlP5.RIGHT_OUTSIDE).setPaddingX(45); SGPS_speed = ScontrolP5.addNumberbox("SGPS_speed",0,5,60,40,14); SGPS_speed.setLabel("Speed-cm/s"); //SGPS_numSat.setColorBackground(red_); SGPS_speed.setMin(0); SGPS_speed.setDirection(Controller.HORIZONTAL); SGPS_speed.setMax(10000); SGPS_speed.setDecimalPrecision(0); SGPS_speed.setGroup(SGGPS); SGPS_speed.setValue(1000); ScontrolP5.getController("SGPS_speed").getCaptionLabel() .align(ControlP5.LEFT, ControlP5.RIGHT_OUTSIDE).setPaddingX(45); SGPS_distanceToHome = ScontrolP5.addNumberbox("SGPS_distanceToHome",0,5,80,40,14); SGPS_distanceToHome.setLabel("Dist Home-M"); //SGPS_numSat.setColorBackground(red_); SGPS_distanceToHome.setMin(0); SGPS_distanceToHome.setDirection(Controller.HORIZONTAL); SGPS_distanceToHome.setMax(1000); SGPS_distanceToHome.setDecimalPrecision(0); SGPS_distanceToHome.setGroup(SGGPS); SGPS_distanceToHome.setValue(350); ScontrolP5.getController("SGPS_distanceToHome").getCaptionLabel() .align(ControlP5.LEFT, ControlP5.RIGHT_OUTSIDE).setPaddingX(45); SGPSHeadHome = ScontrolP5.addKnob("SGPSHeadHome") .setRange(-180,+180) .setValue(0) .setPosition(140,5) .setRadius(25) .setLabel("Head Home") .setColorBackground(color(0, 160, 100)) .setColorActive(color(255,255,0)) .setDragDirection(Knob.HORIZONTAL) .setGroup(SGGPS) ; MW_Pitch_Roll = ScontrolP5.addSlider2D("MWPitch/Roll") .setPosition(25,5) .setSize(50,50) .setArrayValue(new float[] {50, 50}) .setMaxX(45) .setMaxY(-25) .setMinX(-45) .setMinY(25) .setValueLabel("") .setLabel("Roll/Pitch") .setGroup(SGAtitude) ; ScontrolP5.getController("MWPitch/Roll").getCaptionLabel() .align(ControlP5.CENTER, ControlP5.BOTTOM_OUTSIDE).setPaddingX(0); ScontrolP5.getController("MWPitch/Roll").getValueLabel().hide(); HeadingKnob = ScontrolP5.addKnob("MwHeading") .setRange(-180,+180) .setValue(0) .setPosition(25,80) .setRadius(25) .setLabel("Heading") .setColorBackground(color(0, 160, 100)) .setColorActive(color(255,255,0)) .setDragDirection(Knob.HORIZONTAL) .setGroup(SGAtitude) ; Throttle_Yaw = ScontrolP5.addSlider2D("Throttle/Yaw") .setPosition(5,5) .setSize(50,50) .setArrayValue(new float[] {50, 100}) .setMaxX(2000) .setMaxY(1000) .setMinX(1000) .setMinY(2000) .setValueLabel("") .setLabel("") .setGroup(SGRadio) ; ScontrolP5.getController("Throttle/Yaw").getValueLabel().hide(); ScontrolP5.getTooltip().register("Throttle/Yaw","Ctrl Key to hold position"); UnlockControls = ScontrolP5.addCheckBox("UnlockControls",60,25); UnlockControls.setColorBackground(color(120)); UnlockControls.setColorActive(color(255)); UnlockControls.addItem("UnlockControls1",1); UnlockControls.hideLabels(); UnlockControls.setGroup(SGRadio); UnlockControls.activate(0); Pitch_Roll = ScontrolP5.addSlider2D("Pitch/Roll") .setPosition(75,5) .setSize(50,50) .setArrayValue(new float[] {50, 50}) .setMaxX(2000) .setMaxY(1000) .setMinX(1000) .setMinY(2000) .setLabel("") .setGroup(SGRadio) ; ScontrolP5.getController("Pitch/Roll").getValueLabel().hide(); s_Altitude = ScontrolP5.addSlider("sAltitude") .setPosition(5,10) .setSize(8,75) .setRange(-500,1000) .setValue(0) .setLabel("Alt") .setDecimalPrecision(1) .setGroup(SGSensors1) .setValue(500); ScontrolP5.getController("sAltitude").getValueLabel() .setFont(font9); ScontrolP5.getController("sAltitude").getCaptionLabel() .setFont(font9) .align(ControlP5.LEFT, ControlP5.BOTTOM_OUTSIDE).setPaddingX(0); s_Vario = ScontrolP5.addSlider("sVario") .setPosition(47,10) .setSize(8,75) .setRange(-20,20) .setNumberOfTickMarks(41) .showTickMarks(false) .setValue(0) .setLabel("Vario") .setDecimalPrecision(1) .setValue(7) .setGroup(SGSensors1); ScontrolP5.getController("sVario").getValueLabel() .setFont(font9); ScontrolP5.getController("sVario").getCaptionLabel() .setFont(font9) .align(ControlP5.LEFT, ControlP5.BOTTOM_OUTSIDE).setPaddingX(0); s_VBat = ScontrolP5.addSlider("sVBat") .setPosition(90,10) .setSize(8,75) .setRange(9,26) .setValue(0) .setLabel("VBat") .setDecimalPrecision(1) .setValue(15.0f) .setGroup(SGSensors1); ScontrolP5.getController("sVBat").getValueLabel() .setFont(font9); ScontrolP5.getController("sVBat") .getCaptionLabel() .setFont(font9) .align(ControlP5.LEFT, ControlP5.BOTTOM_OUTSIDE).setPaddingX(0); s_MRSSI = ScontrolP5.addSlider("sMRSSI") .setPosition(130,10) .setSize(8,75) .setRange(0,255) .setValue(0) .setLabel("RSSI") .setDecimalPrecision(0) .setValue(70) .setGroup(SGSensors1); ScontrolP5.getController("sMRSSI").getValueLabel() .setFont(font9); ScontrolP5.getController("sMRSSI") .getCaptionLabel() .setFont(font9) .align(ControlP5.LEFT, ControlP5.BOTTOM_OUTSIDE).setPaddingX(0); for(int i=0;i<boxnames.length ;i++) { toggleModeItems[i] = (controlP5.Toggle) hideLabel(ScontrolP5.addToggle("toggleModeItems"+i,false)); toggleModeItems[i].setPosition(5,3+i*16); toggleModeItems[i].setSize(10,10); //toggleConfItem[i].setMode(ControlP5.SWITCH); toggleModeItems[i].setGroup(SGModes); txtlblModeItems[i] = controlP5.addTextlabel("ModeItems"+i,boxnames[i].substring(0, boxnames[i].length()-1) ,20,i*16); txtlblModeItems[i].setGroup(SGModes); } for(int i=2;i<6 ;i++) { toggleModeItems[i].setValue(1); } GetModes(); } public boolean checkKey(int k) { if (keys.length >= k) { return keys[k]; } return false; } public void keyPressed() { keys[keyCode] = true; //println(keyCode); if((checkKey(CONTROL) == true) && (checkKey(85) == true)){ SketchUploader(); } } public void keyReleased() { keys[keyCode] = false; ControlLock(); } public void CalcAlt_Vario(){ if (time2 < time - 1000){ sAltitude += sVario /10; time2 = time; } } public String RightPadd(int inInt,int Places){ String OutString = nf(inInt,Places).replaceFirst("^0+(?!$)", " "); for(int X=0; X<=3; X++) { if (OutString.length() < Places){ OutString = " " + OutString;} } return OutString; } public void ShowVolts(float voltage){ if(confItem[GetSetting("S_DISPLAYVOLTAGE")].value() > 0) { String output = OnePlaceDecimal.format(voltage); mapchar(0x97, SimPosn[voltagePosition]); makeText(output, SimPosn[voltagePosition]+1); }} public void ShowVideoVolts(float voltage){ if(confItem[GetSetting("S_VIDVOLTAGE")].value() > 0) { String output = OnePlaceDecimal.format(voltage); mapchar(0xBF, SimPosn[vidvoltagePosition]); makeText(output, SimPosn[vidvoltagePosition]+1); }} public void ShowFlyTime(String FMinutes_Seconds){ if (PApplet.parseInt(confItem[GetSetting("S_TIMER")].value()) > 0){ mapchar(0x9c, SimPosn[flyTimePosition]); makeText(FMinutes_Seconds, SimPosn[flyTimePosition]+1); }} public void ShowOnTime(String Minutes_Seconds){ if (PApplet.parseInt(confItem[GetSetting("S_TIMER")].value()) > 0){ mapchar(0x9b, SimPosn[onTimePosition]); makeText(Minutes_Seconds, SimPosn[onTimePosition]+1); }} public void ShowCurrentThrottlePosition(){ if(confItem[GetSetting("S_THROTTLEPOSITION")].value() > 0) { mapchar(0xc8, SimPosn[CurrentThrottlePosition]); if(armed){ int CurThrottle = PApplet.parseInt(map(Throttle_Yaw.arrayValue()[1],1000,2000,0,100)); makeText(RightPadd(CurThrottle,3) + "%", SimPosn[CurrentThrottlePosition]+1); } else { makeText(" --", SimPosn[CurrentThrottlePosition]+1); } //makeText(" 40%", CurrentThrottlePosition[ScreenType]+1); }} public void ShowLatLon(){ if(confItem[GetSetting("S_COORDINATES")].value() > 0) { // if(confItem[GetSetting("S_GPSCOORDTOP")].value() > 0) { mapchar(0xca, SimPosn[MwGPSLatPositionTop]); makeText(" 43.09486N", SimPosn[MwGPSLatPositionTop]+1); mapchar(0xcb, SimPosn[MwGPSLonPositionTop]); makeText(" 71.88970W", SimPosn[MwGPSLonPositionTop]+1); // } // else { // mapchar(0xca, SimPosn[MwGPSLatPosition]); // makeText(" 43.09486N", SimPosn[MwGPSLatPosition]+1); // mapchar(0xcb, SimPosn[MwGPSLonPosition]); // makeText(" 71.88970W", SimPosn[MwGPSLonPosition]+1); // } } } public void ShowDebug(){ if(confItem[GetSetting("S_DEBUG")].value() > 0) { makeText("0: "+debug[0], SimPosn[debugPosition]); makeText("1: "+debug[1], SimPosn[debugPosition]+LINE); makeText("2: "+debug[2], SimPosn[debugPosition]+LINE+LINE); makeText("3: "+debug[3], SimPosn[debugPosition]+LINE+LINE+LINE); } } public void ShowSats(){ String output = str(PApplet.parseInt(SGPS_numSat.getValue())); mapchar(0x1e, SimPosn[GPS_numSatPosition]); mapchar(0x1f, SimPosn[GPS_numSatPosition]+1); makeText(output, SimPosn[GPS_numSatPosition]+2); } public void ShowSpeed(){ String output = str(PApplet.parseInt(SGPS_speed.getValue()/27.7778f)); if(confItem[GetSetting("S_UNITSYSTEM")].value() > 0) {mapchar(0xa6, SimPosn[speedPosition]);} else {mapchar(0xa5, SimPosn[speedPosition]);} makeText(output, SimPosn[speedPosition]+1); } public void ShowDirection(){ int dirhome=0x60 + ((180+360+22+MwHeading-PApplet.parseInt(SGPSHeadHome.value()))%360)*2/45; mapchar(dirhome, SimPosn[GPS_directionToHomePosition]); } public void ShowGPSAltitude(){ String output = str(PApplet.parseInt(SGPS_altitude.getValue())/100); if(confItem[GetSetting("S_GPSALTITUDE")].value() > 0) { if(confItem[GetSetting("S_UNITSYSTEM")].value() > 0) {mapchar(0xa8, SimPosn[MwGPSAltPosition]);} else {mapchar(0xa7, SimPosn[MwGPSAltPosition]);} makeText(output, SimPosn[MwGPSAltPosition]+1); }} public void ShownAngletohome(){ String output = str((360+PApplet.parseInt(SGPSHeadHome.getValue()))%360/1); if(confItem[GetSetting("S_ANGLETOHOME")].value() > 0) { switch (output.length()) { case 1: makeText(output, SimPosn[GPS_angleToHomePosition]+2); break; case 2: makeText(output, SimPosn[GPS_angleToHomePosition]+1); break; case 3: makeText(output, SimPosn[GPS_angleToHomePosition]); break; case 4: makeText(output, SimPosn[GPS_angleToHomePosition]-1); break; } mapchar(0xbd, SimPosn[GPS_angleToHomePosition]+3); }} public void ShowAltitude(){ String output = str(PApplet.parseInt(s_Altitude.getValue())); if(confItem[GetSetting("S_BAROALT")].value() > 0) { if(confItem[GetSetting("S_UNITSYSTEM")].value() > 0) {mapchar(0xa8, SimPosn[MwAltitudePosition]);} else {mapchar(0xa7, SimPosn[MwAltitudePosition]);} makeText(output, SimPosn[MwAltitudePosition]+1); }} public void ShowDistance(){ String output = str(PApplet.parseInt(SGPS_distanceToHome.getValue())); if(confItem[GetSetting("S_UNITSYSTEM")].value() > 0) {mapchar(0xb9, SimPosn[GPS_distanceToHomePosition]);} else {mapchar(0xbb, SimPosn[GPS_distanceToHomePosition]);} makeText(output, SimPosn[GPS_distanceToHomePosition]+1); } public void ShowVario(){ if(confItem[GetSetting("S_VARIO")].value() > 0) { mapchar(0x7f, SimPosn[MwClimbRatePosition]-LINE); mapchar(0x8c, SimPosn[MwClimbRatePosition]); mapchar(0x7f, SimPosn[MwClimbRatePosition]+LINE); }} public void ShowRSSI(){ String output = str(PApplet.parseInt(s_MRSSI.getValue())); if(confItem[GetSetting("S_DISPLAYRSSI")].value() > 0) { mapchar(0xba, SimPosn[rssiPosition]); makeText(output + "%", SimPosn[rssiPosition]+1); }} public void ShowAPstatus(){ if (SimPosn[APstatusPosition]==0x3FF) return; String output=""; int SimModebits = 0; int SimBitCounter = 1; for (int i=0; i<boxnames.length; i++) { if(toggleModeItems[i].getValue() > 0) SimModebits |= SimBitCounter; SimBitCounter += SimBitCounter; } if((SimModebits&mode_gpshome) >0){ output = "AUTO RTH"; } else if((SimModebits&mode_gpshold) >0){ output = "AUTO HOLD"; } else if((SimModebits&mode_gpsmission) >0){ output = " MISSION"; } else if((SimModebits&mode_gpsland) >0){ output = "AUTO LAND"; } makeText(output, SimPosn[APstatusPosition]); } public void ShowCallsign(){ if(confItem[GetSetting("S_DISPLAY_CS")].value() > 0) { if (LEWvisible==1){ if (millis() < (csmillis)+4000){ csmillis = (millis()-4000); } } if (millis() > (csmillis)+5000){ String CallSText = controlP5.get(Textfield.class,"CallSign").getText().toUpperCase(); makeText(CallSText, SimPosn[callSignPosition]); if (millis() > (csmillis + 6000)){ csmillis = millis(); } } }} public void ShowAmperage(){ if(confItem[GetSetting("S_AMPER_HOUR")].value() > 0) { mapchar(0xa4, SimPosn[pMeterSumPosition]); makeText("1221", SimPosn[pMeterSumPosition]+1); }} public void ShowTemp(){ makeText("30", SimPosn[temperaturePosition]); mapchar(0x0e, SimPosn[temperaturePosition]+2); } public void ShowAmps(){ if(confItem[GetSetting("S_AMPERAGE")].value() > 0) { makeText("15.2A", SimPosn[amperagePosition]+1); }} public void ShowUTC(){ if(confItem[GetSetting("S_GPSTIME")].value() > 0) { int seconds = second(); int minutes = minute(); int hours = hour(); String PCTimerString =""; if (hours < 10){ PCTimerString = "0" + str(hours) ; } else { PCTimerString = str(hours); } if (minutes < 10){ PCTimerString = PCTimerString +":0" + str(minutes) ; } else { PCTimerString = PCTimerString +":" + str(minutes); } if (seconds < 10){ PCTimerString = PCTimerString +":0" + str(seconds); } else { PCTimerString = PCTimerString +":" + str(seconds); } makeText(PCTimerString, SimPosn[GPS_timePosition]); } } public void displayHeading() { if(confItem[GetSetting("S_SHOWHEADING")].value() > 0) { int heading = MwHeading; if(confItem[GetSetting("S_HEADING360")].value() > 0) { if(heading < 0) heading += 360; } switch (str(heading).length()) { case 1: makeText(str(heading), SimPosn[MwHeadingPosition]+2); break; case 2: makeText(str(heading), SimPosn[MwHeadingPosition]+1); break; case 3: makeText(str(heading), SimPosn[MwHeadingPosition]); break; case 4: makeText(str(heading), SimPosn[MwHeadingPosition]-1); break; } mapchar(MwHeadingUnitAdd,SimPosn[MwHeadingPosition]+3); }} public void SimulateTimer(){ if (SimPosn[flyTimePosition]==0x3FF){ return; } String OnTimerString =""; String FlyTimerString =""; int seconds = (millis() - OnTimer) / 1000; int minutes = seconds / 60; int hours = minutes / 60; seconds -= minutes * 60; minutes -= hours * 60; if (seconds < 10){ OnTimerString = str(minutes) + ":0" + str(seconds); } else { OnTimerString = str(minutes) + ":" + str(seconds); } // ShowOnTime(OnTimerString); if (FlyTimer >0) { seconds = (millis() - FlyTimer) / 1000; minutes = seconds / 60; hours = minutes / 60; seconds -= minutes * 60; minutes -= hours * 60; if (seconds < 10){ FlyTimerString = str(minutes) + ":0" + str(seconds); } else { FlyTimerString = str(minutes) + ":" + str(seconds); } } if ((toggleModeItems[0].getValue() == 0) && (SimItem0 < 1)){ ShowOnTime(OnTimerString); } else { ShowFlyTime(FlyTimerString); } } public void displayMode() { int SimModebits = 0; int SimBitCounter = 1; for (int i=0; i<boxnames.length; i++) { if(toggleModeItems[i].getValue() > 0) SimModebits |= SimBitCounter; SimBitCounter += SimBitCounter; } if(confItem[GetSetting("S_CHECK_")].value() > 0) { if((SimModebits&mode_armed) >0){ makeText(" ARMED", SimPosn[motorArmedPosition]); armed = true; } else{ makeText("DISARMED", SimPosn[motorArmedPosition]); armed = false; } } else{ makeText("DISCONNECTED", SimPosn[motorArmedPosition]-2); armed = false; } if(confItem[GetSetting("S_MODEICON")].value() > 0) { if(confItem[GetSetting("S_MODESENSOR")].value() > 0) { if((SimModebits&mode_stable) >0) mapchar(0xa0,SimPosn[sensorPosition]); if((SimModebits&mode_horizon) >0) mapchar(0xa0,SimPosn[sensorPosition]); if((SimModebits&mode_baro) >0) mapchar(0xa2,SimPosn[sensorPosition]+1); if((SimModebits&mode_mag) >0) mapchar(0xa1,SimPosn[sensorPosition]+2); } if(confItem[GetSetting("S_GIMBAL")].value() > 0) { if((SimModebits&mode_camstab) >0){ mapchar(0x16,SimPosn[gimbalPosition]); mapchar(0x17,SimPosn[gimbalPosition]+1); }} if (SimPosn[ModePosition]!=0x3FF){ if((SimModebits&mode_gpshome) >0){ mapchar(0x9d,SimPosn[ModePosition]); mapchar(0x9e,SimPosn[ModePosition]+1); // mapchar(0x2d,SimPosn[ModePosition]+2); // mapchar(0x9e,SimPosn[statusPosition]+3); // String output = str(int(SGPS_distanceToHome.getValue())); // makeText(output,SimPosn[ModePosition]+3); // mapchar(0x0c,SimPosn[ModePosition]+3+output.length()); } else if((SimModebits&mode_gpshold) >0){ mapchar(0xcd,SimPosn[ModePosition]); mapchar(0xce,SimPosn[ModePosition]+1); } else if((SimModebits&mode_gpsland) >0){ mapchar(0xb7,SimPosn[ModePosition]); mapchar(0xb8,SimPosn[ModePosition]+1); } else if((SimModebits&mode_gpsmission) >0){ mapchar(0xb5,SimPosn[ModePosition]); mapchar(0xb6,SimPosn[ModePosition]+1); mapchar(0x30,SimPosn[ModePosition]+2); } else if((SimModebits&mode_stable) >0){ mapchar(0xac,SimPosn[ModePosition]); mapchar(0xad,SimPosn[ModePosition]+1); } else if((SimModebits&mode_horizon) >0){ mapchar(0xc4,SimPosn[ModePosition]); mapchar(0xc5,SimPosn[ModePosition]+1); } else{ mapchar(0xae,SimPosn[ModePosition]); mapchar(0xaf,SimPosn[ModePosition]+1); } } } } public void displayHorizon(int rollAngle, int pitchAngle) { int minimalscreen=0 ; if (toggleModeItems[9].getValue()>0) minimalscreen=1 ; if (SimPosn[horizonPosition]<0x3FF){ if(pitchAngle>250) pitchAngle=250; //250 if(pitchAngle<-200) pitchAngle=-200; if(rollAngle>400) rollAngle=400; if(rollAngle<-400) rollAngle=-400; for(int X=0; X<=8; X++) { int Y = (rollAngle * (4-X)) / 64; Y += pitchAngle / 8; Y += 41; if(Y >= 0 && Y <= 81) { int pos = 30*(2+Y/9) + 10 + X; if(X < 3 || X >5 || (Y/9) != 4 || confItem[GetSetting("S_DISPLAY_HORIZON_BR")].value() == 0) mapchar(0x80+(Y%9), pos); if(Y>=9 && (Y%9) == 0) mapchar(0x89, pos-30); } } if(confItem[GetSetting("S_HORIZON_ELEVATION")].value() > 0) { for(int X=3; X<=5; X++) { int Y = (rollAngle * (4-X)) / 64; Y += pitchAngle / 8; Y += 31; if(Y >= 0 && Y <= 81) { int pos = 30*(2+Y/9) + 10 + X; if(X < 3 || X >5 || (Y/9) != 4 || confItem[GetSetting("S_DISPLAY_HORIZON_BR")].value() == 0) mapchar(0x80+(Y%9), pos); if(Y>=9 && (Y%9) == 0) mapchar(0x89, pos-30); } Y += 20; if(Y >= 0 && Y <= 81) { int pos = 30*(2+Y/9) + 10 + X; if(X < 3 || X >5 || (Y/9) != 4 || confItem[GetSetting("S_DISPLAY_HORIZON_BR")].value() == 0) mapchar(0x80+(Y%9), pos); if(Y>=9 && (Y%9) == 0) mapchar(0x89, pos-30); } }} if(confItem[GetSetting("S_DISPLAY_HORIZON_BR")].value() > 0) { //Draw center screen mapchar(0x7e, 224-30); mapchar(0x26, 224-30-1); mapchar(0xbc, 224-30+1); } } if (SimPosn[SideBarPosition]<0x3FF){ if(confItem[GetSetting("S_WITHDECORATION")].value() > 0) { mapchar(0xC7,128); mapchar(0xC7,128+30); mapchar(0xC7,128+60); mapchar(0xC7,128+90); mapchar(0xC7,128+120); mapchar(0xC6,128+12); mapchar(0xC6,128+12+30); mapchar(0xC6,128+12+60); mapchar(0xC6,128+12+90); mapchar(0xC6,128+12+120); mapchar(0x02, 229-30); mapchar(0x03, 219-30); } } } public void ShowSideBarArrows(){ if (SimPosn[horizonPosition]==0x3FF) return; if (SimPosn[SideBarScrollPosition]==0x3FF) return; if(confItem[GetSetting("S_SIDEBARTOPS")].value() > 0) { mapchar(0xCf,128+120+30); mapchar(0xCf,128+12+120+30); }} public void displayHeadingGraph() { if(confItem[GetSetting("S_COMPASS")].value() > 0) { int xx; xx = MwHeading * 4; xx = xx + 720 + 45; xx = xx / 90; //for (int i = 0; i < 9; i++){ mapchar(headGraph[xx++],SimPosn[MwHeadingGraphPosition]); mapchar(headGraph[xx++],SimPosn[MwHeadingGraphPosition]+1); mapchar(headGraph[xx++],SimPosn[MwHeadingGraphPosition]+2); mapchar(headGraph[xx++],SimPosn[MwHeadingGraphPosition]+3); mapchar(headGraph[xx++],SimPosn[MwHeadingGraphPosition]+4); mapchar(headGraph[xx++],SimPosn[MwHeadingGraphPosition]+5); mapchar(headGraph[xx++],SimPosn[MwHeadingGraphPosition]+6); mapchar(headGraph[xx++],SimPosn[MwHeadingGraphPosition]+7); mapchar(headGraph[xx],SimPosn[MwHeadingGraphPosition]+8); }} public void ControlLock(){ Pitch_Roll.setArrayValue(new float[] {500, -500}); if(checkKey(CONTROL) == false) { if(UnlockControls.arrayValue()[0] < 1){ float A = (2000-Throttle_Yaw.getArrayValue()[1])*-1; Throttle_Yaw.setArrayValue(new float[] {500, A}); s_Vario.setValue(0); sVario = 0; } } } public void GetModes(){ int bit = 1; int remaining = strBoxNames.length(); int len = 0; mode_armed = 0; mode_stable = 0; mode_horizon = 0; mode_baro = 0; mode_mag = 0; mode_gpshome = 0; mode_gpshold = 0; mode_gpsmission = 0; mode_gpsland = 0; mode_llights = 0; mode_camstab = 0; mode_osd_switch = 0; for (int c = 0; c < boxnames.length; c++) { if (boxnames[c] == "ARM;") mode_armed |= bit; if (boxnames[c] == "ANGLE;") mode_stable |= bit; if (boxnames[c] == "HORIZON;") mode_horizon |= bit; if (boxnames[c] == "MAG;") mode_mag |= bit; if (boxnames[c] == "BARO;") mode_baro |= bit; if (boxnames[c] == "CAMSTAB;") mode_camstab |= bit; if (boxnames[c] == "GPS HOME;") mode_gpshome |= bit; if (boxnames[c] == "GPS HOLD;") mode_gpshold |= bit; if (boxnames[c] == "OSD SW;") mode_osd_switch |= bit; if (boxnames[c] == "MISSION;") mode_gpsmission |= bit; bit <<= 1L; } } public void ShowSPort(){ if (SFRSKY.arrayValue()[0]<1) return; int SYM_MIN = 0xB3; int SYM_AVG = 0xB4; int SYM_CELL0 = 0xF0; // String output = OnePlaceDecimal.format(voltage) float cells=confItem[GetSetting("S_BATCELLS")].value(); if (cells<1) return; float fcellvoltage=(sVBat/cells); fcellvoltage=constrain(fcellvoltage,3.4f,4.2f); int cellpos=PApplet.parseInt (map(fcellvoltage,3.4f,4.2f,0,14)); // cellpos=0; String cellvoltage=TwoPlaceDecimal.format(fcellvoltage); for(int i=0; i<6; i++) { if(i>(cells-1))continue;//empty cell mapchar(SYM_CELL0+cellpos, SimPosn[SportPosition]+(5-i)); } String output = TwoPlaceDecimal.format(sVBat); mapchar(SYM_MIN, SimPosn[SportPosition]+LINE); makeText(cellvoltage+"v", SimPosn[SportPosition]+LINE+1); output = TwoPlaceDecimal.format(sVBat); mapchar(SYM_AVG, SimPosn[SportPosition]+LINE+LINE); makeText(cellvoltage+"v", SimPosn[SportPosition]+LINE+LINE+1); } public void ShowMapMode(){ int mi; if (toggleModeItems[9].getValue()>0) mi = PApplet.parseInt(confItem[GetSetting("S_HUDOSDSW")].value()); else mi = PApplet.parseInt(confItem[GetSetting("S_HUD")].value()); if (CONFIGHUDEN[mi][MapModePosition]==0) return; int SYM_HOME = 0x04; int SYM_AIRCRAFT = 0X05; int SYM_RANGE_100 = 0x21; int SYM_RANGE_500 = 0x22; int SYM_RANGE_2500= 0x23; int SYM_RANGE_MAX = 0x24; int SYM_DIRECTION = 0x72; int xdir=0; int mapstart=0; int mapend=0; int ydir=0; int targetx=0; int targety=0; int range=200; int angle=0; int targetpos=0; int centerpos=0; int maxdistance=0; int mapsymbolcenter=0; int mapsymboltarget=0; int mapsymbolrange=0; int tmp=0; int GPS_directionToHome=PApplet.parseInt(SGPSHeadHome.value()); if(GPS_directionToHome < 0) GPS_directionToHome += 360; if ((toggleModeItems[0].getValue() == 0 )){ armedangle=MwHeading; } // int MwHeading=Mwheading; switch(PApplet.parseInt(confItem[GetSetting("S_MAPMODE")].value())) { case 1: mapstart=0;mapend=1; break; case 2: mapstart=1;mapend=2; break; case 3: mapstart=0;mapend=2; break; case 4: mapstart=1;mapend=2; break; default: return; } for(int maptype=mapstart; maptype<mapend; maptype++) { if (maptype==1) { angle=(180+360+GPS_directionToHome-armedangle) %360; // angle=(180+360+GPS_directionToHome-armedangle+MwHeading)%360; } else { angle=(360+GPS_directionToHome-MwHeading)%360; } tmp = angle/90; switch (tmp) { case 0: xdir=+1; ydir=-1; break; case 1: xdir=+1; ydir=+1; angle=180-angle; break; case 2: xdir=-1; ydir=+1; angle=angle-180; break; case 3: xdir=-1; ydir=-1; angle=360-angle; break; } float rad = angle * PI / 180; // convert to radians int x = PApplet.parseInt(SGPS_distanceToHome.value() * sin(rad)); int y = PApplet.parseInt(SGPS_distanceToHome.value() * cos(rad)); if (y > x) maxdistance=y; else maxdistance=x; if (maxdistance < 100) { range = 100; mapsymbolrange=SYM_RANGE_100; } else if (maxdistance < 500) { range = 500; mapsymbolrange=SYM_RANGE_500; } else if (maxdistance < 2500) { range = 2500; mapsymbolrange=SYM_RANGE_2500; } else { range = maxdistance; mapsymbolrange=SYM_RANGE_MAX; } targetx = PApplet.parseInt(xdir*map(x, 0, range, 0, 16)); targety = PApplet.parseInt(ydir*map(y, 0, range, 0, 15)); if (maxdistance<20) { targetx = 0; targety = 0; } centerpos=SimPosn[MapCenterPosition]; targetpos= centerpos + (targetx/2) + (LINE*(targety/3)); if (maptype==1) { mapsymbolcenter = SYM_HOME; mapsymboltarget = SYM_AIRCRAFT; } else { mapsymbolcenter = SYM_AIRCRAFT; mapsymboltarget = SYM_HOME; } mapchar(mapsymbolcenter,centerpos); /* if (maptype==0) { tmp=(360+382+MwHeading-armedangle)%360/45; tmp = SYM_DIRECTION + tmp; } else { tmp = mapsymboltarget; } */ /* if (confItem[GetSetting("S_MAPMODE")].value()==4) { tmp=(360+382+MwHeading-armedangle)%360/45; mapsymboltarget = SYM_DIRECTION + tmp; } */ int symx = (int)abs(targetx)%2; int symy = (int)abs(targety)%3; if (ydir==1) symy=2-symy; if (xdir==-1) symx=1-symx; if (abs(targety)<3) symy = 1 - ydir; if (abs(targetx)<2){ if (targetx<0) symx=0; else symx=1; } if (maptype==0) tmp = 0xD6; else { tmp = 0xD0; /* if (maptype==1) { tmp=(360+382+MwHeading-armedangle)%360/45; mapsymboltarget = SYM_DIRECTION + tmp; 0x72 } */ } mapsymboltarget = mapsymboltarget + symy + (symx*3); tmp = tmp+ symy + (symx*3); //System.out.println(xdir+" "+ydir+" "+symx+" "+symy+" "+targetx+" "+targety+" "+tmp); mapchar(mapsymbolrange,SimPosn[MapModePosition]); if (confItem[GetSetting("S_MAPMODE")].value()==4) { tmp=(360+382+MwHeading-armedangle)%360/45; tmp = SYM_DIRECTION + tmp; } if (maxdistance>20) { mapchar(tmp,targetpos); } } } public void LinksSetup(){ } byte[][] raw_font; PrintWriter Output; public PImage LoadFont(String filename) { //System.out.println("LoadFont "+filename); raw_font = LoadRawFont(filename); return RawFontToImage(raw_font); } public byte[][] LoadRawFont(String filename) { byte[][] raw = new byte[256][54]; InputStream in = null; byte[] header = { 'M','A','X','7','4','5','6' }; boolean inHeader = true; int hIndex = 0; int bitNo = 0; int byteNo = 0; int charNo = 0; int curByte = 0; try { in = createInput(filename); while(in.available() > 0) { int inB = in.read(); if(inHeader) { if(hIndex < header.length && header[hIndex] == inB) { hIndex++; continue; } if(hIndex == header.length && (inB == '\r' || inB == '\n')) { inHeader = false; //System.out.println("done header"); continue; } hIndex = 0; continue; } else { switch(inB) { case '\r': case '\n': if (bitNo == 0) continue; if (bitNo == 8) { if (byteNo < 54) { //System.out.println("*charNo="+charNo+" byteNo="+byteNo);//+" value="+(int)raw[charNo][byteNo]); raw[charNo][byteNo] = (byte)curByte; } bitNo = 0; curByte = 0; ++byteNo; if(byteNo == 64) { //System.out.println("Loaded char "+charNo); byteNo = 0; ++charNo; } } break; case '0': case '1': if(bitNo >= 8) { throw new Exception("File format error"); } curByte = (curByte << 1) | (inB & 1); ++bitNo; break; } } } } catch (FileNotFoundException e) { System.out.println("File Not Found "+filename); } catch (IOException e) { System.out.println("IOException"); } catch(Exception e) { System.out.println("Exception"); } finally { if(in != null) try { in.close(); } catch (IOException ioe) { } } return raw; } public PImage RawFontToImage(byte[][] raw) { PImage img = createImage(12, 18*256, ARGB); img.loadPixels(); // Pixel values int white = 0xFFFFFFFF; int black = 0xFF000000; int transparent = 0x00000000; int gray = color(120); for(int charNo = 0; charNo < 256; charNo++) { CharImages[charNo].loadPixels(); // CharImages[charNo] = createImage(12, 18, ARGB); for(int byteNo = 0; byteNo < 54; byteNo++) { for(int i = 0; i < 4; i++) { int index = (charNo*12*18) + (byteNo*4) + (3-i); int CharIndex = (byteNo*4) + (3-i); //System.out.println("charNo="+charNo+" byteNo="+byteNo+" index="+index+" CharIndex="+CharIndex+" Charlimit="+CharImages[charNo].pixels.length + " limit="+img.pixels.length); int curByte = (int)raw[charNo][byteNo]; switch((curByte >> (2*i)) & 0x03) { case 0x00: img.pixels[index] = black; CharImages[charNo].pixels[CharIndex] = black; break; case 0x01: img.pixels[index] = transparent; CharImages[charNo].pixels[CharIndex] = gray; break; case 0x02: img.pixels[index] = white; CharImages[charNo].pixels[CharIndex] = white; break; case 0x03: img.pixels[index] = transparent; //CharImages[charNo].pixels[CharIndex] = gray; break; } } } CharImages[charNo].updatePixels(); } img.updatePixels(); return img; } public void CreateFontFile(){ String gray = "01"; // gray in Gui transparrent in OSD String black = "00"; //black String white = "10"; int PixelCounter = 0; int fullpixels = 0; String OutputLine = ""; Output = createWriter("data/custom.mcm"); Output.println("MAX7456"); // write header for(int id = 0; id < 256; id++) { for(int byteNo = 0; byteNo < 216; byteNo++) { switch(CharImages[id].pixels[byteNo]) { case 0xFF000000: OutputLine+=black; PixelCounter+=1; break; case 0xFFFFFFFF: OutputLine+=white; PixelCounter+=1; break; default: OutputLine+=gray; PixelCounter+=1; break; } if(PixelCounter == 4){ Output.println(OutputLine); OutputLine = ""; PixelCounter = 0; } } for(int spacer = 0; spacer < 10; spacer++) { Output.println("01010101"); } } //Output.println("done"); Output.flush(); // Writes the remaining data to the file Output.close(); img_Clear = LoadFont("/data/default.mcm"); } static public void main(String[] passedArgs) { String[] appletArgs = new String[] { "MW_OSD_GUI" }; if (passedArgs != null) { PApplet.main(concat(appletArgs, passedArgs)); } else { PApplet.main(appletArgs); } } }
dale3h/minimosd-flashpack-linux32
MW_OSD_GUI/MW_OSD_GUI_R1.3_SP2/source/MW_OSD_GUI.java
Java
gpl-3.0
172,641
define(["mui"], function(){ function component($q, $resource, $stateParams, AnnotationProjectIdResource){ var _self=this; var url="/annotations/:datasetName/annotation/:dimension/new/dataset/command/core/get-rows"; this.AnnotationValuesResource = $resource(url, { datasetName: $stateParams.datasetId, limit: 30000 }); //to get rows we first must chain a call to get-project-id this.get=function(dimension){ return AnnotationProjectIdResource.get(dimension).then(function(data){ if(data.project<=0) return $q.when({error: "OpenRefine - project not found"}); else data.datasetName=$stateParams.datasetId; data.dimension=dimension; return _self.AnnotationValuesResource.get(data).$promise; }); }; } component.$name="AnnotationValuesResource"; component.$inject=["$q", "$resource", "$stateParams", "AnnotationProjectIdResource"]; component.$provider="service"; return component; });
apartensky/mev
web/src/main/javascript/edu/dfci/cccb/mev/web/libs/domain/annotations/src/main/endpoint/AnnotationValuesResource.js
JavaScript
gpl-3.0
953
package net.minecraft.network.play.server; import cpw.mods.fml.relauncher.Side; import cpw.mods.fml.relauncher.SideOnly; import java.io.IOException; import net.minecraft.network.INetHandler; import net.minecraft.network.Packet; import net.minecraft.network.PacketBuffer; import net.minecraft.network.play.INetHandlerPlayClient; import net.minecraft.world.EnumDifficulty; import net.minecraft.world.WorldSettings; import net.minecraft.world.WorldType; public class S07PacketRespawn extends Packet { private int field_149088_a; private EnumDifficulty field_149086_b; private WorldSettings.GameType field_149087_c; private WorldType field_149085_d; private static final String __OBFID = "CL_00001322"; public S07PacketRespawn() {} public S07PacketRespawn(int p_i45213_1_, EnumDifficulty p_i45213_2_, WorldType p_i45213_3_, WorldSettings.GameType p_i45213_4_) { this.field_149088_a = p_i45213_1_; this.field_149086_b = p_i45213_2_; this.field_149087_c = p_i45213_4_; this.field_149085_d = p_i45213_3_; } public void processPacket(INetHandlerPlayClient p_148833_1_) { p_148833_1_.handleRespawn(this); } public void readPacketData(PacketBuffer p_148837_1_) throws IOException { this.field_149088_a = p_148837_1_.readInt(); this.field_149086_b = EnumDifficulty.getDifficultyEnum(p_148837_1_.readUnsignedByte()); this.field_149087_c = WorldSettings.GameType.getByID(p_148837_1_.readUnsignedByte()); this.field_149085_d = WorldType.parseWorldType(p_148837_1_.readStringFromBuffer(16)); if (this.field_149085_d == null) { this.field_149085_d = WorldType.DEFAULT; } } public void writePacketData(PacketBuffer p_148840_1_) throws IOException { p_148840_1_.writeInt(this.field_149088_a); p_148840_1_.writeByte(this.field_149086_b.getDifficultyId()); p_148840_1_.writeByte(this.field_149087_c.getID()); p_148840_1_.writeStringToBuffer(this.field_149085_d.getWorldTypeName()); } @SideOnly(Side.CLIENT) public int func_149082_c() { return this.field_149088_a; } @SideOnly(Side.CLIENT) public EnumDifficulty func_149081_d() { return this.field_149086_b; } @SideOnly(Side.CLIENT) public WorldSettings.GameType func_149083_e() { return this.field_149087_c; } @SideOnly(Side.CLIENT) public WorldType func_149080_f() { return this.field_149085_d; } public void processPacket(INetHandler p_148833_1_) { this.processPacket((INetHandlerPlayClient)p_148833_1_); } }
Scrik/Cauldron-1
eclipse/cauldron/src/main/java/net/minecraft/network/play/server/S07PacketRespawn.java
Java
gpl-3.0
2,681