text
stringlengths
54
60.6k
<commit_before>/* Copyright 2015 Adam Grandquist 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. */ /** * @author Adam Grandquist * @copyright Apache */ #ifndef REQL_REQL_PROTOCOL_HPP_ #define REQL_REQL_PROTOCOL_HPP_ #include "./reql/handshake.hpp" #include "./reql/query.hpp" #include "./reql/socket.hpp" #include <atomic> #include <cstdint> #include <sstream> #include <string> #include <thread> namespace _ReQL { template <class auth_e, class handshake_e, class socket_e> class Protocol_t { public: template <class addr_t, class auth_t, class func_t, class port_t> void connect(const addr_t &addr, const port_t &port, const auth_t &auth, func_t func) { p_sock.connect(addr, port); Handshake_t<auth_e, handshake_e>(p_sock, auth); std::thread([func, this] { size_t buff_size; std::ostringstream buffer; while (true) { while (buff_size < 12) { auto string = p_sock.read(); buff_size += string.size(); buffer << string; } auto string = buffer.str(); buffer.clear(); buffer << string.substr(12); auto token = get_token(string.c_str()); auto size = get_size(string.c_str() + 8); while (buff_size < size) { auto string = p_sock.read(); buff_size += string.size(); buffer << string; } string = buffer.str(); buffer.clear(); buffer << string.substr(size); func(string.substr(0, size), token); } }).detach(); } void disconnect() { p_sock.disconnect(); } bool connected() const { return p_sock.connected(); } template <class query_t> std::uint64_t operator <<(query_t query) { std::ostringstream wire_query; wire_query << query; auto size = wire_query.str().size(); std::ostringstream stream; char token_bytes[8]; auto token = p_next_token++; make_token(token_bytes, token); char size_bytes[4]; make_size(size_bytes, static_cast<std::uint32_t>(size)); stream << std::string(token_bytes, 8) << std::string(size_bytes, 4) << wire_query.str(); p_sock.write(stream.str()); return token; } void stop(std::uint64_t token) { std::ostringstream wire_query; wire_query << make_query(REQL_STOP); auto size = wire_query.str().size(); std::ostringstream stream; char token_bytes[8]; make_token(token_bytes, token); char size_bytes[4]; make_size(size_bytes, static_cast<std::uint32_t>(size)); stream << std::string(token_bytes, 8) << std::string(size_bytes, 4) << wire_query.str(); p_sock.write(stream.str()); } void cont(std::uint64_t token) { std::ostringstream wire_query; wire_query << make_query(REQL_CONTINUE); auto size = wire_query.str().size(); std::ostringstream stream; char token_bytes[8]; make_token(token_bytes, token); char size_bytes[4]; make_size(size_bytes, static_cast<std::uint32_t>(size)); stream << std::string(token_bytes, 8) << std::string(size_bytes, 4) << wire_query.str(); p_sock.write(stream.str()); } private: static std::uint32_t get_size(const char *buf) { return (static_cast<std::uint32_t>(buf[0]) << 0) | (static_cast<std::uint32_t>(buf[1]) << 8) | (static_cast<std::uint32_t>(buf[2]) << 16) | (static_cast<std::uint32_t>(buf[3]) << 24); } static void make_size(char *buf, const std::uint32_t magic) { buf[0] = static_cast<char>((magic >> 0) & 0xFF); buf[1] = static_cast<char>((magic >> 8) & 0xFF); buf[2] = static_cast<char>((magic >> 16) & 0xFF); buf[3] = static_cast<char>((magic >> 24) & 0xFF); } static std::uint64_t get_token(const char *buf) { return (static_cast<std::uint64_t>(buf[0]) << 0) | (static_cast<std::uint64_t>(buf[1]) << 8) | (static_cast<std::uint64_t>(buf[2]) << 16) | (static_cast<std::uint64_t>(buf[3]) << 24) | (static_cast<std::uint64_t>(buf[4]) << 32) | (static_cast<std::uint64_t>(buf[5]) << 40) | (static_cast<std::uint64_t>(buf[6]) << 48) | (static_cast<std::uint64_t>(buf[7]) << 56); } static void make_token(char *buf, const std::uint64_t magic) { buf[0] = static_cast<char>((magic >> 0) & 0xFF); buf[1] = static_cast<char>((magic >> 8) & 0xFF); buf[2] = static_cast<char>((magic >> 16) & 0xFF); buf[3] = static_cast<char>((magic >> 24) & 0xFF); buf[4] = static_cast<char>((magic >> 32) & 0xFF); buf[5] = static_cast<char>((magic >> 40) & 0xFF); buf[6] = static_cast<char>((magic >> 48) & 0xFF); buf[7] = static_cast<char>((magic >> 56) & 0xFF); } std::atomic<std::uint64_t> p_next_token; Socket_t<socket_e> p_sock; }; } // namespace _ReQL #endif // REQL_REQL_PROTOCOL_HPP_ <commit_msg>Reduce duplicated logic.<commit_after>/* Copyright 2015 Adam Grandquist 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. */ /** * @author Adam Grandquist * @copyright Apache */ #ifndef REQL_REQL_PROTOCOL_HPP_ #define REQL_REQL_PROTOCOL_HPP_ #include "./reql/handshake.hpp" #include "./reql/query.hpp" #include "./reql/socket.hpp" #include <atomic> #include <cstdint> #include <sstream> #include <string> #include <thread> namespace _ReQL { template <class auth_e, class handshake_e, class socket_e> class Protocol_t { public: template <class addr_t, class auth_t, class func_t, class port_t> void connect(const addr_t &addr, const port_t &port, const auth_t &auth, func_t func) { p_sock.connect(addr, port); Handshake_t<auth_e, handshake_e>(p_sock, auth); std::thread([func, this] { size_t buff_size; std::ostringstream buffer; while (true) { while (buff_size < 12) { auto string = p_sock.read(); buff_size += string.size(); buffer << string; } auto string = buffer.str(); buffer.clear(); buffer << string.substr(12); auto token = get_token(string.c_str()); auto size = get_size(string.c_str() + 8); while (buff_size < size) { auto string = p_sock.read(); buff_size += string.size(); buffer << string; } string = buffer.str(); buffer.clear(); buffer << string.substr(size); func(string.substr(0, size), token); } }).detach(); } void disconnect() { p_sock.disconnect(); } bool connected() const { return p_sock.connected(); } template <class query_t> std::uint64_t operator <<(query_t query) { auto token = p_next_token++; run(token, query); return token; } void stop(std::uint64_t token) { run(token, make_query(REQL_STOP)); } void cont(std::uint64_t token) { run(token, make_query(REQL_CONTINUE)); } private: template <class query_t> void run(std::uint64_t token, query_t query) { std::ostringstream wire_query; wire_query << query; auto size = wire_query.str().size(); std::ostringstream stream; char token_bytes[8]; make_token(token_bytes, token); char size_bytes[4]; make_size(size_bytes, static_cast<std::uint32_t>(size)); stream << std::string(token_bytes, 8) << std::string(size_bytes, 4) << wire_query.str(); p_sock.write(stream.str()); } static std::uint32_t get_size(const char *buf) { return (static_cast<std::uint32_t>(buf[0]) << 0) | (static_cast<std::uint32_t>(buf[1]) << 8) | (static_cast<std::uint32_t>(buf[2]) << 16) | (static_cast<std::uint32_t>(buf[3]) << 24); } static void make_size(char *buf, const std::uint32_t magic) { buf[0] = static_cast<char>((magic >> 0) & 0xFF); buf[1] = static_cast<char>((magic >> 8) & 0xFF); buf[2] = static_cast<char>((magic >> 16) & 0xFF); buf[3] = static_cast<char>((magic >> 24) & 0xFF); } static std::uint64_t get_token(const char *buf) { return (static_cast<std::uint64_t>(buf[0]) << 0) | (static_cast<std::uint64_t>(buf[1]) << 8) | (static_cast<std::uint64_t>(buf[2]) << 16) | (static_cast<std::uint64_t>(buf[3]) << 24) | (static_cast<std::uint64_t>(buf[4]) << 32) | (static_cast<std::uint64_t>(buf[5]) << 40) | (static_cast<std::uint64_t>(buf[6]) << 48) | (static_cast<std::uint64_t>(buf[7]) << 56); } static void make_token(char *buf, const std::uint64_t magic) { buf[0] = static_cast<char>((magic >> 0) & 0xFF); buf[1] = static_cast<char>((magic >> 8) & 0xFF); buf[2] = static_cast<char>((magic >> 16) & 0xFF); buf[3] = static_cast<char>((magic >> 24) & 0xFF); buf[4] = static_cast<char>((magic >> 32) & 0xFF); buf[5] = static_cast<char>((magic >> 40) & 0xFF); buf[6] = static_cast<char>((magic >> 48) & 0xFF); buf[7] = static_cast<char>((magic >> 56) & 0xFF); } std::atomic<std::uint64_t> p_next_token; Socket_t<socket_e> p_sock; }; } // namespace _ReQL #endif // REQL_REQL_PROTOCOL_HPP_ <|endoftext|>
<commit_before>/* * Copyright (C) 2017-2018 Red Hat, Inc. * * Licensed under the GNU Lesser General Public License Version 2.1 * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ #define HEXADECIMAL DIGITS "abcdef" #define MODULE_SPECIAL "+._-" #define GLOB "][*?!" #include "nsvcap.hpp" #include "libdnf/utils/utils.hpp" #include <regex/regex.hpp> namespace libdnf { #define MODULE_NAME "([" GLOB ASCII_LETTERS DIGITS MODULE_SPECIAL "]+)" #define MODULE_STREAM MODULE_NAME #define MODULE_VERSION "([" GLOB DIGITS "-]+)" #define MODULE_CONTEXT "([" GLOB HEXADECIMAL "-]+)" #define MODULE_ARCH MODULE_NAME #define MODULE_PROFILE MODULE_NAME static const Regex NSVCAP_FORM_REGEX[]{ Regex("^" MODULE_NAME ":" MODULE_STREAM ":" MODULE_VERSION ":" MODULE_CONTEXT "::?" MODULE_ARCH "\\/" MODULE_PROFILE "$", REG_EXTENDED), Regex("^" MODULE_NAME ":" MODULE_STREAM ":" MODULE_VERSION ":" MODULE_CONTEXT "::?" MODULE_ARCH "\\/?" "()" "$", REG_EXTENDED), Regex("^" MODULE_NAME ":" MODULE_STREAM ":" MODULE_VERSION "()" "::" MODULE_ARCH "\\/" MODULE_PROFILE "$", REG_EXTENDED), Regex("^" MODULE_NAME ":" MODULE_STREAM ":" MODULE_VERSION "()" "::" MODULE_ARCH "\\/?" "()" "$", REG_EXTENDED), Regex("^" MODULE_NAME ":" MODULE_STREAM "()" "()" "::" MODULE_ARCH "\\/" MODULE_PROFILE "$", REG_EXTENDED), Regex("^" MODULE_NAME ":" MODULE_STREAM "()" "()" "::" MODULE_ARCH "\\/?" "()" "$", REG_EXTENDED), Regex("^" MODULE_NAME ":" MODULE_STREAM ":" MODULE_VERSION ":" MODULE_CONTEXT "()" "\\/" MODULE_PROFILE "$", REG_EXTENDED), Regex("^" MODULE_NAME ":" MODULE_STREAM ":" MODULE_VERSION "()" "()" "\\/" MODULE_PROFILE "$", REG_EXTENDED), Regex("^" MODULE_NAME ":" MODULE_STREAM ":" MODULE_VERSION ":" MODULE_CONTEXT "()" "\\/?" "()" "$", REG_EXTENDED), Regex("^" MODULE_NAME ":" MODULE_STREAM ":" MODULE_VERSION "()" "()" "\\/?" "()" "$", REG_EXTENDED), Regex("^" MODULE_NAME ":" MODULE_STREAM "()" "()" "()" "\\/" MODULE_PROFILE "$", REG_EXTENDED), Regex("^" MODULE_NAME ":" MODULE_STREAM "()" "()" "()" "\\/?" "()" "$", REG_EXTENDED), Regex("^" MODULE_NAME "()" "()" "()" "::" MODULE_ARCH "\\/" MODULE_PROFILE "$", REG_EXTENDED), Regex("^" MODULE_NAME "()" "()" "()" "::" MODULE_ARCH "\\/?" "()" "$", REG_EXTENDED), Regex("^" MODULE_NAME "()" "()" "()" "()" "\\/" MODULE_PROFILE "$", REG_EXTENDED), Regex("^" MODULE_NAME "()" "()" "()" "()" "\\/?" "()" "$", REG_EXTENDED) }; bool Nsvcap::parse(const char *nsvcapStr, HyModuleForm form) { enum { NAME = 1, STREAM = 2, VERSION = 3, CONTEXT = 4, ARCH = 5, PROFILE = 6, _LAST_ }; auto matchResult = NSVCAP_FORM_REGEX[form - 1].match(nsvcapStr, false, _LAST_); if (!matchResult.isMatched() || matchResult.getMatchedLen(NAME) == 0) return false; name = matchResult.getMatchedString(NAME); version = matchResult.getMatchedString(VERSION); stream = matchResult.getMatchedString(STREAM); context = matchResult.getMatchedString(CONTEXT); arch = matchResult.getMatchedString(ARCH); profile = matchResult.getMatchedString(PROFILE); return true; } void Nsvcap::clear() { name.clear(); stream.clear(); version.clear(); context.clear(); arch.clear(); profile.clear(); } } <commit_msg>Modify module NSVCA parsing - context definition (RhBug:1926771)<commit_after>/* * Copyright (C) 2017-2018 Red Hat, Inc. * * Licensed under the GNU Lesser General Public License Version 2.1 * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ #define HEXADECIMAL DIGITS "abcdef" #define MODULE_SPECIAL "+._-" #define GLOB "][*?!" #include "nsvcap.hpp" #include "libdnf/utils/utils.hpp" #include <regex/regex.hpp> namespace libdnf { #define MODULE_NAME "([" GLOB ASCII_LETTERS DIGITS MODULE_SPECIAL "]+)" #define MODULE_STREAM MODULE_NAME #define MODULE_VERSION "([" GLOB DIGITS "-]+)" #define MODULE_CONTEXT MODULE_NAME #define MODULE_ARCH MODULE_NAME #define MODULE_PROFILE MODULE_NAME static const Regex NSVCAP_FORM_REGEX[]{ Regex("^" MODULE_NAME ":" MODULE_STREAM ":" MODULE_VERSION ":" MODULE_CONTEXT "::?" MODULE_ARCH "\\/" MODULE_PROFILE "$", REG_EXTENDED), Regex("^" MODULE_NAME ":" MODULE_STREAM ":" MODULE_VERSION ":" MODULE_CONTEXT "::?" MODULE_ARCH "\\/?" "()" "$", REG_EXTENDED), Regex("^" MODULE_NAME ":" MODULE_STREAM ":" MODULE_VERSION "()" "::" MODULE_ARCH "\\/" MODULE_PROFILE "$", REG_EXTENDED), Regex("^" MODULE_NAME ":" MODULE_STREAM ":" MODULE_VERSION "()" "::" MODULE_ARCH "\\/?" "()" "$", REG_EXTENDED), Regex("^" MODULE_NAME ":" MODULE_STREAM "()" "()" "::" MODULE_ARCH "\\/" MODULE_PROFILE "$", REG_EXTENDED), Regex("^" MODULE_NAME ":" MODULE_STREAM "()" "()" "::" MODULE_ARCH "\\/?" "()" "$", REG_EXTENDED), Regex("^" MODULE_NAME ":" MODULE_STREAM ":" MODULE_VERSION ":" MODULE_CONTEXT "()" "\\/" MODULE_PROFILE "$", REG_EXTENDED), Regex("^" MODULE_NAME ":" MODULE_STREAM ":" MODULE_VERSION "()" "()" "\\/" MODULE_PROFILE "$", REG_EXTENDED), Regex("^" MODULE_NAME ":" MODULE_STREAM ":" MODULE_VERSION ":" MODULE_CONTEXT "()" "\\/?" "()" "$", REG_EXTENDED), Regex("^" MODULE_NAME ":" MODULE_STREAM ":" MODULE_VERSION "()" "()" "\\/?" "()" "$", REG_EXTENDED), Regex("^" MODULE_NAME ":" MODULE_STREAM "()" "()" "()" "\\/" MODULE_PROFILE "$", REG_EXTENDED), Regex("^" MODULE_NAME ":" MODULE_STREAM "()" "()" "()" "\\/?" "()" "$", REG_EXTENDED), Regex("^" MODULE_NAME "()" "()" "()" "::" MODULE_ARCH "\\/" MODULE_PROFILE "$", REG_EXTENDED), Regex("^" MODULE_NAME "()" "()" "()" "::" MODULE_ARCH "\\/?" "()" "$", REG_EXTENDED), Regex("^" MODULE_NAME "()" "()" "()" "()" "\\/" MODULE_PROFILE "$", REG_EXTENDED), Regex("^" MODULE_NAME "()" "()" "()" "()" "\\/?" "()" "$", REG_EXTENDED) }; bool Nsvcap::parse(const char *nsvcapStr, HyModuleForm form) { enum { NAME = 1, STREAM = 2, VERSION = 3, CONTEXT = 4, ARCH = 5, PROFILE = 6, _LAST_ }; auto matchResult = NSVCAP_FORM_REGEX[form - 1].match(nsvcapStr, false, _LAST_); if (!matchResult.isMatched() || matchResult.getMatchedLen(NAME) == 0) return false; name = matchResult.getMatchedString(NAME); version = matchResult.getMatchedString(VERSION); stream = matchResult.getMatchedString(STREAM); context = matchResult.getMatchedString(CONTEXT); arch = matchResult.getMatchedString(ARCH); profile = matchResult.getMatchedString(PROFILE); return true; } void Nsvcap::clear() { name.clear(); stream.clear(); version.clear(); context.clear(); arch.clear(); profile.clear(); } } <|endoftext|>
<commit_before>// Copyright (c) 2010 Satoshi Nakamoto // Copyright (c) 2009-2012 The Bitcoin developers // Distributed under the MIT/X11 software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. #include "main.h" #include "bitcoinrpc.h" using namespace json_spirit; using namespace std; extern void TxToJSON(const CTransaction& tx, const uint256 hashBlock, json_spirit::Object& entry); extern enum Checkpoints::CPMode CheckpointsMode; double GetDifficulty(const CBlockIndex* blockindex) { // Floating point number that is a multiple of the minimum difficulty, // minimum difficulty = 1.0. if (blockindex == NULL) { if (pindexBest == NULL) return 1.0; else blockindex = GetLastBlockIndex(pindexBest, false); } int nShift = (blockindex->nBits >> 24) & 0xff; double dDiff = (double)0x0000ffff / (double)(blockindex->nBits & 0x00ffffff); while (nShift < 29) { dDiff *= 256.0; nShift++; } while (nShift > 29) { dDiff /= 256.0; nShift--; } return dDiff; } double GetPoWMHashPS() { if (nBestHeight >= LAST_POW_BLOCK) return 0; int nPoWInterval = 72; int64_t nTargetSpacingWorkMin = 30, nTargetSpacingWork = 30; CBlockIndex* pindex = pindexGenesisBlock; CBlockIndex* pindexPrevWork = pindexGenesisBlock; while (pindex) { if (pindex->IsProofOfWork()) { int64_t nActualSpacingWork = pindex->GetBlockTime() - pindexPrevWork->GetBlockTime(); nTargetSpacingWork = ((nPoWInterval - 1) * nTargetSpacingWork + nActualSpacingWork + nActualSpacingWork) / (nPoWInterval + 1); nTargetSpacingWork = max(nTargetSpacingWork, nTargetSpacingWorkMin); pindexPrevWork = pindex; } pindex = pindex->pnext; } return GetDifficulty() * 4294.967296 / nTargetSpacingWork; } double GetPoSKernelPS(CBlockIndex* pindexPrev) { int nPoSInterval = 72; double dStakeKernelsTriedAvg = 0; int nStakesHandled = 0, nStakesTime = 0; CBlockIndex* pindexPrevStake = NULL; while (pindexPrev && nStakesHandled < nPoSInterval) { if (pindexPrev->IsProofOfStake()) { dStakeKernelsTriedAvg += GetDifficulty(pindexPrev) * 4294967296.0; nStakesTime += pindexPrevStake ? (pindexPrevStake->nTime - pindexPrev->nTime) : 0; pindexPrevStake = pindexPrev; nStakesHandled++; } pindexPrev = pindexPrev->pprev; } return nStakesTime ? dStakeKernelsTriedAvg / nStakesTime : 0; } double GetPoSKernelPS() { return GetPoSKernelPS(pindexBest); } Object blockToJSON(const CBlock& block, const CBlockIndex* blockindex, bool fPrintTransactionDetail) { Object result; result.push_back(Pair("hash", block.GetHash().GetHex())); CMerkleTx txGen(block.vtx[0]); txGen.SetMerkleBranch(&block); result.push_back(Pair("confirmations", (int)txGen.GetDepthInMainChain())); result.push_back(Pair("size", (int)::GetSerializeSize(block, SER_NETWORK, PROTOCOL_VERSION))); result.push_back(Pair("height", blockindex->nHeight)); result.push_back(Pair("version", block.nVersion)); result.push_back(Pair("merkleroot", block.hashMerkleRoot.GetHex())); result.push_back(Pair("mint", ValueFromAmount(blockindex->nMint))); result.push_back(Pair("time", (boost::int64_t)block.GetBlockTime())); result.push_back(Pair("nonce", (boost::uint64_t)block.nNonce)); result.push_back(Pair("bits", HexBits(block.nBits))); result.push_back(Pair("difficulty", GetDifficulty(blockindex))); result.push_back(Pair("blocktrust", leftTrim(blockindex->GetBlockTrust().GetHex(), '0'))); result.push_back(Pair("chaintrust", leftTrim(blockindex->nChainTrust.GetHex(), '0'))); if (blockindex->pprev) result.push_back(Pair("previousblockhash", blockindex->pprev->GetBlockHash().GetHex())); if (blockindex->pnext) result.push_back(Pair("nextblockhash", blockindex->pnext->GetBlockHash().GetHex())); result.push_back(Pair("flags", strprintf("%s%s", blockindex->IsProofOfStake()? "proof-of-stake" : "proof-of-work", blockindex->GeneratedStakeModifier()? " stake-modifier": ""))); result.push_back(Pair("proofhash", blockindex->IsProofOfStake()? blockindex->hashProofOfStake.GetHex() : blockindex->GetBlockHash().GetHex())); result.push_back(Pair("entropybit", (int)blockindex->GetStakeEntropyBit())); result.push_back(Pair("modifier", strprintf("%016"PRIx64, blockindex->nStakeModifier))); result.push_back(Pair("modifierchecksum", strprintf("%08x", blockindex->nStakeModifierChecksum))); Array txinfo; BOOST_FOREACH (const CTransaction& tx, block.vtx) { if (fPrintTransactionDetail) { Object entry; entry.push_back(Pair("txid", tx.GetHash().GetHex())); TxToJSON(tx, 0, entry); txinfo.push_back(entry); } else { txinfo.push_back(tx.GetHash().GetHex()); } } result.push_back(Pair("tx", txinfo)); if (block.IsProofOfStake()) result.push_back(Pair("signature", HexStr(block.vchBlockSig.begin(), block.vchBlockSig.end()))); return result; } Value getbestblockhash(const Array& params, bool fHelp) { if (fHelp || params.size() != 0) throw runtime_error( "getbestblockhash\n" "Returns the hash of the best block in the longest block chain."); return hashBestChain.GetHex(); } Value getblockcount(const Array& params, bool fHelp) { if (fHelp || params.size() != 0) throw runtime_error( "getblockcount\n" "Returns the number of blocks in the longest block chain."); return nBestHeight; } Value getdifficulty(const Array& params, bool fHelp) { if (fHelp || params.size() != 0) throw runtime_error( "getdifficulty\n" "Returns the difficulty as a multiple of the minimum difficulty."); Object obj; obj.push_back(Pair("proof-of-work", GetDifficulty())); obj.push_back(Pair("proof-of-stake", GetDifficulty(GetLastBlockIndex(pindexBest, true)))); obj.push_back(Pair("search-interval", (int)nLastCoinStakeSearchInterval)); return obj; } Value settxfee(const Array& params, bool fHelp) { if (fHelp || params.size() < 1 || params.size() > 1 || AmountFromValue(params[0]) < MIN_TX_FEE) throw runtime_error( "settxfee <amount>\n" "<amount> is a real and is rounded to the nearest 0.01"); nTransactionFee = AmountFromValue(params[0]); nTransactionFee = (nTransactionFee / CENT) * CENT; // round to cent return true; } Value getrawmempool(const Array& params, bool fHelp) { if (fHelp || params.size() != 0) throw runtime_error( "getrawmempool\n" "Returns all transaction ids in memory pool."); vector<uint256> vtxid; mempool.queryHashes(vtxid); Array a; BOOST_FOREACH(const uint256& hash, vtxid) a.push_back(hash.ToString()); return a; } Value getblockhash(const Array& params, bool fHelp) { if (fHelp || params.size() != 1) throw runtime_error( "getblockhash <index>\n" "Returns hash of block in best-block-chain at <index>."); int nHeight = params[0].get_int(); if (nHeight < 0 || nHeight > nBestHeight) throw runtime_error("Block number out of range."); CBlockIndex* pblockindex = FindBlockByHeight(nHeight); return pblockindex->phashBlock->GetHex(); } Value getblock(const Array& params, bool fHelp) { if (fHelp || params.size() < 1 || params.size() > 2) throw runtime_error( "getblock <hash> [txinfo]\n" "txinfo optional to print more detailed tx info\n" "Returns details of a block with given block-hash."); std::string strHash = params[0].get_str(); uint256 hash(strHash); if (mapBlockIndex.count(hash) == 0) throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, "Block not found"); CBlock block; CBlockIndex* pblockindex = mapBlockIndex[hash]; block.ReadFromDisk(pblockindex, true); return blockToJSON(block, pblockindex, params.size() > 1 ? params[1].get_bool() : false); } Value getblockbynumber(const Array& params, bool fHelp) { if (fHelp || params.size() < 1 || params.size() > 2) throw runtime_error( "getblock <number> [txinfo]\n" "txinfo optional to print more detailed tx info\n" "Returns details of a block with given block-number."); int nHeight = params[0].get_int(); if (nHeight < 0 || nHeight > nBestHeight) throw runtime_error("Block number out of range."); CBlock block; CBlockIndex* pblockindex = mapBlockIndex[hashBestChain]; while (pblockindex->nHeight > nHeight) pblockindex = pblockindex->pprev; uint256 hash = *pblockindex->phashBlock; pblockindex = mapBlockIndex[hash]; block.ReadFromDisk(pblockindex, true); return blockToJSON(block, pblockindex, params.size() > 1 ? params[1].get_bool() : false); } // ppcoin: get information of sync-checkpoint Value getcheckpoint(const Array& params, bool fHelp) { if (fHelp || params.size() != 0) throw runtime_error( "getcheckpoint\n" "Show info of synchronized checkpoint.\n"); Object result; CBlockIndex* pindexCheckpoint; result.push_back(Pair("synccheckpoint", Checkpoints::hashSyncCheckpoint.ToString().c_str())); pindexCheckpoint = mapBlockIndex[Checkpoints::hashSyncCheckpoint]; result.push_back(Pair("height", pindexCheckpoint->nHeight)); result.push_back(Pair("timestamp", DateTimeStrFormat(pindexCheckpoint->GetBlockTime()).c_str())); // Check that the block satisfies synchronized checkpoint if (CheckpointsMode == Checkpoints::CPSTRICT) result.push_back(Pair("policy", "strict")); if (CheckpointsMode == Checkpoints::CPADVISORY) result.push_back(Pair("policy", "advisory")); if (CheckpointsMode == Checkpoints::CPPERMISSIVE) result.push_back(Pair("policy", "permissive")); if (mapArgs.count("-checkpointkey")) result.push_back(Pair("checkpointmaster", true)); return result; } <commit_msg>turn off check for best height<commit_after>// Copyright (c) 2010 Satoshi Nakamoto // Copyright (c) 2009-2012 The Bitcoin developers // Distributed under the MIT/X11 software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. #include "main.h" #include "bitcoinrpc.h" using namespace json_spirit; using namespace std; extern void TxToJSON(const CTransaction& tx, const uint256 hashBlock, json_spirit::Object& entry); extern enum Checkpoints::CPMode CheckpointsMode; double GetDifficulty(const CBlockIndex* blockindex) { // Floating point number that is a multiple of the minimum difficulty, // minimum difficulty = 1.0. if (blockindex == NULL) { if (pindexBest == NULL) return 1.0; else blockindex = GetLastBlockIndex(pindexBest, false); } int nShift = (blockindex->nBits >> 24) & 0xff; double dDiff = (double)0x0000ffff / (double)(blockindex->nBits & 0x00ffffff); while (nShift < 29) { dDiff *= 256.0; nShift++; } while (nShift > 29) { dDiff /= 256.0; nShift--; } return dDiff; } double GetPoWMHashPS() { // DEBUG //if (nBestHeight >= LAST_POW_BLOCK) // return 0; int nPoWInterval = 72; int64_t nTargetSpacingWorkMin = 30, nTargetSpacingWork = 30; CBlockIndex* pindex = pindexGenesisBlock; CBlockIndex* pindexPrevWork = pindexGenesisBlock; while (pindex) { if (pindex->IsProofOfWork()) { int64_t nActualSpacingWork = pindex->GetBlockTime() - pindexPrevWork->GetBlockTime(); nTargetSpacingWork = ((nPoWInterval - 1) * nTargetSpacingWork + nActualSpacingWork + nActualSpacingWork) / (nPoWInterval + 1); nTargetSpacingWork = max(nTargetSpacingWork, nTargetSpacingWorkMin); pindexPrevWork = pindex; } pindex = pindex->pnext; } return GetDifficulty() * 4294.967296 / nTargetSpacingWork; } double GetPoSKernelPS(CBlockIndex* pindexPrev) { int nPoSInterval = 72; double dStakeKernelsTriedAvg = 0; int nStakesHandled = 0, nStakesTime = 0; CBlockIndex* pindexPrevStake = NULL; while (pindexPrev && nStakesHandled < nPoSInterval) { if (pindexPrev->IsProofOfStake()) { dStakeKernelsTriedAvg += GetDifficulty(pindexPrev) * 4294967296.0; nStakesTime += pindexPrevStake ? (pindexPrevStake->nTime - pindexPrev->nTime) : 0; pindexPrevStake = pindexPrev; nStakesHandled++; } pindexPrev = pindexPrev->pprev; } return nStakesTime ? dStakeKernelsTriedAvg / nStakesTime : 0; } double GetPoSKernelPS() { return GetPoSKernelPS(pindexBest); } Object blockToJSON(const CBlock& block, const CBlockIndex* blockindex, bool fPrintTransactionDetail) { Object result; result.push_back(Pair("hash", block.GetHash().GetHex())); CMerkleTx txGen(block.vtx[0]); txGen.SetMerkleBranch(&block); result.push_back(Pair("confirmations", (int)txGen.GetDepthInMainChain())); result.push_back(Pair("size", (int)::GetSerializeSize(block, SER_NETWORK, PROTOCOL_VERSION))); result.push_back(Pair("height", blockindex->nHeight)); result.push_back(Pair("version", block.nVersion)); result.push_back(Pair("merkleroot", block.hashMerkleRoot.GetHex())); result.push_back(Pair("mint", ValueFromAmount(blockindex->nMint))); result.push_back(Pair("time", (boost::int64_t)block.GetBlockTime())); result.push_back(Pair("nonce", (boost::uint64_t)block.nNonce)); result.push_back(Pair("bits", HexBits(block.nBits))); result.push_back(Pair("difficulty", GetDifficulty(blockindex))); result.push_back(Pair("blocktrust", leftTrim(blockindex->GetBlockTrust().GetHex(), '0'))); result.push_back(Pair("chaintrust", leftTrim(blockindex->nChainTrust.GetHex(), '0'))); if (blockindex->pprev) result.push_back(Pair("previousblockhash", blockindex->pprev->GetBlockHash().GetHex())); if (blockindex->pnext) result.push_back(Pair("nextblockhash", blockindex->pnext->GetBlockHash().GetHex())); result.push_back(Pair("flags", strprintf("%s%s", blockindex->IsProofOfStake()? "proof-of-stake" : "proof-of-work", blockindex->GeneratedStakeModifier()? " stake-modifier": ""))); result.push_back(Pair("proofhash", blockindex->IsProofOfStake()? blockindex->hashProofOfStake.GetHex() : blockindex->GetBlockHash().GetHex())); result.push_back(Pair("entropybit", (int)blockindex->GetStakeEntropyBit())); result.push_back(Pair("modifier", strprintf("%016"PRIx64, blockindex->nStakeModifier))); result.push_back(Pair("modifierchecksum", strprintf("%08x", blockindex->nStakeModifierChecksum))); Array txinfo; BOOST_FOREACH (const CTransaction& tx, block.vtx) { if (fPrintTransactionDetail) { Object entry; entry.push_back(Pair("txid", tx.GetHash().GetHex())); TxToJSON(tx, 0, entry); txinfo.push_back(entry); } else { txinfo.push_back(tx.GetHash().GetHex()); } } result.push_back(Pair("tx", txinfo)); if (block.IsProofOfStake()) result.push_back(Pair("signature", HexStr(block.vchBlockSig.begin(), block.vchBlockSig.end()))); return result; } Value getbestblockhash(const Array& params, bool fHelp) { if (fHelp || params.size() != 0) throw runtime_error( "getbestblockhash\n" "Returns the hash of the best block in the longest block chain."); return hashBestChain.GetHex(); } Value getblockcount(const Array& params, bool fHelp) { if (fHelp || params.size() != 0) throw runtime_error( "getblockcount\n" "Returns the number of blocks in the longest block chain."); return nBestHeight; } Value getdifficulty(const Array& params, bool fHelp) { if (fHelp || params.size() != 0) throw runtime_error( "getdifficulty\n" "Returns the difficulty as a multiple of the minimum difficulty."); Object obj; obj.push_back(Pair("proof-of-work", GetDifficulty())); obj.push_back(Pair("proof-of-stake", GetDifficulty(GetLastBlockIndex(pindexBest, true)))); obj.push_back(Pair("search-interval", (int)nLastCoinStakeSearchInterval)); return obj; } Value settxfee(const Array& params, bool fHelp) { if (fHelp || params.size() < 1 || params.size() > 1 || AmountFromValue(params[0]) < MIN_TX_FEE) throw runtime_error( "settxfee <amount>\n" "<amount> is a real and is rounded to the nearest 0.01"); nTransactionFee = AmountFromValue(params[0]); nTransactionFee = (nTransactionFee / CENT) * CENT; // round to cent return true; } Value getrawmempool(const Array& params, bool fHelp) { if (fHelp || params.size() != 0) throw runtime_error( "getrawmempool\n" "Returns all transaction ids in memory pool."); vector<uint256> vtxid; mempool.queryHashes(vtxid); Array a; BOOST_FOREACH(const uint256& hash, vtxid) a.push_back(hash.ToString()); return a; } Value getblockhash(const Array& params, bool fHelp) { if (fHelp || params.size() != 1) throw runtime_error( "getblockhash <index>\n" "Returns hash of block in best-block-chain at <index>."); int nHeight = params[0].get_int(); if (nHeight < 0 || nHeight > nBestHeight) throw runtime_error("Block number out of range."); CBlockIndex* pblockindex = FindBlockByHeight(nHeight); return pblockindex->phashBlock->GetHex(); } Value getblock(const Array& params, bool fHelp) { if (fHelp || params.size() < 1 || params.size() > 2) throw runtime_error( "getblock <hash> [txinfo]\n" "txinfo optional to print more detailed tx info\n" "Returns details of a block with given block-hash."); std::string strHash = params[0].get_str(); uint256 hash(strHash); if (mapBlockIndex.count(hash) == 0) throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, "Block not found"); CBlock block; CBlockIndex* pblockindex = mapBlockIndex[hash]; block.ReadFromDisk(pblockindex, true); return blockToJSON(block, pblockindex, params.size() > 1 ? params[1].get_bool() : false); } Value getblockbynumber(const Array& params, bool fHelp) { if (fHelp || params.size() < 1 || params.size() > 2) throw runtime_error( "getblock <number> [txinfo]\n" "txinfo optional to print more detailed tx info\n" "Returns details of a block with given block-number."); int nHeight = params[0].get_int(); if (nHeight < 0 || nHeight > nBestHeight) throw runtime_error("Block number out of range."); CBlock block; CBlockIndex* pblockindex = mapBlockIndex[hashBestChain]; while (pblockindex->nHeight > nHeight) pblockindex = pblockindex->pprev; uint256 hash = *pblockindex->phashBlock; pblockindex = mapBlockIndex[hash]; block.ReadFromDisk(pblockindex, true); return blockToJSON(block, pblockindex, params.size() > 1 ? params[1].get_bool() : false); } // ppcoin: get information of sync-checkpoint Value getcheckpoint(const Array& params, bool fHelp) { if (fHelp || params.size() != 0) throw runtime_error( "getcheckpoint\n" "Show info of synchronized checkpoint.\n"); Object result; CBlockIndex* pindexCheckpoint; result.push_back(Pair("synccheckpoint", Checkpoints::hashSyncCheckpoint.ToString().c_str())); pindexCheckpoint = mapBlockIndex[Checkpoints::hashSyncCheckpoint]; result.push_back(Pair("height", pindexCheckpoint->nHeight)); result.push_back(Pair("timestamp", DateTimeStrFormat(pindexCheckpoint->GetBlockTime()).c_str())); // Check that the block satisfies synchronized checkpoint if (CheckpointsMode == Checkpoints::CPSTRICT) result.push_back(Pair("policy", "strict")); if (CheckpointsMode == Checkpoints::CPADVISORY) result.push_back(Pair("policy", "advisory")); if (CheckpointsMode == Checkpoints::CPPERMISSIVE) result.push_back(Pair("policy", "permissive")); if (mapArgs.count("-checkpointkey")) result.push_back(Pair("checkpointmaster", true)); return result; } <|endoftext|>
<commit_before>#include <FL/Fl_Window.H> #include <FL/Fl_Text_Editor.H> #include <FL/Fl_Text_Buffer.H> #include <FL/Fl_Menu_Bar.H> #include <FL/Fl_Menu_Item.H> #include <FL/Fl.H> #include <FL/Enumerations.H> #include <FL/fl_ask.H> #include <string> #include <cstdio> #include <cassert> /* An example of a text editor program that crashes with FLTK 1.3.3 It only seems to crash in OS X (I've only tried 10.10), not Linux. I also did not have this issue with 1.3.2 (although I have not tried this test with 1.3.2). To make it crash within minutes, all I have to do is open a file (I've used a copy of this file, flare.cpp, to test this), start making small changes, and at some point it will crash. This seems to happen most often when a focus even happens, when I click a menu entry, or when I copy or paste. I actually wondered for a long time if it had to do mainly with c&p, but it will (very occasionally) crash when loading a file, as well. The crashes appear as heap corruption, or as a warning that I've damaged an OS X canary that is put on freed objects (object modified after free). I do not know which one of the two (if either) is true. This text editor is featureful enough that I can actually use it for non-contrived purposes, but it is still small enough that it seems a good example. The usefulness is important to me, anyway, since that makes it much easier to actually do enough to cause a crash. I accept that this could still be my mistake. But I've made many attempts to write a text editor with FLTK, each from scratch, and all of them have these same issues rather extremely. Perhaps it is that I am mishandling the text in the text buffer. In that case, I would certainly love to hear what I am doing wrong. I have attempted to follow the documentation on how to use them as close as I can! */ // Shorthand. inline Fl_Text_Buffer *CreateTextBuffer(){ return new Fl_Text_Buffer(0x100, 0x100); } // A couple attributes for our files. struct EditorData { std::string path; }; // Basically dump what we know. void Info(Fl_Text_Editor *ed){ assert(ed); fl_alert("Editor information:\npath: %s\n", static_cast<struct EditorData *>(ed->user_data())->path.c_str()); } bool Load(Fl_Text_Editor *ed, const char *path){ assert(ed); assert(path); FILE *that = fopen(path, "r"); if(!that){ fl_alert("Cannot open file %s", path); return false; } // Buffer the file in. char buffer[0x100]; unsigned to = 0; // Clear the buffer ed->buffer()->text(nullptr); // Load the file. do{ to = fread(buffer, 1, 0xFF, that); buffer[to] = 0; ed->buffer()->append(buffer); }while(to==0xFF); fclose(that); static_cast<struct EditorData *>(ed->user_data())->path = path; return true; } void Save(Fl_Text_Editor *ed, const char *path){ assert(ed); assert(path); char buffer[0x100]; unsigned to = 0; // Create a backup of the original file, just in case :) const std::string new_file_name = std::string(path)+".baku"; rename(path, new_file_name.c_str()); FILE *that = fopen(path, "w"); if(that){ const char *text = ed->buffer()->text(); const unsigned length = strlen(text); // Try to write the file. if(fwrite(text, 1, length, that)!=length){ fl_alert("Could not save file %s.", path); return; } fclose(that); // If we succeeded, we don't need the backup any more. remove(new_file_name.c_str()); } else // Alert if we couldn't open the file for saving. fl_alert("Could save file %s.", path); } void InfoCallback(Fl_Widget *w, void *a){ Fl_Text_Editor *ed = static_cast<Fl_Text_Editor *>(a); Info(ed); } void SaveCallback(Fl_Widget *w, void *a){ Fl_Text_Editor *ed = static_cast<Fl_Text_Editor *>(a); const std::string path = static_cast<struct EditorData *>(ed->user_data())->path; Save(ed, path.c_str()); } void SaveAsCallback(Fl_Widget *w, void *a){ Fl_Text_Editor *ed = static_cast<Fl_Text_Editor *>(a); std::string &path = static_cast<struct EditorData *>(ed->user_data())->path; const char *file_name = fl_input("Choose a file", nullptr); if(file_name){ path = file_name; Save(ed, path.c_str()); } } void LoadCallback(Fl_Widget *w, void *a){ Fl_Text_Editor *ed = static_cast<Fl_Text_Editor *>(a); std::string &path = static_cast<struct EditorData *>(ed->user_data())->path; if(!path.empty()){ switch(fl_choice("Save changes to file %s?", fl_no, fl_yes, fl_cancel, path.c_str())){ case 0: break; case 1: Save(ed, path.c_str()); break; case 2: return; } } const char *file_name = fl_input("Choose a file", nullptr); if(file_name){ path = file_name; Load(ed, path.c_str()); } } int main(int argc, char *argv[]){ Fl_Window this_window(800, 400, "Flare Editor"); Fl_Menu_Bar main_bar(0, 0, 800, 24); Fl_Text_Editor editor(0, 24, 800, 400-24); editor.user_data(new struct EditorData); editor.textfont(FL_SCREEN); editor.buffer(CreateTextBuffer()); #if FLTK_ABI_VERSION == 10303 editor.linenumber_width(64); #endif editor.end(); this_window.resizable(editor); Fl_Menu_Item menu[] = { {"File", 0, 0, 0, FL_SUBMENU}, {"Open", FL_COMMAND+'o', LoadCallback, &editor}, {"Save", FL_COMMAND+'s', SaveCallback, &editor}, {"Save As", FL_COMMAND+FL_SHIFT+'s', SaveAsCallback, &editor}, {0}, {"Edit", 0, 0, 0, FL_SUBMENU}, {"Properties", FL_COMMAND+'?', InfoCallback, &editor}, {0}, {0} }; main_bar.menu(menu); this_window.show(); this_window.end(); if(argc>1){ Load(&editor, argv[1]); } else{ const char *file_name = fl_input("Choose a file", nullptr); if(file_name && file_name[0]!=0){ Load(&editor, file_name); } } this_window.redraw(); return Fl::run(); } <commit_msg>Removed old file<commit_after><|endoftext|>
<commit_before><commit_msg>third_party: fix tf2 invalid printf arg type<commit_after><|endoftext|>
<commit_before>/* * Copyright 2021 The Imaging Source Europe GmbH * * 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. */ #include "devicewidget.h" DeviceWidget::DeviceWidget(const Device& dev, QListWidget* parent) : QListWidgetItem(parent), _dev(dev) { setIcon(QIcon(QString(icon_path.c_str()))); setTextAlignment(Qt::AlignHCenter | Qt::AlignBottom); setText((_dev.model() + "\n" + _dev.serial() + "\n" + _dev.type()).c_str()); setSizeHint({160,120}); } bool DeviceWidget::operator==(const Device& dev) const { if (_dev == dev) { return true; } return false; } Device DeviceWidget::get_device() const { return _dev; } QSize DeviceWidget::minimumSizeHint() const { QSize s = sizeHint(); return s; }<commit_msg>tcam-capture: Increase DeviceWidget size<commit_after>/* * Copyright 2021 The Imaging Source Europe GmbH * * 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. */ #include "devicewidget.h" DeviceWidget::DeviceWidget(const Device& dev, QListWidget* parent) : QListWidgetItem(parent), _dev(dev) { setIcon(QIcon(QString(icon_path.c_str()))); setTextAlignment(Qt::AlignHCenter | Qt::AlignBottom); setText((_dev.model() + "\n" + _dev.serial() + "\n" + _dev.type()).c_str()); setSizeHint({160,140}); } bool DeviceWidget::operator==(const Device& dev) const { if (_dev == dev) { return true; } return false; } Device DeviceWidget::get_device() const { return _dev; } QSize DeviceWidget::minimumSizeHint() const { QSize s = sizeHint(); return s; } <|endoftext|>
<commit_before>/**************************************************************************** ** ** Copyright (C) 2014 Jolla Ltd. ** Contact: Vesa-Matti Hartikainen <vesa-matti.hartikainen@jollamobile.com> ** ****************************************************************************/ /* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this file, * You can obtain one at http://mozilla.org/MPL/2.0/. */ #include "bookmarkmanager.h" #include <QDebug> #include <QFile> #include <QTextStream> #include <QJsonObject> #include <QJsonArray> #include <QJsonDocument> #include <QRegularExpression> #include <MGConfItem> #include "bookmark.h" #include "browserpaths.h" BookmarkManager::BookmarkManager() : QObject(nullptr) { m_clearBookmarksConfItem = new MGConfItem("/apps/sailfish-browser/actions/clear_bookmarks", this); clearBookmarks(); connect(m_clearBookmarksConfItem.data(), &MGConfItem::valueChanged, this, &BookmarkManager::clearBookmarks); } BookmarkManager* BookmarkManager::instance() { static BookmarkManager* singleton; if (!singleton) { singleton = new BookmarkManager(); } return singleton; } void BookmarkManager::save(const QList<Bookmark*> & bookmarks) { QString dataLocation = BrowserPaths::dataLocation(); if (dataLocation.isNull()) { return; } QString path = dataLocation + "/bookmarks.json"; QFile file(path); if (!file.open(QIODevice::WriteOnly | QIODevice::Text)) { qWarning() << "Can't create file " << path; return; } QTextStream out(&file); QJsonArray items; foreach (Bookmark* bookmark, bookmarks) { QJsonObject title; title.insert("url", QJsonValue(bookmark->url())); title.insert("title", QJsonValue(bookmark->title())); title.insert("favicon", QJsonValue(bookmark->favicon())); title.insert("hasTouchIcon", QJsonValue(bookmark->hasTouchIcon())); items.append(QJsonValue(title)); } QJsonDocument doc(items); out.setCodec("UTF-8"); out << doc.toJson(); file.close(); } void BookmarkManager::clear() { save(QList<Bookmark*>()); emit cleared(); } QList<Bookmark*> BookmarkManager::load() { QList<Bookmark*> bookmarks; QString bookmarkFile = BrowserPaths::dataLocation() + "/bookmarks.json"; QScopedPointer<QFile> file(new QFile(bookmarkFile)); if (!file->open(QIODevice::ReadOnly | QIODevice::Text)) { qWarning() << "Unable to open bookmarks " << bookmarkFile; file.reset(new QFile(QLatin1Literal("/usr/share/sailfish-browser/default-content/bookmarks.json"))); if (!file->open(QIODevice::ReadOnly | QIODevice::Text)) { qWarning() << "Unable to open bookmarks defaults"; return bookmarks; } } QJsonDocument doc = QJsonDocument::fromJson(file->readAll()); if (doc.isArray()) { QJsonArray array = doc.array(); for (const QJsonValue &value : array) { if (value.isObject()) { QJsonObject obj = value.toObject(); QString url = obj.value("url").toString(); QString favicon = obj.value("favicon").toString(); Bookmark* m = new Bookmark(obj.value("title").toString(), url, favicon, obj.value("hasTouchIcon").toBool()); bookmarks.append(m); } } } else { qWarning() << "Bookmarks.json should be an array of items"; } file->close(); return bookmarks; } void BookmarkManager::clearBookmarks() { if (m_clearBookmarksConfItem->value(false).toBool()) { clear(); m_clearBookmarksConfItem->set(false); } } <commit_msg>[browser] Migrate potential leftover bookmarks. Fixes JB#53083<commit_after>/**************************************************************************** ** ** Copyright (C) 2014 Jolla Ltd. ** Contact: Vesa-Matti Hartikainen <vesa-matti.hartikainen@jollamobile.com> ** ****************************************************************************/ /* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this file, * You can obtain one at http://mozilla.org/MPL/2.0/. */ #include "bookmarkmanager.h" #include <QDebug> #include <QFile> #include <QTextStream> #include <QJsonObject> #include <QJsonArray> #include <QJsonDocument> #include <QRegularExpression> #include <MGConfItem> #include <QStandardPaths> #include "bookmark.h" #include "browserpaths.h" BookmarkManager::BookmarkManager() : QObject(nullptr) { m_clearBookmarksConfItem = new MGConfItem("/apps/sailfish-browser/actions/clear_bookmarks", this); clearBookmarks(); connect(m_clearBookmarksConfItem.data(), &MGConfItem::valueChanged, this, &BookmarkManager::clearBookmarks); } BookmarkManager* BookmarkManager::instance() { static BookmarkManager* singleton; if (!singleton) { singleton = new BookmarkManager(); } return singleton; } void BookmarkManager::save(const QList<Bookmark*> & bookmarks) { QString dataLocation = BrowserPaths::dataLocation(); if (dataLocation.isNull()) { return; } QString path = dataLocation + "/bookmarks.json"; QFile file(path); if (!file.open(QIODevice::WriteOnly | QIODevice::Text)) { qWarning() << "Can't create file " << path; return; } QTextStream out(&file); QJsonArray items; foreach (Bookmark* bookmark, bookmarks) { QJsonObject title; title.insert("url", QJsonValue(bookmark->url())); title.insert("title", QJsonValue(bookmark->title())); title.insert("favicon", QJsonValue(bookmark->favicon())); title.insert("hasTouchIcon", QJsonValue(bookmark->hasTouchIcon())); items.append(QJsonValue(title)); } QJsonDocument doc(items); out.setCodec("UTF-8"); out << doc.toJson(); file.close(); } void BookmarkManager::clear() { save(QList<Bookmark*>()); emit cleared(); } QList<Bookmark*> BookmarkManager::load() { QList<Bookmark*> bookmarks; QString bookmarkFile = BrowserPaths::dataLocation() + "/bookmarks.json"; QScopedPointer<QFile> file(new QFile(bookmarkFile)); if (!file->open(QIODevice::ReadOnly | QIODevice::Text)) { qWarning() << "Unable to open bookmarks " << bookmarkFile; file.reset(new QFile(QLatin1Literal("/usr/share/sailfish-browser/default-content/bookmarks.json"))); if (!file->open(QIODevice::ReadOnly | QIODevice::Text)) { qWarning() << "Unable to open bookmarks defaults"; return bookmarks; } } QJsonDocument doc = QJsonDocument::fromJson(file->readAll()); if (doc.isArray()) { QJsonArray array = doc.array(); for (const QJsonValue &value : array) { if (value.isObject()) { QJsonObject obj = value.toObject(); QString url = obj.value("url").toString(); QString favicon = obj.value("favicon").toString(); Bookmark* m = new Bookmark(obj.value("title").toString(), url, favicon, obj.value("hasTouchIcon").toBool()); bookmarks.append(m); } } } else { qWarning() << "Bookmarks.json should be an array of items"; } file->close(); // Cleanup after next stop release. See JB#53083 and JB#52736 bookmarkFile = QStandardPaths::writableLocation(QStandardPaths::GenericDataLocation) + QLatin1String("/org.sailfishos/sailfish-browser/bookmarks.json"); file.reset(new QFile(bookmarkFile)); if (file->exists() && file->open(QIODevice::ReadOnly | QIODevice::Text)) { QJsonDocument doc = QJsonDocument::fromJson(file->readAll()); if (doc.isArray()) { QJsonArray array = doc.array(); for (const QJsonValue &value : array) { if (value.isObject()) { QJsonObject obj = value.toObject(); QString url = obj.value("url").toString(); bool migrate = true; for (const Bookmark *bookmark : bookmarks) { if (bookmark->url() == url) { migrate = false; break; } } if (migrate) { Bookmark* m = new Bookmark(obj.value("title").toString(), url, obj.value("favicon").toString(), obj.value("hasTouchIcon").toBool()); bookmarks.append(m); } } } } file->close(); file->remove(); save(bookmarks); } // End of stop release cleanup... return bookmarks; } void BookmarkManager::clearBookmarks() { if (m_clearBookmarksConfItem->value(false).toBool()) { clear(); m_clearBookmarksConfItem->set(false); } } <|endoftext|>
<commit_before>/* ** * BEGIN_COPYRIGHT * * This file is part of SciDB. Copyright (C) 2008-2014 SciDB, Inc. * * Superfunpack 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. * * SciDB is distributed "AS-IS" AND WITHOUT ANY WARRANTY OF ANY KIND, INCLUDING * ANY IMPLIED WARRANTY OF MERCHANTABILITY, NON-INFRINGEMENT, OR FITNESS FOR A * PARTICULAR PURPOSE. See the GNU General Public License version 2 for the * complete license terms. * * END_COPYRIGHT */ #define _XOPEN_SOURCE #include <stdio.h> #include <string.h> #include <errno.h> #include <boost/assign.hpp> #include <boost/math/distributions/hypergeometric.hpp> #include <boost/math/tools/roots.hpp> #include "query/FunctionLibrary.h" #include "query/FunctionDescription.h" #include "system/ErrorsLibrary.h" using namespace std; using namespace scidb; using namespace boost::assign; /* * @brief Parse the data string into a ms time value. * @param data (string) input data, assumed to be in the form HH:MM:SS.MLS * @returns int64 * XXX use strtol here instead of atoi... */ static void tm2ms(const Value** args, Value *res, void*) { int j, k; char *data, *p1, *p2, *token, *subtoken, *str2; int64_t ms = 0; for (j = 1, data = (char *) args[0]->getString(); ; j++, data=NULL) { token = strtok_r(data, ":", &p1); if (token == NULL) break; switch(j) { case 1: ms = ms + 3600000 * ((int64_t) atoi(token)); break; case 2: ms = ms + 60000 * ((int64_t) atoi(token)); break; case 3: for (k=1, str2=token; ; k++, str2=NULL) { subtoken = strtok_r(str2, ".", &p2); if (subtoken == NULL) break; if(k==1) ms = ms + 1000*((int64_t) atoi(subtoken)); else if(k==2) { ms = ms + (int64_t) atoi(subtoken); break; } } default: break; } } res->setInt64(ms); } REGISTER_FUNCTION(tm2ms, list_of("string"), "int64", tm2ms); <commit_msg>Added fastdate function<commit_after>/* ** * BEGIN_COPYRIGHT * * This file is part of SciDB. Copyright (C) 2008-2014 SciDB, Inc. * * Superfunpack 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. * * SciDB is distributed "AS-IS" AND WITHOUT ANY WARRANTY OF ANY KIND, INCLUDING * ANY IMPLIED WARRANTY OF MERCHANTABILITY, NON-INFRINGEMENT, OR FITNESS FOR A * PARTICULAR PURPOSE. See the GNU General Public License version 2 for the * complete license terms. * * END_COPYRIGHT */ #define _XOPEN_SOURCE #include <stdio.h> #include <string.h> #include <errno.h> #include <boost/assign.hpp> #include <boost/math/distributions/hypergeometric.hpp> #include <boost/math/tools/roots.hpp> #include "query/FunctionLibrary.h" #include "query/FunctionDescription.h" #include "system/ErrorsLibrary.h" using namespace std; using namespace scidb; using namespace boost::assign; /* * @brief Parse the data string into a ms time value. * @param data (string) input data, assumed to be in the form HH:MM:SS.MLS * @returns int64 * XXX use strtol here instead of atoi... */ static void tm2ms(const Value** args, Value *res, void*) { int j, k; char *data, *p1, *p2, *token, *subtoken, *str2; int64_t ms = 0; for (j = 1, data = (char *) args[0]->getString(); ; j++, data=NULL) { token = strtok_r(data, ":", &p1); if (token == NULL) break; switch(j) { case 1: ms = ms + 3600000 * ((int64_t) atoi(token)); break; case 2: ms = ms + 60000 * ((int64_t) atoi(token)); break; case 3: for (k=1, str2=token; ; k++, str2=NULL) { subtoken = strtok_r(str2, ".", &p2); if (subtoken == NULL) break; if(k==1) ms = ms + 1000*((int64_t) atoi(subtoken)); else if(k==2) { ms = ms + (int64_t) atoi(subtoken); break; } } } } res->setInt64(ms); } inline int fast_atoi( const char * str ) { int val = 0; while( *str ) val = val*10 + (*str++ - '0'); return val; } /* Cheesy but fast and order-preserving date string to integer. * ASSUMES date in YYYY-MM-DD format! No error checking! */ static void fastdate(const Value** args, Value *res, void*) { int j; char *data, *p1, *token; int x[3] = {10000, 100, 1}; // year, month, day int64_t ans = 0; for (j = 0, data = (char *) args[0]->getString(); ; j++, data=NULL) { token = strtok_r(data, "-", &p1); if (token == NULL) break; ans = ans + fast_atoi(token)*x[j]; } res->setInt64(ans); } REGISTER_FUNCTION(tm2ms, list_of("string"), "int64", tm2ms); REGISTER_FUNCTION(fastdate, list_of("string"), "int64", fastdate); <|endoftext|>
<commit_before>// Copyright 2012~2013, Weng Xuetian <wengxt@gmail.com> // 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 Google Inc. 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. // workaround #define _FCITX_LOG_H_ #include <fcitx/instance.h> #include <fcitx/ime.h> #include <fcitx/hook.h> #include <fcitx/module.h> #include <fcitx/keys.h> #include <fcitx-config/xdg.h> #include "fcitx_mozc.h" #include "mozc_connection.h" #include "mozc_response_parser.h" typedef struct _FcitxMozcState { mozc::fcitx::FcitxMozc* mozc; int inUsageState; } FcitxMozcState; static void* FcitxMozcCreate(FcitxInstance* instance); static void FcitxMozcDestroy(void *arg); static boolean FcitxMozcInit(void *arg); /**< FcitxMozcInit */ static void FcitxMozcResetIM(void *arg); /**< FcitxMozcResetIM */ static void FcitxMozcReset(void *arg); /**< FcitxMozcResetIM */ static INPUT_RETURN_VALUE FcitxMozcDoInput(void *arg, FcitxKeySym, unsigned int); /**< FcitxMozcDoInput */ static INPUT_RETURN_VALUE FcitxMozcDoReleaseInput(void *arg, FcitxKeySym, unsigned int); /**< FcitxMozcDoInput */ static void FcitxMozcSave(void *arg); /**< FcitxMozcSave */ static void FcitxMozcReloadConfig(void *arg); /**< FcitxMozcReloadConfig */ extern "C" { FCITX_EXPORT_API FcitxIMClass ime = { FcitxMozcCreate, FcitxMozcDestroy }; FCITX_EXPORT_API int ABI_VERSION = FCITX_ABI_VERSION; } static inline bool CheckLayout(FcitxInstance* instance) { char *layout = NULL, *variant = NULL; FcitxModuleFunctionArg args; args.args[0] = &layout; args.args[1] = &variant; bool layout_is_jp = false; FcitxModuleInvokeFunctionByName(instance, "fcitx-xkb", 1, args); if (layout && strcmp(layout, "jp") == 0) layout_is_jp = true; fcitx_utils_free(layout); fcitx_utils_free(variant); return layout_is_jp; } static void* FcitxMozcCreate(FcitxInstance* instance) { FcitxMozcState* mozcState = (FcitxMozcState*) fcitx_utils_malloc0(sizeof(FcitxMozcState)); bindtextdomain("fcitx-mozc", LOCALEDIR); mozcState->mozc = new mozc::fcitx::FcitxMozc( instance, mozc::fcitx::MozcConnection::CreateMozcConnection(), new mozc::fcitx::MozcResponseParser ); mozcState->mozc->SetCompositionMode(mozc::commands::HIRAGANA); FcitxIMEventHook hk; hk.arg = mozcState; hk.func = FcitxMozcReset; FcitxInstanceRegisterResetInputHook(instance, hk); FcitxIMIFace iface; memset(&iface, 0, sizeof(FcitxIMIFace)); iface.Init = FcitxMozcInit; iface.ResetIM = FcitxMozcResetIM; iface.DoInput = FcitxMozcDoInput; iface.DoReleaseInput = FcitxMozcDoReleaseInput; iface.ReloadConfig = FcitxMozcReloadConfig; iface.Save = FcitxMozcSave; FcitxInstanceRegisterIMv2( instance, mozcState, "mozc", "Mozc", mozcState->mozc->GetIconFile("mozc.png").c_str(), iface, 1, "ja" ); return mozcState; } static void FcitxMozcDestroy(void *arg) { FcitxMozcState* mozcState = (FcitxMozcState*) arg; delete mozcState->mozc; free(mozcState); } static const FcitxHotkey MOZC_CTRL_ALT_H[2] = { {NULL, FcitxKey_H, FcitxKeyState_Ctrl_Alt}, {NULL, FcitxKey_None, 0} }; INPUT_RETURN_VALUE FcitxMozcDoInput(void* arg, FcitxKeySym _sym, unsigned int _state) { FcitxMozcState* mozcState = (FcitxMozcState*) arg; FcitxInstance* instance = mozcState->mozc->GetInstance(); FcitxInputState* input = FcitxInstanceGetInputState(mozcState->mozc->GetInstance()); if (mozcState->inUsageState) { if (FcitxHotkeyIsHotKey(_sym, _state, FCITX_ESCAPE)) { mozcState->inUsageState = false; mozcState->mozc->process_key_event(FcitxKey_VoidSymbol, 0, 0, CheckLayout(instance), false); return IRV_DISPLAY_CANDWORDS; } else { return IRV_DO_NOTHING; } } if (FcitxHotkeyIsHotKey(_sym, _state, MOZC_CTRL_ALT_H)) { pair< string, string > usage = mozcState->mozc->GetUsage(); if (usage.first.size() != 0 || usage.second.size() != 0) { mozcState->inUsageState = true; FcitxCandidateWordList* candList = FcitxInputStateGetCandidateList(mozcState->mozc->GetInputState()); FcitxInstanceCleanInputWindow(instance); FcitxCandidateWordReset(candList); FcitxCandidateWordSetPageSize(candList, 9); FcitxCandidateWordSetLayoutHint(candList, CLH_Vertical); FcitxCandidateWordSetChoose(candList, "\0\0\0\0\0\0\0\0\0\0"); FcitxMessages* preedit = FcitxInputStateGetPreedit(input); FcitxMessagesAddMessageAtLast(preedit, MSG_TIPS, "%s[%s]", usage.first.c_str(), _("Press Escape to go back")); UT_array* lines = fcitx_utils_split_string(usage.second.c_str(), '\n'); utarray_foreach(line, lines, char*) { FcitxCandidateWord candWord; candWord.callback = NULL; candWord.extraType = MSG_OTHER; candWord.strExtra = NULL; candWord.priv = NULL; candWord.strWord = strdup(*line); candWord.wordType = MSG_OTHER; candWord.owner = NULL; FcitxCandidateWordAppend(candList, &candWord); } utarray_free(lines); return IRV_DISPLAY_MESSAGE; } } FCITX_UNUSED(_sym); FCITX_UNUSED(_state); FcitxKeySym sym = (FcitxKeySym) FcitxInputStateGetKeySym(input); uint32 keycode = FcitxInputStateGetKeyCode(input); uint32 state = FcitxInputStateGetKeyState(input); bool result = mozcState->mozc->process_key_event(sym, keycode, state, CheckLayout(instance), false); if (!result) return IRV_TO_PROCESS; else return IRV_DISPLAY_CANDWORDS; } INPUT_RETURN_VALUE FcitxMozcDoReleaseInput(void* arg, FcitxKeySym _sym, unsigned int _state) { FcitxMozcState* mozcState = (FcitxMozcState*) arg; FcitxInstance* instance = mozcState->mozc->GetInstance(); FcitxInputState* input = FcitxInstanceGetInputState(mozcState->mozc->GetInstance()); FCITX_UNUSED(_sym); FCITX_UNUSED(_state); if (mozcState->inUsageState) { return IRV_DONOT_PROCESS; } FcitxKeySym sym = (FcitxKeySym) FcitxInputStateGetKeySym(input); uint32 keycode = FcitxInputStateGetKeyCode(input); uint32 state = FcitxInputStateGetKeyState(input); bool result = mozcState->mozc->process_key_event(sym, keycode, state, CheckLayout(instance), true); if (!result) return IRV_TO_PROCESS; else return IRV_DISPLAY_CANDWORDS; } boolean FcitxMozcInit(void* arg) { FcitxMozcState* mozcState = (FcitxMozcState*) arg; mozcState->mozc->init(); return true; } void FcitxMozcReloadConfig(void* arg) { } void FcitxMozcSave(void* arg) { FCITX_UNUSED(arg); } void FcitxMozcResetIM(void* arg) { FcitxMozcState* mozcState = (FcitxMozcState*) arg; mozcState->inUsageState = false; mozcState->mozc->resetim(); } void FcitxMozcReset(void* arg) { FcitxMozcState* mozcState = (FcitxMozcState*) arg; mozcState->mozc->reset(); } <commit_msg>[mozc] don't clear preedit<commit_after>// Copyright 2012~2013, Weng Xuetian <wengxt@gmail.com> // 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 Google Inc. 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. // workaround #define _FCITX_LOG_H_ #include <fcitx/instance.h> #include <fcitx/ime.h> #include <fcitx/hook.h> #include <fcitx/module.h> #include <fcitx/keys.h> #include <fcitx-config/xdg.h> #include "fcitx_mozc.h" #include "mozc_connection.h" #include "mozc_response_parser.h" typedef struct _FcitxMozcState { mozc::fcitx::FcitxMozc* mozc; int inUsageState; } FcitxMozcState; static void* FcitxMozcCreate(FcitxInstance* instance); static void FcitxMozcDestroy(void *arg); static boolean FcitxMozcInit(void *arg); /**< FcitxMozcInit */ static void FcitxMozcResetIM(void *arg); /**< FcitxMozcResetIM */ static void FcitxMozcReset(void *arg); /**< FcitxMozcResetIM */ static INPUT_RETURN_VALUE FcitxMozcDoInput(void *arg, FcitxKeySym, unsigned int); /**< FcitxMozcDoInput */ static INPUT_RETURN_VALUE FcitxMozcDoReleaseInput(void *arg, FcitxKeySym, unsigned int); /**< FcitxMozcDoInput */ static void FcitxMozcSave(void *arg); /**< FcitxMozcSave */ static void FcitxMozcReloadConfig(void *arg); /**< FcitxMozcReloadConfig */ extern "C" { FCITX_EXPORT_API FcitxIMClass ime = { FcitxMozcCreate, FcitxMozcDestroy }; FCITX_EXPORT_API int ABI_VERSION = FCITX_ABI_VERSION; } static inline bool CheckLayout(FcitxInstance* instance) { char *layout = NULL, *variant = NULL; FcitxModuleFunctionArg args; args.args[0] = &layout; args.args[1] = &variant; bool layout_is_jp = false; FcitxModuleInvokeFunctionByName(instance, "fcitx-xkb", 1, args); if (layout && strcmp(layout, "jp") == 0) layout_is_jp = true; fcitx_utils_free(layout); fcitx_utils_free(variant); return layout_is_jp; } static void* FcitxMozcCreate(FcitxInstance* instance) { FcitxMozcState* mozcState = (FcitxMozcState*) fcitx_utils_malloc0(sizeof(FcitxMozcState)); bindtextdomain("fcitx-mozc", LOCALEDIR); mozcState->mozc = new mozc::fcitx::FcitxMozc( instance, mozc::fcitx::MozcConnection::CreateMozcConnection(), new mozc::fcitx::MozcResponseParser ); mozcState->mozc->SetCompositionMode(mozc::commands::HIRAGANA); FcitxIMEventHook hk; hk.arg = mozcState; hk.func = FcitxMozcReset; FcitxInstanceRegisterResetInputHook(instance, hk); FcitxIMIFace iface; memset(&iface, 0, sizeof(FcitxIMIFace)); iface.Init = FcitxMozcInit; iface.ResetIM = FcitxMozcResetIM; iface.DoInput = FcitxMozcDoInput; iface.DoReleaseInput = FcitxMozcDoReleaseInput; iface.ReloadConfig = FcitxMozcReloadConfig; iface.Save = FcitxMozcSave; FcitxInstanceRegisterIMv2( instance, mozcState, "mozc", "Mozc", mozcState->mozc->GetIconFile("mozc.png").c_str(), iface, 1, "ja" ); return mozcState; } static void FcitxMozcDestroy(void *arg) { FcitxMozcState* mozcState = (FcitxMozcState*) arg; delete mozcState->mozc; free(mozcState); } static const FcitxHotkey MOZC_CTRL_ALT_H[2] = { {NULL, FcitxKey_H, FcitxKeyState_Ctrl_Alt}, {NULL, FcitxKey_None, 0} }; INPUT_RETURN_VALUE FcitxMozcDoInput(void* arg, FcitxKeySym _sym, unsigned int _state) { FcitxMozcState* mozcState = (FcitxMozcState*) arg; FcitxInstance* instance = mozcState->mozc->GetInstance(); FcitxInputState* input = FcitxInstanceGetInputState(mozcState->mozc->GetInstance()); if (mozcState->inUsageState) { if (FcitxHotkeyIsHotKey(_sym, _state, FCITX_ESCAPE)) { mozcState->inUsageState = false; // send a dummy key to let server send us the candidate info back without side effect mozcState->mozc->process_key_event(FcitxKey_VoidSymbol, 0, 0, CheckLayout(instance), false); return IRV_DISPLAY_CANDWORDS; } else { return IRV_DO_NOTHING; } } if (FcitxHotkeyIsHotKey(_sym, _state, MOZC_CTRL_ALT_H)) { pair< string, string > usage = mozcState->mozc->GetUsage(); if (usage.first.size() != 0 || usage.second.size() != 0) { mozcState->inUsageState = true; FcitxCandidateWordList* candList = FcitxInputStateGetCandidateList(mozcState->mozc->GetInputState()); // clear preedit, but keep client preedit FcitxMessages* preedit = FcitxInputStateGetPreedit(input); FcitxMessagesSetMessageCount(preedit, 0); FcitxInputStateSetShowCursor(input, false); // clear aux FcitxMessages* auxUp = FcitxInputStateGetAuxUp(input); FcitxMessages* auxDown = FcitxInputStateGetAuxDown(input); FcitxMessagesSetMessageCount(auxUp, 0); FcitxMessagesSetMessageCount(auxDown, 0); // clear candidate table FcitxCandidateWordReset(candList); FcitxCandidateWordSetPageSize(candList, 9); FcitxCandidateWordSetLayoutHint(candList, CLH_Vertical); FcitxCandidateWordSetChoose(candList, "\0\0\0\0\0\0\0\0\0\0"); FcitxMessagesAddMessageAtLast(preedit, MSG_TIPS, "%s [%s]", usage.first.c_str(), _("Press Escape to go back")); UT_array* lines = fcitx_utils_split_string(usage.second.c_str(), '\n'); utarray_foreach(line, lines, char*) { FcitxCandidateWord candWord; candWord.callback = NULL; candWord.extraType = MSG_OTHER; candWord.strExtra = NULL; candWord.priv = NULL; candWord.strWord = strdup(*line); candWord.wordType = MSG_OTHER; candWord.owner = NULL; FcitxCandidateWordAppend(candList, &candWord); } utarray_free(lines); return IRV_DISPLAY_MESSAGE; } } FCITX_UNUSED(_sym); FCITX_UNUSED(_state); FcitxKeySym sym = (FcitxKeySym) FcitxInputStateGetKeySym(input); uint32 keycode = FcitxInputStateGetKeyCode(input); uint32 state = FcitxInputStateGetKeyState(input); bool result = mozcState->mozc->process_key_event(sym, keycode, state, CheckLayout(instance), false); if (!result) return IRV_TO_PROCESS; else return IRV_DISPLAY_CANDWORDS; } INPUT_RETURN_VALUE FcitxMozcDoReleaseInput(void* arg, FcitxKeySym _sym, unsigned int _state) { FcitxMozcState* mozcState = (FcitxMozcState*) arg; FcitxInstance* instance = mozcState->mozc->GetInstance(); FcitxInputState* input = FcitxInstanceGetInputState(mozcState->mozc->GetInstance()); FCITX_UNUSED(_sym); FCITX_UNUSED(_state); if (mozcState->inUsageState) { return IRV_DONOT_PROCESS; } FcitxKeySym sym = (FcitxKeySym) FcitxInputStateGetKeySym(input); uint32 keycode = FcitxInputStateGetKeyCode(input); uint32 state = FcitxInputStateGetKeyState(input); bool result = mozcState->mozc->process_key_event(sym, keycode, state, CheckLayout(instance), true); if (!result) return IRV_TO_PROCESS; else return IRV_DISPLAY_CANDWORDS; } boolean FcitxMozcInit(void* arg) { FcitxMozcState* mozcState = (FcitxMozcState*) arg; mozcState->mozc->init(); return true; } void FcitxMozcReloadConfig(void* arg) { } void FcitxMozcSave(void* arg) { FCITX_UNUSED(arg); } void FcitxMozcResetIM(void* arg) { FcitxMozcState* mozcState = (FcitxMozcState*) arg; mozcState->inUsageState = false; mozcState->mozc->resetim(); } void FcitxMozcReset(void* arg) { FcitxMozcState* mozcState = (FcitxMozcState*) arg; mozcState->mozc->reset(); } <|endoftext|>
<commit_before>/******************************************************************************* * libproxy - A library for proxy configuration * Copyright (C) 2006 Nathaniel McCallum <nathaniel@natemccallum.com> * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA ******************************************************************************/ #include <stdlib.h> #include <string.h> #include <stdarg.h> #include <stdio.h> #include <misc.h> #include <modules.h> #include <config_file.h> #include <QtGui/QApplication> #include <kstandarddirs.h> typedef struct _pxKConfigConfigModule { PX_MODULE_SUBCLASS(pxConfigModule); pxConfigFile *cf; } pxKConfigConfigModule; static void _destructor(void *s) { pxKConfigConfigModule *self = (pxKConfigConfigModule *) s; px_config_file_free(self->cf); px_free(self); } static char * _get_config(pxConfigModule *s, pxURL *url) { // QApplication *app = new QApplication(0,NULL,0); // KGlobal::dirs(); pxKConfigConfigModule *self = (pxKConfigConfigModule *) s; // TODO: make ignores work w/ KDE char *curl = NULL, *tmp = getenv("HOME"); if (!tmp) return NULL; // Open the config file pxConfigFile *cf = self->cf; if (!cf || px_config_file_is_stale(cf)) { if (cf) px_config_file_free(cf); // QString localdir = KGlobal::dirs()->localkdedir(); QString localdir = KStandardDirs().localkdedir(); QByteArray ba = localdir.toLatin1(); tmp = px_strcat(ba.data(), "/share/config/kioslaverc", NULL); cf = px_config_file_new(tmp); px_free(tmp); self->cf = cf; } if (!cf) goto out; // Read the config file to find out what type of proxy to use tmp = px_config_file_get_value(cf, "Proxy Settings", "ProxyType"); if (!tmp) goto out; // Don't use any proxy if (!strcmp(tmp, "0")) curl = px_strdup("direct://"); // Use a manual proxy else if (!strcmp(tmp, "1")) curl = px_config_file_get_value(cf, "Proxy Settings", "httpProxy"); // Use a manual PAC else if (!strcmp(tmp, "2")) { px_free(tmp); tmp = px_config_file_get_value(cf, "Proxy Settings", "Proxy Config Script"); if (tmp) curl = px_strcat("pac+", tmp); else curl = px_strdup("wpad://"); } // Use WPAD else if (!strcmp(tmp, "3")) curl = px_strdup("wpad://"); // Use envvar else if (!strcmp(tmp, "4")) curl = NULL; // We'll bypass this config plugin and let the envvar plugin work // Cleanup px_free(tmp); out: return curl; } static char * _get_ignore(pxConfigModule *self, pxURL *url) { return px_strdup(""); } static bool _get_credentials(pxConfigModule *self, pxURL *proxy, char **username, char **password) { return false; } static bool _set_credentials(pxConfigModule *self, pxURL *proxy, const char *username, const char *password) { return false; } static void * _constructor() { pxKConfigConfigModule *self = (pxKConfigConfigModule *)px_malloc0(sizeof(pxKConfigConfigModule)); PX_CONFIG_MODULE_BUILD(self, PX_CONFIG_MODULE_CATEGORY_SESSION, _get_config, _get_ignore, _get_credentials, _set_credentials); return self; } extern "C" bool px_module_load(pxModuleManager *self) { // If we are running in KDE, then make sure this plugin is registered. char *tmp = getenv("KDE_FULL_SESSION"); if (tmp == NULL) { return false; } return px_module_manager_register_module(self, pxConfigModule, _constructor, _destructor); } <commit_msg>config_kde: clean up test remainings, no require to read HOME envvar<commit_after>/******************************************************************************* * libproxy - A library for proxy configuration * Copyright (C) 2006 Nathaniel McCallum <nathaniel@natemccallum.com> * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA ******************************************************************************/ #include <stdlib.h> #include <string.h> #include <stdarg.h> #include <stdio.h> #include <misc.h> #include <modules.h> #include <config_file.h> #include <kstandarddirs.h> typedef struct _pxKConfigConfigModule { PX_MODULE_SUBCLASS(pxConfigModule); pxConfigFile *cf; } pxKConfigConfigModule; static void _destructor(void *s) { pxKConfigConfigModule *self = (pxKConfigConfigModule *) s; px_config_file_free(self->cf); px_free(self); } static char * _get_config(pxConfigModule *s, pxURL *url) { pxKConfigConfigModule *self = (pxKConfigConfigModule *) s; // TODO: make ignores work w/ KDE char *curl = NULL, *tmp = NULL; // Open the config file pxConfigFile *cf = self->cf; if (!cf || px_config_file_is_stale(cf)) { if (cf) px_config_file_free(cf); QString localdir = KStandardDirs().localkdedir(); QByteArray ba = localdir.toLatin1(); tmp = px_strcat(ba.data(), "/share/config/kioslaverc", NULL); cf = px_config_file_new(tmp); px_free(tmp); self->cf = cf; } if (!cf) goto out; // Read the config file to find out what type of proxy to use tmp = px_config_file_get_value(cf, "Proxy Settings", "ProxyType"); if (!tmp) goto out; // Don't use any proxy if (!strcmp(tmp, "0")) curl = px_strdup("direct://"); // Use a manual proxy else if (!strcmp(tmp, "1")) curl = px_config_file_get_value(cf, "Proxy Settings", "httpProxy"); // Use a manual PAC else if (!strcmp(tmp, "2")) { px_free(tmp); tmp = px_config_file_get_value(cf, "Proxy Settings", "Proxy Config Script"); if (tmp) curl = px_strcat("pac+", tmp); else curl = px_strdup("wpad://"); } // Use WPAD else if (!strcmp(tmp, "3")) curl = px_strdup("wpad://"); // Use envvar else if (!strcmp(tmp, "4")) curl = NULL; // We'll bypass this config plugin and let the envvar plugin work // Cleanup px_free(tmp); out: return curl; } static char * _get_ignore(pxConfigModule *self, pxURL *url) { return px_strdup(""); } static bool _get_credentials(pxConfigModule *self, pxURL *proxy, char **username, char **password) { return false; } static bool _set_credentials(pxConfigModule *self, pxURL *proxy, const char *username, const char *password) { return false; } static void * _constructor() { pxKConfigConfigModule *self = (pxKConfigConfigModule *)px_malloc0(sizeof(pxKConfigConfigModule)); PX_CONFIG_MODULE_BUILD(self, PX_CONFIG_MODULE_CATEGORY_SESSION, _get_config, _get_ignore, _get_credentials, _set_credentials); return self; } extern "C" bool px_module_load(pxModuleManager *self) { // If we are running in KDE, then make sure this plugin is registered. char *tmp = getenv("KDE_FULL_SESSION"); if (tmp == NULL) { return false; } return px_module_manager_register_module(self, pxConfigModule, _constructor, _destructor); } <|endoftext|>
<commit_before>/* * Copyright (c) 2013-2014 ADTECH GmbH * Licensed under MIT (https://github.com/adtechlabs/libtasks/blob/master/COPYING) * * Author: Andreas Pohl */ #include <tasks/serial/term.h> #include <cstring> #include <fcntl.h> #include <unistd.h> namespace tasks { namespace serial { struct termios term::options() { if (m_fd < 0) { throw term_exception("no open device"); } struct termios opts; if (tcgetattr(m_fd, &opts)) { close(); throw term_exception("tcgetattr failed: " + std::string(std::strerror(errno))); } return opts; } void term::set_options(struct termios& opts) { if (m_fd < 0) { throw term_exception("no open device"); } if (tcsetattr(m_fd, TCSANOW, &opts)) { close(); throw term_exception("tcsetattr failed: " + std::string(std::strerror(errno))); } } void term::open(std::string port, speed_t baudrate, charsize_t charsize, parity_t parity, stopbits_t stopbits) { m_fd = ::open(port.c_str(), O_RDWR | O_NOCTTY | O_NONBLOCK); if (m_fd < 0) { throw term_exception("opening " + port + std::string(" failed: ") + std::string(std::strerror(errno))); } // ensure non blocking reads if (fcntl(m_fd, F_SETFL, FNDELAY)) { close(); throw term_exception("fcntl failed: " + std::string(std::strerror(errno))); } // read the current settings struct termios opts = options(); // don't take ownership of the device and enable recieving of data opts.c_cflag |= (CLOCAL | CREAD); // use raw input/output as a default opts.c_lflag &= ~(ICANON | ECHO | ECHOE | ISIG); opts.c_oflag &= ~OPOST; // baudrate if (cfsetispeed(&opts, baudrate)) { close(); throw term_exception("cfsetispeed failed: " + std::string(std::strerror(errno))); } if (cfsetospeed(&opts, baudrate)) { close(); throw term_exception("cfsetospeed failed: " + std::string(std::strerror(errno))); } // charachter size opts.c_cflag &= ~CSIZE; opts.c_cflag |= static_cast<tcflag_t>(charsize); // parity switch (parity) { case parity_t::NONE: opts.c_cflag &= ~PARENB; break; case parity_t::EVEN: opts.c_cflag |= PARENB; opts.c_cflag &= ~PARODD; break; case parity_t::ODD: opts.c_cflag |= PARENB; opts.c_cflag |= PARODD; break; default: close(); throw term_exception("invalid parity parameter"); } // stopbits switch (stopbits) { case stopbits_t::_1: opts.c_cflag &= ~CSTOPB; break; case stopbits_t::_2: opts.c_cflag |= CSTOPB; default: close(); throw term_exception("invalid stopbits parameter"); } set_options(opts); } void term::open(std::string port, speed_t baudrate, termmode_t mode) { switch (mode) { case termmode_t::_8N1: open(port, baudrate, charsize_t::_8, parity_t::NONE, stopbits_t::_1); break; case termmode_t::_7S1: open(port, baudrate, charsize_t::_7, parity_t::NONE, stopbits_t::_1); break; case termmode_t::_7E1: open(port, baudrate, charsize_t::_7, parity_t::EVEN, stopbits_t::_1); break; case termmode_t::_7O1: open(port, baudrate, charsize_t::_7, parity_t::ODD, stopbits_t::_1); break; default: throw term_exception("invalid mode parameter"); } } void term::close() { if (m_fd > -1) { ::close(m_fd); m_fd = -1; } } std::streamsize term::write(const char* data, std::size_t len) { if (m_fd < 0) { throw term_exception("no open device"); } return ::write(m_fd, data, len); } std::streamsize term::read(char* data, std::size_t len) { if (m_fd < 0) { throw term_exception("no open device"); } return ::read(m_fd, data, len); } } // net } // tasks <commit_msg>term.cpp: Fixed typo<commit_after>/* * Copyright (c) 2013-2014 ADTECH GmbH * Licensed under MIT (https://github.com/adtechlabs/libtasks/blob/master/COPYING) * * Author: Andreas Pohl */ #include <tasks/serial/term.h> #include <cstring> #include <fcntl.h> #include <unistd.h> namespace tasks { namespace serial { struct termios term::options() { if (m_fd < 0) { throw term_exception("no open device"); } struct termios opts; if (tcgetattr(m_fd, &opts)) { close(); throw term_exception("tcgetattr failed: " + std::string(std::strerror(errno))); } return opts; } void term::set_options(struct termios& opts) { if (m_fd < 0) { throw term_exception("no open device"); } if (tcsetattr(m_fd, TCSANOW, &opts)) { close(); throw term_exception("tcsetattr failed: " + std::string(std::strerror(errno))); } } void term::open(std::string port, speed_t baudrate, charsize_t charsize, parity_t parity, stopbits_t stopbits) { m_fd = ::open(port.c_str(), O_RDWR | O_NOCTTY | O_NONBLOCK); if (m_fd < 0) { throw term_exception("opening " + port + std::string(" failed: ") + std::string(std::strerror(errno))); } // ensure non blocking reads if (fcntl(m_fd, F_SETFL, FNDELAY)) { close(); throw term_exception("fcntl failed: " + std::string(std::strerror(errno))); } // read the current settings struct termios opts = options(); // don't take ownership of the device and enable recieving of data opts.c_cflag |= (CLOCAL | CREAD); // use raw input/output as a default opts.c_lflag &= ~(ICANON | ECHO | ECHOE | ISIG); opts.c_oflag &= ~OPOST; // baudrate if (cfsetispeed(&opts, baudrate)) { close(); throw term_exception("cfsetispeed failed: " + std::string(std::strerror(errno))); } if (cfsetospeed(&opts, baudrate)) { close(); throw term_exception("cfsetospeed failed: " + std::string(std::strerror(errno))); } // charachter size opts.c_cflag &= ~CSIZE; opts.c_cflag |= static_cast<tcflag_t>(charsize); // parity switch (parity) { case parity_t::NONE: opts.c_cflag &= ~PARENB; break; case parity_t::EVEN: opts.c_cflag |= PARENB; opts.c_cflag &= ~PARODD; break; case parity_t::ODD: opts.c_cflag |= PARENB; opts.c_cflag |= PARODD; break; default: close(); throw term_exception("invalid parity parameter"); } // stopbits switch (stopbits) { case stopbits_t::_1: opts.c_cflag &= ~CSTOPB; break; case stopbits_t::_2: opts.c_cflag |= CSTOPB; default: close(); throw term_exception("invalid stopbits parameter"); } set_options(opts); } void term::open(std::string port, speed_t baudrate, termmode_t mode) { switch (mode) { case termmode_t::_8N1: open(port, baudrate, charsize_t::_8, parity_t::NONE, stopbits_t::_1); break; case termmode_t::_7S1: open(port, baudrate, charsize_t::_7, parity_t::NONE, stopbits_t::_1); break; case termmode_t::_7E1: open(port, baudrate, charsize_t::_7, parity_t::EVEN, stopbits_t::_1); break; case termmode_t::_7O1: open(port, baudrate, charsize_t::_7, parity_t::ODD, stopbits_t::_1); break; default: throw term_exception("invalid mode parameter"); } } void term::close() { if (m_fd > -1) { ::close(m_fd); m_fd = -1; } } std::streamsize term::write(const char* data, std::size_t len) { if (m_fd < 0) { throw term_exception("no open device"); } return ::write(m_fd, data, len); } std::streamsize term::read(char* data, std::size_t len) { if (m_fd < 0) { throw term_exception("no open device"); } return ::read(m_fd, data, len); } } // serial } // tasks <|endoftext|>
<commit_before>/* Copyright (C) 2005-2011, Thorvald Natvig <thorvald@natvig.com> Copyright (C) 2009-2011, Stefan Hacker <dd0t@users.sourceforge.net> 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 Mumble Developers 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 FOUNDATION OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #include "mumble_pch.hpp" #include "LookConfig.h" #include "AudioInput.h" #include "AudioOutput.h" #include "Global.h" #include "MainWindow.h" static ConfigWidget *LookConfigNew(Settings &st) { return new LookConfig(st); } static ConfigRegistrar registrar(1100, LookConfigNew); LookConfig::LookConfig(Settings &st) : ConfigWidget(st) { setupUi(this); #ifndef Q_OS_MAC if (! QSystemTrayIcon::isSystemTrayAvailable()) #endif qgbTray->hide(); qcbLanguage->addItem(tr("System default")); QDir d(QLatin1String(":"),QLatin1String("mumble_*.qm"),QDir::Name,QDir::Files); QStringList langs; foreach(const QString &key, d.entryList()) { QString cc = key.mid(7,key.indexOf(QLatin1Char('.'))-7); langs << cc; qcbLanguage->addItem(cc); } QStringList styles = QStyleFactory::keys(); styles.sort(); qcbStyle->addItem(tr("System default")); foreach(QString key, styles) { qcbStyle->addItem(key); } qcbExpand->addItem(tr("None"), Settings::NoChannels); qcbExpand->addItem(tr("Only with users"), Settings::ChannelsWithUsers); qcbExpand->addItem(tr("All"), Settings::AllChannels); qcbChannelDrag->insertItem(Settings::Ask, tr("Ask"), Settings::Ask); qcbChannelDrag->insertItem(Settings::DoNothing, tr("Do Nothing"), Settings::DoNothing); qcbChannelDrag->insertItem(Settings::Move, tr("Move"), Settings::Move); } QString LookConfig::title() const { return tr("User Interface"); } QIcon LookConfig::icon() const { return QIcon(QLatin1String("skin:config_ui.png")); } void LookConfig::load(const Settings &r) { loadComboBox(qcbLanguage, 0); loadComboBox(qcbStyle, 0); loadComboBox(qcbChannelDrag, 0); // Load Layout checkbox state switch (r.wlWindowLayout) { case Settings::LayoutClassic: qrbLClassic->setChecked(true); break; case Settings::LayoutStacked: qrbLStacked->setChecked(true); break; case Settings::LayoutHybrid: qrbLHybrid->setChecked(true); break; case Settings::LayoutCustom: default: s.wlWindowLayout = Settings::LayoutCustom; qrbLCustom->setChecked(true); break; } for (int i=0;i<qcbLanguage->count();i++) { if (qcbLanguage->itemText(i) == r.qsLanguage) { loadComboBox(qcbLanguage, i); break; } } for (int i=0;i<qcbStyle->count();i++) { if (qcbStyle->itemText(i) == r.qsStyle) { loadComboBox(qcbStyle, i); break; } } loadComboBox(qcbAlwaysOnTop, r.aotbAlwaysOnTop); qleCSS->setText(r.qsSkin); loadComboBox(qcbExpand, r.ceExpand); loadComboBox(qcbChannelDrag, r.ceChannelDrag); loadCheckBox(qcbUsersTop, r.bUserTop); loadCheckBox(qcbAskOnQuit, r.bAskOnQuit); loadCheckBox(qcbHideTray, r.bHideInTray); loadCheckBox(qcbStateInTray, r.bStateInTray); loadCheckBox(qcbShowUserCount, r.bShowUserCount); loadCheckBox(qcbShowContextMenuInMenuBar, r.bShowContextMenuInMenuBar); loadCheckBox(qcbHighContrast, r.bHighContrast); loadCheckBox(qcbChatBarUseSelection, r.bChatBarUseSelection); loadCheckBox(qcbFilterHidesEmptyChannels, r.bFilterHidesEmptyChannels); } void LookConfig::save() const { if (qcbLanguage->currentIndex() == 0) s.qsLanguage = QString(); else s.qsLanguage = qcbLanguage->currentText(); if (qcbStyle->currentIndex() == 0) s.qsStyle = QString(); else s.qsStyle = qcbStyle->currentText(); if (qleCSS->text().isEmpty()) s.qsSkin = QString(); else s.qsSkin = qleCSS->text(); // Save Layout radioboxes state if (qrbLClassic->isChecked()) { s.wlWindowLayout = Settings::LayoutClassic; } else if (qrbLStacked->isChecked()) { s.wlWindowLayout = Settings::LayoutStacked; } else if (qrbLHybrid->isChecked()) { s.wlWindowLayout = Settings::LayoutHybrid; } else { s.wlWindowLayout = Settings::LayoutCustom; } s.ceExpand=static_cast<Settings::ChannelExpand>(qcbExpand->currentIndex()); s.ceChannelDrag=static_cast<Settings::ChannelDrag>(qcbChannelDrag->currentIndex()); s.bUserTop=qcbUsersTop->isChecked(); s.aotbAlwaysOnTop = static_cast<Settings::AlwaysOnTopBehaviour>(qcbAlwaysOnTop->currentIndex()); s.bAskOnQuit = qcbAskOnQuit->isChecked(); s.bHideInTray = qcbHideTray->isChecked(); s.bStateInTray = qcbStateInTray->isChecked(); s.bShowUserCount = qcbShowUserCount->isChecked(); s.bShowContextMenuInMenuBar = qcbShowContextMenuInMenuBar->isChecked(); s.bHighContrast = qcbHighContrast->isChecked(); s.bChatBarUseSelection = qcbChatBarUseSelection->isChecked(); s.bFilterHidesEmptyChannels = qcbFilterHidesEmptyChannels->isChecked(); } void LookConfig::accept() const { if (! s.qsStyle.isEmpty() && g.qsCurrentStyle != s.qsStyle) { qApp->setStyle(s.qsStyle); g.qsCurrentStyle = s.qsStyle; } if (s.qsSkin.isEmpty()) { if (qApp->styleSheet() != MainWindow::defaultStyleSheet) { qApp->setStyleSheet(MainWindow::defaultStyleSheet); g.mw->qteLog->document()->setDefaultStyleSheet(qApp->styleSheet()); } } else { QFile file(s.qsSkin); file.open(QFile::ReadOnly); QString sheet = QLatin1String(file.readAll()); if (! sheet.isEmpty() && (sheet != qApp->styleSheet())) { QFileInfo fi(g.s.qsSkin); QDir::addSearchPath(QLatin1String("skin"), fi.path()); qApp->setStyleSheet(sheet); g.mw->qteLog->document()->setDefaultStyleSheet(sheet); } } g.mw->setShowDockTitleBars(g.s.wlWindowLayout == Settings::LayoutCustom); } bool LookConfig::expert(bool b) { qcbExpand->setVisible(b); qliExpand->setVisible(b); qcbUsersTop->setVisible(b); qcbStyle->setVisible(b); qliStyle->setVisible(b); qcbStateInTray->setVisible(b); qcbShowContextMenuInMenuBar->setVisible(b); return true; } void LookConfig::on_qpbSkinFile_clicked(bool) { QString currentPath(qleCSS->text()); if (currentPath.isEmpty()) { QDir p; #if defined(Q_OS_WIN) p.setPath(QApplication::applicationDirPath()); #else p = g.qdBasePath; #endif currentPath = p.path(); p.cd(QString::fromLatin1("skins")); if (p.exists() && p.isReadable()) { currentPath = p.path(); } } QDir path(currentPath); if (!path.exists() || !path.isReadable()) { path.cdUp(); } QString file = QFileDialog::getOpenFileName(this, tr("Choose skin file"), path.path(), QLatin1String("*.qss")); if (! file.isEmpty()) { qleCSS->setText(file); } } <commit_msg>Display the native language name in the language chooser rather than the locale<commit_after>/* Copyright (C) 2005-2011, Thorvald Natvig <thorvald@natvig.com> Copyright (C) 2009-2011, Stefan Hacker <dd0t@users.sourceforge.net> 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 Mumble Developers 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 FOUNDATION OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #include "mumble_pch.hpp" #include "LookConfig.h" #include "AudioInput.h" #include "AudioOutput.h" #include "Global.h" #include "MainWindow.h" static ConfigWidget *LookConfigNew(Settings &st) { return new LookConfig(st); } static ConfigRegistrar registrar(1100, LookConfigNew); LookConfig::LookConfig(Settings &st) : ConfigWidget(st) { setupUi(this); #ifndef Q_OS_MAC if (! QSystemTrayIcon::isSystemTrayAvailable()) #endif qgbTray->hide(); qcbLanguage->addItem(tr("System default")); QDir d(QLatin1String(":"),QLatin1String("mumble_*.qm"),QDir::Name,QDir::Files); foreach(const QString &key, d.entryList()) { QString cc = key.mid(7,key.indexOf(QLatin1Char('.'))-7); QLocale tmpLocale = QLocale(cc); //If there is no native language name, use the locale if(!tmpLocale.nativeLanguageName().isEmpty()) { qcbLanguage->addItem(tmpLocale.nativeLanguageName(), QVariant(cc)); } else { qcbLanguage->addItem(cc, QVariant(cc)); } } QStringList styles = QStyleFactory::keys(); styles.sort(); qcbStyle->addItem(tr("System default")); foreach(QString key, styles) { qcbStyle->addItem(key); } qcbExpand->addItem(tr("None"), Settings::NoChannels); qcbExpand->addItem(tr("Only with users"), Settings::ChannelsWithUsers); qcbExpand->addItem(tr("All"), Settings::AllChannels); qcbChannelDrag->insertItem(Settings::Ask, tr("Ask"), Settings::Ask); qcbChannelDrag->insertItem(Settings::DoNothing, tr("Do Nothing"), Settings::DoNothing); qcbChannelDrag->insertItem(Settings::Move, tr("Move"), Settings::Move); } QString LookConfig::title() const { return tr("User Interface"); } QIcon LookConfig::icon() const { return QIcon(QLatin1String("skin:config_ui.png")); } void LookConfig::load(const Settings &r) { loadComboBox(qcbLanguage, 0); loadComboBox(qcbStyle, 0); loadComboBox(qcbChannelDrag, 0); // Load Layout checkbox state switch (r.wlWindowLayout) { case Settings::LayoutClassic: qrbLClassic->setChecked(true); break; case Settings::LayoutStacked: qrbLStacked->setChecked(true); break; case Settings::LayoutHybrid: qrbLHybrid->setChecked(true); break; case Settings::LayoutCustom: default: s.wlWindowLayout = Settings::LayoutCustom; qrbLCustom->setChecked(true); break; } for (int i=0;i<qcbLanguage->count();i++) { if (qcbLanguage->itemData(i).toString() == r.qsLanguage) { loadComboBox(qcbLanguage, i); break; } } for (int i=0;i<qcbStyle->count();i++) { if (qcbStyle->itemText(i) == r.qsStyle) { loadComboBox(qcbStyle, i); break; } } loadComboBox(qcbAlwaysOnTop, r.aotbAlwaysOnTop); qleCSS->setText(r.qsSkin); loadComboBox(qcbExpand, r.ceExpand); loadComboBox(qcbChannelDrag, r.ceChannelDrag); loadCheckBox(qcbUsersTop, r.bUserTop); loadCheckBox(qcbAskOnQuit, r.bAskOnQuit); loadCheckBox(qcbHideTray, r.bHideInTray); loadCheckBox(qcbStateInTray, r.bStateInTray); loadCheckBox(qcbShowUserCount, r.bShowUserCount); loadCheckBox(qcbShowContextMenuInMenuBar, r.bShowContextMenuInMenuBar); loadCheckBox(qcbHighContrast, r.bHighContrast); loadCheckBox(qcbChatBarUseSelection, r.bChatBarUseSelection); loadCheckBox(qcbFilterHidesEmptyChannels, r.bFilterHidesEmptyChannels); } void LookConfig::save() const { if (qcbLanguage->currentIndex() == 0) s.qsLanguage = QString(); else s.qsLanguage = qcbLanguage->itemData(qcbLanguage->currentIndex()).toString(); if (qcbStyle->currentIndex() == 0) s.qsStyle = QString(); else s.qsStyle = qcbStyle->currentText(); if (qleCSS->text().isEmpty()) s.qsSkin = QString(); else s.qsSkin = qleCSS->text(); // Save Layout radioboxes state if (qrbLClassic->isChecked()) { s.wlWindowLayout = Settings::LayoutClassic; } else if (qrbLStacked->isChecked()) { s.wlWindowLayout = Settings::LayoutStacked; } else if (qrbLHybrid->isChecked()) { s.wlWindowLayout = Settings::LayoutHybrid; } else { s.wlWindowLayout = Settings::LayoutCustom; } s.ceExpand=static_cast<Settings::ChannelExpand>(qcbExpand->currentIndex()); s.ceChannelDrag=static_cast<Settings::ChannelDrag>(qcbChannelDrag->currentIndex()); s.bUserTop=qcbUsersTop->isChecked(); s.aotbAlwaysOnTop = static_cast<Settings::AlwaysOnTopBehaviour>(qcbAlwaysOnTop->currentIndex()); s.bAskOnQuit = qcbAskOnQuit->isChecked(); s.bHideInTray = qcbHideTray->isChecked(); s.bStateInTray = qcbStateInTray->isChecked(); s.bShowUserCount = qcbShowUserCount->isChecked(); s.bShowContextMenuInMenuBar = qcbShowContextMenuInMenuBar->isChecked(); s.bHighContrast = qcbHighContrast->isChecked(); s.bChatBarUseSelection = qcbChatBarUseSelection->isChecked(); s.bFilterHidesEmptyChannels = qcbFilterHidesEmptyChannels->isChecked(); } void LookConfig::accept() const { if (! s.qsStyle.isEmpty() && g.qsCurrentStyle != s.qsStyle) { qApp->setStyle(s.qsStyle); g.qsCurrentStyle = s.qsStyle; } if (s.qsSkin.isEmpty()) { if (qApp->styleSheet() != MainWindow::defaultStyleSheet) { qApp->setStyleSheet(MainWindow::defaultStyleSheet); g.mw->qteLog->document()->setDefaultStyleSheet(qApp->styleSheet()); } } else { QFile file(s.qsSkin); file.open(QFile::ReadOnly); QString sheet = QLatin1String(file.readAll()); if (! sheet.isEmpty() && (sheet != qApp->styleSheet())) { QFileInfo fi(g.s.qsSkin); QDir::addSearchPath(QLatin1String("skin"), fi.path()); qApp->setStyleSheet(sheet); g.mw->qteLog->document()->setDefaultStyleSheet(sheet); } } g.mw->setShowDockTitleBars(g.s.wlWindowLayout == Settings::LayoutCustom); } bool LookConfig::expert(bool b) { qcbExpand->setVisible(b); qliExpand->setVisible(b); qcbUsersTop->setVisible(b); qcbStyle->setVisible(b); qliStyle->setVisible(b); qcbStateInTray->setVisible(b); qcbShowContextMenuInMenuBar->setVisible(b); return true; } void LookConfig::on_qpbSkinFile_clicked(bool) { QString currentPath(qleCSS->text()); if (currentPath.isEmpty()) { QDir p; #if defined(Q_OS_WIN) p.setPath(QApplication::applicationDirPath()); #else p = g.qdBasePath; #endif currentPath = p.path(); p.cd(QString::fromLatin1("skins")); if (p.exists() && p.isReadable()) { currentPath = p.path(); } } QDir path(currentPath); if (!path.exists() || !path.isReadable()) { path.cdUp(); } QString file = QFileDialog::getOpenFileName(this, tr("Choose skin file"), path.path(), QLatin1String("*.qss")); if (! file.isEmpty()) { qleCSS->setText(file); } } <|endoftext|>
<commit_before>// @(#)root/net:$Name: $:$Id: TSocket.cxx,v 1.2 2000/06/28 15:27:32 rdm Exp $ // Author: Fons Rademakers 18/12/96 /************************************************************************* * Copyright (C) 1995-2000, Rene Brun and Fons Rademakers. * * All rights reserved. * * * * For the licensing terms see $ROOTSYS/LICENSE. * * For the list of contributors see $ROOTSYS/README/CREDITS. * *************************************************************************/ ////////////////////////////////////////////////////////////////////////// // // // TSocket // // // // This class implements client sockets. A socket is an endpoint for // // communication between two machines. // // The actual work is done via the TSystem class (either TUnixSystem, // // TWin32System or TMacSystem). // // // ////////////////////////////////////////////////////////////////////////// #include "TSocket.h" #include "TSystem.h" #include "TMessage.h" #include "Bytes.h" #include "TROOT.h" #include "TError.h" UInt_t TSocket::fgBytesSent = 0; UInt_t TSocket::fgBytesRecv = 0; ClassImp(TSocket) //______________________________________________________________________________ TSocket::TSocket(TInetAddress addr, const char *service) : TNamed(addr.GetHostName(), service) { // Create a socket. Connect to the named service at address addr. // Returns when connection has been accepted by remote side. Use IsValid() // to check the validity of the socket. Every socket is added to the TROOT // sockets list which will make sure that any open sockets are properly // closed on program termination. Assert(gROOT); Assert(gSystem); fService = service; fAddress = addr; fAddress.fPort = gSystem->GetServiceByName(service); fBytesSent = 0; fBytesRecv = 0; if (fAddress.GetPort() != -1) { fSocket = gSystem->OpenConnection(addr.GetHostName(), fAddress.GetPort()); if (fSocket != -1) gROOT->GetListOfSockets()->Add(this); } else fSocket = -1; } //______________________________________________________________________________ TSocket::TSocket(TInetAddress addr, Int_t port) : TNamed(addr.GetHostName(), "") { // Create a socket. Connect to the specified port # at address addr. // Returns when connection has been accepted by remote side. Use IsValid() // to check the validity of the socket. Every socket is added to the TROOT // sockets list which will make sure that any open sockets are properly // closed on program termination. Assert(gROOT); Assert(gSystem); fService = gSystem->GetServiceByPort(port); fAddress = addr; fAddress.fPort = port; SetTitle(fService); fBytesSent = 0; fBytesRecv = 0; fSocket = gSystem->OpenConnection(addr.GetHostName(), fAddress.GetPort()); if (fSocket == -1) fAddress.fPort = -1; else gROOT->GetListOfSockets()->Add(this); } //______________________________________________________________________________ TSocket::TSocket(const char *host, const char *service) : TNamed(host, service) { // Create a socket. Connect to named service on the remote host. // Returns when connection has been accepted by remote side. Use IsValid() // to check the validity of the socket. Every socket is added to the TROOT // sockets list which will make sure that any open sockets are properly // closed on program termination. Assert(gROOT); Assert(gSystem); fService = service; fAddress = gSystem->GetHostByName(host); fAddress.fPort = gSystem->GetServiceByName(service); SetName(fAddress.GetHostName()); fBytesSent = 0; fBytesRecv = 0; if (fAddress.GetPort() != -1) { fSocket = gSystem->OpenConnection(host, fAddress.GetPort()); if (fSocket != -1) gROOT->GetListOfSockets()->Add(this); } else fSocket = -1; } //______________________________________________________________________________ TSocket::TSocket(const char *host, Int_t port) : TNamed(host, "") { // Create a socket. Connect to specified port # on the remote host. // Returns when connection has been accepted by remote side. Use IsValid() // to check the validity of the socket. Every socket is added to the TROOT // sockets list which will make sure that any open sockets are properly // closed on program termination. Assert(gROOT); Assert(gSystem); fService = gSystem->GetServiceByPort(port); fAddress = gSystem->GetHostByName(host); fAddress.fPort = port; SetName(fAddress.GetHostName()); SetTitle(fService); fBytesSent = 0; fBytesRecv = 0; fSocket = gSystem->OpenConnection(host, fAddress.GetPort()); if (fSocket == -1) fAddress.fPort = -1; else gROOT->GetListOfSockets()->Add(this); } //______________________________________________________________________________ TSocket::TSocket(Int_t desc) : TNamed("", "") { // Create a socket. The socket will use descriptor desc. Assert(gROOT); Assert(gSystem); fBytesSent = 0; fBytesRecv = 0; if (desc >= 0) { fSocket = desc; fAddress = gSystem->GetPeerName(fSocket); gROOT->GetListOfSockets()->Add(this); } else fSocket = -1; } //______________________________________________________________________________ TSocket::TSocket(const TSocket &s) { // TSocket copy ctor. fSocket = s.fSocket; fService = s.fService; fAddress = s.fAddress; fLocalAddress = s.fLocalAddress; fBytesSent = s.fBytesSent; fBytesRecv = s.fBytesRecv; if (fSocket != -1) gROOT->GetListOfSockets()->Add(this); } //______________________________________________________________________________ void TSocket::Close(Option_t *option) { // Close the socket. If option is "force", calls shutdown(id,2) to // shut down the connection. This will close the connection also // for the parent of this process. Also called via the dtor (without // option "force", call explicitely Close("force") if this is desired). Bool_t force = option ? (!strcmp(option, "force") ? kTRUE : kFALSE) : kFALSE; if (fSocket != -1) { gSystem->CloseConnection(fSocket, force); gROOT->GetListOfSockets()->Remove(this); } fSocket = -1; } //______________________________________________________________________________ TInetAddress TSocket::GetLocalInetAddress() { // Return internet address of local host to which the socket is bound. // In case of error TInetAddress::IsValid() returns kFALSE. if (fSocket != -1) { if (fLocalAddress.GetPort() == -1) fLocalAddress = gSystem->GetSockName(fSocket); return fLocalAddress; } return TInetAddress(); } //______________________________________________________________________________ Int_t TSocket::GetLocalPort() { // Return the local port # to which the socket is bound. // In case of error return -1. if (fSocket != -1) { if (fLocalAddress.GetPort() == -1) fLocalAddress = GetLocalInetAddress(); return fLocalAddress.GetPort(); } return -1; } //______________________________________________________________________________ Int_t TSocket::Send(Int_t kind) { // Send a single message opcode. Use kind (opcode) to set the // TMessage "what" field. Returns the number of bytes that were sent // (always sizeof(Int_t)) and -1 in case of error. In case the kind has // been or'ed with kMESS_ACK, the call will only return after having // received an acknowledgement, making the sending process synchronous. TMessage mess(kind); return Send(mess); } //______________________________________________________________________________ Int_t TSocket::Send(const char *str, Int_t kind) { // Send a character string buffer. Use kind to set the TMessage "what" field. // Returns the number of bytes in the string str that were sent and -1 in // case of error. In case the kind has been or'ed with kMESS_ACK, the call // will only return after having received an acknowledgement, making the // sending process synchronous. TMessage mess(kind); if (str) mess.WriteString(str); Int_t nsent; if ((nsent = Send(mess)) < 0) return -1; return nsent - sizeof(Int_t); // - TMessage::What() } //______________________________________________________________________________ Int_t TSocket::Send(const TMessage &mess) { // Send a TMessage object. Returns the number of bytes in the TMessage // that were sent and -1 in case of error. In case the TMessage::What // has been or'ed with kMESS_ACK, the call will only return after having // received an acknowledgement, making the sending process synchronous. if (fSocket == -1) return -1; if (mess.IsReading()) { Error("Send", "cannot send a message used for reading"); return -1; } Int_t nsent; mess.SetLength(); //write length in first word of buffer if ((nsent = gSystem->SendRaw(fSocket, mess.Buffer(), mess.Length(), 0)) < 0) return -1; fBytesSent += nsent; fgBytesSent += nsent; // If acknowledgement is desired, wait for it if (mess.What() & kMESS_ACK) { char buf[2]; if (gSystem->RecvRaw(fSocket, buf, sizeof(buf), 0) < 0) return -1; if (strncmp(buf, "ok", 2)) { Error("Send", "bad acknowledgement"); return -1; } fBytesRecv += 2; fgBytesRecv += 2; } return nsent - sizeof(UInt_t); //length - length header } //______________________________________________________________________________ Int_t TSocket::SendObject(const TObject *obj, Int_t kind) { // Send an object. Returns the number of bytes sent and -1 in case of error. // In case the "kind" has been or'ed with kMESS_ACK, the call will only // return after having received an acknowledgement, making the sending // synchronous. TMessage mess(kind); mess.WriteObject(obj); return Send(mess); } //______________________________________________________________________________ Int_t TSocket::SendRaw(const void *buffer, Int_t length, ESendRecvOptions opt) { // Send a raw buffer of specified length. Using option kOob one can send // OOB data. Returns the number of bytes sent or -1 in case of error. if (fSocket == -1) return -1; Int_t nsent; if ((nsent = gSystem->SendRaw(fSocket, buffer, length, (int) opt)) < 0) return -1; fBytesSent += nsent; fgBytesSent += nsent; return nsent; } //______________________________________________________________________________ Int_t TSocket::Recv(char *str, Int_t max) { // Receive a character string message of maximum max length. The expected // message must be of type kMESS_STRING. Returns length of received string // (can be 0 if otherside of connection is closed) or -1 in case of error // or -4 in case a non-blocking socket would block (i.e. there is nothing // to be read). Int_t n, kind; if ((n = Recv(str, max, kind)) <= 0) return n; if (kind != kMESS_STRING) { Error("Recv", "got message of wrong kind (expected %d, got %d)", kMESS_STRING, kind); return -1; } return n; } //______________________________________________________________________________ Int_t TSocket::Recv(char *str, Int_t max, Int_t &kind) { // Receive a character string message of maximum max length. Returns in // kind the message type. Returns length of received string (can be 0 if // other side of connection is closed) or -1 in case of error or -4 in // case a non-blocking socket would block (i.e. there is nothing to be read). Int_t n; TMessage *mess; if ((n = Recv(mess)) <= 0) return n; kind = mess->What(); if (str) { if (mess->BufferSize() > (Int_t)sizeof(Int_t)) // if mess contains more than kind mess->ReadString(str, max); else str[0] = 0; } delete mess; return n - sizeof(Int_t); // number of bytes read - TMessage::What() } //______________________________________________________________________________ Int_t TSocket::Recv(TMessage *&mess) { // Receive a TMessage object. The user must delete the TMessage object. // Returns length of message in bytes (can be 0 if other side of connection // is closed) or -1 in case of error or -4 in case a non-blocking socket would // block (i.e. there is nothing to be read). In those case mess == 0. TSystem::ResetErrno(); if (fSocket == -1) { mess = 0; return -1; } Int_t n; UInt_t len; if ((n = gSystem->RecvRaw(fSocket, &len, sizeof(UInt_t), 0)) <= 0) { mess = 0; return n; } len = net2host(len); //from network to host byte order char *buf = new char[len+sizeof(UInt_t)]; if ((n = gSystem->RecvRaw(fSocket, buf+sizeof(UInt_t), len, 0)) <= 0) { delete [] buf; mess = 0; return n; } fBytesRecv += n + sizeof(UInt_t); fgBytesRecv += n + sizeof(UInt_t); mess = new TMessage(buf, len+sizeof(UInt_t)); if (mess->What() & kMESS_ACK) { char ok[2] = { 'o', 'k' }; if (gSystem->SendRaw(fSocket, ok, sizeof(ok), 0) < 0) { delete mess; mess = 0; return -1; } mess->SetWhat(mess->What() & ~kMESS_ACK); fBytesSent += 2; fgBytesSent += 2; } return n; } //______________________________________________________________________________ Int_t TSocket::RecvRaw(void *buffer, Int_t length, ESendRecvOptions opt) { // Receive a raw buffer of specified length bytes. Using option kPeek // one can peek at incoming data. Returns -1 in case of error. In case // of opt == kOob: -2 means EWOULDBLOCK and -3 EINVAL. In case of non-blocking // mode (kNoBlock) -4 means EWOULDBLOCK. TSystem::ResetErrno(); if (fSocket == -1) return -1; Int_t n; if ((n = gSystem->RecvRaw(fSocket, buffer, length, (int) opt)) <= 0) return n; fBytesRecv += n; fgBytesRecv += n; return n; } //______________________________________________________________________________ Int_t TSocket::SetOption(ESockOptions opt, Int_t val) { // Set socket options. if (fSocket == -1) return -1; return gSystem->SetSockOpt(fSocket, opt, val); } //______________________________________________________________________________ Int_t TSocket::GetOption(ESockOptions opt, Int_t &val) { // Get socket options. Returns -1 in case of error. if (fSocket == -1) return -1; return gSystem->GetSockOpt(fSocket, opt, &val); } //______________________________________________________________________________ Int_t TSocket::GetErrorCode() const { // Returns error code. Meaning depends on context where it is called. // If no error condition returns 0 else a value < 0. // For example see TServerSocket ctor. if (!IsValid()) return fSocket; return 0; } <commit_msg>fix in TSocket::Recv(char*,Int_t,Int_t&), don't return 0, but correctly 4 when 0 str has been send (length of kind). 0 is return code when connection has been closed by the remote side.<commit_after>// @(#)root/net:$Name: $:$Id: TSocket.cxx,v 1.3 2000/08/21 10:37:30 rdm Exp $ // Author: Fons Rademakers 18/12/96 /************************************************************************* * Copyright (C) 1995-2000, Rene Brun and Fons Rademakers. * * All rights reserved. * * * * For the licensing terms see $ROOTSYS/LICENSE. * * For the list of contributors see $ROOTSYS/README/CREDITS. * *************************************************************************/ ////////////////////////////////////////////////////////////////////////// // // // TSocket // // // // This class implements client sockets. A socket is an endpoint for // // communication between two machines. // // The actual work is done via the TSystem class (either TUnixSystem, // // TWin32System or TMacSystem). // // // ////////////////////////////////////////////////////////////////////////// #include "TSocket.h" #include "TSystem.h" #include "TMessage.h" #include "Bytes.h" #include "TROOT.h" #include "TError.h" UInt_t TSocket::fgBytesSent = 0; UInt_t TSocket::fgBytesRecv = 0; ClassImp(TSocket) //______________________________________________________________________________ TSocket::TSocket(TInetAddress addr, const char *service) : TNamed(addr.GetHostName(), service) { // Create a socket. Connect to the named service at address addr. // Returns when connection has been accepted by remote side. Use IsValid() // to check the validity of the socket. Every socket is added to the TROOT // sockets list which will make sure that any open sockets are properly // closed on program termination. Assert(gROOT); Assert(gSystem); fService = service; fAddress = addr; fAddress.fPort = gSystem->GetServiceByName(service); fBytesSent = 0; fBytesRecv = 0; if (fAddress.GetPort() != -1) { fSocket = gSystem->OpenConnection(addr.GetHostName(), fAddress.GetPort()); if (fSocket != -1) gROOT->GetListOfSockets()->Add(this); } else fSocket = -1; } //______________________________________________________________________________ TSocket::TSocket(TInetAddress addr, Int_t port) : TNamed(addr.GetHostName(), "") { // Create a socket. Connect to the specified port # at address addr. // Returns when connection has been accepted by remote side. Use IsValid() // to check the validity of the socket. Every socket is added to the TROOT // sockets list which will make sure that any open sockets are properly // closed on program termination. Assert(gROOT); Assert(gSystem); fService = gSystem->GetServiceByPort(port); fAddress = addr; fAddress.fPort = port; SetTitle(fService); fBytesSent = 0; fBytesRecv = 0; fSocket = gSystem->OpenConnection(addr.GetHostName(), fAddress.GetPort()); if (fSocket == -1) fAddress.fPort = -1; else gROOT->GetListOfSockets()->Add(this); } //______________________________________________________________________________ TSocket::TSocket(const char *host, const char *service) : TNamed(host, service) { // Create a socket. Connect to named service on the remote host. // Returns when connection has been accepted by remote side. Use IsValid() // to check the validity of the socket. Every socket is added to the TROOT // sockets list which will make sure that any open sockets are properly // closed on program termination. Assert(gROOT); Assert(gSystem); fService = service; fAddress = gSystem->GetHostByName(host); fAddress.fPort = gSystem->GetServiceByName(service); SetName(fAddress.GetHostName()); fBytesSent = 0; fBytesRecv = 0; if (fAddress.GetPort() != -1) { fSocket = gSystem->OpenConnection(host, fAddress.GetPort()); if (fSocket != -1) gROOT->GetListOfSockets()->Add(this); } else fSocket = -1; } //______________________________________________________________________________ TSocket::TSocket(const char *host, Int_t port) : TNamed(host, "") { // Create a socket. Connect to specified port # on the remote host. // Returns when connection has been accepted by remote side. Use IsValid() // to check the validity of the socket. Every socket is added to the TROOT // sockets list which will make sure that any open sockets are properly // closed on program termination. Assert(gROOT); Assert(gSystem); fService = gSystem->GetServiceByPort(port); fAddress = gSystem->GetHostByName(host); fAddress.fPort = port; SetName(fAddress.GetHostName()); SetTitle(fService); fBytesSent = 0; fBytesRecv = 0; fSocket = gSystem->OpenConnection(host, fAddress.GetPort()); if (fSocket == -1) fAddress.fPort = -1; else gROOT->GetListOfSockets()->Add(this); } //______________________________________________________________________________ TSocket::TSocket(Int_t desc) : TNamed("", "") { // Create a socket. The socket will use descriptor desc. Assert(gROOT); Assert(gSystem); fBytesSent = 0; fBytesRecv = 0; if (desc >= 0) { fSocket = desc; fAddress = gSystem->GetPeerName(fSocket); gROOT->GetListOfSockets()->Add(this); } else fSocket = -1; } //______________________________________________________________________________ TSocket::TSocket(const TSocket &s) { // TSocket copy ctor. fSocket = s.fSocket; fService = s.fService; fAddress = s.fAddress; fLocalAddress = s.fLocalAddress; fBytesSent = s.fBytesSent; fBytesRecv = s.fBytesRecv; if (fSocket != -1) gROOT->GetListOfSockets()->Add(this); } //______________________________________________________________________________ void TSocket::Close(Option_t *option) { // Close the socket. If option is "force", calls shutdown(id,2) to // shut down the connection. This will close the connection also // for the parent of this process. Also called via the dtor (without // option "force", call explicitely Close("force") if this is desired). Bool_t force = option ? (!strcmp(option, "force") ? kTRUE : kFALSE) : kFALSE; if (fSocket != -1) { gSystem->CloseConnection(fSocket, force); gROOT->GetListOfSockets()->Remove(this); } fSocket = -1; } //______________________________________________________________________________ TInetAddress TSocket::GetLocalInetAddress() { // Return internet address of local host to which the socket is bound. // In case of error TInetAddress::IsValid() returns kFALSE. if (fSocket != -1) { if (fLocalAddress.GetPort() == -1) fLocalAddress = gSystem->GetSockName(fSocket); return fLocalAddress; } return TInetAddress(); } //______________________________________________________________________________ Int_t TSocket::GetLocalPort() { // Return the local port # to which the socket is bound. // In case of error return -1. if (fSocket != -1) { if (fLocalAddress.GetPort() == -1) fLocalAddress = GetLocalInetAddress(); return fLocalAddress.GetPort(); } return -1; } //______________________________________________________________________________ Int_t TSocket::Send(Int_t kind) { // Send a single message opcode. Use kind (opcode) to set the // TMessage "what" field. Returns the number of bytes that were sent // (always sizeof(Int_t)) and -1 in case of error. In case the kind has // been or'ed with kMESS_ACK, the call will only return after having // received an acknowledgement, making the sending process synchronous. TMessage mess(kind); return Send(mess); } //______________________________________________________________________________ Int_t TSocket::Send(const char *str, Int_t kind) { // Send a character string buffer. Use kind to set the TMessage "what" field. // Returns the number of bytes in the string str that were sent and -1 in // case of error. In case the kind has been or'ed with kMESS_ACK, the call // will only return after having received an acknowledgement, making the // sending process synchronous. TMessage mess(kind); if (str) mess.WriteString(str); Int_t nsent; if ((nsent = Send(mess)) < 0) return -1; return nsent - sizeof(Int_t); // - TMessage::What() } //______________________________________________________________________________ Int_t TSocket::Send(const TMessage &mess) { // Send a TMessage object. Returns the number of bytes in the TMessage // that were sent and -1 in case of error. In case the TMessage::What // has been or'ed with kMESS_ACK, the call will only return after having // received an acknowledgement, making the sending process synchronous. if (fSocket == -1) return -1; if (mess.IsReading()) { Error("Send", "cannot send a message used for reading"); return -1; } Int_t nsent; mess.SetLength(); //write length in first word of buffer if ((nsent = gSystem->SendRaw(fSocket, mess.Buffer(), mess.Length(), 0)) < 0) return -1; fBytesSent += nsent; fgBytesSent += nsent; // If acknowledgement is desired, wait for it if (mess.What() & kMESS_ACK) { char buf[2]; if (gSystem->RecvRaw(fSocket, buf, sizeof(buf), 0) < 0) return -1; if (strncmp(buf, "ok", 2)) { Error("Send", "bad acknowledgement"); return -1; } fBytesRecv += 2; fgBytesRecv += 2; } return nsent - sizeof(UInt_t); //length - length header } //______________________________________________________________________________ Int_t TSocket::SendObject(const TObject *obj, Int_t kind) { // Send an object. Returns the number of bytes sent and -1 in case of error. // In case the "kind" has been or'ed with kMESS_ACK, the call will only // return after having received an acknowledgement, making the sending // synchronous. TMessage mess(kind); mess.WriteObject(obj); return Send(mess); } //______________________________________________________________________________ Int_t TSocket::SendRaw(const void *buffer, Int_t length, ESendRecvOptions opt) { // Send a raw buffer of specified length. Using option kOob one can send // OOB data. Returns the number of bytes sent or -1 in case of error. if (fSocket == -1) return -1; Int_t nsent; if ((nsent = gSystem->SendRaw(fSocket, buffer, length, (int) opt)) < 0) return -1; fBytesSent += nsent; fgBytesSent += nsent; return nsent; } //______________________________________________________________________________ Int_t TSocket::Recv(char *str, Int_t max) { // Receive a character string message of maximum max length. The expected // message must be of type kMESS_STRING. Returns length of received string // (can be 0 if otherside of connection is closed) or -1 in case of error // or -4 in case a non-blocking socket would block (i.e. there is nothing // to be read). Int_t n, kind; if ((n = Recv(str, max, kind)) <= 0) return n; if (kind != kMESS_STRING) { Error("Recv", "got message of wrong kind (expected %d, got %d)", kMESS_STRING, kind); return -1; } return n; } //______________________________________________________________________________ Int_t TSocket::Recv(char *str, Int_t max, Int_t &kind) { // Receive a character string message of maximum max length. Returns in // kind the message type. Returns length of received string+4 (can be 0 if // other side of connection is closed) or -1 in case of error or -4 in // case a non-blocking socket would block (i.e. there is nothing to be read). Int_t n; TMessage *mess; if ((n = Recv(mess)) <= 0) return n; kind = mess->What(); if (str) { if (mess->BufferSize() > (Int_t)sizeof(Int_t)) // if mess contains more than kind mess->ReadString(str, max); else str[0] = 0; } delete mess; return n; // number of bytes read (len of str + sizeof(kind) } //______________________________________________________________________________ Int_t TSocket::Recv(TMessage *&mess) { // Receive a TMessage object. The user must delete the TMessage object. // Returns length of message in bytes (can be 0 if other side of connection // is closed) or -1 in case of error or -4 in case a non-blocking socket would // block (i.e. there is nothing to be read). In those case mess == 0. TSystem::ResetErrno(); if (fSocket == -1) { mess = 0; return -1; } Int_t n; UInt_t len; if ((n = gSystem->RecvRaw(fSocket, &len, sizeof(UInt_t), 0)) <= 0) { mess = 0; return n; } len = net2host(len); //from network to host byte order char *buf = new char[len+sizeof(UInt_t)]; if ((n = gSystem->RecvRaw(fSocket, buf+sizeof(UInt_t), len, 0)) <= 0) { delete [] buf; mess = 0; return n; } fBytesRecv += n + sizeof(UInt_t); fgBytesRecv += n + sizeof(UInt_t); mess = new TMessage(buf, len+sizeof(UInt_t)); if (mess->What() & kMESS_ACK) { char ok[2] = { 'o', 'k' }; if (gSystem->SendRaw(fSocket, ok, sizeof(ok), 0) < 0) { delete mess; mess = 0; return -1; } mess->SetWhat(mess->What() & ~kMESS_ACK); fBytesSent += 2; fgBytesSent += 2; } return n; } //______________________________________________________________________________ Int_t TSocket::RecvRaw(void *buffer, Int_t length, ESendRecvOptions opt) { // Receive a raw buffer of specified length bytes. Using option kPeek // one can peek at incoming data. Returns -1 in case of error. In case // of opt == kOob: -2 means EWOULDBLOCK and -3 EINVAL. In case of non-blocking // mode (kNoBlock) -4 means EWOULDBLOCK. TSystem::ResetErrno(); if (fSocket == -1) return -1; Int_t n; if ((n = gSystem->RecvRaw(fSocket, buffer, length, (int) opt)) <= 0) return n; fBytesRecv += n; fgBytesRecv += n; return n; } //______________________________________________________________________________ Int_t TSocket::SetOption(ESockOptions opt, Int_t val) { // Set socket options. if (fSocket == -1) return -1; return gSystem->SetSockOpt(fSocket, opt, val); } //______________________________________________________________________________ Int_t TSocket::GetOption(ESockOptions opt, Int_t &val) { // Get socket options. Returns -1 in case of error. if (fSocket == -1) return -1; return gSystem->GetSockOpt(fSocket, opt, &val); } //______________________________________________________________________________ Int_t TSocket::GetErrorCode() const { // Returns error code. Meaning depends on context where it is called. // If no error condition returns 0 else a value < 0. // For example see TServerSocket ctor. if (!IsValid()) return fSocket; return 0; } <|endoftext|>
<commit_before>// Copyright NVIDIA Corporation 2007 -- Ignacio Castano <icastano@nvidia.com> // // Permission is hereby granted, free of charge, to any person // obtaining a copy of this software and associated documentation // files (the "Software"), to deal in the Software without // restriction, including without limitation the rights to use, // copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the // Software is furnished to do so, subject to the following // conditions: // // The above copyright notice and this permission notice shall be // included in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, // EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES // OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND // NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT // HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, // WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING // FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR // OTHER DEALINGS IN THE SOFTWARE. #include <nvimage/NormalMap.h> #include <nvimage/Filter.h> #include <nvimage/FloatImage.h> #include <nvimage/Image.h> #include <nvmath/Color.h> #include <nvcore/Ptr.h> using namespace nv; // Create normal map using the given kernels. static FloatImage * createNormalMap(const Image * img, FloatImage::WrapMode wm, Vector4::Arg heightWeights, const Kernel2 * kdu, const Kernel2 * kdv) { nvDebugCheck(kdu != NULL); nvDebugCheck(kdv != NULL); nvDebugCheck(img != NULL); const uint w = img->width(); const uint h = img->height(); AutoPtr<FloatImage> fimage(new FloatImage()); fimage->allocate(4, w, h); // Compute height and store in alpha channel: float * alphaChannel = fimage->channel(3); for(uint i = 0; i < w*h; i++) { Vector4 color = toVector4(img->pixel(i)); alphaChannel[i] = dot(color, heightWeights); } float heightScale = 1.0f / 16.0f; // @@ Use a user defined factor. for(uint y = 0; y < h; y++) { for(uint x = 0; x < w; x++) { const float du = fimage->applyKernel(kdu, x, y, 3, wm); const float dv = fimage->applyKernel(kdv, x, y, 3, wm); Vector3 n = normalize(Vector3(du, dv, heightScale)); fimage->setPixel(0.5f * n.x() + 0.5f, x, y, 0); fimage->setPixel(0.5f * n.y() + 0.5f, x, y, 1); fimage->setPixel(0.5f * n.z() + 0.5f, x, y, 2); } } return fimage.release(); } // Create normal map using the given kernels. static FloatImage * createNormalMap(const FloatImage * img, FloatImage::WrapMode wm, const Kernel2 * kdu, const Kernel2 * kdv) { nvDebugCheck(kdu != NULL); nvDebugCheck(kdv != NULL); nvDebugCheck(img != NULL); #pragma message(NV_FILE_LINE "Height scale parameter should go away. It should be a sensible value that produces good results when the heightmap is in the [0, 1] range.") const float heightScale = 1.0f / 16.0f; const uint w = img->width(); const uint h = img->height(); AutoPtr<FloatImage> img_out(new FloatImage()); img_out->allocate(4, w, h); for (uint y = 0; y < h; y++) { for (uint x = 0; x < w; x++) { const float du = img->applyKernel(kdu, x, y, 3, wm); const float dv = img->applyKernel(kdv, x, y, 3, wm); Vector3 n = normalize(Vector3(du, dv, heightScale)); img_out->setPixel(n.x(), x, y, 0); img_out->setPixel(n.y(), x, y, 1); img_out->setPixel(n.z(), x, y, 2); } } // Copy alpha channel. for (uint y = 0; y < h; y++) { for (uint x = 0; x < w; x++) { img_out->setPixel(img->pixel(x, y, 3), x, y, 3); } } return img_out.release(); } /// Create normal map using the given filter. FloatImage * nv::createNormalMap(const Image * img, FloatImage::WrapMode wm, Vector4::Arg heightWeights, NormalMapFilter filter /*= Sobel3x3*/) { nvDebugCheck(img != NULL); // Init the kernels. Kernel2 * kdu = NULL; Kernel2 * kdv = NULL; switch(filter) { case NormalMapFilter_Sobel3x3: kdu = new Kernel2(3); break; case NormalMapFilter_Sobel5x5: kdu = new Kernel2(5); break; case NormalMapFilter_Sobel7x7: kdu = new Kernel2(7); break; case NormalMapFilter_Sobel9x9: kdu = new Kernel2(9); break; default: nvDebugCheck(false); }; kdu->initSobel(); kdu->normalize(); kdv = new Kernel2(*kdu); kdv->transpose(); return ::createNormalMap(img, wm, heightWeights, kdu, kdv); } /// Create normal map combining multiple sobel filters. FloatImage * nv::createNormalMap(const Image * img, FloatImage::WrapMode wm, Vector4::Arg heightWeights, Vector4::Arg filterWeights) { nvDebugCheck(img != NULL); Kernel2 * kdu = NULL; Kernel2 * kdv = NULL; kdu = new Kernel2(9); kdu->initBlendedSobel(filterWeights); kdu->normalize(); kdv = new Kernel2(*kdu); kdv->transpose(); return ::createNormalMap(img, wm, heightWeights, kdu, kdv); } FloatImage * nv::createNormalMap(const FloatImage * img, FloatImage::WrapMode wm, Vector4::Arg filterWeights) { nvDebugCheck(img != NULL); Kernel2 * kdu = NULL; Kernel2 * kdv = NULL; kdu = new Kernel2(9); kdu->initBlendedSobel(filterWeights); kdu->normalize(); kdv = new Kernel2(*kdu); kdv->transpose(); return ::createNormalMap(img, wm, kdu, kdv); } /// Normalize the given image in place. void nv::normalizeNormalMap(FloatImage * img) { nvDebugCheck(img != NULL); #pragma messsage(NV_FILE_LINE "Pack and expand normals explicitly") img->expandNormals(0); img->normalize(0); img->packNormals(0); } <commit_msg>Fix messages.<commit_after>// Copyright NVIDIA Corporation 2007 -- Ignacio Castano <icastano@nvidia.com> // // Permission is hereby granted, free of charge, to any person // obtaining a copy of this software and associated documentation // files (the "Software"), to deal in the Software without // restriction, including without limitation the rights to use, // copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the // Software is furnished to do so, subject to the following // conditions: // // The above copyright notice and this permission notice shall be // included in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, // EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES // OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND // NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT // HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, // WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING // FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR // OTHER DEALINGS IN THE SOFTWARE. #include <nvimage/NormalMap.h> #include <nvimage/Filter.h> #include <nvimage/FloatImage.h> #include <nvimage/Image.h> #include <nvmath/Color.h> #include <nvcore/Ptr.h> using namespace nv; // Create normal map using the given kernels. static FloatImage * createNormalMap(const Image * img, FloatImage::WrapMode wm, Vector4::Arg heightWeights, const Kernel2 * kdu, const Kernel2 * kdv) { nvDebugCheck(kdu != NULL); nvDebugCheck(kdv != NULL); nvDebugCheck(img != NULL); const uint w = img->width(); const uint h = img->height(); AutoPtr<FloatImage> fimage(new FloatImage()); fimage->allocate(4, w, h); // Compute height and store in alpha channel: float * alphaChannel = fimage->channel(3); for(uint i = 0; i < w*h; i++) { Vector4 color = toVector4(img->pixel(i)); alphaChannel[i] = dot(color, heightWeights); } float heightScale = 1.0f / 16.0f; // @@ Use a user defined factor. for(uint y = 0; y < h; y++) { for(uint x = 0; x < w; x++) { const float du = fimage->applyKernel(kdu, x, y, 3, wm); const float dv = fimage->applyKernel(kdv, x, y, 3, wm); Vector3 n = normalize(Vector3(du, dv, heightScale)); fimage->setPixel(0.5f * n.x() + 0.5f, x, y, 0); fimage->setPixel(0.5f * n.y() + 0.5f, x, y, 1); fimage->setPixel(0.5f * n.z() + 0.5f, x, y, 2); } } return fimage.release(); } // Create normal map using the given kernels. static FloatImage * createNormalMap(const FloatImage * img, FloatImage::WrapMode wm, const Kernel2 * kdu, const Kernel2 * kdv) { nvDebugCheck(kdu != NULL); nvDebugCheck(kdv != NULL); nvDebugCheck(img != NULL); #pragma message(NV_FILE_LINE "FIXME: Height scale parameter should go away. It should be a sensible value that produces good results when the heightmap is in the [0, 1] range.") const float heightScale = 1.0f / 16.0f; const uint w = img->width(); const uint h = img->height(); AutoPtr<FloatImage> img_out(new FloatImage()); img_out->allocate(4, w, h); for (uint y = 0; y < h; y++) { for (uint x = 0; x < w; x++) { const float du = img->applyKernel(kdu, x, y, 3, wm); const float dv = img->applyKernel(kdv, x, y, 3, wm); Vector3 n = normalize(Vector3(du, dv, heightScale)); img_out->setPixel(n.x(), x, y, 0); img_out->setPixel(n.y(), x, y, 1); img_out->setPixel(n.z(), x, y, 2); } } // Copy alpha channel. for (uint y = 0; y < h; y++) { for (uint x = 0; x < w; x++) { img_out->setPixel(img->pixel(x, y, 3), x, y, 3); } } return img_out.release(); } /// Create normal map using the given filter. FloatImage * nv::createNormalMap(const Image * img, FloatImage::WrapMode wm, Vector4::Arg heightWeights, NormalMapFilter filter /*= Sobel3x3*/) { nvDebugCheck(img != NULL); // Init the kernels. Kernel2 * kdu = NULL; Kernel2 * kdv = NULL; switch(filter) { case NormalMapFilter_Sobel3x3: kdu = new Kernel2(3); break; case NormalMapFilter_Sobel5x5: kdu = new Kernel2(5); break; case NormalMapFilter_Sobel7x7: kdu = new Kernel2(7); break; case NormalMapFilter_Sobel9x9: kdu = new Kernel2(9); break; default: nvDebugCheck(false); }; kdu->initSobel(); kdu->normalize(); kdv = new Kernel2(*kdu); kdv->transpose(); return ::createNormalMap(img, wm, heightWeights, kdu, kdv); } /// Create normal map combining multiple sobel filters. FloatImage * nv::createNormalMap(const Image * img, FloatImage::WrapMode wm, Vector4::Arg heightWeights, Vector4::Arg filterWeights) { nvDebugCheck(img != NULL); Kernel2 * kdu = NULL; Kernel2 * kdv = NULL; kdu = new Kernel2(9); kdu->initBlendedSobel(filterWeights); kdu->normalize(); kdv = new Kernel2(*kdu); kdv->transpose(); return ::createNormalMap(img, wm, heightWeights, kdu, kdv); } FloatImage * nv::createNormalMap(const FloatImage * img, FloatImage::WrapMode wm, Vector4::Arg filterWeights) { nvDebugCheck(img != NULL); Kernel2 * kdu = NULL; Kernel2 * kdv = NULL; kdu = new Kernel2(9); kdu->initBlendedSobel(filterWeights); kdu->normalize(); kdv = new Kernel2(*kdu); kdv->transpose(); return ::createNormalMap(img, wm, kdu, kdv); } /// Normalize the given image in place. void nv::normalizeNormalMap(FloatImage * img) { nvDebugCheck(img != NULL); #pragma message(NV_FILE_LINE "TODO: Pack and expand normals explicitly") img->expandNormals(0); img->normalize(0); img->packNormals(0); } <|endoftext|>
<commit_before>/* bzflag * Copyright (c) 1993 - 2005 Tim Riker * * This package is free software; you can redistribute it and/or * modify it under the terms of the license found in the file * named COPYING that should have accompanied this file. * * THIS PACKAGE IS PROVIDED ``AS IS'' AND WITHOUT ANY EXPRESS OR * IMPLIED WARRANTIES, INCLUDING, WITHOUT LIMITATION, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. */ #include "common.h" // system headers #include <string> // common headers #include "bzfio.h" #include "StateDatabase.h" #include "bzfgl.h" #include "OpenGLTexture.h" #include "OpenGLGState.h" // // OpenGLTexture::Rep // const GLenum OpenGLTexture::minifyFilter[] = { GL_NEAREST, GL_NEAREST, GL_LINEAR, GL_NEAREST_MIPMAP_NEAREST, GL_LINEAR_MIPMAP_NEAREST, GL_NEAREST_MIPMAP_LINEAR, GL_LINEAR_MIPMAP_LINEAR }; const GLenum OpenGLTexture::magnifyFilter[] = { GL_NEAREST, GL_NEAREST, GL_LINEAR, GL_NEAREST, GL_LINEAR, GL_NEAREST, GL_LINEAR }; const char* OpenGLTexture::configFilterNames[] = { "no", "nearest", "linear", "nearestmipmapnearest", "linearmipmapnearest", "nearestmipmaplinear", "linearmipmaplinear" }; // // OpenGLTexture // const int OpenGLTexture::filterCount = Max + 1; OpenGLTexture::Filter OpenGLTexture::maxFilter = Default; OpenGLTexture::OpenGLTexture(int _width, int _height, const GLvoid* pixels, Filter _filter, bool _repeat, int _internalFormat) : width(_width), height(_height) { alpha = false; repeat = _repeat; internalFormat = _internalFormat; filter = _filter; list = INVALID_GL_TEXTURE_ID; // get internal format if not provided if (internalFormat == 0) internalFormat = getBestFormat(width, height, pixels); // copy/scale the original texture image setupImage((const GLubyte*)pixels); // build and bind the GL texture initContext(); // watch for context recreation OpenGLGState::registerContextInitializer(static_freeContext, static_initContext, (void*)this); } OpenGLTexture::~OpenGLTexture() { OpenGLGState::unregisterContextInitializer(static_freeContext, static_initContext, (void*)this); delete[] imageMemory; freeContext(); return; } void OpenGLTexture::static_freeContext(void *that) { ((OpenGLTexture*) that)->freeContext(); } void OpenGLTexture::static_initContext(void *that) { ((OpenGLTexture*) that)->initContext(); } void OpenGLTexture::freeContext() { // glDeleteTextures should set binding to 0 by itself when the texture // is in use, but some stacks (Linux/glx/matrox) are broken, so play it safe glBindTexture(GL_TEXTURE_2D, 0); if (list != INVALID_GL_TEXTURE_ID) { glDeleteTextures(1, &list); list = INVALID_GL_TEXTURE_ID; } return; } void OpenGLTexture::initContext() { // make texture map object/list glGenTextures(1, &list); // now make texture map display list (compute all mipmaps, if requested). // compute next mipmap from current mipmap to save time. setFilter(filter); glBindTexture(GL_TEXTURE_2D, list); gluBuild2DMipmaps(GL_TEXTURE_2D, internalFormat, scaledWidth, scaledHeight, GL_RGBA, GL_UNSIGNED_BYTE, image); glBindTexture(GL_TEXTURE_2D, 0); return; } bool OpenGLTexture::setupImage(const GLubyte* pixels) { // align to a 2^N value scaledWidth = 1; scaledHeight = 1; while (scaledWidth < width) { scaledWidth <<= 1; } while (scaledHeight < height) { scaledHeight <<= 1; } // get maximum valid size for texture (boost to 2^m x 2^n) GLint maxTextureSize; glGetIntegerv(GL_MAX_TEXTURE_SIZE, &maxTextureSize); // hard limit, some drivers have problems with sizes greater // then this (espeically if you are using glTexSubImage2D) const GLint dbMaxTexSize = BZDB.evalInt("maxTextureSize"); GLint bzMaxTexSize = 1; // align the max size to a power of two (wasteful) while (bzMaxTexSize < dbMaxTexSize) { bzMaxTexSize <<= 1; } if ((maxTextureSize < 0) || (maxTextureSize > bzMaxTexSize)) { maxTextureSize = bzMaxTexSize; } // clamp to the maximum size if (scaledWidth > maxTextureSize) { scaledWidth = maxTextureSize; } if (scaledHeight > maxTextureSize) { scaledHeight = maxTextureSize; } // NOTE: why these are 4-byte aligned is beyond me... // copy the data into a 4-byte aligned buffer GLubyte* unaligned = new GLubyte[4 * width * height + 4]; GLubyte* aligned = (GLubyte*)(((unsigned long)unaligned & ~3) + 4); ::memcpy(aligned, pixels, 4 * width * height); // scale the image if required if ((scaledWidth != width) || (scaledHeight != height)) { GLubyte* unalignedScaled = new GLubyte[4 * scaledWidth * scaledHeight + 4]; GLubyte* alignedScaled = (GLubyte*)(((unsigned long)unalignedScaled & ~3) + 4); // FIXME: 0 is success, return false otherwise... gluScaleImage (GL_RGBA, width, height, GL_UNSIGNED_BYTE, aligned, scaledWidth, scaledHeight, GL_UNSIGNED_BYTE, alignedScaled); delete[] unaligned; unaligned = unalignedScaled; aligned = alignedScaled; DEBUG1("Scaling texture from %ix%i to %ix%i\n", width, height, scaledWidth, scaledHeight); } // set the image image = aligned; imageMemory = unaligned; // note if internal format uses alpha switch (internalFormat) { case GL_LUMINANCE_ALPHA: #if defined(GL_LUMINANCE4_ALPHA4) case GL_LUMINANCE4_ALPHA4: #elif defined(GL_LUMINANCE4_ALPHA4_EXT) case GL_LUMINANCE4_ALPHA4_EXT: #endif case GL_RGBA: #if defined(GL_INTENSITY4) case GL_INTENSITY4: #elif defined(GL_INTENSITY4_EXT) case GL_INTENSITY4_EXT: #endif alpha = true; break; default: alpha = false; break; } return true; } OpenGLTexture::Filter OpenGLTexture::getFilter() { return filter; } void OpenGLTexture::setFilter(Filter _filter) { filter = _filter; int filterIndex = (int) filter; // limit filter. try to keep nearest... filters as nearest and // linear... as linear. if (filterIndex > maxFilter) { if ((filterIndex & 1) == 1) { // nearest... if ((maxFilter & 1) == 1) { filterIndex = maxFilter; } else { filterIndex = maxFilter > 0 ? maxFilter - 1 : 0; } } else { // linear... if ((maxFilter & 1) == 1) { filterIndex = maxFilter - 1; } else { filterIndex = maxFilter; } } } GLint binding; glGetIntegerv (GL_TEXTURE_BINDING_2D, &binding); glBindTexture(GL_TEXTURE_2D, list); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, minifyFilter[filterIndex]); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, magnifyFilter[filterIndex]); glBindTexture(GL_TEXTURE_2D, binding); } OpenGLTexture::Filter OpenGLTexture::getMaxFilter() { return maxFilter; } void OpenGLTexture::setMaxFilter(Filter _filter) { maxFilter = _filter; } void OpenGLTexture::execute() { bind(); } const char* OpenGLTexture::getFilterName(OpenGLTexture::Filter filter) { if ((filter < 0) || (filter > Max)) { return configFilterNames[Max]; } else { return configFilterNames[filter]; } } int OpenGLTexture::getFilterCount() { return filterCount; } const char** OpenGLTexture::getFilterNames() { return configFilterNames; } float OpenGLTexture::getAspectRatio() const { return ((float) height) / ((float) width); } void OpenGLTexture::bind() { if (list != INVALID_GL_TEXTURE_ID) { glBindTexture(GL_TEXTURE_2D, list); } else { glBindTexture(GL_TEXTURE_2D, 0); // heh, it's the same call } } int OpenGLTexture::getBestFormat(int _width, int _height, const GLvoid* pixels) { // see if all pixels are achromatic const GLubyte* scan = (const GLubyte*)pixels; const int size = _width * _height; int i; for (i = 0; i < size; scan += 4, i++) if (scan[0] != scan[1] || scan[0] != scan[2]) break; const bool useLuminance = (i == size); // see if all pixels are opaque scan = (const GLubyte*)pixels; for (i = 0; i < size; scan += 4, i++) if (scan[3] != 0xff) break; const bool useAlpha = (i != size); // intensity format defined in 1.1 and an extension in 1.0 static const bool hasTextureExt = true; // see if all pixels are r=g=b=a. if so return intensity format. // SGI IMPACT and 3Dfx systems don't support GL_INTENSITY. const char* const glRenderer = (const char*)glGetString(GL_RENDERER); static bool noIntensity = ((glRenderer == NULL) || (strncmp(glRenderer, "IMPACT", 6) == 0) || (strncmp(glRenderer, "3Dfx", 4) == 0)); if (!noIntensity) { bool useIntensity = false; if (hasTextureExt && useLuminance) { scan = (const GLubyte*)pixels; for (i = 0; i < size; scan += 4, i++) if (scan[3] != scan[0]) break; useIntensity = (i == size); } if (useIntensity) return GL_INTENSITY; } // pick internal format return (useLuminance ? (useAlpha ? GL_LUMINANCE_ALPHA : GL_LUMINANCE) : (useAlpha ? GL_RGBA : GL_RGB)); } bool OpenGLTexture::getColorAverages(float rgba[4], bool factorAlpha) const { if ((image == NULL) || (scaledWidth <= 0) || (scaledHeight <= 0)) { return false; } factorAlpha = (factorAlpha && alpha); const int channelCount = alpha ? 4 : 3; // tally the values unsigned long long int rgbaTally[4] = {0, 0, 0, 0}; for (int x = 0; x < scaledWidth; x++) { for (int y = 0; y < scaledHeight; y++) { for (int c = 0; c < channelCount; c++) { const int pixelBase = 4 * (x + (y * scaledWidth)); if (factorAlpha) { const GLubyte alphaVal = image[pixelBase + 3]; if (c == 3) { rgbaTally[3] += alphaVal; } else { rgbaTally[c] += image[pixelBase + c] * alphaVal; } } else { rgbaTally[c] += image[pixelBase + c]; } } } } // calculate the alpha average float maxTally = 255.0f * (scaledWidth * scaledHeight); if (channelCount == 3) { rgba[3] = 1.0f; } else { rgba[3] = (float)rgbaTally[3] / maxTally; } // adjust the maxTally for alpha weighting if (factorAlpha) { maxTally = maxTally * 255.0f; } // calcualte the color averages for (int c = 0; c < 3; c++) { rgba[c] = (float)rgbaTally[c] / maxTally; } return true; } // Local Variables: *** // mode:C++ *** // tab-width: 8 *** // c-basic-offset: 2 *** // indent-tabs-mode: t *** // End: *** // ex: shiftwidth=2 tabstop=8 <commit_msg>long long -> s64<commit_after>/* bzflag * Copyright (c) 1993 - 2005 Tim Riker * * This package is free software; you can redistribute it and/or * modify it under the terms of the license found in the file * named COPYING that should have accompanied this file. * * THIS PACKAGE IS PROVIDED ``AS IS'' AND WITHOUT ANY EXPRESS OR * IMPLIED WARRANTIES, INCLUDING, WITHOUT LIMITATION, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. */ #include "common.h" // system headers #include <string> // common headers #include "bzfio.h" #include "StateDatabase.h" #include "bzfgl.h" #include "OpenGLTexture.h" #include "OpenGLGState.h" #ifndef _WIN32 typedef int64_t s64; #else typedef __int64 s64; #endif // // OpenGLTexture::Rep // const GLenum OpenGLTexture::minifyFilter[] = { GL_NEAREST, GL_NEAREST, GL_LINEAR, GL_NEAREST_MIPMAP_NEAREST, GL_LINEAR_MIPMAP_NEAREST, GL_NEAREST_MIPMAP_LINEAR, GL_LINEAR_MIPMAP_LINEAR }; const GLenum OpenGLTexture::magnifyFilter[] = { GL_NEAREST, GL_NEAREST, GL_LINEAR, GL_NEAREST, GL_LINEAR, GL_NEAREST, GL_LINEAR }; const char* OpenGLTexture::configFilterNames[] = { "no", "nearest", "linear", "nearestmipmapnearest", "linearmipmapnearest", "nearestmipmaplinear", "linearmipmaplinear" }; // // OpenGLTexture // const int OpenGLTexture::filterCount = Max + 1; OpenGLTexture::Filter OpenGLTexture::maxFilter = Default; OpenGLTexture::OpenGLTexture(int _width, int _height, const GLvoid* pixels, Filter _filter, bool _repeat, int _internalFormat) : width(_width), height(_height) { alpha = false; repeat = _repeat; internalFormat = _internalFormat; filter = _filter; list = INVALID_GL_TEXTURE_ID; // get internal format if not provided if (internalFormat == 0) internalFormat = getBestFormat(width, height, pixels); // copy/scale the original texture image setupImage((const GLubyte*)pixels); // build and bind the GL texture initContext(); // watch for context recreation OpenGLGState::registerContextInitializer(static_freeContext, static_initContext, (void*)this); } OpenGLTexture::~OpenGLTexture() { OpenGLGState::unregisterContextInitializer(static_freeContext, static_initContext, (void*)this); delete[] imageMemory; freeContext(); return; } void OpenGLTexture::static_freeContext(void *that) { ((OpenGLTexture*) that)->freeContext(); } void OpenGLTexture::static_initContext(void *that) { ((OpenGLTexture*) that)->initContext(); } void OpenGLTexture::freeContext() { // glDeleteTextures should set binding to 0 by itself when the texture // is in use, but some stacks (Linux/glx/matrox) are broken, so play it safe glBindTexture(GL_TEXTURE_2D, 0); if (list != INVALID_GL_TEXTURE_ID) { glDeleteTextures(1, &list); list = INVALID_GL_TEXTURE_ID; } return; } void OpenGLTexture::initContext() { // make texture map object/list glGenTextures(1, &list); // now make texture map display list (compute all mipmaps, if requested). // compute next mipmap from current mipmap to save time. setFilter(filter); glBindTexture(GL_TEXTURE_2D, list); gluBuild2DMipmaps(GL_TEXTURE_2D, internalFormat, scaledWidth, scaledHeight, GL_RGBA, GL_UNSIGNED_BYTE, image); glBindTexture(GL_TEXTURE_2D, 0); return; } bool OpenGLTexture::setupImage(const GLubyte* pixels) { // align to a 2^N value scaledWidth = 1; scaledHeight = 1; while (scaledWidth < width) { scaledWidth <<= 1; } while (scaledHeight < height) { scaledHeight <<= 1; } // get maximum valid size for texture (boost to 2^m x 2^n) GLint maxTextureSize; glGetIntegerv(GL_MAX_TEXTURE_SIZE, &maxTextureSize); // hard limit, some drivers have problems with sizes greater // then this (espeically if you are using glTexSubImage2D) const GLint dbMaxTexSize = BZDB.evalInt("maxTextureSize"); GLint bzMaxTexSize = 1; // align the max size to a power of two (wasteful) while (bzMaxTexSize < dbMaxTexSize) { bzMaxTexSize <<= 1; } if ((maxTextureSize < 0) || (maxTextureSize > bzMaxTexSize)) { maxTextureSize = bzMaxTexSize; } // clamp to the maximum size if (scaledWidth > maxTextureSize) { scaledWidth = maxTextureSize; } if (scaledHeight > maxTextureSize) { scaledHeight = maxTextureSize; } // NOTE: why these are 4-byte aligned is beyond me... // copy the data into a 4-byte aligned buffer GLubyte* unaligned = new GLubyte[4 * width * height + 4]; GLubyte* aligned = (GLubyte*)(((unsigned long)unaligned & ~3) + 4); ::memcpy(aligned, pixels, 4 * width * height); // scale the image if required if ((scaledWidth != width) || (scaledHeight != height)) { GLubyte* unalignedScaled = new GLubyte[4 * scaledWidth * scaledHeight + 4]; GLubyte* alignedScaled = (GLubyte*)(((unsigned long)unalignedScaled & ~3) + 4); // FIXME: 0 is success, return false otherwise... gluScaleImage (GL_RGBA, width, height, GL_UNSIGNED_BYTE, aligned, scaledWidth, scaledHeight, GL_UNSIGNED_BYTE, alignedScaled); delete[] unaligned; unaligned = unalignedScaled; aligned = alignedScaled; DEBUG1("Scaling texture from %ix%i to %ix%i\n", width, height, scaledWidth, scaledHeight); } // set the image image = aligned; imageMemory = unaligned; // note if internal format uses alpha switch (internalFormat) { case GL_LUMINANCE_ALPHA: #if defined(GL_LUMINANCE4_ALPHA4) case GL_LUMINANCE4_ALPHA4: #elif defined(GL_LUMINANCE4_ALPHA4_EXT) case GL_LUMINANCE4_ALPHA4_EXT: #endif case GL_RGBA: #if defined(GL_INTENSITY4) case GL_INTENSITY4: #elif defined(GL_INTENSITY4_EXT) case GL_INTENSITY4_EXT: #endif alpha = true; break; default: alpha = false; break; } return true; } OpenGLTexture::Filter OpenGLTexture::getFilter() { return filter; } void OpenGLTexture::setFilter(Filter _filter) { filter = _filter; int filterIndex = (int) filter; // limit filter. try to keep nearest... filters as nearest and // linear... as linear. if (filterIndex > maxFilter) { if ((filterIndex & 1) == 1) { // nearest... if ((maxFilter & 1) == 1) { filterIndex = maxFilter; } else { filterIndex = maxFilter > 0 ? maxFilter - 1 : 0; } } else { // linear... if ((maxFilter & 1) == 1) { filterIndex = maxFilter - 1; } else { filterIndex = maxFilter; } } } GLint binding; glGetIntegerv (GL_TEXTURE_BINDING_2D, &binding); glBindTexture(GL_TEXTURE_2D, list); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, minifyFilter[filterIndex]); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, magnifyFilter[filterIndex]); glBindTexture(GL_TEXTURE_2D, binding); } OpenGLTexture::Filter OpenGLTexture::getMaxFilter() { return maxFilter; } void OpenGLTexture::setMaxFilter(Filter _filter) { maxFilter = _filter; } void OpenGLTexture::execute() { bind(); } const char* OpenGLTexture::getFilterName(OpenGLTexture::Filter filter) { if ((filter < 0) || (filter > Max)) { return configFilterNames[Max]; } else { return configFilterNames[filter]; } } int OpenGLTexture::getFilterCount() { return filterCount; } const char** OpenGLTexture::getFilterNames() { return configFilterNames; } float OpenGLTexture::getAspectRatio() const { return ((float) height) / ((float) width); } void OpenGLTexture::bind() { if (list != INVALID_GL_TEXTURE_ID) { glBindTexture(GL_TEXTURE_2D, list); } else { glBindTexture(GL_TEXTURE_2D, 0); // heh, it's the same call } } int OpenGLTexture::getBestFormat(int _width, int _height, const GLvoid* pixels) { // see if all pixels are achromatic const GLubyte* scan = (const GLubyte*)pixels; const int size = _width * _height; int i; for (i = 0; i < size; scan += 4, i++) if (scan[0] != scan[1] || scan[0] != scan[2]) break; const bool useLuminance = (i == size); // see if all pixels are opaque scan = (const GLubyte*)pixels; for (i = 0; i < size; scan += 4, i++) if (scan[3] != 0xff) break; const bool useAlpha = (i != size); // intensity format defined in 1.1 and an extension in 1.0 static const bool hasTextureExt = true; // see if all pixels are r=g=b=a. if so return intensity format. // SGI IMPACT and 3Dfx systems don't support GL_INTENSITY. const char* const glRenderer = (const char*)glGetString(GL_RENDERER); static bool noIntensity = ((glRenderer == NULL) || (strncmp(glRenderer, "IMPACT", 6) == 0) || (strncmp(glRenderer, "3Dfx", 4) == 0)); if (!noIntensity) { bool useIntensity = false; if (hasTextureExt && useLuminance) { scan = (const GLubyte*)pixels; for (i = 0; i < size; scan += 4, i++) if (scan[3] != scan[0]) break; useIntensity = (i == size); } if (useIntensity) return GL_INTENSITY; } // pick internal format return (useLuminance ? (useAlpha ? GL_LUMINANCE_ALPHA : GL_LUMINANCE) : (useAlpha ? GL_RGBA : GL_RGB)); } bool OpenGLTexture::getColorAverages(float rgba[4], bool factorAlpha) const { if ((image == NULL) || (scaledWidth <= 0) || (scaledHeight <= 0)) { return false; } factorAlpha = (factorAlpha && alpha); const int channelCount = alpha ? 4 : 3; // tally the values s64 rgbaTally[4] = {0, 0, 0, 0}; for (int x = 0; x < scaledWidth; x++) { for (int y = 0; y < scaledHeight; y++) { for (int c = 0; c < channelCount; c++) { const int pixelBase = 4 * (x + (y * scaledWidth)); if (factorAlpha) { const GLubyte alphaVal = image[pixelBase + 3]; if (c == 3) { rgbaTally[3] += alphaVal; } else { rgbaTally[c] += image[pixelBase + c] * alphaVal; } } else { rgbaTally[c] += image[pixelBase + c]; } } } } // calculate the alpha average float maxTally = 255.0f * (scaledWidth * scaledHeight); if (channelCount == 3) { rgba[3] = 1.0f; } else { rgba[3] = (float)rgbaTally[3] / maxTally; } // adjust the maxTally for alpha weighting if (factorAlpha) { maxTally = maxTally * 255.0f; } // calcualte the color averages for (int c = 0; c < 3; c++) { rgba[c] = (float)rgbaTally[c] / maxTally; } return true; } // Local Variables: *** // mode:C++ *** // tab-width: 8 *** // c-basic-offset: 2 *** // indent-tabs-mode: t *** // End: *** // ex: shiftwidth=2 tabstop=8 <|endoftext|>
<commit_before>#include <iostream> #include <cstdio> #include <stdlib.h> using namespace std; enum direction{ UP, DOWN, LEFT, RIGHT, UP_LEFT, UP_RIGHT, DOWN_LEFT, DOWN_RIGHT }; typedef int point[2]; //Declare a point type that represents a point on the grid class Generator{ char grid[10][10]; //Create a 10x10 grid public: Generator(); char GenerateRandomChar(); bool CanInsert(const char word[], point start, direction x); void ClearGrid(); void FillGrid(); }; Generator::Generator(){ } char Generator::GenerateRandomChar(){ return 'A' + rand()%26; } //Sets all values in grid to 0 void Generator::ClearGrid(){ for(int i=0;i<10;i++){ for(int k=0;k<10;k++){ grid[i][k] = 0; //Empty every value } } } //Checks if word can be inserted in the grid at the given start point bool Generator::CanInsert(const char word[], point start, direction x){ return true; } //Replaces empty tiles with a random character void Generator::FillGrid(){ for(int i=0;i<10;i++){ for(int k=0;k<10;k++){ if(grid[i][k] == 0){ grid[i][k] = GenerateRandomChar(); //Set every null value to a random character } } } } int main(){ /* initialize random seed: */ srand (time(NULL)); Generator gen; gen.ClearGrid(); //int startPos[2] = {1,2}; return 0; } <commit_msg>added print function<commit_after>#include <iostream> #include <cstdio> #include <stdlib.h> using namespace std; enum direction{ UP, DOWN, LEFT, RIGHT, UP_LEFT, UP_RIGHT, DOWN_LEFT, DOWN_RIGHT }; typedef int point[2]; //Declare a point type that represents a point on the grid class Generator{ char grid[10][10]; //Create a 10x10 grid const char NULL_CHAR = 'x'; //The null character will be a lowercase x public: Generator(); char GenerateRandomChar(); bool CanInsert(const char word[], point start, direction x); void ClearGrid(); void FillGrid(); void PrintGrid(); }; Generator::Generator(){ } char Generator::GenerateRandomChar(){ return 'A' + rand()%26; } //Sets all values in grid to 0 void Generator::ClearGrid(){ for(int i=0;i<10;i++){ for(int k=0;k<10;k++){ grid[i][k] = NULL_CHAR; //Every empty value will be a lowercase x } } } //Checks if word can be inserted in the grid at the given start point bool Generator::CanInsert(const char word[], point start, direction x){ return true; } //Replaces empty tiles with a random character void Generator::FillGrid(){ for(int i=0;i<10;i++){ for(int k=0;k<10;k++){ if(grid[i][k] == 0){ grid[i][k] = GenerateRandomChar(); //Set every null value to a random character } } } } //Replaces empty tiles with a random character void Generator::PrintGrid(){ for(int i=0;i<10;i++){ for(int k=0;k<10;k++){ if(k == 9){ printf("%c\n",grid[i][k]); //Append a newline if it is on the last column } else{ printf("%c",grid[i][k]); } } } } int main(){ /* initialize random seed: */ srand (time(NULL)); Generator gen; gen.ClearGrid(); gen.PrintGrid(); //int startPos[2] = {1,2}; return 0; } <|endoftext|>
<commit_before>/* -*-c++-*- OpenSceneGraph - Copyright (C) 1998-2006 Robert Osfield * * This library is open source and may be redistributed and/or modified under * the terms of the OpenSceneGraph Public License (OSGPL) version 0.0 or * (at your option) any later version. The full license is in LICENSE file * included with this distribution, and on the openscenegraph.org website. * * 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 * OpenSceneGraph Public License for more details. */ #include <OpenThreads/ScopedLock> #include <osg/ImageSequence> #include <osg/Notify> #include <osg/Camera> #include <osg/NodeVisitor> #include <osg/Texture2D> #include <math.h> using namespace osg; void ImageSequence::UpdateCallback::operator () (osg::StateAttribute* attr, osg::NodeVisitor* nv) { osg::Texture* texture = attr ? attr->asTexture() : 0; // osg::notify(osg::NOTICE)<<"ImageSequence::UpdateCallback::"<<texture<<std::endl; if (texture) { for(unsigned int i=0; i<texture->getNumImages(); ++i) { texture->getImage(i)->update(nv); } } } ImageSequence::ImageSequence() { _referenceTime = DBL_MAX; _timeMultiplier = 1.0; _mode = PRE_LOAD_ALL_IMAGES; _length = 1.0; _timePerImage = 1.0; _fileNamesIterator = _fileNames.end(); _fileNamesIteratorTime = 0.0; _imageIterator = _images.end(); _imageIteratorTime = 0.0; _seekTime = 0.0; _seekTimeSet = false; } ImageSequence::ImageSequence(const ImageSequence& is,const CopyOp& copyop): osg::ImageStream(is,copyop), _referenceTime(is._referenceTime), _timeMultiplier(is._timeMultiplier), _mode(is._mode), _length(is._length), _timePerImage(is._timePerImage) { _fileNamesIterator = _fileNames.end(); _fileNamesIteratorTime = 0.0; _imageIterator = _images.end(); _imageIteratorTime = 0.0; _seekTime = is._seekTime; _seekTimeSet = is._seekTimeSet; } int ImageSequence::compare(const Image& rhs) const { return ImageStream::compare(rhs); } void ImageSequence::seek(double time) { _seekTime = time; _seekTimeSet = true; } void ImageSequence::play() { _status=PLAYING; } void ImageSequence::pause() { _status=PAUSED; } void ImageSequence::rewind() { seek(0.0f); } void ImageSequence::setMode(Mode mode) { _mode = mode; } void ImageSequence::setLength(double length) { _length = length; computeTimePerImage(); } void ImageSequence::computeTimePerImage() { if (!_fileNames.empty()) _timePerImage = _length / double(_fileNames.size()); else if (!_images.empty()) _timePerImage = _length / double(_images.size()); else _timePerImage = _length; } void ImageSequence::addImageFile(const std::string& fileName) { OpenThreads::ScopedLock<OpenThreads::Mutex> lock(_mutex); _fileNames.push_back(fileName); computeTimePerImage(); if (_fileNamesIterator==_fileNames.end()) { _fileNamesIterator = _fileNames.begin(); _fileNamesIteratorTime = _referenceTime; } } void ImageSequence::addImage(osg::Image* image) { OpenThreads::ScopedLock<OpenThreads::Mutex> lock(_mutex); if (!_filesRequested.empty()) { // follows is a mechanism that ensures that requested images // get merged in the correct time order. if (_filesRequested.front().first != image->getFileName()) { for(FileNameImageList::iterator itr = _filesRequested.begin(); itr != _filesRequested.end(); ++itr) { if (itr->first == image->getFileName()) { osg::notify(osg::NOTICE)<<"inserting image into waiting stake : "<<image->getFileName()<<std::endl; itr->second = image; return; } } // osg::notify(osg::NOTICE)<<"image not expected : "<<image->getFileName()<<std::endl; _images.push_back(image); } else { // osg::notify(osg::NOTICE)<<"merging image in order expected : "<<image->getFileName()<<std::endl; _images.push_back(image); _filesRequested.pop_front(); FileNameImageList::iterator itr; for(itr = _filesRequested.begin(); itr != _filesRequested.end() && itr->second.valid(); ++itr) { // osg::notify(osg::NOTICE)<<" merging previously loaded, but out of order file : "<<itr->first<<std::endl; _images.push_back(itr->second); } _filesRequested.erase(_filesRequested.begin(), itr); } } else { _images.push_back(image); } computeTimePerImage(); if (data()==0) { _imageIterator = _images.begin(); _imageIteratorTime = 0.0; setImageToChild(_imageIterator->get()); } } void ImageSequence::setImageToChild(const osg::Image* image) { // osg::notify(osg::NOTICE)<<"setImageToChild("<<image<<")"<<std::endl; if (image==0) return; setImage(image->s(),image->t(),image->r(), image->getInternalTextureFormat(), image->getPixelFormat(),image->getDataType(), const_cast<unsigned char*>(image->data()), osg::Image::NO_DELETE, image->getPacking()); } void ImageSequence::update(osg::NodeVisitor* nv) { OpenThreads::ScopedLock<OpenThreads::Mutex> lock(_mutex); osg::NodeVisitor::ImageRequestHandler* irh = nv->getImageRequestHandler(); const osg::FrameStamp* fs = nv->getFrameStamp(); // osg::notify(osg::NOTICE)<<"ImageSequence::update("<<fs<<", "<<irh<<")"<<std::endl; if (_referenceTime == DBL_MAX) { _referenceTime = fs->getSimulationTime(); } bool looping = getLoopingMode()==LOOPING; double time = (fs->getSimulationTime() - _referenceTime)*_timeMultiplier; if (_seekTimeSet || _status==PAUSED || _status==INVALID) { time = _seekTime; _referenceTime = fs->getSimulationTime() - time/_timeMultiplier; } if (time>_length) { time -= floor(time/_length)*_length; } _seekTime = time; // _seekTimeSet = false; FileNames::iterator previous_fileNamesIterator = _fileNamesIterator; Images::iterator previous_imageIterator = _imageIterator; bool pruneOldImages = false; switch(_mode) { case(PRE_LOAD_ALL_IMAGES): { if (_fileNames.size()>_images.size()) { FileNames::iterator itr = _fileNames.begin(); for(unsigned int i=0;i<_images.size();++i) ++itr; for(; itr!=_fileNames.end(); ++itr) { osg::Image* image = irh->readImageFile(*itr); _images.push_back(image); } } irh = 0; break; } case(PAGE_AND_RETAIN_IMAGES): { break; } case(PAGE_AND_DISCARD_USED_IMAGES): { pruneOldImages = true; break; } } // osg::notify(osg::NOTICE)<<"time = "<<time<<std::endl; if (irh && _images.size()<_fileNames.size()) { double preLoadTime = time + osg::minimum(irh->getPreLoadTime()*_timeMultiplier, _length); if (preLoadTime>=_length) { // // Advance fileNameIterator to end and wrap around // for(; _fileNamesIterator != _fileNames.end(); ++_fileNamesIterator) { _fileNamesIteratorTime += _timePerImage; double effectTime = fs->getSimulationTime() + (preLoadTime - _fileNamesIteratorTime); _filesRequested.push_back(FileNameImagePair(*_fileNamesIterator,0)); irh->requestImageFile(*_fileNamesIterator, this, effectTime, fs); } preLoadTime -= _length; if (looping) { _fileNamesIterator = _fileNames.begin(); _fileNamesIteratorTime = 0.0; } } if (_fileNamesIterator!=_fileNames.end()) { // // Advance fileNameIterator to encmpass preLoadTime // //osg::notify(osg::NOTICE)<<" _fileNamesIteratorTime = "<<_fileNamesIteratorTime<<" "<<_timePerImage<<std::endl; while(preLoadTime > (_fileNamesIteratorTime + _timePerImage)) { _fileNamesIteratorTime += _timePerImage; //osg::notify(osg::NOTICE)<<" _fileNamesIteratorTime = "<<_fileNamesIteratorTime<<std::endl; //osg::notify(osg::NOTICE)<<" need to preLoad = "<<*_fileNamesIterator<<std::endl; ++_fileNamesIterator; if (previous_fileNamesIterator==_fileNamesIterator) break; if (_fileNamesIterator ==_fileNames.end()) { // return iterator to begining of set. if (looping) _fileNamesIterator = _fileNames.begin(); else break; } double effectTime = fs->getSimulationTime() + (preLoadTime - _fileNamesIteratorTime); _filesRequested.push_back(FileNameImagePair(*_fileNamesIterator,0)); irh->requestImageFile(*_fileNamesIterator, this, effectTime, fs); } } if (looping && _fileNamesIterator==_fileNames.end()) { _fileNamesIterator = _fileNames.begin(); _fileNamesIteratorTime = 0.0; } } { // // Advance imageIterator // if ((looping || _seekTimeSet) && time<_imageIteratorTime) { _imageIterator = _images.begin(); _imageIteratorTime = 0.0; } if (_imageIterator!=_images.end()) { // osg::notify(osg::NOTICE)<<" _imageIteratorTime = "<<_imageIteratorTime<<std::endl; while(time > (_imageIteratorTime + _timePerImage)) { _imageIteratorTime += _timePerImage; // osg::notify(osg::NOTICE)<<" _imageIteratorTime = "<<_imageIteratorTime<<std::endl; ++_imageIterator; if (_imageIterator ==_images.end()) { if (pruneOldImages) { _images.erase(previous_imageIterator, _imageIterator); previous_imageIterator = _images.begin(); } if (looping) { // return iterator to begining of set. _imageIterator = _images.begin(); } else { break; } } } } if (looping && _imageIterator==_images.end()) { _imageIterator = _images.begin(); } } if (_imageIterator!=_images.end() && previous_imageIterator != _imageIterator) { if (pruneOldImages) { _images.erase(previous_imageIterator, _imageIterator); } setImageToChild(_imageIterator->get()); } _seekTimeSet = false; } <commit_msg>Fixed typo<commit_after>/* -*-c++-*- OpenSceneGraph - Copyright (C) 1998-2006 Robert Osfield * * This library is open source and may be redistributed and/or modified under * the terms of the OpenSceneGraph Public License (OSGPL) version 0.0 or * (at your option) any later version. The full license is in LICENSE file * included with this distribution, and on the openscenegraph.org website. * * 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 * OpenSceneGraph Public License for more details. */ #include <OpenThreads/ScopedLock> #include <osg/ImageSequence> #include <osg/Notify> #include <osg/Camera> #include <osg/NodeVisitor> #include <osg/Texture2D> #include <math.h> using namespace osg; void ImageSequence::UpdateCallback::operator () (osg::StateAttribute* attr, osg::NodeVisitor* nv) { osg::Texture* texture = attr ? attr->asTexture() : 0; // osg::notify(osg::NOTICE)<<"ImageSequence::UpdateCallback::"<<texture<<std::endl; if (texture) { for(unsigned int i=0; i<texture->getNumImages(); ++i) { texture->getImage(i)->update(nv); } } } ImageSequence::ImageSequence() { _referenceTime = DBL_MAX; _timeMultiplier = 1.0; _mode = PRE_LOAD_ALL_IMAGES; _length = 1.0; _timePerImage = 1.0; _fileNamesIterator = _fileNames.end(); _fileNamesIteratorTime = 0.0; _imageIterator = _images.end(); _imageIteratorTime = 0.0; _seekTime = 0.0; _seekTimeSet = false; } ImageSequence::ImageSequence(const ImageSequence& is,const CopyOp& copyop): osg::ImageStream(is,copyop), _referenceTime(is._referenceTime), _timeMultiplier(is._timeMultiplier), _mode(is._mode), _length(is._length), _timePerImage(is._timePerImage) { _fileNamesIterator = _fileNames.end(); _fileNamesIteratorTime = 0.0; _imageIterator = _images.end(); _imageIteratorTime = 0.0; _seekTime = is._seekTime; _seekTimeSet = is._seekTimeSet; } int ImageSequence::compare(const Image& rhs) const { return ImageStream::compare(rhs); } void ImageSequence::seek(double time) { _seekTime = time; _seekTimeSet = true; } void ImageSequence::play() { _status=PLAYING; } void ImageSequence::pause() { _status=PAUSED; } void ImageSequence::rewind() { seek(0.0f); } void ImageSequence::setMode(Mode mode) { _mode = mode; } void ImageSequence::setLength(double length) { _length = length; computeTimePerImage(); } void ImageSequence::computeTimePerImage() { if (!_fileNames.empty()) _timePerImage = _length / double(_fileNames.size()); else if (!_images.empty()) _timePerImage = _length / double(_images.size()); else _timePerImage = _length; } void ImageSequence::addImageFile(const std::string& fileName) { OpenThreads::ScopedLock<OpenThreads::Mutex> lock(_mutex); _fileNames.push_back(fileName); computeTimePerImage(); if (_fileNamesIterator==_fileNames.end()) { _fileNamesIterator = _fileNames.begin(); _fileNamesIteratorTime = _referenceTime; } } void ImageSequence::addImage(osg::Image* image) { OpenThreads::ScopedLock<OpenThreads::Mutex> lock(_mutex); if (!_filesRequested.empty()) { // follows is a mechanism that ensures that requested images // get merged in the correct time order. if (_filesRequested.front().first != image->getFileName()) { for(FileNameImageList::iterator itr = _filesRequested.begin(); itr != _filesRequested.end(); ++itr) { if (itr->first == image->getFileName()) { osg::notify(osg::NOTICE)<<"inserting image into waiting queue : "<<image->getFileName()<<std::endl; itr->second = image; return; } } // osg::notify(osg::NOTICE)<<"image not expected : "<<image->getFileName()<<std::endl; _images.push_back(image); } else { // osg::notify(osg::NOTICE)<<"merging image in order expected : "<<image->getFileName()<<std::endl; _images.push_back(image); _filesRequested.pop_front(); FileNameImageList::iterator itr; for(itr = _filesRequested.begin(); itr != _filesRequested.end() && itr->second.valid(); ++itr) { // osg::notify(osg::NOTICE)<<" merging previously loaded, but out of order file : "<<itr->first<<std::endl; _images.push_back(itr->second); } _filesRequested.erase(_filesRequested.begin(), itr); } } else { _images.push_back(image); } computeTimePerImage(); if (data()==0) { _imageIterator = _images.begin(); _imageIteratorTime = 0.0; setImageToChild(_imageIterator->get()); } } void ImageSequence::setImageToChild(const osg::Image* image) { // osg::notify(osg::NOTICE)<<"setImageToChild("<<image<<")"<<std::endl; if (image==0) return; setImage(image->s(),image->t(),image->r(), image->getInternalTextureFormat(), image->getPixelFormat(),image->getDataType(), const_cast<unsigned char*>(image->data()), osg::Image::NO_DELETE, image->getPacking()); } void ImageSequence::update(osg::NodeVisitor* nv) { OpenThreads::ScopedLock<OpenThreads::Mutex> lock(_mutex); osg::NodeVisitor::ImageRequestHandler* irh = nv->getImageRequestHandler(); const osg::FrameStamp* fs = nv->getFrameStamp(); // osg::notify(osg::NOTICE)<<"ImageSequence::update("<<fs<<", "<<irh<<")"<<std::endl; if (_referenceTime == DBL_MAX) { _referenceTime = fs->getSimulationTime(); } bool looping = getLoopingMode()==LOOPING; double time = (fs->getSimulationTime() - _referenceTime)*_timeMultiplier; if (_seekTimeSet || _status==PAUSED || _status==INVALID) { time = _seekTime; _referenceTime = fs->getSimulationTime() - time/_timeMultiplier; } if (time>_length) { time -= floor(time/_length)*_length; } _seekTime = time; // _seekTimeSet = false; FileNames::iterator previous_fileNamesIterator = _fileNamesIterator; Images::iterator previous_imageIterator = _imageIterator; bool pruneOldImages = false; switch(_mode) { case(PRE_LOAD_ALL_IMAGES): { if (_fileNames.size()>_images.size()) { FileNames::iterator itr = _fileNames.begin(); for(unsigned int i=0;i<_images.size();++i) ++itr; for(; itr!=_fileNames.end(); ++itr) { osg::Image* image = irh->readImageFile(*itr); _images.push_back(image); } } irh = 0; break; } case(PAGE_AND_RETAIN_IMAGES): { break; } case(PAGE_AND_DISCARD_USED_IMAGES): { pruneOldImages = true; break; } } // osg::notify(osg::NOTICE)<<"time = "<<time<<std::endl; if (irh && _images.size()<_fileNames.size()) { double preLoadTime = time + osg::minimum(irh->getPreLoadTime()*_timeMultiplier, _length); if (preLoadTime>=_length) { // // Advance fileNameIterator to end and wrap around // for(; _fileNamesIterator != _fileNames.end(); ++_fileNamesIterator) { _fileNamesIteratorTime += _timePerImage; double effectTime = fs->getSimulationTime() + (preLoadTime - _fileNamesIteratorTime); _filesRequested.push_back(FileNameImagePair(*_fileNamesIterator,0)); irh->requestImageFile(*_fileNamesIterator, this, effectTime, fs); } preLoadTime -= _length; if (looping) { _fileNamesIterator = _fileNames.begin(); _fileNamesIteratorTime = 0.0; } } if (_fileNamesIterator!=_fileNames.end()) { // // Advance fileNameIterator to encmpass preLoadTime // //osg::notify(osg::NOTICE)<<" _fileNamesIteratorTime = "<<_fileNamesIteratorTime<<" "<<_timePerImage<<std::endl; while(preLoadTime > (_fileNamesIteratorTime + _timePerImage)) { _fileNamesIteratorTime += _timePerImage; //osg::notify(osg::NOTICE)<<" _fileNamesIteratorTime = "<<_fileNamesIteratorTime<<std::endl; //osg::notify(osg::NOTICE)<<" need to preLoad = "<<*_fileNamesIterator<<std::endl; ++_fileNamesIterator; if (previous_fileNamesIterator==_fileNamesIterator) break; if (_fileNamesIterator ==_fileNames.end()) { // return iterator to begining of set. if (looping) _fileNamesIterator = _fileNames.begin(); else break; } double effectTime = fs->getSimulationTime() + (preLoadTime - _fileNamesIteratorTime); _filesRequested.push_back(FileNameImagePair(*_fileNamesIterator,0)); irh->requestImageFile(*_fileNamesIterator, this, effectTime, fs); } } if (looping && _fileNamesIterator==_fileNames.end()) { _fileNamesIterator = _fileNames.begin(); _fileNamesIteratorTime = 0.0; } } { // // Advance imageIterator // if ((looping || _seekTimeSet) && time<_imageIteratorTime) { _imageIterator = _images.begin(); _imageIteratorTime = 0.0; } if (_imageIterator!=_images.end()) { // osg::notify(osg::NOTICE)<<" _imageIteratorTime = "<<_imageIteratorTime<<std::endl; while(time > (_imageIteratorTime + _timePerImage)) { _imageIteratorTime += _timePerImage; // osg::notify(osg::NOTICE)<<" _imageIteratorTime = "<<_imageIteratorTime<<std::endl; ++_imageIterator; if (_imageIterator ==_images.end()) { if (pruneOldImages) { _images.erase(previous_imageIterator, _imageIterator); previous_imageIterator = _images.begin(); } if (looping) { // return iterator to begining of set. _imageIterator = _images.begin(); } else { break; } } } } if (looping && _imageIterator==_images.end()) { _imageIterator = _images.begin(); } } if (_imageIterator!=_images.end() && previous_imageIterator != _imageIterator) { if (pruneOldImages) { _images.erase(previous_imageIterator, _imageIterator); } setImageToChild(_imageIterator->get()); } _seekTimeSet = false; } <|endoftext|>
<commit_before>class Solution { public: int minPartitions(string n) { char cur = '0'; for (auto& c : n) { if (c > cur) { cur = c; } if (cur == '9') break; } return int(cur-'0'); } }; <commit_msg>Partitioning Into Minimum Number Of Deci-Binary Numbers<commit_after>class Solution { public: int minPartitions(string n) { char cur = '0'; for (auto& c : n) { if (c > cur) { cur = c; } if (cur == '9') break; } return int(cur-'0'); } }; class Solution { public: int minPartitions(string n) { int ret = 0; for (const auto &c : n) { ret = std::max(ret, c-'0'); if (ret == 9) return ret; } return ret; } }; <|endoftext|>
<commit_before>#include "dynet/init.h" #include "dynet/aligned-mem-pool.h" #include "dynet/dynet.h" #include "dynet/weight-decay.h" #include "dynet/globals.h" #include <iostream> #include <random> #include <cmath> #if HAVE_CUDA #include "dynet/cuda.h" #include <device_launch_parameters.h> #endif using namespace std; namespace dynet { DynetParams::DynetParams() : random_seed(0), mem_descriptor("512"), weight_decay(0), autobatch(1), shared_parameters(false) #if HAVE_CUDA , ngpus_requested(false), ids_requested(false), requested_gpus(-1) #endif { #if HAVE_CUDA gpu_mask = std::vector<int>(MAX_GPUS, 0); #endif } DynetParams::~DynetParams() { } static void remove_args(int& argc, char**& argv, int& argi, int n) { for (int i = argi + n; i < argc; ++i) argv[i - n] = argv[i]; argc -= n; DYNET_ASSERT(argc >= 0, "remove_args less than 0"); } DynetParams extract_dynet_params(int& argc, char**& argv, bool shared_parameters) { DynetParams params; params.shared_parameters = shared_parameters; int argi = 1; #if HAVE_CUDA params.gpu_mask = std::vector<int>(MAX_GPUS, 0); #endif while (argi < argc) { string arg = argv[argi]; // Memory if (arg == "--dynet-mem" || arg == "--dynet_mem") { if ((argi + 1) > argc) { throw std::invalid_argument("[dynet] --dynet-mem expects an argument (the memory, in megabytes, to reserve)"); } else { params.mem_descriptor = argv[argi + 1]; remove_args(argc, argv, argi, 2); } } // Weight decay else if (arg == "--dynet-weight-decay" || arg == "--dynet_weight_decay") { if ((argi + 1) > argc) { throw std::invalid_argument("[dynet] --dynet-weight-decay requires an argument (the weight decay per update)"); } else { string a2 = argv[argi + 1]; istringstream d(a2); d >> params.weight_decay; remove_args(argc, argv, argi, 2); } } // Random seed else if (arg == "--dynet-seed" || arg == "--dynet_seed") { if ((argi + 1) > argc) { throw std::invalid_argument("[dynet] --dynet-seed expects an argument (the random number seed)"); } else { string a2 = argv[argi + 1]; istringstream c(a2); c >> params.random_seed; remove_args(argc, argv, argi, 2); } } // Memory else if (arg == "--dynet-autobatch" || arg == "--dynet_autobatch") { if ((argi + 1) > argc) { throw std::invalid_argument("[dynet] --dynet-autobatch expects an argument (0 for none 1 for on)"); } else { string a2 = argv[argi + 1]; istringstream c(a2); c >> params.autobatch; remove_args(argc, argv, argi, 2); } } #if HAVE_CUDA // Number of GPUs else if (arg == "--dynet_gpus" || arg == "--dynet-gpus") { if ((argi + 1) > argc) { throw std::invalid_argument("[dynet] --dynet-gpus expects an argument (number of GPUs to use)"); } else { if (params.ngpus_requested) throw std::invalid_argument("Multiple instances of --dynet-gpus"); params.ngpus_requested = true; string a2 = argv[argi + 1]; istringstream c(a2); c >> params.requested_gpus; remove_args(argc, argv, argi, 2); } } // GPU ids else if (arg == "--dynet_gpu_ids" || arg == "--dynet-gpu-ids") { if ((argi + 1) > argc) { throw std::invalid_argument("[dynet] --dynet-gpu-ids expects an argument (comma separated list of physical GPU ids to use)"); } else { string a2 = argv[argi + 1]; if (params.ids_requested) throw std::invalid_argument("Multiple instances of --dynet-gpu-ids"); params.ids_requested = true; if (a2.size() % 2 != 1) { ostringstream oss; oss << "Bad argument to --dynet-gpu-ids: " << a2; throw std::invalid_argument(oss.str()); } for (unsigned i = 0; i < a2.size(); ++i) { if ((i % 2 == 0 && (a2[i] < '0' || a2[i] > '9')) || (i % 2 == 1 && a2[i] != ',')) { ostringstream oss; oss << "Bad argument to --dynet-gpu-ids: " << a2; throw std::invalid_argument(oss.str()); } if (i % 2 == 0) { int gpu_id = a2[i] - '0'; if (gpu_id >= MAX_GPUS) { throw std::runtime_error("DyNet hard limit on maximum number of GPUs (MAX_GPUS) exceeded. If you need more, modify the code to raise this hard limit."); } params.gpu_mask[gpu_id]++; params.requested_gpus++; if (params.gpu_mask[gpu_id] != 1) { ostringstream oss; oss << "Bad argument to --dynet-gpu-ids: " << a2; throw std::invalid_argument(oss.str()); } } } remove_args(argc, argv, argi, 2); } } #endif // Go to next argument else { argi++; } } #if HAVE_CUDA // Check for conflict between the two ways of requesting GPUs if (params.ids_requested && params.ngpus_requested) throw std::invalid_argument("Use only --dynet_gpus or --dynet_gpu_ids, not both\n"); #endif return params; } void initialize(DynetParams& params) { if (default_device != nullptr) { cerr << "WARNING: Attempting to initialize dynet twice. Ignoring duplicate initialization." << endl; return; } // initialize CUDA vector<Device*> gpudevices; #if HAVE_CUDA cerr << "[dynet] initializing CUDA\n"; gpudevices = initialize_gpu(params); #endif // Set random seed if (params.random_seed == 0) { random_device rd; params.random_seed = rd(); } cerr << "[dynet] random seed: " << params.random_seed << endl; rndeng = new mt19937(params.random_seed); // Set weight decay rate if (params.weight_decay < 0 || params.weight_decay >= 1) throw std::invalid_argument("[dynet] weight decay parameter must be between 0 and 1 (probably very small like 1e-6)\n"); weight_decay_lambda = params.weight_decay; // Set autobatch autobatch_flag = params.autobatch; // Allocate memory cerr << "[dynet] allocating memory: " << params.mem_descriptor << "MB\n"; // TODO: Once multi-device support is added, we will potentially allocate both CPU // and GPU, not either-or int default_index = 0; if (gpudevices.size() > 0) { for (auto gpu : gpudevices) devices.push_back(gpu); } else { devices.push_back(new Device_CPU(devices.size(), params.mem_descriptor, params.shared_parameters)); } default_device = devices[default_index]; // TODO these should be accessed through the relevant device and removed here kSCALAR_MINUSONE = default_device->kSCALAR_MINUSONE; kSCALAR_ONE = default_device->kSCALAR_ONE; kSCALAR_ZERO = default_device->kSCALAR_ZERO; cerr << "[dynet] memory allocation done.\n"; } void initialize(int& argc, char**& argv, bool shared_parameters) { DynetParams params = extract_dynet_params(argc, argv, shared_parameters); initialize(params); } void cleanup() { delete rndeng; // TODO: Devices cannot be deleted at the moment // for(Device* device : devices) delete device; devices.clear(); default_device = nullptr; } } // namespace dynet <commit_msg>Turned autobatching off by default for now<commit_after>#include "dynet/init.h" #include "dynet/aligned-mem-pool.h" #include "dynet/dynet.h" #include "dynet/weight-decay.h" #include "dynet/globals.h" #include <iostream> #include <random> #include <cmath> #if HAVE_CUDA #include "dynet/cuda.h" #include <device_launch_parameters.h> #endif using namespace std; namespace dynet { DynetParams::DynetParams() : random_seed(0), mem_descriptor("512"), weight_decay(0), autobatch(0), shared_parameters(false) #if HAVE_CUDA , ngpus_requested(false), ids_requested(false), requested_gpus(-1) #endif { #if HAVE_CUDA gpu_mask = std::vector<int>(MAX_GPUS, 0); #endif } DynetParams::~DynetParams() { } static void remove_args(int& argc, char**& argv, int& argi, int n) { for (int i = argi + n; i < argc; ++i) argv[i - n] = argv[i]; argc -= n; DYNET_ASSERT(argc >= 0, "remove_args less than 0"); } DynetParams extract_dynet_params(int& argc, char**& argv, bool shared_parameters) { DynetParams params; params.shared_parameters = shared_parameters; int argi = 1; #if HAVE_CUDA params.gpu_mask = std::vector<int>(MAX_GPUS, 0); #endif while (argi < argc) { string arg = argv[argi]; // Memory if (arg == "--dynet-mem" || arg == "--dynet_mem") { if ((argi + 1) > argc) { throw std::invalid_argument("[dynet] --dynet-mem expects an argument (the memory, in megabytes, to reserve)"); } else { params.mem_descriptor = argv[argi + 1]; remove_args(argc, argv, argi, 2); } } // Weight decay else if (arg == "--dynet-weight-decay" || arg == "--dynet_weight_decay") { if ((argi + 1) > argc) { throw std::invalid_argument("[dynet] --dynet-weight-decay requires an argument (the weight decay per update)"); } else { string a2 = argv[argi + 1]; istringstream d(a2); d >> params.weight_decay; remove_args(argc, argv, argi, 2); } } // Random seed else if (arg == "--dynet-seed" || arg == "--dynet_seed") { if ((argi + 1) > argc) { throw std::invalid_argument("[dynet] --dynet-seed expects an argument (the random number seed)"); } else { string a2 = argv[argi + 1]; istringstream c(a2); c >> params.random_seed; remove_args(argc, argv, argi, 2); } } // Memory else if (arg == "--dynet-autobatch" || arg == "--dynet_autobatch") { if ((argi + 1) > argc) { throw std::invalid_argument("[dynet] --dynet-autobatch expects an argument (0 for none 1 for on)"); } else { string a2 = argv[argi + 1]; istringstream c(a2); c >> params.autobatch; remove_args(argc, argv, argi, 2); } } #if HAVE_CUDA // Number of GPUs else if (arg == "--dynet_gpus" || arg == "--dynet-gpus") { if ((argi + 1) > argc) { throw std::invalid_argument("[dynet] --dynet-gpus expects an argument (number of GPUs to use)"); } else { if (params.ngpus_requested) throw std::invalid_argument("Multiple instances of --dynet-gpus"); params.ngpus_requested = true; string a2 = argv[argi + 1]; istringstream c(a2); c >> params.requested_gpus; remove_args(argc, argv, argi, 2); } } // GPU ids else if (arg == "--dynet_gpu_ids" || arg == "--dynet-gpu-ids") { if ((argi + 1) > argc) { throw std::invalid_argument("[dynet] --dynet-gpu-ids expects an argument (comma separated list of physical GPU ids to use)"); } else { string a2 = argv[argi + 1]; if (params.ids_requested) throw std::invalid_argument("Multiple instances of --dynet-gpu-ids"); params.ids_requested = true; if (a2.size() % 2 != 1) { ostringstream oss; oss << "Bad argument to --dynet-gpu-ids: " << a2; throw std::invalid_argument(oss.str()); } for (unsigned i = 0; i < a2.size(); ++i) { if ((i % 2 == 0 && (a2[i] < '0' || a2[i] > '9')) || (i % 2 == 1 && a2[i] != ',')) { ostringstream oss; oss << "Bad argument to --dynet-gpu-ids: " << a2; throw std::invalid_argument(oss.str()); } if (i % 2 == 0) { int gpu_id = a2[i] - '0'; if (gpu_id >= MAX_GPUS) { throw std::runtime_error("DyNet hard limit on maximum number of GPUs (MAX_GPUS) exceeded. If you need more, modify the code to raise this hard limit."); } params.gpu_mask[gpu_id]++; params.requested_gpus++; if (params.gpu_mask[gpu_id] != 1) { ostringstream oss; oss << "Bad argument to --dynet-gpu-ids: " << a2; throw std::invalid_argument(oss.str()); } } } remove_args(argc, argv, argi, 2); } } #endif // Go to next argument else { argi++; } } #if HAVE_CUDA // Check for conflict between the two ways of requesting GPUs if (params.ids_requested && params.ngpus_requested) throw std::invalid_argument("Use only --dynet_gpus or --dynet_gpu_ids, not both\n"); #endif return params; } void initialize(DynetParams& params) { if (default_device != nullptr) { cerr << "WARNING: Attempting to initialize dynet twice. Ignoring duplicate initialization." << endl; return; } // initialize CUDA vector<Device*> gpudevices; #if HAVE_CUDA cerr << "[dynet] initializing CUDA\n"; gpudevices = initialize_gpu(params); #endif // Set random seed if (params.random_seed == 0) { random_device rd; params.random_seed = rd(); } cerr << "[dynet] random seed: " << params.random_seed << endl; rndeng = new mt19937(params.random_seed); // Set weight decay rate if (params.weight_decay < 0 || params.weight_decay >= 1) throw std::invalid_argument("[dynet] weight decay parameter must be between 0 and 1 (probably very small like 1e-6)\n"); weight_decay_lambda = params.weight_decay; // Set autobatch autobatch_flag = params.autobatch; // Allocate memory cerr << "[dynet] allocating memory: " << params.mem_descriptor << "MB\n"; // TODO: Once multi-device support is added, we will potentially allocate both CPU // and GPU, not either-or int default_index = 0; if (gpudevices.size() > 0) { for (auto gpu : gpudevices) devices.push_back(gpu); } else { devices.push_back(new Device_CPU(devices.size(), params.mem_descriptor, params.shared_parameters)); } default_device = devices[default_index]; // TODO these should be accessed through the relevant device and removed here kSCALAR_MINUSONE = default_device->kSCALAR_MINUSONE; kSCALAR_ONE = default_device->kSCALAR_ONE; kSCALAR_ZERO = default_device->kSCALAR_ZERO; cerr << "[dynet] memory allocation done.\n"; } void initialize(int& argc, char**& argv, bool shared_parameters) { DynetParams params = extract_dynet_params(argc, argv, shared_parameters); initialize(params); } void cleanup() { delete rndeng; // TODO: Devices cannot be deleted at the moment // for(Device* device : devices) delete device; devices.clear(); default_device = nullptr; } } // namespace dynet <|endoftext|>
<commit_before>/* * Copyright 2015 Milian Wolff <mail@milianw.de> * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU Library General Public License as * published by the Free Software Foundation; either version 2 of the * License, or (at your option) any later version. * * This 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 "parser.h" #include <ThreadWeaver/ThreadWeaver> #include <KFormat> #include <KLocalizedString> #include <QTextStream> #include <QDebug> #include "../accumulatedtracedata.h" #include "flamegraph.h" #include <vector> using namespace std; namespace { // TODO: use QString directly struct StringCache { StringCache() { } QString func(const InstructionPointer& ip) const { if (ip.functionIndex) { // TODO: support removal of template arguments return stringify(ip.functionIndex); } else { return static_cast<QString>(QLatin1String("0x") + QString::number(ip.instructionPointer, 16)); } } QString file(const InstructionPointer& ip) const { if (ip.fileIndex) { return stringify(ip.fileIndex); } else { return {}; } } QString module(const InstructionPointer& ip) const { return stringify(ip.moduleIndex); } QString stringify(const StringIndex index) const { if (!index || index.index > m_strings.size()) { return {}; } else { return m_strings.at(index.index - 1); } } LocationData location(const InstructionPointer& ip) const { return {func(ip), file(ip), module(ip), ip.line}; } void update(const vector<string>& strings) { transform(strings.begin() + m_strings.size(), strings.end(), back_inserter(m_strings), [] (const string& str) { return QString::fromStdString(str); }); } vector<QString> m_strings; }; struct ChartMergeData { QString function; quint64 leaked; quint64 allocations; quint64 allocated; bool operator<(const QString& rhs) const { return function < rhs; } }; struct ParserData final : public AccumulatedTraceData { ParserData() { chartData.rows.push_back({}); // index 0 indicates the total row chartLeakedLabelIds.insert(i18n("total"), 0); chartAllocatedLabelIds.insert(i18n("total"), 0); chartAllocationsLabelIds.insert(i18n("total"), 0); } void handleTimeStamp(uint64_t /*newStamp*/, uint64_t oldStamp) { stringCache.update(strings); maxLeakedSinceLastTimeStamp = max(maxLeakedSinceLastTimeStamp, leaked); ChartRows data; data.timeStamp = oldStamp; // total data data.leaked.insert(0, maxLeakedSinceLastTimeStamp); data.allocations.insert(0, totalAllocations); data.allocated.insert(0, totalAllocated); // merge data for top 10 functions in this timestamp vector<ChartMergeData> mergedData; for (const auto& allocation : allocations) { const auto function = stringCache.func(findIp(findTrace(allocation.traceIndex).ipIndex)); auto it = lower_bound(mergedData.begin(), mergedData.end(), function); if (it != mergedData.end() && it->function == function) { it->allocated += allocation.allocated; it->allocations += allocation.allocations; it->leaked += allocation.leaked; } else { it = mergedData.insert(it, {function, allocation.leaked, allocation.allocations, allocation.allocated}); } } // TODO: deduplicate code sort(mergedData.begin(), mergedData.end(), [] (const ChartMergeData& left, const ChartMergeData& right) { return left.leaked > right.leaked; }); for (size_t i = 0; i < min(size_t(10), mergedData.size()); ++i) { const auto& alloc = mergedData[i]; if (!alloc.leaked) { break; } auto& id = chartLeakedLabelIds[alloc.function]; if (!id) { id = chartLeakedLabelIds.size() - 1; } data.leaked.insert(id, alloc.leaked); } sort(mergedData.begin(), mergedData.end(), [] (const ChartMergeData& left, const ChartMergeData& right) { return left.allocations > right.allocations; }); for (size_t i = 0; i < min(size_t(10), mergedData.size()); ++i) { const auto& alloc = mergedData[i]; if (!alloc.allocations) { break; } auto& id = chartAllocationsLabelIds[alloc.function]; if (!id) { id = chartAllocationsLabelIds.size() - 1; } data.allocations.insert(id, alloc.allocations); } sort(mergedData.begin(), mergedData.end(), [] (const ChartMergeData& left, const ChartMergeData& right) { return left.allocated > right.allocated; }); for (size_t i = 0; i < min(size_t(10), mergedData.size()); ++i) { const auto& alloc = mergedData[i]; if (!alloc.allocated) { break; } auto& id = chartAllocatedLabelIds[alloc.function]; if (!id) { id = chartAllocatedLabelIds.size() - 1; } data.allocated.insert(id, alloc.allocated); } chartData.rows.push_back(data); maxLeakedSinceLastTimeStamp = 0; } void handleAllocation() { maxLeakedSinceLastTimeStamp = max(maxLeakedSinceLastTimeStamp, leaked); } void handleDebuggee(const char* command) { debuggee = command; } string debuggee; ChartData chartData; QHash<QString, int> chartLeakedLabelIds; QHash<QString, int> chartAllocationsLabelIds; QHash<QString, int> chartAllocatedLabelIds; uint64_t maxLeakedSinceLastTimeStamp = 0; StringCache stringCache; }; QString generateSummary(const ParserData& data) { QString ret; KFormat format; QTextStream stream(&ret); const double totalTimeS = 0.001 * data.totalTime; stream << "<qt>" << i18n("<strong>debuggee</strong>: <code>%1</code>", QString::fromStdString(data.debuggee)) << "<br/>" // xgettext:no-c-format << i18n("<strong>total runtime</strong>: %1s", totalTimeS) << "<br/>" << i18n("<strong>bytes allocated in total</strong> (ignoring deallocations): %1 (%2/s)", format.formatByteSize(data.totalAllocated, 2), format.formatByteSize(data.totalAllocated / totalTimeS)) << "<br/>" << i18n("<strong>calls to allocation functions</strong>: %1 (%2/s)", data.totalAllocations, quint64(data.totalAllocations / totalTimeS)) << "<br/>" << i18n("<strong>peak heap memory consumption</strong>: %1", format.formatByteSize(data.peak)) << "<br/>" << i18n("<strong>total memory leaked</strong>: %1", format.formatByteSize(data.leaked)) << "<br/>"; stream << "</qt>"; return ret; } void setParents(QVector<RowData>& children, const RowData* parent) { for (auto& row: children) { row.parent = parent; setParents(row.children, &row); } } QVector<RowData> mergeAllocations(const ParserData& data) { QVector<RowData> topRows; // merge allocations, leave parent pointers invalid (their location may change) for (const auto& allocation : data.allocations) { auto traceIndex = allocation.traceIndex; auto rows = &topRows; while (traceIndex) { const auto& trace = data.findTrace(traceIndex); const auto& ip = data.findIp(trace.ipIndex); // TODO: only store the IpIndex and use that auto location = data.stringCache.location(ip); auto it = lower_bound(rows->begin(), rows->end(), location); if (it != rows->end() && it->location == location) { it->allocated += allocation.allocated; it->allocations += allocation.allocations; it->leaked += allocation.leaked; it->peak += allocation.peak; } else { it = rows->insert(it, {allocation.allocations, allocation.peak, allocation.leaked, allocation.allocated, location, nullptr, {}}); } if (data.isStopIndex(ip.functionIndex)) { break; } traceIndex = trace.parentIndex; rows = &it->children; } } // now set the parents, the data is constant from here on setParents(topRows, nullptr); return topRows; } RowData* findByLocation(const RowData& row, QVector<RowData>* data) { for (int i = 0; i < data->size(); ++i) { if (data->at(i).location == row.location) { return data->data() + i; } } return nullptr; } void buildTopDown(const QVector<RowData>& bottomUpData, QVector<RowData>* topDownData) { foreach (const auto& row, bottomUpData) { if (row.children.isEmpty()) { // leaf node found, bubble up the parent chain to build a top-down tree auto node = &row; auto stack = topDownData; while (node) { auto data = findByLocation(*node, stack); if (!data) { // create an empty top-down item for this bottom-up node *stack << RowData{0, 0, 0, 0, node->location, nullptr, {}}; data = &stack->back(); } // always use the leaf node's cost and propagate that one up the chain // otherwise we'd count the cost of some nodes multiple times data->allocations += row.allocations; data->peak += row.peak; data->leaked += row.leaked; data->allocated += row.allocated; stack = &data->children; node = node->parent; } } else { // recurse to find a leaf buildTopDown(row.children, topDownData); } } } QVector<RowData> toTopDownData(const QVector<RowData>& bottomUpData) { QVector<RowData> topRows; buildTopDown(bottomUpData, &topRows); // now set the parents, the data is constant from here on setParents(topRows, nullptr); return topRows; } } Parser::Parser(QObject* parent) : QObject(parent) {} Parser::~Parser() = default; void Parser::parse(const QString& path) { using namespace ThreadWeaver; stream() << make_job([=]() { ParserData data; data.read(path.toStdString()); // TODO: deduplicate data.chartData.leakedLabels.reserve(data.chartLeakedLabelIds.size()); for (auto it = data.chartLeakedLabelIds.constBegin(); it != data.chartLeakedLabelIds.constEnd(); ++it) { data.chartData.leakedLabels.insert(it.value(), it.key()); } data.chartData.allocatedLabels.reserve(data.chartAllocatedLabelIds.size()); for (auto it = data.chartAllocatedLabelIds.constBegin(); it != data.chartAllocatedLabelIds.constEnd(); ++it) { data.chartData.allocatedLabels.insert(it.value(), it.key()); } data.chartData.allocationsLabels.reserve(data.chartAllocationsLabelIds.size()); for (auto it = data.chartAllocationsLabelIds.constBegin(); it != data.chartAllocationsLabelIds.constEnd(); ++it) { data.chartData.allocationsLabels.insert(it.value(), it.key()); } emit summaryAvailable(generateSummary(data)); const auto mergedAllocations = mergeAllocations(data); emit bottomUpDataAvailable(mergedAllocations); emit chartDataAvailable(data.chartData); const auto topDownData = toTopDownData(mergedAllocations); emit topDownDataAvailable(topDownData); emit flameGraphDataAvailable(FlameGraph::parseData(topDownData)); emit finished(); }); } <commit_msg>Deduplicate code<commit_after>/* * Copyright 2015 Milian Wolff <mail@milianw.de> * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU Library General Public License as * published by the Free Software Foundation; either version 2 of the * License, or (at your option) any later version. * * This 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 "parser.h" #include <ThreadWeaver/ThreadWeaver> #include <KFormat> #include <KLocalizedString> #include <QTextStream> #include <QDebug> #include "../accumulatedtracedata.h" #include "flamegraph.h" #include <vector> using namespace std; namespace { // TODO: use QString directly struct StringCache { StringCache() { } QString func(const InstructionPointer& ip) const { if (ip.functionIndex) { // TODO: support removal of template arguments return stringify(ip.functionIndex); } else { return static_cast<QString>(QLatin1String("0x") + QString::number(ip.instructionPointer, 16)); } } QString file(const InstructionPointer& ip) const { if (ip.fileIndex) { return stringify(ip.fileIndex); } else { return {}; } } QString module(const InstructionPointer& ip) const { return stringify(ip.moduleIndex); } QString stringify(const StringIndex index) const { if (!index || index.index > m_strings.size()) { return {}; } else { return m_strings.at(index.index - 1); } } LocationData location(const InstructionPointer& ip) const { return {func(ip), file(ip), module(ip), ip.line}; } void update(const vector<string>& strings) { transform(strings.begin() + m_strings.size(), strings.end(), back_inserter(m_strings), [] (const string& str) { return QString::fromStdString(str); }); } vector<QString> m_strings; }; struct ChartMergeData { QString function; quint64 leaked; quint64 allocations; quint64 allocated; bool operator<(const QString& rhs) const { return function < rhs; } }; struct ParserData final : public AccumulatedTraceData { ParserData() { chartData.rows.push_back({}); // index 0 indicates the total row chartLeakedLabelIds.insert(i18n("total"), 0); chartAllocatedLabelIds.insert(i18n("total"), 0); chartAllocationsLabelIds.insert(i18n("total"), 0); } void handleTimeStamp(uint64_t /*newStamp*/, uint64_t oldStamp) { stringCache.update(strings); maxLeakedSinceLastTimeStamp = max(maxLeakedSinceLastTimeStamp, leaked); ChartRows data; data.timeStamp = oldStamp; // total data data.leaked.insert(0, maxLeakedSinceLastTimeStamp); data.allocations.insert(0, totalAllocations); data.allocated.insert(0, totalAllocated); // merge data for top 10 functions in this timestamp vector<ChartMergeData> mergedData; for (const auto& allocation : allocations) { const auto function = stringCache.func(findIp(findTrace(allocation.traceIndex).ipIndex)); auto it = lower_bound(mergedData.begin(), mergedData.end(), function); if (it != mergedData.end() && it->function == function) { it->allocated += allocation.allocated; it->allocations += allocation.allocations; it->leaked += allocation.leaked; } else { it = mergedData.insert(it, {function, allocation.leaked, allocation.allocations, allocation.allocated}); } } auto addChartData = [&] (quint64 ChartMergeData::* member, QHash<QString, int>* ids, QHash<int, quint64>* cost) { sort(mergedData.begin(), mergedData.end(), [=] (const ChartMergeData& left, const ChartMergeData& right) { return left.*member > right.*member; }); for (size_t i = 0; i < min(size_t(10), mergedData.size()); ++i) { const auto& alloc = mergedData[i]; if (!(alloc.*member)) { break; } auto& id = (*ids)[alloc.function]; if (!id) { id = ids->size() - 1; } cost->insert(id, alloc.leaked); } }; addChartData(&ChartMergeData::leaked, &chartLeakedLabelIds, &data.leaked); addChartData(&ChartMergeData::allocated, &chartAllocatedLabelIds, &data.allocated); addChartData(&ChartMergeData::allocations, &chartAllocationsLabelIds, &data.allocations); chartData.rows.push_back(data); maxLeakedSinceLastTimeStamp = 0; } void handleAllocation() { maxLeakedSinceLastTimeStamp = max(maxLeakedSinceLastTimeStamp, leaked); } void handleDebuggee(const char* command) { debuggee = command; } string debuggee; ChartData chartData; QHash<QString, int> chartLeakedLabelIds; QHash<QString, int> chartAllocationsLabelIds; QHash<QString, int> chartAllocatedLabelIds; uint64_t maxLeakedSinceLastTimeStamp = 0; StringCache stringCache; }; QString generateSummary(const ParserData& data) { QString ret; KFormat format; QTextStream stream(&ret); const double totalTimeS = 0.001 * data.totalTime; stream << "<qt>" << i18n("<strong>debuggee</strong>: <code>%1</code>", QString::fromStdString(data.debuggee)) << "<br/>" // xgettext:no-c-format << i18n("<strong>total runtime</strong>: %1s", totalTimeS) << "<br/>" << i18n("<strong>bytes allocated in total</strong> (ignoring deallocations): %1 (%2/s)", format.formatByteSize(data.totalAllocated, 2), format.formatByteSize(data.totalAllocated / totalTimeS)) << "<br/>" << i18n("<strong>calls to allocation functions</strong>: %1 (%2/s)", data.totalAllocations, quint64(data.totalAllocations / totalTimeS)) << "<br/>" << i18n("<strong>peak heap memory consumption</strong>: %1", format.formatByteSize(data.peak)) << "<br/>" << i18n("<strong>total memory leaked</strong>: %1", format.formatByteSize(data.leaked)) << "<br/>"; stream << "</qt>"; return ret; } void setParents(QVector<RowData>& children, const RowData* parent) { for (auto& row: children) { row.parent = parent; setParents(row.children, &row); } } QVector<RowData> mergeAllocations(const ParserData& data) { QVector<RowData> topRows; // merge allocations, leave parent pointers invalid (their location may change) for (const auto& allocation : data.allocations) { auto traceIndex = allocation.traceIndex; auto rows = &topRows; while (traceIndex) { const auto& trace = data.findTrace(traceIndex); const auto& ip = data.findIp(trace.ipIndex); // TODO: only store the IpIndex and use that auto location = data.stringCache.location(ip); auto it = lower_bound(rows->begin(), rows->end(), location); if (it != rows->end() && it->location == location) { it->allocated += allocation.allocated; it->allocations += allocation.allocations; it->leaked += allocation.leaked; it->peak += allocation.peak; } else { it = rows->insert(it, {allocation.allocations, allocation.peak, allocation.leaked, allocation.allocated, location, nullptr, {}}); } if (data.isStopIndex(ip.functionIndex)) { break; } traceIndex = trace.parentIndex; rows = &it->children; } } // now set the parents, the data is constant from here on setParents(topRows, nullptr); return topRows; } RowData* findByLocation(const RowData& row, QVector<RowData>* data) { for (int i = 0; i < data->size(); ++i) { if (data->at(i).location == row.location) { return data->data() + i; } } return nullptr; } void buildTopDown(const QVector<RowData>& bottomUpData, QVector<RowData>* topDownData) { foreach (const auto& row, bottomUpData) { if (row.children.isEmpty()) { // leaf node found, bubble up the parent chain to build a top-down tree auto node = &row; auto stack = topDownData; while (node) { auto data = findByLocation(*node, stack); if (!data) { // create an empty top-down item for this bottom-up node *stack << RowData{0, 0, 0, 0, node->location, nullptr, {}}; data = &stack->back(); } // always use the leaf node's cost and propagate that one up the chain // otherwise we'd count the cost of some nodes multiple times data->allocations += row.allocations; data->peak += row.peak; data->leaked += row.leaked; data->allocated += row.allocated; stack = &data->children; node = node->parent; } } else { // recurse to find a leaf buildTopDown(row.children, topDownData); } } } QVector<RowData> toTopDownData(const QVector<RowData>& bottomUpData) { QVector<RowData> topRows; buildTopDown(bottomUpData, &topRows); // now set the parents, the data is constant from here on setParents(topRows, nullptr); return topRows; } void convertLabels(const QHash<QString, int>& input, QHash<int, QString>* output) { output->reserve(input.size()); for (auto it = input.constBegin(); it != input.constEnd(); ++it) { output->insert(it.value(), it.key()); } } } Parser::Parser(QObject* parent) : QObject(parent) {} Parser::~Parser() = default; void Parser::parse(const QString& path) { using namespace ThreadWeaver; stream() << make_job([=]() { ParserData data; data.read(path.toStdString()); convertLabels(data.chartLeakedLabelIds, &data.chartData.leakedLabels); convertLabels(data.chartAllocatedLabelIds, &data.chartData.allocatedLabels); convertLabels(data.chartAllocationsLabelIds, &data.chartData.allocationsLabels); emit summaryAvailable(generateSummary(data)); const auto mergedAllocations = mergeAllocations(data); emit bottomUpDataAvailable(mergedAllocations); emit chartDataAvailable(data.chartData); const auto topDownData = toTopDownData(mergedAllocations); emit topDownDataAvailable(topDownData); emit flameGraphDataAvailable(FlameGraph::parseData(topDownData)); emit finished(); }); } <|endoftext|>
<commit_before>/* * Copyright(c) Sophist Solutions, Inc. 1990-2020. All rights reserved */ #include "Stroika/Frameworks/StroikaPreComp.h" #include <iostream> #include "Stroika/Foundation/Characters/ToString.h" #include "Stroika/Foundation/DataExchange/Archive/Reader.h" #include "Stroika/Foundation/Debug/Trace.h" #include "Stroika/Foundation/Execution/CommandLine.h" #if qHasFeature_LZMA #include "Stroika/Foundation/DataExchange/Archive/7z/Reader.h" #endif #if qHasFeature_ZLib #include "Stroika/Foundation/DataExchange/Archive/Zip/Reader.h" #endif #include "Stroika/Foundation/IO/FileSystem/Directory.h" #include "Stroika/Foundation/IO/FileSystem/FileInputStream.h" #include "Stroika/Foundation/IO/FileSystem/FileOutputStream.h" #include "Stroika/Foundation/IO/FileSystem/PathName.h" #include "Stroika/Foundation/Streams/MemoryStream.h" #include "Stroika/Foundation/Streams/TextReader.h" using namespace std; using namespace Stroika::Foundation; #if qHasFeature_LZMA || qHasFeature_ZLib using namespace Stroika::Foundation::DataExchange; #endif using namespace Stroika::Foundation::Streams; using Characters::String; using Containers::Sequence; using Memory::BLOB; namespace { struct Options_ { enum class Operation { eList, eExtract, eCreate, eUpdate }; Operation fOperation; filesystem::path fArchiveFileName; optional<filesystem::path> fOutputDirectory; // applies only if extract optional<Sequence<String>> fFiles2Add; optional<bool> fNoFailOnMissingLibrary; // for regression tests }; void Usage_ () { cerr << "Usage: ArchiveUtility (--help | -h) | (--no-fail-on-missing-library) | ((--list | --create | --extract |--update) ARCHIVENAME [--outputDirectory D] [FILES])" << endl; cerr << " --help prints this help" << endl; cerr << " -h prints this help" << endl; cerr << " --no-fail-on-missing-library just warns when we fail because of missing library" << endl; cerr << " --list prints all the files in the argument archive" << endl; cerr << " --create creates the argument ARHCIVE and adds the argument FILES to it" << endl; cerr << " --extract extracts all the files from the argument ARHCIVE and to the output directory specified by --ouptutDirectory (defaulting to .)" << endl; cerr << " --update adds to the argument ARHCIVE and adds the argument FILES to it" << endl; cerr << " ARCHIVENAME can be the single character - to designate stdin" << endl; // NYI } // Emits errors to stderr, and Usage, etc, if needed, and not Optional<> has_value() optional<Options_> ParseOptions_ (int argc, const char* argv[]) { Options_ result{}; Sequence<String> args = Execution::ParseCommandLine (argc, argv); optional<Options_::Operation> operation; optional<String> archiveName; optional<bool> noFailOnMissingLibrary; for (auto argi = args.begin (); argi != args.end (); ++argi) { if (argi == args.begin ()) { continue; // skip argv[0] - command name } if (Execution::MatchesCommandLineArgument (*argi, L"h") or Execution::MatchesCommandLineArgument (*argi, L"help")) { Usage_ (); return optional<Options_>{}; } else if (Execution::MatchesCommandLineArgument (*argi, L"no-fail-on-missing-library")) { noFailOnMissingLibrary = true; } else if (Execution::MatchesCommandLineArgument (*argi, L"list")) { operation = Options_::Operation::eList; } else if (Execution::MatchesCommandLineArgument (*argi, L"create")) { operation = Options_::Operation::eCreate; } else if (Execution::MatchesCommandLineArgument (*argi, L"extract")) { operation = Options_::Operation::eExtract; } else if (Execution::MatchesCommandLineArgument (*argi, L"update")) { operation = Options_::Operation::eUpdate; } else if (not archiveName.has_value ()) { archiveName = *argi; } // else more cases todo } if (not archiveName) { cerr << "Missing name of archive" << endl; Usage_ (); return optional<Options_>{}; } if (not operation) { cerr << "Missing operation" << endl; Usage_ (); return optional<Options_>{}; } result.fOperation = *operation; result.fArchiveFileName = IO::FileSystem::ToPath (*archiveName); // @todo add more.. - files etc result.fNoFailOnMissingLibrary = noFailOnMissingLibrary; return result; } } namespace { DataExchange::Archive::Reader OpenArchive_ (const filesystem::path& archiveName) { // @todo - must support other formats, have a registry, and autodetect #if qHasFeature_LZMA if (IO::FileSystem::FromPath (archiveName).EndsWith (L".7z", Characters::CompareOptions::eCaseInsensitive)) { return move (Archive::_7z::Reader{IO::FileSystem::FileInputStream::New (archiveName)}); } #endif #if qHasFeature_ZLib if (IO::FileSystem::FromPath (archiveName).EndsWith (L".zip", Characters::CompareOptions::eCaseInsensitive)) { return move (Archive::Zip::Reader{IO::FileSystem::FileInputStream::New (archiveName)}); } #endif Execution::Throw (Execution::Exception (L"Unrecognized format"sv)); } } namespace { void ListArchive_ (const filesystem::path& archiveName) { for (String i : OpenArchive_ (archiveName).GetContainedFiles ()) { cout << i.AsNarrowSDKString () << endl; } } void ExtractArchive_ (const filesystem::path& archiveName, const filesystem::path& toDirectory) { Debug::TraceContextBumper ctx{L"ExtractArchive_"}; DbgTrace (L"(archiveName=%s, toDir=%s)", archiveName.c_str (), toDirectory.c_str ()); DataExchange::Archive::Reader archive{OpenArchive_ (archiveName)}; for (String i : archive.GetContainedFiles ()) { String srcFileName = i; filesystem::path trgFileName = toDirectory / IO::FileSystem::ToPath (srcFileName); //DbgTrace (L"(srcFileName=%s, trgFileName=%s)", Characters::ToString (srcFileName).c_str (), Characters::ToString (trgFileName).c_str ()); BLOB b = archive.GetData (srcFileName); //DbgTrace (L"IO::FileSystem::GetFileDirectory (trgFileName)=%s", IO::FileSystem::GetFileDirectory (trgFileName).c_str ()); IO::FileSystem::Directory{trgFileName.parent_path ()}.AssureExists (); IO::FileSystem::FileOutputStream::Ptr ostream = IO::FileSystem::FileOutputStream::New (trgFileName); ostream.Write (b); } } } int main (int argc, const char* argv[]) { Debug::TraceContextBumper ctx{Stroika_Foundation_Debug_OptionalizeTraceArgs (L"main", L"argv=%s", Characters::ToString (vector<const char*>{argv, argv + argc}).c_str ())}; if (optional<Options_> o = ParseOptions_ (argc, argv)) { try { switch (o->fOperation) { case Options_::Operation::eList: ListArchive_ (o->fArchiveFileName); break; case Options_::Operation::eExtract: ExtractArchive_ (o->fArchiveFileName, o->fOutputDirectory.value_or (L".")); break; default: cerr << "that option NYI" << endl; break; } } catch (...) { String exceptMsg = Characters::ToString (current_exception ()); cerr << "Exception: " << exceptMsg.AsNarrowSDKString () << " - terminating..." << endl; if (o->fNoFailOnMissingLibrary.value_or (false)) { #if !qHasFeature_LZMA || !qHasFeature_ZLib if (exceptMsg.Contains (L"Unrecognized format"sv)) { return EXIT_SUCESSS; } #endif } return EXIT_FAILURE; } } else { return EXIT_FAILURE; } return EXIT_SUCCESS; } <commit_msg>fixed typo<commit_after>/* * Copyright(c) Sophist Solutions, Inc. 1990-2020. All rights reserved */ #include "Stroika/Frameworks/StroikaPreComp.h" #include <iostream> #include "Stroika/Foundation/Characters/ToString.h" #include "Stroika/Foundation/DataExchange/Archive/Reader.h" #include "Stroika/Foundation/Debug/Trace.h" #include "Stroika/Foundation/Execution/CommandLine.h" #if qHasFeature_LZMA #include "Stroika/Foundation/DataExchange/Archive/7z/Reader.h" #endif #if qHasFeature_ZLib #include "Stroika/Foundation/DataExchange/Archive/Zip/Reader.h" #endif #include "Stroika/Foundation/IO/FileSystem/Directory.h" #include "Stroika/Foundation/IO/FileSystem/FileInputStream.h" #include "Stroika/Foundation/IO/FileSystem/FileOutputStream.h" #include "Stroika/Foundation/IO/FileSystem/PathName.h" #include "Stroika/Foundation/Streams/MemoryStream.h" #include "Stroika/Foundation/Streams/TextReader.h" using namespace std; using namespace Stroika::Foundation; #if qHasFeature_LZMA || qHasFeature_ZLib using namespace Stroika::Foundation::DataExchange; #endif using namespace Stroika::Foundation::Streams; using Characters::String; using Containers::Sequence; using Memory::BLOB; namespace { struct Options_ { enum class Operation { eList, eExtract, eCreate, eUpdate }; Operation fOperation; filesystem::path fArchiveFileName; optional<filesystem::path> fOutputDirectory; // applies only if extract optional<Sequence<String>> fFiles2Add; optional<bool> fNoFailOnMissingLibrary; // for regression tests }; void Usage_ () { cerr << "Usage: ArchiveUtility (--help | -h) | (--no-fail-on-missing-library) | ((--list | --create | --extract |--update) ARCHIVENAME [--outputDirectory D] [FILES])" << endl; cerr << " --help prints this help" << endl; cerr << " -h prints this help" << endl; cerr << " --no-fail-on-missing-library just warns when we fail because of missing library" << endl; cerr << " --list prints all the files in the argument archive" << endl; cerr << " --create creates the argument ARHCIVE and adds the argument FILES to it" << endl; cerr << " --extract extracts all the files from the argument ARHCIVE and to the output directory specified by --ouptutDirectory (defaulting to .)" << endl; cerr << " --update adds to the argument ARHCIVE and adds the argument FILES to it" << endl; cerr << " ARCHIVENAME can be the single character - to designate stdin" << endl; // NYI } // Emits errors to stderr, and Usage, etc, if needed, and not Optional<> has_value() optional<Options_> ParseOptions_ (int argc, const char* argv[]) { Options_ result{}; Sequence<String> args = Execution::ParseCommandLine (argc, argv); optional<Options_::Operation> operation; optional<String> archiveName; optional<bool> noFailOnMissingLibrary; for (auto argi = args.begin (); argi != args.end (); ++argi) { if (argi == args.begin ()) { continue; // skip argv[0] - command name } if (Execution::MatchesCommandLineArgument (*argi, L"h") or Execution::MatchesCommandLineArgument (*argi, L"help")) { Usage_ (); return optional<Options_>{}; } else if (Execution::MatchesCommandLineArgument (*argi, L"no-fail-on-missing-library")) { noFailOnMissingLibrary = true; } else if (Execution::MatchesCommandLineArgument (*argi, L"list")) { operation = Options_::Operation::eList; } else if (Execution::MatchesCommandLineArgument (*argi, L"create")) { operation = Options_::Operation::eCreate; } else if (Execution::MatchesCommandLineArgument (*argi, L"extract")) { operation = Options_::Operation::eExtract; } else if (Execution::MatchesCommandLineArgument (*argi, L"update")) { operation = Options_::Operation::eUpdate; } else if (not archiveName.has_value ()) { archiveName = *argi; } // else more cases todo } if (not archiveName) { cerr << "Missing name of archive" << endl; Usage_ (); return optional<Options_>{}; } if (not operation) { cerr << "Missing operation" << endl; Usage_ (); return optional<Options_>{}; } result.fOperation = *operation; result.fArchiveFileName = IO::FileSystem::ToPath (*archiveName); // @todo add more.. - files etc result.fNoFailOnMissingLibrary = noFailOnMissingLibrary; return result; } } namespace { DataExchange::Archive::Reader OpenArchive_ (const filesystem::path& archiveName) { // @todo - must support other formats, have a registry, and autodetect #if qHasFeature_LZMA if (IO::FileSystem::FromPath (archiveName).EndsWith (L".7z", Characters::CompareOptions::eCaseInsensitive)) { return move (Archive::_7z::Reader{IO::FileSystem::FileInputStream::New (archiveName)}); } #endif #if qHasFeature_ZLib if (IO::FileSystem::FromPath (archiveName).EndsWith (L".zip", Characters::CompareOptions::eCaseInsensitive)) { return move (Archive::Zip::Reader{IO::FileSystem::FileInputStream::New (archiveName)}); } #endif Execution::Throw (Execution::Exception (L"Unrecognized format"sv)); } } namespace { void ListArchive_ (const filesystem::path& archiveName) { for (String i : OpenArchive_ (archiveName).GetContainedFiles ()) { cout << i.AsNarrowSDKString () << endl; } } void ExtractArchive_ (const filesystem::path& archiveName, const filesystem::path& toDirectory) { Debug::TraceContextBumper ctx{L"ExtractArchive_"}; DbgTrace (L"(archiveName=%s, toDir=%s)", archiveName.c_str (), toDirectory.c_str ()); DataExchange::Archive::Reader archive{OpenArchive_ (archiveName)}; for (String i : archive.GetContainedFiles ()) { String srcFileName = i; filesystem::path trgFileName = toDirectory / IO::FileSystem::ToPath (srcFileName); //DbgTrace (L"(srcFileName=%s, trgFileName=%s)", Characters::ToString (srcFileName).c_str (), Characters::ToString (trgFileName).c_str ()); BLOB b = archive.GetData (srcFileName); //DbgTrace (L"IO::FileSystem::GetFileDirectory (trgFileName)=%s", IO::FileSystem::GetFileDirectory (trgFileName).c_str ()); IO::FileSystem::Directory{trgFileName.parent_path ()}.AssureExists (); IO::FileSystem::FileOutputStream::Ptr ostream = IO::FileSystem::FileOutputStream::New (trgFileName); ostream.Write (b); } } } int main (int argc, const char* argv[]) { Debug::TraceContextBumper ctx{Stroika_Foundation_Debug_OptionalizeTraceArgs (L"main", L"argv=%s", Characters::ToString (vector<const char*>{argv, argv + argc}).c_str ())}; if (optional<Options_> o = ParseOptions_ (argc, argv)) { try { switch (o->fOperation) { case Options_::Operation::eList: ListArchive_ (o->fArchiveFileName); break; case Options_::Operation::eExtract: ExtractArchive_ (o->fArchiveFileName, o->fOutputDirectory.value_or (L".")); break; default: cerr << "that option NYI" << endl; break; } } catch (...) { String exceptMsg = Characters::ToString (current_exception ()); cerr << "Exception: " << exceptMsg.AsNarrowSDKString () << " - terminating..." << endl; if (o->fNoFailOnMissingLibrary.value_or (false)) { #if !qHasFeature_LZMA || !qHasFeature_ZLib if (exceptMsg.Contains (L"Unrecognized format"sv)) { return EXIT_SUCCESS; } #endif } return EXIT_FAILURE; } } else { return EXIT_FAILURE; } return EXIT_SUCCESS; } <|endoftext|>
<commit_before>#ifndef _BINARY_SEARCH_TREE_HPP_ #define _BINARY_SEARCH_TREE_HPP_ template<class T> class BST : private BinaryTree<T> { }; #endif<commit_msg>Binary Search Tree added<commit_after>#ifndef _BINARY_SEARCH_TREE_HPP_ #define _BINARY_SEARCH_TREE_HPP_ template<class T> class BST : public BinaryTree<T> { }; #endif<|endoftext|>
<commit_before>#include <chrono> #include <cstdio> #include <vector> #include <memory> #include <algorithm> #include <poll.h> #include <xf86drm.h> #include <xf86drmMode.h> #include <gbm.h> #include <kms++.h> #include "test.h" #include "cube-egl.h" #include "cube-gles2.h" using namespace kms; using namespace std; static int s_flip_pending; static bool s_need_exit; static bool s_support_planes; class GbmDevice { public: GbmDevice(Card& card) { m_dev = gbm_create_device(card.fd()); FAIL_IF(!m_dev, "failed to create gbm device"); } ~GbmDevice() { gbm_device_destroy(m_dev); } GbmDevice(const GbmDevice& other) = delete; GbmDevice& operator=(const GbmDevice& other) = delete; struct gbm_device* handle() const { return m_dev; } private: struct gbm_device* m_dev; }; class GbmSurface { public: GbmSurface(GbmDevice& gdev, int width, int height) { m_surface = gbm_surface_create(gdev.handle(), width, height, GBM_FORMAT_XRGB8888, GBM_BO_USE_SCANOUT | GBM_BO_USE_RENDERING); FAIL_IF(!m_surface, "failed to create gbm surface"); } ~GbmSurface() { gbm_surface_destroy(m_surface); } GbmSurface(const GbmSurface& other) = delete; GbmSurface& operator=(const GbmSurface& other) = delete; bool has_free() { return gbm_surface_has_free_buffers(m_surface); } gbm_bo* lock_front_buffer() { return gbm_surface_lock_front_buffer(m_surface); } void release_buffer(gbm_bo *bo) { gbm_surface_release_buffer(m_surface, bo); } struct gbm_surface* handle() const { return m_surface; } private: struct gbm_surface* m_surface; }; class GbmEglSurface { public: GbmEglSurface(Card& card, GbmDevice& gdev, const EglState& egl, int width, int height) : card(card), gdev(gdev), egl(egl), m_width(width), m_height(height), bo_prev(0), bo_next(0) { gsurface = unique_ptr<GbmSurface>(new GbmSurface(gdev, width, height)); esurface = eglCreateWindowSurface(egl.display(), egl.config(), gsurface->handle(), NULL); FAIL_IF(esurface == EGL_NO_SURFACE, "failed to create egl surface"); } ~GbmEglSurface() { if (bo_next) gsurface->release_buffer(bo_next); eglDestroySurface(egl.display(), esurface); } void make_current() { FAIL_IF(!gsurface->has_free(), "No free buffers"); eglMakeCurrent(egl.display(), esurface, esurface, egl.context()); } void swap_buffers() { eglSwapBuffers(egl.display(), esurface); } static void drm_fb_destroy_callback(struct gbm_bo *bo, void *data) { auto fb = reinterpret_cast<Framebuffer*>(data); delete fb; } static Framebuffer* drm_fb_get_from_bo(struct gbm_bo *bo, Card& card) { auto fb = reinterpret_cast<Framebuffer*>(gbm_bo_get_user_data(bo)); if (fb) return fb; uint32_t width = gbm_bo_get_width(bo); uint32_t height = gbm_bo_get_height(bo); uint32_t stride = gbm_bo_get_stride(bo); uint32_t handle = gbm_bo_get_handle(bo).u32; fb = new ExtFramebuffer(card, width, height, 24, 32, stride, handle); gbm_bo_set_user_data(bo, fb, drm_fb_destroy_callback); return fb; } struct Framebuffer* lock_next() { bo_prev = bo_next; bo_next = gsurface->lock_front_buffer(); FAIL_IF(!bo_next, "could not lock gbm buffer"); return drm_fb_get_from_bo(bo_next, card); } void free_prev() { if (bo_prev) { gsurface->release_buffer(bo_prev); bo_prev = 0; } } uint32_t width() const { return m_width; } uint32_t height() const { return m_height; } private: Card& card; GbmDevice& gdev; const EglState& egl; unique_ptr<GbmSurface> gsurface; EGLSurface esurface; int m_width; int m_height; struct gbm_bo* bo_prev; struct gbm_bo* bo_next; }; class OutputHandler : private PageFlipHandlerBase { public: OutputHandler(Card& card, GbmDevice& gdev, const EglState& egl, Connector* connector, Crtc* crtc, Videomode& mode, Plane* plane, float rotation_mult) : m_frame_num(0), m_connector(connector), m_crtc(crtc), m_plane(plane), m_mode(mode), m_rotation_mult(rotation_mult) { m_surface1 = unique_ptr<GbmEglSurface>(new GbmEglSurface(card, gdev, egl, mode.hdisplay, mode.vdisplay)); m_scene1 = unique_ptr<GlScene>(new GlScene()); m_scene1->set_viewport(m_surface1->width(), m_surface1->height()); if (m_plane) { m_surface2 = unique_ptr<GbmEglSurface>(new GbmEglSurface(card, gdev, egl, 400, 400)); m_scene2 = unique_ptr<GlScene>(new GlScene()); m_scene2->set_viewport(m_surface2->width(), m_surface2->height()); } } OutputHandler(const OutputHandler& other) = delete; OutputHandler& operator=(const OutputHandler& other) = delete; void setup() { int ret; m_surface1->make_current(); m_surface1->swap_buffers(); struct Framebuffer* fb = m_surface1->lock_next(); struct Framebuffer* planefb = 0; if (m_plane) { m_surface2->make_current(); m_surface2->swap_buffers(); planefb = m_surface2->lock_next(); } ret = m_crtc->set_mode(m_connector, *fb, m_mode); FAIL_IF(ret, "failed to set mode"); if (m_crtc->card().has_atomic()) { Plane* root_plane = 0; for (Plane* p : m_crtc->get_possible_planes()) { if (p->crtc_id() == m_crtc->id()) { root_plane = p; break; } } FAIL_IF(!root_plane, "No primary plane for crtc %d", m_crtc->id()); m_root_plane = root_plane; } if (m_plane) { ret = m_crtc->set_plane(m_plane, *planefb, 0, 0, planefb->width(), planefb->height(), 0, 0, planefb->width(), planefb->height()); FAIL_IF(ret, "failed to set plane"); } } void start_flipping() { m_t1 = chrono::steady_clock::now(); queue_next(); } private: void handle_page_flip(uint32_t frame, double time) { ++m_frame_num; if (m_frame_num % 100 == 0) { auto t2 = chrono::steady_clock::now(); chrono::duration<float> fsec = t2 - m_t1; printf("fps: %f\n", 100.0 / fsec.count()); m_t1 = t2; } s_flip_pending--; m_surface1->free_prev(); if (m_plane) m_surface2->free_prev(); if (s_need_exit) return; queue_next(); } void queue_next() { m_surface1->make_current(); m_scene1->draw(m_frame_num * m_rotation_mult); m_surface1->swap_buffers(); struct Framebuffer* fb = m_surface1->lock_next(); struct Framebuffer* planefb = 0; if (m_plane) { m_surface2->make_current(); m_scene2->draw(m_frame_num * m_rotation_mult * 2); m_surface2->swap_buffers(); planefb = m_surface2->lock_next(); } if (m_crtc->card().has_atomic()) { int r; AtomicReq req(m_crtc->card()); req.add(m_root_plane, "FB_ID", fb->id()); if (m_plane) req.add(m_plane, "FB_ID", planefb->id()); r = req.test(); FAIL_IF(r, "atomic test failed"); r = req.commit(this); FAIL_IF(r, "atomic commit failed"); } else { int ret; ret = m_crtc->page_flip(*fb, this); FAIL_IF(ret, "failed to queue page flip"); if (m_plane) { ret = m_crtc->set_plane(m_plane, *planefb, 0, 0, planefb->width(), planefb->height(), 0, 0, planefb->width(), planefb->height()); FAIL_IF(ret, "failed to set plane"); } } s_flip_pending++; } int m_frame_num; chrono::steady_clock::time_point m_t1; Connector* m_connector; Crtc* m_crtc; Plane* m_plane; Videomode m_mode; Plane* m_root_plane; unique_ptr<GbmEglSurface> m_surface1; unique_ptr<GbmEglSurface> m_surface2; unique_ptr<GlScene> m_scene1; unique_ptr<GlScene> m_scene2; float m_rotation_mult; }; void main_gbm() { Card card; GbmDevice gdev(card); EglState egl(gdev.handle()); vector<unique_ptr<OutputHandler>> outputs; vector<Plane*> used_planes; float rot_mult = 1; for (auto pipe : card.get_connected_pipelines()) { auto connector = pipe.connector; auto crtc = pipe.crtc; auto mode = connector->get_default_mode(); Plane* plane = 0; if (s_support_planes) { for (Plane* p : crtc->get_possible_planes()) { if (find(used_planes.begin(), used_planes.end(), p) != used_planes.end()) continue; if (p->plane_type() != PlaneType::Overlay) continue; plane = p; break; } } if (plane) used_planes.push_back(plane); auto out = new OutputHandler(card, gdev, egl, connector, crtc, mode, plane, rot_mult); outputs.emplace_back(out); rot_mult *= 1.33; } for (auto& out : outputs) out->setup(); for (auto& out : outputs) out->start_flipping(); struct pollfd fds[2] = { }; fds[0].fd = 0; fds[0].events = POLLIN; fds[1].fd = card.fd(); fds[1].events = POLLIN; while (!s_need_exit || s_flip_pending) { int r = poll(fds, ARRAY_SIZE(fds), -1); FAIL_IF(r < 0, "poll error %d", r); if (fds[0].revents) s_need_exit = true; if (fds[1].revents) card.call_page_flip_handlers(); } } <commit_msg>kmscube: fix wrong uses of class Framebuffer<commit_after>#include <chrono> #include <cstdio> #include <vector> #include <memory> #include <algorithm> #include <poll.h> #include <xf86drm.h> #include <xf86drmMode.h> #include <gbm.h> #include <kms++.h> #include "test.h" #include "cube-egl.h" #include "cube-gles2.h" using namespace kms; using namespace std; static int s_flip_pending; static bool s_need_exit; static bool s_support_planes; class GbmDevice { public: GbmDevice(Card& card) { m_dev = gbm_create_device(card.fd()); FAIL_IF(!m_dev, "failed to create gbm device"); } ~GbmDevice() { gbm_device_destroy(m_dev); } GbmDevice(const GbmDevice& other) = delete; GbmDevice& operator=(const GbmDevice& other) = delete; struct gbm_device* handle() const { return m_dev; } private: struct gbm_device* m_dev; }; class GbmSurface { public: GbmSurface(GbmDevice& gdev, int width, int height) { m_surface = gbm_surface_create(gdev.handle(), width, height, GBM_FORMAT_XRGB8888, GBM_BO_USE_SCANOUT | GBM_BO_USE_RENDERING); FAIL_IF(!m_surface, "failed to create gbm surface"); } ~GbmSurface() { gbm_surface_destroy(m_surface); } GbmSurface(const GbmSurface& other) = delete; GbmSurface& operator=(const GbmSurface& other) = delete; bool has_free() { return gbm_surface_has_free_buffers(m_surface); } gbm_bo* lock_front_buffer() { return gbm_surface_lock_front_buffer(m_surface); } void release_buffer(gbm_bo *bo) { gbm_surface_release_buffer(m_surface, bo); } struct gbm_surface* handle() const { return m_surface; } private: struct gbm_surface* m_surface; }; class GbmEglSurface { public: GbmEglSurface(Card& card, GbmDevice& gdev, const EglState& egl, int width, int height) : card(card), gdev(gdev), egl(egl), m_width(width), m_height(height), bo_prev(0), bo_next(0) { gsurface = unique_ptr<GbmSurface>(new GbmSurface(gdev, width, height)); esurface = eglCreateWindowSurface(egl.display(), egl.config(), gsurface->handle(), NULL); FAIL_IF(esurface == EGL_NO_SURFACE, "failed to create egl surface"); } ~GbmEglSurface() { if (bo_next) gsurface->release_buffer(bo_next); eglDestroySurface(egl.display(), esurface); } void make_current() { FAIL_IF(!gsurface->has_free(), "No free buffers"); eglMakeCurrent(egl.display(), esurface, esurface, egl.context()); } void swap_buffers() { eglSwapBuffers(egl.display(), esurface); } static void drm_fb_destroy_callback(struct gbm_bo *bo, void *data) { auto fb = reinterpret_cast<Framebuffer*>(data); delete fb; } static Framebuffer* drm_fb_get_from_bo(struct gbm_bo *bo, Card& card) { auto fb = reinterpret_cast<Framebuffer*>(gbm_bo_get_user_data(bo)); if (fb) return fb; uint32_t width = gbm_bo_get_width(bo); uint32_t height = gbm_bo_get_height(bo); uint32_t stride = gbm_bo_get_stride(bo); uint32_t handle = gbm_bo_get_handle(bo).u32; fb = new ExtFramebuffer(card, width, height, 24, 32, stride, handle); gbm_bo_set_user_data(bo, fb, drm_fb_destroy_callback); return fb; } Framebuffer* lock_next() { bo_prev = bo_next; bo_next = gsurface->lock_front_buffer(); FAIL_IF(!bo_next, "could not lock gbm buffer"); return drm_fb_get_from_bo(bo_next, card); } void free_prev() { if (bo_prev) { gsurface->release_buffer(bo_prev); bo_prev = 0; } } uint32_t width() const { return m_width; } uint32_t height() const { return m_height; } private: Card& card; GbmDevice& gdev; const EglState& egl; unique_ptr<GbmSurface> gsurface; EGLSurface esurface; int m_width; int m_height; struct gbm_bo* bo_prev; struct gbm_bo* bo_next; }; class OutputHandler : private PageFlipHandlerBase { public: OutputHandler(Card& card, GbmDevice& gdev, const EglState& egl, Connector* connector, Crtc* crtc, Videomode& mode, Plane* plane, float rotation_mult) : m_frame_num(0), m_connector(connector), m_crtc(crtc), m_plane(plane), m_mode(mode), m_rotation_mult(rotation_mult) { m_surface1 = unique_ptr<GbmEglSurface>(new GbmEglSurface(card, gdev, egl, mode.hdisplay, mode.vdisplay)); m_scene1 = unique_ptr<GlScene>(new GlScene()); m_scene1->set_viewport(m_surface1->width(), m_surface1->height()); if (m_plane) { m_surface2 = unique_ptr<GbmEglSurface>(new GbmEglSurface(card, gdev, egl, 400, 400)); m_scene2 = unique_ptr<GlScene>(new GlScene()); m_scene2->set_viewport(m_surface2->width(), m_surface2->height()); } } OutputHandler(const OutputHandler& other) = delete; OutputHandler& operator=(const OutputHandler& other) = delete; void setup() { int ret; m_surface1->make_current(); m_surface1->swap_buffers(); Framebuffer* fb = m_surface1->lock_next(); Framebuffer* planefb = 0; if (m_plane) { m_surface2->make_current(); m_surface2->swap_buffers(); planefb = m_surface2->lock_next(); } ret = m_crtc->set_mode(m_connector, *fb, m_mode); FAIL_IF(ret, "failed to set mode"); if (m_crtc->card().has_atomic()) { Plane* root_plane = 0; for (Plane* p : m_crtc->get_possible_planes()) { if (p->crtc_id() == m_crtc->id()) { root_plane = p; break; } } FAIL_IF(!root_plane, "No primary plane for crtc %d", m_crtc->id()); m_root_plane = root_plane; } if (m_plane) { ret = m_crtc->set_plane(m_plane, *planefb, 0, 0, planefb->width(), planefb->height(), 0, 0, planefb->width(), planefb->height()); FAIL_IF(ret, "failed to set plane"); } } void start_flipping() { m_t1 = chrono::steady_clock::now(); queue_next(); } private: void handle_page_flip(uint32_t frame, double time) { ++m_frame_num; if (m_frame_num % 100 == 0) { auto t2 = chrono::steady_clock::now(); chrono::duration<float> fsec = t2 - m_t1; printf("fps: %f\n", 100.0 / fsec.count()); m_t1 = t2; } s_flip_pending--; m_surface1->free_prev(); if (m_plane) m_surface2->free_prev(); if (s_need_exit) return; queue_next(); } void queue_next() { m_surface1->make_current(); m_scene1->draw(m_frame_num * m_rotation_mult); m_surface1->swap_buffers(); Framebuffer* fb = m_surface1->lock_next(); Framebuffer* planefb = 0; if (m_plane) { m_surface2->make_current(); m_scene2->draw(m_frame_num * m_rotation_mult * 2); m_surface2->swap_buffers(); planefb = m_surface2->lock_next(); } if (m_crtc->card().has_atomic()) { int r; AtomicReq req(m_crtc->card()); req.add(m_root_plane, "FB_ID", fb->id()); if (m_plane) req.add(m_plane, "FB_ID", planefb->id()); r = req.test(); FAIL_IF(r, "atomic test failed"); r = req.commit(this); FAIL_IF(r, "atomic commit failed"); } else { int ret; ret = m_crtc->page_flip(*fb, this); FAIL_IF(ret, "failed to queue page flip"); if (m_plane) { ret = m_crtc->set_plane(m_plane, *planefb, 0, 0, planefb->width(), planefb->height(), 0, 0, planefb->width(), planefb->height()); FAIL_IF(ret, "failed to set plane"); } } s_flip_pending++; } int m_frame_num; chrono::steady_clock::time_point m_t1; Connector* m_connector; Crtc* m_crtc; Plane* m_plane; Videomode m_mode; Plane* m_root_plane; unique_ptr<GbmEglSurface> m_surface1; unique_ptr<GbmEglSurface> m_surface2; unique_ptr<GlScene> m_scene1; unique_ptr<GlScene> m_scene2; float m_rotation_mult; }; void main_gbm() { Card card; GbmDevice gdev(card); EglState egl(gdev.handle()); vector<unique_ptr<OutputHandler>> outputs; vector<Plane*> used_planes; float rot_mult = 1; for (auto pipe : card.get_connected_pipelines()) { auto connector = pipe.connector; auto crtc = pipe.crtc; auto mode = connector->get_default_mode(); Plane* plane = 0; if (s_support_planes) { for (Plane* p : crtc->get_possible_planes()) { if (find(used_planes.begin(), used_planes.end(), p) != used_planes.end()) continue; if (p->plane_type() != PlaneType::Overlay) continue; plane = p; break; } } if (plane) used_planes.push_back(plane); auto out = new OutputHandler(card, gdev, egl, connector, crtc, mode, plane, rot_mult); outputs.emplace_back(out); rot_mult *= 1.33; } for (auto& out : outputs) out->setup(); for (auto& out : outputs) out->start_flipping(); struct pollfd fds[2] = { }; fds[0].fd = 0; fds[0].events = POLLIN; fds[1].fd = card.fd(); fds[1].events = POLLIN; while (!s_need_exit || s_flip_pending) { int r = poll(fds, ARRAY_SIZE(fds), -1); FAIL_IF(r < 0, "poll error %d", r); if (fds[0].revents) s_need_exit = true; if (fds[1].revents) card.call_page_flip_handlers(); } } <|endoftext|>
<commit_before>/* * Copyright(c) Sophist Solutions, Inc. 1990-2018. All rights reserved */ #include "Stroika/Frameworks/StroikaPreComp.h" #include <iostream> #include "Stroika/Foundation/Characters/ToString.h" #include "Stroika/Foundation/DataExchange/Archive/Reader.h" #include "Stroika/Foundation/Debug/Trace.h" #include "Stroika/Foundation/Execution/CommandLine.h" #if qHasFeature_LZMA #include "Stroika/Foundation/DataExchange/Archive/7z/Reader.h" #endif #if qHasFeature_ZLib #include "Stroika/Foundation/DataExchange/Archive/Zip/Reader.h" #endif #include "Stroika/Foundation/IO/FileSystem/Directory.h" #include "Stroika/Foundation/IO/FileSystem/FileInputStream.h" #include "Stroika/Foundation/IO/FileSystem/FileOutputStream.h" #include "Stroika/Foundation/IO/FileSystem/PathName.h" #include "Stroika/Foundation/Streams/MemoryStream.h" #include "Stroika/Foundation/Streams/TextReader.h" using namespace std; using namespace Stroika::Foundation; using namespace Stroika::Foundation::DataExchange; using namespace Stroika::Foundation::Streams; using Characters::String; using Containers::Sequence; using Memory::BLOB; using Memory::Byte; using Memory::Optional; namespace { struct Options_ { enum class Operation { eList, eExtract, eCreate, eUpdate }; Operation fOperation; String fArchiveFileName; Optional<String> fOutputDirectory; // applies only if extract Optional<Sequence<String>> fFiles2Add; }; void Usage_ () { cerr << "Usage: ArchiveUtility (--help | -h) | ((--list | --create | --extract |--update) ARCHIVENAME [--outputDirectory D] [FILES])" << endl; cerr << " --help prints this help" << endl; cerr << " -h prints this help" << endl; cerr << " --list prints all the files in the argument archive" << endl; cerr << " --create creates the argument ARHCIVE and adds the argument FILES to it" << endl; cerr << " --extract extracts all the files from the argument ARHCIVE and to the output directory specified by --ouptutDirectory (defaulting to .)" << endl; cerr << " --update adds to the argument ARHCIVE and adds the argument FILES to it" << endl; cerr << " ARCHIVENAME can be the single character - to designate stdin" << endl; // NYI } // Emits errors to stderr, and Usage, etc, if needed, and not Optional<> has_value() Optional<Options_> ParseOptions_ (int argc, const char* argv[]) { Options_ result{}; Sequence<String> args = Execution::ParseCommandLine (argc, argv); Optional<Options_::Operation> operation; Optional<String> archiveName; for (auto argi = args.begin (); argi != args.end (); ++argi) { if (argi == args.begin ()) { continue; // skip argv[0] - command name } if (Execution::MatchesCommandLineArgument (*argi, L"h") or Execution::MatchesCommandLineArgument (*argi, L"help")) { Usage_ (); return Optional<Options_>{}; } else if (Execution::MatchesCommandLineArgument (*argi, L"list")) { operation = Options_::Operation::eList; } else if (Execution::MatchesCommandLineArgument (*argi, L"create")) { operation = Options_::Operation::eCreate; } else if (Execution::MatchesCommandLineArgument (*argi, L"extract")) { operation = Options_::Operation::eExtract; } else if (Execution::MatchesCommandLineArgument (*argi, L"update")) { operation = Options_::Operation::eUpdate; } else if (not archiveName.has_value ()) { archiveName = *argi; } // else more cases todo } if (not archiveName) { cerr << "Missing name of archive" << endl; Usage_ (); return Optional<Options_>{}; } if (not operation) { cerr << "Missing operation" << endl; Usage_ (); return Optional<Options_>{}; } result.fOperation = *operation; result.fArchiveFileName = *archiveName; // @todo add more.. - files etc return result; } } namespace { DataExchange::Archive::Reader OpenArchive_ (const String& archiveName) { // @todo - must support other formats, have a registry, and autodetect #if qHasFeature_LZMA if (archiveName.EndsWith (L".7z", Characters::CompareOptions::eCaseInsensitive)) { return move (Archive::_7z::Reader{IO::FileSystem::FileInputStream::New (archiveName)}); } #endif #if qHasFeature_ZLib if (archiveName.EndsWith (L".zip", Characters::CompareOptions::eCaseInsensitive)) { return move (Archive::Zip::Reader{IO::FileSystem::FileInputStream::New (archiveName)}); } #endif Execution::Throw (Execution::StringException (L"Unrecognized format")); } } namespace { void ListArchive_ (const String& archiveName) { for (String i : OpenArchive_ (archiveName).GetContainedFiles ()) { cout << i.AsNarrowSDKString () << endl; } } void ExtractArchive_ (const String& archiveName, const String& toDirectory) { Debug::TraceContextBumper ctx{L"ExtractArchive_"}; DbgTrace (L"(archiveName=%s, toDir=%s)", archiveName.c_str (), toDirectory.c_str ()); DataExchange::Archive::Reader archive{OpenArchive_ (archiveName)}; for (String i : archive.GetContainedFiles ()) { String srcFileName = i; String trgFileName = toDirectory + L"/" + srcFileName; //tmphac #if qPlatform_Windows trgFileName = trgFileName.ReplaceAll (L"/", L"\\"); #endif //DbgTrace (L"(srcFileName=%s, trgFileName=%s)", srcFileName.c_str (), trgFileName.c_str ()); BLOB b = archive.GetData (srcFileName); //DbgTrace (L"IO::FileSystem::GetFileDirectory (trgFileName)=%s", IO::FileSystem::GetFileDirectory (trgFileName).c_str ()); IO::FileSystem::Directory{IO::FileSystem::GetFileDirectory (trgFileName)}.AssureExists (); IO::FileSystem::FileOutputStream::Ptr ostream = IO::FileSystem::FileOutputStream::New (trgFileName); ostream.Write (b); } } } int main (int argc, const char* argv[]) { if (Optional<Options_> o = ParseOptions_ (argc, argv)) { try { switch (o->fOperation) { case Options_::Operation::eList: ListArchive_ (o->fArchiveFileName); break; case Options_::Operation::eExtract: ExtractArchive_ (o->fArchiveFileName, o->fOutputDirectory.value_or (L".")); break; default: cerr << "that option NYI" << endl; break; } } catch (...) { String exceptMsg = Characters::ToString (current_exception ()); cerr << "Exception: " << exceptMsg.AsNarrowSDKString () << " - terminating..." << endl; return EXIT_FAILURE; } } else { return EXIT_FAILURE; } return EXIT_SUCCESS; } <commit_msg>update Archive sample to use optional instead of Memory::Optional<commit_after>/* * Copyright(c) Sophist Solutions, Inc. 1990-2018. All rights reserved */ #include "Stroika/Frameworks/StroikaPreComp.h" #include <iostream> #include "Stroika/Foundation/Characters/ToString.h" #include "Stroika/Foundation/DataExchange/Archive/Reader.h" #include "Stroika/Foundation/Debug/Trace.h" #include "Stroika/Foundation/Execution/CommandLine.h" #if qHasFeature_LZMA #include "Stroika/Foundation/DataExchange/Archive/7z/Reader.h" #endif #if qHasFeature_ZLib #include "Stroika/Foundation/DataExchange/Archive/Zip/Reader.h" #endif #include "Stroika/Foundation/IO/FileSystem/Directory.h" #include "Stroika/Foundation/IO/FileSystem/FileInputStream.h" #include "Stroika/Foundation/IO/FileSystem/FileOutputStream.h" #include "Stroika/Foundation/IO/FileSystem/PathName.h" #include "Stroika/Foundation/Streams/MemoryStream.h" #include "Stroika/Foundation/Streams/TextReader.h" using namespace std; using namespace Stroika::Foundation; using namespace Stroika::Foundation::DataExchange; using namespace Stroika::Foundation::Streams; using Characters::String; using Containers::Sequence; using Memory::BLOB; using Memory::Byte; namespace { struct Options_ { enum class Operation { eList, eExtract, eCreate, eUpdate }; Operation fOperation; String fArchiveFileName; optional<String> fOutputDirectory; // applies only if extract optional<Sequence<String>> fFiles2Add; }; void Usage_ () { cerr << "Usage: ArchiveUtility (--help | -h) | ((--list | --create | --extract |--update) ARCHIVENAME [--outputDirectory D] [FILES])" << endl; cerr << " --help prints this help" << endl; cerr << " -h prints this help" << endl; cerr << " --list prints all the files in the argument archive" << endl; cerr << " --create creates the argument ARHCIVE and adds the argument FILES to it" << endl; cerr << " --extract extracts all the files from the argument ARHCIVE and to the output directory specified by --ouptutDirectory (defaulting to .)" << endl; cerr << " --update adds to the argument ARHCIVE and adds the argument FILES to it" << endl; cerr << " ARCHIVENAME can be the single character - to designate stdin" << endl; // NYI } // Emits errors to stderr, and Usage, etc, if needed, and not Optional<> has_value() optional<Options_> ParseOptions_ (int argc, const char* argv[]) { Options_ result{}; Sequence<String> args = Execution::ParseCommandLine (argc, argv); optional<Options_::Operation> operation; optional<String> archiveName; for (auto argi = args.begin (); argi != args.end (); ++argi) { if (argi == args.begin ()) { continue; // skip argv[0] - command name } if (Execution::MatchesCommandLineArgument (*argi, L"h") or Execution::MatchesCommandLineArgument (*argi, L"help")) { Usage_ (); return optional<Options_>{}; } else if (Execution::MatchesCommandLineArgument (*argi, L"list")) { operation = Options_::Operation::eList; } else if (Execution::MatchesCommandLineArgument (*argi, L"create")) { operation = Options_::Operation::eCreate; } else if (Execution::MatchesCommandLineArgument (*argi, L"extract")) { operation = Options_::Operation::eExtract; } else if (Execution::MatchesCommandLineArgument (*argi, L"update")) { operation = Options_::Operation::eUpdate; } else if (not archiveName.has_value ()) { archiveName = *argi; } // else more cases todo } if (not archiveName) { cerr << "Missing name of archive" << endl; Usage_ (); return optional<Options_>{}; } if (not operation) { cerr << "Missing operation" << endl; Usage_ (); return optional<Options_>{}; } result.fOperation = *operation; result.fArchiveFileName = *archiveName; // @todo add more.. - files etc return result; } } namespace { DataExchange::Archive::Reader OpenArchive_ (const String& archiveName) { // @todo - must support other formats, have a registry, and autodetect #if qHasFeature_LZMA if (archiveName.EndsWith (L".7z", Characters::CompareOptions::eCaseInsensitive)) { return move (Archive::_7z::Reader{IO::FileSystem::FileInputStream::New (archiveName)}); } #endif #if qHasFeature_ZLib if (archiveName.EndsWith (L".zip", Characters::CompareOptions::eCaseInsensitive)) { return move (Archive::Zip::Reader{IO::FileSystem::FileInputStream::New (archiveName)}); } #endif Execution::Throw (Execution::StringException (L"Unrecognized format")); } } namespace { void ListArchive_ (const String& archiveName) { for (String i : OpenArchive_ (archiveName).GetContainedFiles ()) { cout << i.AsNarrowSDKString () << endl; } } void ExtractArchive_ (const String& archiveName, const String& toDirectory) { Debug::TraceContextBumper ctx{L"ExtractArchive_"}; DbgTrace (L"(archiveName=%s, toDir=%s)", archiveName.c_str (), toDirectory.c_str ()); DataExchange::Archive::Reader archive{OpenArchive_ (archiveName)}; for (String i : archive.GetContainedFiles ()) { String srcFileName = i; String trgFileName = toDirectory + L"/" + srcFileName; //tmphac #if qPlatform_Windows trgFileName = trgFileName.ReplaceAll (L"/", L"\\"); #endif //DbgTrace (L"(srcFileName=%s, trgFileName=%s)", srcFileName.c_str (), trgFileName.c_str ()); BLOB b = archive.GetData (srcFileName); //DbgTrace (L"IO::FileSystem::GetFileDirectory (trgFileName)=%s", IO::FileSystem::GetFileDirectory (trgFileName).c_str ()); IO::FileSystem::Directory{IO::FileSystem::GetFileDirectory (trgFileName)}.AssureExists (); IO::FileSystem::FileOutputStream::Ptr ostream = IO::FileSystem::FileOutputStream::New (trgFileName); ostream.Write (b); } } } int main (int argc, const char* argv[]) { if (optional<Options_> o = ParseOptions_ (argc, argv)) { try { switch (o->fOperation) { case Options_::Operation::eList: ListArchive_ (o->fArchiveFileName); break; case Options_::Operation::eExtract: ExtractArchive_ (o->fArchiveFileName, o->fOutputDirectory.value_or (L".")); break; default: cerr << "that option NYI" << endl; break; } } catch (...) { String exceptMsg = Characters::ToString (current_exception ()); cerr << "Exception: " << exceptMsg.AsNarrowSDKString () << " - terminating..." << endl; return EXIT_FAILURE; } } else { return EXIT_FAILURE; } return EXIT_SUCCESS; } <|endoftext|>
<commit_before>#include "mswin.h" #include "model.h" #include "random.h" #include "cmdline.h" #include "graphics.h" #include "config.h" #include "memory.h" #include "vector.h" #include "glprocs.h" #include "compiler.h" #include "tinyscheme-config.h" #include <scheme-private.h> #include <scheme.h> #include <cstdint> #define IDT_TIMER 1 // Is x one of the space-separated strings in xs? template <typename ConstIterator> bool in (const ConstIterator x, ConstIterator xs) { while (* xs) { ConstIterator t = x; while (* t && * t == * xs) { ++ xs; ++ t; } if (! * t && (! * xs || * xs == ' ')) return true; while (* xs && * xs != ' ') ++ xs; if (* xs) ++ xs; } return false; } struct window_struct_t { model_t model; HDC hdc; HGLRC hglrc; POINT initial_cursor_position; int width, height; run_mode_t mode; }; LRESULT CALLBACK WndProc (HWND hwnd, UINT msg, WPARAM wParam, LPARAM lParam) { bool close_window = false; bool call_def_window_proc = false; if (msg == WM_CREATE) { const CREATESTRUCT * cs = reinterpret_cast <CREATESTRUCT *> (lParam); window_struct_t * ws = reinterpret_cast <window_struct_t *> (cs->lpCreateParams); ::SetWindowLongPtr (hwnd, GWLP_USERDATA, reinterpret_cast <LONG_PTR> (ws)); ::GetCursorPos (& ws->initial_cursor_position); ws->width = cs->cx; ws->height = cs->cy; return 0; } else if (window_struct_t * ws = reinterpret_cast <window_struct_t *> (::GetWindowLongPtr (hwnd, GWLP_USERDATA))) { switch (msg) { case WM_PAINT: ::ValidateRect (hwnd, nullptr); break; case WM_TIMER: { ws->model.proceed (); clear (); ws->model.draw (); ::SwapBuffers (ws->hdc); } break; case WM_SETCURSOR: ::SetCursor (ws->mode == fullscreen ? nullptr : (::LoadCursor (nullptr, IDC_ARROW))); break; case WM_MOUSEMOVE: if (ws->mode == fullscreen) { // Compare the current mouse position with the one stored in the window struct. POINT current { LOWORD (lParam), HIWORD (lParam) }; ::ClientToScreen (hwnd, & current); SHORT dx = current.x - ws->initial_cursor_position.x; SHORT dy = current.y - ws->initial_cursor_position.y; close_window = dx > 10 || dy > 10 || dx * dx + dy * dy > 100; } break; case WM_KEYDOWN: case WM_LBUTTONDOWN: case WM_MBUTTONDOWN: case WM_RBUTTONDOWN: close_window = ws->mode == fullscreen || ws->mode == special; break; case WM_ACTIVATE: case WM_ACTIVATEAPP: case WM_NCACTIVATE: close_window = ws->mode == fullscreen && LOWORD (wParam) == WA_INACTIVE; call_def_window_proc = true; break; case WM_SYSCOMMAND: call_def_window_proc = (ws->mode != fullscreen || wParam != SC_SCREENSAVE) && wParam != SC_CLOSE; break; case WM_CLOSE: ::DestroyWindow (hwnd); break; case WM_DESTROY: ::wglMakeCurrent (nullptr, nullptr); ::wglDeleteContext (ws->hglrc); ::PostQuitMessage (0); break; default: call_def_window_proc = true; break; } } else call_def_window_proc = true; if (close_window) { ::KillTimer (hwnd, IDT_TIMER); ::PostMessage (hwnd, WM_CLOSE, 0, 0); } return call_def_window_proc ? ::DefWindowProc (hwnd, msg, wParam, lParam) : 0; } int WINAPI WinMain (HINSTANCE hInstance, HINSTANCE, LPSTR lpszCmdLine, int) { // Parse the command line. HWND parent = 0; run_mode_t mode = parse_command_line (lpszCmdLine, & parent); if (mode == configure) { ::MessageBox (parent, usr::message, usr::message_window_name, MB_OK | MB_ICONASTERISK); return 0; } // Dummy rendering context to get the address of wglChoosePixelFormatARB. { const char * name = "PolymorphTemp"; WNDCLASS wc; ::ZeroMemory (& wc, sizeof wc); wc.hInstance = hInstance; wc.lpfnWndProc = & ::DefWindowProc; wc.lpszClassName = name; ATOM atom = ::RegisterClass (& wc); if (! atom) return 1; HWND wnd = ::CreateWindowEx (0, MAKEINTATOM (atom), name, 0, CW_USEDEFAULT, 0, CW_USEDEFAULT, 0, 0, 0, hInstance, 0); if (! wnd) return 1; HDC dc = ::GetDC (wnd); PIXELFORMATDESCRIPTOR pfd; ::ZeroMemory (& pfd, sizeof pfd); pfd.nSize = sizeof pfd; pfd.dwFlags = PFD_SUPPORT_OPENGL | PFD_DRAW_TO_WINDOW; int pf = ::ChoosePixelFormat (dc, & pfd); if (! pf) return 1; if (! ::SetPixelFormat (dc, pf, 0)) return 1; HGLRC rc = ::wglCreateContext (dc); if (! rc) return 1; if (! ::wglMakeCurrent (dc, rc)) return 1; // Get all needed gl function pointers while we're here. if (! glprocs ()) return 1; ::wglMakeCurrent (dc, 0); ::wglDeleteContext (rc); ::ReleaseDC (wnd, dc); ::DestroyWindow (wnd); ::UnregisterClass (MAKEINTATOM (atom), hInstance); } // Create the screen saver window. DWORD style; DWORD ex_style; int left, top, width, height; if (mode == embedded) { RECT rect; ::GetClientRect (parent, & rect); left = 0; top = 0; width = rect.right; height = rect.bottom; style = WS_CHILD | WS_VISIBLE; ex_style = 0; } else { left = ::GetSystemMetrics (SM_XVIRTUALSCREEN); top = ::GetSystemMetrics (SM_YVIRTUALSCREEN); width = ::GetSystemMetrics (SM_CXVIRTUALSCREEN); height = ::GetSystemMetrics (SM_CYVIRTUALSCREEN); style = WS_POPUP | WS_VISIBLE; ex_style = ((mode == fullscreen) ? WS_EX_TOPMOST : 0); } WNDCLASS wc; ::ZeroMemory (& wc, sizeof wc); wc.lpfnWndProc = & WndProc; wc.cbWndExtra = 8; wc.hInstance = hInstance; wc.lpszClassName = usr::window_class_name; ATOM atom = ::RegisterClass (& wc); if (! atom) return 1; window_struct_t ws ALIGNED16; ws.mode = mode; // HWND CreateWindowEx HWND hwnd = ::CreateWindowEx (ex_style, // (DWORD dwExStyle, MAKEINTATOM (atom), // LPCTSTR lpClassName, usr::window_name, // LPCTSTR lpWindowName, style, // DWORD dwStyle, left, // int x, top, // int y, width, // int nWidth, height, // int nHeight, parent, // HWND hWndParent, 0, // HMENU hMenu, hInstance, // HINSTANCE hInstance, & ws); // LPVOID lpParam); if (! hwnd) return 1; ws.hdc = ::GetDC (hwnd); if (! ws.hdc) return 1; int ilist [] = { WGL_DRAW_TO_WINDOW_ARB, GL_TRUE, WGL_SUPPORT_OPENGL_ARB, GL_TRUE, WGL_DOUBLE_BUFFER_ARB, GL_TRUE, WGL_ACCELERATION_ARB, WGL_FULL_ACCELERATION_ARB, WGL_SWAP_METHOD_ARB, WGL_SWAP_EXCHANGE_ARB, WGL_COLOR_BITS_ARB, 32, WGL_SAMPLE_BUFFERS_ARB, GL_TRUE, WGL_SAMPLES_ARB, 5, 0, 0, }; float flist [] = { 0, 0, }; enum { pfcountmax = 256 }; UINT pfcount; int pfs [pfcountmax]; bool status = wglChoosePixelFormatARB (ws.hdc, ilist, flist, pfcountmax, pfs, & pfcount); if (! (status && pfcount && pfcount < pfcountmax)) return 1; if (! ::SetPixelFormat (ws.hdc, pfs [0], 0)) return 1; ws.hglrc = ::wglCreateContext (ws.hdc); if (! ws.hglrc) return 1; if (! ::wglMakeCurrent (ws.hdc, ws.hglrc)) { ::wglDeleteContext (ws.hglrc); return 1; } LARGE_INTEGER pc; ::QueryPerformanceCounter (& pc); if (! ws.model.initialize (pc.QuadPart, ws.width, ws.height)) { return 1; } ::SetTimer (hwnd, IDT_TIMER, 10, nullptr); // Enter the main loop. MSG msg; BOOL bRet; while ((bRet = ::GetMessage (& msg, nullptr, 0, 0)) != 0) { if (bRet == -1) { // TODO: check error code return ::GetLastError (); } else { ::TranslateMessage (& msg); ::DispatchMessage (& msg); } } return (msg.message == WM_QUIT ? msg.wParam : 1); } <commit_msg>Use icon for screensaver window<commit_after>#include "mswin.h" #include "model.h" #include "random.h" #include "cmdline.h" #include "graphics.h" #include "config.h" #include "memory.h" #include "vector.h" #include "glprocs.h" #include "compiler.h" #include "tinyscheme-config.h" #include <scheme-private.h> #include <scheme.h> #include <cstdint> #define IDT_TIMER 1 // Is x one of the space-separated strings in xs? template <typename ConstIterator> bool in (const ConstIterator x, ConstIterator xs) { while (* xs) { ConstIterator t = x; while (* t && * t == * xs) { ++ xs; ++ t; } if (! * t && (! * xs || * xs == ' ')) return true; while (* xs && * xs != ' ') ++ xs; if (* xs) ++ xs; } return false; } struct window_struct_t { model_t model; HDC hdc; HGLRC hglrc; POINT initial_cursor_position; int width, height; run_mode_t mode; }; LRESULT CALLBACK WndProc (HWND hwnd, UINT msg, WPARAM wParam, LPARAM lParam) { bool close_window = false; bool call_def_window_proc = false; if (msg == WM_CREATE) { const CREATESTRUCT * cs = reinterpret_cast <CREATESTRUCT *> (lParam); window_struct_t * ws = reinterpret_cast <window_struct_t *> (cs->lpCreateParams); ::SetWindowLongPtr (hwnd, GWLP_USERDATA, reinterpret_cast <LONG_PTR> (ws)); ::GetCursorPos (& ws->initial_cursor_position); ws->width = cs->cx; ws->height = cs->cy; return 0; } else if (window_struct_t * ws = reinterpret_cast <window_struct_t *> (::GetWindowLongPtr (hwnd, GWLP_USERDATA))) { switch (msg) { case WM_PAINT: ::ValidateRect (hwnd, nullptr); break; case WM_TIMER: { ws->model.proceed (); clear (); ws->model.draw (); ::SwapBuffers (ws->hdc); } break; case WM_SETCURSOR: ::SetCursor (ws->mode == fullscreen ? nullptr : (::LoadCursor (nullptr, IDC_ARROW))); break; case WM_MOUSEMOVE: if (ws->mode == fullscreen) { // Compare the current mouse position with the one stored in the window struct. POINT current { LOWORD (lParam), HIWORD (lParam) }; ::ClientToScreen (hwnd, & current); SHORT dx = current.x - ws->initial_cursor_position.x; SHORT dy = current.y - ws->initial_cursor_position.y; close_window = dx > 10 || dy > 10 || dx * dx + dy * dy > 100; } break; case WM_KEYDOWN: case WM_LBUTTONDOWN: case WM_MBUTTONDOWN: case WM_RBUTTONDOWN: close_window = ws->mode == fullscreen || ws->mode == special; break; case WM_ACTIVATE: case WM_ACTIVATEAPP: case WM_NCACTIVATE: close_window = ws->mode == fullscreen && LOWORD (wParam) == WA_INACTIVE; call_def_window_proc = true; break; case WM_SYSCOMMAND: call_def_window_proc = (ws->mode != fullscreen || wParam != SC_SCREENSAVE) && wParam != SC_CLOSE; break; case WM_CLOSE: ::DestroyWindow (hwnd); break; case WM_DESTROY: ::wglMakeCurrent (nullptr, nullptr); ::wglDeleteContext (ws->hglrc); ::PostQuitMessage (0); break; default: call_def_window_proc = true; break; } } else call_def_window_proc = true; if (close_window) { ::KillTimer (hwnd, IDT_TIMER); ::PostMessage (hwnd, WM_CLOSE, 0, 0); } return call_def_window_proc ? ::DefWindowProc (hwnd, msg, wParam, lParam) : 0; } int WINAPI WinMain (HINSTANCE hInstance, HINSTANCE, LPSTR lpszCmdLine, int) { // Parse the command line. HWND parent = 0; run_mode_t mode = parse_command_line (lpszCmdLine, & parent); if (mode == configure) { ::MessageBox (parent, usr::message, usr::message_window_name, MB_OK | MB_ICONASTERISK); return 0; } // Dummy rendering context to get the address of wglChoosePixelFormatARB. { const char * name = "PolymorphTemp"; WNDCLASS wc; ::ZeroMemory (& wc, sizeof wc); wc.hInstance = hInstance; wc.lpfnWndProc = & ::DefWindowProc; wc.lpszClassName = name; ATOM atom = ::RegisterClass (& wc); if (! atom) return 1; HWND wnd = ::CreateWindowEx (0, MAKEINTATOM (atom), name, 0, CW_USEDEFAULT, 0, CW_USEDEFAULT, 0, 0, 0, hInstance, 0); if (! wnd) return 1; HDC dc = ::GetDC (wnd); PIXELFORMATDESCRIPTOR pfd; ::ZeroMemory (& pfd, sizeof pfd); pfd.nSize = sizeof pfd; pfd.dwFlags = PFD_SUPPORT_OPENGL | PFD_DRAW_TO_WINDOW; int pf = ::ChoosePixelFormat (dc, & pfd); if (! pf) return 1; if (! ::SetPixelFormat (dc, pf, 0)) return 1; HGLRC rc = ::wglCreateContext (dc); if (! rc) return 1; if (! ::wglMakeCurrent (dc, rc)) return 1; // Get all needed gl function pointers while we're here. if (! glprocs ()) return 1; ::wglMakeCurrent (dc, 0); ::wglDeleteContext (rc); ::ReleaseDC (wnd, dc); ::DestroyWindow (wnd); ::UnregisterClass (MAKEINTATOM (atom), hInstance); } // Create the screen saver window. DWORD style; DWORD ex_style; int left, top, width, height; if (mode == embedded) { RECT rect; ::GetClientRect (parent, & rect); left = 0; top = 0; width = rect.right; height = rect.bottom; style = WS_CHILD | WS_VISIBLE; ex_style = 0; } else { left = ::GetSystemMetrics (SM_XVIRTUALSCREEN); top = ::GetSystemMetrics (SM_YVIRTUALSCREEN); width = ::GetSystemMetrics (SM_CXVIRTUALSCREEN); height = ::GetSystemMetrics (SM_CYVIRTUALSCREEN); style = WS_POPUP | WS_VISIBLE; ex_style = ((mode == fullscreen) ? WS_EX_TOPMOST : 0); } WNDCLASS wc; ::ZeroMemory (& wc, sizeof wc); wc.lpfnWndProc = & WndProc; wc.cbWndExtra = 8; wc.hInstance = hInstance; wc.hIcon = ::LoadIcon (hInstance, MAKEINTRESOURCE (257)); wc.lpszClassName = usr::window_class_name; ATOM atom = ::RegisterClass (& wc); if (! atom) return 1; window_struct_t ws ALIGNED16; ws.mode = mode; // HWND CreateWindowEx HWND hwnd = ::CreateWindowEx (ex_style, // (DWORD dwExStyle, MAKEINTATOM (atom), // LPCTSTR lpClassName, usr::window_name, // LPCTSTR lpWindowName, style, // DWORD dwStyle, left, // int x, top, // int y, width, // int nWidth, height, // int nHeight, parent, // HWND hWndParent, 0, // HMENU hMenu, hInstance, // HINSTANCE hInstance, & ws); // LPVOID lpParam); if (! hwnd) return 1; ws.hdc = ::GetDC (hwnd); if (! ws.hdc) return 1; int ilist [] = { WGL_DRAW_TO_WINDOW_ARB, GL_TRUE, WGL_SUPPORT_OPENGL_ARB, GL_TRUE, WGL_DOUBLE_BUFFER_ARB, GL_TRUE, WGL_ACCELERATION_ARB, WGL_FULL_ACCELERATION_ARB, WGL_SWAP_METHOD_ARB, WGL_SWAP_EXCHANGE_ARB, WGL_COLOR_BITS_ARB, 32, WGL_SAMPLE_BUFFERS_ARB, GL_TRUE, WGL_SAMPLES_ARB, 5, 0, 0, }; float flist [] = { 0, 0, }; enum { pfcountmax = 256 }; UINT pfcount; int pfs [pfcountmax]; bool status = wglChoosePixelFormatARB (ws.hdc, ilist, flist, pfcountmax, pfs, & pfcount); if (! (status && pfcount && pfcount < pfcountmax)) return 1; if (! ::SetPixelFormat (ws.hdc, pfs [0], 0)) return 1; ws.hglrc = ::wglCreateContext (ws.hdc); if (! ws.hglrc) return 1; if (! ::wglMakeCurrent (ws.hdc, ws.hglrc)) { ::wglDeleteContext (ws.hglrc); return 1; } LARGE_INTEGER pc; ::QueryPerformanceCounter (& pc); if (! ws.model.initialize (pc.QuadPart, ws.width, ws.height)) { return 1; } ::SetTimer (hwnd, IDT_TIMER, 10, nullptr); // Enter the main loop. MSG msg; BOOL bRet; while ((bRet = ::GetMessage (& msg, nullptr, 0, 0)) != 0) { if (bRet == -1) { // TODO: check error code return ::GetLastError (); } else { ::TranslateMessage (& msg); ::DispatchMessage (& msg); } } return (msg.message == WM_QUIT ? msg.wParam : 1); } <|endoftext|>
<commit_before>/* libvisio * Copyright (C) 2011 Fridrich Strba <fridrich.strba@bluewin.ch> * Copyright (C) 2011 Eilidh McAdam <tibbylickle@gmail.com> * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Library General Public * License as published by the Free Software Foundation; either * version 2 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Library General Public License for more details. * * You should have received a copy of the GNU Library General Public * License along with this library; if not, write to the * Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, * Boston, MA 02111-1301 USA */ #include <libwpd-stream/libwpd-stream.h> #include <locale.h> #include <sstream> #include <string> #include "libvisio_utils.h" #include "VSD11Parser.h" #include "VSDInternalStream.h" #include "VSDXDocumentStructure.h" #include "VSDXContentCollector.h" #include "VSDXStylesCollector.h" const libvisio::VSD11Parser::StreamHandler libvisio::VSD11Parser::streamHandlers[] = { {VSD_PAGE, "Page", &libvisio::VSD11Parser::handlePage}, {VSD_COLORS, "Colors", &libvisio::VSD11Parser::readColours}, {VSD_PAGES, "Pages", &libvisio::VSD11Parser::handlePages}, {0, 0, 0} }; const struct libvisio::VSD11Parser::ChunkHandler libvisio::VSD11Parser::chunkHandlers[] = { {VSD_SHAPE_GROUP, "ShapeType=\"Group\"", &libvisio::VSD11Parser::shapeChunk}, {VSD_SHAPE_SHAPE, "ShapeType=\"Shape\"", &libvisio::VSD11Parser::shapeChunk}, {VSD_SHAPE_FOREIGN, "ShapeType=\"Foreign\"", &libvisio::VSD11Parser::shapeChunk}, #if 0 {VSD_XFORM_DATA, "XForm Data", &libvisio::VSD11Parser::readXFormData}, {VSD_SHAPE_ID, "Shape Id", &libvisio::VSD11Parser::readShapeID}, {VSD_LINE, "Line", &libvisio::VSD11Parser::readLine}, {VSD_FILL_AND_SHADOW, "Fill and Shadow", &libvisio::VSD11Parser::readFillAndShadow}, {VSD_GEOM_LIST, "Geom List", &libvisio::VSD11Parser::readGeomList}, {VSD_GEOMETRY, "Geometry", &libvisio::VSD11Parser::readGeometry}, {VSD_MOVE_TO, "Move To", &libvisio::VSD11Parser::readMoveTo}, {VSD_LINE_TO, "Line To", &libvisio::VSD11Parser::readLineTo}, {VSD_ARC_TO, "Arc To", &libvisio::VSD11Parser::readArcTo}, {VSD_ELLIPSE, "Ellipse", &libvisio::VSD11Parser::readEllipse}, {VSD_ELLIPTICAL_ARC_TO, "Elliptical Arc To", &libvisio::VSD11Parser::readEllipticalArcTo}, {VSD_FOREIGN_DATA_TYPE, "Foreign Data Type", &libvisio::VSD11Parser::readForeignDataType}, {VSD_FOREIGN_DATA, "Foreign Data", &libvisio::VSD11Parser::readForeignData}, #endif {0, 0, 0} }; libvisio::VSD11Parser::VSD11Parser(WPXInputStream *input, libwpg::WPGPaintInterface *painter) : VSDXParser(input, painter) {} libvisio::VSD11Parser::~VSD11Parser() {} /** Parses VSD 2003 input stream content, making callbacks to functions provided by WPGPaintInterface class implementation as needed. \param iface A WPGPaintInterface implementation \return A value indicating whether parsing was successful */ bool libvisio::VSD11Parser::parse() { if (!m_input) { return false; } // Seek to trailer stream pointer m_input->seek(0x24, WPX_SEEK_SET); m_input->seek(8, WPX_SEEK_CUR); unsigned int offset = readU32(m_input); unsigned int length = readU32(m_input); unsigned short format = readU16(m_input); bool compressed = ((format & 2) == 2); m_input->seek(offset, WPX_SEEK_SET); WPXInputStream *trailerStream = new VSDInternalStream(m_input, length, compressed); /* VSDXStylesCollector stylesCollector; m_collector = &stylesCollector; if (!parseDocument(trailerStream)) { delete trailerStream; return false; } */ VSDXContentCollector contentCollector(m_painter); m_collector = &contentCollector; if (!parseDocument(trailerStream)) { delete trailerStream; return false; } delete trailerStream; return true; } bool libvisio::VSD11Parser::parseDocument(WPXInputStream *input) { const unsigned int SHIFT = 4; unsigned int ptrType; unsigned int ptrOffset; unsigned int ptrLength; unsigned int ptrFormat; // Parse out pointers to other streams from trailer input->seek(SHIFT, WPX_SEEK_SET); unsigned offset = readU32(input); input->seek(offset+SHIFT, WPX_SEEK_SET); unsigned int pointerCount = readU32(input); input->seek(SHIFT, WPX_SEEK_CUR); for (unsigned int i = 0; i < pointerCount; i++) { ptrType = readU32(input); input->seek(4, WPX_SEEK_CUR); // Skip dword ptrOffset = readU32(input); ptrLength = readU32(input); ptrFormat = readU16(input); int index = -1; for (int j = 0; (index < 0) && streamHandlers[j].type; j++) { if (streamHandlers[j].type == ptrType) index = j; } if (index < 0) { VSD_DEBUG_MSG(("Unknown stream pointer type 0x%02x found in trailer at %li\n", ptrType, input->tell() - 18)); } else { StreamMethod streamHandler = streamHandlers[index].handler; if (!streamHandler) VSD_DEBUG_MSG(("Stream '%s', type 0x%02x, format 0x%02x at %li ignored\n", streamHandlers[index].name, streamHandlers[index].type, ptrFormat, input->tell() - 18)); else { VSD_DEBUG_MSG(("Stream '%s', type 0x%02x, format 0x%02x at %li handled\n", streamHandlers[index].name, streamHandlers[index].type, ptrFormat, input->tell() - 18)); bool compressed = ((ptrFormat & 2) == 2); m_input->seek(ptrOffset, WPX_SEEK_SET); WPXInputStream *input = new VSDInternalStream(m_input, ptrLength, compressed); (this->*streamHandler)(input); delete input; } } } m_collector->endPage(); return true; } bool libvisio::VSD11Parser::getChunkHeader(WPXInputStream *input) { unsigned char tmpChar = 0; while (!input->atEOS() && !tmpChar) tmpChar = readU8(input); if (input->atEOS()) return false; else input->seek(-1, WPX_SEEK_CUR); m_header.chunkType = readU32(input); m_header.id = readU32(input); m_header.list = readU32(input); // Certain chunk types seem to always have a trailer m_header.trailer = 0; if (m_header.list != 0 || m_header.chunkType == 0x71 || m_header.chunkType == 0x70 || m_header.chunkType == 0x6b || m_header.chunkType == 0x6a || m_header.chunkType == 0x69 || m_header.chunkType == 0x66 || m_header.chunkType == 0x65 || m_header.chunkType == 0x2c) m_header.trailer += 8; // 8 byte trailer m_header.dataLength = readU32(input); m_header.level = readU16(input); m_header.unknown = readU8(input); // Add word separator under certain circumstances for v11 // Below are known conditions, may be more or a simpler pattern if (m_header.list != 0 || (m_header.level == 2 && m_header.unknown == 0x55) || (m_header.level == 2 && m_header.unknown == 0x54 && m_header.chunkType == 0xaa) || (m_header.level == 3 && m_header.unknown != 0x50 && m_header.unknown != 0x54) || m_header.chunkType == 0x69 || m_header.chunkType == 0x6a || m_header.chunkType == 0x6b || m_header.chunkType == 0x71 || m_header.chunkType == 0xb6 || m_header.chunkType == 0xb9 || m_header.chunkType == 0xa9 || m_header.chunkType == 0x92) { m_header.trailer += 4; } // 0x1f (OLE data) and 0xc9 (Name ID) never have trailer if (m_header.chunkType == 0x1f || m_header.chunkType == 0xc9) { m_header.trailer = 0; } return true; } void libvisio::VSD11Parser::handlePages(WPXInputStream *input) { unsigned int offset = readU32(input); input->seek(offset, WPX_SEEK_SET); unsigned int pointerCount = readU32(input); input->seek(4, WPX_SEEK_CUR); // Ignore 0x0 dword unsigned int ptrType; unsigned int ptrOffset; unsigned int ptrLength; unsigned int ptrFormat; for (unsigned int i = 0; i < pointerCount; i++) { ptrType = readU32(input); input->seek(4, WPX_SEEK_CUR); // Skip dword ptrOffset = readU32(input); ptrLength = readU32(input); ptrFormat = readU16(input); int index = -1; for (int j = 0; (index < 0) && streamHandlers[j].type; j++) { if (streamHandlers[j].type == ptrType) index = j; } if (index < 0) { VSD_DEBUG_MSG(("Unknown stream pointer type 0x%02x found in pages at %li\n", ptrType, input->tell() - 18)); } else { StreamMethod streamHandler = streamHandlers[index].handler; if (!streamHandler) VSD_DEBUG_MSG(("Stream '%s', type 0x%02x, format 0x%02x at %li ignored\n", streamHandlers[index].name, streamHandlers[index].type, ptrFormat, input->tell() - 18)); else { VSD_DEBUG_MSG(("Stream '%s', type 0x%02x, format 0x%02x at %li handled\n", streamHandlers[index].name, streamHandlers[index].type, ptrFormat, input->tell() - 18)); bool compressed = ((ptrFormat & 2) == 2); m_input->seek(ptrOffset, WPX_SEEK_SET); WPXInputStream *tmpInput = new VSDInternalStream(m_input, ptrLength, compressed); (this->*streamHandler)(tmpInput); delete tmpInput; } } } } void libvisio::VSD11Parser::handlePage(WPXInputStream *input) { long endPos = 0; m_collector->startPage(); while (!input->atEOS()) { if (!getChunkHeader(input)) break; endPos = m_header.dataLength+m_header.trailer+input->tell(); int index = -1; for (int i = 0; (index < 0) && chunkHandlers[i].type; i++) { if (chunkHandlers[i].type == m_header.chunkType) index = i; } if (index >= 0) { // Skip rest of this chunk input->seek(m_header.dataLength + m_header.trailer, WPX_SEEK_CUR); ChunkMethod chunkHandler = chunkHandlers[index].handler; if (chunkHandler) (this->*chunkHandler)(input); continue; } VSD_DEBUG_MSG(("Parsing chunk type %02x with trailer (%d) and length %x\n", m_header.chunkType, m_header.trailer, m_header.dataLength)); if (m_header.chunkType == VSD_PAGE_PROPS) readPageProps(input); input->seek(endPos, WPX_SEEK_SET); } } <commit_msg>Enable two passes (first one is still noop though)<commit_after>/* libvisio * Copyright (C) 2011 Fridrich Strba <fridrich.strba@bluewin.ch> * Copyright (C) 2011 Eilidh McAdam <tibbylickle@gmail.com> * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Library General Public * License as published by the Free Software Foundation; either * version 2 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Library General Public License for more details. * * You should have received a copy of the GNU Library General Public * License along with this library; if not, write to the * Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, * Boston, MA 02111-1301 USA */ #include <libwpd-stream/libwpd-stream.h> #include <locale.h> #include <sstream> #include <string> #include "libvisio_utils.h" #include "VSD11Parser.h" #include "VSDInternalStream.h" #include "VSDXDocumentStructure.h" #include "VSDXContentCollector.h" #include "VSDXStylesCollector.h" const libvisio::VSD11Parser::StreamHandler libvisio::VSD11Parser::streamHandlers[] = { {VSD_PAGE, "Page", &libvisio::VSD11Parser::handlePage}, {VSD_COLORS, "Colors", &libvisio::VSD11Parser::readColours}, {VSD_PAGES, "Pages", &libvisio::VSD11Parser::handlePages}, {0, 0, 0} }; const struct libvisio::VSD11Parser::ChunkHandler libvisio::VSD11Parser::chunkHandlers[] = { {VSD_SHAPE_GROUP, "ShapeType=\"Group\"", &libvisio::VSD11Parser::shapeChunk}, {VSD_SHAPE_SHAPE, "ShapeType=\"Shape\"", &libvisio::VSD11Parser::shapeChunk}, {VSD_SHAPE_FOREIGN, "ShapeType=\"Foreign\"", &libvisio::VSD11Parser::shapeChunk}, #if 0 {VSD_XFORM_DATA, "XForm Data", &libvisio::VSD11Parser::readXFormData}, {VSD_SHAPE_ID, "Shape Id", &libvisio::VSD11Parser::readShapeID}, {VSD_LINE, "Line", &libvisio::VSD11Parser::readLine}, {VSD_FILL_AND_SHADOW, "Fill and Shadow", &libvisio::VSD11Parser::readFillAndShadow}, {VSD_GEOM_LIST, "Geom List", &libvisio::VSD11Parser::readGeomList}, {VSD_GEOMETRY, "Geometry", &libvisio::VSD11Parser::readGeometry}, {VSD_MOVE_TO, "Move To", &libvisio::VSD11Parser::readMoveTo}, {VSD_LINE_TO, "Line To", &libvisio::VSD11Parser::readLineTo}, {VSD_ARC_TO, "Arc To", &libvisio::VSD11Parser::readArcTo}, {VSD_ELLIPSE, "Ellipse", &libvisio::VSD11Parser::readEllipse}, {VSD_ELLIPTICAL_ARC_TO, "Elliptical Arc To", &libvisio::VSD11Parser::readEllipticalArcTo}, {VSD_FOREIGN_DATA_TYPE, "Foreign Data Type", &libvisio::VSD11Parser::readForeignDataType}, {VSD_FOREIGN_DATA, "Foreign Data", &libvisio::VSD11Parser::readForeignData}, #endif {0, 0, 0} }; libvisio::VSD11Parser::VSD11Parser(WPXInputStream *input, libwpg::WPGPaintInterface *painter) : VSDXParser(input, painter) {} libvisio::VSD11Parser::~VSD11Parser() {} /** Parses VSD 2003 input stream content, making callbacks to functions provided by WPGPaintInterface class implementation as needed. \param iface A WPGPaintInterface implementation \return A value indicating whether parsing was successful */ bool libvisio::VSD11Parser::parse() { if (!m_input) { return false; } // Seek to trailer stream pointer m_input->seek(0x24, WPX_SEEK_SET); m_input->seek(8, WPX_SEEK_CUR); unsigned int offset = readU32(m_input); unsigned int length = readU32(m_input); unsigned short format = readU16(m_input); bool compressed = ((format & 2) == 2); m_input->seek(offset, WPX_SEEK_SET); WPXInputStream *trailerStream = new VSDInternalStream(m_input, length, compressed); VSDXStylesCollector stylesCollector; m_collector = &stylesCollector; if (!parseDocument(trailerStream)) { delete trailerStream; return false; } VSDXContentCollector contentCollector(m_painter); m_collector = &contentCollector; if (!parseDocument(trailerStream)) { delete trailerStream; return false; } delete trailerStream; return true; } bool libvisio::VSD11Parser::parseDocument(WPXInputStream *input) { const unsigned int SHIFT = 4; unsigned int ptrType; unsigned int ptrOffset; unsigned int ptrLength; unsigned int ptrFormat; // Parse out pointers to other streams from trailer input->seek(SHIFT, WPX_SEEK_SET); unsigned offset = readU32(input); input->seek(offset+SHIFT, WPX_SEEK_SET); unsigned int pointerCount = readU32(input); input->seek(SHIFT, WPX_SEEK_CUR); for (unsigned int i = 0; i < pointerCount; i++) { ptrType = readU32(input); input->seek(4, WPX_SEEK_CUR); // Skip dword ptrOffset = readU32(input); ptrLength = readU32(input); ptrFormat = readU16(input); int index = -1; for (int j = 0; (index < 0) && streamHandlers[j].type; j++) { if (streamHandlers[j].type == ptrType) index = j; } if (index < 0) { VSD_DEBUG_MSG(("Unknown stream pointer type 0x%02x found in trailer at %li\n", ptrType, input->tell() - 18)); } else { StreamMethod streamHandler = streamHandlers[index].handler; if (!streamHandler) VSD_DEBUG_MSG(("Stream '%s', type 0x%02x, format 0x%02x at %li ignored\n", streamHandlers[index].name, streamHandlers[index].type, ptrFormat, input->tell() - 18)); else { VSD_DEBUG_MSG(("Stream '%s', type 0x%02x, format 0x%02x at %li handled\n", streamHandlers[index].name, streamHandlers[index].type, ptrFormat, input->tell() - 18)); bool compressed = ((ptrFormat & 2) == 2); m_input->seek(ptrOffset, WPX_SEEK_SET); WPXInputStream *input = new VSDInternalStream(m_input, ptrLength, compressed); (this->*streamHandler)(input); delete input; } } } m_collector->endPage(); return true; } bool libvisio::VSD11Parser::getChunkHeader(WPXInputStream *input) { unsigned char tmpChar = 0; while (!input->atEOS() && !tmpChar) tmpChar = readU8(input); if (input->atEOS()) return false; else input->seek(-1, WPX_SEEK_CUR); m_header.chunkType = readU32(input); m_header.id = readU32(input); m_header.list = readU32(input); // Certain chunk types seem to always have a trailer m_header.trailer = 0; if (m_header.list != 0 || m_header.chunkType == 0x71 || m_header.chunkType == 0x70 || m_header.chunkType == 0x6b || m_header.chunkType == 0x6a || m_header.chunkType == 0x69 || m_header.chunkType == 0x66 || m_header.chunkType == 0x65 || m_header.chunkType == 0x2c) m_header.trailer += 8; // 8 byte trailer m_header.dataLength = readU32(input); m_header.level = readU16(input); m_header.unknown = readU8(input); // Add word separator under certain circumstances for v11 // Below are known conditions, may be more or a simpler pattern if (m_header.list != 0 || (m_header.level == 2 && m_header.unknown == 0x55) || (m_header.level == 2 && m_header.unknown == 0x54 && m_header.chunkType == 0xaa) || (m_header.level == 3 && m_header.unknown != 0x50 && m_header.unknown != 0x54) || m_header.chunkType == 0x69 || m_header.chunkType == 0x6a || m_header.chunkType == 0x6b || m_header.chunkType == 0x71 || m_header.chunkType == 0xb6 || m_header.chunkType == 0xb9 || m_header.chunkType == 0xa9 || m_header.chunkType == 0x92) { m_header.trailer += 4; } // 0x1f (OLE data) and 0xc9 (Name ID) never have trailer if (m_header.chunkType == 0x1f || m_header.chunkType == 0xc9) { m_header.trailer = 0; } return true; } void libvisio::VSD11Parser::handlePages(WPXInputStream *input) { unsigned int offset = readU32(input); input->seek(offset, WPX_SEEK_SET); unsigned int pointerCount = readU32(input); input->seek(4, WPX_SEEK_CUR); // Ignore 0x0 dword unsigned int ptrType; unsigned int ptrOffset; unsigned int ptrLength; unsigned int ptrFormat; for (unsigned int i = 0; i < pointerCount; i++) { ptrType = readU32(input); input->seek(4, WPX_SEEK_CUR); // Skip dword ptrOffset = readU32(input); ptrLength = readU32(input); ptrFormat = readU16(input); int index = -1; for (int j = 0; (index < 0) && streamHandlers[j].type; j++) { if (streamHandlers[j].type == ptrType) index = j; } if (index < 0) { VSD_DEBUG_MSG(("Unknown stream pointer type 0x%02x found in pages at %li\n", ptrType, input->tell() - 18)); } else { StreamMethod streamHandler = streamHandlers[index].handler; if (!streamHandler) VSD_DEBUG_MSG(("Stream '%s', type 0x%02x, format 0x%02x at %li ignored\n", streamHandlers[index].name, streamHandlers[index].type, ptrFormat, input->tell() - 18)); else { VSD_DEBUG_MSG(("Stream '%s', type 0x%02x, format 0x%02x at %li handled\n", streamHandlers[index].name, streamHandlers[index].type, ptrFormat, input->tell() - 18)); bool compressed = ((ptrFormat & 2) == 2); m_input->seek(ptrOffset, WPX_SEEK_SET); WPXInputStream *tmpInput = new VSDInternalStream(m_input, ptrLength, compressed); (this->*streamHandler)(tmpInput); delete tmpInput; } } } } void libvisio::VSD11Parser::handlePage(WPXInputStream *input) { long endPos = 0; m_collector->startPage(); while (!input->atEOS()) { if (!getChunkHeader(input)) break; endPos = m_header.dataLength+m_header.trailer+input->tell(); int index = -1; for (int i = 0; (index < 0) && chunkHandlers[i].type; i++) { if (chunkHandlers[i].type == m_header.chunkType) index = i; } if (index >= 0) { // Skip rest of this chunk input->seek(m_header.dataLength + m_header.trailer, WPX_SEEK_CUR); ChunkMethod chunkHandler = chunkHandlers[index].handler; if (chunkHandler) (this->*chunkHandler)(input); continue; } VSD_DEBUG_MSG(("Parsing chunk type %02x with trailer (%d) and length %x\n", m_header.chunkType, m_header.trailer, m_header.dataLength)); if (m_header.chunkType == VSD_PAGE_PROPS) readPageProps(input); input->seek(endPos, WPX_SEEK_SET); } } <|endoftext|>
<commit_before>#include <iostream> #include <algorithm> #include <sstream> #include <cctype> #include <clocale> #include <string> #include <vector> #include <list> #include <stdio.h> #include <stdlib.h> #include <unistd.h> #include <sys/stat.h> #include <sys/types.h> #include <sys/wait.h> #include <stack> #include <string.h> #include <netdb.h> #include <pwd.h> #include <sys/socket.h> #include <boost/algorithm/string.hpp> using namespace std; using namespace boost::algorithm; //Virtual Base Class - Ammar class Base { public: Base(){}; //Function Inherited by each class - Ammar virtual bool evaluate() = 0; }; class Test{ private: int flagNum; public: // filetype found bool found; // format args Test(vector<string> argsTest){ if (argsTest[0] =="-e") { argsTest.erase(argsTest.begin()); flagNum =1; } else if (argsTest[0] =="-f") { argsTest.erase(argsTest.begin()); flagNum =2; } else if (argsTest[0] =="-d") { argsTest.erase(argsTest.begin()); flagNum =3; } else{ flagNum = 1; } vector<char *> charVec; charVec.push_back(const_cast<char *>(argsTest[0].c_str())); charVec.push_back(('\0')); char** charVec_two = &charVec[0]; struct stat statStruct; if(stat(const_cast<char *>(charVec[0]), &statStruct)<0){ // testing if file was located found = 1; } else{ if (flagNum == 1) { found = true; } else if(flagNum == 2) { (S_ISREG(statStruct.st_mode)) ? found = 1 : found = 0; } else if (flagNum == 3) { (S_ISDIR(statStruct.st_mode)) ? found = 1 : found = 0; } else { cout << "Error" << endl; } } } }; // Command Class that each command will inherit from - Ammar class Command : public Base { private: //Vector of commands - Ammar vector<string> commandVec; public: //Contructor to take in vector and set it to commands vectors Command(vector<string>s){ commandVec = s; } bool evaluate(){ //exit if cmd is "exit" if(commandVec[0] == "exit") { //Program stops if input is "exit" - Ammar exit(0); } //this chunk is to format the vector in the way we want it vector<char *> temp2; for(unsigned int i = 0; i < commandVec.size(); i++) { temp2.push_back(const_cast<char *>(commandVec[i].c_str())); } temp2.push_back('\0'); //'\0 is to make sure there is a null char in c-str' char** arrChar = &temp2[0]; //here we will use fork() so we can do multiple process at once int status; pid_t pid = fork(); if (pid < 0) { //to chck if fork failed perror("FAILED"); exit(1); } else if (pid == 0) { //if it reaches here, you can pass into execvp //execvp will do all the work for you execvp(const_cast<char *>(arrChar[0]), arrChar); //if it reaches here there is some error exit(127); // exit 127 "command not found" } else if(pid > 0){ //have to wait until child finishes // use wait pid or wait ???? waitpid(pid, &status, 0); wait(&status); if(wait(&status) != -1){ perror("ERROR: wait"); } if(WIFEXITED(status)){ if(WEXITSTATUS(status) == 0) { //program is succesful return true; } else { //this return is false, then the program failed but exiting was normal return false; } } else { //the program messed up and exited abnormally perror("EXIT: ABNORMAL CHILD"); return false; } } return false; } }; class Connectors : public Base { public: Connectors(){}; protected: bool leftCommand; //command b4 the connector Base* rightCommand; //command @ft3r the connect0r }; //will always attempt to run rightCommand class Semicolon : public Connectors { public: Semicolon(bool l, Base* r){ leftCommand = l; rightCommand = r; } bool evaluate() { return rightCommand->evaluate(); } }; //will run the rightcommand if leftcommand succededs class And : public Connectors{ public: And(bool l, Base* r){ leftCommand = l; rightCommand = r; } bool evaluate(){ if(leftCommand) return rightCommand->evaluate(); return false; } }; //will run the rightCommand if the LeftCommand fails class Or : public Connectors{ public: Or(bool l, Base* r){ leftCommand = l; rightCommand = r; } //Return if it evaluated or not bool evaluate(){ if(!leftCommand) return rightCommand->evaluate(); return false; } }; //This Function takes the user input and parses it returns us a vector of strings - Ammar vector<string> parser(string toSplit, const char* delimiters) { char* toTokenize = new char[toSplit.size() + 1]; strcpy(toTokenize, toSplit.c_str()); toTokenize[toSplit.size() + 1] = '\0'; char* cutThis; //begin parsing cutThis = strtok(toTokenize, delimiters); vector<string> returnThis; while (cutThis != NULL) { string currWord(cutThis); trim(currWord); returnThis.push_back(currWord); cutThis = strtok(NULL, delimiters); } return returnThis; } unsigned perEnds(string commandInput, int a){ stack<char> charStack; int i =a; charStack.push('f'); i++; for(int i=0; i < commandInput.size(); i++) { if(commandInput.at(i)== '('){ charStack.push('('); } else if(commandInput.at(i) == ')'){ char open = charStack.top(); charStack.pop(); if(charStack.empty() && open =='f') { return i; } } } return i; } string parsePer(string commandInput){ stack<char> charStack; bool isBool = 0; do{ trim(commandInput); if(commandInput.find('(') !=0){ return commandInput; } else if(perEnds(commandInput, 0) == commandInput.size()-1){ commandInput.erase(0,1); commandInput.erase(commandInput.size()-1); if(perEnds(commandInput, 0)== commandInput.size()-1){ isBool = 1; } else{ return commandInput; } } else{ return commandInput; } } while(isBool == 1); return commandInput; } void perCheck(string commandInput){ stack<char> charStack; for(int i =0; i < commandInput.size();i++) { if(commandInput.at(i)== '('){ charStack.push('('); } else if(commandInput.at(i)== ')'){ if(!charStack.empty()){ charStack.pop(); } else{ cout << "Error"; exit(0); } } } if(!charStack.empty()){ cout << "Error"; exit(0); } } class Chunks:public Base{ private: string commandInput; vector<bool> track; bool isNested; public: bool evaluate() { return 0; } } int main () { string commandInput = ""; string formattedInput; vector<string> v; Base* theLine; while (true) { string login = getlogin(); char hostname[100]; gethostname(hostname, 100); cout << "[" << login << "@" << hostname << "] $ "; getline(cin, commandInput); trim(commandInput); theLine = new Line(commandInput); vector<string> parsedVector; if ((commandInput.find("(") != string::npos) && (commandInput.find(")") != string::npos)) { //there is precedence string command; for (unsigned int i = 0; i < commandInput.size(); ++i) { if (commandInput.at(i) == '&' && i != commandInput.size() - 1) { if (commandInput.at(i + 1) == '&') { parsedVector.push_back(command); command = ""; parsedVector.push_back("&&"); } } else if (commandInput.at(i) == '|' && i != commandInput.size() - 1) { if (commandInput.at(i + 1) == '|') { parsedVector.push_back(command); command = ""; parsedVector.push_back("||"); } } else if (commandInput.at(i) == ';') { parsedVector.push_back(command); command = ""; parsedVector.push_back(";"); } else { command += commandInput.at(i); } } printVec(parsedVector); vector<string> postfix; //infix2postfix(parsedVector, postfix); //printVec(postfix); } else { theLine->evaluate(); } } return 0; } <commit_msg>Update main.cpp<commit_after>#include <iostream> #include <algorithm> #include <sstream> #include <cctype> #include <clocale> #include <string> #include <vector> #include <list> #include <stdio.h> #include <stdlib.h> #include <unistd.h> #include <sys/stat.h> #include <sys/types.h> #include <sys/wait.h> #include <stack> #include <string.h> #include <netdb.h> #include <pwd.h> #include <sys/socket.h> #include <boost/algorithm/string.hpp> using namespace std; using namespace boost::algorithm; //Virtual Base Class - Ammar class Base { public: Base(){}; //Function Inherited by each class - Ammar virtual bool evaluate() = 0; }; class Test{ private: int flagNum; public: // filetype found bool found; // format args Test(vector<string> argsTest){ if (argsTest[0] =="-e") { argsTest.erase(argsTest.begin()); flagNum =1; } else if (argsTest[0] =="-f") { argsTest.erase(argsTest.begin()); flagNum =2; } else if (argsTest[0] =="-d") { argsTest.erase(argsTest.begin()); flagNum =3; } else{ flagNum = 1; } vector<char *> charVec; charVec.push_back(const_cast<char *>(argsTest[0].c_str())); charVec.push_back(('\0')); char** charVec_two = &charVec[0]; struct stat statStruct; if(stat(const_cast<char *>(charVec[0]), &statStruct)<0){ // testing if file was located found = 1; } else{ if (flagNum == 1) { found = true; } else if(flagNum == 2) { (S_ISREG(statStruct.st_mode)) ? found = 1 : found = 0; } else if (flagNum == 3) { (S_ISDIR(statStruct.st_mode)) ? found = 1 : found = 0; } else { cout << "Error" << endl; } } } }; // Command Class that each command will inherit from - Ammar class Command : public Base { private: //Vector of commands - Ammar vector<string> commandVec; public: //Contructor to take in vector and set it to commands vectors Command(vector<string>s){ commandVec = s; } bool evaluate(){ //exit if cmd is "exit" if(commandVec[0] == "exit") { //Program stops if input is "exit" - Ammar exit(0); } //this chunk is to format the vector in the way we want it vector<char *> temp2; for(unsigned int i = 0; i < commandVec.size(); i++) { temp2.push_back(const_cast<char *>(commandVec[i].c_str())); } temp2.push_back('\0'); //'\0 is to make sure there is a null char in c-str' char** arrChar = &temp2[0]; //here we will use fork() so we can do multiple process at once int status; pid_t pid = fork(); if (pid < 0) { //to chck if fork failed perror("FAILED"); exit(1); } else if (pid == 0) { //if it reaches here, you can pass into execvp //execvp will do all the work for you execvp(const_cast<char *>(arrChar[0]), arrChar); //if it reaches here there is some error exit(127); // exit 127 "command not found" } else if(pid > 0){ //have to wait until child finishes // use wait pid or wait ???? waitpid(pid, &status, 0); wait(&status); if(wait(&status) != -1){ perror("ERROR: wait"); } if(WIFEXITED(status)){ if(WEXITSTATUS(status) == 0) { //program is succesful return true; } else { //this return is false, then the program failed but exiting was normal return false; } } else { //the program messed up and exited abnormally perror("EXIT: ABNORMAL CHILD"); return false; } } return false; } }; class Connectors : public Base { public: Connectors(){}; protected: bool leftCommand; //command b4 the connector Base* rightCommand; //command @ft3r the connect0r }; //will always attempt to run rightCommand class Semicolon : public Connectors { public: Semicolon(bool l, Base* r){ leftCommand = l; rightCommand = r; } bool evaluate() { return rightCommand->evaluate(); } }; //will run the rightcommand if leftcommand succededs class And : public Connectors{ public: And(bool l, Base* r){ leftCommand = l; rightCommand = r; } bool evaluate(){ if(leftCommand) return rightCommand->evaluate(); return false; } }; //will run the rightCommand if the LeftCommand fails class Or : public Connectors{ public: Or(bool l, Base* r){ leftCommand = l; rightCommand = r; } //Return if it evaluated or not bool evaluate(){ if(!leftCommand) return rightCommand->evaluate(); return false; } }; //This Function takes the user input and parses it returns us a vector of strings - Ammar vector<string> parser(string toSplit, const char* delimiters) { char* toTokenize = new char[toSplit.size() + 1]; strcpy(toTokenize, toSplit.c_str()); toTokenize[toSplit.size() + 1] = '\0'; char* cutThis; //begin parsing cutThis = strtok(toTokenize, delimiters); vector<string> returnThis; while (cutThis != NULL) { string currWord(cutThis); trim(currWord); returnThis.push_back(currWord); cutThis = strtok(NULL, delimiters); } return returnThis; } unsigned perEnds(string commandInput, int a){ stack<char> charStack; int i =a; charStack.push('f'); i++; for(int i=0; i < commandInput.size(); i++) { if(commandInput.at(i)== '('){ charStack.push('('); } else if(commandInput.at(i) == ')'){ char open = charStack.top(); charStack.pop(); if(charStack.empty() && open =='f') { return i; } } } return i; } string parsePer(string commandInput){ stack<char> charStack; bool isBool = 0; do{ trim(commandInput); if(commandInput.find('(') !=0){ return commandInput; } else if(perEnds(commandInput, 0) == commandInput.size()-1){ commandInput.erase(0,1); commandInput.erase(commandInput.size()-1); if(perEnds(commandInput, 0)== commandInput.size()-1){ isBool = 1; } else{ return commandInput; } } else{ return commandInput; } } while(isBool == 1); return commandInput; } void perCheck(string commandInput){ stack<char> charStack; for(int i =0; i < commandInput.size();i++) { if(commandInput.at(i)== '('){ charStack.push('('); } else if(commandInput.at(i)== ')'){ if(!charStack.empty()){ charStack.pop(); } else{ cout << "Error"; exit(0); } } } if(!charStack.empty()){ cout << "Error"; exit(0); } } class Chunks:public Base{ private: string commandInput; vector<bool> track; bool isNested; public: bool evaluate() { trim(commandInput); commandInput = parsePer(commandInput); if(commandInput == ""){ return 1; } isNested = 0; for(int i =0;i<commandInput.size();i++){ if(commandInput.at(i)=='('){ isNested =1; } } return 0; } } int main () { string commandInput = ""; string formattedInput; vector<string> v; Base* theLine; while (true) { string login = getlogin(); char hostname[100]; gethostname(hostname, 100); cout << "[" << login << "@" << hostname << "] $ "; getline(cin, commandInput); trim(commandInput); theLine = new Line(commandInput); vector<string> parsedVector; if ((commandInput.find("(") != string::npos) && (commandInput.find(")") != string::npos)) { //there is precedence string command; for (unsigned int i = 0; i < commandInput.size(); ++i) { if (commandInput.at(i) == '&' && i != commandInput.size() - 1) { if (commandInput.at(i + 1) == '&') { parsedVector.push_back(command); command = ""; parsedVector.push_back("&&"); } } else if (commandInput.at(i) == '|' && i != commandInput.size() - 1) { if (commandInput.at(i + 1) == '|') { parsedVector.push_back(command); command = ""; parsedVector.push_back("||"); } } else if (commandInput.at(i) == ';') { parsedVector.push_back(command); command = ""; parsedVector.push_back(";"); } else { command += commandInput.at(i); } } printVec(parsedVector); vector<string> postfix; //infix2postfix(parsedVector, postfix); //printVec(postfix); } else { theLine->evaluate(); } } return 0; } <|endoftext|>
<commit_before><commit_msg>Modify search engine dialog to only appear if the user does not have an existing preferences file.<commit_after><|endoftext|>
<commit_before><commit_msg>scanner cleanup for consistency<commit_after><|endoftext|>
<commit_before><commit_msg>janitorial: c++-style cast<commit_after><|endoftext|>
<commit_before>/* This source file is part of the Tomviz project, https://tomviz.org/. It is released under the 3-Clause BSD License, see "LICENSE". */ #include "AnimationHelperDialog.h" #include "ui_AnimationHelperDialog.h" #include "ActiveObjects.h" #include "ContourAnimation.h" #include "ModuleManager.h" #include "Utilities.h" #include <pqAnimationCue.h> #include <pqAnimationManager.h> #include <pqAnimationScene.h> #include <pqPVApplicationCore.h> #include <pqPropertyLinks.h> #include <pqRenderView.h> #include <pqSMAdaptor.h> #include <QPointer> #include <QPushButton> #include <QSignalBlocker> #include <QTimer> #include <QDebug> namespace tomviz { class AnimationHelperDialog::Internal : public QObject { public: Ui::AnimationHelperDialog ui; pqPropertyLinks pqLinks; QPointer<AnimationHelperDialog> parent; QList<QPointer<ModuleAnimation>> moduleAnimations; Internal(AnimationHelperDialog* p) : QObject(p), parent(p) { // Must call setupUi() before using p in any way ui.setupUi(p); // We will change tabs automatically ui.modulesTabWidget->tabBar()->hide(); updateGui(); setupConnections(); } void setupConnections() { // Camera animations connect(ui.clearCameraAnimations, &QPushButton::clicked, this, &Internal::clearCameraAnimations); connect(ui.createCameraOrbit, &QPushButton::clicked, this, &Internal::createCameraOrbitInternal); // Time series connect(&activeObjects(), &ActiveObjects::timeSeriesAnimationsEnableStateChanged, ui.enableTimeSeriesAnimations, &QCheckBox::setChecked); connect(ui.enableTimeSeriesAnimations, &QCheckBox::toggled, &activeObjects(), &ActiveObjects::enableTimeSeriesAnimations); connect(ui.enableTimeSeriesAnimations, &QCheckBox::toggled, this, &Internal::updateEnableStates); // Modules connect(&moduleManager(), &ModuleManager::dataSourceAdded, this, &Internal::onDataSourceAdded); connect(&moduleManager(), &ModuleManager::dataSourceRemoved, this, &Internal::onDataSourceRemoved); connect(ui.selectedDataSource, QOverload<int>::of(&QComboBox::currentIndexChanged), this, &Internal::selectedDataSourceChanged); connect(&moduleManager(), &ModuleManager::moduleAdded, this, &Internal::updateModuleOptions); connect(&moduleManager(), &ModuleManager::moduleRemoved, this, &Internal::updateModuleOptions); connect(ui.selectedModule, QOverload<int>::of(&QComboBox::currentIndexChanged), this, &Internal::selectedModuleChanged); connect(ui.addModuleAnimation, &QPushButton::clicked, this, &Internal::addModuleAnimation); connect(ui.clearModuleAnimations, &QPushButton::clicked, this, &Internal::clearModuleAnimations); // All animations pqLinks.addPropertyLink(ui.numberOfFrames, "value", SIGNAL(valueChanged(int)), scene()->getProxy(), scene()->getProxy()->GetProperty("NumberOfFrames"), 0); connect(ui.numberOfFrames, QOverload<int>::of(&QSpinBox::valueChanged), this, &Internal::numberOfFramesModified); connect(ui.clearAllAnimations, &QPushButton::clicked, this, &Internal::clearAllAnimations); } void updateGui() { ui.enableTimeSeriesAnimations->setChecked( activeObjects().timeSeriesAnimationsEnabled()); updateDataSourceOptions(); updateEnableStates(); } void updateEnableStates() { bool hasCameraAnimations = false; for (auto* cue : scene()->getCues()) { if (cue->getSMName().startsWith("CameraAnimationCue")) { hasCameraAnimations = true; break; } } bool hasTimeSeries = false; for (auto* ds : moduleManager().allDataSources()) { if (ds->hasTimeSteps()) { hasTimeSeries = true; break; } } bool timeSeriesEnabled = ui.enableTimeSeriesAnimations->isChecked() && hasTimeSeries; bool hasDataSourceOptions = ui.selectedDataSource->count() != 0; bool hasModuleOptions = ui.selectedModule->count() != 0; bool moduleSelected = selectedModule() != nullptr; bool hasModuleAnimations = !moduleAnimations.empty(); bool hasAnyAnimations = hasCameraAnimations || timeSeriesEnabled || hasModuleAnimations; ui.clearCameraAnimations->setEnabled(hasCameraAnimations); ui.enableTimeSeriesAnimations->setEnabled(hasTimeSeries); ui.addModuleAnimation->setEnabled(moduleSelected); ui.selectedDataSource->setEnabled(hasDataSourceOptions); ui.selectedModule->setEnabled(hasModuleOptions); ui.clearModuleAnimations->setEnabled(hasModuleAnimations); ui.clearAllAnimations->setEnabled(hasAnyAnimations); } // Camera void clearCameraAnimations() { clearCameraCues(); updateEnableStates(); } void createCameraOrbitInternal() { auto* renderView = activeObjects().activePqRenderView(); // Remove all previous camera cues, and create the orbit clearCameraCues(renderView->getRenderViewProxy()); createCameraOrbit(renderView->getRenderViewProxy()); updateEnableStates(); } QStringList moduleTabTexts() { QStringList types; for (int i = 0; i < ui.modulesTabWidget->count(); ++i) { types.append(ui.modulesTabWidget->tabText(i)); } return types; } QStringList allowedModuleTypes() { // This is based upon tab texts return moduleTabTexts(); } // Data sources void updateDataSourceOptions() { QSignalBlocker blocked(ui.selectedDataSource); auto* previouslySelected = selectedDataSource(); int previouslySelectedIndex = -1; ui.selectedDataSource->clear(); auto& manager = moduleManager(); auto dataSources = manager.allDataSourcesDepthFirst(); auto labels = manager.createUniqueLabels(dataSources); for (int i = 0; i < dataSources.size(); ++i) { auto* dataSource = dataSources[i]; auto label = labels[i]; QVariant data; data.setValue(dataSource); ui.selectedDataSource->addItem(label, data); if (dataSource == previouslySelected) { previouslySelectedIndex = i; } } if (previouslySelectedIndex != -1) { ui.selectedDataSource->setCurrentIndex(previouslySelectedIndex); } else { selectedDataSourceChanged(); } updateEnableStates(); } DataSource* selectedDataSource() { if (ui.selectedDataSource->count() == 0) { return nullptr; } return ui.selectedDataSource->currentData().value<DataSource*>(); } // Modules void updateModuleOptions() { QSignalBlocker blocked(ui.selectedModule); auto* previouslySelected = selectedModule(); int previouslySelectedIndex = -1; ui.selectedModule->clear(); auto* dataSource = selectedDataSource(); if (!dataSource) { return; } auto& manager = moduleManager(); QStringList labels; QList<Module*> modules; auto allowedTypes = allowedModuleTypes(); for (auto* module : manager.findModulesGeneric(dataSource, nullptr)) { if (allowedTypes.contains(module->label())) { modules.append(module); int i = 1; auto label = module->label(); while (labels.contains(label)) { label = module->label() + " " + QString::number(++i); } labels.append(label); } } for (int i = 0; i < modules.size(); ++i) { auto* module = modules[i]; auto label = labels[i]; QVariant data; data.setValue(module); ui.selectedModule->addItem(label, data); if (module == previouslySelected) { previouslySelectedIndex = i; } } if (previouslySelectedIndex != -1) { ui.selectedModule->setCurrentIndex(previouslySelectedIndex); } else { selectedModuleChanged(); } updateEnableStates(); } Module* selectedModule() { if (ui.selectedModule->count() == 0) { return nullptr; } return ui.selectedModule->currentData().value<Module*>(); } void selectedDataSourceChanged() { updateModuleOptions(); } void selectedModuleChanged() { // Show animation options for the selected module auto* module = selectedModule(); auto tabIndex = 0; if (module) { tabIndex = moduleTabTexts().indexOf(module->label()); } ui.modulesTabWidget->setCurrentIndex(tabIndex); if (qobject_cast<ModuleContour*>(module)) { setupContourTab(); } updateEnableStates(); } void onDataSourceAdded() { // This is done later because when the dataSourceAdded // signal gets emitted, the data source does not yet have a label, // but it gets added later. It appears to have the label, though, // if we simple post this to the event loop to be performed later. QTimer::singleShot(0, this, &Internal::updateDataSourceOptions); updateEnableStates(); } void onDataSourceRemoved() { updateDataSourceOptions(); updateEnableStates(); } void setupContourTab() { auto* module = qobject_cast<ModuleContour*>(selectedModule()); double range[2]; module->isoRange(range); ui.contourStart->setMinimum(range[0]); ui.contourStart->setMaximum(range[1]); ui.contourStop->setMinimum(range[0]); ui.contourStop->setMaximum(range[1]); // Set reasonable default values ui.contourStart->setValue((range[1] - range[0]) / 3 + range[0]); ui.contourStop->setValue((range[1] - range[0]) * 2 / 3 + range[0]); } void addModuleAnimation() { auto* module = selectedModule(); if (!module) { return; } for (int i = 0; i < moduleAnimations.size(); ++i) { if (module == moduleAnimations[i]->baseModule) { // We only allow one animation per module // Remove the old one moduleAnimations[i]->deleteLater(); moduleAnimations.removeAt(i); --i; } } if (qobject_cast<ModuleContour*>(module)) { addContourAnimation(); } else { qDebug() << "Unknown module type: " << module; } updateEnableStates(); } void addContourAnimation() { auto start = ui.contourStart->value(); auto stop = ui.contourStop->value(); auto* module = qobject_cast<ModuleContour*>(selectedModule()); moduleAnimations.append(new ContourAnimation(module, start, stop)); } void clearModuleAnimations() { for (auto animation : moduleAnimations) { animation->deleteLater(); } moduleAnimations.clear(); updateEnableStates(); } // All animations void numberOfFramesModified() { // The number of frames only makes sense if the play mode is a sequence. // If the user modified the number of frames, set the play mode to // sequence. pqSMAdaptor::setEnumerationProperty( scene()->getProxy()->GetProperty("PlayMode"), "Sequence"); } void clearAllAnimations() { clearCameraAnimations(); if (ui.enableTimeSeriesAnimations->isEnabled()) { ui.enableTimeSeriesAnimations->setChecked(false); } clearModuleAnimations(); updateEnableStates(); } ActiveObjects& activeObjects() { return ActiveObjects::instance(); } ModuleManager& moduleManager() { return ModuleManager::instance(); } pqAnimationScene* scene() { return pqPVApplicationCore::instance() ->animationManager() ->getActiveScene(); } }; // end class Internal AnimationHelperDialog::AnimationHelperDialog(QWidget* parent) : QDialog(parent), m_internal(new Internal(this)) { } AnimationHelperDialog::~AnimationHelperDialog() = default; } // namespace tomviz <commit_msg>Automatically play when animation is added<commit_after>/* This source file is part of the Tomviz project, https://tomviz.org/. It is released under the 3-Clause BSD License, see "LICENSE". */ #include "AnimationHelperDialog.h" #include "ui_AnimationHelperDialog.h" #include "ActiveObjects.h" #include "ContourAnimation.h" #include "ModuleManager.h" #include "Utilities.h" #include <pqAnimationCue.h> #include <pqAnimationManager.h> #include <pqAnimationScene.h> #include <pqPVApplicationCore.h> #include <pqPropertyLinks.h> #include <pqRenderView.h> #include <pqSMAdaptor.h> #include <QPointer> #include <QPushButton> #include <QSignalBlocker> #include <QTimer> #include <QDebug> namespace tomviz { class AnimationHelperDialog::Internal : public QObject { public: Ui::AnimationHelperDialog ui; pqPropertyLinks pqLinks; QPointer<AnimationHelperDialog> parent; QList<QPointer<ModuleAnimation>> moduleAnimations; Internal(AnimationHelperDialog* p) : QObject(p), parent(p) { // Must call setupUi() before using p in any way ui.setupUi(p); // We will change tabs automatically ui.modulesTabWidget->tabBar()->hide(); updateGui(); setupConnections(); } void setupConnections() { // Camera animations connect(ui.clearCameraAnimations, &QPushButton::clicked, this, &Internal::clearCameraAnimations); connect(ui.createCameraOrbit, &QPushButton::clicked, this, &Internal::createCameraOrbitInternal); // Time series connect(&activeObjects(), &ActiveObjects::timeSeriesAnimationsEnableStateChanged, ui.enableTimeSeriesAnimations, &QCheckBox::setChecked); connect(ui.enableTimeSeriesAnimations, &QCheckBox::toggled, &activeObjects(), &ActiveObjects::enableTimeSeriesAnimations); connect(ui.enableTimeSeriesAnimations, &QCheckBox::toggled, this, [this](bool b) { updateEnableStates(); if (b) { play(); } }); // Modules connect(&moduleManager(), &ModuleManager::dataSourceAdded, this, &Internal::onDataSourceAdded); connect(&moduleManager(), &ModuleManager::dataSourceRemoved, this, &Internal::onDataSourceRemoved); connect(ui.selectedDataSource, QOverload<int>::of(&QComboBox::currentIndexChanged), this, &Internal::selectedDataSourceChanged); connect(&moduleManager(), &ModuleManager::moduleAdded, this, &Internal::updateModuleOptions); connect(&moduleManager(), &ModuleManager::moduleRemoved, this, &Internal::updateModuleOptions); connect(ui.selectedModule, QOverload<int>::of(&QComboBox::currentIndexChanged), this, &Internal::selectedModuleChanged); connect(ui.addModuleAnimation, &QPushButton::clicked, this, &Internal::addModuleAnimation); connect(ui.clearModuleAnimations, &QPushButton::clicked, this, &Internal::clearModuleAnimations); // All animations pqLinks.addPropertyLink(ui.numberOfFrames, "value", SIGNAL(valueChanged(int)), scene()->getProxy(), scene()->getProxy()->GetProperty("NumberOfFrames"), 0); connect(ui.numberOfFrames, QOverload<int>::of(&QSpinBox::valueChanged), this, &Internal::numberOfFramesModified); connect(ui.clearAllAnimations, &QPushButton::clicked, this, &Internal::clearAllAnimations); } void play() { scene()->getProxy()->InvokeCommand("Play"); } void updateGui() { ui.enableTimeSeriesAnimations->setChecked( activeObjects().timeSeriesAnimationsEnabled()); updateDataSourceOptions(); updateEnableStates(); } void updateEnableStates() { bool hasCameraAnimations = false; for (auto* cue : scene()->getCues()) { if (cue->getSMName().startsWith("CameraAnimationCue")) { hasCameraAnimations = true; break; } } bool hasTimeSeries = false; for (auto* ds : moduleManager().allDataSources()) { if (ds->hasTimeSteps()) { hasTimeSeries = true; break; } } bool timeSeriesEnabled = ui.enableTimeSeriesAnimations->isChecked() && hasTimeSeries; bool hasDataSourceOptions = ui.selectedDataSource->count() != 0; bool hasModuleOptions = ui.selectedModule->count() != 0; bool moduleSelected = selectedModule() != nullptr; bool hasModuleAnimations = !moduleAnimations.empty(); bool hasAnyAnimations = hasCameraAnimations || timeSeriesEnabled || hasModuleAnimations; ui.clearCameraAnimations->setEnabled(hasCameraAnimations); ui.enableTimeSeriesAnimations->setEnabled(hasTimeSeries); ui.addModuleAnimation->setEnabled(moduleSelected); ui.selectedDataSource->setEnabled(hasDataSourceOptions); ui.selectedModule->setEnabled(hasModuleOptions); ui.clearModuleAnimations->setEnabled(hasModuleAnimations); ui.clearAllAnimations->setEnabled(hasAnyAnimations); } // Camera void clearCameraAnimations() { clearCameraCues(); updateEnableStates(); } void createCameraOrbitInternal() { auto* renderView = activeObjects().activePqRenderView(); // Remove all previous camera cues, and create the orbit clearCameraCues(renderView->getRenderViewProxy()); createCameraOrbit(renderView->getRenderViewProxy()); updateEnableStates(); play(); } QStringList moduleTabTexts() { QStringList types; for (int i = 0; i < ui.modulesTabWidget->count(); ++i) { types.append(ui.modulesTabWidget->tabText(i)); } return types; } QStringList allowedModuleTypes() { // This is based upon tab texts return moduleTabTexts(); } // Data sources void updateDataSourceOptions() { QSignalBlocker blocked(ui.selectedDataSource); auto* previouslySelected = selectedDataSource(); int previouslySelectedIndex = -1; ui.selectedDataSource->clear(); auto& manager = moduleManager(); auto dataSources = manager.allDataSourcesDepthFirst(); auto labels = manager.createUniqueLabels(dataSources); for (int i = 0; i < dataSources.size(); ++i) { auto* dataSource = dataSources[i]; auto label = labels[i]; QVariant data; data.setValue(dataSource); ui.selectedDataSource->addItem(label, data); if (dataSource == previouslySelected) { previouslySelectedIndex = i; } } if (previouslySelectedIndex != -1) { ui.selectedDataSource->setCurrentIndex(previouslySelectedIndex); } else { selectedDataSourceChanged(); } updateEnableStates(); } DataSource* selectedDataSource() { if (ui.selectedDataSource->count() == 0) { return nullptr; } return ui.selectedDataSource->currentData().value<DataSource*>(); } // Modules void updateModuleOptions() { QSignalBlocker blocked(ui.selectedModule); auto* previouslySelected = selectedModule(); int previouslySelectedIndex = -1; ui.selectedModule->clear(); auto* dataSource = selectedDataSource(); if (!dataSource) { return; } auto& manager = moduleManager(); QStringList labels; QList<Module*> modules; auto allowedTypes = allowedModuleTypes(); for (auto* module : manager.findModulesGeneric(dataSource, nullptr)) { if (allowedTypes.contains(module->label())) { modules.append(module); int i = 1; auto label = module->label(); while (labels.contains(label)) { label = module->label() + " " + QString::number(++i); } labels.append(label); } } for (int i = 0; i < modules.size(); ++i) { auto* module = modules[i]; auto label = labels[i]; QVariant data; data.setValue(module); ui.selectedModule->addItem(label, data); if (module == previouslySelected) { previouslySelectedIndex = i; } } if (previouslySelectedIndex != -1) { ui.selectedModule->setCurrentIndex(previouslySelectedIndex); } else { selectedModuleChanged(); } updateEnableStates(); } Module* selectedModule() { if (ui.selectedModule->count() == 0) { return nullptr; } return ui.selectedModule->currentData().value<Module*>(); } void selectedDataSourceChanged() { updateModuleOptions(); } void selectedModuleChanged() { // Show animation options for the selected module auto* module = selectedModule(); auto tabIndex = 0; if (module) { tabIndex = moduleTabTexts().indexOf(module->label()); } ui.modulesTabWidget->setCurrentIndex(tabIndex); if (qobject_cast<ModuleContour*>(module)) { setupContourTab(); } updateEnableStates(); } void onDataSourceAdded() { // This is done later because when the dataSourceAdded // signal gets emitted, the data source does not yet have a label, // but it gets added later. It appears to have the label, though, // if we simple post this to the event loop to be performed later. QTimer::singleShot(0, this, &Internal::updateDataSourceOptions); updateEnableStates(); } void onDataSourceRemoved() { updateDataSourceOptions(); updateEnableStates(); } void setupContourTab() { auto* module = qobject_cast<ModuleContour*>(selectedModule()); double range[2]; module->isoRange(range); ui.contourStart->setMinimum(range[0]); ui.contourStart->setMaximum(range[1]); ui.contourStop->setMinimum(range[0]); ui.contourStop->setMaximum(range[1]); // Set reasonable default values ui.contourStart->setValue((range[1] - range[0]) / 3 + range[0]); ui.contourStop->setValue((range[1] - range[0]) * 2 / 3 + range[0]); } void addModuleAnimation() { auto* module = selectedModule(); if (!module) { return; } for (int i = 0; i < moduleAnimations.size(); ++i) { if (module == moduleAnimations[i]->baseModule) { // We only allow one animation per module // Remove the old one moduleAnimations[i]->deleteLater(); moduleAnimations.removeAt(i); --i; } } if (qobject_cast<ModuleContour*>(module)) { addContourAnimation(); } else { qDebug() << "Unknown module type: " << module; } updateEnableStates(); play(); } void addContourAnimation() { auto start = ui.contourStart->value(); auto stop = ui.contourStop->value(); auto* module = qobject_cast<ModuleContour*>(selectedModule()); moduleAnimations.append(new ContourAnimation(module, start, stop)); } void clearModuleAnimations() { for (auto animation : moduleAnimations) { animation->deleteLater(); } moduleAnimations.clear(); updateEnableStates(); } // All animations void numberOfFramesModified() { // The number of frames only makes sense if the play mode is a sequence. // If the user modified the number of frames, set the play mode to // sequence. pqSMAdaptor::setEnumerationProperty( scene()->getProxy()->GetProperty("PlayMode"), "Sequence"); } void clearAllAnimations() { clearCameraAnimations(); if (ui.enableTimeSeriesAnimations->isEnabled()) { ui.enableTimeSeriesAnimations->setChecked(false); } clearModuleAnimations(); updateEnableStates(); } ActiveObjects& activeObjects() { return ActiveObjects::instance(); } ModuleManager& moduleManager() { return ModuleManager::instance(); } pqAnimationScene* scene() { return pqPVApplicationCore::instance() ->animationManager() ->getActiveScene(); } }; // end class Internal AnimationHelperDialog::AnimationHelperDialog(QWidget* parent) : QDialog(parent), m_internal(new Internal(this)) { } AnimationHelperDialog::~AnimationHelperDialog() = default; } // namespace tomviz <|endoftext|>
<commit_before>// // Created by ariel on 10/30/16. // #include <iostream> #include <SFML/Graphics.hpp> #include <SFML/Audio.hpp> #include "Tower/Tower.h" #include "Tower/TowerMan.h" using std::cout; using std::endl; using Towers::Tower; using Towers::TowerType; using Towers::TowerMan; using Monsters::MonsterMan; int main () { sf::RenderWindow window(sf::VideoMode(640, 480, 32), "Tower Defense", sf::Style::Close); MonsterMan monstMan(window); TowerMan towerMan(window, monstMan); window.setFramerateLimit(240); sf::SoundBuffer sound; sound.loadFromFile("Resources/Sounds/TowerFireSound-1.wav"); sf::Sound sound1; sound1.setBuffer(sound); //sound1.play(); while (window.isOpen()) { sf::Event event; while(window.pollEvent(event)) { if (event.type == sf::Event::Closed) { cout << "received close event" << endl; window.close(); } else if (event.type == sf::Event::MouseButtonReleased) { towerMan.createTower(TowerType::SHORT_RANGE, sf::Mouse::getPosition(window).x, sf::Mouse::getPosition(window).y); cout << "mouse clicked" << endl; } } window.clear(sf::Color::Black); towerMan.update(); towerMan.render(); monstMan.update(); monstMan.render(); window.display(); } return 0; } <commit_msg>Minor style tweaks<commit_after>// // Created by ariel on 10/30/16. // #include <iostream> #include <SFML/Graphics.hpp> #include <SFML/Audio.hpp> #include "Tower/Tower.h" #include "Tower/TowerMan.h" using std::cout; using std::endl; using Towers::Tower; using Towers::TowerType; using Towers::TowerMan; using Monsters::MonsterMan; int main () { sf::RenderWindow window(sf::VideoMode(640, 480, 32), "Tower Defense", sf::Style::Close); MonsterMan monstMan(window); TowerMan towerMan(window, monstMan); window.setFramerateLimit(240); sf::SoundBuffer fireSound; fireSound.loadFromFile("Resources/Sounds/TowerFireSound-1.wav"); sf::Sound sound; sound.setBuffer(fireSound); //sound1.play(); while (window.isOpen()) { sf::Event event; while(window.pollEvent(event)) { if (event.type == sf::Event::Closed) { cout << "received close event" << endl; window.close(); } else if (event.type == sf::Event::MouseButtonReleased) { towerMan.createTower(TowerType::SHORT_RANGE, sf::Mouse::getPosition(window).x, sf::Mouse::getPosition(window).y); } } window.clear(sf::Color::Black); towerMan.update(); towerMan.render(); monstMan.update(); monstMan.render(); window.display(); } return 0; } <|endoftext|>
<commit_before><commit_msg>Add GMT restriction to buildtime calculation<commit_after><|endoftext|>
<commit_before>#include <iostream> #include <signal.h> #include <sys/resource.h> #include <cstdio> #include <cstring> #include <unistd.h> #include <string.h> #include "bpforc.h" #include "bpftrace.h" #include "clang_parser.h" #include "codegen_llvm.h" #include "driver.h" #include "list.h" #include "printer.h" #include "semantic_analyser.h" #include "tracepoint_format_parser.h" using namespace bpftrace; void usage() { std::cerr << "USAGE:" << std::endl; std::cerr << " bpftrace [options] filename" << std::endl; std::cerr << " bpftrace [options] -e 'program'" << std::endl << std::endl; std::cerr << "OPTIONS:" << std::endl; std::cerr << " -B MODE output buffering mode ('line', 'full', or 'none')" << std::endl; std::cerr << " -d debug info dry run" << std::endl; std::cerr << " -dd verbose debug info dry run" << std::endl; std::cerr << " -e 'program' execute this program" << std::endl; std::cerr << " -h show this help message" << std::endl; std::cerr << " -l [search] list probes" << std::endl; std::cerr << " -p PID enable USDT probes on PID" << std::endl; std::cerr << " -c 'CMD' run CMD and enable USDT probes on resulting process" << std::endl; std::cerr << " -v verbose messages" << std::endl; std::cerr << " --version bpftrace version" << std::endl << std::endl; std::cerr << "ENVIRONMENT:" << std::endl; std::cerr << " BPFTRACE_STRLEN [default: 64] bytes on BPF stack per str()" << std::endl; std::cerr << " BPFTRACE_NO_CPP_DEMANGLE [default: 0] disable C++ symbol demangling" << std::endl << std::endl; std::cerr << "EXAMPLES:" << std::endl; std::cerr << "bpftrace -l '*sleep*'" << std::endl; std::cerr << " list probes containing \"sleep\"" << std::endl; std::cerr << "bpftrace -e 'kprobe:do_nanosleep { printf(\"PID %d sleeping...\\n\", pid); }'" << std::endl; std::cerr << " trace processes calling sleep" << std::endl; std::cerr << "bpftrace -e 'tracepoint:raw_syscalls:sys_enter { @[comm] = count(); }'" << std::endl; std::cerr << " count syscalls by process name" << std::endl; } static void enforce_infinite_rlimit() { struct rlimit rl = {}; int err; rl.rlim_max = RLIM_INFINITY; rl.rlim_cur = rl.rlim_max; err = setrlimit(RLIMIT_MEMLOCK, &rl); if (err) std::cerr << std::strerror(err)<<": couldn't set RLIMIT for bpftrace. " << "If your program is not loading, you can try " << "\"ulimit -l 8192\" to fix the problem" << std::endl; } bool is_root() { if (geteuid() != 0) { std::cerr << "ERROR: bpftrace currently only supports running as the root user." << std::endl; return false; } else return true; } bool is_numeric(char* string) { while(char current_char = *string++) { if (!isdigit(current_char)) return false; } return true; } int main(int argc, char *argv[]) { int err; char *pid_str = nullptr; char *cmd_str = nullptr; bool listing = false; if (argc > 1 && strcmp(argv[1], "--version") == 0) { std::cout << "bpftrace " << BPFTRACE_VERSION<< "\n" << std::endl; return 0; } std::string script, search, file_name; int c; while ((c = getopt(argc, argv, "dB:e:hlp:vc:")) != -1) { switch (c) { case 'd': bt_debug++; if (bt_debug == DebugLevel::kNone) { usage(); return 1; } break; case 'v': bt_verbose = true; break; case 'B': if (std::strcmp(optarg, "line") == 0) { std::setvbuf(stdout, NULL, _IOLBF, BUFSIZ); } else if (std::strcmp(optarg, "full") == 0) { std::setvbuf(stdout, NULL, _IOFBF, BUFSIZ); } else if (std::strcmp(optarg, "none") == 0) { std::setvbuf(stdout, NULL, _IONBF, BUFSIZ); } else { std::cerr << "USAGE: -B must be either 'line', 'full', or 'none'." << std::endl; return 1; } break; case 'e': script = optarg; break; case 'p': pid_str = optarg; break; case 'l': listing = true; break; case 'c': cmd_str = optarg; break; case 'h': usage(); return 0; default: usage(); return 1; } } if (argc == 1) { usage(); return 1; } if (bt_verbose && (bt_debug != DebugLevel::kNone)) { // TODO: allow both std::cerr << "USAGE: Use either -v or -d." << std::endl; return 1; } if (cmd_str && pid_str) { std::cerr << "USAGE: Cannot use both -c and -p." << std::endl; usage(); return 1; } BPFtrace bpftrace; Driver driver(bpftrace); // PID is currently only used for USDT probes that need enabling. Future work: // - make PID a filter for all probe types: pass to perf_event_open(), etc. // - provide PID in USDT probe specification as a way to override -p. bpftrace.pid_ = 0; if (pid_str) { if (!is_numeric(pid_str)) { std::cerr << "ERROR: pid '" << pid_str << "' is not a valid number." << std::endl; return 1; } bpftrace.pid_ = strtol(pid_str, NULL, 10); } // Listing probes if (listing) { if (!is_root()) return 1; if (optind == argc-1) list_probes(argv[optind], bpftrace.pid_); else if (optind == argc) list_probes("", bpftrace.pid_); else { usage(); } return 0; } if (script.empty()) { // Script file file_name = std::string(argv[optind]); if (file_name.empty()) { std::cerr << "USAGE: filename or -e 'program' required." << std::endl; return 1; } err = driver.parse_file(file_name); optind++; } else { // Script is provided as a command line argument err = driver.parse_str(script); } if (!is_root()) return 1; if (err) return err; // FIXME (mmarchini): maybe we don't want to always enforce an infinite // rlimit? enforce_infinite_rlimit(); // positional parameters while (optind < argc) { bpftrace.add_param(argv[optind]); optind++; } // defaults bpftrace.join_argnum_ = 16; bpftrace.join_argsize_ = 1024; if(const char* env_p = std::getenv("BPFTRACE_STRLEN")) { uint64_t proposed; std::istringstream stringstream(env_p); if (!(stringstream >> proposed)) { std::cerr << "Env var 'BPFTRACE_STRLEN' did not contain a valid uint64_t, or was zero-valued." << std::endl; return 1; } // in practice, the largest buffer I've seen fit into the BPF stack was 240 bytes. // I've set the bar lower, in case your program has a deeper stack than the one from my tests, // in the hope that you'll get this instructive error instead of getting the BPF verifier's error. if (proposed > 200) { // the verifier errors you would encounter when attempting larger allocations would be: // >240= <Looks like the BPF stack limit of 512 bytes is exceeded. Please move large on stack variables into BPF per-cpu array map.> // ~1024= <A call to built-in function 'memset' is not supported.> std::cerr << "'BPFTRACE_STRLEN' " << proposed << " exceeds the current maximum of 200 bytes." << std::endl << "This limitation is because strings are currently stored on the 512 byte BPF stack." << std::endl << "Long strings will be pursued in: https://github.com/iovisor/bpftrace/issues/305" << std::endl; return 1; } bpftrace.strlen_ = proposed; } if (const char* env_p = std::getenv("BPFTRACE_NO_CPP_DEMANGLE")) { if (std::string(env_p) == "1") bpftrace.demangle_cpp_symbols = false; else if (std::string(env_p) == "0") bpftrace.demangle_cpp_symbols = true; else { std::cerr << "Env var 'BPFTRACE_NO_CPP_DEMANGLE' did not contain a valid value (0 or 1)." << std::endl; return 1; } } if (cmd_str) bpftrace.cmd_ = cmd_str; if (TracepointFormatParser::parse(driver.root_) == false) return 1; if (bt_debug != DebugLevel::kNone) { ast::Printer p(std::cout); driver.root_->accept(p); std::cout << std::endl; } ClangParser clang; clang.parse(driver.root_, bpftrace); if (script.empty()) { err = driver.parse_file(file_name); } else { err = driver.parse_str(script); } if (err) return err; ast::SemanticAnalyser semantics(driver.root_, bpftrace); err = semantics.analyse(); if (err) return err; err = semantics.create_maps(bt_debug != DebugLevel::kNone); if (err) return err; ast::CodegenLLVM llvm(driver.root_, bpftrace); auto bpforc = llvm.compile(bt_debug); if (bt_debug != DebugLevel::kNone) return 0; // Empty signal handler for cleanly terminating the program struct sigaction act = {}; act.sa_handler = [](int) { }; sigaction(SIGINT, &act, NULL); int num_probes = bpftrace.num_probes(); if (num_probes == 0) { std::cout << "No probes to attach" << std::endl; return 1; } else if (num_probes == 1) std::cout << "Attaching " << bpftrace.num_probes() << " probe..." << std::endl; else std::cout << "Attaching " << bpftrace.num_probes() << " probes..." << std::endl; err = bpftrace.run(move(bpforc)); if (err) return err; std::cout << "\n\n"; err = bpftrace.print_maps(); if (err) return err; return 0; } <commit_msg>Avoid crash if incorrect command line option is used<commit_after>#include <iostream> #include <signal.h> #include <sys/resource.h> #include <cstdio> #include <cstring> #include <unistd.h> #include <string.h> #include "bpforc.h" #include "bpftrace.h" #include "clang_parser.h" #include "codegen_llvm.h" #include "driver.h" #include "list.h" #include "printer.h" #include "semantic_analyser.h" #include "tracepoint_format_parser.h" using namespace bpftrace; void usage() { std::cerr << "USAGE:" << std::endl; std::cerr << " bpftrace [options] filename" << std::endl; std::cerr << " bpftrace [options] -e 'program'" << std::endl << std::endl; std::cerr << "OPTIONS:" << std::endl; std::cerr << " -B MODE output buffering mode ('line', 'full', or 'none')" << std::endl; std::cerr << " -d debug info dry run" << std::endl; std::cerr << " -dd verbose debug info dry run" << std::endl; std::cerr << " -e 'program' execute this program" << std::endl; std::cerr << " -h show this help message" << std::endl; std::cerr << " -l [search] list probes" << std::endl; std::cerr << " -p PID enable USDT probes on PID" << std::endl; std::cerr << " -c 'CMD' run CMD and enable USDT probes on resulting process" << std::endl; std::cerr << " -v verbose messages" << std::endl; std::cerr << " --version bpftrace version" << std::endl << std::endl; std::cerr << "ENVIRONMENT:" << std::endl; std::cerr << " BPFTRACE_STRLEN [default: 64] bytes on BPF stack per str()" << std::endl; std::cerr << " BPFTRACE_NO_CPP_DEMANGLE [default: 0] disable C++ symbol demangling" << std::endl << std::endl; std::cerr << "EXAMPLES:" << std::endl; std::cerr << "bpftrace -l '*sleep*'" << std::endl; std::cerr << " list probes containing \"sleep\"" << std::endl; std::cerr << "bpftrace -e 'kprobe:do_nanosleep { printf(\"PID %d sleeping...\\n\", pid); }'" << std::endl; std::cerr << " trace processes calling sleep" << std::endl; std::cerr << "bpftrace -e 'tracepoint:raw_syscalls:sys_enter { @[comm] = count(); }'" << std::endl; std::cerr << " count syscalls by process name" << std::endl; } static void enforce_infinite_rlimit() { struct rlimit rl = {}; int err; rl.rlim_max = RLIM_INFINITY; rl.rlim_cur = rl.rlim_max; err = setrlimit(RLIMIT_MEMLOCK, &rl); if (err) std::cerr << std::strerror(err)<<": couldn't set RLIMIT for bpftrace. " << "If your program is not loading, you can try " << "\"ulimit -l 8192\" to fix the problem" << std::endl; } bool is_root() { if (geteuid() != 0) { std::cerr << "ERROR: bpftrace currently only supports running as the root user." << std::endl; return false; } else return true; } bool is_numeric(char* string) { while(char current_char = *string++) { if (!isdigit(current_char)) return false; } return true; } int main(int argc, char *argv[]) { int err; char *pid_str = nullptr; char *cmd_str = nullptr; bool listing = false; if (argc > 1 && strcmp(argv[1], "--version") == 0) { std::cout << "bpftrace " << BPFTRACE_VERSION<< "\n" << std::endl; return 0; } std::string script, search, file_name; int c; while ((c = getopt(argc, argv, "dB:e:hlp:vc:")) != -1) { switch (c) { case 'd': bt_debug++; if (bt_debug == DebugLevel::kNone) { usage(); return 1; } break; case 'v': bt_verbose = true; break; case 'B': if (std::strcmp(optarg, "line") == 0) { std::setvbuf(stdout, NULL, _IOLBF, BUFSIZ); } else if (std::strcmp(optarg, "full") == 0) { std::setvbuf(stdout, NULL, _IOFBF, BUFSIZ); } else if (std::strcmp(optarg, "none") == 0) { std::setvbuf(stdout, NULL, _IONBF, BUFSIZ); } else { std::cerr << "USAGE: -B must be either 'line', 'full', or 'none'." << std::endl; return 1; } break; case 'e': script = optarg; break; case 'p': pid_str = optarg; break; case 'l': listing = true; break; case 'c': cmd_str = optarg; break; case 'h': usage(); return 0; default: usage(); return 1; } } if (argc == 1) { usage(); return 1; } if (bt_verbose && (bt_debug != DebugLevel::kNone)) { // TODO: allow both std::cerr << "USAGE: Use either -v or -d." << std::endl; return 1; } if (cmd_str && pid_str) { std::cerr << "USAGE: Cannot use both -c and -p." << std::endl; usage(); return 1; } BPFtrace bpftrace; Driver driver(bpftrace); // PID is currently only used for USDT probes that need enabling. Future work: // - make PID a filter for all probe types: pass to perf_event_open(), etc. // - provide PID in USDT probe specification as a way to override -p. bpftrace.pid_ = 0; if (pid_str) { if (!is_numeric(pid_str)) { std::cerr << "ERROR: pid '" << pid_str << "' is not a valid number." << std::endl; return 1; } bpftrace.pid_ = strtol(pid_str, NULL, 10); } // Listing probes if (listing) { if (!is_root()) return 1; if (optind == argc-1) list_probes(argv[optind], bpftrace.pid_); else if (optind == argc) list_probes("", bpftrace.pid_); else { usage(); } return 0; } if (script.empty()) { // Script file if (argv[optind] == nullptr) { std::cerr << "USAGE: filename or -e 'program' required." << std::endl; return 1; } file_name = std::string(argv[optind]); err = driver.parse_file(file_name); optind++; } else { // Script is provided as a command line argument err = driver.parse_str(script); } if (!is_root()) return 1; if (err) return err; // FIXME (mmarchini): maybe we don't want to always enforce an infinite // rlimit? enforce_infinite_rlimit(); // positional parameters while (optind < argc) { bpftrace.add_param(argv[optind]); optind++; } // defaults bpftrace.join_argnum_ = 16; bpftrace.join_argsize_ = 1024; if(const char* env_p = std::getenv("BPFTRACE_STRLEN")) { uint64_t proposed; std::istringstream stringstream(env_p); if (!(stringstream >> proposed)) { std::cerr << "Env var 'BPFTRACE_STRLEN' did not contain a valid uint64_t, or was zero-valued." << std::endl; return 1; } // in practice, the largest buffer I've seen fit into the BPF stack was 240 bytes. // I've set the bar lower, in case your program has a deeper stack than the one from my tests, // in the hope that you'll get this instructive error instead of getting the BPF verifier's error. if (proposed > 200) { // the verifier errors you would encounter when attempting larger allocations would be: // >240= <Looks like the BPF stack limit of 512 bytes is exceeded. Please move large on stack variables into BPF per-cpu array map.> // ~1024= <A call to built-in function 'memset' is not supported.> std::cerr << "'BPFTRACE_STRLEN' " << proposed << " exceeds the current maximum of 200 bytes." << std::endl << "This limitation is because strings are currently stored on the 512 byte BPF stack." << std::endl << "Long strings will be pursued in: https://github.com/iovisor/bpftrace/issues/305" << std::endl; return 1; } bpftrace.strlen_ = proposed; } if (const char* env_p = std::getenv("BPFTRACE_NO_CPP_DEMANGLE")) { if (std::string(env_p) == "1") bpftrace.demangle_cpp_symbols = false; else if (std::string(env_p) == "0") bpftrace.demangle_cpp_symbols = true; else { std::cerr << "Env var 'BPFTRACE_NO_CPP_DEMANGLE' did not contain a valid value (0 or 1)." << std::endl; return 1; } } if (cmd_str) bpftrace.cmd_ = cmd_str; if (TracepointFormatParser::parse(driver.root_) == false) return 1; if (bt_debug != DebugLevel::kNone) { ast::Printer p(std::cout); driver.root_->accept(p); std::cout << std::endl; } ClangParser clang; clang.parse(driver.root_, bpftrace); if (script.empty()) { err = driver.parse_file(file_name); } else { err = driver.parse_str(script); } if (err) return err; ast::SemanticAnalyser semantics(driver.root_, bpftrace); err = semantics.analyse(); if (err) return err; err = semantics.create_maps(bt_debug != DebugLevel::kNone); if (err) return err; ast::CodegenLLVM llvm(driver.root_, bpftrace); auto bpforc = llvm.compile(bt_debug); if (bt_debug != DebugLevel::kNone) return 0; // Empty signal handler for cleanly terminating the program struct sigaction act = {}; act.sa_handler = [](int) { }; sigaction(SIGINT, &act, NULL); int num_probes = bpftrace.num_probes(); if (num_probes == 0) { std::cout << "No probes to attach" << std::endl; return 1; } else if (num_probes == 1) std::cout << "Attaching " << bpftrace.num_probes() << " probe..." << std::endl; else std::cout << "Attaching " << bpftrace.num_probes() << " probes..." << std::endl; err = bpftrace.run(move(bpforc)); if (err) return err; std::cout << "\n\n"; err = bpftrace.print_maps(); if (err) return err; return 0; } <|endoftext|>
<commit_before>/* * Copyright (C) 2009 Google Inc. 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 Google Inc. nor the names of its * contributors may be used to endorse or promote products derived from * this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #include "config.h" #include "WebRuntimeFeatures.h" #include "WebMediaPlayerClientImpl.h" #include "RuntimeEnabledFeatures.h" #include "modules/websockets/WebSocket.h" #include <wtf/UnusedParam.h> using namespace WebCore; namespace WebKit { void WebRuntimeFeatures::enableStableFeatures(bool enable) { // FIXME: Actually respect the enable arg once the 3-part // change dance with content/ is over. ASSERT_UNUSED(enable, enable); // These are copied directly from RenderThreadImpl::InitializeWebKit. // All the "false" values should be removed, and all the flags // which default to "true" in RuntimeEnabledFeatures.cpp // should be moved here or enableTestingFeatures instead. enableDatabase(true); enableApplicationCache(true); enableNotifications(true); enableLocalStorage(true); enableSessionStorage(true); enableIndexedDatabase(true); enableGeolocation(true); enableMediaSource(true); enableMediaPlayer(true); enableMediaStream(true); enablePeerConnection(true); enableFullScreenAPI(true); enableEncryptedMedia(true); enableWebAudio(true); enableWebMIDI(false); enableDeviceMotion(false); enableDeviceOrientation(true); enableSpeechInput(true); enableScriptedSpeech(true); enableGamepad(true); enableFileSystem(true); enableJavaScriptI18NAPI(true); enableQuota(true); enableSeamlessIFrames(false); enableExperimentalWebSocket(false); enableExperimentalCanvasFeatures(false); enableSpeechSynthesis(false); } void WebRuntimeFeatures::enableExperimentalFeatures(bool enable) { // FIXME: Actually respect the enable arg once the 3-part // change dance with content/ is over. ASSERT_UNUSED(enable, enable); enableStyleScoped(true); enableCustomDOMElements(true); enableCSSExclusions(true); enableExperimentalContentSecurityPolicyFeatures(true); enableCSSRegions(true); enableCSSCompositing(true); enableDialogElement(true); enableFontLoadEvents(true); enableSeamlessIFrames(true); } void WebRuntimeFeatures::enableTestOnlyFeatures(bool enable) { // FIXME: This will be populated with features which // are currently initialized true, but always set // to false in enableStableFeatures. // This method should be used by ContentShell // to enable features which should be enabled for // the layout tests but are not yet "experimental". } void WebRuntimeFeatures::enableDatabase(bool enable) { RuntimeEnabledFeatures::setDatabaseEnabled(enable); } bool WebRuntimeFeatures::isDatabaseEnabled() { return RuntimeEnabledFeatures::databaseEnabled(); } // FIXME: Remove the ability to enable this feature at runtime. void WebRuntimeFeatures::enableLocalStorage(bool enable) { RuntimeEnabledFeatures::setLocalStorageEnabled(enable); } // FIXME: Remove the ability to enable this feature at runtime. bool WebRuntimeFeatures::isLocalStorageEnabled() { return RuntimeEnabledFeatures::localStorageEnabled(); } // FIXME: Remove the ability to enable this feature at runtime. void WebRuntimeFeatures::enableSessionStorage(bool enable) { RuntimeEnabledFeatures::setSessionStorageEnabled(enable); } // FIXME: Remove the ability to enable this feature at runtime. bool WebRuntimeFeatures::isSessionStorageEnabled() { return RuntimeEnabledFeatures::sessionStorageEnabled(); } void WebRuntimeFeatures::enableMediaPlayer(bool enable) { WebMediaPlayerClientImpl::setIsEnabled(enable); } bool WebRuntimeFeatures::isMediaPlayerEnabled() { return WebMediaPlayerClientImpl::isEnabled(); } void WebRuntimeFeatures::enableNotifications(bool enable) { #if ENABLE(NOTIFICATIONS) || ENABLE(LEGACY_NOTIFICATIONS) RuntimeEnabledFeatures::setWebkitNotificationsEnabled(enable); #endif } bool WebRuntimeFeatures::isNotificationsEnabled() { #if ENABLE(NOTIFICATIONS) || ENABLE(LEGACY_NOTIFICATIONS) return RuntimeEnabledFeatures::webkitNotificationsEnabled(); #else return false; #endif } void WebRuntimeFeatures::enableApplicationCache(bool enable) { RuntimeEnabledFeatures::setApplicationCacheEnabled(enable); } bool WebRuntimeFeatures::isApplicationCacheEnabled() { return RuntimeEnabledFeatures::applicationCacheEnabled(); } void WebRuntimeFeatures::enableGeolocation(bool enable) { RuntimeEnabledFeatures::setGeolocationEnabled(enable); } bool WebRuntimeFeatures::isGeolocationEnabled() { return RuntimeEnabledFeatures::geolocationEnabled(); } void WebRuntimeFeatures::enableIndexedDatabase(bool enable) { RuntimeEnabledFeatures::setIndexedDBEnabled(enable); } bool WebRuntimeFeatures::isIndexedDatabaseEnabled() { return RuntimeEnabledFeatures::indexedDBEnabled(); } void WebRuntimeFeatures::enableWebAudio(bool enable) { RuntimeEnabledFeatures::setAudioContextEnabled(enable); } bool WebRuntimeFeatures::isWebAudioEnabled() { return RuntimeEnabledFeatures::audioContextEnabled(); } void WebRuntimeFeatures::enableTouch(bool enable) { RuntimeEnabledFeatures::setTouchEnabled(enable); } bool WebRuntimeFeatures::isTouchEnabled() { return RuntimeEnabledFeatures::touchEnabled(); } void WebRuntimeFeatures::enableDeviceMotion(bool enable) { RuntimeEnabledFeatures::setDeviceMotionEnabled(enable); } bool WebRuntimeFeatures::isDeviceMotionEnabled() { return RuntimeEnabledFeatures::deviceMotionEnabled(); } void WebRuntimeFeatures::enableDeviceOrientation(bool enable) { RuntimeEnabledFeatures::setDeviceOrientationEnabled(enable); } bool WebRuntimeFeatures::isDeviceOrientationEnabled() { return RuntimeEnabledFeatures::deviceOrientationEnabled(); } void WebRuntimeFeatures::enableSpeechInput(bool enable) { RuntimeEnabledFeatures::setSpeechInputEnabled(enable); } bool WebRuntimeFeatures::isSpeechInputEnabled() { return RuntimeEnabledFeatures::speechInputEnabled(); } void WebRuntimeFeatures::enableScriptedSpeech(bool enable) { RuntimeEnabledFeatures::setScriptedSpeechEnabled(enable); } bool WebRuntimeFeatures::isScriptedSpeechEnabled() { return RuntimeEnabledFeatures::scriptedSpeechEnabled(); } void WebRuntimeFeatures::enableXHRResponseBlob(bool enable) { } bool WebRuntimeFeatures::isXHRResponseBlobEnabled() { return true; } void WebRuntimeFeatures::enableFileSystem(bool enable) { RuntimeEnabledFeatures::setFileSystemEnabled(enable); } bool WebRuntimeFeatures::isFileSystemEnabled() { return RuntimeEnabledFeatures::fileSystemEnabled(); } void WebRuntimeFeatures::enableJavaScriptI18NAPI(bool enable) { RuntimeEnabledFeatures::setJavaScriptI18NAPIEnabled(enable); } bool WebRuntimeFeatures::isJavaScriptI18NAPIEnabled() { return RuntimeEnabledFeatures::javaScriptI18NAPIEnabled(); } void WebRuntimeFeatures::enableQuota(bool enable) { RuntimeEnabledFeatures::setQuotaEnabled(enable); } bool WebRuntimeFeatures::isQuotaEnabled() { return RuntimeEnabledFeatures::quotaEnabled(); } void WebRuntimeFeatures::enableMediaStream(bool enable) { RuntimeEnabledFeatures::setMediaStreamEnabled(enable); } bool WebRuntimeFeatures::isMediaStreamEnabled() { return RuntimeEnabledFeatures::mediaStreamEnabled(); } void WebRuntimeFeatures::enablePeerConnection(bool enable) { RuntimeEnabledFeatures::setPeerConnectionEnabled(enable); } bool WebRuntimeFeatures::isPeerConnectionEnabled() { return RuntimeEnabledFeatures::peerConnectionEnabled(); } void WebRuntimeFeatures::enableFullScreenAPI(bool enable) { RuntimeEnabledFeatures::setFullscreenEnabled(enable); } bool WebRuntimeFeatures::isFullScreenAPIEnabled() { return RuntimeEnabledFeatures::fullscreenEnabled(); } void WebRuntimeFeatures::enableMediaSource(bool enable) { RuntimeEnabledFeatures::setMediaSourceEnabled(enable); } bool WebRuntimeFeatures::isMediaSourceEnabled() { return RuntimeEnabledFeatures::mediaSourceEnabled(); } void WebRuntimeFeatures::enableEncryptedMedia(bool enable) { RuntimeEnabledFeatures::setEncryptedMediaEnabled(enable); } bool WebRuntimeFeatures::isEncryptedMediaEnabled() { return RuntimeEnabledFeatures::encryptedMediaEnabled(); } void WebRuntimeFeatures::enableVideoTrack(bool enable) { RuntimeEnabledFeatures::setWebkitVideoTrackEnabled(enable); } bool WebRuntimeFeatures::isVideoTrackEnabled() { return RuntimeEnabledFeatures::webkitVideoTrackEnabled(); } void WebRuntimeFeatures::enableGamepad(bool enable) { RuntimeEnabledFeatures::setWebkitGetGamepadsEnabled(enable); } bool WebRuntimeFeatures::isGamepadEnabled() { return RuntimeEnabledFeatures::webkitGetGamepadsEnabled(); } void WebRuntimeFeatures::enableExperimentalShadowDOM(bool enable) { RuntimeEnabledFeatures::setExperimentalShadowDOMEnabled(enable); } bool WebRuntimeFeatures::isExperimentalShadowDOMEnabled() { return RuntimeEnabledFeatures::experimentalShadowDOMEnabled(); } void WebRuntimeFeatures::enableCustomDOMElements(bool enable) { RuntimeEnabledFeatures::setCustomDOMElementsEnabled(enable); } bool WebRuntimeFeatures::isCustomDOMElementsEnabled() { return RuntimeEnabledFeatures::customDOMElementsEnabled(); } void WebRuntimeFeatures::enableStyleScoped(bool enable) { RuntimeEnabledFeatures::setStyleScopedEnabled(enable); } bool WebRuntimeFeatures::isStyleScopedEnabled() { return RuntimeEnabledFeatures::styleScopedEnabled(); } void WebRuntimeFeatures::enableInputTypeDateTime(bool enable) { RuntimeEnabledFeatures::setInputTypeDateTimeEnabled(enable); } bool WebRuntimeFeatures::isInputTypeDateTimeEnabled() { return RuntimeEnabledFeatures::inputTypeDateTimeEnabled(); } void WebRuntimeFeatures::enableInputTypeWeek(bool enable) { RuntimeEnabledFeatures::setInputTypeWeekEnabled(enable); } bool WebRuntimeFeatures::isInputTypeWeekEnabled() { return RuntimeEnabledFeatures::inputTypeWeekEnabled(); } void WebRuntimeFeatures::enableDialogElement(bool enable) { RuntimeEnabledFeatures::setDialogElementEnabled(enable); } bool WebRuntimeFeatures::isDialogElementEnabled() { return RuntimeEnabledFeatures::dialogElementEnabled(); } void WebRuntimeFeatures::enableLazyLayout(bool enable) { RuntimeEnabledFeatures::setLazyLayoutEnabled(enable); } bool WebRuntimeFeatures::isLazyLayoutEnabled() { return RuntimeEnabledFeatures::lazyLayoutEnabled(); } void WebRuntimeFeatures::enableExperimentalContentSecurityPolicyFeatures(bool enable) { RuntimeEnabledFeatures::setExperimentalContentSecurityPolicyFeaturesEnabled(enable); } bool WebRuntimeFeatures::isExperimentalContentSecurityPolicyFeaturesEnabled() { return RuntimeEnabledFeatures::experimentalContentSecurityPolicyFeaturesEnabled(); } void WebRuntimeFeatures::enableSeamlessIFrames(bool enable) { return RuntimeEnabledFeatures::setSeamlessIFramesEnabled(enable); } bool WebRuntimeFeatures::areSeamlessIFramesEnabled() { return RuntimeEnabledFeatures::seamlessIFramesEnabled(); } void WebRuntimeFeatures::enableCanvasPath(bool enable) { RuntimeEnabledFeatures::setCanvasPathEnabled(enable); } bool WebRuntimeFeatures::isCanvasPathEnabled() { return RuntimeEnabledFeatures::canvasPathEnabled(); } void WebRuntimeFeatures::enableCSSExclusions(bool enable) { RuntimeEnabledFeatures::setCSSExclusionsEnabled(enable); } bool WebRuntimeFeatures::isCSSExclusionsEnabled() { return RuntimeEnabledFeatures::cssExclusionsEnabled(); } void WebRuntimeFeatures::enableCSSRegions(bool enable) { RuntimeEnabledFeatures::setCSSRegionsEnabled(enable); } bool WebRuntimeFeatures::isCSSRegionsEnabled() { return RuntimeEnabledFeatures::cssRegionsEnabled(); } void WebRuntimeFeatures::enableCSSCompositing(bool enable) { RuntimeEnabledFeatures::setCSSCompositingEnabled(enable); } bool WebRuntimeFeatures::isCSSCompositingEnabled() { return RuntimeEnabledFeatures::cssCompositingEnabled(); } void WebRuntimeFeatures::enableFontLoadEvents(bool enable) { RuntimeEnabledFeatures::setFontLoadEventsEnabled(enable); } bool WebRuntimeFeatures::isFontLoadEventsEnabled() { return RuntimeEnabledFeatures::fontLoadEventsEnabled(); } void WebRuntimeFeatures::enableRequestAutocomplete(bool enable) { RuntimeEnabledFeatures::setRequestAutocompleteEnabled(enable); } bool WebRuntimeFeatures::isRequestAutocompleteEnabled() { return RuntimeEnabledFeatures::requestAutocompleteEnabled(); } void WebRuntimeFeatures::enableWebPInAcceptHeader(bool enable) { RuntimeEnabledFeatures::setWebPInAcceptHeaderEnabled(enable); } bool WebRuntimeFeatures::isWebPInAcceptHeaderEnabled() { return RuntimeEnabledFeatures::webPInAcceptHeaderEnabled(); } void WebRuntimeFeatures::enableDirectoryUpload(bool enable) { RuntimeEnabledFeatures::setDirectoryUploadEnabled(enable); } bool WebRuntimeFeatures::isDirectoryUploadEnabled() { return RuntimeEnabledFeatures::directoryUploadEnabled(); } void WebRuntimeFeatures::enableExperimentalWebSocket(bool enable) { RuntimeEnabledFeatures::setExperimentalWebSocketEnabled(enable); } bool WebRuntimeFeatures::isExperimentalWebSocketEnabled() { return RuntimeEnabledFeatures::experimentalWebSocketEnabled(); } void WebRuntimeFeatures::enableWebMIDI(bool enable) { return RuntimeEnabledFeatures::setWebMIDIEnabled(enable); } bool WebRuntimeFeatures::isWebMIDIEnabled() { return RuntimeEnabledFeatures::webMIDIEnabled(); } void WebRuntimeFeatures::enableIMEAPI(bool enable) { RuntimeEnabledFeatures::setIMEAPIEnabled(enable); } bool WebRuntimeFeatures::isIMEAPIEnabled() { return RuntimeEnabledFeatures::imeAPIEnabled(); } void WebRuntimeFeatures::enableExperimentalCanvasFeatures(bool enable) { RuntimeEnabledFeatures::setExperimentalCanvasFeaturesEnabled(enable); } bool WebRuntimeFeatures::areExperimentalCanvasFeaturesEnabled() { return RuntimeEnabledFeatures::experimentalCanvasFeaturesEnabled(); } void WebRuntimeFeatures::enableSpeechSynthesis(bool enable) { RuntimeEnabledFeatures::setSpeechSynthesisEnabled(enable); } bool WebRuntimeFeatures::isSpeechSynthesisEnabled() { return RuntimeEnabledFeatures::speechSynthesisEnabled(); } } // namespace WebKit <commit_msg>Sort enable* calls in WebPreferences for easier comparsion with RuntimeEnabledFeatures.in<commit_after>/* * Copyright (C) 2009 Google Inc. 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 Google Inc. nor the names of its * contributors may be used to endorse or promote products derived from * this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #include "config.h" #include "WebRuntimeFeatures.h" #include "WebMediaPlayerClientImpl.h" #include "RuntimeEnabledFeatures.h" #include "modules/websockets/WebSocket.h" #include <wtf/UnusedParam.h> using namespace WebCore; namespace WebKit { void WebRuntimeFeatures::enableStableFeatures(bool enable) { // FIXME: Actually respect the enable arg once the 3-part // change dance with content/ is over. ASSERT_UNUSED(enable, enable); // These are copied directly from RenderThreadImpl::InitializeWebKit. // All the "false" values should be removed, and all the flags // which default to "true" in RuntimeEnabledFeatures.cpp // should be moved here or enableTestingFeatures instead. enableApplicationCache(true); enableDatabase(true); enableDeviceMotion(false); enableDeviceOrientation(true); enableEncryptedMedia(true); enableExperimentalCanvasFeatures(false); enableExperimentalWebSocket(false); enableFileSystem(true); enableFullScreenAPI(true); enableGamepad(true); enableGeolocation(true); enableIndexedDatabase(true); enableJavaScriptI18NAPI(true); enableLocalStorage(true); enableMediaPlayer(true); enableMediaSource(true); enableMediaStream(true); enableNotifications(true); enablePeerConnection(true); enableQuota(true); enableScriptedSpeech(true); enableSeamlessIFrames(false); enableSessionStorage(true); enableSpeechInput(true); enableSpeechSynthesis(false); enableWebAudio(true); enableWebMIDI(false); } void WebRuntimeFeatures::enableExperimentalFeatures(bool enable) { // FIXME: Actually respect the enable arg once the 3-part // change dance with content/ is over. ASSERT_UNUSED(enable, enable); enableCSSCompositing(true); enableCSSExclusions(true); enableCSSRegions(true); enableCustomDOMElements(true); enableDialogElement(true); enableExperimentalContentSecurityPolicyFeatures(true); enableFontLoadEvents(true); enableSeamlessIFrames(true); enableStyleScoped(true); } void WebRuntimeFeatures::enableTestOnlyFeatures(bool enable) { // FIXME: This will be populated with features which // are currently initialized true, but always set // to false in enableStableFeatures. // This method should be used by ContentShell // to enable features which should be enabled for // the layout tests but are not yet "experimental". } void WebRuntimeFeatures::enableDatabase(bool enable) { RuntimeEnabledFeatures::setDatabaseEnabled(enable); } bool WebRuntimeFeatures::isDatabaseEnabled() { return RuntimeEnabledFeatures::databaseEnabled(); } // FIXME: Remove the ability to enable this feature at runtime. void WebRuntimeFeatures::enableLocalStorage(bool enable) { RuntimeEnabledFeatures::setLocalStorageEnabled(enable); } // FIXME: Remove the ability to enable this feature at runtime. bool WebRuntimeFeatures::isLocalStorageEnabled() { return RuntimeEnabledFeatures::localStorageEnabled(); } // FIXME: Remove the ability to enable this feature at runtime. void WebRuntimeFeatures::enableSessionStorage(bool enable) { RuntimeEnabledFeatures::setSessionStorageEnabled(enable); } // FIXME: Remove the ability to enable this feature at runtime. bool WebRuntimeFeatures::isSessionStorageEnabled() { return RuntimeEnabledFeatures::sessionStorageEnabled(); } void WebRuntimeFeatures::enableMediaPlayer(bool enable) { WebMediaPlayerClientImpl::setIsEnabled(enable); } bool WebRuntimeFeatures::isMediaPlayerEnabled() { return WebMediaPlayerClientImpl::isEnabled(); } void WebRuntimeFeatures::enableNotifications(bool enable) { #if ENABLE(NOTIFICATIONS) || ENABLE(LEGACY_NOTIFICATIONS) RuntimeEnabledFeatures::setWebkitNotificationsEnabled(enable); #endif } bool WebRuntimeFeatures::isNotificationsEnabled() { #if ENABLE(NOTIFICATIONS) || ENABLE(LEGACY_NOTIFICATIONS) return RuntimeEnabledFeatures::webkitNotificationsEnabled(); #else return false; #endif } void WebRuntimeFeatures::enableApplicationCache(bool enable) { RuntimeEnabledFeatures::setApplicationCacheEnabled(enable); } bool WebRuntimeFeatures::isApplicationCacheEnabled() { return RuntimeEnabledFeatures::applicationCacheEnabled(); } void WebRuntimeFeatures::enableGeolocation(bool enable) { RuntimeEnabledFeatures::setGeolocationEnabled(enable); } bool WebRuntimeFeatures::isGeolocationEnabled() { return RuntimeEnabledFeatures::geolocationEnabled(); } void WebRuntimeFeatures::enableIndexedDatabase(bool enable) { RuntimeEnabledFeatures::setIndexedDBEnabled(enable); } bool WebRuntimeFeatures::isIndexedDatabaseEnabled() { return RuntimeEnabledFeatures::indexedDBEnabled(); } void WebRuntimeFeatures::enableWebAudio(bool enable) { RuntimeEnabledFeatures::setAudioContextEnabled(enable); } bool WebRuntimeFeatures::isWebAudioEnabled() { return RuntimeEnabledFeatures::audioContextEnabled(); } void WebRuntimeFeatures::enableTouch(bool enable) { RuntimeEnabledFeatures::setTouchEnabled(enable); } bool WebRuntimeFeatures::isTouchEnabled() { return RuntimeEnabledFeatures::touchEnabled(); } void WebRuntimeFeatures::enableDeviceMotion(bool enable) { RuntimeEnabledFeatures::setDeviceMotionEnabled(enable); } bool WebRuntimeFeatures::isDeviceMotionEnabled() { return RuntimeEnabledFeatures::deviceMotionEnabled(); } void WebRuntimeFeatures::enableDeviceOrientation(bool enable) { RuntimeEnabledFeatures::setDeviceOrientationEnabled(enable); } bool WebRuntimeFeatures::isDeviceOrientationEnabled() { return RuntimeEnabledFeatures::deviceOrientationEnabled(); } void WebRuntimeFeatures::enableSpeechInput(bool enable) { RuntimeEnabledFeatures::setSpeechInputEnabled(enable); } bool WebRuntimeFeatures::isSpeechInputEnabled() { return RuntimeEnabledFeatures::speechInputEnabled(); } void WebRuntimeFeatures::enableScriptedSpeech(bool enable) { RuntimeEnabledFeatures::setScriptedSpeechEnabled(enable); } bool WebRuntimeFeatures::isScriptedSpeechEnabled() { return RuntimeEnabledFeatures::scriptedSpeechEnabled(); } void WebRuntimeFeatures::enableXHRResponseBlob(bool enable) { } bool WebRuntimeFeatures::isXHRResponseBlobEnabled() { return true; } void WebRuntimeFeatures::enableFileSystem(bool enable) { RuntimeEnabledFeatures::setFileSystemEnabled(enable); } bool WebRuntimeFeatures::isFileSystemEnabled() { return RuntimeEnabledFeatures::fileSystemEnabled(); } void WebRuntimeFeatures::enableJavaScriptI18NAPI(bool enable) { RuntimeEnabledFeatures::setJavaScriptI18NAPIEnabled(enable); } bool WebRuntimeFeatures::isJavaScriptI18NAPIEnabled() { return RuntimeEnabledFeatures::javaScriptI18NAPIEnabled(); } void WebRuntimeFeatures::enableQuota(bool enable) { RuntimeEnabledFeatures::setQuotaEnabled(enable); } bool WebRuntimeFeatures::isQuotaEnabled() { return RuntimeEnabledFeatures::quotaEnabled(); } void WebRuntimeFeatures::enableMediaStream(bool enable) { RuntimeEnabledFeatures::setMediaStreamEnabled(enable); } bool WebRuntimeFeatures::isMediaStreamEnabled() { return RuntimeEnabledFeatures::mediaStreamEnabled(); } void WebRuntimeFeatures::enablePeerConnection(bool enable) { RuntimeEnabledFeatures::setPeerConnectionEnabled(enable); } bool WebRuntimeFeatures::isPeerConnectionEnabled() { return RuntimeEnabledFeatures::peerConnectionEnabled(); } void WebRuntimeFeatures::enableFullScreenAPI(bool enable) { RuntimeEnabledFeatures::setFullscreenEnabled(enable); } bool WebRuntimeFeatures::isFullScreenAPIEnabled() { return RuntimeEnabledFeatures::fullscreenEnabled(); } void WebRuntimeFeatures::enableMediaSource(bool enable) { RuntimeEnabledFeatures::setMediaSourceEnabled(enable); } bool WebRuntimeFeatures::isMediaSourceEnabled() { return RuntimeEnabledFeatures::mediaSourceEnabled(); } void WebRuntimeFeatures::enableEncryptedMedia(bool enable) { RuntimeEnabledFeatures::setEncryptedMediaEnabled(enable); } bool WebRuntimeFeatures::isEncryptedMediaEnabled() { return RuntimeEnabledFeatures::encryptedMediaEnabled(); } void WebRuntimeFeatures::enableVideoTrack(bool enable) { RuntimeEnabledFeatures::setWebkitVideoTrackEnabled(enable); } bool WebRuntimeFeatures::isVideoTrackEnabled() { return RuntimeEnabledFeatures::webkitVideoTrackEnabled(); } void WebRuntimeFeatures::enableGamepad(bool enable) { RuntimeEnabledFeatures::setWebkitGetGamepadsEnabled(enable); } bool WebRuntimeFeatures::isGamepadEnabled() { return RuntimeEnabledFeatures::webkitGetGamepadsEnabled(); } void WebRuntimeFeatures::enableExperimentalShadowDOM(bool enable) { RuntimeEnabledFeatures::setExperimentalShadowDOMEnabled(enable); } bool WebRuntimeFeatures::isExperimentalShadowDOMEnabled() { return RuntimeEnabledFeatures::experimentalShadowDOMEnabled(); } void WebRuntimeFeatures::enableCustomDOMElements(bool enable) { RuntimeEnabledFeatures::setCustomDOMElementsEnabled(enable); } bool WebRuntimeFeatures::isCustomDOMElementsEnabled() { return RuntimeEnabledFeatures::customDOMElementsEnabled(); } void WebRuntimeFeatures::enableStyleScoped(bool enable) { RuntimeEnabledFeatures::setStyleScopedEnabled(enable); } bool WebRuntimeFeatures::isStyleScopedEnabled() { return RuntimeEnabledFeatures::styleScopedEnabled(); } void WebRuntimeFeatures::enableInputTypeDateTime(bool enable) { RuntimeEnabledFeatures::setInputTypeDateTimeEnabled(enable); } bool WebRuntimeFeatures::isInputTypeDateTimeEnabled() { return RuntimeEnabledFeatures::inputTypeDateTimeEnabled(); } void WebRuntimeFeatures::enableInputTypeWeek(bool enable) { RuntimeEnabledFeatures::setInputTypeWeekEnabled(enable); } bool WebRuntimeFeatures::isInputTypeWeekEnabled() { return RuntimeEnabledFeatures::inputTypeWeekEnabled(); } void WebRuntimeFeatures::enableDialogElement(bool enable) { RuntimeEnabledFeatures::setDialogElementEnabled(enable); } bool WebRuntimeFeatures::isDialogElementEnabled() { return RuntimeEnabledFeatures::dialogElementEnabled(); } void WebRuntimeFeatures::enableLazyLayout(bool enable) { RuntimeEnabledFeatures::setLazyLayoutEnabled(enable); } bool WebRuntimeFeatures::isLazyLayoutEnabled() { return RuntimeEnabledFeatures::lazyLayoutEnabled(); } void WebRuntimeFeatures::enableExperimentalContentSecurityPolicyFeatures(bool enable) { RuntimeEnabledFeatures::setExperimentalContentSecurityPolicyFeaturesEnabled(enable); } bool WebRuntimeFeatures::isExperimentalContentSecurityPolicyFeaturesEnabled() { return RuntimeEnabledFeatures::experimentalContentSecurityPolicyFeaturesEnabled(); } void WebRuntimeFeatures::enableSeamlessIFrames(bool enable) { return RuntimeEnabledFeatures::setSeamlessIFramesEnabled(enable); } bool WebRuntimeFeatures::areSeamlessIFramesEnabled() { return RuntimeEnabledFeatures::seamlessIFramesEnabled(); } void WebRuntimeFeatures::enableCanvasPath(bool enable) { RuntimeEnabledFeatures::setCanvasPathEnabled(enable); } bool WebRuntimeFeatures::isCanvasPathEnabled() { return RuntimeEnabledFeatures::canvasPathEnabled(); } void WebRuntimeFeatures::enableCSSExclusions(bool enable) { RuntimeEnabledFeatures::setCSSExclusionsEnabled(enable); } bool WebRuntimeFeatures::isCSSExclusionsEnabled() { return RuntimeEnabledFeatures::cssExclusionsEnabled(); } void WebRuntimeFeatures::enableCSSRegions(bool enable) { RuntimeEnabledFeatures::setCSSRegionsEnabled(enable); } bool WebRuntimeFeatures::isCSSRegionsEnabled() { return RuntimeEnabledFeatures::cssRegionsEnabled(); } void WebRuntimeFeatures::enableCSSCompositing(bool enable) { RuntimeEnabledFeatures::setCSSCompositingEnabled(enable); } bool WebRuntimeFeatures::isCSSCompositingEnabled() { return RuntimeEnabledFeatures::cssCompositingEnabled(); } void WebRuntimeFeatures::enableFontLoadEvents(bool enable) { RuntimeEnabledFeatures::setFontLoadEventsEnabled(enable); } bool WebRuntimeFeatures::isFontLoadEventsEnabled() { return RuntimeEnabledFeatures::fontLoadEventsEnabled(); } void WebRuntimeFeatures::enableRequestAutocomplete(bool enable) { RuntimeEnabledFeatures::setRequestAutocompleteEnabled(enable); } bool WebRuntimeFeatures::isRequestAutocompleteEnabled() { return RuntimeEnabledFeatures::requestAutocompleteEnabled(); } void WebRuntimeFeatures::enableWebPInAcceptHeader(bool enable) { RuntimeEnabledFeatures::setWebPInAcceptHeaderEnabled(enable); } bool WebRuntimeFeatures::isWebPInAcceptHeaderEnabled() { return RuntimeEnabledFeatures::webPInAcceptHeaderEnabled(); } void WebRuntimeFeatures::enableDirectoryUpload(bool enable) { RuntimeEnabledFeatures::setDirectoryUploadEnabled(enable); } bool WebRuntimeFeatures::isDirectoryUploadEnabled() { return RuntimeEnabledFeatures::directoryUploadEnabled(); } void WebRuntimeFeatures::enableExperimentalWebSocket(bool enable) { RuntimeEnabledFeatures::setExperimentalWebSocketEnabled(enable); } bool WebRuntimeFeatures::isExperimentalWebSocketEnabled() { return RuntimeEnabledFeatures::experimentalWebSocketEnabled(); } void WebRuntimeFeatures::enableWebMIDI(bool enable) { return RuntimeEnabledFeatures::setWebMIDIEnabled(enable); } bool WebRuntimeFeatures::isWebMIDIEnabled() { return RuntimeEnabledFeatures::webMIDIEnabled(); } void WebRuntimeFeatures::enableIMEAPI(bool enable) { RuntimeEnabledFeatures::setIMEAPIEnabled(enable); } bool WebRuntimeFeatures::isIMEAPIEnabled() { return RuntimeEnabledFeatures::imeAPIEnabled(); } void WebRuntimeFeatures::enableExperimentalCanvasFeatures(bool enable) { RuntimeEnabledFeatures::setExperimentalCanvasFeaturesEnabled(enable); } bool WebRuntimeFeatures::areExperimentalCanvasFeaturesEnabled() { return RuntimeEnabledFeatures::experimentalCanvasFeaturesEnabled(); } void WebRuntimeFeatures::enableSpeechSynthesis(bool enable) { RuntimeEnabledFeatures::setSpeechSynthesisEnabled(enable); } bool WebRuntimeFeatures::isSpeechSynthesisEnabled() { return RuntimeEnabledFeatures::speechSynthesisEnabled(); } } // namespace WebKit <|endoftext|>
<commit_before>#include <iostream> #include <string> #include <chrono> #include "args.h" #include "load_scene.h" #include "render/render_target.h" #include "driver.h" #ifdef BUILD_PREVIEWER #include "previewer.h" #endif const static std::string USAGE = "Usage for prj1:\n\ ----------------------------\n\ -f <file> - Specify the scene file to render\n\ -o <prefix> - Specify the prefix name for the output files\n\ color is written to <prefix>.ppm and depth to\n\ <prefix>.pgm\n\ -n <num> - Optional: specify the number of threads to render with,\n\ this number will be rounded up to the nearest even number.\n\ A warning will be printed if we can't evenly partition the\n\ image into <num> rectangles for rendering. Default is 1.\n\ -h - Show this help information\n" #ifdef BUILD_PREVIEWER + std::string{"-p - Show a live preview of the image as it's rendered.\n\ Rendering performance is not measured in this mode\n"} #endif + std::string{"----------------------------\n"}; int main(int argc, char **argv){ if (flag(argv, argv + argc, "-h")){ std::cout << USAGE; return 0; } if (!flag(argv, argv + argc, "-f")){ std::cerr << "Error: No scene file passed\n" << USAGE; return 1; } //if we built the previewer it's valid to not specify a file output but //we need some way to output #ifdef BUILD_PREVIEWER if (!flag(argv, argv + argc, "-o") && !flag(argv, argv + argc, "-p")){ std::cerr << "Error: No output medium specified\n" << USAGE; return 1; } #else if (!flag(argv, argv + argc, "-o")){ std::cerr << "Error: No output filename passed\n" << USAGE; return 1; } #endif int n_threads = 1; if (flag(argv, argv + argc, "-n")){ n_threads = get_param<int>(argv, argv + argc, "-n"); if (n_threads > 1 && n_threads % 2 != 0){ std::cerr << "Warning: num threads not even, increasing thread count by 1\n"; ++n_threads; } } std::string scene_file = get_param<std::string>(argv, argv + argc, "-f"); Scene scene = load_scene(scene_file); Driver driver{scene, n_threads}; #ifdef BUILD_PREVIEWER if (flag(argv, argv + argc, "-p")){ //The user might abort before rendering completes or we could encounter //an SDL/OpenGL error, so don't save the images if the render doesn't complete //Also need to validate that file output was turned on if we're running the previewer if (render_with_preview(driver) && flag(argv, argv + argc, "-o")){ std::string out_file = get_param<std::string>(argv, argv + argc, "-o"); RenderTarget &target = scene.get_render_target(); target.save_image(out_file + ".ppm"); target.save_depth(out_file + ".pgm"); } return 0; } else { #endif auto start = std::chrono::high_resolution_clock::now(); //While the driver is rendering defer priority to the worker threads driver.render(); while (!driver.done()){ std::this_thread::yield(); } auto end = std::chrono::high_resolution_clock::now(); auto elapsed = end - start; std::cout << "Rendering took: " << std::chrono::duration_cast<std::chrono::milliseconds>(elapsed).count() << "ms\n"; #ifdef BUILD_PREVIEWER } #endif std::string out_file = get_param<std::string>(argv, argv + argc, "-o"); RenderTarget &target = scene.get_render_target(); target.save_image(out_file + ".ppm"); target.save_depth(out_file + ".pgm"); return 0; } <commit_msg>Now print an error if no filename passed<commit_after>#include <iostream> #include <string> #include <chrono> #include "args.h" #include "load_scene.h" #include "render/render_target.h" #include "driver.h" #ifdef BUILD_PREVIEWER #include "previewer.h" #endif const static std::string USAGE = "Usage for prj1:\n\ ----------------------------\n\ -f <file> - Specify the scene file to render\n\ -o <prefix> - Specify the prefix name for the output files\n\ color is written to <prefix>.ppm and depth to\n\ <prefix>.pgm\n\ -n <num> - Optional: specify the number of threads to render with,\n\ this number will be rounded up to the nearest even number.\n\ A warning will be printed if we can't evenly partition the\n\ image into <num> rectangles for rendering. Default is 1.\n\ -h - Show this help information\n" #ifdef BUILD_PREVIEWER + std::string{"-p - Show a live preview of the image as it's rendered.\n\ Rendering performance is not measured in this mode\n"} #endif + std::string{"----------------------------\n"}; int main(int argc, char **argv){ if (flag(argv, argv + argc, "-h")){ std::cout << USAGE; return 0; } if (!flag(argv, argv + argc, "-f")){ std::cerr << "Error: No scene file passed\n" << USAGE; return 1; } //if we built the previewer it's valid to not specify a file output but //we need some way to output #ifdef BUILD_PREVIEWER if (!flag(argv, argv + argc, "-o") && !flag(argv, argv + argc, "-p")){ std::cerr << "Error: No output medium specified\n" << USAGE; return 1; } #else if (!flag(argv, argv + argc, "-o")){ std::cerr << "Error: No output filename passed\n" << USAGE; return 1; } #endif int n_threads = 1; if (flag(argv, argv + argc, "-n")){ n_threads = get_param<int>(argv, argv + argc, "-n"); if (n_threads > 1 && n_threads % 2 != 0){ std::cerr << "Warning: num threads not even, increasing thread count by 1\n"; ++n_threads; } } std::string scene_file = get_param<std::string>(argv, argv + argc, "-f"); Scene scene = load_scene(scene_file); Driver driver{scene, n_threads}; #ifdef BUILD_PREVIEWER if (flag(argv, argv + argc, "-p")){ //The user might abort before rendering completes or we could encounter //an SDL/OpenGL error, so don't save the images if the render doesn't complete //Also need to validate that file output was turned on if we're running the previewer if (render_with_preview(driver) && flag(argv, argv + argc, "-o")){ std::string out_file = get_param<std::string>(argv, argv + argc, "-o"); if (out_file.empty()){ std::cerr << "Error: No output filename specified\n"; return 1; } RenderTarget &target = scene.get_render_target(); target.save_image(out_file + ".ppm"); target.save_depth(out_file + ".pgm"); } return 0; } else { #endif auto start = std::chrono::high_resolution_clock::now(); //While the driver is rendering defer priority to the worker threads driver.render(); while (!driver.done()){ std::this_thread::yield(); } auto end = std::chrono::high_resolution_clock::now(); auto elapsed = end - start; std::cout << "Rendering took: " << std::chrono::duration_cast<std::chrono::milliseconds>(elapsed).count() << "ms\n"; #ifdef BUILD_PREVIEWER } #endif std::string out_file = get_param<std::string>(argv, argv + argc, "-o"); if (out_file.empty()){ std::cerr << "Error: No output filename specified\n"; return 1; } RenderTarget &target = scene.get_render_target(); target.save_image(out_file + ".ppm"); target.save_depth(out_file + ".pgm"); return 0; } <|endoftext|>
<commit_before>/* * Copyright (C) 2006, 2007 Apple Computer, Inc. * Copyright (c) 2006, 2007, 2008, 2009, 2012 Google Inc. 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 Google Inc. nor the names of its * contributors may be used to endorse or promote products derived from * this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #include "config.h" #include "platform/fonts/FontPlatformData.h" #include "platform/LayoutTestSupport.h" #include "platform/fonts/FontCache.h" #if USE(HARFBUZZ) #include "platform/fonts/harfbuzz/HarfBuzzFace.h" #endif #include "platform/fonts/skia/SkiaFontWin.h" #include "platform/graphics/GraphicsContext.h" #include "platform/win/HWndDC.h" #include "public/platform/Platform.h" #include "public/platform/win/WebSandboxSupport.h" #include "wtf/PassOwnPtr.h" #include "wtf/StdLibExtras.h" #include <mlang.h> #include <objidl.h> #include <windows.h> namespace WebCore { void FontPlatformData::setupPaint(SkPaint* paint, GraphicsContext* context) const { const float ts = m_textSize >= 0 ? m_textSize : 12; paint->setTextSize(SkFloatToScalar(m_textSize)); paint->setTypeface(typeface()); paint->setFakeBoldText(m_syntheticBold); paint->setTextSkewX(m_syntheticItalic ? -SK_Scalar1 / 4 : 0); paint->setSubpixelText(m_useSubpixelPositioning); int textFlags = paintTextFlags(); // Only set painting flags when we're actually painting. if (context && !context->couldUseLCDRenderedText()) { textFlags &= ~SkPaint::kLCDRenderText_Flag; // If we *just* clear our request for LCD, then GDI seems to // sometimes give us AA text, and sometimes give us BW text. Since the // original intent was LCD, we want to force AA (rather than BW), so we // add a special bit to tell Skia to do its best to avoid the BW: by // drawing LCD offscreen and downsampling that to AA. textFlags |= SkPaint::kGenA8FromLCD_Flag; } static const uint32_t textFlagsMask = SkPaint::kAntiAlias_Flag | SkPaint::kLCDRenderText_Flag | SkPaint::kGenA8FromLCD_Flag; SkASSERT(!(textFlags & ~textFlagsMask)); uint32_t flags = paint->getFlags(); flags &= ~textFlagsMask; flags |= textFlags; paint->setFlags(flags); } // Lookup the current system settings for font smoothing. // We cache these values for performance, but if the browser has a way to be // notified when these change, we could re-query them at that time. static uint32_t getSystemTextFlags() { static bool gInited; static uint32_t gFlags; if (!gInited) { BOOL enabled; gFlags = 0; if (SystemParametersInfo(SPI_GETFONTSMOOTHING, 0, &enabled, 0) && enabled) { gFlags |= SkPaint::kAntiAlias_Flag; UINT smoothType; if (SystemParametersInfo(SPI_GETFONTSMOOTHINGTYPE, 0, &smoothType, 0)) { if (FE_FONTSMOOTHINGCLEARTYPE == smoothType) gFlags |= SkPaint::kLCDRenderText_Flag; } } gInited = true; } return gFlags; } static bool isWebFont(const String& familyName) { // Web-fonts have artifical names constructed to always be: // 1. 24 characters, followed by a '\0' // 2. the last two characters are '==' return familyName.length() == 24 && '=' == familyName[22] && '=' == familyName[23]; } static int computePaintTextFlags(String fontFamilyName) { int textFlags = getSystemTextFlags(); // Many web-fonts are so poorly hinted that they are terrible to read when drawn in BW. // In these cases, we have decided to FORCE these fonts to be drawn with at least grayscale AA, // even when the System (getSystemTextFlags) tells us to draw only in BW. if (isWebFont(fontFamilyName) && !isRunningLayoutTest()) textFlags |= SkPaint::kAntiAlias_Flag; return textFlags; } #if !USE(HARFBUZZ) PassRefPtr<SkTypeface> CreateTypefaceFromHFont(HFONT hfont, int* size) { LOGFONT info; GetObject(hfont, sizeof(info), &info); if (size) { int height = info.lfHeight; if (height < 0) height = -height; *size = height; } return adoptRef(SkCreateTypefaceFromLOGFONT(info)); } #endif FontPlatformData::FontPlatformData(WTF::HashTableDeletedValueType) : m_textSize(-1) , m_syntheticBold(false) , m_syntheticItalic(false) , m_orientation(Horizontal) , m_typeface(adoptRef(SkTypeface::RefDefault())) , m_paintTextFlags(0) , m_isHashTableDeletedValue(true) , m_useSubpixelPositioning(false) { #if !USE(HARFBUZZ) m_font = 0; m_scriptCache = 0; #endif } FontPlatformData::FontPlatformData() : m_textSize(0) , m_syntheticBold(false) , m_syntheticItalic(false) , m_orientation(Horizontal) , m_typeface(adoptRef(SkTypeface::RefDefault())) , m_paintTextFlags(0) , m_isHashTableDeletedValue(false) , m_useSubpixelPositioning(false) { #if !USE(HARFBUZZ) m_font = 0; m_scriptCache = 0; #endif } // FIXME: this constructor is needed for SVG fonts but doesn't seem to do much FontPlatformData::FontPlatformData(float size, bool bold, bool oblique) : m_textSize(size) , m_syntheticBold(false) , m_syntheticItalic(false) , m_orientation(Horizontal) , m_typeface(adoptRef(SkTypeface::RefDefault())) , m_paintTextFlags(0) , m_isHashTableDeletedValue(false) , m_useSubpixelPositioning(false) { #if !USE(HARFBUZZ) m_font = 0; m_scriptCache = 0; #endif } FontPlatformData::FontPlatformData(const FontPlatformData& data) : m_textSize(data.m_textSize) , m_syntheticBold(data.m_syntheticBold) , m_syntheticItalic(data.m_syntheticItalic) , m_orientation(data.m_orientation) , m_typeface(data.m_typeface) , m_paintTextFlags(data.m_paintTextFlags) , m_isHashTableDeletedValue(false) , m_useSubpixelPositioning(data.m_useSubpixelPositioning) { #if !USE(HARFBUZZ) m_font = data.m_font; m_scriptCache = 0; #endif } FontPlatformData::FontPlatformData(const FontPlatformData& data, float textSize) : m_textSize(textSize) , m_syntheticBold(data.m_syntheticBold) , m_syntheticItalic(data.m_syntheticItalic) , m_orientation(data.m_orientation) , m_typeface(data.m_typeface) , m_paintTextFlags(data.m_paintTextFlags) , m_isHashTableDeletedValue(false) , m_useSubpixelPositioning(data.m_useSubpixelPositioning) { #if !USE(HARFBUZZ) m_font = data.m_font; m_scriptCache = 0; #endif } FontPlatformData::FontPlatformData(PassRefPtr<SkTypeface> tf, const char* family, float textSize, bool syntheticBold, bool syntheticItalic, FontOrientation orientation, bool useSubpixelPositioning) : m_textSize(textSize) , m_syntheticBold(syntheticBold) , m_syntheticItalic(syntheticItalic) , m_orientation(orientation) , m_typeface(tf) , m_isHashTableDeletedValue(false) , m_useSubpixelPositioning(useSubpixelPositioning) { m_paintTextFlags = computePaintTextFlags(fontFamilyName()); #if !USE(HARFBUZZ) // FIXME: This can be removed together with m_font once the last few // uses of hfont() has been eliminated. LOGFONT logFont; SkLOGFONTFromTypeface(m_typeface.get(), &logFont); logFont.lfHeight = -textSize; HFONT hFont = CreateFontIndirect(&logFont); m_font = hFont ? RefCountedHFONT::create(hFont) : 0; m_scriptCache = 0; #endif } FontPlatformData& FontPlatformData::operator=(const FontPlatformData& data) { if (this != &data) { m_textSize = data.m_textSize; m_syntheticBold = data.m_syntheticBold; m_syntheticItalic = data.m_syntheticItalic; m_orientation = data.m_orientation; m_typeface = data.m_typeface; m_paintTextFlags = data.m_paintTextFlags; #if !USE(HARFBUZZ) m_font = data.m_font; // The following fields will get re-computed if necessary. ScriptFreeCache(&m_scriptCache); m_scriptCache = 0; m_scriptFontProperties.clear(); #endif } return *this; } FontPlatformData::~FontPlatformData() { #if !USE(HARFBUZZ) ScriptFreeCache(&m_scriptCache); m_scriptCache = 0; #endif } String FontPlatformData::fontFamilyName() const { // FIXME: This returns the requested name, perhaps a better solution would be to // return the list of names provided by SkTypeface::createFamilyNameIterator. ASSERT(typeface()); SkString familyName; typeface()->getFamilyName(&familyName); return String::fromUTF8(familyName.c_str()); } bool FontPlatformData::isFixedPitch() const { return typeface() && typeface()->isFixedPitch(); } bool FontPlatformData::operator==(const FontPlatformData& a) const { return SkTypeface::Equal(m_typeface.get(), a.m_typeface.get()) && m_textSize == a.m_textSize && m_syntheticBold == a.m_syntheticBold && m_syntheticItalic == a.m_syntheticItalic && m_orientation == a.m_orientation && m_isHashTableDeletedValue == a.m_isHashTableDeletedValue; } #if USE(HARFBUZZ) HarfBuzzFace* FontPlatformData::harfBuzzFace() const { if (!m_harfBuzzFace) m_harfBuzzFace = HarfBuzzFace::create(const_cast<FontPlatformData*>(this), uniqueID()); return m_harfBuzzFace.get(); } #else FontPlatformData::RefCountedHFONT::~RefCountedHFONT() { DeleteObject(m_hfont); } SCRIPT_FONTPROPERTIES* FontPlatformData::scriptFontProperties() const { if (!m_scriptFontProperties) { m_scriptFontProperties = adoptPtr(new SCRIPT_FONTPROPERTIES); memset(m_scriptFontProperties.get(), 0, sizeof(SCRIPT_FONTPROPERTIES)); m_scriptFontProperties->cBytes = sizeof(SCRIPT_FONTPROPERTIES); HRESULT result = ScriptGetFontProperties(0, scriptCache(), m_scriptFontProperties.get()); if (result == E_PENDING) { HWndDC dc(0); HGDIOBJ oldFont = SelectObject(dc, hfont()); HRESULT hr = ScriptGetFontProperties(dc, scriptCache(), m_scriptFontProperties.get()); if (S_OK != hr) { if (FontPlatformData::ensureFontLoaded(hfont())) { // FIXME: Handle gracefully the error if this call also fails. hr = ScriptGetFontProperties(dc, scriptCache(), m_scriptFontProperties.get()); if (S_OK != hr) { WTF_LOG_ERROR("Unable to get the font properties after second attempt"); } } } SelectObject(dc, oldFont); } } return m_scriptFontProperties.get(); } bool FontPlatformData::ensureFontLoaded(HFONT font) { blink::WebSandboxSupport* sandboxSupport = blink::Platform::current()->sandboxSupport(); // if there is no sandbox, then we can assume the font // was able to be loaded successfully already return sandboxSupport ? sandboxSupport->ensureFontLoaded(font) : true; } #endif bool FontPlatformData::defaultUseSubpixelPositioning() { #if OS(WIN) return FontCache::fontCache()->useSubpixelPositioning(); #else return false; #endif } #ifndef NDEBUG String FontPlatformData::description() const { return String(); } #endif } // namespace WebCore <commit_msg>Remove redundant ifdef in FontPlatformDataWin.cpp<commit_after>/* * Copyright (C) 2006, 2007 Apple Computer, Inc. * Copyright (c) 2006, 2007, 2008, 2009, 2012 Google Inc. 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 Google Inc. nor the names of its * contributors may be used to endorse or promote products derived from * this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #include "config.h" #include "platform/fonts/FontPlatformData.h" #include "platform/LayoutTestSupport.h" #include "platform/fonts/FontCache.h" #if USE(HARFBUZZ) #include "platform/fonts/harfbuzz/HarfBuzzFace.h" #endif #include "platform/fonts/skia/SkiaFontWin.h" #include "platform/graphics/GraphicsContext.h" #include "platform/win/HWndDC.h" #include "public/platform/Platform.h" #include "public/platform/win/WebSandboxSupport.h" #include "wtf/PassOwnPtr.h" #include "wtf/StdLibExtras.h" #include <mlang.h> #include <objidl.h> #include <windows.h> namespace WebCore { void FontPlatformData::setupPaint(SkPaint* paint, GraphicsContext* context) const { const float ts = m_textSize >= 0 ? m_textSize : 12; paint->setTextSize(SkFloatToScalar(m_textSize)); paint->setTypeface(typeface()); paint->setFakeBoldText(m_syntheticBold); paint->setTextSkewX(m_syntheticItalic ? -SK_Scalar1 / 4 : 0); paint->setSubpixelText(m_useSubpixelPositioning); int textFlags = paintTextFlags(); // Only set painting flags when we're actually painting. if (context && !context->couldUseLCDRenderedText()) { textFlags &= ~SkPaint::kLCDRenderText_Flag; // If we *just* clear our request for LCD, then GDI seems to // sometimes give us AA text, and sometimes give us BW text. Since the // original intent was LCD, we want to force AA (rather than BW), so we // add a special bit to tell Skia to do its best to avoid the BW: by // drawing LCD offscreen and downsampling that to AA. textFlags |= SkPaint::kGenA8FromLCD_Flag; } static const uint32_t textFlagsMask = SkPaint::kAntiAlias_Flag | SkPaint::kLCDRenderText_Flag | SkPaint::kGenA8FromLCD_Flag; SkASSERT(!(textFlags & ~textFlagsMask)); uint32_t flags = paint->getFlags(); flags &= ~textFlagsMask; flags |= textFlags; paint->setFlags(flags); } // Lookup the current system settings for font smoothing. // We cache these values for performance, but if the browser has a way to be // notified when these change, we could re-query them at that time. static uint32_t getSystemTextFlags() { static bool gInited; static uint32_t gFlags; if (!gInited) { BOOL enabled; gFlags = 0; if (SystemParametersInfo(SPI_GETFONTSMOOTHING, 0, &enabled, 0) && enabled) { gFlags |= SkPaint::kAntiAlias_Flag; UINT smoothType; if (SystemParametersInfo(SPI_GETFONTSMOOTHINGTYPE, 0, &smoothType, 0)) { if (FE_FONTSMOOTHINGCLEARTYPE == smoothType) gFlags |= SkPaint::kLCDRenderText_Flag; } } gInited = true; } return gFlags; } static bool isWebFont(const String& familyName) { // Web-fonts have artifical names constructed to always be: // 1. 24 characters, followed by a '\0' // 2. the last two characters are '==' return familyName.length() == 24 && '=' == familyName[22] && '=' == familyName[23]; } static int computePaintTextFlags(String fontFamilyName) { int textFlags = getSystemTextFlags(); // Many web-fonts are so poorly hinted that they are terrible to read when drawn in BW. // In these cases, we have decided to FORCE these fonts to be drawn with at least grayscale AA, // even when the System (getSystemTextFlags) tells us to draw only in BW. if (isWebFont(fontFamilyName) && !isRunningLayoutTest()) textFlags |= SkPaint::kAntiAlias_Flag; return textFlags; } #if !USE(HARFBUZZ) PassRefPtr<SkTypeface> CreateTypefaceFromHFont(HFONT hfont, int* size) { LOGFONT info; GetObject(hfont, sizeof(info), &info); if (size) { int height = info.lfHeight; if (height < 0) height = -height; *size = height; } return adoptRef(SkCreateTypefaceFromLOGFONT(info)); } #endif FontPlatformData::FontPlatformData(WTF::HashTableDeletedValueType) : m_textSize(-1) , m_syntheticBold(false) , m_syntheticItalic(false) , m_orientation(Horizontal) , m_typeface(adoptRef(SkTypeface::RefDefault())) , m_paintTextFlags(0) , m_isHashTableDeletedValue(true) , m_useSubpixelPositioning(false) { #if !USE(HARFBUZZ) m_font = 0; m_scriptCache = 0; #endif } FontPlatformData::FontPlatformData() : m_textSize(0) , m_syntheticBold(false) , m_syntheticItalic(false) , m_orientation(Horizontal) , m_typeface(adoptRef(SkTypeface::RefDefault())) , m_paintTextFlags(0) , m_isHashTableDeletedValue(false) , m_useSubpixelPositioning(false) { #if !USE(HARFBUZZ) m_font = 0; m_scriptCache = 0; #endif } // FIXME: this constructor is needed for SVG fonts but doesn't seem to do much FontPlatformData::FontPlatformData(float size, bool bold, bool oblique) : m_textSize(size) , m_syntheticBold(false) , m_syntheticItalic(false) , m_orientation(Horizontal) , m_typeface(adoptRef(SkTypeface::RefDefault())) , m_paintTextFlags(0) , m_isHashTableDeletedValue(false) , m_useSubpixelPositioning(false) { #if !USE(HARFBUZZ) m_font = 0; m_scriptCache = 0; #endif } FontPlatformData::FontPlatformData(const FontPlatformData& data) : m_textSize(data.m_textSize) , m_syntheticBold(data.m_syntheticBold) , m_syntheticItalic(data.m_syntheticItalic) , m_orientation(data.m_orientation) , m_typeface(data.m_typeface) , m_paintTextFlags(data.m_paintTextFlags) , m_isHashTableDeletedValue(false) , m_useSubpixelPositioning(data.m_useSubpixelPositioning) { #if !USE(HARFBUZZ) m_font = data.m_font; m_scriptCache = 0; #endif } FontPlatformData::FontPlatformData(const FontPlatformData& data, float textSize) : m_textSize(textSize) , m_syntheticBold(data.m_syntheticBold) , m_syntheticItalic(data.m_syntheticItalic) , m_orientation(data.m_orientation) , m_typeface(data.m_typeface) , m_paintTextFlags(data.m_paintTextFlags) , m_isHashTableDeletedValue(false) , m_useSubpixelPositioning(data.m_useSubpixelPositioning) { #if !USE(HARFBUZZ) m_font = data.m_font; m_scriptCache = 0; #endif } FontPlatformData::FontPlatformData(PassRefPtr<SkTypeface> tf, const char* family, float textSize, bool syntheticBold, bool syntheticItalic, FontOrientation orientation, bool useSubpixelPositioning) : m_textSize(textSize) , m_syntheticBold(syntheticBold) , m_syntheticItalic(syntheticItalic) , m_orientation(orientation) , m_typeface(tf) , m_isHashTableDeletedValue(false) , m_useSubpixelPositioning(useSubpixelPositioning) { m_paintTextFlags = computePaintTextFlags(fontFamilyName()); #if !USE(HARFBUZZ) // FIXME: This can be removed together with m_font once the last few // uses of hfont() has been eliminated. LOGFONT logFont; SkLOGFONTFromTypeface(m_typeface.get(), &logFont); logFont.lfHeight = -textSize; HFONT hFont = CreateFontIndirect(&logFont); m_font = hFont ? RefCountedHFONT::create(hFont) : 0; m_scriptCache = 0; #endif } FontPlatformData& FontPlatformData::operator=(const FontPlatformData& data) { if (this != &data) { m_textSize = data.m_textSize; m_syntheticBold = data.m_syntheticBold; m_syntheticItalic = data.m_syntheticItalic; m_orientation = data.m_orientation; m_typeface = data.m_typeface; m_paintTextFlags = data.m_paintTextFlags; #if !USE(HARFBUZZ) m_font = data.m_font; // The following fields will get re-computed if necessary. ScriptFreeCache(&m_scriptCache); m_scriptCache = 0; m_scriptFontProperties.clear(); #endif } return *this; } FontPlatformData::~FontPlatformData() { #if !USE(HARFBUZZ) ScriptFreeCache(&m_scriptCache); m_scriptCache = 0; #endif } String FontPlatformData::fontFamilyName() const { // FIXME: This returns the requested name, perhaps a better solution would be to // return the list of names provided by SkTypeface::createFamilyNameIterator. ASSERT(typeface()); SkString familyName; typeface()->getFamilyName(&familyName); return String::fromUTF8(familyName.c_str()); } bool FontPlatformData::isFixedPitch() const { return typeface() && typeface()->isFixedPitch(); } bool FontPlatformData::operator==(const FontPlatformData& a) const { return SkTypeface::Equal(m_typeface.get(), a.m_typeface.get()) && m_textSize == a.m_textSize && m_syntheticBold == a.m_syntheticBold && m_syntheticItalic == a.m_syntheticItalic && m_orientation == a.m_orientation && m_isHashTableDeletedValue == a.m_isHashTableDeletedValue; } #if USE(HARFBUZZ) HarfBuzzFace* FontPlatformData::harfBuzzFace() const { if (!m_harfBuzzFace) m_harfBuzzFace = HarfBuzzFace::create(const_cast<FontPlatformData*>(this), uniqueID()); return m_harfBuzzFace.get(); } #else FontPlatformData::RefCountedHFONT::~RefCountedHFONT() { DeleteObject(m_hfont); } SCRIPT_FONTPROPERTIES* FontPlatformData::scriptFontProperties() const { if (!m_scriptFontProperties) { m_scriptFontProperties = adoptPtr(new SCRIPT_FONTPROPERTIES); memset(m_scriptFontProperties.get(), 0, sizeof(SCRIPT_FONTPROPERTIES)); m_scriptFontProperties->cBytes = sizeof(SCRIPT_FONTPROPERTIES); HRESULT result = ScriptGetFontProperties(0, scriptCache(), m_scriptFontProperties.get()); if (result == E_PENDING) { HWndDC dc(0); HGDIOBJ oldFont = SelectObject(dc, hfont()); HRESULT hr = ScriptGetFontProperties(dc, scriptCache(), m_scriptFontProperties.get()); if (S_OK != hr) { if (FontPlatformData::ensureFontLoaded(hfont())) { // FIXME: Handle gracefully the error if this call also fails. hr = ScriptGetFontProperties(dc, scriptCache(), m_scriptFontProperties.get()); if (S_OK != hr) { WTF_LOG_ERROR("Unable to get the font properties after second attempt"); } } } SelectObject(dc, oldFont); } } return m_scriptFontProperties.get(); } bool FontPlatformData::ensureFontLoaded(HFONT font) { blink::WebSandboxSupport* sandboxSupport = blink::Platform::current()->sandboxSupport(); // if there is no sandbox, then we can assume the font // was able to be loaded successfully already return sandboxSupport ? sandboxSupport->ensureFontLoaded(font) : true; } #endif bool FontPlatformData::defaultUseSubpixelPositioning() { return FontCache::fontCache()->useSubpixelPositioning(); } #ifndef NDEBUG String FontPlatformData::description() const { return String(); } #endif } // namespace WebCore <|endoftext|>
<commit_before>/* * (C) Copyright 2014 Kurento (http://kurento.org/) * * 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. * */ #define BOOST_TEST_DYN_LINK #define BOOST_TEST_MODULE Serializer #include <boost/test/unit_test.hpp> #include <jsonrpc/JsonSerializer.hpp> #include <map> #include <iostream> BOOST_AUTO_TEST_CASE (serialize_map) { std::map<std::string, int> intMap; std::map<std::string, int> newMap; kurento::JsonSerializer writer (true); kurento::JsonSerializer writer2 (true); kurento::JsonSerializer reader (false); intMap ["key1"] = 1; intMap ["key2"] = 2; writer.Serialize ("map", intMap); reader.JsonValue = writer.JsonValue; reader.Serialize ("map", newMap); writer2.Serialize ("map", newMap); BOOST_ASSERT (writer.JsonValue.toStyledString() == writer2.JsonValue.toStyledString() ); } BOOST_AUTO_TEST_CASE (serialize_map_of_map) { std::map<std::string, int> intMap; std::map<std::string, int> intMap2; std::map<std::string, std::map<std::string, int>> mapMap; std::map<std::string, std::map<std::string, int>> newMap; kurento::JsonSerializer writer (true); kurento::JsonSerializer writer2 (true); kurento::JsonSerializer reader (false); intMap ["key1"] = 1; intMap ["key2"] = 2; intMap2 ["key3"] = 3; intMap2 ["key4"] = 4; mapMap ["map1"] = intMap; mapMap ["map2"] = intMap2; writer.Serialize ("map", mapMap); reader.JsonValue = writer.JsonValue; reader.Serialize ("map", newMap); writer2.Serialize ("map", newMap); BOOST_ASSERT (writer.JsonValue.toStyledString() == writer2.JsonValue.toStyledString() ); } BOOST_AUTO_TEST_CASE (serialize_empty_array) { std::vector <int> array; std::vector <int> newArray; kurento::JsonSerializer writer (true); kurento::JsonSerializer writer2 (true); kurento::JsonSerializer reader (false); writer.Serialize ("array", array); reader.JsonValue = writer.JsonValue; reader.Serialize ("array", newArray); BOOST_ASSERT (writer.JsonValue.toStyledString().find ("[]") != std::string::npos ); writer2.Serialize ("array", newArray); BOOST_ASSERT (writer.JsonValue.toStyledString() == writer2.JsonValue.toStyledString() ); } BOOST_AUTO_TEST_CASE (serialize_list) { std::list <std::string> array; std::list <std::string> newArray; kurento::JsonSerializer writer (true); kurento::JsonSerializer writer2 (true); kurento::JsonSerializer reader (false); array.push_back ("first"); array.push_back ("2"); array.push_back ("three"); writer.Serialize ("array", array); reader.JsonValue = writer.JsonValue; reader.Serialize ("array", newArray); writer2.Serialize ("array", newArray); BOOST_ASSERT (writer.JsonValue.toStyledString() == writer2.JsonValue.toStyledString() ); } BOOST_AUTO_TEST_CASE (serialize_vector) { std::vector <int> array; std::vector <int> newArray; kurento::JsonSerializer writer (true); kurento::JsonSerializer writer2 (true); kurento::JsonSerializer reader (false); array.push_back (1); array.push_back (2); array.push_back (3); writer.Serialize ("array", array); reader.JsonValue = writer.JsonValue; reader.Serialize ("array", newArray); writer2.Serialize ("array", newArray); BOOST_ASSERT (writer.JsonValue.toStyledString() == writer2.JsonValue.toStyledString() ); } BOOST_AUTO_TEST_CASE (serialize_int64) { int64_t data = LLONG_MAX; int64_t newData = 0; kurento::JsonSerializer writer (true); kurento::JsonSerializer writer2 (true); kurento::JsonSerializer reader (false); writer.Serialize ("intValue", data); std::cout << writer.JsonValue.toStyledString () << std::endl; reader.JsonValue = writer.JsonValue; reader.Serialize ("intValue", newData); writer2.Serialize ("intValue", newData); std::cout << "old value " << data << " new value " << newData << std::endl; BOOST_ASSERT (writer.JsonValue.toStyledString() == writer2.JsonValue.toStyledString() ); } <commit_msg>clang-tidy fix: [modernize-use-emplace]<commit_after>/* * (C) Copyright 2014 Kurento (http://kurento.org/) * * 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. * */ #define BOOST_TEST_DYN_LINK #define BOOST_TEST_MODULE Serializer #include <boost/test/unit_test.hpp> #include <jsonrpc/JsonSerializer.hpp> #include <map> #include <iostream> BOOST_AUTO_TEST_CASE (serialize_map) { std::map<std::string, int> intMap; std::map<std::string, int> newMap; kurento::JsonSerializer writer (true); kurento::JsonSerializer writer2 (true); kurento::JsonSerializer reader (false); intMap ["key1"] = 1; intMap ["key2"] = 2; writer.Serialize ("map", intMap); reader.JsonValue = writer.JsonValue; reader.Serialize ("map", newMap); writer2.Serialize ("map", newMap); BOOST_ASSERT (writer.JsonValue.toStyledString() == writer2.JsonValue.toStyledString() ); } BOOST_AUTO_TEST_CASE (serialize_map_of_map) { std::map<std::string, int> intMap; std::map<std::string, int> intMap2; std::map<std::string, std::map<std::string, int>> mapMap; std::map<std::string, std::map<std::string, int>> newMap; kurento::JsonSerializer writer (true); kurento::JsonSerializer writer2 (true); kurento::JsonSerializer reader (false); intMap ["key1"] = 1; intMap ["key2"] = 2; intMap2 ["key3"] = 3; intMap2 ["key4"] = 4; mapMap ["map1"] = intMap; mapMap ["map2"] = intMap2; writer.Serialize ("map", mapMap); reader.JsonValue = writer.JsonValue; reader.Serialize ("map", newMap); writer2.Serialize ("map", newMap); BOOST_ASSERT (writer.JsonValue.toStyledString() == writer2.JsonValue.toStyledString() ); } BOOST_AUTO_TEST_CASE (serialize_empty_array) { std::vector <int> array; std::vector <int> newArray; kurento::JsonSerializer writer (true); kurento::JsonSerializer writer2 (true); kurento::JsonSerializer reader (false); writer.Serialize ("array", array); reader.JsonValue = writer.JsonValue; reader.Serialize ("array", newArray); BOOST_ASSERT (writer.JsonValue.toStyledString().find ("[]") != std::string::npos ); writer2.Serialize ("array", newArray); BOOST_ASSERT (writer.JsonValue.toStyledString() == writer2.JsonValue.toStyledString() ); } BOOST_AUTO_TEST_CASE (serialize_list) { std::list <std::string> array; std::list <std::string> newArray; kurento::JsonSerializer writer (true); kurento::JsonSerializer writer2 (true); kurento::JsonSerializer reader (false); array.emplace_back("first"); array.emplace_back("2"); array.emplace_back("three"); writer.Serialize ("array", array); reader.JsonValue = writer.JsonValue; reader.Serialize ("array", newArray); writer2.Serialize ("array", newArray); BOOST_ASSERT (writer.JsonValue.toStyledString() == writer2.JsonValue.toStyledString() ); } BOOST_AUTO_TEST_CASE (serialize_vector) { std::vector <int> array; std::vector <int> newArray; kurento::JsonSerializer writer (true); kurento::JsonSerializer writer2 (true); kurento::JsonSerializer reader (false); array.push_back (1); array.push_back (2); array.push_back (3); writer.Serialize ("array", array); reader.JsonValue = writer.JsonValue; reader.Serialize ("array", newArray); writer2.Serialize ("array", newArray); BOOST_ASSERT (writer.JsonValue.toStyledString() == writer2.JsonValue.toStyledString() ); } BOOST_AUTO_TEST_CASE (serialize_int64) { int64_t data = LLONG_MAX; int64_t newData = 0; kurento::JsonSerializer writer (true); kurento::JsonSerializer writer2 (true); kurento::JsonSerializer reader (false); writer.Serialize ("intValue", data); std::cout << writer.JsonValue.toStyledString () << std::endl; reader.JsonValue = writer.JsonValue; reader.Serialize ("intValue", newData); writer2.Serialize ("intValue", newData); std::cout << "old value " << data << " new value " << newData << std::endl; BOOST_ASSERT (writer.JsonValue.toStyledString() == writer2.JsonValue.toStyledString() ); } <|endoftext|>
<commit_before>/* * Copyright 2016 Christian Lockley * * 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. */ #include "watchdogd.hpp" #include "sub.hpp" #include "main.hpp" #include "init.hpp" #include "configfile.hpp" #include "threads.hpp" #include "identify.hpp" #include "bootstatus.hpp" #include "multicall.hpp" extern "C" { #include "dbusapi.h" } #include <systemd/sd-event.h> const bool DISARM_WATCHDOG_BEFORE_REBOOT = true; static volatile sig_atomic_t quit = 0; volatile sig_atomic_t stop = 0; volatile sig_atomic_t stopPing = 0; ProcessList processes; static void PrintConfiguration(struct cfgoptions *const cfg) { Logmsg(LOG_INFO, "int=%is realtime=%s sync=%s softboot=%s force=%s mla=%.2f mem=%li pid=%li", cfg->sleeptime, cfg->options & REALTIME ? "yes" : "no", cfg->options & SYNC ? "yes" : "no", cfg->options & SOFTBOOT ? "yes" : "no", cfg->options & FORCE ? "yes" : "no", cfg->maxLoadOne, cfg->minfreepages, getppid()); if (cfg->options & ENABLEPING) { for (int cnt = 0; cnt < config_setting_length(cfg->ipAddresses); cnt++) { const char *ipAddress = config_setting_get_string_elem(cfg->ipAddresses, cnt); assert(ipAddress != NULL); Logmsg(LOG_INFO, "ping: %s", ipAddress); } } else { Logmsg(LOG_INFO, "ping: no ip adresses to ping"); } if (cfg->options & ENABLEPIDCHECKER) { for (int cnt = 0; cnt < config_setting_length(cfg->pidFiles); cnt++) { const char *pidFilePathName = config_setting_get_string_elem(cfg->pidFiles, cnt); assert(pidFilePathName != NULL); Logmsg(LOG_DEBUG, "pidfile: %s", pidFilePathName); } } else { Logmsg(LOG_INFO, "pidfile: no server process to check"); } Logmsg(LOG_INFO, "test=%s(%i) repair=%s(%i) no_act=%s", cfg->testexepathname == NULL ? "no" : cfg->testexepathname, cfg->testBinTimeout, cfg->exepathname == NULL ? "no" : cfg->exepathname, cfg->repairBinTimeout, cfg->options & NOACTION ? "yes" : "no"); } static void BlockSignals() { sigset_t set; sigemptyset(&set); sigaddset(&set, SIGTERM); sigaddset(&set, SIGUSR2); sigaddset(&set, SIGINT); sigaddset(&set, SIGHUP); pthread_sigmask(SIG_BLOCK, &set, NULL); } static int SignalHandler(sd_event_source * s, const signalfd_siginfo * si, void *cxt) { switch (sd_event_source_get_signal(s)) { case SIGTERM: case SIGINT: quit = 1; sd_event_exit((sd_event *) cxt, 0); break; case SIGHUP: //reload; break; } return 1; } static void InstallSignalHandlers(sd_event * event) { int r1 = sd_event_add_signal(event, NULL, SIGTERM, SignalHandler, event); int r2 = sd_event_add_signal(event, NULL, SIGHUP, SignalHandler, event); int r3 = sd_event_add_signal(event, NULL, SIGUSR2, SignalHandler, event); int r4 = sd_event_add_signal(event, NULL, SIGINT, SignalHandler, event); if (r1 < 0 || r2 < 0 || r3 < 0 || r4 < 0) { abort(); } } static int Pinger(sd_event_source * s, uint64_t usec, void *cxt) { Watchdog *watchdog = (Watchdog *) cxt; watchdog->Ping(); sd_event_now(sd_event_source_get_event(s), CLOCK_REALTIME, &usec); usec += watchdog->GetPingInterval() * 1000000; sd_event_add_time(sd_event_source_get_event(s), &s, CLOCK_REALTIME, usec, 1, Pinger, (void *)cxt); return 0; } static bool InstallPinger(sd_event * e, int time, Watchdog * w) { sd_event_source *s = NULL; uint64_t usec = 0; w->SetPingInterval(time); sd_event_now(e, CLOCK_REALTIME, &usec); sd_event_add_time(e, &s, CLOCK_REALTIME, usec, 1, Pinger, (void *)w); return true; } int ServiceMain(int argc, char **argv, int fd, bool restarted) { cfgoptions options; Watchdog watchdog; cfgoptions *tmp = &options; Watchdog *tmp2 = &watchdog; struct dbusinfo temp = {.config = &tmp,.wdt = &tmp2 };; temp.fd = fd; if (MyStrerrorInit() == false) { std::perror("Unable to create a new locale object"); return EXIT_FAILURE; } int ret = ParseCommandLine(&argc, argv, &options); if (ret < 0) { return EXIT_FAILURE; } else if (ret != 0) { return EXIT_SUCCESS; } if (strcasecmp(GetExeName(), "wd_identify") == 0 || strcasecmp(GetExeName(), "wd_identify.sh") == 0) { options.options |= IDENTIFY; } if (ReadConfigurationFile(&options) < 0) { return EXIT_FAILURE; } if (options.options & IDENTIFY) { watchdog.Open(options.devicepath); ret = Identify(watchdog.GetRawTimeout(), (const char *)watchdog.GetIdentity(), options.devicepath, options.options & VERBOSE); watchdog.Close(); return ret; } if (PingInit(&options) < 0) { return EXIT_FAILURE; } if (restarted) { Logmsg(LOG_INFO,"restarting service (%s)", PACKAGE_VERSION); } else { Logmsg(LOG_INFO, "starting service (%s)", PACKAGE_VERSION); } PrintConfiguration(&options); if (ExecuteRepairScriptsPreFork(&processes, &options) == false) { Logmsg(LOG_ERR, "ExecuteRepairScriptsPreFork failed"); FatalError(&options); } sd_event *event = NULL; sd_event_default(&event); BlockSignals(); InstallSignalHandlers(event); if (StartHelperThreads(&options) != 0) { FatalError(&options); } pthread_t dbusThread; if (!(options.options & NOACTION)) { errno = 0; ret = watchdog.Open(options.devicepath); if (errno == EBUSY && ret < 0) { Logmsg(LOG_ERR, "Unable to open watchdog device"); return EXIT_FAILURE; } else if (ret <= -1) { LoadKernelModule(); ret = watchdog.Open(options.devicepath); } if (ret <= -1) { FatalError(&options); } if (watchdog.ConfigureWatchdogTimeout(options.watchdogTimeout) < 0 && options.watchdogTimeout != -1) { Logmsg(LOG_ERR, "unable to set watchdog device timeout\n"); Logmsg(LOG_ERR, "program exiting\n"); EndDaemon(&options, false); watchdog.Close(); return EXIT_FAILURE; } if (options.sleeptime == -1) { options.sleeptime = watchdog.GetOptimalPingInterval(); Logmsg(LOG_INFO, "ping interval autodetect: %i", options.sleeptime); } if (options.watchdogTimeout != -1 && watchdog.CheckWatchdogTimeout(options.sleeptime) == true) { Logmsg(LOG_ERR, "WDT timeout is less than or equal watchdog daemon ping interval"); Logmsg(LOG_ERR, "Using this interval may result in spurious reboots"); if (!(options.options & FORCE)) { watchdog.Close(); Logmsg(LOG_WARNING, "use the -f option to force this configuration"); return EXIT_FAILURE; } } WriteBootStatus(watchdog.GetStatus(), "/run/watchdogd.status", options.sleeptime, watchdog.GetRawTimeout()); static struct identinfo i; strncpy(i.name, (char *)watchdog.GetIdentity(), sizeof(i.name) - 1); i.timeout = watchdog.GetRawTimeout(); strncpy(i.daemonVersion, PACKAGE_VERSION, sizeof(i.daemonVersion) - 1); strncpy(i.deviceName, options.devicepath, sizeof(i.deviceName) - 1); i.flags = watchdog.GetStatus(); i.firmwareVersion = watchdog.GetFirmwareVersion(); CreateDetachedThread(IdentityThread, &i); pthread_create(&dbusThread, NULL, DbusHelper, &temp); InstallPinger(event, options.sleeptime, &watchdog); write(fd, "", sizeof(char)); } if (SetupAuxManagerThread(&options) < 0) { FatalError(&options); } if (PlatformInit() != true) { FatalError(&options); } sd_event_loop(event); if (stop == 1) { while (true) { if (stopPing == 1) { if (DISARM_WATCHDOG_BEFORE_REBOOT) { watchdog.Close(); } } else { watchdog.Ping(); } sleep(1); } } pthread_cancel(dbusThread); pthread_join(dbusThread, NULL); watchdog.Close(); unlink("/run/watchdogd.status"); if (EndDaemon(&options, false) < 0) { return EXIT_FAILURE; } return EXIT_SUCCESS; } int main(int argc, char **argv) { int sock[2] = { 0 }; socketpair(AF_UNIX, SOCK_STREAM | SOCK_CLOEXEC, 0, sock); pid_t pid = fork(); if (pid == 0) { OnParentDeathSend(SIGKILL); close(sock[1]); DbusApiInit(sock[0]); _Exit(0); } close(sock[0]); sigset_t mask; bool restarted = false; char name[64] = {0}; sd_bus *bus = NULL; sd_bus_message *m = NULL; sd_bus_error error = {0}; int fildes[2] = {0}; sigemptyset (&mask); sigaddset (&mask, SIGTERM); sigaddset (&mask, SIGINT); sigaddset (&mask, SIGHUP); sigprocmask(SIG_BLOCK, &mask, NULL); int sfd = signalfd (-1, &mask, 0); init: pipe(fildes); pid = fork(); if (pid == 0) { close(sfd); ResetSignalHandlers(64); sigprocmask(SIG_UNBLOCK, &mask, NULL); close(fildes[1]); read(fildes[0], fildes+1, sizeof(int)); close(fildes[0]); _Exit(ServiceMain(argc, argv, sock[1], restarted)); } else { sd_bus_open_system(&bus); sprintf(name, "watchdogd.%li.scope", pid); sd_bus_message_new_method_call(bus, &m, "org.freedesktop.systemd1", "/org/freedesktop/systemd1", "org.freedesktop.systemd1.Manager", "StartTransientUnit"); sd_bus_message_append(m, "ss", name, "fail"); sd_bus_message_open_container(m, 'a', "(sv)"); sd_bus_message_append(m, "(sv)", "Description", "s", " "); sd_bus_message_append(m, "(sv)", "KillSignal", "i", SIGKILL); sd_bus_message_append(m, "(sv)", "PIDs", "au", 1, (uint32_t) pid); sd_bus_message_close_container(m); sd_bus_message_append(m, "a(sa(sv))", 0); sd_bus_message * reply; sd_bus_call(bus, m, 0, &error, &reply); close(fildes[0]); close(fildes[1]); sd_bus_flush_close_unref(bus); } sd_notifyf(0, "READY=1\n" "MAINPID=%lu", (unsigned long)getpid()); while (true) { struct signalfd_siginfo si = {0}; ssize_t ret = read (sfd, &si, sizeof(si)); switch (si.ssi_signo) { case SIGHUP: sd_bus_open_system(&bus); sd_bus_call_method(bus, "org.freedesktop.systemd1", "/org/freedesktop/systemd1", "org.freedesktop.systemd1.Manager", "StopUnit", &error, NULL, "ss", name, "ignore-dependencies"); sd_bus_flush_close_unref(bus); restarted = true; goto init; break; case SIGINT: case SIGTERM: sd_bus_open_system(&bus); sd_bus_call_method(bus, "org.freedesktop.systemd1", "/org/freedesktop/systemd1", "org.freedesktop.systemd1.Manager", "StopUnit", &error, NULL, "ss", name, "ignore-dependencies"); sd_bus_flush_close_unref(bus); exit(0); break; } } } <commit_msg>zero ssi_signo between signals<commit_after>/* * Copyright 2016 Christian Lockley * * 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. */ #include "watchdogd.hpp" #include "sub.hpp" #include "main.hpp" #include "init.hpp" #include "configfile.hpp" #include "threads.hpp" #include "identify.hpp" #include "bootstatus.hpp" #include "multicall.hpp" extern "C" { #include "dbusapi.h" } #include <systemd/sd-event.h> const bool DISARM_WATCHDOG_BEFORE_REBOOT = true; static volatile sig_atomic_t quit = 0; volatile sig_atomic_t stop = 0; volatile sig_atomic_t stopPing = 0; ProcessList processes; static void PrintConfiguration(struct cfgoptions *const cfg) { Logmsg(LOG_INFO, "int=%is realtime=%s sync=%s softboot=%s force=%s mla=%.2f mem=%li pid=%li", cfg->sleeptime, cfg->options & REALTIME ? "yes" : "no", cfg->options & SYNC ? "yes" : "no", cfg->options & SOFTBOOT ? "yes" : "no", cfg->options & FORCE ? "yes" : "no", cfg->maxLoadOne, cfg->minfreepages, getppid()); if (cfg->options & ENABLEPING) { for (int cnt = 0; cnt < config_setting_length(cfg->ipAddresses); cnt++) { const char *ipAddress = config_setting_get_string_elem(cfg->ipAddresses, cnt); assert(ipAddress != NULL); Logmsg(LOG_INFO, "ping: %s", ipAddress); } } else { Logmsg(LOG_INFO, "ping: no ip adresses to ping"); } if (cfg->options & ENABLEPIDCHECKER) { for (int cnt = 0; cnt < config_setting_length(cfg->pidFiles); cnt++) { const char *pidFilePathName = config_setting_get_string_elem(cfg->pidFiles, cnt); assert(pidFilePathName != NULL); Logmsg(LOG_DEBUG, "pidfile: %s", pidFilePathName); } } else { Logmsg(LOG_INFO, "pidfile: no server process to check"); } Logmsg(LOG_INFO, "test=%s(%i) repair=%s(%i) no_act=%s", cfg->testexepathname == NULL ? "no" : cfg->testexepathname, cfg->testBinTimeout, cfg->exepathname == NULL ? "no" : cfg->exepathname, cfg->repairBinTimeout, cfg->options & NOACTION ? "yes" : "no"); } static void BlockSignals() { sigset_t set; sigemptyset(&set); sigaddset(&set, SIGTERM); sigaddset(&set, SIGUSR2); sigaddset(&set, SIGINT); sigaddset(&set, SIGHUP); pthread_sigmask(SIG_BLOCK, &set, NULL); } static int SignalHandler(sd_event_source * s, const signalfd_siginfo * si, void *cxt) { switch (sd_event_source_get_signal(s)) { case SIGTERM: case SIGINT: quit = 1; sd_event_exit((sd_event *) cxt, 0); break; case SIGHUP: //reload; break; } return 1; } static void InstallSignalHandlers(sd_event * event) { int r1 = sd_event_add_signal(event, NULL, SIGTERM, SignalHandler, event); int r2 = sd_event_add_signal(event, NULL, SIGHUP, SignalHandler, event); int r3 = sd_event_add_signal(event, NULL, SIGUSR2, SignalHandler, event); int r4 = sd_event_add_signal(event, NULL, SIGINT, SignalHandler, event); if (r1 < 0 || r2 < 0 || r3 < 0 || r4 < 0) { abort(); } } static int Pinger(sd_event_source * s, uint64_t usec, void *cxt) { Watchdog *watchdog = (Watchdog *) cxt; watchdog->Ping(); sd_event_now(sd_event_source_get_event(s), CLOCK_REALTIME, &usec); usec += watchdog->GetPingInterval() * 1000000; sd_event_add_time(sd_event_source_get_event(s), &s, CLOCK_REALTIME, usec, 1, Pinger, (void *)cxt); return 0; } static bool InstallPinger(sd_event * e, int time, Watchdog * w) { sd_event_source *s = NULL; uint64_t usec = 0; w->SetPingInterval(time); sd_event_now(e, CLOCK_REALTIME, &usec); sd_event_add_time(e, &s, CLOCK_REALTIME, usec, 1, Pinger, (void *)w); return true; } int ServiceMain(int argc, char **argv, int fd, bool restarted) { cfgoptions options; Watchdog watchdog; cfgoptions *tmp = &options; Watchdog *tmp2 = &watchdog; struct dbusinfo temp = {.config = &tmp,.wdt = &tmp2 };; temp.fd = fd; if (MyStrerrorInit() == false) { std::perror("Unable to create a new locale object"); return EXIT_FAILURE; } int ret = ParseCommandLine(&argc, argv, &options); if (ret < 0) { return EXIT_FAILURE; } else if (ret != 0) { return EXIT_SUCCESS; } if (strcasecmp(GetExeName(), "wd_identify") == 0 || strcasecmp(GetExeName(), "wd_identify.sh") == 0) { options.options |= IDENTIFY; } if (ReadConfigurationFile(&options) < 0) { return EXIT_FAILURE; } if (options.options & IDENTIFY) { watchdog.Open(options.devicepath); ret = Identify(watchdog.GetRawTimeout(), (const char *)watchdog.GetIdentity(), options.devicepath, options.options & VERBOSE); watchdog.Close(); return ret; } if (PingInit(&options) < 0) { return EXIT_FAILURE; } if (restarted) { Logmsg(LOG_INFO,"restarting service (%s)", PACKAGE_VERSION); } else { Logmsg(LOG_INFO, "starting service (%s)", PACKAGE_VERSION); } PrintConfiguration(&options); if (ExecuteRepairScriptsPreFork(&processes, &options) == false) { Logmsg(LOG_ERR, "ExecuteRepairScriptsPreFork failed"); FatalError(&options); } sd_event *event = NULL; sd_event_default(&event); BlockSignals(); InstallSignalHandlers(event); if (StartHelperThreads(&options) != 0) { FatalError(&options); } pthread_t dbusThread; if (!(options.options & NOACTION)) { errno = 0; ret = watchdog.Open(options.devicepath); if (errno == EBUSY && ret < 0) { Logmsg(LOG_ERR, "Unable to open watchdog device"); return EXIT_FAILURE; } else if (ret <= -1) { LoadKernelModule(); ret = watchdog.Open(options.devicepath); } if (ret <= -1) { FatalError(&options); } if (watchdog.ConfigureWatchdogTimeout(options.watchdogTimeout) < 0 && options.watchdogTimeout != -1) { Logmsg(LOG_ERR, "unable to set watchdog device timeout\n"); Logmsg(LOG_ERR, "program exiting\n"); EndDaemon(&options, false); watchdog.Close(); return EXIT_FAILURE; } if (options.sleeptime == -1) { options.sleeptime = watchdog.GetOptimalPingInterval(); Logmsg(LOG_INFO, "ping interval autodetect: %i", options.sleeptime); } if (options.watchdogTimeout != -1 && watchdog.CheckWatchdogTimeout(options.sleeptime) == true) { Logmsg(LOG_ERR, "WDT timeout is less than or equal watchdog daemon ping interval"); Logmsg(LOG_ERR, "Using this interval may result in spurious reboots"); if (!(options.options & FORCE)) { watchdog.Close(); Logmsg(LOG_WARNING, "use the -f option to force this configuration"); return EXIT_FAILURE; } } WriteBootStatus(watchdog.GetStatus(), "/run/watchdogd.status", options.sleeptime, watchdog.GetRawTimeout()); static struct identinfo i; strncpy(i.name, (char *)watchdog.GetIdentity(), sizeof(i.name) - 1); i.timeout = watchdog.GetRawTimeout(); strncpy(i.daemonVersion, PACKAGE_VERSION, sizeof(i.daemonVersion) - 1); strncpy(i.deviceName, options.devicepath, sizeof(i.deviceName) - 1); i.flags = watchdog.GetStatus(); i.firmwareVersion = watchdog.GetFirmwareVersion(); CreateDetachedThread(IdentityThread, &i); pthread_create(&dbusThread, NULL, DbusHelper, &temp); InstallPinger(event, options.sleeptime, &watchdog); write(fd, "", sizeof(char)); } if (SetupAuxManagerThread(&options) < 0) { FatalError(&options); } if (PlatformInit() != true) { FatalError(&options); } sd_event_loop(event); if (stop == 1) { while (true) { if (stopPing == 1) { if (DISARM_WATCHDOG_BEFORE_REBOOT) { watchdog.Close(); } } else { watchdog.Ping(); } sleep(1); } } pthread_cancel(dbusThread); pthread_join(dbusThread, NULL); watchdog.Close(); unlink("/run/watchdogd.status"); if (EndDaemon(&options, false) < 0) { return EXIT_FAILURE; } return EXIT_SUCCESS; } int main(int argc, char **argv) { int sock[2] = { 0 }; socketpair(AF_UNIX, SOCK_STREAM | SOCK_CLOEXEC, 0, sock); pid_t pid = fork(); if (pid == 0) { OnParentDeathSend(SIGKILL); close(sock[1]); DbusApiInit(sock[0]); _Exit(0); } close(sock[0]); sigset_t mask; bool restarted = false; char name[64] = {0}; sd_bus *bus = NULL; sd_bus_message *m = NULL; sd_bus_error error = {0}; int fildes[2] = {0}; sigemptyset (&mask); sigaddset (&mask, SIGTERM); sigaddset (&mask, SIGINT); sigaddset (&mask, SIGHUP); sigprocmask(SIG_BLOCK, &mask, NULL); int sfd = signalfd (-1, &mask, 0); init: pipe(fildes); pid = fork(); if (pid == 0) { close(sfd); ResetSignalHandlers(64); sigprocmask(SIG_UNBLOCK, &mask, NULL); close(fildes[1]); read(fildes[0], fildes+1, sizeof(int)); close(fildes[0]); _Exit(ServiceMain(argc, argv, sock[1], restarted)); } else { sd_bus_open_system(&bus); sprintf(name, "watchdogd.%li.scope", pid); sd_bus_message_new_method_call(bus, &m, "org.freedesktop.systemd1", "/org/freedesktop/systemd1", "org.freedesktop.systemd1.Manager", "StartTransientUnit"); sd_bus_message_append(m, "ss", name, "fail"); sd_bus_message_open_container(m, 'a', "(sv)"); sd_bus_message_append(m, "(sv)", "Description", "s", " "); sd_bus_message_append(m, "(sv)", "KillSignal", "i", SIGKILL); sd_bus_message_append(m, "(sv)", "PIDs", "au", 1, (uint32_t) pid); sd_bus_message_close_container(m); sd_bus_message_append(m, "a(sa(sv))", 0); sd_bus_message * reply; sd_bus_call(bus, m, 0, &error, &reply); close(fildes[0]); close(fildes[1]); sd_bus_flush_close_unref(bus); } sd_notifyf(0, "READY=1\n" "MAINPID=%lu", (unsigned long)getpid()); while (true) { struct signalfd_siginfo si = {0}; ssize_t ret = read (sfd, &si, sizeof(si)); switch (si.ssi_signo) { case SIGHUP: sd_bus_open_system(&bus); sd_bus_call_method(bus, "org.freedesktop.systemd1", "/org/freedesktop/systemd1", "org.freedesktop.systemd1.Manager", "StopUnit", &error, NULL, "ss", name, "ignore-dependencies"); sd_bus_flush_close_unref(bus); restarted = true; si.ssi_signo = 0; goto init; break; case SIGINT: case SIGTERM: sd_bus_open_system(&bus); sd_bus_call_method(bus, "org.freedesktop.systemd1", "/org/freedesktop/systemd1", "org.freedesktop.systemd1.Manager", "StopUnit", &error, NULL, "ss", name, "ignore-dependencies"); sd_bus_flush_close_unref(bus); exit(0); break; } } } <|endoftext|>
<commit_before>#ifndef RDB_PROTOCOL_FUNC_HPP_ #define RDB_PROTOCOL_FUNC_HPP_ #include <map> #include <utility> #include <vector> #include "utils.hpp" #include "containers/ptr_bag.hpp" #include "containers/scoped.hpp" #include "protob/protob.hpp" #include "rdb_protocol/js.hpp" #include "rdb_protocol/term.hpp" #include "rpc/serialize_macros.hpp" namespace ql { class func_t : public ptr_baggable_t, public pb_rcheckable_t { public: func_t(env_t *env, js::id_t id, term_t *parent); func_t(env_t *env, const Term *_source); // Some queries, like filter, can take a shortcut object instead of a // function as their argument. static func_t *new_filter_func(env_t *env, const datum_t *obj, const pb_rcheckable_t *root); static func_t *new_identity_func(env_t *env, const datum_t *obj, const pb_rcheckable_t *root); val_t *call(const std::vector<const datum_t *> &args); // Prefer these two version of call. val_t *call(const datum_t *arg); val_t *call(const datum_t *arg1, const datum_t *arg2); bool filter_call(env_t *env, const datum_t *arg); void dump_scope(std::map<int, Datum> *out) const; bool is_deterministic() const; private: // Pointers to this function's arguments. std::vector<const datum_t *> argptrs; term_t *body; // body to evaluate with functions bound // This is what's serialized over the wire. friend class wire_func_t; const Term *source; bool implicit_bound; // TODO: make this smarter (it's sort of slow and shitty as-is) std::map<int, const datum_t **> scope; term_t *js_parent; env_t *js_env; js::id_t js_id; }; class js_result_visitor_t : public boost::static_visitor<val_t *> { public: typedef val_t *result_type; js_result_visitor_t(env_t *_env, term_t *_parent) : env(_env), parent(_parent) { } // This JS evaluation resulted in an error result_type operator()(const std::string err_val) const { rfail_target(parent, "%s", err_val.c_str()); unreachable(); } // This JS call resulted in a JSON value result_type operator()(const boost::shared_ptr<scoped_cJSON_t> json_val) const { return parent->new_val(new datum_t(json_val, env)); } // This JS evaluation resulted in an id for a js function result_type operator()(const id_t id_val) const { return parent->new_val(new func_t(env, id_val, parent)); } private: env_t *env; term_t *parent; }; RDB_MAKE_PROTOB_SERIALIZABLE(Term); RDB_MAKE_PROTOB_SERIALIZABLE(Datum); // Used to serialize a function (or gmr) over the wire. class wire_func_t { public: wire_func_t(); wire_func_t(env_t *env, func_t *_func); wire_func_t(const Term &_source, std::map<int, Datum> *_scope); func_t *compile(env_t *env); RDB_MAKE_ME_SERIALIZABLE_2(source, scope); private: // We cache a separate function for every environment. std::map<env_t *, func_t *> cached_funcs; Term source; std::map<int, Datum> scope; }; class map_wire_func_t : public wire_func_t { public: template <class... Args> map_wire_func_t(Args... args) : wire_func_t(args...) { } }; class filter_wire_func_t : public wire_func_t { public: template <class... Args> filter_wire_func_t(Args... args) : wire_func_t(args...) { } }; class reduce_wire_func_t : public wire_func_t { public: template <class... Args> reduce_wire_func_t(Args... args) : wire_func_t(args...) { } }; class concatmap_wire_func_t : public wire_func_t { public: template <class... Args> concatmap_wire_func_t(Args... args) : wire_func_t(args...) { } }; // Count is a fake function because we don't need to send anything. struct count_wire_func_t { RDB_MAKE_ME_SERIALIZABLE_0() }; // Grouped Map Reduce class gmr_wire_func_t { public: gmr_wire_func_t() { } gmr_wire_func_t(env_t *env, func_t *_group, func_t *_map, func_t *_reduce) : group(env, _group), map(env, _map), reduce(env, _reduce) { } func_t *compile_group(env_t *env) { return group.compile(env); } func_t *compile_map(env_t *env) { return map.compile(env); } func_t *compile_reduce(env_t *env) { return reduce.compile(env); } private: map_wire_func_t group; map_wire_func_t map; reduce_wire_func_t reduce; public: RDB_MAKE_ME_SERIALIZABLE_3(group, map, reduce); }; // Evaluating this returns a `func_t` wrapped in a `val_t`. class func_term_t : public term_t { public: func_term_t(env_t *env, const Term *term); private: virtual bool is_deterministic_impl() const; virtual val_t *eval_impl(); virtual const char *name() const { return "func"; } func_t *func; }; } // namespace ql #endif // RDB_PROTOCOL_FUNC_HPP_ <commit_msg>Made wire_func_t be composed into map_wire_func_t, etc.<commit_after>#ifndef RDB_PROTOCOL_FUNC_HPP_ #define RDB_PROTOCOL_FUNC_HPP_ #include <map> #include <utility> #include <vector> #include "utils.hpp" #include "containers/ptr_bag.hpp" #include "containers/scoped.hpp" #include "protob/protob.hpp" #include "rdb_protocol/js.hpp" #include "rdb_protocol/term.hpp" #include "rpc/serialize_macros.hpp" namespace ql { class func_t : public ptr_baggable_t, public pb_rcheckable_t { public: func_t(env_t *env, js::id_t id, term_t *parent); func_t(env_t *env, const Term *_source); // Some queries, like filter, can take a shortcut object instead of a // function as their argument. static func_t *new_filter_func(env_t *env, const datum_t *obj, const pb_rcheckable_t *root); static func_t *new_identity_func(env_t *env, const datum_t *obj, const pb_rcheckable_t *root); val_t *call(const std::vector<const datum_t *> &args); // Prefer these two version of call. val_t *call(const datum_t *arg); val_t *call(const datum_t *arg1, const datum_t *arg2); bool filter_call(env_t *env, const datum_t *arg); void dump_scope(std::map<int, Datum> *out) const; bool is_deterministic() const; private: // Pointers to this function's arguments. std::vector<const datum_t *> argptrs; term_t *body; // body to evaluate with functions bound // This is what's serialized over the wire. friend class wire_func_t; const Term *source; bool implicit_bound; // TODO: make this smarter (it's sort of slow and shitty as-is) std::map<int, const datum_t **> scope; term_t *js_parent; env_t *js_env; js::id_t js_id; }; class js_result_visitor_t : public boost::static_visitor<val_t *> { public: typedef val_t *result_type; js_result_visitor_t(env_t *_env, term_t *_parent) : env(_env), parent(_parent) { } // This JS evaluation resulted in an error result_type operator()(const std::string err_val) const { rfail_target(parent, "%s", err_val.c_str()); unreachable(); } // This JS call resulted in a JSON value result_type operator()(const boost::shared_ptr<scoped_cJSON_t> json_val) const { return parent->new_val(new datum_t(json_val, env)); } // This JS evaluation resulted in an id for a js function result_type operator()(const id_t id_val) const { return parent->new_val(new func_t(env, id_val, parent)); } private: env_t *env; term_t *parent; }; RDB_MAKE_PROTOB_SERIALIZABLE(Term); RDB_MAKE_PROTOB_SERIALIZABLE(Datum); // Used to serialize a function (or gmr) over the wire. class wire_func_t { public: wire_func_t(); wire_func_t(env_t *env, func_t *_func); wire_func_t(const Term &_source, std::map<int, Datum> *_scope); func_t *compile(env_t *env); RDB_MAKE_ME_SERIALIZABLE_2(source, scope); private: // We cache a separate function for every environment. std::map<env_t *, func_t *> cached_funcs; Term source; std::map<int, Datum> scope; }; class map_wire_func_t { public: template <class... Args> map_wire_func_t(Args... args) : wire_func(args...) { } func_t *compile(env_t *env) { return wire_func.compile(env); } RDB_MAKE_ME_SERIALIZABLE_1(wire_func); private: wire_func_t wire_func; }; class filter_wire_func_t { public: template <class... Args> filter_wire_func_t(Args... args) : wire_func(args...) { } func_t *compile(env_t *env) { return wire_func.compile(env); } RDB_MAKE_ME_SERIALIZABLE_1(wire_func); private: wire_func_t wire_func; }; class reduce_wire_func_t { public: template <class... Args> reduce_wire_func_t(Args... args) : wire_func(args...) { } func_t *compile(env_t *env) { return wire_func.compile(env); } RDB_MAKE_ME_SERIALIZABLE_1(wire_func); private: wire_func_t wire_func; }; class concatmap_wire_func_t { public: template <class... Args> concatmap_wire_func_t(Args... args) : wire_func(args...) { } func_t *compile(env_t *env) { return wire_func.compile(env); } RDB_MAKE_ME_SERIALIZABLE_1(wire_func); private: wire_func_t wire_func; }; // Count is a fake function because we don't need to send anything. struct count_wire_func_t { RDB_MAKE_ME_SERIALIZABLE_0() }; // Grouped Map Reduce class gmr_wire_func_t { public: gmr_wire_func_t() { } gmr_wire_func_t(env_t *env, func_t *_group, func_t *_map, func_t *_reduce) : group(env, _group), map(env, _map), reduce(env, _reduce) { } func_t *compile_group(env_t *env) { return group.compile(env); } func_t *compile_map(env_t *env) { return map.compile(env); } func_t *compile_reduce(env_t *env) { return reduce.compile(env); } private: map_wire_func_t group; map_wire_func_t map; reduce_wire_func_t reduce; public: RDB_MAKE_ME_SERIALIZABLE_3(group, map, reduce); }; // Evaluating this returns a `func_t` wrapped in a `val_t`. class func_term_t : public term_t { public: func_term_t(env_t *env, const Term *term); private: virtual bool is_deterministic_impl() const; virtual val_t *eval_impl(); virtual const char *name() const { return "func"; } func_t *func; }; } // namespace ql #endif // RDB_PROTOCOL_FUNC_HPP_ <|endoftext|>
<commit_before>/** * Copyright (c) 2014-present, Facebook, Inc. * All rights reserved. * * This source code is licensed under both the Apache 2.0 license (found in the * LICENSE file in the root directory of this source tree) and the GPLv2 (found * in the COPYING file in the root directory of this source tree). * You may select, at your option, one of the above-listed licenses. */ #include <osquery/enroll.h> #include <osquery/flags.h> #include <osquery/killswitch/killswitch_plugin.h> #include <osquery/killswitch/plugins/killswitch_tls.h> #include <osquery/logger.h> #include <osquery/registry.h> #include <osquery/remote/serializers/json.h> #include <osquery/remote/utility.h> namespace osquery { CLI_FLAG(uint64, killswitch_tls_max_attempts, 3, "Number of attempts to retry a TLS killswitch config request"); /// Config retrieval TLS endpoint (path) using TLS hostname. CLI_FLAG(string, killswitch_tls_endpoint, "", "TLS/HTTPS endpoint for killswitch config retrieval"); DECLARE_bool(enroll_always); REGISTER(TLSKillswitchPlugin, Killswitch::killswitch_, "tls"); Status TLSKillswitchPlugin::setUp() { if (FLAGS_enroll_always && !FLAGS_disable_enrollment) { // clear any cached node key clearNodeKey(); auto node_key = getNodeKey("tls"); if (node_key.size() == 0) { // Could not generate a node key, continue logging to stderr. return Status(1, "No node key, TLS config failed."); } } uri_ = TLSRequestHelper::makeURI(FLAGS_killswitch_tls_endpoint); return Status(0, "OK"); } ExpectedSuccess<KillswitchRefreshablePlugin::RefreshError> TLSKillswitchPlugin::refresh() { std::string content; JSON params; // The TLS node API morphs some verbs and variables. params.add("_get", true); auto s = TLSRequestHelper::go<JSONSerializer>( uri_, params, content, FLAGS_killswitch_tls_max_attempts); if (!s.ok()) { return createError( KillswitchRefreshablePlugin::RefreshError::NoContentReached, "Could not retreive config file from network"); } auto result = KillswitchPlugin::parseMapJSON(content); if (result) { setCache(*result); return Success(); } else { return createError(KillswitchRefreshablePlugin::RefreshError::ParsingError, result.getError().getFullMessageRecursive()); } } } // namespace osquery <commit_msg>Killswitch TLS plugin improved interface (#4791)<commit_after>/** * Copyright (c) 2014-present, Facebook, Inc. * All rights reserved. * * This source code is licensed under both the Apache 2.0 license (found in the * LICENSE file in the root directory of this source tree) and the GPLv2 (found * in the COPYING file in the root directory of this source tree). * You may select, at your option, one of the above-listed licenses. */ #include <osquery/enroll.h> #include <osquery/flags.h> #include <osquery/killswitch/killswitch_plugin.h> #include <osquery/killswitch/plugins/killswitch_tls.h> #include <osquery/logger.h> #include <osquery/registry.h> #include <osquery/remote/serializers/json.h> #include <osquery/remote/utility.h> namespace osquery { CLI_FLAG(uint64, killswitch_tls_max_attempts, 3, "Number of attempts to retry a TLS killswitch config request"); /// Config retrieval TLS endpoint (path) using TLS hostname. CLI_FLAG(string, killswitch_tls_endpoint, "", "TLS/HTTPS endpoint for killswitch config retrieval"); DECLARE_bool(enroll_always); REGISTER(TLSKillswitchPlugin, Killswitch::killswitch_, "tls"); Status TLSKillswitchPlugin::setUp() { if (FLAGS_enroll_always && !FLAGS_disable_enrollment) { // clear any cached node key clearNodeKey(); auto node_key = getNodeKey("tls"); if (node_key.size() == 0) { // Could not generate a node key, continue logging to stderr. return Status(1, "No node key, TLS config failed."); } } uri_ = TLSRequestHelper::makeURI(FLAGS_killswitch_tls_endpoint); uri_ += ((uri_.find('?') != std::string::npos) ? "&" : "?"); uri_ += "request=killswitch"; return KillswitchRefreshablePlugin::setUp(); } ExpectedSuccess<KillswitchRefreshablePlugin::RefreshError> TLSKillswitchPlugin::refresh() { std::string content; JSON params; // The TLS node API morphs some verbs and variables. params.add("_get", true); auto s = TLSRequestHelper::go<JSONSerializer>( uri_, params, content, FLAGS_killswitch_tls_max_attempts); if (!s.ok()) { return createError( KillswitchRefreshablePlugin::RefreshError::NoContentReached, "Could not retreive config file from network"); } JSON tree; Status parse_status = tree.fromString(content); if (!parse_status.ok()) { return createError(KillswitchRefreshablePlugin::RefreshError::ParsingError, "Could not parse JSON from TLS killswitch node API"); } // Extract config map from json auto it = tree.doc().FindMember("config"); if (it == tree.doc().MemberEnd()) { return createError(KillswitchRefreshablePlugin::RefreshError::ParsingError, "killswitch member config is not string"); } content = it->value.GetString(); auto result = KillswitchPlugin::parseMapJSON(content); if (result) { setCache(*result); return Success(); } else { return createError(KillswitchRefreshablePlugin::RefreshError::ParsingError, result.getError().getFullMessageRecursive()); } } } // namespace osquery <|endoftext|>
<commit_before>/*========================================================================= Program: Visualization Toolkit Module: vtkPriorityQueue.cxx Copyright (c) Ken Martin, Will Schroeder, Bill Lorensen All rights reserved. See Copyright.txt or http://www.kitware.com/Copyright.htm for details. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the above copyright notice for more information. =========================================================================*/ #include "vtkPriorityQueue.h" #include "vtkObjectFactory.h" vtkStandardNewMacro(vtkPriorityQueue); // Instantiate priority queue with default size and extension size of 1000. vtkPriorityQueue::vtkPriorityQueue() { this->Size = 0; this->Extend = 1000; this->Array = NULL; this->MaxId = -1; this->ItemLocation = vtkIdTypeArray::New(); } // Allocate priority queue with specified size and amount to extend // queue (if reallocation required). void vtkPriorityQueue::Allocate(const vtkIdType sz, const vtkIdType ext) { this->ItemLocation->Allocate(sz,ext); for (vtkIdType i=0; i < sz; i++) { this->ItemLocation->SetValue(i,-1); } this->Size = ( sz > 0 ? sz : 1); if ( this->Array != NULL ) { delete [] this->Array; } this->Array = new vtkPriorityQueue::Item[sz]; this->Extend = ( ext > 0 ? ext : 1); this->MaxId = -1; } // Destructor for the vtkPriorityQueue class vtkPriorityQueue::~vtkPriorityQueue() { this->ItemLocation->Delete(); if ( this->Array ) { delete [] this->Array; } } // Insert id with priority specified. void vtkPriorityQueue::Insert(double priority, vtkIdType id) { vtkIdType i, idx; vtkPriorityQueue::Item temp; // check and make sure item hasn't been inserted before if ( id <= this->ItemLocation->GetMaxId() && this->ItemLocation->GetValue(id) != -1 ) { return; } // start by placing new entry at bottom of tree if ( ++this->MaxId >= this->Size ) { this->Resize(this->MaxId + 1); } this->Array[this->MaxId].priority = priority; this->Array[this->MaxId].id = id; if ( id >= this->ItemLocation->GetSize() ) //might have to resize and initialize { vtkIdType oldSize = this->ItemLocation->GetSize(); this->ItemLocation->InsertValue(id,this->MaxId); for (i=oldSize; i < this->ItemLocation->GetSize(); i++) { this->ItemLocation->SetValue(i, -1); } this->ItemLocation->SetValue(id,this->MaxId); } this->ItemLocation->InsertValue(id,this->MaxId); // now begin percolating towards top of tree for ( i=this->MaxId; i > 0 && this->Array[i].priority < this->Array[(idx=(i-1)/2)].priority; i=idx) { temp = this->Array[i]; this->ItemLocation->SetValue(temp.id,idx); this->Array[i] = this->Array[idx]; this->ItemLocation->SetValue(this->Array[idx].id,i); this->Array[idx] = temp; } } // Simplified call for easier wrapping for Tcl. vtkIdType vtkPriorityQueue::Pop(vtkIdType location) { double priority; return this->Pop(location, priority); } // Removes item at specified location from tree; then reorders and // balances tree. The location == 0 is the root of the tree. vtkIdType vtkPriorityQueue::Pop(vtkIdType location, double &priority) { vtkIdType id, i, idx; vtkPriorityQueue::Item temp; if ( this->MaxId < 0 ) { return -1; } id = this->Array[location].id; priority = this->Array[location].priority; // move the last item to the location specified and push into the tree this->Array[location].id = this->Array[this->MaxId].id; this->Array[location].priority = this->Array[this->MaxId].priority; this->ItemLocation->SetValue(this->Array[location].id,location); this->ItemLocation->SetValue(id,-1); if ( --this->MaxId <= 0 ) { return id; } // percolate down the tree from the specified location int lastNodeToCheck = (this->MaxId-1)/2; for ( vtkIdType j=0, i=location; i <= lastNodeToCheck; i=j ) { idx = 2*i + 1; if ( this->Array[idx].priority < this->Array[idx+1].priority || idx == this->MaxId ) { j = idx; } else { j = idx + 1; } if ( this->Array[i].priority > this->Array[j].priority ) { temp = this->Array[i]; this->ItemLocation->SetValue(temp.id,j); this->Array[i] = this->Array[j]; this->ItemLocation->SetValue(this->Array[j].id,i); this->Array[j] = temp; } else { break; } } // percolate up the tree from the specified location for ( i=location; i > 0; i=idx ) { idx = (i-1)/2; if ( this->Array[i].priority < this->Array[idx].priority ) { temp = this->Array[i]; this->ItemLocation->SetValue(temp.id,idx); this->Array[i] = this->Array[idx]; this->ItemLocation->SetValue(this->Array[idx].id,i); this->Array[idx] = temp; } else { break; } } return id; } // Protected method reallocates queue. vtkPriorityQueue::Item *vtkPriorityQueue::Resize(const vtkIdType sz) { vtkPriorityQueue::Item *newArray; vtkIdType newSize; if (sz >= this->Size) { newSize = this->Size + sz; } else { newSize = sz; } if (newSize <= 0) { newSize = 1; } newArray = new vtkPriorityQueue::Item[newSize]; if (this->Array) { memcpy(newArray, this->Array, (sz < this->Size ? sz : this->Size) * sizeof(vtkPriorityQueue::Item)); delete [] this->Array; } this->Size = newSize; this->Array = newArray; return this->Array; } // Reset all of the entries in the queue so they don not have a priority void vtkPriorityQueue::Reset() { this->MaxId = -1; for (int i=0; i <= this->ItemLocation->GetMaxId(); i++) { this->ItemLocation->SetValue(i,-1); } this->ItemLocation->Reset(); } void vtkPriorityQueue::PrintSelf(ostream& os, vtkIndent indent) { this->Superclass::PrintSelf(os,indent); os << indent << "Number Of Entries: " << this->MaxId + 1 << "\n"; os << indent << "Size: " << this->Size << "\n"; os << indent << "Extend size: " << this->Extend << "\n"; } <commit_msg>Fix shadowed variable warning in vtkPriorityQueue<commit_after>/*========================================================================= Program: Visualization Toolkit Module: vtkPriorityQueue.cxx Copyright (c) Ken Martin, Will Schroeder, Bill Lorensen All rights reserved. See Copyright.txt or http://www.kitware.com/Copyright.htm for details. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the above copyright notice for more information. =========================================================================*/ #include "vtkPriorityQueue.h" #include "vtkObjectFactory.h" vtkStandardNewMacro(vtkPriorityQueue); // Instantiate priority queue with default size and extension size of 1000. vtkPriorityQueue::vtkPriorityQueue() { this->Size = 0; this->Extend = 1000; this->Array = NULL; this->MaxId = -1; this->ItemLocation = vtkIdTypeArray::New(); } // Allocate priority queue with specified size and amount to extend // queue (if reallocation required). void vtkPriorityQueue::Allocate(const vtkIdType sz, const vtkIdType ext) { this->ItemLocation->Allocate(sz,ext); for (vtkIdType i=0; i < sz; i++) { this->ItemLocation->SetValue(i,-1); } this->Size = ( sz > 0 ? sz : 1); if ( this->Array != NULL ) { delete [] this->Array; } this->Array = new vtkPriorityQueue::Item[sz]; this->Extend = ( ext > 0 ? ext : 1); this->MaxId = -1; } // Destructor for the vtkPriorityQueue class vtkPriorityQueue::~vtkPriorityQueue() { this->ItemLocation->Delete(); if ( this->Array ) { delete [] this->Array; } } // Insert id with priority specified. void vtkPriorityQueue::Insert(double priority, vtkIdType id) { vtkIdType i, idx; vtkPriorityQueue::Item temp; // check and make sure item hasn't been inserted before if ( id <= this->ItemLocation->GetMaxId() && this->ItemLocation->GetValue(id) != -1 ) { return; } // start by placing new entry at bottom of tree if ( ++this->MaxId >= this->Size ) { this->Resize(this->MaxId + 1); } this->Array[this->MaxId].priority = priority; this->Array[this->MaxId].id = id; if ( id >= this->ItemLocation->GetSize() ) //might have to resize and initialize { vtkIdType oldSize = this->ItemLocation->GetSize(); this->ItemLocation->InsertValue(id,this->MaxId); for (i=oldSize; i < this->ItemLocation->GetSize(); i++) { this->ItemLocation->SetValue(i, -1); } this->ItemLocation->SetValue(id,this->MaxId); } this->ItemLocation->InsertValue(id,this->MaxId); // now begin percolating towards top of tree for ( i=this->MaxId; i > 0 && this->Array[i].priority < this->Array[(idx=(i-1)/2)].priority; i=idx) { temp = this->Array[i]; this->ItemLocation->SetValue(temp.id,idx); this->Array[i] = this->Array[idx]; this->ItemLocation->SetValue(this->Array[idx].id,i); this->Array[idx] = temp; } } // Simplified call for easier wrapping for Tcl. vtkIdType vtkPriorityQueue::Pop(vtkIdType location) { double priority; return this->Pop(location, priority); } // Removes item at specified location from tree; then reorders and // balances tree. The location == 0 is the root of the tree. vtkIdType vtkPriorityQueue::Pop(vtkIdType location, double &priority) { vtkIdType idx; vtkPriorityQueue::Item temp; if ( this->MaxId < 0 ) { return -1; } vtkIdType id = this->Array[location].id; priority = this->Array[location].priority; // move the last item to the location specified and push into the tree this->Array[location].id = this->Array[this->MaxId].id; this->Array[location].priority = this->Array[this->MaxId].priority; this->ItemLocation->SetValue(this->Array[location].id,location); this->ItemLocation->SetValue(id,-1); if ( --this->MaxId <= 0 ) { return id; } // percolate down the tree from the specified location int lastNodeToCheck = (this->MaxId-1)/2; for ( vtkIdType j=0, i=location; i <= lastNodeToCheck; i=j ) { idx = 2*i + 1; if ( this->Array[idx].priority < this->Array[idx+1].priority || idx == this->MaxId ) { j = idx; } else { j = idx + 1; } if ( this->Array[i].priority > this->Array[j].priority ) { temp = this->Array[i]; this->ItemLocation->SetValue(temp.id,j); this->Array[i] = this->Array[j]; this->ItemLocation->SetValue(this->Array[j].id,i); this->Array[j] = temp; } else { break; } } // percolate up the tree from the specified location for (vtkIdType i=location; i > 0; i=idx ) { idx = (i-1)/2; if ( this->Array[i].priority < this->Array[idx].priority ) { temp = this->Array[i]; this->ItemLocation->SetValue(temp.id,idx); this->Array[i] = this->Array[idx]; this->ItemLocation->SetValue(this->Array[idx].id,i); this->Array[idx] = temp; } else { break; } } return id; } // Protected method reallocates queue. vtkPriorityQueue::Item *vtkPriorityQueue::Resize(const vtkIdType sz) { vtkPriorityQueue::Item *newArray; vtkIdType newSize; if (sz >= this->Size) { newSize = this->Size + sz; } else { newSize = sz; } if (newSize <= 0) { newSize = 1; } newArray = new vtkPriorityQueue::Item[newSize]; if (this->Array) { memcpy(newArray, this->Array, (sz < this->Size ? sz : this->Size) * sizeof(vtkPriorityQueue::Item)); delete [] this->Array; } this->Size = newSize; this->Array = newArray; return this->Array; } // Reset all of the entries in the queue so they don not have a priority void vtkPriorityQueue::Reset() { this->MaxId = -1; for (int i=0; i <= this->ItemLocation->GetMaxId(); i++) { this->ItemLocation->SetValue(i,-1); } this->ItemLocation->Reset(); } void vtkPriorityQueue::PrintSelf(ostream& os, vtkIndent indent) { this->Superclass::PrintSelf(os,indent); os << indent << "Number Of Entries: " << this->MaxId + 1 << "\n"; os << indent << "Size: " << this->Size << "\n"; os << indent << "Extend size: " << this->Extend << "\n"; } <|endoftext|>
<commit_before>#include "stdafx.h" #include "Stage.h" #include "SceneMgr.h" #include "RenderMgr.h" #include "Terrain.h" #include "TimeMgr.h" #include "ObjMgr.h" #include "Flower.h" #include "Player.h" #include "StaticObject.h" #include "Camera.h" #include "Info.h" #include "ResourcesMgr.h" #include "Frustum.h" #include "FaceUI.h" #include "LightMgr.h" #include "BaseUI.h" #include "HpBar.h" #include "FeverBar.h" #include "RuneBar.h" #include "Input.h" CStage::CStage() : m_bFirstLogin(false) { } CStage::~CStage() { } HRESULT CStage::Initialize(void) { if (FAILED(CreateObj())) return E_FAIL; return S_OK; } int CStage::Update(void) { if (m_bFirstLogin == false) { m_bFirstLogin = true; } if (CInput::GetInstance()->GetDIKeyState(DIK_F10) & 0x80) { if (CRenderMgr::GetInstance()->m_bUIRender) CRenderMgr::GetInstance()->m_bUIRender = false; else if (!CRenderMgr::GetInstance()->m_bUIRender) CRenderMgr::GetInstance()->m_bUIRender = true; } CObjMgr::GetInstance()->Update(); return 0; } void CStage::Render(void) { float fTime = CTimeMgr::GetInstance()->GetTime(); CRenderMgr::GetInstance()->Render(fTime); } void CStage::Release(void) { //CResourcesMgr::GetInstance()->ResourceReset(RESOURCE_STATIC); //CResourcesMgr::GetInstance()->ResourceReset(RESOURCE_STAGE); } CStage * CStage::Create(void) { CStage* pLogo = new CStage; if (FAILED(pLogo->Initialize())) { ::Safe_Delete(pLogo); } return pLogo; } HRESULT CStage::CreateObj(void) { CRenderMgr* pRenderer = CRenderMgr::GetInstance(); //ͷ CObj* pObj = NULL; ///////////////߸/////////////// TCHAR szMeshKey[MAX_PATH] = L""; TCHAR szTexKey[MAX_PATH] = L""; int iHigh = 0; pObj = CTerrain::Create(); if (pObj == NULL) return E_FAIL; CObjMgr::GetInstance()->AddObject(L"Terrain", pObj); /*for (int i = 0; i < 20; ++i) { pObj = CFlower::Create(); if (pObj == NULL) return E_FAIL; float fX = float(rand() % VERTEXCOUNTX); float fZ = float(rand() % VERTEXCOUNTZ); pObj->SetPos(D3DXVECTOR3(fX, 0.f, fZ)); CObjMgr::GetInstance()->AddObject(L"Flower", pObj); }*/ // pObj = CHpBar::Create(); if (pObj == NULL) return E_FAIL; CObjMgr::GetInstance()->AddObject(L"HpBar", pObj); pObj = CFeverBar::Create(); if (pObj == NULL) return E_FAIL; CObjMgr::GetInstance()->AddObject(L"FeverBar", pObj); for (int i = 0; i < 10; ++i) { pObj = CRuneBar::Create(80.f+(22.f * i),50.f); if (pObj == NULL) return E_FAIL; CObjMgr::GetInstance()->AddObject(L"FeverBar", pObj); } pObj = CFaceUI::Create(); if (pObj == NULL) return E_FAIL; CObjMgr::GetInstance()->AddObject(L"FaceUI", pObj); pObj = CBaseUI::Create(); if (pObj == NULL) return E_FAIL; CObjMgr::GetInstance()->AddObject(L"BaseUI", pObj); pObj = CPlayer::Create(); pObj->SetPos(D3DXVECTOR3(155.f, 0.f, 400.f)); CObjMgr::GetInstance()->AddObject(L"Player", pObj); CCamera::GetInstance()->SetCameraTarget(pObj->GetInfo()); DataLoad(); return S_OK; } void CStage::DataLoad(void) { HANDLE hFile = CreateFile(L"..\\Resource\\Data\\Norumac2.dat", GENERIC_READ, 0, NULL, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, NULL); CLightMgr* pLightMgr = CLightMgr::GetInstance(); DWORD dwByte; int iObjSize = 0; ReadFile(hFile, &iObjSize, sizeof(int), &dwByte, NULL); for (int i = 0; i < iObjSize; ++i) { TCHAR* pObjectKey = new TCHAR[50]; ReadFile(hFile, pObjectKey, sizeof(TCHAR) * 50, &dwByte, NULL); int iNum; ReadFile(hFile, &iNum, sizeof(int), &dwByte, NULL); if(0==iNum) continue; CObj* pGameObject = NULL; for (int j = 0; j < iNum; ++j) { pGameObject = CStaticObject::Create(pObjectKey); CObjMgr::GetInstance()->AddObject(pObjectKey, pGameObject); CRenderMgr::GetInstance()->AddRenderGroup(TYPE_NONEALPHA, pGameObject); const CComponent* pComponent = pGameObject->GetComponent(L"Transform"); ReadFile(hFile, ((CInfo*)pComponent)->m_fAngle, sizeof(float) * ANGLE_END, &dwByte, NULL); ReadFile(hFile, ((CInfo*)pComponent)->m_vScale, sizeof(D3DXVECTOR3), &dwByte, NULL); ReadFile(hFile, ((CInfo*)pComponent)->m_vPos, sizeof(D3DXVECTOR3), &dwByte, NULL); ReadFile(hFile, ((CInfo*)pComponent)->m_vDir, sizeof(D3DXVECTOR3), &dwByte, NULL); ReadFile(hFile, ((CInfo*)pComponent)->m_matWorld, sizeof(D3DXMATRIX), &dwByte, NULL); if (0 == wcscmp(pObjectKey, L"streetlamp")) { D3DXVECTOR3 vPos; vPos.x = ((CInfo*)pComponent)->m_vPos.x - 0.5f; vPos.y = ((CInfo*)pComponent)->m_vPos.y+1; vPos.z = ((CInfo*)pComponent)->m_vPos.z; pLightMgr->AddPointLight(vPos, 3.f, D3DXVECTOR3(1.0f, 0.0f, 0.0f)); } } } CloseHandle(hFile); } <commit_msg>[홍승필] 디버깅키 삭제<commit_after>#include "stdafx.h" #include "Stage.h" #include "SceneMgr.h" #include "RenderMgr.h" #include "Terrain.h" #include "TimeMgr.h" #include "ObjMgr.h" #include "Flower.h" #include "Player.h" #include "StaticObject.h" #include "Camera.h" #include "Info.h" #include "ResourcesMgr.h" #include "Frustum.h" #include "FaceUI.h" #include "LightMgr.h" #include "BaseUI.h" #include "HpBar.h" #include "FeverBar.h" #include "RuneBar.h" #include "Input.h" CStage::CStage() : m_bFirstLogin(false) { } CStage::~CStage() { } HRESULT CStage::Initialize(void) { if (FAILED(CreateObj())) return E_FAIL; return S_OK; } int CStage::Update(void) { if (m_bFirstLogin == false) { m_bFirstLogin = true; } CObjMgr::GetInstance()->Update(); return 0; } void CStage::Render(void) { float fTime = CTimeMgr::GetInstance()->GetTime(); CRenderMgr::GetInstance()->Render(fTime); } void CStage::Release(void) { //CResourcesMgr::GetInstance()->ResourceReset(RESOURCE_STATIC); //CResourcesMgr::GetInstance()->ResourceReset(RESOURCE_STAGE); } CStage * CStage::Create(void) { CStage* pLogo = new CStage; if (FAILED(pLogo->Initialize())) { ::Safe_Delete(pLogo); } return pLogo; } HRESULT CStage::CreateObj(void) { CRenderMgr* pRenderer = CRenderMgr::GetInstance(); //ͷ CObj* pObj = NULL; ///////////////߸/////////////// TCHAR szMeshKey[MAX_PATH] = L""; TCHAR szTexKey[MAX_PATH] = L""; int iHigh = 0; pObj = CTerrain::Create(); if (pObj == NULL) return E_FAIL; CObjMgr::GetInstance()->AddObject(L"Terrain", pObj); /*for (int i = 0; i < 20; ++i) { pObj = CFlower::Create(); if (pObj == NULL) return E_FAIL; float fX = float(rand() % VERTEXCOUNTX); float fZ = float(rand() % VERTEXCOUNTZ); pObj->SetPos(D3DXVECTOR3(fX, 0.f, fZ)); CObjMgr::GetInstance()->AddObject(L"Flower", pObj); }*/ // pObj = CHpBar::Create(); if (pObj == NULL) return E_FAIL; CObjMgr::GetInstance()->AddObject(L"HpBar", pObj); pObj = CFeverBar::Create(); if (pObj == NULL) return E_FAIL; CObjMgr::GetInstance()->AddObject(L"FeverBar", pObj); for (int i = 0; i < 10; ++i) { pObj = CRuneBar::Create(80.f+(22.f * i),50.f); if (pObj == NULL) return E_FAIL; CObjMgr::GetInstance()->AddObject(L"FeverBar", pObj); } pObj = CFaceUI::Create(); if (pObj == NULL) return E_FAIL; CObjMgr::GetInstance()->AddObject(L"FaceUI", pObj); pObj = CBaseUI::Create(); if (pObj == NULL) return E_FAIL; CObjMgr::GetInstance()->AddObject(L"BaseUI", pObj); pObj = CPlayer::Create(); pObj->SetPos(D3DXVECTOR3(155.f, 0.f, 400.f)); CObjMgr::GetInstance()->AddObject(L"Player", pObj); CCamera::GetInstance()->SetCameraTarget(pObj->GetInfo()); DataLoad(); return S_OK; } void CStage::DataLoad(void) { HANDLE hFile = CreateFile(L"..\\Resource\\Data\\Norumac2.dat", GENERIC_READ, 0, NULL, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, NULL); CLightMgr* pLightMgr = CLightMgr::GetInstance(); DWORD dwByte; int iObjSize = 0; ReadFile(hFile, &iObjSize, sizeof(int), &dwByte, NULL); for (int i = 0; i < iObjSize; ++i) { TCHAR* pObjectKey = new TCHAR[50]; ReadFile(hFile, pObjectKey, sizeof(TCHAR) * 50, &dwByte, NULL); int iNum; ReadFile(hFile, &iNum, sizeof(int), &dwByte, NULL); if(0==iNum) continue; CObj* pGameObject = NULL; for (int j = 0; j < iNum; ++j) { pGameObject = CStaticObject::Create(pObjectKey); CObjMgr::GetInstance()->AddObject(pObjectKey, pGameObject); CRenderMgr::GetInstance()->AddRenderGroup(TYPE_NONEALPHA, pGameObject); const CComponent* pComponent = pGameObject->GetComponent(L"Transform"); ReadFile(hFile, ((CInfo*)pComponent)->m_fAngle, sizeof(float) * ANGLE_END, &dwByte, NULL); ReadFile(hFile, ((CInfo*)pComponent)->m_vScale, sizeof(D3DXVECTOR3), &dwByte, NULL); ReadFile(hFile, ((CInfo*)pComponent)->m_vPos, sizeof(D3DXVECTOR3), &dwByte, NULL); ReadFile(hFile, ((CInfo*)pComponent)->m_vDir, sizeof(D3DXVECTOR3), &dwByte, NULL); ReadFile(hFile, ((CInfo*)pComponent)->m_matWorld, sizeof(D3DXMATRIX), &dwByte, NULL); if (0 == wcscmp(pObjectKey, L"streetlamp")) { D3DXVECTOR3 vPos; vPos.x = ((CInfo*)pComponent)->m_vPos.x - 0.5f; vPos.y = ((CInfo*)pComponent)->m_vPos.y+1; vPos.z = ((CInfo*)pComponent)->m_vPos.z; pLightMgr->AddPointLight(vPos, 3.f, D3DXVECTOR3(1.0f, 0.0f, 0.0f)); } } } CloseHandle(hFile); } <|endoftext|>
<commit_before>/* This file is part of the KDE project Copyright (C) 2005-2006 Matthias Kretz <kretz@kde.org> This library is free software; you can redistribute it and/or modify it under the terms of the GNU Library General Public License version 2 as published by the Free Software Foundation. This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Library General Public License for more details. You should have received a copy of the GNU Library General Public License along with this library; see the file COPYING.LIB. If not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ #include "audiopath.h" #include "audiopath_p.h" #include "factory.h" #include "audioeffect.h" #include "abstractaudiooutput.h" #define PHONON_CLASSNAME AudioPath namespace Phonon { PHONON_OBJECT_IMPL AudioPath::~AudioPath() { K_D( AudioPath ); foreach(AbstractAudioOutput *ao, d->outputs) d->removeDestructionHandler(ao, d); foreach(AudioEffect *ae, d->effects) d->removeDestructionHandler(ae, d); } bool AudioPath::addOutput( AbstractAudioOutput* audioOutput ) { K_D( AudioPath ); if( d->outputs.contains( audioOutput ) ) return false; if( iface() ) { bool success; BACKEND_GET1( bool, success, "addOutput", QObject*, audioOutput->iface() ); if( success ) { d->addDestructionHandler(audioOutput, d); d->outputs << audioOutput; return true; } } return false; } bool AudioPath::removeOutput( AbstractAudioOutput* audioOutput ) { K_D( AudioPath ); if( !d->outputs.contains( audioOutput ) ) return false; if( d->backendObject ) { bool success; BACKEND_GET1( bool, success, "removeOutput", QObject*, audioOutput->iface() ); if( success ) { d->outputs.removeAll( audioOutput ); return true; } } return false; } const QList<AbstractAudioOutput*>& AudioPath::outputs() const { K_D( const AudioPath ); return d->outputs; } bool AudioPath::insertEffect( AudioEffect* newEffect, AudioEffect* insertBefore ) { // effects may be added multiple times, but that means the objects are // different (the class is still the same) K_D( AudioPath ); if( d->effects.contains( newEffect ) ) return false; if( iface() ) { bool success; BACKEND_GET2( bool, success, "insertEffect", QObject*, newEffect->iface(), QObject*, insertBefore ? insertBefore->iface() : 0 ); if( success ) { d->addDestructionHandler(newEffect, d); if( insertBefore ) d->effects.insert( d->effects.indexOf( insertBefore ), newEffect ); else d->effects << newEffect; return true; } } return false; } bool AudioPath::removeEffect( AudioEffect* effect ) { K_D( AudioPath ); if( !d->effects.contains( effect ) ) return false; if( d->backendObject ) { bool success; BACKEND_GET1( bool, success, "removeEffect", QObject*, effect->iface() ); if( success ) { d->effects.removeAll( effect ); return true; } } return false; } const QList<AudioEffect*>& AudioPath::effects() const { K_D( const AudioPath ); return d->effects; } bool AudioPathPrivate::aboutToDeleteIface() { return true; } void AudioPath::setupIface() { K_D( AudioPath ); Q_ASSERT( d->backendObject ); // set up attributes bool success; QList<AbstractAudioOutput*> outputList = d->outputs; foreach( AbstractAudioOutput* output, outputList ) { BACKEND_GET1( bool, success, "addOutput", QObject*, output->iface() ); if( !success ) d->outputs.removeAll( output ); } QList<AudioEffect*> effectList = d->effects; foreach( AudioEffect* effect, effectList ) { BACKEND_GET1( bool, success, "insertEffect", QObject*, effect->iface() ); if( !success ) d->effects.removeAll( effect ); } } void AudioPathPrivate::phononObjectDestroyed( Base* o ) { // this method is called from Phonon::Base::~Base(), meaning the AudioEffect // dtor has already been called, also virtual functions don't work anymore // (therefore qobject_cast can only downcast from Base) Q_ASSERT( o ); AbstractAudioOutput* output = static_cast<AbstractAudioOutput*>( o ); AudioEffect* audioEffect = static_cast<AudioEffect*>( o ); if( outputs.contains( output ) ) { if( backendObject ) pBACKEND_CALL1( "removeOutput", QObject*, output->iface() ); outputs.removeAll( output ); } else if( effects.contains( audioEffect ) ) { if( backendObject ) pBACKEND_CALL1( "removeEffect", QObject*, audioEffect->iface() ); effects.removeAll( audioEffect ); } } } //namespace Phonon #include "audiopath.moc" #undef PHONON_CLASSNAME // vim: sw=4 ts=4 tw=80 <commit_msg>don't call the backend for invalid frontend objects (a frontend object is !isValid() if there's no backend object, and none can be created)<commit_after>/* This file is part of the KDE project Copyright (C) 2005-2006 Matthias Kretz <kretz@kde.org> This library is free software; you can redistribute it and/or modify it under the terms of the GNU Library General Public License version 2 as published by the Free Software Foundation. This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Library General Public License for more details. You should have received a copy of the GNU Library General Public License along with this library; see the file COPYING.LIB. If not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ #include "audiopath.h" #include "audiopath_p.h" #include "factory.h" #include "audioeffect.h" #include "abstractaudiooutput.h" #define PHONON_CLASSNAME AudioPath namespace Phonon { PHONON_OBJECT_IMPL AudioPath::~AudioPath() { K_D( AudioPath ); foreach(AbstractAudioOutput *ao, d->outputs) d->removeDestructionHandler(ao, d); foreach(AudioEffect *ae, d->effects) d->removeDestructionHandler(ae, d); } bool AudioPath::addOutput( AbstractAudioOutput* audioOutput ) { K_D( AudioPath ); if( d->outputs.contains( audioOutput ) ) return false; if (iface() && audioOutput->iface()) { bool success; BACKEND_GET1( bool, success, "addOutput", QObject*, audioOutput->iface() ); if( success ) { d->addDestructionHandler(audioOutput, d); d->outputs << audioOutput; return true; } } return false; } bool AudioPath::removeOutput( AbstractAudioOutput* audioOutput ) { K_D( AudioPath ); if( !d->outputs.contains( audioOutput ) ) return false; if (d->backendObject && audioOutput->iface()) { bool success; BACKEND_GET1( bool, success, "removeOutput", QObject*, audioOutput->iface() ); if( success ) { d->outputs.removeAll( audioOutput ); return true; } } return false; } const QList<AbstractAudioOutput*>& AudioPath::outputs() const { K_D( const AudioPath ); return d->outputs; } bool AudioPath::insertEffect( AudioEffect* newEffect, AudioEffect* insertBefore ) { // effects may be added multiple times, but that means the objects are // different (the class is still the same) K_D( AudioPath ); if( d->effects.contains( newEffect ) ) return false; if (iface() && newEffect->iface()) { bool success; BACKEND_GET2( bool, success, "insertEffect", QObject*, newEffect->iface(), QObject*, insertBefore ? insertBefore->iface() : 0 ); if( success ) { d->addDestructionHandler(newEffect, d); if( insertBefore ) d->effects.insert( d->effects.indexOf( insertBefore ), newEffect ); else d->effects << newEffect; return true; } } return false; } bool AudioPath::removeEffect( AudioEffect* effect ) { K_D( AudioPath ); if( !d->effects.contains( effect ) ) return false; if( d->backendObject ) { bool success; BACKEND_GET1( bool, success, "removeEffect", QObject*, effect->iface() ); if( success ) { d->effects.removeAll( effect ); return true; } } return false; } const QList<AudioEffect*>& AudioPath::effects() const { K_D( const AudioPath ); return d->effects; } bool AudioPathPrivate::aboutToDeleteIface() { return true; } void AudioPath::setupIface() { K_D( AudioPath ); Q_ASSERT( d->backendObject ); // set up attributes bool success; QList<AbstractAudioOutput*> outputList = d->outputs; foreach( AbstractAudioOutput* output, outputList ) { if (output->iface()) { BACKEND_GET1(bool, success, "addOutput", QObject*, output->iface()); } else { success = false; } if( !success ) d->outputs.removeAll( output ); } QList<AudioEffect*> effectList = d->effects; foreach( AudioEffect* effect, effectList ) { if (effect->iface()) { BACKEND_GET1( bool, success, "insertEffect", QObject*, effect->iface() ); } else { success = false; } if( !success ) d->effects.removeAll( effect ); } } void AudioPathPrivate::phononObjectDestroyed( Base* o ) { // this method is called from Phonon::Base::~Base(), meaning the AudioEffect // dtor has already been called, also virtual functions don't work anymore // (therefore qobject_cast can only downcast from Base) Q_ASSERT( o ); AbstractAudioOutput* output = static_cast<AbstractAudioOutput*>( o ); AudioEffect* audioEffect = static_cast<AudioEffect*>( o ); if( outputs.contains( output ) ) { if (backendObject && output->iface()) { pBACKEND_CALL1( "removeOutput", QObject*, output->iface() ); } outputs.removeAll( output ); } else if( effects.contains( audioEffect ) ) { if (backendObject && audioEffect->iface()) { pBACKEND_CALL1( "removeEffect", QObject*, audioEffect->iface() ); } effects.removeAll( audioEffect ); } } } //namespace Phonon #include "audiopath.moc" #undef PHONON_CLASSNAME // vim: sw=4 ts=4 tw=80 <|endoftext|>
<commit_before>/* * Copyright (c) 2000-2008 Stephen Williams (steve@icarus.com) * * This source code is free software; you can redistribute it * and/or modify it in source code form under the terms of the GNU * General Public License as published by the Free Software * Foundation; either version 2 of the License, or (at your option) * any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA */ # include "config.h" # include "PExpr.h" # include "compiler.h" # include "util.h" # include "netmisc.h" # include <cstdlib> # include <iostream> # include "ivl_assert.h" NetExpr*PExpr::elaborate_pexpr(Design*des, NetScope*sc) const { cerr << get_fileline() << ": error: invalid parameter expression: " << *this << endl; des->errors += 1; return 0; } /* * Binary operators have sub-expressions that must be elaborated as * parameter expressions. If either of them fail, then give up. Once * they are taken care of, make the base object just as in any other * expression. */ NetExpr*PEBinary::elaborate_pexpr (Design*des, NetScope*scope) const { NetExpr*lp = left_->elaborate_pexpr(des, scope); NetExpr*rp = right_->elaborate_pexpr(des, scope); if ((lp == 0) || (rp == 0)) { delete lp; delete rp; return 0; } NetEBinary*tmp = elaborate_expr_base_(des, lp, rp, -2); return tmp; } /* * Event though parameters are not generally sized, parameter * expressions can include concatenation expressions. This requires * that the subexpressions all have well-defined size (in spite of * being in a parameter expression) in order to get a defined * value. The sub-expressions themselves must also be value parameter * expressions. */ NetEConcat* PEConcat::elaborate_pexpr(Design*des, NetScope*scope) const { NetExpr* repeat = 0; /* If there is a repeat expression, then evaluate the constant value and set the repeat count. */ if (repeat_) { repeat = repeat_->elaborate_pexpr(des, scope); if (repeat == 0) { cerr << get_fileline() << ": error: " "concatenation repeat expression cannot be evaluated." << endl; des->errors += 1; return 0; } /* continue on even if the repeat expression doesn't work, as we can find more errors. */ } /* Make the empty concat expression. */ NetEConcat*tmp = new NetEConcat(parms_.count(), repeat); tmp->set_line(*this); /* Elaborate all the operands and attach them to the concat node. Use the elaborate_pexpr method instead of the elaborate_expr method. */ for (unsigned idx = 0 ; idx < parms_.count() ; idx += 1) { assert(parms_[idx]); NetExpr*ex = parms_[idx]->elaborate_pexpr(des, scope); if (ex == 0) continue; ex->set_line(*parms_[idx]); if (dynamic_cast<NetEParam*>(ex)) { /* If this parameter is a NetEParam, then put off the width check for later. */ } else if (! ex->has_width()) { cerr << ex->get_fileline() << ": error: operand of " << "concatenation has indefinite width: " << *ex << endl; des->errors += 1; delete tmp; return 0; } tmp->set(idx, ex); } return tmp; } NetExpr*PEFNumber::elaborate_pexpr(Design*des, NetScope*scope) const { return elaborate_expr(des, scope, -1, false); } /* * Parameter expressions may reference other parameters, but only in * the current scope. Preserve the parameter reference in the * parameter expression I'm generating, instead of evaluating it now, * because the referenced parameter may yet be overridden. */ NetExpr*PEIdent::elaborate_pexpr(Design*des, NetScope*scope) const { pform_name_t path = path_; name_component_t name_tail = path_.back(); path.pop_back(); NetScope*pscope = scope; if (path_.size() > 0) { list<hname_t> tmp = eval_scope_path(des, scope, path); pscope = des->find_scope(scope, tmp); } const NetExpr*ex_msb; const NetExpr*ex_lsb; const NetExpr*ex = 0; // Look up the parameter name in the current scope. If the // name is not found in the pscope, look in containing scopes, // but do not go outside the containing module instance. for (;;) { ex = pscope->get_parameter(name_tail.name, ex_msb, ex_lsb); if (ex != 0) break; if (pscope->type() == NetScope::MODULE) break; pscope = pscope->parent(); ivl_assert(*this, pscope); } if (ex == 0) { cerr << get_fileline() << ": error: identifier ``" << name_tail.name << "'' is not a parameter in "<< scope_path(scope)<< "." << endl; des->errors += 1; return 0; } NetExpr*res = new NetEParam(des, pscope, name_tail.name); res->set_line(*this); assert(res); index_component_t::ctype_t use_sel = index_component_t::SEL_NONE; if (!name_tail.index.empty()) use_sel = name_tail.index.back().sel; switch (use_sel) { case index_component_t::SEL_NONE: break; default: case index_component_t::SEL_PART: cerr << get_fileline() << ": sorry: Cannot part select " "bits of parameters." << endl; des->errors += 1; delete res; return 0; case index_component_t::SEL_BIT: /* We have here a bit select. Insert a NetESelect node to handle it. */ NetExpr*tmp = name_tail.index.back().msb->elaborate_pexpr(des, scope); if (tmp == 0) { delete res; return 0; } res = new NetESelect(res, tmp, 1); res->set_line(*this); break; } return res; } /* * Simple numbers can be elaborated by the elaborate_expr method. */ NetExpr*PENumber::elaborate_pexpr(Design*des, NetScope*sc) const { return elaborate_expr(des, sc, -1, false); } NetEConst* PEString::elaborate_pexpr(Design*des, NetScope*scope) const { return elaborate_expr(des, scope, -1, false); } NetETernary* PETernary::elaborate_pexpr(Design*des, NetScope*scope) const { NetExpr*c = expr_->elaborate_pexpr(des, scope); NetExpr*t = tru_->elaborate_pexpr(des, scope); NetExpr*f = fal_->elaborate_pexpr(des, scope); if (c == 0 || t == 0 || f == 0) return 0; NetETernary*tmp = new NetETernary(c, t, f); tmp->set_line(*this); return tmp; } NetExpr*PEUnary::elaborate_pexpr (Design*des, NetScope*scope) const { NetExpr*ip = expr_->elaborate_pexpr(des, scope); if (ip == 0) return 0; /* Should we evaluate expressions ahead of time, * just like in PEBinary::elaborate_expr() ? */ NetEUnary*tmp; switch (op_) { default: tmp = new NetEUnary(op_, ip); tmp->set_line(*this); break; case '~': tmp = new NetEUBits(op_, ip); tmp->set_line(*this); break; case '!': // Logical NOT case '&': // Reduction AND case '|': // Reduction OR case '^': // Reduction XOR case 'A': // Reduction NAND (~&) case 'N': // Reduction NOR (~|) case 'X': // Reduction NXOR (~^) tmp = new NetEUReduce(op_, ip); tmp->set_line(*this); break; } return tmp; } <commit_msg>Some elab_pexpr debug text.<commit_after>/* * Copyright (c) 2000-2008 Stephen Williams (steve@icarus.com) * * This source code is free software; you can redistribute it * and/or modify it in source code form under the terms of the GNU * General Public License as published by the Free Software * Foundation; either version 2 of the License, or (at your option) * any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA */ # include "config.h" # include "PExpr.h" # include "compiler.h" # include "util.h" # include "netmisc.h" # include <cstdlib> # include <iostream> # include "ivl_assert.h" NetExpr*PExpr::elaborate_pexpr(Design*des, NetScope*sc) const { cerr << get_fileline() << ": error: invalid parameter expression: " << *this << endl; des->errors += 1; return 0; } /* * Binary operators have sub-expressions that must be elaborated as * parameter expressions. If either of them fail, then give up. Once * they are taken care of, make the base object just as in any other * expression. */ NetExpr*PEBinary::elaborate_pexpr (Design*des, NetScope*scope) const { NetExpr*lp = left_->elaborate_pexpr(des, scope); NetExpr*rp = right_->elaborate_pexpr(des, scope); if ((lp == 0) || (rp == 0)) { delete lp; delete rp; return 0; } NetEBinary*tmp = elaborate_expr_base_(des, lp, rp, -2); return tmp; } /* * Event though parameters are not generally sized, parameter * expressions can include concatenation expressions. This requires * that the subexpressions all have well-defined size (in spite of * being in a parameter expression) in order to get a defined * value. The sub-expressions themselves must also be value parameter * expressions. */ NetEConcat* PEConcat::elaborate_pexpr(Design*des, NetScope*scope) const { NetExpr* repeat = 0; /* If there is a repeat expression, then evaluate the constant value and set the repeat count. */ if (repeat_) { repeat = repeat_->elaborate_pexpr(des, scope); if (repeat == 0) { cerr << get_fileline() << ": error: " "concatenation repeat expression cannot be evaluated." << endl; des->errors += 1; return 0; } /* continue on even if the repeat expression doesn't work, as we can find more errors. */ } /* Make the empty concat expression. */ NetEConcat*tmp = new NetEConcat(parms_.count(), repeat); tmp->set_line(*this); /* Elaborate all the operands and attach them to the concat node. Use the elaborate_pexpr method instead of the elaborate_expr method. */ for (unsigned idx = 0 ; idx < parms_.count() ; idx += 1) { assert(parms_[idx]); NetExpr*ex = parms_[idx]->elaborate_pexpr(des, scope); if (ex == 0) continue; ex->set_line(*parms_[idx]); if (dynamic_cast<NetEParam*>(ex)) { /* If this parameter is a NetEParam, then put off the width check for later. */ } else if (! ex->has_width()) { cerr << ex->get_fileline() << ": error: operand of " << "concatenation has indefinite width: " << *ex << endl; des->errors += 1; delete tmp; return 0; } tmp->set(idx, ex); } return tmp; } NetExpr*PEFNumber::elaborate_pexpr(Design*des, NetScope*scope) const { return elaborate_expr(des, scope, -1, false); } /* * Parameter expressions may reference other parameters, but only in * the current scope. Preserve the parameter reference in the * parameter expression I'm generating, instead of evaluating it now, * because the referenced parameter may yet be overridden. */ NetExpr*PEIdent::elaborate_pexpr(Design*des, NetScope*scope) const { pform_name_t path = path_; name_component_t name_tail = path_.back(); path.pop_back(); NetScope*pscope = scope; if (path_.size() > 0) { list<hname_t> tmp = eval_scope_path(des, scope, path); pscope = des->find_scope(scope, tmp); } const NetExpr*ex_msb; const NetExpr*ex_lsb; const NetExpr*ex = 0; // Look up the parameter name in the current scope. If the // name is not found in the pscope, look in containing scopes, // but do not go outside the containing module instance. for (;;) { ex = pscope->get_parameter(name_tail.name, ex_msb, ex_lsb); if (ex != 0) break; if (pscope->type() == NetScope::MODULE) break; pscope = pscope->parent(); ivl_assert(*this, pscope); } if (ex == 0) { cerr << get_fileline() << ": error: identifier ``" << name_tail.name << "'' is not a parameter in "<< scope_path(scope)<< "." << endl; des->errors += 1; return 0; } NetExpr*res = new NetEParam(des, pscope, name_tail.name); res->set_line(*this); assert(res); index_component_t::ctype_t use_sel = index_component_t::SEL_NONE; if (!name_tail.index.empty()) use_sel = name_tail.index.back().sel; switch (use_sel) { case index_component_t::SEL_NONE: break; default: case index_component_t::SEL_PART: cerr << get_fileline() << ": sorry: Cannot part select " "bits of parameters." << endl; des->errors += 1; delete res; return 0; case index_component_t::SEL_BIT: /* We have here a bit select. Insert a NetESelect node to handle it. */ NetExpr*tmp = name_tail.index.back().msb->elaborate_pexpr(des, scope); if (tmp == 0) { delete res; return 0; } if (debug_elaborate) cerr << get_fileline() << ": debug: " << "Bit select [" << *tmp << "]" << " in parameter expression." << endl; res = new NetESelect(res, tmp, 1); res->set_line(*this); break; } return res; } /* * Simple numbers can be elaborated by the elaborate_expr method. */ NetExpr*PENumber::elaborate_pexpr(Design*des, NetScope*sc) const { return elaborate_expr(des, sc, -1, false); } NetEConst* PEString::elaborate_pexpr(Design*des, NetScope*scope) const { return elaborate_expr(des, scope, -1, false); } NetETernary* PETernary::elaborate_pexpr(Design*des, NetScope*scope) const { NetExpr*c = expr_->elaborate_pexpr(des, scope); NetExpr*t = tru_->elaborate_pexpr(des, scope); NetExpr*f = fal_->elaborate_pexpr(des, scope); if (c == 0 || t == 0 || f == 0) return 0; NetETernary*tmp = new NetETernary(c, t, f); tmp->set_line(*this); return tmp; } NetExpr*PEUnary::elaborate_pexpr (Design*des, NetScope*scope) const { NetExpr*ip = expr_->elaborate_pexpr(des, scope); if (ip == 0) return 0; /* Should we evaluate expressions ahead of time, * just like in PEBinary::elaborate_expr() ? */ NetEUnary*tmp; switch (op_) { default: tmp = new NetEUnary(op_, ip); tmp->set_line(*this); break; case '~': tmp = new NetEUBits(op_, ip); tmp->set_line(*this); break; case '!': // Logical NOT case '&': // Reduction AND case '|': // Reduction OR case '^': // Reduction XOR case 'A': // Reduction NAND (~&) case 'N': // Reduction NOR (~|) case 'X': // Reduction NXOR (~^) tmp = new NetEUReduce(op_, ip); tmp->set_line(*this); break; } return tmp; } <|endoftext|>
<commit_before>// This file is part of the dune-grid-multiscale project: // http://users.dune-project.org/projects/dune-grid-multiscale // Copyright holders: Felix Albrecht // License: BSD 2-Clause License (http://opensource.org/licenses/BSD-2-Clause) #ifndef DUNE_GRID_PART_ITERATOR_CODIM0_HH #define DUNE_GRID_PART_ITERATOR_CODIM0_HH #ifdef HAVE_CMAKE_CONFIG #include "cmake_config.h" #elif defined (HAVE_CONFIG_H) #include <config.h> #endif // ifdef HAVE_CMAKE_CONFIG // system #include <map> // dune-common #include <dune/common/exceptions.hh> #include <dune/common/shared_ptr.hh> // dune-geometry #include <dune/geometry/type.hh> // dune-grid #include <dune/grid/common/grid.hh> namespace Dune { namespace grid { namespace Part { namespace Iterator { namespace Local { /** * \brief Iterates over those entities of a grid part, the indices of which match predefined ones. * \todo Replace GlobalGridPartImp with Interface< GlobalGridPartTraitsImp >! * \todo Document! */ template< class GlobalGridPartImp, int codim, Dune::PartitionIteratorType pitype > class IndexBased : public GlobalGridPartImp::template Codim< codim >::template Partition< pitype >::IteratorType { public: typedef GlobalGridPartImp GlobalGridPartType; typedef IndexBased< GlobalGridPartType, codim, pitype > ThisType; typedef typename GlobalGridPartImp::template Codim< codim >::template Partition< pitype >::IteratorType BaseType; typedef typename GlobalGridPartType::IndexSetType::IndexType IndexType; typedef Dune::GeometryType GeometryType; private: typedef std::map< IndexType, IndexType > IndexMapType; public: typedef std::map< GeometryType, std::map< IndexType, IndexType > > IndexContainerType; typedef typename BaseType::Entity Entity; IndexBased(const GlobalGridPartType& globalGridPart, const Dune::shared_ptr< const IndexContainerType > indexContainer, const bool end = false) : BaseType(end ? globalGridPart.template end< codim, pitype >() : globalGridPart.template begin< codim, pitype >()), globalGridPart_(globalGridPart), indexContainer_(indexContainer), workAtAll_(0) { if (!end) { // loop over all GeometryTypes for (typename IndexContainerType::const_iterator iterator = indexContainer_->begin(); iterator != indexContainer_->end(); ++iterator) { // treat only the codim 0 ones if (iterator->first.dim() == (GlobalGridPartType::GridType::dimension - codim)) { ++workAtAll_; last_.insert(std::make_pair(iterator->first, iterator->second.rbegin()->first)); end_.insert(std::make_pair(iterator->first, iterator->second.end())); } // treat only the codim 0 ones } // loop over all GeometryTypes forward(); } // if (!end) } // IndexBased ThisType& operator++() { if (workAtAll_ > 0) { BaseType::operator++(); forward(); } else BaseType::operator=(globalGridPart_.template end< codim, pitype >()); return *this; } // ThisType& operator++() private: //! iterates forward until we find the next entity that belongs to the local grid part void forward() { bool found = false; while (!found && (workAtAll_ > 0)) { const Entity& entity = BaseType::operator*(); const IndexType& index = globalGridPart_.indexSet().index(entity); const GeometryType& geometryType = entity.type(); typename IndexContainerType::const_iterator indexMap = indexContainer_->find(geometryType); if (indexMap != indexContainer_->end()) { const typename IndexMapType::const_iterator result = indexMap->second.find(index); if ((result != end_.find(geometryType)->second)) { found = true; if (result->first == last_.find(geometryType)->second) --workAtAll_; } else BaseType::operator++(); } else BaseType::operator++(); } } // void forward() const GlobalGridPartType& globalGridPart_; const Dune::shared_ptr< const IndexContainerType > indexContainer_; unsigned int workAtAll_; std::map< GeometryType, IndexType > last_; std::map< GeometryType, typename IndexMapType::const_iterator > end_; }; // class IndexBased } // namespace Local } // namespace Iterator } // namespace Part } // namespace grid } // namespace Dune #endif // DUNE_GRID_PART_ITERATOR_CODIM0_HH <commit_msg>[grid.part.iterator.local.indexbased] add std::iterator_traits<commit_after>// This file is part of the dune-grid-multiscale project: // http://users.dune-project.org/projects/dune-grid-multiscale // Copyright holders: Felix Albrecht // License: BSD 2-Clause License (http://opensource.org/licenses/BSD-2-Clause) #ifndef DUNE_GRID_PART_ITERATOR_CODIM0_HH #define DUNE_GRID_PART_ITERATOR_CODIM0_HH #ifdef HAVE_CMAKE_CONFIG #include "cmake_config.h" #elif defined (HAVE_CONFIG_H) #include <config.h> #endif // ifdef HAVE_CMAKE_CONFIG // system #include <map> // dune-common #include <dune/common/exceptions.hh> #include <dune/common/shared_ptr.hh> // dune-geometry #include <dune/geometry/type.hh> // dune-grid #include <dune/grid/common/grid.hh> namespace Dune { namespace grid { namespace Part { namespace Iterator { namespace Local { /** * \brief Iterates over those entities of a grid part, the indices of which match predefined ones. * \todo Replace GlobalGridPartImp with Interface< GlobalGridPartTraitsImp >! * \todo Document! */ template< class GlobalGridPartImp, int codim, Dune::PartitionIteratorType pitype > class IndexBased : public GlobalGridPartImp::template Codim< codim >::template Partition< pitype >::IteratorType { public: typedef GlobalGridPartImp GlobalGridPartType; typedef IndexBased< GlobalGridPartType, codim, pitype > ThisType; typedef typename GlobalGridPartImp::template Codim< codim >::template Partition< pitype >::IteratorType BaseType; typedef typename GlobalGridPartType::IndexSetType::IndexType IndexType; typedef Dune::GeometryType GeometryType; private: typedef std::map< IndexType, IndexType > IndexMapType; public: typedef std::map< GeometryType, std::map< IndexType, IndexType > > IndexContainerType; typedef typename BaseType::Entity Entity; IndexBased(const GlobalGridPartType& globalGridPart, const Dune::shared_ptr< const IndexContainerType > indexContainer, const bool end = false) : BaseType(end ? globalGridPart.template end< codim, pitype >() : globalGridPart.template begin< codim, pitype >()), globalGridPart_(globalGridPart), indexContainer_(indexContainer), workAtAll_(0) { if (!end) { // loop over all GeometryTypes for (typename IndexContainerType::const_iterator iterator = indexContainer_->begin(); iterator != indexContainer_->end(); ++iterator) { // treat only the codim 0 ones if (iterator->first.dim() == (GlobalGridPartType::GridType::dimension - codim)) { ++workAtAll_; last_.insert(std::make_pair(iterator->first, iterator->second.rbegin()->first)); end_.insert(std::make_pair(iterator->first, iterator->second.end())); } // treat only the codim 0 ones } // loop over all GeometryTypes forward(); } // if (!end) } // IndexBased ThisType& operator++() { if (workAtAll_ > 0) { BaseType::operator++(); forward(); } else BaseType::operator=(globalGridPart_.template end< codim, pitype >()); return *this; } // ThisType& operator++() private: //! iterates forward until we find the next entity that belongs to the local grid part void forward() { bool found = false; while (!found && (workAtAll_ > 0)) { const Entity& entity = BaseType::operator*(); const IndexType& index = globalGridPart_.indexSet().index(entity); const GeometryType& geometryType = entity.type(); typename IndexContainerType::const_iterator indexMap = indexContainer_->find(geometryType); if (indexMap != indexContainer_->end()) { const typename IndexMapType::const_iterator result = indexMap->second.find(index); if ((result != end_.find(geometryType)->second)) { found = true; if (result->first == last_.find(geometryType)->second) --workAtAll_; } else BaseType::operator++(); } else BaseType::operator++(); } } // void forward() const GlobalGridPartType& globalGridPart_; const Dune::shared_ptr< const IndexContainerType > indexContainer_; unsigned int workAtAll_; std::map< GeometryType, IndexType > last_; std::map< GeometryType, typename IndexMapType::const_iterator > end_; }; // class IndexBased } // namespace Local } // namespace Iterator } // namespace Part } // namespace grid } // namespace Dune namespace std { template< class GlobalGridPartImp, int codim, Dune::PartitionIteratorType pitype > struct iterator_traits< Dune::grid::Part::Iterator::Local::IndexBased< GlobalGridPartImp, codim, pitype > > { typedef ptrdiff_t difference_type; typedef const typename Dune::grid::Part::Iterator::Local::IndexBased< GlobalGridPartImp, codim, pitype >::Entity value_type; typedef value_type *pointer; typedef value_type &reference; typedef forward_iterator_tag iterator_category; }; } // namespace std #endif // DUNE_GRID_PART_ITERATOR_CODIM0_HH <|endoftext|>
<commit_before>/* * Copyright 2011 Google Inc. * * Use of this source code is governed by a BSD-style license that can be * found in the LICENSE file. */ #include "gm.h" #include "SkCanvas.h" #include "SkPath.h" // Reproduces bug found here: http://jsfiddle.net/R8Cu5/1/ // #include "SkGradientShader.h" static void test_grad(SkCanvas* canvas) { SkPoint pts[] = { { 478.544067f, -84.2041016f }, { 602.455933f, 625.204102f }, }; SkColor colors[] = { SK_ColorBLACK, SK_ColorBLACK, SK_ColorRED, SK_ColorRED }; SkScalar pos[] = { 0, 0.3f, 0.3f, 1.0f }; SkShader* s = SkGradientShader::CreateLinear(pts, colors, pos, 4, SkShader::kClamp_TileMode); SkPaint p; p.setShader(s)->unref(); canvas->drawPaint(p); } static SkCanvas* MakeCanvas(const SkIRect& bounds) { SkBitmap bm; bm.setConfig(SkBitmap::kARGB_8888_Config, bounds.width(), bounds.height()); bm.allocPixels(); bm.eraseColor(SK_ColorTRANSPARENT); SkCanvas* canvas = new SkCanvas(bm); canvas->translate(-SkIntToScalar(bounds.fLeft), -SkIntToScalar(bounds.fTop)); return canvas; } #ifdef SK_DEBUG static void GetBitmap(const SkCanvas* canvas, SkBitmap* bm) { *bm = canvas->getDevice()->accessBitmap(false); } #endif static void compare_canvas(const SkCanvas* a, const SkCanvas* b) { #ifdef SK_DEBUG SkBitmap bma, bmb; GetBitmap(a, &bma); GetBitmap(b, &bmb); SkASSERT(bma.width() == bmb.width()); SkASSERT(bma.height() == bmb.height()); bma.lockPixels(); bmb.lockPixels(); for (int y = 0; y < bma.height(); ++y) { const SkPMColor* rowa = bma.getAddr32(0, y); const SkPMColor* rowb = bmb.getAddr32(0, y); SkASSERT(!memcmp(rowa, rowb, bma.width() << 2)); for (int x = 1; x < bma.width() - 1; ++x) { SkASSERT(0xFF000000 == rowa[x]); SkASSERT(0xFF000000 == rowb[x]); } } #endif } static void drawRectAsPath(SkCanvas* canvas, const SkRect& r, const SkPaint& p) { SkPath path; path.addRect(r); canvas->drawPath(path, p); } static void test_maskFromPath(const SkPath& path) { SkIRect bounds; path.getBounds().roundOut(&bounds); SkPaint paint; paint.setAntiAlias(true); SkAutoTUnref<SkCanvas> path_canvas(MakeCanvas(bounds)); path_canvas->drawPath(path, paint); SkAutoTUnref<SkCanvas> rect_canvas(MakeCanvas(bounds)); drawRectAsPath(rect_canvas, path.getBounds(), paint); compare_canvas(path_canvas, rect_canvas); } static void test_mask() { for (int i = 1; i <= 20; ++i) { const SkScalar dx = SK_Scalar1 / i; const SkRect constr = SkRect::MakeWH(dx, SkIntToScalar(2)); for (int n = 2; n < 20; ++n) { SkPath path; path.setFillType(SkPath::kEvenOdd_FillType); SkRect r = constr; while (r.fRight < SkIntToScalar(4)) { path.addRect(r); r.offset(dx, 0); } test_maskFromPath(path); } } } namespace skiagm { /** Draw a 2px border around the target, then red behind the target; set the clip to match the target, then draw >> the target in blue. */ static void draw (SkCanvas* canvas, SkRect& target, int x, int y) { SkPaint borderPaint; borderPaint.setColor(SkColorSetRGB(0x0, 0xDD, 0x0)); borderPaint.setAntiAlias(true); SkPaint backgroundPaint; backgroundPaint.setColor(SkColorSetRGB(0xDD, 0x0, 0x0)); backgroundPaint.setAntiAlias(true); SkPaint foregroundPaint; foregroundPaint.setColor(SkColorSetRGB(0x0, 0x0, 0xDD)); foregroundPaint.setAntiAlias(true); canvas->save(); canvas->translate(SkIntToScalar(x), SkIntToScalar(y)); target.inset(SkIntToScalar(-2), SkIntToScalar(-2)); canvas->drawRect(target, borderPaint); target.inset(SkIntToScalar(2), SkIntToScalar(2)); canvas->drawRect(target, backgroundPaint); canvas->clipRect(target, SkRegion::kIntersect_Op, true); target.inset(SkIntToScalar(-4), SkIntToScalar(-4)); canvas->drawRect(target, foregroundPaint); canvas->restore(); } static void draw_square (SkCanvas* canvas, int x, int y) { SkRect target (SkRect::MakeWH(10 * SK_Scalar1, 10 * SK_Scalar1)); draw(canvas, target, x, y); } static void draw_column (SkCanvas* canvas, int x, int y) { SkRect target (SkRect::MakeWH(1 * SK_Scalar1, 10 * SK_Scalar1)); draw(canvas, target, x, y); } static void draw_bar (SkCanvas* canvas, int x, int y) { SkRect target (SkRect::MakeWH(10 * SK_Scalar1, 1 * SK_Scalar1)); draw(canvas, target, x, y); } static void draw_rect_tests (SkCanvas* canvas) { draw_square(canvas, 10, 10); draw_column(canvas, 30, 10); draw_bar(canvas, 10, 30); } /** Test a set of clipping problems discovered while writing blitAntiRect, and test all the code paths through the clipping blitters. Each region should show as a blue center surrounded by a 2px green border, with no red. */ class AAClipGM : public GM { public: AAClipGM() { } protected: virtual SkString onShortName() { return SkString("aaclip"); } virtual SkISize onISize() { return make_isize(640, 480); } virtual void onDraw(SkCanvas* canvas) { if (false) { test_grad(canvas); return; } if (false) { // avoid bit rot, suppress warning test_mask(); } // Initial pixel-boundary-aligned draw draw_rect_tests(canvas); // Repeat 4x with .2, .4, .6, .8 px offsets canvas->translate(SK_Scalar1 / 5, SK_Scalar1 / 5); canvas->translate(SkIntToScalar(50), 0); draw_rect_tests(canvas); canvas->translate(SK_Scalar1 / 5, SK_Scalar1 / 5); canvas->translate(SkIntToScalar(50), 0); draw_rect_tests(canvas); canvas->translate(SK_Scalar1 / 5, SK_Scalar1 / 5); canvas->translate(SkIntToScalar(50), 0); draw_rect_tests(canvas); canvas->translate(SK_Scalar1 / 5, SK_Scalar1 / 5); canvas->translate(SkIntToScalar(50), 0); draw_rect_tests(canvas); } virtual uint32_t onGetFlags() const { return kSkipPipe_Flag; } private: typedef GM INHERITED; }; ////////////////////////////////////////////////////////////////////////////// static GM* MyFactory(void*) { return new AAClipGM; } static GMRegistry reg(MyFactory); } <commit_msg>add (disabled) test for big dashing<commit_after>/* * Copyright 2011 Google Inc. * * Use of this source code is governed by a BSD-style license that can be * found in the LICENSE file. */ #include "gm.h" #include "SkCanvas.h" #include "SkPath.h" #include "SkDashPathEffect.h" static void test_giant_dash(SkCanvas* canvas) { SkPaint paint; const SkScalar intervals[] = { SK_Scalar1, SK_Scalar1 }; paint.setStrokeWidth(2); paint.setPathEffect(new SkDashPathEffect(intervals, 2, 0))->unref(); SkScalar big = 500 * 1000; canvas->drawLine(10, 10, big, 10, paint); canvas->drawLine(-big, 20, 500, 20, paint); canvas->drawLine(-big, 30, big, 30, paint); const SkScalar intervals2[] = { 20, 5, 10, 5 }; paint.setPathEffect(new SkDashPathEffect(intervals2, 4, 17))->unref(); canvas->translate(0, 40); SkScalar x = -500; SkScalar width = 3173; for (int i = 0; i < 40; ++i) { if (i > 10) canvas->drawLine(x, 0, x + width, 0, paint); x += 1; canvas->translate(0, 4); } } // Reproduces bug found here: http://jsfiddle.net/R8Cu5/1/ // #include "SkGradientShader.h" static void test_grad(SkCanvas* canvas) { SkPoint pts[] = { { 478.544067f, -84.2041016f }, { 602.455933f, 625.204102f }, }; SkColor colors[] = { SK_ColorBLACK, SK_ColorBLACK, SK_ColorRED, SK_ColorRED }; SkScalar pos[] = { 0, 0.3f, 0.3f, 1.0f }; SkShader* s = SkGradientShader::CreateLinear(pts, colors, pos, 4, SkShader::kClamp_TileMode); SkPaint p; p.setShader(s)->unref(); canvas->drawPaint(p); } static SkCanvas* MakeCanvas(const SkIRect& bounds) { SkBitmap bm; bm.setConfig(SkBitmap::kARGB_8888_Config, bounds.width(), bounds.height()); bm.allocPixels(); bm.eraseColor(SK_ColorTRANSPARENT); SkCanvas* canvas = new SkCanvas(bm); canvas->translate(-SkIntToScalar(bounds.fLeft), -SkIntToScalar(bounds.fTop)); return canvas; } #ifdef SK_DEBUG static void GetBitmap(const SkCanvas* canvas, SkBitmap* bm) { *bm = canvas->getDevice()->accessBitmap(false); } #endif static void compare_canvas(const SkCanvas* a, const SkCanvas* b) { #ifdef SK_DEBUG SkBitmap bma, bmb; GetBitmap(a, &bma); GetBitmap(b, &bmb); SkASSERT(bma.width() == bmb.width()); SkASSERT(bma.height() == bmb.height()); bma.lockPixels(); bmb.lockPixels(); for (int y = 0; y < bma.height(); ++y) { const SkPMColor* rowa = bma.getAddr32(0, y); const SkPMColor* rowb = bmb.getAddr32(0, y); SkASSERT(!memcmp(rowa, rowb, bma.width() << 2)); for (int x = 1; x < bma.width() - 1; ++x) { SkASSERT(0xFF000000 == rowa[x]); SkASSERT(0xFF000000 == rowb[x]); } } #endif } static void drawRectAsPath(SkCanvas* canvas, const SkRect& r, const SkPaint& p) { SkPath path; path.addRect(r); canvas->drawPath(path, p); } static void test_maskFromPath(const SkPath& path) { SkIRect bounds; path.getBounds().roundOut(&bounds); SkPaint paint; paint.setAntiAlias(true); SkAutoTUnref<SkCanvas> path_canvas(MakeCanvas(bounds)); path_canvas->drawPath(path, paint); SkAutoTUnref<SkCanvas> rect_canvas(MakeCanvas(bounds)); drawRectAsPath(rect_canvas, path.getBounds(), paint); compare_canvas(path_canvas, rect_canvas); } static void test_mask() { for (int i = 1; i <= 20; ++i) { const SkScalar dx = SK_Scalar1 / i; const SkRect constr = SkRect::MakeWH(dx, SkIntToScalar(2)); for (int n = 2; n < 20; ++n) { SkPath path; path.setFillType(SkPath::kEvenOdd_FillType); SkRect r = constr; while (r.fRight < SkIntToScalar(4)) { path.addRect(r); r.offset(dx, 0); } test_maskFromPath(path); } } } namespace skiagm { /** Draw a 2px border around the target, then red behind the target; set the clip to match the target, then draw >> the target in blue. */ static void draw (SkCanvas* canvas, SkRect& target, int x, int y) { SkPaint borderPaint; borderPaint.setColor(SkColorSetRGB(0x0, 0xDD, 0x0)); borderPaint.setAntiAlias(true); SkPaint backgroundPaint; backgroundPaint.setColor(SkColorSetRGB(0xDD, 0x0, 0x0)); backgroundPaint.setAntiAlias(true); SkPaint foregroundPaint; foregroundPaint.setColor(SkColorSetRGB(0x0, 0x0, 0xDD)); foregroundPaint.setAntiAlias(true); canvas->save(); canvas->translate(SkIntToScalar(x), SkIntToScalar(y)); target.inset(SkIntToScalar(-2), SkIntToScalar(-2)); canvas->drawRect(target, borderPaint); target.inset(SkIntToScalar(2), SkIntToScalar(2)); canvas->drawRect(target, backgroundPaint); canvas->clipRect(target, SkRegion::kIntersect_Op, true); target.inset(SkIntToScalar(-4), SkIntToScalar(-4)); canvas->drawRect(target, foregroundPaint); canvas->restore(); } static void draw_square (SkCanvas* canvas, int x, int y) { SkRect target (SkRect::MakeWH(10 * SK_Scalar1, 10 * SK_Scalar1)); draw(canvas, target, x, y); } static void draw_column (SkCanvas* canvas, int x, int y) { SkRect target (SkRect::MakeWH(1 * SK_Scalar1, 10 * SK_Scalar1)); draw(canvas, target, x, y); } static void draw_bar (SkCanvas* canvas, int x, int y) { SkRect target (SkRect::MakeWH(10 * SK_Scalar1, 1 * SK_Scalar1)); draw(canvas, target, x, y); } static void draw_rect_tests (SkCanvas* canvas) { draw_square(canvas, 10, 10); draw_column(canvas, 30, 10); draw_bar(canvas, 10, 30); } /** Test a set of clipping problems discovered while writing blitAntiRect, and test all the code paths through the clipping blitters. Each region should show as a blue center surrounded by a 2px green border, with no red. */ class AAClipGM : public GM { public: AAClipGM() { } protected: virtual SkString onShortName() { return SkString("aaclip"); } virtual SkISize onISize() { return make_isize(640, 480); } virtual void onDraw(SkCanvas* canvas) SK_OVERRIDE { if (false) { test_giant_dash(canvas); return; } if (false) { test_grad(canvas); return; } if (false) { // avoid bit rot, suppress warning test_mask(); } // Initial pixel-boundary-aligned draw draw_rect_tests(canvas); // Repeat 4x with .2, .4, .6, .8 px offsets canvas->translate(SK_Scalar1 / 5, SK_Scalar1 / 5); canvas->translate(SkIntToScalar(50), 0); draw_rect_tests(canvas); canvas->translate(SK_Scalar1 / 5, SK_Scalar1 / 5); canvas->translate(SkIntToScalar(50), 0); draw_rect_tests(canvas); canvas->translate(SK_Scalar1 / 5, SK_Scalar1 / 5); canvas->translate(SkIntToScalar(50), 0); draw_rect_tests(canvas); canvas->translate(SK_Scalar1 / 5, SK_Scalar1 / 5); canvas->translate(SkIntToScalar(50), 0); draw_rect_tests(canvas); } virtual uint32_t onGetFlags() const { return kSkipPipe_Flag; } private: typedef GM INHERITED; }; ////////////////////////////////////////////////////////////////////////////// static GM* MyFactory(void*) { return new AAClipGM; } static GMRegistry reg(MyFactory); } <|endoftext|>
<commit_before>/* The MIT License Copyright (c) 2014 Adrian Tan <atks@umich.edu> Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ #include "decompose.h" namespace { class Igor : Program { public: /////////// //options// /////////// std::string input_vcf_file; std::string output_vcf_file; std::vector<GenomeInterval> intervals; std::string ref_fasta_file; /////// //i/o// /////// BCFOrderedReader *odr; BCFOrderedWriter *odw; bcf1_t *v; kstring_t s; kstring_t new_alleles; kstring_t old_alleles; ///////// //stats// ///////// uint32_t no_variants; uint32_t no_biallelic; uint32_t no_multiallelic; uint32_t no_additional_biallelic; ///////// //tools// ///////// VariantManip *vm; Igor(int argc, char **argv) { version = "0.5"; ////////////////////////// //options initialization// ////////////////////////// try { std::string desc = "decomposes multialleic variants into biallelic in a VCF file, only sites are output."; TCLAP::CmdLine cmd(desc, ' ', version); VTOutput my; cmd.setOutput(&my); TCLAP::ValueArg<std::string> arg_intervals("i", "i", "intervals []", false, "", "str", cmd); TCLAP::ValueArg<std::string> arg_interval_list("I", "I", "file containing list of intervals []", false, "", "file", cmd); TCLAP::ValueArg<std::string> arg_output_vcf_file("o", "o", "output VCF file [-]", false, "-", "str", cmd); TCLAP::UnlabeledValueArg<std::string> arg_input_vcf_file("<in.vcf>", "input VCF file", true, "","file", cmd); cmd.parse(argc, argv); input_vcf_file = arg_input_vcf_file.getValue(); output_vcf_file = arg_output_vcf_file.getValue(); parse_intervals(intervals, arg_interval_list.getValue(), arg_intervals.getValue()); } catch (TCLAP::ArgException &e) { std::cerr << "error: " << e.error() << " for arg " << e.argId() << "\n"; abort(); } }; void initialize() { ////////////////////// //i/o initialization// ////////////////////// odr = new BCFOrderedReader(input_vcf_file, intervals); odw = new BCFOrderedWriter(output_vcf_file, 100000); odw->link_hdr(bcf_hdr_subset(odr->hdr, 0, 0, 0)); bcf_hdr_append(odw->hdr, "##INFO=<ID=OLD_MULTIALLELIC,Number=1,Type=String,Description=\"Original chr:pos:ref:alt encoding\">\n"); odw->write_hdr(); s = {0,0,0}; old_alleles = {0,0,0}; new_alleles = {0,0,0}; //////////////////////// //stats initialization// //////////////////////// no_variants = 0; no_biallelic = 0; no_multiallelic = 0; no_additional_biallelic = 0; //////////////////////// //tools initialization// //////////////////////// } void decompose() { v = odw->get_bcf1_from_pool(); Variant variant; while (odr->read(v)) { bcf_unpack(v, BCF_UN_INFO); int32_t n_allele = bcf_get_n_allele(v); if (n_allele > 2) { ++no_multiallelic; no_additional_biallelic += n_allele; old_alleles.l = 0; bcf_variant2string(odw->hdr, v, &old_alleles); int32_t rid = bcf_get_rid(v); int32_t pos1 = bcf_get_pos1(v); char** allele = bcf_get_allele(v); for (uint32_t i=1; i<n_allele; ++i) { bcf_set_rid(v, rid); bcf_set_pos1(v, pos1); new_alleles.l=0; kputs(allele[0], &new_alleles); kputc(',', &new_alleles); kputs(allele[i], &new_alleles); bcf_update_alleles_str(odw->hdr, v, new_alleles.s); bcf_update_info_string(odw->hdr, v, "OLD_MULTIALLELIC", old_alleles.s); bcf_subset(odw->hdr, v, 0, 0); odw->write(v); v = odw->get_bcf1_from_pool(); } } else { ++no_biallelic; bcf_subset(odw->hdr, v, 0, 0); odw->write(v); v = odw->get_bcf1_from_pool(); } ++no_variants; } odr->close(); odw->close(); }; void print_options() { std::clog << "decompose v" << version << "\n"; std::clog << "\n"; std::clog << "options: input VCF file " << input_vcf_file << "\n"; std::clog << " [o] output VCF file " << output_vcf_file << "\n"; print_int_op(" [i] intervals ", intervals); std::clog << "\n"; } void print_stats() { std::clog << "\n"; std::clog << "stats: no. variants : " << no_variants << "\n"; std::clog << " no. biallelic variants : " << no_biallelic << "\n"; std::clog << " no. multiallelic variants : " << no_multiallelic << "\n"; std::clog << "\n"; std::clog << " no. additional biallelics : " << no_additional_biallelic << "\n"; std::clog << " after decomposition\n"; std::clog << "\n"; }; ~Igor() {}; private: }; } void decompose(int argc, char ** argv) { Igor igor(argc, argv); igor.print_options(); igor.initialize(); igor.decompose(); igor.print_stats(); }; <commit_msg>fixed overcounting of new decomposed variants<commit_after>/* The MIT License Copyright (c) 2014 Adrian Tan <atks@umich.edu> Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ #include "decompose.h" namespace { class Igor : Program { public: /////////// //options// /////////// std::string input_vcf_file; std::string output_vcf_file; std::vector<GenomeInterval> intervals; std::string ref_fasta_file; /////// //i/o// /////// BCFOrderedReader *odr; BCFOrderedWriter *odw; bcf1_t *v; kstring_t s; kstring_t new_alleles; kstring_t old_alleles; ///////// //stats// ///////// uint32_t no_variants; uint32_t no_biallelic; uint32_t no_multiallelic; uint32_t no_additional_biallelic; ///////// //tools// ///////// VariantManip *vm; Igor(int argc, char **argv) { version = "0.5"; ////////////////////////// //options initialization// ////////////////////////// try { std::string desc = "decomposes multialleic variants into biallelic in a VCF file, only sites are output."; TCLAP::CmdLine cmd(desc, ' ', version); VTOutput my; cmd.setOutput(&my); TCLAP::ValueArg<std::string> arg_intervals("i", "i", "intervals []", false, "", "str", cmd); TCLAP::ValueArg<std::string> arg_interval_list("I", "I", "file containing list of intervals []", false, "", "file", cmd); TCLAP::ValueArg<std::string> arg_output_vcf_file("o", "o", "output VCF file [-]", false, "-", "str", cmd); TCLAP::UnlabeledValueArg<std::string> arg_input_vcf_file("<in.vcf>", "input VCF file", true, "","file", cmd); cmd.parse(argc, argv); input_vcf_file = arg_input_vcf_file.getValue(); output_vcf_file = arg_output_vcf_file.getValue(); parse_intervals(intervals, arg_interval_list.getValue(), arg_intervals.getValue()); } catch (TCLAP::ArgException &e) { std::cerr << "error: " << e.error() << " for arg " << e.argId() << "\n"; abort(); } }; void initialize() { ////////////////////// //i/o initialization// ////////////////////// odr = new BCFOrderedReader(input_vcf_file, intervals); odw = new BCFOrderedWriter(output_vcf_file, 100000); odw->link_hdr(bcf_hdr_subset(odr->hdr, 0, 0, 0)); bcf_hdr_append(odw->hdr, "##INFO=<ID=OLD_MULTIALLELIC,Number=1,Type=String,Description=\"Original chr:pos:ref:alt encoding\">\n"); odw->write_hdr(); s = {0,0,0}; old_alleles = {0,0,0}; new_alleles = {0,0,0}; //////////////////////// //stats initialization// //////////////////////// no_variants = 0; no_biallelic = 0; no_multiallelic = 0; no_additional_biallelic = 0; //////////////////////// //tools initialization// //////////////////////// } void decompose() { v = odw->get_bcf1_from_pool(); Variant variant; while (odr->read(v)) { bcf_unpack(v, BCF_UN_INFO); int32_t n_allele = bcf_get_n_allele(v); if (n_allele > 2) { ++no_multiallelic; no_additional_biallelic += n_allele-1; old_alleles.l = 0; bcf_variant2string(odw->hdr, v, &old_alleles); int32_t rid = bcf_get_rid(v); int32_t pos1 = bcf_get_pos1(v); char** allele = bcf_get_allele(v); for (uint32_t i=1; i<n_allele; ++i) { bcf_set_rid(v, rid); bcf_set_pos1(v, pos1); new_alleles.l=0; kputs(allele[0], &new_alleles); kputc(',', &new_alleles); kputs(allele[i], &new_alleles); bcf_update_alleles_str(odw->hdr, v, new_alleles.s); bcf_update_info_string(odw->hdr, v, "OLD_MULTIALLELIC", old_alleles.s); bcf_subset(odw->hdr, v, 0, 0); odw->write(v); v = odw->get_bcf1_from_pool(); } } else { ++no_biallelic; bcf_subset(odw->hdr, v, 0, 0); odw->write(v); v = odw->get_bcf1_from_pool(); } ++no_variants; } odr->close(); odw->close(); }; void print_options() { std::clog << "decompose v" << version << "\n"; std::clog << "\n"; std::clog << "options: input VCF file " << input_vcf_file << "\n"; std::clog << " [o] output VCF file " << output_vcf_file << "\n"; print_int_op(" [i] intervals ", intervals); std::clog << "\n"; } void print_stats() { std::clog << "\n"; std::clog << "stats: no. variants : " << no_variants << "\n"; std::clog << " no. biallelic variants : " << no_biallelic << "\n"; std::clog << " no. multiallelic variants : " << no_multiallelic << "\n"; std::clog << "\n"; std::clog << " no. additional biallelics : " << no_additional_biallelic << "\n"; std::clog << " after decomposition\n"; std::clog << "\n"; }; ~Igor() {}; private: }; } void decompose(int argc, char ** argv) { Igor igor(argc, argv); igor.print_options(); igor.initialize(); igor.decompose(); igor.print_stats(); }; <|endoftext|>
<commit_before>// Copyright (c) 2009-2010 Satoshi Nakamoto // Copyright (c) 2009-2019 The Syscoin Core developers // Distributed under the MIT software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. #include <util/validation.h> #include <consensus/validation.h> #include <tinyformat.h> /** Convert CValidationState to a human-readable message for logging */ std::string FormatStateMessage(const CValidationState &state) { return strprintf("%s%s (code %i)", state.GetRejectReason(), state.GetDebugMessage().empty() ? "" : ", "+state.GetDebugMessage(), state.GetRejectCode()); } const std::string strMessageMagic = "Bitcoin Signed Message:\n"; <commit_msg>use syscoin signed message message magic<commit_after>// Copyright (c) 2009-2010 Satoshi Nakamoto // Copyright (c) 2009-2019 The Syscoin Core developers // Distributed under the MIT software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. #include <util/validation.h> #include <consensus/validation.h> #include <tinyformat.h> /** Convert CValidationState to a human-readable message for logging */ std::string FormatStateMessage(const CValidationState &state) { return strprintf("%s%s (code %i)", state.GetRejectReason(), state.GetDebugMessage().empty() ? "" : ", "+state.GetDebugMessage(), state.GetRejectCode()); } const std::string strMessageMagic = "Syscoin Signed Message:\n"; <|endoftext|>
<commit_before>/** * @file ObstacleLocator.h * * @author <a href="mailto:mellmann@informatik.hu-berlin.de">Heinrich Mellmann</a> * @author <a href="mailto:borisov@informatik.hu-berlin.de">Alexander Borisov</a> * @author <a href="mailto:krienelk@informatik.hu-berlin.de">Dominik Krienelke</a> * Implementation of class ObstacleLocator */ #include "UltraSoundObstacleLocator.h" // in accordance to the Aldeberan documentation and the raw values const double UltraSoundObstacleLocator::invalidDistanceValue = 2550.0; const double UltraSoundObstacleLocator::maxValidDistance = 500.0; UltraSoundObstacleLocator::UltraSoundObstacleLocator() : wasFrontBlockedInLastFrame(false) { DEBUG_REQUEST_REGISTER("UltraSoundObstacleLocator:drawObstacle", "draw the modelled Obstacle on the field", false); DEBUG_REQUEST_REGISTER("UltraSoundObstacleLocator:drawSensorData", "draw the measured echos", false); DEBUG_REQUEST_REGISTER("UltraSoundObstacleLocator:drawBuffer", "draw buffer of measurements", false); getDebugParameterList().add(&params); } UltraSoundObstacleLocator::~UltraSoundObstacleLocator() { getDebugParameterList().remove(&params); } void UltraSoundObstacleLocator::execute() { getObstacleModel().leftDistance = invalidDistanceValue; getObstacleModel().rightDistance = invalidDistanceValue; getObstacleModel().frontDistance = invalidDistanceValue; fillBuffer(); // Compute mean of seen obstacles and use that data as estimated USObstacle // in local obstacle model provideToLocalObstacleModel(); //Draw ObstacleModel drawObstacleModel(); }//end execute void UltraSoundObstacleLocator::drawObstacleModel() { DEBUG_REQUEST("UltraSoundObstacleLocator:drawBuffer", FIELD_DRAWING_CONTEXT; PEN("FF0000", 25); for(int i = 0; i < bufferLeft.size(); i++) { double dist = bufferLeft[i]; CIRCLE( dist, dist, 10); } PEN("0000FF", 25); for(int i = 0; i < bufferRight.size(); i++) { double dist = bufferRight[i]; CIRCLE( dist, -dist, 10); } ); DEBUG_REQUEST("UltraSoundObstacleLocator:drawSensorData", FIELD_DRAWING_CONTEXT; Color colorLeft(Color::blue); Color colorRight(Color::red); colorLeft[Color::Alpha] = 0.5; colorRight[Color::Alpha] = 0.5; // draw raw sensor data for(unsigned int i = 0; i < UltraSoundReceiveData::numOfUSEcho; i++) { double distLeft = getUltraSoundReceiveData().dataLeft[i] * 1000.0; double distRight = getUltraSoundReceiveData().dataRight[i] * 1000.0; PEN(colorLeft, 25); CIRCLE( distLeft, distLeft, 50); PEN(colorRight, 25); CIRCLE( distRight, -distRight, 50); }//end for ); // draw model DEBUG_REQUEST("UltraSoundObstacleLocator:drawObstacle", FIELD_DRAWING_CONTEXT; PEN("FF0000", 50); CIRCLE( getObstacleModel().leftDistance, getObstacleModel().leftDistance, 50); PEN("0000FF", 50); CIRCLE( getObstacleModel().rightDistance, -getObstacleModel().rightDistance, 50); PEN("000000", 50); LINE(getObstacleModel().frontDistance, -200, getObstacleModel().frontDistance, 200); ); } //end drawObstacleMode bool UltraSoundObstacleLocator::isNewDataAvaliable() const { // NOTE: this can lead to unexpected/undesired behavior, if the sensor - for whatever reson - // returns the same data for some time! for(int i = 0; i < UltraSoundReceiveData::numOfUSEcho; i++) { if(getUltraSoundReceiveData().dataLeft[i] != lastValidUltraSoundReceiveData.dataLeft[i] || getUltraSoundReceiveData().dataRight[i] != lastValidUltraSoundReceiveData.dataRight[i]) { return true; } } return false; } void UltraSoundObstacleLocator::fillBuffer() { if(!isNewDataAvaliable()) { return; } lastValidUltraSoundReceiveData = getUltraSoundReceiveData(); // convert to mm double leftMeasurement = getUltraSoundReceiveData().dataLeft[0] * 1000.0; double rightMeasurement = getUltraSoundReceiveData().dataRight[0] * 1000.0; bufferRight.add(rightMeasurement); bufferLeft.add(leftMeasurement); } void UltraSoundObstacleLocator::provideToLocalObstacleModel() { ObstacleModel& model = getObstacleModel(); if(bufferLeft.size() == 0) { model.leftDistance = invalidDistanceValue; } else { model.leftDistance = bufferLeft.getMedian(); } if(bufferRight.size() == 0) { model.rightDistance = invalidDistanceValue; } else { model.rightDistance = bufferRight.getMedian(); } if(model.leftDistance <= maxValidDistance || model.rightDistance <= maxValidDistance) { model.frontDistance = std::min(model.leftDistance, model.rightDistance); } if(model.frontDistance < params.minBlockedDistance) { if(!wasFrontBlockedInLastFrame) { timeWhenFrontBlockStarted = getFrameInfo(); } wasFrontBlockedInLastFrame = true; model.blockedTime = getFrameInfo().getTimeSince(timeWhenFrontBlockStarted.getTime()); } else { model.blockedTime = -1; wasFrontBlockedInLastFrame = false; } } //end provideToLocalObstacleModel <commit_msg>if measurements are 0 the sonars have an error. This change adapts the US Obstacledetector such that it will ignore the error and behave like no obstacle is there.<commit_after>/** * @file ObstacleLocator.h * * @author <a href="mailto:mellmann@informatik.hu-berlin.de">Heinrich Mellmann</a> * @author <a href="mailto:borisov@informatik.hu-berlin.de">Alexander Borisov</a> * @author <a href="mailto:krienelk@informatik.hu-berlin.de">Dominik Krienelke</a> * Implementation of class ObstacleLocator */ #include "UltraSoundObstacleLocator.h" // in accordance to the Aldeberan documentation and the raw values const double UltraSoundObstacleLocator::invalidDistanceValue = 2550.0; const double UltraSoundObstacleLocator::maxValidDistance = 500.0; UltraSoundObstacleLocator::UltraSoundObstacleLocator() : wasFrontBlockedInLastFrame(false) { DEBUG_REQUEST_REGISTER("UltraSoundObstacleLocator:drawObstacle", "draw the modelled Obstacle on the field", false); DEBUG_REQUEST_REGISTER("UltraSoundObstacleLocator:drawSensorData", "draw the measured echos", false); DEBUG_REQUEST_REGISTER("UltraSoundObstacleLocator:drawBuffer", "draw buffer of measurements", false); getDebugParameterList().add(&params); } UltraSoundObstacleLocator::~UltraSoundObstacleLocator() { getDebugParameterList().remove(&params); } void UltraSoundObstacleLocator::execute() { getObstacleModel().leftDistance = invalidDistanceValue; getObstacleModel().rightDistance = invalidDistanceValue; getObstacleModel().frontDistance = invalidDistanceValue; fillBuffer(); // Compute mean of seen obstacles and use that data as estimated USObstacle // in local obstacle model provideToLocalObstacleModel(); //Draw ObstacleModel drawObstacleModel(); }//end execute void UltraSoundObstacleLocator::drawObstacleModel() { DEBUG_REQUEST("UltraSoundObstacleLocator:drawBuffer", FIELD_DRAWING_CONTEXT; PEN("FF0000", 25); for(int i = 0; i < bufferLeft.size(); i++) { double dist = bufferLeft[i]; CIRCLE( dist, dist, 10); } PEN("0000FF", 25); for(int i = 0; i < bufferRight.size(); i++) { double dist = bufferRight[i]; CIRCLE( dist, -dist, 10); } ); DEBUG_REQUEST("UltraSoundObstacleLocator:drawSensorData", FIELD_DRAWING_CONTEXT; Color colorLeft(Color::blue); Color colorRight(Color::red); colorLeft[Color::Alpha] = 0.5; colorRight[Color::Alpha] = 0.5; // draw raw sensor data for(unsigned int i = 0; i < UltraSoundReceiveData::numOfUSEcho; i++) { double distLeft = getUltraSoundReceiveData().dataLeft[i] * 1000.0; double distRight = getUltraSoundReceiveData().dataRight[i] * 1000.0; PEN(colorLeft, 25); CIRCLE( distLeft, distLeft, 50); PEN(colorRight, 25); CIRCLE( distRight, -distRight, 50); }//end for ); // draw model DEBUG_REQUEST("UltraSoundObstacleLocator:drawObstacle", FIELD_DRAWING_CONTEXT; PEN("FF0000", 50); CIRCLE( getObstacleModel().leftDistance, getObstacleModel().leftDistance, 50); PEN("0000FF", 50); CIRCLE( getObstacleModel().rightDistance, -getObstacleModel().rightDistance, 50); PEN("000000", 50); LINE(getObstacleModel().frontDistance, -200, getObstacleModel().frontDistance, 200); ); } //end drawObstacleMode bool UltraSoundObstacleLocator::isNewDataAvaliable() const { // NOTE: this can lead to unexpected/undesired behavior, if the sensor - for whatever reson - // returns the same data for some time! for(int i = 0; i < UltraSoundReceiveData::numOfUSEcho; i++) { if(getUltraSoundReceiveData().dataLeft[i] != lastValidUltraSoundReceiveData.dataLeft[i] || getUltraSoundReceiveData().dataRight[i] != lastValidUltraSoundReceiveData.dataRight[i]) { return true; } } return false; } void UltraSoundObstacleLocator::fillBuffer() { if(!isNewDataAvaliable()) { return; } lastValidUltraSoundReceiveData = getUltraSoundReceiveData(); // http://doc.aldebaran.com/2-1/family/nao_dcm/actuator_sensor_names.html#actuator-sensor-list-nao // http://doc.aldebaran.com/2-8/family/nao_technical/lola/actuator_sensor_names.html#sonars // http://doc.aldebaran.com/1-14/family/robots/sonar_robot.html // convert to mm double leftMeasurement = getUltraSoundReceiveData().dataLeft[0] * 1000.0; double rightMeasurement = getUltraSoundReceiveData().dataRight[0] * 1000.0; // for v5 and v6 the 0.0 value should be treated as invalid // NOTE: Stella 2021/04/14 does not explain the full behavior yet if(leftMeasurement == 0.0){ leftMeasurement = invalidDistanceValue; } if (rightMeasurement == 0.0) { rightMeasurement = invalidDistanceValue; } bufferRight.add(rightMeasurement); bufferLeft.add(leftMeasurement); } void UltraSoundObstacleLocator::provideToLocalObstacleModel() { ObstacleModel& model = getObstacleModel(); if(bufferLeft.size() == 0) { model.leftDistance = invalidDistanceValue; } else { model.leftDistance = bufferLeft.getMedian(); } if(bufferRight.size() == 0) { model.rightDistance = invalidDistanceValue; } else { model.rightDistance = bufferRight.getMedian(); } if(model.leftDistance <= maxValidDistance || model.rightDistance <= maxValidDistance) { model.frontDistance = std::min(model.leftDistance, model.rightDistance); } if(model.frontDistance < params.minBlockedDistance) { if(!wasFrontBlockedInLastFrame) { timeWhenFrontBlockStarted = getFrameInfo(); } wasFrontBlockedInLastFrame = true; model.blockedTime = getFrameInfo().getTimeSince(timeWhenFrontBlockStarted.getTime()); } else { model.blockedTime = -1; wasFrontBlockedInLastFrame = false; } } //end provideToLocalObstacleModel <|endoftext|>
<commit_before><commit_msg>fix #2661 v2<commit_after><|endoftext|>
<commit_before>/*========================================================================= Program: Insight Segmentation & Registration Toolkit Module: itkMapRankImageFilterTest.cxx Language: C++ Date: $Date$ Version: $Revision$ Copyright (c) Insight Software Consortium. All rights reserved. See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the above copyright notices for more information. =========================================================================*/ #if defined(_MSC_VER) #pragma warning ( disable : 4786 ) #endif #include <fstream> #include "itkRankImageFilter.h" #include "itkImageFileReader.h" #include "itkImageFileWriter.h" #include "itkTextOutput.h" #include "itkNumericTraits.h" #include "itkFilterWatcher.h" int itkMapRankImageFilterTest(int ac, char* av[] ) { // Comment the following if you want to use the itk text output window itk::OutputWindow::SetInstance(itk::TextOutput::New()); if(ac < 4) { std::cerr << "Usage: " << av[0] << " InputImage BaselineImage radius" << std::endl; return -1; } typedef itk::Image<unsigned short, 2> ImageType; typedef itk::ImageFileReader<ImageType> ReaderType; ReaderType::Pointer input = ReaderType::New(); input->SetFileName(av[1]); // Create a filter typedef itk::FlatStructuringElement<2> SEType; typedef itk::RankImageFilter<ImageType,ImageType,SEType> FilterType; FilterType::Pointer filter = FilterType::New(); FilterWatcher filterWatch(filter); typedef FilterType::RadiusType RadiusType; // test default values RadiusType r1; r1.Fill( 1 ); if ( filter->GetRadius() != r1 ) { std::cerr << "Wrong default Radius." << std::endl; return EXIT_FAILURE; } if ( filter->GetRank() != 0.5 ) { std::cerr << "Wrong default Rank." << std::endl; return EXIT_FAILURE; } // set radius with a radius type RadiusType r5; r5.Fill( 5 ); filter->SetRadius( r5 ); if ( filter->GetRadius() != r5 ) { std::cerr << "Radius value is not the expected one:r5." << std::endl; return EXIT_FAILURE; } // set radius with an integer filter->SetRadius( 1 ); if ( filter->GetRadius() != r1 ) { std::cerr << "Radius value is not the expected one:r1." << std::endl; return EXIT_FAILURE; } filter->SetRank( 0.25 ); if ( filter->GetRank() != 0.25 ) { std::cerr << "Rank value is not the expected one: " << filter->GetRank() << std::endl; return EXIT_FAILURE; } try { int r = atoi( av[3] ); filter->SetInput(input->GetOutput()); filter->SetRadius( r ); filter->SetRank( 0.5 ); filter->Update(); } catch (itk::ExceptionObject& e) { std::cerr << "Exception detected: " << e.GetDescription(); return EXIT_FAILURE; } // Generate test image typedef itk::ImageFileWriter<ImageType> WriterType; WriterType::Pointer writer = WriterType::New(); writer->SetInput( filter->GetOutput() ); writer->SetFileName( av[2] ); writer->Update(); return EXIT_SUCCESS; } <commit_msg>STYLE: Fixing typedefs alignments.<commit_after>/*========================================================================= Program: Insight Segmentation & Registration Toolkit Module: itkMapRankImageFilterTest.cxx Language: C++ Date: $Date$ Version: $Revision$ Copyright (c) Insight Software Consortium. All rights reserved. See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the above copyright notices for more information. =========================================================================*/ #if defined(_MSC_VER) #pragma warning ( disable : 4786 ) #endif #include <fstream> #include "itkRankImageFilter.h" #include "itkImageFileReader.h" #include "itkImageFileWriter.h" #include "itkTextOutput.h" #include "itkNumericTraits.h" #include "itkFilterWatcher.h" int itkMapRankImageFilterTest(int ac, char* av[] ) { // Comment the following if you want to use the itk text output window itk::OutputWindow::SetInstance(itk::TextOutput::New()); if(ac < 4) { std::cerr << "Usage: " << av[0] << " InputImage BaselineImage radius" << std::endl; return -1; } typedef itk::Image<unsigned short, 2> ImageType; typedef itk::ImageFileReader<ImageType> ReaderType; ReaderType::Pointer input = ReaderType::New(); input->SetFileName(av[1]); // Create a filter typedef itk::FlatStructuringElement<2> SEType; typedef itk::RankImageFilter<ImageType,ImageType,SEType> FilterType; FilterType::Pointer filter = FilterType::New(); FilterWatcher filterWatch(filter); typedef FilterType::RadiusType RadiusType; // test default values RadiusType r1; r1.Fill( 1 ); if ( filter->GetRadius() != r1 ) { std::cerr << "Wrong default Radius." << std::endl; return EXIT_FAILURE; } if ( filter->GetRank() != 0.5 ) { std::cerr << "Wrong default Rank." << std::endl; return EXIT_FAILURE; } // set radius with a radius type RadiusType r5; r5.Fill( 5 ); filter->SetRadius( r5 ); if ( filter->GetRadius() != r5 ) { std::cerr << "Radius value is not the expected one:r5." << std::endl; return EXIT_FAILURE; } // set radius with an integer filter->SetRadius( 1 ); if ( filter->GetRadius() != r1 ) { std::cerr << "Radius value is not the expected one:r1." << std::endl; return EXIT_FAILURE; } filter->SetRank( 0.25 ); if ( filter->GetRank() != 0.25 ) { std::cerr << "Rank value is not the expected one: " << filter->GetRank() << std::endl; return EXIT_FAILURE; } try { int r = atoi( av[3] ); filter->SetInput(input->GetOutput()); filter->SetRadius( r ); filter->SetRank( 0.5 ); filter->Update(); } catch (itk::ExceptionObject& e) { std::cerr << "Exception detected: " << e.GetDescription(); return EXIT_FAILURE; } // Generate test image typedef itk::ImageFileWriter<ImageType> WriterType; WriterType::Pointer writer = WriterType::New(); writer->SetInput( filter->GetOutput() ); writer->SetFileName( av[2] ); writer->Update(); return EXIT_SUCCESS; } <|endoftext|>
<commit_before> #include <sys/types.h> #include <sys/stat.h> #include <stdio.h> #include <stdlib.h> #include <string.h> #include <unistd.h> #include <stdint.h> #include <errno.h> #include <fcntl.h> using namespace std; #include <string> typedef uint32_t linecount_t; bool is_file(const char * const path) { struct stat st; if (stat(path,&st)) return false; return S_ISREG(st.st_mode); } bool is_file(const string &path) { return is_file(path.c_str()); } class haxpp_linesource { private: linecount_t lineno = 0; string sourcepath; FILE* fp = NULL; char* line = NULL; size_t line_alloc = 0; public: static constexpr size_t line_alloc_minimum = 128u; static constexpr size_t line_alloc_default = 1200u; static constexpr size_t line_alloc_maximum = 65536u; public: inline size_t linesize() const; /* total buffer size including room for NUL terminator */ inline const string&getsourcename() const; haxpp_linesource(); haxpp_linesource(const string &path); ~haxpp_linesource(); bool lineresize(const size_t newsz); void close(); bool is_open() const; bool eof() const; bool error() const; bool open(); char *readline(); }; inline const string& haxpp_linesource::getsourcename() const { return sourcepath; } inline size_t haxpp_linesource::linesize() const { return line_alloc; } bool haxpp_linesource::lineresize(const size_t newsz) { if (line != NULL && line_alloc == newsz) return true; if (newsz < line_alloc_minimum || newsz > line_alloc_maximum) return false; if (line != NULL) { delete[] line; line = NULL; line_alloc = 0; } line = new char[newsz]; if (line == NULL) return false; line_alloc = newsz; return true; } haxpp_linesource::haxpp_linesource() { } haxpp_linesource::haxpp_linesource(const string &path) { sourcepath = path; } haxpp_linesource::~haxpp_linesource() { close(); } void haxpp_linesource::close() { if (fp != nullptr) { fclose(fp); fp = nullptr; } } bool haxpp_linesource::is_open() const { return (fp != NULL); } bool haxpp_linesource::eof() const { if (is_open()) return (feof(fp) != 0); return true; } bool haxpp_linesource::error() const { if (is_open()) return (ferror(fp) != 0); return true; } bool haxpp_linesource::open() { if (!is_open()) { if (line == NULL && !lineresize(line_alloc_default)) { errno = ENOMEM; return false; } if (sourcepath.empty() || line_alloc < line_alloc_minimum) { errno = EINVAL; return false; } if (!is_file(sourcepath)) { errno = EINVAL; return false; } fp = fopen(sourcepath.c_str(),"r"); if (fp == NULL) { /* fopen set errno */ return false; } lineno = 1; } return true; } char *haxpp_linesource::readline() { errno = 0; if (is_open()) { if (!ferror(fp) && !feof(fp)) { /* write a NUL to the last two bytes of the buffer. * if those bytes are no longer NUL it means fgets() read a line that's too long. * This is faster than using strlen() on the returned string. */ const size_t s = linesize(); /* must be >= 2 */ line[s-2] = line[s-1] = 0; /* fgets() will read up to s-1 bytes, and store a NUL where it stops (which is why we test line[s-2] instead). * the returned string will contain the entire line including the '\n' newline. */ if (fgets(line,s,fp) == NULL) return NULL; /* check for line too long */ if (line[s-2] != 0) { errno = E2BIG; return NULL; } return line; } } return NULL; } int main(int argc,char **argv) { for (int i=1;i < argc;i++) { haxpp_linesource ls(argv[i]); if (!ls.open()) { fprintf(stderr,"Unable to open %s, error %s\n",ls.getsourcename().c_str(),strerror(errno)); return 1; } while (!ls.eof()) { char *line = ls.readline(); if (line == NULL) { if (!ls.error() && ls.eof()) { break; } else { fprintf(stderr,"Problem reading. error=%u eof=%u errno=%s\n",ls.error(),ls.eof(),strerror(errno)); return 1; } } printf("%s",line); /* often provides it's own newline */ } if (ls.error()) { fprintf(stderr,"An error occurred while parsing %s\n",ls.getsourcename().c_str()); return 1; } } return 0; } <commit_msg>free line too<commit_after> #include <sys/types.h> #include <sys/stat.h> #include <stdio.h> #include <stdlib.h> #include <string.h> #include <unistd.h> #include <stdint.h> #include <errno.h> #include <fcntl.h> using namespace std; #include <string> typedef uint32_t linecount_t; bool is_file(const char * const path) { struct stat st; if (stat(path,&st)) return false; return S_ISREG(st.st_mode); } bool is_file(const string &path) { return is_file(path.c_str()); } class haxpp_linesource { private: linecount_t lineno = 0; string sourcepath; FILE* fp = NULL; char* line = NULL; size_t line_alloc = 0; public: static constexpr size_t line_alloc_minimum = 128u; static constexpr size_t line_alloc_default = 1200u; static constexpr size_t line_alloc_maximum = 65536u; public: inline size_t linesize() const; /* total buffer size including room for NUL terminator */ inline const string&getsourcename() const; haxpp_linesource(); haxpp_linesource(const string &path); ~haxpp_linesource(); bool lineresize(const size_t newsz); void linefree(); void close(); bool is_open() const; bool eof() const; bool error() const; bool open(); char *readline(); }; inline const string& haxpp_linesource::getsourcename() const { return sourcepath; } inline size_t haxpp_linesource::linesize() const { return line_alloc; } void haxpp_linesource::linefree() { if (line != NULL) { delete[] line; line = NULL; } line_alloc = 0; } bool haxpp_linesource::lineresize(const size_t newsz) { if (line != NULL && line_alloc == newsz) return true; if (newsz < line_alloc_minimum || newsz > line_alloc_maximum) return false; if (line != NULL) { delete[] line; line = NULL; line_alloc = 0; } line = new char[newsz]; if (line == NULL) return false; line_alloc = newsz; return true; } haxpp_linesource::haxpp_linesource() { } haxpp_linesource::haxpp_linesource(const string &path) { sourcepath = path; } haxpp_linesource::~haxpp_linesource() { linefree(); close(); } void haxpp_linesource::close() { if (fp != nullptr) { fclose(fp); fp = nullptr; } } bool haxpp_linesource::is_open() const { return (fp != NULL); } bool haxpp_linesource::eof() const { if (is_open()) return (feof(fp) != 0); return true; } bool haxpp_linesource::error() const { if (is_open()) return (ferror(fp) != 0); return true; } bool haxpp_linesource::open() { if (!is_open()) { if (line == NULL && !lineresize(line_alloc_default)) { errno = ENOMEM; return false; } if (sourcepath.empty() || line_alloc < line_alloc_minimum) { errno = EINVAL; return false; } if (!is_file(sourcepath)) { errno = EINVAL; return false; } fp = fopen(sourcepath.c_str(),"r"); if (fp == NULL) { /* fopen set errno */ return false; } lineno = 1; } return true; } char *haxpp_linesource::readline() { errno = 0; if (is_open()) { if (!ferror(fp) && !feof(fp)) { /* write a NUL to the last two bytes of the buffer. * if those bytes are no longer NUL it means fgets() read a line that's too long. * This is faster than using strlen() on the returned string. */ const size_t s = linesize(); /* must be >= 2 */ line[s-2] = line[s-1] = 0; /* fgets() will read up to s-1 bytes, and store a NUL where it stops (which is why we test line[s-2] instead). * the returned string will contain the entire line including the '\n' newline. */ if (fgets(line,s,fp) == NULL) return NULL; /* check for line too long */ if (line[s-2] != 0) { errno = E2BIG; return NULL; } return line; } } return NULL; } int main(int argc,char **argv) { for (int i=1;i < argc;i++) { haxpp_linesource ls(argv[i]); if (!ls.open()) { fprintf(stderr,"Unable to open %s, error %s\n",ls.getsourcename().c_str(),strerror(errno)); return 1; } while (!ls.eof()) { char *line = ls.readline(); if (line == NULL) { if (!ls.error() && ls.eof()) { break; } else { fprintf(stderr,"Problem reading. error=%u eof=%u errno=%s\n",ls.error(),ls.eof(),strerror(errno)); return 1; } } printf("%s",line); /* often provides it's own newline */ } if (ls.error()) { fprintf(stderr,"An error occurred while parsing %s\n",ls.getsourcename().c_str()); return 1; } } return 0; } <|endoftext|>
<commit_before>#include "RegularRectMerge.h" #include "PixelUncoveredLUT.h" #include "RegularRectCondense.h" namespace eimage { RegularRectMerge::RegularRectMerge(const std::vector<Rect>& rects, int width, int height, bool* ori_pixels) : m_width(width) , m_height(height) { m_uncovered_lut = new PixelUncoveredLUT(width, height); m_condense = new RegularRectCondense(rects, width, height, ori_pixels); } RegularRectMerge::~RegularRectMerge() { delete m_condense; delete m_uncovered_lut; } void RegularRectMerge::Merge() { static const int COUNT_MIN = 6; static const int AREA_MIN = 16 * 16; static const int ENLARGE_MAX = 16 * 16 * 2; int debug_count = 0; m_condense->Condense(Rect(0, 0, m_width, m_height)); while (true) { std::vector<Rect> rects; m_condense->GetSortedRects(rects); if (rects.size() <= 1) { break; } assert(rects[0].w > 0 && rects[0].h > 0); //if (rects[0].w * rects[0].h > AREA_MIN && rects.size() < COUNT_MIN) { // break; //} m_uncovered_lut->LoadRects(rects); int cost_min = INT_MAX; int r0_min = -1, r1_min = -1; //int r_min = -1; // for (int i = 1, n = rects.size(); i < n; ++i) { // const Rect& r1 = rects[i]; // // int left = std::min(r0.x, r1.x), // right = std::max(r0.x + r0.w, r1.x + r1.w); // int down = std::min(r0.y, r1.y), // up = std::max(r0.y + r0.h, r1.y + r1.h); // Rect mr(left, down, right - left, up - down); // // int cost = ComputeCost(mr, rects); // if (cost == 0) { // cost_min = 0; // r_min = i; // break; // } else if (cost < cost_min) { // cost_min = cost; // r_min = i; // } // } if (debug_count == 15) { int zz = 0; } for (int i = 0, n = rects.size(); i < n - 1 && cost_min > 0; ++i) { const Rect& r0 = rects[i]; for (int j = i + 1; j < n && cost_min > 0; ++j) { const Rect& r1 = rects[j]; int left = std::min(r0.x, r1.x), right = std::max(r0.x + r0.w, r1.x + r1.w); int down = std::min(r0.y, r1.y), up = std::max(r0.y + r0.h, r1.y + r1.h); Rect mr(left, down, right - left, up - down); if (mr.x == 40 && mr.y == 11) { int zz = 0; } int cost = ComputeCost(mr, rects); if (cost == 0) { cost_min = 0; r0_min = i; r1_min = j; break; } else if (cost < cost_min) { cost_min = cost; r0_min = i; r1_min = j; } } } if (cost_min > ENLARGE_MAX) { break; } assert(r0_min != -1 && r1_min != -1); const Rect& r0 = rects[r0_min]; const Rect& r1 = rects[r1_min]; int left = std::min(r0.x, r1.x), right = std::max(r0.x + r0.w, r1.x + r1.w); int down = std::min(r0.y, r1.y), up = std::max(r0.y + r0.h, r1.y + r1.h); Rect mr(left, down, right - left, up - down); // if (debug_count == 1) { // break; // } m_condense->Remove(r0); m_condense->Remove(r1); m_condense->Insert(mr); m_condense->Condense(mr); ++debug_count; // if (debug_count == 3) { // break; // } } } void RegularRectMerge::GetResult(std::vector<Rect>& result) const { m_condense->GetSortedRects(result); } int RegularRectMerge::ComputeCost(const Rect& r, const std::vector<Rect>& rects) const { int cost = 0; for (int i = 0, n = rects.size(); i < n; ++i) { const Rect& b = rects[i]; if (r.x > b.x && (r.x + r.w < b.x + b.w) && r.y < b.y && (r.y + r.h > b.y + b.h)) { return INT_MAX; } if (b.x > r.x && (b.x + b.w < r.x + r.w) && b.y < r.y && (b.y + b.h > r.y + r.h)) { return INT_MAX; } if (r.x > b.x && (r.x < b.x + b.w) && r.y > b.y && (r.y < b.y + b.h) && (r.x + r.w > b.x + b.w) && (r.y + r.h > b.y + b.h)) { cost += (b.x + b.w - r.x) * (b.y + b.h - r.y); } if (r.x > b.x && (r.x < b.x + b.w) && (r.y + r.h > b.y) && (r.y + r.h < b.y + b.h) && (r.x + r.w > b.x + b.w) && (r.y < b.y)) { cost += (b.x + b.w - r.x) * (r.y + r.h - 1 - b.y); } if ((r.x + r.w > b.x) && (r.x + r.w < b.x + b.w) && (r.y + r.h > b.y) && (r.y + r.h < b.y + b.h) && r.x < b.x && r.y < b.y) { cost += (r.x + r.w - 1 - b.x) * (r.y + r.h - 1 - b.y); } if ((r.x + r.w > b.x) && (r.x + r.w < b.x + b.w) && (r.y > b.y) && (r.y < b.y + b.h) && r.x < b.x && (r.y + r.h > b.y + b.h)) { cost += (r.x + r.w - 1 - b.x) * (b.y + b.h - r.y); } } cost += m_uncovered_lut->GetUncoveredArea(r.x, r.y, r.w, r.h); return cost; } }<commit_msg>[FIXED] rect cut merge的参数<commit_after>#include "RegularRectMerge.h" #include "PixelUncoveredLUT.h" #include "RegularRectCondense.h" namespace eimage { RegularRectMerge::RegularRectMerge(const std::vector<Rect>& rects, int width, int height, bool* ori_pixels) : m_width(width) , m_height(height) { m_uncovered_lut = new PixelUncoveredLUT(width, height); m_condense = new RegularRectCondense(rects, width, height, ori_pixels); } RegularRectMerge::~RegularRectMerge() { delete m_condense; delete m_uncovered_lut; } void RegularRectMerge::Merge() { static const int COUNT_MIN = 6; static const int AREA_MIN = 16 * 16; const int ENLARGE_MAX = (int)std::max(16 * 16 * 2.0f, m_width * 0.1f * m_height * 0.1f); int debug_count = 0; m_condense->Condense(Rect(0, 0, m_width, m_height)); while (true) { std::vector<Rect> rects; m_condense->GetSortedRects(rects); if (rects.size() <= 1) { break; } assert(rects[0].w > 0 && rects[0].h > 0); //if (rects[0].w * rects[0].h > AREA_MIN && rects.size() < COUNT_MIN) { // break; //} m_uncovered_lut->LoadRects(rects); int cost_min = INT_MAX; int r0_min = -1, r1_min = -1; //int r_min = -1; // for (int i = 1, n = rects.size(); i < n; ++i) { // const Rect& r1 = rects[i]; // // int left = std::min(r0.x, r1.x), // right = std::max(r0.x + r0.w, r1.x + r1.w); // int down = std::min(r0.y, r1.y), // up = std::max(r0.y + r0.h, r1.y + r1.h); // Rect mr(left, down, right - left, up - down); // // int cost = ComputeCost(mr, rects); // if (cost == 0) { // cost_min = 0; // r_min = i; // break; // } else if (cost < cost_min) { // cost_min = cost; // r_min = i; // } // } if (debug_count == 15) { int zz = 0; } for (int i = 0, n = rects.size(); i < n - 1 && cost_min > 0; ++i) { const Rect& r0 = rects[i]; for (int j = i + 1; j < n && cost_min > 0; ++j) { const Rect& r1 = rects[j]; int left = std::min(r0.x, r1.x), right = std::max(r0.x + r0.w, r1.x + r1.w); int down = std::min(r0.y, r1.y), up = std::max(r0.y + r0.h, r1.y + r1.h); Rect mr(left, down, right - left, up - down); if (mr.x == 40 && mr.y == 11) { int zz = 0; } int cost = ComputeCost(mr, rects); if (cost == 0) { cost_min = 0; r0_min = i; r1_min = j; break; } else if (cost < cost_min) { cost_min = cost; r0_min = i; r1_min = j; } } } if (cost_min > ENLARGE_MAX) { break; } assert(r0_min != -1 && r1_min != -1); const Rect& r0 = rects[r0_min]; const Rect& r1 = rects[r1_min]; int left = std::min(r0.x, r1.x), right = std::max(r0.x + r0.w, r1.x + r1.w); int down = std::min(r0.y, r1.y), up = std::max(r0.y + r0.h, r1.y + r1.h); Rect mr(left, down, right - left, up - down); // if (debug_count == 1) { // break; // } m_condense->Remove(r0); m_condense->Remove(r1); m_condense->Insert(mr); m_condense->Condense(mr); ++debug_count; // if (debug_count == 3) { // break; // } } } void RegularRectMerge::GetResult(std::vector<Rect>& result) const { m_condense->GetSortedRects(result); } int RegularRectMerge::ComputeCost(const Rect& r, const std::vector<Rect>& rects) const { int cost = 0; for (int i = 0, n = rects.size(); i < n; ++i) { const Rect& b = rects[i]; if (r.x > b.x && (r.x + r.w < b.x + b.w) && r.y < b.y && (r.y + r.h > b.y + b.h)) { return INT_MAX; } if (b.x > r.x && (b.x + b.w < r.x + r.w) && b.y < r.y && (b.y + b.h > r.y + r.h)) { return INT_MAX; } if (r.x > b.x && (r.x < b.x + b.w) && r.y > b.y && (r.y < b.y + b.h) && (r.x + r.w > b.x + b.w) && (r.y + r.h > b.y + b.h)) { cost += (b.x + b.w - r.x) * (b.y + b.h - r.y); } if (r.x > b.x && (r.x < b.x + b.w) && (r.y + r.h > b.y) && (r.y + r.h < b.y + b.h) && (r.x + r.w > b.x + b.w) && (r.y < b.y)) { cost += (b.x + b.w - r.x) * (r.y + r.h - 1 - b.y); } if ((r.x + r.w > b.x) && (r.x + r.w < b.x + b.w) && (r.y + r.h > b.y) && (r.y + r.h < b.y + b.h) && r.x < b.x && r.y < b.y) { cost += (r.x + r.w - 1 - b.x) * (r.y + r.h - 1 - b.y); } if ((r.x + r.w > b.x) && (r.x + r.w < b.x + b.w) && (r.y > b.y) && (r.y < b.y + b.h) && r.x < b.x && (r.y + r.h > b.y + b.h)) { cost += (r.x + r.w - 1 - b.x) * (b.y + b.h - r.y); } } cost += m_uncovered_lut->GetUncoveredArea(r.x, r.y, r.w, r.h); return cost; } }<|endoftext|>
<commit_before>/************************************************************************* * * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * Copyright 2008 by Sun Microsystems, Inc. * * OpenOffice.org - a multi-platform office productivity suite * * $RCSfile: typeconverter.hxx,v $ * $Revision: 1.9 $ * * This file is part of OpenOffice.org. * * OpenOffice.org is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License version 3 * only, as published by the Free Software Foundation. * * OpenOffice.org 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 version 3 for more details * (a copy is included in the LICENSE file that accompanied this code). * * You should have received a copy of the GNU Lesser General Public License * version 3 along with OpenOffice.org. If not, see * <http://www.openoffice.org/license.html> * for a copy of the LGPLv3 License. * ************************************************************************/ #ifndef CONFIGMGR_TYPECONVERTER_HXX #define CONFIGMGR_TYPECONVERTER_HXX #include "utility.hxx" #include <com/sun/star/script/XTypeConverter.hpp> #include <rtl/ustring.hxx> #include <com/sun/star/uno/Sequence.hxx> namespace configmgr { namespace uno = ::com::sun::star::uno; namespace script = ::com::sun::star::script; // UNO Type handling uno::Type getSequenceElementType(uno::Type const& rSequenceType); uno::Type getBasicType(uno::Type const& rType, bool& bSequence); inline uno::Type getBasicType(uno::Type const& rType) { bool dummy; return getBasicType(rType,dummy); } // Any Conversion - uses TypeConverter uno::Any toAny( const uno::Reference< script::XTypeConverter >& xTypeConverter, const ::rtl::OUString& _rValue, const uno::TypeClass& _rTypeClass) CFG_UNO_THROW1( script::CannotConvertException ); rtl::OUString toString(const uno::Reference< script::XTypeConverter >& xTypeConverter, const uno::Any& rValue) CFG_UNO_THROW1( script::CannotConvertException ); // Type conversion uno::TypeClass toTypeClass(const ::rtl::OUString& _rType); ::rtl::OUString toTypeName(const uno::TypeClass& _rTypeClass); uno::Type toType(const ::rtl::OUString& _rsType); uno::Type toListType(const ::rtl::OUString& _rsElementType); ::rtl::OUString toTypeName(const uno::Type& _rType); inline uno::Type toType(const ::rtl::OUString& _rsSimpleType, bool isList) { return isList ? toListType(_rsSimpleType) : toType(_rsSimpleType); } // template names ::rtl::OUString toTemplateName(const uno::Type& _rType); ::rtl::OUString toTemplateName(const uno::TypeClass& _rBasicType, bool bList = false); ::rtl::OUString toTemplateName(const ::rtl::OUString& _rBasicTypeName, bool bList = false); uno::Type parseTemplateName(::rtl::OUString const& sTypeName); bool parseTemplateName(::rtl::OUString const& sTypeName, uno::TypeClass& _rType, bool& bList); bool parseTemplateName(::rtl::OUString const& sTypeName, ::rtl::OUString& _rBasicName, bool& bList); } // namespace configmgr #endif /* CONFIGMGR_TYPECONVERTER_HXX */ <commit_msg>INTEGRATION: CWS sb88 (1.9.10); FILE MERGED 2008/06/03 15:29:49 sb 1.9.10.1: #i89553 applied patch by cmc<commit_after>/************************************************************************* * * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * Copyright 2008 by Sun Microsystems, Inc. * * OpenOffice.org - a multi-platform office productivity suite * * $RCSfile: typeconverter.hxx,v $ * $Revision: 1.10 $ * * This file is part of OpenOffice.org. * * OpenOffice.org is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License version 3 * only, as published by the Free Software Foundation. * * OpenOffice.org 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 version 3 for more details * (a copy is included in the LICENSE file that accompanied this code). * * You should have received a copy of the GNU Lesser General Public License * version 3 along with OpenOffice.org. If not, see * <http://www.openoffice.org/license.html> * for a copy of the LGPLv3 License. * ************************************************************************/ #ifndef CONFIGMGR_TYPECONVERTER_HXX #define CONFIGMGR_TYPECONVERTER_HXX #include "utility.hxx" #include <com/sun/star/script/XTypeConverter.hpp> #include <rtl/ustring.hxx> #include <com/sun/star/uno/Sequence.hxx> namespace configmgr { namespace uno = ::com::sun::star::uno; namespace script = ::com::sun::star::script; // UNO Type handling uno::Type getSequenceElementType(uno::Type const& rSequenceType); uno::Type getBasicType(uno::Type const& rType, bool& bSequence); inline uno::Type getBasicType(uno::Type const& rType) { bool dummy; return getBasicType(rType,dummy); } // Any Conversion - uses TypeConverter uno::Any toAny( const uno::Reference< script::XTypeConverter >& xTypeConverter, const ::rtl::OUString& _rValue, const uno::TypeClass& _rTypeClass) CFG_UNO_THROW1( script::CannotConvertException ); rtl::OUString toString(const uno::Reference< script::XTypeConverter >& xTypeConverter, const uno::Any& rValue) CFG_UNO_THROW1( script::CannotConvertException ); // Type conversion ::rtl::OUString toTypeName(const uno::TypeClass& _rTypeClass); uno::Type toType(const ::rtl::OUString& _rsType); uno::Type toListType(const ::rtl::OUString& _rsElementType); ::rtl::OUString toTypeName(const uno::Type& _rType); inline uno::Type toType(const ::rtl::OUString& _rsSimpleType, bool isList) { return isList ? toListType(_rsSimpleType) : toType(_rsSimpleType); } // template names ::rtl::OUString toTemplateName(const uno::Type& _rType); ::rtl::OUString toTemplateName(const uno::TypeClass& _rBasicType, bool bList = false); ::rtl::OUString toTemplateName(const ::rtl::OUString& _rBasicTypeName, bool bList = false); uno::Type parseTemplateName(::rtl::OUString const& sTypeName); bool parseTemplateName(::rtl::OUString const& sTypeName, ::rtl::OUString& _rBasicName, bool& bList); } // namespace configmgr #endif /* CONFIGMGR_TYPECONVERTER_HXX */ <|endoftext|>
<commit_before>#include "Halide.h" #include <stdio.h> using namespace Halide; #include "halide_image_io.h" using namespace Halide::Tools; #include "clock.h" Func rgb_to_grey(Image<uint8_t> input) { Var x("x"), y("y"), c("c"), d("d"); Func clamped("clamped"); clamped = BoundaryConditions::repeat_edge(input); Func greyImg("greyImg"); greyImg(x,y,d) = clamped(x,y,0) * 0.3f + clamped(x,y,1) * 0.59f + clamped(x,y,2) * 0.11f; return greyImg; } void imwrite(std::string fname, int width, int height, Func continuation) { Image<uint8_t> result(width, height, 1); double t1 = current_time(); continuation.realize(result); double t2 = current_time(); std::cout << ((t2 - t1) / 1000.0) << "\n"; save_image(result, fname); } Func blurX(Func continuation) { Var x("x"), y("y"), c("c"); Func input_16("input_16"); // input_16(x, y, c) = cast<uint16_t>(continuation(x, y, c)); Func blur_x("blur_x"); blur_x(x, y, c) = (continuation(x-1, y, c) + 2 * continuation(x, y, c) + continuation(x+1, y, c)) / 4; blur_x.vectorize(x, 8).parallel(y); blur_x.compute_root(); // Func output("outputBlurX"); // output(x, y, c) = cast<uint8_t>(blur_x(x, y, c)); return blur_x; } Func blurY(Func continuation) { Var x("x"), y("y"), c("c"); Func input_16("input_16"); //input_16(x, y, c) = cast<uint16_t>(continuation(x, y, c)); Func blur_y("blur_y"); blur_y(x, y, c) = (continuation(x, y-1, c) + 2 * continuation(x, y, c) + continuation(x, y+1, c)) / 4; blur_y.vectorize(y, 8).parallel(x); blur_y.compute_root(); Func output("outputBlurY"); // output(x, y, c) = cast<uint8_t>(blur_y(x, y, c)); return blur_y; } Func brightenBy(int brightenByVal, Func continuation) { Func brighten("brighten"); Var x, y, c; Expr value = continuation(x, y, c); value = Halide::cast<float>(value); value = value + brightenByVal; value = Halide::min(value, 255.0f); value = Halide::cast<uint8_t>(value); brighten(x, y, c) = value; brighten.vectorize(x, 8).parallel(y); brighten.compute_root(); return brighten; } Func darkenBy(int darkenByVal, Func continuation) { Func darken("darken"); Var x, y, c; Expr value = continuation(x, y, c); value = Halide::cast<float>(value); value = value - darkenByVal; value = Halide::cast<uint8_t>(value); darken(x, y, c) = value; darken.vectorize(x, 8).parallel(y); darken.compute_root(); return darken; } <commit_msg>(Halide) Use machine specific vector widths<commit_after>#include "Halide.h" #include <stdio.h> using namespace Halide; #include "halide_image_io.h" using namespace Halide::Tools; #include "clock.h" Func rgb_to_grey(Image<uint8_t> input) { Var x("x"), y("y"), c("c"), d("d"); Func clamped("clamped"); clamped = BoundaryConditions::repeat_edge(input); Func greyImg("greyImg"); greyImg(x,y,d) = clamped(x,y,0) * 0.3f + clamped(x,y,1) * 0.59f + clamped(x,y,2) * 0.11f; return greyImg; } void imwrite(std::string fname, int width, int height, Func continuation) { Image<uint8_t> result(width, height, 1); double t1 = current_time(); continuation.realize(result); double t2 = current_time(); std::cout << ((t2 - t1) / 1000.0) << "\n"; save_image(result, fname); } Func blurX(Func continuation) { Var x("x"), y("y"), c("c"); Func input_16("input_16"); // input_16(x, y, c) = cast<uint16_t>(continuation(x, y, c)); Func blur_x("blur_x"); blur_x(x, y, c) = (continuation(x-1, y, c) + 2 * continuation(x, y, c) + continuation(x+1, y, c)) / 4; blur_x.vectorize(x, get_target_from_environment().natural_vector_size<uint16_t>()).parallel(y); blur_x.compute_root(); // Func output("outputBlurX"); // output(x, y, c) = cast<uint8_t>(blur_x(x, y, c)); return blur_x; } Func blurY(Func continuation) { Var x("x"), y("y"), c("c"); Func input_16("input_16"); //input_16(x, y, c) = cast<uint16_t>(continuation(x, y, c)); Func blur_y("blur_y"); blur_y(x, y, c) = (continuation(x, y-1, c) + 2 * continuation(x, y, c) + continuation(x, y+1, c)) / 4; blur_y.vectorize(y, get_target_from_environment().natural_vector_size<uint16_t>()).parallel(x); blur_y.compute_root(); Func output("outputBlurY"); // output(x, y, c) = cast<uint8_t>(blur_y(x, y, c)); return blur_y; } Func brightenBy(int brightenByVal, Func continuation) { Func brighten("brighten"); Var x, y, c; Expr value = continuation(x, y, c); value = Halide::cast<float>(value); value = value + brightenByVal; value = Halide::min(value, 255.0f); value = Halide::cast<uint8_t>(value); brighten(x, y, c) = value; brighten.vectorize(x, get_target_from_environment().natural_vector_size<uint16_t>()).parallel(y); brighten.compute_root(); return brighten; } Func darkenBy(int darkenByVal, Func continuation) { Func darken("darken"); Var x, y, c; Expr value = continuation(x, y, c); value = Halide::cast<float>(value); value = value - darkenByVal; value = Halide::cast<uint8_t>(value); darken(x, y, c) = value; darken.vectorize(x, get_target_from_environment().natural_vector_size<uint16_t>()).parallel(y); darken.compute_root(); return darken; } <|endoftext|>
<commit_before>// Copyright (C) 2018 Elviss Strazdins // This file is part of the Ouzel engine. #include <cstdlib> #include <unistd.h> #include <pthread.h> #include <GL/gl.h> #include <GL/glext.h> #include <X11/XKBlib.h> #include <X11/extensions/scrnsaver.h> #include "EngineLinux.hpp" #include "WindowResourceLinux.hpp" #include "events/Event.hpp" #include "graphics/RenderDevice.hpp" #include "input/Input.hpp" #include "input/linux/InputLinux.hpp" #include "thread/Lock.hpp" #include "utils/Log.hpp" namespace ouzel { EngineLinux::EngineLinux(int initArgc, char* initArgv[]): argc(initArgc), argv(initArgv) { for (int i = 0; i < initArgc; ++i) { args.push_back(initArgv[i]); } } int EngineLinux::run() { if (!XInitThreads()) { Log(Log::Level::ERR) << "Failed to initialize thread support"; return false; } if (!init()) { return EXIT_FAILURE; } start(); /*for (;;) { executeAll(); }*/ XEvent event; WindowResourceLinux* windowLinux = static_cast<WindowResourceLinux*>(window.getResource()); input::InputLinux* inputLinux = static_cast<input::InputLinux*>(input.get()); while (active) { XNextEvent(windowLinux->getDisplay(), &event); switch (event.type) { case ClientMessage: { if (event.xclient.message_type == windowLinux->getProtocolsAtom() && static_cast<Atom>(event.xclient.data.l[0]) == windowLinux->getDeleteAtom()) { exit(); } else if (event.xclient.message_type == windowLinux->getExecuteAtom()) { executeAll(); } break; } case FocusIn: resume(); break; case FocusOut: pause(); break; case KeyPress: // keyboard case KeyRelease: { KeySym keySym = XkbKeycodeToKeysym(windowLinux->getDisplay(), event.xkey.keycode, 0, event.xkey.state & ShiftMask ? 1 : 0); if (event.type == KeyPress) { input->keyPress(input::InputLinux::convertKeyCode(keySym), input::InputLinux::getModifiers(event.xkey.state)); } else { input->keyRelease(input::InputLinux::convertKeyCode(keySym), input::InputLinux::getModifiers(event.xkey.state)); } break; } case ButtonPress: // mouse button case ButtonRelease: { Vector2 pos(static_cast<float>(event.xbutton.x), static_cast<float>(event.xbutton.y)); input::MouseButton button; switch (event.xbutton.button) { case 1: button = input::MouseButton::LEFT; break; case 2: button = input::MouseButton::RIGHT; break; case 3: button = input::MouseButton::MIDDLE; break; default: button = input::MouseButton::NONE; break; } if (event.type == ButtonPress) { input->mouseButtonPress(button, window.convertWindowToNormalizedLocation(pos), input::InputLinux::getModifiers(event.xbutton.state)); } else { input->mouseButtonRelease(button, window.convertWindowToNormalizedLocation(pos), input::InputLinux::getModifiers(event.xbutton.state)); } break; } case MotionNotify: { Vector2 pos(static_cast<float>(event.xmotion.x), static_cast<float>(event.xmotion.y)); input->mouseMove(window.convertWindowToNormalizedLocation(pos), input::InputLinux::getModifiers(event.xmotion.state)); break; } case ConfigureNotify: { windowLinux->handleResize(Size2(static_cast<float>(event.xconfigure.width), static_cast<float>(event.xconfigure.height))); break; } case Expose: { // need to redraw break; } case GenericEvent: { XGenericEventCookie* cookie = &event.xcookie; inputLinux->handleXInput2Event(cookie); break; } } } exit(); return EXIT_SUCCESS; } void EngineLinux::executeOnMainThread(const std::function<void(void)>& func) { WindowResourceLinux* windowLinux = static_cast<WindowResourceLinux*>(window.getResource()); XEvent event; event.type = ClientMessage; event.xclient.window = windowLinux->getNativeWindow(); event.xclient.message_type = windowLinux->getExecuteAtom(); event.xclient.format = 32; // data is set as 32-bit integers event.xclient.data.l[0] = 0; event.xclient.data.l[1] = CurrentTime; event.xclient.data.l[2] = 0; // unused event.xclient.data.l[3] = 0; // unused event.xclient.data.l[4] = 0; // unused Lock lock(executeMutex); executeQueue.push(func); if (!XSendEvent(windowLinux->getDisplay(), windowLinux->getNativeWindow(), False, NoEventMask, &event)) { Log(Log::Level::ERR) << "Failed to send X11 delete message"; } XFlush(windowLinux->getDisplay()); } bool EngineLinux::openURL(const std::string& url) { ::exit(execl("/usr/bin/xdg-open", "xdg-open", url.c_str(), nullptr)); return true; } void EngineLinux::setScreenSaverEnabled(bool newScreenSaverEnabled) { Engine::setScreenSaverEnabled(newScreenSaverEnabled); executeOnMainThread([this, newScreenSaverEnabled]() { WindowResourceLinux* windowLinux = static_cast<WindowResourceLinux*>(window.getResource()); XScreenSaverSuspend(windowLinux->getDisplay(), !newScreenSaverEnabled); }); } void EngineLinux::executeAll() { std::function<void(void)> func; for (;;) { { Lock lock(executeMutex); if (executeQueue.empty()) { break; } func = std::move(executeQueue.front()); executeQueue.pop(); } if (func) { func(); } } } } <commit_msg>Reverse the event check on Linux<commit_after>// Copyright (C) 2018 Elviss Strazdins // This file is part of the Ouzel engine. #include <cstdlib> #include <unistd.h> #include <pthread.h> #include <GL/gl.h> #include <GL/glext.h> #include <X11/XKBlib.h> #include <X11/extensions/scrnsaver.h> #include "EngineLinux.hpp" #include "WindowResourceLinux.hpp" #include "events/Event.hpp" #include "graphics/RenderDevice.hpp" #include "input/Input.hpp" #include "input/linux/InputLinux.hpp" #include "thread/Lock.hpp" #include "utils/Log.hpp" namespace ouzel { EngineLinux::EngineLinux(int initArgc, char* initArgv[]): argc(initArgc), argv(initArgv) { for (int i = 0; i < initArgc; ++i) { args.push_back(initArgv[i]); } } int EngineLinux::run() { if (!XInitThreads()) { Log(Log::Level::ERR) << "Failed to initialize thread support"; return false; } if (!init()) { return EXIT_FAILURE; } start(); /*for (;;) { executeAll(); }*/ XEvent event; WindowResourceLinux* windowLinux = static_cast<WindowResourceLinux*>(window.getResource()); input::InputLinux* inputLinux = static_cast<input::InputLinux*>(input.get()); while (active) { // XNextEvent will block if there is no event pending, so don't call it if engine is not paused if (paused || XPending(windowLinux->getDisplay())) { XNextEvent(windowLinux->getDisplay(), &event); switch (event.type) { case ClientMessage: { if (event.xclient.message_type == windowLinux->getProtocolsAtom() && static_cast<Atom>(event.xclient.data.l[0]) == windowLinux->getDeleteAtom()) { exit(); } else if (event.xclient.message_type == windowLinux->getExecuteAtom()) { executeAll(); } break; } case FocusIn: resume(); break; case FocusOut: pause(); break; case KeyPress: // keyboard case KeyRelease: { KeySym keySym = XkbKeycodeToKeysym(windowLinux->getDisplay(), event.xkey.keycode, 0, event.xkey.state & ShiftMask ? 1 : 0); if (event.type == KeyPress) { input->keyPress(input::InputLinux::convertKeyCode(keySym), input::InputLinux::getModifiers(event.xkey.state)); } else { input->keyRelease(input::InputLinux::convertKeyCode(keySym), input::InputLinux::getModifiers(event.xkey.state)); } break; } case ButtonPress: // mouse button case ButtonRelease: { Vector2 pos(static_cast<float>(event.xbutton.x), static_cast<float>(event.xbutton.y)); input::MouseButton button; switch (event.xbutton.button) { case 1: button = input::MouseButton::LEFT; break; case 2: button = input::MouseButton::RIGHT; break; case 3: button = input::MouseButton::MIDDLE; break; default: button = input::MouseButton::NONE; break; } if (event.type == ButtonPress) { input->mouseButtonPress(button, window.convertWindowToNormalizedLocation(pos), input::InputLinux::getModifiers(event.xbutton.state)); } else { input->mouseButtonRelease(button, window.convertWindowToNormalizedLocation(pos), input::InputLinux::getModifiers(event.xbutton.state)); } break; } case MotionNotify: { Vector2 pos(static_cast<float>(event.xmotion.x), static_cast<float>(event.xmotion.y)); input->mouseMove(window.convertWindowToNormalizedLocation(pos), input::InputLinux::getModifiers(event.xmotion.state)); break; } case ConfigureNotify: { windowLinux->handleResize(Size2(static_cast<float>(event.xconfigure.width), static_cast<float>(event.xconfigure.height))); break; } case Expose: { // need to redraw break; } case GenericEvent: { XGenericEventCookie* cookie = &event.xcookie; inputLinux->handleXInput2Event(cookie); break; } } } } exit(); return EXIT_SUCCESS; } void EngineLinux::executeOnMainThread(const std::function<void(void)>& func) { WindowResourceLinux* windowLinux = static_cast<WindowResourceLinux*>(window.getResource()); XEvent event; event.type = ClientMessage; event.xclient.window = windowLinux->getNativeWindow(); event.xclient.message_type = windowLinux->getExecuteAtom(); event.xclient.format = 32; // data is set as 32-bit integers event.xclient.data.l[0] = 0; event.xclient.data.l[1] = CurrentTime; event.xclient.data.l[2] = 0; // unused event.xclient.data.l[3] = 0; // unused event.xclient.data.l[4] = 0; // unused Lock lock(executeMutex); executeQueue.push(func); if (!XSendEvent(windowLinux->getDisplay(), windowLinux->getNativeWindow(), False, NoEventMask, &event)) { Log(Log::Level::ERR) << "Failed to send X11 delete message"; } XFlush(windowLinux->getDisplay()); } bool EngineLinux::openURL(const std::string& url) { ::exit(execl("/usr/bin/xdg-open", "xdg-open", url.c_str(), nullptr)); return true; } void EngineLinux::setScreenSaverEnabled(bool newScreenSaverEnabled) { Engine::setScreenSaverEnabled(newScreenSaverEnabled); executeOnMainThread([this, newScreenSaverEnabled]() { WindowResourceLinux* windowLinux = static_cast<WindowResourceLinux*>(window.getResource()); XScreenSaverSuspend(windowLinux->getDisplay(), !newScreenSaverEnabled); }); } void EngineLinux::executeAll() { std::function<void(void)> func; for (;;) { { Lock lock(executeMutex); if (executeQueue.empty()) { break; } func = std::move(executeQueue.front()); executeQueue.pop(); } if (func) { func(); } } } } <|endoftext|>
<commit_before>/* * Copyright (C) 2015 Luke San Antonio * All rights reserved. */ #include <fstream> #include <sstream> #include <cstdlib> #include <vector> #include <thread> #include "common/log.h" #include "gfx/gl/driver.h" #include "gfx/camera.h" #include "gfx/object.h" #include "gfx/scene_node.h" #include "gfx/idriver_ui_adapter.h" #include "common/software_texture.h" #include "common/texture_load.h" #include "common/software_mesh.h" #include "common/mesh_load.h" #include "common/mesh_write.h" #include "ui/load.h" #include "ui/freetype_renderer.h" #include "ui/mouse_logic.h" #include "ui/simple_controller.h" #include "map/map.h" #include "map/json_structure.h" #include "glad/glad.h" #include "glfw3.h" #define GLM_FORCE_RADIANS #include "glm/glm.hpp" #include "glm/gtc/matrix_transform.hpp" #include "uv.h" #define CATCH_CONFIG_RUNNER #include "catch/catch.hpp" glm::vec4 project_point(glm::vec4 pt, glm::mat4 const& model, glm::mat4 const& view, glm::mat4 const& proj) noexcept { pt = proj * view * model * pt; pt /= pt.w; return pt; } void scroll_callback(GLFWwindow* window, double, double deltay) { auto cam_ptr = glfwGetWindowUserPointer(window); auto& camera = *((game::gfx::Camera*) cam_ptr); camera.fp.pos += -deltay; } game::ui::Mouse_State gen_mouse_state(GLFWwindow* w) { game::ui::Mouse_State ret; ret.button_down =glfwGetMouseButton(w, GLFW_MOUSE_BUTTON_LEFT) == GLFW_PRESS; game::Vec<double> pos; glfwGetCursorPos(w, &pos.x, &pos.y); ret.position = game::vec_cast<int>(pos); return ret; } void log_gl_limits(game::Log_Severity s) noexcept { GLint i = 0; glGetIntegerv(GL_MAX_ELEMENTS_VERTICES, &i); log(s, "GL_MAX_ELEMENTS_VERTICES: %", i); } struct Command_Options { }; Command_Options parse_command_line(int argc, char**) { Command_Options opt; for(int i = 0; i < argc; ++i) { //auto option = argv[i]; } return opt; } int main(int argc, char** argv) { using namespace game; set_log_level(Log_Severity::Debug); uv_chdir("assets/"); // Initialize logger. Scoped_Log_Init log_init_raii_lock{}; // Parse command line arguments. auto options = parse_command_line(argc - 1, argv+1); // Init glfw. if(!glfwInit()) return EXIT_FAILURE; auto window = glfwCreateWindow(1000, 1000, "Hello World", NULL, NULL); if(!window) { glfwTerminate(); return EXIT_FAILURE; } // Init context + load gl functions. glfwMakeContextCurrent(window); gladLoadGLLoader((GLADloadproc) glfwGetProcAddress); // Log glfw version. log_i("Initialized GLFW %", glfwGetVersionString()); int maj = glfwGetWindowAttrib(window, GLFW_CONTEXT_VERSION_MAJOR); int min = glfwGetWindowAttrib(window, GLFW_CONTEXT_VERSION_MINOR); int rev = glfwGetWindowAttrib(window, GLFW_CONTEXT_REVISION); // Log GL profile. log_i("OpenGL core profile %.%.%", maj, min, rev); { // Make an OpenGL driver. gfx::gl::Driver driver{Vec<int>{1000, 1000}}; // Make an isometric camera. auto cam = gfx::make_isometric_camera(); auto terrain_obj = gfx::Object{}; *terrain_obj.material = gfx::load_material("mat/terrain.json"); // Load the image Software_Texture terrain_image; load_png("map/default.png", terrain_image); // Convert it into a heightmap auto terrain_heightmap = make_heightmap_from_image(terrain_image); auto terrain = make_terrain_mesh(*terrain_obj.mesh, terrain_heightmap,{20,20}, .01f, .01); write_obj("../terrain.obj", terrain_obj.mesh->mesh_data()); prepare_object(driver, terrain_obj); // Load our house structure auto house_struct = Json_Structure{"structure/house.json"}; // This is code smell, right here. The fact that before, we were preparing // a temporary but it still worked because of the implementation of // Json_Structure and the object sharing mechanism. auto house_obj = house_struct.make_obj(); prepare_object(driver, house_obj); std::vector<Structure_Instance> house_instances; Structure_Instance moveable_instance{house_struct, Orient::N}; int fps = 0; int time = glfwGetTime(); // Set up some pre-rendering state. driver.clear_color_value(Color{0x55, 0x66, 0x77}); driver.clear_depth_value(1.0); glEnable(GL_DEPTH_TEST); glDepthFunc(GL_LEQUAL); glEnable(GL_CULL_FACE); // Our quick hack to avoid splitting into multiple functions and dealing // either with global variables or like a bound struct or something. bool has_clicked_down = false; // Load our ui gfx::IDriver_UI_Adapter ui_adapter{driver}; ui::Freetype_Renderer freetype_font; auto ui_load_params = ui::Load_Params{freetype_font, ui_adapter}; auto hud = ui::load("ui/hud.json", ui_load_params); auto controller = ui::Simple_Controller{}; hud->find_child_r("build_button")->add_click_listener([](auto const& pt) { log_i("BUILD!"); }); hud->layout(driver.window_extents()); controller.add_click_listener([&](auto const&) { // Commit the current position of our moveable instance. house_instances.push_back(moveable_instance); }); controller.add_hover_listener([&](auto const& pt) { if(pt.x < 0 || pt.x > 1000.0 || pt.y < 0 || pt.y > 1000.0) { moveable_instance.obj.model_matrix = glm::mat4(1.0); } else { // Find our depth. GLfloat z; glReadPixels((float) pt.x, (float) 1000.0 - pt.y, 1, 1, GL_DEPTH_COMPONENT, GL_FLOAT, &z); // Unproject our depth. auto val = glm::unProject(glm::vec3(pt.x, 1000.0 - pt.y, z), camera_view_matrix(cam), camera_proj_matrix(cam), glm::vec4(0.0, 0.0, 1000.0, 1000.0)); // We have our position, render a single house there. moveable_instance.obj.model_matrix = glm::translate(glm::mat4(1.0), val); } // Move the house by however much the structure *type* requires. moveable_instance.obj.model_matrix = moveable_instance.obj.model_matrix * house_struct.make_obj().model_matrix; }); controller.add_drag_listener([&](auto const& np, auto const& op) { // pan auto movement = vec_cast<float>(np - op); movement /= -75; glm::vec4 move_vec(movement.x, 0.0f, movement.y, 0.0f); move_vec = glm::inverse(camera_view_matrix(cam)) * move_vec; cam.fp.pos.x += move_vec.x; cam.fp.pos.z += move_vec.z; }); glfwSetWindowUserPointer(window, &cam); glfwSetScrollCallback(window, scroll_callback); while(!glfwWindowShouldClose(window)) { ++fps; glfwPollEvents(); // Clear the screen and render the terrain. driver.clear(); use_camera(driver, cam); for(auto const& chunk : terrain.chunks) { // Check each point of the aabb for visibility. //for(auto iter = begin_point_iter(chunk.aabb); //iter != end_point_iter(); ++iter) { //glm::vec4 pt(*iter, 1.0f); //auto pt = project_point(pt); } render_object(driver, terrain_obj, chunk.mesh.offset, chunk.mesh.count); } // Render the terrain before we calculate the depth of the mouse position. auto mouse_state = gen_mouse_state(window); controller.step(hud, mouse_state); // Render our movable instance of a house. render_object(driver, moveable_instance.obj); // Render all of our other house instances. for(auto const& instance : house_instances) { render_object(driver, instance.obj); } { ui::Draw_Scoped_Lock scoped_draw_lock{ui_adapter}; hud->render(ui_adapter); } glfwSwapBuffers(window); if(int(glfwGetTime()) != time) { time = glfwGetTime(); log_d("fps: %", fps); fps = 0; } flush_log(); } } glfwTerminate(); return 0; } <commit_msg>Added some non-transparent water generated by the flat terrain function.<commit_after>/* * Copyright (C) 2015 Luke San Antonio * All rights reserved. */ #include <fstream> #include <sstream> #include <cstdlib> #include <vector> #include <thread> #include "common/log.h" #include "gfx/gl/driver.h" #include "gfx/camera.h" #include "gfx/object.h" #include "gfx/scene_node.h" #include "gfx/idriver_ui_adapter.h" #include "common/software_texture.h" #include "common/texture_load.h" #include "common/software_mesh.h" #include "common/mesh_load.h" #include "common/mesh_write.h" #include "ui/load.h" #include "ui/freetype_renderer.h" #include "ui/mouse_logic.h" #include "ui/simple_controller.h" #include "map/map.h" #include "map/json_structure.h" #include "glad/glad.h" #include "glfw3.h" #define GLM_FORCE_RADIANS #include "glm/glm.hpp" #include "glm/gtc/matrix_transform.hpp" #include "uv.h" #define CATCH_CONFIG_RUNNER #include "catch/catch.hpp" glm::vec4 project_point(glm::vec4 pt, glm::mat4 const& model, glm::mat4 const& view, glm::mat4 const& proj) noexcept { pt = proj * view * model * pt; pt /= pt.w; return pt; } void scroll_callback(GLFWwindow* window, double, double deltay) { auto cam_ptr = glfwGetWindowUserPointer(window); auto& camera = *((game::gfx::Camera*) cam_ptr); camera.fp.pos += -deltay; } game::ui::Mouse_State gen_mouse_state(GLFWwindow* w) { game::ui::Mouse_State ret; ret.button_down =glfwGetMouseButton(w, GLFW_MOUSE_BUTTON_LEFT) == GLFW_PRESS; game::Vec<double> pos; glfwGetCursorPos(w, &pos.x, &pos.y); ret.position = game::vec_cast<int>(pos); return ret; } void log_gl_limits(game::Log_Severity s) noexcept { GLint i = 0; glGetIntegerv(GL_MAX_ELEMENTS_VERTICES, &i); log(s, "GL_MAX_ELEMENTS_VERTICES: %", i); } struct Command_Options { }; Command_Options parse_command_line(int argc, char**) { Command_Options opt; for(int i = 0; i < argc; ++i) { //auto option = argv[i]; } return opt; } int main(int argc, char** argv) { using namespace game; set_log_level(Log_Severity::Debug); uv_chdir("assets/"); // Initialize logger. Scoped_Log_Init log_init_raii_lock{}; // Parse command line arguments. auto options = parse_command_line(argc - 1, argv+1); // Init glfw. if(!glfwInit()) return EXIT_FAILURE; auto window = glfwCreateWindow(1000, 1000, "Hello World", NULL, NULL); if(!window) { glfwTerminate(); return EXIT_FAILURE; } // Init context + load gl functions. glfwMakeContextCurrent(window); gladLoadGLLoader((GLADloadproc) glfwGetProcAddress); // Log glfw version. log_i("Initialized GLFW %", glfwGetVersionString()); int maj = glfwGetWindowAttrib(window, GLFW_CONTEXT_VERSION_MAJOR); int min = glfwGetWindowAttrib(window, GLFW_CONTEXT_VERSION_MINOR); int rev = glfwGetWindowAttrib(window, GLFW_CONTEXT_REVISION); // Log GL profile. log_i("OpenGL core profile %.%.%", maj, min, rev); { // Make an OpenGL driver. gfx::gl::Driver driver{Vec<int>{1000, 1000}}; // Make an isometric camera. auto cam = gfx::make_isometric_camera(); auto terrain_obj = gfx::Object{}; *terrain_obj.material = gfx::load_material("mat/terrain.json"); // Load the image Software_Texture terrain_image; load_png("map/default.png", terrain_image); // Convert it into a heightmap auto terrain_heightmap = make_heightmap_from_image(terrain_image); auto terrain = make_terrain_mesh(*terrain_obj.mesh, terrain_heightmap,{20,20}, .001f, .01); write_obj("../terrain.obj", terrain_obj.mesh->mesh_data()); prepare_object(driver, terrain_obj); // Make water. gfx::Object water_obj; *water_obj.material = gfx::load_material("mat/terrain.json"); water_obj.material->diffuse_color = colors::blue; auto water_heightmap = make_flat_heightmap(-1, 2, 2); auto water = make_terrain_mesh(*water_obj.mesh, water_heightmap, {1,1}, .01f, 2.56f); prepare_object(driver, water_obj); // Load our house structure auto house_struct = Json_Structure{"structure/house.json"}; // This is code smell, right here. The fact that before, we were preparing // a temporary but it still worked because of the implementation of // Json_Structure and the object sharing mechanism. auto house_obj = house_struct.make_obj(); prepare_object(driver, house_obj); std::vector<Structure_Instance> house_instances; Structure_Instance moveable_instance{house_struct, Orient::N}; int fps = 0; int time = glfwGetTime(); // Set up some pre-rendering state. driver.clear_color_value(Color{0x55, 0x66, 0x77}); driver.clear_depth_value(1.0); glEnable(GL_DEPTH_TEST); glDepthFunc(GL_LEQUAL); glEnable(GL_CULL_FACE); // Our quick hack to avoid splitting into multiple functions and dealing // either with global variables or like a bound struct or something. bool has_clicked_down = false; // Load our ui gfx::IDriver_UI_Adapter ui_adapter{driver}; ui::Freetype_Renderer freetype_font; auto ui_load_params = ui::Load_Params{freetype_font, ui_adapter}; auto hud = ui::load("ui/hud.json", ui_load_params); auto controller = ui::Simple_Controller{}; hud->find_child_r("build_button")->add_click_listener([](auto const& pt) { log_i("BUILD!"); }); hud->layout(driver.window_extents()); controller.add_click_listener([&](auto const&) { // Commit the current position of our moveable instance. house_instances.push_back(moveable_instance); }); controller.add_hover_listener([&](auto const& pt) { if(pt.x < 0 || pt.x > 1000.0 || pt.y < 0 || pt.y > 1000.0) { moveable_instance.obj.model_matrix = glm::mat4(1.0); } else { // Find our depth. GLfloat z; glReadPixels((float) pt.x, (float) 1000.0 - pt.y, 1, 1, GL_DEPTH_COMPONENT, GL_FLOAT, &z); // Unproject our depth. auto val = glm::unProject(glm::vec3(pt.x, 1000.0 - pt.y, z), camera_view_matrix(cam), camera_proj_matrix(cam), glm::vec4(0.0, 0.0, 1000.0, 1000.0)); // We have our position, render a single house there. moveable_instance.obj.model_matrix = glm::translate(glm::mat4(1.0), val); } // Move the house by however much the structure *type* requires. moveable_instance.obj.model_matrix = moveable_instance.obj.model_matrix * house_struct.make_obj().model_matrix; }); controller.add_drag_listener([&](auto const& np, auto const& op) { // pan auto movement = vec_cast<float>(np - op); movement /= -75; glm::vec4 move_vec(movement.x, 0.0f, movement.y, 0.0f); move_vec = glm::inverse(camera_view_matrix(cam)) * move_vec; cam.fp.pos.x += move_vec.x; cam.fp.pos.z += move_vec.z; }); glfwSetWindowUserPointer(window, &cam); glfwSetScrollCallback(window, scroll_callback); while(!glfwWindowShouldClose(window)) { ++fps; glfwPollEvents(); // Clear the screen and render the terrain. driver.clear(); use_camera(driver, cam); for(auto const& chunk : terrain.chunks) { // Check each point of the aabb for visibility. //for(auto iter = begin_point_iter(chunk.aabb); //iter != end_point_iter(); ++iter) { //glm::vec4 pt(*iter, 1.0f); //auto pt = project_point(pt); } render_object(driver, terrain_obj, chunk.mesh.offset, chunk.mesh.count); } render_object(driver, water_obj); // Render the terrain before we calculate the depth of the mouse position. auto mouse_state = gen_mouse_state(window); controller.step(hud, mouse_state); // Render our movable instance of a house. render_object(driver, moveable_instance.obj); // Render all of our other house instances. for(auto const& instance : house_instances) { render_object(driver, instance.obj); } { ui::Draw_Scoped_Lock scoped_draw_lock{ui_adapter}; hud->render(ui_adapter); } glfwSwapBuffers(window); if(int(glfwGetTime()) != time) { time = glfwGetTime(); log_d("fps: %", fps); fps = 0; } flush_log(); } } glfwTerminate(); return 0; } <|endoftext|>
<commit_before>// $Author: afinit $ // $Date$ // $Log$ // Contains the Process class for afin #include "process.hpp" #include <thread> int max_search_loops; int contig_sub_len; int extend_len; int max_sort_char; int min_cov; int min_overlap; int max_threads; int initial_trim; int max_missed; double stop_ext; bool test_run; int print_fused; int screen_output; int log_output; int verbose; int no_fusion; double mismatch_threshold; std::mutex log_mut; //////////////////////////////////// //////// PROCESS DEFINITIONS /////// //////////////////////////////////// // Process constructor Process::Process(){ outfile = "afin_out"; readsfiles = ""; contigsfiles = ""; reads = 0; contigs = 0; fuse = 0; max_iterations = 1; // initialize unordered_map for iterable options iterable_opts["max_search_loops"] = "10"; iterable_opts["contig_sub_len"] = "100"; iterable_opts["extend_len"] = "40"; iterable_opts["max_sort_char"] = "4"; iterable_opts["min_cov"] = "3"; iterable_opts["min_overlap"] = "20"; iterable_opts["initial_trim"] = "0"; iterable_opts["max_missed"] = "5"; iterable_opts["stop_ext"] = "0.5"; iterable_opts["mismatch_threshold"] = "0.1"; // Declare vector variables for storing iterable_opts std::vector<int> max_search_loops_iter; std::vector<int> contig_sub_len_iter; std::vector<int> extend_len_iter; std::vector<int> max_sort_char_iter; std::vector<int> min_cov_iter; std::vector<int> min_overlap_iter; std::vector<int> initial_trim_iter; std::vector<int> max_missed_iter; std::vector<double> stop_ext_iter; std::vector<double> mismatch_threshold_iter; } Process::~Process(){ delete fuse; delete reads; delete contigs; } // initalize logfile void Process::logfile_init(){ Log::Inst()->open_log( outfile + ".log" ); // output starting option values Log::Inst()->log_it( "OPTION VALUES" ); Log::Inst()->log_it( "contig_sub_len: " + std::to_string(contig_sub_len) ); Log::Inst()->log_it( "extend_len: " + std::to_string(extend_len) ); Log::Inst()->log_it( "max_search_loops: " + std::to_string(max_search_loops) ); Log::Inst()->log_it( "max_sort_char: " + std::to_string(max_sort_char) ); Log::Inst()->log_it( "min_cov: " + std::to_string(min_cov) ); Log::Inst()->log_it( "min_overlap: " + std::to_string(min_overlap) ); Log::Inst()->log_it( "initial_trim: " + std::to_string(initial_trim) ); Log::Inst()->log_it( "max_missed: " + std::to_string(max_missed) ); Log::Inst()->log_it( "mismatch_threshold: " + std::to_string(mismatch_threshold) ); Log::Inst()->log_it( "max_threads: " + std::to_string(max_threads) ); Log::Inst()->log_it( "stop_ext: " + std::to_string(stop_ext) ); } // Parse option int void Process::parse_option( std::string opt_key, std::vector<int>* iter_vect ){ std::string opt = iterable_opts[opt_key]; try{ // check for commas in string if( ! opt.find(',') ){ iter_vect->push_back(std::stoi(opt)); } else{ // split along commas if found std::stringstream ss(opt); std::string item; while( getline( ss, item, ',' )){ iter_vect->push_back(std::stoi(item)); } } } catch( std::exception const & e ){ Log::Inst()->log_it( "Error: " + std::string(e.what(), strlen(e.what())) + " : Invalid values: " + opt + " For option: " + opt_key ); exit(0); } } // Parse option double void Process::parse_option( std::string opt_key, std::vector<double>* iter_vect ){ std::string opt = iterable_opts[opt_key]; try{ // check for commas in string if( ! opt.find(',') ){ iter_vect->push_back(std::stof(opt)); } else{ // split along commas if found std::stringstream ss(opt); std::string item; while( getline( ss, item, ',' )){ iter_vect->push_back(std::stof(item)); } } } catch( std::exception const & e ){ Log::Inst()->log_it( "Error: " + std::string(e.what(), strlen(e.what())) + " : Invalid values: " + opt + " For option: " + opt_key ); exit(0); } } // Populate iterable options vector void Process::populate_iterables(){ // process iterable options parse_option( "max_search_loops", &max_search_loops_iter ); parse_option( "contig_sub_len", &contig_sub_len_iter ); parse_option( "extend_len", &extend_len_iter ); parse_option( "max_sort_char", &max_sort_char_iter ); parse_option( "min_cov", &min_cov_iter ); parse_option( "min_overlap", &min_overlap_iter ); parse_option( "initial_trim", &initial_trim_iter ); parse_option( "max_missed", &max_missed_iter ); parse_option( "stop_ext", &stop_ext_iter ); parse_option( "mismatch_threshold", &mismatch_threshold_iter ); } // set iterables global values at each iteration // NOTE:: rebuild to check for length of vector void Process::set_iterables( int i ){ // max_search_loops_iter if( max_search_loops_iter.size() > i ){ max_search_loops = max_search_loops_iter[i]; } else{ max_search_loops = max_search_loops_iter.back(); } // contig_sub_len_iter if( contig_sub_len_iter.size() > i ){ contig_sub_len = contig_sub_len_iter[i]; } else{ contig_sub_len = contig_sub_len_iter.back(); } // extend_len_iter if( extend_len_iter.size() > i ){ extend_len = extend_len_iter[i]; } else{ extend_len = extend_len_iter.back(); } // max_sort_char_iter if( max_sort_char_iter.size() > i ){ max_sort_char = max_sort_char_iter[i]; } else{ max_sort_char = max_sort_char_iter.back(); } // min_cov_iter if( min_cov_iter.size() > i ){ min_cov = min_cov_iter[i]; } else{ min_cov = min_cov_iter.back(); } // min_overlap_iter if( min_overlap_iter.size() > i ){ min_overlap = min_overlap_iter[i]; } else{ min_overlap = min_overlap_iter.back(); } // initial_trim_iter if( initial_trim_iter.size() > i ){ initial_trim = initial_trim_iter[i]; } else{ initial_trim = initial_trim_iter.back(); } // max_missed_iter if( max_missed_iter.size() > i ){ max_missed = max_missed_iter[i]; } else{ max_missed = max_missed_iter.back(); } // stop_ext_iter if( stop_ext_iter.size() > i ){ stop_ext = stop_ext_iter[i]; } else{ stop_ext = stop_ext_iter.back(); } // mismatch_threshold_iter if( mismatch_threshold_iter.size() > i ){ mismatch_threshold = mismatch_threshold_iter[i]; } else{ mismatch_threshold = mismatch_threshold_iter.back(); } } // Initializes data structures and turns over control to run_manager() void Process::start_run(){ // initialize logfile if logging enabled if( log_output || screen_output ){ logfile_init(); } // process iterable options populate_iterables(); // import reads once reads = new Readlist( readsfiles ); // loop through iterated options if present for( int i=0; i < max_iterations; i++ ){ // prevent printing of fused contigs if( no_fusion ) print_fused = 0; // Set options for this iteration set_iterables(i); // log output file Log::Inst()->log_it( std::string("output file: ") + outfile ); // initialize objects contigs = new Contiglist( reads, contigsfiles, outfile ); fuse = new Fusion( contigs, reads ); Log::Inst()->log_it( "End initialization phase" ); // make initial attempt to fuse contigs if( ! no_fusion ) fuse->run_fusion( true ); if( test_run ) contigs->output_contigs( 0, outfile + ".fus", "mid" ); run_manager(); // write contigs to fasta contigs->create_final_fasta(i); } } // Manages run void Process::run_manager(){ // create thread array with max_thread entries std::vector<std::thread> t; Queue<int> qu; // loop max search loops for( int j=0; j<max_search_loops; j++ ){ Log::Inst()->log_it( "Begin Extensions" ); // initialize threads for( int i=0; i<max_threads; i++ ){ t.push_back(std::thread( &Process::thread_worker, this, std::ref(qu), i )); } if( test_run ){ Log::Inst()->log_it( "contigs.size(): " + std::to_string(contigs->get_list_size()) + " max_threads: " + std::to_string(max_threads) ); } // push each thread onto queue for( int i=0; i<contigs->get_list_size(); i++ ){ qu.push( i ); } // push stop signals onto queue for each thread for( int i=0; i<max_threads; i++ ){ qu.push( -1 ); } // join threads for( int i=0; i<max_threads; i++ ){ t[i].join(); } // remove threads from vector t.erase( t.begin(), t.begin()+max_threads ); // removed for master branch until algorithm can be adjusted if( ! no_fusion ) fuse->run_fusion( false ); if( test_run ){ contigs->output_contigs( 0, outfile + ".fus" + std::to_string(j), "mid" ); } } } // Consume function which will act as the driver for an individual thread void Process::thread_worker( Queue<int>& q, unsigned int id) { for (;;) { auto item = q.pop(); if( item == -1 ){ break; } else{ contigs->get_contig_ref(item)->extend( false ); contigs->get_contig_ref(item)->extend( true ); } } } ////////////////////////// // END PROCESS /////////// ////////////////////////// <commit_msg>fixed missing std::<commit_after>// $Author: afinit $ // $Date$ // $Log$ // Contains the Process class for afin #include "process.hpp" #include <thread> int max_search_loops; int contig_sub_len; int extend_len; int max_sort_char; int min_cov; int min_overlap; int max_threads; int initial_trim; int max_missed; double stop_ext; bool test_run; int print_fused; int screen_output; int log_output; int verbose; int no_fusion; double mismatch_threshold; std::mutex log_mut; //////////////////////////////////// //////// PROCESS DEFINITIONS /////// //////////////////////////////////// // Process constructor Process::Process(){ outfile = "afin_out"; readsfiles = ""; contigsfiles = ""; reads = 0; contigs = 0; fuse = 0; max_iterations = 1; // initialize unordered_map for iterable options iterable_opts["max_search_loops"] = "10"; iterable_opts["contig_sub_len"] = "100"; iterable_opts["extend_len"] = "40"; iterable_opts["max_sort_char"] = "4"; iterable_opts["min_cov"] = "3"; iterable_opts["min_overlap"] = "20"; iterable_opts["initial_trim"] = "0"; iterable_opts["max_missed"] = "5"; iterable_opts["stop_ext"] = "0.5"; iterable_opts["mismatch_threshold"] = "0.1"; // Declare vector variables for storing iterable_opts std::vector<int> max_search_loops_iter; std::vector<int> contig_sub_len_iter; std::vector<int> extend_len_iter; std::vector<int> max_sort_char_iter; std::vector<int> min_cov_iter; std::vector<int> min_overlap_iter; std::vector<int> initial_trim_iter; std::vector<int> max_missed_iter; std::vector<double> stop_ext_iter; std::vector<double> mismatch_threshold_iter; } Process::~Process(){ delete fuse; delete reads; delete contigs; } // initalize logfile void Process::logfile_init(){ Log::Inst()->open_log( outfile + ".log" ); // output starting option values Log::Inst()->log_it( "OPTION VALUES" ); Log::Inst()->log_it( "contig_sub_len: " + std::to_string(contig_sub_len) ); Log::Inst()->log_it( "extend_len: " + std::to_string(extend_len) ); Log::Inst()->log_it( "max_search_loops: " + std::to_string(max_search_loops) ); Log::Inst()->log_it( "max_sort_char: " + std::to_string(max_sort_char) ); Log::Inst()->log_it( "min_cov: " + std::to_string(min_cov) ); Log::Inst()->log_it( "min_overlap: " + std::to_string(min_overlap) ); Log::Inst()->log_it( "initial_trim: " + std::to_string(initial_trim) ); Log::Inst()->log_it( "max_missed: " + std::to_string(max_missed) ); Log::Inst()->log_it( "mismatch_threshold: " + std::to_string(mismatch_threshold) ); Log::Inst()->log_it( "max_threads: " + std::to_string(max_threads) ); Log::Inst()->log_it( "stop_ext: " + std::to_string(stop_ext) ); } // Parse option int void Process::parse_option( std::string opt_key, std::vector<int>* iter_vect ){ std::string opt = iterable_opts[opt_key]; try{ // check for commas in string if( ! opt.find(',') ){ iter_vect->push_back(std::stoi(opt)); } else{ // split along commas if found std::stringstream ss(opt); std::string item; while( getline( ss, item, ',' )){ iter_vect->push_back(std::stoi(item)); } } } catch( std::exception const & e ){ Log::Inst()->log_it( "Error: " + std::string(e.what(), std::strlen(e.what())) + " : Invalid values: " + opt + " For option: " + opt_key ); exit(0); } } // Parse option double void Process::parse_option( std::string opt_key, std::vector<double>* iter_vect ){ std::string opt = iterable_opts[opt_key]; try{ // check for commas in string if( ! opt.find(',') ){ iter_vect->push_back(std::stof(opt)); } else{ // split along commas if found std::stringstream ss(opt); std::string item; while( getline( ss, item, ',' )){ iter_vect->push_back(std::stof(item)); } } } catch( std::exception const & e ){ Log::Inst()->log_it( "Error: " + std::string(e.what(), std::strlen(e.what())) + " : Invalid values: " + opt + " For option: " + opt_key ); exit(0); } } // Populate iterable options vector void Process::populate_iterables(){ // process iterable options parse_option( "max_search_loops", &max_search_loops_iter ); parse_option( "contig_sub_len", &contig_sub_len_iter ); parse_option( "extend_len", &extend_len_iter ); parse_option( "max_sort_char", &max_sort_char_iter ); parse_option( "min_cov", &min_cov_iter ); parse_option( "min_overlap", &min_overlap_iter ); parse_option( "initial_trim", &initial_trim_iter ); parse_option( "max_missed", &max_missed_iter ); parse_option( "stop_ext", &stop_ext_iter ); parse_option( "mismatch_threshold", &mismatch_threshold_iter ); } // set iterables global values at each iteration // NOTE:: rebuild to check for length of vector void Process::set_iterables( int i ){ // max_search_loops_iter if( max_search_loops_iter.size() > i ){ max_search_loops = max_search_loops_iter[i]; } else{ max_search_loops = max_search_loops_iter.back(); } // contig_sub_len_iter if( contig_sub_len_iter.size() > i ){ contig_sub_len = contig_sub_len_iter[i]; } else{ contig_sub_len = contig_sub_len_iter.back(); } // extend_len_iter if( extend_len_iter.size() > i ){ extend_len = extend_len_iter[i]; } else{ extend_len = extend_len_iter.back(); } // max_sort_char_iter if( max_sort_char_iter.size() > i ){ max_sort_char = max_sort_char_iter[i]; } else{ max_sort_char = max_sort_char_iter.back(); } // min_cov_iter if( min_cov_iter.size() > i ){ min_cov = min_cov_iter[i]; } else{ min_cov = min_cov_iter.back(); } // min_overlap_iter if( min_overlap_iter.size() > i ){ min_overlap = min_overlap_iter[i]; } else{ min_overlap = min_overlap_iter.back(); } // initial_trim_iter if( initial_trim_iter.size() > i ){ initial_trim = initial_trim_iter[i]; } else{ initial_trim = initial_trim_iter.back(); } // max_missed_iter if( max_missed_iter.size() > i ){ max_missed = max_missed_iter[i]; } else{ max_missed = max_missed_iter.back(); } // stop_ext_iter if( stop_ext_iter.size() > i ){ stop_ext = stop_ext_iter[i]; } else{ stop_ext = stop_ext_iter.back(); } // mismatch_threshold_iter if( mismatch_threshold_iter.size() > i ){ mismatch_threshold = mismatch_threshold_iter[i]; } else{ mismatch_threshold = mismatch_threshold_iter.back(); } } // Initializes data structures and turns over control to run_manager() void Process::start_run(){ // initialize logfile if logging enabled if( log_output || screen_output ){ logfile_init(); } // process iterable options populate_iterables(); // import reads once reads = new Readlist( readsfiles ); // loop through iterated options if present for( int i=0; i < max_iterations; i++ ){ // prevent printing of fused contigs if( no_fusion ) print_fused = 0; // Set options for this iteration set_iterables(i); // log output file Log::Inst()->log_it( std::string("output file: ") + outfile ); // initialize objects contigs = new Contiglist( reads, contigsfiles, outfile ); fuse = new Fusion( contigs, reads ); Log::Inst()->log_it( "End initialization phase" ); // make initial attempt to fuse contigs if( ! no_fusion ) fuse->run_fusion( true ); if( test_run ) contigs->output_contigs( 0, outfile + ".fus", "mid" ); run_manager(); // write contigs to fasta contigs->create_final_fasta(i); } } // Manages run void Process::run_manager(){ // create thread array with max_thread entries std::vector<std::thread> t; Queue<int> qu; // loop max search loops for( int j=0; j<max_search_loops; j++ ){ Log::Inst()->log_it( "Begin Extensions" ); // initialize threads for( int i=0; i<max_threads; i++ ){ t.push_back(std::thread( &Process::thread_worker, this, std::ref(qu), i )); } if( test_run ){ Log::Inst()->log_it( "contigs.size(): " + std::to_string(contigs->get_list_size()) + " max_threads: " + std::to_string(max_threads) ); } // push each thread onto queue for( int i=0; i<contigs->get_list_size(); i++ ){ qu.push( i ); } // push stop signals onto queue for each thread for( int i=0; i<max_threads; i++ ){ qu.push( -1 ); } // join threads for( int i=0; i<max_threads; i++ ){ t[i].join(); } // remove threads from vector t.erase( t.begin(), t.begin()+max_threads ); // removed for master branch until algorithm can be adjusted if( ! no_fusion ) fuse->run_fusion( false ); if( test_run ){ contigs->output_contigs( 0, outfile + ".fus" + std::to_string(j), "mid" ); } } } // Consume function which will act as the driver for an individual thread void Process::thread_worker( Queue<int>& q, unsigned int id) { for (;;) { auto item = q.pop(); if( item == -1 ){ break; } else{ contigs->get_contig_ref(item)->extend( false ); contigs->get_contig_ref(item)->extend( true ); } } } ////////////////////////// // END PROCESS /////////// ////////////////////////// <|endoftext|>
<commit_before>#include "main.h" #include "cvar.h" #include "sound.h" #include "event.h" vgui::ISystem* g_pSystem; IVEngineClient* g_pEngineClient; IGameEventManager2* g_pEventManager; IFileSystem* g_pFileSystem; ICvar* g_pCVar; Class g_localPlayerClass = Class::Null; DemoInfo::DemoInfo( const char *path, const char *file, const char *tag, const char *date, const char *map, const char *blu, const char *red) : fullpath(path), filename(file), tag(tag), date(date), mapname(map), bluteam(blu), redteam(red), hasMarks(false) { } void DemoInfo::Mark() { hasMarks = true; } bool DemoInfo::HasMarks() const { return hasMarks; } std::unique_ptr<DemoInfo> g_pDemoInfo(nullptr); std::unique_ptr<DemoInfo> g_pPrevDemoInfo(nullptr);; bool g_demoIsInternal = false; bool g_roundIsActive = false; class PluginImpl: public IServerPluginCallbacks { public: PluginImpl(); virtual ~PluginImpl(); /* * Declare virtual functions from IServerPluginCallbacks */ virtual bool Load(CreateInterfaceFn interfaceFactory, CreateInterfaceFn gameServerFactory); virtual void Unload(); virtual void Pause(); virtual void UnPause(); virtual const char* GetPluginDescription(); virtual void LevelInit(char const *pMapName); virtual void ServerActivate(edict_t *pEdictList, int edictCount, int clientMax); virtual void GameFrame(bool simulating); virtual void LevelShutdown(); virtual void OnQueryCvarValueFinished(QueryCvarCookie_t iCookie, edict_t *pPlayerEntity, EQueryCvarValueStatus eStatus, const char *pCvarName, const char *pCvarValue); virtual void OnEdictAllocated(edict_t *edict); virtual void OnEdictFreed(const edict_t *edict); virtual PLUGIN_RESULT ClientConnect(bool *bAllowConnect, edict_t *pEntity, const char *pszName, const char *pszAddress, char *reject, int maxrejectlen); virtual void ClientPutInServer(edict_t *pEntity, char const *playername); virtual void ClientActive(edict_t *pEntity); virtual void ClientDisconnect(edict_t *pEntity); virtual void SetCommandClient(int index); virtual void ClientSettingsChanged(edict_t *pEdict); virtual PLUGIN_RESULT ClientCommand(edict_t *pEntity, const CCommand &args); virtual PLUGIN_RESULT NetworkIDValidated(const char *pszUserName, const char *pszNetworkID); }; PluginImpl g_PluginObj; //EXPOSE_SINGLE_INTERFACE_GL0BALVAR(PluginImpl, IServerPluginCallbacks, INTERFACEVERSION_ISERVERPLUGINCALLBACKS, g_PluginObj) // Manual expansion of EXPOSE_SINGLE_INTERFACE_GLOBALVAR // TODO: Determine why macro causes build to fail under GCC 5.1.0 static void* __CreatePluginImplIServerPluginCallbacks_interface() {return static_cast<IServerPluginCallbacks*>( &g_PluginObj );} static InterfaceReg __g_CreatePluginImplIServerPluginCallbacks_reg(__CreatePluginImplIServerPluginCallbacks_interface, INTERFACEVERSION_ISERVERPLUGINCALLBACKS); PluginImpl::PluginImpl() { // Do nothing! } PluginImpl::~PluginImpl() { // Do nothing! } bool PluginImpl::Load(CreateInterfaceFn interfaceFactory, CreateInterfaceFn gameServerFactory) { g_pSystem = static_cast<vgui::ISystem*>(interfaceFactory(VGUI_SYSTEM_INTERFACE_VERSION, NULL)); if (g_pSystem == nullptr) { Msg("Failed to initialize VGUI System interface\n"); return false; } g_pEngineClient = static_cast<IVEngineClient*>(interfaceFactory(VENGINE_CLIENT_INTERFACE_VERSION, NULL)); if (g_pEngineClient == nullptr) { Msg("Failed to initialize Client Engine interface\n"); return false; } g_pEventManager = static_cast<IGameEventManager2*>(interfaceFactory(INTERFACEVERSION_GAMEEVENTSMANAGER2, NULL)); if (g_pEventManager == nullptr) { Msg("Failed to initialize Game Event interface\n"); return false; } g_pFileSystem = static_cast<IFileSystem*>(interfaceFactory(FILESYSTEM_INTERFACE_VERSION, NULL)); if (g_pFileSystem == nullptr) { Msg("Failed to initialize Filesystem interface\n"); return false; } g_pCVar = static_cast<ICvar*>(interfaceFactory(CVAR_INTERFACE_VERSION, NULL)); if (g_pCVar == nullptr) { Msg("Failed to initialize Cvar interface\n"); return false; } if (!register_cvars()) { Msg("Failed to register cvars\n"); return false; } if (!register_concommands()) { Msg("Failed to register ConCommands\n"); return false; } if (!load_sound_table()) { Msg("Failed to load sound table\n"); return false; } if (!register_eventlisteners()) { Msg("Failed to load event listeners\n"); return false; } Msg(OPENPREC_NAME " loaded!\n"); return true; } void PluginImpl::Unload() { unregister_cvars(); unregister_concommands(); unregister_eventlisteners(); } void PluginImpl::Pause() {} void PluginImpl::UnPause() {} const char *PluginImpl::GetPluginDescription() { return OPENPREC_NAME " v" OPENPREC_VERSION ": " OPENPREC_DESC ", by " OPENPREC_AUTH; } void PluginImpl::LevelInit(char const *pMapName) { g_localPlayerClass = Class::Null; } void PluginImpl::ServerActivate(edict_t *pEdictList, int edictCount, int clientMax) {} void PluginImpl::GameFrame(bool simulating) { if (simulating && g_demoIsInternal) { g_demoIsInternal = g_pEngineClient->IsRecordingDemo(); if (!g_demoIsInternal && !g_pDemoInfo->HasMarks() && prec_delete_useless_demo.GetInt() == 1) { prec_delete_demo(CCommand(0, nullptr)); } } } void PluginImpl::LevelShutdown() { g_roundIsActive = false; if (g_pEngineClient->IsRecordingDemo() && g_demoIsInternal) { ConCommand *stop = g_pCVar->FindCommand("stop"); const char *argv[1] = {"stop"}; stop->Dispatch(CCommand(1, argv)); g_demoIsInternal = false; if (!g_pDemoInfo->HasMarks() && prec_delete_useless_demo.GetInt() == 1) { prec_delete_demo(CCommand(0, nullptr)); } } } void PluginImpl::OnQueryCvarValueFinished(QueryCvarCookie_t iCookie, edict_t *pPlayerEntity, EQueryCvarValueStatus eStatus, const char *pCvarName, const char *pCvarValue) {} void PluginImpl::OnEdictAllocated(edict_t *edict) {} void PluginImpl::OnEdictFreed(const edict_t *edict) {} PLUGIN_RESULT PluginImpl::ClientConnect(bool *bAllowConnect, edict_t *pEntity, const char *pszName, const char *pszAddress, char *reject, int maxrejectlen) { return PLUGIN_CONTINUE; } void PluginImpl::ClientPutInServer(edict_t *pEntity, char const *playername) {} void PluginImpl::ClientActive(edict_t *pEntity) {} void PluginImpl::ClientDisconnect(edict_t *pEntity) {} void PluginImpl::SetCommandClient(int index) {} void PluginImpl::ClientSettingsChanged(edict_t *pEdict) {} PLUGIN_RESULT PluginImpl::ClientCommand(edict_t *pEntity, const CCommand &args) { return PLUGIN_CONTINUE; } PLUGIN_RESULT PluginImpl::NetworkIDValidated(const char *pszUserName, const char *pszNetworkID) { return PLUGIN_CONTINUE; } <commit_msg>Fix linkage with tier1.a<commit_after>#include "main.h" #include "cvar.h" #include "sound.h" #include "event.h" vgui::ISystem* g_pSystem; IVEngineClient* g_pEngineClient; IGameEventManager2* g_pEventManager; IFileSystem* g_pFileSystem; Class g_localPlayerClass = Class::Null; DemoInfo::DemoInfo( const char *path, const char *file, const char *tag, const char *date, const char *map, const char *blu, const char *red) : fullpath(path), filename(file), tag(tag), date(date), mapname(map), bluteam(blu), redteam(red), hasMarks(false) { } void DemoInfo::Mark() { hasMarks = true; } bool DemoInfo::HasMarks() const { return hasMarks; } std::unique_ptr<DemoInfo> g_pDemoInfo(nullptr); std::unique_ptr<DemoInfo> g_pPrevDemoInfo(nullptr);; bool g_demoIsInternal = false; bool g_roundIsActive = false; class PluginImpl: public IServerPluginCallbacks { public: PluginImpl(); virtual ~PluginImpl(); /* * Declare virtual functions from IServerPluginCallbacks */ virtual bool Load(CreateInterfaceFn interfaceFactory, CreateInterfaceFn gameServerFactory); virtual void Unload(); virtual void Pause(); virtual void UnPause(); virtual const char* GetPluginDescription(); virtual void LevelInit(char const *pMapName); virtual void ServerActivate(edict_t *pEdictList, int edictCount, int clientMax); virtual void GameFrame(bool simulating); virtual void LevelShutdown(); virtual void OnQueryCvarValueFinished(QueryCvarCookie_t iCookie, edict_t *pPlayerEntity, EQueryCvarValueStatus eStatus, const char *pCvarName, const char *pCvarValue); virtual void OnEdictAllocated(edict_t *edict); virtual void OnEdictFreed(const edict_t *edict); virtual PLUGIN_RESULT ClientConnect(bool *bAllowConnect, edict_t *pEntity, const char *pszName, const char *pszAddress, char *reject, int maxrejectlen); virtual void ClientPutInServer(edict_t *pEntity, char const *playername); virtual void ClientActive(edict_t *pEntity); virtual void ClientDisconnect(edict_t *pEntity); virtual void SetCommandClient(int index); virtual void ClientSettingsChanged(edict_t *pEdict); virtual PLUGIN_RESULT ClientCommand(edict_t *pEntity, const CCommand &args); virtual PLUGIN_RESULT NetworkIDValidated(const char *pszUserName, const char *pszNetworkID); }; PluginImpl g_PluginObj; //EXPOSE_SINGLE_INTERFACE_GL0BALVAR(PluginImpl, IServerPluginCallbacks, INTERFACEVERSION_ISERVERPLUGINCALLBACKS, g_PluginObj) // Manual expansion of EXPOSE_SINGLE_INTERFACE_GLOBALVAR // TODO: Determine why macro causes build to fail under GCC 5.1.0 static void* __CreatePluginImplIServerPluginCallbacks_interface() {return static_cast<IServerPluginCallbacks*>( &g_PluginObj );} static InterfaceReg __g_CreatePluginImplIServerPluginCallbacks_reg(__CreatePluginImplIServerPluginCallbacks_interface, INTERFACEVERSION_ISERVERPLUGINCALLBACKS); PluginImpl::PluginImpl() { // Do nothing! } PluginImpl::~PluginImpl() { // Do nothing! } bool PluginImpl::Load(CreateInterfaceFn interfaceFactory, CreateInterfaceFn gameServerFactory) { g_pSystem = static_cast<vgui::ISystem*>(interfaceFactory(VGUI_SYSTEM_INTERFACE_VERSION, NULL)); if (g_pSystem == nullptr) { Msg("Failed to initialize VGUI System interface\n"); return false; } g_pEngineClient = static_cast<IVEngineClient*>(interfaceFactory(VENGINE_CLIENT_INTERFACE_VERSION, NULL)); if (g_pEngineClient == nullptr) { Msg("Failed to initialize Client Engine interface\n"); return false; } g_pEventManager = static_cast<IGameEventManager2*>(interfaceFactory(INTERFACEVERSION_GAMEEVENTSMANAGER2, NULL)); if (g_pEventManager == nullptr) { Msg("Failed to initialize Game Event interface\n"); return false; } g_pFileSystem = static_cast<IFileSystem*>(interfaceFactory(FILESYSTEM_INTERFACE_VERSION, NULL)); if (g_pFileSystem == nullptr) { Msg("Failed to initialize Filesystem interface\n"); return false; } g_pCVar = static_cast<ICvar*>(interfaceFactory(CVAR_INTERFACE_VERSION, NULL)); if (g_pCVar == nullptr) { Msg("Failed to initialize Cvar interface\n"); return false; } if (!register_cvars()) { Msg("Failed to register cvars\n"); return false; } if (!register_concommands()) { Msg("Failed to register ConCommands\n"); return false; } if (!load_sound_table()) { Msg("Failed to load sound table\n"); return false; } if (!register_eventlisteners()) { Msg("Failed to load event listeners\n"); return false; } Msg(OPENPREC_NAME " loaded!\n"); return true; } void PluginImpl::Unload() { unregister_cvars(); unregister_concommands(); unregister_eventlisteners(); } void PluginImpl::Pause() {} void PluginImpl::UnPause() {} const char *PluginImpl::GetPluginDescription() { return OPENPREC_NAME " v" OPENPREC_VERSION ": " OPENPREC_DESC ", by " OPENPREC_AUTH; } void PluginImpl::LevelInit(char const *pMapName) { g_localPlayerClass = Class::Null; } void PluginImpl::ServerActivate(edict_t *pEdictList, int edictCount, int clientMax) {} void PluginImpl::GameFrame(bool simulating) { if (simulating && g_demoIsInternal) { g_demoIsInternal = g_pEngineClient->IsRecordingDemo(); if (!g_demoIsInternal && !g_pDemoInfo->HasMarks() && prec_delete_useless_demo.GetInt() == 1) { prec_delete_demo(CCommand(0, nullptr)); } } } void PluginImpl::LevelShutdown() { g_roundIsActive = false; if (g_pEngineClient->IsRecordingDemo() && g_demoIsInternal) { ConCommand *stop = g_pCVar->FindCommand("stop"); const char *argv[1] = {"stop"}; stop->Dispatch(CCommand(1, argv)); g_demoIsInternal = false; if (!g_pDemoInfo->HasMarks() && prec_delete_useless_demo.GetInt() == 1) { prec_delete_demo(CCommand(0, nullptr)); } } } void PluginImpl::OnQueryCvarValueFinished(QueryCvarCookie_t iCookie, edict_t *pPlayerEntity, EQueryCvarValueStatus eStatus, const char *pCvarName, const char *pCvarValue) {} void PluginImpl::OnEdictAllocated(edict_t *edict) {} void PluginImpl::OnEdictFreed(const edict_t *edict) {} PLUGIN_RESULT PluginImpl::ClientConnect(bool *bAllowConnect, edict_t *pEntity, const char *pszName, const char *pszAddress, char *reject, int maxrejectlen) { return PLUGIN_CONTINUE; } void PluginImpl::ClientPutInServer(edict_t *pEntity, char const *playername) {} void PluginImpl::ClientActive(edict_t *pEntity) {} void PluginImpl::ClientDisconnect(edict_t *pEntity) {} void PluginImpl::SetCommandClient(int index) {} void PluginImpl::ClientSettingsChanged(edict_t *pEdict) {} PLUGIN_RESULT PluginImpl::ClientCommand(edict_t *pEntity, const CCommand &args) { return PLUGIN_CONTINUE; } PLUGIN_RESULT PluginImpl::NetworkIDValidated(const char *pszUserName, const char *pszNetworkID) { return PLUGIN_CONTINUE; } <|endoftext|>
<commit_before>#pragma once #include <cstdlib> #include <cassert> #include <cstring> #include <type_traits> #include <stdexcept> #include <limits> #include <memory> #include <tuple> //for cuda #ifdef __CUDACC__ #if __CUDACC_VER_MAJOR__ < 8 #error CUDA minimum version is 8.0 #endif #define MATAZURE_CUDA #endif #ifdef MATAZURE_CUDA #define MATAZURE_GENERAL __host__ __device__ #define MATAZURE_DEVICE __device__ #define MATAZURE_GLOBAL __global__ #define __matazure__ MATAZURE_GENERAL #else #define MATAZURE_DEVICE #define MATAZURE_GENERAL #define MATAZURE_GLOBAL #define __matazure__ #endif #ifdef _OPENMP #define MATAZURE_OPENMP #endif //for using namespace matazure { typedef int int_t; using std::shared_ptr; using std::make_shared; using std::unique_ptr; using std::move; typedef unsigned char byte; using std::decay; using std::remove_const; using std::remove_reference; using std::remove_cv; using std::remove_all_extents; using std::forward; using std::is_same; using std::conditional; using std::enable_if; using std::integral_constant; using std::is_integral; using std::numeric_limits; using std::tuple; using std::make_tuple; using std::tuple_size; using std::tuple_element; using std::tie; using std::get; template<bool _Val> using bool_constant = integral_constant<bool, _Val>; template<typename _Ty> using decay_t = typename decay<_Ty>::type; template<typename _Ty> using remove_reference_t = typename remove_reference<_Ty>::type; template<bool _Test, class _Ty = void> using enable_if_t = typename enable_if<_Test, _Ty>::type; template<bool _Test, class _Ty1, class _Ty2> using conditional_t = typename conditional<_Test, _Ty1, _Ty2>::type; template<typename _Ty> using remove_const_t = typename remove_const<_Ty>::type; template <typename _Ty> using remove_cv_t = typename remove_cv<_Ty>::type; struct blank_t {}; } //for assert #define MATAZURE_STATIC_ASSERT_DIM_MATCHED(T1, T2) static_assert(T1::rank == T2::rank, "the rank is not matched") #define MATAZURE_STATIC_ASSERT_VALUE_TYPE_MATCHED(T1, T2) static_assert(std::is_same<typename T1::value_type, typename T2::value_type>::value, \ "the value type is not matched") #define MATAZURE_STATIC_ASSERT_MEMORY_TYPE_MATCHED(T1, T2) static_assert(std::is_same<typename T1::memory_type, typename T2::memory_type>::value, "the memory type is not matched") #define MATAZURE_STATIC_ASSERT_MATRIX_RANK(T) static_assert(T::rank == 2, "the matrix rank should be 2") #define MATAZURE_CURRENT_FUNCTION "(unknown)" #if defined(__has_builtin) #if __has_builtin(__builtin_expect) #define MATAZURE_LIKELY(x) __builtin_expect(x, 1) #define MATAZURE_UNLIKELY(x) __builtin_expect(x, 0) #else #define MATAZURE_LIKELY(x) x #define MATAZURE_UNLIKELY(x) x #endif #else #define MATAZURE_LIKELY(x) x #define MATAZURE_UNLIKELY(x) x #endif #if defined(MATAZURE_DISABLE_ASSERTS) #define MATAZURE_ASSERT(expr, msg) ((void)0) #else namespace matazure { class assert_failed: public std::runtime_error{ public: assert_failed(const std::string &msg) : std::runtime_error(msg) { } }; inline void assertion_failed(char const * expr, char const * msg, char const * function, char const * file, long line) { throw assert_failed(std::string(msg)); } } #define MATAZURE_ASSERT(expr, msg) (MATAZURE_LIKELY(!!(expr))? ((void)0): ::matazure::assertion_failed(#expr, msg, MATAZURE_CURRENT_FUNCTION, __FILE__, __LINE__)) #endif <commit_msg>add algorithm header<commit_after>#pragma once #include <cstdlib> #include <cassert> #include <cstring> #include <type_traits> #include <stdexcept> #include <limits> #include <memory> #include <tuple> #include <algorithm> //for cuda #ifdef __CUDACC__ #if __CUDACC_VER_MAJOR__ < 8 #error CUDA minimum version is 8.0 #endif #define MATAZURE_CUDA #endif #ifdef MATAZURE_CUDA #define MATAZURE_GENERAL __host__ __device__ #define MATAZURE_DEVICE __device__ #define MATAZURE_GLOBAL __global__ #define __matazure__ MATAZURE_GENERAL #else #define MATAZURE_DEVICE #define MATAZURE_GENERAL #define MATAZURE_GLOBAL #define __matazure__ #endif #ifdef _OPENMP #define MATAZURE_OPENMP #endif //for using namespace matazure { typedef int int_t; using std::shared_ptr; using std::make_shared; using std::unique_ptr; using std::move; typedef unsigned char byte; using std::decay; using std::remove_const; using std::remove_reference; using std::remove_cv; using std::remove_all_extents; using std::forward; using std::is_same; using std::conditional; using std::enable_if; using std::integral_constant; using std::is_integral; using std::numeric_limits; using std::tuple; using std::make_tuple; using std::tuple_size; using std::tuple_element; using std::tie; using std::get; template<bool _Val> using bool_constant = integral_constant<bool, _Val>; template<typename _Ty> using decay_t = typename decay<_Ty>::type; template<typename _Ty> using remove_reference_t = typename remove_reference<_Ty>::type; template<bool _Test, class _Ty = void> using enable_if_t = typename enable_if<_Test, _Ty>::type; template<bool _Test, class _Ty1, class _Ty2> using conditional_t = typename conditional<_Test, _Ty1, _Ty2>::type; template<typename _Ty> using remove_const_t = typename remove_const<_Ty>::type; template <typename _Ty> using remove_cv_t = typename remove_cv<_Ty>::type; struct blank_t {}; } //for assert #define MATAZURE_STATIC_ASSERT_DIM_MATCHED(T1, T2) static_assert(T1::rank == T2::rank, "the rank is not matched") #define MATAZURE_STATIC_ASSERT_VALUE_TYPE_MATCHED(T1, T2) static_assert(std::is_same<typename T1::value_type, typename T2::value_type>::value, \ "the value type is not matched") #define MATAZURE_STATIC_ASSERT_MEMORY_TYPE_MATCHED(T1, T2) static_assert(std::is_same<typename T1::memory_type, typename T2::memory_type>::value, "the memory type is not matched") #define MATAZURE_STATIC_ASSERT_MATRIX_RANK(T) static_assert(T::rank == 2, "the matrix rank should be 2") #define MATAZURE_CURRENT_FUNCTION "(unknown)" #if defined(__has_builtin) #if __has_builtin(__builtin_expect) #define MATAZURE_LIKELY(x) __builtin_expect(x, 1) #define MATAZURE_UNLIKELY(x) __builtin_expect(x, 0) #else #define MATAZURE_LIKELY(x) x #define MATAZURE_UNLIKELY(x) x #endif #else #define MATAZURE_LIKELY(x) x #define MATAZURE_UNLIKELY(x) x #endif #if defined(MATAZURE_DISABLE_ASSERTS) #define MATAZURE_ASSERT(expr, msg) ((void)0) #else namespace matazure { class assert_failed: public std::runtime_error{ public: assert_failed(const std::string &msg) : std::runtime_error(msg) { } }; inline void assertion_failed(char const * expr, char const * msg, char const * function, char const * file, long line) { throw assert_failed(std::string(msg)); } } #define MATAZURE_ASSERT(expr, msg) (MATAZURE_LIKELY(!!(expr))? ((void)0): ::matazure::assertion_failed(#expr, msg, MATAZURE_CURRENT_FUNCTION, __FILE__, __LINE__)) #endif <|endoftext|>
<commit_before> #include <string> #include <fstream> #include <iostream> #include "thermalPrinter.h" static inline bool loadFromPath(const std::string& path, std::string* into) { std::ifstream file; std::string buffer; file.open(path.c_str()); if(!file.is_open()) return false; while(!file.eof()) { getline(file, buffer); (*into) += buffer + "\n"; } file.close(); return true; } static inline bool haveExt(const std::string& file, const std::string& ext){ return file.find("."+ext) != std::string::npos; } ThermalPrinter printer; // Main program //============================================================================ int main(int argc, char **argv){ // Get a list of ports std::string port = "NONE"; std::vector<serial::PortInfo> ports = serial::list_ports(); for (uint i = 0; i < ports.size(); i++){ // std::cout << ports[i].port << " - " << ports[i].description << " - " << ports[i].hardware_id << std::endl; std::string::size_type found = ports[i].description.find("Prolific Technology Inc. USB-Serial Controller"); if (found != std::string::npos){ port = ports[i].port; break; } } // Contect the printer to the port std::cout << "Connecting to port [" << port << "] "; if (printer.open(port)){ std::cout << "successfully."<< std::endl; } else { std::cout << "error."<< std::endl; return 0; } // Load files to watch for (int i = 1; i < argc ; i++){ std::string argument = std::string(argv[i]); if ( haveExt(argument,"png") || haveExt(argument,"PNG") || haveExt(argument,"jpg") || haveExt(argument,"JPG") || haveExt(argument,"jpeg") || haveExt(argument,"JPEG") ){ // Load Image and print it printer.printImg(argument); } else if ( haveExt(argument,"txt") || haveExt(argument,"TXT") || haveExt(argument,"md") || haveExt(argument,"MD") ){ // Load Text to print std::string text = ""; loadFromPath(argument,&text); printer.print(text+"\n"); } else if (argument == "-s") { std::string text = ""; for (uint j = i+1; j < argc ; j++){ text += std::string(argv[j]) + " "; } printer.print(text+"\n"); break; } } printer.close(); return 0; }<commit_msg>non uint<commit_after> #include <string> #include <fstream> #include <iostream> #include "thermalPrinter.h" static inline bool loadFromPath(const std::string& path, std::string* into) { std::ifstream file; std::string buffer; file.open(path.c_str()); if(!file.is_open()) return false; while(!file.eof()) { getline(file, buffer); (*into) += buffer + "\n"; } file.close(); return true; } static inline bool haveExt(const std::string& file, const std::string& ext){ return file.find("."+ext) != std::string::npos; } ThermalPrinter printer; // Main program //============================================================================ int main(int argc, char **argv){ // Get a list of ports std::string port = "NONE"; std::vector<serial::PortInfo> ports = serial::list_ports(); for (uint i = 0; i < ports.size(); i++){ // std::cout << ports[i].port << " - " << ports[i].description << " - " << ports[i].hardware_id << std::endl; std::string::size_type found = ports[i].description.find("Prolific Technology Inc. USB-Serial Controller"); if (found != std::string::npos){ port = ports[i].port; break; } } // Contect the printer to the port std::cout << "Connecting to port [" << port << "] "; if (printer.open(port)){ std::cout << "successfully."<< std::endl; } else { std::cout << "error."<< std::endl; return 0; } // Load files to watch for (int i = 1; i < argc ; i++){ std::string argument = std::string(argv[i]); if ( haveExt(argument,"png") || haveExt(argument,"PNG") || haveExt(argument,"jpg") || haveExt(argument,"JPG") || haveExt(argument,"jpeg") || haveExt(argument,"JPEG") ){ // Load Image and print it printer.printImg(argument); } else if ( haveExt(argument,"txt") || haveExt(argument,"TXT") || haveExt(argument,"md") || haveExt(argument,"MD") ){ // Load Text to print std::string text = ""; loadFromPath(argument,&text); printer.print(text+"\n"); } else if (argument == "-s") { std::string text = ""; for (int j = i+1; j < argc ; j++){ text += std::string(argv[j]) + " "; } printer.print(text+"\n"); break; } } printer.close(); return 0; }<|endoftext|>
<commit_before>#include "Image.h" #include "../raster/BgraFrame.h" namespace Aggplus { //////////////////////////////////////////////////////////////////////////////////////// CImage::CImage() : m_dwWidth(0), m_dwHeight(0), m_nStride(0), m_pImgData(NULL), m_bExternalBuffer(false), m_Status(WrongState) { } CImage::CImage(const std::wstring& filename) : m_dwWidth(0), m_dwHeight(0), m_nStride(0), m_pImgData(NULL), m_bExternalBuffer(false) { Create(filename); } CImage::~CImage() { Destroy(); } void CImage::Create(const std::wstring& filename) { Destroy(); CBgraFrame oFrame; bool bOpen = oFrame.OpenFile(filename); if (bOpen) { m_pImgData = oFrame.get_Data(); m_dwWidth = (DWORD)oFrame.get_Width(); m_dwHeight = (DWORD)oFrame.get_Height(); m_nStride = oFrame.get_Stride(); m_Status = Ok; } oFrame.ClearNoAttack(); } void CImage::Destroy() { if (NULL != m_pImgData) { if (!m_bExternalBuffer) { delete [] m_pImgData; } } m_Status = WrongState; m_pImgData = NULL; m_dwWidth = 0; m_dwHeight = 0; m_nStride = 0; m_bExternalBuffer = false; } DWORD CImage::GetWidth() const { return(m_dwWidth); } DWORD CImage::GetHeight() const { return(m_dwHeight); } Status CImage::GetLastStatus() const { return(m_Status); } //////////////////////////////////////////////////////////////////////////////////////// CBitmap::CBitmap(LONG width, LONG height, PixelFormat format) : CImage() { if(width <= 0 || height <= 0) { m_Status=InvalidParameter; return; } LONG lSize = 4 * width * height; m_pImgData = new BYTE[lSize]; if (m_pImgData) { memset(m_pImgData, 0, lSize); m_dwWidth = width; m_dwHeight = height; m_nStride = 4 * m_dwWidth; m_Status = Ok; } } CBitmap::CBitmap(LONG width, LONG height, LONG stride, PixelFormat format, BYTE* scan0) : CImage() { //Warning! This is not Gdiplus behavior; it returns Ok! if(width <= 0 || height <= 0 || stride == 0) { m_Status = InvalidParameter; return; } m_bExternalBuffer = true; if (stride > 0) { m_pImgData = scan0; } else { m_pImgData = scan0 + (height - 1) * (-stride); } m_dwWidth = width; m_dwHeight = height; m_nStride = stride; m_Status = Ok; } CBitmap::CBitmap(const std::wstring& filename) : CImage(filename) { } CBitmap::~CBitmap() { } void CBitmap::LockBits(const RectF* rect, PixelFormat format, CBitmapData* lockedBitmapData) { // TODO: return; } }<commit_msg>git-svn-id: svn://fileserver/activex/AVS/Sources/TeamlabOffice/trunk/ServerComponents@55215 954022d7-b5bf-4e40-9824-e11837661b57<commit_after>#include "Image.h" #include "../raster/BgraFrame.h" namespace Aggplus { //////////////////////////////////////////////////////////////////////////////////////// CImage::CImage() : m_dwWidth(0), m_dwHeight(0), m_nStride(0), m_pImgData(NULL), m_bExternalBuffer(false), m_Status(WrongState) { } CImage::CImage(const std::wstring& filename) : m_dwWidth(0), m_dwHeight(0), m_nStride(0), m_pImgData(NULL), m_bExternalBuffer(false) { Create(filename); } CImage::~CImage() { Destroy(); } void CImage::Create(const std::wstring& filename) { Destroy(); CBgraFrame oFrame; bool bOpen = oFrame.OpenFile(filename); if (bOpen) { m_pImgData = oFrame.get_Data(); m_dwWidth = (DWORD)oFrame.get_Width(); m_dwHeight = (DWORD)oFrame.get_Height(); m_nStride = oFrame.get_Stride(); m_Status = Ok; } oFrame.ClearNoAttack(); } void CImage::Destroy() { if (NULL != m_pImgData) { if (!m_bExternalBuffer) { delete [] m_pImgData; } } m_Status = WrongState; m_pImgData = NULL; m_dwWidth = 0; m_dwHeight = 0; m_nStride = 0; m_bExternalBuffer = false; } DWORD CImage::GetWidth() const { return(m_dwWidth); } DWORD CImage::GetHeight() const { return(m_dwHeight); } Status CImage::GetLastStatus() const { return(m_Status); } //////////////////////////////////////////////////////////////////////////////////////// CBitmap::CBitmap(LONG width, LONG height, PixelFormat format) : CImage() { if(width <= 0 || height <= 0) { m_Status=InvalidParameter; return; } LONG lSize = 4 * width * height; m_pImgData = new BYTE[lSize]; if (m_pImgData) { memset(m_pImgData, 0, lSize); m_dwWidth = width; m_dwHeight = height; m_nStride = 4 * m_dwWidth; m_Status = Ok; } } CBitmap::CBitmap(LONG width, LONG height, LONG stride, PixelFormat format, BYTE* scan0) : CImage() { //Warning! This is not Gdiplus behavior; it returns Ok! if(width <= 0 || height <= 0 || stride == 0) { m_Status = InvalidParameter; return; } m_bExternalBuffer = true; if (stride > 0) { m_pImgData = scan0; } else { m_pImgData = scan0 + (height - 1) * (-stride); } m_dwWidth = width; m_dwHeight = height; m_nStride = stride; m_Status = Ok; } CBitmap::CBitmap(const std::wstring& filename) : CImage(filename) { } CBitmap::~CBitmap() { } void CBitmap::LockBits(const RectF* rect, PixelFormat format, CBitmapData* lockedBitmapData) { // TODO: return; } } <|endoftext|>
<commit_before>/* * Copyright 2013 Matthew Harvey * * 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. */ // TODO HIGH PRIORITY Under KDE (at least on Mageia) the way I have set // up the widths of wxComboBox and wxTextCtrl and wxButton (in various // controls in which these feature), where they are // supposed to be the same height, they actually turn out to be slightly // different heights. However even if I manually set them all to the same // hard-coded height number, they still seem to come out different heights // on KDE. It doesn't make a lot of sense. // TODO MEDIUM PRIORITY Tooltips aren't showing on Windows. /// TODO MEDIUM PRIORITY The database file should perhaps have a checksum to // guard against its contents changing other than via the application. // TODO HIGH PRIORITY Facilitate automatic checking for updates from user's // machine, or at least provide an easy process for installing updates // via NSIS. It appears that the default configuration of CPack/NSIS is // such that updates will not overwrite existing files. Some manual NSIS // scripting may be required to enable this. Also take into account that // the user may have to restart their computer in the event that they have // files open while the installer (or "updater") is running (although I // \e think that the default configuration under CPack does this // automatically). // TODO HIGH PRIORITY Create a decent icon for the application. We want this // in both .ico form (for Windows executable icon) and .xpm // form (for icon for Frame). Note, when I exported my // "token icon" using GIMP to .ico format, and later used this // to create a double-clickable icon in Windows, only the text // on the icon appeared, and the background image became // transparent for some reason. Furthermore, when set as the // large in-windows icon in the CPack/NSIS installer, the icon // wasn't showing at all. Once decent icon is created, also make sure it is // pulled into the wxBitmap in SetupWizard. // TODO HIGH PRIORITY Create a better name for the application. // TODO HIGH PRIORITY Make the GUI display acceptably on smaller screen // i.e. laptop. // TODO MEDIUM PRIORITY Startup time under Windows is really slow, even when // compiled in Release mode. // TODO MEDIUM PRIORITY Give user the option to export to CSV. // TODO LOW PRIORITY Allow export/import to/from .qif (?) format. // TODO HIGH PRIORITY On Windows, at least on Windows 7, at least on some // machines, tab traversal is not working properly in SetupWizard, and you // can't traverse out of a wxComboBox using tab, for some reason. // TODO MEDIUM PRIORITY Allow window borders to be dragged around, especially // for DraftJournalListCtrl. This make it easier for users on laptops. // TODO HIGH PRIORITY User guide. // TODO MEDIUM PRIORITY When the user creates a new file, ask if they want to // create a shortcut to the file on their Desktop (assuming they didn't // actually create the file in their desktop). #include "app.hpp" #include <wx/app.h> wxIMPLEMENT_APP(phatbooks::App); <commit_msg>Updated a TODO.<commit_after>/* * Copyright 2013 Matthew Harvey * * 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. */ // TODO HIGH PRIORITY Under KDE (at least on Mageia) the way I have set // up the widths of wxComboBox and wxTextCtrl and wxButton (in various // controls in which these feature), where they are // supposed to be the same height, they actually turn out to be slightly // different heights. However even if I manually set them all to the same // hard-coded height number, they still seem to come out different heights // on KDE. It doesn't make a lot of sense. // TODO MEDIUM PRIORITY Tooltips aren't showing on Windows. /// TODO MEDIUM PRIORITY The database file should perhaps have a checksum to // guard against its contents changing other than via the application. // TODO HIGH PRIORITY Facilitate automatic checking for updates from user's // machine, or at least provide an easy process for installing updates // via NSIS. It appears that the default configuration of CPack/NSIS is // such that updates will not overwrite existing files. Some manual NSIS // scripting may be required to enable this. Also take into account that // the user may have to restart their computer in the event that they have // files open while the installer (or "updater") is running (although I // \e think that the default configuration under CPack does this // automatically). // TODO HIGH PRIORITY Create a decent icon for the application. We want this // in both .ico form (for Windows executable icon) and .xpm // form (for icon for Frame). Note, when I exported my // "token icon" using GIMP to .ico format, and later used this // to create a double-clickable icon in Windows, only the text // on the icon appeared, and the background image became // transparent for some reason. Furthermore, when set as the // large in-windows icon in the CPack/NSIS installer, the icon // wasn't showing at all. Once decent icon is created, also make sure it is // pulled into the wxBitmap in SetupWizard. // TODO HIGH PRIORITY Create a better name for the application. // TODO HIGH PRIORITY Make the GUI display acceptably on smaller screen // i.e. laptop. // TODO MEDIUM PRIORITY Startup time under Windows is really slow, even when // compiled in Release mode. // TODO MEDIUM PRIORITY Give user the option to export to CSV. // TODO LOW PRIORITY Allow export/import to/from .qif (?) format. // TODO HIGH PRIORITY On Windows, at least on Windows 7, at least on some // machines, tab traversal is not working properly in SetupWizard, and you // can't traverse out of a wxComboBox using tab, for some reason. Have now // created phatbooks::gui::ComboBox class and substituted it for // wxComboBox class throughout; but still need to write event interception // code to handle tab key presses manually in ComboBox class, and hopefully // this will fix it. // TODO MEDIUM PRIORITY Allow window borders to be dragged around, especially // for DraftJournalListCtrl. This make it easier for users on laptops. // TODO HIGH PRIORITY User guide. // TODO MEDIUM PRIORITY When the user creates a new file, ask if they want to // create a shortcut to the file on their Desktop (assuming they didn't // actually create the file in their desktop). #include "app.hpp" #include <wx/app.h> wxIMPLEMENT_APP(phatbooks::App); <|endoftext|>
<commit_before>#include "PDL.h" #include "SDL.h" #include "SDL_image.h" #include "chipmunk/chipmunk.h" #include <iostream> #include <vector> using namespace std; const float FRAMES_PER_SECOND = 60.0; const int SCREEN_WIDTH = 320; const int SCREEN_HEIGHT = 480; const int PADDING = 20; const int GRAVITY = 600; // gravity strength // making these global because I'm lazy SDL_Surface *screen; SDL_Surface *ball; void updateShape(void*, void*); void defineBorders(cpSpace*); int main(int argc, char* argv[]) { bool in_loop = true; float xForce; float yForce; // SDL setup SDL_Init(SDL_INIT_VIDEO | SDL_INIT_JOYSTICK); screen = SDL_SetVideoMode(SCREEN_WIDTH, SCREEN_HEIGHT, 32, 0); if (screen == NULL) return -1; SDL_Event event; SDL_Joystick *joystick = SDL_JoystickOpen(0); ball = IMG_Load("assets/ball.gif"); // chipmunk setup cpSpace *space; cpBody *body; cpInitChipmunk(); space = cpSpaceNew(); space->iterations = 10; space->elasticIterations = 10; space->gravity = cpv(0, GRAVITY); defineBorders(space); // gameloop while (in_loop) { // get data from the accelerometer xForce = (float) SDL_JoystickGetAxis(joystick, 0) / 32768.0; yForce = (float) SDL_JoystickGetAxis(joystick, 1) / 32768.0; space->gravity = cpv(xForce * GRAVITY, yForce * GRAVITY); // capture the events and send the relevent tap events to the game scene while (SDL_PollEvent(&event)) { if (event.type == SDL_QUIT) in_loop = false; else if (event.type == SDL_MOUSEBUTTONDOWN) { if ((event.motion.x > PADDING && event.motion.x < SCREEN_WIDTH - PADDING) && (event.motion.y > PADDING && event.motion.y < SCREEN_HEIGHT - PADDING)) { body = cpBodyNew(10.0f, INFINITY); body->p = cpv(event.motion.x, event.motion.y); cpSpaceAddBody(space, body); cpShape *shape = cpSpaceAddShape(space, cpCircleShapeNew(body, 20.0, cpvzero)); shape->e = 0.3f; shape->u = 0.1f; } } } // clear the screen SDL_FillRect(SDL_GetVideoSurface(), NULL, 0); // recalculate the physics objects cpSpaceStep(space, 1.0f/FRAMES_PER_SECOND); cpSpaceHashEach(space->activeShapes, &updateShape, NULL); // update the display SDL_Flip(screen); } // shutdown Chipmunk cpSpaceFreeChildren(space); cpSpaceFree(space); // shutdown SDL SDL_FreeSurface(ball); PDL_Quit(); SDL_Quit(); return 0; } // update a shape's visual representation void updateShape(void *ptr, void* unused) { cpShape *shape = (cpShape*)ptr; // make sure the shape is constructed correctly if(shape == NULL || shape->body == NULL) { return; } // Use a temporary rectangle to pass our x and y to the offsets when blitting SDL_Rect offset; offset.x = shape->body->p.x; offset.y = shape->body->p.y; SDL_BlitSurface(ball, NULL, screen, &offset); } // create borders around the screen void defineBorders(cpSpace *space) { cpBody *body = cpBodyNew(INFINITY, INFINITY); float border_elasticity = 0.3f; float border_friction = 1.0f; // top border cpShape *border_top = cpSegmentShapeNew(body, cpv(PADDING, PADDING), cpv(SCREEN_WIDTH - PADDING, PADDING), 1.0f); border_top->e = border_elasticity; border_top->u = border_friction; cpSpaceAddStaticShape(space, border_top); // right border cpShape *border_right = cpSegmentShapeNew(body, cpv(SCREEN_WIDTH - PADDING, PADDING), cpv(SCREEN_WIDTH - PADDING, SCREEN_HEIGHT - PADDING), 1.0f); border_right->e = border_elasticity; border_right->u = border_friction; cpSpaceAddStaticShape(space, border_right); // bottom border cpShape *border_bottom = cpSegmentShapeNew(body, cpv(PADDING, SCREEN_HEIGHT - PADDING), cpv(SCREEN_WIDTH - PADDING, SCREEN_HEIGHT - PADDING), 1.0f); border_bottom->e = border_elasticity; border_bottom->u = border_friction; cpSpaceAddStaticShape(space, border_bottom); // left border cpShape *border_left = cpSegmentShapeNew(body, cpv(PADDING, PADDING), cpv(PADDING, SCREEN_HEIGHT - PADDING), 1.0f); border_left->e = border_elasticity; border_left->u = border_friction; cpSpaceAddStaticShape(space, border_left); }<commit_msg>Fixed the border padding to so the balls can touch the edges of the screen<commit_after>#include "PDL.h" #include "SDL.h" #include "SDL_image.h" #include "chipmunk/chipmunk.h" #include <iostream> #include <vector> using namespace std; const float FRAMES_PER_SECOND = 60.0; const int SCREEN_WIDTH = 320; const int SCREEN_HEIGHT = 480; const int PADDING = 20; const int GRAVITY = 600; // gravity strength // making these global because I'm lazy SDL_Surface *screen; SDL_Surface *ball; void updateShape(void*, void*); void defineBorders(cpSpace*); int main(int argc, char* argv[]) { bool in_loop = true; float xForce; float yForce; // SDL setup SDL_Init(SDL_INIT_VIDEO | SDL_INIT_JOYSTICK); screen = SDL_SetVideoMode(SCREEN_WIDTH, SCREEN_HEIGHT, 32, 0); if (screen == NULL) return -1; SDL_Event event; SDL_Joystick *joystick = SDL_JoystickOpen(0); ball = IMG_Load("assets/ball.gif"); // chipmunk setup cpSpace *space; cpBody *body; cpInitChipmunk(); space = cpSpaceNew(); space->iterations = 10; space->elasticIterations = 10; space->gravity = cpv(0, GRAVITY); defineBorders(space); // gameloop while (in_loop) { // get data from the accelerometer xForce = (float) SDL_JoystickGetAxis(joystick, 0) / 32768.0; yForce = (float) SDL_JoystickGetAxis(joystick, 1) / 32768.0; space->gravity = cpv(xForce * GRAVITY, yForce * GRAVITY); // capture the events and send the relevent tap events to the game scene while (SDL_PollEvent(&event)) { if (event.type == SDL_QUIT) in_loop = false; else if (event.type == SDL_MOUSEBUTTONDOWN) { if ((event.motion.x > PADDING && event.motion.x < SCREEN_WIDTH - PADDING) && (event.motion.y > PADDING && event.motion.y < SCREEN_HEIGHT - PADDING)) { body = cpBodyNew(10.0f, INFINITY); body->p = cpv(event.motion.x, event.motion.y); cpSpaceAddBody(space, body); cpShape *shape = cpSpaceAddShape(space, cpCircleShapeNew(body, 20.0, cpvzero)); shape->e = 0.3f; shape->u = 0.1f; } } } // clear the screen SDL_FillRect(SDL_GetVideoSurface(), NULL, 0); // recalculate the physics objects cpSpaceStep(space, 1.0f/FRAMES_PER_SECOND); cpSpaceHashEach(space->activeShapes, &updateShape, NULL); // update the display SDL_Flip(screen); } // shutdown Chipmunk cpSpaceFreeChildren(space); cpSpaceFree(space); // shutdown SDL SDL_FreeSurface(ball); PDL_Quit(); SDL_Quit(); return 0; } // update a shape's visual representation void updateShape(void *ptr, void* unused) { cpShape *shape = (cpShape*)ptr; // make sure the shape is constructed correctly if(shape == NULL || shape->body == NULL) { return; } // Use a temporary rectangle to pass our x and y to the offsets when blitting SDL_Rect offset; offset.x = shape->body->p.x; offset.y = shape->body->p.y; SDL_BlitSurface(ball, NULL, screen, &offset); } // create borders around the screen void defineBorders(cpSpace *space) { cpBody *body = cpBodyNew(INFINITY, INFINITY); float border_elasticity = 0.3f; float border_friction = 1.0f; // top border cpShape *border_top = cpSegmentShapeNew(body, cpv(-PADDING, -PADDING), cpv(SCREEN_WIDTH - PADDING, -PADDING), 1.0f); border_top->e = border_elasticity; border_top->u = border_friction; cpSpaceAddStaticShape(space, border_top); // right border cpShape *border_right = cpSegmentShapeNew(body, cpv(SCREEN_WIDTH - PADDING, -PADDING), cpv(SCREEN_WIDTH - PADDING, SCREEN_HEIGHT - PADDING), 1.0f); border_right->e = border_elasticity; border_right->u = border_friction; cpSpaceAddStaticShape(space, border_right); // bottom border cpShape *border_bottom = cpSegmentShapeNew(body, cpv(-PADDING, SCREEN_HEIGHT - PADDING), cpv(SCREEN_WIDTH - PADDING, SCREEN_HEIGHT - PADDING), 1.0f); border_bottom->e = border_elasticity; border_bottom->u = border_friction; cpSpaceAddStaticShape(space, border_bottom); // left border cpShape *border_left = cpSegmentShapeNew(body, cpv(-PADDING, -PADDING), cpv(-PADDING, SCREEN_HEIGHT - PADDING), 1.0f); border_left->e = border_elasticity; border_left->u = border_friction; cpSpaceAddStaticShape(space, border_left); }<|endoftext|>
<commit_before>#include <stdio.h> #include <getopt.h> #include <string.h> #include <unistd.h> #include "ftdi.hpp" #include "dionysus.hpp" #include "gpio.hpp" #include "arduino.hpp" #define PROGRAM_NAME "dionysus-ftdi" #define MEMORY_TEST false //5 seconds #define GPIO_TEST_WAIT 10 using namespace Ftdi; #define DEFAULT_ARGUMENTS \ { \ .vendor = DIONYSUS_VID, \ .product = DIONYSUS_PID, \ .debug = false \ } struct arguments { int vendor; int product; bool debug; }; static double TimevalDiff(const struct timeval *a, const struct timeval *b) { return (a->tv_sec - b->tv_sec) + 1e-6 * (a->tv_usec - b->tv_usec); } static void usage (int exit_status){ fprintf (exit_status == EXIT_SUCCESS ? stdout : stderr, "\n" "USAGE: %s [-v <vendor>] [-p <product>] [-d]\n" "\n" "Options:\n" " -h, --help\n" "\tPrints this helpful message\n" " -d, --debug\n" "\tEnable Debug output\n" " -v, --vendor\n" "\tSpecify an alternate vendor ID (in hex) to use (Default: %04X)\n" " -p, --product\n" "\tSpecify an alternate product ID (in hex) to use (Default: %04X)\n" , PROGRAM_NAME, DIONYSUS_VID, DIONYSUS_PID); exit(exit_status); } static void parse_args(struct arguments* args, int argc, char *const argv[]){ int print_usage = 0; const char shortopts[] = "hdv:p:"; struct option longopts[5]; longopts[0].name = "help"; longopts[0].has_arg = no_argument; longopts[0].flag = NULL; longopts[0].val = 'h'; longopts[1].name = "debug"; longopts[1].has_arg = no_argument; longopts[1].flag = NULL; longopts[1].val = 'd'; longopts[2].name = "vendor"; longopts[2].has_arg = required_argument; longopts[2].flag = NULL; longopts[2].val = 'v'; longopts[3].name = "help"; longopts[3].has_arg = required_argument; longopts[3].flag = NULL; longopts[3].val = 'p'; longopts[4].name = 0; longopts[4].has_arg = 0; longopts[4].flag = 0; longopts[4].val = 0; while (1) { int option_idx = 0; int c = getopt_long(argc, argv, shortopts, longopts, &option_idx); if (c == -1){ break; } switch (c){ case 0: /* no arguments */ if (print_usage){ usage(EXIT_SUCCESS); } break; case 'h': usage(EXIT_SUCCESS); break; case 'd': printf ("debug enabled\n"); args->debug = true; break; case 'v': args->vendor = strtol(optarg, (char**)0, 16); break; case 'p': args->product = strtol(optarg, (char**)0, 16); break; case '?': /* Fall through */ default: printf ("Unknown Command\n"); usage (EXIT_FAILURE); break; } } } void breath(GPIO *g, uint32_t timeout){ struct timeval test_start; struct timeval test_now; double interval = 1.0; gettimeofday(&test_start, NULL); gettimeofday(&test_now, NULL); uint32_t period; uint32_t max_val = 10; uint32_t current = 0; uint32_t position = 0; uint32_t delay_count = 0; uint32_t delay = 0; uint8_t direction = 1; printf ("Breath\n"); printf ("Max value: %d\n", max_val); while (interval < GPIO_TEST_WAIT){ if (direction){ if (current < max_val){ if (position < max_val) { //printf ("pos++\n"); position++; } else { //printf ("position = 0\n"); position = 0; if (delay_count < delay){ delay_count++; } else { //printf ("increment count\n"); delay_count = 0; current++; } } } else { //printf ("go down\n"); direction = 0; } } else { if (current > 0){ if (position < max_val){ position++; } else { position = 0; if (delay_count < delay){ delay_count++; } else { delay_count = 0; current--; } } } else { //printf ("go up\n"); direction = 1; } } if (position < current){ //printf ("HI\n"); //g->digitalWrite(0, LOW); g->set_gpios(0x00000002); } else { //printf ("LOW\n"); g->set_gpios(0x00000001); //g->digitalWrite(0, HIGH); } gettimeofday(&test_now, NULL); interval = TimevalDiff(&test_now, &test_start); } }; void test_gpios(Nysa *nysa, uint32_t dev_index, bool debug){ if (dev_index == 0){ printf ("Device index == 0!, this is the DRT!"); } struct timeval test_start; struct timeval test_now; double interval = 1.0; double led_interval = 1.0; printf ("Setting up new gpio device\n"); //Setup GPIO GPIO *gpio = new GPIO(nysa, dev_index, debug); printf ("Got new GPIO Device\n"); try { gpio->pinMode(0, OUTPUT); //LED 0 gpio->pinMode(1, OUTPUT); //LED 1 gpio->pinMode(2, INPUT); //Button 0 gpio->pinMode(3, INPUT); //Button 1 } catch (int e) { printf ("Error while setting pinMode: Error: %d\n", e); } printf ("set pin modes!\n"); //Length of GPIO tests gettimeofday(&test_start, NULL); gettimeofday(&test_now, NULL); //Pulse width of the LED interval = TimevalDiff(&test_now, &test_start); printf ("Interval: %f\n", interval); breath(gpio, GPIO_TEST_WAIT); /* while (interval < GPIO_TEST_WAIT){ gpio->toggle(0); usleep(1000000); gettimeofday(&test_now, NULL); interval = TimevalDiff(&test_now, &test_start); //printf ("Interval: %f\n", interval); } */ //Loop for about two seconds printf ("Set 0 to high\n"); gpio->digitalWrite(0, LOW); gpio->digitalWrite(1, LOW); } int main(int argc, char **argv){ struct arguments args; args.vendor = DIONYSUS_VID; args.product = DIONYSUS_PID; args.debug = false; uint8_t* buffer = new uint8_t [8196]; uint32_t num_devices; uint32_t device_type = 0; uint32_t device_addres = 0; uint32_t device_size = 0; bool memory_device = false; bool fail = false; uint32_t fail_count = 0; struct timeval start; struct timeval end; double interval = 1.0; double mem_size; double rate = 0; uint32_t memory_device_index = 0; parse_args(&args, argc, argv); //Dionysus dionysus = Dionysus((uint32_t)DEFAULT_BUFFER_SIZE, args.debug); Dionysus dionysus = Dionysus(args.debug); dionysus.open(args.vendor, args.product); if (dionysus.is_open()){ dionysus.reset(); //dionysus.program_fpga(); //dionysus.soft_reset(); gettimeofday(&start, NULL); dionysus.ping(); gettimeofday(&end, NULL); interval = TimevalDiff(&end, &start); rate = 9 / interval; //Megabytes/Sec printf ("Time difference: %f\n", interval); printf ("Ping Rate: %.2f Bytes/Sec\n", rate); printf ("Reading from the DRT\n"); //dionysus.read_periph_data(0, 0, buffer, 32); dionysus.read_drt(); for (int i = 1; i < dionysus.get_drt_device_count() + 1; i++){ printf ("Device %d:\n", i); printf ("\tType:\t\t0x%08X\n", dionysus.get_drt_device_type(i)); printf ("\tSize:\t\t0x%08X (32-bit values)\n", dionysus.get_drt_device_size(i)); printf ("\tAddress:\t0x%08X\n", dionysus.get_drt_device_addr(i)); if (dionysus.is_memory_device(i)){ printf ("\t\tOn the memory bus\n"); } } //Buffer Data: //for (int i = 0; i < 32; i++){ // printf ("%02X ", buffer[i]); //} printf ("\n"); //dionysus.read_periph_data(0, 0, buffer, 4096); printf ("Peripheral Write Test. read a lot of data from the DRT\n"); printf ("\t(DRT will just ignore this data)\n"); dionysus.write_periph_data(0, 0, buffer, 8192); printf ("Peripheral Read Test. Read a lot of data from the DRT\n"); printf ("\t(Data from the DRT will just loop)\n"); dionysus.read_periph_data(0, 0, buffer, 8192); delete(buffer); printf ("Look for a memory device\n"); if (MEMORY_TEST){ for (int i = 1; i < dionysus.get_drt_device_count() + 1; i++){ if (dionysus.get_drt_device_type(i) == 5){ memory_device_index = i; } } } if (memory_device_index > 0){ printf ("Found a memory device at position: %d\n", memory_device_index); printf ("Memory Test! Read and write: 0x%08X Bytes\n", dionysus.get_drt_device_size(memory_device_index)); buffer = new uint8_t[dionysus.get_drt_device_size(memory_device_index)]; for (int i = 0; i < dionysus.get_drt_device_size(memory_device_index); i++){ buffer[i] = i; } printf ("Testing Full Memory Write Time...\n"); gettimeofday(&start, NULL); dionysus.write_memory(0x00000000, buffer, dionysus.get_drt_device_size(memory_device_index)); gettimeofday(&end, NULL); interval = TimevalDiff(&end, &start); mem_size = dionysus.get_drt_device_size(memory_device_index); rate = mem_size/ interval / 1e6; //Megabytes/Sec printf ("Time difference: %f\n", interval); printf ("Write Rate: %.2f MB/Sec\n", rate); for (int i = 0; i < dionysus.get_drt_device_size(memory_device_index); i++){ buffer[i] = 0; } gettimeofday(&start, NULL); dionysus.read_memory(0x00000000, buffer, dionysus.get_drt_device_size(memory_device_index)); gettimeofday(&end, NULL); interval = TimevalDiff(&end, &start); mem_size = dionysus.get_drt_device_size(memory_device_index); rate = mem_size/ interval / 1e6; //Megabytes/Sec printf ("Time difference: %f\n", interval); printf ("Read Rate: %.2f MB/Sec\n", rate); for (int i = 0; i < dionysus.get_drt_device_size(memory_device_index); i++){ if (buffer[i] != i % 256){ if (!fail){ if (fail_count > 16){ fail = true; } fail_count += 1; printf ("Failed @ 0x%08X\n", i); printf ("Value should be: 0x%08X but is: 0x%08X\n", i, buffer[i]); } } } if (!fail){ printf ("Memory Test Passed!\n"); } delete (buffer); } uint32_t gpio_device = 0; for (int i = 1; i < dionysus.get_drt_device_count() + 1; i++){ if (dionysus.get_drt_device_type(i) == get_gpio_device_type()){ gpio_device = i; } } if (gpio_device > 0){ test_gpios(&dionysus, gpio_device, args.debug); } dionysus.close(); } return 0; } <commit_msg>Added more command line controls<commit_after>#include <stdio.h> #include <getopt.h> #include <string.h> #include <unistd.h> #include "ftdi.hpp" #include "dionysus.hpp" #include "gpio.hpp" #include "arduino.hpp" #define PROGRAM_NAME "dionysus-nysa-test" #define MEMORY_TEST false //5 seconds #define GPIO_TEST_WAIT 10 using namespace Ftdi; #define DEFAULT_ARGUMENTS \ { \ .vendor = DIONYSUS_VID, \ .product = DIONYSUS_PID, \ .debug = false \ } struct arguments { int vendor; int product; bool debug; bool leds; bool buttons; bool memory; }; static double TimevalDiff(const struct timeval *a, const struct timeval *b) { return (a->tv_sec - b->tv_sec) + 1e-6 * (a->tv_usec - b->tv_usec); } static void usage (int exit_status){ fprintf (exit_status == EXIT_SUCCESS ? stdout : stderr, "\n" "USAGE: %s [-v <vendor>] [-p <product>] [-d] [-12m]\n" "\n" "Options:\n" "-h, --help\n" "\tPrints this helpful message\n" "-d, --debug\n" "\tEnable Debug output\n" "-v, --vendor\n" "\tSpecify an alternate vendor ID (in hex) to use (Default: %04X)\n" "-p, --product\n" "\tSpecify an alternate product ID (in hex) to use (Default: %04X)\n" "-l, --leds\n" "\tleds test (Breathing)\n" "-b, --buttons\n" "\tbuttons test (Button Interrupt)\n" "-m, --memory\n" "\tMemory Test\n" , PROGRAM_NAME, DIONYSUS_VID, DIONYSUS_PID); exit(exit_status); } static void parse_args(struct arguments* args, int argc, char *const argv[]){ int print_usage = 0; const char shortopts[] = "hdv:p:lbm"; struct option longopts[8]; longopts[0].name = "help"; longopts[0].has_arg = no_argument; longopts[0].flag = NULL; longopts[0].val = 'h'; longopts[1].name = "debug"; longopts[1].has_arg = no_argument; longopts[1].flag = NULL; longopts[1].val = 'd'; longopts[2].name = "vendor"; longopts[2].has_arg = required_argument; longopts[2].flag = NULL; longopts[2].val = 'v'; longopts[3].name = "help"; longopts[3].has_arg = required_argument; longopts[3].flag = NULL; longopts[3].val = 'p'; longopts[4].name = "leds"; longopts[4].has_arg = no_argument; longopts[4].flag = NULL; longopts[4].val = 'l'; longopts[5].name = "buttons"; longopts[5].has_arg = no_argument; longopts[5].flag = NULL; longopts[5].val = 'b'; longopts[6].name = "memory"; longopts[6].has_arg = no_argument; longopts[6].flag = NULL; longopts[6].val = '2'; longopts[7].name = 0; longopts[7].has_arg = 0; longopts[7].flag = 0; longopts[7].val = 0; while (1) { int option_idx = 0; int c = getopt_long(argc, argv, shortopts, longopts, &option_idx); if (c == -1){ break; } switch (c){ case 0: /* no arguments */ if (print_usage){ usage(EXIT_SUCCESS); } break; case 'h': usage(EXIT_SUCCESS); break; case 'd': printf ("debug enabled\n"); args->debug = true; break; case 'v': args->vendor = strtol(optarg, (char**)0, 16); break; case 'p': args->product = strtol(optarg, (char**)0, 16); break; case 'l': args->leds = true; break; case 'b': args->buttons = true; break; case 'm': args->memory = true; break; case '?': /* Fall through */ default: printf ("Unknown Command\n"); usage (EXIT_FAILURE); break; } } } void breath(GPIO *g, uint32_t timeout){ struct timeval test_start; struct timeval test_now; double interval = 1.0; gettimeofday(&test_start, NULL); gettimeofday(&test_now, NULL); uint32_t period; uint32_t max_val = 4; uint32_t current = 0; uint32_t position = 0; uint32_t delay_count = 0; uint32_t delay = 4; uint8_t direction = 1; printf ("Breath\n"); printf ("Max value: %d\n", max_val); while (interval < GPIO_TEST_WAIT){ if (direction){ if (current < max_val){ if (position < max_val) { position++; } else { position = 0; if (delay_count < delay){ delay_count++; } else { delay_count = 0; current++; } } } else { direction = 0; } } else { if (current > 0){ if (position < max_val){ position++; } else { position = 0; if (delay_count < delay){ delay_count++; } else { delay_count = 0; current--; } } } else { //printf ("go up\n"); direction = 1; } } if (position < current){ g->set_gpios(0x00000002); } else { g->set_gpios(0x00000001); } gettimeofday(&test_now, NULL); interval = TimevalDiff(&test_now, &test_start); } }; void test_buttons(Nysa *nysa, uint32_t dev_index, bool debug){ uint32_t interrupts = 0; if (dev_index == 0){ printf ("Device index == 0!, this is the DRT!"); } printf ("Setting up new gpio device\n"); //Setup GPIO GPIO *gpio = new GPIO(nysa, dev_index, debug); printf ("Got new GPIO Device\n"); gpio->pinMode(0, OUTPUT); //LED 0 gpio->pinMode(1, OUTPUT); //LED 1 gpio->pinMode(2, INPUT); //Button 0 gpio->pinMode(3, INPUT); //Button 1 gpio->set_interrupts_enable(0x0000000C); gpio->set_interrupts_edge_mask(0x0000000C); //gpio->set_interrupts_edge_mask(0x00000000); printf ("set pin modes!\n"); //Pulse width of the LED printf ("Waiting for button press...\n"); //wait 10 seconds printf ("Buttons: 0x%08X\n", gpio->get_gpios()); gpio->get_interrupts(); printf ("Interrupts: 0x%08X\n", gpio->get_interrupts()); nysa->wait_for_interrupts(GPIO_TEST_WAIT * 1000, &interrupts); printf ("Interrupts: 0x%08X\n", interrupts); if (gpio->is_interrupt_for_device(interrupts)){ printf ("GPIO interrupts: 0x%08X\n", gpio->get_interrupts()); printf ("Found interrupts for GPIOs: 0x%08X\n", gpio->get_gpios()); } printf ("Set 0 to high\n"); gpio->digitalWrite(0, LOW); gpio->digitalWrite(1, LOW); delete(gpio); } int main(int argc, char **argv){ struct arguments args; args.vendor = DIONYSUS_VID; args.product = DIONYSUS_PID; args.debug = false; args.leds = false; args.buttons = false; args.memory = false; uint8_t* buffer = new uint8_t [8196]; uint32_t num_devices; uint32_t device_type = 0; uint32_t device_addres = 0; uint32_t device_size = 0; bool memory_device = false; bool fail = false; uint32_t fail_count = 0; struct timeval start; struct timeval end; double interval = 1.0; double mem_size; double rate = 0; uint32_t memory_device_index = 0; parse_args(&args, argc, argv); //Dionysus dionysus = Dionysus((uint32_t)DEFAULT_BUFFER_SIZE, args.debug); Dionysus dionysus = Dionysus(args.debug); dionysus.open(args.vendor, args.product); if (dionysus.is_open()){ dionysus.reset(); //dionysus.program_fpga(); //dionysus.soft_reset(); gettimeofday(&start, NULL); dionysus.ping(); gettimeofday(&end, NULL); interval = TimevalDiff(&end, &start); rate = 9 / interval; //Megabytes/Sec printf ("Time difference: %f\n", interval); printf ("Ping Rate: %.2f Bytes/Sec\n", rate); printf ("Reading from the DRT\n"); //dionysus.read_periph_data(0, 0, buffer, 32); dionysus.read_drt(); for (int i = 1; i < dionysus.get_drt_device_count() + 1; i++){ printf ("Device %d:\n", i); printf ("\tType:\t\t0x%08X\n", dionysus.get_drt_device_type(i)); printf ("\tSize:\t\t0x%08X (32-bit values)\n", dionysus.get_drt_device_size(i)); printf ("\tAddress:\t0x%08X\n", dionysus.get_drt_device_addr(i)); if (dionysus.is_memory_device(i)){ printf ("\t\tOn the memory bus\n"); } } //Buffer Data: //for (int i = 0; i < 32; i++){ // printf ("%02X ", buffer[i]); //} printf ("\n"); //dionysus.read_periph_data(0, 0, buffer, 4096); printf ("Peripheral Write Test. read a lot of data from the DRT\n"); printf ("\t(DRT will just ignore this data)\n"); dionysus.write_periph_data(0, 0, buffer, 8192); printf ("Peripheral Read Test. Read a lot of data from the DRT\n"); printf ("\t(Data from the DRT will just loop)\n"); dionysus.read_periph_data(0, 0, buffer, 8192); delete(buffer); printf ("Look for a memory device\n"); if (args.memory){ for (int i = 1; i < dionysus.get_drt_device_count() + 1; i++){ if (dionysus.get_drt_device_type(i) == 5){ memory_device_index = i; } } } if (memory_device_index > 0){ printf ("Found a memory device at position: %d\n", memory_device_index); printf ("Memory Test! Read and write: 0x%08X Bytes\n", dionysus.get_drt_device_size(memory_device_index)); buffer = new uint8_t[dionysus.get_drt_device_size(memory_device_index)]; for (int i = 0; i < dionysus.get_drt_device_size(memory_device_index); i++){ buffer[i] = i; } printf ("Testing Full Memory Write Time...\n"); gettimeofday(&start, NULL); dionysus.write_memory(0x00000000, buffer, dionysus.get_drt_device_size(memory_device_index)); gettimeofday(&end, NULL); interval = TimevalDiff(&end, &start); mem_size = dionysus.get_drt_device_size(memory_device_index); rate = mem_size/ interval / 1e6; //Megabytes/Sec printf ("Time difference: %f\n", interval); printf ("Write Rate: %.2f MB/Sec\n", rate); for (int i = 0; i < dionysus.get_drt_device_size(memory_device_index); i++){ buffer[i] = 0; } gettimeofday(&start, NULL); dionysus.read_memory(0x00000000, buffer, dionysus.get_drt_device_size(memory_device_index)); gettimeofday(&end, NULL); interval = TimevalDiff(&end, &start); mem_size = dionysus.get_drt_device_size(memory_device_index); rate = mem_size/ interval / 1e6; //Megabytes/Sec printf ("Time difference: %f\n", interval); printf ("Read Rate: %.2f MB/Sec\n", rate); for (int i = 0; i < dionysus.get_drt_device_size(memory_device_index); i++){ if (buffer[i] != i % 256){ if (!fail){ if (fail_count > 16){ fail = true; } fail_count += 1; printf ("Failed @ 0x%08X\n", i); printf ("Value should be: 0x%08X but is: 0x%08X\n", i, buffer[i]); } } } if (!fail){ printf ("Memory Test Passed!\n"); } delete (buffer); } uint32_t gpio_device = 0; for (int i = 1; i < dionysus.get_drt_device_count() + 1; i++){ if (dionysus.get_drt_device_type(i) == get_gpio_device_type()){ gpio_device = i; } } if (gpio_device > 0){ if (args.buttons){ printf ("Testing buttons...\n"); test_buttons(&dionysus, gpio_device, args.debug); } if (args.leds){ GPIO *gpio = new GPIO(&dionysus, gpio_device, args.debug); gpio->pinMode(0, OUTPUT); //LED 0 gpio->pinMode(1, OUTPUT); //LED 1 gpio->pinMode(2, INPUT); //Button 0 gpio->pinMode(3, INPUT); //Button 1 breath(gpio, GPIO_TEST_WAIT); gpio->digitalWrite(0, LOW); gpio->digitalWrite(1, LOW); delete(gpio); } } dionysus.close(); } return 0; } <|endoftext|>
<commit_before>/* * noise≈ * Noiselator object for Jamoma Multicore * Copyright © 2008 by Timothy Place * * License: This code is licensed under the terms of the GNU LGPL * http://www.gnu.org/licenses/lgpl.html */ #include "maxMulticore.h" // Data Structure for this object typedef struct Noise { t_object obj; TTMulticoreObjectPtr multicoreObject; TTPtr multicoreOutlet; float mGain; SymbolPtr attrMode; }; typedef Noise* NoisePtr; // Prototypes for methods NoisePtr NoiseNew(SymbolPtr msg, AtomCount argc, AtomPtr argv); void NoiseFree(NoisePtr self); void NoiseAssist(NoisePtr self, void* b, long msg, long arg, char* dst); TTErr NoiseReset(NoisePtr self); TTErr NoiseSetup(NoisePtr self); MaxErr NoiseSetMode(NoisePtr self, void* attr, AtomCount argc, AtomPtr argv); MaxErr NoiseSetGain(NoisePtr self, void* attr, AtomCount argc, AtomPtr argv); // Globals static ClassPtr sNoiseClass; /************************************************************************************/ // Main() Function int main(void) { ClassPtr c; TTMulticoreInit(); common_symbols_init(); c = class_new("jcom.noise≈", (method)NoiseNew, (method)NoiseFree, sizeof(Noise), (method)0L, A_GIMME, 0); class_addmethod(c, (method)NoiseReset, "multicore.reset", A_CANT, 0); class_addmethod(c, (method)NoiseSetup, "multicore.setup", A_CANT, 0); class_addmethod(c, (method)NoiseAssist, "assist", A_CANT, 0); class_addmethod(c, (method)object_obex_dumpout, "dumpout", A_CANT, 0); CLASS_ATTR_SYM(c, "mode", 0, Noise, attrMode); CLASS_ATTR_ACCESSORS(c, "mode", NULL, NoiseSetMode); CLASS_ATTR_ENUM(c, "mode", 0, "white pink brown blue"); CLASS_ATTR_FLOAT(c, "gain", 0, Noise, mGain); CLASS_ATTR_ACCESSORS(c, "gain", NULL, NoiseSetGain); class_register(_sym_box, c); sNoiseClass = c; return 0; } /************************************************************************************/ // Object Creation Method NoisePtr NoiseNew(SymbolPtr msg, AtomCount argc, AtomPtr argv) { NoisePtr self = NoisePtr(object_alloc(sNoiseClass)); TTValue v; TTErr err; if (self) { v.setSize(2); v.set(0, TT("noise")); v.set(1, TTUInt32(1)); err = TTObjectInstantiate(TT("multicore.object"), (TTObjectPtr*)&self->multicoreObject, v); self->multicoreObject->addFlag(kTTMulticoreGenerator); attr_args_process(self, argc, argv); object_obex_store((void*)self, _sym_dumpout, (object*)outlet_new(self, NULL)); self->multicoreOutlet = outlet_new((t_pxobject*)self, "multicore.connect"); } return self; } // Memory Deallocation void NoiseFree(NoisePtr self) { TTObjectRelease((TTObjectPtr*)&self->multicoreObject); } /************************************************************************************/ // Methods bound to input/inlets // Method for Assistance Messages void NoiseAssist(NoisePtr self, void* b, long msg, long arg, char* dst) { if (msg==1) // Inlets strcpy(dst, "multichannel audio connection and control messages"); else if (msg==2) { // Outlets if (arg == 0) strcpy(dst, "multichannel audio connection"); else strcpy(dst, "dumpout"); } } TTErr NoiseReset(NoisePtr self) { return self->multicoreObject->reset(); } TTErr NoiseSetup(NoisePtr self) { Atom a[2]; atom_setobj(a+0, ObjectPtr(self->multicoreObject)); atom_setlong(a+1, 0); outlet_anything(self->multicoreOutlet, gensym("multicore.connect"), 2, a); return kTTErrNone; } MaxErr NoiseSetGain(NoisePtr self, void* attr, AtomCount argc, AtomPtr argv) { if (argc) { self->mGain = atom_getfloat(argv); self->multicoreObject->mUnitGenerator->setAttributeValue(TT("Gain"), self->mGain); } return MAX_ERR_NONE; } MaxErr NoiseSetMode(NoisePtr self, void* attr, AtomCount argc, AtomPtr argv) { if (argc) { self->attrMode = atom_getsym(argv); self->multicoreObject->mUnitGenerator->setAttributeValue(TT("Mode"), TT(self->attrMode->s_name)); } return MAX_ERR_NONE; } <commit_msg>noise≈: now uses the class wrapper, and thus supports live-patching.<commit_after>/* * noise≈ * Noiselator object for Jamoma Multicore * Copyright © 2008 by Timothy Place * * License: This code is licensed under the terms of the GNU LGPL * http://www.gnu.org/licenses/lgpl.html */ #include "maxMulticore.h" int main(void) { WrappedClassOptionsPtr options = new WrappedClassOptions; TTValue value(0); WrappedClassPtr c = NULL; TTMulticoreInit(); options->append(TT("generator"), value); wrapAsMaxMulticore(TT("noise"), "jcom.noise≈", &c, options); CLASS_ATTR_ENUM(c->maxClass, "mode", 0, "white pink brown blue"); return 0; } <|endoftext|>
<commit_before>/* Copyright 2019 Benjamin Worpitz, René Widera * * This file is part of alpaka. * * This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ #pragma once #ifdef ALPAKA_ACC_CPU_BT_OMP4_ENABLED #if _OPENMP < 201307 #error If ALPAKA_ACC_CPU_BT_OMP4_ENABLED is set, the compiler has to support OpenMP 4.0 or higher! #endif // Specialized traits. #include <alpaka/acc/Traits.hpp> #include <alpaka/dev/Traits.hpp> #include <alpaka/dim/Traits.hpp> #include <alpaka/pltf/Traits.hpp> #include <alpaka/idx/Traits.hpp> // Implementation details. #include <alpaka/acc/AccCpuOmp4.hpp> #include <alpaka/core/Decay.hpp> #include <alpaka/dev/DevCpu.hpp> #include <alpaka/idx/MapIdx.hpp> #include <alpaka/kernel/Traits.hpp> #include <alpaka/workdiv/WorkDivMembers.hpp> #include <alpaka/meta/ApplyTuple.hpp> #include <omp.h> #include <functional> #include <stdexcept> #include <tuple> #include <type_traits> #include <algorithm> #if ALPAKA_DEBUG >= ALPAKA_DEBUG_MINIMAL #include <iostream> #endif namespace alpaka { namespace kernel { //############################################################################# //! The CPU OpenMP 4.0 accelerator execution task. template< typename TDim, typename TIdx, typename TKernelFnObj, typename... TArgs> class TaskKernelCpuOmp4 final : public workdiv::WorkDivMembers<TDim, TIdx> { public: //----------------------------------------------------------------------------- template< typename TWorkDiv> ALPAKA_FN_HOST TaskKernelCpuOmp4( TWorkDiv && workDiv, TKernelFnObj const & kernelFnObj, TArgs && ... args) : workdiv::WorkDivMembers<TDim, TIdx>(std::forward<TWorkDiv>(workDiv)), m_kernelFnObj(kernelFnObj), m_args(std::forward<TArgs>(args)...) { static_assert( dim::Dim<std::decay_t<TWorkDiv>>::value == TDim::value, "The work division and the execution task have to be of the same dimensionality!"); } //----------------------------------------------------------------------------- TaskKernelCpuOmp4(TaskKernelCpuOmp4 const & other) = default; //----------------------------------------------------------------------------- TaskKernelCpuOmp4(TaskKernelCpuOmp4 && other) = default; //----------------------------------------------------------------------------- auto operator=(TaskKernelCpuOmp4 const &) -> TaskKernelCpuOmp4 & = default; //----------------------------------------------------------------------------- auto operator=(TaskKernelCpuOmp4 &&) -> TaskKernelCpuOmp4 & = default; //----------------------------------------------------------------------------- ~TaskKernelCpuOmp4() = default; //----------------------------------------------------------------------------- //! Executes the kernel function object. ALPAKA_FN_HOST auto operator()() const -> void { ALPAKA_DEBUG_MINIMAL_LOG_SCOPE; auto const gridBlockExtent( workdiv::getWorkDiv<Grid, Blocks>(*this)); auto const blockThreadExtent( workdiv::getWorkDiv<Block, Threads>(*this)); auto const threadElemExtent( workdiv::getWorkDiv<Thread, Elems>(*this)); std::cout << "m_gridBlockExtent=" << this->m_gridBlockExtent << "\tgridBlockExtent=" << gridBlockExtent << std::endl; std::cout << "m_blockThreadExtent=" << this->m_blockThreadExtent << "\tblockThreadExtent=" << blockThreadExtent << std::endl; std::cout << "m_threadElemExtent=" << this->m_threadElemExtent << "\tthreadElemExtent=" << threadElemExtent << std::endl; // Get the size of the block shared dynamic memory. auto const blockSharedMemDynSizeBytes( meta::apply( [&](ALPAKA_DECAY_T(TArgs) const & ... args) { return kernel::getBlockSharedMemDynSizeBytes< acc::AccCpuOmp4<TDim, TIdx>>( m_kernelFnObj, blockThreadExtent, threadElemExtent, args...); }, m_args)); #if ALPAKA_DEBUG >= ALPAKA_DEBUG_FULL std::cout << __func__ << " blockSharedMemDynSizeBytes: " << blockSharedMemDynSizeBytes << " B" << std::endl; #endif // The number of blocks in the grid. TIdx const gridBlockCount(gridBlockExtent.prod()); // The number of threads in a block. TIdx const blockThreadCount(blockThreadExtent.prod()); // We have to make sure, that the OpenMP runtime keeps enough threads for executing a block in parallel. TIdx const maxOmpThreadCount(static_cast<TIdx>(::omp_get_max_threads())); assert(blockThreadCount <= static_cast<TIdx>(maxOmpThreadCount)); TIdx const teamCount(std::min(static_cast<TIdx>(maxOmpThreadCount/blockThreadCount), gridBlockCount)); std::cout << "threadElemCount=" << threadElemExtent[0u] << std::endl; std::cout << "teamCount=" << teamCount << "\tgridBlockCount=" << gridBlockCount << std::endl; if(::omp_in_parallel() != 0) { throw std::runtime_error("The OpenMP 4.0 backend can not be used within an existing parallel region!"); } // Force the environment to use the given number of threads. int const ompIsDynamic(::omp_get_dynamic()); ::omp_set_dynamic(0); // `When an if(scalar-expression) evaluates to false, the structured block is executed on the host.` auto argsD = m_args; #pragma omp target map(to:argsD) { #pragma omp teams num_teams(teamCount) thread_limit(blockThreadCount) { #if ALPAKA_DEBUG >= ALPAKA_DEBUG_MINIMAL // The first team does some checks ... if((::omp_get_team_num() == 0)) { int const iNumTeams(::omp_get_num_teams()); printf("%s omp_get_num_teams: %d\n", __func__, iNumTeams); } #endif printf("threadElemCount_dev %d\n", int(threadElemExtent[0u])); // iterate over groups of teams to stay withing thread limit for(TIdx t = 0u; t < gridBlockCount; t+=teamCount) { acc::AccCpuOmp4<TDim, TIdx> acc( threadElemExtent, blockThreadExtent, gridBlockExtent, t, blockSharedMemDynSizeBytes); printf("acc->threadElemCount %d\n" , int(acc.m_threadElemExtent[0])); const TIdx bsup = std::min(static_cast<TIdx>(t + teamCount), gridBlockCount); #pragma omp distribute for(TIdx b = t; b<bsup; ++b) { vec::Vec<dim::DimInt<1u>, TIdx> const gridBlockIdx(b); // When this is not repeated here: // error: gridBlockExtent referenced in target region does not have a mappable type auto const gridBlockExtent2( workdiv::getWorkDiv<Grid, Blocks>(*static_cast<workdiv::WorkDivMembers<TDim, TIdx> const *>(this))); acc.m_gridBlockIdx = idx::mapIdx<TDim::value>( gridBlockIdx, gridBlockExtent2); // Execute the threads in parallel. // Parallel execution of the threads in a block is required because when syncBlockThreads is called all of them have to be done with their work up to this line. // So we have to spawn one OS thread per thread in a block. // 'omp for' is not useful because it is meant for cases where multiple iterations are executed by one thread but in our case a 1:1 mapping is required. // Therefore we use 'omp parallel' with the specified number of threads in a block. #pragma omp parallel num_threads(blockThreadCount) { #if ALPAKA_DEBUG >= ALPAKA_DEBUG_MINIMAL // The first thread does some checks in the first block executed. if((::omp_get_thread_num() == 0) && (b == 0)) { int const numThreads(::omp_get_num_threads()); printf("%s omp_get_num_threads: %d\n", __func__, numThreads); if(numThreads != static_cast<int>(blockThreadCount)) { printf("ERROR: The OpenMP runtime did not use the number of threads that had been requested!\n"); } } #endif meta::apply( [&](TArgs ... args) { m_kernelFnObj( acc, args...); }, argsD); // Wait for all threads to finish before deleting the shared memory. // This is done by default if the omp 'nowait' clause is missing //block::sync::syncBlockThreads(acc); } // After a block has been processed, the shared memory has to be deleted. block::shared::st::freeMem(acc); } } } } // Reset the dynamic thread number setting. ::omp_set_dynamic(ompIsDynamic); } private: TKernelFnObj m_kernelFnObj; std::tuple<std::decay_t<TArgs>...> m_args; }; } namespace acc { namespace traits { //############################################################################# //! The CPU OpenMP 4.0 execution task accelerator type trait specialization. template< typename TDim, typename TIdx, typename TKernelFnObj, typename... TArgs> struct AccType< kernel::TaskKernelCpuOmp4<TDim, TIdx, TKernelFnObj, TArgs...>> { using type = acc::AccCpuOmp4<TDim, TIdx>; }; } } namespace dev { namespace traits { //############################################################################# //! The CPU OpenMP 4.0 execution task device type trait specialization. template< typename TDim, typename TIdx, typename TKernelFnObj, typename... TArgs> struct DevType< kernel::TaskKernelCpuOmp4<TDim, TIdx, TKernelFnObj, TArgs...>> { using type = dev::DevCpu; }; } } namespace dim { namespace traits { //############################################################################# //! The CPU OpenMP 4.0 execution task dimension getter trait specialization. template< typename TDim, typename TIdx, typename TKernelFnObj, typename... TArgs> struct DimType< kernel::TaskKernelCpuOmp4<TDim, TIdx, TKernelFnObj, TArgs...>> { using type = TDim; }; } } namespace pltf { namespace traits { //############################################################################# //! The CPU OpenMP 4.0 execution task platform type trait specialization. template< typename TDim, typename TIdx, typename TKernelFnObj, typename... TArgs> struct PltfType< kernel::TaskKernelCpuOmp4<TDim, TIdx, TKernelFnObj, TArgs...>> { using type = pltf::PltfCpu; }; } } namespace idx { namespace traits { //############################################################################# //! The CPU OpenMP 4.0 execution task idx type trait specialization. template< typename TDim, typename TIdx, typename TKernelFnObj, typename... TArgs> struct IdxType< kernel::TaskKernelCpuOmp4<TDim, TIdx, TKernelFnObj, TArgs...>> { using type = TIdx; }; } } } #endif <commit_msg>TaskKernelCpuOmp4: Fix workdiv init of Acc<commit_after>/* Copyright 2019 Benjamin Worpitz, René Widera * * This file is part of alpaka. * * This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ #pragma once #ifdef ALPAKA_ACC_CPU_BT_OMP4_ENABLED #if _OPENMP < 201307 #error If ALPAKA_ACC_CPU_BT_OMP4_ENABLED is set, the compiler has to support OpenMP 4.0 or higher! #endif // Specialized traits. #include <alpaka/acc/Traits.hpp> #include <alpaka/dev/Traits.hpp> #include <alpaka/dim/Traits.hpp> #include <alpaka/pltf/Traits.hpp> #include <alpaka/idx/Traits.hpp> // Implementation details. #include <alpaka/acc/AccCpuOmp4.hpp> #include <alpaka/core/Decay.hpp> #include <alpaka/dev/DevCpu.hpp> #include <alpaka/idx/MapIdx.hpp> #include <alpaka/kernel/Traits.hpp> #include <alpaka/workdiv/WorkDivMembers.hpp> #include <alpaka/meta/ApplyTuple.hpp> #include <omp.h> #include <functional> #include <stdexcept> #include <tuple> #include <type_traits> #include <algorithm> #if ALPAKA_DEBUG >= ALPAKA_DEBUG_MINIMAL #include <iostream> #endif namespace alpaka { namespace kernel { //############################################################################# //! The CPU OpenMP 4.0 accelerator execution task. template< typename TDim, typename TIdx, typename TKernelFnObj, typename... TArgs> class TaskKernelCpuOmp4 final : public workdiv::WorkDivMembers<TDim, TIdx> { public: //----------------------------------------------------------------------------- template< typename TWorkDiv> ALPAKA_FN_HOST TaskKernelCpuOmp4( TWorkDiv && workDiv, TKernelFnObj const & kernelFnObj, TArgs && ... args) : workdiv::WorkDivMembers<TDim, TIdx>(std::forward<TWorkDiv>(workDiv)), m_kernelFnObj(kernelFnObj), m_args(std::forward<TArgs>(args)...) { static_assert( dim::Dim<std::decay_t<TWorkDiv>>::value == TDim::value, "The work division and the execution task have to be of the same dimensionality!"); } //----------------------------------------------------------------------------- TaskKernelCpuOmp4(TaskKernelCpuOmp4 const & other) = default; //----------------------------------------------------------------------------- TaskKernelCpuOmp4(TaskKernelCpuOmp4 && other) = default; //----------------------------------------------------------------------------- auto operator=(TaskKernelCpuOmp4 const &) -> TaskKernelCpuOmp4 & = default; //----------------------------------------------------------------------------- auto operator=(TaskKernelCpuOmp4 &&) -> TaskKernelCpuOmp4 & = default; //----------------------------------------------------------------------------- ~TaskKernelCpuOmp4() = default; //----------------------------------------------------------------------------- //! Executes the kernel function object. ALPAKA_FN_HOST auto operator()() const -> void { ALPAKA_DEBUG_MINIMAL_LOG_SCOPE; auto const gridBlockExtent( workdiv::getWorkDiv<Grid, Blocks>(*this)); auto const blockThreadExtent( workdiv::getWorkDiv<Block, Threads>(*this)); auto const threadElemExtent( workdiv::getWorkDiv<Thread, Elems>(*this)); std::cout << "m_gridBlockExtent=" << this->m_gridBlockExtent << "\tgridBlockExtent=" << gridBlockExtent << std::endl; std::cout << "m_blockThreadExtent=" << this->m_blockThreadExtent << "\tblockThreadExtent=" << blockThreadExtent << std::endl; std::cout << "m_threadElemExtent=" << this->m_threadElemExtent << "\tthreadElemExtent=" << threadElemExtent << std::endl; // Get the size of the block shared dynamic memory. auto const blockSharedMemDynSizeBytes( meta::apply( [&](ALPAKA_DECAY_T(TArgs) const & ... args) { return kernel::getBlockSharedMemDynSizeBytes< acc::AccCpuOmp4<TDim, TIdx>>( m_kernelFnObj, blockThreadExtent, threadElemExtent, args...); }, m_args)); #if ALPAKA_DEBUG >= ALPAKA_DEBUG_FULL std::cout << __func__ << " blockSharedMemDynSizeBytes: " << blockSharedMemDynSizeBytes << " B" << std::endl; #endif // The number of blocks in the grid. TIdx const gridBlockCount(gridBlockExtent.prod()); // The number of threads in a block. TIdx const blockThreadCount(blockThreadExtent.prod()); // We have to make sure, that the OpenMP runtime keeps enough threads for executing a block in parallel. TIdx const maxOmpThreadCount(static_cast<TIdx>(::omp_get_max_threads())); assert(blockThreadCount <= static_cast<TIdx>(maxOmpThreadCount)); TIdx const teamCount(std::min(static_cast<TIdx>(maxOmpThreadCount/blockThreadCount), gridBlockCount)); std::cout << "threadElemCount=" << threadElemExtent[0u] << std::endl; std::cout << "teamCount=" << teamCount << "\tgridBlockCount=" << gridBlockCount << std::endl; if(::omp_in_parallel() != 0) { throw std::runtime_error("The OpenMP 4.0 backend can not be used within an existing parallel region!"); } // Force the environment to use the given number of threads. int const ompIsDynamic(::omp_get_dynamic()); ::omp_set_dynamic(0); // `When an if(scalar-expression) evaluates to false, the structured block is executed on the host.` auto argsD = m_args; #pragma omp target map(to:argsD) { #pragma omp teams num_teams(teamCount) thread_limit(blockThreadCount) { #if ALPAKA_DEBUG >= ALPAKA_DEBUG_MINIMAL // The first team does some checks ... if((::omp_get_team_num() == 0)) { int const iNumTeams(::omp_get_num_teams()); printf("%s omp_get_num_teams: %d\n", __func__, iNumTeams); } #endif printf("threadElemCount_dev %d\n", int(threadElemExtent[0u])); // iterate over groups of teams to stay withing thread limit for(TIdx t = 0u; t < gridBlockCount; t+=teamCount) { acc::AccCpuOmp4<TDim, TIdx> acc( gridBlockExtent, blockThreadExtent, threadElemExtent, t, blockSharedMemDynSizeBytes); // printf("acc->threadElemCount %d\n" // , int(acc.m_threadElemExtent[0])); const TIdx bsup = std::min(static_cast<TIdx>(t + teamCount), gridBlockCount); #pragma omp distribute for(TIdx b = t; b<bsup; ++b) { vec::Vec<dim::DimInt<1u>, TIdx> const gridBlockIdx(b); // When this is not repeated here: // error: gridBlockExtent referenced in target region does not have a mappable type auto const gridBlockExtent2( workdiv::getWorkDiv<Grid, Blocks>(*static_cast<workdiv::WorkDivMembers<TDim, TIdx> const *>(this))); acc.m_gridBlockIdx = idx::mapIdx<TDim::value>( gridBlockIdx, gridBlockExtent2); // Execute the threads in parallel. // Parallel execution of the threads in a block is required because when syncBlockThreads is called all of them have to be done with their work up to this line. // So we have to spawn one OS thread per thread in a block. // 'omp for' is not useful because it is meant for cases where multiple iterations are executed by one thread but in our case a 1:1 mapping is required. // Therefore we use 'omp parallel' with the specified number of threads in a block. #pragma omp parallel num_threads(blockThreadCount) { #if ALPAKA_DEBUG >= ALPAKA_DEBUG_MINIMAL // The first thread does some checks in the first block executed. if((::omp_get_thread_num() == 0) && (b == 0)) { int const numThreads(::omp_get_num_threads()); printf("%s omp_get_num_threads: %d\n", __func__, numThreads); if(numThreads != static_cast<int>(blockThreadCount)) { printf("ERROR: The OpenMP runtime did not use the number of threads that had been requested!\n"); } } #endif meta::apply( [&](TArgs ... args) { m_kernelFnObj( acc, args...); }, argsD); // Wait for all threads to finish before deleting the shared memory. // This is done by default if the omp 'nowait' clause is missing //block::sync::syncBlockThreads(acc); } // After a block has been processed, the shared memory has to be deleted. block::shared::st::freeMem(acc); } } } } // Reset the dynamic thread number setting. ::omp_set_dynamic(ompIsDynamic); } private: TKernelFnObj m_kernelFnObj; std::tuple<std::decay_t<TArgs>...> m_args; }; } namespace acc { namespace traits { //############################################################################# //! The CPU OpenMP 4.0 execution task accelerator type trait specialization. template< typename TDim, typename TIdx, typename TKernelFnObj, typename... TArgs> struct AccType< kernel::TaskKernelCpuOmp4<TDim, TIdx, TKernelFnObj, TArgs...>> { using type = acc::AccCpuOmp4<TDim, TIdx>; }; } } namespace dev { namespace traits { //############################################################################# //! The CPU OpenMP 4.0 execution task device type trait specialization. template< typename TDim, typename TIdx, typename TKernelFnObj, typename... TArgs> struct DevType< kernel::TaskKernelCpuOmp4<TDim, TIdx, TKernelFnObj, TArgs...>> { using type = dev::DevCpu; }; } } namespace dim { namespace traits { //############################################################################# //! The CPU OpenMP 4.0 execution task dimension getter trait specialization. template< typename TDim, typename TIdx, typename TKernelFnObj, typename... TArgs> struct DimType< kernel::TaskKernelCpuOmp4<TDim, TIdx, TKernelFnObj, TArgs...>> { using type = TDim; }; } } namespace pltf { namespace traits { //############################################################################# //! The CPU OpenMP 4.0 execution task platform type trait specialization. template< typename TDim, typename TIdx, typename TKernelFnObj, typename... TArgs> struct PltfType< kernel::TaskKernelCpuOmp4<TDim, TIdx, TKernelFnObj, TArgs...>> { using type = pltf::PltfCpu; }; } } namespace idx { namespace traits { //############################################################################# //! The CPU OpenMP 4.0 execution task idx type trait specialization. template< typename TDim, typename TIdx, typename TKernelFnObj, typename... TArgs> struct IdxType< kernel::TaskKernelCpuOmp4<TDim, TIdx, TKernelFnObj, TArgs...>> { using type = TIdx; }; } } } #endif <|endoftext|>
<commit_before>// Copyright 2014 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "chrome/browser/safe_browsing/incident_reporting/environment_data_collection_win.h" #include <string> #include "base/base_paths.h" #include "base/files/file_path.h" #include "base/path_service.h" #include "base/scoped_native_library.h" #include "base/strings/utf_string_conversions.h" #include "base/test/test_reg_util_win.h" #include "base/win/registry.h" #include "chrome/browser/safe_browsing/incident_reporting/module_integrity_unittest_util_win.h" #include "chrome/browser/safe_browsing/incident_reporting/module_integrity_verifier_win.h" #include "chrome/browser/safe_browsing/path_sanitizer.h" #include "chrome/common/safe_browsing/csd.pb.h" #include "chrome_elf/chrome_elf_constants.h" #include "net/base/winsock_init.h" #include "testing/gtest/include/gtest/gtest.h" namespace { const wchar_t test_dll[] = L"test_name.dll"; // Helper function that returns true if a dll with filename |dll_name| is // found in |process_report|. bool ProcessReportContainsDll( const safe_browsing::ClientIncidentReport_EnvironmentData_Process& process_report, const base::FilePath& dll_name) { for (int i = 0; i < process_report.dll_size(); ++i) { base::FilePath current_dll = base::FilePath::FromUTF8Unsafe(process_report.dll(i).path()); if (current_dll.BaseName() == dll_name) return true; } return false; } // Look through dll entries and check for the presence of the LSP feature for // |dll|. bool DllEntryContainsLspFeature( const safe_browsing::ClientIncidentReport_EnvironmentData_Process& process_report, const std::string& dll) { for (int i = 0; i < process_report.dll_size(); ++i) { if (process_report.dll(i).path() == dll) { // Verify each feature of |dll|. for (int j = 0; j < process_report.dll(i).feature_size(); ++j) { if (process_report.dll(i).feature(j) == safe_browsing::ClientIncidentReport_EnvironmentData_Process_Dll:: LSP) // LSP feature found. return true; } } } return false; } } // namespace TEST(SafeBrowsingEnvironmentDataCollectionWinTest, CollectDlls) { // This test will check if the CollectDlls method works by loading // a dll and then checking if we can find it within the process report. // Pick msvidc32.dll as it is present from WinXP to Win8 and yet rarely used. // msvidc32.dll exists in both 32 and 64 bit versions. base::FilePath msvdc32_dll(L"msvidc32.dll"); safe_browsing::ClientIncidentReport_EnvironmentData_Process process_report; safe_browsing::CollectDlls(&process_report); ASSERT_FALSE(ProcessReportContainsDll(process_report, msvdc32_dll)); // Redo the same verification after loading a new dll. base::ScopedNativeLibrary library(msvdc32_dll); process_report.clear_dll(); safe_browsing::CollectDlls(&process_report); ASSERT_TRUE(ProcessReportContainsDll(process_report, msvdc32_dll)); } TEST(SafeBrowsingEnvironmentDataCollectionWinTest, RecordLspFeature) { net::EnsureWinsockInit(); // Populate our incident report with loaded modules. safe_browsing::ClientIncidentReport_EnvironmentData_Process process_report; safe_browsing::CollectDlls(&process_report); // We'll test RecordLspFeatures against a real dll registered as a LSP. All // dll paths are expected to be lowercase in the process report. std::string lsp = "c:\\windows\\system32\\mswsock.dll"; int base_address = 0x77770000; int length = 0x180000; safe_browsing::RecordLspFeature(&process_report); // Return successfully if LSP feature is found. if (DllEntryContainsLspFeature(process_report, lsp)) return; // |lsp| was not already loaded into the current process. Manually add it // to the process report so that it will get marked as a LSP. safe_browsing::ClientIncidentReport_EnvironmentData_Process_Dll* dll = process_report.add_dll(); dll->set_path(lsp); dll->set_base_address(base_address); dll->set_length(length); safe_browsing::RecordLspFeature(&process_report); // Return successfully if LSP feature is found. if (DllEntryContainsLspFeature(process_report, lsp)) return; FAIL() << "No LSP feature found for " << lsp; } TEST(SafeBrowsingEnvironmentDataCollectionWinTest, CollectDllBlacklistData) { // Ensure that CollectDllBlacklistData correctly adds the set of sanitized dll // names currently stored in the registry to the report. registry_util::RegistryOverrideManager override_manager; override_manager.OverrideRegistry(HKEY_CURRENT_USER, L"safe_browsing_test"); base::win::RegKey blacklist_registry_key(HKEY_CURRENT_USER, blacklist::kRegistryFinchListPath, KEY_QUERY_VALUE | KEY_SET_VALUE); // Check that with an empty registry the blacklisted dlls field is left empty. safe_browsing::ClientIncidentReport_EnvironmentData_Process process_report; safe_browsing::CollectDllBlacklistData(&process_report); EXPECT_EQ(0, process_report.blacklisted_dll_size()); // Check that after adding exactly one dll to the registry it appears in the // process report. blacklist_registry_key.WriteValue(test_dll, test_dll); safe_browsing::CollectDllBlacklistData(&process_report); ASSERT_EQ(1, process_report.blacklisted_dll_size()); base::string16 process_report_dll = base::UTF8ToWide(process_report.blacklisted_dll(0)); EXPECT_EQ(base::string16(test_dll), process_report_dll); // Check that if the registry contains the full path to a dll it is properly // sanitized before being reported. blacklist_registry_key.DeleteValue(test_dll); process_report.clear_blacklisted_dll(); base::FilePath path; ASSERT_TRUE(PathService::Get(base::DIR_HOME, &path)); base::string16 input_path = path.Append(FILE_PATH_LITERAL("test_path.dll")).value(); std::string path_expected = base::FilePath(FILE_PATH_LITERAL("~")) .Append(FILE_PATH_LITERAL("test_path.dll")) .AsUTF8Unsafe(); blacklist_registry_key.WriteValue(input_path.c_str(), input_path.c_str()); safe_browsing::CollectDllBlacklistData(&process_report); ASSERT_EQ(1, process_report.blacklisted_dll_size()); std::string process_report_path = process_report.blacklisted_dll(0); EXPECT_EQ(path_expected, process_report_path); } TEST(SafeBrowsingEnvironmentDataCollectionWinTest, VerifyLoadedModules) { // Load the test modules. std::vector<base::ScopedNativeLibrary> test_dlls( safe_browsing::kTestDllNamesCount); for (size_t i = 0; i < safe_browsing::kTestDllNamesCount; ++i) { test_dlls[i].Reset(LoadNativeLibrary( base::FilePath(safe_browsing::kTestDllNames[i]), NULL)); } // Edit the first byte of the function exported by the first module. HMODULE module_handle = NULL; EXPECT_TRUE( GetModuleHandleEx(0, safe_browsing::kTestDllNames[0], &module_handle)); uint8_t* export_addr = reinterpret_cast<uint8_t*>( GetProcAddress(module_handle, safe_browsing::kTestExportName)); EXPECT_NE(reinterpret_cast<uint8_t*>(NULL), export_addr); uint8_t new_val = (*export_addr) + 1; SIZE_T bytes_written = 0; WriteProcessMemory(GetCurrentProcess(), export_addr, reinterpret_cast<void*>(&new_val), 1, &bytes_written); EXPECT_EQ(1, bytes_written); safe_browsing::ClientIncidentReport_EnvironmentData_Process process_report; safe_browsing::CollectModuleVerificationData( safe_browsing::kTestDllNames, safe_browsing::kTestDllNamesCount, &process_report); // CollectModuleVerificationData should return the single modified module and // its modified export. The other module, being unmodified, is omitted from // the returned list of modules. EXPECT_EQ(1, process_report.module_state_size()); EXPECT_EQ(base::WideToUTF8(std::wstring(safe_browsing::kTestDllNames[0])), process_report.module_state(0).name()); EXPECT_EQ( safe_browsing::ClientIncidentReport_EnvironmentData_Process_ModuleState:: MODULE_STATE_MODIFIED, process_report.module_state(0).modified_state()); EXPECT_EQ(1, process_report.module_state(0).modified_export_size()); EXPECT_EQ(std::string(safe_browsing::kTestExportName), process_report.module_state(0).modified_export(0)); } <commit_msg>GetModuleHandleEx was incrementing the module ref count so the library was not freed at the end of the test. Another unrelated unit test was expecting the dll to not be loaded.<commit_after>// Copyright 2014 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "chrome/browser/safe_browsing/incident_reporting/environment_data_collection_win.h" #include <string> #include "base/base_paths.h" #include "base/files/file_path.h" #include "base/path_service.h" #include "base/scoped_native_library.h" #include "base/strings/utf_string_conversions.h" #include "base/test/test_reg_util_win.h" #include "base/win/registry.h" #include "chrome/browser/safe_browsing/incident_reporting/module_integrity_unittest_util_win.h" #include "chrome/browser/safe_browsing/incident_reporting/module_integrity_verifier_win.h" #include "chrome/browser/safe_browsing/path_sanitizer.h" #include "chrome/common/safe_browsing/csd.pb.h" #include "chrome_elf/chrome_elf_constants.h" #include "net/base/winsock_init.h" #include "testing/gtest/include/gtest/gtest.h" namespace { const wchar_t test_dll[] = L"test_name.dll"; // Helper function that returns true if a dll with filename |dll_name| is // found in |process_report|. bool ProcessReportContainsDll( const safe_browsing::ClientIncidentReport_EnvironmentData_Process& process_report, const base::FilePath& dll_name) { for (int i = 0; i < process_report.dll_size(); ++i) { base::FilePath current_dll = base::FilePath::FromUTF8Unsafe(process_report.dll(i).path()); if (current_dll.BaseName() == dll_name) return true; } return false; } // Look through dll entries and check for the presence of the LSP feature for // |dll|. bool DllEntryContainsLspFeature( const safe_browsing::ClientIncidentReport_EnvironmentData_Process& process_report, const std::string& dll) { for (int i = 0; i < process_report.dll_size(); ++i) { if (process_report.dll(i).path() == dll) { // Verify each feature of |dll|. for (int j = 0; j < process_report.dll(i).feature_size(); ++j) { if (process_report.dll(i).feature(j) == safe_browsing::ClientIncidentReport_EnvironmentData_Process_Dll:: LSP) // LSP feature found. return true; } } } return false; } } // namespace TEST(SafeBrowsingEnvironmentDataCollectionWinTest, CollectDlls) { // This test will check if the CollectDlls method works by loading // a dll and then checking if we can find it within the process report. // Pick msvidc32.dll as it is present from WinXP to Win8 and yet rarely used. // msvidc32.dll exists in both 32 and 64 bit versions. base::FilePath msvdc32_dll(L"msvidc32.dll"); safe_browsing::ClientIncidentReport_EnvironmentData_Process process_report; safe_browsing::CollectDlls(&process_report); ASSERT_FALSE(ProcessReportContainsDll(process_report, msvdc32_dll)); // Redo the same verification after loading a new dll. base::ScopedNativeLibrary library(msvdc32_dll); process_report.clear_dll(); safe_browsing::CollectDlls(&process_report); ASSERT_TRUE(ProcessReportContainsDll(process_report, msvdc32_dll)); } TEST(SafeBrowsingEnvironmentDataCollectionWinTest, RecordLspFeature) { net::EnsureWinsockInit(); // Populate our incident report with loaded modules. safe_browsing::ClientIncidentReport_EnvironmentData_Process process_report; safe_browsing::CollectDlls(&process_report); // We'll test RecordLspFeatures against a real dll registered as a LSP. All // dll paths are expected to be lowercase in the process report. std::string lsp = "c:\\windows\\system32\\mswsock.dll"; int base_address = 0x77770000; int length = 0x180000; safe_browsing::RecordLspFeature(&process_report); // Return successfully if LSP feature is found. if (DllEntryContainsLspFeature(process_report, lsp)) return; // |lsp| was not already loaded into the current process. Manually add it // to the process report so that it will get marked as a LSP. safe_browsing::ClientIncidentReport_EnvironmentData_Process_Dll* dll = process_report.add_dll(); dll->set_path(lsp); dll->set_base_address(base_address); dll->set_length(length); safe_browsing::RecordLspFeature(&process_report); // Return successfully if LSP feature is found. if (DllEntryContainsLspFeature(process_report, lsp)) return; FAIL() << "No LSP feature found for " << lsp; } TEST(SafeBrowsingEnvironmentDataCollectionWinTest, CollectDllBlacklistData) { // Ensure that CollectDllBlacklistData correctly adds the set of sanitized dll // names currently stored in the registry to the report. registry_util::RegistryOverrideManager override_manager; override_manager.OverrideRegistry(HKEY_CURRENT_USER, L"safe_browsing_test"); base::win::RegKey blacklist_registry_key(HKEY_CURRENT_USER, blacklist::kRegistryFinchListPath, KEY_QUERY_VALUE | KEY_SET_VALUE); // Check that with an empty registry the blacklisted dlls field is left empty. safe_browsing::ClientIncidentReport_EnvironmentData_Process process_report; safe_browsing::CollectDllBlacklistData(&process_report); EXPECT_EQ(0, process_report.blacklisted_dll_size()); // Check that after adding exactly one dll to the registry it appears in the // process report. blacklist_registry_key.WriteValue(test_dll, test_dll); safe_browsing::CollectDllBlacklistData(&process_report); ASSERT_EQ(1, process_report.blacklisted_dll_size()); base::string16 process_report_dll = base::UTF8ToWide(process_report.blacklisted_dll(0)); EXPECT_EQ(base::string16(test_dll), process_report_dll); // Check that if the registry contains the full path to a dll it is properly // sanitized before being reported. blacklist_registry_key.DeleteValue(test_dll); process_report.clear_blacklisted_dll(); base::FilePath path; ASSERT_TRUE(PathService::Get(base::DIR_HOME, &path)); base::string16 input_path = path.Append(FILE_PATH_LITERAL("test_path.dll")).value(); std::string path_expected = base::FilePath(FILE_PATH_LITERAL("~")) .Append(FILE_PATH_LITERAL("test_path.dll")) .AsUTF8Unsafe(); blacklist_registry_key.WriteValue(input_path.c_str(), input_path.c_str()); safe_browsing::CollectDllBlacklistData(&process_report); ASSERT_EQ(1, process_report.blacklisted_dll_size()); std::string process_report_path = process_report.blacklisted_dll(0); EXPECT_EQ(path_expected, process_report_path); } TEST(SafeBrowsingEnvironmentDataCollectionWinTest, VerifyLoadedModules) { // Load the test modules. std::vector<base::ScopedNativeLibrary> test_dlls( safe_browsing::kTestDllNamesCount); for (size_t i = 0; i < safe_browsing::kTestDllNamesCount; ++i) { test_dlls[i].Reset(LoadNativeLibrary( base::FilePath(safe_browsing::kTestDllNames[i]), NULL)); } // Edit the first byte of the function exported by the first module. Calling // GetModuleHandle so we do not increment the library ref count. HMODULE module_handle = GetModuleHandle(safe_browsing::kTestDllNames[0]); EXPECT_NE(reinterpret_cast<HANDLE>(NULL), module_handle); uint8_t* export_addr = reinterpret_cast<uint8_t*>( GetProcAddress(module_handle, safe_browsing::kTestExportName)); EXPECT_NE(reinterpret_cast<uint8_t*>(NULL), export_addr); uint8_t new_val = (*export_addr) + 1; SIZE_T bytes_written = 0; WriteProcessMemory(GetCurrentProcess(), export_addr, reinterpret_cast<void*>(&new_val), 1, &bytes_written); EXPECT_EQ(1, bytes_written); safe_browsing::ClientIncidentReport_EnvironmentData_Process process_report; safe_browsing::CollectModuleVerificationData( safe_browsing::kTestDllNames, safe_browsing::kTestDllNamesCount, &process_report); // CollectModuleVerificationData should return the single modified module and // its modified export. The other module, being unmodified, is omitted from // the returned list of modules. EXPECT_EQ(1, process_report.module_state_size()); EXPECT_EQ(base::WideToUTF8(std::wstring(safe_browsing::kTestDllNames[0])), process_report.module_state(0).name()); EXPECT_EQ( safe_browsing::ClientIncidentReport_EnvironmentData_Process_ModuleState:: MODULE_STATE_MODIFIED, process_report.module_state(0).modified_state()); EXPECT_EQ(1, process_report.module_state(0).modified_export_size()); EXPECT_EQ(std::string(safe_browsing::kTestExportName), process_report.module_state(0).modified_export(0)); } <|endoftext|>
<commit_before>// (C) Copyright Gennadiy Rozental 2005. // Distributed under the Boost Software License, Version 1.0. // (See accompanying file LICENSE_1_0.txt or copy at // http://www.boost.org/LICENSE_1_0.txt) // See http://www.boost.org/libs/test for the library home page. // // File : $RCSfile$ // // Version : $Revision$ // // Description : privide core implementation for Unit Test Framework. // Extensions could be provided in separate files // *************************************************************************** #ifndef BOOST_TEST_UNIT_TEST_SUITE_IPP_012205GER #define BOOST_TEST_UNIT_TEST_SUITE_IPP_012205GER // Boost.Test #include <boost/test/unit_test_suite.hpp> #include <boost/test/framework.hpp> #include <boost/test/utils/foreach.hpp> #include <boost/test/results_collector.hpp> #include <boost/test/detail/unit_test_parameters.hpp> // Boost #include <boost/timer.hpp> // STL #include <algorithm> #include <vector> #include <boost/test/detail/suppress_warnings.hpp> //____________________________________________________________________________// namespace boost { namespace unit_test { // ************************************************************************** // // ************** test_unit ************** // // ************************************************************************** // test_unit::test_unit( const_string name, test_unit_type t ) : p_name( std::string( name.begin(), name.size() ) ) , p_type( t ) , p_type_name( t == tut_case ? "case" : "suite" ) , p_id( INV_TEST_UNIT_ID ) { } //____________________________________________________________________________// void test_unit::depends_on( test_unit* tu ) { m_dependencies.push_back( tu->p_id ); } //____________________________________________________________________________// bool test_unit::check_dependencies() const { BOOST_TEST_FOREACH( test_unit_id, tu_id, m_dependencies ) { if( !unit_test::results_collector.results( tu_id ).passed() ) return false; } return true; } //____________________________________________________________________________// // ************************************************************************** // // ************** test_case ************** // // ************************************************************************** // test_case::test_case( const_string name, callback0<> const& test_func ) : test_unit( name, (test_unit_type)type ) , m_test_func( test_func ) { // !! weirdest MSVC BUG; try to remove this statement; looks like it eats first token of next statement #if BOOST_WORKAROUND(BOOST_MSVC,<=1200) 0; #endif framework::register_test_unit( this ); } //____________________________________________________________________________// // ************************************************************************** // // ************** test_suite ************** // // ************************************************************************** // //____________________________________________________________________________// test_suite::test_suite( const_string name ) : test_unit( name, (test_unit_type)type ) { framework::register_test_unit( this ); } //____________________________________________________________________________// // !! need to prevent modifing test unit once it is added to tree void test_suite::add( test_unit* tu, counter_t expected_failures, unsigned timeout ) { if( expected_failures != 0 ) tu->p_expected_failures.value = expected_failures; p_expected_failures.value += tu->p_expected_failures; if( timeout != 0 ) tu->p_timeout.value = timeout; m_members.push_back( tu->p_id ); } //____________________________________________________________________________// void test_suite::add( test_unit_generator const& gen, unsigned timeout ) { test_unit* tu; while((tu = gen.next(), tu)) add( tu, 0, timeout ); } //____________________________________________________________________________// // ************************************************************************** // // ************** traverse_test_tree ************** // // ************************************************************************** // void traverse_test_tree( test_case const& tc, test_tree_visitor& V ) { V.visit( tc ); } //____________________________________________________________________________// void traverse_test_tree( test_suite const& suite, test_tree_visitor& V ) { if( !V.test_suite_start( suite ) ) return; try { if( runtime_config::random_seed() == 0 ) { BOOST_TEST_FOREACH( test_unit_id, id, suite.m_members ) traverse_test_tree( id, V ); } else { std::vector<test_unit_id> members( suite.m_members ); std::random_shuffle( members.begin(), members.end() ); BOOST_TEST_FOREACH( test_unit_id, id, members ) traverse_test_tree( id, V ); } } catch( test_aborted const& ) { V.test_suite_finish( suite ); throw; } V.test_suite_finish( suite ); } //____________________________________________________________________________// void traverse_test_tree( test_unit_id id, test_tree_visitor& V ) { if( test_id_2_unit_type( id ) == tut_case ) traverse_test_tree( framework::get<test_case>( id ), V ); else traverse_test_tree( framework::get<test_suite>( id ), V ); } //____________________________________________________________________________// // ************************************************************************** // // ************** object generators ************** // // ************************************************************************** // namespace ut_detail { std::string normalize_test_case_name( const_string name ) { return ( name[0] == '&' ? std::string( name.begin()+1, name.size()-1 ) : std::string( name.begin(), name.size() ) ); } //____________________________________________________________________________// } // namespace ut_detail } // namespace unit_test } // namespace boost //____________________________________________________________________________// #include <boost/test/detail/enable_warnings.hpp> // *************************************************************************** // Revision History : // // $Log$ // Revision 1.6 2005/02/21 10:12:24 rogeeff // Support for random order of test cases implemented // // Revision 1.5 2005/02/20 08:27:07 rogeeff // This a major update for Boost.Test framework. See release docs for complete list of fixes/updates // // *************************************************************************** #endif // BOOST_TEST_UNIT_TEST_SUITE_IPP_012205GER <commit_msg>fix for random_shuffle on Borland 5.x w/ STLPort<commit_after>// (C) Copyright Gennadiy Rozental 2005. // Distributed under the Boost Software License, Version 1.0. // (See accompanying file LICENSE_1_0.txt or copy at // http://www.boost.org/LICENSE_1_0.txt) // See http://www.boost.org/libs/test for the library home page. // // File : $RCSfile$ // // Version : $Revision$ // // Description : privide core implementation for Unit Test Framework. // Extensions could be provided in separate files // *************************************************************************** #ifndef BOOST_TEST_UNIT_TEST_SUITE_IPP_012205GER #define BOOST_TEST_UNIT_TEST_SUITE_IPP_012205GER // Boost.Test #include <boost/detail/workaround.hpp> #include <boost/test/unit_test_suite.hpp> #include <boost/test/framework.hpp> #include <boost/test/utils/foreach.hpp> #include <boost/test/results_collector.hpp> #include <boost/test/detail/unit_test_parameters.hpp> // Boost #include <boost/timer.hpp> // STL #include <algorithm> #include <vector> #include <boost/test/detail/suppress_warnings.hpp> #if BOOST_WORKAROUND(__BORLANDC__, < 0x600) && \ BOOST_WORKAROUND(_STLPORT_VERSION, <= 0x450) \ /**/ using std::rand; // rand is in std and random_shuffle is in _STL #endif //____________________________________________________________________________// namespace boost { namespace unit_test { // ************************************************************************** // // ************** test_unit ************** // // ************************************************************************** // test_unit::test_unit( const_string name, test_unit_type t ) : p_name( std::string( name.begin(), name.size() ) ) , p_type( t ) , p_type_name( t == tut_case ? "case" : "suite" ) , p_id( INV_TEST_UNIT_ID ) { } //____________________________________________________________________________// void test_unit::depends_on( test_unit* tu ) { m_dependencies.push_back( tu->p_id ); } //____________________________________________________________________________// bool test_unit::check_dependencies() const { BOOST_TEST_FOREACH( test_unit_id, tu_id, m_dependencies ) { if( !unit_test::results_collector.results( tu_id ).passed() ) return false; } return true; } //____________________________________________________________________________// // ************************************************************************** // // ************** test_case ************** // // ************************************************************************** // test_case::test_case( const_string name, callback0<> const& test_func ) : test_unit( name, (test_unit_type)type ) , m_test_func( test_func ) { // !! weirdest MSVC BUG; try to remove this statement; looks like it eats first token of next statement #if BOOST_WORKAROUND(BOOST_MSVC,<=1200) 0; #endif framework::register_test_unit( this ); } //____________________________________________________________________________// // ************************************************************************** // // ************** test_suite ************** // // ************************************************************************** // //____________________________________________________________________________// test_suite::test_suite( const_string name ) : test_unit( name, (test_unit_type)type ) { framework::register_test_unit( this ); } //____________________________________________________________________________// // !! need to prevent modifing test unit once it is added to tree void test_suite::add( test_unit* tu, counter_t expected_failures, unsigned timeout ) { if( expected_failures != 0 ) tu->p_expected_failures.value = expected_failures; p_expected_failures.value += tu->p_expected_failures; if( timeout != 0 ) tu->p_timeout.value = timeout; m_members.push_back( tu->p_id ); } //____________________________________________________________________________// void test_suite::add( test_unit_generator const& gen, unsigned timeout ) { test_unit* tu; while((tu = gen.next(), tu)) add( tu, 0, timeout ); } //____________________________________________________________________________// // ************************************************************************** // // ************** traverse_test_tree ************** // // ************************************************************************** // void traverse_test_tree( test_case const& tc, test_tree_visitor& V ) { V.visit( tc ); } //____________________________________________________________________________// void traverse_test_tree( test_suite const& suite, test_tree_visitor& V ) { if( !V.test_suite_start( suite ) ) return; try { if( runtime_config::random_seed() == 0 ) { BOOST_TEST_FOREACH( test_unit_id, id, suite.m_members ) traverse_test_tree( id, V ); } else { std::vector<test_unit_id> members( suite.m_members ); //#if !defined(__BORLANDC__) || !defined(__SGI_STL_PORT) && !defined(_STLPORT_VERSION) std::random_shuffle( members.begin(), members.end() ); //#else // bool random_test_order_not_supported_on_borland = false; // assert(random_test_order_not_supported_on_borland); //#endif BOOST_TEST_FOREACH( test_unit_id, id, members ) traverse_test_tree( id, V ); } } catch( test_aborted const& ) { V.test_suite_finish( suite ); throw; } V.test_suite_finish( suite ); } //____________________________________________________________________________// void traverse_test_tree( test_unit_id id, test_tree_visitor& V ) { if( test_id_2_unit_type( id ) == tut_case ) traverse_test_tree( framework::get<test_case>( id ), V ); else traverse_test_tree( framework::get<test_suite>( id ), V ); } //____________________________________________________________________________// // ************************************************************************** // // ************** object generators ************** // // ************************************************************************** // namespace ut_detail { std::string normalize_test_case_name( const_string name ) { return ( name[0] == '&' ? std::string( name.begin()+1, name.size()-1 ) : std::string( name.begin(), name.size() ) ); } //____________________________________________________________________________// } // namespace ut_detail } // namespace unit_test } // namespace boost //____________________________________________________________________________// #include <boost/test/detail/enable_warnings.hpp> // *************************************************************************** // Revision History : // // $Log$ // Revision 1.7 2005/02/25 21:27:44 turkanis // fix for random_shuffle on Borland 5.x w/ STLPort // // Revision 1.6 2005/02/21 10:12:24 rogeeff // Support for random order of test cases implemented // // Revision 1.5 2005/02/20 08:27:07 rogeeff // This a major update for Boost.Test framework. See release docs for complete list of fixes/updates // // *************************************************************************** #endif // BOOST_TEST_UNIT_TEST_SUITE_IPP_012205GER <|endoftext|>
<commit_before> /** * \file * \brief StaticRawMessageQueue class header * * \author Copyright (C) 2015 Kamil Szczygiel http://www.distortec.com http://www.freddiechopin.info * * \par License * This Source Code Form is subject to the terms of the Mozilla Public License, v. 2.0. If a copy of the MPL was not * distributed with this file, You can obtain one at http://mozilla.org/MPL/2.0/. * * \date 2015-01-18 */ #ifndef INCLUDE_DISTORTOS_STATICRAWMESSAGEQUEUE_HPP_ #define INCLUDE_DISTORTOS_STATICRAWMESSAGEQUEUE_HPP_ #include "distortos/RawMessageQueue.hpp" namespace distortos { /** * \brief StaticRawMessageQueue class is a variant of RawMessageQueue that has automatic storage for queue's contents. * * \param T is the type of data in queue * \param QueueSize is the maximum number of elements in queue */ template<typename T, size_t QueueSize> class StaticRawMessageQueue : public RawMessageQueue { public: /** * \brief StaticRawMessageQueue's constructor */ explicit StaticRawMessageQueue() : RawMessageQueue{entryStorage_, valueStorage_} { } private: /// storage for queue's entries std::array<EntryStorage, QueueSize> entryStorage_; /// storage for queue's contents std::array<typename std::aligned_storage<sizeof(T), alignof(T)>::type, QueueSize> valueStorage_; }; /** * \brief StaticRawMessageQueueFromSize type alias is a variant of StaticRawMessageQueue which uses size of element * (instead of type) as template argument. * * \param ElementSize is the size of single queue element, bytes * \param QueueSize is the maximum number of elements in queue */ template<size_t ElementSize, size_t QueueSize> using StaticRawMessageQueueFromSize = StaticRawMessageQueue<typename std::aligned_storage<ElementSize, ElementSize>::type, QueueSize>; } // namespace distortos #endif // INCLUDE_DISTORTOS_STATICRAWMESSAGEQUEUE_HPP_ <commit_msg>StaticRawMessageQueue: use composition instead of inheritance<commit_after> /** * \file * \brief StaticRawMessageQueue class header * * \author Copyright (C) 2015 Kamil Szczygiel http://www.distortec.com http://www.freddiechopin.info * * \par License * This Source Code Form is subject to the terms of the Mozilla Public License, v. 2.0. If a copy of the MPL was not * distributed with this file, You can obtain one at http://mozilla.org/MPL/2.0/. * * \date 2015-10-15 */ #ifndef INCLUDE_DISTORTOS_STATICRAWMESSAGEQUEUE_HPP_ #define INCLUDE_DISTORTOS_STATICRAWMESSAGEQUEUE_HPP_ #include "distortos/RawMessageQueue.hpp" namespace distortos { /** * \brief StaticRawMessageQueue class is a wrapper for RawMessageQueue that also provides automatic storage for queue's * contents. * * \note Objects of this class can be safely casted to (const) reference to RawMessageQueue. * * \param T is the type of data in queue * \param QueueSize is the maximum number of elements in queue */ template<typename T, size_t QueueSize> class StaticRawMessageQueue { public: /** * \brief StaticRawMessageQueue's constructor */ explicit StaticRawMessageQueue() : rawMessageQueue_{entryStorage_, valueStorage_} { } /** * \brief conversion to RawMessageQueue& * * \return reference to internal RawMessageQueue object */ operator RawMessageQueue&() { return rawMessageQueue_; } /** * \brief conversion to const RawMessageQueue& * * \return const reference to internal RawMessageQueue object */ operator const RawMessageQueue&() const { return rawMessageQueue_; } /** * \brief Wrapper for RawMessageQueue::pop(uint8_t&, void*, size_t) */ int pop(uint8_t& priority, void* const buffer, const size_t size) { return rawMessageQueue_.pop(priority, buffer, size); } /** * \brief Wrapper for RawMessageQueue::pop(uint8_t&, T&) */ template<typename U> int pop(uint8_t& priority, U& buffer) { return rawMessageQueue_.pop(priority, buffer); } /** * \brief Wrapper for RawMessageQueue::push(uint8_t, const void*, size_t) */ int push(const uint8_t priority, const void* const data, const size_t size) { return rawMessageQueue_.push(priority, data, size); } /** * \brief Wrapper for RawMessageQueue::push(uint8_t, const T&) */ template<typename U> int push(const uint8_t priority, const U& data) { return rawMessageQueue_.push(priority, data); } /** * \brief Wrapper for RawMessageQueue::tryPop(uint8_t&, void*, size_t) */ int tryPop(uint8_t& priority, void* const buffer, const size_t size) { return rawMessageQueue_.tryPop(priority, buffer, size); } /** * \brief Wrapper for RawMessageQueue::tryPop(uint8_t&, T&) */ template<typename U> int tryPop(uint8_t& priority, U& buffer) { return rawMessageQueue_.tryPop(priority, buffer); } /** * \brief Wrapper for RawMessageQueue::tryPopFor(std::chrono::duration<Rep, Period>, uint8_t&, void*, size_t) */ template<typename Rep, typename Period> int tryPopFor(const std::chrono::duration<Rep, Period> duration, uint8_t& priority, void* const buffer, const size_t size) { return rawMessageQueue_.tryPopFor(duration, priority, buffer, size); } /** * \brief Wrapper for RawMessageQueue::tryPopFor(std::chrono::duration<Rep, Period>, uint8_t&, T&) */ template<typename Rep, typename Period, typename U> int tryPopFor(const std::chrono::duration<Rep, Period> duration, uint8_t& priority, U& buffer) { return rawMessageQueue_.tryPopFor(duration, priority, buffer); } /** * \brief Wrapper for * RawMessageQueue::tryPopUntil(std::chrono::time_point<TickClock, Duration>, uint8_t&, void*, size_t) */ template<typename Duration> int tryPopUntil(const std::chrono::time_point<TickClock, Duration> timePoint, uint8_t& priority, void* const buffer, const size_t size) { return rawMessageQueue_.tryPopUntil(timePoint, priority, buffer, size); } /** * \brief Wrapper for RawMessageQueue::tryPopUntil(std::chrono::time_point<TickClock, Duration>, uint8_t&, T&) */ template<typename Duration, typename U> int tryPopUntil(const std::chrono::time_point<TickClock, Duration> timePoint, uint8_t& priority, U& buffer) { return rawMessageQueue_.tryPopUntil(timePoint, priority, buffer); } /** * \brief Wrapper for RawMessageQueue::tryPush(uint8_t, const void*, size_t) */ int tryPush(const uint8_t priority, const void* const data, const size_t size) { return rawMessageQueue_.tryPush(priority, data, size); } /** * \brief Wrapper for RawMessageQueue::tryPush(uint8_t, const T&) */ template<typename U> int tryPush(const uint8_t priority, const U& data) { return rawMessageQueue_.tryPush(priority, data); } /** * \brief Wrapper for RawMessageQueue::tryPushFor(std::chrono::duration<Rep, Period>, uint8_t, const void*, size_t) */ template<typename Rep, typename Period> int tryPushFor(const std::chrono::duration<Rep, Period> duration, const uint8_t priority, const void* const data, const size_t size) { return rawMessageQueue_.tryPushFor(duration, priority, data, size); } /** * \brief Wrapper for RawMessageQueue::tryPushFor(std::chrono::duration<Rep, Period>, uint8_t, const T&) */ template<typename Rep, typename Period, typename U> int tryPushFor(const std::chrono::duration<Rep, Period> duration, const uint8_t priority, const U& data) { return rawMessageQueue_.tryPushFor(duration, priority, data); } /** * \brief Wrapper for * RawMessageQueue::tryPushUntil(std::chrono::time_point<TickClock, Duration>, uint8_t, const void*, size_t) */ template<typename Duration> int tryPushUntil(const std::chrono::time_point<TickClock, Duration> timePoint, const uint8_t priority, const void* const data, const size_t size) { return rawMessageQueue_.tryPushUntil(timePoint, priority, data, size); } /** * \brief Wrapper for RawMessageQueue::tryPushUntil(std::chrono::time_point<TickClock, Duration>, uint8_t, const T&) */ template<typename Duration, typename U> int tryPushUntil(const std::chrono::time_point<TickClock, Duration> timePoint, const uint8_t priority, const U& data) { return rawMessageQueue_.tryPushUntil(timePoint, priority, data); } private: /// storage for queue's entries std::array<RawMessageQueue::EntryStorage, QueueSize> entryStorage_; /// storage for queue's contents std::array<typename std::aligned_storage<sizeof(T), alignof(T)>::type, QueueSize> valueStorage_; /// internal RawMessageQueue object RawMessageQueue rawMessageQueue_; }; /** * \brief StaticRawMessageQueueFromSize type alias is a variant of StaticRawMessageQueue which uses size of element * (instead of type) as template argument. * * \param ElementSize is the size of single queue element, bytes * \param QueueSize is the maximum number of elements in queue */ template<size_t ElementSize, size_t QueueSize> using StaticRawMessageQueueFromSize = StaticRawMessageQueue<typename std::aligned_storage<ElementSize, ElementSize>::type, QueueSize>; } // namespace distortos #endif // INCLUDE_DISTORTOS_STATICRAWMESSAGEQUEUE_HPP_ <|endoftext|>
<commit_before>/************************************************************************* * * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * Copyright 2000, 2010 Oracle and/or its affiliates. * * OpenOffice.org - a multi-platform office productivity suite * * This file is part of OpenOffice.org. * * OpenOffice.org is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License version 3 * only, as published by the Free Software Foundation. * * OpenOffice.org 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 version 3 for more details * (a copy is included in the LICENSE file that accompanied this code). * * You should have received a copy of the GNU Lesser General Public License * version 3 along with OpenOffice.org. If not, see * <http://www.openoffice.org/license.html> * for a copy of the LGPLv3 License. * ************************************************************************/ #include "oox/drawingml/chart/chartspaceconverter.hxx" #include <com/sun/star/chart/MissingValueTreatment.hpp> #include <com/sun/star/chart/XChartDocument.hpp> #include <com/sun/star/chart2/XChartDocument.hpp> #include <com/sun/star/chart2/XTitled.hpp> #include <com/sun/star/chart2/data/XDataReceiver.hpp> #include <com/sun/star/drawing/XDrawPageSupplier.hpp> #include "oox/core/xmlfilterbase.hxx" #include "oox/drawingml/chart/chartconverter.hxx" #include "oox/drawingml/chart/chartdrawingfragment.hxx" #include "oox/drawingml/chart/chartspacemodel.hxx" #include "oox/drawingml/chart/plotareaconverter.hxx" #include "oox/drawingml/chart/titleconverter.hxx" #include "properties.hxx" using ::rtl::OUString; using ::com::sun::star::awt::Point; using ::com::sun::star::uno::Reference; using ::com::sun::star::uno::Exception; using ::com::sun::star::uno::UNO_QUERY; using ::com::sun::star::uno::UNO_QUERY_THROW; using ::com::sun::star::uno::makeAny; using ::com::sun::star::util::XNumberFormatsSupplier; using ::com::sun::star::drawing::XDrawPageSupplier; using ::com::sun::star::drawing::XShapes; using ::com::sun::star::chart2::XDiagram; using ::com::sun::star::chart2::XTitled; using ::com::sun::star::chart2::data::XDataReceiver; using ::com::sun::star::beans::XPropertySet; namespace oox { namespace drawingml { namespace chart { // ============================================================================ using namespace ::com::sun::star::awt; using namespace ::com::sun::star::chart2; using namespace ::com::sun::star::chart2::data; using namespace ::com::sun::star::drawing; using namespace ::com::sun::star::uno; using namespace ::com::sun::star::util; using ::rtl::OUString; // ============================================================================ ChartSpaceConverter::ChartSpaceConverter( const ConverterRoot& rParent, ChartSpaceModel& rModel ) : ConverterBase< ChartSpaceModel >( rParent, rModel ) { } ChartSpaceConverter::~ChartSpaceConverter() { } void ChartSpaceConverter::convertFromModel( const Reference< XShapes >& rxExternalPage, const Point& rChartPos ) { /* create data provider (virtual function in the ChartConverter class, derived converters may create an external data provider) */ getChartConverter().createDataProvider( getChartDocument() ); // attach number formatter of container document to data receiver try { Reference< XDataReceiver > xDataRec( getChartDocument(), UNO_QUERY_THROW ); Reference< XNumberFormatsSupplier > xNumFmtSupp( getFilter().getModel(), UNO_QUERY_THROW ); xDataRec->attachNumberFormatsSupplier( xNumFmtSupp ); } catch( Exception& ) { } // formatting of the chart background PropertySet aBackPropSet( getChartDocument()->getPageBackground() ); getFormatter().convertFrameFormatting( aBackPropSet, mrModel.mxShapeProp, OBJECTTYPE_CHARTSPACE ); // convert plot area (container of all chart type groups) PlotAreaConverter aPlotAreaConv( *this, mrModel.mxPlotArea.getOrCreate() ); aPlotAreaConv.convertFromModel( mrModel.mxView3D.getOrCreate() ); // plot area converter has created the diagram object Reference< XDiagram > xDiagram = getChartDocument()->getFirstDiagram(); // convert wall and floor formatting in 3D charts if( xDiagram.is() && aPlotAreaConv.isWall3dChart() ) { WallFloorConverter aFloorConv( *this, mrModel.mxFloor.getOrCreate() ); aFloorConv.convertFromModel( xDiagram, OBJECTTYPE_FLOOR ); WallFloorConverter aWallConv( *this, mrModel.mxBackWall.getOrCreate() ); aWallConv.convertFromModel( xDiagram, OBJECTTYPE_WALL ); } // chart title if( !mrModel.mbAutoTitleDel ) try { /* If the title model is missing, but the chart shows exactly one series, the series title is shown as chart title. */ OUString aAutoTitle = aPlotAreaConv.getAutomaticTitle(); if( mrModel.mxTitle.is() || (aAutoTitle.getLength() > 0) ) { if( aAutoTitle.getLength() == 0 ) aAutoTitle = CREATE_OUSTRING( "Chart Title" ); Reference< XTitled > xTitled( getChartDocument(), UNO_QUERY_THROW ); TitleConverter aTitleConv( *this, mrModel.mxTitle.getOrCreate() ); aTitleConv.convertFromModel( xTitled, aAutoTitle, OBJECTTYPE_CHARTTITLE ); } } catch( Exception& ) { } // legend if( xDiagram.is() && mrModel.mxLegend.is() ) { LegendConverter aLegendConv( *this, *mrModel.mxLegend ); aLegendConv.convertFromModel( xDiagram ); } // treatment of missing values if( xDiagram.is() ) { using namespace ::com::sun::star::chart::MissingValueTreatment; sal_Int32 nMissingValues = LEAVE_GAP; switch( mrModel.mnDispBlanksAs ) { case XML_gap: nMissingValues = LEAVE_GAP; break; case XML_zero: nMissingValues = USE_ZERO; break; case XML_span: nMissingValues = CONTINUE; break; } PropertySet aDiaProp( xDiagram ); aDiaProp.setProperty( PROP_MissingValueTreatment, nMissingValues ); } /* Following all conversions needing the old Chart1 API that involves full initialization of the chart view. */ namespace cssc = ::com::sun::star::chart; Reference< cssc::XChartDocument > xChart1Doc( getChartDocument(), UNO_QUERY ); if( xChart1Doc.is() ) { /* Set the IncludeHiddenCells property via the old API as only this ensures that the data provider and all created sequences get this flag correctly. */ PropertySet aDiaProp( xChart1Doc->getDiagram() ); aDiaProp.setProperty( PROP_IncludeHiddenCells, !mrModel.mbPlotVisOnly ); // plot area position and size aPlotAreaConv.convertPositionFromModel(); // positions of main title and all axis titles convertTitlePositions(); } // embedded drawing shapes if( mrModel.maDrawingPath.getLength() > 0 ) try { /* Get the internal draw page of the chart document, if no external drawing page has been passed. */ Reference< XShapes > xShapes; Point aShapesOffset( 0, 0 ); if( rxExternalPage.is() ) { xShapes = rxExternalPage; // offset for embedded shapes to move them inside the chart area aShapesOffset = rChartPos; } else { Reference< XDrawPageSupplier > xDrawPageSupp( getChartDocument(), UNO_QUERY_THROW ); xShapes.set( xDrawPageSupp->getDrawPage(), UNO_QUERY_THROW ); } /* If an external drawing page is passed, all embedded shapes will be inserted there (used e.g. with 'chart sheets' in spreadsheet documents). In this case, all types of shapes including OLE objects are supported. If the shapes are inserted into the internal chart drawing page instead, it is not possible to embed OLE objects. */ bool bOleSupport = rxExternalPage.is(); // now, xShapes is not null anymore getFilter().importFragment( new ChartDrawingFragment( getFilter(), mrModel.maDrawingPath, xShapes, getChartSize(), aShapesOffset, bOleSupport ) ); } catch( Exception& ) { } // pivot chart if ( mrModel.mbPivotChart ) { PropertySet aProps( getChartDocument() ); aProps.setProperty( PROP_DisableDataTableDialog , true ); aProps.setProperty( PROP_DisableComplexChartTypes , true ); } } // ============================================================================ } // namespace chart } // namespace drawingml } // namespace oox <commit_msg>masterfix: #i10000# header file removed<commit_after>/************************************************************************* * * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * Copyright 2000, 2010 Oracle and/or its affiliates. * * OpenOffice.org - a multi-platform office productivity suite * * This file is part of OpenOffice.org. * * OpenOffice.org is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License version 3 * only, as published by the Free Software Foundation. * * OpenOffice.org 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 version 3 for more details * (a copy is included in the LICENSE file that accompanied this code). * * You should have received a copy of the GNU Lesser General Public License * version 3 along with OpenOffice.org. If not, see * <http://www.openoffice.org/license.html> * for a copy of the LGPLv3 License. * ************************************************************************/ #include "oox/drawingml/chart/chartspaceconverter.hxx" #include <com/sun/star/chart/MissingValueTreatment.hpp> #include <com/sun/star/chart/XChartDocument.hpp> #include <com/sun/star/chart2/XChartDocument.hpp> #include <com/sun/star/chart2/XTitled.hpp> #include <com/sun/star/chart2/data/XDataReceiver.hpp> #include <com/sun/star/drawing/XDrawPageSupplier.hpp> #include "oox/core/xmlfilterbase.hxx" #include "oox/drawingml/chart/chartconverter.hxx" #include "oox/drawingml/chart/chartdrawingfragment.hxx" #include "oox/drawingml/chart/chartspacemodel.hxx" #include "oox/drawingml/chart/plotareaconverter.hxx" #include "oox/drawingml/chart/titleconverter.hxx" using ::rtl::OUString; using ::com::sun::star::awt::Point; using ::com::sun::star::uno::Reference; using ::com::sun::star::uno::Exception; using ::com::sun::star::uno::UNO_QUERY; using ::com::sun::star::uno::UNO_QUERY_THROW; using ::com::sun::star::uno::makeAny; using ::com::sun::star::util::XNumberFormatsSupplier; using ::com::sun::star::drawing::XDrawPageSupplier; using ::com::sun::star::drawing::XShapes; using ::com::sun::star::chart2::XDiagram; using ::com::sun::star::chart2::XTitled; using ::com::sun::star::chart2::data::XDataReceiver; using ::com::sun::star::beans::XPropertySet; namespace oox { namespace drawingml { namespace chart { // ============================================================================ using namespace ::com::sun::star::awt; using namespace ::com::sun::star::chart2; using namespace ::com::sun::star::chart2::data; using namespace ::com::sun::star::drawing; using namespace ::com::sun::star::uno; using namespace ::com::sun::star::util; using ::rtl::OUString; // ============================================================================ ChartSpaceConverter::ChartSpaceConverter( const ConverterRoot& rParent, ChartSpaceModel& rModel ) : ConverterBase< ChartSpaceModel >( rParent, rModel ) { } ChartSpaceConverter::~ChartSpaceConverter() { } void ChartSpaceConverter::convertFromModel( const Reference< XShapes >& rxExternalPage, const Point& rChartPos ) { /* create data provider (virtual function in the ChartConverter class, derived converters may create an external data provider) */ getChartConverter().createDataProvider( getChartDocument() ); // attach number formatter of container document to data receiver try { Reference< XDataReceiver > xDataRec( getChartDocument(), UNO_QUERY_THROW ); Reference< XNumberFormatsSupplier > xNumFmtSupp( getFilter().getModel(), UNO_QUERY_THROW ); xDataRec->attachNumberFormatsSupplier( xNumFmtSupp ); } catch( Exception& ) { } // formatting of the chart background PropertySet aBackPropSet( getChartDocument()->getPageBackground() ); getFormatter().convertFrameFormatting( aBackPropSet, mrModel.mxShapeProp, OBJECTTYPE_CHARTSPACE ); // convert plot area (container of all chart type groups) PlotAreaConverter aPlotAreaConv( *this, mrModel.mxPlotArea.getOrCreate() ); aPlotAreaConv.convertFromModel( mrModel.mxView3D.getOrCreate() ); // plot area converter has created the diagram object Reference< XDiagram > xDiagram = getChartDocument()->getFirstDiagram(); // convert wall and floor formatting in 3D charts if( xDiagram.is() && aPlotAreaConv.isWall3dChart() ) { WallFloorConverter aFloorConv( *this, mrModel.mxFloor.getOrCreate() ); aFloorConv.convertFromModel( xDiagram, OBJECTTYPE_FLOOR ); WallFloorConverter aWallConv( *this, mrModel.mxBackWall.getOrCreate() ); aWallConv.convertFromModel( xDiagram, OBJECTTYPE_WALL ); } // chart title if( !mrModel.mbAutoTitleDel ) try { /* If the title model is missing, but the chart shows exactly one series, the series title is shown as chart title. */ OUString aAutoTitle = aPlotAreaConv.getAutomaticTitle(); if( mrModel.mxTitle.is() || (aAutoTitle.getLength() > 0) ) { if( aAutoTitle.getLength() == 0 ) aAutoTitle = CREATE_OUSTRING( "Chart Title" ); Reference< XTitled > xTitled( getChartDocument(), UNO_QUERY_THROW ); TitleConverter aTitleConv( *this, mrModel.mxTitle.getOrCreate() ); aTitleConv.convertFromModel( xTitled, aAutoTitle, OBJECTTYPE_CHARTTITLE ); } } catch( Exception& ) { } // legend if( xDiagram.is() && mrModel.mxLegend.is() ) { LegendConverter aLegendConv( *this, *mrModel.mxLegend ); aLegendConv.convertFromModel( xDiagram ); } // treatment of missing values if( xDiagram.is() ) { using namespace ::com::sun::star::chart::MissingValueTreatment; sal_Int32 nMissingValues = LEAVE_GAP; switch( mrModel.mnDispBlanksAs ) { case XML_gap: nMissingValues = LEAVE_GAP; break; case XML_zero: nMissingValues = USE_ZERO; break; case XML_span: nMissingValues = CONTINUE; break; } PropertySet aDiaProp( xDiagram ); aDiaProp.setProperty( PROP_MissingValueTreatment, nMissingValues ); } /* Following all conversions needing the old Chart1 API that involves full initialization of the chart view. */ namespace cssc = ::com::sun::star::chart; Reference< cssc::XChartDocument > xChart1Doc( getChartDocument(), UNO_QUERY ); if( xChart1Doc.is() ) { /* Set the IncludeHiddenCells property via the old API as only this ensures that the data provider and all created sequences get this flag correctly. */ PropertySet aDiaProp( xChart1Doc->getDiagram() ); aDiaProp.setProperty( PROP_IncludeHiddenCells, !mrModel.mbPlotVisOnly ); // plot area position and size aPlotAreaConv.convertPositionFromModel(); // positions of main title and all axis titles convertTitlePositions(); } // embedded drawing shapes if( mrModel.maDrawingPath.getLength() > 0 ) try { /* Get the internal draw page of the chart document, if no external drawing page has been passed. */ Reference< XShapes > xShapes; Point aShapesOffset( 0, 0 ); if( rxExternalPage.is() ) { xShapes = rxExternalPage; // offset for embedded shapes to move them inside the chart area aShapesOffset = rChartPos; } else { Reference< XDrawPageSupplier > xDrawPageSupp( getChartDocument(), UNO_QUERY_THROW ); xShapes.set( xDrawPageSupp->getDrawPage(), UNO_QUERY_THROW ); } /* If an external drawing page is passed, all embedded shapes will be inserted there (used e.g. with 'chart sheets' in spreadsheet documents). In this case, all types of shapes including OLE objects are supported. If the shapes are inserted into the internal chart drawing page instead, it is not possible to embed OLE objects. */ bool bOleSupport = rxExternalPage.is(); // now, xShapes is not null anymore getFilter().importFragment( new ChartDrawingFragment( getFilter(), mrModel.maDrawingPath, xShapes, getChartSize(), aShapesOffset, bOleSupport ) ); } catch( Exception& ) { } // pivot chart if ( mrModel.mbPivotChart ) { PropertySet aProps( getChartDocument() ); aProps.setProperty( PROP_DisableDataTableDialog , true ); aProps.setProperty( PROP_DisableComplexChartTypes , true ); } } // ============================================================================ } // namespace chart } // namespace drawingml } // namespace oox <|endoftext|>
<commit_before>/* * This file is open source software, licensed to you under the terms * of the Apache License, Version 2.0 (the "License"). See the NOTICE file * distributed with this work for additional information regarding copyright * ownership. You may not use this file except in compliance with the License. * * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ /* * Copyright (C) 2019 Scylla DB Ltd */ #include <boost/range/adaptor/filtered.hpp> #include <seastar/core/scheduling.hh> #include <array> #include <vector> #pragma once namespace seastar { namespace internal { struct scheduling_group_specific_thread_local_data { struct per_scheduling_group { bool queue_is_initialized = false; /** * This array holds pointers to the scheduling group specific * data. The pointer is not use as is but is cast to a reference * to the appropriate type that is actually pointed to. */ std::vector<void*> specific_vals; }; std::array<per_scheduling_group, max_scheduling_groups()> per_scheduling_group_data; std::vector<scheduling_group_key_config> scheduling_group_key_configs; }; inline scheduling_group_specific_thread_local_data** get_scheduling_group_specific_thread_local_data_ptr() noexcept { static thread_local scheduling_group_specific_thread_local_data* data; return &data; } inline scheduling_group_specific_thread_local_data& get_scheduling_group_specific_thread_local_data() noexcept { return **get_scheduling_group_specific_thread_local_data_ptr(); } [[noreturn]] void no_such_scheduling_group(scheduling_group sg); /** * Returns a pointer to the given scheduling group specific data. * @param sg - The scheduling group which it's data needs to be accessed * @param key - The scheduling group key that for the data to access * @return A pointer of type T* to the data, if sg is valid initialized. * * @note The parameter T has to be given since there is no way to deduce it. */ template<typename T> T* scheduling_group_get_specific_ptr(scheduling_group sg, scheduling_group_key key) noexcept { auto& data = internal::get_scheduling_group_specific_thread_local_data(); #ifdef SEASTAR_DEBUG assert(std::type_index(typeid(T)) == data.scheduling_group_key_configs[key.id()].type_index); #endif auto sg_id = internal::scheduling_group_index(sg); if (__builtin_expect(sg_id < data.per_scheduling_group_data.size() && data.per_scheduling_group_data[sg_id].queue_is_initialized, true)) { return reinterpret_cast<T*>(data.per_scheduling_group_data[sg_id].specific_vals[key.id()]); } return nullptr; } } /** * Returns a reference to the given scheduling group specific data. * @param sg - The scheduling group which it's data needs to be accessed * @param key - The scheduling group key that for the data to access * @return A reference of type T& to the data. * * @note The parameter T has to be given since there is no way to deduce it. */ template<typename T> T& scheduling_group_get_specific(scheduling_group sg, scheduling_group_key key) { T* p = internal::scheduling_group_get_specific_ptr<T>(sg, std::move(key)); if (!p) { internal::no_such_scheduling_group(sg); } return *p; } /** * Returns a reference to the current specific data. * @param key - The scheduling group key that for the data to access * @return A reference of type T& to the data. * * @note The parameter T has to be given since there is no way to deduce it. */ template<typename T> T& scheduling_group_get_specific(scheduling_group_key key) { return *internal::scheduling_group_get_specific_ptr<T>(current_scheduling_group(), std::move(key)); } /** * A map reduce over all values of a specific scheduling group data. * @param mapper - A functor SomeType(SpecificValType&) or SomeType(SpecificValType) that maps * the specific data to a value of any type. * @param reducer - A functor of of type ConvetibleToInitial(Initial, MapperReurnType) that reduces * a value of type Initial and of the mapper return type to a value of type convertible to Initial. * @param initial_val - the initial value to pass in the first call to the reducer. * @param key - the key to the specific data that the mapper should act upon. * @return A future that resolves when the result of the map reduce is ready. * @note The type of SpecificValType must be given because there is no way to deduce it in a *consistent* * manner. * @note Theoretically the parameter type of Mapper can be deduced to be the type (function_traits<Mapper>::arg<0>) * but then there is a danger when the Mapper accepts a parameter type T where SpecificValType is convertible to * SpecificValType. */ template<typename SpecificValType, typename Mapper, typename Reducer, typename Initial> SEASTAR_CONCEPT( requires requires(SpecificValType specific_val, Mapper mapper, Reducer reducer, Initial initial) { {reducer(initial, mapper(specific_val))} -> std::convertible_to<Initial>; }) future<typename function_traits<Reducer>::return_type> map_reduce_scheduling_group_specific(Mapper mapper, Reducer reducer, Initial initial_val, scheduling_group_key key) { using per_scheduling_group = internal::scheduling_group_specific_thread_local_data::per_scheduling_group; auto& data = internal::get_scheduling_group_specific_thread_local_data(); auto wrapped_mapper = [key, mapper] (per_scheduling_group& psg) { auto id = internal::scheduling_group_key_id(key); return make_ready_future<typename function_traits<Mapper>::return_type> (mapper(*reinterpret_cast<SpecificValType*>(psg.specific_vals[id]))); }; return map_reduce( data.per_scheduling_group_data | boost::adaptors::filtered(std::mem_fn(&per_scheduling_group::queue_is_initialized)), wrapped_mapper, std::move(initial_val), reducer); } /** * A reduce over all values of a specific scheduling group data. * @param reducer - A functor of of type ConvetibleToInitial(Initial, SpecificValType) that reduces * a value of type Initial and of the sg specific data type to a value of type convertible to Initial. * @param initial_val - the initial value to pass in the first call to the reducer. * @param key - the key to the specific data that the mapper should act upon. * @return A future that resolves when the result of the reduce is ready. * * @note The type of SpecificValType must be given because there is no way to deduce it in a *consistent* * manner. * @note Theoretically the parameter type of Reducer can be deduced to be the type (function_traits<Reducer>::arg<0>) * but then there is a danger when the Reducer accepts a parameter type T where SpecificValType is convertible to * SpecificValType. */ template<typename SpecificValType, typename Reducer, typename Initial> SEASTAR_CONCEPT( requires requires(SpecificValType specific_val, Reducer reducer, Initial initial) { {reducer(initial, specific_val)} -> std::convertible_to<Initial>; }) future<typename function_traits<Reducer>::return_type> reduce_scheduling_group_specific(Reducer reducer, Initial initial_val, scheduling_group_key key) { using per_scheduling_group = internal::scheduling_group_specific_thread_local_data::per_scheduling_group; auto& data = internal::get_scheduling_group_specific_thread_local_data(); auto mapper = [key] (per_scheduling_group& psg) { auto id = internal::scheduling_group_key_id(key); return make_ready_future<SpecificValType>(*reinterpret_cast<SpecificValType*>(psg.specific_vals[id])); }; return map_reduce( data.per_scheduling_group_data | boost::adaptors::filtered(std::mem_fn(&per_scheduling_group::queue_is_initialized)), mapper, std::move(initial_val), reducer); } } <commit_msg>scheduling_specific: specify scheduling_group_get_specific as noexcept<commit_after>/* * This file is open source software, licensed to you under the terms * of the Apache License, Version 2.0 (the "License"). See the NOTICE file * distributed with this work for additional information regarding copyright * ownership. You may not use this file except in compliance with the License. * * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ /* * Copyright (C) 2019 Scylla DB Ltd */ #include <boost/range/adaptor/filtered.hpp> #include <seastar/core/scheduling.hh> #include <array> #include <vector> #pragma once namespace seastar { namespace internal { struct scheduling_group_specific_thread_local_data { struct per_scheduling_group { bool queue_is_initialized = false; /** * This array holds pointers to the scheduling group specific * data. The pointer is not use as is but is cast to a reference * to the appropriate type that is actually pointed to. */ std::vector<void*> specific_vals; }; std::array<per_scheduling_group, max_scheduling_groups()> per_scheduling_group_data; std::vector<scheduling_group_key_config> scheduling_group_key_configs; }; inline scheduling_group_specific_thread_local_data** get_scheduling_group_specific_thread_local_data_ptr() noexcept { static thread_local scheduling_group_specific_thread_local_data* data; return &data; } inline scheduling_group_specific_thread_local_data& get_scheduling_group_specific_thread_local_data() noexcept { return **get_scheduling_group_specific_thread_local_data_ptr(); } [[noreturn]] void no_such_scheduling_group(scheduling_group sg); /** * Returns a pointer to the given scheduling group specific data. * @param sg - The scheduling group which it's data needs to be accessed * @param key - The scheduling group key that for the data to access * @return A pointer of type T* to the data, if sg is valid initialized. * * @note The parameter T has to be given since there is no way to deduce it. */ template<typename T> T* scheduling_group_get_specific_ptr(scheduling_group sg, scheduling_group_key key) noexcept { auto& data = internal::get_scheduling_group_specific_thread_local_data(); #ifdef SEASTAR_DEBUG assert(std::type_index(typeid(T)) == data.scheduling_group_key_configs[key.id()].type_index); #endif auto sg_id = internal::scheduling_group_index(sg); if (__builtin_expect(sg_id < data.per_scheduling_group_data.size() && data.per_scheduling_group_data[sg_id].queue_is_initialized, true)) { return reinterpret_cast<T*>(data.per_scheduling_group_data[sg_id].specific_vals[key.id()]); } return nullptr; } } /** * Returns a reference to the given scheduling group specific data. * @param sg - The scheduling group which it's data needs to be accessed * @param key - The scheduling group key that for the data to access * @return A reference of type T& to the data. * * @note The parameter T has to be given since there is no way to deduce it. * May throw std::invalid_argument if sg does not exist or is uninitialized. */ template<typename T> T& scheduling_group_get_specific(scheduling_group sg, scheduling_group_key key) { T* p = internal::scheduling_group_get_specific_ptr<T>(sg, std::move(key)); if (!p) { internal::no_such_scheduling_group(sg); } return *p; } /** * Returns a reference to the current specific data. * @param key - The scheduling group key that for the data to access * @return A reference of type T& to the data. * * @note The parameter T has to be given since there is no way to deduce it. */ template<typename T> T& scheduling_group_get_specific(scheduling_group_key key) noexcept { return *internal::scheduling_group_get_specific_ptr<T>(current_scheduling_group(), std::move(key)); } /** * A map reduce over all values of a specific scheduling group data. * @param mapper - A functor SomeType(SpecificValType&) or SomeType(SpecificValType) that maps * the specific data to a value of any type. * @param reducer - A functor of of type ConvetibleToInitial(Initial, MapperReurnType) that reduces * a value of type Initial and of the mapper return type to a value of type convertible to Initial. * @param initial_val - the initial value to pass in the first call to the reducer. * @param key - the key to the specific data that the mapper should act upon. * @return A future that resolves when the result of the map reduce is ready. * @note The type of SpecificValType must be given because there is no way to deduce it in a *consistent* * manner. * @note Theoretically the parameter type of Mapper can be deduced to be the type (function_traits<Mapper>::arg<0>) * but then there is a danger when the Mapper accepts a parameter type T where SpecificValType is convertible to * SpecificValType. */ template<typename SpecificValType, typename Mapper, typename Reducer, typename Initial> SEASTAR_CONCEPT( requires requires(SpecificValType specific_val, Mapper mapper, Reducer reducer, Initial initial) { {reducer(initial, mapper(specific_val))} -> std::convertible_to<Initial>; }) future<typename function_traits<Reducer>::return_type> map_reduce_scheduling_group_specific(Mapper mapper, Reducer reducer, Initial initial_val, scheduling_group_key key) { using per_scheduling_group = internal::scheduling_group_specific_thread_local_data::per_scheduling_group; auto& data = internal::get_scheduling_group_specific_thread_local_data(); auto wrapped_mapper = [key, mapper] (per_scheduling_group& psg) { auto id = internal::scheduling_group_key_id(key); return make_ready_future<typename function_traits<Mapper>::return_type> (mapper(*reinterpret_cast<SpecificValType*>(psg.specific_vals[id]))); }; return map_reduce( data.per_scheduling_group_data | boost::adaptors::filtered(std::mem_fn(&per_scheduling_group::queue_is_initialized)), wrapped_mapper, std::move(initial_val), reducer); } /** * A reduce over all values of a specific scheduling group data. * @param reducer - A functor of of type ConvetibleToInitial(Initial, SpecificValType) that reduces * a value of type Initial and of the sg specific data type to a value of type convertible to Initial. * @param initial_val - the initial value to pass in the first call to the reducer. * @param key - the key to the specific data that the mapper should act upon. * @return A future that resolves when the result of the reduce is ready. * * @note The type of SpecificValType must be given because there is no way to deduce it in a *consistent* * manner. * @note Theoretically the parameter type of Reducer can be deduced to be the type (function_traits<Reducer>::arg<0>) * but then there is a danger when the Reducer accepts a parameter type T where SpecificValType is convertible to * SpecificValType. */ template<typename SpecificValType, typename Reducer, typename Initial> SEASTAR_CONCEPT( requires requires(SpecificValType specific_val, Reducer reducer, Initial initial) { {reducer(initial, specific_val)} -> std::convertible_to<Initial>; }) future<typename function_traits<Reducer>::return_type> reduce_scheduling_group_specific(Reducer reducer, Initial initial_val, scheduling_group_key key) { using per_scheduling_group = internal::scheduling_group_specific_thread_local_data::per_scheduling_group; auto& data = internal::get_scheduling_group_specific_thread_local_data(); auto mapper = [key] (per_scheduling_group& psg) { auto id = internal::scheduling_group_key_id(key); return make_ready_future<SpecificValType>(*reinterpret_cast<SpecificValType*>(psg.specific_vals[id])); }; return map_reduce( data.per_scheduling_group_data | boost::adaptors::filtered(std::mem_fn(&per_scheduling_group::queue_is_initialized)), mapper, std::move(initial_val), reducer); } } <|endoftext|>
<commit_before>/* Copyright © 2012 Jesse 'Jeaye' Wilkerson See licensing at: http://opensource.org/licenses/BSD-3-Clause File: main.cpp Author: Jesse 'Jeaye' Wilkerson */ #include <iostream> #include <stdint.h> #include <string> #include "value.h" int32_t main(int32_t argc, char **argv) { /* To start with, create the map and load the file. */ json_map map; map.load_file("doc/getting_started/myFile.json"); /* We can look at some specify top-level values with "get". Notice that "get" returns a reference to the object. */ std::string &str(map.get<std::string>("str")); // Get "str" as a string reference std::cout << "str = " << str << std::endl; json_array &arr(map.get_array("arr")); // get_array and get_map are convenience functions (void)arr; // avoid warnings /* A fallback value can also be specified with "get". It does two things: 1. Helps deduce the type so that an explicit invocation is not needed 2. Provides a default fallback value, should anything go wrong while accessing Note that these functions do NOT return references, due to incompatibilities with the fallback. */ std::string str_copy(map.get("str", "Default boringness")); // Second param is the defaulted string /* Delving into maps using dot-notated paths works, too. The type can be explicitly specified, or implicit based on the provided fallback. */ std::cout << map.get_for_path<std::string>("person.name") << " has " // No fallback << map.get_for_path("person.inventory.coins", 0) << " coins\n"; // Fallback is 0 /* Iterators work as expected, based on the C++ stdlib. (const and non-const) */ for(json_array::const_iterator it(arr.cbegin()); it != arr.cend(); ++it) std::cout << (*it).as<double>() << " "; std::cout << std::endl; } <commit_msg>Include jeayeson.h<commit_after>/* Copyright © 2012 Jesse 'Jeaye' Wilkerson See licensing at: http://opensource.org/licenses/BSD-3-Clause File: main.cpp Author: Jesse 'Jeaye' Wilkerson */ #include <iostream> #include <stdint.h> #include <string> #include "jeayeson.h" int32_t main(int32_t argc, char **argv) { /* To start with, create the map and load the file. */ json_map map; map.load_file("doc/getting_started/myFile.json"); /* We can look at some specify top-level values with "get". Notice that "get" returns a reference to the object. */ std::string &str(map.get<std::string>("str")); // Get "str" as a string reference std::cout << "str = " << str << std::endl; json_array &arr(map.get_array("arr")); // get_array and get_map are convenience functions (void)arr; // avoid warnings /* A fallback value can also be specified with "get". It does two things: 1. Helps deduce the type so that an explicit invocation is not needed 2. Provides a default fallback value, should anything go wrong while accessing Note that these functions do NOT return references, due to incompatibilities with the fallback. */ std::string str_copy(map.get("str", "Default boringness")); // Second param is the defaulted string /* Delving into maps using dot-notated paths works, too. The type can be explicitly specified, or implicit based on the provided fallback. */ std::cout << map.get_for_path<std::string>("person.name") << " has " // No fallback << map.get_for_path("person.inventory.coins", 0) << " coins\n"; // Fallback is 0 /* Iterators work as expected, based on the C++ stdlib. (const and non-const) */ for(json_array::const_iterator it(arr.cbegin()); it != arr.cend(); ++it) std::cout << (*it).as<double>() << " "; std::cout << std::endl; } <|endoftext|>
<commit_before>// This file is distributed under the MIT license. // See the LICENSE file for details. #include <array> #include <limits> #include "stack.h" #include "traverse.h" namespace visionaray { template <typename T, typename B> VSNRAY_FUNC inline hit_record<basic_ray<T>, primitive<unsigned>> intersect ( basic_ray<T> const& ray, B const& b ) { using namespace detail; hit_record<basic_ray<T>, primitive<unsigned>> result; result.hit = T(0.0); // result.t = T(std::numeric_limits<double>::max()); result.t = T(3.402823466e+38f); result.prim_id = T(0.0); stack<32> st; /*static*/ unsigned const Sentinel = unsigned(-1); st.push(Sentinel); unsigned addr = 0; auto node = b.node(addr); auto inv_dir = T(1.0) / ray.dir; for (;;) { if (is_leaf(node)) { auto begin = node.first_prim; auto end = node.first_prim + node.num_prims; for (auto i = begin; i != end; ++i) { auto prim = b.primitive(i); auto hr = intersect(ray, prim); auto closer = hr.hit & ( hr.t >= T(0.0) && hr.t < result.t ); result.hit |= closer; result.t = select( closer, hr.t, result.t ); result.prim_type = select( closer, hr.prim_type, result.prim_type ); result.prim_id = select( closer, hr.prim_id, result.prim_id ); result.geom_id = select( closer, hr.geom_id, result.geom_id ); result.u = select( closer, hr.u, result.u ); result.v = select( closer, hr.v, result.v ); } addr = st.pop(); } else { auto children = &b.node(node.first_child); auto hr1 = intersect(ray, children[0].bbox, inv_dir); auto hr2 = intersect(ray, children[1].bbox, inv_dir); auto b1 = hr1.tnear < hr1.tfar && hr1.tnear < result.t && hr1.tfar >= T(0.0); auto b2 = hr2.tnear < hr2.tfar && hr2.tnear < result.t && hr2.tfar >= T(0.0); if (any(b1) && any(b2)) { unsigned near_addr = all( hr1.tnear < hr2.tnear ) ? 0 : 1; st.push(node.first_child + (!near_addr)); addr = node.first_child + near_addr; } else if (any(b1)) { addr = node.first_child; } else if (any(b2)) { addr = node.first_child + 1; } else { addr = st.pop(); } } if (addr != Sentinel) { node = b.node(addr); } else { break; } } return result; } } // visionaray <commit_msg>Fix ray / bvh intersection<commit_after>// This file is distributed under the MIT license. // See the LICENSE file for details. #include <array> #include <limits> #include "stack.h" #include "traverse.h" namespace visionaray { template <typename T, typename B> VSNRAY_FUNC inline hit_record<basic_ray<T>, primitive<unsigned>> intersect ( basic_ray<T> const& ray, B const& b ) { using namespace detail; hit_record<basic_ray<T>, primitive<unsigned>> result; result.hit = T(0.0); // result.t = T(std::numeric_limits<double>::max()); result.t = T(3.402823466e+38f); result.prim_id = T(0.0); stack<32> st; /*static*/ unsigned const Sentinel = unsigned(-1); st.push(Sentinel); unsigned addr = 0; auto node = b.node(addr); auto inv_dir = T(1.0) / ray.dir; for (;;) { if (is_leaf(node)) { auto begin = node.first_prim; auto end = node.first_prim + node.num_prims; for (auto i = begin; i != end; ++i) { auto prim = b.primitive(i); auto hr = intersect(ray, prim); auto closer = hr.hit & ( hr.t >= T(0.0) && hr.t < result.t ); result.hit |= closer; result.t = select( closer, hr.t, result.t ); result.prim_type = select( closer, hr.prim_type, result.prim_type ); result.prim_id = select( closer, hr.prim_id, result.prim_id ); result.geom_id = select( closer, hr.geom_id, result.geom_id ); result.u = select( closer, hr.u, result.u ); result.v = select( closer, hr.v, result.v ); } addr = st.pop(); } else { auto children = &b.node(node.first_child); auto hr1 = intersect(ray, children[0].bbox, inv_dir); auto hr2 = intersect(ray, children[1].bbox, inv_dir); auto b1 = hr1.tnear <= hr1.tfar && hr1.tnear < result.t && hr1.tfar >= T(0.0); auto b2 = hr2.tnear <= hr2.tfar && hr2.tnear < result.t && hr2.tfar >= T(0.0); if (any(b1) && any(b2)) { unsigned near_addr = all( hr1.tnear < hr2.tnear ) ? 0 : 1; st.push(node.first_child + (!near_addr)); addr = node.first_child + near_addr; } else if (any(b1)) { addr = node.first_child; } else if (any(b2)) { addr = node.first_child + 1; } else { addr = st.pop(); } } if (addr != Sentinel) { node = b.node(addr); } else { break; } } return result; } } // visionaray <|endoftext|>
<commit_before>#include <iostream> #include <multi_value.h> #include "logger/log.h" #include "command.h" INITIALIZE_EASYLOGGINGPP class FuckDemo { public: void help() { LOG(INFO) << "fuck helper -- "; }; void version() { LOG(INFO) << "fuck version -- "; } void classPath(std::string cp) { LOG(INFO) << "fuck cp -- " << cp; } void getJrePath(std::string cp) { LOG(INFO) << "fuck jre -- " << cp; } void getClass(std::string classFile) { LOG(INFO) << "fuck class -- " << classFile; } void getArgs(std::string args) { // for (auto arg : args) { // LOG(INFO) << "fuck args -- " << arg; // } } }; int main(int argc, char *argv[]) { FuckDemo demo; printf("%s \n", getenv("JAVA_HOME")); // print help message auto help = std::make_shared<cmd::Option<void>>("-h", "Help", std::bind(&FuckDemo::help, &demo)); // vm version auto version = std::make_shared<cmd::Option<void>>("-v", "Version", std::bind(&FuckDemo::version, &demo)); // multi parts of class path auto multiPath = std::make_shared<cmd::Option<std::string>>("-cp", "ClassPath", std::bind(&FuckDemo::classPath, &demo, std::placeholders::_1)); // class path auto classPath = std::make_shared<cmd::MultiValue>(";", multiPath); auto xJreOption = std::make_shared<cmd::Option<std::string>>("XjreOption", "JRE PATH", std::bind(&FuckDemo::getJrePath, &demo, std::placeholders::_1) ); // class file auto classFile = std::make_shared<cmd::Option<std::string>>("-class", "Class", std::bind(&FuckDemo::getClass, &demo, std::placeholders::_1)); auto args = std::make_shared<cmd::Option<std::string>>("-args", "Args", std::bind(&FuckDemo::getArgs, &demo, std::placeholders::_1)); cmd::Command command(argc, argv, {help, version, xJreOption, classPath, classFile, args}); return 0; } <commit_msg>update args<commit_after>#include <iostream> #include <multi_value.h> #include "logger/log.h" #include "command.h" INITIALIZE_EASYLOGGINGPP class FuckDemo { public: void help() { LOG(INFO) << "fuck helper -- "; }; void version() { LOG(INFO) << "fuck version -- "; } void classPath(std::string cp) { LOG(INFO) << "fuck cp -- " << cp; } void getJrePath(std::string cp) { LOG(INFO) << "fuck jre -- " << cp; } void getClass(std::string classFile) { LOG(INFO) << "fuck class -- " << classFile; } void getArgs(std::string args) { LOG(INFO) << "fuck args -- " << args; } }; int main(int argc, char *argv[]) { FuckDemo demo; printf("%s \n", getenv("JAVA_HOME")); // print help message auto help = std::make_shared<cmd::Option<void>>("-h", "Help", std::bind(&FuckDemo::help, &demo)); // vm version auto version = std::make_shared<cmd::Option<void>>("-v", "Version", std::bind(&FuckDemo::version, &demo)); // multi parts of class path auto multiPath = std::make_shared<cmd::Option<std::string>>("-cp", "ClassPath", std::bind(&FuckDemo::classPath, &demo, std::placeholders::_1)); // class path auto classPath = std::make_shared<cmd::MultiValue>(";", multiPath); auto xJreOption = std::make_shared<cmd::Option<std::string>>("XjreOption", "JRE PATH", std::bind(&FuckDemo::getJrePath, &demo, std::placeholders::_1) ); // class file auto classFile = std::make_shared<cmd::Option<std::string>>("-class", "Class", std::bind(&FuckDemo::getClass, &demo, std::placeholders::_1)); auto arg = std::make_shared<cmd::Option<std::string>>("-args", "Args", std::bind(&FuckDemo::getArgs, &demo, std::placeholders::_1)); auto args = std::make_shared<cmd::MultiValue>(";", arg); cmd::Command command(argc, argv, {help, version, xJreOption, classPath, classFile, args}); return 0; } <|endoftext|>
<commit_before>/*************************************************************************** * Copyright (C) 1998-2010 by authors (see AUTHORS.txt ) * * * * This file is part of LuxRays. * * * * LuxRays 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. * * * * LuxRays 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/>. * * * * LuxRays website: http://www.luxrender.net * ***************************************************************************/ #if !defined(LUXRAYS_DISABLE_OPENCL) #include <iostream> #include <fstream> #include <boost/lexical_cast.hpp> #include <boost/filesystem.hpp> #include <string.h> #include "luxrays/utils/ocl/utils.h" using namespace luxrays; using namespace luxrays::utils; // Helper function to get error string std::string luxrays::utils::oclErrorString(cl_int error) { switch (error) { case CL_SUCCESS: return "CL_SUCCESS"; case CL_DEVICE_NOT_FOUND: return "CL_DEVICE_NOT_FOUND"; case CL_DEVICE_NOT_AVAILABLE: return "CL_DEVICE_NOT_AVAILABLE"; case CL_COMPILER_NOT_AVAILABLE: return "CL_COMPILER_NOT_AVAILABLE"; case CL_MEM_OBJECT_ALLOCATION_FAILURE: return "CL_MEM_OBJECT_ALLOCATION_FAILURE"; case CL_OUT_OF_RESOURCES: return "CL_OUT_OF_RESOURCES"; case CL_OUT_OF_HOST_MEMORY: return "CL_OUT_OF_HOST_MEMORY"; case CL_PROFILING_INFO_NOT_AVAILABLE: return "CL_PROFILING_INFO_NOT_AVAILABLE"; case CL_MEM_COPY_OVERLAP: return "CL_MEM_COPY_OVERLAP"; case CL_IMAGE_FORMAT_MISMATCH: return "CL_IMAGE_FORMAT_MISMATCH"; case CL_IMAGE_FORMAT_NOT_SUPPORTED: return "CL_IMAGE_FORMAT_NOT_SUPPORTED"; case CL_BUILD_PROGRAM_FAILURE: return "CL_BUILD_PROGRAM_FAILURE"; case CL_MAP_FAILURE: return "CL_MAP_FAILURE"; #ifdef CL_VERSION_1_1 case CL_MISALIGNED_SUB_BUFFER_OFFSET: return "CL_MISALIGNED_SUB_BUFFER_OFFSET"; case CL_EXEC_STATUS_ERROR_FOR_EVENTS_IN_WAIT_LIST: return "CL_EXEC_STATUS_ERROR_FOR_EVENTS_IN_WAIT_LIST"; #endif case CL_INVALID_VALUE: return "CL_INVALID_VALUE"; case CL_INVALID_DEVICE_TYPE: return "CL_INVALID_DEVICE_TYPE"; case CL_INVALID_PLATFORM: return "CL_INVALID_PLATFORM"; case CL_INVALID_DEVICE: return "CL_INVALID_DEVICE"; case CL_INVALID_CONTEXT: return "CL_INVALID_CONTEXT"; case CL_INVALID_QUEUE_PROPERTIES: return "CL_INVALID_QUEUE_PROPERTIES"; case CL_INVALID_COMMAND_QUEUE: return "CL_INVALID_COMMAND_QUEUE"; case CL_INVALID_HOST_PTR: return "CL_INVALID_HOST_PTR"; case CL_INVALID_MEM_OBJECT: return "CL_INVALID_MEM_OBJECT"; case CL_INVALID_IMAGE_FORMAT_DESCRIPTOR: return "CL_INVALID_IMAGE_FORMAT_DESCRIPTOR"; case CL_INVALID_IMAGE_SIZE: return "CL_INVALID_IMAGE_SIZE"; case CL_INVALID_SAMPLER: return "CL_INVALID_SAMPLER"; case CL_INVALID_BINARY: return "CL_INVALID_BINARY"; case CL_INVALID_BUILD_OPTIONS: return "CL_INVALID_BUILD_OPTIONS"; case CL_INVALID_PROGRAM: return "CL_INVALID_PROGRAM"; case CL_INVALID_PROGRAM_EXECUTABLE: return "CL_INVALID_PROGRAM_EXECUTABLE"; case CL_INVALID_KERNEL_NAME: return "CL_INVALID_KERNEL_NAME"; case CL_INVALID_KERNEL_DEFINITION: return "CL_INVALID_KERNEL_DEFINITION"; case CL_INVALID_KERNEL: return "CL_INVALID_KERNEL"; case CL_INVALID_ARG_INDEX: return "CL_INVALID_ARG_INDEX"; case CL_INVALID_ARG_VALUE: return "CL_INVALID_ARG_VALUE"; case CL_INVALID_ARG_SIZE: return "CL_INVALID_ARG_SIZE"; case CL_INVALID_KERNEL_ARGS: return "CL_INVALID_KERNEL_ARGS"; case CL_INVALID_WORK_DIMENSION: return "CL_INVALID_WORK_DIMENSION"; case CL_INVALID_WORK_GROUP_SIZE: return "CL_INVALID_WORK_GROUP_SIZE"; case CL_INVALID_WORK_ITEM_SIZE: return "CL_INVALID_WORK_ITEM_SIZE"; case CL_INVALID_GLOBAL_OFFSET: return "CL_INVALID_GLOBAL_OFFSET"; case CL_INVALID_EVENT_WAIT_LIST: return "CL_INVALID_EVENT_WAIT_LIST"; case CL_INVALID_EVENT: return "CL_INVALID_EVENT"; case CL_INVALID_OPERATION: return "CL_INVALID_OPERATION"; case CL_INVALID_GL_OBJECT: return "CL_INVALID_GL_OBJECT"; case CL_INVALID_BUFFER_SIZE: return "CL_INVALID_BUFFER_SIZE"; case CL_INVALID_MIP_LEVEL: return "CL_INVALID_MIP_LEVEL"; case CL_INVALID_GLOBAL_WORK_SIZE: return "CL_INVALID_GLOBAL_WORK_SIZE"; default: return boost::lexical_cast<std::string > (error); } } //------------------------------------------------------------------------------ // oclKernelCache //------------------------------------------------------------------------------ cl::Program *oclKernelCache::ForcedCompile(cl::Context &context, cl::Device &device, const std::string &kernelsParameters, const std::string &kernelSource) { cl::Program::Sources source(1, std::make_pair(kernelSource.c_str(), kernelSource.length())); cl::Program *program = new cl::Program(context, source); VECTOR_CLASS<cl::Device> buildDevice; buildDevice.push_back(device); program->build(buildDevice, kernelsParameters.c_str()); return program; } //------------------------------------------------------------------------------ // oclKernelVolatileCache //------------------------------------------------------------------------------ oclKernelVolatileCache::oclKernelVolatileCache() { } oclKernelVolatileCache::~oclKernelVolatileCache() { for (std::vector<char *>::iterator it = kernels.begin(); it != kernels.end(); it++) delete[] (*it); } cl::Program *oclKernelVolatileCache::Compile(cl::Context &context, cl::Device& device, const std::string &kernelsParameters, const std::string &kernelSource, bool *cached) { // Check if the kernel is available in the cache std::map<std::string, cl::Program::Binaries>::iterator it = kernelCache.find(kernelsParameters); if (it == kernelCache.end()) { // It isn't available, compile the source cl::Program *program = ForcedCompile( context, device, kernelsParameters, kernelSource); // Obtain the binaries of the sources VECTOR_CLASS<char *> bins = program->getInfo<CL_PROGRAM_BINARIES>(); assert (bins.size() == 1); VECTOR_CLASS<size_t> sizes = program->getInfo<CL_PROGRAM_BINARY_SIZES>(); assert (sizes.size() == 1); if (sizes[0] > 0) { // Add the kernel to the cache char *bin = new char[sizes[0]]; memcpy(bin, bins[0], sizes[0]); kernels.push_back(bin); kernelCache[kernelsParameters] = cl::Program::Binaries(1, std::make_pair(bin, sizes[0])); } if (cached) *cached = false; return program; } else { // Compile from the binaries VECTOR_CLASS<cl::Device> buildDevice; buildDevice.push_back(device); cl::Program *program = new cl::Program(context, buildDevice, it->second); program->build(buildDevice); if (cached) *cached = true; return program; } } //------------------------------------------------------------------------------ // oclKernelPersistentCache //------------------------------------------------------------------------------ oclKernelPersistentCache::oclKernelPersistentCache(const std::string &applicationName) { appName = applicationName; // Crate the cache directory boost::filesystem::create_directories("kernel_cache/" + appName); } oclKernelPersistentCache::~oclKernelPersistentCache() { } // Bob Jenkins's One-at-a-Time hash // From: http://eternallyconfuzzled.com/tuts/algorithms/jsw_tut_hashing.aspx std::string oclKernelPersistentCache::HashString(const std::string &ss) { const char *s = ss.c_str(); uint32_t hash = 0; for (; *s; ++s) { hash += *s; hash += (hash << 10); hash ^= (hash >> 6); } hash += (hash << 3); hash ^= (hash >> 11); hash += (hash << 15); char buf[9]; sprintf(buf, "%08x", hash); return std::string(buf); } cl::Program *oclKernelPersistentCache::Compile(cl::Context &context, cl::Device& device, const std::string &kernelsParameters, const std::string &kernelSource, bool *cached) { // Check if the kernel is available in the cache cl::Platform platform = device.getInfo<CL_DEVICE_PLATFORM>(); std::string platformName = platform.getInfo<CL_PLATFORM_VENDOR>(); std::string deviceName = device.getInfo<CL_DEVICE_NAME>(); std::string kernelName = HashString(kernelsParameters) + "-" + HashString(kernelSource) + ".ocl"; std::string dirName = "kernel_cache/" + appName + "/" + platformName + "/" + deviceName; std::string fileName = dirName +"/" +kernelName; if (!boost::filesystem::exists(fileName)) { // It isn't available, compile the source cl::Program *program = ForcedCompile( context, device, kernelsParameters, kernelSource); // Obtain the binaries of the sources VECTOR_CLASS<char *> bins = program->getInfo<CL_PROGRAM_BINARIES>(); assert (bins.size() == 1); VECTOR_CLASS<size_t> sizes = program->getInfo<CL_PROGRAM_BINARY_SIZES >(); assert (sizes.size() == 1); std::cerr << "DEBUG: Kernel binary size = " << sizes[0] << std::endl; // Create the file only if the binaries include something if (sizes[0] > 0) { // Add the kernel to the cache boost::filesystem::create_directories(dirName); std::ofstream file(fileName.c_str(), std::ios_base::out | std::ios_base::binary); file.write(bins[0], sizes[0]); // Check for errors char buf[512]; if (file.fail()) { sprintf(buf, "Unable to write kernel file cache %s", fileName.c_str()); throw std::runtime_error(buf); } file.close(); } if (cached) *cached = false; return program; } else { const size_t kernelSize = boost::filesystem::file_size(fileName); if (kernelSize > 0) { char *kernelBin = new char[kernelSize]; std::ifstream file(fileName.c_str(), std::ios_base::in | std::ios_base::binary); file.read(kernelBin, kernelSize); // Check for errors char buf[512]; if (file.fail()) { sprintf(buf, "Unable to read kernel file cache %s", fileName.c_str()); throw std::runtime_error(buf); } file.close(); // Compile from the binaries VECTOR_CLASS<cl::Device> buildDevice; buildDevice.push_back(device); cl::Program *program = new cl::Program(context, buildDevice, cl::Program::Binaries(1, std::make_pair(kernelBin, kernelSize))); program->build(buildDevice); if (cached) *cached = true; delete[] kernelBin; return program; } else { // Something wrong in the file, remove the file and retry boost::filesystem::remove(fileName); return Compile(context, device, kernelsParameters, kernelSource, cached); } } } #endif <commit_msg>Fixed a type problem on Windows<commit_after>/*************************************************************************** * Copyright (C) 1998-2010 by authors (see AUTHORS.txt ) * * * * This file is part of LuxRays. * * * * LuxRays 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. * * * * LuxRays 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/>. * * * * LuxRays website: http://www.luxrender.net * ***************************************************************************/ #if !defined(LUXRAYS_DISABLE_OPENCL) #include <iostream> #include <fstream> #include <boost/lexical_cast.hpp> #include <boost/filesystem.hpp> #include <string.h> #include "luxrays/utils/ocl/utils.h" using namespace luxrays; using namespace luxrays::utils; // Helper function to get error string std::string luxrays::utils::oclErrorString(cl_int error) { switch (error) { case CL_SUCCESS: return "CL_SUCCESS"; case CL_DEVICE_NOT_FOUND: return "CL_DEVICE_NOT_FOUND"; case CL_DEVICE_NOT_AVAILABLE: return "CL_DEVICE_NOT_AVAILABLE"; case CL_COMPILER_NOT_AVAILABLE: return "CL_COMPILER_NOT_AVAILABLE"; case CL_MEM_OBJECT_ALLOCATION_FAILURE: return "CL_MEM_OBJECT_ALLOCATION_FAILURE"; case CL_OUT_OF_RESOURCES: return "CL_OUT_OF_RESOURCES"; case CL_OUT_OF_HOST_MEMORY: return "CL_OUT_OF_HOST_MEMORY"; case CL_PROFILING_INFO_NOT_AVAILABLE: return "CL_PROFILING_INFO_NOT_AVAILABLE"; case CL_MEM_COPY_OVERLAP: return "CL_MEM_COPY_OVERLAP"; case CL_IMAGE_FORMAT_MISMATCH: return "CL_IMAGE_FORMAT_MISMATCH"; case CL_IMAGE_FORMAT_NOT_SUPPORTED: return "CL_IMAGE_FORMAT_NOT_SUPPORTED"; case CL_BUILD_PROGRAM_FAILURE: return "CL_BUILD_PROGRAM_FAILURE"; case CL_MAP_FAILURE: return "CL_MAP_FAILURE"; #ifdef CL_VERSION_1_1 case CL_MISALIGNED_SUB_BUFFER_OFFSET: return "CL_MISALIGNED_SUB_BUFFER_OFFSET"; case CL_EXEC_STATUS_ERROR_FOR_EVENTS_IN_WAIT_LIST: return "CL_EXEC_STATUS_ERROR_FOR_EVENTS_IN_WAIT_LIST"; #endif case CL_INVALID_VALUE: return "CL_INVALID_VALUE"; case CL_INVALID_DEVICE_TYPE: return "CL_INVALID_DEVICE_TYPE"; case CL_INVALID_PLATFORM: return "CL_INVALID_PLATFORM"; case CL_INVALID_DEVICE: return "CL_INVALID_DEVICE"; case CL_INVALID_CONTEXT: return "CL_INVALID_CONTEXT"; case CL_INVALID_QUEUE_PROPERTIES: return "CL_INVALID_QUEUE_PROPERTIES"; case CL_INVALID_COMMAND_QUEUE: return "CL_INVALID_COMMAND_QUEUE"; case CL_INVALID_HOST_PTR: return "CL_INVALID_HOST_PTR"; case CL_INVALID_MEM_OBJECT: return "CL_INVALID_MEM_OBJECT"; case CL_INVALID_IMAGE_FORMAT_DESCRIPTOR: return "CL_INVALID_IMAGE_FORMAT_DESCRIPTOR"; case CL_INVALID_IMAGE_SIZE: return "CL_INVALID_IMAGE_SIZE"; case CL_INVALID_SAMPLER: return "CL_INVALID_SAMPLER"; case CL_INVALID_BINARY: return "CL_INVALID_BINARY"; case CL_INVALID_BUILD_OPTIONS: return "CL_INVALID_BUILD_OPTIONS"; case CL_INVALID_PROGRAM: return "CL_INVALID_PROGRAM"; case CL_INVALID_PROGRAM_EXECUTABLE: return "CL_INVALID_PROGRAM_EXECUTABLE"; case CL_INVALID_KERNEL_NAME: return "CL_INVALID_KERNEL_NAME"; case CL_INVALID_KERNEL_DEFINITION: return "CL_INVALID_KERNEL_DEFINITION"; case CL_INVALID_KERNEL: return "CL_INVALID_KERNEL"; case CL_INVALID_ARG_INDEX: return "CL_INVALID_ARG_INDEX"; case CL_INVALID_ARG_VALUE: return "CL_INVALID_ARG_VALUE"; case CL_INVALID_ARG_SIZE: return "CL_INVALID_ARG_SIZE"; case CL_INVALID_KERNEL_ARGS: return "CL_INVALID_KERNEL_ARGS"; case CL_INVALID_WORK_DIMENSION: return "CL_INVALID_WORK_DIMENSION"; case CL_INVALID_WORK_GROUP_SIZE: return "CL_INVALID_WORK_GROUP_SIZE"; case CL_INVALID_WORK_ITEM_SIZE: return "CL_INVALID_WORK_ITEM_SIZE"; case CL_INVALID_GLOBAL_OFFSET: return "CL_INVALID_GLOBAL_OFFSET"; case CL_INVALID_EVENT_WAIT_LIST: return "CL_INVALID_EVENT_WAIT_LIST"; case CL_INVALID_EVENT: return "CL_INVALID_EVENT"; case CL_INVALID_OPERATION: return "CL_INVALID_OPERATION"; case CL_INVALID_GL_OBJECT: return "CL_INVALID_GL_OBJECT"; case CL_INVALID_BUFFER_SIZE: return "CL_INVALID_BUFFER_SIZE"; case CL_INVALID_MIP_LEVEL: return "CL_INVALID_MIP_LEVEL"; case CL_INVALID_GLOBAL_WORK_SIZE: return "CL_INVALID_GLOBAL_WORK_SIZE"; default: return boost::lexical_cast<std::string > (error); } } //------------------------------------------------------------------------------ // oclKernelCache //------------------------------------------------------------------------------ cl::Program *oclKernelCache::ForcedCompile(cl::Context &context, cl::Device &device, const std::string &kernelsParameters, const std::string &kernelSource) { cl::Program::Sources source(1, std::make_pair(kernelSource.c_str(), kernelSource.length())); cl::Program *program = new cl::Program(context, source); VECTOR_CLASS<cl::Device> buildDevice; buildDevice.push_back(device); program->build(buildDevice, kernelsParameters.c_str()); return program; } //------------------------------------------------------------------------------ // oclKernelVolatileCache //------------------------------------------------------------------------------ oclKernelVolatileCache::oclKernelVolatileCache() { } oclKernelVolatileCache::~oclKernelVolatileCache() { for (std::vector<char *>::iterator it = kernels.begin(); it != kernels.end(); it++) delete[] (*it); } cl::Program *oclKernelVolatileCache::Compile(cl::Context &context, cl::Device& device, const std::string &kernelsParameters, const std::string &kernelSource, bool *cached) { // Check if the kernel is available in the cache std::map<std::string, cl::Program::Binaries>::iterator it = kernelCache.find(kernelsParameters); if (it == kernelCache.end()) { // It isn't available, compile the source cl::Program *program = ForcedCompile( context, device, kernelsParameters, kernelSource); // Obtain the binaries of the sources VECTOR_CLASS<char *> bins = program->getInfo<CL_PROGRAM_BINARIES>(); assert (bins.size() == 1); VECTOR_CLASS<size_t> sizes = program->getInfo<CL_PROGRAM_BINARY_SIZES>(); assert (sizes.size() == 1); if (sizes[0] > 0) { // Add the kernel to the cache char *bin = new char[sizes[0]]; memcpy(bin, bins[0], sizes[0]); kernels.push_back(bin); kernelCache[kernelsParameters] = cl::Program::Binaries(1, std::make_pair(bin, sizes[0])); } if (cached) *cached = false; return program; } else { // Compile from the binaries VECTOR_CLASS<cl::Device> buildDevice; buildDevice.push_back(device); cl::Program *program = new cl::Program(context, buildDevice, it->second); program->build(buildDevice); if (cached) *cached = true; return program; } } //------------------------------------------------------------------------------ // oclKernelPersistentCache //------------------------------------------------------------------------------ oclKernelPersistentCache::oclKernelPersistentCache(const std::string &applicationName) { appName = applicationName; // Crate the cache directory boost::filesystem::create_directories("kernel_cache/" + appName); } oclKernelPersistentCache::~oclKernelPersistentCache() { } // Bob Jenkins's One-at-a-Time hash // From: http://eternallyconfuzzled.com/tuts/algorithms/jsw_tut_hashing.aspx std::string oclKernelPersistentCache::HashString(const std::string &ss) { const char *s = ss.c_str(); unsigned int hash = 0; for (; *s; ++s) { hash += *s; hash += (hash << 10); hash ^= (hash >> 6); } hash += (hash << 3); hash ^= (hash >> 11); hash += (hash << 15); char buf[9]; sprintf(buf, "%08x", hash); return std::string(buf); } cl::Program *oclKernelPersistentCache::Compile(cl::Context &context, cl::Device& device, const std::string &kernelsParameters, const std::string &kernelSource, bool *cached) { // Check if the kernel is available in the cache cl::Platform platform = device.getInfo<CL_DEVICE_PLATFORM>(); std::string platformName = platform.getInfo<CL_PLATFORM_VENDOR>(); std::string deviceName = device.getInfo<CL_DEVICE_NAME>(); std::string kernelName = HashString(kernelsParameters) + "-" + HashString(kernelSource) + ".ocl"; std::string dirName = "kernel_cache/" + appName + "/" + platformName + "/" + deviceName; std::string fileName = dirName +"/" +kernelName; if (!boost::filesystem::exists(fileName)) { // It isn't available, compile the source cl::Program *program = ForcedCompile( context, device, kernelsParameters, kernelSource); // Obtain the binaries of the sources VECTOR_CLASS<char *> bins = program->getInfo<CL_PROGRAM_BINARIES>(); assert (bins.size() == 1); VECTOR_CLASS<size_t> sizes = program->getInfo<CL_PROGRAM_BINARY_SIZES >(); assert (sizes.size() == 1); std::cerr << "DEBUG: Kernel binary size = " << sizes[0] << std::endl; // Create the file only if the binaries include something if (sizes[0] > 0) { // Add the kernel to the cache boost::filesystem::create_directories(dirName); std::ofstream file(fileName.c_str(), std::ios_base::out | std::ios_base::binary); file.write(bins[0], sizes[0]); // Check for errors char buf[512]; if (file.fail()) { sprintf(buf, "Unable to write kernel file cache %s", fileName.c_str()); throw std::runtime_error(buf); } file.close(); } if (cached) *cached = false; return program; } else { const size_t kernelSize = boost::filesystem::file_size(fileName); if (kernelSize > 0) { char *kernelBin = new char[kernelSize]; std::ifstream file(fileName.c_str(), std::ios_base::in | std::ios_base::binary); file.read(kernelBin, kernelSize); // Check for errors char buf[512]; if (file.fail()) { sprintf(buf, "Unable to read kernel file cache %s", fileName.c_str()); throw std::runtime_error(buf); } file.close(); // Compile from the binaries VECTOR_CLASS<cl::Device> buildDevice; buildDevice.push_back(device); cl::Program *program = new cl::Program(context, buildDevice, cl::Program::Binaries(1, std::make_pair(kernelBin, kernelSize))); program->build(buildDevice); if (cached) *cached = true; delete[] kernelBin; return program; } else { // Something wrong in the file, remove the file and retry boost::filesystem::remove(fileName); return Compile(context, device, kernelsParameters, kernelSource, cached); } } } #endif <|endoftext|>
<commit_before>/* This file is part of the PhantomJS project from Ofi Labs. Copyright (C) 2011 Ariya Hidayat <ariya.hidayat@gmail.com> 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 <organization> 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 <COPYRIGHT HOLDER> 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. */ #ifdef _WIN32 #define NOMINMAX #endif #include "consts.h" #include "utils.h" #include "env.h" #include "phantom.h" #ifdef Q_OS_LINUX #include "client/linux/handler/exception_handler.h" #endif #ifdef Q_OS_MAC #include "client/mac/handler/exception_handler.h" #endif #include <QApplication> #include <QSslSocket> #ifdef Q_OS_WIN32 using namespace google_breakpad; static google_breakpad::ExceptionHandler* eh; #if !defined(QT_SHARED) && !defined(QT_DLL) Q_IMPORT_PLUGIN(qico) #endif #endif #if QT_VERSION != QT_VERSION_CHECK(5, 1, 1) #error Something is wrong with the setup. Please report to the mailing list! #endif int main(int argc, char** argv, const char** envp) { // Setup Google Breakpad exception handler #ifdef Q_OS_LINUX google_breakpad::ExceptionHandler eh("/tmp", NULL, Utils::exceptionHandler, NULL, true); #endif #ifdef Q_OS_MAC google_breakpad::ExceptionHandler eh("/tmp", NULL, Utils::exceptionHandler, NULL, true, NULL); #endif #ifdef Q_OS_WIN32 // This is needed for CRT to not show dialog for invalid param // failures and instead let the code handle it. _CrtSetReportMode(_CRT_ASSERT, 0); DWORD cbBuffer = ExpandEnvironmentStrings(TEXT("%TEMP%"), NULL, 0); if (cbBuffer == 0) { eh = new ExceptionHandler(TEXT("."), NULL, Utils::exceptionHandler, NULL, ExceptionHandler::HANDLER_ALL); } else { LPWSTR szBuffer = reinterpret_cast<LPWSTR>(malloc(sizeof(TCHAR) * (cbBuffer + 1))); if (ExpandEnvironmentStrings(TEXT("%TEMP%"), szBuffer, cbBuffer + 1) > 0) { wstring lpDumpPath(szBuffer); eh = new ExceptionHandler(lpDumpPath, NULL, Utils::exceptionHandler, NULL, ExceptionHandler::HANDLER_ALL); } free(szBuffer); } #endif QApplication app(argc, argv); app.setWindowIcon(QIcon(":/phantomjs-icon.png")); app.setApplicationName("PhantomJS"); app.setOrganizationName("Ofi Labs"); app.setOrganizationDomain("www.ofilabs.com"); app.setApplicationVersion(PHANTOMJS_VERSION_STRING); // Prepare the "env" singleton using the environment variables Env::instance()->parse(envp); // Registering an alternative Message Handler qInstallMessageHandler(Utils::messageHandler); #if defined(Q_OS_LINUX) if (QSslSocket::supportsSsl()) { // Don't perform on-demand loading of root certificates on Linux QSslSocket::addDefaultCaCertificates(QSslSocket::systemCaCertificates()); } #endif // Get the Phantom singleton Phantom *phantom = Phantom::instance(); // Start script execution if (phantom->execute()) { app.exec(); } // End script execution: delete the phantom singleton and set execution return value int retVal = phantom->returnValue(); delete phantom; return retVal; } <commit_msg>Remove ICO plugin<commit_after>/* This file is part of the PhantomJS project from Ofi Labs. Copyright (C) 2011 Ariya Hidayat <ariya.hidayat@gmail.com> 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 <organization> 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 <COPYRIGHT HOLDER> 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. */ #ifdef _WIN32 #define NOMINMAX #endif #include "consts.h" #include "utils.h" #include "env.h" #include "phantom.h" #ifdef Q_OS_LINUX #include "client/linux/handler/exception_handler.h" #endif #ifdef Q_OS_MAC #include "client/mac/handler/exception_handler.h" #endif #include <QApplication> #include <QSslSocket> #ifdef Q_OS_WIN32 using namespace google_breakpad; static google_breakpad::ExceptionHandler* eh; #endif #if QT_VERSION != QT_VERSION_CHECK(5, 1, 1) #error Something is wrong with the setup. Please report to the mailing list! #endif int main(int argc, char** argv, const char** envp) { // Setup Google Breakpad exception handler #ifdef Q_OS_LINUX google_breakpad::ExceptionHandler eh("/tmp", NULL, Utils::exceptionHandler, NULL, true); #endif #ifdef Q_OS_MAC google_breakpad::ExceptionHandler eh("/tmp", NULL, Utils::exceptionHandler, NULL, true, NULL); #endif #ifdef Q_OS_WIN32 // This is needed for CRT to not show dialog for invalid param // failures and instead let the code handle it. _CrtSetReportMode(_CRT_ASSERT, 0); DWORD cbBuffer = ExpandEnvironmentStrings(TEXT("%TEMP%"), NULL, 0); if (cbBuffer == 0) { eh = new ExceptionHandler(TEXT("."), NULL, Utils::exceptionHandler, NULL, ExceptionHandler::HANDLER_ALL); } else { LPWSTR szBuffer = reinterpret_cast<LPWSTR>(malloc(sizeof(TCHAR) * (cbBuffer + 1))); if (ExpandEnvironmentStrings(TEXT("%TEMP%"), szBuffer, cbBuffer + 1) > 0) { wstring lpDumpPath(szBuffer); eh = new ExceptionHandler(lpDumpPath, NULL, Utils::exceptionHandler, NULL, ExceptionHandler::HANDLER_ALL); } free(szBuffer); } #endif QApplication app(argc, argv); app.setWindowIcon(QIcon(":/phantomjs-icon.png")); app.setApplicationName("PhantomJS"); app.setOrganizationName("Ofi Labs"); app.setOrganizationDomain("www.ofilabs.com"); app.setApplicationVersion(PHANTOMJS_VERSION_STRING); // Prepare the "env" singleton using the environment variables Env::instance()->parse(envp); // Registering an alternative Message Handler qInstallMessageHandler(Utils::messageHandler); #if defined(Q_OS_LINUX) if (QSslSocket::supportsSsl()) { // Don't perform on-demand loading of root certificates on Linux QSslSocket::addDefaultCaCertificates(QSslSocket::systemCaCertificates()); } #endif // Get the Phantom singleton Phantom *phantom = Phantom::instance(); // Start script execution if (phantom->execute()) { app.exec(); } // End script execution: delete the phantom singleton and set execution return value int retVal = phantom->returnValue(); delete phantom; return retVal; } <|endoftext|>
<commit_before> #include "common/Formatter.h" #include "rgw_swift.h" #include "rgw_rest_swift.h" #include <sstream> void RGWListBuckets_REST_SWIFT::send_response() { set_req_state_err(s, ret); dump_errno(s); dump_start(s); if (ret < 0) { end_header(s); return; } s->formatter->open_array_section("account"); // dump_owner(s, s->user.user_id, s->user.display_name); map<string, RGWBucketEnt>& m = buckets.get_buckets(); map<string, RGWBucketEnt>::iterator iter; string marker = s->args.get("marker"); if (marker.empty()) iter = m.begin(); else iter = m.upper_bound(marker); int limit = 10000; string limit_str = s->args.get("limit"); if (!limit_str.empty()) limit = atoi(limit_str.c_str()); for (int i = 0; i < limit && iter != m.end(); ++iter, ++i) { RGWBucketEnt obj = iter->second; s->formatter->open_object_section("container"); s->formatter->dump_format("name", obj.bucket.name.c_str()); s->formatter->dump_int("count", obj.count); s->formatter->dump_int("bytes", obj.size); s->formatter->close_section(); } s->formatter->close_section(); ostringstream oss; s->formatter->flush(oss); std::string outs(oss.str()); string::size_type outs_size = outs.size(); dump_content_length(s, outs_size); end_header(s); if (!outs.empty()) { CGI_PutStr(s, outs.c_str(), outs_size); } s->formatter->reset(); } void RGWListBucket_REST_SWIFT::send_response() { set_req_state_err(s, (ret < 0 ? ret : 0)); dump_errno(s); dump_start(s); if (ret < 0) { end_header(s); return; } vector<RGWObjEnt>::iterator iter = objs.begin(); map<string, bool>::iterator pref_iter = common_prefixes.begin(); s->formatter->open_array_section("container"); while (iter != objs.end() || pref_iter != common_prefixes.end()) { bool do_pref = false; bool do_objs = false; if (pref_iter == common_prefixes.end()) do_objs = true; else if (iter == objs.end()) do_pref = true; else if (iter->name.compare(pref_iter->first) == 0) { do_objs = true; pref_iter++; } else if (iter->name.compare(pref_iter->first) <= 0) do_objs = true; else do_pref = true; if (do_objs && (marker.empty() || iter->name.compare(marker) > 0)) { s->formatter->open_object_section("object"); s->formatter->dump_format("name", iter->name.c_str()); s->formatter->dump_format("hash", "\"%s\"", iter->etag); s->formatter->dump_int("bytes", iter->size); if (iter->content_type.size()) s->formatter->dump_format("content_type", iter->content_type.c_str()); dump_time(s, "last_modified", &iter->mtime); s->formatter->close_section(); } if (do_pref && (marker.empty() || pref_iter->first.compare(marker) > 0)) { s->formatter->open_object_section("object"); s->formatter->dump_format("name", pref_iter->first.c_str()); s->formatter->close_section(); } if (do_objs) iter++; else pref_iter++; } s->formatter->close_section(); end_header(s); flush_formatter_to_req_state(s, s->formatter); } static void dump_container_metadata(struct req_state *s, RGWBucketEnt& bucket) { char buf[16]; snprintf(buf, sizeof(buf), "%lld", (long long)bucket.count); CGI_PRINTF(s,"X-Container-Object-Count: %s\n", buf); snprintf(buf, sizeof(buf), "%lld", (long long)bucket.size); CGI_PRINTF(s,"X-Container-Bytes-Used: %s\n", buf); } void RGWStatBucket_REST_SWIFT::send_response() { if (ret >= 0) dump_container_metadata(s, bucket); if (ret < 0) set_req_state_err(s, ret); dump_errno(s); end_header(s); dump_start(s); flush_formatter_to_req_state(s, s->formatter); } void RGWCreateBucket_REST_SWIFT::send_response() { if (ret) set_req_state_err(s, ret); dump_errno(s); end_header(s); flush_formatter_to_req_state(s, s->formatter); } void RGWDeleteBucket_REST_SWIFT::send_response() { int r = ret; if (!r) r = 204; set_req_state_err(s, r); dump_errno(s); end_header(s); flush_formatter_to_req_state(s, s->formatter); } void RGWPutObj_REST_SWIFT::send_response() { if (!ret) ret = 201; // "created" dump_etag(s, etag.c_str()); set_req_state_err(s, ret); dump_errno(s); end_header(s); flush_formatter_to_req_state(s, s->formatter); } void RGWDeleteObj_REST_SWIFT::send_response() { int r = ret; if (!r) r = 204; set_req_state_err(s, r); dump_errno(s); end_header(s); flush_formatter_to_req_state(s, s->formatter); } int RGWGetObj_REST_SWIFT::send_response(void *handle) { const char *content_type = NULL; int orig_ret = ret; if (sent_header) goto send_data; if (range_str) dump_range(s, ofs, start, s->obj_size); dump_content_length(s, total_len); dump_last_modified(s, lastmod); if (!ret) { map<string, bufferlist>::iterator iter = attrs.find(RGW_ATTR_ETAG); if (iter != attrs.end()) { bufferlist& bl = iter->second; if (bl.length()) { char *etag = bl.c_str(); dump_etag(s, etag); } } for (iter = attrs.begin(); iter != attrs.end(); ++iter) { const char *name = iter->first.c_str(); if (strncmp(name, RGW_ATTR_META_PREFIX, sizeof(RGW_ATTR_META_PREFIX)-1) == 0) { name += sizeof(RGW_ATTR_PREFIX) - 1; CGI_PRINTF(s,"%s: %s\r\n", name, iter->second.c_str()); } else if (!content_type && strcmp(name, RGW_ATTR_CONTENT_TYPE) == 0) { content_type = iter->second.c_str(); } } } if (range_str && !ret) ret = 206; /* partial content */ if (ret) set_req_state_err(s, ret); dump_errno(s); if (!content_type) content_type = "binary/octet-stream"; end_header(s, content_type); sent_header = true; send_data: if (get_data && !orig_ret) { CGI_PutStr(s, data, len); } flush_formatter_to_req_state(s, s->formatter); return 0; } RGWOp *RGWHandler_REST_SWIFT::get_retrieve_obj_op(bool get_data) { if (is_acl_op()) { return new RGWGetACLs_REST_SWIFT; } if (s->object) { RGWGetObj_REST_SWIFT *get_obj_op = new RGWGetObj_REST_SWIFT; get_obj_op->set_get_data(get_data); return get_obj_op; } else if (!s->bucket_name) { return NULL; } if (get_data) return new RGWListBucket_REST_SWIFT; else return new RGWStatBucket_REST_SWIFT; } RGWOp *RGWHandler_REST_SWIFT::get_retrieve_op(bool get_data) { if (s->bucket_name) { if (is_acl_op()) { return new RGWGetACLs_REST_SWIFT; } return get_retrieve_obj_op(get_data); } return new RGWListBuckets_REST_SWIFT; } RGWOp *RGWHandler_REST_SWIFT::get_create_op() { if (is_acl_op()) { return new RGWPutACLs_REST_SWIFT; } else if (s->object) { if (!s->copy_source) return new RGWPutObj_REST_SWIFT; else return new RGWCopyObj_REST_SWIFT; } else if (s->bucket_name) { return new RGWCreateBucket_REST_SWIFT; } return NULL; } RGWOp *RGWHandler_REST_SWIFT::get_delete_op() { if (s->object) return new RGWDeleteObj_REST_SWIFT; else if (s->bucket_name) return new RGWDeleteBucket_REST_SWIFT; return NULL; } int RGWHandler_REST_SWIFT::authorize() { bool authorized = rgw_verify_os_token(s); if (!authorized) return -EPERM; s->perm_mask = RGW_PERM_FULL_CONTROL; return 0; } <commit_msg>rgw: pass POD c-string instead of string to formatter<commit_after> #include "common/Formatter.h" #include "rgw_swift.h" #include "rgw_rest_swift.h" #include <sstream> void RGWListBuckets_REST_SWIFT::send_response() { set_req_state_err(s, ret); dump_errno(s); dump_start(s); if (ret < 0) { end_header(s); return; } s->formatter->open_array_section("account"); // dump_owner(s, s->user.user_id, s->user.display_name); map<string, RGWBucketEnt>& m = buckets.get_buckets(); map<string, RGWBucketEnt>::iterator iter; string marker = s->args.get("marker"); if (marker.empty()) iter = m.begin(); else iter = m.upper_bound(marker); int limit = 10000; string limit_str = s->args.get("limit"); if (!limit_str.empty()) limit = atoi(limit_str.c_str()); for (int i = 0; i < limit && iter != m.end(); ++iter, ++i) { RGWBucketEnt obj = iter->second; s->formatter->open_object_section("container"); s->formatter->dump_format("name", obj.bucket.name.c_str()); s->formatter->dump_int("count", obj.count); s->formatter->dump_int("bytes", obj.size); s->formatter->close_section(); } s->formatter->close_section(); ostringstream oss; s->formatter->flush(oss); std::string outs(oss.str()); string::size_type outs_size = outs.size(); dump_content_length(s, outs_size); end_header(s); if (!outs.empty()) { CGI_PutStr(s, outs.c_str(), outs_size); } s->formatter->reset(); } void RGWListBucket_REST_SWIFT::send_response() { set_req_state_err(s, (ret < 0 ? ret : 0)); dump_errno(s); dump_start(s); if (ret < 0) { end_header(s); return; } vector<RGWObjEnt>::iterator iter = objs.begin(); map<string, bool>::iterator pref_iter = common_prefixes.begin(); s->formatter->open_array_section("container"); while (iter != objs.end() || pref_iter != common_prefixes.end()) { bool do_pref = false; bool do_objs = false; if (pref_iter == common_prefixes.end()) do_objs = true; else if (iter == objs.end()) do_pref = true; else if (iter->name.compare(pref_iter->first) == 0) { do_objs = true; pref_iter++; } else if (iter->name.compare(pref_iter->first) <= 0) do_objs = true; else do_pref = true; if (do_objs && (marker.empty() || iter->name.compare(marker) > 0)) { s->formatter->open_object_section("object"); s->formatter->dump_format("name", iter->name.c_str()); s->formatter->dump_format("hash", "\"%s\"", iter->etag.c_str()); s->formatter->dump_int("bytes", iter->size); if (iter->content_type.size()) s->formatter->dump_format("content_type", iter->content_type.c_str()); dump_time(s, "last_modified", &iter->mtime); s->formatter->close_section(); } if (do_pref && (marker.empty() || pref_iter->first.compare(marker) > 0)) { s->formatter->open_object_section("object"); s->formatter->dump_format("name", pref_iter->first.c_str()); s->formatter->close_section(); } if (do_objs) iter++; else pref_iter++; } s->formatter->close_section(); end_header(s); flush_formatter_to_req_state(s, s->formatter); } static void dump_container_metadata(struct req_state *s, RGWBucketEnt& bucket) { char buf[16]; snprintf(buf, sizeof(buf), "%lld", (long long)bucket.count); CGI_PRINTF(s,"X-Container-Object-Count: %s\n", buf); snprintf(buf, sizeof(buf), "%lld", (long long)bucket.size); CGI_PRINTF(s,"X-Container-Bytes-Used: %s\n", buf); } void RGWStatBucket_REST_SWIFT::send_response() { if (ret >= 0) dump_container_metadata(s, bucket); if (ret < 0) set_req_state_err(s, ret); dump_errno(s); end_header(s); dump_start(s); flush_formatter_to_req_state(s, s->formatter); } void RGWCreateBucket_REST_SWIFT::send_response() { if (ret) set_req_state_err(s, ret); dump_errno(s); end_header(s); flush_formatter_to_req_state(s, s->formatter); } void RGWDeleteBucket_REST_SWIFT::send_response() { int r = ret; if (!r) r = 204; set_req_state_err(s, r); dump_errno(s); end_header(s); flush_formatter_to_req_state(s, s->formatter); } void RGWPutObj_REST_SWIFT::send_response() { if (!ret) ret = 201; // "created" dump_etag(s, etag.c_str()); set_req_state_err(s, ret); dump_errno(s); end_header(s); flush_formatter_to_req_state(s, s->formatter); } void RGWDeleteObj_REST_SWIFT::send_response() { int r = ret; if (!r) r = 204; set_req_state_err(s, r); dump_errno(s); end_header(s); flush_formatter_to_req_state(s, s->formatter); } int RGWGetObj_REST_SWIFT::send_response(void *handle) { const char *content_type = NULL; int orig_ret = ret; if (sent_header) goto send_data; if (range_str) dump_range(s, ofs, start, s->obj_size); dump_content_length(s, total_len); dump_last_modified(s, lastmod); if (!ret) { map<string, bufferlist>::iterator iter = attrs.find(RGW_ATTR_ETAG); if (iter != attrs.end()) { bufferlist& bl = iter->second; if (bl.length()) { char *etag = bl.c_str(); dump_etag(s, etag); } } for (iter = attrs.begin(); iter != attrs.end(); ++iter) { const char *name = iter->first.c_str(); if (strncmp(name, RGW_ATTR_META_PREFIX, sizeof(RGW_ATTR_META_PREFIX)-1) == 0) { name += sizeof(RGW_ATTR_PREFIX) - 1; CGI_PRINTF(s,"%s: %s\r\n", name, iter->second.c_str()); } else if (!content_type && strcmp(name, RGW_ATTR_CONTENT_TYPE) == 0) { content_type = iter->second.c_str(); } } } if (range_str && !ret) ret = 206; /* partial content */ if (ret) set_req_state_err(s, ret); dump_errno(s); if (!content_type) content_type = "binary/octet-stream"; end_header(s, content_type); sent_header = true; send_data: if (get_data && !orig_ret) { CGI_PutStr(s, data, len); } flush_formatter_to_req_state(s, s->formatter); return 0; } RGWOp *RGWHandler_REST_SWIFT::get_retrieve_obj_op(bool get_data) { if (is_acl_op()) { return new RGWGetACLs_REST_SWIFT; } if (s->object) { RGWGetObj_REST_SWIFT *get_obj_op = new RGWGetObj_REST_SWIFT; get_obj_op->set_get_data(get_data); return get_obj_op; } else if (!s->bucket_name) { return NULL; } if (get_data) return new RGWListBucket_REST_SWIFT; else return new RGWStatBucket_REST_SWIFT; } RGWOp *RGWHandler_REST_SWIFT::get_retrieve_op(bool get_data) { if (s->bucket_name) { if (is_acl_op()) { return new RGWGetACLs_REST_SWIFT; } return get_retrieve_obj_op(get_data); } return new RGWListBuckets_REST_SWIFT; } RGWOp *RGWHandler_REST_SWIFT::get_create_op() { if (is_acl_op()) { return new RGWPutACLs_REST_SWIFT; } else if (s->object) { if (!s->copy_source) return new RGWPutObj_REST_SWIFT; else return new RGWCopyObj_REST_SWIFT; } else if (s->bucket_name) { return new RGWCreateBucket_REST_SWIFT; } return NULL; } RGWOp *RGWHandler_REST_SWIFT::get_delete_op() { if (s->object) return new RGWDeleteObj_REST_SWIFT; else if (s->bucket_name) return new RGWDeleteBucket_REST_SWIFT; return NULL; } int RGWHandler_REST_SWIFT::authorize() { bool authorized = rgw_verify_os_token(s); if (!authorized) return -EPERM; s->perm_mask = RGW_PERM_FULL_CONTROL; return 0; } <|endoftext|>
<commit_before>/* qgvdial is a cross platform Google Voice Dialer Copyright (C) 2010 Yuvraaj Kelkar This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA Contact: yuvraaj@gmail.com */ #include "MainApp.h" #include "MainWindow.h" #include "Singletons.h" #include <iostream> using namespace std; QtMsgHandler pOldHandler = NULL; MainWindow *pw = NULL; QFile fLogfile; //! Logfile int logLevel = 5; //! Log level void myMessageOutput(QtMsgType type, const char *msg) { int level = -1; switch (type) { case QtDebugMsg: level = 3; break; case QtWarningMsg: level = 2; break; case QtCriticalMsg: level = 1; break; case QtFatalMsg: level = 0; } QDateTime dt = QDateTime::currentDateTime (); QString strLog = QString("%1 : %2 : %3") .arg(dt.toString ("yyyy-MM-dd hh:mm:ss.zzz")) .arg(level) .arg(msg); // Send to standard output cout << strLog.toStdString () << endl; QRegExp regex("^\"(.*)\"\\s*"); if (strLog.indexOf (regex) != -1) { strLog = regex.cap (1); } if (strLog.contains ("password", Qt::CaseInsensitive)) { strLog = QString("%1 : %2 : %3") .arg(dt.toString ("yyyy-MM-dd hh:mm:ss.zzz")) .arg(level) .arg("Log message with password blocked"); } if ((level <= logLevel) && (NULL != pw)) { pw->log (strLog); } strLog += '\n'; if (level <= logLevel) { // Append it to the file fLogfile.write(strLog.toLatin1 ()); } if (NULL == pOldHandler) { if (NULL == pw) { fwrite (strLog.toLatin1 (), strLog.size (), 1, stderr); } if (QtFatalMsg == type) { abort(); } } else { pOldHandler (type, strLog.toLatin1 ()); } }//myMessageOutput static void initLogging () { OsDependent &osd = Singletons::getRef().getOSD (); QString strLogfile = osd.getAppDirectory (); strLogfile += QDir::separator (); strLogfile += "qgvdial.log"; fLogfile.setFileName (strLogfile); fLogfile.open (QIODevice::WriteOnly | QIODevice::Append); fLogfile.seek (fLogfile.size ()); pOldHandler = qInstallMsgHandler(myMessageOutput); }//initLogging static void deinitLogging () { pw = NULL; }//deinitLogging int main (int argc, char *argv[]) { #if defined(Q_WS_S60) MainApp::setAttribute (Qt::AA_S60DontConstructApplicationPanes); #endif initLogging (); MainApp app(argc, argv); bool bQuit = false; if ((app.argc() >= 2) && (0 == strcmp(app.argv()[1],"quit"))) { bQuit = true; } if (app.isRunning ()) { if (bQuit) { app.sendMessage ("quit"); } else { app.sendMessage ("show"); bQuit = true; } } if (bQuit == true) { return (0); } OsDependent &osd = Singletons::getRef().getOSD (); osd.init (); MainWindow w; pw = &w; app.setActivationWindow (&w); #if defined(Q_OS_SYMBIAN) app.setQuitOnLastWindowClosed (true); #else app.setQuitOnLastWindowClosed (false); #endif #if MOBILE_OS w.showFullScreen (); #else w.show(); #endif int rv = app.exec(); deinitLogging (); return (rv); }//main <commit_msg>flush logs periodically<commit_after>/* qgvdial is a cross platform Google Voice Dialer Copyright (C) 2010 Yuvraaj Kelkar This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA Contact: yuvraaj@gmail.com */ #include "MainApp.h" #include "MainWindow.h" #include "Singletons.h" #include <iostream> using namespace std; QtMsgHandler pOldHandler = NULL; MainWindow *pw = NULL; QFile fLogfile; //! Logfile int logLevel = 5; //! Log level int logCounter = 0; //! Number of log entries since the last log flush void myMessageOutput(QtMsgType type, const char *msg) { int level = -1; switch (type) { case QtDebugMsg: level = 3; break; case QtWarningMsg: level = 2; break; case QtCriticalMsg: level = 1; break; case QtFatalMsg: level = 0; } QDateTime dt = QDateTime::currentDateTime (); QString strLog = QString("%1 : %2 : %3") .arg(dt.toString ("yyyy-MM-dd hh:mm:ss.zzz")) .arg(level) .arg(msg); // Send to standard output cout << strLog.toStdString () << endl; QRegExp regex("^\"(.*)\"\\s*"); if (strLog.indexOf (regex) != -1) { strLog = regex.cap (1); } if (strLog.contains ("password", Qt::CaseInsensitive)) { strLog = QString("%1 : %2 : %3") .arg(dt.toString ("yyyy-MM-dd hh:mm:ss.zzz")) .arg(level) .arg("Log message with password blocked"); } if ((level <= logLevel) && (NULL != pw)) { pw->log (strLog); } strLog += '\n'; if (level <= logLevel) { if (fLogfile.isOpen ()) { // Append it to the file fLogfile.write(strLog.toLatin1 ()); ++logCounter; if (logCounter > 100) { logCounter = 0; fLogfile.flush (); } } } if (NULL == pOldHandler) { if (NULL == pw) { fwrite (strLog.toLatin1 (), strLog.size (), 1, stderr); } if (QtFatalMsg == type) { abort(); } } else { pOldHandler (type, strLog.toLatin1 ()); } }//myMessageOutput static void initLogging () { OsDependent &osd = Singletons::getRef().getOSD (); QString strLogfile = osd.getAppDirectory (); strLogfile += QDir::separator (); strLogfile += "qgvdial.log"; fLogfile.setFileName (strLogfile); fLogfile.open (QIODevice::WriteOnly | QIODevice::Append); fLogfile.seek (fLogfile.size ()); pOldHandler = qInstallMsgHandler(myMessageOutput); }//initLogging static void deinitLogging () { pw = NULL; fLogfile.close (); }//deinitLogging int main (int argc, char *argv[]) { #if defined(Q_WS_S60) MainApp::setAttribute (Qt::AA_S60DontConstructApplicationPanes); #endif initLogging (); MainApp app(argc, argv); bool bQuit = false; if ((app.argc() >= 2) && (0 == strcmp(app.argv()[1],"quit"))) { bQuit = true; } if (app.isRunning ()) { if (bQuit) { app.sendMessage ("quit"); } else { app.sendMessage ("show"); bQuit = true; } } if (bQuit == true) { return (0); } OsDependent &osd = Singletons::getRef().getOSD (); osd.init (); MainWindow w; pw = &w; app.setActivationWindow (&w); #if defined(Q_OS_SYMBIAN) app.setQuitOnLastWindowClosed (true); #else app.setQuitOnLastWindowClosed (false); #endif #if MOBILE_OS w.showFullScreen (); #else w.show(); #endif int rv = app.exec(); deinitLogging (); return (rv); }//main <|endoftext|>
<commit_before>#include <tclap/CmdLine.h> #include <llvm/IR/Module.h> #include <fstream> #include <sstream> #include <chrono> #include "utils/util.hpp" #include "utils/error.hpp" #include "lexer.hpp" #include "parser/tokenParser.hpp" #include "parser/xmlParser.hpp" #include "llvm/compiler.hpp" #include "llvm/runner.hpp" enum ExitCodes: int { NORMAL_EXIT = 0, ///< Everything is OK TCLAP_ERROR = 11, ///< TCLAP did something bad, should not happen CLI_ERROR = 1, ///< The user is retar-- uh I mean the user used a wrong option USER_PROGRAM_ERROR = 2, ///< The thing we had to lex/parse/run has an issue INTERNAL_ERROR = 3 ///< Unrecoverable error in this program, almost always a bug }; int notReallyMain(int argc, const char* argv[]); int main(int argc, const char* argv[]) { #ifdef XYLENE_MEASURE_TIME auto begin = std::chrono::steady_clock::now(); #endif int exitCode = notReallyMain(argc, argv); #ifdef XYLENE_MEASURE_TIME auto end = std::chrono::steady_clock::now(); println( "Time diff:", std::chrono::duration_cast<std::chrono::microseconds>(end - begin).count(), "μs" ); #endif return exitCode; } int notReallyMain(int argc, const char* argv[]) { try { TCLAP::CmdLine cmd("Xylene", ' ', "pre-release"); TCLAP::SwitchArg asXML("", "xml", "Read file using the XML parser", cmd); TCLAP::SwitchArg printTokens("", "tokens", "Print token list", cmd); TCLAP::SwitchArg printAST("", "ast", "Print AST (if applicable)", cmd); TCLAP::SwitchArg printIR("", "ir", "Print LLVM IR (if applicable)", cmd); TCLAP::SwitchArg doNotParse("", "no-parse", "Don't parse the token list", cmd); TCLAP::SwitchArg doNotRun("", "no-run", "Don't execute the AST", cmd); std::vector<std::string> runnerValues {"interpret", "compile"}; TCLAP::ValuesConstraint<std::string> runnerConstraint(runnerValues); TCLAP::ValueArg<std::string> runner("r", "runner", "How to run this code", false, "interpret", &runnerConstraint, cmd, nullptr); TCLAP::ValueArg<std::string> code("e", "eval", "Code to evaluate", false, std::string(), "string", cmd, nullptr); TCLAP::ValueArg<std::string> filePath("f", "file", "Load code from this file", false, std::string(), "path", cmd, nullptr); TCLAP::ValueArg<std::string> outPath("o", "output", "Write exe to this file", false, std::string(), "path", cmd, nullptr); cmd.parse(argc, argv); if (code.getValue().empty() && filePath.getValue().empty()) { TCLAP::ArgException arg("Must specify either option -e or -f"); cmd.getOutput()->failure(cmd, arg); } std::unique_ptr<AST> ast; if (asXML.getValue()) { if (doNotParse.getValue()) return NORMAL_EXIT; if (filePath.getValue().empty()) { TCLAP::ArgException arg("XML option only works with files"); cmd.getOutput()->failure(cmd, arg); } ast = std::make_unique<AST>(XMLParser().parse(rapidxml::file<>(filePath.getValue().c_str())).getTree()); } else { std::string input; if (!filePath.getValue().empty()) { std::ifstream file(filePath.getValue()); std::stringstream buffer; buffer << file.rdbuf(); input = buffer.str(); } else { input = code.getValue(); } auto lx = Lexer(); lx.tokenize(input, filePath.getValue().empty() ? "<cli-eval>" : filePath.getValue()); if (printTokens.getValue()) for (auto tok : lx.getTokens()) println(tok); if (doNotParse.getValue()) return NORMAL_EXIT; ast = std::make_unique<AST>(TokenParser().parse(lx.getTokens()).getTree()); } if (printAST.getValue()) ast->print(); if (doNotRun.getValue()) return NORMAL_EXIT; ModuleCompiler::Link v = ModuleCompiler::create("Command Line Module", *ast); v->visit(); if (printIR.getValue()) v->getModule()->dump(); if (runner.getValue() == "interpret") { return Runner(v).run(); } else if (runner.getValue() == "compile") { // TODO: rearrange this somehow, right now the module is compiled twice Compiler cp(filePath.getValue(), outPath.getValue()); cp.compile(); return NORMAL_EXIT; } } catch (const TCLAP::ExitException& arg) { return CLI_ERROR; } catch (const TCLAP::ArgException& arg) { println("TCLAP error", arg.error(), "for", arg.argId()); return TCLAP_ERROR; } catch (const Error& err) { println(err.what()); return USER_PROGRAM_ERROR; } // If we're debugging, crash the program on InternalError #ifndef CRASH_ON_INTERNAL_ERROR catch (const InternalError& err) { println(err.what()); return INTERNAL_ERROR; } #endif return 0; } <commit_msg>Update CLI<commit_after>#include <tclap/CmdLine.h> #include <llvm/IR/Module.h> #include <fstream> #include <sstream> #include <chrono> #include "utils/util.hpp" #include "utils/error.hpp" #include "lexer.hpp" #include "parser/tokenParser.hpp" #include "parser/xmlParser.hpp" #include "llvm/compiler.hpp" #include "llvm/runner.hpp" enum ExitCodes: int { NORMAL_EXIT = 0, ///< Everything is OK TCLAP_ERROR = 11, ///< TCLAP did something bad, should not happen CLI_ERROR = 1, ///< The user used a wrong combination of options USER_PROGRAM_ERROR = 2, ///< The thing we had to lex/parse/run has an issue INTERNAL_ERROR = 3 ///< Unrecoverable error in this program, almost always a bug }; #pragma GCC diagnostic push #pragma GCC diagnostic ignored "-Wmissing-declarations" std::unique_ptr<AST> parseXML(fs::path filePath, std::string cliEval) { if (!filePath.empty()) { // Read from file auto file = rapidxml::file<>(filePath.c_str()); return std::make_unique<AST>(XMLParser().parse(file).getTree()); } else { // Read from CLI char* mutableCode = new char[cliEval.size() + 1]; std::move(ALL(cliEval), mutableCode); mutableCode[cliEval.size()] = '\0'; return std::make_unique<AST>(XMLParser().parse(mutableCode).getTree()); } } std::vector<Token> tokenize(fs::path filePath, std::string cliEval) { std::string input; if (!filePath.empty()) { std::ifstream file(filePath); std::stringstream buffer; buffer << file.rdbuf(); input = buffer.str(); } else { input = cliEval; } auto lx = Lexer(); return lx.tokenize(input, filePath.empty() ? "<cli-eval>" : filePath).getTokens(); } void assertCliIntegrity(TCLAP::CmdLine& cmd, bool value, std::string message) { if (!value) return; TCLAP::ArgException arg(message); cmd.getOutput()->failure(cmd, arg); } int notReallyMain(int argc, const char* argv[]) { try { TCLAP::CmdLine cmd("Xylene", ' ', "pre-release"); TCLAP::SwitchArg asXML("", "xml", "Read file using the XML parser", cmd); TCLAP::SwitchArg printTokens("", "tokens", "Print token list (if applicable)", cmd); TCLAP::SwitchArg printAST("", "ast", "Print AST (if applicable)", cmd); TCLAP::SwitchArg printIR("", "ir", "Print LLVM IR (if applicable)", cmd); TCLAP::SwitchArg doNotParse("", "no-parse", "Don't parse the token list", cmd); TCLAP::SwitchArg doNotRun("", "no-run", "Don't execute the AST", cmd); std::vector<std::string> runnerValues {"interpret", "compile"}; TCLAP::ValuesConstraint<std::string> runnerConstraint(runnerValues); TCLAP::ValueArg<std::string> runner("r", "runner", "How to run this code", false, "interpret", &runnerConstraint, cmd, nullptr); TCLAP::ValueArg<std::string> code("e", "eval", "Code to evaluate", false, std::string(), "string", cmd, nullptr); TCLAP::ValueArg<std::string> filePath("f", "file", "Load code from this file", false, std::string(), "path", cmd, nullptr); TCLAP::ValueArg<std::string> outPath("o", "output", "Write exe to this file", false, std::string(), "path", cmd, nullptr); cmd.parse(argc, argv); // There must be at least one input assertCliIntegrity(cmd, code.getValue().empty() && filePath.getValue().empty(), "Must specify either option -e or -f"); // There is not much you can do to the XML without parsing it assertCliIntegrity(cmd, asXML.getValue() && doNotParse.getValue(), "--no-parse and --xml are incompatible"); // The XML parser does not use tokens assertCliIntegrity(cmd, asXML.getValue() && printTokens.getValue(), "--tokens and --xml are incompatible"); // Can't print AST without creating it first assertCliIntegrity(cmd, printAST.getValue() && doNotParse.getValue(), "--no-parse and --ast are incompatible"); // Can't print IR without parsing the AST assertCliIntegrity(cmd, printIR.getValue() && doNotParse.getValue(), "--no-parse and --ir are incompatible"); std::unique_ptr<AST> ast; if (asXML.getValue()) { ast = parseXML(filePath.getValue(), code.getValue()); } else { auto tokens = tokenize(filePath.getValue(), code.getValue()); if (printTokens.getValue()) for (auto tok : tokens) println(tok); if (doNotParse.getValue()) return NORMAL_EXIT; ast = std::make_unique<AST>(TokenParser().parse(tokens).getTree()); } if (printAST.getValue()) ast->print(); if (doNotRun.getValue()) return NORMAL_EXIT; ModuleCompiler::Link mc = ModuleCompiler::create("Command Line Module", *ast); mc->visit(); if (printIR.getValue()) mc->getModule()->dump(); if (runner.getValue() == "interpret") { return Runner(mc).run(); } else if (runner.getValue() == "compile") { Compiler(std::unique_ptr<llvm::Module>(mc->getModule()), filePath.getValue(), outPath.getValue()).compile(); return NORMAL_EXIT; } } catch (const TCLAP::ExitException& arg) { return CLI_ERROR; } catch (const TCLAP::ArgException& arg) { println("TCLAP error", arg.error(), "for", arg.argId()); return TCLAP_ERROR; } catch (const Error& err) { println(err.what()); return USER_PROGRAM_ERROR; } // If we're debugging, crash the program on InternalError #ifndef CRASH_ON_INTERNAL_ERROR catch (const InternalError& err) { println(err.what()); return INTERNAL_ERROR; } #endif return 0; } #pragma GCC diagnostic pop int main(int argc, const char* argv[]) { #ifdef XYLENE_MEASURE_TIME auto begin = std::chrono::steady_clock::now(); #endif int exitCode = notReallyMain(argc, argv); #ifdef XYLENE_MEASURE_TIME auto end = std::chrono::steady_clock::now(); println( "Time diff:", std::chrono::duration_cast<std::chrono::microseconds>(end - begin).count(), "μs" ); #endif return exitCode; } <|endoftext|>
<commit_before>/* * Copyright 2014-2020 Real Logic Limited. * * 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 * * https://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. */ #include <exception> #include <functional> #include <string> #include <gtest/gtest.h> #include "aeron_client_test_utils.h" extern "C" { #include "aeron_subscription.h" #include "aeron_image.h" } #define FILE_PAGE_SIZE (4 * 1024) #define SUB_URI "aeron:udp?endpoint=localhost:24567" #define STREAM_ID (101) #define SESSION_ID (110) #define REGISTRATION_ID (27) using namespace aeron::test; class SubscriptionTest : public testing::Test { public: SubscriptionTest() : m_conductor(nullptr), m_subscription(createSubscription(m_conductor, &m_channel_status)) { } ~SubscriptionTest() override { if (nullptr != m_subscription) { aeron_subscription_delete(m_subscription); } std::for_each(m_filenames.begin(), m_filenames.end(), [&](std::string &filename) { ::unlink(filename.c_str()); }); } static aeron_subscription_t *createSubscription(aeron_client_conductor_t *conductor, int64_t *channel_status) { aeron_subscription_t *subscription = nullptr; if (aeron_subscription_create( &subscription, conductor, ::strdup(SUB_URI), STREAM_ID, REGISTRATION_ID, channel_status, nullptr, nullptr, nullptr, nullptr) < 0) { throw std::runtime_error("could not create subscription: %s" + std::string(aeron_errmsg())); } return subscription; } int64_t createImage(int64_t *subscriber_position) { aeron_image_t *image = nullptr; aeron_log_buffer_t *log_buffer = nullptr; std::string filename = tempFileName(); createLogFile(filename); if (aeron_log_buffer_create(&log_buffer, filename.c_str(), m_correlationId, false) < 0) { throw std::runtime_error("could not create log_buffer: " + std::string(aeron_errmsg())); } if (aeron_image_create( &image, m_conductor, log_buffer, subscriber_position, m_correlationId, (int32_t)m_correlationId) < 0) { throw std::runtime_error("could not create image: " + std::string(aeron_errmsg())); } m_imageMap.insert(std::pair<int64_t, aeron_image_t *>(m_correlationId, image)); m_filenames.emplace_back(filename); return m_correlationId++; } static void null_fragment_handler( void *clientd, uint8_t *buffer, size_t offset, size_t length, aeron_header_t *header) { } protected: aeron_client_conductor_t *m_conductor = nullptr; aeron_subscription_t *m_subscription = nullptr; int64_t m_channel_status = AERON_COUNTER_CHANNEL_ENDPOINT_STATUS_ACTIVE; int64_t m_correlationId = 0; std::map<int64_t, aeron_image_t *> m_imageMap; std::vector<std::string> m_filenames; }; TEST_F(SubscriptionTest, shouldInitAndDelete) { } TEST_F(SubscriptionTest, shouldAddAndRemoveImageWithoutPoll) { int64_t image_id = createImage(&m_channel_status); aeron_image_t *image = m_imageMap.find(image_id)->second; ASSERT_EQ(aeron_client_conductor_subscription_add_image(m_subscription, image), 0); EXPECT_EQ(aeron_subscription_image_count(m_subscription), 1); ASSERT_EQ(aeron_client_conductor_subscription_remove_image(m_subscription, image), 0); EXPECT_EQ(aeron_subscription_image_count(m_subscription), 0); EXPECT_EQ(aeron_client_conductor_subscription_prune_image_lists(m_subscription), 0); EXPECT_TRUE(aeron_image_is_in_use(image, aeron_subscription_last_image_list_change_number(m_subscription))); aeron_log_buffer_delete(image->log_buffer); aeron_image_delete(image); } TEST_F(SubscriptionTest, shouldAddAndRemoveImageWithPollAfter) { int64_t image_id = createImage(&m_channel_status); aeron_image_t *image = m_imageMap.find(image_id)->second; ASSERT_EQ(aeron_client_conductor_subscription_add_image(m_subscription, image), 0); ASSERT_EQ(aeron_client_conductor_subscription_remove_image(m_subscription, image), 0); ASSERT_EQ(aeron_subscription_poll(m_subscription, null_fragment_handler, this, 1), 0); EXPECT_EQ(aeron_subscription_image_count(m_subscription), 0); EXPECT_EQ(aeron_client_conductor_subscription_prune_image_lists(m_subscription), 2); EXPECT_FALSE(aeron_image_is_in_use(image, aeron_subscription_last_image_list_change_number(m_subscription))); aeron_log_buffer_delete(image->log_buffer); aeron_image_delete(image); } TEST_F(SubscriptionTest, shouldAddAndRemoveImageWithPollBetween) { int64_t image_id = createImage(&m_channel_status); aeron_image_t *image = m_imageMap.find(image_id)->second; ASSERT_EQ(aeron_client_conductor_subscription_add_image(m_subscription, image), 0); ASSERT_EQ(aeron_subscription_poll(m_subscription, null_fragment_handler, this, 1), 0); ASSERT_EQ(aeron_client_conductor_subscription_remove_image(m_subscription, image), 0); EXPECT_EQ(aeron_subscription_image_count(m_subscription), 0); EXPECT_EQ(aeron_client_conductor_subscription_prune_image_lists(m_subscription), 1); EXPECT_TRUE(aeron_image_is_in_use(image, aeron_subscription_last_image_list_change_number(m_subscription))); aeron_log_buffer_delete(image->log_buffer); aeron_image_delete(image); } <commit_msg>[C]: fix signature.<commit_after>/* * Copyright 2014-2020 Real Logic Limited. * * 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 * * https://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. */ #include <exception> #include <functional> #include <string> #include <gtest/gtest.h> #include "aeron_client_test_utils.h" extern "C" { #include "aeron_subscription.h" #include "aeron_image.h" } #define FILE_PAGE_SIZE (4 * 1024) #define SUB_URI "aeron:udp?endpoint=localhost:24567" #define STREAM_ID (101) #define SESSION_ID (110) #define REGISTRATION_ID (27) using namespace aeron::test; class SubscriptionTest : public testing::Test { public: SubscriptionTest() : m_conductor(nullptr), m_subscription(createSubscription(m_conductor, &m_channel_status)) { } ~SubscriptionTest() override { if (nullptr != m_subscription) { aeron_subscription_delete(m_subscription); } std::for_each(m_filenames.begin(), m_filenames.end(), [&](std::string &filename) { ::unlink(filename.c_str()); }); } static aeron_subscription_t *createSubscription(aeron_client_conductor_t *conductor, int64_t *channel_status) { aeron_subscription_t *subscription = nullptr; if (aeron_subscription_create( &subscription, conductor, ::strdup(SUB_URI), STREAM_ID, REGISTRATION_ID, channel_status, nullptr, nullptr, nullptr, nullptr) < 0) { throw std::runtime_error("could not create subscription: %s" + std::string(aeron_errmsg())); } return subscription; } int64_t createImage(int64_t *subscriber_position) { aeron_image_t *image = nullptr; aeron_log_buffer_t *log_buffer = nullptr; std::string filename = tempFileName(); createLogFile(filename); if (aeron_log_buffer_create(&log_buffer, filename.c_str(), m_correlationId, false) < 0) { throw std::runtime_error("could not create log_buffer: " + std::string(aeron_errmsg())); } if (aeron_image_create( &image, m_conductor, log_buffer, subscriber_position, m_correlationId, (int32_t)m_correlationId) < 0) { throw std::runtime_error("could not create image: " + std::string(aeron_errmsg())); } m_imageMap.insert(std::pair<int64_t, aeron_image_t *>(m_correlationId, image)); m_filenames.emplace_back(filename); return m_correlationId++; } static void null_fragment_handler( void *clientd, const uint8_t *buffer, size_t offset, size_t length, aeron_header_t *header) { } protected: aeron_client_conductor_t *m_conductor = nullptr; aeron_subscription_t *m_subscription = nullptr; int64_t m_channel_status = AERON_COUNTER_CHANNEL_ENDPOINT_STATUS_ACTIVE; int64_t m_correlationId = 0; std::map<int64_t, aeron_image_t *> m_imageMap; std::vector<std::string> m_filenames; }; TEST_F(SubscriptionTest, shouldInitAndDelete) { } TEST_F(SubscriptionTest, shouldAddAndRemoveImageWithoutPoll) { int64_t image_id = createImage(&m_channel_status); aeron_image_t *image = m_imageMap.find(image_id)->second; ASSERT_EQ(aeron_client_conductor_subscription_add_image(m_subscription, image), 0); EXPECT_EQ(aeron_subscription_image_count(m_subscription), 1); ASSERT_EQ(aeron_client_conductor_subscription_remove_image(m_subscription, image), 0); EXPECT_EQ(aeron_subscription_image_count(m_subscription), 0); EXPECT_EQ(aeron_client_conductor_subscription_prune_image_lists(m_subscription), 0); EXPECT_TRUE(aeron_image_is_in_use(image, aeron_subscription_last_image_list_change_number(m_subscription))); aeron_log_buffer_delete(image->log_buffer); aeron_image_delete(image); } TEST_F(SubscriptionTest, shouldAddAndRemoveImageWithPollAfter) { int64_t image_id = createImage(&m_channel_status); aeron_image_t *image = m_imageMap.find(image_id)->second; ASSERT_EQ(aeron_client_conductor_subscription_add_image(m_subscription, image), 0); ASSERT_EQ(aeron_client_conductor_subscription_remove_image(m_subscription, image), 0); ASSERT_EQ(aeron_subscription_poll(m_subscription, null_fragment_handler, this, 1), 0); EXPECT_EQ(aeron_subscription_image_count(m_subscription), 0); EXPECT_EQ(aeron_client_conductor_subscription_prune_image_lists(m_subscription), 2); EXPECT_FALSE(aeron_image_is_in_use(image, aeron_subscription_last_image_list_change_number(m_subscription))); aeron_log_buffer_delete(image->log_buffer); aeron_image_delete(image); } TEST_F(SubscriptionTest, shouldAddAndRemoveImageWithPollBetween) { int64_t image_id = createImage(&m_channel_status); aeron_image_t *image = m_imageMap.find(image_id)->second; ASSERT_EQ(aeron_client_conductor_subscription_add_image(m_subscription, image), 0); ASSERT_EQ(aeron_subscription_poll(m_subscription, null_fragment_handler, this, 1), 0); ASSERT_EQ(aeron_client_conductor_subscription_remove_image(m_subscription, image), 0); EXPECT_EQ(aeron_subscription_image_count(m_subscription), 0); EXPECT_EQ(aeron_client_conductor_subscription_prune_image_lists(m_subscription), 1); EXPECT_TRUE(aeron_image_is_in_use(image, aeron_subscription_last_image_list_change_number(m_subscription))); aeron_log_buffer_delete(image->log_buffer); aeron_image_delete(image); } <|endoftext|>
<commit_before>/**************************************************************************** * * Copyright (c) 2013-2016 PX4 Development Team. All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in * the documentation and/or other materials provided with the * distribution. * 3. Neither the name PX4 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. * ****************************************************************************/ /* * @file FixedwingLandDetector.cpp * * @author Johan Jansen <jnsn.johan@gmail.com> * @author Lorenz Meier <lorenz@px4.io> * @author Julian Oes <julian@oes.ch> */ #include <px4_config.h> #include <px4_defines.h> #include <cmath> #include <drivers/drv_hrt.h> #include "FixedwingLandDetector.h" namespace land_detector { FixedwingLandDetector::FixedwingLandDetector() : LandDetector(), _paramHandle(), _params(), _controlStateSub(-1), _armingSub(-1), _airspeedSub(-1), _controlState{}, _arming{}, _airspeed{}, _velocity_xy_filtered(0.0f), _velocity_z_filtered(0.0f), _airspeed_filtered(0.0f), _accel_horz_lp(0.0f) { _paramHandle.maxVelocity = param_find("LNDFW_VEL_XY_MAX"); _paramHandle.maxClimbRate = param_find("LNDFW_VEL_Z_MAX"); _paramHandle.maxAirSpeed = param_find("LNDFW_AIRSPD_MAX"); _paramHandle.maxIntVelocity = param_find("LNDFW_VELI_MAX"); } void FixedwingLandDetector::_initialize_topics() { _controlStateSub = orb_subscribe(ORB_ID(control_state)); _armingSub = orb_subscribe(ORB_ID(actuator_armed)); _airspeedSub = orb_subscribe(ORB_ID(airspeed)); } void FixedwingLandDetector::_update_topics() { _orb_update(ORB_ID(control_state), _controlStateSub, &_controlState); _orb_update(ORB_ID(actuator_armed), _armingSub, &_arming); _orb_update(ORB_ID(airspeed), _airspeedSub, &_airspeed); } void FixedwingLandDetector::_update_params() { param_get(_paramHandle.maxVelocity, &_params.maxVelocity); param_get(_paramHandle.maxClimbRate, &_params.maxClimbRate); param_get(_paramHandle.maxAirSpeed, &_params.maxAirSpeed); param_get(_paramHandle.maxIntVelocity, &_params.maxIntVelocity); } bool FixedwingLandDetector::_get_freefall_state() { // TODO return false; } bool FixedwingLandDetector::_get_ground_contact_state(){ // TODO return false; } bool FixedwingLandDetector::_get_landed_state() { // only trigger flight conditions if we are armed if (!_arming.armed) { return true; } bool landDetected = false; if (hrt_elapsed_time(&_controlState.timestamp) < 500 * 1000) { float val = 0.97f * _velocity_xy_filtered + 0.03f * sqrtf(_controlState.x_vel * _controlState.x_vel + _controlState.y_vel * _controlState.y_vel); if (PX4_ISFINITE(val)) { _velocity_xy_filtered = val; } val = 0.99f * _velocity_z_filtered + 0.01f * fabsf(_controlState.z_vel); if (PX4_ISFINITE(val)) { _velocity_z_filtered = val; } _airspeed_filtered = 0.95f * _airspeed_filtered + 0.05f * _airspeed.true_airspeed_m_s; // a leaking lowpass prevents biases from building up, but // gives a mostly correct response for short impulses _accel_horz_lp = _accel_horz_lp * 0.8f + _controlState.horz_acc_mag * 0.18f; // crude land detector for fixedwing if (_velocity_xy_filtered < _params.maxVelocity && _velocity_z_filtered < _params.maxClimbRate && _airspeed_filtered < _params.maxAirSpeed && _accel_horz_lp < _params.maxIntVelocity) { landDetected = true; } else { landDetected = false; } } else { // Control state topic has timed out and we need to assume we're landed. landDetected = true; } return landDetected; } } // namespace land_detector <commit_msg>Fix3dwinglandDetector.cpp: adjusted to astyle<commit_after>/**************************************************************************** * * Copyright (c) 2013-2016 PX4 Development Team. All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in * the documentation and/or other materials provided with the * distribution. * 3. Neither the name PX4 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. * ****************************************************************************/ /* * @file FixedwingLandDetector.cpp * * @author Johan Jansen <jnsn.johan@gmail.com> * @author Lorenz Meier <lorenz@px4.io> * @author Julian Oes <julian@oes.ch> */ #include <px4_config.h> #include <px4_defines.h> #include <cmath> #include <drivers/drv_hrt.h> #include "FixedwingLandDetector.h" namespace land_detector { FixedwingLandDetector::FixedwingLandDetector() : LandDetector(), _paramHandle(), _params(), _controlStateSub(-1), _armingSub(-1), _airspeedSub(-1), _controlState{}, _arming{}, _airspeed{}, _velocity_xy_filtered(0.0f), _velocity_z_filtered(0.0f), _airspeed_filtered(0.0f), _accel_horz_lp(0.0f) { _paramHandle.maxVelocity = param_find("LNDFW_VEL_XY_MAX"); _paramHandle.maxClimbRate = param_find("LNDFW_VEL_Z_MAX"); _paramHandle.maxAirSpeed = param_find("LNDFW_AIRSPD_MAX"); _paramHandle.maxIntVelocity = param_find("LNDFW_VELI_MAX"); } void FixedwingLandDetector::_initialize_topics() { _controlStateSub = orb_subscribe(ORB_ID(control_state)); _armingSub = orb_subscribe(ORB_ID(actuator_armed)); _airspeedSub = orb_subscribe(ORB_ID(airspeed)); } void FixedwingLandDetector::_update_topics() { _orb_update(ORB_ID(control_state), _controlStateSub, &_controlState); _orb_update(ORB_ID(actuator_armed), _armingSub, &_arming); _orb_update(ORB_ID(airspeed), _airspeedSub, &_airspeed); } void FixedwingLandDetector::_update_params() { param_get(_paramHandle.maxVelocity, &_params.maxVelocity); param_get(_paramHandle.maxClimbRate, &_params.maxClimbRate); param_get(_paramHandle.maxAirSpeed, &_params.maxAirSpeed); param_get(_paramHandle.maxIntVelocity, &_params.maxIntVelocity); } bool FixedwingLandDetector::_get_freefall_state() { // TODO return false; } bool FixedwingLandDetector::_get_ground_contact_state() { // TODO return false; } bool FixedwingLandDetector::_get_landed_state() { // only trigger flight conditions if we are armed if (!_arming.armed) { return true; } bool landDetected = false; if (hrt_elapsed_time(&_controlState.timestamp) < 500 * 1000) { float val = 0.97f * _velocity_xy_filtered + 0.03f * sqrtf(_controlState.x_vel * _controlState.x_vel + _controlState.y_vel * _controlState.y_vel); if (PX4_ISFINITE(val)) { _velocity_xy_filtered = val; } val = 0.99f * _velocity_z_filtered + 0.01f * fabsf(_controlState.z_vel); if (PX4_ISFINITE(val)) { _velocity_z_filtered = val; } _airspeed_filtered = 0.95f * _airspeed_filtered + 0.05f * _airspeed.true_airspeed_m_s; // a leaking lowpass prevents biases from building up, but // gives a mostly correct response for short impulses _accel_horz_lp = _accel_horz_lp * 0.8f + _controlState.horz_acc_mag * 0.18f; // crude land detector for fixedwing if (_velocity_xy_filtered < _params.maxVelocity && _velocity_z_filtered < _params.maxClimbRate && _airspeed_filtered < _params.maxAirSpeed && _accel_horz_lp < _params.maxIntVelocity) { landDetected = true; } else { landDetected = false; } } else { // Control state topic has timed out and we need to assume we're landed. landDetected = true; } return landDetected; } } // namespace land_detector <|endoftext|>
<commit_before>#include <iostream> #include <fstream> #include <regex> #include <memory> #include <iomanip> #include "channel.hpp" #include "config.hpp" #include <signal.h> #include <signal.h> static std::atomic_bool running = ATOMIC_FLAG_INIT; static void sighandler(int signum) { if (signum == SIGINT) { running = false; std::cout << "SIGINT caught. Finalizing data. " << "Will exit after next tick." << std::endl; } } int main(int argc, char* argv[]) { if (argc < 2) { std::cerr << "Please use " << argv[0] << " config.ini" << std::endl; return 1; } std::string filename = argv[1]; std::list<std::shared_ptr<Hub::Hub> > hublist; std::ifstream config_stream; config_stream.open(filename); while(!config_stream.eof()) { std::regex sectionRe("^\\s*\\[(\\S+)\\]\\s*$"); std::smatch optionMatches; std::string line; config_stream >> line; std::cout << "Parsing '" << line << "'" << std::endl; /* Hub parsing */ if (std::regex_match(line, optionMatches, sectionRe)) { if (config::strutil::cistrcmp(optionMatches[1], "hub")) { std::string buffer = "data://"; /* Hub options */ do { config_stream >> line; buffer.append(line + "\n"); } while(!std::regex_match(line, optionMatches, sectionRe)); std::cout << "Hub: " << buffer << std::endl; config::ConfigParser hubOptions(buffer); const auto& currentHub = std::make_shared<Hub::Hub>(hubOptions["name"]); /* Hub created */ /* Channel parsing */ buffer = "data://"; while (true) { config_stream >> line; if (std::regex_match(line, optionMatches, sectionRe) || config_stream.eof()) { std::cout << "Channel : " << buffer << std::endl; config::ConfigParser channelOptions(buffer); channeling::ChannelFactory::create(std::string(channelOptions["type"]), currentHub.get(), buffer); buffer = "data://"; if (config::strutil::cistrcmp(optionMatches[1], "hub")) break; if (!config::strutil::cistrcmp(optionMatches[1], "channel")) throw config::config_error("Config file format error"); } else buffer.append(line + "\n"); } hublist.push_back(std::move(currentHub)); } } } config_stream.close(); /* Signal handling */ struct sigaction sa; sa.sa_handler = sighandler; sigemptyset(&sa.sa_mask); sa.sa_flags = SA_RESTART; /* Restart functions if interrupted by handler */ if (sigaction(SIGINT, &sa, NULL) == -1) std::cerr << "Couldn't set up signal handling, continuing without graceful death possibility" << std::endl; running = true; for (auto & c : hublist) c->activate(); while (running) { const auto now = std::chrono::system_clock::now(); std::this_thread::sleep_for(std::chrono::milliseconds (1200000)); std::time_t now_c = std::chrono::system_clock::to_time_t(now); std::cout << "[" << std::put_time(std::localtime(&now_c), "%F0 %T0") << "] tick" << std::endl; } for (auto & c : hublist) c->deactivate(); return 0; } <commit_msg>[Main] Add tick_timeout option support<commit_after>#include <iostream> #include <fstream> #include <regex> #include <memory> #include <iomanip> #include "channel.hpp" #include "config.hpp" #include <signal.h> #include <signal.h> static std::atomic_bool running = ATOMIC_FLAG_INIT; static void sighandler(int signum) { if (signum == SIGINT) { running = false; std::cout << "SIGINT caught. Finalizing data. " << "Will exit after next tick." << std::endl; } } int main(int argc, char* argv[]) { uint64_t tick_timeout = 120000; if (argc < 2) { std::cerr << "Please use " << argv[0] << " config.ini" << std::endl; return 1; } std::string filename = argv[1]; std::list<std::shared_ptr<Hub::Hub> > hublist; std::ifstream config_stream; config_stream.open(filename); while(!config_stream.eof()) { std::regex sectionRe("^\\s*\\[(\\S+)\\]\\s*$"); std::smatch optionMatches; std::string line; config_stream >> line; std::cout << "Parsing '" << line << "'" << std::endl; /* Hub parsing */ if (std::regex_match(line, optionMatches, sectionRe)) { if (config::strutil::cistrcmp(optionMatches[1], "general")) { std::string buffer = "data://"; do { config_stream >> line; buffer.append(line + "\n"); } while(!std::regex_match(line, optionMatches, sectionRe)); config::ConfigParser generalOptions(buffer); tick_timeout = generalOptions.get("tick_timeout", "1200000"); std::cout << "Tick timeout set to: " << tick_timeout << std::endl; } if (config::strutil::cistrcmp(optionMatches[1], "hub")) { std::string buffer = "data://"; /* Hub options */ do { config_stream >> line; buffer.append(line + "\n"); } while(!std::regex_match(line, optionMatches, sectionRe)); std::cout << "Hub: " << buffer << std::endl; config::ConfigParser hubOptions(buffer); const auto& currentHub = std::make_shared<Hub::Hub>(hubOptions["name"]); /* Hub created */ /* Channel parsing */ buffer = "data://"; while (true) { config_stream >> line; if (std::regex_match(line, optionMatches, sectionRe) || config_stream.eof()) { std::cout << "Channel : " << buffer << std::endl; config::ConfigParser channelOptions(buffer); channeling::ChannelFactory::create(std::string(channelOptions["type"]), currentHub.get(), buffer); buffer = "data://"; if (config::strutil::cistrcmp(optionMatches[1], "hub")) break; if (!config::strutil::cistrcmp(optionMatches[1], "channel")) throw config::config_error("Config file format error"); } else buffer.append(line + "\n"); } hublist.push_back(std::move(currentHub)); } } } config_stream.close(); /* Signal handling */ struct sigaction sa; sa.sa_handler = sighandler; sigemptyset(&sa.sa_mask); sa.sa_flags = SA_RESTART; /* Restart functions if interrupted by handler */ if (sigaction(SIGINT, &sa, NULL) == -1) std::cerr << "Couldn't set up signal handling, continuing without graceful death possibility" << std::endl; running = true; for (auto & c : hublist) c->activate(); while (running) { const auto now = std::chrono::system_clock::now(); std::this_thread::sleep_for(std::chrono::milliseconds (tick_timeout)); std::time_t now_c = std::chrono::system_clock::to_time_t(now); std::cout << "[" << std::put_time(std::localtime(&now_c), "%F0 %T0") << "] tick" << std::endl; } for (auto & c : hublist) c->deactivate(); return 0; } <|endoftext|>
<commit_before>/******************************************************************************* * Copyright 2017-2018 Intel Corporation * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. *******************************************************************************/ #include <algorithm> #include <map> #include "ngraph/runtime/gpu/gpu_cuda_function_builder.hpp" #include "ngraph/runtime/gpu/gpu_cuda_function_pool.hpp" #include "ngraph/runtime/gpu/gpu_cuda_kernel_builder.hpp" #include "ngraph/runtime/gpu/gpu_cuda_kernel_emitters.hpp" namespace ngraph { namespace runtime { namespace gpu { namespace cuda { namespace kernel { void emit_abs(void* in, void* out, size_t count) { std::string name = "abs"; // Create an instance of nvrtcProgram with the code string. if (CudaFunctionPool::Instance().get(name) == nullptr) { const char* opts[] = {"--gpu-architecture=compute_35", "--relocatable-device-code=true"}; std::string kernel; CudaKernelBuilder::get_1_element_op(name, "float", "fabsf", kernel); CudaFunctionPool::Instance().set( name, CudaFunctionBuilder::get("cuda_" + name, kernel, 2, opts)); } //convert runtime ptr to driver api ptr CUdeviceptr d_ptr_in, d_ptr_out; d_ptr_in = (CUdeviceptr)in; d_ptr_out = (CUdeviceptr)out; void* args_list[] = {&d_ptr_in, &d_ptr_out, &count}; CUDA_SAFE_CALL( cuLaunchKernel(*CudaFunctionPool::Instance().get(name).get(), count, 1, 1, // grid dim 1, 1, 1, // block dim 0, NULL, // shared mem and stream args_list, 0)); // arguments CUDA_SAFE_CALL(cuCtxSynchronize()); // Retrieve and print output. } } } } } } <commit_msg>code style<commit_after>/******************************************************************************* * Copyright 2017-2018 Intel Corporation * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. *******************************************************************************/ #include <algorithm> #include <map> #include "ngraph/runtime/gpu/gpu_cuda_function_builder.hpp" #include "ngraph/runtime/gpu/gpu_cuda_function_pool.hpp" #include "ngraph/runtime/gpu/gpu_cuda_kernel_builder.hpp" #include "ngraph/runtime/gpu/gpu_cuda_kernel_emitters.hpp" namespace ngraph { namespace runtime { namespace gpu { namespace cuda { namespace kernel { void emit_abs(void* in, void* out, size_t count) { std::string name = "abs"; // Create an instance of nvrtcProgram with the code string. if (CudaFunctionPool::instance().get(name) == nullptr) { const char* opts[] = {"--gpu-architecture=compute_35", "--relocatable-device-code=true"}; std::string kernel; CudaKernelBuilder::get_1_element_op(name, "float", "fabsf", kernel); CudaFunctionPool::instance().set( name, CudaFunctionBuilder::get("cuda_" + name, kernel, 2, opts)); } //convert runtime ptr to driver api ptr CUdeviceptr d_ptr_in, d_ptr_out; d_ptr_in = (CUdeviceptr)in; d_ptr_out = (CUdeviceptr)out; void* args_list[] = {&d_ptr_in, &d_ptr_out, &count}; CUDA_SAFE_CALL( cuLaunchKernel(*CudaFunctionPool::instance().get(name).get(), count, 1, 1, // grid dim 1, 1, 1, // block dim 0, NULL, // shared mem and stream args_list, 0)); // arguments CUDA_SAFE_CALL(cuCtxSynchronize()); // Retrieve and print output. } } } } } } <|endoftext|>
<commit_before>/* * Copyright (C) 2015 Luke San Antonio * All rights reserved. */ #include <fstream> #include <sstream> #include <cstdlib> #include <vector> #include <thread> #include "common/log.h" #include "gfx/gl/driver.h" #include "gfx/camera.h" #include "gfx/mesh_chunk.h" #include "gfx/idriver_ui_adapter.h" #include "gfx/support/load_wavefront.h" #include "gfx/support/mesh_conversion.h" #include "gfx/support/generate_aabb.h" #include "gfx/support/write_data_to_mesh.h" #include "gfx/support/texture_load.h" #include "gfx/support/software_texture.h" #include "ui/load.h" #include "ui/freetype_renderer.h" #include "ui/mouse_logic.h" #include "ui/simple_controller.h" #include "map/map.h" #include "map/water.h" #include "map/terrain.h" #include "glad/glad.h" #include "glfw3.h" #define GLM_FORCE_RADIANS #include "glm/glm.hpp" #include "glm/gtc/matrix_transform.hpp" #include "uv.h" #define CATCH_CONFIG_RUNNER #include "catch/catch.hpp" glm::vec4 project_point(glm::vec4 pt, glm::mat4 const& model, glm::mat4 const& view, glm::mat4 const& proj) noexcept { pt = proj * view * model * pt; pt /= pt.w; return pt; } void scroll_callback(GLFWwindow* window, double, double deltay) { auto cam_ptr = glfwGetWindowUserPointer(window); auto& camera = *((game::gfx::Camera*) cam_ptr); camera.fp.pos += -deltay; } game::ui::Mouse_State gen_mouse_state(GLFWwindow* w) { game::ui::Mouse_State ret; ret.button_down =glfwGetMouseButton(w, GLFW_MOUSE_BUTTON_LEFT) == GLFW_PRESS; game::Vec<double> pos; glfwGetCursorPos(w, &pos.x, &pos.y); ret.position = game::vec_cast<int>(pos); return ret; } void log_gl_limits(game::Log_Severity s) noexcept { GLint i = 0; glGetIntegerv(GL_MAX_ELEMENTS_VERTICES, &i); log(s, "GL_MAX_ELEMENTS_VERTICES: %", i); } struct Command_Options { }; Command_Options parse_command_line(int argc, char**) { Command_Options opt; for(int i = 0; i < argc; ++i) { //auto option = argv[i]; } return opt; } int main(int argc, char** argv) { using namespace game; set_log_level(Log_Severity::Debug); uv_chdir("assets/"); // Initialize logger. Scoped_Log_Init log_init_raii_lock{}; // Parse command line arguments. auto options = parse_command_line(argc - 1, argv+1); // Init glfw. if(!glfwInit()) return EXIT_FAILURE; auto window = glfwCreateWindow(1000, 1000, "Hello World", NULL, NULL); if(!window) { glfwTerminate(); return EXIT_FAILURE; } // Init context + load gl functions. glfwMakeContextCurrent(window); gladLoadGLLoader((GLADloadproc) glfwGetProcAddress); // Log glfw version. log_i("Initialized GLFW %", glfwGetVersionString()); int maj = glfwGetWindowAttrib(window, GLFW_CONTEXT_VERSION_MAJOR); int min = glfwGetWindowAttrib(window, GLFW_CONTEXT_VERSION_MINOR); int rev = glfwGetWindowAttrib(window, GLFW_CONTEXT_REVISION); // Log GL profile. log_i("OpenGL core profile %.%.%", maj, min, rev); { // Make an OpenGL driver. gfx::gl::Driver driver{Vec<int>{1000, 1000}}; // Load our default shader. auto default_shader = driver.make_shader_repr(); default_shader->load_vertex_part("shader/basic/v"); default_shader->load_fragment_part("shader/basic/f"); default_shader->set_projection_name("proj"); default_shader->set_view_name("view"); default_shader->set_model_name("model"); default_shader->set_sampler_name("tex"); default_shader->set_diffuse_name("dif"); driver.use_shader(*default_shader); default_shader->set_sampler(0); // Load our textures. auto grass_tex = driver.make_texture_repr(); load_png("tex/grass.png", *grass_tex); // Make an isometric camera. auto cam = gfx::make_isometric_camera(); // Load the image Software_Texture terrain_image; load_png("map/default.png", terrain_image); // Convert it into a heightmap Maybe_Owned<Mesh> terrain = driver.make_mesh_repr(); auto terrain_heightmap = make_heightmap_from_image(terrain_image); auto terrain_data = make_terrain_mesh(terrain_heightmap, {20, 20}, .001f, .01); auto terrain_model = glm::scale(glm::mat4(1.0f), glm::vec3(5.0f, 1.0f, 5.0f)); gfx::allocate_mesh_buffers(terrain_data.mesh, *terrain); gfx::write_data_to_mesh(terrain_data.mesh, ref_mo(terrain)); gfx::format_mesh_buffers(*terrain); terrain->set_primitive_type(Primitive_Type::Triangle); int fps = 0; int time = glfwGetTime(); // Set up some pre-rendering state. driver.clear_color_value(Color{0x55, 0x66, 0x77}); driver.clear_depth_value(1.0); glEnable(GL_DEPTH_TEST); glDepthFunc(GL_LEQUAL); glEnable(GL_CULL_FACE); // Our quick hack to avoid splitting into multiple functions and dealing // either with global variables or like a bound struct or something. bool has_clicked_down = false; // Load our ui gfx::IDriver_UI_Adapter ui_adapter{driver}; ui::Freetype_Renderer freetype_font; auto ui_load_params = ui::Load_Params{freetype_font, ui_adapter}; auto hud = ui::load("ui/hud.json", ui_load_params); auto controller = ui::Simple_Controller{}; hud->find_child_r("build_house")->add_click_listener([](auto const& pt) { log_i("build house!"); }); hud->find_child_r("build_gvn_build")->add_click_listener([](auto const& pt) { log_i("build government building!"); }); hud->layout(driver.window_extents()); controller.add_drag_listener([&](auto const& np, auto const& op) { // pan auto movement = vec_cast<float>(np - op); movement /= -75; glm::vec4 move_vec(movement.x, 0.0f, movement.y, 0.0f); move_vec = glm::inverse(camera_view_matrix(cam)) * move_vec; cam.fp.pos.x += move_vec.x; cam.fp.pos.z += move_vec.z; }); glfwSetWindowUserPointer(window, &cam); glfwSetScrollCallback(window, scroll_callback); //water_obj.material->diffuse_color = Color{0xaa, 0xaa, 0xff}; while(!glfwWindowShouldClose(window)) { ++fps; glfwPollEvents(); // Clear the screen and render the terrain. driver.clear(); use_camera(driver, cam); driver.bind_texture(*grass_tex, 0); default_shader->set_diffuse(colors::white); default_shader->set_model(terrain_model); terrain->draw_elements(0, terrain_data.mesh.elements.size()); // Render the terrain before we calculate the depth of the mouse position. auto mouse_state = gen_mouse_state(window); controller.step(hud, mouse_state); { ui::Draw_Scoped_Lock scoped_draw_lock{ui_adapter}; hud->render(ui_adapter); } glfwSwapBuffers(window); if(int(glfwGetTime()) != time) { time = glfwGetTime(); log_d("fps: %", fps); fps = 0; } flush_log(); } } glfwTerminate(); return 0; } <commit_msg>Start of relatively organized building "system".<commit_after>/* * Copyright (C) 2015 Luke San Antonio * All rights reserved. */ #include <fstream> #include <sstream> #include <cstdlib> #include <vector> #include <thread> #include <future> #include "common/log.h" #include "gfx/gl/driver.h" #include "gfx/camera.h" #include "gfx/mesh_chunk.h" #include "gfx/idriver_ui_adapter.h" #include "gfx/support/load_wavefront.h" #include "gfx/support/mesh_conversion.h" #include "gfx/support/generate_aabb.h" #include "gfx/support/write_data_to_mesh.h" #include "gfx/support/texture_load.h" #include "gfx/support/software_texture.h" #include "ui/load.h" #include "ui/freetype_renderer.h" #include "ui/mouse_logic.h" #include "ui/simple_controller.h" #include "map/map.h" #include "map/water.h" #include "map/terrain.h" #include "stratlib/player_state.h" #include "glad/glad.h" #include "glfw3.h" #define GLM_FORCE_RADIANS #include "glm/glm.hpp" #include "glm/gtc/matrix_transform.hpp" #include "uv.h" #define CATCH_CONFIG_RUNNER #include "catch/catch.hpp" glm::vec4 project_point(glm::vec4 pt, glm::mat4 const& model, glm::mat4 const& view, glm::mat4 const& proj) noexcept { pt = proj * view * model * pt; pt /= pt.w; return pt; } void scroll_callback(GLFWwindow* window, double, double deltay) { auto cam_ptr = glfwGetWindowUserPointer(window); auto& camera = *((game::gfx::Camera*) cam_ptr); camera.fp.pos += -deltay; } game::ui::Mouse_State gen_mouse_state(GLFWwindow* w) { game::ui::Mouse_State ret; ret.button_down =glfwGetMouseButton(w, GLFW_MOUSE_BUTTON_LEFT) == GLFW_PRESS; game::Vec<double> pos; glfwGetCursorPos(w, &pos.x, &pos.y); ret.position = game::vec_cast<int>(pos); return ret; } void log_gl_limits(game::Log_Severity s) noexcept { GLint i = 0; glGetIntegerv(GL_MAX_ELEMENTS_VERTICES, &i); log(s, "GL_MAX_ELEMENTS_VERTICES: %", i); } struct Command_Options { }; Command_Options parse_command_line(int argc, char**) { Command_Options opt; for(int i = 0; i < argc; ++i) { //auto option = argv[i]; } return opt; } int main(int argc, char** argv) { using namespace game; set_log_level(Log_Severity::Debug); uv_chdir("assets/"); // Initialize logger. Scoped_Log_Init log_init_raii_lock{}; // Parse command line arguments. auto options = parse_command_line(argc - 1, argv+1); // Init glfw. if(!glfwInit()) return EXIT_FAILURE; auto window = glfwCreateWindow(1000, 1000, "Hello World", NULL, NULL); if(!window) { glfwTerminate(); return EXIT_FAILURE; } // Init context + load gl functions. glfwMakeContextCurrent(window); gladLoadGLLoader((GLADloadproc) glfwGetProcAddress); // Log glfw version. log_i("Initialized GLFW %", glfwGetVersionString()); int maj = glfwGetWindowAttrib(window, GLFW_CONTEXT_VERSION_MAJOR); int min = glfwGetWindowAttrib(window, GLFW_CONTEXT_VERSION_MINOR); int rev = glfwGetWindowAttrib(window, GLFW_CONTEXT_REVISION); // Log GL profile. log_i("OpenGL core profile %.%.%", maj, min, rev); { // Make an OpenGL driver. gfx::gl::Driver driver{Vec<int>{1000, 1000}}; // Load our default shader. auto default_shader = driver.make_shader_repr(); default_shader->load_vertex_part("shader/basic/v"); default_shader->load_fragment_part("shader/basic/f"); default_shader->set_projection_name("proj"); default_shader->set_view_name("view"); default_shader->set_model_name("model"); default_shader->set_sampler_name("tex"); default_shader->set_diffuse_name("dif"); driver.use_shader(*default_shader); default_shader->set_sampler(0); // Load our textures. auto grass_tex = driver.make_texture_repr(); load_png("tex/grass.png", *grass_tex); // Make an isometric camera. auto cam = gfx::make_isometric_camera(); // Load the image Software_Texture terrain_image; load_png("map/default.png", terrain_image); // Convert it into a heightmap Maybe_Owned<Mesh> terrain = driver.make_mesh_repr(); auto terrain_heightmap = make_heightmap_from_image(terrain_image); auto terrain_data = make_terrain_mesh(terrain_heightmap, {20, 20}, .001f, .01); auto terrain_model = glm::scale(glm::mat4(1.0f), glm::vec3(5.0f, 1.0f, 5.0f)); gfx::allocate_mesh_buffers(terrain_data.mesh, *terrain); gfx::write_data_to_mesh(terrain_data.mesh, ref_mo(terrain)); gfx::format_mesh_buffers(*terrain); terrain->set_primitive_type(Primitive_Type::Triangle); // Map + structures. Maybe_Owned<Mesh> structure_mesh = driver.make_mesh_repr(); Map map; strat::Player_State player_state{strat::Player_State_Type::Nothing}; auto structures_future = std::async(std::launch::async, load_structures,"structure/structures.json", ref_mo(structure_mesh)); int fps = 0; int time = glfwGetTime(); // Set up some pre-rendering state. driver.clear_color_value(Color{0x55, 0x66, 0x77}); driver.clear_depth_value(1.0); glEnable(GL_DEPTH_TEST); glDepthFunc(GL_LEQUAL); glEnable(GL_CULL_FACE); // Our quick hack to avoid splitting into multiple functions and dealing // either with global variables or like a bound struct or something. bool has_clicked_down = false; // Load our ui gfx::IDriver_UI_Adapter ui_adapter{driver}; ui::Freetype_Renderer freetype_font; auto ui_load_params = ui::Load_Params{freetype_font, ui_adapter}; auto hud = ui::load("ui/hud.json", ui_load_params); auto controller = ui::Simple_Controller{}; auto structures = structures_future.get(); hud->find_child_r("build_house")->add_click_listener([&](auto const& pt) { player_state.type = strat::Player_State_Type::Building; player_state.building.to_build = &structures[0]; }); hud->find_child_r("build_gvn_build")->add_click_listener([&](auto const& pt) { player_state.type = strat::Player_State_Type::Building; player_state.building.to_build = &structures[1]; }); hud->layout(driver.window_extents()); controller.add_drag_listener([&](auto const& np, auto const& op) { // pan auto movement = vec_cast<float>(np - op); movement /= -75; glm::vec4 move_vec(movement.x, 0.0f, movement.y, 0.0f); move_vec = glm::inverse(camera_view_matrix(cam)) * move_vec; cam.fp.pos.x += move_vec.x; cam.fp.pos.z += move_vec.z; }); glfwSetWindowUserPointer(window, &cam); glfwSetScrollCallback(window, scroll_callback); //water_obj.material->diffuse_color = Color{0xaa, 0xaa, 0xff}; while(!glfwWindowShouldClose(window)) { ++fps; glfwPollEvents(); // Clear the screen and render the terrain. driver.clear(); use_camera(driver, cam); driver.bind_texture(*grass_tex, 0); default_shader->set_diffuse(colors::white); default_shader->set_model(terrain_model); terrain->draw_elements(0, terrain_data.mesh.elements.size()); // Render the terrain before we calculate the depth of the mouse position. auto mouse_state = gen_mouse_state(window); controller.step(hud, mouse_state); { ui::Draw_Scoped_Lock scoped_draw_lock{ui_adapter}; hud->render(ui_adapter); } glfwSwapBuffers(window); if(int(glfwGetTime()) != time) { time = glfwGetTime(); log_d("fps: %", fps); fps = 0; } flush_log(); } } glfwTerminate(); return 0; } <|endoftext|>
<commit_before>#include <stdexcept> #include <limits> #include <algorithm> #include <array> #include <memory> #include <iomanip> #include <string> #include <sstream> #include <iostream> #include <fstream> #include <vector> //#include <sys/stat.h> #include <cerrno> #include <cstring> #include <system_error> #include <openssl/md5.h> #include <openssl/sha.h> #include <openssl/evp.h> /* #include <stdio.h> #include <stdlib.h> #include <sys/mman.h> #include <fcntl.h> #include <string.h> */ #ifndef EFU_CURLEASY_H #include "curleasy.h" #endif #if defined(_WIN32) && !defined(EFU_WINERRORSTRING_H) #include "win_error_string.hpp" #endif const std::string version("0.1.0"); const std::string listing("http://nwn.efupw.com/rootdir/index.dat"); const std::string patch_dir("http://nwn.efupw.com/rootdir/patch/"); const std::string file_checksum(const std::string &path); std::vector<std::string> &split(const std::string &s, char delim, std::vector<std::string> &elems) { std::stringstream ss(s); std::string item; while (std::getline(ss, item, delim)) { elems.push_back(item); } return elems; } std::vector<std::string> split(const std::string &s, char delim) { std::vector<std::string> elems; return split(s, delim, elems); } void make_dir(const std::string &path) { #ifdef _WIN32 unsigned file_start = path.find_last_of("/\\"); if (!CreateDirectory(path.substr(0, file_start).c_str(), nullptr)) { WinErrorString wes; if (wes.code() != ERROR_ALREADY_EXISTS) { throw std::ios_base::failure("sdf" + wes.str()); } } #else auto elems = split(path, '/'); std::string descend; for (size_t i = 0, k = elems.size() - 1; i < k; ++i) { const std::string &s(elems[i]); if (s.size() && s != ".") { descend.append((i > 0 ? "/" : "") + s); auto status = mkdir(descend.c_str(), S_IRWXU); if (status == -1) { std::error_code err(errno, std::generic_category()); if (err != std::errc::file_exists) { std::cout << "error making dir: " << descend << ": " << err.message() << std::endl; } } } } #endif } // TODO #ifdef CPP11_ENUM_CLASS #define ENUM_CLASS enum class #else #define ENUM_CLASS enum #endif class Target { public: ENUM_CLASS Status { Nonexistent, Outdated, Current }; explicit Target(const std::string &name, const std::string &checksum): m_name(name.find_first_of('/') == std::string::npos ? name : name, name.find_first_of('/') + 1, name.size() - 1), m_checksum(checksum) {} std::string name() const { return m_name; } const std::string checksum() const { return m_checksum; } void fetch() { std::cout << "Statting target " << name() << "..."; std::fstream fs(name(), std::ios_base::in); if (!fs.good()) { fs.close(); std::cout << " doesn't exist, creating new." << std::endl; make_dir(name()); fs.open(name(), std::ios_base::out); if (!fs.good()) { fs.close(); std::cout << "Failed to create file: " << name() << std::endl; } else { fs.close(); do_fetch(); return; } } if (fs.good()) { fs.close(); if (status() == Status::Current) { std::cout << " already up to date." << std::endl; } else { std::cout << " outdated, downloading new." << std::endl; do_fetch(); } } } Status status() { std::ifstream is(name()); if (!is.good()) { return Status::Nonexistent; } is.close(); auto calcsum(file_checksum(name())); if (calcsum == checksum()) { return Status::Current; } else { return Status::Outdated; } } private: void do_fetch() { std::ofstream ofs(name(), std::ios::binary); if (ofs.good()) { std::string s; std::string url(patch_dir + name()); CurlEasy curl(url); curl.write_to(s); curl.progressbar(true); curl.perform(); ofs << s; ofs.close(); std::cout << "Finished downloading " << name() << std::endl; } else { std::cout << "Couldn't write to " << name() << std::endl; } } std::string m_name; std::string m_checksum; }; std::ostream& operator<<(std::ostream &os, const Target &t) { return os << "name: " << t.name() << ", checksum: " << t.checksum(); } const std::string file_checksum(const std::string &path) { #ifdef md_md5 auto md = EVP_md5(); const int md_len = MD5_DIGEST_LENGTH; #else auto md = EVP_sha1(); const int md_len = SHA_DIGEST_LENGTH; #endif std::array<unsigned char, md_len> result; EVP_MD_CTX *mdctx = nullptr; std::ifstream is(path, std::ios::binary); if (!is.good()) { std::cout << "Couldn't open file " << path << " for checksumming." << std::endl; return std::string(); } const int length = 8192; std::array<unsigned char, length> buffer; auto buf = reinterpret_cast<char *>(buffer.data()); mdctx = EVP_MD_CTX_create(); int status = EVP_DigestInit_ex(mdctx, md, nullptr); while (status && is) { is.read(buf, length); status = EVP_DigestUpdate(mdctx, buffer.data(), is.gcount()); } status = EVP_DigestFinal_ex(mdctx, result.data(), nullptr); EVP_MD_CTX_destroy(mdctx); std::stringstream calcsum; calcsum << std::setfill('0'); #ifdef CPP11_FOR_EACH for (const unsigned char c : result) #else std::for_each(std::begin(result), std::end(result), [&calcsum](const unsigned char c) #endif { calcsum << std::hex << std::setw(2) << static_cast<unsigned int>(c); } #ifndef CPP11_FOR_EACH ); #endif return calcsum.str(); } namespace Options { bool version(const std::string &val) { return val == "version"; } bool update_path(const std::string &val) { return val == "update path"; } }; bool confirm() { char c; do { std::cin >> c; std::cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n'); c = static_cast<char>(tolower(c)); } while (c != 'y' && c != 'n'); return c == 'y'; } class EfuLauncher { public: // TODO: assignment, copy operator explicit EfuLauncher(const std::string path, const std::string update_check): m_path(path), m_update_check(update_check), m_has_update(false) {} bool has_update() { if (m_has_update) { return m_has_update; } std::string fetch; CurlEasy curl(m_update_check.c_str()); curl.write_to(fetch); //TODO try { curl.perform(); } catch (CurlEasyException &e) { std::cout << e.what() << std::endl; } std::vector<std::string> lines(split(fetch, '\n')); fetch.clear(); for (auto beg = std::begin(lines), end = std::end(lines); beg != end; ++beg) { auto keyvals(split(*beg, '=')); if (keyvals.size() != 2) { std::cerr << "Malformed option: " + *beg + ", aborting launcher update check." << std::endl; return m_has_update = false; } if (Options::version(keyvals[0])) { const std::string version_test(keyvals[1]); m_has_update = version_test != version; } else if (Options::update_path(keyvals[0])) { m_update_path = keyvals[1]; } } return m_has_update; } bool get_update() { if (!m_has_update || m_update_path.empty()) { return m_has_update = false; } return !(m_has_update = false); } void stat_targets() { std::string fetch; CurlEasy curl(listing); curl.write_to(fetch); curl.perform(); auto lines(split(fetch, '\n')); std::vector<Target> new_targets, old_targets; for (auto beg = std::begin(lines), end = std::end(lines); beg != end; ++beg) { auto data(split(*beg, '@')); Target t(data[0], data[data.size() - 1]); auto status = t.status(); // TODO #ifdef CPP11_ENUM_CLASS if (status == Target::Status::Nonexistent) #else if (status == Target::Nonexistent) #endif { new_targets.push_back(std::move(t)); } // TODO #ifdef CPP11_ENUM_CLASS else if (status == Target::Status::Outdated) #else else if (status == Target::Outdated) #endif { old_targets.push_back(std::move(t)); } } if (new_targets.size()) { std::cout << "New targets: " << new_targets.size() << std::endl; #ifdef CPP11_FOR_EACH for (auto &t : new_targets) #else std::for_each(new_targets.cbegin(), new_targets.cend(), [](const Target &t) #endif { std::cout << "- " << t.name() << std::endl; } #ifndef CPP11_FOR_EACH ); #endif } else { std::cout << "No new targets." << std::endl; } if (old_targets.size()) { std::cout << "Outdated targets: " << old_targets.size() << std::endl; #ifdef CPP11_FOR_EACH for (auto &t : old_targets) #else std::for_each(old_targets.cbegin(), old_targets.cend(), [](const Target &t) #endif { std::cout << "- " << t.name() << std::endl; } #ifndef CPP11_FOR_EACH ); #endif } else { std::cout << "No targets out of date." << std::endl; } #ifndef DEBUG #ifdef CPP11_FOR_EACH for (auto &t : old_targets) #else std::for_each(old_targets.cbegin(), old_targets.cend(), [](Target &t) #endif { t.fetch(); } #ifndef CPP11_FOR_EACH ); std::for_each(old_targets.cbegin(), old_targets.cend(), [](Target &t) #else for (auto &t : old_targets) #endif { t.fetch(); } #ifndef CPP11_FOR_EACH ); #endif #endif } private: const std::string path() const { return m_path; } const std::string m_path; const std::string m_update_check; std::string m_update_path; bool m_has_update; }; int main(int argc, char *argv[]) { CurlGlobalInit curl_global; EfuLauncher l(argv[0], "https://raw.github.com/commonquail/efulauncher/"\ "master/versioncheck"); if (l.has_update()) { std::cout << "A new version of the launcher is available."\ " Would you like to download it (y/n)?" << std::endl; bool download(confirm()); if (!download) { std::cout << "It is strongly recommended to always use"\ " the latest launcher. Would you like to download it (y/n)?" << std::endl; download = confirm(); } if (download) { // Download. std::cout << "Downloading new launcher..." << std::endl; if (l.get_update()) { std::cout << "Done. Please extract and run the new launcher." << std::endl; } return 0; } } try { l.stat_targets(); } catch (std::exception &e) { std::cerr << e.what() << std::endl; } return 0; } <commit_msg>Add missing const qualifiers.<commit_after>#include <stdexcept> #include <limits> #include <algorithm> #include <array> #include <memory> #include <iomanip> #include <string> #include <sstream> #include <iostream> #include <fstream> #include <vector> //#include <sys/stat.h> #include <cerrno> #include <cstring> #include <system_error> #include <openssl/md5.h> #include <openssl/sha.h> #include <openssl/evp.h> /* #include <stdio.h> #include <stdlib.h> #include <sys/mman.h> #include <fcntl.h> #include <string.h> */ #ifndef EFU_CURLEASY_H #include "curleasy.h" #endif #if defined(_WIN32) && !defined(EFU_WINERRORSTRING_H) #include "win_error_string.hpp" #endif const std::string version("0.1.0"); const std::string listing("http://nwn.efupw.com/rootdir/index.dat"); const std::string patch_dir("http://nwn.efupw.com/rootdir/patch/"); const std::string file_checksum(const std::string &path); std::vector<std::string> &split(const std::string &s, char delim, std::vector<std::string> &elems) { std::stringstream ss(s); std::string item; while (std::getline(ss, item, delim)) { elems.push_back(item); } return elems; } std::vector<std::string> split(const std::string &s, char delim) { std::vector<std::string> elems; return split(s, delim, elems); } void make_dir(const std::string &path) { #ifdef _WIN32 unsigned file_start = path.find_last_of("/\\"); if (!CreateDirectory(path.substr(0, file_start).c_str(), nullptr)) { WinErrorString wes; if (wes.code() != ERROR_ALREADY_EXISTS) { throw std::ios_base::failure("sdf" + wes.str()); } } #else auto elems = split(path, '/'); std::string descend; for (size_t i = 0, k = elems.size() - 1; i < k; ++i) { const std::string &s(elems[i]); if (s.size() && s != ".") { descend.append((i > 0 ? "/" : "") + s); auto status = mkdir(descend.c_str(), S_IRWXU); if (status == -1) { std::error_code err(errno, std::generic_category()); if (err != std::errc::file_exists) { std::cout << "error making dir: " << descend << ": " << err.message() << std::endl; } } } } #endif } // TODO #ifdef CPP11_ENUM_CLASS #define ENUM_CLASS enum class #else #define ENUM_CLASS enum #endif class Target { public: ENUM_CLASS Status { Nonexistent, Outdated, Current }; explicit Target(const std::string &name, const std::string &checksum): m_name(name.find_first_of('/') == std::string::npos ? name : name, name.find_first_of('/') + 1, name.size() - 1), m_checksum(checksum) {} std::string name() const { return m_name; } const std::string checksum() const { return m_checksum; } void fetch() const { std::cout << "Statting target " << name() << "..."; std::fstream fs(name(), std::ios_base::in); if (!fs.good()) { fs.close(); std::cout << " doesn't exist, creating new." << std::endl; make_dir(name()); fs.open(name(), std::ios_base::out); if (!fs.good()) { fs.close(); std::cout << "Failed to create file: " << name() << std::endl; } else { fs.close(); do_fetch(); return; } } if (fs.good()) { fs.close(); if (status() == Status::Current) { std::cout << " already up to date." << std::endl; } else { std::cout << " outdated, downloading new." << std::endl; do_fetch(); } } } Status status() const { std::ifstream is(name()); if (!is.good()) { return Status::Nonexistent; } is.close(); auto calcsum(file_checksum(name())); if (calcsum == checksum()) { return Status::Current; } else { return Status::Outdated; } } private: void do_fetch() const { std::ofstream ofs(name(), std::ios::binary); if (ofs.good()) { std::string s; std::string url(patch_dir + name()); CurlEasy curl(url); curl.write_to(s); curl.progressbar(true); curl.perform(); ofs << s; ofs.close(); std::cout << "Finished downloading " << name() << std::endl; } else { std::cout << "Couldn't write to " << name() << std::endl; } } std::string m_name; std::string m_checksum; }; std::ostream& operator<<(std::ostream &os, const Target &t) { return os << "name: " << t.name() << ", checksum: " << t.checksum(); } const std::string file_checksum(const std::string &path) { #ifdef md_md5 auto md = EVP_md5(); const int md_len = MD5_DIGEST_LENGTH; #else auto md = EVP_sha1(); const int md_len = SHA_DIGEST_LENGTH; #endif std::array<unsigned char, md_len> result; EVP_MD_CTX *mdctx = nullptr; std::ifstream is(path, std::ios::binary); if (!is.good()) { std::cout << "Couldn't open file " << path << " for checksumming." << std::endl; return std::string(); } const int length = 8192; std::array<unsigned char, length> buffer; auto buf = reinterpret_cast<char *>(buffer.data()); mdctx = EVP_MD_CTX_create(); int status = EVP_DigestInit_ex(mdctx, md, nullptr); while (status && is) { is.read(buf, length); status = EVP_DigestUpdate(mdctx, buffer.data(), is.gcount()); } status = EVP_DigestFinal_ex(mdctx, result.data(), nullptr); EVP_MD_CTX_destroy(mdctx); std::stringstream calcsum; calcsum << std::setfill('0'); #ifdef CPP11_FOR_EACH for (const unsigned char c : result) #else std::for_each(std::begin(result), std::end(result), [&calcsum](const unsigned char c) #endif { calcsum << std::hex << std::setw(2) << static_cast<unsigned int>(c); } #ifndef CPP11_FOR_EACH ); #endif return calcsum.str(); } namespace Options { bool version(const std::string &val) { return val == "version"; } bool update_path(const std::string &val) { return val == "update path"; } }; bool confirm() { char c; do { std::cin >> c; std::cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n'); c = static_cast<char>(tolower(c)); } while (c != 'y' && c != 'n'); return c == 'y'; } class EfuLauncher { public: // TODO: assignment, copy operator explicit EfuLauncher(const std::string path, const std::string update_check): m_path(path), m_update_check(update_check), m_has_update(false) {} bool has_update() { if (m_has_update) { return m_has_update; } std::string fetch; CurlEasy curl(m_update_check.c_str()); curl.write_to(fetch); //TODO try { curl.perform(); } catch (CurlEasyException &e) { std::cout << e.what() << std::endl; } std::vector<std::string> lines(split(fetch, '\n')); fetch.clear(); for (auto beg = std::begin(lines), end = std::end(lines); beg != end; ++beg) { auto keyvals(split(*beg, '=')); if (keyvals.size() != 2) { std::cerr << "Malformed option: " + *beg + ", aborting launcher update check." << std::endl; return m_has_update = false; } if (Options::version(keyvals[0])) { const std::string version_test(keyvals[1]); m_has_update = version_test != version; } else if (Options::update_path(keyvals[0])) { m_update_path = keyvals[1]; } } return m_has_update; } bool get_update() { if (!m_has_update || m_update_path.empty()) { return m_has_update = false; } return !(m_has_update = false); } void stat_targets() { std::string fetch; CurlEasy curl(listing); curl.write_to(fetch); curl.perform(); auto lines(split(fetch, '\n')); std::vector<Target> new_targets, old_targets; for (auto beg = std::begin(lines), end = std::end(lines); beg != end; ++beg) { auto data(split(*beg, '@')); Target t(data[0], data[data.size() - 1]); auto status = t.status(); // TODO #ifdef CPP11_ENUM_CLASS if (status == Target::Status::Nonexistent) #else if (status == Target::Nonexistent) #endif { new_targets.push_back(std::move(t)); } // TODO #ifdef CPP11_ENUM_CLASS else if (status == Target::Status::Outdated) #else else if (status == Target::Outdated) #endif { old_targets.push_back(std::move(t)); } } if (new_targets.size()) { std::cout << "New targets: " << new_targets.size() << std::endl; #ifdef CPP11_FOR_EACH for (auto &t : new_targets) #else std::for_each(new_targets.cbegin(), new_targets.cend(), [](const Target &t) #endif { std::cout << "- " << t.name() << std::endl; } #ifndef CPP11_FOR_EACH ); #endif } else { std::cout << "No new targets." << std::endl; } if (old_targets.size()) { std::cout << "Outdated targets: " << old_targets.size() << std::endl; #ifdef CPP11_FOR_EACH for (auto &t : old_targets) #else std::for_each(old_targets.cbegin(), old_targets.cend(), [](const Target &t) #endif { std::cout << "- " << t.name() << std::endl; } #ifndef CPP11_FOR_EACH ); #endif } else { std::cout << "No targets out of date." << std::endl; } #ifndef DEBUG #ifdef CPP11_FOR_EACH for (auto &t : old_targets) #else std::for_each(old_targets.cbegin(), old_targets.cend(), [](Target &t) #endif { t.fetch(); } #ifndef CPP11_FOR_EACH ); std::for_each(old_targets.cbegin(), old_targets.cend(), [](Target &t) #else for (auto &t : old_targets) #endif { t.fetch(); } #ifndef CPP11_FOR_EACH ); #endif #endif } private: const std::string path() const { return m_path; } const std::string m_path; const std::string m_update_check; std::string m_update_path; bool m_has_update; }; int main(int argc, char *argv[]) { CurlGlobalInit curl_global; EfuLauncher l(argv[0], "https://raw.github.com/commonquail/efulauncher/"\ "master/versioncheck"); if (l.has_update()) { std::cout << "A new version of the launcher is available."\ " Would you like to download it (y/n)?" << std::endl; bool download(confirm()); if (!download) { std::cout << "It is strongly recommended to always use"\ " the latest launcher. Would you like to download it (y/n)?" << std::endl; download = confirm(); } if (download) { // Download. std::cout << "Downloading new launcher..." << std::endl; if (l.get_update()) { std::cout << "Done. Please extract and run the new launcher." << std::endl; } return 0; } } try { l.stat_targets(); } catch (std::exception &e) { std::cerr << e.what() << std::endl; } return 0; } <|endoftext|>
<commit_before>#include <iostream> // last include (requires previous includes) #include "globals.hpp" #define DEBUG int main() { // window settings //window.setVerticalSyncEnabled(true); //window.setFramerateLimit(30); // avoid noise ;) // define a clock to measure time sf::Clock clock; sf::Time deltaT = clock.restart(); globalClock.restart(); soundManager.playSound("sound/test.wav"); // main loop while (window.isOpen()) { // poll events (do not use for input handling) sf::Event event; while (window.pollEvent(event)) { if (event.type == sf::Event::Closed || ((event.type == sf::Event::KeyPressed) && (event.key.code == sf::Keyboard::Escape))) { window.close(); } if (event.type == sf::Event::LostFocus) { focus = false; } if (event.type == sf::Event::GainedFocus) { focus = true; } } // retrieve input (either gamepad or keyboard) if (sf::Joystick::isConnected(0)) { // retrieve current gamepad input input[0] = sf::Joystick::getAxisPosition(0, sf::Joystick::Axis::PovX) == -100; input[1] = sf::Joystick::getAxisPosition(0, sf::Joystick::Axis::PovX) == 100; input[2] = sf::Joystick::getAxisPosition(0, sf::Joystick::Axis::PovY) == -100; input[3] = sf::Joystick::getAxisPosition(0, sf::Joystick::Axis::PovY) == 100; // TODO input 4 - 7 buggy? for (int i = 0; i < 3; ++i) { input[i + 4] = sf::Joystick::isButtonPressed(0, i); } } else { // retrieve current keyboard input for (int i = 0; i < INPUT_SIZE; ++i) { input[i] = sf::Keyboard::isKeyPressed(keyboardBinding[i]) && focus; } } #ifdef DEBUG // show input bitstring if any key is pressed if (input.any()) { // std::cout << input << std::endl; } #endif // clear window content window.clear(); // reset clock and determine elapsed time since last frame deltaT = clock.restart(); // update game with deltaT when focused if (focus) { sceneManager.update(deltaT); } window.display(); } } <commit_msg>added resizing<commit_after>#include <iostream> // last include (requires previous includes) #include "globals.hpp" #define DEBUG int main() { // window settings //window.setVerticalSyncEnabled(true); //window.setFramerateLimit(30); // avoid noise ;) // define a clock to measure time sf::Clock clock; sf::Time deltaT = clock.restart(); globalClock.restart(); soundManager.playSound("sound/test.wav"); // main loop while (window.isOpen()) { // poll events (do not use for input handling) sf::Event event; while (window.pollEvent(event)) { if (event.type == sf::Event::Closed || ((event.type == sf::Event::KeyPressed) && (event.key.code == sf::Keyboard::Escape))) { window.close(); } if (event.type == sf::Event::LostFocus) { focus = false; } if (event.type == sf::Event::GainedFocus) { focus = true; } // maintain aspect ratio if (event.type == sf::Event::Resized) { // get ratio based on the original size float widthRatio = (float) window.getSize().x / screenWidth; float heightRatio = (float) window.getSize().y / screenHeight; // use the smaller ratio to update the window size //window.waitEvent(sf::Event::Resized); if (heightRatio > widthRatio) { window.setView(sf::View(sf::FloatRect(0, 0, event.size.width / widthRatio, event.size.height / widthRatio))); } else { window.setView(sf::View(sf::FloatRect(0, 0, event.size.width / heightRatio, event.size.height / heightRatio))); } } } // retrieve input (either gamepad or keyboard) if (sf::Joystick::isConnected(0)) { // retrieve current gamepad input input[0] = sf::Joystick::getAxisPosition(0, sf::Joystick::Axis::PovX) == -100; input[1] = sf::Joystick::getAxisPosition(0, sf::Joystick::Axis::PovX) == 100; input[2] = sf::Joystick::getAxisPosition(0, sf::Joystick::Axis::PovY) == -100; input[3] = sf::Joystick::getAxisPosition(0, sf::Joystick::Axis::PovY) == 100; // TODO input 4 - 7 buggy? for (int i = 0; i < 3; ++i) { input[i + 4] = sf::Joystick::isButtonPressed(0, i); } } else { // retrieve current keyboard input for (int i = 0; i < INPUT_SIZE; ++i) { input[i] = sf::Keyboard::isKeyPressed(keyboardBinding[i]) && focus; } } #ifdef DEBUG // show input bitstring if any key is pressed if (input.any()) { // std::cout << input << std::endl; } #endif // clear window content window.clear(); // reset clock and determine elapsed time since last frame deltaT = clock.restart(); // update game with deltaT when focused if (focus) { sceneManager.update(deltaT); } window.display(); } } <|endoftext|>
<commit_before>#include <QApplication> #include "mainwindow.h" #include "daemon_client.h" int main(int argc, char *argv[]) { QApplication app(argc, argv); //MainWindow mainWindow; //mainWindow.show(); DaemonClient client; client.processTransaction("1234", 0); app.exec(); } <commit_msg>Revert main.cpp.<commit_after>#include <QApplication> #include "mainwindow.h" int main(int argc, char *argv[]) { QApplication app(argc, argv); MainWindow mainWindow; mainWindow.show(); app.exec(); } <|endoftext|>
<commit_before>#include "cmdline.hpp" #include <boost/lexical_cast.hpp> #include <boost/filesystem/operations.hpp> #include "State.hpp" #include "svc/LuaVm.hpp" #include "svc/FileSystem.hpp" #include "svc/ServiceLocator.hpp" #include "svc/Mainloop.hpp" #include "svc/DrawService.hpp" #include "svc/EventDispatcher.hpp" #include "svc/Configuration.hpp" #include "svc/StateManager.hpp" #include "svc/Timer.hpp" #include "svc/SoundManager.hpp" #include <SFML/Graphics/RenderWindow.hpp> #include <luabind/function.hpp> // call_function (used @ loadStateFromLua) #include <boost/bind.hpp> #include "Logfile.hpp" #include <physfs.h> #include "base64.hpp" #include "LuaUtils.hpp" #include <array> #include <luabind/adopt_policy.hpp> #ifdef _WIN32 # define WIN32_LEAN_AND_MEAN # define NOMINMAX # include <Windows.h> # endif #if defined(BOOST_MSVC) && defined(_DEBUG) && defined(JD_HAS_VLD) # include <vld.h> #endif namespace { static std::vector<std::string> cmdLine; static int argc_ = 0; static const char* const* argv_ = nullptr; template<typename T> struct ServiceEntry: public T { ServiceEntry() { ServiceLocator::registerService(*this); } }; static State* loadStateFromLua(std::string const& name) { std::string const filename = "lua/states/" + name + ".lua"; if (!PHYSFS_exists(filename.c_str())) return nullptr; LOG_D("Loading state \"" + name + "\"..."); State* s = nullptr; try { lua_State* L = ServiceLocator::luaVm().L(); luaU::load(ServiceLocator::luaVm().L(), filename); luabind::object chunk(luabind::from_stack(L, -1)); lua_pop(L, 1); // The state must stay alive as long as the StateManager. // However, if we simply use luabind::adopt here, we cause a memory // leak. So, instead we bind the lifetime of the state to the one // from the lua_State (== LuaVm in this case). As long as the LuaVm is // destroyed (shortly) *after* the StateManager it just works. // Otherwise, we would have a real problem: how could you possibly keep // a Lua object alive, longer than it's lua_State? luabind::object sobj = chunk(); s = luabind::object_cast<State*>(sobj); sobj.push(L); luaL_ref(L, LUA_REGISTRYINDEX); } catch (luabind::cast_failed const& e) { LOG_E("failed casting lua value to " + std::string(e.info().name())); } catch (luabind::error const& e) { LOG_E(luaU::Error(e, "failed loading state \"" + name + '\"').what()); } catch (std::exception const& e) { LOG_EX(e); } log().write( "Loading State " + name + (s ? " finished." : " failed."), s ? loglevel::debug : loglevel::error, LOGFILE_LOCATION); return s; } } // anonymous namespace int argc() { return argc_; } const char* const* argv() { return argv_; } std::vector<std::string> const& commandLine() { return cmdLine; } int main(int argc, char* argv[]) { // First thing to do: get the logfile opened. // Create directory for log file namespace fs = boost::filesystem; # ifdef _WIN32 fs::path const basepath(std::string(getenv("APPDATA")) + "/JadeEngine/"); # else fs::path const basepath("~/.jade/"); #endif fs::create_directories(basepath); int r = EXIT_FAILURE; try { // Open the logfile log().setMinLevel(loglevel::debug); log().open((basepath / "jd.log").string()); #ifndef NDEBUG LOG_I("This is a debug build."); #endif LOG_D("Initialization..."); // setup commandline functions // argc_ = argc; argv_ = argv; cmdLine.assign(argv, argv + argc); // Construct and register services // auto const regSvc = ServiceLocator::registerService; LOG_D("Initializing virtual filesystem..."); FileSystem::Init fsinit; regSvc(FileSystem::get()); fs::path datapath(basepath / "data"); fs::create_directories(datapath); if (!PHYSFS_setWriteDir(datapath.string().c_str())) throw FileSystem::Error("failed setting write directory"); if (!PHYSFS_mount(PHYSFS_getWriteDir(), nullptr, false /* prepend to path */)) throw FileSystem::Error("failed mounting write directory"); LOG_D("Finished initializing virtual filesystem."); LOG_D("Initializing Lua..."); ServiceEntry<LuaVm> luaVm; try { luaVm.initLibs(); LOG_D("Finished initializing Lua."); ServiceEntry<Mainloop> mainloop; ServiceEntry<Configuration> conf; ServiceEntry<Timer> timer; ServiceEntry<SoundManager> sound; // Create the RenderWindow now, because some services depend on it. LOG_D("Preparing window and SFML..."); sf::RenderWindow window; LOG_D("Finished preparing window and SFML."); ServiceEntry<StateManager> stateManager; EventDispatcher eventDispatcher(window); regSvc(eventDispatcher); using boost::bind; mainloop.connect_processInput( bind(&EventDispatcher::dispatch, &eventDispatcher)); // Various other initializations // ServiceLocator::stateManager().setStateNotFoundCallback(&loadStateFromLua); LOG_D("Loading configuration..."); conf.load(); LOG_D("Finished loading configuration."); DrawService drawService(window, conf.get<std::size_t>("misc.layerCount", 1UL)); regSvc(drawService); mainloop.connect_preFrame(bind(&Timer::beginFrame, &timer)); mainloop.connect_update(bind(&Timer::processCallbacks, &timer)); mainloop.connect_update(bind(&SoundManager::fade, &sound)); mainloop.connect_preDraw(bind(&DrawService::clear, &drawService)); mainloop.connect_draw(bind(&DrawService::draw, &drawService)); mainloop.connect_postDraw(bind(&DrawService::display, &drawService)); mainloop.connect_postFrame(bind(&Timer::endFrame, &timer)); timer.callEvery(sf::seconds(10), bind(&SoundManager::tidy, &sound)); LOG_D("Creating window..."); std::string const title = conf.get<std::string>("misc.title", "Jade"); window.create( conf.get("video.mode", sf::VideoMode(800, 600)), title, conf.get("video.fullscreen", false) ? sf::Style::Close | sf::Style::Fullscreen : sf::Style::Default); window.setVerticalSyncEnabled(conf.get("video.vsync", true)); window.setFramerateLimit(conf.get("video.framelimit", 0U)); window.setKeyRepeatEnabled(false); LOG_D("Finished creating window."); drawService.resetLayerViews(); timer.callEvery(sf::milliseconds(600), [&timer, &window, &title]() { std::string const fps = boost::lexical_cast<std::string>( 1.f / timer.frameDuration().asSeconds()); window.setTitle(title + " [" + fps + " fps]"); }); timer.callEvery(sf::seconds(60), [&timer]() { std::string const fps = boost::lexical_cast<std::string>( 1.f / timer.frameDuration().asSeconds()); LOG_D("Current framerate (fps): " + fps); }); // Execute init.lua // # define INIT_LUA "lua/init.lua" LOG_D("Executing \"" INIT_LUA "\"..."); luaU::exec(luaVm.L(), INIT_LUA); LOG_D("Finished executing \"" INIT_LUA "\"."); # undef INIT_LUA LOG_D("Finished initialization."); // Run mainloop // LOG_D("Mainloop..."); r = ServiceLocator::mainloop().exec(); LOG_D("Mainloop finished with exit code " + boost::lexical_cast<std::string>(r) + "."); LOG_D("Cleanup..."); stateManager.clear(); luaVm.deinit(); } catch (luabind::error const& e) { throw luaU::Error(e); } catch (luabind::cast_failed const& e) { throw luaU::Error(e.what() + std::string("; type: ") + e.info().name()); } // In case of an exception, log it and notify the user // } catch (std::exception const& e) { log().logEx(e, loglevel::fatal, LOGFILE_LOCATION); # ifdef _WIN32 MessageBoxA(NULL, e.what(), "Jade Engine", MB_ICONERROR | MB_TASKMODAL); # else std::cerr << "Exception: " << e.what(); # endif return EXIT_FAILURE; } LOG_D("Cleanup finished."); return r; } <commit_msg>main: Remove 3 superflous includes.<commit_after>#include "cmdline.hpp" #include <boost/lexical_cast.hpp> #include <boost/filesystem/operations.hpp> #include "State.hpp" #include "svc/LuaVm.hpp" #include "svc/FileSystem.hpp" #include "svc/ServiceLocator.hpp" #include "svc/Mainloop.hpp" #include "svc/DrawService.hpp" #include "svc/EventDispatcher.hpp" #include "svc/Configuration.hpp" #include "svc/StateManager.hpp" #include "svc/Timer.hpp" #include "svc/SoundManager.hpp" #include <SFML/Graphics/RenderWindow.hpp> #include <luabind/function.hpp> // call_function (used @ loadStateFromLua) #include <boost/bind.hpp> #include "Logfile.hpp" #include <physfs.h> #include "LuaUtils.hpp" #ifdef _WIN32 # include <cstdio> # define WIN32_LEAN_AND_MEAN # define NOMINMAX # include <Windows.h> # endif #if defined(BOOST_MSVC) && defined(_DEBUG) && defined(JD_HAS_VLD) # include <vld.h> #endif namespace { static std::vector<std::string> cmdLine; static int argc_ = 0; static const char* const* argv_ = nullptr; template<typename T> struct ServiceEntry: public T { ServiceEntry() { ServiceLocator::registerService(*this); } }; static State* loadStateFromLua(std::string const& name) { std::string const filename = "lua/states/" + name + ".lua"; if (!PHYSFS_exists(filename.c_str())) return nullptr; LOG_D("Loading state \"" + name + "\"..."); State* s = nullptr; try { lua_State* L = ServiceLocator::luaVm().L(); luaU::load(ServiceLocator::luaVm().L(), filename); luabind::object chunk(luabind::from_stack(L, -1)); lua_pop(L, 1); // The state must stay alive as long as the StateManager. // However, if we simply use luabind::adopt here, we cause a memory // leak. So, instead we bind the lifetime of the state to the one // from the lua_State (== LuaVm in this case). As long as the LuaVm is // destroyed (shortly) *after* the StateManager it just works. // Otherwise, we would have a real problem: how could you possibly keep // a Lua object alive, longer than it's lua_State? luabind::object sobj = chunk(); s = luabind::object_cast<State*>(sobj); sobj.push(L); luaL_ref(L, LUA_REGISTRYINDEX); } catch (luabind::cast_failed const& e) { LOG_E("failed casting lua value to " + std::string(e.info().name())); } catch (luabind::error const& e) { LOG_E(luaU::Error(e, "failed loading state \"" + name + '\"').what()); } catch (std::exception const& e) { LOG_EX(e); } log().write( "Loading State " + name + (s ? " finished." : " failed."), s ? loglevel::debug : loglevel::error, LOGFILE_LOCATION); return s; } } // anonymous namespace int argc() { return argc_; } const char* const* argv() { return argv_; } std::vector<std::string> const& commandLine() { return cmdLine; } int main(int argc, char* argv[]) { // First thing to do: get the logfile opened. // Create directory for log file namespace fs = boost::filesystem; # ifdef _WIN32 fs::path const basepath(std::string(getenv("APPDATA")) + "/JadeEngine/"); # else fs::path const basepath("~/.jade/"); #endif fs::create_directories(basepath); int r = EXIT_FAILURE; try { // Open the logfile log().setMinLevel(loglevel::debug); log().open((basepath / "jd.log").string()); #ifndef NDEBUG LOG_I("This is a debug build."); #endif LOG_D("Initialization..."); // setup commandline functions // argc_ = argc; argv_ = argv; cmdLine.assign(argv, argv + argc); // Construct and register services // auto const regSvc = ServiceLocator::registerService; LOG_D("Initializing virtual filesystem..."); FileSystem::Init fsinit; regSvc(FileSystem::get()); fs::path datapath(basepath / "data"); fs::create_directories(datapath); if (!PHYSFS_setWriteDir(datapath.string().c_str())) throw FileSystem::Error("failed setting write directory"); if (!PHYSFS_mount(PHYSFS_getWriteDir(), nullptr, false /* prepend to path */)) throw FileSystem::Error("failed mounting write directory"); LOG_D("Finished initializing virtual filesystem."); LOG_D("Initializing Lua..."); ServiceEntry<LuaVm> luaVm; try { luaVm.initLibs(); LOG_D("Finished initializing Lua."); ServiceEntry<Mainloop> mainloop; ServiceEntry<Configuration> conf; ServiceEntry<Timer> timer; ServiceEntry<SoundManager> sound; // Create the RenderWindow now, because some services depend on it. LOG_D("Preparing window and SFML..."); sf::RenderWindow window; LOG_D("Finished preparing window and SFML."); ServiceEntry<StateManager> stateManager; EventDispatcher eventDispatcher(window); regSvc(eventDispatcher); using boost::bind; mainloop.connect_processInput( bind(&EventDispatcher::dispatch, &eventDispatcher)); // Various other initializations // ServiceLocator::stateManager().setStateNotFoundCallback(&loadStateFromLua); LOG_D("Loading configuration..."); conf.load(); LOG_D("Finished loading configuration."); DrawService drawService(window, conf.get<std::size_t>("misc.layerCount", 1UL)); regSvc(drawService); mainloop.connect_preFrame(bind(&Timer::beginFrame, &timer)); mainloop.connect_update(bind(&Timer::processCallbacks, &timer)); mainloop.connect_update(bind(&SoundManager::fade, &sound)); mainloop.connect_preDraw(bind(&DrawService::clear, &drawService)); mainloop.connect_draw(bind(&DrawService::draw, &drawService)); mainloop.connect_postDraw(bind(&DrawService::display, &drawService)); mainloop.connect_postFrame(bind(&Timer::endFrame, &timer)); timer.callEvery(sf::seconds(10), bind(&SoundManager::tidy, &sound)); LOG_D("Creating window..."); std::string const title = conf.get<std::string>("misc.title", "Jade"); window.create( conf.get("video.mode", sf::VideoMode(800, 600)), title, conf.get("video.fullscreen", false) ? sf::Style::Close | sf::Style::Fullscreen : sf::Style::Default); window.setVerticalSyncEnabled(conf.get("video.vsync", true)); window.setFramerateLimit(conf.get("video.framelimit", 0U)); window.setKeyRepeatEnabled(false); LOG_D("Finished creating window."); drawService.resetLayerViews(); timer.callEvery(sf::milliseconds(600), [&timer, &window, &title]() { std::string const fps = boost::lexical_cast<std::string>( 1.f / timer.frameDuration().asSeconds()); window.setTitle(title + " [" + fps + " fps]"); }); timer.callEvery(sf::seconds(60), [&timer]() { std::string const fps = boost::lexical_cast<std::string>( 1.f / timer.frameDuration().asSeconds()); LOG_D("Current framerate (fps): " + fps); }); // Execute init.lua // # define INIT_LUA "lua/init.lua" LOG_D("Executing \"" INIT_LUA "\"..."); luaU::exec(luaVm.L(), INIT_LUA); LOG_D("Finished executing \"" INIT_LUA "\"."); # undef INIT_LUA LOG_D("Finished initialization."); // Run mainloop // LOG_D("Mainloop..."); r = ServiceLocator::mainloop().exec(); LOG_D("Mainloop finished with exit code " + boost::lexical_cast<std::string>(r) + "."); LOG_D("Cleanup..."); stateManager.clear(); luaVm.deinit(); } catch (luabind::error const& e) { throw luaU::Error(e); } catch (luabind::cast_failed const& e) { throw luaU::Error(e.what() + std::string("; type: ") + e.info().name()); } // In case of an exception, log it and notify the user // } catch (std::exception const& e) { log().logEx(e, loglevel::fatal, LOGFILE_LOCATION); # ifdef _WIN32 MessageBoxA(NULL, e.what(), "Jade Engine", MB_ICONERROR | MB_TASKMODAL); # else std::cerr << "Exception: " << e.what(); # endif return EXIT_FAILURE; } LOG_D("Cleanup finished."); return r; } <|endoftext|>
<commit_before>/* * Copyright (C) 2012-2016. TomTom International BV (http://tomtom.com). * * 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. */ #include "Component.h" #include "Input.h" #include "CmakeRegen.h" #include "Output.h" #include "Analysis.h" #include "Constants.h" #include <boost/filesystem.hpp> #include <boost/filesystem/fstream.hpp> /** * These variables contain the global lists of components and files. * They are globally accessible. */ std::unordered_map<std::string, Component *> components; std::unordered_map<std::string, File> files; static bool CheckVersionFile() { const std::string currentVersion = CURRENT_VERSION; std::string version; boost::filesystem::ifstream in(VERSION_FILE); getline(in, version); return (version == currentVersion); } std::string targetFrom(const std::string &arg) { std::string target = arg; if (!target.empty() && target.back() == '/') { target.pop_back(); } std::replace(target.begin(), target.end(), '.', '/'); return target; } std::map<std::string, void (*)(int, char **)> functions = { {"--graph", [](int argc, char **argv) { if (argc != 3) { printf("Usage: %s --graph <outputfile>\n", argv[0]); } else { FindCircularDependencies(); OutputFlatDependencies(argv[2]); } }}, {"--graph-cycles", [](int argc, char **argv) { if (argc != 3) { printf("Usage: %s --graph-cycles <outputfile>\n", argv[0]); } else { FindCircularDependencies(); OutputCircularDependencies(argv[2]); } }}, {"--graph-target", [](int argc, char **argv) { if (argc != 4) { printf("Usage: %s --graph-target <targetname> <outputfile>\n", argv[0]); } else { FindCircularDependencies(); PrintGraphOnTarget(argv[3], components[std::string("./") + targetFrom(argv[2])]); } }}, {"--cycles", [](int argc, char **argv) { if (argc != 3) { printf("Usage: %s --cycles <targetname>\n", argv[0]); } else { FindCircularDependencies(); PrintCyclesForTarget(components[std::string("./") + targetFrom(argv[2])]); } }}, {"--stats", [](int, char **) { std::size_t totalPublicLinks(0), totalPrivateLinks(0); for (const auto &c : components) { totalPublicLinks += c.second->pubDeps.size(); totalPrivateLinks += c.second->privDeps.size(); } fprintf(stderr, "%zu components with %zu public dependencies, %zu private dependencies\n", components.size(), totalPublicLinks, totalPrivateLinks); FindCircularDependencies(); fprintf(stderr, "Detected %zu nodes in cycles\n", NodesWithCycles()); }}, {"--inout", [](int argc, char **argv) { if (argc != 3) { printf("Usage: %s --inout <targetname>\n", argv[0]); } else { PrintLinksForTarget(components[std::string("./") + targetFrom(argv[2])]); } }}, {"--shortest", [](int argc, char **argv) { if (argc != 4) { printf("Usage: %s --shortest <targetname-from> <targetname-to>\n", argv[0]); } else { FindSpecificLink(components[std::string("./") + targetFrom(argv[2])], components[std::string("./") + targetFrom(argv[3])]); } }}, {"--info", [](int argc, char **argv) { if (argc != 3) { printf("Usage: %s --info <targetname>\n", argv[0]); } else { PrintInfoOnTarget(components[std::string("./") + targetFrom(argv[2])]); } }}, {"--usedby", [](int argc, char **argv) { if (argc != 3) { printf("Usage: %s --usedby <filename>\n", argv[0]); } else { auto f = &files[std::string("./") + argv[2]]; for (auto &p : files) { if (p.second.dependencies.find(f) != p.second.dependencies.end()) { std::cout << p.second.path.string() << "\n"; } } } }}, {"--regen", [](int argc, char **argv) { if (argc >= 3) { for (int n = 2; n < argc; n++) { if (components.find(targetFrom(argv[n])) != components.end()) { RegenerateCmakeFilesForComponent(components[targetFrom(argv[2])], false); } else { std::cout << "Target '" << targetFrom(argv[2]) << "' not found\n"; } } } else { for (auto &c : components) { RegenerateCmakeFilesForComponent(c.second, false); } } }}, {"--dryregen", [](int argc, char **argv) { if (argc >= 3) { for (int n = 2; n < argc; n++) { if (components.find(targetFrom(argv[n])) != components.end()) { RegenerateCmakeFilesForComponent(components[targetFrom(argv[2])], true); } else { std::cout << "Target '" << targetFrom(argv[2]) << "' not found\n"; } } } else { for (auto &c : components) { RegenerateCmakeFilesForComponent(c.second, true); } } }}, {"--help", [](int, char **argv) { printf("C++ Dependencies -- a tool to analyze large C++ code bases for #include dependency information\n"); printf("Copyright (C) 2016, TomTom International BV\n"); printf("\n"); printf(" Usage:\n"); printf(" %s [--dir <source-directory>] <command>\n", argv[0]); printf(" Source directory is assumed to be the current one if unspecified\n"); printf("\n"); printf(" Commands:\n"); printf(" --help : Produce this help text\n"); printf("\n"); printf(" Extracting graphs:\n"); printf(" --graph <output> : Graph of all components with dependencies\n"); printf(" --graph-cycles <output> : Graph of components with cyclic dependencies on other components\n"); printf(" --graph-for <output> <target> : Graph for all dependencies of a specific target\n"); printf("\n"); printf(" Getting information:\n"); printf(" --stats : Info about code base size, complexity and cyclic dependency count\n"); printf(" --cycles <targetname> : Find all possible paths from this target back to itself\n"); printf(" --shortest : Determine shortest path between components and its reason\n"); printf("\n"); printf(" Target information:\n"); printf(" --info : Show all information on a given specific target\n"); printf(" --usedby : Find all references to a specific header file\n"); printf(" --inout : Find all incoming and outgoing links for a target\n"); printf(" --ambiguous : Find all include statements that could refer to more than one header\n"); }}, // --ignore : Handled during input parsing as it is a pre-filter for CheckCycles instead. }; int main(int argc, char **argv) { boost::filesystem::path root = boost::filesystem::current_path(); std::unordered_set<std::string> ignorefiles = { "unistd.h", "console.h", "stdint.h", "windows.h", "library.h", "endian.h", "rle.h", }; if (argc > 1 && argv[1] == std::string("--dir")) { // Extract the root directory, reshuffle the other parameters. root = argv[2]; argv[2] = argv[0]; argv += 2; argc -= 2; } std::string command; if (argc > 1) { std::transform(argv[1], argv[1] + strlen(argv[1]), std::back_inserter(command), ::tolower); } else { command = "--help"; } if (command == "--ignore") { for (int n = 2; n < argc; n++) { ignorefiles.insert(argv[n]); } argc = 1; command = "--stats"; } if (command == "--regen" && !CheckVersionFile()) { fprintf(stderr, "Version of dependency checker not the same as the one used to generate the existing cmakelists. Refusing to regen\n" "Please manually update " VERSION_FILE " to version \"" CURRENT_VERSION "\" if you really want to do this.\n"); command = "--dryregen"; } LoadFileList(ignorefiles, root); CheckVersionFile(); { std::map<std::string, std::set<std::string>> collisions; std::unordered_map<std::string, std::string> includeLookup; CreateIncludeLookupTable(includeLookup, collisions); MapFilesToComponents(); std::map<std::string, std::vector<std::string>> ambiguous; MapIncludesToDependencies(includeLookup, ambiguous); if (command == "--ambiguous") { printf("Found %zu ambiguous includes\n\n", ambiguous.size()); for (auto &i : ambiguous) { printf("Include for %s\nFound in:\n", i.first.c_str()); for (auto &s : i.second) { printf(" included from %s\n", s.c_str()); } printf("Options for file:\n"); for (auto &c : collisions[i.first]) { printf(" %s\n", c.c_str()); } printf("\n"); } exit(0); } } PropagateExternalIncludes(); ExtractPublicDependencies(); void (*function)(int, char **); function = functions[command]; if (!function) { function = functions["--help"]; } function(argc, argv); return 0; } <commit_msg>Added cycle check before --shortest so that it will print cycle colors for links that are part of a cycle<commit_after>/* * Copyright (C) 2012-2016. TomTom International BV (http://tomtom.com). * * 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. */ #include "Component.h" #include "Input.h" #include "CmakeRegen.h" #include "Output.h" #include "Analysis.h" #include "Constants.h" #include <boost/filesystem.hpp> #include <boost/filesystem/fstream.hpp> /** * These variables contain the global lists of components and files. * They are globally accessible. */ std::unordered_map<std::string, Component *> components; std::unordered_map<std::string, File> files; static bool CheckVersionFile() { const std::string currentVersion = CURRENT_VERSION; std::string version; boost::filesystem::ifstream in(VERSION_FILE); getline(in, version); return (version == currentVersion); } std::string targetFrom(const std::string &arg) { std::string target = arg; if (!target.empty() && target.back() == '/') { target.pop_back(); } std::replace(target.begin(), target.end(), '.', '/'); return target; } std::map<std::string, void (*)(int, char **)> functions = { {"--graph", [](int argc, char **argv) { if (argc != 3) { printf("Usage: %s --graph <outputfile>\n", argv[0]); } else { FindCircularDependencies(); OutputFlatDependencies(argv[2]); } }}, {"--graph-cycles", [](int argc, char **argv) { if (argc != 3) { printf("Usage: %s --graph-cycles <outputfile>\n", argv[0]); } else { FindCircularDependencies(); OutputCircularDependencies(argv[2]); } }}, {"--graph-target", [](int argc, char **argv) { if (argc != 4) { printf("Usage: %s --graph-target <targetname> <outputfile>\n", argv[0]); } else { FindCircularDependencies(); PrintGraphOnTarget(argv[3], components[std::string("./") + targetFrom(argv[2])]); } }}, {"--cycles", [](int argc, char **argv) { if (argc != 3) { printf("Usage: %s --cycles <targetname>\n", argv[0]); } else { FindCircularDependencies(); PrintCyclesForTarget(components[std::string("./") + targetFrom(argv[2])]); } }}, {"--stats", [](int, char **) { std::size_t totalPublicLinks(0), totalPrivateLinks(0); for (const auto &c : components) { totalPublicLinks += c.second->pubDeps.size(); totalPrivateLinks += c.second->privDeps.size(); } fprintf(stderr, "%zu components with %zu public dependencies, %zu private dependencies\n", components.size(), totalPublicLinks, totalPrivateLinks); FindCircularDependencies(); fprintf(stderr, "Detected %zu nodes in cycles\n", NodesWithCycles()); }}, {"--inout", [](int argc, char **argv) { if (argc != 3) { printf("Usage: %s --inout <targetname>\n", argv[0]); } else { PrintLinksForTarget(components[std::string("./") + targetFrom(argv[2])]); } }}, {"--shortest", [](int argc, char **argv) { if (argc != 4) { printf("Usage: %s --shortest <targetname-from> <targetname-to>\n", argv[0]); } else { FindCircularDependencies(); FindSpecificLink(components[std::string("./") + targetFrom(argv[2])], components[std::string("./") + targetFrom(argv[3])]); } }}, {"--info", [](int argc, char **argv) { if (argc != 3) { printf("Usage: %s --info <targetname>\n", argv[0]); } else { PrintInfoOnTarget(components[std::string("./") + targetFrom(argv[2])]); } }}, {"--usedby", [](int argc, char **argv) { if (argc != 3) { printf("Usage: %s --usedby <filename>\n", argv[0]); } else { auto f = &files[std::string("./") + argv[2]]; for (auto &p : files) { if (p.second.dependencies.find(f) != p.second.dependencies.end()) { std::cout << p.second.path.string() << "\n"; } } } }}, {"--regen", [](int argc, char **argv) { if (argc >= 3) { for (int n = 2; n < argc; n++) { if (components.find(targetFrom(argv[n])) != components.end()) { RegenerateCmakeFilesForComponent(components[targetFrom(argv[2])], false); } else { std::cout << "Target '" << targetFrom(argv[2]) << "' not found\n"; } } } else { for (auto &c : components) { RegenerateCmakeFilesForComponent(c.second, false); } } }}, {"--dryregen", [](int argc, char **argv) { if (argc >= 3) { for (int n = 2; n < argc; n++) { if (components.find(targetFrom(argv[n])) != components.end()) { RegenerateCmakeFilesForComponent(components[targetFrom(argv[2])], true); } else { std::cout << "Target '" << targetFrom(argv[2]) << "' not found\n"; } } } else { for (auto &c : components) { RegenerateCmakeFilesForComponent(c.second, true); } } }}, {"--help", [](int, char **argv) { printf("C++ Dependencies -- a tool to analyze large C++ code bases for #include dependency information\n"); printf("Copyright (C) 2016, TomTom International BV\n"); printf("\n"); printf(" Usage:\n"); printf(" %s [--dir <source-directory>] <command>\n", argv[0]); printf(" Source directory is assumed to be the current one if unspecified\n"); printf("\n"); printf(" Commands:\n"); printf(" --help : Produce this help text\n"); printf("\n"); printf(" Extracting graphs:\n"); printf(" --graph <output> : Graph of all components with dependencies\n"); printf(" --graph-cycles <output> : Graph of components with cyclic dependencies on other components\n"); printf(" --graph-for <output> <target> : Graph for all dependencies of a specific target\n"); printf("\n"); printf(" Getting information:\n"); printf(" --stats : Info about code base size, complexity and cyclic dependency count\n"); printf(" --cycles <targetname> : Find all possible paths from this target back to itself\n"); printf(" --shortest : Determine shortest path between components and its reason\n"); printf("\n"); printf(" Target information:\n"); printf(" --info : Show all information on a given specific target\n"); printf(" --usedby : Find all references to a specific header file\n"); printf(" --inout : Find all incoming and outgoing links for a target\n"); printf(" --ambiguous : Find all include statements that could refer to more than one header\n"); }}, // --ignore : Handled during input parsing as it is a pre-filter for CheckCycles instead. }; int main(int argc, char **argv) { boost::filesystem::path root = boost::filesystem::current_path(); std::unordered_set<std::string> ignorefiles = { "unistd.h", "console.h", "stdint.h", "windows.h", "library.h", "endian.h", "rle.h", }; if (argc > 1 && argv[1] == std::string("--dir")) { // Extract the root directory, reshuffle the other parameters. root = argv[2]; argv[2] = argv[0]; argv += 2; argc -= 2; } std::string command; if (argc > 1) { std::transform(argv[1], argv[1] + strlen(argv[1]), std::back_inserter(command), ::tolower); } else { command = "--help"; } if (command == "--ignore") { for (int n = 2; n < argc; n++) { ignorefiles.insert(argv[n]); } argc = 1; command = "--stats"; } if (command == "--regen" && !CheckVersionFile()) { fprintf(stderr, "Version of dependency checker not the same as the one used to generate the existing cmakelists. Refusing to regen\n" "Please manually update " VERSION_FILE " to version \"" CURRENT_VERSION "\" if you really want to do this.\n"); command = "--dryregen"; } LoadFileList(ignorefiles, root); CheckVersionFile(); { std::map<std::string, std::set<std::string>> collisions; std::unordered_map<std::string, std::string> includeLookup; CreateIncludeLookupTable(includeLookup, collisions); MapFilesToComponents(); std::map<std::string, std::vector<std::string>> ambiguous; MapIncludesToDependencies(includeLookup, ambiguous); if (command == "--ambiguous") { printf("Found %zu ambiguous includes\n\n", ambiguous.size()); for (auto &i : ambiguous) { printf("Include for %s\nFound in:\n", i.first.c_str()); for (auto &s : i.second) { printf(" included from %s\n", s.c_str()); } printf("Options for file:\n"); for (auto &c : collisions[i.first]) { printf(" %s\n", c.c_str()); } printf("\n"); } exit(0); } } PropagateExternalIncludes(); ExtractPublicDependencies(); void (*function)(int, char **); function = functions[command]; if (!function) { function = functions["--help"]; } function(argc, argv); return 0; } <|endoftext|>
<commit_before>#include "Arduino.h" #include "LiquidCrystal.h" LiquidCrystal lcd(12, 11, 5, 4, 3, 2); const unsigned int NUM_READS = 8; const unsigned int TEMP_SENSOR_PIN = A0; const unsigned int VOLTAGE_SENSOR_PIN = A1; const float baseline_temp = 20.0; void setup() { analogReference(EXTERNAL); Serial.begin(9600); pinMode(8, OUTPUT); digitalWrite(8, LOW); lcd.begin(16, 2); } void loop() { unsigned int temp_sensor = 0; float voltage, temp; analogRead(TEMP_SENSOR_PIN); for (unsigned int i = 0; i < NUM_READS; i++) { temp_sensor += analogRead(TEMP_SENSOR_PIN); } temp_sensor /= NUM_READS; voltage = (temp_sensor / 1024.0) * 3.3; temp = (voltage - 0.5) * 100; Serial.print("Temperature Sensor Value: "); Serial.print(temp_sensor); Serial.print(", Voltage: "); Serial.print(voltage); Serial.print(", Temperature: "); Serial.print(temp); Serial.println(" degrees C"); lcd.clear(); lcd.print(temp); lcd.print((char) 223); lcd.print("C"); delay(1000); } int main(void) { init(); setup(); for (;;) { loop(); } } <commit_msg>Playing w/ servo<commit_after>#include "Arduino.h" #include "LiquidCrystal.h" // #include "Servo.h" LiquidCrystal lcd(12, 11, 5, 4, 3, 2); const unsigned int NUM_READS = 8; const unsigned int TEMP_SENSOR_PIN = A0; const unsigned int VOLTAGE_SENSOR_PIN = A1; const float baseline_temp = 20.0; // unsigned int angle = 0; // Servo servo; void setup() { analogReference(EXTERNAL); Serial.begin(9600); // relay pinMode(8, OUTPUT); digitalWrite(8, LOW); // servo // servo.attach(9); // servo.write(angle); // lcd lcd.begin(16, 2); } void loop() { unsigned int temp_sensor = 0; float voltage, temp; analogRead(TEMP_SENSOR_PIN); for (unsigned int i = 0; i < NUM_READS; i++) { temp_sensor += analogRead(TEMP_SENSOR_PIN); } temp_sensor /= NUM_READS; voltage = (temp_sensor / 1024.0) * 3.3; temp = (voltage - 0.5) * 100; Serial.print("Temperature Sensor Value: "); Serial.print(temp_sensor); Serial.print(", Voltage: "); Serial.print(voltage); Serial.print(", Temperature: "); Serial.print(temp); Serial.println(" degrees C"); lcd.clear(); lcd.print(temp); lcd.print((char) 223); lcd.print("C"); // unsigned long time = millis(); // angle = (angle + 60) % 180; // lcd.setCursor(0, 1); // lcd.print(angle); // lcd.print((char) 223); // servo.write(angle); delay(1000); } int main(void) { init(); setup(); for (;;) { loop(); } } <|endoftext|>
<commit_before>#include <iostream> #include <vector> #include <chrono> #include "nnlib.h" using namespace std; using namespace nnlib; int main() { cout << "========== Sanity Test ==========" << endl; size_t inps = 3; size_t outs = 2; size_t batch = 5; Linear<double> layer1(inps, outs, batch); Vector<double> &bias = *(Vector<double> *)layer1.parameters()[0]; Matrix<double> &weights = *(Matrix<double> *)layer1.parameters()[1]; Vector<double> parameters(layer1.parameters()); for(double &val : parameters) val = Random<double>::normal(0, 1, 1); Matrix<double> inputs(batch, inps); for(double &val : inputs) val = Random<double>::normal(0, 1, 1); Matrix<double> blame(batch, outs); for(double &val : blame) val = Random<double>::normal(0, 1, 1); Matrix<double> targets(batch, outs); targets.fill(-0.25); Matrix<double> outputs(batch, outs); for(size_t i = 0; i < batch; ++i) { for(size_t j = 0; j < outs; ++j) { outputs(i, j) = bias(j); for(size_t k = 0; k < inps; ++k) outputs(i, j) += inputs(i, k) * weights(j, k); } } layer1.forward(inputs); for(size_t i = 0; i < batch; ++i) for(size_t j = 0; j < outs; ++j) NNAssert(fabs(outputs(i, j) - layer1.output()(i, j)) < 1e-6, "Linear::forward failed!"); cout << "Linear::forward passed!" << endl; Matrix<double> inputBlame(batch, inps, 0); for(size_t i = 0; i < batch; ++i) for(size_t j = 0; j < inps; ++j) for(size_t k = 0; k < outs; ++k) inputBlame(i, j) += blame(i, k) * weights(k, j); layer1.backward(inputs, blame); for(size_t i = 0; i < batch; ++i) for(size_t j = 0; j < inps; ++j) NNAssert(fabs(inputBlame(i, j) - layer1.inputBlame()(i, j)) < 1e-6, "Linear::backword failed!"); cout << "Linear::backward passed!" << endl; TanH<double> layer2(outs, batch); Sequential<double> nn; nn.add(new Linear<double>(layer1)); nn.add(new TanH<double>(layer2)); SSE<double> critic(outs, batch); SGD<Module<double>, SSE<double>> optimizer(nn, critic); nn.forward(inputs); for(size_t i = 0; i < batch; ++i) for(size_t j = 0; j < outs; ++j) NNAssert(fabs(nn.output()(i, j) - tanh(layer1.output()(i, j))) < 1e-6, "Sequential::forward failed!"); cout << "Sequential::forward passed!" << endl; for(size_t i = 0; i < 10000; ++i) { Matrix<double>::shuffleRows(inputs, targets); optimizer.optimize(inputs, targets); } NNAssert(critic.forward(nn.forward(inputs), targets).sum() < 1.25, "SGD::optimize failed!"); cout << "SGD::optimize passed!" << endl; cout << "Sanity test passed!" << endl << endl; using clock = chrono::high_resolution_clock; chrono::time_point<clock> start; // MARK: Concat Test { cout << "========== Simple Concat ==========" << endl; Sequential<> *one = new Sequential<>(new Linear<>(1, 1)); Sequential<> *two = new Sequential<>(new Linear<>(1, 1), new Sin<>()); Concat<> *concat = new Concat<>(one, two); Sequential<> nn(concat); dynamic_cast<Linear<> *>(one->component(0))->bias().fill(0); dynamic_cast<Linear<> *>(one->component(0))->weights().fill(1); dynamic_cast<Linear<> *>(two->component(0))->bias().fill(0); dynamic_cast<Linear<> *>(two->component(0))->weights().fill(1); Matrix<> input(1, 1); input(0, 0) = 1; nn.forward(input); NNHardAssert(nn.output()(0, 0) == 1, "Linear portion failed!"); NNHardAssert(nn.output()(0, 1) == sin(1), "Sinusoid portion failed!"); cout << "Simple concat test passed!" << endl << endl; } { cout << "========== Concat Test ==========" << endl; cout << "Loading data..." << flush; Matrix<> train = Loader<>::loadArff("../datasets/mackey-glass/train.arff"); Matrix<> test = Loader<>::loadArff("../datasets/mackey-glass/test.arff"); cout << " Done." << endl; cout << "Preprocessing data..." << flush; Matrix<> trainFeat = train.block(0, 0, train.rows(), 1); Matrix<> trainLab = train.block(0, 1, train.rows(), 1); Matrix<> testFeat = test.block(0, 0, test.rows(), 1); Matrix<> testLab = test.block(0, 1, test.rows(), 1); double biggest = trainLab(0, 0), smallest = trainLab(0, 0); for(auto d : trainLab) biggest = std::max(biggest, d), smallest = std::min(smallest, d); for(auto &d : trainLab) d = 10 * (d - smallest) / (biggest - smallest); for(auto &d : testLab) d = 10 * (d - smallest) / (biggest - smallest); Saver<>::saveArff(trainLab, "newtrain.arff"); cout << " Done." << endl; cout << "Creating network..." << flush; Linear<> *sine = new Linear<>(1, train.rows()), *line = new Linear<>(1, 10), *out = new Linear<>(1); Concat<> *concat = new Concat<>( new Sequential<>(sine, new Sin<>()), new Sequential<>(line) ); Sequential<> nn(concat, out); SSE<double> critic(1); auto optimizer = MakeOptimizer<SGD>(nn, critic); optimizer.learningRate(0.001); cout << " Done." << endl; cout << "Initializing weights..." << flush; { auto &bias = sine->bias(); auto &weights = sine->weights(); for(size_t i = 0; i < bias.size() / 2; ++i) { for(size_t j = 0; j < weights.cols(); ++j) { weights(2 * i, j) = 2.0 * M_PI * (i + 1); weights(2 * i + 1, j) = 2.0 * M_PI * (i + 1); } bias(2 * i) = 0.5 * M_PI; bias(2 * i + 1) = M_PI; } } line->bias().fill(0); line->weights().fill(1); out->bias().scale(0.001); out->weights().scale(0.001); cout << " Done." << endl; cout << "Initial SSE: " << flush; nn.batch(testFeat.rows()); critic.batch(testFeat.rows()); cout << critic.forward(nn.forward(testFeat), testLab).sum() << endl; size_t epochs = 1000; size_t batchesPerEpoch = train.rows(); size_t batchSize = 1; double l1 = 0.01; Batcher<double> batcher(trainFeat, trainLab, batchSize); nn.batch(batchSize); critic.batch(batchSize); cout << "Training..." << endl; for(size_t i = 0; i < epochs; ++i) { for(size_t j = 0; j < batchesPerEpoch; ++j) { for(auto &w : out->bias()) w = w > 0 ? std::max(0.0, w - l1) : std::min(0.0, w + l1); for(auto &w : out->weights()) w = w > 0 ? std::max(0.0, w - l1) : std::min(0.0, w + l1); optimizer.optimize(batcher.features(), batcher.labels()); batcher.next(true); } Progress::display(i, epochs); nn.batch(testFeat.rows()); critic.batch(testFeat.rows()); cout << "\t" << critic.forward(nn.forward(testFeat), testLab).sum() << flush; nn.batch(batchSize); critic.batch(batchSize); } Progress::display(epochs, epochs, '\n'); nn.batch(testFeat.rows()); nn.forward(testFeat); for(auto &d : nn.output()) d = d * (biggest - smallest) / 10.0 + smallest; Saver<>::saveArff(nn.output(), "prediction.arff"); cout << endl; } // MARK: MNIST Test { cout << "========== MNIST Test ==========" << endl; cout << "Loading data..." << flush; start = clock::now(); Matrix<double> train = Loader<double>::loadArff("../datasets/mnist/train.arff"); Matrix<double> test = Loader<double>::loadArff("../datasets/mnist/test.arff"); cout << " Done in " << chrono::duration<double>(clock::now() - start).count() << endl; cout << "Preprocessing data..." << flush; start = clock::now(); Matrix<double> trainLab(train.rows(), 10, 0.0); Matrix<double> trainFeat = train.block(0, 0, train.rows(), train.cols() - 1); trainFeat.scale(1.0 / 255.0); Matrix<double> testLab(test.rows(), 10, 0.0); Matrix<double> testFeat = test.block(0, 0, test.rows(), test.cols() - 1); testFeat.scale(1.0 / 255.0); for(size_t i = 0; i < train.rows(); ++i) trainLab(i, train(i).back()) = 1.0; for(size_t i = 0; i < test.rows(); ++i) testLab(i, test(i).back()) = 1.0; cout << " Done in " << chrono::duration<double>(clock::now() - start).count() << endl; cout << "Creating network..." << flush; start = clock::now(); Sequential<> nn; nn.add( new Linear<>(trainFeat.cols(), 300), new TanH<>(), new Linear<>(100), new TanH<>(), new Linear<>(10), new TanH<>() ); SSE<double> critic(10); auto optimizer = MakeOptimizer<RMSProp>(nn, critic); cout << " Done in " << chrono::duration<double>(clock::now() - start).count() << endl; cout << "Initial SSE: " << flush; nn.batch(testFeat.rows()); critic.batch(testFeat.rows()); cout << critic.forward(nn.forward(testFeat), testLab).sum() << endl; size_t epochs = 100; size_t batchesPerEpoch = 100; size_t batchSize = 10; Batcher<double> batcher(trainFeat, trainLab, batchSize); nn.batch(batchSize); critic.batch(batchSize); cout << "Training..." << endl; start = clock::now(); for(size_t i = 0; i < epochs; ++i) { for(size_t j = 0; j < batchesPerEpoch; ++j) { optimizer.optimize(batcher.features(), batcher.labels()); batcher.next(true); } Progress::display(i, epochs); nn.batch(testFeat.rows()); critic.batch(testFeat.rows()); cout << "\t" << critic.forward(nn.forward(testFeat), testLab).sum() << flush; nn.batch(batchSize); critic.batch(batchSize); } Progress::display(epochs, epochs, '\n'); cout << " Done in " << chrono::duration<double>(clock::now() - start).count() << endl; } return 0; } <commit_msg>Simple concat test checks forward and backward now.<commit_after>#include <iostream> #include <vector> #include <chrono> #include "nnlib.h" using namespace std; using namespace nnlib; int main() { cout << "========== Sanity Test ==========" << endl; size_t inps = 3; size_t outs = 2; size_t batch = 5; Linear<double> layer1(inps, outs, batch); Vector<double> &bias = *(Vector<double> *)layer1.parameters()[0]; Matrix<double> &weights = *(Matrix<double> *)layer1.parameters()[1]; Vector<double> parameters(layer1.parameters()); for(double &val : parameters) val = Random<double>::normal(0, 1, 1); Matrix<double> inputs(batch, inps); for(double &val : inputs) val = Random<double>::normal(0, 1, 1); Matrix<double> blame(batch, outs); for(double &val : blame) val = Random<double>::normal(0, 1, 1); Matrix<double> targets(batch, outs); targets.fill(-0.25); Matrix<double> outputs(batch, outs); for(size_t i = 0; i < batch; ++i) { for(size_t j = 0; j < outs; ++j) { outputs(i, j) = bias(j); for(size_t k = 0; k < inps; ++k) outputs(i, j) += inputs(i, k) * weights(j, k); } } layer1.forward(inputs); for(size_t i = 0; i < batch; ++i) for(size_t j = 0; j < outs; ++j) NNAssert(fabs(outputs(i, j) - layer1.output()(i, j)) < 1e-6, "Linear::forward failed!"); cout << "Linear::forward passed!" << endl; Matrix<double> inputBlame(batch, inps, 0); for(size_t i = 0; i < batch; ++i) for(size_t j = 0; j < inps; ++j) for(size_t k = 0; k < outs; ++k) inputBlame(i, j) += blame(i, k) * weights(k, j); layer1.backward(inputs, blame); for(size_t i = 0; i < batch; ++i) for(size_t j = 0; j < inps; ++j) NNAssert(fabs(inputBlame(i, j) - layer1.inputBlame()(i, j)) < 1e-6, "Linear::backword failed!"); cout << "Linear::backward passed!" << endl; TanH<double> layer2(outs, batch); Sequential<double> nn; nn.add(new Linear<double>(layer1)); nn.add(new TanH<double>(layer2)); SSE<double> critic(outs, batch); SGD<Module<double>, SSE<double>> optimizer(nn, critic); nn.forward(inputs); for(size_t i = 0; i < batch; ++i) for(size_t j = 0; j < outs; ++j) NNAssert(fabs(nn.output()(i, j) - tanh(layer1.output()(i, j))) < 1e-6, "Sequential::forward failed!"); cout << "Sequential::forward passed!" << endl; for(size_t i = 0; i < 10000; ++i) { Matrix<double>::shuffleRows(inputs, targets); optimizer.optimize(inputs, targets); } NNAssert(critic.forward(nn.forward(inputs), targets).sum() < 1.25, "SGD::optimize failed!"); cout << "SGD::optimize passed!" << endl; cout << "Sanity test passed!" << endl << endl; using clock = chrono::high_resolution_clock; chrono::time_point<clock> start; // MARK: Concat Test { cout << "========== Simple Concat ==========" << endl; Sequential<> *one = new Sequential<>(new Linear<>(1, 1)); Sequential<> *two = new Sequential<>(new Linear<>(1, 1), new Sin<>()); Concat<> *concat = new Concat<>(one, two); Sequential<> nn(concat); dynamic_cast<Linear<> *>(one->component(0))->bias().fill(0); dynamic_cast<Linear<> *>(one->component(0))->weights().fill(1); dynamic_cast<Linear<> *>(two->component(0))->bias().fill(0); dynamic_cast<Linear<> *>(two->component(0))->weights().fill(1); Matrix<> input(1, 1); input(0, 0) = 1; Matrix<> blame(1, 2); blame(0, 0) = 1; blame(0, 1) = 0.5; nn.forward(input); nn.backward(input, blame); NNHardAssert(nn.output()(0, 0) == 1, "Linear forward in concat failed!"); NNHardAssert(nn.output()(0, 1) == sin(1), "Sinusoid forward in concat failed!"); NNHardAssert(nn.inputBlame()(0, 0) == 1 + 0.5 * cos(1), "Backward in concat failed!"); cout << "Simple concat test passed!" << endl << endl; } { cout << "========== Concat Test ==========" << endl; cout << "Loading data..." << flush; Matrix<> train = Loader<>::loadArff("../datasets/mackey-glass/train.arff"); Matrix<> test = Loader<>::loadArff("../datasets/mackey-glass/test.arff"); cout << " Done." << endl; cout << "Preprocessing data..." << flush; Matrix<> trainFeat = train.block(0, 0, train.rows(), 1); Matrix<> trainLab = train.block(0, 1, train.rows(), 1); Matrix<> testFeat = test.block(0, 0, test.rows(), 1); Matrix<> testLab = test.block(0, 1, test.rows(), 1); double biggest = trainLab(0, 0), smallest = trainLab(0, 0); for(auto d : trainLab) biggest = std::max(biggest, d), smallest = std::min(smallest, d); for(auto &d : trainLab) d = 10 * (d - smallest) / (biggest - smallest); for(auto &d : testLab) d = 10 * (d - smallest) / (biggest - smallest); Saver<>::saveArff(trainLab, "newtrain.arff"); cout << " Done." << endl; cout << "Creating network..." << flush; Linear<> *sine = new Linear<>(1, train.rows()), *line = new Linear<>(1, 10), *out = new Linear<>(1); Concat<> *concat = new Concat<>( new Sequential<>(sine, new Sin<>()), new Sequential<>(line) ); Sequential<> nn(concat, out); SSE<double> critic(1); auto optimizer = MakeOptimizer<SGD>(nn, critic); optimizer.learningRate(0.001); cout << " Done." << endl; cout << "Initializing weights..." << flush; { auto &bias = sine->bias(); auto &weights = sine->weights(); for(size_t i = 0; i < bias.size() / 2; ++i) { for(size_t j = 0; j < weights.cols(); ++j) { weights(2 * i, j) = 2.0 * M_PI * (i + 1); weights(2 * i + 1, j) = 2.0 * M_PI * (i + 1); } bias(2 * i) = 0.5 * M_PI; bias(2 * i + 1) = M_PI; } } line->bias().fill(0); line->weights().fill(1); out->bias().scale(0.001); out->weights().scale(0.001); cout << " Done." << endl; cout << "Initial SSE: " << flush; nn.batch(testFeat.rows()); critic.batch(testFeat.rows()); cout << critic.forward(nn.forward(testFeat), testLab).sum() << endl; size_t epochs = 1000; size_t batchesPerEpoch = train.rows(); size_t batchSize = 1; double l1 = 0.01; Batcher<double> batcher(trainFeat, trainLab, batchSize); nn.batch(batchSize); critic.batch(batchSize); cout << "Training..." << endl; for(size_t i = 0; i < epochs; ++i) { for(size_t j = 0; j < batchesPerEpoch; ++j) { for(auto &w : out->bias()) w = w > 0 ? std::max(0.0, w - l1) : std::min(0.0, w + l1); for(auto &w : out->weights()) w = w > 0 ? std::max(0.0, w - l1) : std::min(0.0, w + l1); optimizer.optimize(batcher.features(), batcher.labels()); batcher.next(true); } Progress::display(i, epochs); nn.batch(testFeat.rows()); critic.batch(testFeat.rows()); cout << "\t" << critic.forward(nn.forward(testFeat), testLab).sum() << flush; nn.batch(batchSize); critic.batch(batchSize); } Progress::display(epochs, epochs, '\n'); nn.batch(testFeat.rows()); nn.forward(testFeat); for(auto &d : nn.output()) d = d * (biggest - smallest) / 10.0 + smallest; Saver<>::saveArff(nn.output(), "prediction.arff"); cout << endl; } // MARK: MNIST Test { cout << "========== MNIST Test ==========" << endl; cout << "Loading data..." << flush; start = clock::now(); Matrix<double> train = Loader<double>::loadArff("../datasets/mnist/train.arff"); Matrix<double> test = Loader<double>::loadArff("../datasets/mnist/test.arff"); cout << " Done in " << chrono::duration<double>(clock::now() - start).count() << endl; cout << "Preprocessing data..." << flush; start = clock::now(); Matrix<double> trainLab(train.rows(), 10, 0.0); Matrix<double> trainFeat = train.block(0, 0, train.rows(), train.cols() - 1); trainFeat.scale(1.0 / 255.0); Matrix<double> testLab(test.rows(), 10, 0.0); Matrix<double> testFeat = test.block(0, 0, test.rows(), test.cols() - 1); testFeat.scale(1.0 / 255.0); for(size_t i = 0; i < train.rows(); ++i) trainLab(i, train(i).back()) = 1.0; for(size_t i = 0; i < test.rows(); ++i) testLab(i, test(i).back()) = 1.0; cout << " Done in " << chrono::duration<double>(clock::now() - start).count() << endl; cout << "Creating network..." << flush; start = clock::now(); Sequential<> nn; nn.add( new Linear<>(trainFeat.cols(), 300), new TanH<>(), new Linear<>(100), new TanH<>(), new Linear<>(10), new TanH<>() ); SSE<double> critic(10); auto optimizer = MakeOptimizer<RMSProp>(nn, critic); cout << " Done in " << chrono::duration<double>(clock::now() - start).count() << endl; cout << "Initial SSE: " << flush; nn.batch(testFeat.rows()); critic.batch(testFeat.rows()); cout << critic.forward(nn.forward(testFeat), testLab).sum() << endl; size_t epochs = 100; size_t batchesPerEpoch = 100; size_t batchSize = 10; Batcher<double> batcher(trainFeat, trainLab, batchSize); nn.batch(batchSize); critic.batch(batchSize); cout << "Training..." << endl; start = clock::now(); for(size_t i = 0; i < epochs; ++i) { for(size_t j = 0; j < batchesPerEpoch; ++j) { optimizer.optimize(batcher.features(), batcher.labels()); batcher.next(true); } Progress::display(i, epochs); nn.batch(testFeat.rows()); critic.batch(testFeat.rows()); cout << "\t" << critic.forward(nn.forward(testFeat), testLab).sum() << flush; nn.batch(batchSize); critic.batch(batchSize); } Progress::display(epochs, epochs, '\n'); cout << " Done in " << chrono::duration<double>(clock::now() - start).count() << endl; } return 0; } <|endoftext|>
<commit_before>#include <iostream> #include <vector> #include "World.h" #include "Renderer.h" #include "ForwardRasterizer.h" #include "DeferredRasterizer.h" #include "Camera.h" #include "Light.h" #include "DirectionalLight.h" #include "PointLight.h" #include "OrthographicCamera.h" #include "PerspectiveCamera.h" #include "Constants.h" // Forward declaration utils functions void buildAlignedBox(std::vector<Point3D>& vertices, std::vector<Vector2D>& texture_coords, std::vector<uint32_t>& indices, const float side); GeometryObject* buildPlainBox(Material* material, const RGBColor& color, const Point3D& center, const float side); GeometryObject* buildTexturedBox(Material* material, const Point3D& center, const float side); void buildHorizontalPlane(std::vector<Point3D>& vertices, std::vector<Vector2D>& texture_coords, std::vector<uint32_t>& indices, const float side); GeometryObject* buildTexturedPlane(Material* material, const Point3D& center, const float side); GeometryObject* buildPlainPlane(Material* material, const RGBColor& color, const Point3D& center, const float side); GeometryObject* buildMultiColorBox(Material* material, const Point3D& center, const float side); const std::vector<GeometryObject*> setupFlatScene(); const std::vector<GeometryObject*> setupTexturedScene(); Camera * camera; Renderer * renderer; int main (){ std::vector<Light*> lights = { new DirectionalLight(Colors::WHITE, Vector3D(-1, -1, -1)) }; const std::vector<GeometryObject*> objects_flat = setupFlatScene(); const std::vector<GeometryObject*> objects_textured = setupTexturedScene(); World * world = new World(objects_textured, lights, camera); #ifdef _FORWARD renderer = new ForwardRasterizer(world); #endif #ifdef _DEFERRED renderer = new DeferredRasterizer(world); #endif #ifdef _ORTHOGRAPHIC camera = new OrthographicCamera(CAMERA_POS, CAMERA_TARGET, IMAGE_HEIGHT, IMAGE_WIDTH, renderer); #endif #ifdef _PERSPECTIVE camera = new PerspectiveCamera(CAMERA_POS, CAMERA_TARGET, IMAGE_HEIGHT, IMAGE_WIDTH, renderer); #endif world->m_camera = camera; renderer->render(); renderer->export_output(IMAGE_NAME); return 0; } const std::vector<GeometryObject*> setupFlatScene() { std::vector<GeometryObject*> objects; // Objects /**/ GeometryObject* ground = buildPlainPlane(Materials::FLAT_PLASTIC, Colors::GREY, Point3D(0, 0, 0), 500); objects.push_back(ground); GeometryObject* flat_box = buildPlainBox(Materials::FLAT_PLASTIC, Colors::RED, Point3D(0, 0, 0), 100); flat_box->translate(Vector3D(150, 50, 100)); flat_box->rotate(0, 45, 0); objects.push_back(flat_box); //GeometryObject* ground2 = buildPlainPlane(Materials::FLAT_PLASTIC, Colors::YELLOW, Point3D(247, 0.29, -249), 10); //objects.push_back(ground2); /* GeometryObject* flat_box2 = buildPlainBox(Materials::FLAT_PLASTIC, Colors::BLUE, Point3D(150, 125, 100), 50); objects.push_back(flat_box2); GeometryObject* flying_box = buildPlainBox(Materials::FLAT_PLASTIC, Colors::GREEN, Point3D(-100, 80, 75), 50); flying_box->rotate(45, -45, 45); objects.push_back(flying_box); GeometryObject* multicolor_box = buildMultiColorBox(Materials::FLAT_PLASTIC, Point3D(-100, 50, -90), 100); objects.push_back(multicolor_box); GeometryObject* small_box1 = buildPlainBox(Materials::FLAT_PLASTIC, Colors::YELLOW, Point3D(150, 40, -100), 20); objects.push_back(small_box1); GeometryObject* small_box2 = buildPlainBox(Materials::FLAT_PLASTIC, Colors::YELLOW, Point3D(150, 60, -100), 20); objects.push_back(small_box2); GeometryObject* small_box3 = buildPlainBox(Materials::FLAT_PLASTIC, Colors::YELLOW, Point3D(130, 40, -100), 20); objects.push_back(small_box3); GeometryObject* small_box4 = buildPlainBox(Materials::FLAT_PLASTIC, Colors::YELLOW, Point3D(150, 40, -120), 20); objects.push_back(small_box4); GeometryObject* small_box5 = buildPlainBox(Materials::FLAT_PLASTIC, Colors::YELLOW, Point3D(125, 40, -125), 20); small_box5->rotate(0, 45, 0); objects.push_back(small_box5); */ return objects; } const std::vector<GeometryObject*> setupTexturedScene() { std::vector<GeometryObject*> objects; // Objects GeometryObject* ground = buildTexturedPlane(Materials::GROUND, Point3D(0, 0, 0), 500); objects.push_back(ground); GeometryObject* flat_box = buildTexturedBox(Materials::BOX, Point3D(0, 0, 0), 100); flat_box->translate(Vector3D(150, 50, 100)); flat_box->rotate(0, 45, 0); objects.push_back(flat_box); GeometryObject* flat_box2 = buildTexturedBox(Materials::BOX, Point3D(150, 125, 100), 50); objects.push_back(flat_box2); GeometryObject* flying_box = buildTexturedBox(Materials::BOX, Point3D(-100, 80, 75), 50); flying_box->rotate(45, -45, 45); objects.push_back(flying_box); GeometryObject* multicolor_box = buildTexturedBox(Materials::BOX, Point3D(-100, 50, -90), 100); objects.push_back(multicolor_box); GeometryObject* small_box1 = buildTexturedBox(Materials::DEFAULT, Point3D(150, 60, -155), 60); small_box1->rotate(0, -45, 0); objects.push_back(small_box1); /* GeometryObject* small_box2 = buildTexturedBox(Materials::DEFAULT, Point3D(150, 70, -100), 50); objects.push_back(small_box2); GeometryObject* small_box3 = buildTexturedBox(Materials::DEFAULT,Point3D(130, 40, -100), 20); objects.push_back(small_box3); GeometryObject* small_box4 = buildTexturedBox(Materials::DEFAULT, Point3D(150, 40, -120), 20); objects.push_back(small_box4); GeometryObject* small_box5 = buildTexturedBox(Materials::DEFAULT, Point3D(125, 40, -125), 20); small_box5->rotate(0, 45, 0); objects.push_back(small_box5); */ return objects; } void buildAlignedBox(std::vector<Point3D>& vertices, std::vector<Vector2D>& texture_coords, std::vector<uint32_t>& indices, const float side) { const float half_diagonal = (side / 2) / sin(PI / 2); // Distance to center // Front const Point3D v1(-half_diagonal, -half_diagonal, -half_diagonal); const Point3D v2(v1.x, v1.y + side, v1.z); const Point3D v3(v1.x + side, v1.y + side, v1.z); const Point3D v4(v1.x + side, v1.y, v1.z); // Back const Point3D v5(v1.x, v1.y, v1.z + side); const Point3D v6(v2.x, v2.y, v2.z + side); const Point3D v7(v3.x, v3.y, v3.z + side); const Point3D v8(v4.x, v4.y, v4.z + side); vertices = { // Front face v1, v2, v3, v4, // Back face v5, v6, v7, v8, // Top face v2, v6, v7, v3, // Bottom face v1, v5, v8, v4, // Left face v1, v2, v6, v5, // Right face v4, v3, v7, v8 }; texture_coords = { // Texture coordinates // Front face Vector2D(0, 0), Vector2D(0, 1), Vector2D(1, 1), Vector2D(1, 0), // Back face Vector2D(1, 1), Vector2D(1, 0), Vector2D(0, 0), Vector2D(0, 1), // Top face Vector2D(0, 0), Vector2D(0, 1), Vector2D(1, 1), Vector2D(1, 0), //// Bottom face Vector2D(0, 0), Vector2D(0, 1), Vector2D(1, 1), Vector2D(1, 0), //// Left face Vector2D(1, 0), Vector2D(1, 1), Vector2D(0, 1), Vector2D(0, 0), //// Right face Vector2D(0, 0), Vector2D(0, 1), Vector2D(1, 1), Vector2D(1, 0) }; indices = { // Vertices indices // Front face 0, 1, 2, 2, 3, 0, // Back face 6, 5, 4, 4, 7, 6, // Top face 8, 9, 10, 10, 11, 8, // Bottom face 14, 13, 12, 12, 15, 14, // Left face 16, 19, 18, 18, 17, 16, // Right face 20, 21, 22, 22, 23, 20 }; } GeometryObject* buildPlainBox(Material* material, const RGBColor& color, const Point3D& center, const float side) { const std::vector<RGBColor> colors = std::vector<RGBColor>(24, color); std::vector<Point3D> vertices; std::vector<Vector2D> texture_coords; std::vector<uint32_t> indices; buildAlignedBox(vertices, texture_coords, indices, side); GeometryObject* box = new GeometryObject(material, vertices, colors, texture_coords, indices, center); return box; } GeometryObject* buildMultiColorBox(Material* material, const Point3D& center, const float side) { const std::vector<RGBColor> colors = { Colors::RED, Colors::GREEN, Colors::RED, Colors::BLUE, Colors::RED, Colors::GREEN, Colors::RED, Colors::BLUE, Colors::RED, Colors::GREEN, Colors::RED, Colors::BLUE, Colors::RED, Colors::GREEN, Colors::RED, Colors::BLUE, Colors::RED, Colors::GREEN, Colors::RED, Colors::BLUE, Colors::RED, Colors::GREEN, Colors::RED, Colors::BLUE, }; std::vector<Point3D> vertices; std::vector<Vector2D> texture_coords; std::vector<uint32_t> indices; buildAlignedBox(vertices, texture_coords, indices, side); GeometryObject* box = new GeometryObject(material, vertices, colors, texture_coords, indices, center); return box; } GeometryObject* buildTexturedBox(Material* material, const Point3D& center, const float side) { std::vector<Point3D> vertices; std::vector<Vector2D> texture_coords; std::vector<uint32_t> indices; buildAlignedBox(vertices, texture_coords, indices, side); GeometryObject* box = new GeometryObject(material, vertices, std::vector<RGBColor>(), texture_coords, indices, center); return box; } void buildHorizontalPlane(std::vector<Point3D>& vertices, std::vector<Vector2D>& texture_coords, std::vector<uint32_t>& indices, const float side) { const float half_diagonal = (side / 2) / sin(PI / 2); // Distance to center const Point3D v1(-half_diagonal, 0, -half_diagonal); const Point3D v2(v1.x, v1.y, v1.z + side); const Point3D v3(v1.x + side, v1.y, v1.z); const Point3D v4(v1.x + side, v1.y, v1.z + side); vertices = { // Vertices positions v1, v2, v3, v4 }; texture_coords = { // Texture coordinates Vector2D(0, 0), Vector2D(0, 3), Vector2D(3, 0), Vector2D(3, 3) }; indices = { // Indices 0, 1, 2, 1, 3, 2 }; } GeometryObject* buildPlainPlane(Material* material, const RGBColor& color, const Point3D& center, const float side) { const std::vector<RGBColor> colors = std::vector<RGBColor>(4, color); std::vector<Point3D> vertices; std::vector<Vector2D> texture_coords; std::vector<uint32_t> indices; buildHorizontalPlane(vertices, texture_coords, indices, side); GeometryObject* box = new GeometryObject(material, vertices, colors, texture_coords, indices, center); return box; } GeometryObject* buildTexturedPlane(Material* material, const Point3D& center, const float side) { std::vector<Point3D> vertices; std::vector<Vector2D> texture_coords; std::vector<uint32_t> indices; buildHorizontalPlane(vertices, texture_coords, indices, side); GeometryObject* box = new GeometryObject(material, vertices, std::vector<RGBColor>(), texture_coords, indices, center); return box; }<commit_msg>Fixed build horizontal plane function (vertices, indices, and texture coords)<commit_after>#include <iostream> #include <vector> #include "World.h" #include "Renderer.h" #include "ForwardRasterizer.h" #include "DeferredRasterizer.h" #include "Camera.h" #include "Light.h" #include "DirectionalLight.h" #include "PointLight.h" #include "OrthographicCamera.h" #include "PerspectiveCamera.h" #include "Constants.h" // Forward declaration utils functions void buildAlignedBox(std::vector<Point3D>& vertices, std::vector<Vector2D>& texture_coords, std::vector<uint32_t>& indices, const float side); GeometryObject* buildPlainBox(Material* material, const RGBColor& color, const Point3D& center, const float side); GeometryObject* buildTexturedBox(Material* material, const Point3D& center, const float side); void buildHorizontalPlane(std::vector<Point3D>& vertices, std::vector<Vector2D>& texture_coords, std::vector<uint32_t>& indices, const float side); GeometryObject* buildTexturedPlane(Material* material, const Point3D& center, const float side); GeometryObject* buildPlainPlane(Material* material, const RGBColor& color, const Point3D& center, const float side); GeometryObject* buildMultiColorBox(Material* material, const Point3D& center, const float side); const std::vector<GeometryObject*> setupFlatScene(); const std::vector<GeometryObject*> setupTexturedScene(); Camera * camera; Renderer * renderer; int main (){ std::vector<Light*> lights = { new DirectionalLight(Colors::WHITE, Vector3D(-1, -1, -1)) }; const std::vector<GeometryObject*> objects_flat = setupFlatScene(); const std::vector<GeometryObject*> objects_textured = setupTexturedScene(); World * world = new World(objects_textured, lights, camera); #ifdef _FORWARD renderer = new ForwardRasterizer(world); #endif #ifdef _DEFERRED renderer = new DeferredRasterizer(world); #endif #ifdef _ORTHOGRAPHIC camera = new OrthographicCamera(CAMERA_POS, CAMERA_TARGET, IMAGE_HEIGHT, IMAGE_WIDTH, renderer); #endif #ifdef _PERSPECTIVE camera = new PerspectiveCamera(CAMERA_POS, CAMERA_TARGET, IMAGE_HEIGHT, IMAGE_WIDTH, renderer); #endif world->m_camera = camera; renderer->render(); renderer->export_output(IMAGE_NAME); return 0; } const std::vector<GeometryObject*> setupFlatScene() { std::vector<GeometryObject*> objects; // Objects /**/ GeometryObject* ground = buildPlainPlane(Materials::FLAT_PLASTIC, Colors::GREY, Point3D(0, 0, 0), 500); objects.push_back(ground); GeometryObject* flat_box = buildPlainBox(Materials::FLAT_PLASTIC, Colors::RED, Point3D(0, 0, 0), 100); flat_box->translate(Vector3D(150, 50, 100)); flat_box->rotate(0, 45, 0); objects.push_back(flat_box); //GeometryObject* ground2 = buildPlainPlane(Materials::FLAT_PLASTIC, Colors::YELLOW, Point3D(247, 0.29, -249), 10); //objects.push_back(ground2); /* GeometryObject* flat_box2 = buildPlainBox(Materials::FLAT_PLASTIC, Colors::BLUE, Point3D(150, 125, 100), 50); objects.push_back(flat_box2); GeometryObject* flying_box = buildPlainBox(Materials::FLAT_PLASTIC, Colors::GREEN, Point3D(-100, 80, 75), 50); flying_box->rotate(45, -45, 45); objects.push_back(flying_box); GeometryObject* multicolor_box = buildMultiColorBox(Materials::FLAT_PLASTIC, Point3D(-100, 50, -90), 100); objects.push_back(multicolor_box); GeometryObject* small_box1 = buildPlainBox(Materials::FLAT_PLASTIC, Colors::YELLOW, Point3D(150, 40, -100), 20); objects.push_back(small_box1); GeometryObject* small_box2 = buildPlainBox(Materials::FLAT_PLASTIC, Colors::YELLOW, Point3D(150, 60, -100), 20); objects.push_back(small_box2); GeometryObject* small_box3 = buildPlainBox(Materials::FLAT_PLASTIC, Colors::YELLOW, Point3D(130, 40, -100), 20); objects.push_back(small_box3); GeometryObject* small_box4 = buildPlainBox(Materials::FLAT_PLASTIC, Colors::YELLOW, Point3D(150, 40, -120), 20); objects.push_back(small_box4); GeometryObject* small_box5 = buildPlainBox(Materials::FLAT_PLASTIC, Colors::YELLOW, Point3D(125, 40, -125), 20); small_box5->rotate(0, 45, 0); objects.push_back(small_box5); */ return objects; } const std::vector<GeometryObject*> setupTexturedScene() { std::vector<GeometryObject*> objects; // Objects GeometryObject* ground = buildTexturedPlane(Materials::GROUND, Point3D(0, 0, 0), 500); objects.push_back(ground); /* GeometryObject* flat_box = buildTexturedBox(Materials::BOX, Point3D(0, 0, 0), 100); flat_box->translate(Vector3D(150, 50, 100)); flat_box->rotate(0, 45, 0); objects.push_back(flat_box); GeometryObject* flat_box2 = buildTexturedBox(Materials::BOX, Point3D(150, 125, 100), 50); objects.push_back(flat_box2); GeometryObject* flying_box = buildTexturedBox(Materials::BOX, Point3D(-100, 80, 75), 50); flying_box->rotate(45, -45, 45); objects.push_back(flying_box); GeometryObject* multicolor_box = buildTexturedBox(Materials::BOX, Point3D(-100, 50, -90), 100); objects.push_back(multicolor_box); GeometryObject* small_box1 = buildTexturedBox(Materials::DEFAULT, Point3D(150, 60, -155), 60); small_box1->rotate(0, -45, 0); objects.push_back(small_box1); */ /* GeometryObject* small_box2 = buildTexturedBox(Materials::DEFAULT, Point3D(150, 70, -100), 50); objects.push_back(small_box2); GeometryObject* small_box3 = buildTexturedBox(Materials::DEFAULT,Point3D(130, 40, -100), 20); objects.push_back(small_box3); GeometryObject* small_box4 = buildTexturedBox(Materials::DEFAULT, Point3D(150, 40, -120), 20); objects.push_back(small_box4); GeometryObject* small_box5 = buildTexturedBox(Materials::DEFAULT, Point3D(125, 40, -125), 20); small_box5->rotate(0, 45, 0); objects.push_back(small_box5); */ return objects; } void buildAlignedBox(std::vector<Point3D>& vertices, std::vector<Vector2D>& texture_coords, std::vector<uint32_t>& indices, const float side) { const float half_diagonal = (side / 2) / sin(PI / 2); // Distance to center // Front const Point3D v1(-half_diagonal, -half_diagonal, -half_diagonal); const Point3D v2(v1.x, v1.y + side, v1.z); const Point3D v3(v1.x + side, v1.y + side, v1.z); const Point3D v4(v1.x + side, v1.y, v1.z); // Back const Point3D v5(v1.x, v1.y, v1.z + side); const Point3D v6(v2.x, v2.y, v2.z + side); const Point3D v7(v3.x, v3.y, v3.z + side); const Point3D v8(v4.x, v4.y, v4.z + side); vertices = { // Front face v1, v2, v3, v4, // Back face v5, v6, v7, v8, // Top face v2, v6, v7, v3, // Bottom face v1, v5, v8, v4, // Left face v1, v2, v6, v5, // Right face v4, v3, v7, v8 }; texture_coords = { // Texture coordinates // Front face Vector2D(0, 0), Vector2D(0, 1), Vector2D(1, 1), Vector2D(1, 0), // Back face Vector2D(1, 1), Vector2D(1, 0), Vector2D(0, 0), Vector2D(0, 1), // Top face Vector2D(0, 0), Vector2D(0, 1), Vector2D(1, 1), Vector2D(1, 0), //// Bottom face Vector2D(0, 0), Vector2D(0, 1), Vector2D(1, 1), Vector2D(1, 0), //// Left face Vector2D(1, 0), Vector2D(1, 1), Vector2D(0, 1), Vector2D(0, 0), //// Right face Vector2D(0, 0), Vector2D(0, 1), Vector2D(1, 1), Vector2D(1, 0) }; indices = { // Vertices indices // Front face 0, 1, 2, 2, 3, 0, // Back face 6, 5, 4, 4, 7, 6, // Top face 8, 9, 10, 10, 11, 8, // Bottom face 14, 13, 12, 12, 15, 14, // Left face 16, 19, 18, 18, 17, 16, // Right face 20, 21, 22, 22, 23, 20 }; } GeometryObject* buildPlainBox(Material* material, const RGBColor& color, const Point3D& center, const float side) { const std::vector<RGBColor> colors = std::vector<RGBColor>(24, color); std::vector<Point3D> vertices; std::vector<Vector2D> texture_coords; std::vector<uint32_t> indices; buildAlignedBox(vertices, texture_coords, indices, side); GeometryObject* box = new GeometryObject(material, vertices, colors, texture_coords, indices, center); return box; } GeometryObject* buildMultiColorBox(Material* material, const Point3D& center, const float side) { const std::vector<RGBColor> colors = { Colors::RED, Colors::GREEN, Colors::RED, Colors::BLUE, Colors::RED, Colors::GREEN, Colors::RED, Colors::BLUE, Colors::RED, Colors::GREEN, Colors::RED, Colors::BLUE, Colors::RED, Colors::GREEN, Colors::RED, Colors::BLUE, Colors::RED, Colors::GREEN, Colors::RED, Colors::BLUE, Colors::RED, Colors::GREEN, Colors::RED, Colors::BLUE, }; std::vector<Point3D> vertices; std::vector<Vector2D> texture_coords; std::vector<uint32_t> indices; buildAlignedBox(vertices, texture_coords, indices, side); GeometryObject* box = new GeometryObject(material, vertices, colors, texture_coords, indices, center); return box; } GeometryObject* buildTexturedBox(Material* material, const Point3D& center, const float side) { std::vector<Point3D> vertices; std::vector<Vector2D> texture_coords; std::vector<uint32_t> indices; buildAlignedBox(vertices, texture_coords, indices, side); GeometryObject* box = new GeometryObject(material, vertices, std::vector<RGBColor>(), texture_coords, indices, center); return box; } void buildHorizontalPlane(std::vector<Point3D>& vertices, std::vector<Vector2D>& texture_coords, std::vector<uint32_t>& indices, const float side) { const float half_diagonal = (side / 2) / sin(PI / 2); // Distance to center const Point3D v1(-half_diagonal, 0, -half_diagonal); const Point3D v2(v1.x, v1.y, v1.z + side); const Point3D v3(v1.x + side, v1.y, v1.z + side); const Point3D v4(v1.x + side, v1.y, v1.z); vertices = { // Vertices positions v1, v2, v3, v4 }; texture_coords = { // Texture coordinates Vector2D(0, 0), Vector2D(0, 1), Vector2D(1, 1), Vector2D(1, 0), }; indices = { // Indices 0, 1, 2, 2, 3, 0 }; } GeometryObject* buildPlainPlane(Material* material, const RGBColor& color, const Point3D& center, const float side) { const std::vector<RGBColor> colors = std::vector<RGBColor>(4, color); std::vector<Point3D> vertices; std::vector<Vector2D> texture_coords; std::vector<uint32_t> indices; buildHorizontalPlane(vertices, texture_coords, indices, side); GeometryObject* box = new GeometryObject(material, vertices, colors, texture_coords, indices, center); return box; } GeometryObject* buildTexturedPlane(Material* material, const Point3D& center, const float side) { std::vector<Point3D> vertices; std::vector<Vector2D> texture_coords; std::vector<uint32_t> indices; buildHorizontalPlane(vertices, texture_coords, indices, side); GeometryObject* box = new GeometryObject(material, vertices, std::vector<RGBColor>(), texture_coords, indices, center); return box; }<|endoftext|>
<commit_before>#include <boost/filesystem.hpp> #include <paxos/replicaset.hpp> #include "main.hpp" #include "partition.hpp" dafs::Partition SetupPartition(std::string directory, std::string hostport) { if (!boost::filesystem::exists(directory)) { boost::filesystem::create_directory(directory); boost::filesystem::path replicasetfile(directory); replicasetfile /= ReplicasetFilename; std::fstream s(replicasetfile.string(), std::ios::in | std::ios::out | std::ios::trunc); s << hostport << std::endl; } return dafs::Partition(dafs::Root(directory)); } int main(void) { auto partition_minus = SetupPartition("p-minus", "127.0.0.1:8070"); auto partition_zero = SetupPartition("p-zero", "127.0.0.1:8080"); auto partition_plus = SetupPartition("p-plus", "127.0.0.1:8090"); partition_minus.SetIdentity(dafs::Partition::Identity{"111"}); partition_minus.SetIdentity(dafs::Partition::Identity{"222"}); partition_zero.SetIdentity(dafs::Partition::Identity{"333"}); partition_plus.SetIdentity(dafs::Partition::Identity{"444"}); partition_plus.SetIdentity(dafs::Partition::Identity{"555"}); //partition_plus.AddNode("1.1.1.1", 1111); //partition_zero.AddNode("2.2.2.2", 2222); //partition_zero.AddNode("3.3.3.3", 3333); //partition_zero.AddNode("4.4.4.4", 4444); //partition.RemoveNode("2.2.2.2", 8081); partition_plus.CreateBlock(dafs::BlockInfo{"myblock", "1.1.1.1", 1111, 0}); partition_plus.CreateBlock(dafs::BlockInfo{"yourblock", "2.2.2.2", 2222, 0}); partition_plus.CreateBlock(dafs::BlockInfo{"ourblock", "3.3.3.3", 3333, 0}); partition_plus.WriteBlock(dafs::BlockInfo{"myblock", "1.1.1.1", 1111, 0}, dafs::BlockFormat{"contents of myblock"}); //partition_plus.DeleteBlock(dafs::BlockInfo{"myblock", "127.0.0.1", 8080, 0}); for (;;); } <commit_msg>Add node with slot partitions<commit_after>#include <boost/filesystem.hpp> #include <paxos/replicaset.hpp> #include "main.hpp" #include "partition.hpp" void SetupPartition(std::string directory, std::string hostport) { if (!boost::filesystem::exists(directory)) { boost::filesystem::create_directory(directory); boost::filesystem::path replicasetfile(directory); replicasetfile /= ReplicasetFilename; std::fstream s(replicasetfile.string(), std::ios::in | std::ios::out | std::ios::trunc); s << hostport << std::endl; } } class Node { public: enum class Slot { Minus, Zero, Plus }; Node() : slot_minus(dafs::Root("p-minus")), slot_zero(dafs::Root("p-zero")), slot_plus(dafs::Root("p-plus")) { } dafs::Partition& GetPartition(Slot slot) { switch (slot) { case Slot::Minus: { return slot_minus; } case Slot::Zero: { return slot_zero; } case Slot::Plus: { return slot_plus; } } } private: dafs::Partition slot_minus; dafs::Partition slot_zero; dafs::Partition slot_plus; }; int main(void) { SetupPartition("p-minus", "127.0.0.1:8070"); SetupPartition("p-zero", "127.0.0.1:8080"); SetupPartition("p-plus", "127.0.0.1:8090"); Node n; n.GetPartition(Node::Slot::Minus).SetIdentity(dafs::Partition::Identity{"111"}); n.GetPartition(Node::Slot::Minus).SetIdentity(dafs::Partition::Identity{"222"}); n.GetPartition(Node::Slot::Zero).SetIdentity(dafs::Partition::Identity{"333"}); n.GetPartition(Node::Slot::Plus).SetIdentity(dafs::Partition::Identity{"444"}); n.GetPartition(Node::Slot::Plus).SetIdentity(dafs::Partition::Identity{"555"}); n.GetPartition(Node::Slot::Plus).CreateBlock(dafs::BlockInfo{"myblock", "1.1.1.1", 1111, 0}); n.GetPartition(Node::Slot::Plus).CreateBlock(dafs::BlockInfo{"yourblock", "2.2.2.2", 2222, 0}); n.GetPartition(Node::Slot::Plus).CreateBlock(dafs::BlockInfo{"ourblock", "3.3.3.3", 3333, 0}); n.GetPartition(Node::Slot::Plus).WriteBlock(dafs::BlockInfo{"myblock", "1.1.1.1", 1111, 0}, dafs::BlockFormat{"contents of myblock"}); n.GetPartition(Node::Slot::Plus).AddNode("1.1.1.1", 1111); n.GetPartition(Node::Slot::Zero).AddNode("2.2.2.2", 2222); n.GetPartition(Node::Slot::Zero).RemoveNode("2.2.2.2", 2222); for (;;); } <|endoftext|>
<commit_before>/* * Copyright (C) 2008-2011 The QXmpp developers * * Authors: * Ian Reinhart Geiser * Jeremy Lainé * * Source: * http://code.google.com/p/qxmpp * * This file is a part of QXmpp library. * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * */ #include <QAudioInput> #include <QAudioOutput> #include <QDebug> #include "QXmppCallManager.h" #include "QXmppJingleIq.h" #include "QXmppRtpChannel.h" #include "QXmppUtils.h" #include "xmppClient.h" xmppClient::xmppClient(QObject *parent) : QXmppClient(parent) { // add QXmppCallManager extension callManager = new QXmppCallManager; addExtension(callManager); bool check = connect(this, SIGNAL(presenceReceived(QXmppPresence)), this, SLOT(slotPresenceReceived(QXmppPresence))); Q_ASSERT(check); check = connect(callManager, SIGNAL(callReceived(QXmppCall*)), this, SLOT(slotCallReceived(QXmppCall*))); Q_ASSERT(check); } /// A call was received. void xmppClient::slotCallReceived(QXmppCall *call) { qDebug() << "Got call from:" << call->jid(); bool check = connect(call, SIGNAL(connected()), this, SLOT(slotConnected())); Q_ASSERT(check); check = connect(call, SIGNAL(finished()), this, SLOT(slotFinished())); Q_ASSERT(check); // accept call call->accept(); } /// A call connected. void xmppClient::slotConnected() { QXmppCall *call = qobject_cast<QXmppCall*>(sender()); Q_ASSERT(call); qDebug() << "Call connected"; QXmppRtpChannel *channel = call->audioChannel(); // prepare audio format QAudioFormat format; format.setFrequency(channel->payloadType().clockrate()); format.setChannels(channel->payloadType().channels()); format.setSampleSize(16); format.setCodec("audio/pcm"); format.setByteOrder(QAudioFormat::LittleEndian); format.setSampleType(QAudioFormat::SignedInt); // the size in bytes of the audio samples for a single RTP packet const int packetSize = (format.frequency() * format.channels() * (format.sampleSize() / 8)) * channel->payloadType().ptime() / 1000; // initialise audio output QAudioOutput *audioOutput = new QAudioOutput(format, this); audioOutput->setBufferSize(2 * packetSize); audioOutput->start(channel); // initialise audio input QAudioInput *audioInput = new QAudioInput(format, this); audioInput->setBufferSize(2 * packetSize); audioInput->start(channel); } /// A call finished. void xmppClient::slotFinished() { qDebug() << "Call finished"; } /// A presence was received. void xmppClient::slotPresenceReceived(const QXmppPresence &presence) { const QLatin1String recipient("qxmpp.test2@gmail.com"); // if we are the recipient, or if the presence is not from the recipient, // do nothing if (jidToBareJid(configuration().jid()) == recipient || jidToBareJid(presence.from()) != recipient || presence.type() != QXmppPresence::Available) return; // start the call and connect to the its signals QXmppCall *call = callManager->call(presence.from()); bool check = connect(call, SIGNAL(connected()), this, SLOT(slotConnected())); Q_ASSERT(check); check = connect(call, SIGNAL(finished()), this, SLOT(slotFinished())); Q_ASSERT(check); } <commit_msg>change the default buffer size in call handling example<commit_after>/* * Copyright (C) 2008-2011 The QXmpp developers * * Authors: * Ian Reinhart Geiser * Jeremy Lainé * * Source: * http://code.google.com/p/qxmpp * * This file is a part of QXmpp library. * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * */ #include <QAudioInput> #include <QAudioOutput> #include <QDebug> #include "QXmppCallManager.h" #include "QXmppJingleIq.h" #include "QXmppRtpChannel.h" #include "QXmppUtils.h" #include "xmppClient.h" xmppClient::xmppClient(QObject *parent) : QXmppClient(parent) { // add QXmppCallManager extension callManager = new QXmppCallManager; addExtension(callManager); bool check = connect(this, SIGNAL(presenceReceived(QXmppPresence)), this, SLOT(slotPresenceReceived(QXmppPresence))); Q_ASSERT(check); check = connect(callManager, SIGNAL(callReceived(QXmppCall*)), this, SLOT(slotCallReceived(QXmppCall*))); Q_ASSERT(check); } /// A call was received. void xmppClient::slotCallReceived(QXmppCall *call) { qDebug() << "Got call from:" << call->jid(); bool check = connect(call, SIGNAL(connected()), this, SLOT(slotConnected())); Q_ASSERT(check); check = connect(call, SIGNAL(finished()), this, SLOT(slotFinished())); Q_ASSERT(check); // accept call call->accept(); } /// A call connected. void xmppClient::slotConnected() { QXmppCall *call = qobject_cast<QXmppCall*>(sender()); Q_ASSERT(call); qDebug() << "Call connected"; QXmppRtpChannel *channel = call->audioChannel(); // prepare audio format QAudioFormat format; format.setFrequency(channel->payloadType().clockrate()); format.setChannels(channel->payloadType().channels()); format.setSampleSize(16); format.setCodec("audio/pcm"); format.setByteOrder(QAudioFormat::LittleEndian); format.setSampleType(QAudioFormat::SignedInt); // the size in bytes of the audio buffers to/from sound devices // 160 ms seems to be the minimum to work consistently on Linux/Mac/Windows const int bufferSize = (format.frequency() * format.channels() * (format.sampleSize() / 8) * 160) / 1000; // initialise audio output QAudioOutput *audioOutput = new QAudioOutput(format, this); audioOutput->setBufferSize(bufferSize); audioOutput->start(channel); // initialise audio input QAudioInput *audioInput = new QAudioInput(format, this); audioInput->setBufferSize(bufferSize); audioInput->start(channel); } /// A call finished. void xmppClient::slotFinished() { qDebug() << "Call finished"; } /// A presence was received. void xmppClient::slotPresenceReceived(const QXmppPresence &presence) { const QLatin1String recipient("qxmpp.test2@gmail.com"); // if we are the recipient, or if the presence is not from the recipient, // do nothing if (jidToBareJid(configuration().jid()) == recipient || jidToBareJid(presence.from()) != recipient || presence.type() != QXmppPresence::Available) return; // start the call and connect to the its signals QXmppCall *call = callManager->call(presence.from()); bool check = connect(call, SIGNAL(connected()), this, SLOT(slotConnected())); Q_ASSERT(check); check = connect(call, SIGNAL(finished()), this, SLOT(slotFinished())); Q_ASSERT(check); } <|endoftext|>
<commit_before>/************************************************************************* * * OpenOffice.org - a multi-platform office productivity suite * * $RCSfile: DataFmtTransl.cxx,v $ * * $Revision: 1.21 $ * * last change: $Author: obo $ $Date: 2006-09-17 17:00:27 $ * * The Contents of this file are made available subject to * the terms of GNU Lesser General Public License Version 2.1. * * * GNU Lesser General Public License Version 2.1 * ============================================= * Copyright 2005 by Sun Microsystems, Inc. * 901 San Antonio Road, Palo Alto, CA 94303, USA * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License version 2.1, as published by the Free Software Foundation. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, * MA 02111-1307 USA * ************************************************************************/ // MARKER(update_precomp.py): autogen include statement, do not remove #include "precompiled_dtrans.hxx" //------------------------------------------------------------------------ // includes //------------------------------------------------------------------------ #ifndef _DATAFMTTRANSL_HXX_ #include "DataFmtTransl.hxx" #endif #ifndef _RTL_STRING_HXX_ #include <rtl/string.hxx> #endif #ifndef _OSL_DIAGNOSE_H_ #include <osl/diagnose.h> #endif #ifndef _RTL_TENCINFO_H #include <rtl/tencinfo.h> #endif #ifndef _IMPLHELPER_HXX_ #include "..\misc\ImplHelper.hxx" #endif #ifndef _WINCLIP_HXX_ #include "..\misc\WinClip.hxx" #endif #ifndef _MIMEATTRIB_HXX_ #include "MimeAttrib.hxx" #endif #ifndef _DTRANSHELPER_HXX_ #include "DTransHelper.hxx" #endif #ifndef _RTL_STRING_H_ #include <rtl/string.h> #endif #ifndef _FETC_HXX_ #include "Fetc.hxx" #endif #if defined _MSC_VER #pragma warning(push,1) #pragma warning(disable:4917) #endif #include <windows.h> #if (_MSC_VER < 1300) #include <olestd.h> #endif #include <shlobj.h> #if defined _MSC_VER #pragma warning(pop) #endif //------------------------------------------------------------------------ // namespace directives //------------------------------------------------------------------------ using namespace rtl; using namespace std; using namespace com::sun::star::uno; using namespace com::sun::star::datatransfer; using namespace com::sun::star::lang; //------------------------------------------------------------------------ // const //------------------------------------------------------------------------ const Type CPPUTYPE_SALINT32 = getCppuType((sal_Int32*)0); const Type CPPUTYPE_SALINT8 = getCppuType((sal_Int8*)0); const Type CPPUTYPE_OUSTRING = getCppuType((OUString*)0); const Type CPPUTYPE_SEQSALINT8 = getCppuType((Sequence< sal_Int8>*)0); const sal_Int32 MAX_CLIPFORMAT_NAME = 256; const OUString TEXT_PLAIN_CHARSET = OUString::createFromAscii( "text/plain;charset=" ); const OUString HPNAME_OEM_ANSI_TEXT = OUString::createFromAscii( "OEM/ANSI Text" ); const OUString HTML_FORMAT_NAME_WINDOWS = OUString::createFromAscii( "HTML Format" ); const OUString HTML_FORMAT_NAME_SOFFICE = OUString::createFromAscii( "HTML (HyperText Markup Language)" ); //------------------------------------------------------------------------ // //------------------------------------------------------------------------ CDataFormatTranslator::CDataFormatTranslator( const Reference< XMultiServiceFactory >& aServiceManager ) : m_SrvMgr( aServiceManager ) { m_XDataFormatTranslator = Reference< XDataFormatTranslator >( m_SrvMgr->createInstance( OUString::createFromAscii( "com.sun.star.datatransfer.DataFormatTranslator" ) ), UNO_QUERY ); } //------------------------------------------------------------------------ // //------------------------------------------------------------------------ CFormatEtc CDataFormatTranslator::getFormatEtcFromDataFlavor( const DataFlavor& aDataFlavor ) const { sal_Int32 cf = CF_INVALID; try { if( m_XDataFormatTranslator.is( ) ) { Any aFormat = m_XDataFormatTranslator->getSystemDataTypeFromDataFlavor( aDataFlavor ); if ( aFormat.hasValue( ) ) { if ( aFormat.getValueType( ) == CPPUTYPE_SALINT32 ) { aFormat >>= cf; OSL_ENSURE( CF_INVALID != cf, "Invalid Clipboard format delivered" ); } else if ( aFormat.getValueType( ) == CPPUTYPE_OUSTRING ) { OUString aClipFmtName; aFormat >>= aClipFmtName; OSL_ASSERT( aClipFmtName.getLength( ) ); cf = RegisterClipboardFormatW( aClipFmtName.getStr( ) ); OSL_ENSURE( CF_INVALID != cf, "RegisterClipboardFormat failed" ); } else OSL_ENSURE( sal_False, "Wrong Any-Type detected" ); } } } catch( ... ) { OSL_ENSURE( sal_False, "Unexpected error" ); } return sal::static_int_cast<CFormatEtc>(getFormatEtcForClipformat( sal::static_int_cast<CLIPFORMAT>(cf) )); } //------------------------------------------------------------------------ // //------------------------------------------------------------------------ DataFlavor CDataFormatTranslator::getDataFlavorFromFormatEtc( const FORMATETC& aFormatEtc, LCID lcid ) const { DataFlavor aFlavor; try { CLIPFORMAT aClipformat = aFormatEtc.cfFormat; Any aAny; aAny <<= static_cast< sal_Int32 >( aClipformat ); if ( isOemOrAnsiTextFormat( aClipformat ) ) { aFlavor.MimeType = TEXT_PLAIN_CHARSET; aFlavor.MimeType += getTextCharsetFromLCID( lcid, aClipformat ); aFlavor.HumanPresentableName = HPNAME_OEM_ANSI_TEXT; aFlavor.DataType = CPPUTYPE_SEQSALINT8; } else if ( CF_INVALID != aClipformat ) { if ( m_XDataFormatTranslator.is( ) ) { aFlavor = m_XDataFormatTranslator->getDataFlavorFromSystemDataType( aAny ); if ( !aFlavor.MimeType.getLength( ) ) { // lookup of DataFlavor from clipboard format id // failed, so we try to resolve via clipboard // format name OUString clipFormatName = getClipboardFormatName( aClipformat ); // if we could not get a clipboard format name an // error must have occured or it is a standard // clipboard format that we don't translate, e.g. // CF_BITMAP (the office only uses CF_DIB) if ( clipFormatName.getLength( ) ) { aAny <<= clipFormatName; aFlavor = m_XDataFormatTranslator->getDataFlavorFromSystemDataType( aAny ); } } } } } catch( ... ) { OSL_ENSURE( sal_False, "Unexpected error" ); } return aFlavor; } //------------------------------------------------------------------------ // //------------------------------------------------------------------------ CFormatEtc SAL_CALL CDataFormatTranslator::getFormatEtcForClipformatName( const OUString& aClipFmtName ) const { // check parameter if ( !aClipFmtName.getLength( ) ) return CFormatEtc( CF_INVALID ); CLIPFORMAT cf = sal::static_int_cast<CLIPFORMAT>(RegisterClipboardFormatW( aClipFmtName.getStr( ) )); return getFormatEtcForClipformat( cf ); } //------------------------------------------------------------------------ // //------------------------------------------------------------------------ OUString CDataFormatTranslator::getClipboardFormatName( CLIPFORMAT aClipformat ) const { OSL_PRECOND( CF_INVALID != aClipformat, "Invalid clipboard format" ); sal_Unicode wBuff[ MAX_CLIPFORMAT_NAME ]; sal_Int32 nLen = GetClipboardFormatNameW( aClipformat, wBuff, MAX_CLIPFORMAT_NAME ); return OUString( wBuff, nLen ); } //------------------------------------------------------------------------ // //------------------------------------------------------------------------ CFormatEtc SAL_CALL CDataFormatTranslator::getFormatEtcForClipformat( CLIPFORMAT cf ) const { CFormatEtc fetc( cf, TYMED_NULL, NULL, DVASPECT_CONTENT ); switch( cf ) { case CF_METAFILEPICT: fetc.setTymed( TYMED_MFPICT ); break; case CF_ENHMETAFILE: fetc.setTymed( TYMED_ENHMF ); break; default: fetc.setTymed( TYMED_HGLOBAL /*| TYMED_ISTREAM*/ ); } /* hack: in order to paste urls copied by Internet Explorer with "copy link" we set the lindex member to 0 but if we really want to support CFSTR_FILECONTENT and the accompany format CFSTR_FILEDESCRIPTOR (FileGroupDescriptor) the client of the clipboard service has to provide a id of which FileContents it wants to paste see MSDN: "Handling Shell Data Transfer Scenarios" */ if ( cf == RegisterClipboardFormatA( CFSTR_FILECONTENTS ) ) fetc.setLindex( 0 ); return fetc; } //------------------------------------------------------------------------ // //------------------------------------------------------------------------ sal_Bool SAL_CALL CDataFormatTranslator::isOemOrAnsiTextFormat( CLIPFORMAT cf ) const { return ( (cf == CF_TEXT) || (cf == CF_OEMTEXT) ); } //------------------------------------------------------------------------ // //------------------------------------------------------------------------ sal_Bool SAL_CALL CDataFormatTranslator::isUnicodeTextFormat( CLIPFORMAT cf ) const { return ( cf == CF_UNICODETEXT ); } //------------------------------------------------------------------------ // //------------------------------------------------------------------------ sal_Bool SAL_CALL CDataFormatTranslator::isTextFormat( CLIPFORMAT cf ) const { return ( isOemOrAnsiTextFormat( cf ) || isUnicodeTextFormat( cf ) ); } //------------------------------------------------------------------------ // //------------------------------------------------------------------------ sal_Bool SAL_CALL CDataFormatTranslator::isHTMLFormat( CLIPFORMAT cf ) const { OUString clipFormatName = getClipboardFormatName( cf ); return ( clipFormatName == HTML_FORMAT_NAME_WINDOWS ); } //------------------------------------------------------------------------ // //------------------------------------------------------------------------ sal_Bool SAL_CALL CDataFormatTranslator::isTextHtmlFormat( CLIPFORMAT cf ) const { OUString clipFormatName = getClipboardFormatName( cf ); return ( clipFormatName.equalsIgnoreAsciiCase( HTML_FORMAT_NAME_SOFFICE ) ); } //------------------------------------------------------------------------ // //------------------------------------------------------------------------ OUString SAL_CALL CDataFormatTranslator::getTextCharsetFromLCID( LCID lcid, CLIPFORMAT aClipformat ) const { OSL_ASSERT( isOemOrAnsiTextFormat( aClipformat ) ); OUString charset; if ( CF_TEXT == aClipformat ) { charset = getMimeCharsetFromLocaleId( lcid, LOCALE_IDEFAULTANSICODEPAGE, PRE_WINDOWS_CODEPAGE ); } else if ( CF_OEMTEXT == aClipformat ) { charset = getMimeCharsetFromLocaleId( lcid, LOCALE_IDEFAULTCODEPAGE, PRE_OEM_CODEPAGE ); } else // CF_UNICODE OSL_ASSERT( sal_False ); return charset; } <commit_msg>INTEGRATION: CWS mingwport03 (1.20.16); FILE MERGED 2006/11/08 09:43:08 vg 1.20.16.2: RESYNC: (1.20-1.21); FILE MERGED 2006/09/21 16:12:05 vg 1.20.16.1: #i53572# MinGW port<commit_after>/************************************************************************* * * OpenOffice.org - a multi-platform office productivity suite * * $RCSfile: DataFmtTransl.cxx,v $ * * $Revision: 1.22 $ * * last change: $Author: vg $ $Date: 2007-03-26 15:07:10 $ * * The Contents of this file are made available subject to * the terms of GNU Lesser General Public License Version 2.1. * * * GNU Lesser General Public License Version 2.1 * ============================================= * Copyright 2005 by Sun Microsystems, Inc. * 901 San Antonio Road, Palo Alto, CA 94303, USA * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License version 2.1, as published by the Free Software Foundation. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, * MA 02111-1307 USA * ************************************************************************/ // MARKER(update_precomp.py): autogen include statement, do not remove #include "precompiled_dtrans.hxx" //------------------------------------------------------------------------ // includes //------------------------------------------------------------------------ #ifndef _DATAFMTTRANSL_HXX_ #include "DataFmtTransl.hxx" #endif #ifndef _RTL_STRING_HXX_ #include <rtl/string.hxx> #endif #ifndef _OSL_DIAGNOSE_H_ #include <osl/diagnose.h> #endif #ifndef _RTL_TENCINFO_H #include <rtl/tencinfo.h> #endif #ifndef _IMPLHELPER_HXX_ #include "..\misc\ImplHelper.hxx" #endif #ifndef _WINCLIP_HXX_ #include "..\misc\WinClip.hxx" #endif #ifndef _MIMEATTRIB_HXX_ #include "MimeAttrib.hxx" #endif #ifndef _DTRANSHELPER_HXX_ #include "DTransHelper.hxx" #endif #ifndef _RTL_STRING_H_ #include <rtl/string.h> #endif #ifndef _FETC_HXX_ #include "Fetc.hxx" #endif #if defined _MSC_VER #pragma warning(push,1) #pragma warning(disable:4917) #endif #include <windows.h> #if (_MSC_VER < 1300) && !defined(__MINGW32__) #include <olestd.h> #endif #include <shlobj.h> #if defined _MSC_VER #pragma warning(pop) #endif //------------------------------------------------------------------------ // namespace directives //------------------------------------------------------------------------ using namespace rtl; using namespace std; using namespace com::sun::star::uno; using namespace com::sun::star::datatransfer; using namespace com::sun::star::lang; //------------------------------------------------------------------------ // const //------------------------------------------------------------------------ const Type CPPUTYPE_SALINT32 = getCppuType((sal_Int32*)0); const Type CPPUTYPE_SALINT8 = getCppuType((sal_Int8*)0); const Type CPPUTYPE_OUSTRING = getCppuType((OUString*)0); const Type CPPUTYPE_SEQSALINT8 = getCppuType((Sequence< sal_Int8>*)0); const sal_Int32 MAX_CLIPFORMAT_NAME = 256; const OUString TEXT_PLAIN_CHARSET = OUString::createFromAscii( "text/plain;charset=" ); const OUString HPNAME_OEM_ANSI_TEXT = OUString::createFromAscii( "OEM/ANSI Text" ); const OUString HTML_FORMAT_NAME_WINDOWS = OUString::createFromAscii( "HTML Format" ); const OUString HTML_FORMAT_NAME_SOFFICE = OUString::createFromAscii( "HTML (HyperText Markup Language)" ); //------------------------------------------------------------------------ // //------------------------------------------------------------------------ CDataFormatTranslator::CDataFormatTranslator( const Reference< XMultiServiceFactory >& aServiceManager ) : m_SrvMgr( aServiceManager ) { m_XDataFormatTranslator = Reference< XDataFormatTranslator >( m_SrvMgr->createInstance( OUString::createFromAscii( "com.sun.star.datatransfer.DataFormatTranslator" ) ), UNO_QUERY ); } //------------------------------------------------------------------------ // //------------------------------------------------------------------------ CFormatEtc CDataFormatTranslator::getFormatEtcFromDataFlavor( const DataFlavor& aDataFlavor ) const { sal_Int32 cf = CF_INVALID; try { if( m_XDataFormatTranslator.is( ) ) { Any aFormat = m_XDataFormatTranslator->getSystemDataTypeFromDataFlavor( aDataFlavor ); if ( aFormat.hasValue( ) ) { if ( aFormat.getValueType( ) == CPPUTYPE_SALINT32 ) { aFormat >>= cf; OSL_ENSURE( CF_INVALID != cf, "Invalid Clipboard format delivered" ); } else if ( aFormat.getValueType( ) == CPPUTYPE_OUSTRING ) { OUString aClipFmtName; aFormat >>= aClipFmtName; OSL_ASSERT( aClipFmtName.getLength( ) ); cf = RegisterClipboardFormatW( reinterpret_cast<LPCWSTR>(aClipFmtName.getStr( )) ); OSL_ENSURE( CF_INVALID != cf, "RegisterClipboardFormat failed" ); } else OSL_ENSURE( sal_False, "Wrong Any-Type detected" ); } } } catch( ... ) { OSL_ENSURE( sal_False, "Unexpected error" ); } return sal::static_int_cast<CFormatEtc>(getFormatEtcForClipformat( sal::static_int_cast<CLIPFORMAT>(cf) )); } //------------------------------------------------------------------------ // //------------------------------------------------------------------------ DataFlavor CDataFormatTranslator::getDataFlavorFromFormatEtc( const FORMATETC& aFormatEtc, LCID lcid ) const { DataFlavor aFlavor; try { CLIPFORMAT aClipformat = aFormatEtc.cfFormat; Any aAny; aAny <<= static_cast< sal_Int32 >( aClipformat ); if ( isOemOrAnsiTextFormat( aClipformat ) ) { aFlavor.MimeType = TEXT_PLAIN_CHARSET; aFlavor.MimeType += getTextCharsetFromLCID( lcid, aClipformat ); aFlavor.HumanPresentableName = HPNAME_OEM_ANSI_TEXT; aFlavor.DataType = CPPUTYPE_SEQSALINT8; } else if ( CF_INVALID != aClipformat ) { if ( m_XDataFormatTranslator.is( ) ) { aFlavor = m_XDataFormatTranslator->getDataFlavorFromSystemDataType( aAny ); if ( !aFlavor.MimeType.getLength( ) ) { // lookup of DataFlavor from clipboard format id // failed, so we try to resolve via clipboard // format name OUString clipFormatName = getClipboardFormatName( aClipformat ); // if we could not get a clipboard format name an // error must have occured or it is a standard // clipboard format that we don't translate, e.g. // CF_BITMAP (the office only uses CF_DIB) if ( clipFormatName.getLength( ) ) { aAny <<= clipFormatName; aFlavor = m_XDataFormatTranslator->getDataFlavorFromSystemDataType( aAny ); } } } } } catch( ... ) { OSL_ENSURE( sal_False, "Unexpected error" ); } return aFlavor; } //------------------------------------------------------------------------ // //------------------------------------------------------------------------ CFormatEtc SAL_CALL CDataFormatTranslator::getFormatEtcForClipformatName( const OUString& aClipFmtName ) const { // check parameter if ( !aClipFmtName.getLength( ) ) return CFormatEtc( CF_INVALID ); CLIPFORMAT cf = sal::static_int_cast<CLIPFORMAT>(RegisterClipboardFormatW( reinterpret_cast<LPCWSTR>(aClipFmtName.getStr( )) )); return getFormatEtcForClipformat( cf ); } //------------------------------------------------------------------------ // //------------------------------------------------------------------------ OUString CDataFormatTranslator::getClipboardFormatName( CLIPFORMAT aClipformat ) const { OSL_PRECOND( CF_INVALID != aClipformat, "Invalid clipboard format" ); sal_Unicode wBuff[ MAX_CLIPFORMAT_NAME ]; sal_Int32 nLen = GetClipboardFormatNameW( aClipformat, reinterpret_cast<LPWSTR>(wBuff), MAX_CLIPFORMAT_NAME ); return OUString( wBuff, nLen ); } //------------------------------------------------------------------------ // //------------------------------------------------------------------------ CFormatEtc SAL_CALL CDataFormatTranslator::getFormatEtcForClipformat( CLIPFORMAT cf ) const { CFormatEtc fetc( cf, TYMED_NULL, NULL, DVASPECT_CONTENT ); switch( cf ) { case CF_METAFILEPICT: fetc.setTymed( TYMED_MFPICT ); break; case CF_ENHMETAFILE: fetc.setTymed( TYMED_ENHMF ); break; default: fetc.setTymed( TYMED_HGLOBAL /*| TYMED_ISTREAM*/ ); } /* hack: in order to paste urls copied by Internet Explorer with "copy link" we set the lindex member to 0 but if we really want to support CFSTR_FILECONTENT and the accompany format CFSTR_FILEDESCRIPTOR (FileGroupDescriptor) the client of the clipboard service has to provide a id of which FileContents it wants to paste see MSDN: "Handling Shell Data Transfer Scenarios" */ if ( cf == RegisterClipboardFormatA( CFSTR_FILECONTENTS ) ) fetc.setLindex( 0 ); return fetc; } //------------------------------------------------------------------------ // //------------------------------------------------------------------------ sal_Bool SAL_CALL CDataFormatTranslator::isOemOrAnsiTextFormat( CLIPFORMAT cf ) const { return ( (cf == CF_TEXT) || (cf == CF_OEMTEXT) ); } //------------------------------------------------------------------------ // //------------------------------------------------------------------------ sal_Bool SAL_CALL CDataFormatTranslator::isUnicodeTextFormat( CLIPFORMAT cf ) const { return ( cf == CF_UNICODETEXT ); } //------------------------------------------------------------------------ // //------------------------------------------------------------------------ sal_Bool SAL_CALL CDataFormatTranslator::isTextFormat( CLIPFORMAT cf ) const { return ( isOemOrAnsiTextFormat( cf ) || isUnicodeTextFormat( cf ) ); } //------------------------------------------------------------------------ // //------------------------------------------------------------------------ sal_Bool SAL_CALL CDataFormatTranslator::isHTMLFormat( CLIPFORMAT cf ) const { OUString clipFormatName = getClipboardFormatName( cf ); return ( clipFormatName == HTML_FORMAT_NAME_WINDOWS ); } //------------------------------------------------------------------------ // //------------------------------------------------------------------------ sal_Bool SAL_CALL CDataFormatTranslator::isTextHtmlFormat( CLIPFORMAT cf ) const { OUString clipFormatName = getClipboardFormatName( cf ); return ( clipFormatName.equalsIgnoreAsciiCase( HTML_FORMAT_NAME_SOFFICE ) ); } //------------------------------------------------------------------------ // //------------------------------------------------------------------------ OUString SAL_CALL CDataFormatTranslator::getTextCharsetFromLCID( LCID lcid, CLIPFORMAT aClipformat ) const { OSL_ASSERT( isOemOrAnsiTextFormat( aClipformat ) ); OUString charset; if ( CF_TEXT == aClipformat ) { charset = getMimeCharsetFromLocaleId( lcid, LOCALE_IDEFAULTANSICODEPAGE, PRE_WINDOWS_CODEPAGE ); } else if ( CF_OEMTEXT == aClipformat ) { charset = getMimeCharsetFromLocaleId( lcid, LOCALE_IDEFAULTCODEPAGE, PRE_OEM_CODEPAGE ); } else // CF_UNICODE OSL_ASSERT( sal_False ); return charset; } <|endoftext|>
<commit_before>// This file is part of the dune-hdd project: // http://users.dune-project.org/projects/dune-hdd // Copyright holders: Felix Schindler // License: BSD 2-Clause License (http://opensource.org/licenses/BSD-2-Clause) #ifndef DUNE_HDD_LINEARELLIPTIC_TESTCASES_OS2015_HH #define DUNE_HDD_LINEARELLIPTIC_TESTCASES_OS2015_HH #include <algorithm> #include <cmath> #include <map> #include <dune/stuff/common/disable_warnings.hh> # if HAVE_ALUGRID # include <dune/grid/alugrid.hh> # endif #include <dune/stuff/common/reenable_warnings.hh> #include <dune/stuff/functions/constant.hh> #include <dune/pymor/functions/default.hh> #include <dune/hdd/linearelliptic/problems/OS2015.hh> #include "base.hh" namespace Dune { namespace HDD { namespace LinearElliptic { namespace TestCases { namespace OS2015 { namespace internal { template< class GridType > class ParametricConvergenceBase { static_assert(GridType::dimension == 2, "This test case is only available in 2d!"); public: typedef typename GridType::template Codim< 0 >::Entity EntityType; typedef typename GridType::ctype DomainFieldType; static const unsigned int dimDomain = GridType::dimension; typedef double RangeFieldType; static const unsigned int dimRange = 1; public: typedef Problems::OS2015::ParametricESV2007 < EntityType, DomainFieldType, dimDomain, RangeFieldType, dimRange > ProblemType; typedef Stuff::Functions::Constant < EntityType, DomainFieldType, dimDomain, RangeFieldType, dimRange > ExactSolutionType; typedef typename ProblemType::FunctionType::NonparametricType FunctionType; typedef std::map< std::string, Pymor::ParameterType > ParameterTypesMapType; typedef std::map< std::string, Pymor::Parameter > ParametersMapType; protected: static const size_t default_num_refinements_ = 3; static int initial_refinements() { int ret = 1; #if HAVE_ALUGRID if (std::is_same< GridType, ALUConformGrid< 2, 2 > >::value || std::is_same< GridType, ALUGrid< 2, 2, simplex, conforming > >::value) ret += 1; #endif // HAVE_ALUGRID return ret; } // ... initial_refinements() static ParametersMapType add_parameter_range(const ParametersMapType& parameters) { ParametersMapType ret = parameters; ret["parameter_range_min"] = Pymor::Parameter("mu", 0.1); ret["parameter_range_max"] = Pymor::Parameter("mu", 1.0); return ret; } // ... add_parameter_range(...) public: static ParameterTypesMapType required_parameters() { return ParameterTypesMapType({{"mu", Pymor::ParameterType("mu", 1)}, {"mu_bar", Pymor::ParameterType("mu", 1)}, {"mu_hat", Pymor::ParameterType("mu", 1)}}); } ParametricConvergenceBase(const ParametersMapType& parameters) : parameters_(add_parameter_range(parameters)) , boundary_info_cfg_(Stuff::Grid::BoundaryInfoConfigs::AllDirichlet::default_config()) , problem_(3) , exact_solution_(0) {} void print_header(std::ostream& out = std::cout) const { out << "+==========================================================+\n" << "|+========================================================+|\n" << "|| Testcase OS2014: (parametric) ESV2007 ||\n" << "|| (see Ohlberger, Schindler, 2014) ||\n" << "|+--------------------------------------------------------+|\n" << "|| domain = [-1, 1] x [-1, 1] ||\n" << "|| diffusion = 1 + (1 - mu) cos(1/2 pi x) cos(1/2 pi y) ||\n" << "|| force = 1/2 pi^2 cos(1/2 pi x) cos(1/2 pi y) ||\n" << "|| dirichlet = 0 ||\n" << "|| reference solution: discrete solution on finest grid ||\n" << "|| parameter: mu in [0.1, 1] ||\n" << "|+========================================================+|\n" << "+==========================================================+" << std::endl; } // ... print_header(...) const Stuff::Common::Configuration& boundary_info() const { return boundary_info_cfg_; } const ProblemType& problem() const { return problem_; } bool provides_exact_solution() const { return false; } const ExactSolutionType& exact_solution() const { DUNE_THROW(Stuff::Exceptions::you_are_using_this_wrong, "Do not call exact_solution() if provides_exact_solution() is false!"); } const ParametersMapType& parameters() const { return parameters_; } protected: const ParametersMapType parameters_; const Stuff::Common::Configuration boundary_info_cfg_; const ProblemType problem_; const ExactSolutionType exact_solution_; }; // class ParametricConvergenceBase } // namespace internal #if HAVE_DUNE_GRID_MULTISCALE template< class GridType > class Academic : public internal::ParametricConvergenceBase< GridType > , public MultiscaleCubeBase< GridType > { typedef internal::ParametricConvergenceBase< GridType > ParametricConvergenceBaseType; typedef MultiscaleCubeBase< GridType > TestCaseBaseType; static Stuff::Common::Configuration initial_grid_cfg(const std::string num_partitions, const size_t oversampling_layers) { Stuff::Common::Configuration grid_cfg = Stuff::Grid::Providers::Cube< GridType >::default_config(); grid_cfg["lower_left"] = "-1"; grid_cfg["upper_right"] = "1"; grid_cfg["num_elements"] = "4"; grid_cfg["num_partitions"] = num_partitions; grid_cfg.set("oversampling_layers", oversampling_layers, /*overwrite=*/true); return grid_cfg; } // ... initial_grid_cfg(...) public: typedef typename TestCaseBaseType::ParametersMapType ParametersMapType; using ParametricConvergenceBaseType::required_parameters; using ParametricConvergenceBaseType::parameters; Academic(const ParametersMapType parameters, const std::string num_partitions = "[1 1 1]", const size_t num_refinements = ParametricConvergenceBaseType::default_num_refinements_, const size_t oversampling_layers = 0, const bool H_with_h = false) : ParametricConvergenceBaseType(parameters) , TestCaseBaseType(initial_grid_cfg(num_partitions, oversampling_layers), ParametricConvergenceBaseType::initial_refinements(), num_refinements, H_with_h) { this->check_parameters(ParametricConvergenceBaseType::required_parameters(), parameters); this->inherit_parameter_type(this->problem_, "problem"); } }; // class Academic #endif // HAVE_DUNE_GRID_MULTISCALE } // namespace OS2015 } // namespace TestCases } // namespace LinearElliptic } // namespace HDD } // namespace Dune #endif // DUNE_HDD_LINEARELLIPTIC_TESTCASES_OS2015_HH <commit_msg>[linearelliptic...OS2015] minor updates to academic testcase<commit_after>// This file is part of the dune-hdd project: // http://users.dune-project.org/projects/dune-hdd // Copyright holders: Felix Schindler // License: BSD 2-Clause License (http://opensource.org/licenses/BSD-2-Clause) #ifndef DUNE_HDD_LINEARELLIPTIC_TESTCASES_OS2015_HH #define DUNE_HDD_LINEARELLIPTIC_TESTCASES_OS2015_HH #include <algorithm> #include <cmath> #include <map> #include <dune/stuff/common/disable_warnings.hh> # if HAVE_ALUGRID # include <dune/grid/alugrid.hh> # endif #include <dune/stuff/common/reenable_warnings.hh> #include <dune/stuff/functions/constant.hh> #include <dune/pymor/functions/default.hh> #include <dune/hdd/linearelliptic/problems/OS2015.hh> #include "base.hh" namespace Dune { namespace HDD { namespace LinearElliptic { namespace TestCases { namespace OS2015 { namespace internal { template< class GridType > class AcademicBase { static_assert(GridType::dimension == 2, "This test case is only available in 2d!"); public: typedef typename GridType::template Codim< 0 >::Entity EntityType; typedef typename GridType::ctype DomainFieldType; static const unsigned int dimDomain = GridType::dimension; typedef double RangeFieldType; static const unsigned int dimRange = 1; public: typedef Problems::OS2015::ParametricESV2007 < EntityType, DomainFieldType, dimDomain, RangeFieldType, dimRange > ProblemType; typedef Stuff::Functions::Constant < EntityType, DomainFieldType, dimDomain, RangeFieldType, dimRange > ExactSolutionType; typedef typename ProblemType::FunctionType::NonparametricType FunctionType; typedef std::map< std::string, Pymor::ParameterType > ParameterTypesMapType; typedef std::map< std::string, Pymor::Parameter > ParametersMapType; protected: static const size_t default_num_refinements_ = 3; static int initial_refinements() { int ret = 1; #if HAVE_ALUGRID if (std::is_same< GridType, ALUConformGrid< 2, 2 > >::value || std::is_same< GridType, ALUGrid< 2, 2, simplex, conforming > >::value) ret += 1; #endif // HAVE_ALUGRID return ret; } // ... initial_refinements() static ParametersMapType add_parameter_range(const ParametersMapType& parameters) { ParametersMapType ret = parameters; ret["parameter_range_min"] = Pymor::Parameter("mu", 0.1); ret["parameter_range_max"] = Pymor::Parameter("mu", 1.0); return ret; } // ... add_parameter_range(...) public: static ParameterTypesMapType required_parameters() { return ParameterTypesMapType({{"mu", Pymor::ParameterType("mu", 1)}, {"mu_bar", Pymor::ParameterType("mu", 1)}, {"mu_hat", Pymor::ParameterType("mu", 1)}}); } AcademicBase(const ParametersMapType& parameters) : parameters_(add_parameter_range(parameters)) , boundary_info_cfg_(Stuff::Grid::BoundaryInfoConfigs::AllDirichlet::default_config()) , problem_(3) , exact_solution_(0) {} void print_header(std::ostream& out = std::cout) const { out << "+==========================================================+\n" << "|+========================================================+|\n" << "|| Testcase OS2015: (parametric) ESV2007 ||\n" << "|| (see Ohlberger, Schindler, 2016, sec. 6) ||\n" << "|+--------------------------------------------------------+|\n" << "|| domain = [-1, 1] x [-1, 1] ||\n" << "|| diffusion = 1 + (1 - mu) cos(1/2 pi x) cos(1/2 pi y) ||\n" << "|| force = 1/2 pi^2 cos(1/2 pi x) cos(1/2 pi y) ||\n" << "|| dirichlet = 0 ||\n" << "|| reference solution: discrete solution on finest grid ||\n" << "|| parameter: mu in [0.1, 1] ||\n" << "|+========================================================+|\n" << "+==========================================================+" << std::endl; } // ... print_header(...) const Stuff::Common::Configuration& boundary_info() const { return boundary_info_cfg_; } const ProblemType& problem() const { return problem_; } bool provides_exact_solution() const { return false; } const ExactSolutionType& exact_solution() const { DUNE_THROW(Stuff::Exceptions::you_are_using_this_wrong, "Do not call exact_solution() if provides_exact_solution() is false!"); } const ParametersMapType& parameters() const { return parameters_; } protected: const ParametersMapType parameters_; const Stuff::Common::Configuration boundary_info_cfg_; const ProblemType problem_; const ExactSolutionType exact_solution_; }; // class AcademicBase } // namespace internal #if HAVE_DUNE_GRID_MULTISCALE template< class GridType > class Academic : public internal::AcademicBase< GridType > , public MultiscaleCubeBase< GridType > { typedef internal::AcademicBase< GridType > AcademicBaseType; typedef MultiscaleCubeBase< GridType > TestCaseBaseType; static Stuff::Common::Configuration initial_grid_cfg(const std::string num_partitions, const size_t oversampling_layers) { Stuff::Common::Configuration grid_cfg = Stuff::Grid::Providers::Cube< GridType >::default_config(); grid_cfg["lower_left"] = "-1"; grid_cfg["upper_right"] = "1"; grid_cfg["num_elements"] = "4"; grid_cfg["num_partitions"] = num_partitions; grid_cfg.set("oversampling_layers", oversampling_layers, /*overwrite=*/true); return grid_cfg; } // ... initial_grid_cfg(...) public: typedef typename TestCaseBaseType::ParametersMapType ParametersMapType; using AcademicBaseType::required_parameters; using AcademicBaseType::parameters; Academic(const ParametersMapType parameters, const std::string num_partitions = "[1 1 1]", const size_t num_refinements = AcademicBaseType::default_num_refinements_, const size_t oversampling_layers = 0, const bool H_with_h = false) : AcademicBaseType(parameters) , TestCaseBaseType(initial_grid_cfg(num_partitions, oversampling_layers), AcademicBaseType::initial_refinements(), num_refinements, H_with_h) { this->check_parameters(AcademicBaseType::required_parameters(), parameters); this->inherit_parameter_type(this->problem_, "problem"); } }; // class Academic #endif // HAVE_DUNE_GRID_MULTISCALE } // namespace OS2015 } // namespace TestCases } // namespace LinearElliptic } // namespace HDD } // namespace Dune #endif // DUNE_HDD_LINEARELLIPTIC_TESTCASES_OS2015_HH <|endoftext|>
<commit_before>// This file is part of the dune-stuff project: // https://github.com/wwu-numerik/dune-stuff // Copyright holders: Rene Milk, Felix Schindler // License: BSD 2-Clause License (http://opensource.org/licenses/BSD-2-Clause) #include "config.h" #include <boost/numeric/conversion/cast.hpp> #include "threadmanager.hh" #include <dune/stuff/common/configuration.hh> #include <dune/common/exceptions.hh> #include <dune/stuff/fem/namespace.hh> #if HAVE_DUNE_FEM # include <dune/fem/misc/threads/threadmanager.hh> #endif #if HAVE_EIGEN # include <Eigen/Core> #endif #if HAVE_TBB #include <tbb/compat/thread> size_t Dune::Stuff::ThreadManager::max_threads() { const auto threads = DSC_CONFIG_GET("threading.max_count", 1); WITH_DUNE_FEM(assert(Dune::Fem::ThreadManager::maxThreads() == threads);) return threads; } size_t Dune::Stuff::ThreadManager::current_threads() { const auto threads = max_threads(); WITH_DUNE_FEM(assert(long(Dune::Fem::ThreadManager::currentThreads()) == long(threads));) return threads; } size_t Dune::Stuff::ThreadManager::thread() { const auto tbb_id = tbb::this_tbb_thread::get_id(); static std::map<decltype(tbb_id), size_t> thread_ids; const auto it = thread_ids.find(tbb_id); if (it==thread_ids.end()) thread_ids.emplace(tbb_id, thread_ids.size()); return thread_ids.at(tbb_id); } void Dune::Stuff::ThreadManager::set_max_threads(const size_t count) { max_threads_ = count; WITH_DUNE_FEM(Dune::Fem::ThreadManager::setMaxNumberThreads(count);) #if HAVE_EIGEN Eigen::setNbThreads(boost::numeric_cast< int >(count)); #endif tbb_init_->terminate(); tbb_init_->initialize(boost::numeric_cast< int >(count)); } Dune::Stuff::ThreadManager::ThreadManager() : max_threads_(1) , tbb_init_(nullptr) { #if HAVE_EIGEN // must be called before tbb threads are created via tbb::task_scheduler_init object ctor Eigen::initParallel(); Eigen::setNbThreads(1); #endif tbb_init_ = Common::make_unique<tbb::task_scheduler_init>(boost::numeric_cast< int >(max_threads_)); set_max_threads(std::thread::hardware_concurrency()); } #else // if HAVE_TBB size_t Dune::Stuff::ThreadManager::max_threads() { return 1; } size_t Dune::Stuff::ThreadManager::current_threads() { return 1; } size_t Dune::Stuff::ThreadManager::thread() { return 1; } void Dune::Stuff::ThreadManager::set_max_threads(const size_t count) { if (count > 1) DUNE_THROW(InvalidStateException, "Trying to use more than one thread w/o TBB"); } Dune::Stuff::ThreadManager::ThreadManager() : max_threads_(1) {} #endif // HAVE_DUNE_FEM <commit_msg>[common.parallel.threadmanger] update include, refs #37<commit_after>// This file is part of the dune-stuff project: // https://github.com/wwu-numerik/dune-stuff // Copyright holders: Rene Milk, Felix Schindler // License: BSD 2-Clause License (http://opensource.org/licenses/BSD-2-Clause) #include "config.h" #include <boost/numeric/conversion/cast.hpp> #include "threadmanager.hh" #include <dune/stuff/common/configuration.hh> #include <dune/common/exceptions.hh> #include <dune/stuff/fem.hh> #if HAVE_DUNE_FEM # include <dune/fem/misc/threads/threadmanager.hh> #endif #if HAVE_EIGEN # include <Eigen/Core> #endif #if HAVE_TBB #include <tbb/compat/thread> size_t Dune::Stuff::ThreadManager::max_threads() { const auto threads = DSC_CONFIG_GET("threading.max_count", 1); WITH_DUNE_FEM(assert(Dune::Fem::ThreadManager::maxThreads() == threads);) return threads; } size_t Dune::Stuff::ThreadManager::current_threads() { const auto threads = max_threads(); WITH_DUNE_FEM(assert(long(Dune::Fem::ThreadManager::currentThreads()) == long(threads));) return threads; } size_t Dune::Stuff::ThreadManager::thread() { const auto tbb_id = tbb::this_tbb_thread::get_id(); static std::map<decltype(tbb_id), size_t> thread_ids; const auto it = thread_ids.find(tbb_id); if (it==thread_ids.end()) thread_ids.emplace(tbb_id, thread_ids.size()); return thread_ids.at(tbb_id); } void Dune::Stuff::ThreadManager::set_max_threads(const size_t count) { max_threads_ = count; WITH_DUNE_FEM(Dune::Fem::ThreadManager::setMaxNumberThreads(count);) #if HAVE_EIGEN Eigen::setNbThreads(boost::numeric_cast< int >(count)); #endif tbb_init_->terminate(); tbb_init_->initialize(boost::numeric_cast< int >(count)); } Dune::Stuff::ThreadManager::ThreadManager() : max_threads_(1) , tbb_init_(nullptr) { #if HAVE_EIGEN // must be called before tbb threads are created via tbb::task_scheduler_init object ctor Eigen::initParallel(); Eigen::setNbThreads(1); #endif tbb_init_ = Common::make_unique<tbb::task_scheduler_init>(boost::numeric_cast< int >(max_threads_)); set_max_threads(std::thread::hardware_concurrency()); } #else // if HAVE_TBB size_t Dune::Stuff::ThreadManager::max_threads() { return 1; } size_t Dune::Stuff::ThreadManager::current_threads() { return 1; } size_t Dune::Stuff::ThreadManager::thread() { return 1; } void Dune::Stuff::ThreadManager::set_max_threads(const size_t count) { if (count > 1) DUNE_THROW(InvalidStateException, "Trying to use more than one thread w/o TBB"); } Dune::Stuff::ThreadManager::ThreadManager() : max_threads_(1) {} #endif // HAVE_DUNE_FEM <|endoftext|>
<commit_before>/************************************************************************* * * $RCSfile: contentidentifier.hxx,v $ * * $Revision: 1.3 $ * * last change: $Author: vg $ $Date: 2005-02-16 15:44:27 $ * * The Contents of this file are made available subject to the terms of * either of the following licenses * * - GNU Lesser General Public License Version 2.1 * - Sun Industry Standards Source License Version 1.1 * * Sun Microsystems Inc., October, 2000 * * GNU Lesser General Public License Version 2.1 * ============================================= * Copyright 2000 by Sun Microsystems, Inc. * 901 San Antonio Road, Palo Alto, CA 94303, USA * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License version 2.1, as published by the Free Software Foundation. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, * MA 02111-1307 USA * * * Sun Industry Standards Source License Version 1.1 * ================================================= * The contents of this file are subject to the Sun Industry Standards * Source License Version 1.1 (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.openoffice.org/license.html. * * Software provided under this License is provided on an "AS IS" basis, * WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, * WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS, * MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING. * See the License for the specific provisions governing your rights and * obligations concerning the Software. * * The Initial Developer of the Original Code is: Sun Microsystems, Inc. * * Copyright: 2000 by Sun Microsystems, Inc. * * All Rights Reserved. * * Contributor(s): _______________________________________ * * ************************************************************************/ #ifndef _UCBHELPER_CONTENTIDENTIFIER_HXX #define _UCBHELPER_CONTENTIDENTIFIER_HXX #ifndef _CPPUHELPER_WEAK_HXX_ #include <cppuhelper/weak.hxx> #endif #ifndef _COM_SUN_STAR_LANG_XTYPEPROVIDER_HPP_ #include <com/sun/star/lang/XTypeProvider.hpp> #endif #ifndef _COM_SUN_STAR_UCB_XCONTENTIDENTIFIER_HPP_ #include <com/sun/star/ucb/XContentIdentifier.hpp> #endif #ifndef INCLUDED_UCBHELPERDLLAPI_H #include "ucbhelper/ucbhelperdllapi.h" #endif namespace com { namespace sun { namespace star { namespace lang { class XMultiServiceFactory; } } } } namespace rtl { class OUString; } namespace ucb { struct ContentIdentifier_Impl; //========================================================================= /** * This class implements a simple identifier object for UCB contents. * It mainly stores and returns the URL as it was passed to the constructor - * The only difference is that the URL scheme will be lower cased. This can * be done, because URL schemes are never case sensitive. */ class UCBHELPER_DLLPUBLIC ContentIdentifier : public cppu::OWeakObject, public com::sun::star::lang::XTypeProvider, public com::sun::star::ucb::XContentIdentifier { public: ContentIdentifier( const com::sun::star::uno::Reference< com::sun::star::lang::XMultiServiceFactory >& rxSMgr, const rtl::OUString& rURL ); ContentIdentifier( const rtl::OUString& rURL ); virtual ~ContentIdentifier(); // XInterface virtual com::sun::star::uno::Any SAL_CALL queryInterface( const com::sun::star::uno::Type & rType ) throw( com::sun::star::uno::RuntimeException ); virtual void SAL_CALL acquire() throw(); virtual void SAL_CALL release() throw(); // XTypeProvider virtual com::sun::star::uno::Sequence< sal_Int8 > SAL_CALL getImplementationId() throw( com::sun::star::uno::RuntimeException ); virtual com::sun::star::uno::Sequence< com::sun::star::uno::Type > SAL_CALL getTypes() throw( com::sun::star::uno::RuntimeException ); // XContentIdentifier virtual rtl::OUString SAL_CALL getContentIdentifier() throw( com::sun::star::uno::RuntimeException ); virtual rtl::OUString SAL_CALL getContentProviderScheme() throw( com::sun::star::uno::RuntimeException ); private: ContentIdentifier_Impl* m_pImpl; }; } /* namespace ucb */ #endif /* !_UCBHELPER_CONTENTIDENTIFIER_HXX */ <commit_msg>INTEGRATION: CWS ooo19126 (1.3.14); FILE MERGED 2005/09/05 13:13:44 rt 1.3.14.1: #i54170# Change license header: remove SISSL<commit_after>/************************************************************************* * * OpenOffice.org - a multi-platform office productivity suite * * $RCSfile: contentidentifier.hxx,v $ * * $Revision: 1.4 $ * * last change: $Author: rt $ $Date: 2005-09-09 16:27:32 $ * * The Contents of this file are made available subject to * the terms of GNU Lesser General Public License Version 2.1. * * * GNU Lesser General Public License Version 2.1 * ============================================= * Copyright 2005 by Sun Microsystems, Inc. * 901 San Antonio Road, Palo Alto, CA 94303, USA * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License version 2.1, as published by the Free Software Foundation. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, * MA 02111-1307 USA * ************************************************************************/ #ifndef _UCBHELPER_CONTENTIDENTIFIER_HXX #define _UCBHELPER_CONTENTIDENTIFIER_HXX #ifndef _CPPUHELPER_WEAK_HXX_ #include <cppuhelper/weak.hxx> #endif #ifndef _COM_SUN_STAR_LANG_XTYPEPROVIDER_HPP_ #include <com/sun/star/lang/XTypeProvider.hpp> #endif #ifndef _COM_SUN_STAR_UCB_XCONTENTIDENTIFIER_HPP_ #include <com/sun/star/ucb/XContentIdentifier.hpp> #endif #ifndef INCLUDED_UCBHELPERDLLAPI_H #include "ucbhelper/ucbhelperdllapi.h" #endif namespace com { namespace sun { namespace star { namespace lang { class XMultiServiceFactory; } } } } namespace rtl { class OUString; } namespace ucb { struct ContentIdentifier_Impl; //========================================================================= /** * This class implements a simple identifier object for UCB contents. * It mainly stores and returns the URL as it was passed to the constructor - * The only difference is that the URL scheme will be lower cased. This can * be done, because URL schemes are never case sensitive. */ class UCBHELPER_DLLPUBLIC ContentIdentifier : public cppu::OWeakObject, public com::sun::star::lang::XTypeProvider, public com::sun::star::ucb::XContentIdentifier { public: ContentIdentifier( const com::sun::star::uno::Reference< com::sun::star::lang::XMultiServiceFactory >& rxSMgr, const rtl::OUString& rURL ); ContentIdentifier( const rtl::OUString& rURL ); virtual ~ContentIdentifier(); // XInterface virtual com::sun::star::uno::Any SAL_CALL queryInterface( const com::sun::star::uno::Type & rType ) throw( com::sun::star::uno::RuntimeException ); virtual void SAL_CALL acquire() throw(); virtual void SAL_CALL release() throw(); // XTypeProvider virtual com::sun::star::uno::Sequence< sal_Int8 > SAL_CALL getImplementationId() throw( com::sun::star::uno::RuntimeException ); virtual com::sun::star::uno::Sequence< com::sun::star::uno::Type > SAL_CALL getTypes() throw( com::sun::star::uno::RuntimeException ); // XContentIdentifier virtual rtl::OUString SAL_CALL getContentIdentifier() throw( com::sun::star::uno::RuntimeException ); virtual rtl::OUString SAL_CALL getContentProviderScheme() throw( com::sun::star::uno::RuntimeException ); private: ContentIdentifier_Impl* m_pImpl; }; } /* namespace ucb */ #endif /* !_UCBHELPER_CONTENTIDENTIFIER_HXX */ <|endoftext|>