url
stringlengths
12
221
text
stringlengths
176
1.03M
encoding
stringclasses
16 values
confidence
float64
0.7
1
license
stringlengths
0
347
copyright
stringlengths
3
31.8k
qtdeclarative-opensource-src-gles-5.15.2+dfsg/src/qml/jsruntime/qv4property_p.h
/**************************************************************************** ** ** Copyright (C) 2016 The Qt Company Ltd. ** Contact: https://www.qt.io/licensing/ ** ** This file is part of the QtQml module of the Qt Toolkit. ** ** $QT_BEGIN_LICENSE:LGPL$ ** Commercial License Usage ** Licensees holding valid commercial Qt licenses may use this file in ** accordance with the commercial license agreement provided with the ** Software or, alternatively, in accordance with the terms contained in ** a written agreement between you and The Qt Company. For licensing terms ** and conditions see https://www.qt.io/terms-conditions. For further ** information use the contact form at https://www.qt.io/contact-us. ** ** GNU Lesser General Public License Usage ** Alternatively, this file may be used under the terms of the GNU Lesser ** General Public License version 3 as published by the Free Software ** Foundation and appearing in the file LICENSE.LGPL3 included in the ** packaging of this file. Please review the following information to ** ensure the GNU Lesser General Public License version 3 requirements ** will be met: https://www.gnu.org/licenses/lgpl-3.0.html. ** ** GNU General Public License Usage ** Alternatively, this file may be used under the terms of the GNU ** General Public License version 2.0 or (at your option) the GNU General ** Public license version 3 or any later version approved by the KDE Free ** Qt Foundation. The licenses are as published by the Free Software ** Foundation and appearing in the file LICENSE.GPL2 and LICENSE.GPL3 ** included in the packaging of this file. Please review the following ** information to ensure the GNU General Public License requirements will ** be met: https://www.gnu.org/licenses/gpl-2.0.html and ** https://www.gnu.org/licenses/gpl-3.0.html. ** ** $QT_END_LICENSE$ ** ****************************************************************************/ #ifndef QV4PROPERTYDESCRIPTOR_H #define QV4PROPERTYDESCRIPTOR_H // // W A R N I N G // ------------- // // This file is not part of the Qt API. It exists purely as an // implementation detail. This header file may change from version to // version without notice, or even be removed. // // We mean it. // #include "qv4global_p.h" #include "qv4value_p.h" QT_BEGIN_NAMESPACE namespace QV4 { struct FunctionObject; struct Property { Value value; Value set; // Section 8.10 inline void fullyPopulated(PropertyAttributes *attrs) { if (!attrs->hasType()) { value = Value::undefinedValue(); } if (attrs->type() == PropertyAttributes::Accessor) { attrs->clearWritable(); if (value.isEmpty()) value = Value::undefinedValue(); if (set.isEmpty()) set = Value::undefinedValue(); } attrs->resolve(); } // ES8: 6.2.5.6 void completed(PropertyAttributes *attrs) { if (value.isEmpty()) value = Encode::undefined(); if (attrs->isGeneric() || attrs->isData()) { attrs->setType(PropertyAttributes::Data); if (!attrs->hasWritable()) attrs->setWritable(false); } else { if (set.isEmpty()) set = Encode::undefined(); } if (!attrs->hasEnumerable()) attrs->setEnumerable(false); if (!attrs->hasConfigurable()) attrs->setConfigurable(false); } inline bool isSubset(const PropertyAttributes &attrs, const Property *other, PropertyAttributes otherAttrs) const; inline void merge(PropertyAttributes &attrs, const Property *other, PropertyAttributes otherAttrs); inline Heap::FunctionObject *getter() const { return reinterpret_cast<Heap::FunctionObject *>(value.heapObject()); } inline Heap::FunctionObject *setter() const { return reinterpret_cast<Heap::FunctionObject *>(set.heapObject()); } inline void setGetter(FunctionObject *g) { value = reinterpret_cast<Managed *>(g); } inline void setSetter(FunctionObject *s) { set = (s ? reinterpret_cast<Managed *>(s) : nullptr); } void copy(const Property *other, PropertyAttributes attrs) { value = other->value; if (attrs.isAccessor()) set = other->set; } // ES8, section 9.1.6.2/9,.1.6.3 bool isCompatible(PropertyAttributes &attrs, const Property *other, PropertyAttributes otherAttrs) const { if (otherAttrs.isEmpty()) return true; if (!attrs.isConfigurable()) { if (otherAttrs.hasConfigurable() && otherAttrs.isConfigurable()) return false; if (otherAttrs.hasEnumerable() && otherAttrs.isEnumerable() != attrs.isEnumerable()) return false; } if (otherAttrs.isGeneric()) return true; if (attrs.isData() != otherAttrs.isData()) { if (!attrs.isConfigurable()) return false; } else if (attrs.isData() && otherAttrs.isData()) { if (!attrs.isConfigurable() && !attrs.isWritable()) { if (otherAttrs.hasWritable() && otherAttrs.isWritable()) return false; if (!other->value.isEmpty() && !value.sameValue(other->value)) return false; } } else if (attrs.isAccessor() && otherAttrs.isAccessor()) { if (!attrs.isConfigurable()) { if (!other->value.isEmpty() && !value.sameValue(other->value)) return false; if (!other->set.isEmpty() && !set.sameValue(other->set)) return false; } } return true; } explicit Property() { value = Encode::undefined(); set = Value::fromHeapObject(nullptr); } Property(Heap::FunctionObject *getter, Heap::FunctionObject *setter) { value.setM(reinterpret_cast<Heap::Base *>(getter)); set.setM(reinterpret_cast<Heap::Base *>(setter)); } private: Q_DISABLE_COPY(Property) }; inline bool Property::isSubset(const PropertyAttributes &attrs, const Property *other, PropertyAttributes otherAttrs) const { if (attrs.type() != PropertyAttributes::Generic && attrs.type() != otherAttrs.type()) return false; if (attrs.hasEnumerable() && attrs.isEnumerable() != otherAttrs.isEnumerable()) return false; if (attrs.hasConfigurable() && attrs.isConfigurable() != otherAttrs.isConfigurable()) return false; if (attrs.hasWritable() && attrs.isWritable() != otherAttrs.isWritable()) return false; if (attrs.type() == PropertyAttributes::Data && !value.sameValue(other->value)) return false; if (attrs.type() == PropertyAttributes::Accessor) { if (value.heapObject() != other->value.heapObject()) return false; if (set.heapObject() != other->set.heapObject()) return false; } return true; } inline void Property::merge(PropertyAttributes &attrs, const Property *other, PropertyAttributes otherAttrs) { if (otherAttrs.hasEnumerable()) attrs.setEnumerable(otherAttrs.isEnumerable()); if (otherAttrs.hasConfigurable()) attrs.setConfigurable(otherAttrs.isConfigurable()); if (otherAttrs.hasWritable()) attrs.setWritable(otherAttrs.isWritable()); if (otherAttrs.type() == PropertyAttributes::Accessor) { attrs.setType(PropertyAttributes::Accessor); if (!other->value.isEmpty()) value = other->value; if (!other->set.isEmpty()) set = other->set; } else if (otherAttrs.type() == PropertyAttributes::Data){ attrs.setType(PropertyAttributes::Data); value = other->value; } } struct PropertyIndex { Heap::Base *base; Value *slot; void set(EngineBase *e, Value newVal) { WriteBarrier::write(e, base, slot->data_ptr(), newVal.asReturnedValue()); } const Value *operator->() const { return slot; } const Value &operator*() const { return *slot; } bool isNull() const { return !slot; } }; } Q_DECLARE_TYPEINFO(QV4::Property, Q_MOVABLE_TYPE); QT_END_NAMESPACE #endif
utf-8
1
LGPL-3 or GPL-2+
2016-2020 The Qt Company Ltd.
log4cxx-0.12.1/src/test/cpp/filter/stringmatchfiltertest.cpp
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include <log4cxx/filter/stringmatchfilter.h> #include <log4cxx/logger.h> #include <log4cxx/spi/filter.h> #include <log4cxx/spi/loggingevent.h> #include "../logunit.h" using namespace log4cxx; using namespace log4cxx::filter; using namespace log4cxx::spi; using namespace log4cxx::helpers; /** * Unit tests for StringMatchFilter. */ LOGUNIT_CLASS(StringMatchFilterTest) { LOGUNIT_TEST_SUITE(StringMatchFilterTest); LOGUNIT_TEST(test1); LOGUNIT_TEST(test2); LOGUNIT_TEST(test3); LOGUNIT_TEST(test4); LOGUNIT_TEST_SUITE_END(); public: /** * Check that StringMatchFilter.decide() returns Filter.NEUTRAL * when string to match is unspecified. */ void test1() { LoggingEventPtr event(new LoggingEvent( LOG4CXX_STR("org.apache.log4j.filter.StringMatchFilterTest"), Level::getInfo(), LOG4CXX_STR("Hello, World"), LOG4CXX_LOCATION)); FilterPtr filter(new StringMatchFilter()); Pool p; filter->activateOptions(p); LOGUNIT_ASSERT_EQUAL(Filter::NEUTRAL, filter->decide(event)); } /** * Check that StringMatchFilter.decide() returns Filter.NEUTRAL * when string to match does not appear in message. */ void test2() { LoggingEventPtr event(new LoggingEvent( LOG4CXX_STR("org.apache.log4j.filter.StringMatchFilterTest"), Level::getInfo(), LOG4CXX_STR("Hello, World"), LOG4CXX_LOCATION)); StringMatchFilterPtr filter(new StringMatchFilter()); filter->setStringToMatch(LOG4CXX_STR("Monde")); Pool p; filter->activateOptions(p); LOGUNIT_ASSERT_EQUAL(Filter::NEUTRAL, filter->decide(event)); } /** * Check that StringMatchFilter.decide() returns Filter.ACCEPT * when string to match does appear in message. */ void test3() { LoggingEventPtr event(new LoggingEvent( LOG4CXX_STR("org.apache.log4j.filter.StringMatchFilterTest"), Level::getInfo(), LOG4CXX_STR("Hello, World"), LOG4CXX_LOCATION)); StringMatchFilterPtr filter(new StringMatchFilter()); filter->setStringToMatch(LOG4CXX_STR("World")); Pool p; filter->activateOptions(p); LOGUNIT_ASSERT_EQUAL(Filter::ACCEPT, filter->decide(event)); } /** * Check that StringMatchFilter.decide() returns Filter.DENY * when string to match does appear in message and * accept on match is false. */ void test4() { LoggingEventPtr event(new LoggingEvent( LOG4CXX_STR("org.apache.log4j.filter.StringMatchFilterTest"), Level::getInfo(), LOG4CXX_STR("Hello, World"), LOG4CXX_LOCATION)); StringMatchFilterPtr filter(new StringMatchFilter()); filter->setStringToMatch(LOG4CXX_STR("World")); filter->setAcceptOnMatch(false); Pool p; filter->activateOptions(p); LOGUNIT_ASSERT_EQUAL(Filter::DENY, filter->decide(event)); } /** * Check that StringMatchFilter.decide() returns Filter.NEUTRAL * when string to match does appear in message but differs in case. */ void test5() { LoggingEventPtr event(new LoggingEvent( LOG4CXX_STR("org.apache.log4j.filter.StringMatchFilterTest"), Level::getInfo(), LOG4CXX_STR("Hello, World"), LOG4CXX_LOCATION)); StringMatchFilterPtr filter(new StringMatchFilter()); filter->setStringToMatch(LOG4CXX_STR("world")); Pool p; filter->activateOptions(p); LOGUNIT_ASSERT_EQUAL(Filter::NEUTRAL, filter->decide(event)); } }; LOGUNIT_TEST_SUITE_REGISTRATION(StringMatchFilterTest);
utf-8
1
Apache-2.0
2004-2021 The Apache Software Foundation
zynaddsubfx-3.0.5/src/Misc/BankDb.cpp
#include "BankDb.h" #include "XMLwrapper.h" #include "Util.h" #include "../globals.h" #include <cstring> #include <dirent.h> #include <sys/stat.h> namespace zyn { static const char* INSTRUMENT_EXTENSION = ".xiz"; using std::string; typedef BankDb::svec svec; typedef BankDb::bvec bvec; BankEntry::BankEntry(void) :id(0), add(false), pad(false), sub(false), time(0) {} bool platform_strcasestr(const char *hay, const char *needle) { int n = strlen(hay); int m = strlen(needle); for(int i=0; i<n; i++) { int good = 1; for(int j=0; j<m; ++j) { if(toupper(hay[i+j]) != toupper(needle[j])) { good = 0; break; } } if(good) return 1; } return 0; } bool sfind(std::string hay, std::string needle) { //return strcasestr(hay.c_str(), needle.c_str()); return platform_strcasestr(hay.c_str(), needle.c_str()); return false; } bool BankEntry::match(string s) const { if(s == "#pad") return pad; else if(s == "#sub") return sub; else if(s == "#add") return add; return sfind(file,s) || sfind(name,s) || sfind(bank, s) || sfind(type, s) || sfind(comments,s) || sfind(author,s); } bool BankEntry::operator<(const BankEntry &b) const { return (this->bank+this->file) < (b.bank+b.file); } static svec split(string s) { svec vec; string ss; for(char c:s) { if(isspace(c) && !ss.empty()) { vec.push_back(ss); ss.clear(); } else if(!isspace(c)) { ss.push_back(c); } } if(!ss.empty()) vec.push_back(ss); return vec; } //static string line(string s) //{ // string ss; // for(char c:s) { // if(c != '\n') // ss.push_back(c); // else // return ss; // } // return ss; //} bvec BankDb::search(std::string ss) const { bvec vec; const svec sterm = split(ss); for(auto field:fields) { bool match = true; for(auto s:sterm) match &= field.match(s); if(match) vec.push_back(field); } std::sort(vec.begin(), vec.end()); return vec; } void BankDb::addBankDir(std::string bnk) { bool repeat = false; for(auto b:banks) repeat |= b == bnk; if(!repeat) banks.push_back(bnk); } void BankDb::clear(void) { banks.clear(); fields.clear(); } static std::string getCacheName(void) { char name[512] = {0}; snprintf(name, sizeof(name), "%s%s", getenv("HOME"), "/.zynaddsubfx-bank-cache.xml"); return name; } static bvec loadCache(void) { bvec cache; XMLwrapper xml; xml.loadXMLfile(getCacheName()); if(xml.enterbranch("bank-cache")) { auto nodes = xml.getBranch(); for(auto node:nodes) { BankEntry be; #define bind(x,y) if(node.has(#x)) {be.x = y(node[#x].c_str());} bind(file, string); bind(bank, string); bind(name, string); bind(comments, string); bind(author, string); bind(type, atoi); bind(id, atoi); bind(add, atoi); bind(pad, atoi); bind(sub, atoi); bind(time, atoi); #undef bind cache.push_back(be); } } return cache; } static void saveCache(bvec vec) { XMLwrapper xml; xml.beginbranch("bank-cache"); for(auto value:vec) { XmlNode binding("instrument-entry"); #define bind(x) binding[#x] = to_s(value.x); bind(file); bind(bank); bind(name); bind(comments); bind(author); bind(type); bind(id); bind(add); bind(pad); bind(sub); bind(time); #undef bind xml.add(binding); } xml.endbranch(); xml.saveXMLfile(getCacheName(), 0); } void BankDb::scanBanks(void) { fields.clear(); bvec cache = loadCache(); bmap cc; for(auto c:cache) cc[c.bank + c.file] = c; bvec ncache; for(auto bank:banks) { DIR *dir = opendir(bank.c_str()); if(!dir) continue; struct dirent *fn; while((fn = readdir(dir))) { const char *filename = fn->d_name; //check for extension if(!strstr(filename, INSTRUMENT_EXTENSION)) continue; auto xiz = processXiz(filename, bank, cc); fields.push_back(xiz); ncache.push_back(xiz); } closedir(dir); } saveCache(ncache); } BankEntry BankDb::processXiz(std::string filename, std::string bank, bmap &cache) const { string fname = bank+filename; //Grab a timestamp struct stat st; int time = 0; //gah windows, just implement the darn standard APIs #ifndef WIN32 int ret = lstat(fname.c_str(), &st); if(ret != -1) # ifdef __APPLE__ time = st.st_mtimespec.tv_sec; # else time = st.st_mtim.tv_sec; # endif #else int ret = 0; time = rand(); #endif //quickly check if the file exists in the cache and if it is up-to-date if(cache.find(fname) != cache.end() && cache[fname].time == time) return cache[fname]; //verify if the name is like this NNNN-name (where N is a digit) int no = 0; unsigned int startname = 0; for(unsigned int i = 0; i < 4; ++i) { if(filename.length() <= i) break; if(isdigit(filename[i])) { no = no * 10 + (filename[i] - '0'); startname++; } } if(startname + 1 < filename.length()) startname++; //to take out the "-" std::string name = filename; //remove the file extension for(int i = name.size() - 1; i >= 2; i--) { if(name[i] == '.') { name = name.substr(0, i); break; } } BankEntry entry; entry.file = filename; entry.bank = bank; entry.id = no; entry.time = time; if(no != 0) //the instrument position in the bank is found entry.name = name.substr(startname); else entry.name = name; const char *types[] = { "None", "Piano", "Chromatic Percussion", "Organ", "Guitar", "Bass", "Solo Strings", "Ensemble", "Brass", "Reed", "Pipe", "Synth Lead", "Synth Pad", "Synth Effects", "Ethnic", "Percussive", "Sound Effects", }; //Try to obtain other metadata (expensive) XMLwrapper xml; ret = xml.loadXMLfile(fname); if(xml.enterbranch("INSTRUMENT")) { if(xml.enterbranch("INFO")) { char author[1024]; char comments[1024]; int type = 0; xml.getparstr("author", author, 1024); xml.getparstr("comments", comments, 1024); type = xml.getpar("type", 0, 0, 16); entry.author = author; entry.comments = comments; entry.type = types[type]; xml.exitbranch(); } if(xml.enterbranch("INSTRUMENT_KIT")) { for(int i = 0; i < NUM_KIT_ITEMS; ++i) { if(xml.enterbranch("INSTRUMENT_KIT_ITEM", i) == 0) { entry.add |= xml.getparbool("add_enabled", false); entry.sub |= xml.getparbool("sub_enabled", false); entry.pad |= xml.getparbool("pad_enabled", false); xml.exitbranch(); } } xml.exitbranch(); } xml.exitbranch(); } //printf("Bank Entry:\n"); //printf("\tname - %s\n", entry.name.c_str()); //printf("\tauthor - %s\n", line(entry.author).c_str()); //printf("\tbank - %s\n", entry.bank.c_str()); //printf("\tadd/pad/sub - %d/%d/%d\n", entry.add, entry.pad, entry.sub); return entry; } }
utf-8
1
GPL-2+
2002-2009 Nasca Octavian Paul <zynaddsubfx@yahoo.com> 2006-2009 Lars Luthman 2009-2010 Ryan Billing 2009-2010 Mark McCurry 2009 Harald Hvaal
libtoxcore-0.2.13/toxcore/group.c
/* SPDX-License-Identifier: GPL-3.0-or-later * Copyright © 2016-2018 The TokTok team. * Copyright © 2014 Tox project. */ /* * Slightly better groupchats implementation. */ #ifdef HAVE_CONFIG_H #include "config.h" #endif #include "group.h" #include <assert.h> #include <stdlib.h> #include <string.h> #include "mono_time.h" #include "state.h" #include "util.h" /** * Packet type IDs as per the protocol specification. */ typedef enum Group_Message_Id { GROUP_MESSAGE_PING_ID = 0, GROUP_MESSAGE_NEW_PEER_ID = 16, GROUP_MESSAGE_KILL_PEER_ID = 17, GROUP_MESSAGE_FREEZE_PEER_ID = 18, GROUP_MESSAGE_NAME_ID = 48, GROUP_MESSAGE_TITLE_ID = 49, } Group_Message_Id; #define GROUP_MESSAGE_NEW_PEER_LENGTH (sizeof(uint16_t) + CRYPTO_PUBLIC_KEY_SIZE * 2) #define GROUP_MESSAGE_KILL_PEER_LENGTH (sizeof(uint16_t)) #define MAX_GROUP_MESSAGE_DATA_LEN (MAX_CRYPTO_DATA_SIZE - (1 + MIN_MESSAGE_PACKET_LEN)) typedef enum Invite_Id { INVITE_ID = 0, INVITE_ACCEPT_ID = 1, INVITE_MEMBER_ID = 2, } Invite_Id; #define INVITE_PACKET_SIZE (1 + sizeof(uint16_t) + 1 + GROUP_ID_LENGTH) #define INVITE_ACCEPT_PACKET_SIZE (1 + sizeof(uint16_t) * 2 + 1 + GROUP_ID_LENGTH) #define INVITE_MEMBER_PACKET_SIZE (1 + sizeof(uint16_t) * 2 + 1 + GROUP_ID_LENGTH + sizeof(uint16_t)) #define ONLINE_PACKET_DATA_SIZE (sizeof(uint16_t) + 1 + GROUP_ID_LENGTH) typedef enum Peer_Id { PEER_INTRODUCED_ID = 1, PEER_QUERY_ID = 8, PEER_RESPONSE_ID = 9, PEER_TITLE_ID = 10, } Peer_Id; #define MIN_MESSAGE_PACKET_LEN (sizeof(uint16_t) * 2 + sizeof(uint32_t) + 1) /* return false if the groupnumber is not valid. * return true if the groupnumber is valid. */ static bool is_groupnumber_valid(const Group_Chats *g_c, uint32_t groupnumber) { return groupnumber < g_c->num_chats && g_c->chats != nullptr && g_c->chats[groupnumber].status != GROUPCHAT_STATUS_NONE; } /* Set the size of the groupchat list to num. * * return false if realloc fails. * return true if it succeeds. */ static bool realloc_conferences(Group_Chats *g_c, uint16_t num) { if (num == 0) { free(g_c->chats); g_c->chats = nullptr; return true; } Group_c *newgroup_chats = (Group_c *)realloc(g_c->chats, num * sizeof(Group_c)); if (newgroup_chats == nullptr) { return false; } g_c->chats = newgroup_chats; return true; } static void setup_conference(Group_c *g) { memset(g, 0, sizeof(Group_c)); g->maxfrozen = MAX_FROZEN_DEFAULT; } /* Create a new empty groupchat connection. * * return -1 on failure. * return groupnumber on success. */ static int32_t create_group_chat(Group_Chats *g_c) { for (uint16_t i = 0; i < g_c->num_chats; ++i) { if (g_c->chats[i].status == GROUPCHAT_STATUS_NONE) { return i; } } if (realloc_conferences(g_c, g_c->num_chats + 1)) { uint16_t id = g_c->num_chats; ++g_c->num_chats; setup_conference(&g_c->chats[id]); return id; } return -1; } /* Wipe a groupchat. * * return true on success. */ static bool wipe_group_chat(Group_Chats *g_c, uint32_t groupnumber) { if (!is_groupnumber_valid(g_c, groupnumber)) { return false; } uint16_t i; crypto_memzero(&g_c->chats[groupnumber], sizeof(Group_c)); for (i = g_c->num_chats; i != 0; --i) { if (g_c->chats[i - 1].status != GROUPCHAT_STATUS_NONE) { break; } } if (g_c->num_chats != i) { g_c->num_chats = i; realloc_conferences(g_c, g_c->num_chats); } return true; } static Group_c *get_group_c(const Group_Chats *g_c, uint32_t groupnumber) { if (!is_groupnumber_valid(g_c, groupnumber)) { return nullptr; } return &g_c->chats[groupnumber]; } /* * check if peer with real_pk is in peer array. * * return peer index if peer is in group. * return -1 if peer is not in group. * * TODO(irungentoo): make this more efficient. */ static int peer_in_group(const Group_c *g, const uint8_t *real_pk) { for (uint32_t i = 0; i < g->numpeers; ++i) { if (id_equal(g->group[i].real_pk, real_pk)) { return i; } } return -1; } static int frozen_in_group(const Group_c *g, const uint8_t *real_pk) { for (uint32_t i = 0; i < g->numfrozen; ++i) { if (id_equal(g->frozen[i].real_pk, real_pk)) { return i; } } return -1; } /* * check if group with the given type and id is in group array. * * return group number if peer is in list. * return -1 if group is not in list. * * TODO(irungentoo): make this more efficient and maybe use constant time comparisons? */ static int32_t get_group_num(const Group_Chats *g_c, const uint8_t type, const uint8_t *id) { for (uint16_t i = 0; i < g_c->num_chats; ++i) { if (g_c->chats[i].type == type && crypto_memcmp(g_c->chats[i].id, id, GROUP_ID_LENGTH) == 0) { return i; } } return -1; } int32_t conference_by_id(const Group_Chats *g_c, const uint8_t *id) { for (uint16_t i = 0; i < g_c->num_chats; ++i) { if (crypto_memcmp(g_c->chats[i].id, id, GROUP_ID_LENGTH) == 0) { return i; } } return -1; } /* * check if peer with peer_number is in peer array. * * return peer index if peer is in chat. * return -1 if peer is not in chat. * * TODO(irungentoo): make this more efficient. */ static int get_peer_index(const Group_c *g, uint16_t peer_number) { for (uint32_t i = 0; i < g->numpeers; ++i) { if (g->group[i].peer_number == peer_number) { return i; } } return -1; } static uint64_t calculate_comp_value(const uint8_t *pk1, const uint8_t *pk2) { uint64_t cmp1 = 0; uint64_t cmp2 = 0; for (size_t i = 0; i < sizeof(uint64_t); ++i) { cmp1 = (cmp1 << 8) + (uint64_t)pk1[i]; cmp2 = (cmp2 << 8) + (uint64_t)pk2[i]; } return cmp1 - cmp2; } typedef enum Groupchat_Closest_Change { GROUPCHAT_CLOSEST_CHANGE_NONE, GROUPCHAT_CLOSEST_CHANGE_ADDED, GROUPCHAT_CLOSEST_CHANGE_REMOVED, } Groupchat_Closest_Change; static bool add_to_closest(Group_c *g, const uint8_t *real_pk, const uint8_t *temp_pk) { if (public_key_cmp(g->real_pk, real_pk) == 0) { return false; } unsigned int index = DESIRED_CLOSEST; for (unsigned int i = 0; i < DESIRED_CLOSEST; ++i) { if (g->closest_peers[i].entry && public_key_cmp(real_pk, g->closest_peers[i].real_pk) == 0) { return true; } } for (unsigned int i = 0; i < DESIRED_CLOSEST; ++i) { if (g->closest_peers[i].entry == 0) { index = i; break; } } if (index == DESIRED_CLOSEST) { uint64_t comp_val = calculate_comp_value(g->real_pk, real_pk); uint64_t comp_d = 0; for (unsigned int i = 0; i < (DESIRED_CLOSEST / 2); ++i) { uint64_t comp = calculate_comp_value(g->real_pk, g->closest_peers[i].real_pk); if (comp > comp_val && comp > comp_d) { index = i; comp_d = comp; } } comp_val = calculate_comp_value(real_pk, g->real_pk); for (unsigned int i = (DESIRED_CLOSEST / 2); i < DESIRED_CLOSEST; ++i) { uint64_t comp = calculate_comp_value(g->closest_peers[i].real_pk, g->real_pk); if (comp > comp_val && comp > comp_d) { index = i; comp_d = comp; } } } if (index == DESIRED_CLOSEST) { return false; } uint8_t old_real_pk[CRYPTO_PUBLIC_KEY_SIZE]; uint8_t old_temp_pk[CRYPTO_PUBLIC_KEY_SIZE]; uint8_t old = 0; if (g->closest_peers[index].entry) { memcpy(old_real_pk, g->closest_peers[index].real_pk, CRYPTO_PUBLIC_KEY_SIZE); memcpy(old_temp_pk, g->closest_peers[index].temp_pk, CRYPTO_PUBLIC_KEY_SIZE); old = 1; } g->closest_peers[index].entry = 1; memcpy(g->closest_peers[index].real_pk, real_pk, CRYPTO_PUBLIC_KEY_SIZE); memcpy(g->closest_peers[index].temp_pk, temp_pk, CRYPTO_PUBLIC_KEY_SIZE); if (old) { add_to_closest(g, old_real_pk, old_temp_pk); } if (!g->changed) { g->changed = GROUPCHAT_CLOSEST_CHANGE_ADDED; } return true; } static bool pk_in_closest_peers(const Group_c *g, uint8_t *real_pk) { for (unsigned int i = 0; i < DESIRED_CLOSEST; ++i) { if (!g->closest_peers[i].entry) { continue; } if (public_key_cmp(g->closest_peers[i].real_pk, real_pk) == 0) { return true; } } return false; } static void remove_connection_reason(Group_Chats *g_c, Group_c *g, uint16_t i, uint8_t reason); static void purge_closest(Group_Chats *g_c, uint32_t groupnumber) { Group_c *g = get_group_c(g_c, groupnumber); if (!g) { return; } for (uint32_t i = 0; i < MAX_GROUP_CONNECTIONS; ++i) { if (g->connections[i].type == GROUPCHAT_CONNECTION_NONE) { continue; } if (!(g->connections[i].reasons & GROUPCHAT_CONNECTION_REASON_CLOSEST)) { continue; } uint8_t real_pk[CRYPTO_PUBLIC_KEY_SIZE]; get_friendcon_public_keys(real_pk, nullptr, g_c->fr_c, g->connections[i].number); if (!pk_in_closest_peers(g, real_pk)) { remove_connection_reason(g_c, g, i, GROUPCHAT_CONNECTION_REASON_CLOSEST); } } } static int send_packet_online(Friend_Connections *fr_c, int friendcon_id, uint16_t group_num, uint8_t type, const uint8_t *id); static int add_conn_to_groupchat(Group_Chats *g_c, int friendcon_id, Group_c *g, uint8_t reason, uint8_t lock); static void add_closest_connections(Group_Chats *g_c, uint32_t groupnumber, void *userdata) { Group_c *g = get_group_c(g_c, groupnumber); if (!g) { return; } for (uint32_t i = 0; i < DESIRED_CLOSEST; ++i) { if (!g->closest_peers[i].entry) { continue; } int friendcon_id = getfriend_conn_id_pk(g_c->fr_c, g->closest_peers[i].real_pk); uint8_t fresh = 0; if (friendcon_id == -1) { friendcon_id = new_friend_connection(g_c->fr_c, g->closest_peers[i].real_pk); fresh = 1; if (friendcon_id == -1) { continue; } set_dht_temp_pk(g_c->fr_c, friendcon_id, g->closest_peers[i].temp_pk, userdata); } const int connection_index = add_conn_to_groupchat(g_c, friendcon_id, g, GROUPCHAT_CONNECTION_REASON_CLOSEST, !fresh); if (connection_index == -1) { if (fresh) { kill_friend_connection(g_c->fr_c, friendcon_id); } continue; } if (friend_con_connected(g_c->fr_c, friendcon_id) == FRIENDCONN_STATUS_CONNECTED && g->connections[connection_index].type == GROUPCHAT_CONNECTION_CONNECTING) { send_packet_online(g_c->fr_c, friendcon_id, groupnumber, g->type, g->id); } } } static bool connect_to_closest(Group_Chats *g_c, uint32_t groupnumber, void *userdata) { Group_c *g = get_group_c(g_c, groupnumber); if (!g) { return false; } if (!g->changed) { return true; } if (g->changed == GROUPCHAT_CLOSEST_CHANGE_REMOVED) { for (uint32_t i = 0; i < g->numpeers; ++i) { add_to_closest(g, g->group[i].real_pk, g->group[i].temp_pk); } } purge_closest(g_c, groupnumber); add_closest_connections(g_c, groupnumber, userdata); g->changed = GROUPCHAT_CLOSEST_CHANGE_NONE; return true; } static int get_frozen_index(const Group_c *g, uint16_t peer_number) { for (uint32_t i = 0; i < g->numfrozen; ++i) { if (g->frozen[i].peer_number == peer_number) { return i; } } return -1; } static bool delete_frozen(Group_c *g, uint32_t frozen_index) { if (frozen_index >= g->numfrozen) { return false; } --g->numfrozen; if (g->numfrozen == 0) { free(g->frozen); g->frozen = nullptr; } else { if (g->numfrozen != frozen_index) { g->frozen[frozen_index] = g->frozen[g->numfrozen]; } Group_Peer *const frozen_temp = (Group_Peer *)realloc(g->frozen, sizeof(Group_Peer) * (g->numfrozen)); if (frozen_temp == nullptr) { return false; } g->frozen = frozen_temp; } return true; } /* Update last_active timestamp on peer, and thaw the peer if it is frozen. * * return peer index if peer is in the conference. * return -1 otherwise, and on error. */ static int note_peer_active(Group_Chats *g_c, uint32_t groupnumber, uint16_t peer_number, void *userdata) { Group_c *g = get_group_c(g_c, groupnumber); if (!g) { return -1; } const int peer_index = get_peer_index(g, peer_number); if (peer_index != -1) { g->group[peer_index].last_active = mono_time_get(g_c->mono_time); return peer_index; } const int frozen_index = get_frozen_index(g, peer_number); if (frozen_index == -1) { return -1; } /* Now thaw the peer */ Group_Peer *temp = (Group_Peer *)realloc(g->group, sizeof(Group_Peer) * (g->numpeers + 1)); if (temp == nullptr) { return -1; } const uint32_t thawed_index = g->numpeers; g->group = temp; g->group[thawed_index] = g->frozen[frozen_index]; g->group[thawed_index].temp_pk_updated = false; g->group[thawed_index].last_active = mono_time_get(g_c->mono_time); add_to_closest(g, g->group[thawed_index].real_pk, g->group[thawed_index].temp_pk); ++g->numpeers; delete_frozen(g, frozen_index); if (g_c->peer_list_changed_callback) { g_c->peer_list_changed_callback(g_c->m, groupnumber, userdata); } if (g->peer_on_join) { g->peer_on_join(g->object, groupnumber, thawed_index); } g->need_send_name = true; return thawed_index; } static bool delpeer(Group_Chats *g_c, uint32_t groupnumber, int peer_index, void *userdata); static void delete_any_peer_with_pk(Group_Chats *g_c, uint32_t groupnumber, const uint8_t *real_pk, void *userdata) { Group_c *g = get_group_c(g_c, groupnumber); if (!g) { return; } const int peer_index = peer_in_group(g, real_pk); if (peer_index >= 0) { delpeer(g_c, groupnumber, peer_index, userdata); } const int frozen_index = frozen_in_group(g, real_pk); if (frozen_index >= 0) { delete_frozen(g, frozen_index); } } /* Add a peer to the group chat, or update an existing peer. * * fresh indicates whether we should consider this information on the peer to * be current, and so should update temp_pk and consider the peer active. * * do_gc_callback indicates whether we want to trigger callbacks set by the client * via the public API. This should be set to false if this function is called * from outside of the tox_iterate() loop. * * return peer_index if success or peer already in chat. * return -1 if error. */ static int addpeer(Group_Chats *g_c, uint32_t groupnumber, const uint8_t *real_pk, const uint8_t *temp_pk, uint16_t peer_number, void *userdata, bool fresh, bool do_gc_callback) { Group_c *g = get_group_c(g_c, groupnumber); if (!g) { return -1; } const int peer_index = fresh ? note_peer_active(g_c, groupnumber, peer_number, userdata) : get_peer_index(g, peer_number); if (peer_index != -1) { if (!id_equal(g->group[peer_index].real_pk, real_pk)) { return -1; } if (fresh || !g->group[peer_index].temp_pk_updated) { id_copy(g->group[peer_index].temp_pk, temp_pk); g->group[peer_index].temp_pk_updated = true; } return peer_index; } if (!fresh) { const int frozen_index = get_frozen_index(g, peer_number); if (frozen_index != -1) { if (!id_equal(g->frozen[frozen_index].real_pk, real_pk)) { return -1; } id_copy(g->frozen[frozen_index].temp_pk, temp_pk); return -1; } } delete_any_peer_with_pk(g_c, groupnumber, real_pk, userdata); Group_Peer *temp = (Group_Peer *)realloc(g->group, sizeof(Group_Peer) * (g->numpeers + 1)); if (temp == nullptr) { return -1; } memset(&temp[g->numpeers], 0, sizeof(Group_Peer)); g->group = temp; const uint32_t new_index = g->numpeers; id_copy(g->group[new_index].real_pk, real_pk); id_copy(g->group[new_index].temp_pk, temp_pk); g->group[new_index].temp_pk_updated = true; g->group[new_index].peer_number = peer_number; g->group[new_index].last_active = mono_time_get(g_c->mono_time); g->group[new_index].is_friend = (getfriend_id(g_c->m, real_pk) != -1); ++g->numpeers; add_to_closest(g, real_pk, temp_pk); if (do_gc_callback && g_c->peer_list_changed_callback) { g_c->peer_list_changed_callback(g_c->m, groupnumber, userdata); } if (g->peer_on_join) { g->peer_on_join(g->object, groupnumber, new_index); } return new_index; } static void remove_connection(Group_Chats *g_c, Group_c *g, uint16_t i) { if (g->connections[i].reasons & GROUPCHAT_CONNECTION_REASON_INTRODUCER) { --g->num_introducer_connections; } kill_friend_connection(g_c->fr_c, g->connections[i].number); g->connections[i].type = GROUPCHAT_CONNECTION_NONE; } static void remove_from_closest(Group_c *g, int peer_index) { for (uint32_t i = 0; i < DESIRED_CLOSEST; ++i) { if (g->closest_peers[i].entry && id_equal(g->closest_peers[i].real_pk, g->group[peer_index].real_pk)) { g->closest_peers[i].entry = 0; g->changed = GROUPCHAT_CLOSEST_CHANGE_REMOVED; break; } } } /* * Delete a peer from the group chat. * * return true on success */ static bool delpeer(Group_Chats *g_c, uint32_t groupnumber, int peer_index, void *userdata) { Group_c *g = get_group_c(g_c, groupnumber); if (!g) { return false; } remove_from_closest(g, peer_index); const int friendcon_id = getfriend_conn_id_pk(g_c->fr_c, g->group[peer_index].real_pk); if (friendcon_id != -1) { for (uint32_t i = 0; i < MAX_GROUP_CONNECTIONS; ++i) { if (g->connections[i].type == GROUPCHAT_CONNECTION_NONE) { continue; } if (g->connections[i].number == (unsigned int)friendcon_id) { remove_connection(g_c, g, i); break; } } } --g->numpeers; void *peer_object = g->group[peer_index].object; if (g->numpeers == 0) { free(g->group); g->group = nullptr; } else { if (g->numpeers != (uint32_t)peer_index) { g->group[peer_index] = g->group[g->numpeers]; } Group_Peer *temp = (Group_Peer *)realloc(g->group, sizeof(Group_Peer) * (g->numpeers)); if (temp == nullptr) { return false; } g->group = temp; } if (g_c->peer_list_changed_callback) { g_c->peer_list_changed_callback(g_c->m, groupnumber, userdata); } if (g->peer_on_leave) { g->peer_on_leave(g->object, groupnumber, peer_object); } return true; } static int cmp_u64(uint64_t a, uint64_t b) { return (a > b) - (a < b); } /* Order peers with friends first and with more recently active earlier */ static int cmp_frozen(const void *a, const void *b) { const Group_Peer *pa = (const Group_Peer *) a; const Group_Peer *pb = (const Group_Peer *) b; if (pa->is_friend ^ pb->is_friend) { return pa->is_friend ? -1 : 1; } return cmp_u64(pb->last_active, pa->last_active); } /* Delete frozen peers as necessary to ensure at most g->maxfrozen remain. * * return true if any frozen peers are removed. */ static bool delete_old_frozen(Group_c *g) { if (g->numfrozen <= g->maxfrozen) { return false; } if (g->maxfrozen == 0) { free(g->frozen); g->frozen = nullptr; g->numfrozen = 0; return true; } qsort(g->frozen, g->numfrozen, sizeof(Group_Peer), cmp_frozen); Group_Peer *temp = (Group_Peer *)realloc(g->frozen, sizeof(Group_Peer) * g->maxfrozen); if (temp == nullptr) { return false; } g->frozen = temp; g->numfrozen = g->maxfrozen; return true; } static bool try_send_rejoin(Group_Chats *g_c, Group_c *g, const uint8_t *real_pk); static bool freeze_peer(Group_Chats *g_c, uint32_t groupnumber, int peer_index, void *userdata) { Group_c *g = get_group_c(g_c, groupnumber); if (!g) { return false; } Group_Peer *temp = (Group_Peer *)realloc(g->frozen, sizeof(Group_Peer) * (g->numfrozen + 1)); if (temp == nullptr) { return false; } g->frozen = temp; g->frozen[g->numfrozen] = g->group[peer_index]; g->frozen[g->numfrozen].object = nullptr; if (!delpeer(g_c, groupnumber, peer_index, userdata)) { return false; } try_send_rejoin(g_c, g, g->frozen[g->numfrozen].real_pk); ++g->numfrozen; delete_old_frozen(g); return true; } /* Set the nick for a peer. * * do_gc_callback indicates whether we want to trigger callbacks set by the client * via the public API. This should be set to false if this function is called * from outside of the tox_iterate() loop. * * return true on success. */ static bool setnick(Group_Chats *g_c, uint32_t groupnumber, int peer_index, const uint8_t *nick, uint16_t nick_len, void *userdata, bool do_gc_callback) { if (nick_len > MAX_NAME_LENGTH) { return false; } Group_c *g = get_group_c(g_c, groupnumber); if (!g) { return false; } g->group[peer_index].nick_updated = true; if (g->group[peer_index].nick_len == nick_len && (nick_len == 0 || !memcmp(g->group[peer_index].nick, nick, nick_len))) { /* same name as already stored */ return true; } if (nick_len) { memcpy(g->group[peer_index].nick, nick, nick_len); } g->group[peer_index].nick_len = nick_len; if (do_gc_callback && g_c->peer_name_callback) { g_c->peer_name_callback(g_c->m, groupnumber, peer_index, nick, nick_len, userdata); } return true; } /* Set the title for a group. * * return true on success. */ static bool settitle(Group_Chats *g_c, uint32_t groupnumber, int peer_index, const uint8_t *title, uint8_t title_len, void *userdata) { if (title_len > MAX_NAME_LENGTH || title_len == 0) { return false; } Group_c *g = get_group_c(g_c, groupnumber); if (!g) { return false; } if (g->title_len == title_len && !memcmp(g->title, title, title_len)) { /* same title as already set */ return true; } memcpy(g->title, title, title_len); g->title_len = title_len; g->title_fresh = true; if (g_c->title_callback) { g_c->title_callback(g_c->m, groupnumber, peer_index, title, title_len, userdata); } return true; } /* Check if the group has no online connection, and freeze all peers if so */ static void check_disconnected(Group_Chats *g_c, uint32_t groupnumber, void *userdata) { Group_c *g = get_group_c(g_c, groupnumber); if (!g) { return; } for (uint32_t i = 0; i < MAX_GROUP_CONNECTIONS; ++i) { if (g->connections[i].type == GROUPCHAT_CONNECTION_ONLINE) { return; } } for (uint32_t i = 0; i < g->numpeers; ++i) { while (i < g->numpeers && !id_equal(g->group[i].real_pk, g->real_pk)) { freeze_peer(g_c, groupnumber, i, userdata); } } } static void set_conns_type_connections(Group_Chats *g_c, uint32_t groupnumber, int friendcon_id, uint8_t type, void *userdata) { Group_c *g = get_group_c(g_c, groupnumber); if (!g) { return; } for (uint32_t i = 0; i < MAX_GROUP_CONNECTIONS; ++i) { if (g->connections[i].type == GROUPCHAT_CONNECTION_NONE) { continue; } if (g->connections[i].number != (unsigned int)friendcon_id) { continue; } if (type == GROUPCHAT_CONNECTION_ONLINE) { send_packet_online(g_c->fr_c, friendcon_id, groupnumber, g->type, g->id); } else { g->connections[i].type = type; check_disconnected(g_c, groupnumber, userdata); } } } /* Set the type for all connections with friendcon_id */ static void set_conns_status_groups(Group_Chats *g_c, int friendcon_id, uint8_t type, void *userdata) { for (uint16_t i = 0; i < g_c->num_chats; ++i) { set_conns_type_connections(g_c, i, friendcon_id, type, userdata); } } static void rejoin_frozen_friend(Group_Chats *g_c, int friendcon_id) { uint8_t real_pk[CRYPTO_PUBLIC_KEY_SIZE]; get_friendcon_public_keys(real_pk, nullptr, g_c->fr_c, friendcon_id); for (uint16_t i = 0; i < g_c->num_chats; ++i) { Group_c *g = get_group_c(g_c, i); if (!g) { continue; } for (uint32_t j = 0; j < g->numfrozen; ++j) { if (id_equal(g->frozen[j].real_pk, real_pk)) { try_send_rejoin(g_c, g, real_pk); break; } } } } static int g_handle_any_status(void *object, int friendcon_id, uint8_t status, void *userdata) { Group_Chats *g_c = (Group_Chats *)object; if (status) { rejoin_frozen_friend(g_c, friendcon_id); } return 0; } static int g_handle_status(void *object, int friendcon_id, uint8_t status, void *userdata) { Group_Chats *g_c = (Group_Chats *)object; if (status) { /* Went online */ set_conns_status_groups(g_c, friendcon_id, GROUPCHAT_CONNECTION_ONLINE, userdata); } else { /* Went offline */ set_conns_status_groups(g_c, friendcon_id, GROUPCHAT_CONNECTION_CONNECTING, userdata); // TODO(irungentoo): remove timedout connections? } return 0; } static int g_handle_packet(void *object, int friendcon_id, const uint8_t *data, uint16_t length, void *userdata); static int handle_lossy(void *object, int friendcon_id, const uint8_t *data, uint16_t length, void *userdata); /* Add friend to group chat. * * return connections index on success * return -1 on failure. */ static int add_conn_to_groupchat(Group_Chats *g_c, int friendcon_id, Group_c *g, uint8_t reason, uint8_t lock) { uint16_t empty = MAX_GROUP_CONNECTIONS; uint16_t ind = MAX_GROUP_CONNECTIONS; for (uint16_t i = 0; i < MAX_GROUP_CONNECTIONS; ++i) { if (g->connections[i].type == GROUPCHAT_CONNECTION_NONE) { empty = i; continue; } if (g->connections[i].number == (uint32_t)friendcon_id) { ind = i; /* Already in list. */ break; } } if (ind == MAX_GROUP_CONNECTIONS) { if (empty == MAX_GROUP_CONNECTIONS) { return -1; } if (lock) { friend_connection_lock(g_c->fr_c, friendcon_id); } g->connections[empty].type = GROUPCHAT_CONNECTION_CONNECTING; g->connections[empty].number = friendcon_id; g->connections[empty].reasons = 0; // TODO(irungentoo): friend_connection_callbacks(g_c->m->fr_c, friendcon_id, GROUPCHAT_CALLBACK_INDEX, &g_handle_status, &g_handle_packet, &handle_lossy, g_c, friendcon_id); ind = empty; } if (!(g->connections[ind].reasons & reason)) { g->connections[ind].reasons |= reason; if (reason == GROUPCHAT_CONNECTION_REASON_INTRODUCER) { ++g->num_introducer_connections; } } return ind; } static unsigned int send_peer_introduced(Group_Chats *g_c, int friendcon_id, uint16_t group_num); /* Removes reason for keeping connection. * * Kills connection if this was the last reason. */ static void remove_connection_reason(Group_Chats *g_c, Group_c *g, uint16_t i, uint8_t reason) { if (!(g->connections[i].reasons & reason)) { return; } g->connections[i].reasons &= ~reason; if (reason == GROUPCHAT_CONNECTION_REASON_INTRODUCER) { --g->num_introducer_connections; if (g->connections[i].type == GROUPCHAT_CONNECTION_ONLINE) { send_peer_introduced(g_c, g->connections[i].number, g->connections[i].group_number); } } if (g->connections[i].reasons == 0) { kill_friend_connection(g_c->fr_c, g->connections[i].number); g->connections[i].type = GROUPCHAT_CONNECTION_NONE; } } /* Creates a new groupchat and puts it in the chats array. * * type is one of `GROUPCHAT_TYPE_*` * * return group number on success. * return -1 on failure. */ int add_groupchat(Group_Chats *g_c, uint8_t type) { const int32_t groupnumber = create_group_chat(g_c); if (groupnumber == -1) { return -1; } Group_c *g = &g_c->chats[groupnumber]; g->status = GROUPCHAT_STATUS_CONNECTED; g->type = type; new_symmetric_key(g->id); g->peer_number = 0; /* Founder is peer 0. */ memcpy(g->real_pk, nc_get_self_public_key(g_c->m->net_crypto), CRYPTO_PUBLIC_KEY_SIZE); const int peer_index = addpeer(g_c, groupnumber, g->real_pk, dht_get_self_public_key(g_c->m->dht), 0, nullptr, true, false); if (peer_index == -1) { return -1; } setnick(g_c, groupnumber, peer_index, g_c->m->name, g_c->m->name_length, nullptr, false); return groupnumber; } static bool group_leave(const Group_Chats *g_c, uint32_t groupnumber, bool permanent); /* Delete a groupchat from the chats array, informing the group first as * appropriate. * * return 0 on success. * return -1 if groupnumber is invalid. */ int del_groupchat(Group_Chats *g_c, uint32_t groupnumber, bool leave_permanently) { Group_c *g = get_group_c(g_c, groupnumber); if (!g) { return -1; } group_leave(g_c, groupnumber, leave_permanently); for (uint32_t i = 0; i < MAX_GROUP_CONNECTIONS; ++i) { if (g->connections[i].type == GROUPCHAT_CONNECTION_NONE) { continue; } g->connections[i].type = GROUPCHAT_CONNECTION_NONE; kill_friend_connection(g_c->fr_c, g->connections[i].number); } for (uint32_t i = 0; i < g->numpeers; ++i) { if (g->peer_on_leave) { g->peer_on_leave(g->object, groupnumber, g->group[i].object); } } free(g->group); free(g->frozen); if (g->group_on_delete) { g->group_on_delete(g->object, groupnumber); } return wipe_group_chat(g_c, groupnumber); } static const Group_Peer *peer_in_list(const Group_c *g, uint32_t peernumber, bool frozen) { const Group_Peer *list = frozen ? g->frozen : g->group; const uint32_t num = frozen ? g->numfrozen : g->numpeers; if (peernumber >= num) { return nullptr; } return &list[peernumber]; } /* Copy the public key of (frozen, if frozen is true) peernumber who is in * groupnumber to pk. pk must be CRYPTO_PUBLIC_KEY_SIZE long. * * return 0 on success * return -1 if groupnumber is invalid. * return -2 if peernumber is invalid. */ int group_peer_pubkey(const Group_Chats *g_c, uint32_t groupnumber, uint32_t peernumber, uint8_t *pk, bool frozen) { const Group_c *g = get_group_c(g_c, groupnumber); if (!g) { return -1; } const Group_Peer *peer = peer_in_list(g, peernumber, frozen); if (peer == nullptr) { return -2; } memcpy(pk, peer->real_pk, CRYPTO_PUBLIC_KEY_SIZE); return 0; } /* * Return the size of (frozen, if frozen is true) peernumber's name. * * return -1 if groupnumber is invalid. * return -2 if peernumber is invalid. */ int group_peername_size(const Group_Chats *g_c, uint32_t groupnumber, uint32_t peernumber, bool frozen) { const Group_c *g = get_group_c(g_c, groupnumber); if (!g) { return -1; } const Group_Peer *peer = peer_in_list(g, peernumber, frozen); if (peer == nullptr) { return -2; } return peer->nick_len; } /* Copy the name of (frozen, if frozen is true) peernumber who is in * groupnumber to name. name must be at least MAX_NAME_LENGTH long. * * return length of name if success * return -1 if groupnumber is invalid. * return -2 if peernumber is invalid. */ int group_peername(const Group_Chats *g_c, uint32_t groupnumber, uint32_t peernumber, uint8_t *name, bool frozen) { const Group_c *g = get_group_c(g_c, groupnumber); if (!g) { return -1; } const Group_Peer *peer = peer_in_list(g, peernumber, frozen); if (peer == nullptr) { return -2; } if (peer->nick_len > 0) { memcpy(name, peer->nick, peer->nick_len); } return peer->nick_len; } /* Copy last active timestamp of frozennumber who is in groupnumber to * last_active. * * return 0 on success. * return -1 if groupnumber is invalid. * return -2 if frozennumber is invalid. */ int group_frozen_last_active(const Group_Chats *g_c, uint32_t groupnumber, uint32_t peernumber, uint64_t *last_active) { const Group_c *g = get_group_c(g_c, groupnumber); if (!g) { return -1; } if (peernumber >= g->numfrozen) { return -2; } *last_active = g->frozen[peernumber].last_active; return 0; } /* Set maximum number of frozen peers. * * return 0 on success. * return -1 if groupnumber is invalid. */ int group_set_max_frozen(const Group_Chats *g_c, uint32_t groupnumber, uint32_t maxfrozen) { Group_c *g = get_group_c(g_c, groupnumber); if (!g) { return -1; } g->maxfrozen = maxfrozen; delete_old_frozen(g); return 0; } /* Return the number of (frozen, if frozen is true) peers in the group chat on * success. * return -1 if groupnumber is invalid. */ int group_number_peers(const Group_Chats *g_c, uint32_t groupnumber, bool frozen) { const Group_c *g = get_group_c(g_c, groupnumber); if (!g) { return -1; } return frozen ? g->numfrozen : g->numpeers; } /* return 1 if the peernumber corresponds to ours. * return 0 if the peernumber is not ours. * return -1 if groupnumber is invalid. * return -2 if peernumber is invalid. * return -3 if we are not connected to the group chat. */ int group_peernumber_is_ours(const Group_Chats *g_c, uint32_t groupnumber, uint32_t peernumber) { const Group_c *g = get_group_c(g_c, groupnumber); if (!g) { return -1; } if (peernumber >= g->numpeers) { return -2; } if (g->status != GROUPCHAT_STATUS_CONNECTED) { return -3; } return g->peer_number == g->group[peernumber].peer_number; } /* return the type of groupchat (GROUPCHAT_TYPE_) that groupnumber is. * * return -1 on failure. * return type on success. */ int group_get_type(const Group_Chats *g_c, uint32_t groupnumber) { const Group_c *g = get_group_c(g_c, groupnumber); if (!g) { return -1; } return g->type; } /* Copies the unique id of `group_chat[groupnumber]` into `id`. * * return false on failure. * return true on success. */ bool conference_get_id(const Group_Chats *g_c, uint32_t groupnumber, uint8_t *id) { const Group_c *g = get_group_c(g_c, groupnumber); if (!g) { return false; } if (id != nullptr) { memcpy(id, g->id, sizeof(g->id)); } return true; } /* Send a group packet to friendcon_id. * * return 1 on success * return 0 on failure */ static unsigned int send_packet_group_peer(Friend_Connections *fr_c, int friendcon_id, uint8_t packet_id, uint16_t group_num, const uint8_t *data, uint16_t length) { if (1 + sizeof(uint16_t) + length > MAX_CRYPTO_DATA_SIZE) { return 0; } group_num = net_htons(group_num); VLA(uint8_t, packet, 1 + sizeof(uint16_t) + length); packet[0] = packet_id; memcpy(packet + 1, &group_num, sizeof(uint16_t)); memcpy(packet + 1 + sizeof(uint16_t), data, length); return write_cryptpacket(friendconn_net_crypto(fr_c), friend_connection_crypt_connection_id(fr_c, friendcon_id), packet, SIZEOF_VLA(packet), 0) != -1; } /* Send a group lossy packet to friendcon_id. * * return 1 on success * return 0 on failure */ static unsigned int send_lossy_group_peer(Friend_Connections *fr_c, int friendcon_id, uint8_t packet_id, uint16_t group_num, const uint8_t *data, uint16_t length) { if (1 + sizeof(uint16_t) + length > MAX_CRYPTO_DATA_SIZE) { return 0; } group_num = net_htons(group_num); VLA(uint8_t, packet, 1 + sizeof(uint16_t) + length); packet[0] = packet_id; memcpy(packet + 1, &group_num, sizeof(uint16_t)); memcpy(packet + 1 + sizeof(uint16_t), data, length); return send_lossy_cryptpacket(friendconn_net_crypto(fr_c), friend_connection_crypt_connection_id(fr_c, friendcon_id), packet, SIZEOF_VLA(packet)) != -1; } /* invite friendnumber to groupnumber. * * return 0 on success. * return -1 if groupnumber is invalid. * return -2 if invite packet failed to send. * return -3 if we are not connected to the group chat. */ int invite_friend(Group_Chats *g_c, uint32_t friendnumber, uint32_t groupnumber) { Group_c *g = get_group_c(g_c, groupnumber); if (!g) { return -1; } if (g->status != GROUPCHAT_STATUS_CONNECTED) { return -3; } uint8_t invite[INVITE_PACKET_SIZE]; invite[0] = INVITE_ID; const uint16_t groupchat_num = net_htons((uint16_t)groupnumber); memcpy(invite + 1, &groupchat_num, sizeof(groupchat_num)); invite[1 + sizeof(groupchat_num)] = g->type; memcpy(invite + 1 + sizeof(groupchat_num) + 1, g->id, GROUP_ID_LENGTH); if (send_conference_invite_packet(g_c->m, friendnumber, invite, sizeof(invite))) { return 0; } return -2; } /* Send a rejoin packet to a peer if we have a friend connection to the peer. * return true if a packet was sent. * return false otherwise. */ static bool try_send_rejoin(Group_Chats *g_c, Group_c *g, const uint8_t *real_pk) { const int friendcon_id = getfriend_conn_id_pk(g_c->fr_c, real_pk); if (friendcon_id == -1) { return false; } uint8_t packet[1 + 1 + GROUP_ID_LENGTH]; packet[0] = PACKET_ID_REJOIN_CONFERENCE; packet[1] = g->type; memcpy(packet + 2, g->id, GROUP_ID_LENGTH); if (write_cryptpacket(friendconn_net_crypto(g_c->fr_c), friend_connection_crypt_connection_id(g_c->fr_c, friendcon_id), packet, sizeof(packet), 0) == -1) { return false; } add_conn_to_groupchat(g_c, friendcon_id, g, GROUPCHAT_CONNECTION_REASON_INTRODUCER, 1); return true; } static unsigned int send_peer_query(Group_Chats *g_c, int friendcon_id, uint16_t group_num); static bool send_invite_response(Group_Chats *g_c, int groupnumber, uint32_t friendnumber, const uint8_t *data, uint16_t length); /* Join a group (we need to have been invited first.) * * expected_type is the groupchat type we expect the chat we are joining to * have. * * return group number on success. * return -1 if data length is invalid. * return -2 if group is not the expected type. * return -3 if friendnumber is invalid. * return -4 if client is already in this group. * return -5 if group instance failed to initialize. * return -6 if join packet fails to send. */ int join_groupchat(Group_Chats *g_c, uint32_t friendnumber, uint8_t expected_type, const uint8_t *data, uint16_t length) { if (length != sizeof(uint16_t) + 1 + GROUP_ID_LENGTH) { return -1; } if (data[sizeof(uint16_t)] != expected_type) { return -2; } const int friendcon_id = getfriendcon_id(g_c->m, friendnumber); if (friendcon_id == -1) { return -3; } if (get_group_num(g_c, data[sizeof(uint16_t)], data + sizeof(uint16_t) + 1) != -1) { return -4; } const int groupnumber = create_group_chat(g_c); if (groupnumber == -1) { return -5; } Group_c *g = &g_c->chats[groupnumber]; g->status = GROUPCHAT_STATUS_VALID; memcpy(g->real_pk, nc_get_self_public_key(g_c->m->net_crypto), CRYPTO_PUBLIC_KEY_SIZE); if (!send_invite_response(g_c, groupnumber, friendnumber, data, length)) { g->status = GROUPCHAT_STATUS_NONE; return -6; } return groupnumber; } static bool send_invite_response(Group_Chats *g_c, int groupnumber, uint32_t friendnumber, const uint8_t *data, uint16_t length) { Group_c *g = get_group_c(g_c, groupnumber); if (g == nullptr) { return false; } const bool member = (g->status == GROUPCHAT_STATUS_CONNECTED); VLA(uint8_t, response, member ? INVITE_MEMBER_PACKET_SIZE : INVITE_ACCEPT_PACKET_SIZE); response[0] = member ? INVITE_MEMBER_ID : INVITE_ACCEPT_ID; net_pack_u16(response + 1, groupnumber); memcpy(response + 1 + sizeof(uint16_t), data, length); if (member) { net_pack_u16(response + 1 + sizeof(uint16_t) + length, g->peer_number); } if (!send_conference_invite_packet(g_c->m, friendnumber, response, SIZEOF_VLA(response))) { return false; } if (!member) { g->type = data[sizeof(uint16_t)]; memcpy(g->id, data + sizeof(uint16_t) + 1, GROUP_ID_LENGTH); } uint16_t other_groupnum; net_unpack_u16(data, &other_groupnum); const int friendcon_id = getfriendcon_id(g_c->m, friendnumber); if (friendcon_id == -1) { return false; } const int connection_index = add_conn_to_groupchat(g_c, friendcon_id, g, GROUPCHAT_CONNECTION_REASON_INTRODUCER, 1); if (member) { add_conn_to_groupchat(g_c, friendcon_id, g, GROUPCHAT_CONNECTION_REASON_INTRODUCING, 0); } if (connection_index != -1) { g->connections[connection_index].group_number = other_groupnum; g->connections[connection_index].type = GROUPCHAT_CONNECTION_ONLINE; } send_peer_query(g_c, friendcon_id, other_groupnum); return true; } /* Set handlers for custom lossy packets. */ void group_lossy_packet_registerhandler(Group_Chats *g_c, uint8_t byte, lossy_packet_cb *function) { g_c->lossy_packethandlers[byte].function = function; } /* Set the callback for group invites. */ void g_callback_group_invite(Group_Chats *g_c, g_conference_invite_cb *function) { g_c->invite_callback = function; } /* Set the callback for group connection. */ void g_callback_group_connected(Group_Chats *g_c, g_conference_connected_cb *function) { g_c->connected_callback = function; } /* Set the callback for group messages. */ void g_callback_group_message(Group_Chats *g_c, g_conference_message_cb *function) { g_c->message_callback = function; } /* Set callback function for peer nickname changes. * * It gets called every time a peer changes their nickname. */ void g_callback_peer_name(Group_Chats *g_c, peer_name_cb *function) { g_c->peer_name_callback = function; } /* Set callback function for peer list changes. * * It gets called every time the name list changes(new peer, deleted peer) */ void g_callback_peer_list_changed(Group_Chats *g_c, peer_list_changed_cb *function) { g_c->peer_list_changed_callback = function; } /* Set callback function for title changes. */ void g_callback_group_title(Group_Chats *g_c, title_cb *function) { g_c->title_callback = function; } /* Set a function to be called when a new peer joins a group chat. * * return 0 on success. * return -1 on failure. */ int callback_groupchat_peer_new(const Group_Chats *g_c, uint32_t groupnumber, peer_on_join_cb *function) { Group_c *g = get_group_c(g_c, groupnumber); if (!g) { return -1; } g->peer_on_join = function; return 0; } /* Set a function to be called when a peer leaves a group chat. * * return 0 on success. * return -1 on failure. */ int callback_groupchat_peer_delete(Group_Chats *g_c, uint32_t groupnumber, peer_on_leave_cb *function) { Group_c *g = get_group_c(g_c, groupnumber); if (!g) { return -1; } g->peer_on_leave = function; return 0; } /* Set a function to be called when the group chat is deleted. * * return 0 on success. * return -1 on failure. */ int callback_groupchat_delete(Group_Chats *g_c, uint32_t groupnumber, group_on_delete_cb *function) { Group_c *g = get_group_c(g_c, groupnumber); if (!g) { return -1; } g->group_on_delete = function; return 0; } static int send_message_group(const Group_Chats *g_c, uint32_t groupnumber, uint8_t message_id, const uint8_t *data, uint16_t len); /* send a ping message * return true on success */ static bool group_ping_send(const Group_Chats *g_c, uint32_t groupnumber) { if (send_message_group(g_c, groupnumber, GROUP_MESSAGE_PING_ID, nullptr, 0) > 0) { return true; } return false; } /* send a new_peer message * return true on success */ static bool group_new_peer_send(const Group_Chats *g_c, uint32_t groupnumber, uint16_t peer_num, const uint8_t *real_pk, uint8_t *temp_pk) { uint8_t packet[GROUP_MESSAGE_NEW_PEER_LENGTH]; peer_num = net_htons(peer_num); memcpy(packet, &peer_num, sizeof(uint16_t)); memcpy(packet + sizeof(uint16_t), real_pk, CRYPTO_PUBLIC_KEY_SIZE); memcpy(packet + sizeof(uint16_t) + CRYPTO_PUBLIC_KEY_SIZE, temp_pk, CRYPTO_PUBLIC_KEY_SIZE); if (send_message_group(g_c, groupnumber, GROUP_MESSAGE_NEW_PEER_ID, packet, sizeof(packet)) > 0) { return true; } return false; } /* send a kill_peer message * return true on success */ static bool group_kill_peer_send(const Group_Chats *g_c, uint32_t groupnumber, uint16_t peer_num) { uint8_t packet[GROUP_MESSAGE_KILL_PEER_LENGTH]; peer_num = net_htons(peer_num); memcpy(packet, &peer_num, sizeof(uint16_t)); if (send_message_group(g_c, groupnumber, GROUP_MESSAGE_KILL_PEER_ID, packet, sizeof(packet)) > 0) { return true; } return false; } /* send a freeze_peer message * return true on success */ static bool group_freeze_peer_send(const Group_Chats *g_c, uint32_t groupnumber, uint16_t peer_num) { uint8_t packet[GROUP_MESSAGE_KILL_PEER_LENGTH]; peer_num = net_htons(peer_num); memcpy(packet, &peer_num, sizeof(uint16_t)); if (send_message_group(g_c, groupnumber, GROUP_MESSAGE_FREEZE_PEER_ID, packet, sizeof(packet)) > 0) { return true; } return false; } /* send a name message * return true on success */ static bool group_name_send(const Group_Chats *g_c, uint32_t groupnumber, const uint8_t *nick, uint16_t nick_len) { if (nick_len > MAX_NAME_LENGTH) { return false; } if (send_message_group(g_c, groupnumber, GROUP_MESSAGE_NAME_ID, nick, nick_len) > 0) { return true; } return false; } /* send message to announce leaving group * return true on success */ static bool group_leave(const Group_Chats *g_c, uint32_t groupnumber, bool permanent) { const Group_c *g = get_group_c(g_c, groupnumber); if (!g) { return false; } if (permanent) { return group_kill_peer_send(g_c, groupnumber, g->peer_number); } else { return group_freeze_peer_send(g_c, groupnumber, g->peer_number); } } /* set the group's title, limited to MAX_NAME_LENGTH * return 0 on success * return -1 if groupnumber is invalid. * return -2 if title is too long or empty. * return -3 if packet fails to send. */ int group_title_send(const Group_Chats *g_c, uint32_t groupnumber, const uint8_t *title, uint8_t title_len) { Group_c *g = get_group_c(g_c, groupnumber); if (!g) { return -1; } if (title_len > MAX_NAME_LENGTH || title_len == 0) { return -2; } /* same as already set? */ if (g->title_len == title_len && !memcmp(g->title, title, title_len)) { return 0; } memcpy(g->title, title, title_len); g->title_len = title_len; if (g->numpeers == 1) { return 0; } if (send_message_group(g_c, groupnumber, GROUP_MESSAGE_TITLE_ID, title, title_len) > 0) { return 0; } return -3; } /* return the group's title size. * return -1 of groupnumber is invalid. * return -2 if title is too long or empty. */ int group_title_get_size(const Group_Chats *g_c, uint32_t groupnumber) { const Group_c *g = get_group_c(g_c, groupnumber); if (!g) { return -1; } if (g->title_len > MAX_NAME_LENGTH || g->title_len == 0) { return -2; } return g->title_len; } /* Get group title from groupnumber and put it in title. * Title needs to be a valid memory location with a size of at least MAX_NAME_LENGTH (128) bytes. * * return length of copied title if success. * return -1 if groupnumber is invalid. * return -2 if title is too long or empty. */ int group_title_get(const Group_Chats *g_c, uint32_t groupnumber, uint8_t *title) { const Group_c *g = get_group_c(g_c, groupnumber); if (!g) { return -1; } if (g->title_len > MAX_NAME_LENGTH || g->title_len == 0) { return -2; } memcpy(title, g->title, g->title_len); return g->title_len; } static bool get_peer_number(const Group_c *g, const uint8_t *real_pk, uint16_t *peer_number) { const int peer_index = peer_in_group(g, real_pk); if (peer_index >= 0) { *peer_number = g->group[peer_index].peer_number; return true; } const int frozen_index = frozen_in_group(g, real_pk); if (frozen_index >= 0) { *peer_number = g->frozen[frozen_index].peer_number; return true; } return false; } static void handle_friend_invite_packet(Messenger *m, uint32_t friendnumber, const uint8_t *data, uint16_t length, void *userdata) { Group_Chats *g_c = m->conferences_object; if (length <= 1) { return; } const uint8_t *invite_data = data + 1; const uint16_t invite_length = length - 1; switch (data[0]) { case INVITE_ID: { if (length != INVITE_PACKET_SIZE) { return; } const int groupnumber = get_group_num(g_c, data[1 + sizeof(uint16_t)], data + 1 + sizeof(uint16_t) + 1); if (groupnumber == -1) { if (g_c->invite_callback) { g_c->invite_callback(m, friendnumber, invite_data[sizeof(uint16_t)], invite_data, invite_length, userdata); } return; } else { Group_c *g = get_group_c(g_c, groupnumber); if (g && g->status == GROUPCHAT_STATUS_CONNECTED) { send_invite_response(g_c, groupnumber, friendnumber, invite_data, invite_length); } } break; } case INVITE_ACCEPT_ID: case INVITE_MEMBER_ID: { const bool member = (data[0] == INVITE_MEMBER_ID); if (length != (member ? INVITE_MEMBER_PACKET_SIZE : INVITE_ACCEPT_PACKET_SIZE)) { return; } uint16_t other_groupnum; uint16_t groupnum; net_unpack_u16(data + 1, &other_groupnum); net_unpack_u16(data + 1 + sizeof(uint16_t), &groupnum); Group_c *g = get_group_c(g_c, groupnum); if (!g) { return; } if (data[1 + sizeof(uint16_t) * 2] != g->type) { return; } if (crypto_memcmp(data + 1 + sizeof(uint16_t) * 2 + 1, g->id, GROUP_ID_LENGTH) != 0) { return; } uint16_t peer_number; if (member) { net_unpack_u16(data + 1 + sizeof(uint16_t) * 2 + 1 + GROUP_ID_LENGTH, &peer_number); } else { /* TODO(irungentoo): what if two people enter the group at the * same time and are given the same peer_number by different * nodes? */ peer_number = random_u16(); unsigned int tries = 0; while (get_peer_index(g, peer_number) != -1 || get_frozen_index(g, peer_number) != -1) { peer_number = random_u16(); ++tries; if (tries > 32) { return; } } } const int friendcon_id = getfriendcon_id(m, friendnumber); if (friendcon_id == -1) { // TODO(iphydf): Log something? return; } uint8_t real_pk[CRYPTO_PUBLIC_KEY_SIZE]; uint8_t temp_pk[CRYPTO_PUBLIC_KEY_SIZE]; get_friendcon_public_keys(real_pk, temp_pk, g_c->fr_c, friendcon_id); addpeer(g_c, groupnum, real_pk, temp_pk, peer_number, userdata, true, true); const int connection_index = add_conn_to_groupchat(g_c, friendcon_id, g, GROUPCHAT_CONNECTION_REASON_INTRODUCING, 1); if (member) { add_conn_to_groupchat(g_c, friendcon_id, g, GROUPCHAT_CONNECTION_REASON_INTRODUCER, 0); send_peer_query(g_c, friendcon_id, other_groupnum); } if (connection_index != -1) { g->connections[connection_index].group_number = other_groupnum; g->connections[connection_index].type = GROUPCHAT_CONNECTION_ONLINE; } group_new_peer_send(g_c, groupnum, peer_number, real_pk, temp_pk); break; } default: return; } } /* Find index of friend in the connections list. * * return index on success * return -1 on failure. */ static int friend_in_connections(const Group_c *g, int friendcon_id) { for (unsigned int i = 0; i < MAX_GROUP_CONNECTIONS; ++i) { if (g->connections[i].type == GROUPCHAT_CONNECTION_NONE) { continue; } if (g->connections[i].number == (uint32_t)friendcon_id) { return i; } } return -1; } /* return number of connections. */ static unsigned int count_connected(const Group_c *g) { unsigned int count = 0; for (unsigned int i = 0; i < MAX_GROUP_CONNECTIONS; ++i) { if (g->connections[i].type == GROUPCHAT_CONNECTION_ONLINE) { ++count; } } return count; } static int send_packet_online(Friend_Connections *fr_c, int friendcon_id, uint16_t group_num, uint8_t type, const uint8_t *id) { uint8_t packet[1 + ONLINE_PACKET_DATA_SIZE]; group_num = net_htons(group_num); packet[0] = PACKET_ID_ONLINE_PACKET; memcpy(packet + 1, &group_num, sizeof(uint16_t)); packet[1 + sizeof(uint16_t)] = type; memcpy(packet + 1 + sizeof(uint16_t) + 1, id, GROUP_ID_LENGTH); return write_cryptpacket(friendconn_net_crypto(fr_c), friend_connection_crypt_connection_id(fr_c, friendcon_id), packet, sizeof(packet), 0) != -1; } static bool ping_groupchat(Group_Chats *g_c, uint32_t groupnumber); static int handle_packet_online(Group_Chats *g_c, int friendcon_id, const uint8_t *data, uint16_t length) { if (length != ONLINE_PACKET_DATA_SIZE) { return -1; } const int groupnumber = get_group_num(g_c, data[sizeof(uint16_t)], data + sizeof(uint16_t) + 1); if (groupnumber == -1) { return -1; } uint16_t other_groupnum; memcpy(&other_groupnum, data, sizeof(uint16_t)); other_groupnum = net_ntohs(other_groupnum); Group_c *g = get_group_c(g_c, groupnumber); if (!g) { return -1; } const int index = friend_in_connections(g, friendcon_id); if (index == -1) { return -1; } if (g->connections[index].type == GROUPCHAT_CONNECTION_ONLINE) { return -1; } if (count_connected(g) == 0 || (g->connections[index].reasons & GROUPCHAT_CONNECTION_REASON_INTRODUCER)) { send_peer_query(g_c, friendcon_id, other_groupnum); } g->connections[index].group_number = other_groupnum; g->connections[index].type = GROUPCHAT_CONNECTION_ONLINE; send_packet_online(g_c->fr_c, friendcon_id, groupnumber, g->type, g->id); if (g->connections[index].reasons & GROUPCHAT_CONNECTION_REASON_INTRODUCING) { uint8_t real_pk[CRYPTO_PUBLIC_KEY_SIZE]; uint8_t temp_pk[CRYPTO_PUBLIC_KEY_SIZE]; get_friendcon_public_keys(real_pk, temp_pk, g_c->fr_c, friendcon_id); const int peer_index = peer_in_group(g, real_pk); if (peer_index != -1) { group_new_peer_send(g_c, groupnumber, g->group[peer_index].peer_number, real_pk, temp_pk); } g->need_send_name = true; } ping_groupchat(g_c, groupnumber); return 0; } static int handle_packet_rejoin(Group_Chats *g_c, int friendcon_id, const uint8_t *data, uint16_t length, void *userdata) { if (length < 1 + GROUP_ID_LENGTH) { return -1; } const int32_t groupnum = get_group_num(g_c, *data, data + 1); Group_c *g = get_group_c(g_c, groupnum); if (!g) { return -1; } uint8_t real_pk[CRYPTO_PUBLIC_KEY_SIZE]; uint8_t temp_pk[CRYPTO_PUBLIC_KEY_SIZE]; get_friendcon_public_keys(real_pk, temp_pk, g_c->fr_c, friendcon_id); uint16_t peer_number; if (!get_peer_number(g, real_pk, &peer_number)) { return -1; } addpeer(g_c, groupnum, real_pk, temp_pk, peer_number, userdata, true, true); const int connection_index = add_conn_to_groupchat(g_c, friendcon_id, g, GROUPCHAT_CONNECTION_REASON_INTRODUCING, 1); if (connection_index != -1) { send_packet_online(g_c->fr_c, friendcon_id, groupnum, g->type, g->id); } return 0; } // we could send title with invite, but then if it changes between sending and accepting inv, joinee won't see it /* return 1 on success. * return 0 on failure */ static unsigned int send_peer_introduced(Group_Chats *g_c, int friendcon_id, uint16_t group_num) { uint8_t packet[1]; packet[0] = PEER_INTRODUCED_ID; return send_packet_group_peer(g_c->fr_c, friendcon_id, PACKET_ID_DIRECT_CONFERENCE, group_num, packet, sizeof(packet)); } /* return 1 on success. * return 0 on failure */ static unsigned int send_peer_query(Group_Chats *g_c, int friendcon_id, uint16_t group_num) { uint8_t packet[1]; packet[0] = PEER_QUERY_ID; return send_packet_group_peer(g_c->fr_c, friendcon_id, PACKET_ID_DIRECT_CONFERENCE, group_num, packet, sizeof(packet)); } /* return number of peers sent on success. * return 0 on failure. */ static unsigned int send_peers(Group_Chats *g_c, const Group_c *g, int friendcon_id, uint16_t group_num) { uint8_t response_packet[MAX_CRYPTO_DATA_SIZE - (1 + sizeof(uint16_t))]; response_packet[0] = PEER_RESPONSE_ID; uint8_t *p = response_packet + 1; uint16_t sent = 0; for (uint32_t i = 0;; ++i) { if (i == g->numpeers || (p - response_packet) + sizeof(uint16_t) + CRYPTO_PUBLIC_KEY_SIZE * 2 + 1 + g->group[i].nick_len > sizeof(response_packet)) { if (send_packet_group_peer(g_c->fr_c, friendcon_id, PACKET_ID_DIRECT_CONFERENCE, group_num, response_packet, (p - response_packet))) { sent = i; } else { return sent; } if (i == g->numpeers) { break; } p = response_packet + 1; } const uint16_t peer_num = net_htons(g->group[i].peer_number); memcpy(p, &peer_num, sizeof(peer_num)); p += sizeof(peer_num); memcpy(p, g->group[i].real_pk, CRYPTO_PUBLIC_KEY_SIZE); p += CRYPTO_PUBLIC_KEY_SIZE; memcpy(p, g->group[i].temp_pk, CRYPTO_PUBLIC_KEY_SIZE); p += CRYPTO_PUBLIC_KEY_SIZE; *p = g->group[i].nick_len; p += 1; memcpy(p, g->group[i].nick, g->group[i].nick_len); p += g->group[i].nick_len; } if (g->title_len) { VLA(uint8_t, title_packet, 1 + g->title_len); title_packet[0] = PEER_TITLE_ID; memcpy(title_packet + 1, g->title, g->title_len); send_packet_group_peer(g_c->fr_c, friendcon_id, PACKET_ID_DIRECT_CONFERENCE, group_num, title_packet, SIZEOF_VLA(title_packet)); } return sent; } static int handle_send_peers(Group_Chats *g_c, uint32_t groupnumber, const uint8_t *data, uint16_t length, void *userdata) { if (length == 0) { return -1; } Group_c *g = get_group_c(g_c, groupnumber); if (!g) { return -1; } const uint8_t *d = data; while ((unsigned int)(length - (d - data)) >= sizeof(uint16_t) + CRYPTO_PUBLIC_KEY_SIZE * 2 + 1) { uint16_t peer_num; memcpy(&peer_num, d, sizeof(peer_num)); peer_num = net_ntohs(peer_num); d += sizeof(uint16_t); if (g->status == GROUPCHAT_STATUS_VALID && public_key_cmp(d, nc_get_self_public_key(g_c->m->net_crypto)) == 0) { g->peer_number = peer_num; g->status = GROUPCHAT_STATUS_CONNECTED; if (g_c->connected_callback) { g_c->connected_callback(g_c->m, groupnumber, userdata); } g->need_send_name = true; } const int peer_index = addpeer(g_c, groupnumber, d, d + CRYPTO_PUBLIC_KEY_SIZE, peer_num, userdata, false, true); if (peer_index == -1) { return -1; } d += CRYPTO_PUBLIC_KEY_SIZE * 2; const uint8_t name_length = *d; d += 1; if (name_length > (length - (d - data)) || name_length > MAX_NAME_LENGTH) { return -1; } if (!g->group[peer_index].nick_updated) { setnick(g_c, groupnumber, peer_index, d, name_length, userdata, true); } d += name_length; } return 0; } static void handle_direct_packet(Group_Chats *g_c, uint32_t groupnumber, const uint8_t *data, uint16_t length, int connection_index, void *userdata) { if (length == 0) { return; } Group_c *g = get_group_c(g_c, groupnumber); if (!g) { return; } switch (data[0]) { case PEER_INTRODUCED_ID: { remove_connection_reason(g_c, g, connection_index, GROUPCHAT_CONNECTION_REASON_INTRODUCING); } break; case PEER_QUERY_ID: { if (g->connections[connection_index].type != GROUPCHAT_CONNECTION_ONLINE) { return; } send_peers(g_c, g, g->connections[connection_index].number, g->connections[connection_index].group_number); } break; case PEER_RESPONSE_ID: { handle_send_peers(g_c, groupnumber, data + 1, length - 1, userdata); } break; case PEER_TITLE_ID: { if (!g->title_fresh) { settitle(g_c, groupnumber, -1, data + 1, length - 1, userdata); } } break; } } /* Send message to all connections except receiver (if receiver isn't -1) * NOTE: this function appends the group chat number to the data passed to it. * * return number of messages sent. */ static unsigned int send_message_all_connections(const Group_Chats *g_c, const Group_c *g, const uint8_t *data, uint16_t length, int receiver) { uint16_t sent = 0; for (uint16_t i = 0; i < MAX_GROUP_CONNECTIONS; ++i) { if (g->connections[i].type != GROUPCHAT_CONNECTION_ONLINE) { continue; } if ((int)i == receiver) { continue; } if (send_packet_group_peer(g_c->fr_c, g->connections[i].number, PACKET_ID_MESSAGE_CONFERENCE, g->connections[i].group_number, data, length)) { ++sent; } } return sent; } /* Send lossy message to all connections except receiver (if receiver isn't -1) * NOTE: this function appends the group chat number to the data passed to it. * * return number of messages sent. */ static unsigned int send_lossy_all_connections(const Group_Chats *g_c, const Group_c *g, const uint8_t *data, uint16_t length, int receiver) { unsigned int sent = 0; unsigned int num_connected_closest = 0; unsigned int connected_closest[DESIRED_CLOSEST]; for (unsigned int i = 0; i < MAX_GROUP_CONNECTIONS; ++i) { if (g->connections[i].type != GROUPCHAT_CONNECTION_ONLINE) { continue; } if ((int)i == receiver) { continue; } if (g->connections[i].reasons & GROUPCHAT_CONNECTION_REASON_CLOSEST) { connected_closest[num_connected_closest] = i; ++num_connected_closest; continue; } if (send_lossy_group_peer(g_c->fr_c, g->connections[i].number, PACKET_ID_LOSSY_CONFERENCE, g->connections[i].group_number, data, length)) { ++sent; } } if (!num_connected_closest) { return sent; } unsigned int to_send[2] = {0, 0}; uint64_t comp_val_old[2] = {(uint64_t) -1, (uint64_t) -1}; for (unsigned int i = 0; i < num_connected_closest; ++i) { uint8_t real_pk[CRYPTO_PUBLIC_KEY_SIZE] = {0}; get_friendcon_public_keys(real_pk, nullptr, g_c->fr_c, g->connections[connected_closest[i]].number); const uint64_t comp_val = calculate_comp_value(g->real_pk, real_pk); for (uint8_t j = 0; j < 2; ++j) { if (j ? (comp_val > comp_val_old[j]) : (comp_val < comp_val_old[j])) { to_send[j] = connected_closest[i]; comp_val_old[j] = comp_val; } } } for (uint8_t j = 0; j < 2; ++j) { if (j && to_send[1] == to_send[0]) { break; } if (send_lossy_group_peer(g_c->fr_c, g->connections[to_send[j]].number, PACKET_ID_LOSSY_CONFERENCE, g->connections[to_send[j]].group_number, data, length)) { ++sent; } } return sent; } /* Send data of len with message_id to groupnumber. * * return number of peers it was sent to on success. * return -1 if groupnumber is invalid. * return -2 if message is too long. * return -3 if we are not connected to the group. * return -4 if message failed to send. */ static int send_message_group(const Group_Chats *g_c, uint32_t groupnumber, uint8_t message_id, const uint8_t *data, uint16_t len) { Group_c *g = get_group_c(g_c, groupnumber); if (!g) { return -1; } if (len > MAX_GROUP_MESSAGE_DATA_LEN) { return -2; } if (g->status != GROUPCHAT_STATUS_CONNECTED || count_connected(g) == 0) { return -3; } VLA(uint8_t, packet, sizeof(uint16_t) + sizeof(uint32_t) + 1 + len); const uint16_t peer_num = net_htons(g->peer_number); memcpy(packet, &peer_num, sizeof(peer_num)); ++g->message_number; if (!g->message_number) { ++g->message_number; } const uint32_t message_num = net_htonl(g->message_number); memcpy(packet + sizeof(uint16_t), &message_num, sizeof(message_num)); packet[sizeof(uint16_t) + sizeof(uint32_t)] = message_id; if (len) { memcpy(packet + sizeof(uint16_t) + sizeof(uint32_t) + 1, data, len); } unsigned int ret = send_message_all_connections(g_c, g, packet, SIZEOF_VLA(packet), -1); if (ret == 0) { return -4; } return ret; } /* send a group message * return 0 on success * see: send_message_group() for error codes. */ int group_message_send(const Group_Chats *g_c, uint32_t groupnumber, const uint8_t *message, uint16_t length) { const int ret = send_message_group(g_c, groupnumber, PACKET_ID_MESSAGE, message, length); if (ret > 0) { return 0; } return ret; } /* send a group action * return 0 on success * see: send_message_group() for error codes. */ int group_action_send(const Group_Chats *g_c, uint32_t groupnumber, const uint8_t *action, uint16_t length) { const int ret = send_message_group(g_c, groupnumber, PACKET_ID_ACTION, action, length); if (ret > 0) { return 0; } return ret; } /* High level function to send custom lossy packets. * * return -1 on failure. * return 0 on success. */ int send_group_lossy_packet(const Group_Chats *g_c, uint32_t groupnumber, const uint8_t *data, uint16_t length) { // TODO(irungentoo): length check here? Group_c *g = get_group_c(g_c, groupnumber); if (!g) { return -1; } VLA(uint8_t, packet, sizeof(uint16_t) * 2 + length); const uint16_t peer_number = net_htons(g->peer_number); memcpy(packet, &peer_number, sizeof(uint16_t)); const uint16_t message_num = net_htons(g->lossy_message_number); memcpy(packet + sizeof(uint16_t), &message_num, sizeof(uint16_t)); memcpy(packet + sizeof(uint16_t) * 2, data, length); if (send_lossy_all_connections(g_c, g, packet, SIZEOF_VLA(packet), -1) == 0) { return -1; } ++g->lossy_message_number; return 0; } static Message_Info *find_message_slot_or_reject(uint32_t message_number, uint8_t message_id, Group_Peer *peer) { const bool ignore_older = (message_id == GROUP_MESSAGE_NAME_ID || message_id == GROUP_MESSAGE_TITLE_ID); Message_Info *i; for (i = peer->last_message_infos; i < peer->last_message_infos + peer->num_last_message_infos; ++i) { if (message_number - (i->message_number + 1) <= ((uint32_t)1 << 31)) { break; } if (message_number == i->message_number) { return nullptr; } if (ignore_older && message_id == i->message_id) { return nullptr; } } return i; } /* Stores message info in peer->last_message_infos. * * return true if message should be processed. * return false otherwise. */ static bool check_message_info(uint32_t message_number, uint8_t message_id, Group_Peer *peer) { Message_Info *const i = find_message_slot_or_reject(message_number, message_id, peer); if (i == nullptr) { return false; } if (i == peer->last_message_infos + MAX_LAST_MESSAGE_INFOS) { return false; } if (peer->num_last_message_infos < MAX_LAST_MESSAGE_INFOS) { ++peer->num_last_message_infos; } memmove(i + 1, i, ((peer->last_message_infos + peer->num_last_message_infos - 1) - i) * sizeof(Message_Info)); i->message_number = message_number; i->message_id = message_id; return true; } static void handle_message_packet_group(Group_Chats *g_c, uint32_t groupnumber, const uint8_t *data, uint16_t length, int connection_index, void *userdata) { if (length < sizeof(uint16_t) + sizeof(uint32_t) + 1) { return; } Group_c *g = get_group_c(g_c, groupnumber); if (!g) { return; } uint16_t peer_number; memcpy(&peer_number, data, sizeof(uint16_t)); peer_number = net_ntohs(peer_number); uint32_t message_number; memcpy(&message_number, data + sizeof(uint16_t), sizeof(message_number)); message_number = net_ntohl(message_number); const uint8_t message_id = data[sizeof(uint16_t) + sizeof(message_number)]; const uint8_t *msg_data = data + sizeof(uint16_t) + sizeof(message_number) + 1; const uint16_t msg_data_len = length - (sizeof(uint16_t) + sizeof(message_number) + 1); const bool ignore_frozen = message_id == GROUP_MESSAGE_FREEZE_PEER_ID; const int index = ignore_frozen ? get_peer_index(g, peer_number) : note_peer_active(g_c, groupnumber, peer_number, userdata); if (index == -1) { if (ignore_frozen) { return; } if (g->connections[connection_index].type != GROUPCHAT_CONNECTION_ONLINE) { return; } /* If we don't know the peer this packet came from, then we query the * list of peers from the relaying peer. * (They wouldn't have relayed it if they didn't know the peer.) */ send_peer_query(g_c, g->connections[connection_index].number, g->connections[connection_index].group_number); return; } if (g->num_introducer_connections > 0 && count_connected(g) > DESIRED_CLOSEST) { for (uint32_t i = 0; i < MAX_GROUP_CONNECTIONS; ++i) { if (g->connections[i].type == GROUPCHAT_CONNECTION_NONE || !(g->connections[i].reasons & GROUPCHAT_CONNECTION_REASON_INTRODUCER) || i == connection_index) { continue; } uint8_t real_pk[CRYPTO_PUBLIC_KEY_SIZE]; get_friendcon_public_keys(real_pk, nullptr, g_c->fr_c, g->connections[i].number); if (id_equal(g->group[index].real_pk, real_pk)) { /* Received message from peer relayed via another peer, so * the introduction was successful */ remove_connection_reason(g_c, g, i, GROUPCHAT_CONNECTION_REASON_INTRODUCER); } } } if (!check_message_info(message_number, message_id, &g->group[index])) { return; } uint8_t real_pk[CRYPTO_PUBLIC_KEY_SIZE]; get_friendcon_public_keys(real_pk, nullptr, g_c->fr_c, g->connections[connection_index].number); const bool direct_from_sender = id_equal(g->group[index].real_pk, real_pk); switch (message_id) { case GROUP_MESSAGE_PING_ID: break; case GROUP_MESSAGE_NEW_PEER_ID: { if (msg_data_len != GROUP_MESSAGE_NEW_PEER_LENGTH) { return; } uint16_t new_peer_number; memcpy(&new_peer_number, msg_data, sizeof(uint16_t)); new_peer_number = net_ntohs(new_peer_number); addpeer(g_c, groupnumber, msg_data + sizeof(uint16_t), msg_data + sizeof(uint16_t) + CRYPTO_PUBLIC_KEY_SIZE, new_peer_number, userdata, true, true); } break; case GROUP_MESSAGE_KILL_PEER_ID: case GROUP_MESSAGE_FREEZE_PEER_ID: { if (msg_data_len != GROUP_MESSAGE_KILL_PEER_LENGTH) { return; } uint16_t kill_peer_number; memcpy(&kill_peer_number, msg_data, sizeof(uint16_t)); kill_peer_number = net_ntohs(kill_peer_number); if (peer_number == kill_peer_number) { if (message_id == GROUP_MESSAGE_KILL_PEER_ID) { delpeer(g_c, groupnumber, index, userdata); } else { freeze_peer(g_c, groupnumber, index, userdata); } } else { return; // TODO(irungentoo): } } break; case GROUP_MESSAGE_NAME_ID: { if (!setnick(g_c, groupnumber, index, msg_data, msg_data_len, userdata, true)) { return; } } break; case GROUP_MESSAGE_TITLE_ID: { if (!settitle(g_c, groupnumber, index, msg_data, msg_data_len, userdata)) { return; } } break; case PACKET_ID_MESSAGE: { if (msg_data_len == 0) { return; } VLA(uint8_t, newmsg, msg_data_len + 1); memcpy(newmsg, msg_data, msg_data_len); newmsg[msg_data_len] = 0; // TODO(irungentoo): if (g_c->message_callback) { g_c->message_callback(g_c->m, groupnumber, index, 0, newmsg, msg_data_len, userdata); } break; } case PACKET_ID_ACTION: { if (msg_data_len == 0) { return; } VLA(uint8_t, newmsg, msg_data_len + 1); memcpy(newmsg, msg_data, msg_data_len); newmsg[msg_data_len] = 0; // TODO(irungentoo): if (g_c->message_callback) { g_c->message_callback(g_c->m, groupnumber, index, 1, newmsg, msg_data_len, userdata); } break; } default: return; } /* If the packet was received from the peer who sent the message, relay it * back. When the sender only has one group connection (e.g. because there * are only two peers in the group), this is the only way for them to * receive their own message. */ send_message_all_connections(g_c, g, data, length, direct_from_sender ? -1 : connection_index); } static int g_handle_packet(void *object, int friendcon_id, const uint8_t *data, uint16_t length, void *userdata) { Group_Chats *g_c = (Group_Chats *)object; if (length < 1 + sizeof(uint16_t) + 1) { return -1; } if (data[0] == PACKET_ID_ONLINE_PACKET) { return handle_packet_online(g_c, friendcon_id, data + 1, length - 1); } if (data[0] == PACKET_ID_REJOIN_CONFERENCE) { return handle_packet_rejoin(g_c, friendcon_id, data + 1, length - 1, userdata); } uint16_t groupnumber; memcpy(&groupnumber, data + 1, sizeof(uint16_t)); groupnumber = net_ntohs(groupnumber); const Group_c *g = get_group_c(g_c, groupnumber); if (!g) { return -1; } const int index = friend_in_connections(g, friendcon_id); if (index == -1) { return -1; } if (data[0] == PACKET_ID_DIRECT_CONFERENCE) { handle_direct_packet(g_c, groupnumber, data + 1 + sizeof(uint16_t), length - (1 + sizeof(uint16_t)), index, userdata); return 0; } if (data[0] == PACKET_ID_MESSAGE_CONFERENCE) { handle_message_packet_group(g_c, groupnumber, data + 1 + sizeof(uint16_t), length - (1 + sizeof(uint16_t)), index, userdata); return 0; } return -1; } /* Did we already receive the lossy packet or not. * * return -1 on failure. * return 0 if packet was not received. * return 1 if packet was received. * * TODO(irungentoo): test this */ static int lossy_packet_not_received(const Group_c *g, int peer_index, uint16_t message_number) { if (peer_index == -1) { return -1; } if (g->group[peer_index].bottom_lossy_number == g->group[peer_index].top_lossy_number) { g->group[peer_index].top_lossy_number = message_number; g->group[peer_index].bottom_lossy_number = (message_number - MAX_LOSSY_COUNT) + 1; g->group[peer_index].recv_lossy[message_number % MAX_LOSSY_COUNT] = 1; return 0; } if ((uint16_t)(message_number - g->group[peer_index].bottom_lossy_number) < MAX_LOSSY_COUNT) { if (g->group[peer_index].recv_lossy[message_number % MAX_LOSSY_COUNT]) { return 1; } g->group[peer_index].recv_lossy[message_number % MAX_LOSSY_COUNT] = 1; return 0; } if ((uint16_t)(message_number - g->group[peer_index].bottom_lossy_number) > (1 << 15)) { return -1; } const uint16_t top_distance = message_number - g->group[peer_index].top_lossy_number; if (top_distance >= MAX_LOSSY_COUNT) { crypto_memzero(g->group[peer_index].recv_lossy, sizeof(g->group[peer_index].recv_lossy)); } else { // top_distance < MAX_LOSSY_COUNT for (unsigned int i = g->group[peer_index].bottom_lossy_number; i != g->group[peer_index].bottom_lossy_number + top_distance; ++i) { g->group[peer_index].recv_lossy[i % MAX_LOSSY_COUNT] = 0; } } g->group[peer_index].top_lossy_number = message_number; g->group[peer_index].bottom_lossy_number = (message_number - MAX_LOSSY_COUNT) + 1; g->group[peer_index].recv_lossy[message_number % MAX_LOSSY_COUNT] = 1; return 0; } /* Does this group type make use of lossy packets? */ static bool type_uses_lossy(uint8_t type) { return (type == GROUPCHAT_TYPE_AV); } static int handle_lossy(void *object, int friendcon_id, const uint8_t *data, uint16_t length, void *userdata) { Group_Chats *g_c = (Group_Chats *)object; if (data[0] != PACKET_ID_LOSSY_CONFERENCE) { return -1; } if (length < 1 + sizeof(uint16_t) * 3 + 1) { return -1; } uint16_t groupnumber; uint16_t peer_number; uint16_t message_number; memcpy(&groupnumber, data + 1, sizeof(uint16_t)); memcpy(&peer_number, data + 1 + sizeof(uint16_t), sizeof(uint16_t)); memcpy(&message_number, data + 1 + sizeof(uint16_t) * 2, sizeof(uint16_t)); groupnumber = net_ntohs(groupnumber); peer_number = net_ntohs(peer_number); message_number = net_ntohs(message_number); const Group_c *g = get_group_c(g_c, groupnumber); if (!g) { return -1; } if (!type_uses_lossy(g->type)) { return -1; } const int index = friend_in_connections(g, friendcon_id); if (index == -1) { return -1; } if (peer_number == g->peer_number) { return -1; } const int peer_index = get_peer_index(g, peer_number); if (peer_index == -1) { return -1; } if (lossy_packet_not_received(g, peer_index, message_number) != 0) { return -1; } const uint8_t *lossy_data = data + 1 + sizeof(uint16_t) * 3; uint16_t lossy_length = length - (1 + sizeof(uint16_t) * 3); const uint8_t message_id = lossy_data[0]; ++lossy_data; --lossy_length; send_lossy_all_connections(g_c, g, data + 1 + sizeof(uint16_t), length - (1 + sizeof(uint16_t)), index); if (!g_c->lossy_packethandlers[message_id].function) { return -1; } if (g_c->lossy_packethandlers[message_id].function(g->object, groupnumber, peer_index, g->group[peer_index].object, lossy_data, lossy_length) == -1) { return -1; } return 0; } /* Set the object that is tied to the group chat. * * return 0 on success. * return -1 on failure */ int group_set_object(const Group_Chats *g_c, uint32_t groupnumber, void *object) { Group_c *g = get_group_c(g_c, groupnumber); if (!g) { return -1; } g->object = object; return 0; } /* Set the object that is tied to the group peer. * * return 0 on success. * return -1 on failure */ int group_peer_set_object(const Group_Chats *g_c, uint32_t groupnumber, uint32_t peernumber, void *object) { const Group_c *g = get_group_c(g_c, groupnumber); if (!g) { return -1; } if (peernumber >= g->numpeers) { return -1; } g->group[peernumber].object = object; return 0; } /* Return the object tied to the group chat previously set by group_set_object. * * return NULL on failure. * return object on success. */ void *group_get_object(const Group_Chats *g_c, uint32_t groupnumber) { const Group_c *g = get_group_c(g_c, groupnumber); if (!g) { return nullptr; } return g->object; } /* Return the object tied to the group chat peer previously set by group_peer_set_object. * * return NULL on failure. * return object on success. */ void *group_peer_get_object(const Group_Chats *g_c, uint32_t groupnumber, uint32_t peernumber) { const Group_c *g = get_group_c(g_c, groupnumber); if (!g) { return nullptr; } if (peernumber >= g->numpeers) { return nullptr; } return g->group[peernumber].object; } /* Interval in seconds to send ping messages */ #define GROUP_PING_INTERVAL 20 static bool ping_groupchat(Group_Chats *g_c, uint32_t groupnumber) { Group_c *g = get_group_c(g_c, groupnumber); if (!g) { return false; } if (mono_time_is_timeout(g_c->mono_time, g->last_sent_ping, GROUP_PING_INTERVAL)) { if (group_ping_send(g_c, groupnumber)) { g->last_sent_ping = mono_time_get(g_c->mono_time); } } return true; } /* Seconds of inactivity after which to freeze a peer */ #define FREEZE_TIMEOUT (GROUP_PING_INTERVAL * 3) static bool groupchat_freeze_timedout(Group_Chats *g_c, uint32_t groupnumber, void *userdata) { Group_c *g = get_group_c(g_c, groupnumber); if (!g) { return false; } for (uint32_t i = 0; i < g->numpeers; ++i) { if (g->group[i].peer_number == g->peer_number) { continue; } if (mono_time_is_timeout(g_c->mono_time, g->group[i].last_active, FREEZE_TIMEOUT)) { freeze_peer(g_c, groupnumber, i, userdata); } } if (g->numpeers <= 1) { g->title_fresh = false; } return true; } /* Push non-empty slots to start. */ static void squash_connections(Group_c *g) { uint16_t i = 0; for (uint16_t j = 0; j < MAX_GROUP_CONNECTIONS; ++j) { if (g->connections[j].type != GROUPCHAT_CONNECTION_NONE) { g->connections[i] = g->connections[j]; ++i; } } for (; i < MAX_GROUP_CONNECTIONS; ++i) { g->connections[i].type = GROUPCHAT_CONNECTION_NONE; } } #define MIN_EMPTY_CONNECTIONS (1 + MAX_GROUP_CONNECTIONS / 10) /* Remove old connections as necessary to ensure we have space for new * connections. This invalidates connections array indices (which is * why we do this periodically rather than on adding a connection). */ static void clean_connections(Group_Chats *g_c, Group_c *g) { uint16_t to_clear = MIN_EMPTY_CONNECTIONS; for (uint16_t i = 0; i < MAX_GROUP_CONNECTIONS; ++i) { if (g->connections[i].type == GROUPCHAT_CONNECTION_NONE) { --to_clear; if (to_clear == 0) { break; } } } for (; to_clear > 0; --to_clear) { // Remove a connection. Prefer non-closest connections, and given // that prefer non-online connections, and given that prefer earlier // slots. uint16_t i = 0; while (i < MAX_GROUP_CONNECTIONS && (g->connections[i].type != GROUPCHAT_CONNECTION_CONNECTING || (g->connections[i].reasons & GROUPCHAT_CONNECTION_REASON_CLOSEST))) { ++i; } if (i == MAX_GROUP_CONNECTIONS) { i = 0; while (i < MAX_GROUP_CONNECTIONS - to_clear && (g->connections[i].type != GROUPCHAT_CONNECTION_ONLINE || (g->connections[i].reasons & GROUPCHAT_CONNECTION_REASON_CLOSEST))) { ++i; } } if (g->connections[i].type != GROUPCHAT_CONNECTION_NONE) { remove_connection(g_c, g, i); } } squash_connections(g); } /* Send current name (set in messenger) to all online groups. */ void send_name_all_groups(Group_Chats *g_c) { for (uint16_t i = 0; i < g_c->num_chats; ++i) { Group_c *g = get_group_c(g_c, i); if (!g) { continue; } if (g->status == GROUPCHAT_STATUS_CONNECTED) { group_name_send(g_c, i, g_c->m->name, g_c->m->name_length); g->need_send_name = false; } } } #define SAVED_PEER_SIZE_CONSTANT (2 * CRYPTO_PUBLIC_KEY_SIZE + sizeof(uint16_t) + sizeof(uint64_t) + 1) static uint32_t saved_peer_size(const Group_Peer *peer) { return SAVED_PEER_SIZE_CONSTANT + peer->nick_len; } static uint8_t *save_peer(const Group_Peer *peer, uint8_t *data) { memcpy(data, peer->real_pk, CRYPTO_PUBLIC_KEY_SIZE); data += CRYPTO_PUBLIC_KEY_SIZE; memcpy(data, peer->temp_pk, CRYPTO_PUBLIC_KEY_SIZE); data += CRYPTO_PUBLIC_KEY_SIZE; host_to_lendian_bytes16(data, peer->peer_number); data += sizeof(uint16_t); host_to_lendian_bytes64(data, peer->last_active); data += sizeof(uint64_t); *data = peer->nick_len; ++data; memcpy(data, peer->nick, peer->nick_len); data += peer->nick_len; return data; } #define SAVED_CONF_SIZE_CONSTANT (1 + GROUP_ID_LENGTH + sizeof(uint32_t) \ + sizeof(uint16_t) + sizeof(uint16_t) + sizeof(uint32_t) + 1) static uint32_t saved_conf_size(const Group_c *g) { uint32_t len = SAVED_CONF_SIZE_CONSTANT + g->title_len; for (uint32_t j = 0; j < g->numpeers + g->numfrozen; ++j) { const Group_Peer *peer = (j < g->numpeers) ? &g->group[j] : &g->frozen[j - g->numpeers]; if (id_equal(peer->real_pk, g->real_pk)) { continue; } len += saved_peer_size(peer); } return len; } /* Save a future message number. The save will remain valid until we have sent * this many more messages. */ #define SAVE_OFFSET_MESSAGE_NUMBER (1 << 16) #define SAVE_OFFSET_LOSSY_MESSAGE_NUMBER (1 << 13) static uint8_t *save_conf(const Group_c *g, uint8_t *data) { *data = g->type; ++data; memcpy(data, g->id, GROUP_ID_LENGTH); data += GROUP_ID_LENGTH; host_to_lendian_bytes32(data, g->message_number + SAVE_OFFSET_MESSAGE_NUMBER); data += sizeof(uint32_t); host_to_lendian_bytes16(data, g->lossy_message_number + SAVE_OFFSET_LOSSY_MESSAGE_NUMBER); data += sizeof(uint16_t); host_to_lendian_bytes16(data, g->peer_number); data += sizeof(uint16_t); uint8_t *const numsaved_location = data; data += sizeof(uint32_t); *data = g->title_len; ++data; memcpy(data, g->title, g->title_len); data += g->title_len; uint32_t numsaved = 0; for (uint32_t j = 0; j < g->numpeers + g->numfrozen; ++j) { const Group_Peer *peer = (j < g->numpeers) ? &g->group[j] : &g->frozen[j - g->numpeers]; if (id_equal(peer->real_pk, g->real_pk)) { continue; } data = save_peer(peer, data); ++numsaved; } host_to_lendian_bytes32(numsaved_location, numsaved); return data; } static uint32_t conferences_section_size(const Group_Chats *g_c) { uint32_t len = 0; for (uint16_t i = 0; i < g_c->num_chats; ++i) { const Group_c *g = get_group_c(g_c, i); if (!g || g->status != GROUPCHAT_STATUS_CONNECTED) { continue; } len += saved_conf_size(g); } return len; } uint32_t conferences_size(const Group_Chats *g_c) { return 2 * sizeof(uint32_t) + conferences_section_size(g_c); } uint8_t *conferences_save(const Group_Chats *g_c, uint8_t *data) { const uint32_t len = conferences_section_size(g_c); data = state_write_section_header(data, STATE_COOKIE_TYPE, len, STATE_TYPE_CONFERENCES); for (uint16_t i = 0; i < g_c->num_chats; ++i) { const Group_c *g = get_group_c(g_c, i); if (!g || g->status != GROUPCHAT_STATUS_CONNECTED) { continue; } data = save_conf(g, data); } return data; } static State_Load_Status load_conferences(Group_Chats *g_c, const uint8_t *data, uint32_t length) { const uint8_t *init_data = data; while (length >= (uint32_t)(data - init_data) + SAVED_CONF_SIZE_CONSTANT) { const int groupnumber = create_group_chat(g_c); if (groupnumber == -1) { return STATE_LOAD_STATUS_ERROR; } Group_c *g = &g_c->chats[groupnumber]; g->type = *data; ++data; memcpy(g->id, data, GROUP_ID_LENGTH); data += GROUP_ID_LENGTH; lendian_bytes_to_host32(&g->message_number, data); data += sizeof(uint32_t); lendian_bytes_to_host16(&g->lossy_message_number, data); data += sizeof(uint16_t); lendian_bytes_to_host16(&g->peer_number, data); data += sizeof(uint16_t); lendian_bytes_to_host32(&g->numfrozen, data); data += sizeof(uint32_t); if (g->numfrozen > 0) { g->frozen = (Group_Peer *)malloc(sizeof(Group_Peer) * g->numfrozen); if (g->frozen == nullptr) { return STATE_LOAD_STATUS_ERROR; } } g->title_len = *data; if (g->title_len > MAX_NAME_LENGTH) { return STATE_LOAD_STATUS_ERROR; } ++data; if (length < (uint32_t)(data - init_data) + g->title_len) { return STATE_LOAD_STATUS_ERROR; } memcpy(g->title, data, g->title_len); data += g->title_len; for (uint32_t j = 0; j < g->numfrozen; ++j) { if (length < (uint32_t)(data - init_data) + SAVED_PEER_SIZE_CONSTANT) { return STATE_LOAD_STATUS_ERROR; } Group_Peer *peer = &g->frozen[j]; memset(peer, 0, sizeof(Group_Peer)); id_copy(peer->real_pk, data); data += CRYPTO_PUBLIC_KEY_SIZE; id_copy(peer->temp_pk, data); data += CRYPTO_PUBLIC_KEY_SIZE; lendian_bytes_to_host16(&peer->peer_number, data); data += sizeof(uint16_t); lendian_bytes_to_host64(&peer->last_active, data); data += sizeof(uint64_t); peer->nick_len = *data; if (peer->nick_len > MAX_NAME_LENGTH) { return STATE_LOAD_STATUS_ERROR; } ++data; if (length < (uint32_t)(data - init_data) + peer->nick_len) { return STATE_LOAD_STATUS_ERROR; } memcpy(peer->nick, data, peer->nick_len); data += peer->nick_len; // NOTE: this relies on friends being loaded before conferences. peer->is_friend = (getfriend_id(g_c->m, peer->real_pk) != -1); } if (g->numfrozen > g->maxfrozen) { g->maxfrozen = g->numfrozen; } g->status = GROUPCHAT_STATUS_CONNECTED; memcpy(g->real_pk, nc_get_self_public_key(g_c->m->net_crypto), CRYPTO_PUBLIC_KEY_SIZE); const int peer_index = addpeer(g_c, groupnumber, g->real_pk, dht_get_self_public_key(g_c->m->dht), g->peer_number, nullptr, true, false); if (peer_index == -1) { return STATE_LOAD_STATUS_ERROR; } setnick(g_c, groupnumber, peer_index, g_c->m->name, g_c->m->name_length, nullptr, false); } return STATE_LOAD_STATUS_CONTINUE; } bool conferences_load_state_section(Group_Chats *g_c, const uint8_t *data, uint32_t length, uint16_t type, State_Load_Status *status) { if (type != STATE_TYPE_CONFERENCES) { return false; } *status = load_conferences(g_c, data, length); return true; } /* Create new groupchat instance. */ Group_Chats *new_groupchats(Mono_Time *mono_time, Messenger *m) { if (!m) { return nullptr; } Group_Chats *temp = (Group_Chats *)calloc(1, sizeof(Group_Chats)); if (temp == nullptr) { return nullptr; } temp->mono_time = mono_time; temp->m = m; temp->fr_c = m->fr_c; m->conferences_object = temp; m_callback_conference_invite(m, &handle_friend_invite_packet); set_global_status_callback(m->fr_c, &g_handle_any_status, temp); return temp; } /* main groupchats loop. */ void do_groupchats(Group_Chats *g_c, void *userdata) { for (uint16_t i = 0; i < g_c->num_chats; ++i) { Group_c *g = get_group_c(g_c, i); if (!g) { continue; } if (g->status == GROUPCHAT_STATUS_CONNECTED) { connect_to_closest(g_c, i, userdata); ping_groupchat(g_c, i); groupchat_freeze_timedout(g_c, i, userdata); clean_connections(g_c, g); if (g->need_send_name) { group_name_send(g_c, i, g_c->m->name, g_c->m->name_length); g->need_send_name = false; } } } // TODO(irungentoo): } /* Free everything related with group chats. */ void kill_groupchats(Group_Chats *g_c) { for (uint16_t i = 0; i < g_c->num_chats; ++i) { del_groupchat(g_c, i, false); } m_callback_conference_invite(g_c->m, nullptr); set_global_status_callback(g_c->m->fr_c, nullptr, nullptr); g_c->m->conferences_object = nullptr; free(g_c); } /* Return the number of chats in the instance m. * You should use this to determine how much memory to allocate * for copy_chatlist. */ uint32_t count_chatlist(const Group_Chats *g_c) { uint32_t ret = 0; for (uint16_t i = 0; i < g_c->num_chats; ++i) { if (g_c->chats[i].status != GROUPCHAT_STATUS_NONE) { ++ret; } } return ret; } /* Copy a list of valid chat IDs into the array out_list. * If out_list is NULL, returns 0. * Otherwise, returns the number of elements copied. * If the array was too small, the contents * of out_list will be truncated to list_size. */ uint32_t copy_chatlist(const Group_Chats *g_c, uint32_t *out_list, uint32_t list_size) { if (!out_list) { return 0; } if (g_c->num_chats == 0) { return 0; } uint32_t ret = 0; for (uint16_t i = 0; i < g_c->num_chats; ++i) { if (ret >= list_size) { break; /* Abandon ship */ } if (g_c->chats[i].status > GROUPCHAT_STATUS_NONE) { out_list[ret] = i; ++ret; } } return ret; }
utf-8
1
GPL-3+
2013-2017 Tox Project 2016-2018 The TokTok team
cardpeek-0.8.4/lua_ui.c
/********************************************************************** * * This file is part of Cardpeek, the smart card reader utility. * * Copyright 2009-2014 by Alain Pannetrat <L1L1@gmx.com> * * Cardpeek 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. * * Cardpeek 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 Cardpeek. If not, see <http://www.gnu.org/licenses/>. * */ #include <lauxlib.h> #include "lua_ui.h" #include "ui.h" #include "dyntree_model.h" #include "misc.h" #include <string.h> #include <stdlib.h> #include "bytestring.h" #include "lua_bytes.h" #include <glib.h> #include <glib/gprintf.h> static int subr_ui_save_view(lua_State* L) { const char *filename; if (lua_isnoneornil(L,1)) return luaL_error(L,"Expecting one parameter: a filename (string)"); filename= lua_tostring(L,1); if (dyntree_model_iter_to_xml_file(CARD_DATA_STORE,NULL,filename)==0) { log_printf(LOG_ERROR,"Could not write xml data to '%s'",filename); lua_pushboolean(L,0); } else { log_printf(LOG_INFO,"Wrote card data to '%s'",filename); lua_pushboolean(L,1); } return 1; } static int subr_ui_load_view(lua_State* L) { const char *filename; int retval; if (lua_isnoneornil(L,1)) return luaL_error(L,"Expecting one parameter: a filename (string)"); filename = lua_tostring(L,1); if (strcmp(filename_extension(filename),".lua")==0) { log_printf(LOG_WARNING,"%s seems to be a card LUA script: perhaps you should use the 'Analyzer'" " menu instead to open this file.",filename_base(filename)); } dyntree_model_iter_remove(CARD_DATA_STORE,NULL); retval = dyntree_model_iter_from_xml_file(CARD_DATA_STORE,NULL,filename); lua_pushboolean(L,retval); return 1; } static int subr_ui_question(lua_State* L) { const char* message; const char** items; unsigned item_count; unsigned i; int result; if (!lua_isstring(L,1) || !lua_istable(L,2)) return luaL_error(L,"expecting a string and a table as arguments to this function"); if (!lua_isnil(L,1)) message = lua_tostring(L,1); else message = ""; item_count = lua_rawlen(L,2); items = malloc(sizeof(char *)*item_count); for (i=0; i<item_count; i++) { lua_rawgeti(L,2,i+1); if (lua_isstring(L,-1)) items[i] = lua_tostring(L,-1); else items[i] = "(error)"; lua_pop(L,1); } result = ui_question_l(message,item_count,items); free(items); if (result<0) lua_pushnil(L); else lua_pushinteger(L,result+1); return 1; } static int subr_ui_readline(lua_State* L) { const char* message; unsigned len; const char* default_value; char *value; if (!lua_isnoneornil(L,1)) message = lua_tostring(L,1); else message = "Input"; if (!lua_isnoneornil(L,2)) len = lua_tointeger(L,2); else len = 40; if (!lua_isnoneornil(L,3)) default_value = lua_tostring(L,3); else default_value = ""; value = g_malloc(len+1); strncpy(value,default_value,len); if (ui_readline(message,len,value)) lua_pushstring(L,value); else lua_pushnil(L); g_free(value); return 1; } static int subr_ui_select_file(lua_State* L) { const char* title; const char* path; const char* filename; char **pair; title = lua_tostring(L,1); if (!lua_isnoneornil(L,2)) path = lua_tostring(L,2); else path = NULL; if (!lua_isnoneornil(L,3)) filename = lua_tostring(L,3); else filename = NULL; pair = ui_select_file(title,path,filename); if (pair[0]) { lua_pushstring(L,pair[0]); g_free(pair[0]); } else lua_pushnil(L); if (pair[1]) { lua_pushstring(L,pair[1]); g_free(pair[1]); } else lua_pushnil(L); return 2; } static int subr_ui_about(lua_State* L) { UNUSED(L); ui_about(); return 0; } static int subr_ui_exit(lua_State* L) { UNUSED(L); ui_exit(); return 0; } static const struct luaL_Reg uilib [] = { {"save_view",subr_ui_save_view }, {"load_view",subr_ui_load_view }, {"readline",subr_ui_readline }, {"question",subr_ui_question }, {"select_file",subr_ui_select_file }, {"about", subr_ui_about }, {"exit", subr_ui_exit }, {NULL,NULL} /* sentinel */ }; int luaopen_ui(lua_State* L) { luaL_newlib(L, uilib); lua_setglobal(L,"ui"); return 1; }
utf-8
1
GPL-3+
2009-2013 Alain Pannetrat <L1L1@gmx.com>
ksh93u+m-1.0.0~beta.2/src/lib/libast/vmalloc/vmclear.c
/*********************************************************************** * * * This software is part of the ast package * * Copyright (c) 1985-2011 AT&T Intellectual Property * * Copyright (c) 2020-2021 Contributors to ksh 93u+m * * and is licensed under the * * Eclipse Public License, Version 1.0 * * by AT&T Intellectual Property * * * * A copy of the License is available at * * http://www.eclipse.org/org/documents/epl-v10.html * * (with md5 checksum b35adb5213ca9657e911e9befb180842) * * * * Information and Software Systems Research * * AT&T Research * * Florham Park NJ * * * * Glenn Fowler <gsf@research.att.com> * * David Korn <dgk@research.att.com> * * Phong Vo <kpv@research.att.com> * * * ***********************************************************************/ #if defined(_UWIN) && defined(_BLD_ast) void _STUB_vmclear(){} #else #include "vmhdr.h" /* Clear out all allocated space. ** ** Written by Kiem-Phong Vo, kpv@research.att.com, 01/16/94. */ #if __STD_C int vmclear(Vmalloc_t* vm) #else int vmclear(vm) Vmalloc_t* vm; #endif { Seg_t *seg, *next; Block_t *tp; size_t size, s; Vmdata_t *vd = vm->data; SETLOCK(vm, 0); vd->free = vd->wild = NIL(Block_t*); vd->pool = 0; if(vd->mode&(VM_MTBEST|VM_MTDEBUG|VM_MTPROFILE) ) { vd->root = NIL(Block_t*); for(s = 0; s < S_TINY; ++s) TINY(vd)[s] = NIL(Block_t*); for(s = 0; s <= S_CACHE; ++s) CACHE(vd)[s] = NIL(Block_t*); } for(seg = vd->seg; seg; seg = next) { next = seg->next; tp = SEGBLOCK(seg); size = seg->baddr - ((Vmuchar_t*)tp) - 2*sizeof(Head_t); SEG(tp) = seg; SIZE(tp) = size; if((vd->mode&(VM_MTLAST|VM_MTPOOL)) ) seg->free = tp; else { SIZE(tp) |= BUSY|JUNK; LINK(tp) = CACHE(vd)[C_INDEX(SIZE(tp))]; CACHE(vd)[C_INDEX(SIZE(tp))] = tp; } tp = BLOCK(seg->baddr); SEG(tp) = seg; SIZE(tp) = BUSY; } CLRLOCK(vm, 0); return 0; } #endif
utf-8
1
Eclipse_Public_License_1.0
1982-2012, AT&T Intellectual Property
mame-0.240+dfsg.1/src/mame/drivers/microb.cpp
// license:BSD-3-Clause // copyright-holders:Robbbert, AJR /*************************************************************************** BEEHIVE Micro B Series 25/05/2009 Skeleton driver [Robbbert] This is a series of conventional computer terminals using a serial link. DM3270 is a clone of the IBM3276-2. The character gen rom is not dumped. Using the one from 'c10' for the moment. System beeps if ^G or ^Z pressed. Pressing ^Q is the same as Enter. 25/04/2011 Added partial keyboard. 26/06/2011 Added modifier keys. ****************************************************************************/ #include "emu.h" #include "cpu/i8085/i8085.h" #include "machine/input_merger.h" #include "machine/i8251.h" #include "machine/i8255.h" #include "machine/i8257.h" #include "machine/pit8253.h" #include "video/i8275.h" #include "bus/rs232/rs232.h" #include "sound/beep.h" #include "screen.h" #include "speaker.h" class microb_state : public driver_device { public: microb_state(const machine_config &mconfig, device_type type, const char *tag) : driver_device(mconfig, type, tag) , m_maincpu(*this, "maincpu") , m_dmac(*this, "dmac") , m_p_chargen(*this, "chargen") , m_beep(*this, "beep") , m_usart(*this, "usart%u", 1U) , m_rs232(*this, "rs232%c", 'a') , m_io_keyboard(*this, "X%u", 0U) { } void microb(machine_config &config); protected: virtual void machine_start() override; private: DECLARE_WRITE_LINE_MEMBER(dmac_hrq_w); u8 dmac_mem_r(offs_t offset); void dmac_mem_w(offs_t offset, u8 data); I8275_DRAW_CHARACTER_MEMBER(draw_character); u8 ppi2_pa_r(); void ppi2_pc_w(u8 data); void microb_io(address_map &map); void microb_mem(address_map &map); required_device<cpu_device> m_maincpu; required_device<i8257_device> m_dmac; required_region_ptr<u8> m_p_chargen; required_device<beep_device> m_beep; required_device_array<i8251_device, 2> m_usart; required_device_array<rs232_port_device, 2> m_rs232; required_ioport_array<16> m_io_keyboard; u8 m_keyline; }; WRITE_LINE_MEMBER(microb_state::dmac_hrq_w) { m_maincpu->set_input_line(INPUT_LINE_HALT, state ? ASSERT_LINE : CLEAR_LINE); m_dmac->hlda_w(state); } u8 microb_state::dmac_mem_r(offs_t offset) { return m_maincpu->space(AS_PROGRAM).read_byte(offset); } void microb_state::dmac_mem_w(offs_t offset, u8 data) { return m_maincpu->space(AS_PROGRAM).write_byte(offset, data); } u8 microb_state::ppi2_pa_r() { return m_io_keyboard[m_keyline & 15]->read(); } void microb_state::ppi2_pc_w(u8 data) { m_keyline = data; m_beep->set_state(!BIT(data, 4)); } void microb_state::microb_mem(address_map &map) { map.unmap_value_high(); map(0x0000, 0x17ff).rom(); map(0x8000, 0x8fff).ram(); } void microb_state::microb_io(address_map &map) { map.global_mask(0xff); map.unmap_value_high(); map(0x00, 0x09).rw(m_dmac, FUNC(i8257_device::read), FUNC(i8257_device::write)); map(0x10, 0x13).rw("ppi1", FUNC(i8255_device::read), FUNC(i8255_device::write)); map(0x20, 0x21).rw(m_usart[0], FUNC(i8251_device::read), FUNC(i8251_device::write)); map(0x30, 0x31).rw(m_usart[1], FUNC(i8251_device::read), FUNC(i8251_device::write)); map(0x50, 0x51).rw("crtc", FUNC(i8275_device::read), FUNC(i8275_device::write)); map(0x60, 0x63).rw("ppi2", FUNC(i8255_device::read), FUNC(i8255_device::write)); map(0xe0, 0xe3).rw("pit1", FUNC(pit8253_device::read), FUNC(pit8253_device::write)); map(0xf0, 0xf3).rw("pit2", FUNC(pit8253_device::read), FUNC(pit8253_device::write)); } /* Input ports */ static INPUT_PORTS_START( microb ) PORT_START("X0") PORT_BIT(0x01, IP_ACTIVE_LOW, IPT_KEYBOARD) PORT_NAME("Q") PORT_CODE(KEYCODE_Q) PORT_CHAR('q') PORT_CHAR('Q') PORT_BIT(0x02, IP_ACTIVE_LOW, IPT_KEYBOARD) PORT_NAME("W") PORT_CODE(KEYCODE_W) PORT_CHAR('w') PORT_CHAR('W') PORT_BIT(0x04, IP_ACTIVE_LOW, IPT_KEYBOARD) PORT_NAME("E") PORT_CODE(KEYCODE_E) PORT_CHAR('e') PORT_CHAR('E') PORT_BIT(0x08, IP_ACTIVE_LOW, IPT_KEYBOARD) PORT_NAME("R") PORT_CODE(KEYCODE_R) PORT_CHAR('r') PORT_CHAR('R') PORT_BIT(0x10, IP_ACTIVE_LOW, IPT_KEYBOARD) PORT_NAME("T") PORT_CODE(KEYCODE_T) PORT_CHAR('t') PORT_CHAR('T') PORT_BIT(0x20, IP_ACTIVE_LOW, IPT_KEYBOARD) PORT_NAME("Y") PORT_CODE(KEYCODE_Y) PORT_CHAR('y') PORT_CHAR('Y') PORT_BIT(0x40, IP_ACTIVE_LOW, IPT_KEYBOARD) PORT_NAME("U") PORT_CODE(KEYCODE_U) PORT_CHAR('u') PORT_CHAR('U') PORT_BIT(0x80, IP_ACTIVE_LOW, IPT_KEYBOARD) PORT_NAME("I") PORT_CODE(KEYCODE_I) PORT_CHAR('i') PORT_CHAR('I') PORT_START("X1") PORT_BIT(0x01, IP_ACTIVE_LOW, IPT_KEYBOARD) PORT_NAME("O") PORT_CODE(KEYCODE_O) PORT_CHAR('o') PORT_CHAR('O') PORT_BIT(0x02, IP_ACTIVE_LOW, IPT_KEYBOARD) PORT_NAME("P") PORT_CODE(KEYCODE_P) PORT_CHAR('p') PORT_CHAR('P') PORT_BIT(0x04, IP_ACTIVE_LOW, IPT_KEYBOARD) PORT_NAME("A") PORT_CODE(KEYCODE_A) PORT_CHAR('a') PORT_CHAR('A') PORT_BIT(0x08, IP_ACTIVE_LOW, IPT_KEYBOARD) PORT_NAME("S") PORT_CODE(KEYCODE_S) PORT_CHAR('s') PORT_CHAR('S') PORT_BIT(0x10, IP_ACTIVE_LOW, IPT_KEYBOARD) PORT_NAME("D") PORT_CODE(KEYCODE_D) PORT_CHAR('d') PORT_CHAR('D') PORT_BIT(0x20, IP_ACTIVE_LOW, IPT_KEYBOARD) PORT_NAME("F") PORT_CODE(KEYCODE_F) PORT_CHAR('f') PORT_CHAR('F') PORT_BIT(0x40, IP_ACTIVE_LOW, IPT_KEYBOARD) PORT_NAME("G") PORT_CODE(KEYCODE_G) PORT_CHAR('g') PORT_CHAR('G') PORT_BIT(0x80, IP_ACTIVE_LOW, IPT_KEYBOARD) PORT_NAME("H") PORT_CODE(KEYCODE_H) PORT_CHAR('h') PORT_CHAR('H') PORT_START("X2") PORT_BIT(0x01, IP_ACTIVE_LOW, IPT_KEYBOARD) PORT_NAME("J") PORT_CODE(KEYCODE_J) PORT_CHAR('j') PORT_CHAR('J') PORT_BIT(0x02, IP_ACTIVE_LOW, IPT_KEYBOARD) PORT_NAME("K") PORT_CODE(KEYCODE_K) PORT_CHAR('k') PORT_CHAR('K') PORT_BIT(0x04, IP_ACTIVE_LOW, IPT_KEYBOARD) PORT_NAME("L") PORT_CODE(KEYCODE_L) PORT_CHAR('l') PORT_CHAR('L') PORT_BIT(0x08, IP_ACTIVE_LOW, IPT_KEYBOARD) PORT_NAME("Z") PORT_CODE(KEYCODE_Z) PORT_CHAR('z') PORT_CHAR('Z') PORT_BIT(0x10, IP_ACTIVE_LOW, IPT_KEYBOARD) PORT_NAME("X") PORT_CODE(KEYCODE_X) PORT_CHAR('x') PORT_CHAR('X') PORT_BIT(0x20, IP_ACTIVE_LOW, IPT_KEYBOARD) PORT_NAME("C") PORT_CODE(KEYCODE_C) PORT_CHAR('c') PORT_CHAR('C') PORT_BIT(0x40, IP_ACTIVE_LOW, IPT_KEYBOARD) PORT_NAME("V") PORT_CODE(KEYCODE_V) PORT_CHAR('v') PORT_CHAR('V') PORT_BIT(0x80, IP_ACTIVE_LOW, IPT_KEYBOARD) PORT_NAME("B") PORT_CODE(KEYCODE_B) PORT_CHAR('b') PORT_CHAR('B') PORT_START("X3") PORT_BIT(0x01, IP_ACTIVE_LOW, IPT_KEYBOARD) PORT_NAME("N") PORT_CODE(KEYCODE_N) PORT_CHAR('n') PORT_CHAR('N') PORT_BIT(0x02, IP_ACTIVE_LOW, IPT_KEYBOARD) PORT_NAME("M") PORT_CODE(KEYCODE_M) PORT_CHAR('m') PORT_CHAR('M') PORT_BIT(0x04, IP_ACTIVE_LOW, IPT_KEYBOARD) PORT_NAME("`") PORT_CODE(KEYCODE_TILDE) PORT_CHAR('`') PORT_CHAR('~') PORT_BIT(0x08, IP_ACTIVE_LOW, IPT_KEYBOARD) PORT_NAME("[") PORT_CODE(KEYCODE_OPENBRACE) PORT_CHAR('[') PORT_CHAR(']') PORT_BIT(0x10, IP_ACTIVE_LOW, IPT_KEYBOARD) PORT_NAME("\\") PORT_CODE(KEYCODE_BACKSLASH) PORT_CHAR('\\') PORT_CHAR('|') PORT_BIT(0x20, IP_ACTIVE_LOW, IPT_KEYBOARD) PORT_NAME(";") PORT_CODE(KEYCODE_COLON) PORT_CHAR(';') PORT_CHAR(':') PORT_BIT(0x40, IP_ACTIVE_LOW, IPT_KEYBOARD) PORT_NAME("'") PORT_CODE(KEYCODE_QUOTE) PORT_CHAR('\'') PORT_CHAR('"') PORT_BIT(0x80, IP_ACTIVE_LOW, IPT_KEYBOARD) PORT_NAME("{") PORT_CODE(KEYCODE_CLOSEBRACE) PORT_CHAR('{') PORT_CHAR('}') PORT_START("X4") PORT_BIT(0x01, IP_ACTIVE_LOW, IPT_KEYBOARD) PORT_NAME("<") PORT_CODE(KEYCODE_BACKSLASH2) PORT_CHAR('<') PORT_CHAR('>') PORT_BIT(0x02, IP_ACTIVE_LOW, IPT_KEYBOARD) PORT_NAME(",") PORT_CODE(KEYCODE_COMMA) PORT_CHAR(',') PORT_BIT(0x04, IP_ACTIVE_LOW, IPT_KEYBOARD) PORT_NAME(".") PORT_CODE(KEYCODE_STOP) PORT_CHAR('.') PORT_BIT(0x08, IP_ACTIVE_LOW, IPT_KEYBOARD) PORT_NAME("/") PORT_CODE(KEYCODE_SLASH) PORT_CHAR('/') PORT_CHAR('?') PORT_BIT(0x10, IP_ACTIVE_LOW, IPT_KEYBOARD) PORT_NAME("1") PORT_CODE(KEYCODE_1) PORT_CHAR('1') PORT_CHAR('!') PORT_BIT(0x20, IP_ACTIVE_LOW, IPT_KEYBOARD) PORT_NAME("2") PORT_CODE(KEYCODE_2) PORT_CHAR('2') PORT_CHAR('@') PORT_BIT(0x40, IP_ACTIVE_LOW, IPT_KEYBOARD) PORT_NAME("3") PORT_CODE(KEYCODE_3) PORT_CHAR('3') PORT_CHAR('#') PORT_BIT(0x80, IP_ACTIVE_LOW, IPT_KEYBOARD) PORT_NAME("4") PORT_CODE(KEYCODE_4) PORT_CHAR('4') PORT_CHAR('$') PORT_START("X5") PORT_BIT(0x01, IP_ACTIVE_LOW, IPT_KEYBOARD) PORT_NAME("5") PORT_CODE(KEYCODE_5) PORT_CHAR('5') PORT_CHAR('%') PORT_BIT(0x02, IP_ACTIVE_LOW, IPT_KEYBOARD) PORT_NAME("6") PORT_CODE(KEYCODE_6) PORT_CHAR('6') PORT_CHAR('^') PORT_BIT(0x04, IP_ACTIVE_LOW, IPT_KEYBOARD) PORT_NAME("7") PORT_CODE(KEYCODE_7) PORT_CHAR('7') PORT_CHAR('&') PORT_BIT(0x08, IP_ACTIVE_LOW, IPT_KEYBOARD) PORT_NAME("8") PORT_CODE(KEYCODE_8) PORT_CHAR('8') PORT_CHAR('*') PORT_BIT(0x10, IP_ACTIVE_LOW, IPT_KEYBOARD) PORT_NAME("9") PORT_CODE(KEYCODE_9) PORT_CHAR('9') PORT_CHAR('(') PORT_BIT(0x20, IP_ACTIVE_LOW, IPT_KEYBOARD) PORT_NAME("0") PORT_CODE(KEYCODE_0) PORT_CHAR('0') PORT_CHAR(')') PORT_BIT(0x40, IP_ACTIVE_LOW, IPT_KEYBOARD) PORT_NAME("-") PORT_CODE(KEYCODE_MINUS) PORT_CHAR('-') PORT_CHAR('_') PORT_BIT(0x80, IP_ACTIVE_LOW, IPT_KEYBOARD) PORT_NAME("=") PORT_CODE(KEYCODE_EQUALS) PORT_CHAR('=') PORT_CHAR('+') PORT_START("X6") PORT_BIT(0x01, IP_ACTIVE_LOW, IPT_UNUSED) PORT_BIT(0x02, IP_ACTIVE_LOW, IPT_UNUSED) PORT_BIT(0x04, IP_ACTIVE_LOW, IPT_UNUSED) PORT_BIT(0x08, IP_ACTIVE_LOW, IPT_UNUSED) PORT_BIT(0x10, IP_ACTIVE_LOW, IPT_KEYBOARD) PORT_NAME("7pad") PORT_CODE(KEYCODE_7_PAD) PORT_BIT(0x20, IP_ACTIVE_LOW, IPT_KEYBOARD) PORT_NAME("8pad") PORT_CODE(KEYCODE_8_PAD) PORT_BIT(0x40, IP_ACTIVE_LOW, IPT_KEYBOARD) PORT_NAME("9pad") PORT_CODE(KEYCODE_9_PAD) PORT_BIT(0x80, IP_ACTIVE_LOW, IPT_UNUSED) PORT_START("X7") PORT_BIT(0x01, IP_ACTIVE_LOW, IPT_UNUSED) PORT_BIT(0x02, IP_ACTIVE_LOW, IPT_UNUSED) // Does a HOME PORT_BIT(0x04, IP_ACTIVE_LOW, IPT_KEYBOARD) PORT_NAME("Home") PORT_CODE(KEYCODE_HOME) PORT_BIT(0x08, IP_ACTIVE_LOW, IPT_KEYBOARD) PORT_NAME("4pad") PORT_CODE(KEYCODE_4_PAD) PORT_BIT(0x10, IP_ACTIVE_LOW, IPT_KEYBOARD) PORT_NAME("5pad") PORT_CODE(KEYCODE_5_PAD) PORT_BIT(0x20, IP_ACTIVE_LOW, IPT_KEYBOARD) PORT_NAME("6pad") PORT_CODE(KEYCODE_6_PAD) PORT_BIT(0x40, IP_ACTIVE_LOW, IPT_KEYBOARD) PORT_NAME("Backspace") PORT_CODE(KEYCODE_BACKSPACE) PORT_CHAR(8) PORT_BIT(0x80, IP_ACTIVE_LOW, IPT_UNUSED) PORT_START("X8") PORT_BIT(0x01, IP_ACTIVE_LOW, IPT_KEYBOARD) PORT_NAME("1pad") PORT_CODE(KEYCODE_1_PAD) PORT_BIT(0x02, IP_ACTIVE_LOW, IPT_KEYBOARD) PORT_NAME("2pad") PORT_CODE(KEYCODE_2_PAD) PORT_BIT(0x04, IP_ACTIVE_LOW, IPT_KEYBOARD) PORT_NAME("3pad") PORT_CODE(KEYCODE_3_PAD) PORT_BIT(0x08, IP_ACTIVE_LOW, IPT_KEYBOARD) PORT_NAME("Esc") PORT_CODE(KEYCODE_ESC) PORT_BIT(0x10, IP_ACTIVE_LOW, IPT_KEYBOARD) PORT_NAME("Show/Hide Status") PORT_BIT(0x20, IP_ACTIVE_LOW, IPT_KEYBOARD) PORT_NAME("Down") PORT_CODE(KEYCODE_DOWN) PORT_CHAR(UCHAR_MAMEKEY(DOWN)) PORT_BIT(0x40, IP_ACTIVE_LOW, IPT_KEYBOARD) PORT_NAME("Up") PORT_CODE(KEYCODE_UP) PORT_CHAR(UCHAR_MAMEKEY(UP)) PORT_BIT(0x80, IP_ACTIVE_LOW, IPT_KEYBOARD) PORT_NAME("0pad") PORT_CODE(KEYCODE_0_PAD) PORT_START("X9") PORT_BIT(0x01, IP_ACTIVE_LOW, IPT_KEYBOARD) PORT_NAME(".pad") PORT_CODE(KEYCODE_DEL_PAD) PORT_BIT(0x02, IP_ACTIVE_LOW, IPT_KEYBOARD) PORT_NAME("-pad") PORT_CODE(KEYCODE_MINUS_PAD) PORT_BIT(0x04, IP_ACTIVE_LOW, IPT_UNUSED) PORT_BIT(0x08, IP_ACTIVE_LOW, IPT_UNUSED) PORT_BIT(0x10, IP_ACTIVE_LOW, IPT_UNUSED) PORT_BIT(0x20, IP_ACTIVE_LOW, IPT_KEYBOARD) PORT_NAME("Cursor Blink On/Off") PORT_BIT(0x40, IP_ACTIVE_LOW, IPT_UNUSED) // carriage return PORT_BIT(0x80, IP_ACTIVE_LOW, IPT_KEYBOARD) PORT_NAME("Left") PORT_CODE(KEYCODE_LEFT) PORT_CHAR(UCHAR_MAMEKEY(LEFT)) PORT_START("X10") PORT_BIT(0x01, IP_ACTIVE_LOW, IPT_KEYBOARD) PORT_NAME("Right") PORT_CODE(KEYCODE_RIGHT) PORT_CHAR(UCHAR_MAMEKEY(RIGHT)) PORT_BIT(0x02, IP_ACTIVE_LOW, IPT_KEYBOARD) PORT_NAME("Space") PORT_CODE(KEYCODE_SPACE) PORT_CHAR(' ') PORT_BIT(0x04, IP_ACTIVE_LOW, IPT_KEYBOARD) PORT_NAME("XMIT") PORT_CODE(KEYCODE_ENTER) PORT_CHAR(13) PORT_BIT(0x08, IP_ACTIVE_LOW, IPT_UNUSED) PORT_BIT(0x10, IP_ACTIVE_LOW, IPT_UNUSED) PORT_BIT(0x20, IP_ACTIVE_LOW, IPT_UNUSED) PORT_BIT(0x40, IP_ACTIVE_LOW, IPT_UNUSED) PORT_BIT(0x80, IP_ACTIVE_LOW, IPT_UNUSED) // This row is scanned but nothing happens PORT_START("X11") PORT_BIT(0xff, IP_ACTIVE_LOW, IPT_UNUSED) // These probably not exist PORT_START("X12") PORT_BIT(0xff, IP_ACTIVE_LOW, IPT_UNUSED) PORT_START("X13") PORT_BIT(0xff, IP_ACTIVE_LOW, IPT_UNUSED) PORT_START("X14") PORT_BIT(0xff, IP_ACTIVE_LOW, IPT_UNUSED) PORT_START("X15") PORT_BIT(0xff, IP_ACTIVE_LOW, IPT_UNUSED) PORT_START("MODIFIERS") PORT_BIT(0x04, IP_ACTIVE_LOW, IPT_KEYBOARD) PORT_NAME("Capslock") PORT_CODE(KEYCODE_CAPSLOCK) PORT_BIT(0x08, IP_ACTIVE_LOW, IPT_KEYBOARD) PORT_NAME("LCtrl") PORT_CODE(KEYCODE_LCONTROL) PORT_CHAR(UCHAR_SHIFT_2) PORT_BIT(0x10, IP_ACTIVE_LOW, IPT_KEYBOARD) PORT_NAME("RCtrl") PORT_CODE(KEYCODE_RCONTROL) PORT_BIT(0x20, IP_ACTIVE_LOW, IPT_KEYBOARD) PORT_NAME("LShift") PORT_CODE(KEYCODE_LSHIFT) PORT_CHAR(UCHAR_SHIFT_1) PORT_BIT(0x40, IP_ACTIVE_LOW, IPT_KEYBOARD) PORT_NAME("RShift") PORT_CODE(KEYCODE_RSHIFT) PORT_BIT(0x83, IP_ACTIVE_LOW, IPT_UNUSED) // assumed to be dipswitches, purpose unknown, see code from 12D PORT_START("DIPS") PORT_DIPNAME( 0x01, 0x01, "Switch A") PORT_DIPLOCATION("SW1:1") PORT_DIPSETTING( 0x01, DEF_STR(Off)) PORT_DIPSETTING( 0x00, DEF_STR(On)) PORT_DIPNAME( 0x02, 0x02, "Switch B") PORT_DIPLOCATION("SW1:2") PORT_DIPSETTING( 0x02, DEF_STR(Off)) PORT_DIPSETTING( 0x00, DEF_STR(On)) PORT_BIT(0x3c, 0x2c, IPT_UNUSED) // this is required to sync keyboard and A-LOCK indicator PORT_BIT(0x40, IP_ACTIVE_LOW, IPT_UNUSED) // unused PORT_DIPNAME( 0x80, 0x80, "Switch C") PORT_DIPLOCATION("SW1:3") PORT_DIPSETTING( 0x80, DEF_STR(Off)) PORT_DIPSETTING( 0x00, DEF_STR(On)) INPUT_PORTS_END void microb_state::machine_start() { save_item(NAME(m_keyline)); } I8275_DRAW_CHARACTER_MEMBER(microb_state::draw_character) { u8 dots = lten ? 0xff : (vsp || linecount == 9) ? 0 : m_p_chargen[(charcode << 4) | linecount]; if (rvv) dots ^= 0xff; // HLGT is active on status line rgb_t const fg = hlgt ? rgb_t(0xc0, 0xc0, 0xc0) : rgb_t::white(); u32 *pix = &bitmap.pix(y, x); for (int i = 0; i < 8; i++) { *pix++ = BIT(dots, 7) ? fg : rgb_t::black(); dots <<= 1; } } void microb_state::microb(machine_config &config) { /* basic machine hardware */ I8085A(config, m_maincpu, XTAL(4'000'000)); m_maincpu->set_addrmap(AS_PROGRAM, &microb_state::microb_mem); m_maincpu->set_addrmap(AS_IO, &microb_state::microb_io); INPUT_MERGER_ANY_HIGH(config, "usartint").output_handler().set_inputline(m_maincpu, I8085_RST55_LINE); I8257(config, m_dmac, 2'000'000); m_dmac->out_hrq_cb().set(FUNC(microb_state::dmac_hrq_w)); m_dmac->in_memr_cb().set(FUNC(microb_state::dmac_mem_r)); m_dmac->out_memw_cb().set(FUNC(microb_state::dmac_mem_w)); m_dmac->out_iow_cb<2>().set("crtc", FUNC(i8275_device::dack_w)); m_dmac->out_tc_cb().set_inputline(m_maincpu, I8085_RST75_LINE); /* video hardware */ screen_device &screen(SCREEN(config, "screen", SCREEN_TYPE_RASTER, rgb_t::green())); screen.set_raw(1'620'000 * 8, 800, 0, 640, 324, 0, 300); //screen.set_raw(1'620'000 * 8, 800, 0, 640, 270, 0, 250); screen.set_screen_update("crtc", FUNC(i8275_device::screen_update)); i8275_device &crtc(I8275(config, "crtc", 1'620'000)); crtc.set_screen("screen"); crtc.set_character_width(8); crtc.set_display_callback(FUNC(microb_state::draw_character)); crtc.irq_wr_callback().set_inputline(m_maincpu, I8085_RST65_LINE); crtc.drq_wr_callback().set(m_dmac, FUNC(i8257_device::dreq2_w)); i8255_device &ppi1(I8255(config, "ppi1")); ppi1.in_pb_callback().set_ioport("DIPS"); i8255_device &ppi2(I8255(config, "ppi2")); ppi2.in_pa_callback().set(FUNC(microb_state::ppi2_pa_r)); ppi2.in_pb_callback().set_ioport("MODIFIERS"); ppi2.out_pc_callback().set(FUNC(microb_state::ppi2_pc_w)); pit8253_device &pit1(PIT8253(config, "pit1")); pit1.set_clk<2>(1'536'000); pit1.out_handler<2>().set(m_usart[1], FUNC(i8251_device::write_rxc)); pit8253_device &pit2(PIT8253(config, "pit2")); pit2.set_clk<0>(1'536'000); pit2.set_clk<1>(1'536'000); pit2.set_clk<2>(1'536'000); pit2.out_handler<0>().set(m_usart[0], FUNC(i8251_device::write_txc)); pit2.out_handler<1>().set(m_usart[0], FUNC(i8251_device::write_rxc)); pit2.out_handler<2>().set(m_usart[1], FUNC(i8251_device::write_txc)); SPEAKER(config, "mono").front_center(); BEEP(config, m_beep, 1000).add_route(ALL_OUTPUTS, "mono", 0.5); I8251(config, m_usart[0], 0); m_usart[0]->txd_handler().set(m_rs232[0], FUNC(rs232_port_device::write_txd)); m_usart[0]->dtr_handler().set(m_rs232[0], FUNC(rs232_port_device::write_dtr)); m_usart[0]->rts_handler().set(m_rs232[0], FUNC(rs232_port_device::write_rts)); m_usart[0]->rxrdy_handler().set("usartint", FUNC(input_merger_device::in_w<0>)); m_usart[0]->txrdy_handler().set("usartint", FUNC(input_merger_device::in_w<1>)); RS232_PORT(config, m_rs232[0], default_rs232_devices, nullptr); m_rs232[0]->rxd_handler().set(m_usart[0], FUNC(i8251_device::write_rxd)); m_rs232[0]->dsr_handler().set(m_usart[0], FUNC(i8251_device::write_dsr)); m_rs232[0]->cts_handler().set(m_usart[0], FUNC(i8251_device::write_cts)); I8251(config, m_usart[1], 0); m_usart[1]->txd_handler().set(m_rs232[1], FUNC(rs232_port_device::write_txd)); m_usart[1]->dtr_handler().set(m_rs232[1], FUNC(rs232_port_device::write_dtr)); m_usart[1]->rts_handler().set(m_rs232[1], FUNC(rs232_port_device::write_rts)); m_usart[1]->rxrdy_handler().set("usartint", FUNC(input_merger_device::in_w<2>)); m_usart[1]->txrdy_handler().set("usartint", FUNC(input_merger_device::in_w<3>)); RS232_PORT(config, m_rs232[1], default_rs232_devices, nullptr); m_rs232[1]->rxd_handler().set(m_usart[1], FUNC(i8251_device::write_rxd)); m_rs232[1]->dsr_handler().set(m_usart[1], FUNC(i8251_device::write_dsr)); m_rs232[1]->cts_handler().set(m_usart[1], FUNC(i8251_device::write_cts)); } /* ROM definition */ ROM_START( dm3270 ) ROM_REGION( 0x1800, "maincpu", 0 ) ROM_LOAD( "dm3270-1.rom", 0x0000, 0x0800, CRC(781bde32) SHA1(a3fe25baadd2bfc2b1791f509bb0f4960281ee32) ) ROM_LOAD( "dm3270-2.rom", 0x0800, 0x0800, CRC(4d3476b7) SHA1(627ad42029ca6c8574cda8134d047d20515baf53) ) ROM_LOAD( "dm3270-3.rom", 0x1000, 0x0800, CRC(dbf15833) SHA1(ae93117260a259236c50885c5cecead2aad9b3c4) ) /* character generator not dumped, using the one from 'c10' for now */ ROM_REGION( 0x2000, "chargen", 0 ) ROM_LOAD( "c10_char.bin", 0x0000, 0x2000, BAD_DUMP CRC(cb530b6f) SHA1(95590bbb433db9c4317f535723b29516b9b9fcbf)) ROM_END /* Driver */ // YEAR NAME PARENT COMPAT MACHINE INPU CLASS INIT COMPANY FULLNAME FLAGS COMP( 1982, dm3270, 0, 0, microb, microb, microb_state, empty_init, "Beehive International", "DM3270 Control Unit Display Station", MACHINE_IMPERFECT_SOUND | MACHINE_SUPPORTS_SAVE )
utf-8
1
BSD-3-clause
Aaron Giles Alex Pasadyn Alex Wulms Antoine Mine Brad Martin Bryan McPhail Chris Kirmse Dag Lem Dreamer Nom Eric Smith Ernesto Corvi Fabio Priuli Frank Palazzolo F. Ulivi Grazvydas Ignotas hap Igor Jarek Burczynski Jason Eckhardt John Butler John Weidman Jonas Quinn Jonathan Gevaryahu Joseph Zbiciak Juergen Buchmueller J. Wallace Karl Stenerud Kris Bleakley Lancer MAME32/MAMEUI team Mariusz Wojcieszek Michael Soderstrom Miodrag Milanovic Mirko Buffoni Nach Nicola Salmoria Olivier Galibert Peter J.C.Clare Peter Trauner Raphael Nabet Ron Fries R. Belmont Sean Young smf Steve Baines Steve Ellenoff Sven Gothel Tatsuyuki Satoh The AGEMAME Development Team The MAME team The MESS team Tim Lindner Tony La Porta XelaSoft z80 gaiden Zsolt Vasvari
network-manager-1.35.91/src/core/devices/wwan/nm-device-modem.h
/* SPDX-License-Identifier: GPL-2.0-or-later */ /* * Copyright (C) 2011 Red Hat, Inc. */ #ifndef __NETWORKMANAGER_DEVICE_MODEM_H__ #define __NETWORKMANAGER_DEVICE_MODEM_H__ #include "devices/nm-device.h" #include "nm-modem.h" #define NM_TYPE_DEVICE_MODEM (nm_device_modem_get_type()) #define NM_DEVICE_MODEM(obj) \ (G_TYPE_CHECK_INSTANCE_CAST((obj), NM_TYPE_DEVICE_MODEM, NMDeviceModem)) #define NM_DEVICE_MODEM_CLASS(klass) \ (G_TYPE_CHECK_CLASS_CAST((klass), NM_TYPE_DEVICE_MODEM, NMDeviceModemClass)) #define NM_IS_DEVICE_MODEM(obj) (G_TYPE_CHECK_INSTANCE_TYPE((obj), NM_TYPE_DEVICE_MODEM)) #define NM_IS_DEVICE_MODEM_CLASS(klass) (G_TYPE_CHECK_CLASS_TYPE((klass), NM_TYPE_DEVICE_MODEM)) #define NM_DEVICE_MODEM_GET_CLASS(obj) \ (G_TYPE_INSTANCE_GET_CLASS((obj), NM_TYPE_DEVICE_MODEM, NMDeviceModemClass)) #define NM_DEVICE_MODEM_MODEM "modem" #define NM_DEVICE_MODEM_CAPABILITIES "modem-capabilities" #define NM_DEVICE_MODEM_CURRENT_CAPABILITIES "current-capabilities" #define NM_DEVICE_MODEM_DEVICE_ID "device-id" #define NM_DEVICE_MODEM_OPERATOR_CODE "operator-code" #define NM_DEVICE_MODEM_APN "apn" typedef struct _NMDeviceModem NMDeviceModem; typedef struct _NMDeviceModemClass NMDeviceModemClass; GType nm_device_modem_get_type(void); NMDevice *nm_device_modem_new(NMModem *modem); #endif /* __NETWORKMANAGER_DEVICE_MODEM_H__ */
utf-8
1
GPL-2+
2004 - 2019 Red Hat, Inc. 2005 - 2009 Novell, Inc.
qt3d-opensource-src-5.15.2+dfsg/src/extras/defaults/qnormaldiffusemapalphamaterial.cpp
/**************************************************************************** ** ** Copyright (C) 2014 Klaralvdalens Datakonsult AB (KDAB). ** Contact: https://www.qt.io/licensing/ ** ** This file is part of the Qt3D module of the Qt Toolkit. ** ** $QT_BEGIN_LICENSE:LGPL$ ** Commercial License Usage ** Licensees holding valid commercial Qt licenses may use this file in ** accordance with the commercial license agreement provided with the ** Software or, alternatively, in accordance with the terms contained in ** a written agreement between you and The Qt Company. For licensing terms ** and conditions see https://www.qt.io/terms-conditions. For further ** information use the contact form at https://www.qt.io/contact-us. ** ** GNU Lesser General Public License Usage ** Alternatively, this file may be used under the terms of the GNU Lesser ** General Public License version 3 as published by the Free Software ** Foundation and appearing in the file LICENSE.LGPL3 included in the ** packaging of this file. Please review the following information to ** ensure the GNU Lesser General Public License version 3 requirements ** will be met: https://www.gnu.org/licenses/lgpl-3.0.html. ** ** GNU General Public License Usage ** Alternatively, this file may be used under the terms of the GNU ** General Public License version 2.0 or (at your option) the GNU General ** Public license version 3 or any later version approved by the KDE Free ** Qt Foundation. The licenses are as published by the Free Software ** Foundation and appearing in the file LICENSE.GPL2 and LICENSE.GPL3 ** included in the packaging of this file. Please review the following ** information to ensure the GNU General Public License requirements will ** be met: https://www.gnu.org/licenses/gpl-2.0.html and ** https://www.gnu.org/licenses/gpl-3.0.html. ** ** $QT_END_LICENSE$ ** ****************************************************************************/ #include "qnormaldiffusemapalphamaterial.h" #include "qnormaldiffusemapalphamaterial_p.h" #include <Qt3DRender/qeffect.h> #include <Qt3DRender/qtexture.h> #include <Qt3DRender/qtechnique.h> #include <Qt3DRender/qparameter.h> #include <Qt3DRender/qshaderprogram.h> #include <Qt3DRender/qshaderprogrambuilder.h> #include <Qt3DRender/qrenderpass.h> #include <Qt3DRender/qgraphicsapifilter.h> #include <Qt3DRender/qalphacoverage.h> #include <Qt3DRender/qdepthtest.h> #include <QtCore/QUrl> #include <QtGui/QVector3D> #include <QtGui/QVector4D> QT_BEGIN_NAMESPACE using namespace Qt3DRender; namespace Qt3DExtras { QNormalDiffuseMapAlphaMaterialPrivate::QNormalDiffuseMapAlphaMaterialPrivate() : QNormalDiffuseMapMaterialPrivate() , m_alphaCoverage(new QAlphaCoverage()) , m_depthTest(new QDepthTest()) { } void QNormalDiffuseMapAlphaMaterialPrivate::init() { Q_Q(QNormalDiffuseMapMaterial); connect(m_ambientParameter, &Qt3DRender::QParameter::valueChanged, this, &QNormalDiffuseMapMaterialPrivate::handleAmbientChanged); connect(m_diffuseParameter, &Qt3DRender::QParameter::valueChanged, this, &QNormalDiffuseMapMaterialPrivate::handleDiffuseChanged); connect(m_normalParameter, &Qt3DRender::QParameter::valueChanged, this, &QNormalDiffuseMapMaterialPrivate::handleNormalChanged); connect(m_specularParameter, &Qt3DRender::QParameter::valueChanged, this, &QNormalDiffuseMapMaterialPrivate::handleSpecularChanged); connect(m_shininessParameter, &Qt3DRender::QParameter::valueChanged, this, &QNormalDiffuseMapMaterialPrivate::handleShininessChanged); connect(m_textureScaleParameter, &Qt3DRender::QParameter::valueChanged, this, &QNormalDiffuseMapMaterialPrivate::handleTextureScaleChanged); m_normalDiffuseGL3Shader->setVertexShaderCode(QShaderProgram::loadSource(QUrl(QStringLiteral("qrc:/shaders/gl3/default.vert")))); m_normalDiffuseGL3ShaderBuilder->setParent(q); m_normalDiffuseGL3ShaderBuilder->setShaderProgram(m_normalDiffuseGL3Shader); m_normalDiffuseGL3ShaderBuilder->setFragmentShaderGraph(QUrl(QStringLiteral("qrc:/shaders/graphs/phong.frag.json"))); m_normalDiffuseGL3ShaderBuilder->setEnabledLayers({QStringLiteral("diffuseTexture"), QStringLiteral("specular"), QStringLiteral("normalTexture")}); m_normalDiffuseGL2ES2Shader->setVertexShaderCode(QShaderProgram::loadSource(QUrl(QStringLiteral("qrc:/shaders/es2/default.vert")))); m_normalDiffuseGL2ES2ShaderBuilder->setParent(q); m_normalDiffuseGL2ES2ShaderBuilder->setShaderProgram(m_normalDiffuseGL2ES2Shader); m_normalDiffuseGL2ES2ShaderBuilder->setFragmentShaderGraph(QUrl(QStringLiteral("qrc:/shaders/graphs/phong.frag.json"))); m_normalDiffuseGL2ES2ShaderBuilder->setEnabledLayers({QStringLiteral("diffuseTexture"), QStringLiteral("specular"), QStringLiteral("normalTexture")}); m_normalDiffuseRHIShader->setVertexShaderCode(QShaderProgram::loadSource(QUrl(QStringLiteral("qrc:/shaders/rhi/default.vert")))); m_normalDiffuseRHIShaderBuilder->setParent(q); m_normalDiffuseRHIShaderBuilder->setShaderProgram(m_normalDiffuseRHIShader); m_normalDiffuseRHIShaderBuilder->setFragmentShaderGraph(QUrl(QStringLiteral("qrc:/shaders/graphs/phong.frag.json"))); m_normalDiffuseRHIShaderBuilder->setEnabledLayers({QStringLiteral("diffuseTexture"), QStringLiteral("specular"), QStringLiteral("normalTexture")}); m_normalDiffuseGL3Technique->graphicsApiFilter()->setApi(QGraphicsApiFilter::OpenGL); m_normalDiffuseGL3Technique->graphicsApiFilter()->setMajorVersion(3); m_normalDiffuseGL3Technique->graphicsApiFilter()->setMinorVersion(1); m_normalDiffuseGL3Technique->graphicsApiFilter()->setProfile(QGraphicsApiFilter::CoreProfile); m_normalDiffuseGL2Technique->graphicsApiFilter()->setApi(QGraphicsApiFilter::OpenGL); m_normalDiffuseGL2Technique->graphicsApiFilter()->setMajorVersion(2); m_normalDiffuseGL2Technique->graphicsApiFilter()->setMinorVersion(0); m_normalDiffuseGL2Technique->graphicsApiFilter()->setProfile(QGraphicsApiFilter::NoProfile); m_normalDiffuseES2Technique->graphicsApiFilter()->setApi(QGraphicsApiFilter::OpenGLES); m_normalDiffuseES2Technique->graphicsApiFilter()->setMajorVersion(2); m_normalDiffuseES2Technique->graphicsApiFilter()->setMinorVersion(0); m_normalDiffuseES2Technique->graphicsApiFilter()->setProfile(QGraphicsApiFilter::NoProfile); m_normalDiffuseRHITechnique->graphicsApiFilter()->setApi(QGraphicsApiFilter::RHI); m_normalDiffuseRHITechnique->graphicsApiFilter()->setMajorVersion(1); m_normalDiffuseRHITechnique->graphicsApiFilter()->setMinorVersion(0); m_filterKey->setParent(q); m_filterKey->setName(QStringLiteral("renderingStyle")); m_filterKey->setValue(QStringLiteral("forward")); m_normalDiffuseGL3Technique->addFilterKey(m_filterKey); m_normalDiffuseGL2Technique->addFilterKey(m_filterKey); m_normalDiffuseES2Technique->addFilterKey(m_filterKey); m_normalDiffuseRHITechnique->addFilterKey(m_filterKey); m_depthTest->setDepthFunction(QDepthTest::Less); m_normalDiffuseGL3RenderPass->setShaderProgram(m_normalDiffuseGL3Shader); m_normalDiffuseGL3RenderPass->addRenderState(m_alphaCoverage); m_normalDiffuseGL3RenderPass->addRenderState(m_depthTest); m_normalDiffuseGL2RenderPass->setShaderProgram(m_normalDiffuseGL2ES2Shader); m_normalDiffuseGL2RenderPass->addRenderState(m_alphaCoverage); m_normalDiffuseGL2RenderPass->addRenderState(m_depthTest); m_normalDiffuseES2RenderPass->setShaderProgram(m_normalDiffuseGL2ES2Shader); m_normalDiffuseES2RenderPass->addRenderState(m_alphaCoverage); m_normalDiffuseES2RenderPass->addRenderState(m_depthTest); m_normalDiffuseRHIRenderPass->setShaderProgram(m_normalDiffuseRHIShader); m_normalDiffuseRHIRenderPass->addRenderState(m_alphaCoverage); m_normalDiffuseRHIRenderPass->addRenderState(m_depthTest); m_normalDiffuseGL3Technique->addRenderPass(m_normalDiffuseGL3RenderPass); m_normalDiffuseGL2Technique->addRenderPass(m_normalDiffuseGL2RenderPass); m_normalDiffuseES2Technique->addRenderPass(m_normalDiffuseES2RenderPass); m_normalDiffuseRHITechnique->addRenderPass(m_normalDiffuseRHIRenderPass); m_normalDiffuseEffect->addTechnique(m_normalDiffuseGL3Technique); m_normalDiffuseEffect->addTechnique(m_normalDiffuseGL2Technique); m_normalDiffuseEffect->addTechnique(m_normalDiffuseES2Technique); m_normalDiffuseEffect->addTechnique(m_normalDiffuseRHITechnique); m_normalDiffuseEffect->addParameter(m_ambientParameter); m_normalDiffuseEffect->addParameter(m_diffuseParameter); m_normalDiffuseEffect->addParameter(m_normalParameter); m_normalDiffuseEffect->addParameter(m_specularParameter); m_normalDiffuseEffect->addParameter(m_shininessParameter); m_normalDiffuseEffect->addParameter(m_textureScaleParameter); q->setEffect(m_normalDiffuseEffect); } /*! \class Qt3DExtras::QNormalDiffuseMapAlphaMaterial \brief The QNormalDiffuseMapAlphaMaterial provides a specialization of QNormalDiffuseMapMaterial with alpha coverage and a depth test performed in the rendering pass. \inmodule Qt3DExtras \since 5.7 \inherits Qt3DExtras::QNormalDiffuseMapMaterial \deprecated This class is deprecated; use Qt3DExtras::QDiffuseSpecularMaterial instead. The specular lighting effect is based on the combination of 3 lighting components ambient, diffuse and specular. The relative strengths of these components are controlled by means of their reflectivity coefficients which are modelled as RGB triplets: \list \li Ambient is the color that is emitted by an object without any other light source. \li Diffuse is the color that is emitted for rought surface reflections with the lights. \li Specular is the color emitted for shiny surface reflections with the lights. \li The shininess of a surface is controlled by a float property. \endlist This material uses an effect with a single render pass approach and performs per fragment lighting. Techniques are provided for OpenGL 2, OpenGL 3 or above as well as OpenGL ES 2. */ /*! Constructs a new QNormalDiffuseMapAlphaMaterial instance with parent object \a parent. */ QNormalDiffuseMapAlphaMaterial::QNormalDiffuseMapAlphaMaterial(QNode *parent) : QNormalDiffuseMapMaterial(*new QNormalDiffuseMapAlphaMaterialPrivate, parent) { } /*! Destroys the QNormalDiffuseMapAlphaMaterial instance. */ QNormalDiffuseMapAlphaMaterial::~QNormalDiffuseMapAlphaMaterial() { } } // namespace Qt3DRender QT_END_NAMESPACE
utf-8
1
LGPL-3 or GPL-2
2013 Research In Motion 2014-2020 Klarälvdalens Datakonsult AB (KDAB) 2015-2018 The Qt Company Ltd and/or its subsidiary(-ies) 2013 Dmitrii Kosarev aka Kakadu <kakadu.hafanana@gmail.com> 2015 Konstantin Ritt 2015 Lorenz Esch (TU Ilmenau) 2015-2016 Paul Lemire <paul.lemire350@gmail.com> 2016 Svenn-Arne Dragly 2017 Juan José Casafranca 2019 Ford Motor Company
ghc-8.8.4/rts/WSDeque.h
/* ----------------------------------------------------------------------------- * * (c) The GHC Team, 2009 * * Work-stealing Deque data structure * * ---------------------------------------------------------------------------*/ #pragma once typedef struct WSDeque_ { // Size of elements array. Used for modulo calculation: we round up // to powers of 2 and use the dyadic log (modulo == bitwise &) StgWord size; StgWord moduloSize; /* bitmask for modulo */ // top, index where multiple readers steal() (protected by a cas) volatile StgWord top; // bottom, index of next free place where one writer can push // elements. This happens unsynchronised. volatile StgWord bottom; // both top and bottom are continuously incremented, and used as // an index modulo the current array size. // lower bound on the current top value. This is an internal // optimisation to avoid unnecessarily accessing the top field // inside pushBottom volatile StgWord topBound; // The elements array void ** elements; // Please note: the dataspace cannot follow the admin fields // immediately, as it should be possible to enlarge it without // disposing the old one automatically (as realloc would)! } WSDeque; /* INVARIANTS, in this order: reasonable size, topBound consistent, space pointer, space accessible to us. NB. This is safe to use only (a) on a spark pool owned by the current thread, or (b) when there's only one thread running, or no stealing going on (e.g. during GC). */ #define ASSERT_WSDEQUE_INVARIANTS(p) \ ASSERT((p)->size > 0); \ ASSERT((p)->topBound <= (p)->top); \ ASSERT((p)->elements != NULL); \ ASSERT(*((p)->elements) || 1); \ ASSERT(*((p)->elements - 1 + ((p)->size)) || 1); // No: it is possible that top > bottom when using pop() // ASSERT((p)->bottom >= (p)->top); // ASSERT((p)->size > (p)->bottom - (p)->top); /* ----------------------------------------------------------------------------- * Operations * * A WSDeque has an *owner* thread. The owner can perform any operation; * other threads are only allowed to call stealWSDeque_(), * stealWSDeque(), looksEmptyWSDeque(), and dequeElements(). * * -------------------------------------------------------------------------- */ // Allocation, deallocation WSDeque * newWSDeque (uint32_t size); void freeWSDeque (WSDeque *q); // Take an element from the "write" end of the pool. Can be called // by the pool owner only. void* popWSDeque (WSDeque *q); // Push onto the "write" end of the pool. Return true if the push // succeeded, or false if the deque is full. bool pushWSDeque (WSDeque *q, void *elem); // Removes all elements from the deque EXTERN_INLINE void discardElements (WSDeque *q); // Removes an element of the deque from the "read" end, or returns // NULL if the pool is empty, or if there was a collision with another // thief. void * stealWSDeque_ (WSDeque *q); // Removes an element of the deque from the "read" end, or returns // NULL if the pool is empty. void * stealWSDeque (WSDeque *q); // "guesses" whether a deque is empty. Can return false negatives in // presence of concurrent steal() calls, and false positives in // presence of a concurrent pushBottom(). EXTERN_INLINE bool looksEmptyWSDeque (WSDeque* q); EXTERN_INLINE long dequeElements (WSDeque *q); /* ----------------------------------------------------------------------------- * PRIVATE below here * -------------------------------------------------------------------------- */ EXTERN_INLINE long dequeElements (WSDeque *q) { StgWord t = q->top; StgWord b = q->bottom; // try to prefer false negatives by reading top first return ((long)b - (long)t); } EXTERN_INLINE bool looksEmptyWSDeque (WSDeque *q) { return (dequeElements(q) <= 0); } EXTERN_INLINE void discardElements (WSDeque *q) { q->top = q->bottom; // pool->topBound = pool->top; }
utf-8
1
BSD-3-clause
2007 Andy Gill 2006 Esa Ilari Vuokko 2007 Ian Lynagh 2009 Isaac Dupree 2010 Jargen Nicklisch-Franken 2008 Jose Iborra 2008 Lennart Kolmodin 1997-2003 Alastair Reid 2009 Andres Loeh 2007 Bjorn Bringert 2007-2014 Bryan O'Sullivan 1999-2001 Daan Leijner 2005 David Himmelstrup 2006-2010 David Waern 2007-2009,2012-2013 Duncan Coutts 2003-2007 Isaac Jones 2011 Johan Tibell 2003-2005 Malcolm Wallace 2004 Martin Sjgren 2004,2013-2014 Mateusz Kowalczyk 1993-1995 Microsoft Coprporation 2006-2008 Neil Mitchell 2002-2012 Simon Marlow 1995-2014 The GHC Team 1993-2013 The University of Glasgow 2010,2011 Thomas Tuegel
ugene-40.1+dfsg/src/corelibs/U2Core/src/datatype/UdrSchemaRegistry.cpp
/** * UGENE - Integrated Bioinformatics Tools. * Copyright (C) 2008-2021 UniPro <ugene@unipro.ru> * http://ugene.net * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, * MA 02110-1301, USA. */ #include "UdrSchemaRegistry.h" #include <QRegExp> #include <U2Core/U2OpStatusUtils.h> #include <U2Core/U2SafePoints.h> namespace U2 { UdrSchemaRegistry::UdrSchemaRegistry() : mutex(QMutex::Recursive) { } UdrSchemaRegistry::~UdrSchemaRegistry() { qDeleteAll(schemas.values()); } void UdrSchemaRegistry::registerSchema(const UdrSchema *schema, U2OpStatus &os) { QMutexLocker lock(&mutex); CHECK_EXT(nullptr != schema, os.setError("NULL schema"), ); CHECK_EXT(isCorrectName(schema->getId()), os.setError("Incorrect schema id"), ); CHECK_EXT(!schemas.contains(schema->getId()), os.setError("Duplicate schema id"), ); schemas[schema->getId()] = schema; } QList<UdrSchemaId> UdrSchemaRegistry::getRegisteredSchemas() const { QMutexLocker lock(&mutex); return schemas.keys(); } const UdrSchema *UdrSchemaRegistry::getSchemaById(const UdrSchemaId &id) const { QMutexLocker lock(&mutex); return schemas.value(id, nullptr); } bool UdrSchemaRegistry::isCorrectName(const QByteArray &name) { QRegExp regExp("([A-z]|_)([A-z]|_|\\d)*"); return regExp.exactMatch(name); } } // namespace U2
utf-8
1
GPL-2+
© 2008-2015 UniPro <ugene@unipro.ru>
ion-3.2.1+dfsg/nm/agent/adm_ltp_priv.c
/****************************************************************************** ** COPYRIGHT NOTICE ** (c) 2012 The Johns Hopkins University Applied Physics Laboratory ** All rights reserved. ** ** This material may only be used, modified, or reproduced by or for the ** U.S. Government pursuant to the license rights granted under ** FAR clause 52.227-14 or DFARS clauses 252.227-7013/7014 ** ** For any other permissions, please contact the Legal Office at JHU/APL. ******************************************************************************/ #ifdef _HAVE_LTP_ADM_ /***************************************************************************** ** ** File Name: adm_ltp_priv.c ** ** Description: This implements the private aspects of a LTP ADM. ** ** Notes: ** ** Assumptions: ** ** ** Modification History: ** MM/DD/YY AUTHOR DESCRIPTION ** -------- ------------ --------------------------------------------- ** 07/16/13 E. Birrane Initial Implementation *****************************************************************************/ #include "platform.h" #include "ion.h" #include "shared/utils/utils.h" #include "shared/adm/adm_ltp.h" #include "adm_ltp_priv.h" void agent_adm_init_ltp() { uint8_t mid_str[ADM_MID_ALLOC]; adm_build_mid_str(0x00, ADM_LTP_NODE_NN, ADM_LTP_NODE_NN_LEN, 0, mid_str); adm_add_datadef_collect(mid_str, ltp_get_node_resources_all); adm_build_mid_str(0x00, ADM_LTP_NODE_NN, ADM_LTP_NODE_NN_LEN, 1, mid_str); adm_add_datadef_collect(mid_str, ltp_get_heap_bytes_reserved); adm_build_mid_str(0x00, ADM_LTP_NODE_NN, ADM_LTP_NODE_NN_LEN, 2, mid_str); adm_add_datadef_collect(mid_str, ltp_get_heap_bytes_used); adm_build_mid_str(0x00, ADM_LTP_NODE_NN, ADM_LTP_NODE_NN_LEN, 3, mid_str); adm_add_datadef_collect(mid_str, ltp_get_engines); adm_build_mid_str(0x40, ADM_LTP_ENGINE_NN, ADM_LTP_ENGINE_NN_LEN, 0, mid_str); adm_add_datadef_collect(mid_str, ltp_get_eng_all); adm_build_mid_str(0x40, ADM_LTP_ENGINE_NN, ADM_LTP_ENGINE_NN_LEN, 1, mid_str); adm_add_datadef_collect(mid_str, ltp_get_eng_num); adm_build_mid_str(0x40, ADM_LTP_ENGINE_NN, ADM_LTP_ENGINE_NN_LEN, 2, mid_str); adm_add_datadef_collect(mid_str, ltp_get_eng_exp_sess); adm_build_mid_str(0x40, ADM_LTP_ENGINE_NN, ADM_LTP_ENGINE_NN_LEN, 3, mid_str); adm_add_datadef_collect(mid_str, ltp_get_eng_cur_out_seg); adm_build_mid_str(0x40, ADM_LTP_ENGINE_NN, ADM_LTP_ENGINE_NN_LEN, 4, mid_str); adm_add_datadef_collect(mid_str, ltp_get_eng_cur_imp_sess); adm_build_mid_str(0x40, ADM_LTP_ENGINE_NN, ADM_LTP_ENGINE_NN_LEN, 5, mid_str); adm_add_datadef_collect(mid_str, ltp_get_eng_cur_in_seg); adm_build_mid_str(0x40, ADM_LTP_ENGINE_NN, ADM_LTP_ENGINE_NN_LEN, 6, mid_str); adm_add_datadef_collect(mid_str, ltp_get_eng_last_reset_time); adm_build_mid_str(0x40, ADM_LTP_ENGINE_NN, ADM_LTP_ENGINE_NN_LEN, 7, mid_str); adm_add_datadef_collect(mid_str, ltp_get_eng_out_seg_q_cnt); adm_build_mid_str(0x40, ADM_LTP_ENGINE_NN, ADM_LTP_ENGINE_NN_LEN, 8, mid_str); adm_add_datadef_collect(mid_str, ltp_get_eng_out_seg_q_byte); adm_build_mid_str(0x40, ADM_LTP_ENGINE_NN, ADM_LTP_ENGINE_NN_LEN, 9, mid_str); adm_add_datadef_collect(mid_str, ltp_get_eng_out_seg_pop_cnt); adm_build_mid_str(0x40, ADM_LTP_ENGINE_NN, ADM_LTP_ENGINE_NN_LEN, 10, mid_str); adm_add_datadef_collect(mid_str, ltp_get_eng_out_seg_pop_byte); adm_build_mid_str(0x40, ADM_LTP_ENGINE_NN, ADM_LTP_ENGINE_NN_LEN, 11, mid_str); adm_add_datadef_collect(mid_str, ltp_get_eng_out_ckp_xmit_cnt); adm_build_mid_str(0x40, ADM_LTP_ENGINE_NN, ADM_LTP_ENGINE_NN_LEN, 12, mid_str); adm_add_datadef_collect(mid_str, ltp_get_eng_out_pos_ack_rcv_cnt); adm_build_mid_str(0x40, ADM_LTP_ENGINE_NN, ADM_LTP_ENGINE_NN_LEN, 13, mid_str); adm_add_datadef_collect(mid_str, ltp_get_eng_out_neg_ack_rcv_cnt); adm_build_mid_str(0x40, ADM_LTP_ENGINE_NN, ADM_LTP_ENGINE_NN_LEN, 14, mid_str); adm_add_datadef_collect(mid_str, ltp_get_eng_out_canc_rcv_cnt); adm_build_mid_str(0x40, ADM_LTP_ENGINE_NN, ADM_LTP_ENGINE_NN_LEN, 15, mid_str); adm_add_datadef_collect(mid_str, ltp_get_eng_out_ckp_rexmt_cnt); adm_build_mid_str(0x40, ADM_LTP_ENGINE_NN, ADM_LTP_ENGINE_NN_LEN, 16, mid_str); adm_add_datadef_collect(mid_str, ltp_get_eng_out_canc_xmit_cnt); adm_build_mid_str(0x40, ADM_LTP_ENGINE_NN, ADM_LTP_ENGINE_NN_LEN, 17, mid_str); adm_add_datadef_collect(mid_str, ltp_get_eng_out_compl_cnt); adm_build_mid_str(0x40, ADM_LTP_ENGINE_NN, ADM_LTP_ENGINE_NN_LEN, 18, mid_str); adm_add_datadef_collect(mid_str, ltp_get_eng_in_seg_rcv_red_cnt); adm_build_mid_str(0x40, ADM_LTP_ENGINE_NN, ADM_LTP_ENGINE_NN_LEN, 19, mid_str); adm_add_datadef_collect(mid_str, ltp_get_eng_in_seg_rcv_red_byte); adm_build_mid_str(0x40, ADM_LTP_ENGINE_NN, ADM_LTP_ENGINE_NN_LEN, 20, mid_str); adm_add_datadef_collect(mid_str, ltp_get_eng_in_seg_rcv_grn_cnt); adm_build_mid_str(0x40, ADM_LTP_ENGINE_NN, ADM_LTP_ENGINE_NN_LEN, 21, mid_str); adm_add_datadef_collect(mid_str, ltp_get_eng_in_seg_rcv_grn_byte); adm_build_mid_str(0x40, ADM_LTP_ENGINE_NN, ADM_LTP_ENGINE_NN_LEN, 22, mid_str); adm_add_datadef_collect(mid_str, ltp_get_eng_in_seg_rdndt_cnt); adm_build_mid_str(0x40, ADM_LTP_ENGINE_NN, ADM_LTP_ENGINE_NN_LEN, 23, mid_str); adm_add_datadef_collect(mid_str, ltp_get_eng_in_seg_rdndt_byte); adm_build_mid_str(0x40, ADM_LTP_ENGINE_NN, ADM_LTP_ENGINE_NN_LEN, 24, mid_str); adm_add_datadef_collect(mid_str, ltp_get_eng_in_seg_mal_cnt); adm_build_mid_str(0x40, ADM_LTP_ENGINE_NN, ADM_LTP_ENGINE_NN_LEN, 25, mid_str); adm_add_datadef_collect(mid_str, ltp_get_eng_in_seg_mal_byte); adm_build_mid_str(0x40, ADM_LTP_ENGINE_NN, ADM_LTP_ENGINE_NN_LEN, 26, mid_str); adm_add_datadef_collect(mid_str, ltp_get_eng_in_seg_unk_snd_cnt); adm_build_mid_str(0x40, ADM_LTP_ENGINE_NN, ADM_LTP_ENGINE_NN_LEN, 27, mid_str); adm_add_datadef_collect(mid_str, ltp_get_eng_in_seg_unk_snd_byte); adm_build_mid_str(0x40, ADM_LTP_ENGINE_NN, ADM_LTP_ENGINE_NN_LEN, 28, mid_str); adm_add_datadef_collect(mid_str, ltp_get_eng_in_seg_unk_cli_cnt); adm_build_mid_str(0x40, ADM_LTP_ENGINE_NN, ADM_LTP_ENGINE_NN_LEN, 29, mid_str); adm_add_datadef_collect(mid_str, ltp_get_eng_in_seg_unk_cli_byte); adm_build_mid_str(0x40, ADM_LTP_ENGINE_NN, ADM_LTP_ENGINE_NN_LEN, 30, mid_str); adm_add_datadef_collect(mid_str, ltp_get_eng_in_seg_stray_cnt); adm_build_mid_str(0x40, ADM_LTP_ENGINE_NN, ADM_LTP_ENGINE_NN_LEN, 31, mid_str); adm_add_datadef_collect(mid_str, ltp_get_eng_in_seg_stray_byte); adm_build_mid_str(0x40, ADM_LTP_ENGINE_NN, ADM_LTP_ENGINE_NN_LEN, 32, mid_str); adm_add_datadef_collect(mid_str, ltp_get_eng_in_seg_miscol_cnt); adm_build_mid_str(0x40, ADM_LTP_ENGINE_NN, ADM_LTP_ENGINE_NN_LEN, 33, mid_str); adm_add_datadef_collect(mid_str, ltp_get_eng_in_seg_miscol_byte); adm_build_mid_str(0x40, ADM_LTP_ENGINE_NN, ADM_LTP_ENGINE_NN_LEN, 34, mid_str); adm_add_datadef_collect(mid_str, ltp_get_eng_in_seg_clsd_cnt); adm_build_mid_str(0x40, ADM_LTP_ENGINE_NN, ADM_LTP_ENGINE_NN_LEN, 35, mid_str); adm_add_datadef_collect(mid_str, ltp_get_eng_in_seg_clsd_byte); adm_build_mid_str(0x40, ADM_LTP_ENGINE_NN, ADM_LTP_ENGINE_NN_LEN, 36, mid_str); adm_add_datadef_collect(mid_str, ltp_get_eng_in_ckp_rcv_cnt); adm_build_mid_str(0x40, ADM_LTP_ENGINE_NN, ADM_LTP_ENGINE_NN_LEN, 37, mid_str); adm_add_datadef_collect(mid_str, ltp_get_eng_in_pos_ack_xmit_cnt); adm_build_mid_str(0x40, ADM_LTP_ENGINE_NN, ADM_LTP_ENGINE_NN_LEN, 38, mid_str); adm_add_datadef_collect(mid_str, ltp_get_eng_in_neg_ack_xmit_cnt); adm_build_mid_str(0x40, ADM_LTP_ENGINE_NN, ADM_LTP_ENGINE_NN_LEN, 39, mid_str); adm_add_datadef_collect(mid_str, ltp_get_eng_in_canc_xmit_cnt); adm_build_mid_str(0x40, ADM_LTP_ENGINE_NN, ADM_LTP_ENGINE_NN_LEN, 40, mid_str); adm_add_datadef_collect(mid_str, ltp_get_eng_in_ack_rexmt_cnt); adm_build_mid_str(0x40, ADM_LTP_ENGINE_NN, ADM_LTP_ENGINE_NN_LEN, 41, mid_str); adm_add_datadef_collect(mid_str, ltp_get_eng_in_canc_rcv_cnt); adm_build_mid_str(0x40, ADM_LTP_ENGINE_NN, ADM_LTP_ENGINE_NN_LEN, 42, mid_str); adm_add_datadef_collect(mid_str, ltp_get_eng_in_compl_cnt); adm_build_mid_str(0x41, ADM_LTP_CTRL_NN, ADM_LTP_CTRL_NN_LEN, 0, mid_str); adm_add_ctrl_run(mid_str, ltp_engine_reset); } /* Get Functions */ expr_result_t ltp_get_node_resources_all(Lyst params) { unsigned long bytes_reserved = 0; unsigned long bytes_used = 0; expr_result_t result; result.type = EXPR_TYPE_BLOB; ltpnm_resources(&bytes_reserved, &bytes_used); result.length = sizeof(unsigned long) * 2; result.value = (uint8_t*) MTAKE(result.length); memcpy(result.value, &bytes_reserved, sizeof(bytes_reserved)); memcpy(&(result.value[sizeof(bytes_reserved)]), &bytes_used, sizeof(bytes_used)); return result; } expr_result_t ltp_get_heap_bytes_reserved(Lyst params) { unsigned long bytes_reserved = 0; unsigned long bytes_used = 0; expr_result_t result; result.type = EXPR_TYPE_UINT32; ltpnm_resources(&bytes_reserved, &bytes_used); result.length = sizeof(unsigned long); result.value = (uint8_t*) MTAKE(result.length); memcpy(result.value, &bytes_reserved, sizeof(bytes_reserved)); return result; } expr_result_t ltp_get_heap_bytes_used(Lyst params) { unsigned long bytes_reserved = 0; unsigned long bytes_used = 0; expr_result_t result; result.type = EXPR_TYPE_UINT32; ltpnm_resources(&bytes_reserved, &bytes_used); result.length = sizeof(unsigned long); result.value = (uint8_t*) MTAKE(result.length); memcpy(result.value, &bytes_used, sizeof(bytes_used)); return result; } expr_result_t ltp_get_engines(Lyst params) { unsigned int ids[32]; uint8_t *cursor = NULL; int num = 0; unsigned long val = 0; Sdnv num_sdnv; expr_result_t result; result.type = EXPR_TYPE_BLOB; ltpnm_spanEngineIds_get(ids, &num); if(num > 32) { fprintf(stderr,"We do not support more than 32 engines. Aborting.\n"); exit(1); } encodeSdnv(&num_sdnv, num); result.length = num_sdnv.length + /* NUM as SDNV length */ (num * sizeof(unsigned long)); result.value = (uint8_t *) MTAKE(result.length); cursor = result.value; memcpy(cursor,num_sdnv.text, num_sdnv.length); cursor += num_sdnv.length; for(int i = 0; i < num; i++) { val = ids[i]; memcpy(cursor,&val, sizeof(val)); cursor += sizeof(val); } return result; } expr_result_t ltp_get_eng_all(Lyst params) { datacol_entry_t *entry = (datacol_entry_t*)lyst_data(lyst_first(params)); unsigned long val = 0; unsigned int engineId = 0; expr_result_t result; result.type = EXPR_TYPE_UINT32; /* \todo: Check for NULL entry here. */ NmltpSpan span; int success = 0; memcpy(&val, entry->value, sizeof(val)); engineId = val; result.length = 0; result.value = NULL; ltpnm_span_get(engineId, &span, &success); if(success != 0) { result.value = (uint8_t*) MTAKE(sizeof(span)); memcpy(result.value, &span, sizeof(span)); result.length = sizeof(span); } return result; } expr_result_t ltp_get_eng_num(Lyst params) { datacol_entry_t *entry = (datacol_entry_t*)lyst_data(lyst_first(params)); unsigned long val = 0; unsigned int engineId = 0; expr_result_t result; result.type = EXPR_TYPE_UINT32; /* \todo: Check for NULL entry here. */ NmltpSpan span; int success = 0; memcpy(&val, entry->value, sizeof(val)); engineId = val; result.length = 0; result.value = NULL; ltpnm_span_get(engineId, &span, &success); if(success != 0) { val = span.remoteEngineNbr; result.value = adm_copy_integer((uint8_t*)&val, sizeof(val), &(result.length)); } return result; } expr_result_t ltp_get_eng_exp_sess(Lyst params) { datacol_entry_t *entry = (datacol_entry_t*)lyst_data(lyst_first(params)); unsigned long val = 0; unsigned int engineId = 0; expr_result_t result; result.type = EXPR_TYPE_UINT32; /* \todo: Check for NULL entry here. */ NmltpSpan span; int success = 0; memcpy(&val, entry->value, sizeof(val)); engineId = val; result.length = 0; result.value = NULL; ltpnm_span_get(engineId, &span, &success); if(success != 0) { val = span.currentExportSessions; result.value = adm_copy_integer((uint8_t*)&val, sizeof(val), &(result.length)); } return result; } expr_result_t ltp_get_eng_cur_out_seg(Lyst params) { datacol_entry_t *entry = (datacol_entry_t*)lyst_data(lyst_first(params)); unsigned long val = 0; unsigned int engineId = 0; expr_result_t result; result.type = EXPR_TYPE_UINT32; /* \todo: Check for NULL entry here. */ NmltpSpan span; int success = 0; memcpy(&val, entry->value, sizeof(val)); engineId = val; result.length = 0; result.value = NULL; ltpnm_span_get(engineId, &span, &success); if(success != 0) { val = span.currentOutboundSegments; result.value = adm_copy_integer((uint8_t*)&val, sizeof(val), &(result.length)); } return result; } expr_result_t ltp_get_eng_cur_imp_sess(Lyst params) { datacol_entry_t *entry = (datacol_entry_t*)lyst_data(lyst_first(params)); unsigned long val = 0; unsigned int engineId = 0; expr_result_t result; result.type = EXPR_TYPE_UINT32; /* \todo: Check for NULL entry here. */ NmltpSpan span; int success = 0; memcpy(&val, entry->value, sizeof(val)); engineId = val; result.length = 0; result.value = NULL; ltpnm_span_get(engineId, &span, &success); if(success != 0) { val = span.currentImportSessions; result.value = adm_copy_integer((uint8_t*)&val, sizeof(val), &(result.length)); } return result; } expr_result_t ltp_get_eng_cur_in_seg(Lyst params) { datacol_entry_t *entry = (datacol_entry_t*)lyst_data(lyst_first(params)); unsigned long val = 0; unsigned int engineId = 0; expr_result_t result; result.type = EXPR_TYPE_UINT32; /* \todo: Check for NULL entry here. */ NmltpSpan span; int success = 0; memcpy(&val, entry->value, sizeof(val)); engineId = val; result.length = 0; result.value = NULL; ltpnm_span_get(engineId, &span, &success); if(success != 0) { val = span.currentInboundSegments; result.value = adm_copy_integer((uint8_t*)&val, sizeof(val), &(result.length)); } return result; } expr_result_t ltp_get_eng_last_reset_time(Lyst params) { datacol_entry_t *entry = (datacol_entry_t*)lyst_data(lyst_first(params)); unsigned long val = 0; unsigned int engineId = 0; expr_result_t result; result.type = EXPR_TYPE_UINT32; /* \todo: Check for NULL entry here. */ NmltpSpan span; int success = 0; memcpy(&val, entry->value, sizeof(val)); engineId = val; result.length = 0; result.value = NULL; ltpnm_span_get(engineId, &span, &success); if(success != 0) { val = span.lastResetTime; result.value = adm_copy_integer((uint8_t*)&val, sizeof(val), &(result.length)); } return result; } expr_result_t ltp_get_eng_out_seg_q_cnt(Lyst params) { datacol_entry_t *entry = (datacol_entry_t*)lyst_data(lyst_first(params)); unsigned long val = 0; unsigned int engineId = 0; expr_result_t result; result.type = EXPR_TYPE_UINT32; /* \todo: Check for NULL entry here. */ NmltpSpan span; int success = 0; memcpy(&val, entry->value, sizeof(val)); engineId = val; result.length = 0; result.value = NULL; ltpnm_span_get(engineId, &span, &success); if(success != 0) { val = span.outputSegQueuedCount; result.value = adm_copy_integer((uint8_t*)&val, sizeof(val), &(result.length)); } return result; } expr_result_t ltp_get_eng_out_seg_q_byte(Lyst params) { datacol_entry_t *entry = (datacol_entry_t*)lyst_data(lyst_first(params)); unsigned long val = 0; unsigned int engineId = 0; expr_result_t result; result.type = EXPR_TYPE_UINT32; /* \todo: Check for NULL entry here. */ NmltpSpan span; int success = 0; memcpy(&val, entry->value, sizeof(val)); engineId = val; result.length = 0; result.value = NULL; ltpnm_span_get(engineId, &span, &success); if(success != 0) { val = span.outputSegQueuedBytes; result.value = adm_copy_integer((uint8_t*)&val, sizeof(val), &(result.length)); } return result; } expr_result_t ltp_get_eng_out_seg_pop_cnt(Lyst params) { datacol_entry_t *entry = (datacol_entry_t*)lyst_data(lyst_first(params)); unsigned long val = 0; unsigned int engineId = 0; expr_result_t result; result.type = EXPR_TYPE_UINT32; /* \todo: Check for NULL entry here. */ NmltpSpan span; int success = 0; memcpy(&val, entry->value, sizeof(val)); engineId = val; result.length = 0; result.value = NULL; ltpnm_span_get(engineId, &span, &success); if(success != 0) { val = span.outputSegPoppedCount; result.value = adm_copy_integer((uint8_t*)&val, sizeof(val), &(result.length)); } return result; } expr_result_t ltp_get_eng_out_seg_pop_byte(Lyst params) { datacol_entry_t *entry = (datacol_entry_t*)lyst_data(lyst_first(params)); unsigned long val = 0; unsigned int engineId = 0; expr_result_t result; result.type = EXPR_TYPE_UINT32; /* \todo: Check for NULL entry here. */ NmltpSpan span; int success = 0; memcpy(&val, entry->value, sizeof(val)); engineId = val; result.length = 0; result.value = NULL; ltpnm_span_get(engineId, &span, &success); if(success != 0) { val = span.outputSegPoppedBytes; result.value = adm_copy_integer((uint8_t*)&val, sizeof(val), &(result.length)); } return result; } expr_result_t ltp_get_eng_out_ckp_xmit_cnt(Lyst params) { datacol_entry_t *entry = (datacol_entry_t*)lyst_data(lyst_first(params)); unsigned long val = 0; unsigned int engineId = 0; expr_result_t result; result.type = EXPR_TYPE_UINT32; /* \todo: Check for NULL entry here. */ NmltpSpan span; int success = 0; memcpy(&val, entry->value, sizeof(val)); engineId = val; result.length = 0; result.value = NULL; ltpnm_span_get(engineId, &span, &success); if(success != 0) { val = span.outputCkptXmitCount; result.value = adm_copy_integer((uint8_t*)&val, sizeof(val), &(result.length)); } return result; } expr_result_t ltp_get_eng_out_pos_ack_rcv_cnt(Lyst params) { datacol_entry_t *entry = (datacol_entry_t*)lyst_data(lyst_first(params)); unsigned long val = 0; unsigned int engineId = 0; expr_result_t result; result.type = EXPR_TYPE_UINT32; /* \todo: Check for NULL entry here. */ NmltpSpan span; int success = 0; memcpy(&val, entry->value, sizeof(val)); engineId = val; result.length = 0; result.value = NULL; ltpnm_span_get(engineId, &span, &success); if(success != 0) { val = span.outputPosAckRecvCount; result.value = adm_copy_integer((uint8_t*)&val, sizeof(val), &(result.length)); } return result; } expr_result_t ltp_get_eng_out_neg_ack_rcv_cnt(Lyst params) { datacol_entry_t *entry = (datacol_entry_t*)lyst_data(lyst_first(params)); unsigned long val = 0; unsigned int engineId = 0; expr_result_t result; result.type = EXPR_TYPE_UINT32; /* \todo: Check for NULL entry here. */ NmltpSpan span; int success = 0; memcpy(&val, entry->value, sizeof(val)); engineId = val; result.length = 0; result.value = NULL; ltpnm_span_get(engineId, &span, &success); if(success != 0) { val = span.outputNegAckRecvCount; result.value = adm_copy_integer((uint8_t*)&val, sizeof(val), &(result.length)); } return result; } expr_result_t ltp_get_eng_out_canc_rcv_cnt(Lyst params) { datacol_entry_t *entry = (datacol_entry_t*)lyst_data(lyst_first(params)); unsigned long val = 0; unsigned int engineId = 0; expr_result_t result; result.type = EXPR_TYPE_UINT32; /* \todo: Check for NULL entry here. */ NmltpSpan span; int success = 0; memcpy(&val, entry->value, sizeof(val)); engineId = val; result.length = 0; result.value = NULL; ltpnm_span_get(engineId, &span, &success); if(success != 0) { val = span.outputCancelRecvCount; result.value = adm_copy_integer((uint8_t*)&val, sizeof(val), &(result.length)); } return result; } expr_result_t ltp_get_eng_out_ckp_rexmt_cnt(Lyst params) { datacol_entry_t *entry = (datacol_entry_t*)lyst_data(lyst_first(params)); unsigned long val = 0; unsigned int engineId = 0; expr_result_t result; result.type = EXPR_TYPE_UINT32; /* \todo: Check for NULL entry here. */ NmltpSpan span; int success = 0; memcpy(&val, entry->value, sizeof(val)); engineId = val; result.length = 0; result.value = NULL; ltpnm_span_get(engineId, &span, &success); if(success != 0) { val = span.outputCkptReXmitCount; result.value = adm_copy_integer((uint8_t*)&val, sizeof(val), &(result.length)); } return result; } expr_result_t ltp_get_eng_out_canc_xmit_cnt(Lyst params) { datacol_entry_t *entry = (datacol_entry_t*)lyst_data(lyst_first(params)); unsigned long val = 0; unsigned int engineId = 0; expr_result_t result; result.type = EXPR_TYPE_UINT32; /* \todo: Check for NULL entry here. */ NmltpSpan span; int success = 0; memcpy(&val, entry->value, sizeof(val)); engineId = val; result.length = 0; result.value = NULL; ltpnm_span_get(engineId, &span, &success); if(success != 0) { val = span.outputCancelXmitCount; result.value = adm_copy_integer((uint8_t*)&val, sizeof(val), &(result.length)); } return result; } expr_result_t ltp_get_eng_out_compl_cnt(Lyst params) { datacol_entry_t *entry = (datacol_entry_t*)lyst_data(lyst_first(params)); unsigned long val = 0; unsigned int engineId = 0; expr_result_t result; result.type = EXPR_TYPE_UINT32; /* \todo: Check for NULL entry here. */ NmltpSpan span; int success = 0; memcpy(&val, entry->value, sizeof(val)); engineId = val; result.length = 0; result.value = NULL; ltpnm_span_get(engineId, &span, &success); if(success != 0) { val = span.outputCompleteCount; result.value = adm_copy_integer((uint8_t*)&val, sizeof(val), &(result.length)); } return result; } expr_result_t ltp_get_eng_in_seg_rcv_red_cnt(Lyst params) { datacol_entry_t *entry = (datacol_entry_t*)lyst_data(lyst_first(params)); unsigned long val = 0; unsigned int engineId = 0; expr_result_t result; result.type = EXPR_TYPE_UINT32; /* \todo: Check for NULL entry here. */ NmltpSpan span; int success = 0; memcpy(&val, entry->value, sizeof(val)); engineId = val; result.length = 0; result.value = NULL; ltpnm_span_get(engineId, &span, &success); if(success != 0) { val = span.inputSegRecvRedCount; result.value = adm_copy_integer((uint8_t*)&val, sizeof(val), &(result.length)); } return result; } expr_result_t ltp_get_eng_in_seg_rcv_red_byte(Lyst params) { datacol_entry_t *entry = (datacol_entry_t*)lyst_data(lyst_first(params)); unsigned long val = 0; unsigned int engineId = 0; expr_result_t result; result.type = EXPR_TYPE_UINT32; /* \todo: Check for NULL entry here. */ NmltpSpan span; int success = 0; memcpy(&val, entry->value, sizeof(val)); engineId = val; result.length = 0; result.value = NULL; ltpnm_span_get(engineId, &span, &success); if(success != 0) { val = span.inputSegRecvRedBytes; result.value = adm_copy_integer((uint8_t*)&val, sizeof(val), &(result.length)); } return result; } expr_result_t ltp_get_eng_in_seg_rcv_grn_cnt(Lyst params) { datacol_entry_t *entry = (datacol_entry_t*)lyst_data(lyst_first(params)); unsigned long val = 0; unsigned int engineId = 0; expr_result_t result; result.type = EXPR_TYPE_UINT32; /* \todo: Check for NULL entry here. */ NmltpSpan span; int success = 0; memcpy(&val, entry->value, sizeof(val)); engineId = val; result.length = 0; result.value = NULL; ltpnm_span_get(engineId, &span, &success); if(success != 0) { val = span.inputSegRecvGreenCount; result.value = adm_copy_integer((uint8_t*)&val, sizeof(val), &(result.length)); } return result; } expr_result_t ltp_get_eng_in_seg_rcv_grn_byte(Lyst params) { datacol_entry_t *entry = (datacol_entry_t*)lyst_data(lyst_first(params)); unsigned long val = 0; unsigned int engineId = 0; expr_result_t result; result.type = EXPR_TYPE_UINT32; result.length = 0; result.value = NULL; /* \todo: Check for NULL entry here. */ NmltpSpan span; int success = 0; memcpy(&val, entry->value, sizeof(val)); engineId = val; ltpnm_span_get(engineId, &span, &success); if(success != 0) { val = span.inputSegRecvGreenBytes; result.value = adm_copy_integer((uint8_t*)&val, sizeof(val), &(result.length)); } return result; } expr_result_t ltp_get_eng_in_seg_rdndt_cnt(Lyst params) { datacol_entry_t *entry = (datacol_entry_t*)lyst_data(lyst_first(params)); unsigned long val = 0; unsigned int engineId = 0; expr_result_t result; result.type = EXPR_TYPE_UINT32; result.length = 0; result.value = NULL; /* \todo: Check for NULL entry here. */ NmltpSpan span; int success = 0; memcpy(&val, entry->value, sizeof(val)); engineId = val; ltpnm_span_get(engineId, &span, &success); if(success != 0) { val = span.inputSegRedundantCount; result.value = adm_copy_integer((uint8_t*)&val, sizeof(val), &(result.length)); } return result; } expr_result_t ltp_get_eng_in_seg_rdndt_byte(Lyst params) { datacol_entry_t *entry = (datacol_entry_t*)lyst_data(lyst_first(params)); unsigned long val = 0; unsigned int engineId = 0; expr_result_t result; result.type = EXPR_TYPE_UINT32; result.length = 0; result.value = NULL; /* \todo: Check for NULL entry here. */ NmltpSpan span; int success = 0; memcpy(&val, entry->value, sizeof(val)); engineId = val; ltpnm_span_get(engineId, &span, &success); if(success != 0) { val = span.inputSegRedundantBytes; result.value = adm_copy_integer((uint8_t*)&val, sizeof(val), &(result.length)); } return result; } expr_result_t ltp_get_eng_in_seg_mal_cnt(Lyst params) { datacol_entry_t *entry = (datacol_entry_t*)lyst_data(lyst_first(params)); unsigned long val = 0; unsigned int engineId = 0; expr_result_t result; result.type = EXPR_TYPE_UINT32; result.length = 0; result.value = NULL; /* \todo: Check for NULL entry here. */ NmltpSpan span; int success = 0; memcpy(&val, entry->value, sizeof(val)); engineId = val; ltpnm_span_get(engineId, &span, &success); if(success != 0) { val = span.inputSegMalformedCount; result.value = adm_copy_integer((uint8_t*)&val, sizeof(val), &(result.length)); } return result; } expr_result_t ltp_get_eng_in_seg_mal_byte(Lyst params) { datacol_entry_t *entry = (datacol_entry_t*)lyst_data(lyst_first(params)); unsigned long val = 0; unsigned int engineId = 0; expr_result_t result; result.type = EXPR_TYPE_UINT32; result.length = 0; result.value = NULL; /* \todo: Check for NULL entry here. */ NmltpSpan span; int success = 0; memcpy(&val, entry->value, sizeof(val)); engineId = val; ltpnm_span_get(engineId, &span, &success); if(success != 0) { val = span.inputSegMalformedBytes; result.value = adm_copy_integer((uint8_t*)&val, sizeof(val), &(result.length)); } return result; } expr_result_t ltp_get_eng_in_seg_unk_snd_cnt(Lyst params) { datacol_entry_t *entry = (datacol_entry_t*)lyst_data(lyst_first(params)); unsigned long val = 0; unsigned int engineId = 0; expr_result_t result; result.type = EXPR_TYPE_UINT32; result.length = 0; result.value = NULL; /* \todo: Check for NULL entry here. */ NmltpSpan span; int success = 0; memcpy(&val, entry->value, sizeof(val)); engineId = val; ltpnm_span_get(engineId, &span, &success); if(success != 0) { val = span.inputSegUnkSenderCount; result.value = adm_copy_integer((uint8_t*)&val, sizeof(val), &(result.length)); } return result; } expr_result_t ltp_get_eng_in_seg_unk_snd_byte(Lyst params) { datacol_entry_t *entry = (datacol_entry_t*)lyst_data(lyst_first(params)); unsigned long val = 0; unsigned int engineId = 0; expr_result_t result; result.type = EXPR_TYPE_UINT32; result.length = 0; result.value = NULL; /* \todo: Check for NULL entry here. */ NmltpSpan span; int success = 0; memcpy(&val, entry->value, sizeof(val)); engineId = val; ltpnm_span_get(engineId, &span, &success); if(success != 0) { val = span.inputSegUnkSenderBytes; result.value = adm_copy_integer((uint8_t*)&val, sizeof(val), &(result.length)); } return result; } expr_result_t ltp_get_eng_in_seg_unk_cli_cnt(Lyst params) { datacol_entry_t *entry = (datacol_entry_t*)lyst_data(lyst_first(params)); unsigned long val = 0; unsigned int engineId = 0; expr_result_t result; result.type = EXPR_TYPE_UINT32; result.length = 0; result.value = NULL; /* \todo: Check for NULL entry here. */ NmltpSpan span; int success = 0; memcpy(&val, entry->value, sizeof(val)); engineId = val; ltpnm_span_get(engineId, &span, &success); if(success != 0) { val = span.inputSegUnkClientCount; result.value = adm_copy_integer((uint8_t*)&val, sizeof(val), &(result.length)); } return result; } expr_result_t ltp_get_eng_in_seg_unk_cli_byte(Lyst params) { datacol_entry_t *entry = (datacol_entry_t*)lyst_data(lyst_first(params)); unsigned long val = 0; unsigned int engineId = 0; expr_result_t result; result.type = EXPR_TYPE_UINT32; result.length = 0; result.value = NULL; /* \todo: Check for NULL entry here. */ NmltpSpan span; int success = 0; memcpy(&val, entry->value, sizeof(val)); engineId = val; ltpnm_span_get(engineId, &span, &success); if(success != 0) { val = span.inputSegUnkClientBytes; result.value = adm_copy_integer((uint8_t*)&val, sizeof(val), &(result.length)); } return result; } expr_result_t ltp_get_eng_in_seg_stray_cnt(Lyst params) { datacol_entry_t *entry = (datacol_entry_t*)lyst_data(lyst_first(params)); unsigned long val = 0; unsigned int engineId = 0; expr_result_t result; result.type = EXPR_TYPE_UINT32; result.length = 0; result.value = NULL; /* \todo: Check for NULL entry here. */ NmltpSpan span; int success = 0; memcpy(&val, entry->value, sizeof(val)); engineId = val; ltpnm_span_get(engineId, &span, &success); if(success != 0) { val = span.inputSegStrayCount; result.value = adm_copy_integer((uint8_t*)&val, sizeof(val), &(result.length)); } return result; } expr_result_t ltp_get_eng_in_seg_stray_byte(Lyst params) { datacol_entry_t *entry = (datacol_entry_t*)lyst_data(lyst_first(params)); unsigned long val = 0; unsigned int engineId = 0; expr_result_t result; result.type = EXPR_TYPE_UINT32; result.length = 0; result.value = NULL; /* \todo: Check for NULL entry here. */ NmltpSpan span; int success = 0; memcpy(&val, entry->value, sizeof(val)); engineId = val; ltpnm_span_get(engineId, &span, &success); if(success != 0) { val = span.inputSegStrayBytes; result.value = adm_copy_integer((uint8_t*)&val, sizeof(val), &(result.length)); } return result; } expr_result_t ltp_get_eng_in_seg_miscol_cnt(Lyst params) { datacol_entry_t *entry = (datacol_entry_t*)lyst_data(lyst_first(params)); unsigned long val = 0; unsigned int engineId = 0; expr_result_t result; result.type = EXPR_TYPE_UINT32; result.length = 0; result.value = NULL; /* \todo: Check for NULL entry here. */ NmltpSpan span; int success = 0; memcpy(&val, entry->value, sizeof(val)); engineId = val; ltpnm_span_get(engineId, &span, &success); if(success != 0) { val = span.inputSegMiscolorCount; result.value = adm_copy_integer((uint8_t*)&val, sizeof(val), &(result.length)); } return result; } expr_result_t ltp_get_eng_in_seg_miscol_byte(Lyst params) { datacol_entry_t *entry = (datacol_entry_t*)lyst_data(lyst_first(params)); unsigned long val = 0; unsigned int engineId = 0; expr_result_t result; result.type = EXPR_TYPE_UINT32; result.length = 0; result.value = NULL; /* \todo: Check for NULL entry here. */ NmltpSpan span; int success = 0; memcpy(&val, entry->value, sizeof(val)); engineId = val; ltpnm_span_get(engineId, &span, &success); if(success != 0) { val = span.inputSegMiscolorBytes; result.value = adm_copy_integer((uint8_t*)&val, sizeof(val), &(result.length)); } return result; } expr_result_t ltp_get_eng_in_seg_clsd_cnt(Lyst params) { datacol_entry_t *entry = (datacol_entry_t*)lyst_data(lyst_first(params)); unsigned long val = 0; unsigned int engineId = 0; expr_result_t result; result.type = EXPR_TYPE_UINT32; result.length = 0; result.value = NULL; /* \todo: Check for NULL entry here. */ NmltpSpan span; int success = 0; memcpy(&val, entry->value, sizeof(val)); engineId = val; ltpnm_span_get(engineId, &span, &success); if(success != 0) { val = span.inputSegClosedCount; result.value = adm_copy_integer((uint8_t*)&val, sizeof(val), &(result.length)); } return result; } expr_result_t ltp_get_eng_in_seg_clsd_byte(Lyst params) { datacol_entry_t *entry = (datacol_entry_t*)lyst_data(lyst_first(params)); unsigned long val = 0; unsigned int engineId = 0; expr_result_t result; result.type = EXPR_TYPE_UINT32; result.length = 0; result.value = NULL; /* \todo: Check for NULL entry here. */ NmltpSpan span; int success = 0; memcpy(&val, entry->value, sizeof(val)); engineId = val; ltpnm_span_get(engineId, &span, &success); if(success != 0) { val = span.inputSegClosedBytes; result.value = adm_copy_integer((uint8_t*)&val, sizeof(val), &(result.length)); } return result; } expr_result_t ltp_get_eng_in_ckp_rcv_cnt(Lyst params) { datacol_entry_t *entry = (datacol_entry_t*)lyst_data(lyst_first(params)); unsigned long val = 0; unsigned int engineId = 0; expr_result_t result; result.type = EXPR_TYPE_UINT32; result.length = 0; result.value = NULL; /* \todo: Check for NULL entry here. */ NmltpSpan span; int success = 0; memcpy(&val, entry->value, sizeof(val)); engineId = val; ltpnm_span_get(engineId, &span, &success); if(success != 0) { val = span.inputCkptRecvCount; result.value = adm_copy_integer((uint8_t*)&val, sizeof(val), &(result.length)); } return result; } expr_result_t ltp_get_eng_in_pos_ack_xmit_cnt(Lyst params) { datacol_entry_t *entry = (datacol_entry_t*)lyst_data(lyst_first(params)); unsigned long val = 0; unsigned int engineId = 0; expr_result_t result; result.type = EXPR_TYPE_UINT32; result.length = 0; result.value = NULL; /* \todo: Check for NULL entry here. */ NmltpSpan span; int success = 0; memcpy(&val, entry->value, sizeof(val)); engineId = val; ltpnm_span_get(engineId, &span, &success); if(success != 0) { val = span.inputPosAckXmitCount; result.value = adm_copy_integer((uint8_t*)&val, sizeof(val), &(result.length)); } return result; } expr_result_t ltp_get_eng_in_neg_ack_xmit_cnt(Lyst params) { datacol_entry_t *entry = (datacol_entry_t*)lyst_data(lyst_first(params)); unsigned long val = 0; unsigned int engineId = 0; expr_result_t result; result.type = EXPR_TYPE_UINT32; result.length = 0; result.value = NULL; /* \todo: Check for NULL entry here. */ NmltpSpan span; int success = 0; memcpy(&val, entry->value, sizeof(val)); engineId = val; ltpnm_span_get(engineId, &span, &success); if(success != 0) { val = span.inputNegAckXmitCount; result.value = adm_copy_integer((uint8_t*)&val, sizeof(val), &(result.length)); } return result; } expr_result_t ltp_get_eng_in_canc_xmit_cnt(Lyst params) { datacol_entry_t *entry = (datacol_entry_t*)lyst_data(lyst_first(params)); unsigned long val = 0; unsigned int engineId = 0; expr_result_t result; result.type = EXPR_TYPE_UINT32; result.length = 0; result.value = NULL; /* \todo: Check for NULL entry here. */ NmltpSpan span; int success = 0; memcpy(&val, entry->value, sizeof(val)); engineId = val; ltpnm_span_get(engineId, &span, &success); if(success != 0) { val = span.inputCancelXmitCount; result.value = adm_copy_integer((uint8_t*)&val, sizeof(val), &(result.length)); } return result; } expr_result_t ltp_get_eng_in_ack_rexmt_cnt(Lyst params) { datacol_entry_t *entry = (datacol_entry_t*)lyst_data(lyst_first(params)); unsigned long val = 0; unsigned int engineId = 0; expr_result_t result; result.type = EXPR_TYPE_UINT32; result.length = 0; result.value = NULL; /* \todo: Check for NULL entry here. */ NmltpSpan span; int success = 0; memcpy(&val, entry->value, sizeof(val)); engineId = val; ltpnm_span_get(engineId, &span, &success); if(success != 0) { val = span.inputAckReXmitCount; result.value = adm_copy_integer((uint8_t*)&val, sizeof(val), &(result.length)); } return result; } expr_result_t ltp_get_eng_in_canc_rcv_cnt(Lyst params) { datacol_entry_t *entry = (datacol_entry_t*)lyst_data(lyst_first(params)); unsigned long val = 0; unsigned int engineId = 0; expr_result_t result; result.type = EXPR_TYPE_UINT32; result.length = 0; result.value = NULL; /* \todo: Check for NULL entry here. */ NmltpSpan span; int success = 0; memcpy(&val, entry->value, sizeof(val)); engineId = val; ltpnm_span_get(engineId, &span, &success); if(success != 0) { val = span.inputCancelRecvCount; result.value = adm_copy_integer((uint8_t*)&val, sizeof(val), &(result.length)); } return result; } expr_result_t ltp_get_eng_in_compl_cnt(Lyst params) { datacol_entry_t *entry = (datacol_entry_t*)lyst_data(lyst_first(params)); unsigned long val = 0; unsigned int engineId = 0; expr_result_t result; result.type = EXPR_TYPE_UINT32; result.length = 0; result.value = NULL; /* \todo: Check for NULL entry here. */ NmltpSpan span; int success = 0; memcpy(&val, entry->value, sizeof(val)); engineId = val; ltpnm_span_get(engineId, &span, &success); if(success != 0) { val = span.inputCompleteCount; result.value = adm_copy_integer((uint8_t*)&val, sizeof(val), &(result.length)); } return result; } /* Controls */ uint32_t ltp_engine_reset(Lyst params) { return 0; } #endif /* _HAVE_LTP_ADM_*/
utf-8
1
BSD-3-clause
2002-2011, California Institute of Technology.
mariadb-10.6-10.6.5/plugin/query_response_time/query_response_time.cc
#include "mysql_version.h" #include "my_global.h" #ifdef HAVE_RESPONSE_TIME_DISTRIBUTION #include "mysql_com.h" #include "rpl_tblmap.h" #include "table.h" #include "field.h" #include "sql_show.h" #include "query_response_time.h" #define TIME_STRING_POSITIVE_POWER_LENGTH QRT_TIME_STRING_POSITIVE_POWER_LENGTH #define TIME_STRING_NEGATIVE_POWER_LENGTH 6 #define TOTAL_STRING_POSITIVE_POWER_LENGTH QRT_TOTAL_STRING_POSITIVE_POWER_LENGTH #define TOTAL_STRING_NEGATIVE_POWER_LENGTH 6 #define MINIMUM_BASE 2 #define MAXIMUM_BASE QRT_MAXIMUM_BASE #define POSITIVE_POWER_FILLER QRT_POSITIVE_POWER_FILLER #define NEGATIVE_POWER_FILLER QRT_NEGATIVE_POWER_FILLER #define TIME_OVERFLOW QRT_TIME_OVERFLOW #define DEFAULT_BASE QRT_DEFAULT_BASE #define do_xstr(s) do_str(s) #define do_str(s) #s #define do_format(filler,width) "%" filler width "lld" /* Format strings for snprintf. Generate from: POSITIVE_POWER_FILLER and TIME_STRING_POSITIVE_POWER_LENGTH NEFATIVE_POWER_FILLER and TIME_STRING_NEGATIVE_POWER_LENGTH */ #define TIME_STRING_POSITIVE_POWER_FORMAT do_format(POSITIVE_POWER_FILLER,do_xstr(TIME_STRING_POSITIVE_POWER_LENGTH)) #define TIME_STRING_NEGATIVE_POWER_FORMAT do_format(NEGATIVE_POWER_FILLER,do_xstr(TIME_STRING_NEGATIVE_POWER_LENGTH)) #define TIME_STRING_FORMAT TIME_STRING_POSITIVE_POWER_FORMAT "." TIME_STRING_NEGATIVE_POWER_FORMAT #define TOTAL_STRING_POSITIVE_POWER_FORMAT do_format(POSITIVE_POWER_FILLER,do_xstr(TOTAL_STRING_POSITIVE_POWER_LENGTH)) #define TOTAL_STRING_NEGATIVE_POWER_FORMAT do_format(NEGATIVE_POWER_FILLER,do_xstr(TOTAL_STRING_NEGATIVE_POWER_LENGTH)) #define TOTAL_STRING_FORMAT TOTAL_STRING_POSITIVE_POWER_FORMAT "." TOTAL_STRING_NEGATIVE_POWER_FORMAT #define TIME_STRING_LENGTH QRT_TIME_STRING_LENGTH #define TIME_STRING_BUFFER_LENGTH (TIME_STRING_LENGTH + 1 /* '\0' */) #define TOTAL_STRING_LENGTH QRT_TOTAL_STRING_LENGTH #define TOTAL_STRING_BUFFER_LENGTH (TOTAL_STRING_LENGTH + 1 /* '\0' */) /* Calculate length of "log linear" 1) (MINIMUM_BASE ^ result) <= (10 ^ STRING_POWER_LENGTH) < (MINIMUM_BASE ^ (result + 1)) 2) (MINIMUM_BASE ^ result) <= (10 ^ STRING_POWER_LENGTH) and (MINIMUM_BASE ^ (result + 1)) > (10 ^ STRING_POWER_LENGTH) 3) result <= LOG(MINIMUM_BASE, 10 ^ STRING_POWER_LENGTH)= STRING_POWER_LENGTH * LOG(MINIMUM_BASE,10) result + 1 > LOG(MINIMUM_BASE, 10 ^ STRING_POWER_LENGTH)= STRING_POWER_LENGTH * LOG(MINIMUM_BASE,10) 4) STRING_POWER_LENGTH * LOG(MINIMUM_BASE,10) - 1 < result <= STRING_POWER_LENGTH * LOG(MINIMUM_BASE,10) MINIMUM_BASE= 2 always, LOG(MINIMUM_BASE,10)= 3.3219280948873626, result= (int)3.3219280948873626 * STRING_POWER_LENGTH Last counter always use for time overflow */ #define POSITIVE_POWER_COUNT ((int)(3.32192809 * TIME_STRING_POSITIVE_POWER_LENGTH)) #define NEGATIVE_POWER_COUNT ((int)(3.32192809 * TIME_STRING_NEGATIVE_POWER_LENGTH)) #define OVERALL_POWER_COUNT (NEGATIVE_POWER_COUNT + 1 + POSITIVE_POWER_COUNT) #define MILLION ((unsigned long)1000 * 1000) namespace query_response_time { class utility { public: utility() : m_base(0) { m_max_dec_value= MILLION; for(int i= 0; TIME_STRING_POSITIVE_POWER_LENGTH > i; ++i) m_max_dec_value *= 10; setup(DEFAULT_BASE); } public: uint base() const { return m_base; } uint negative_count() const { return m_negative_count; } uint positive_count() const { return m_positive_count; } uint bound_count() const { return m_bound_count; } ulonglong max_dec_value() const { return m_max_dec_value; } ulonglong bound(uint index) const { return m_bound[ index ]; } public: void setup(uint base) { if(base != m_base) { m_base= base; const ulonglong million= 1000 * 1000; ulonglong value= million; m_negative_count= 0; while(value > 0) { m_negative_count += 1; value /= m_base; } m_negative_count -= 1; value= million; m_positive_count= 0; while(value < m_max_dec_value) { m_positive_count += 1; value *= m_base; } m_bound_count= m_negative_count + m_positive_count; value= million; for(uint i= 0; i < m_negative_count; ++i) { value /= m_base; m_bound[m_negative_count - i - 1]= value; } value= million; for(uint i= 0; i < m_positive_count; ++i) { m_bound[m_negative_count + i]= value; value *= m_base; } } } private: uint m_base; uint m_negative_count; uint m_positive_count; uint m_bound_count; ulonglong m_max_dec_value; /* for TIME_STRING_POSITIVE_POWER_LENGTH=7 is 10000000 */ ulonglong m_bound[OVERALL_POWER_COUNT]; }; static void print_time(char* buffer, std::size_t buffer_size, const char* format, uint64 value) { ulonglong second= (value / MILLION); ulonglong microsecond= (value % MILLION); my_snprintf(buffer, buffer_size, format, second, microsecond); } class time_collector { utility *m_utility; Atomic_counter<uint32_t> m_count[OVERALL_POWER_COUNT + 1]; Atomic_counter<uint64_t> m_total[OVERALL_POWER_COUNT + 1]; public: time_collector(utility& u): m_utility(&u) { flush(); } ~time_collector() { } uint32_t count(uint index) { return m_count[index]; } uint64_t total(uint index) { return m_total[index]; } void flush() { for (auto i= 0; i < OVERALL_POWER_COUNT + 1; i++) { m_count[i]= 0; m_total[i]= 0; } } void collect(uint64_t time) { int i= 0; for(int count= m_utility->bound_count(); count > i; ++i) { if(m_utility->bound(i) > time) { m_count[i]++; m_total[i]+= time; break; } } } }; class collector { public: collector() : m_time(m_utility) { m_utility.setup(DEFAULT_BASE); } public: void flush() { m_utility.setup(opt_query_response_time_range_base); m_time.flush(); } int fill(THD* thd, TABLE_LIST *tables, COND *cond) { DBUG_ENTER("fill_schema_query_response_time"); TABLE *table= static_cast<TABLE*>(tables->table); Field **fields= table->field; for(uint i= 0, count= bound_count() + 1 /* with overflow */; count > i; ++i) { char time[TIME_STRING_BUFFER_LENGTH]; char total[TOTAL_STRING_BUFFER_LENGTH]; if(i == bound_count()) { assert(sizeof(TIME_OVERFLOW) <= TIME_STRING_BUFFER_LENGTH); assert(sizeof(TIME_OVERFLOW) <= TOTAL_STRING_BUFFER_LENGTH); memcpy(time,TIME_OVERFLOW,sizeof(TIME_OVERFLOW)); memcpy(total,TIME_OVERFLOW,sizeof(TIME_OVERFLOW)); } else { print_time(time, sizeof(time), TIME_STRING_FORMAT, this->bound(i)); print_time(total, sizeof(total), TOTAL_STRING_FORMAT, this->total(i)); } fields[0]->store(time,strlen(time),system_charset_info); fields[1]->store((longlong)this->count(i),true); fields[2]->store(total,strlen(total),system_charset_info); if (schema_table_store_record(thd, table)) { DBUG_RETURN(1); } } DBUG_RETURN(0); } void collect(ulonglong time) { m_time.collect(time); } uint bound_count() const { return m_utility.bound_count(); } ulonglong bound(uint index) { return m_utility.bound(index); } ulonglong count(uint index) { return m_time.count(index); } ulonglong total(uint index) { return m_time.total(index); } private: utility m_utility; time_collector m_time; }; static collector g_collector; } // namespace query_response_time void query_response_time_init() { } void query_response_time_free() { query_response_time::g_collector.flush(); } int query_response_time_flush() { query_response_time::g_collector.flush(); return 0; } void query_response_time_collect(ulonglong query_time) { query_response_time::g_collector.collect(query_time); } int query_response_time_fill(THD* thd, TABLE_LIST *tables, COND *cond) { return query_response_time::g_collector.fill(thd,tables,cond); } #endif // HAVE_RESPONSE_TIME_DISTRIBUTION
utf-8
1
GPL-2
2000-2016, Oracle and/or its affiliates. All rights reserved. 2008-2013 Monty Program AB 2008-2014 SkySQL Ab 2013-2016 MariaDB Corporation 2012-2016 MariaDB Foundation
ncl-6.6.2/ncarg2d/src/libncarg_gks/awiC/setcid.c
/* * $Id: setcid.c,v 1.4 2008-07-23 17:24:25 haley Exp $ */ /************************************************************************ * * * Copyright (C) 2000 * * University Corporation for Atmospheric Research * * All Rights Reserved * * * * The use of this Software is governed by a License Agreement. * * * ************************************************************************/ /* * Set the smallest available connection identifier */ #include <stdio.h> #define MAX_OPEN_WK 15 extern int conn_id_list[]; extern int smallest_avail_id; extern int num_used_conn_ids; void set_avail_conn_id #ifdef NeedFuncProto ( void ) #else () #endif { int i; /* * Get the smallest available connection identifier. * Cannot use either "5" or "6" since these are stdin and stdout * respectively. */ smallest_avail_id = 0; for( i = 0; i < num_used_conn_ids - 1; i++ ) { if( conn_id_list[i] != 4 && conn_id_list[i] != conn_id_list[i+1] ) { smallest_avail_id = conn_id_list[i] + 1; break; } else if( conn_id_list[i] == 4 && conn_id_list[i+1] != 7 ) { smallest_avail_id = 7; } } if( !smallest_avail_id ) smallest_avail_id = conn_id_list[num_used_conn_ids-1] + 1; }
utf-8
1
unknown
unknown
xdmf-3.0+git20190531/core/dsm/tests/Cxx/XdmfConnectTest2Paged.cpp
#include <mpi.h> #include <stdlib.h> #include <iostream> #include <fstream> #include <string.h> #include <XdmfArray.hpp> #include <XdmfArrayType.hpp> #include <XdmfHDF5WriterDSM.hpp> #include <XdmfHDF5ControllerDSM.hpp> #include <XdmfDSMBuffer.hpp> #include <XdmfDSMCommMPI.hpp> int main(int argc, char *argv[]) { // This test does not work properly with openmpi // due to an issue with the openmpi code #ifndef OPEN_MPI int size, id, dsmSize; dsmSize = 64; MPI_Status status; MPI_Comm comm = MPI_COMM_WORLD; MPI_Init(&argc, &argv); MPI_Comm_rank(comm, &id); MPI_Comm_size(comm, &size); XdmfDSMCommMPI::SetUseEnvFileName(true); std::string newPath = "dsm"; std::string newSetPath = "Data"; // Initializing objects //since the start and end ids are larger than the size there are no buffers alloted //thus, no blockage occurs XdmfDSMCommMPI * testComm = new XdmfDSMCommMPI(); testComm->DupComm(comm); testComm->Init(); testComm->SetApplicationName("Connect 2"); XdmfDSMBuffer * testBuffer = new XdmfDSMBuffer(); testBuffer->SetIsServer(false); testBuffer->SetComm(testComm); testBuffer->SetIsConnected(true); std::vector<unsigned int> readStartVector; std::vector<unsigned int> readStrideVector; std::vector<unsigned int> readCountVector; std::vector<unsigned int> readDataSizeVector; readStartVector.push_back(5*id); readStrideVector.push_back(1); readCountVector.push_back(5); readDataSizeVector.push_back(5*size); shared_ptr<XdmfArray> readArray = XdmfArray::New(); readArray->initialize<int>(0); readArray->reserve(5); shared_ptr<XdmfHDF5ControllerDSM> readController = XdmfHDF5ControllerDSM::New( newPath, newSetPath, XdmfArrayType::Int32(), readStartVector, readStrideVector, readCountVector, readDataSizeVector, testBuffer); #ifdef _WIN32 Sleep(1000) #else sleep(10); #endif char * configFileName = strdup(testComm->GetDsmFileName().c_str()); std::ifstream testStream; testStream.open(configFileName); while (!testStream.good()) { // Wait for the config file to be generated testStream.close(); #ifdef _WIN32 Sleep(500) #else sleep(5); #endif testStream.open(configFileName); } readController->getServerBuffer()->GetComm()->ReadDsmPortName(); readController->getServerBuffer()->Connect(); shared_ptr<XdmfHDF5WriterDSM> exampleWriter = XdmfHDF5WriterDSM::New(newPath, testBuffer); std::vector<unsigned int> writeStartVector; std::vector<unsigned int> writeStrideVector; std::vector<unsigned int> writeCountVector; std::vector<unsigned int> writeDataSizeVector; writeStartVector.push_back(id*5); writeStrideVector.push_back(1); writeCountVector.push_back(5); writeDataSizeVector.push_back(5*size); shared_ptr<XdmfHDF5ControllerDSM> writeController = XdmfHDF5ControllerDSM::New( newPath, newSetPath, XdmfArrayType::Int32(), writeStartVector, writeStrideVector, writeCountVector, writeDataSizeVector, exampleWriter->getServerBuffer()); exampleWriter->setMode(XdmfHeavyDataWriter::Hyperslab); // Done initialization MPI_Barrier(readController->getServerBuffer()->GetComm()->GetIntraComm()); // Let waits be set up #ifdef _WIN32 Sleep(100) #else sleep(1); #endif // Test Notify exampleWriter->waitRelease(newPath, "notify", 3); // Testing the structure of the DSM if (id == 0) { std::vector<unsigned int> structuresizes; structuresizes.push_back(1); structuresizes.push_back(1); structuresizes.push_back(2); structuresizes.push_back(2); std::vector<std::string> structurenames; structurenames.push_back("Application"); structurenames.push_back("Server"); structurenames.push_back("Connect 1"); structurenames.push_back("Connect 2"); std::vector<std::pair<std::string, unsigned int> > teststructure = exampleWriter->getServerBuffer()->GetComm()->GetDsmProcessStructure(); printf("DSM Structure:\n"); for (unsigned int i = 0; i < teststructure.size(); ++i) { std::cout << "(" << teststructure[i].first << ", " << teststructure[i].second << ")" << std::endl; assert(teststructure[i].second == structuresizes[i]); assert(teststructure[i].first.compare(structurenames[i]) == 0); } } MPI_Barrier(exampleWriter->getServerBuffer()->GetComm()->GetIntraComm()); for (unsigned int numloops = 0; numloops < 4; ++numloops) { if (id == 0) { int receiveData = 0; readController->getServerBuffer()->ReceiveAcknowledgment(readController->getServerBuffer()->GetComm()->GetInterId() - 1, receiveData, XDMF_DSM_EXCHANGE_TAG, XDMF_DSM_INTER_COMM); } MPI_Barrier(readController->getServerBuffer()->GetComm()->GetIntraComm()); if (readArray->getNumberHeavyDataControllers() > 0) { readArray->removeHeavyDataController(0); } readArray->insert(readController); readArray->read(); for (int i = 0; i < size; ++i) { MPI_Barrier(readController->getServerBuffer()->GetComm()->GetIntraComm()); if (i == id) { std::stringstream outputstream; outputstream << "Array on core " << exampleWriter->getServerBuffer()->GetComm()->GetInterId() << " contains:" << std::endl; for (unsigned int j = 0; j < readArray->getSize(); ++j) { int tempVal = readArray->getValue<int>(j); tempVal = tempVal * 3; readArray->insert(j, tempVal); outputstream << "[" << j << "]" << readArray->getValue<int>(j) << std::endl; } std::cout << outputstream.str(); } } MPI_Barrier(readController->getServerBuffer()->GetComm()->GetIntraComm()); if (id == 0) { std::cout << std::endl << std::endl; } readArray->removeHeavyDataController(0); readArray->insert(writeController); readArray->accept(exampleWriter); if (id == 0) { int receiveData = 0; readController->getServerBuffer()->SendAcknowledgment(readController->getServerBuffer()->GetComm()->GetInterId() - 1, receiveData, XDMF_DSM_EXCHANGE_TAG, XDMF_DSM_INTER_COMM); } } //this last acknowledgment is to end the loop. if (id == 0) { int receiveData = 0; readController->getServerBuffer()->ReceiveAcknowledgment(readController->getServerBuffer()->GetComm()->GetInterId() - 1, receiveData, XDMF_DSM_EXCHANGE_TAG, XDMF_DSM_INTER_COMM); } MPI_Barrier(readController->getServerBuffer()->GetComm()->GetIntraComm()); // Do work stuff here if (id == 0) { readController->stopDSM(); } MPI_Barrier(readController->getServerBuffer()->GetComm()->GetInterComm()); MPI_Finalize(); #endif return 0; }
utf-8
1
unknown
unknown
libdnf-0.55.2/libdnf/transaction/Item.hpp
/* * 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 */ #ifndef LIBDNF_TRANSACTION_ITEM_HPP #define LIBDNF_TRANSACTION_ITEM_HPP #include <memory> #include <string> #include "../utils/sqlite3/Sqlite3.hpp" namespace libdnf { class Item; typedef std::shared_ptr< Item > ItemPtr; } #include "Types.hpp" namespace libdnf { class Item { public: /// Default constructor. explicit Item(SQLite3Ptr conn); /// Default destructor. virtual ~Item() = default; /// Returns the ID of this item. int64_t getId() const noexcept { return id; } /// Sets the ID of this item. void setId(int64_t value) { id = value; } virtual ItemType getItemType() const noexcept { return itemType; } virtual std::string toStr() const; virtual void save(); protected: void dbInsert(); SQLite3Ptr conn; int64_t id = 0; const ItemType itemType = ItemType::UNKNOWN; }; } // namespace libdnf #endif // LIBDNF_TRANSACTION_ITEM_HPP
utf-8
1
LGPL-2.1
2012-2020, Red Hat, Inc.
gcc-arm-none-eabi-10.3-2021.07/gcc/testsuite/gcc.dg/cpp/pragma-3.c
/* { dg-options "-fopenmp" } { dg-do preprocess } { dg-require-effective-target fopenmp } */ void foo (void) { int i1, j1, k1; #define p parallel #define P(x) private (x##1) #define S(x) shared (x##1) #define F(x) firstprivate (x##1) #pragma omp \ p \ P(i) \ S(j) \ F(k) ; } /* The bug here was that we had a line like: # 33554432 "../../gcc/testsuite/gcc.dg/cpp/pragma-3.c" Before line: #pragma omp parallel private (i1) shared (j1) firstprivate (k1) Note the very big integer there. Normally we should just have this: # 13 "../../gcc/testsuite/gcc.dg/cpp/pragma-3.c" #pragma omp parallel private (i1) shared (j1) firstprivate (k1) So let's check that we have no line with a number of 3 or more digit after #: { dg-final { scan-file-not pragma-3.i "# \[0-9\]{3} \[^\n\r\]*pragma-3.c" } } */
utf-8
1
unknown
unknown
libkcompactdisc-21.08.0/src/wmlib/plat_template.c
/* * This file is part of WorkMan, the civilized CD player library * Copyright (C) 1991-1997 by Steven Grimm <koreth@midwinter.com> * Copyright (C) by Dirk Försterling <milliByte@DeathsDoor.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 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA * * * This file surely contains nonsense. It's the porter's part to fill * the gaps and assure that the resulting code makes sense. * */ #if [TEMPLATESYSTEM] #include "include/wm_config.h" #include "include/wm_struct.h" #include "include/wm_cdtext.h" #define WM_MSG_CLASS WM_MSG_CLASS_PLATFORM /* * gen_init(); * */ int gen_init(struct wm_drive *d) { return (0); } /* gen_init() */ /* * gen_open() * */ int gen_open(struct wm_drive *d) { if( ! d ) { errno = EFAULT; return -1; } if(d->fd > -1) /* device already open? */ { wm_lib_message(WM_MSG_LEVEL_DEBUG|WM_MSG_CLASS, "gen_open(): [device is open (fd=%d)]\n", d->fd); return 0; } return (0); } /* gen_open() */ /* * gen_scsi() * */ int gen_scsi(struct wm_drive *d, uchar_t *cdb, int cdblen,void *retbuf,int retbuflen,int getreply) { return -1; } /* gen_scsi() */ /* * close the CD device */ int gen_close(struct wm_drive *d) { if(d->fd != -1) { wm_lib_message(WM_MSG_LEVEL_DEBUG, "closing the device\n"); close(d->fd); d->fd = -1; } return 0; } /* gen_close() */ /* * gen_get_drive_status() * */ int gen_get_drive_status(struct wm_drive *d, int oldmode, int *mode, int *pos, int *track, int *index) { return (0); } /* gen_get_drive_status() */ /* * gen_get_trackcount() * */ int gen_get_trackcount(struct wm_drive *d,int *tracks) { return (0); } /* gen_get_trackcount() */ /* * gen_get_trackinfo() * */ int gen_get_trackinfo(struct wm_drive *d,int track,int *data,int *startframe) { return (0); } /* gen_get_trackinfo() */ /* * gen_get_cdlen() * */ int gen_get_cdlen(struct wm_drive *d,int *frames) { return (0); } /* gen_get_cdlen() */ /* * gen_play() * */ int gen_play(struct wm_drive *d,int start,int end) { return (0); } /* gen_play() */ /* * gen_pause() * */ int gen_pause(struct wm_drive *d) { return ioctl( 0 ); } /* gen_pause() */ /* * gen_resume * */ int gen_resume(struct wm_drive *d) { return (0); } /* gen_resume() */ /* * gen_stop() * */ int gen_stop(struct wm_drive *d) { return (0); } /* gen_stop() */ /* * gen_eject() * */ int gen_eject(struct wm_drive *d) { return (0); } /* gen_eject() */ /*----------------------------------------* * Close the CD tray *----------------------------------------*/ int gen_closetray(struct wm_drive *d) { return -1; } /* gen_closetray() */ int scale_volume(int vol,int max) { return ((vol * (max_volume - min_volume)) / max + min_volume); } /* scale_volume() */ int unscale_volume(int vol,int max) { int n; n = ( vol - min_volume ) * max_volume / (max - min_volume); return (n <0)?0:n; } /* unscale_volume() */ /* * gen_set_volume() * */ int gen_set_volume(struct wm_drive *d,int left,int right) { return (0); } /* gen_set_volume() */ /* * gen_get_volume() * */ int gen_get_volume(struct wm_drive *d,int *left,int *right) { return (0); } /* gen_get_volume() */ #endif /* TEMPLATESYSTEM */
utf-8
1
GPL-2+
2007, Alexander Kern <alex.kern@gmx.de> 2018, Free Software Foundation 2010, Rosetta Contributors and Canonical Ltd 2005, Shaheedur R. Haque <srhaque@iee.org>
enigma-1.20-dfsg.1/lib-src/enet/include/enet/time.h
/** @file time.h @brief ENet time constants and macros */ #ifndef __ENET_TIME_H__ #define __ENET_TIME_H__ #define ENET_TIME_OVERFLOW 86400000 #define ENET_TIME_LESS(a, b) ((a) - (b) >= ENET_TIME_OVERFLOW) #define ENET_TIME_GREATER(a, b) ((b) - (a) >= ENET_TIME_OVERFLOW) #define ENET_TIME_LESS_EQUAL(a, b) (! ENET_TIME_GREATER (a, b)) #define ENET_TIME_GREATER_EQUAL(a, b) (! ENET_TIME_LESS (a, b)) #define ENET_TIME_DIFFERENCE(a, b) ((a) - (b) >= ENET_TIME_OVERFLOW ? (b) - (a) : (a) - (b)) #endif /* __ENET_TIME_H__ */
utf-8
1
unknown
unknown
kmymoney-5.1.2/kmymoney/dialogs/settings/ksettingsonlinequotes.cpp
/* SPDX-FileCopyrightText: 2005-2010 Thomas Baumgart <tbaumgart@kde.org> SPDX-FileCopyrightText: 2017-2018 Łukasz Wojniłowicz <lukasz.wojnilowicz@gmail.com> SPDX-License-Identifier: GPL-2.0-or-later */ #include "ksettingsonlinequotes.h" // ---------------------------------------------------------------------------- // QT Includes #include <QCheckBox> #include <QIcon> // ---------------------------------------------------------------------------- // KDE Includes #include <KConfig> #include <KLocalizedString> #include <KMessageBox> // ---------------------------------------------------------------------------- // Project Includes #include "ui_ksettingsonlinequotes.h" #include "kmymoney/converter/webpricequote.h" #include "mymoneyfile.h" #include "mymoneysecurity.h" #include "icons/icons.h" using namespace Icons; class KSettingsOnlineQuotesPrivate { Q_DISABLE_COPY(KSettingsOnlineQuotesPrivate) public: KSettingsOnlineQuotesPrivate() : ui(new Ui::KSettingsOnlineQuotes), m_quoteInEditing(false) { } ~KSettingsOnlineQuotesPrivate() { delete ui; } Ui::KSettingsOnlineQuotes *ui; QList<WebPriceQuoteSource> m_resetList; WebPriceQuoteSource m_currentItem; bool m_quoteInEditing; }; KSettingsOnlineQuotes::KSettingsOnlineQuotes(QWidget *parent) : QWidget(parent), d_ptr(new KSettingsOnlineQuotesPrivate) { Q_D(KSettingsOnlineQuotes); d->ui->setupUi(this); QStringList groups = WebPriceQuote::quoteSources(); loadList(true /*updateResetList*/); d->ui->m_updateButton->setEnabled(false); d->ui->m_updateButton->setIcon(Icons::get(Icon::DialogOK)); d->ui->m_deleteButton->setIcon(Icons::get(Icon::EditDelete)); d->ui->m_newButton->setIcon(Icons::get(Icon::DocumentNew)); d->ui->m_editIdentifyBy->addItem(i18nc("@item:inlistbox Stock", "Symbol"), WebPriceQuoteSource::identifyBy::Symbol); d->ui->m_editIdentifyBy->addItem(i18nc("@item:inlistbox Stock", "Identification number"), WebPriceQuoteSource::identifyBy::IdentificationNumber); d->ui->m_editIdentifyBy->addItem(i18nc("@item:inlistbox Stock", "Name"), WebPriceQuoteSource::identifyBy::Name); connect(d->ui->m_dumpCSVProfile, &QAbstractButton::clicked, this, &KSettingsOnlineQuotes::slotDumpCSVProfile); connect(d->ui->m_updateButton, &QAbstractButton::clicked, this, &KSettingsOnlineQuotes::slotUpdateEntry); connect(d->ui->m_newButton, &QAbstractButton::clicked, this, &KSettingsOnlineQuotes::slotNewEntry); connect(d->ui->m_deleteButton, &QAbstractButton::clicked, this, &KSettingsOnlineQuotes::slotDeleteEntry); connect(d->ui->m_quoteSourceList, &QListWidget::itemSelectionChanged, this, &KSettingsOnlineQuotes::slotLoadWidgets); connect(d->ui->m_quoteSourceList, &QListWidget::itemChanged, this, &KSettingsOnlineQuotes::slotEntryRenamed); connect(d->ui->m_quoteSourceList, &QListWidget::itemDoubleClicked, this, &KSettingsOnlineQuotes::slotStartRename); connect(d->ui->m_editURL, &QLineEdit::textChanged, this, static_cast<void (KSettingsOnlineQuotes::*)(const QString &)>(&KSettingsOnlineQuotes::slotEntryChanged)); connect(d->ui->m_editCSVURL, &QLineEdit::textChanged, this, static_cast<void (KSettingsOnlineQuotes::*)(const QString &)>(&KSettingsOnlineQuotes::slotEntryChanged)); connect(d->ui->m_editIdentifier, &QLineEdit::textChanged, this, static_cast<void (KSettingsOnlineQuotes::*)(const QString &)>(&KSettingsOnlineQuotes::slotEntryChanged)); connect(d->ui->m_editIdentifyBy, static_cast<void (QComboBox::*)(int)>(&QComboBox::currentIndexChanged), this, static_cast<void (KSettingsOnlineQuotes::*)(int)>(&KSettingsOnlineQuotes::slotEntryChanged)); connect(d->ui->m_editDate, &QLineEdit::textChanged, this, static_cast<void (KSettingsOnlineQuotes::*)(const QString &)>(&KSettingsOnlineQuotes::slotEntryChanged)); connect(d->ui->m_editDateFormat, &QLineEdit::textChanged, this, static_cast<void (KSettingsOnlineQuotes::*)(const QString &)>(&KSettingsOnlineQuotes::slotEntryChanged)); connect(d->ui->m_editPrice, &QLineEdit::textChanged, this, static_cast<void (KSettingsOnlineQuotes::*)(const QString &)>(&KSettingsOnlineQuotes::slotEntryChanged)); connect(d->ui->m_skipStripping, &QAbstractButton::toggled, this, static_cast<void (KSettingsOnlineQuotes::*)(bool)>(&KSettingsOnlineQuotes::slotEntryChanged)); } KSettingsOnlineQuotes::~KSettingsOnlineQuotes() { Q_D(KSettingsOnlineQuotes); delete d; } void KSettingsOnlineQuotes::loadList(const bool updateResetList) { Q_D(KSettingsOnlineQuotes); //disconnect the slot while items are being loaded and reconnect at the end disconnect(d->ui->m_quoteSourceList, &QListWidget::itemChanged, this, &KSettingsOnlineQuotes::slotEntryRenamed); d->m_quoteInEditing = false; QStringList groups = WebPriceQuote::quoteSources(); if (updateResetList) d->m_resetList.clear(); d->ui->m_quoteSourceList->clear(); QStringList::Iterator it; for (it = groups.begin(); it != groups.end(); ++it) { QListWidgetItem* item = new QListWidgetItem(*it); item->setFlags(Qt::ItemIsEditable | Qt::ItemIsSelectable | Qt::ItemIsEnabled); d->ui->m_quoteSourceList->addItem(item); if (updateResetList) d->m_resetList += WebPriceQuoteSource(*it); } d->ui->m_quoteSourceList->sortItems(); QListWidgetItem* first = d->ui->m_quoteSourceList->item(0); if (first) d->ui->m_quoteSourceList->setCurrentItem(first); slotLoadWidgets(); d->ui->m_newButton->setEnabled((d->ui->m_quoteSourceList->findItems(i18n("New Quote Source"), Qt::MatchExactly)).count() == 0); connect(d->ui->m_quoteSourceList, &QListWidget::itemChanged, this, &KSettingsOnlineQuotes::slotEntryRenamed); } void KSettingsOnlineQuotes::resetConfig() { Q_D(KSettingsOnlineQuotes); QStringList::ConstIterator it; QStringList groups = WebPriceQuote::quoteSources(); // delete all currently defined entries for (it = groups.constBegin(); it != groups.constEnd(); ++it) { WebPriceQuoteSource(*it).remove(); } // and write back the one's from the reset list QList<WebPriceQuoteSource>::ConstIterator itr; for (itr = d->m_resetList.constBegin(); itr != d->m_resetList.constEnd(); ++itr) { (*itr).write(); } loadList(); } void KSettingsOnlineQuotes::slotLoadWidgets() { Q_D(KSettingsOnlineQuotes); d->m_quoteInEditing = false; QListWidgetItem* item = d->ui->m_quoteSourceList->currentItem(); d->ui->m_editURL->setEnabled(true); d->ui->m_editCSVURL->setEnabled(true); d->ui->m_editIdentifier->setEnabled(true); d->ui->m_editIdentifyBy->setEnabled(true); d->ui->m_editPrice->setEnabled(true); d->ui->m_editDate->setEnabled(true); d->ui->m_editDateFormat->setEnabled(true); d->ui->m_skipStripping->setEnabled(true); d->ui->m_dumpCSVProfile->setEnabled(true); d->ui->m_deleteButton->setEnabled(true); d->ui->m_editURL->setText(QString()); d->ui->m_editCSVURL->setText(QString()); d->ui->m_editIdentifier->setText(QString()); d->ui->m_editIdentifyBy->setCurrentIndex(WebPriceQuoteSource::identifyBy::Symbol); d->ui->m_editPrice->setText(QString()); d->ui->m_editDate->setText(QString()); d->ui->m_editDateFormat->setText(QString()); if (item) { d->m_currentItem = WebPriceQuoteSource(item->text()); d->ui->m_editURL->setText(d->m_currentItem.m_url); d->ui->m_editCSVURL->setText(d->m_currentItem.m_csvUrl); d->ui->m_editIdentifier->setText(d->m_currentItem.m_webID); d->ui->m_editIdentifyBy->setCurrentIndex(d->m_currentItem.m_webIDBy); d->ui->m_editPrice->setText(d->m_currentItem.m_price); d->ui->m_editDate->setText(d->m_currentItem.m_date); d->ui->m_editDateFormat->setText(d->m_currentItem.m_dateformat); d->ui->m_skipStripping->setChecked(d->m_currentItem.m_skipStripping); } else { d->ui->m_editURL->setEnabled(false); d->ui->m_editCSVURL->setEnabled(false); d->ui->m_editIdentifier->setEnabled(false); d->ui->m_editIdentifyBy->setEnabled(false); d->ui->m_editPrice->setEnabled(false); d->ui->m_editDate->setEnabled(false); d->ui->m_editDateFormat->setEnabled(false); d->ui->m_skipStripping->setEnabled(false); d->ui->m_dumpCSVProfile->setEnabled(false); d->ui->m_deleteButton->setEnabled(false); } d->ui->m_updateButton->setEnabled(false); } void KSettingsOnlineQuotes::slotEntryChanged() { Q_D(KSettingsOnlineQuotes); // clang-format off bool modified = d->ui->m_editURL->text() != d->m_currentItem.m_url || d->ui->m_editCSVURL->text() != d->m_currentItem.m_csvUrl || d->ui->m_editIdentifier->text() != d->m_currentItem.m_webID || d->ui->m_editIdentifyBy->currentData().toInt() != static_cast<int>(d->m_currentItem.m_webIDBy) || d->ui->m_editDate->text() != d->m_currentItem.m_date || d->ui->m_editDateFormat->text() != d->m_currentItem.m_dateformat || d->ui->m_editPrice->text() != d->m_currentItem.m_price || d->ui->m_skipStripping->isChecked() != d->m_currentItem.m_skipStripping; // clang-format on d->ui->m_updateButton->setEnabled(modified); } void KSettingsOnlineQuotes::slotEntryChanged(int) { slotEntryChanged(); } void KSettingsOnlineQuotes::slotEntryChanged(const QString&) { slotEntryChanged(); } void KSettingsOnlineQuotes::slotEntryChanged(bool) { slotEntryChanged(); } void KSettingsOnlineQuotes::slotDumpCSVProfile() { Q_D(KSettingsOnlineQuotes); KSharedConfigPtr config = CSVImporterCore::configFile(); PricesProfile profile; profile.m_profileName = d->m_currentItem.m_name; profile.m_profileType = Profile::StockPrices; bool profileExists = false; bool writeProfile = true; if (profile.readSettings(config)) profileExists = true; else { profile.m_profileType = Profile::CurrencyPrices; if (profile.readSettings(config)) profileExists = true; } if (profileExists) writeProfile = (KMessageBox::questionYesNoCancel(this, i18n("CSV profile <b>%1</b> already exists.<br>" "Do you want to overwrite it?", d->m_currentItem.m_name), i18n("CSV Profile Already Exists")) == KMessageBox::Yes ? true : false); if (writeProfile) { QMap<QString, PricesProfile> quoteSources = WebPriceQuote::defaultCSVQuoteSources(); profile = quoteSources.value(d->m_currentItem.m_name); if (profile.m_profileName.compare(d->m_currentItem.m_name, Qt::CaseInsensitive) == 0) { profile.writeSettings(config); CSVImporterCore::profilesAction(profile.type(), ProfileAction::Add, profile.m_profileName, profile.m_profileName); } } CSVImporterCore::profilesAction(profile.type(), ProfileAction::UpdateLastUsed, profile.m_profileName, profile.m_profileName); } void KSettingsOnlineQuotes::slotUpdateEntry() { Q_D(KSettingsOnlineQuotes); d->m_currentItem.m_url = d->ui->m_editURL->text(); d->m_currentItem.m_csvUrl = d->ui->m_editCSVURL->text(); d->m_currentItem.m_webID = d->ui->m_editIdentifier->text(); d->m_currentItem.m_webIDBy = static_cast<WebPriceQuoteSource::identifyBy>(d->ui->m_editIdentifyBy->currentData().toInt()); d->m_currentItem.m_date = d->ui->m_editDate->text(); d->m_currentItem.m_dateformat = d->ui->m_editDateFormat->text(); d->m_currentItem.m_price = d->ui->m_editPrice->text(); d->m_currentItem.m_skipStripping = d->ui->m_skipStripping->isChecked(); d->m_currentItem.write(); slotEntryChanged(); } void KSettingsOnlineQuotes::slotNewEntry() { Q_D(KSettingsOnlineQuotes); WebPriceQuoteSource newSource(i18n("New Quote Source")); newSource.write(); loadList(); QListWidgetItem* item = d->ui->m_quoteSourceList->findItems(i18n("New Quote Source"), Qt::MatchExactly).at(0); if (item) { d->ui->m_quoteSourceList->setCurrentItem(item); slotLoadWidgets(); } } void KSettingsOnlineQuotes::slotDeleteEntry() { Q_D(KSettingsOnlineQuotes); // first check if no security is using this online source auto securities = MyMoneyFile::instance()->securityList(); foreach(const auto security, securities) { if (security.value(QStringLiteral("kmm-online-source")).compare(d->m_currentItem.m_name) == 0) { if (KMessageBox::questionYesNo(this, i18n("Security <b>%1</b> uses this quote source.<br>" "Do you really want to remove it?", security.name()), i18n("Delete quote source")) == KMessageBox::Yes) break; // webpricequote can handle missing online quotes, so proceed without any extra action else return; } } // remove online source from webpricequote... d->m_currentItem.remove(); // ...and from setting's list auto row = d->ui->m_quoteSourceList->currentRow(); QListWidgetItem *item = d->ui->m_quoteSourceList->takeItem(row); if (item) delete item; item = nullptr; int count = d->ui->m_quoteSourceList->count(); if (row < count) // select next available entry... item = d->ui->m_quoteSourceList->item(row); else if (row >= count && count > 0) // ...or last entry if this was the last entry... item = d->ui->m_quoteSourceList->item(count - 1); if (item) { d->ui->m_quoteSourceList->setCurrentItem(item); slotLoadWidgets(); } } void KSettingsOnlineQuotes::slotStartRename(QListWidgetItem* item) { Q_D(KSettingsOnlineQuotes); d->m_quoteInEditing = true; d->ui->m_quoteSourceList->editItem(item); } void KSettingsOnlineQuotes::slotEntryRenamed(QListWidgetItem* item) { Q_D(KSettingsOnlineQuotes); //if there is no current item selected, exit if (d->m_quoteInEditing == false || !d->ui->m_quoteSourceList->currentItem() || item != d->ui->m_quoteSourceList->currentItem()) return; d->m_quoteInEditing = false; QString text = item->text(); int nameCount = 0; for (auto i = 0; i < d->ui->m_quoteSourceList->count(); ++i) { if (d->ui->m_quoteSourceList->item(i)->text() == text) ++nameCount; } // Make sure we get a non-empty and unique name if (text.length() > 0 && nameCount == 1) { d->m_currentItem.rename(text); } else { item->setText(d->m_currentItem.m_name); } d->ui->m_quoteSourceList->sortItems(); d->ui->m_newButton->setEnabled(d->ui->m_quoteSourceList->findItems(i18n("New Quote Source"), Qt::MatchExactly).count() == 0); }
utf-8
1
unknown
unknown
linux-5.16.7/drivers/iio/gyro/fxas21002c.h
/* SPDX-License-Identifier: GPL-2.0 */ /* * Driver for NXP FXAS21002C Gyroscope - Header * * Copyright (C) 2019 Linaro Ltd. */ #ifndef FXAS21002C_H_ #define FXAS21002C_H_ #include <linux/regmap.h> #define FXAS21002C_REG_STATUS 0x00 #define FXAS21002C_REG_OUT_X_MSB 0x01 #define FXAS21002C_REG_OUT_X_LSB 0x02 #define FXAS21002C_REG_OUT_Y_MSB 0x03 #define FXAS21002C_REG_OUT_Y_LSB 0x04 #define FXAS21002C_REG_OUT_Z_MSB 0x05 #define FXAS21002C_REG_OUT_Z_LSB 0x06 #define FXAS21002C_REG_DR_STATUS 0x07 #define FXAS21002C_REG_F_STATUS 0x08 #define FXAS21002C_REG_F_SETUP 0x09 #define FXAS21002C_REG_F_EVENT 0x0A #define FXAS21002C_REG_INT_SRC_FLAG 0x0B #define FXAS21002C_REG_WHO_AM_I 0x0C #define FXAS21002C_REG_CTRL0 0x0D #define FXAS21002C_REG_RT_CFG 0x0E #define FXAS21002C_REG_RT_SRC 0x0F #define FXAS21002C_REG_RT_THS 0x10 #define FXAS21002C_REG_RT_COUNT 0x11 #define FXAS21002C_REG_TEMP 0x12 #define FXAS21002C_REG_CTRL1 0x13 #define FXAS21002C_REG_CTRL2 0x14 #define FXAS21002C_REG_CTRL3 0x15 enum fxas21002c_fields { F_DR_STATUS, F_OUT_X_MSB, F_OUT_X_LSB, F_OUT_Y_MSB, F_OUT_Y_LSB, F_OUT_Z_MSB, F_OUT_Z_LSB, /* DR_STATUS */ F_ZYX_OW, F_Z_OW, F_Y_OW, F_X_OW, F_ZYX_DR, F_Z_DR, F_Y_DR, F_X_DR, /* F_STATUS */ F_OVF, F_WMKF, F_CNT, /* F_SETUP */ F_MODE, F_WMRK, /* F_EVENT */ F_EVENT, FE_TIME, /* INT_SOURCE_FLAG */ F_BOOTEND, F_SRC_FIFO, F_SRC_RT, F_SRC_DRDY, /* WHO_AM_I */ F_WHO_AM_I, /* CTRL_REG0 */ F_BW, F_SPIW, F_SEL, F_HPF_EN, F_FS, /* RT_CFG */ F_ELE, F_ZTEFE, F_YTEFE, F_XTEFE, /* RT_SRC */ F_EA, F_ZRT, F_ZRT_POL, F_YRT, F_YRT_POL, F_XRT, F_XRT_POL, /* RT_THS */ F_DBCNTM, F_THS, /* RT_COUNT */ F_RT_COUNT, /* TEMP */ F_TEMP, /* CTRL_REG1 */ F_RST, F_ST, F_DR, F_ACTIVE, F_READY, /* CTRL_REG2 */ F_INT_CFG_FIFO, F_INT_EN_FIFO, F_INT_CFG_RT, F_INT_EN_RT, F_INT_CFG_DRDY, F_INT_EN_DRDY, F_IPOL, F_PP_OD, /* CTRL_REG3 */ F_WRAPTOONE, F_EXTCTRLEN, F_FS_DOUBLE, /* MAX FIELDS */ F_MAX_FIELDS, }; extern const struct dev_pm_ops fxas21002c_pm_ops; int fxas21002c_core_probe(struct device *dev, struct regmap *regmap, int irq, const char *name); void fxas21002c_core_remove(struct device *dev); #endif
utf-8
1
GPL-2
1991-2012 Linus Torvalds and many others
qonk-0.3.1/src/planets.cpp
// Copyright 2005 by Anthony Liekens anthony@liekens.net #include <math.h> #include "planets.h" #include "timer.h" #include "ships.h" #include "extensions.h" #include "settings.h" #include "animations.h" #include "coordinate.h" #include "selection.h" #include "players.h" #include "universe.h" #include "messages.h" #include "canvas.h" using namespace std; // ##### PLANET ##### Planet::Planet() : nearestPlanet(false), owner(), mother() { rotationSpeed = ( ( rand() % 2 ) * 2 - 1 ) * ( rand() % 60000 + 20000 ); rotationDistance = 0.05 + 0.4 * ( double )rand() / RAND_MAX; rotationOffset = rand() % 10000000; size = 4 + rand() % 4; // [4 ... 8) isAMoon = false; selected = false; sourceSelected = false; shipCreationSpeed = 12500 - size*1000; double angle = rotationOffset / rotationSpeed; locationVector.setX(cos(angle)); locationVector.setY(sin(angle)); buildStartTime = 0; buildEndTime = shipCreationSpeed; } void Planet::makeMoon( Planet* mother ) { rotationSpeed = ( ( rand() % 2 ) * 2 - 1 ) * ( rand() % 2000 + 2000 ); rotationDistance = 0.01 + 0.03 * ( double )rand() / RAND_MAX; rotationOffset = rand() % 100000; size = 2 + rand() % 2; // [2 ... 4) isAMoon = true; this->mother = mother; shipCreationSpeed = 15000 - size*1000; } void Planet::update(Uint32 time) { double angle = (double)(rotationOffset + time) / rotationSpeed; locationVector.setX(cos(angle)); locationVector.setY(sin(angle)); if (buildEndTime <= time) { createShip(time); buildStartTime = time; buildEndTime = time + shipCreationSpeed; } if( residentShips.size() > 0 ) { Coordinate location = getLocation(); int counter = 0; double offset = 500 * rotationDistance + (double) time / 10000; for( list< Ship* >::iterator i = residentShips.begin(); i != residentShips.end(); i++ ) { double shipX = location.getX() + 0.02 * cos( offset + counter * 2 * M_PI / residentShips.size() ); double shipY = location.getY() + 0.02 * sin( offset + counter * 2 * M_PI / residentShips.size() ); (*i)->setLocation( shipX, shipY ); counter++; } } } Coordinate Planet::getLocation() const { Coordinate motherLocation; if( isAMoon ) { motherLocation = mother->getLocation(); } else { motherLocation.setX( 0.5 ); motherLocation.setY( 0.5 ); } double x = motherLocation.getX() + rotationDistance * locationVector.getX(); double y = motherLocation.getY() + rotationDistance * locationVector.getY(); return Coordinate( x, y ); } void Planet::addResident( Ship* ship, Uint32 time ) { if (owner != ship->getOwner()) { // Planet is conquered. if (residentShips.size() == 0) { setOwner(ship->getOwner()); // Plays correspoing animation. // TODO: This should be triggered through player->removePlanet()/addPlanet() Uint32 color = owner->getColor(); universe->animationQueue->scheduleAction(time + 1200, new SonarAnimation(this, color, isAMoon ? 50 : 100, time, time + 1000, true)); residentShips.push_back( ship ); } else { ship->die(); Ship* resident = *( residentShips.begin() ); removeResident( resident ); resident->die(); // show an animation of die'ing ships that are of our interest if( ( ship->getOwner()->getPlayerType() == Player::HUMAN ) || ( owner->getPlayerType() == Player::HUMAN ) ) universe->animationQueue->scheduleAction( time + 1000, new SonarAnimation( this, ship->getOwner()->getColor(), 20, time, time + 1000, true ) ); } } else { residentShips.push_back( ship ); } } void Planet::setOwner(Player *newOwner) { if (owner == newOwner) return; if (owner != NULL) owner->removePlanet(this); newOwner->addPlanet(this); owner = newOwner; } void Planet::removeResident( Ship* ship ) { residentShips.remove( ship ); } void Planet::render(Uint32 time) const { if( owner->getPlayerType() == Player::HUMAN ) renderBuildProgress(time); Coordinate location = getLocation(); Canvas::drawPlanet(location, size, owner->getColor() ); if( selected ) { Canvas::drawSelector(location, -4, 10, 10, 0, 0, 0); Canvas::drawSelector(location, -5, 10, 10, 255, 192, 0); } if( sourceSelected ) { Canvas::drawSelector(location, -4, 10, 10, 0, 0, 0); Canvas::drawSelector(location, -5, 10, 10, 255, 255, 0); } if (nearestPlanet) { Canvas::drawNearestPlanetSelector(location, size); } } void Planet::renderOrbit( ) const { Coordinate centerLocation; if( isAMoon ) { centerLocation = mother->getLocation(); } else { centerLocation.setX( 0.5 ); centerLocation.setY( 0.5 ); } if( owner != NULL ) Canvas::drawOrbit(centerLocation, rotationDistance, owner->getColor()); if( getMoon() ) { mother->renderOrbit( ); } } void Planet::renderBuildProgress(Uint32 time) const { Coordinate location = getLocation(); int x = location.getXMapped(); int y = location.getYMapped(); double percentage = 100.0 * ( time - buildStartTime ) / ( buildEndTime - buildStartTime ); Canvas::drawBuildProgress(location, size, percentage); } double Planet::distance( Planet* planet ) { return planet->getLocation().distance( getLocation() ); } void Planet::setNearestPlanet(bool b) { nearestPlanet = b; } void Planet::setSourceSelected( bool selected ) { sourceSelected = selected; } void Planet::setSelected( bool selected ) { this->selected = selected; } void Planet::setUniverse( Universe* universe ) { this->universe = universe; } void Planet::createShip(const Uint32& time) { if( owner && owner->getPlayerType() != Player::NEUTRAL ) owner->addShip(time, this); } void Planet::moveResidentsTo(Uint32 time, Planet *destination, int fleetSelection) { // Save same fuel ... :) if (destination == this || !residentShips.size()) { return; } // fleetSelection of 1 means "send one ship". Otherwise it means // "send fleetSelection percent of the available ships.". int decampeeCount = (fleetSelection == 1) ? ((residentShips.size() > 0) ? 1 : 0) : (fleetSelection * residentShips.size()) / 100; if (!decampeeCount) return; // Calling Ship->moveTo will affect the residentShips list so we have to // copy the ships which are going for war into their own list. list <Ship *> decampees; for (list <Ship *>::iterator i = residentShips.begin(); decampeeCount > 0; i++) { decampees.push_back(*i); decampeeCount--; } for (list <Ship *>::iterator i = decampees.begin(); i != decampees.end(); i++) { (*i)->moveTo(time + rand() % 500, destination, universe->actionQueue); } } // ##### PLANETS ##### Planets::Planets() { } Planets::Planets( int numberOfPlanets, int numberOfMoons ) { addPlanets( numberOfPlanets ); addMoons( numberOfMoons ); } Planets::~Planets() { for (list < Planet *>::iterator i = begin(); i != end(); i++) { delete *i; } } void Planets::addPlanets( int numberOfPlanets ) { for( int i = 0; i < numberOfPlanets; i++ ) { push_back( new Planet() ); } } void Planets::addMoons( int numberOfMoons ) { if( size() == 0 ) { cerr << "Error constructing moons, no planets yet" << endl; exit( 1 ); } for( int i = 0; i < numberOfMoons; i++ ) { iterator motherPlanet; bool done = false; do { int mother = rand() % size(); motherPlanet = begin(); for( int j = 0; j < mother; j++ ) motherPlanet++; done = !(*motherPlanet)->getMoon(); } while( !done ); Planet *p = new Planet(); p->makeMoon(*motherPlanet); push_back( p ); } } void Planets::render(Uint32 time) const { for( const_iterator i = begin(); i != end(); i++ ) (*i)->render(time); } void Planets::renderOrbits( ) const { for( const_iterator i = begin(); i != end(); i++ ) (*i)->renderOrbit( ); } Planet* Planets::closestToCoordinate( const Coordinate& c ) { double closestDistance = 5000; Planet* closestPlanet = NULL; for( iterator i = begin(); i != end(); i++ ) { double distance = (*i)->getLocation().distance( c ); if( distance < closestDistance ) { closestDistance = distance; closestPlanet = (*i); } } return closestPlanet; } Planet* Planets::closestToCoordinate( const Coordinate& c, double treshold ) { Planet* closest = closestToCoordinate( c ); if( closest->getLocation().distance( c ) < treshold ) return closest; else return NULL; } void Planets::select( Selection selection ) { double minX = selection.getMinX(); double maxX = selection.getMaxX(); double minY = selection.getMinY(); double maxY = selection.getMaxY(); for( iterator i = begin(); i != end(); i++ ) { Coordinate location = (*i)->getLocation(); if( ( location.getX() > minX ) && ( location.getX() < maxX ) && ( location.getY() > minY ) && ( location.getY() < maxY ) ) (*i)->setSelected( true ); else (*i)->setSelected( false ); } } void Planets::sourceSelect( Selection *selection, Player *owner ) { double minX = selection->getMinX(); double maxX = selection->getMaxX(); double minY = selection->getMinY(); double maxY = selection->getMaxY(); for( iterator i = begin(); i != end(); i++ ) { Coordinate location = (*i)->getLocation(); if( ( location.getX() > minX ) && ( location.getX() < maxX ) && ( location.getY() > minY ) && ( location.getY() < maxY ) && (*i)->getOwner() == owner ) (*i)->setSourceSelected( true ); else (*i)->setSourceSelected( false ); } } void Planets::update(Uint32 time) { for( iterator i = begin(); i != end(); i++ ) (*i)->update(time); } void Planets::setUniverse( Universe* universe ) { for( iterator i = begin(); i != end(); i++ ) (*i)->setUniverse( universe ); } Planet* Planets::getRandomPlanet() { int number = rand() % size(); iterator i = begin(); for( int k = 0; k < number; k++ ) i++; return (*i); } Planet* Planets::getRandomEnemyPlanet( Player* player ) { // TODO: This has to be implemented } Planet* Planets::getRandomNearbyPlanet( Planet* planet ) { Planet* result; do { result = getRandomPlanet(); } while( result == planet ); double distance = planet->distance( result ); for( int i = 0; i < size() / 2; i++ ) { Planet* otherPlanet; do { otherPlanet = getRandomPlanet(); } while( otherPlanet == planet ); double otherDistance = planet->distance( otherPlanet ); // which planets do we prefer? if( otherPlanet->getOwner() != planet->getOwner() ) otherDistance *= 0.1; if( otherPlanet->getOwner()->getPlayerType() == Player::NEUTRAL ) otherDistance *= 0.5; if( ! otherPlanet->getMoon() ) otherDistance *= 0.8; if( otherDistance < distance ) { result = otherPlanet; distance = otherDistance; } } return result; } // ##### CREATESHIPACTION ##### CreateShipAction::CreateShipAction(Planet *planet ) { this->planet = planet; actionID = 1; } void CreateShipAction::execute( const Uint32& time ) { planet->createShip(time); }
utf-8
1
unknown
unknown
r-cran-git2r-0.29.0/src/libgit2/src/odb_pack.c
/* * Copyright (C) the libgit2 contributors. All rights reserved. * * This file is part of libgit2, distributed under the GNU GPL v2 with * a Linking Exception. For full terms see the included COPYING file. */ #include "common.h" #include <zlib.h> #include "git2/repository.h" #include "git2/indexer.h" #include "git2/sys/odb_backend.h" #include "delta.h" #include "futils.h" #include "hash.h" #include "midx.h" #include "mwindow.h" #include "odb.h" #include "pack.h" #include "git2/odb_backend.h" /* re-freshen pack files no more than every 2 seconds */ #define FRESHEN_FREQUENCY 2 struct pack_backend { git_odb_backend parent; git_midx_file *midx; git_vector midx_packs; git_vector packs; struct git_pack_file *last_found; char *pack_folder; }; struct pack_writepack { struct git_odb_writepack parent; git_indexer *indexer; }; /** * The wonderful tale of a Packed Object lookup query * =================================================== * A riveting and epic story of epicness and ASCII * art, presented by yours truly, * Sir Vicent of Marti * * * Chapter 1: Once upon a time... * Initialization of the Pack Backend * -------------------------------------------------- * * # git_odb_backend_pack * | Creates the pack backend structure, initializes the * | callback pointers to our default read() and exist() methods, * | and tries to find the `pack` folder, if it exists. ODBs without a `pack` * | folder are ignored altogether. If there is a `pack` folder, it tries to * | preload all the known packfiles in the ODB. * | * |-# pack_backend__refresh * | The `multi-pack-index` is loaded if it exists and is valid. * | Then we run a `dirent` callback through every file in the pack folder, * | even those present in `multi-pack-index`. The unindexed packfiles are * | then sorted according to a sorting callback. * | * |-# refresh_multi_pack_index * | Detect the presence of the `multi-pack-index` file. If it needs to be * | refreshed, frees the old copy and tries to load the new one, together * | with all the packfiles it indexes. If the process fails, fall back to * | the old behavior, as if the `multi-pack-index` file was not there. * | * |-# packfile_load__cb * | | This callback is called from `dirent` with every single file * | | inside the pack folder. We find the packs by actually locating * | | their index (ends in ".idx"). From that index, we verify that * | | the corresponding packfile exists and is valid, and if so, we * | | add it to the pack list. * | | * | # git_mwindow_get_pack * | Make sure that there's a packfile to back this index, and store * | some very basic information regarding the packfile itself, * | such as the full path, the size, and the modification time. * | We don't actually open the packfile to check for internal consistency. * | * |-# packfile_sort__cb * Sort all the preloaded packs according to some specific criteria: * we prioritize the "newer" packs because it's more likely they * contain the objects we are looking for, and we prioritize local * packs over remote ones. * * * * Chapter 2: To be, or not to be... * A standard packed `exist` query for an OID * -------------------------------------------------- * * # pack_backend__exists / pack_backend__exists_prefix * | Check if the given SHA1 oid (or a SHA1 oid prefix) exists in any of the * | packs that have been loaded for our ODB. * | * |-# pack_entry_find / pack_entry_find_prefix * | If there is a multi-pack-index present, search the SHA1 oid in that * | index first. If it is not found there, iterate through all the unindexed * | packs that have been preloaded (starting by the pack where the latest * | object was found) to try to find the OID in one of them. * | * |-# git_midx_entry_find * | Search for the SHA1 oid in the multi-pack-index. See * | <https://github.com/git/git/blob/master/Documentation/technical/pack-format.txt> * | for specifics on the multi-pack-index format and how do we find * | entries in it. * | * |-# git_pack_entry_find * | Check the index of an individual unindexed pack to see if the SHA1 * | OID can be found. If we can find the offset to that SHA1 inside of the * | index, that means the object is contained inside of the packfile and * | we can stop searching. Before returning, we verify that the * | packfile behing the index we are searching still exists on disk. * | * |-# pack_entry_find_offset * | Mmap the actual index file to disk if it hasn't been opened * | yet, and run a binary search through it to find the OID. * | See <https://github.com/git/git/blob/master/Documentation/technical/pack-format.txt> * | for specifics on the Packfile Index format and how do we find * | entries in it. * | * |-# pack_index_open * | Guess the name of the index based on the full path to the * | packfile, open it and verify its contents. Only if the index * | has not been opened already. * | * |-# pack_index_check * Mmap the index file and do a quick run through the header * to guess the index version (right now we support v1 and v2), * and to verify that the size of the index makes sense. * * * * Chapter 3: The neverending story... * A standard packed `lookup` query for an OID * -------------------------------------------------- * * # pack_backend__read / pack_backend__read_prefix * | Check if the given SHA1 oid (or a SHA1 oid prefix) exists in any of the * | packs that have been loaded for our ODB. If it does, open the packfile and * | read from it. * | * |-# git_packfile_unpack * Armed with a packfile and the offset within it, we can finally unpack * the object pointed at by the SHA1 oid. This involves mmapping part of * the `.pack` file, and uncompressing the object within it (if it is * stored in the undelfitied representation), or finding a base object and * applying some deltas to its uncompressed representation (if it is stored * in the deltified representation). See * <https://github.com/git/git/blob/master/Documentation/technical/pack-format.txt> * for specifics on the Packfile format and how do we read from it. * */ /*********************************************************** * * FORWARD DECLARATIONS * ***********************************************************/ static int packfile_sort__cb(const void *a_, const void *b_); static int packfile_load__cb(void *_data, git_buf *path); static int packfile_byname_search_cmp(const void *path, const void *pack_entry); static int pack_entry_find(struct git_pack_entry *e, struct pack_backend *backend, const git_oid *oid); /* Can find the offset of an object given * a prefix of an identifier. * Sets GIT_EAMBIGUOUS if short oid is ambiguous. * This method assumes that len is between * GIT_OID_MINPREFIXLEN and GIT_OID_HEXSZ. */ static int pack_entry_find_prefix( struct git_pack_entry *e, struct pack_backend *backend, const git_oid *short_oid, size_t len); /*********************************************************** * * PACK WINDOW MANAGEMENT * ***********************************************************/ static int packfile_byname_search_cmp(const void *path_, const void *p_) { const git_buf *path = (const git_buf *)path_; const struct git_pack_file *p = (const struct git_pack_file *)p_; return strncmp(p->pack_name, git_buf_cstr(path), git_buf_len(path)); } static int packfile_sort__cb(const void *a_, const void *b_) { const struct git_pack_file *a = a_; const struct git_pack_file *b = b_; int st; /* * Local packs tend to contain objects specific to our * variant of the project than remote ones. In addition, * remote ones could be on a network mounted filesystem. * Favor local ones for these reasons. */ st = a->pack_local - b->pack_local; if (st) return -st; /* * Younger packs tend to contain more recent objects, * and more recent objects tend to get accessed more * often. */ if (a->mtime < b->mtime) return 1; else if (a->mtime == b->mtime) return 0; return -1; } static int packfile_load__cb(void *data, git_buf *path) { struct pack_backend *backend = data; struct git_pack_file *pack; const char *path_str = git_buf_cstr(path); git_buf index_prefix = GIT_BUF_INIT; size_t cmp_len = git_buf_len(path); int error; if (cmp_len <= strlen(".idx") || git__suffixcmp(path_str, ".idx") != 0) return 0; /* not an index */ cmp_len -= strlen(".idx"); git_buf_attach_notowned(&index_prefix, path_str, cmp_len); if (git_vector_search2(NULL, &backend->midx_packs, packfile_byname_search_cmp, &index_prefix) == 0) return 0; if (git_vector_search2(NULL, &backend->packs, packfile_byname_search_cmp, &index_prefix) == 0) return 0; error = git_mwindow_get_pack(&pack, path->ptr); /* ignore missing .pack file as git does */ if (error == GIT_ENOTFOUND) { git_error_clear(); return 0; } if (!error) error = git_vector_insert(&backend->packs, pack); return error; } static int pack_entry_find(struct git_pack_entry *e, struct pack_backend *backend, const git_oid *oid) { struct git_pack_file *last_found = backend->last_found, *p; git_midx_entry midx_entry; size_t i; if (backend->midx && git_midx_entry_find(&midx_entry, backend->midx, oid, GIT_OID_HEXSZ) == 0 && midx_entry.pack_index < git_vector_length(&backend->midx_packs)) { e->offset = midx_entry.offset; git_oid_cpy(&e->sha1, &midx_entry.sha1); e->p = git_vector_get(&backend->midx_packs, midx_entry.pack_index); return 0; } if (last_found && git_pack_entry_find(e, last_found, oid, GIT_OID_HEXSZ) == 0) return 0; git_vector_foreach(&backend->packs, i, p) { if (p == last_found) continue; if (git_pack_entry_find(e, p, oid, GIT_OID_HEXSZ) == 0) { backend->last_found = p; return 0; } } return git_odb__error_notfound( "failed to find pack entry", oid, GIT_OID_HEXSZ); } static int pack_entry_find_prefix( struct git_pack_entry *e, struct pack_backend *backend, const git_oid *short_oid, size_t len) { int error; size_t i; git_oid found_full_oid = {{0}}; bool found = false; struct git_pack_file *last_found = backend->last_found, *p; git_midx_entry midx_entry; if (backend->midx) { error = git_midx_entry_find(&midx_entry, backend->midx, short_oid, len); if (error == GIT_EAMBIGUOUS) return error; if (!error && midx_entry.pack_index < git_vector_length(&backend->midx_packs)) { e->offset = midx_entry.offset; git_oid_cpy(&e->sha1, &midx_entry.sha1); e->p = git_vector_get(&backend->midx_packs, midx_entry.pack_index); git_oid_cpy(&found_full_oid, &e->sha1); found = true; } } if (last_found) { error = git_pack_entry_find(e, last_found, short_oid, len); if (error == GIT_EAMBIGUOUS) return error; if (!error) { if (found && git_oid_cmp(&e->sha1, &found_full_oid)) return git_odb__error_ambiguous("found multiple pack entries"); git_oid_cpy(&found_full_oid, &e->sha1); found = true; } } git_vector_foreach(&backend->packs, i, p) { if (p == last_found) continue; error = git_pack_entry_find(e, p, short_oid, len); if (error == GIT_EAMBIGUOUS) return error; if (!error) { if (found && git_oid_cmp(&e->sha1, &found_full_oid)) return git_odb__error_ambiguous("found multiple pack entries"); git_oid_cpy(&found_full_oid, &e->sha1); found = true; backend->last_found = p; } } if (!found) return git_odb__error_notfound("no matching pack entry for prefix", short_oid, len); else return 0; } /*********************************************************** * * MULTI-PACK-INDEX SUPPORT * * Functions needed to support the multi-pack-index. * ***********************************************************/ /* * Remove the multi-pack-index, and move all midx_packs to packs. */ static int remove_multi_pack_index(struct pack_backend *backend) { size_t i, j = git_vector_length(&backend->packs); struct pack_backend *p; int error = git_vector_size_hint( &backend->packs, j + git_vector_length(&backend->midx_packs)); if (error < 0) return error; git_vector_foreach(&backend->midx_packs, i, p) git_vector_set(NULL, &backend->packs, j++, p); git_vector_clear(&backend->midx_packs); git_midx_free(backend->midx); backend->midx = NULL; return 0; } /* * Loads a single .pack file referred to by the multi-pack-index. These must * match the order in which they are declared in the multi-pack-index file, * since these files are referred to by their index. */ static int process_multi_pack_index_pack( struct pack_backend *backend, size_t i, const char *packfile_name) { int error; struct git_pack_file *pack; size_t found_position; git_buf pack_path = GIT_BUF_INIT, index_prefix = GIT_BUF_INIT; error = git_buf_joinpath(&pack_path, backend->pack_folder, packfile_name); if (error < 0) return error; /* This is ensured by midx_parse_packfile_name() */ if (git_buf_len(&pack_path) <= strlen(".idx") || git__suffixcmp(git_buf_cstr(&pack_path), ".idx") != 0) return git_odb__error_notfound("midx file contained a non-index", NULL, 0); git_buf_attach_notowned(&index_prefix, git_buf_cstr(&pack_path), git_buf_len(&pack_path) - strlen(".idx")); if (git_vector_search2(&found_position, &backend->packs, packfile_byname_search_cmp, &index_prefix) == 0) { /* Pack was found in the packs list. Moving it to the midx_packs list. */ git_buf_dispose(&pack_path); git_vector_set(NULL, &backend->midx_packs, i, git_vector_get(&backend->packs, found_position)); git_vector_remove(&backend->packs, found_position); return 0; } /* Pack was not found. Allocate a new one. */ error = git_mwindow_get_pack(&pack, git_buf_cstr(&pack_path)); git_buf_dispose(&pack_path); if (error < 0) return error; git_vector_set(NULL, &backend->midx_packs, i, pack); return 0; } /* * Reads the multi-pack-index. If this fails for whatever reason, the * multi-pack-index object is freed, and all the packfiles that are related to * it are moved to the unindexed packfiles vector. */ static int refresh_multi_pack_index(struct pack_backend *backend) { int error; git_buf midx_path = GIT_BUF_INIT; const char *packfile_name; size_t i; error = git_buf_joinpath(&midx_path, backend->pack_folder, "multi-pack-index"); if (error < 0) return error; /* * Check whether the multi-pack-index has changed. If it has, close any * old multi-pack-index and move all the packfiles to the unindexed * packs. This is done to prevent losing any open packfiles in case * refreshing the new multi-pack-index fails, or the file is deleted. */ if (backend->midx) { if (!git_midx_needs_refresh(backend->midx, git_buf_cstr(&midx_path))) { git_buf_dispose(&midx_path); return 0; } error = remove_multi_pack_index(backend); if (error < 0) { git_buf_dispose(&midx_path); return error; } } error = git_midx_open(&backend->midx, git_buf_cstr(&midx_path)); git_buf_dispose(&midx_path); if (error < 0) return error; git_vector_resize_to(&backend->midx_packs, git_vector_length(&backend->midx->packfile_names)); git_vector_foreach(&backend->midx->packfile_names, i, packfile_name) { error = process_multi_pack_index_pack(backend, i, packfile_name); if (error < 0) { /* * Something failed during reading multi-pack-index. * Restore the state of backend as if the * multi-pack-index was never there, and move all * packfiles that have been processed so far to the * unindexed packs. */ git_vector_resize_to(&backend->midx_packs, i); remove_multi_pack_index(backend); return error; } } return 0; } /*********************************************************** * * PACKED BACKEND PUBLIC API * * Implement the git_odb_backend API calls * ***********************************************************/ static int pack_backend__refresh(git_odb_backend *backend_) { int error; struct stat st; git_buf path = GIT_BUF_INIT; struct pack_backend *backend = (struct pack_backend *)backend_; if (backend->pack_folder == NULL) return 0; if (p_stat(backend->pack_folder, &st) < 0 || !S_ISDIR(st.st_mode)) return git_odb__error_notfound("failed to refresh packfiles", NULL, 0); if (refresh_multi_pack_index(backend) < 0) { /* * It is okay if this fails. We will just not use the * multi-pack-index in this case. */ git_error_clear(); } /* reload all packs */ git_buf_sets(&path, backend->pack_folder); error = git_path_direach(&path, 0, packfile_load__cb, backend); git_buf_dispose(&path); git_vector_sort(&backend->packs); return error; } static int pack_backend__read_header( size_t *len_p, git_object_t *type_p, struct git_odb_backend *backend, const git_oid *oid) { struct git_pack_entry e; int error; GIT_ASSERT_ARG(len_p); GIT_ASSERT_ARG(type_p); GIT_ASSERT_ARG(backend); GIT_ASSERT_ARG(oid); if ((error = pack_entry_find(&e, (struct pack_backend *)backend, oid)) < 0) return error; return git_packfile_resolve_header(len_p, type_p, e.p, e.offset); } static int pack_backend__freshen( git_odb_backend *backend, const git_oid *oid) { struct git_pack_entry e; time_t now; int error; if ((error = pack_entry_find(&e, (struct pack_backend *)backend, oid)) < 0) return error; now = time(NULL); if (e.p->last_freshen > now - FRESHEN_FREQUENCY) return 0; if ((error = git_futils_touch(e.p->pack_name, &now)) < 0) return error; e.p->last_freshen = now; return 0; } static int pack_backend__read( void **buffer_p, size_t *len_p, git_object_t *type_p, git_odb_backend *backend, const git_oid *oid) { struct git_pack_entry e; git_rawobj raw = {NULL}; int error; if ((error = pack_entry_find(&e, (struct pack_backend *)backend, oid)) < 0 || (error = git_packfile_unpack(&raw, e.p, &e.offset)) < 0) return error; *buffer_p = raw.data; *len_p = raw.len; *type_p = raw.type; return 0; } static int pack_backend__read_prefix( git_oid *out_oid, void **buffer_p, size_t *len_p, git_object_t *type_p, git_odb_backend *backend, const git_oid *short_oid, size_t len) { int error = 0; if (len < GIT_OID_MINPREFIXLEN) error = git_odb__error_ambiguous("prefix length too short"); else if (len >= GIT_OID_HEXSZ) { /* We can fall back to regular read method */ error = pack_backend__read(buffer_p, len_p, type_p, backend, short_oid); if (!error) git_oid_cpy(out_oid, short_oid); } else { struct git_pack_entry e; git_rawobj raw = {NULL}; if ((error = pack_entry_find_prefix( &e, (struct pack_backend *)backend, short_oid, len)) == 0 && (error = git_packfile_unpack(&raw, e.p, &e.offset)) == 0) { *buffer_p = raw.data; *len_p = raw.len; *type_p = raw.type; git_oid_cpy(out_oid, &e.sha1); } } return error; } static int pack_backend__exists(git_odb_backend *backend, const git_oid *oid) { struct git_pack_entry e; return pack_entry_find(&e, (struct pack_backend *)backend, oid) == 0; } static int pack_backend__exists_prefix( git_oid *out, git_odb_backend *backend, const git_oid *short_id, size_t len) { int error; struct pack_backend *pb = (struct pack_backend *)backend; struct git_pack_entry e = {0}; error = pack_entry_find_prefix(&e, pb, short_id, len); git_oid_cpy(out, &e.sha1); return error; } static int pack_backend__foreach(git_odb_backend *_backend, git_odb_foreach_cb cb, void *data) { int error; struct git_pack_file *p; struct pack_backend *backend; unsigned int i; GIT_ASSERT_ARG(_backend); GIT_ASSERT_ARG(cb); backend = (struct pack_backend *)_backend; /* Make sure we know about the packfiles */ if ((error = pack_backend__refresh(_backend)) != 0) return error; if (backend->midx && (error = git_midx_foreach_entry(backend->midx, cb, data)) != 0) return error; git_vector_foreach(&backend->packs, i, p) { if ((error = git_pack_foreach_entry(p, cb, data)) != 0) return error; } return 0; } static int pack_backend__writepack_append(struct git_odb_writepack *_writepack, const void *data, size_t size, git_indexer_progress *stats) { struct pack_writepack *writepack = (struct pack_writepack *)_writepack; GIT_ASSERT_ARG(writepack); return git_indexer_append(writepack->indexer, data, size, stats); } static int pack_backend__writepack_commit(struct git_odb_writepack *_writepack, git_indexer_progress *stats) { struct pack_writepack *writepack = (struct pack_writepack *)_writepack; GIT_ASSERT_ARG(writepack); return git_indexer_commit(writepack->indexer, stats); } static void pack_backend__writepack_free(struct git_odb_writepack *_writepack) { struct pack_writepack *writepack; if (!_writepack) return; writepack = (struct pack_writepack *)_writepack; git_indexer_free(writepack->indexer); git__free(writepack); } static int pack_backend__writepack(struct git_odb_writepack **out, git_odb_backend *_backend, git_odb *odb, git_indexer_progress_cb progress_cb, void *progress_payload) { git_indexer_options opts = GIT_INDEXER_OPTIONS_INIT; struct pack_backend *backend; struct pack_writepack *writepack; GIT_ASSERT_ARG(out); GIT_ASSERT_ARG(_backend); *out = NULL; opts.progress_cb = progress_cb; opts.progress_cb_payload = progress_payload; backend = (struct pack_backend *)_backend; writepack = git__calloc(1, sizeof(struct pack_writepack)); GIT_ERROR_CHECK_ALLOC(writepack); if (git_indexer_new(&writepack->indexer, backend->pack_folder, 0, odb, &opts) < 0) { git__free(writepack); return -1; } writepack->parent.backend = _backend; writepack->parent.append = pack_backend__writepack_append; writepack->parent.commit = pack_backend__writepack_commit; writepack->parent.free = pack_backend__writepack_free; *out = (git_odb_writepack *)writepack; return 0; } static int get_idx_path( git_buf *idx_path, struct pack_backend *backend, struct git_pack_file *p) { size_t path_len; int error; error = git_path_prettify(idx_path, p->pack_name, backend->pack_folder); if (error < 0) return error; path_len = git_buf_len(idx_path); if (path_len <= strlen(".pack") || git__suffixcmp(git_buf_cstr(idx_path), ".pack") != 0) return git_odb__error_notfound("packfile does not end in .pack", NULL, 0); path_len -= strlen(".pack"); error = git_buf_splice(idx_path, path_len, strlen(".pack"), ".idx", strlen(".idx")); if (error < 0) return error; return 0; } static int pack_backend__writemidx(git_odb_backend *_backend) { struct pack_backend *backend; git_midx_writer *w = NULL; struct git_pack_file *p; size_t i; int error = 0; GIT_ASSERT_ARG(_backend); backend = (struct pack_backend *)_backend; error = git_midx_writer_new(&w, backend->pack_folder); if (error < 0) return error; git_vector_foreach(&backend->midx_packs, i, p) { git_buf idx_path = GIT_BUF_INIT; error = get_idx_path(&idx_path, backend, p); if (error < 0) goto cleanup; error = git_midx_writer_add(w, git_buf_cstr(&idx_path)); git_buf_dispose(&idx_path); if (error < 0) goto cleanup; } git_vector_foreach(&backend->packs, i, p) { git_buf idx_path = GIT_BUF_INIT; error = get_idx_path(&idx_path, backend, p); if (error < 0) goto cleanup; error = git_midx_writer_add(w, git_buf_cstr(&idx_path)); git_buf_dispose(&idx_path); if (error < 0) goto cleanup; } /* * Invalidate the previous midx before writing the new one. */ error = remove_multi_pack_index(backend); if (error < 0) goto cleanup; error = git_midx_writer_commit(w); if (error < 0) goto cleanup; error = refresh_multi_pack_index(backend); cleanup: git_midx_writer_free(w); return error; } static void pack_backend__free(git_odb_backend *_backend) { struct pack_backend *backend; struct git_pack_file *p; size_t i; if (!_backend) return; backend = (struct pack_backend *)_backend; git_vector_foreach(&backend->midx_packs, i, p) git_mwindow_put_pack(p); git_vector_foreach(&backend->packs, i, p) git_mwindow_put_pack(p); git_midx_free(backend->midx); git_vector_free(&backend->midx_packs); git_vector_free(&backend->packs); git__free(backend->pack_folder); git__free(backend); } static int pack_backend__alloc(struct pack_backend **out, size_t initial_size) { struct pack_backend *backend = git__calloc(1, sizeof(struct pack_backend)); GIT_ERROR_CHECK_ALLOC(backend); if (git_vector_init(&backend->midx_packs, 0, NULL) < 0) { git__free(backend); return -1; } if (git_vector_init(&backend->packs, initial_size, packfile_sort__cb) < 0) { git_vector_free(&backend->midx_packs); git__free(backend); return -1; } backend->parent.version = GIT_ODB_BACKEND_VERSION; backend->parent.read = &pack_backend__read; backend->parent.read_prefix = &pack_backend__read_prefix; backend->parent.read_header = &pack_backend__read_header; backend->parent.exists = &pack_backend__exists; backend->parent.exists_prefix = &pack_backend__exists_prefix; backend->parent.refresh = &pack_backend__refresh; backend->parent.foreach = &pack_backend__foreach; backend->parent.writepack = &pack_backend__writepack; backend->parent.writemidx = &pack_backend__writemidx; backend->parent.freshen = &pack_backend__freshen; backend->parent.free = &pack_backend__free; *out = backend; return 0; } int git_odb_backend_one_pack(git_odb_backend **backend_out, const char *idx) { struct pack_backend *backend = NULL; struct git_pack_file *packfile = NULL; if (pack_backend__alloc(&backend, 1) < 0) return -1; if (git_mwindow_get_pack(&packfile, idx) < 0 || git_vector_insert(&backend->packs, packfile) < 0) { pack_backend__free((git_odb_backend *)backend); return -1; } *backend_out = (git_odb_backend *)backend; return 0; } int git_odb_backend_pack(git_odb_backend **backend_out, const char *objects_dir) { int error = 0; struct pack_backend *backend = NULL; git_buf path = GIT_BUF_INIT; if (pack_backend__alloc(&backend, 8) < 0) return -1; if (!(error = git_buf_joinpath(&path, objects_dir, "pack")) && git_path_isdir(git_buf_cstr(&path))) { backend->pack_folder = git_buf_detach(&path); error = pack_backend__refresh((git_odb_backend *)backend); } if (error < 0) { pack_backend__free((git_odb_backend *)backend); backend = NULL; } *backend_out = (git_odb_backend *)backend; git_buf_dispose(&path); return error; }
utf-8
1
GPL-2
2014-2018 Stefan Widgren <stefan.widgren@gmail.com>
gcc-avr-5.4.0+Atmel3.6.2/gcc/gcc/testsuite/c-c++-common/goacc/data-2.c
void foo (void) { int a, b[100]; int n; #pragma acc enter data copyin (a, b) async wait #pragma acc enter data create (b[20:30]) async wait #pragma acc enter data (a) /* { dg-error "expected '#pragma acc' clause before '\\\(' token" } */ #pragma acc enter data create (b(1:10)) /* { dg-error "expected '\\\)' before '\\\(' token" } */ #pragma acc exit data delete (a) if (0) #pragma acc exit data copyout (b) if (a) #pragma acc exit data delete (b) #pragma acc enter /* { dg-error "expected 'data' in" } */ #pragma acc exit /* { dg-error "expected 'data' in" } */ #pragma acc enter data /* { dg-error "has no data movement clause" } */ #pragma acc exit data /* { dg-error "has no data movement clause" } */ #pragma acc enter Data /* { dg-error "invalid pragma before" } */ #pragma acc exit copyout (b) /* { dg-error "invalid pragma before" } */ } /* { dg-error "has no data movement clause" "" { target *-*-* } 8 } */
utf-8
1
unknown
unknown
wireshark-3.6.2/ui/qt/capture_filter_syntax_worker.cpp
/* capture_filter_syntax_worker.cpp * * Wireshark - Network traffic analyzer * By Gerald Combs <gerald@wireshark.org> * Copyright 1998 Gerald Combs * * SPDX-License-Identifier: GPL-2.0-or-later */ #include "config.h" #ifdef HAVE_LIBPCAP #include <glib.h> #include "wspcap.h" #include "capture_opts.h" #include "ui/capture_globals.h" #endif #include "extcap.h" #include "capture_filter_syntax_worker.h" #include <ui/qt/widgets/syntax_line_edit.h> #include <QMutexLocker> #include <QSet> // We use a global mutex to protect pcap_compile since it calls gethostbyname. // This probably isn't needed on Windows (where pcap_comple calls // EnterCriticalSection + LeaveCriticalSection) or *BSD or macOS where // gethostbyname(3) claims that it's thread safe. static QMutex pcap_compile_mtx_; #if 0 #include <QDebug> #include <QThread> #define DEBUG_SYNTAX_CHECK(state1, state2) qDebug() << "CF state" << QThread::currentThreadId() << state1 << "->" << state2 << ":" << filter #define DEBUG_SLEEP_TIME 5000 // ms #else #define DEBUG_SYNTAX_CHECK(state1, state2) #define DEBUG_SLEEP_TIME 0 // ms #endif #define DUMMY_SNAPLENGTH 65535 #define DUMMY_NETMASK 0xFF000000 void CaptureFilterSyntaxWorker::checkFilter(const QString filter) { #ifdef HAVE_LIBPCAP QSet<gint> active_dlts; QSet<guint> active_extcap; struct bpf_program fcode; pcap_t *pd; int pc_err; enum SyntaxLineEdit::SyntaxState state = SyntaxLineEdit::Valid; QString err_str; DEBUG_SYNTAX_CHECK("received", "?"); if (global_capture_opts.num_selected < 1) { emit syntaxResult(filter, SyntaxLineEdit::Invalid, QString("No interfaces selected")); DEBUG_SYNTAX_CHECK("unknown", "no interfaces"); return; } for (guint if_idx = 0; if_idx < global_capture_opts.all_ifaces->len; if_idx++) { interface_t *device; device = &g_array_index(global_capture_opts.all_ifaces, interface_t, if_idx); if (device->selected) { if (device->if_info.extcap == NULL || strlen(device->if_info.extcap) == 0) { if (device->active_dlt >= DLT_USER0 && device->active_dlt <= DLT_USER15) { // Capture filter for DLT_USER is unknown state = SyntaxLineEdit::Deprecated; err_str = "Unable to check capture filter"; } else { active_dlts.insert(device->active_dlt); } } else { active_extcap.insert(if_idx); } } } foreach(gint dlt, active_dlts.values()) { pcap_compile_mtx_.lock(); pd = pcap_open_dead(dlt, DUMMY_SNAPLENGTH); if (pd == NULL) { //don't have ability to verify capture filter break; } #ifdef PCAP_NETMASK_UNKNOWN pc_err = pcap_compile(pd, &fcode, filter.toUtf8().data(), 1 /* Do optimize */, PCAP_NETMASK_UNKNOWN); #else pc_err = pcap_compile(pd, &fcode, filter.toUtf8().data(), 1 /* Do optimize */, 0); #endif #if DEBUG_SLEEP_TIME > 0 QThread::msleep(DEBUG_SLEEP_TIME); #endif if (pc_err) { DEBUG_SYNTAX_CHECK("unknown", "known bad"); state = SyntaxLineEdit::Invalid; err_str = pcap_geterr(pd); } else { DEBUG_SYNTAX_CHECK("unknown", "known good"); } pcap_close(pd); pcap_compile_mtx_.unlock(); if (state == SyntaxLineEdit::Invalid) break; } // If it's already invalid, don't bother to check extcap if (state != SyntaxLineEdit::Invalid) { foreach(guint extcapif, active_extcap.values()) { interface_t *device; gchar *error = NULL; device = &g_array_index(global_capture_opts.all_ifaces, interface_t, extcapif); extcap_filter_status status = extcap_verify_capture_filter(device->name, filter.toUtf8().constData(), &error); if (status == EXTCAP_FILTER_VALID) { DEBUG_SYNTAX_CHECK("unknown", "known good"); } else if (status == EXTCAP_FILTER_INVALID) { DEBUG_SYNTAX_CHECK("unknown", "known bad"); state = SyntaxLineEdit::Invalid; err_str = error; break; } else { state = SyntaxLineEdit::Deprecated; err_str = "Unable to check capture filter"; } g_free(error); } } emit syntaxResult(filter, state, err_str); DEBUG_SYNTAX_CHECK("known", "idle"); #else emit syntaxResult(filter, SyntaxLineEdit::Deprecated, QString("Syntax checking unavailable")); #endif // HAVE_LIBPCAP }
utf-8
1
GPL-2+
Gerald Combs <gerald@wireshark.org> and contributors
cantata-2.4.2.ds1/devices/devicespage.h
/* * Cantata * * Copyright (c) 2011-2020 Craig Drummond <craig.p.drummond@gmail.com> * * ---- * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; see the file COPYING. If not, write to * the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, * Boston, MA 02110-1301, USA. */ #ifndef DEVICESPAGE_H #define DEVICESPAGE_H #include "device.h" #include "widgets/singlepagewidget.h" #ifdef ENABLE_REMOTE_DEVICES #include "remotefsdevice.h" #endif #include "cdalbum.h" #include "models/musiclibraryproxymodel.h" class Action; class DevicesPage : public SinglePageWidget { Q_OBJECT public: DevicesPage(QWidget *p); ~DevicesPage() override; void clear(); QString activeFsDeviceUdi() const; QStringList playableUrls() const; QList<Song> selectedSongs(bool allowPlaylists=false) const override; void addSelectionToPlaylist(const QString &name=QString(), int action=MPDConnection::Append, quint8 priority=0, bool decreasePriority=false) override; void focusSearch() override { view->focusSearch(); } void refresh() override; void resort() { proxy.sort(); } public Q_SLOTS: void itemDoubleClicked(const QModelIndex &); void searchItems(); void controlActions() override; void copyToLibrary(); void configureDevice(); void refreshDevice(); void deleteSongs() override; void addRemoteDevice(); void forgetRemoteDevice(); void sync(); void toggleDevice(); void updated(const QModelIndex &idx); void cdMatches(const QString &udi, const QList<CdAlbum> &albums); void editDetails(); private: Device * activeFsDevice() const; Q_SIGNALS: void addToDevice(const QString &from, const QString &to, const QList<Song> &songs); void deleteSongs(const QString &from, const QList<Song> &songs); private: MusicLibraryProxyModel proxy; Action *copyAction; Action *syncAction; #ifdef ENABLE_REMOTE_DEVICES Action *forgetDeviceAction; #endif }; #endif
utf-8
1
GPL-2+
2011-2018, Craig Drummond <craig.p.drummond@gmail.com>
plasma-nm-5.23.5/kded/modemmonitor.h
/* SPDX-FileCopyrightText: 2009 Will Stephenson <wstephenson@kde.org> SPDX-FileCopyrightText: 2013 Lukas Tinkl <ltinkl@redhat.com> SPDX-FileCopyrightText: 2014 Jan Grulich <jgrulich@redhat.com> SPDX-License-Identifier: LGPL-2.1-only OR LGPL-3.0-only OR LicenseRef-KDE-Accepted-LGPL */ #ifndef PLASMA_NM_MODEM_MONITOR_H #define PLASMA_NM_MODEM_MONITOR_H #include <QDBusPendingCallWatcher> #include <QObject> #include <ModemManagerQt/Modem> #include <ModemManagerQt/ModemDevice> class ModemMonitorPrivate; /** * Monitors modem hardware and provides a PIN unlock dialog */ class Q_DECL_EXPORT ModemMonitor : public QObject { Q_OBJECT Q_DECLARE_PRIVATE(ModemMonitor) public: explicit ModemMonitor(QObject *parent); ~ModemMonitor() override; public Q_SLOTS: void unlockModem(const QString &modemUni); private Q_SLOTS: void requestPin(MMModemLock lock); void onSendPinArrived(QDBusPendingCallWatcher *); private: ModemMonitorPrivate *d_ptr; }; #endif // PLASMA_NM_MODEM_MONITOR_H
utf-8
1
LGPL-2.1+3+KDEeV
2013, Daniel Nicoletti <dantti12@gmail.com> 2011, Ilia Kats <ilia-kats@gmx.de> 2011, Ilia Kats <ilia-kats@gmx.net> 2013-2014, Jan Grulich <jgrulich@redhat.com> 2010-2013, Lamarque V. Souza <lamarque@kde.org> 2013-2014, Lukas Tinkl <ltinkl@redhat.com> 2010, Sebastian Kügler <sebas@kde.org> 2008-2009, Will Stephenson <wstephenson@kde.org> 2014, Xuetian Weng <wengxt@gmail.com>
codelite-14.0+dfsg/CodeLite/codelite_events.cpp
#include "codelite_events.h" wxDEFINE_EVENT(wxEVT_FILE_DELETED, clFileSystemEvent); wxDEFINE_EVENT(wxEVT_FOLDER_DELETED, clFileSystemEvent); wxDEFINE_EVENT(wxEVT_INIT_DONE, wxCommandEvent); wxDEFINE_EVENT(wxEVT_EDITOR_CONFIG_CHANGED, wxCommandEvent); wxDEFINE_EVENT(wxEVT_WORKSPACE_LOADED, wxCommandEvent); wxDEFINE_EVENT(wxEVT_WORKSPACE_CONFIG_CHANGED, wxCommandEvent); wxDEFINE_EVENT(wxEVT_WORKSPACE_CLOSED, wxCommandEvent); wxDEFINE_EVENT(wxEVT_WORKSPACE_CLOSING, wxCommandEvent); wxDEFINE_EVENT(wxEVT_FILE_VIEW_INIT_DONE, wxCommandEvent); wxDEFINE_EVENT(wxEVT_FILE_VIEW_REFRESHED, wxCommandEvent); wxDEFINE_EVENT(wxEVT_FILE_EXP_INIT_DONE, wxCommandEvent); wxDEFINE_EVENT(wxEVT_FILE_EXP_REFRESHED, wxCommandEvent); wxDEFINE_EVENT(wxEVT_CMD_FILE_EXP_ITEM_EXPANDING, wxCommandEvent); wxDEFINE_EVENT(wxEVT_TREE_ITEM_FILE_ACTIVATED, clCommandEvent); wxDEFINE_EVENT(wxEVT_PROJ_FILE_ADDED, clCommandEvent); wxDEFINE_EVENT(wxEVT_PROJ_FILE_REMOVED, clCommandEvent); wxDEFINE_EVENT(wxEVT_PROJ_REMOVED, clCommandEvent); wxDEFINE_EVENT(wxEVT_PROJ_ADDED, clCommandEvent); wxDEFINE_EVENT(wxEVT_FILE_SAVE_BY_BUILD_START, wxCommandEvent); wxDEFINE_EVENT(wxEVT_FILE_SAVE_BY_BUILD_END, wxCommandEvent); wxDEFINE_EVENT(wxEVT_FILE_SAVED, clCommandEvent); wxDEFINE_EVENT(wxEVT_FILE_RENAMED, clFileSystemEvent); wxDEFINE_EVENT(wxEVT_FILE_SAVEAS, clFileSystemEvent); wxDEFINE_EVENT(wxEVT_FILE_CREATED, clFileSystemEvent); wxDEFINE_EVENT(wxEVT_FOLDER_CREATED, clFileSystemEvent); wxDEFINE_EVENT(wxEVT_FILE_RETAGGED, wxCommandEvent); wxDEFINE_EVENT(wxEVT_ACTIVE_EDITOR_CHANGED, wxCommandEvent); wxDEFINE_EVENT(wxEVT_EDITOR_CLOSING, wxCommandEvent); wxDEFINE_EVENT(wxEVT_ALL_EDITORS_CLOSING, wxCommandEvent); wxDEFINE_EVENT(wxEVT_ALL_EDITORS_CLOSED, wxCommandEvent); wxDEFINE_EVENT(wxEVT_EDITOR_CLICKED, wxCommandEvent); wxDEFINE_EVENT(wxEVT_EDITOR_SETTINGS_CHANGED, wxCommandEvent); wxDEFINE_EVENT(wxEVT_CMD_RELOAD_EXTERNALLY_MODIFIED, wxCommandEvent); wxDEFINE_EVENT(wxEVT_CMD_RELOAD_EXTERNALLY_MODIFIED_NOPROMPT, wxCommandEvent); wxDEFINE_EVENT(wxEVT_CMD_PROJ_SETTINGS_SAVED, clProjectSettingsEvent); wxDEFINE_EVENT(wxEVT_CMD_EXECUTE_ACTIVE_PROJECT, clExecuteEvent); wxDEFINE_EVENT(wxEVT_CMD_IS_PROGRAM_RUNNING, clExecuteEvent); wxDEFINE_EVENT(wxEVT_CMD_STOP_EXECUTED_PROGRAM, clExecuteEvent); wxDEFINE_EVENT(wxEVT_PROGRAM_STARTED, clExecuteEvent); wxDEFINE_EVENT(wxEVT_PROGRAM_TERMINATED, clExecuteEvent); wxDEFINE_EVENT(wxEVT_BUILD_STARTED, clBuildEvent); wxDEFINE_EVENT(wxEVT_BUILD_ENDED, clBuildEvent); wxDEFINE_EVENT(wxEVT_BUILD_STARTING, clBuildEvent); wxDEFINE_EVENT(wxEVT_STOP_BUILD, clBuildEvent); wxDEFINE_EVENT(wxEVT_GET_PROJECT_CLEAN_CMD, clBuildEvent); wxDEFINE_EVENT(wxEVT_GET_PROJECT_BUILD_CMD, clBuildEvent); wxDEFINE_EVENT(wxEVT_GET_IS_PLUGIN_MAKEFILE, clBuildEvent); wxDEFINE_EVENT(wxEVT_GET_IS_PLUGIN_BUILD, clBuildEvent); wxDEFINE_EVENT(wxEVT_GET_ADDITIONAL_COMPILEFLAGS, clBuildEvent); wxDEFINE_EVENT(wxEVT_GET_ADDITIONAL_LINKFLAGS, clBuildEvent); wxDEFINE_EVENT(wxEVT_PLUGIN_EXPORT_MAKEFILE, clBuildEvent); wxDEFINE_EVENT(wxEVT_GET_IS_BUILD_IN_PROGRESS, clBuildEvent); wxDEFINE_EVENT(wxEVT_DEBUG_STARTING, clDebugEvent); wxDEFINE_EVENT(wxEVT_DEBUG_STARTED, clDebugEvent); wxDEFINE_EVENT(wxEVT_DEBUG_ENDING, clDebugEvent); wxDEFINE_EVENT(wxEVT_DEBUG_ENDED, clDebugEvent); wxDEFINE_EVENT(wxEVT_DEBUGGER_REFRESH_PANE, clDebugEvent); wxDEFINE_EVENT(wxEVT_DEBUGGER_SET_MEMORY, clDebugEvent); wxDEFINE_EVENT(wxEVT_QUICK_DEBUG_DLG_SHOWING, clDebugEvent); wxDEFINE_EVENT(wxEVT_QUICK_DEBUG_DLG_DISMISSED_OK, clDebugEvent); wxDEFINE_EVENT(wxEVT_DEBUG_EDITOR_LOST_CONTROL, wxCommandEvent); wxDEFINE_EVENT(wxEVT_DEBUG_EDITOR_GOT_CONTROL, wxCommandEvent); wxDEFINE_EVENT(wxEVT_CC_CODE_COMPLETE, clCodeCompletionEvent); wxDEFINE_EVENT(wxEVT_CC_WORD_COMPLETE, clCodeCompletionEvent); wxDEFINE_EVENT(wxEVT_CCBOX_SELECTION_MADE, clCodeCompletionEvent); wxDEFINE_EVENT(wxEVT_CC_CODE_COMPLETE_FUNCTION_CALLTIP, clCodeCompletionEvent); wxDEFINE_EVENT(wxEVT_CC_CODE_COMPLETE_BOX_DISMISSED, clCodeCompletionEvent); wxDEFINE_EVENT(wxEVT_CCBOX_SHOWING, clCodeCompletionEvent); wxDEFINE_EVENT(wxEVT_CC_SHOW_QUICK_OUTLINE, clCodeCompletionEvent); wxDEFINE_EVENT(wxEVT_CC_TYPEINFO_TIP, clCodeCompletionEvent); wxDEFINE_EVENT(wxEVT_CC_CODE_COMPLETE_LANG_KEYWORD, clCodeCompletionEvent); wxDEFINE_EVENT(wxEVT_CC_JUMP_HYPER_LINK, clCodeCompletionEvent); wxDEFINE_EVENT(wxEVT_CC_FIND_SYMBOL, clCodeCompletionEvent); wxDEFINE_EVENT(wxEVT_CC_FIND_SYMBOL_DECLARATION, clCodeCompletionEvent); wxDEFINE_EVENT(wxEVT_CC_FIND_SYMBOL_DEFINITION, clCodeCompletionEvent); wxDEFINE_EVENT(wxEVT_CC_GENERATE_DOXY_BLOCK, clCodeCompletionEvent); wxDEFINE_EVENT(wxEVT_CC_UPDATE_NAVBAR, clCodeCompletionEvent); wxDEFINE_EVENT(wxEVT_CC_BLOCK_COMMENT_CODE_COMPLETE, clCodeCompletionEvent); wxDEFINE_EVENT(wxEVT_CC_BLOCK_COMMENT_WORD_COMPLETE, clCodeCompletionEvent); wxDEFINE_EVENT(wxEVT_CMD_CREATE_NEW_WORKSPACE, clCommandEvent); wxDEFINE_EVENT(wxEVT_CMD_OPEN_WORKSPACE, clCommandEvent); wxDEFINE_EVENT(wxEVT_CMD_CLOSE_WORKSPACE, clCommandEvent); wxDEFINE_EVENT(wxEVT_CMD_IS_WORKSPACE_OPEN, clCommandEvent); wxDEFINE_EVENT(wxEVT_CMD_RETAG_WORKSPACE, wxCommandEvent); wxDEFINE_EVENT(wxEVT_CMD_RETAG_WORKSPACE_FULL, wxCommandEvent); wxDEFINE_EVENT(wxEVT_CMD_GET_WORKSPACE_FILES, wxCommandEvent); wxDEFINE_EVENT(wxEVT_CMD_GET_ACTIVE_PROJECT_FILES, wxCommandEvent); wxDEFINE_EVENT(wxEVT_CMD_GET_CURRENT_FILE_PROJECT_FILES, wxCommandEvent); wxDEFINE_EVENT(wxEVT_CMD_OPEN_RESOURCE, wxCommandEvent); wxDEFINE_EVENT(wxEVT_CMD_EDITOR_CONTEXT_MENU, wxCommandEvent); wxDEFINE_EVENT(wxEVT_CMD_RETAG_COMPLETED, wxCommandEvent); wxDEFINE_EVENT(wxEVT_NOTIFY_PAGE_CLOSING, wxNotifyEvent); wxDEFINE_EVENT(wxEVT_CMD_PAGE_CHANGED, wxCommandEvent); wxDEFINE_EVENT(wxEVT_REBUILD_WORKSPACE_TREE, wxCommandEvent); wxDEFINE_EVENT(wxEVT_ACTIVE_PROJECT_CHANGED, clProjectSettingsEvent); wxDEFINE_EVENT(wxEVT_FINDBAR_ABOUT_TO_SHOW, clFindEvent); wxDEFINE_EVENT(wxEVT_FINDBAR_RELEASE_EDITOR, clFindEvent); wxDEFINE_EVENT(wxEVT_FINDINFILES_DLG_SHOWING, clFindInFilesEvent); wxDEFINE_EVENT(wxEVT_FINDINFILES_DLG_DISMISSED, clFindInFilesEvent); wxDEFINE_EVENT(wxEVT_CMD_BUILD_PROJECT_ONLY, wxCommandEvent); wxDEFINE_EVENT(wxEVT_CMD_CLEAN_PROJECT_ONLY, wxCommandEvent); wxDEFINE_EVENT(wxEVT_CL_THEME_CHANGED, wxCommandEvent); wxDEFINE_EVENT(wxEVT_CODEFORMATTER_INDENT_COMPLETED, wxCommandEvent); wxDEFINE_EVENT(wxEVT_CODEFORMATTER_INDENT_STARTING, wxCommandEvent); wxDEFINE_EVENT(wxEVT_CODELITE_MAINFRAME_GOT_FOCUS, wxCommandEvent); wxDEFINE_EVENT(wxEVT_PROJECT_TREEITEM_CLICKED, wxCommandEvent); wxDEFINE_EVENT(wxEVT_CODELITE_ALL_BREAKPOINTS_DELETED, wxCommandEvent); wxDEFINE_EVENT(wxEVT_CC_SHOW_QUICK_NAV_MENU, clCodeCompletionEvent); wxDEFINE_EVENT(wxEVT_CMD_RELOAD_WORKSPACE, clCommandEvent); wxDEFINE_EVENT(wxEVT_COLOUR_TAB, clColourEvent); wxDEFINE_EVENT(wxEVT_WORKSPACE_VIEW_BUILD_STARTING, clCommandEvent); wxDEFINE_EVENT(wxEVT_WORKSPACE_VIEW_CUSTOMIZE_PROJECT, clColourEvent); wxDEFINE_EVENT(wxEVT_GET_TAB_BORDER_COLOUR, clColourEvent); wxDEFINE_EVENT(wxEVT_DBG_UI_START, clDebugEvent); wxDEFINE_EVENT(wxEVT_DBG_UI_CONTINUE, clDebugEvent); wxDEFINE_EVENT(wxEVT_DBG_UI_STOP, clDebugEvent); wxDEFINE_EVENT(wxEVT_DBG_UI_STEP_IN, clDebugEvent); wxDEFINE_EVENT(wxEVT_DBG_UI_STEP_I, clDebugEvent); wxDEFINE_EVENT(wxEVT_DBG_UI_STEP_OUT, clDebugEvent); wxDEFINE_EVENT(wxEVT_DBG_UI_NEXT, clDebugEvent); wxDEFINE_EVENT(wxEVT_DBG_UI_NEXT_INST, clDebugEvent); wxDEFINE_EVENT(wxEVT_DBG_UI_INTERRUPT, clDebugEvent); wxDEFINE_EVENT(wxEVT_DBG_UI_SHOW_CURSOR, clDebugEvent); wxDEFINE_EVENT(wxEVT_DBG_UI_RESTART, clDebugEvent); wxDEFINE_EVENT(wxEVT_DBG_IS_RUNNING, clDebugEvent); wxDEFINE_EVENT(wxEVT_DBG_UI_TOGGLE_BREAKPOINT, clDebugEvent); wxDEFINE_EVENT(wxEVT_DBG_CAN_INTERACT, clDebugEvent); wxDEFINE_EVENT(wxEVT_DBG_EXPR_TOOLTIP, clDebugEvent); wxDEFINE_EVENT(wxEVT_DBG_IS_PLUGIN_DEBUGGER, clDebugEvent); wxDEFINE_EVENT(wxEVT_DBG_UI_QUICK_DEBUG, clDebugEvent); wxDEFINE_EVENT(wxEVT_DBG_UI_CORE_FILE, clDebugEvent); wxDEFINE_EVENT(wxEVT_DBG_UI_ATTACH_TO_PROCESS, clDebugEvent); wxDEFINE_EVENT(wxEVT_DBG_UI_DELETE_ALL_BREAKPOINTS, clDebugEvent); wxDEFINE_EVENT(wxEVT_DBG_UI_ENABLE_ALL_BREAKPOINTS, clDebugEvent); wxDEFINE_EVENT(wxEVT_DBG_UI_DISABLE_ALL_BREAKPOINTS, clDebugEvent); wxDEFINE_EVENT(wxEVT_CMD_OPEN_PROJ_SETTINGS, clCommandEvent); wxDEFINE_EVENT(wxEVT_WORKSPACE_RELOAD_STARTED, clCommandEvent); wxDEFINE_EVENT(wxEVT_WORKSPACE_RELOAD_ENDED, clCommandEvent); wxDEFINE_EVENT(wxEVT_NEW_PROJECT_WIZARD_SHOWING, clNewProjectEvent); wxDEFINE_EVENT(wxEVT_NEW_PROJECT_WIZARD_FINISHED, clNewProjectEvent); wxDEFINE_EVENT(wxEVT_COMPILER_LIST_UPDATED, clCompilerEvent); wxDEFINE_EVENT(wxEVT_SAVE_ALL_EDITORS, clCommandEvent); wxDEFINE_EVENT(wxEVT_FORMAT_STRING, clSourceFormatEvent); wxDEFINE_EVENT(wxEVT_FORMAT_FILE, clSourceFormatEvent); wxDEFINE_EVENT(wxEVT_CONTEXT_MENU_EDITOR, clContextMenuEvent); wxDEFINE_EVENT(wxEVT_CONTEXT_MENU_EDITOR_MARGIN, clContextMenuEvent); wxDEFINE_EVENT(wxEVT_CONTEXT_MENU_FOLDER, clContextMenuEvent); wxDEFINE_EVENT(wxEVT_CONTEXT_MENU_VIRTUAL_FOLDER, clContextMenuEvent); wxDEFINE_EVENT(wxEVT_CONTEXT_MENU_FILE, clContextMenuEvent); wxDEFINE_EVENT(wxEVT_CONTEXT_MENU_PROJECT, clContextMenuEvent); wxDEFINE_EVENT(wxEVT_CONTEXT_MENU_WORKSPACE, clContextMenuEvent); wxDEFINE_EVENT(wxEVT_CONTEXT_MENU_TAB_LABEL, clContextMenuEvent); wxDEFINE_EVENT(wxEVT_CMD_COLOURS_FONTS_UPDATED, clCommandEvent); wxDEFINE_EVENT(wxEVT_FILE_LOADED, clCommandEvent); wxDEFINE_EVENT(wxEVT_FILE_CLOSED, clCommandEvent); wxDEFINE_EVENT(wxEVT_CL_FRAME_TITLE, clCommandEvent); wxDEFINE_EVENT(wxEVT_BEFORE_EDITOR_SAVE, clCommandEvent); wxDEFINE_EVENT(wxEVT_EDITOR_MODIFIED, clCommandEvent); wxDEFINE_EVENT(wxEVT_CLANG_CODE_COMPLETE_MESSAGE, clCommandEvent); wxDEFINE_EVENT(wxEVT_GOING_DOWN, clCommandEvent); wxDEFINE_EVENT(wxEVT_PROJ_RENAMED, clCommandEvent); wxDEFINE_EVENT(wxEVT_EDITOR_INITIALIZING, clCommandEvent); wxDEFINE_EVENT(wxEVT_FILE_SYSTEM_UPDATED, clFileSystemEvent); wxDEFINE_EVENT(wxEVT_FILES_MODIFIED_REPLACE_IN_FILES, clFileSystemEvent); wxDEFINE_EVENT(wxEVT_SAVE_SESSION_NEEDED, clCommandEvent); wxDEFINE_EVENT(wxEVT_ENVIRONMENT_VARIABLES_MODIFIED, clCommandEvent); wxDEFINE_EVENT(wxEVT_DND_FOLDER_DROPPED, clCommandEvent); wxDEFINE_EVENT(wxEVT_DND_FILE_DROPPED, clCommandEvent); wxDEFINE_EVENT(wxEVT_RESTART_CODELITE, clCommandEvent); wxDEFINE_EVENT(wxEVT_SHOW_WORKSPACE_TAB, clCommandEvent); wxDEFINE_EVENT(wxEVT_SHOW_OUTPUT_TAB, clCommandEvent); wxDEFINE_EVENT(wxEVT_PAGE_MODIFIED_UPDATE_UI, clCommandEvent); wxDEFINE_EVENT(wxEVT_EDITOR_CONFIG_LOADING, clEditorConfigEvent); wxDEFINE_EVENT(wxEVT_PHP_SETTINGS_CHANGED, clCommandEvent); wxDEFINE_EVENT(wxEVT_WORKSPACE_BUILD_CONFIG_CHANGED, clCommandEvent); wxDEFINE_EVENT(wxEVT_GOTO_ANYTHING_SELECTED, clGotoEvent); wxDEFINE_EVENT(wxEVT_GOTO_ANYTHING_SHOWING, clGotoEvent); wxDEFINE_EVENT(wxEVT_GOTO_ANYTHING_SORT_NEEDED, clGotoEvent); wxDEFINE_EVENT(wxEVT_NAVBAR_SCOPE_MENU_SHOWING, clContextMenuEvent); wxDEFINE_EVENT(wxEVT_NAVBAR_SCOPE_MENU_SELECTION_MADE, clCommandEvent); wxDEFINE_EVENT(wxEVT_MARKER_CHANGED, clCommandEvent); wxDEFINE_EVENT(wxEVT_INFO_BAR_BUTTON, clCommandEvent); wxDEFINE_EVENT(wxEVT_BUILD_CUSTOM_TARGETS_MENU_SHOWING, clContextMenuEvent); wxDEFINE_EVENT(wxEVT_SOURCE_CONTROL_PUSHED, clSourceControlEvent); wxDEFINE_EVENT(wxEVT_SOURCE_CONTROL_COMMIT_LOCALLY, clSourceControlEvent); wxDEFINE_EVENT(wxEVT_SOURCE_CONTROL_RESET_FILES, clSourceControlEvent); wxDEFINE_EVENT(wxEVT_SOURCE_CONTROL_PULLED, clSourceControlEvent);
utf-8
1
CodeLite
2007-2014 Eran Ifrah <eran.ifrah@gmail.com> 2011-2014 David Hart <david@codelite.co.uk> 2014-2016 The CodeLite Team
gcc-arm-none-eabi-10.3-2021.07/gcc/testsuite/g++.dg/pr93674.C
// { dg-do compile } // { dg-options "-O3 -std=c++14 -fstrict-enums -pedantic -fdump-tree-optimized" } enum some_enum { x = 1000 }; void sink(some_enum); int __attribute__((noinline)) func() { int sum = 0; for (int i = 0; i < 3; ++i) { for (int j = 3; j >= 0; --j) { sink((some_enum)(i + j)); } } return sum; } // { dg-final { scan-tree-dump-not "some_enum ivtmp" "optimized" } }
utf-8
1
unknown
unknown
gcl-2.6.12/gmp4/mini-gmp/tests/t-str.c
/* Copyright 2012, 2013 Free Software Foundation, Inc. This file is part of the GNU MP Library test suite. The GNU MP Library test suite 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. The GNU MP Library test suite 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 the GNU MP Library test suite. If not, see https://www.gnu.org/licenses/. */ #include <assert.h> #include <limits.h> #include <stdlib.h> #include <stdio.h> #include <string.h> #include "testutils.h" #define MAXBITS 400 #define COUNT 2000 #define GMP_LIMB_BITS (sizeof(mp_limb_t) * CHAR_BIT) #define MAXLIMBS ((MAXBITS + GMP_LIMB_BITS - 1) / GMP_LIMB_BITS) static void test_small (void) { struct { const char *input; const char *decimal; } data[] = { { "183407", "183407" }, { " 763959", "763959" }, { "9 81999", "981999" }, { "10\t7398", "107398" }, { "-9585 44", "-00958544" }, { "-0", "0000" }, { " -000 ", "0" }, { "0704436", "231710" }, { " 02503517", "689999" }, { "0 1312143", "365667" }, { "-03 274062", "-882738" }, { "012\t242", "005282" }, { "0b11010111110010001111", "883855" }, { " 0b11001010010100001", "103585" }, { "-0b101010110011101111", "-175343" }, { "0b 1111111011011100110", "521958" }, { "0b1 1111110111001000011", "1044035" }, { " 0x53dfc", "343548" }, { "0xfA019", "1024025" }, { "0x 642d1", "410321" }, { "0x5 8067", "360551" }, { "-0xd6Be6", "-879590" }, { "\t0B1110000100000000011", "460803" }, { "0B\t1111110010010100101", "517285" }, { "0B1\t010111101101110100", "359284" }, { "-0B101\t1001101111111001", "-367609" }, { "0B10001001010111110000", "562672" }, { "0Xe4B7e", "936830" }, { "0X1E4bf", "124095" }, { "-0Xfdb90", "-1039248" }, { "0X7fc47", "523335" }, { "0X8167c", "530044" }, /* Some invalid inputs */ { "0ab", NULL }, { "10x0", NULL }, { "0xxab", NULL }, { "ab", NULL }, { "0%#", NULL }, { "$foo", NULL }, { NULL, NULL } }; unsigned i; mpz_t a, b; mpz_init (b); for (i = 0; data[i].input; i++) { int res = mpz_init_set_str (a, data[i].input, 0); if (data[i].decimal) { if (res != 0) { fprintf (stderr, "mpz_set_str returned -1, input: %s\n", data[i].input); abort (); } if (mpz_set_str (b, data[i].decimal, 10) != 0) { fprintf (stderr, "mpz_set_str returned -1, decimal input: %s\n", data[i].input); abort (); } if (mpz_cmp (a, b) != 0) { fprintf (stderr, "mpz_set_str failed for input: %s\n", data[i].input); dump ("got", a); dump ("ref", b); abort (); } } else if (res != -1) { fprintf (stderr, "mpz_set_str returned %d, invalid input: %s\n", res, data[i].input); abort (); } mpz_clear (a); } mpz_clear (b); } void testmain (int argc, char **argv) { unsigned i; char *ap; char *bp; char *rp; size_t bn, rn, arn; mpz_t a, b; FILE *tmp; test_small (); mpz_init (a); mpz_init (b); tmp = tmpfile (); if (!tmp) fprintf (stderr, "Failed to create temporary file. Skipping mpz_out_str tests.\n"); for (i = 0; i < COUNT; i++) { int base; for (base = 0; base <= 36; base += 1 + (base == 0)) { hex_random_str_op (MAXBITS, i&1 ? base: -base, &ap, &rp); if (mpz_set_str (a, ap, 16) != 0) { fprintf (stderr, "mpz_set_str failed on input %s\n", ap); abort (); } rn = strlen (rp); arn = rn - (rp[0] == '-'); bn = mpz_sizeinbase (a, base ? base : 10); if (bn < arn || bn > (arn + 1)) { fprintf (stderr, "mpz_sizeinbase failed:\n"); dump ("a", a); fprintf (stderr, "r = %s\n", rp); fprintf (stderr, " base %d, correct size %u, got %u\n", base, (unsigned) arn, (unsigned)bn); abort (); } bp = mpz_get_str (NULL, i&1 ? base: -base, a); if (strcmp (bp, rp)) { fprintf (stderr, "mpz_get_str failed:\n"); dump ("a", a); fprintf (stderr, "b = %s\n", bp); fprintf (stderr, " base = %d\n", base); fprintf (stderr, "r = %s\n", rp); abort (); } /* Just a few tests with file i/o. */ if (tmp && i < 20) { size_t tn; rewind (tmp); tn = mpz_out_str (tmp, i&1 ? base: -base, a); if (tn != rn) { fprintf (stderr, "mpz_out_str, bad return value:\n"); dump ("a", a); fprintf (stderr, "r = %s\n", rp); fprintf (stderr, " base %d, correct size %u, got %u\n", base, (unsigned) rn, (unsigned)tn); abort (); } rewind (tmp); memset (bp, 0, rn); tn = fread (bp, 1, rn, tmp); if (tn != rn) { fprintf (stderr, "fread failed, expected %lu bytes, got only %lu.\n", (unsigned long) rn, (unsigned long) tn); abort (); } if (memcmp (bp, rp, rn) != 0) { fprintf (stderr, "mpz_out_str failed:\n"); dump ("a", a); fprintf (stderr, "b = %s\n", bp); fprintf (stderr, " base = %d\n", base); fprintf (stderr, "r = %s\n", rp); abort (); } } mpz_set_str (b, rp, base); if (mpz_cmp (a, b)) { fprintf (stderr, "mpz_set_str failed:\n"); fprintf (stderr, "r = %s\n", rp); fprintf (stderr, " base = %d\n", base); fprintf (stderr, "r = %s\n", ap); fprintf (stderr, " base = 16\n"); dump ("b", b); dump ("r", a); abort (); } /* Test mpn interface */ if (base && mpz_sgn (a)) { size_t i; const char *absr; mp_limb_t t[MAXLIMBS]; mp_size_t tn = mpz_size (a); assert (tn <= MAXLIMBS); mpn_copyi (t, a->_mp_d, tn); bn = mpn_get_str (bp, base, t, tn); if (bn != arn) { fprintf (stderr, "mpn_get_str failed:\n"); fprintf (stderr, "returned length: %lu (bad)\n", (unsigned long) bn); fprintf (stderr, "expected: %lu\n", (unsigned long) arn); fprintf (stderr, " base = %d\n", base); fprintf (stderr, "r = %s\n", ap); fprintf (stderr, " base = 16\n"); dump ("b", b); dump ("r", a); abort (); } absr = rp + (rp[0] == '-'); for (i = 0; i < bn; i++) { unsigned char digit = absr[i]; unsigned value; if (digit >= '0' && digit <= '9') value = digit - '0'; else if (digit >= 'a' && digit <= 'z') value = digit - 'a' + 10; else if (digit >= 'A' && digit <= 'Z') value = digit - 'A' + 10; else { fprintf (stderr, "Internal error in test.\n"); abort(); } if (bp[i] != value) { fprintf (stderr, "mpn_get_str failed:\n"); fprintf (stderr, "digit %lu: %d (bad)\n", (unsigned long) i, bp[i]); fprintf (stderr, "expected: %d\n", value); fprintf (stderr, " base = %d\n", base); fprintf (stderr, "r = %s\n", ap); fprintf (stderr, " base = 16\n"); dump ("b", b); dump ("r", a); abort (); } } tn = mpn_set_str (t, bp, bn, base); if (tn != mpz_size (a) || mpn_cmp (t, a->_mp_d, tn)) { fprintf (stderr, "mpn_set_str failed:\n"); fprintf (stderr, "r = %s\n", rp); fprintf (stderr, " base = %d\n", base); fprintf (stderr, "r = %s\n", ap); fprintf (stderr, " base = 16\n"); dump ("r", a); abort (); } } free (ap); testfree (bp); } } mpz_clear (a); mpz_clear (b); }
utf-8
1
unknown
unknown
ares-126/ares/ng/lspc/color.cpp
auto LSPC::color(n32 color) -> n64 { n32 b = color.bit(15) << 0 | color.bit(12) << 1 | color.bit(0, 3) << 2; n32 g = color.bit(15) << 0 | color.bit(13) << 1 | color.bit(4, 7) << 2; n32 r = color.bit(15) << 0 | color.bit(14) << 1 | color.bit(8,11) << 2; n64 R = image::normalize(r, 6, 16); n64 G = image::normalize(g, 6, 16); n64 B = image::normalize(b, 6, 16); if(color.bit(16)) { R >>= 1; G >>= 1; B >>= 1; } return R << 32 | G << 16 | B << 0; }
utf-8
1
ISC
Copyright (c) 2004-2021 ares team, Near et al
efax-gtk-3.2.8/src/addressbook.cpp
/* Copyright (C) 2001 to 2011 Chris Vine This program is distributed under the General Public Licence, version 2. For particulars of this and relevant disclaimers see the file COPYING distributed with the source files. */ #include <fstream> #include <cstdlib> #include <ios> #include <ostream> #include <gdk/gdk.h> #include <gdk/gdkkeysyms.h> // the key codes are here #include "addressbook.h" #include "dialogs.h" #include "utils/tree_path_handle.h" #include "addressbook_icons.h" #include <c++-gtk-utils/convert.h> #ifdef ENABLE_NLS #include <libintl.h> #endif #define ADDRESS_FILE ".efax-gtk_addressbook" #define ADDRESS_DIVIDER 3 int AddressBook::is_address_list = 0; namespace { namespace ModelColumns { enum {name, number, cols_num}; } // namespace ModelColumns } // anonymous namespace void AddressBookCB::addr_book_button_clicked(GtkWidget* widget_p, void* data) { AddressBook* instance_p = static_cast<AddressBook*>(data); if (widget_p == instance_p->ok_button_p) { if (instance_p->ok_impl()) instance_p->close(); } else if (widget_p == instance_p->cancel_button_p) { instance_p->result = ""; instance_p->close(); } else if (widget_p == instance_p->add_button_p) { instance_p->add_address_prompt(); } else if (widget_p == instance_p->delete_button_p) { instance_p->delete_address_prompt(); } else if (widget_p == instance_p->up_button_p) { instance_p->move_up_impl(); } else if (widget_p == instance_p->down_button_p) { instance_p->move_down_impl(); } else { write_error("Callback error in AddressBookCB::addr_book_button_clicked()\n"); instance_p->close(); } } void AddressBookCB::addr_book_drag_n_drop(GtkTreeModel*, GtkTreePath*, void* data) { static_cast<AddressBook*>(data)->save_list(); } AddressBook::AddressBook(const int size, GtkWindow* parent_p): WinBase(gettext("efax-gtk: Address book"), prog_config.window_icon_h, true, parent_p), standard_size(size) { // notify the existence of this object in case I later decide to use this dialog as modeless // by changing the modal parameter above to false is_address_list++; ok_button_p = gtk_button_new_from_stock(GTK_STOCK_OK); cancel_button_p = gtk_button_new_from_stock(GTK_STOCK_CANCEL); add_button_p = gtk_button_new(); delete_button_p = gtk_button_new(); up_button_p = gtk_button_new(); down_button_p = gtk_button_new(); GtkWidget* button_box_p = gtk_hbutton_box_new(); GtkTable* table_p = GTK_TABLE(gtk_table_new(2, 1, false)); GtkTable* list_table_p = GTK_TABLE(gtk_table_new(5, 2, false)); GtkScrolledWindow* scrolled_window_p = GTK_SCROLLED_WINDOW(gtk_scrolled_window_new(0, 0)); gtk_button_box_set_layout(GTK_BUTTON_BOX(button_box_p), GTK_BUTTONBOX_END); gtk_box_set_spacing(GTK_BOX(button_box_p), standard_size/2); gtk_container_add(GTK_CONTAINER(button_box_p), cancel_button_p); gtk_container_add(GTK_CONTAINER(button_box_p), ok_button_p); gtk_scrolled_window_set_shadow_type(scrolled_window_p, GTK_SHADOW_IN); gtk_scrolled_window_set_policy(scrolled_window_p, GTK_POLICY_ALWAYS, GTK_POLICY_ALWAYS); // create the tree model and put it in a GobjHandle to handle its // lifetime, because it is not owned by a GTK+ container list_store_h = GobjHandle<GtkTreeModel>(GTK_TREE_MODEL(gtk_list_store_new(ModelColumns::cols_num, G_TYPE_STRING, G_TYPE_STRING))); // populate the model (containing the address list) read_list(); // create the tree view tree_view_p = GTK_TREE_VIEW(gtk_tree_view_new_with_model(list_store_h)); gtk_container_add(GTK_CONTAINER(scrolled_window_p), GTK_WIDGET(tree_view_p)); // provide renderers for tree view, pack into tree view columns // and connect to the tree model columns GtkCellRenderer* renderer_p = gtk_cell_renderer_text_new(); GtkTreeViewColumn* column_p = gtk_tree_view_column_new_with_attributes(gettext("Name"), renderer_p, "text", ModelColumns::name, static_cast<void*>(0)); gtk_tree_view_append_column(tree_view_p, column_p); renderer_p = gtk_cell_renderer_text_new(); column_p = gtk_tree_view_column_new_with_attributes(gettext("Number"), renderer_p, "text", ModelColumns::number, static_cast<void*>(0)); gtk_tree_view_append_column(tree_view_p, column_p); GtkTreeSelection* selection_p = gtk_tree_view_get_selection(tree_view_p); // single line selection gtk_tree_selection_set_mode(selection_p, GTK_SELECTION_SINGLE); // make drag and drop work gtk_tree_view_set_reorderable(tree_view_p, true); // get any drag and drop to be saved to the addresses file g_signal_connect(G_OBJECT(list_store_h.get()), "row_deleted", G_CALLBACK(AddressBookCB::addr_book_drag_n_drop), this); // bring up the icon size registered in MainWindow::MainWindow() GtkIconSize efax_gtk_button_size = gtk_icon_size_from_name("EFAX_GTK_BUTTON_SIZE"); GtkWidget* image_p; { // provide a scope block for the GobjHandle // GdkPixbufs are not owned by a GTK+ container when passed to it so use a GobjHandle GobjHandle<GdkPixbuf> pixbuf_h(gdk_pixbuf_new_from_xpm_data(add_xpm)); image_p = gtk_image_new_from_pixbuf(pixbuf_h); gtk_container_add(GTK_CONTAINER(add_button_p), image_p); } image_p = gtk_image_new_from_stock(GTK_STOCK_DELETE, efax_gtk_button_size); gtk_container_add(GTK_CONTAINER(delete_button_p), image_p); image_p = gtk_image_new_from_stock(GTK_STOCK_GO_UP, efax_gtk_button_size); gtk_container_add(GTK_CONTAINER(up_button_p), image_p); image_p = gtk_image_new_from_stock(GTK_STOCK_GO_DOWN, efax_gtk_button_size); gtk_container_add(GTK_CONTAINER(down_button_p), image_p); GtkWidget* dummy_p = gtk_label_new(0); gtk_table_attach(list_table_p, add_button_p, 0, 1, 0, 1, GTK_SHRINK, GTK_SHRINK, standard_size/2, 0); gtk_table_attach(list_table_p, delete_button_p, 0, 1, 1, 2, GTK_SHRINK, GTK_SHRINK, standard_size/2, 0); gtk_table_attach(list_table_p, up_button_p, 0, 1, 2, 3, GTK_SHRINK, GTK_SHRINK, standard_size/2, 0); gtk_table_attach(list_table_p, down_button_p, 0, 1, 3, 4, GTK_SHRINK, GTK_SHRINK, standard_size/2, 0); gtk_table_attach(list_table_p, dummy_p, 0, 1, 4, 5, GTK_SHRINK, GTK_EXPAND, standard_size/2, 0); gtk_table_attach(list_table_p, GTK_WIDGET(scrolled_window_p), 1, 2, 0, 5, GtkAttachOptions(GTK_FILL | GTK_EXPAND), GtkAttachOptions(GTK_FILL | GTK_EXPAND), 0, 0); gtk_widget_set_tooltip_text(add_button_p, gettext("Add new address")); gtk_widget_set_tooltip_text(delete_button_p, gettext("Delete address")); gtk_widget_set_tooltip_text(up_button_p, gettext("Move address up")); gtk_widget_set_tooltip_text(down_button_p, gettext("Move address down")); gtk_table_attach(table_p, GTK_WIDGET(list_table_p), 0, 1, 0, 1, GtkAttachOptions(GTK_FILL | GTK_EXPAND), GtkAttachOptions(GTK_FILL | GTK_EXPAND), standard_size/3, standard_size/3); gtk_table_attach(table_p, button_box_p, 0, 1, 1, 2, GtkAttachOptions(GTK_FILL | GTK_EXPAND), GTK_SHRINK, standard_size/3, standard_size/3); g_signal_connect(G_OBJECT(ok_button_p), "clicked", G_CALLBACK(AddressBookCB::addr_book_button_clicked), this); g_signal_connect(G_OBJECT(cancel_button_p), "clicked", G_CALLBACK(AddressBookCB::addr_book_button_clicked), this); g_signal_connect(G_OBJECT(add_button_p), "clicked", G_CALLBACK(AddressBookCB::addr_book_button_clicked), this); g_signal_connect(G_OBJECT(delete_button_p), "clicked", G_CALLBACK(AddressBookCB::addr_book_button_clicked), this); g_signal_connect(G_OBJECT(up_button_p), "clicked", G_CALLBACK(AddressBookCB::addr_book_button_clicked), this); g_signal_connect(G_OBJECT(down_button_p), "clicked", G_CALLBACK(AddressBookCB::addr_book_button_clicked), this); #if GTK_CHECK_VERSION(2,20,0) gtk_widget_set_can_default(ok_button_p, true); gtk_widget_set_can_default(cancel_button_p, true); gtk_widget_set_can_default(add_button_p, false); gtk_widget_set_can_default(delete_button_p, false); gtk_widget_set_can_focus(up_button_p, false); gtk_widget_set_can_focus(down_button_p, false); #else GTK_WIDGET_SET_FLAGS(ok_button_p, GTK_CAN_DEFAULT); GTK_WIDGET_SET_FLAGS(cancel_button_p, GTK_CAN_DEFAULT); GTK_WIDGET_UNSET_FLAGS(add_button_p, GTK_CAN_DEFAULT); GTK_WIDGET_UNSET_FLAGS(delete_button_p, GTK_CAN_DEFAULT); GTK_WIDGET_UNSET_FLAGS(up_button_p, GTK_CAN_FOCUS); GTK_WIDGET_UNSET_FLAGS(down_button_p, GTK_CAN_FOCUS); #endif gtk_container_set_border_width(GTK_CONTAINER(table_p), standard_size/3); gtk_container_add(GTK_CONTAINER(get_win()), GTK_WIDGET(table_p)); gtk_window_set_type_hint(get_win(), GDK_WINDOW_TYPE_HINT_DIALOG); gtk_window_set_position(get_win(), GTK_WIN_POS_CENTER_ON_PARENT); gtk_widget_grab_focus(cancel_button_p); gtk_window_set_default_size(get_win(), standard_size * 15, standard_size * 8); gtk_widget_show_all(GTK_WIDGET(get_win())); } AddressBook::~AddressBook(void) { // notify the destruction of this object is_address_list--; } void AddressBook::on_delete_event(void) { gtk_widget_hide(GTK_WIDGET(get_win())); result = ""; close(); } bool AddressBook::ok_impl(void) { bool return_val = false; if (get_number().get()) result = get_number().get(); if (!result.empty()) { accepted(result); return_val = true; } else beep(); return return_val; } GcharSharedHandle AddressBook::get_number(void) { GtkTreeIter iter; GtkTreeModel* model_p; gchar* number_p = 0; GtkTreeSelection* selection_p(gtk_tree_view_get_selection(tree_view_p)); if (gtk_tree_selection_get_selected(selection_p, &model_p, &iter)) { gtk_tree_model_get(model_p, &iter, ModelColumns::number, &number_p, -1); } return GcharSharedHandle(number_p); } void AddressBook::add_address_prompt(void) { AddressDialog* dialog_p = new AddressDialog(standard_size, this->get_win()); dialog_p->accepted.connect(Callback::make(*this, &AddressBook::add_address_impl)); // there is no memory leak -- AddressDailog will delete its own memory // when it is closed } void AddressBook::add_address_impl(const std::vector<std::string>& address) { GtkTreeIter iter; gtk_list_store_append(GTK_LIST_STORE(list_store_h.get()), &iter); gtk_list_store_set(GTK_LIST_STORE(list_store_h.get()), &iter, ModelColumns::name, address[0].c_str(), ModelColumns::number, address[1].c_str(), -1); save_list(); } void AddressBook::delete_address_prompt(void) { GtkTreeIter iter; GtkTreeSelection* selection_p(gtk_tree_view_get_selection(tree_view_p)); if (gtk_tree_selection_get_selected(selection_p, 0, &iter)) { PromptDialog* dialog_p = new PromptDialog(gettext("Delete selected address?"), gettext("efax-gtk: Delete address"), standard_size, get_win()); dialog_p->accepted.connect(Callback::make(*this, &AddressBook::delete_address_impl)); // there is no memory leak -- the memory will be deleted when PromptDialog closes } else beep(); } void AddressBook::delete_address_impl(void) { GtkTreeIter iter; GtkTreeModel* model_p; GtkTreeSelection* selection_p(gtk_tree_view_get_selection(tree_view_p)); if (gtk_tree_selection_get_selected(selection_p, &model_p, &iter)) { // delete the address by removing it from the list store gtk_list_store_remove(GTK_LIST_STORE(model_p), &iter); save_list(); } } void AddressBook::read_list(void) { std::string filename(prog_config.working_dir); filename += "/" ADDRESS_FILE; #ifdef HAVE_IOS_NOCREATE std::ifstream filein(filename.c_str(), std::ios::in | std::ios::nocreate); #else // we must have Std C++ so we probably don't need a ios::nocreate // flag on a read open to ensure uniqueness std::ifstream filein(filename.c_str(), std::ios::in); #endif if (filein) { gtk_list_store_clear(GTK_LIST_STORE(list_store_h.get())); std::string line; while (std::getline(filein, line)) { if (!line.empty()) { std::string::size_type pos = line.find(ADDRESS_DIVIDER, 0); // pos now is set to end of name value // get a list store row to insert the number and name in GtkTreeIter iter; gtk_list_store_append(GTK_LIST_STORE(list_store_h.get()), &iter); try { gtk_list_store_set(GTK_LIST_STORE(list_store_h.get()), &iter, ModelColumns::name, Utf8::locale_to_utf8(line.substr(0, pos)).c_str(), -1); } catch (Utf8::ConversionError&) { write_error("UTF-8 conversion error in AddressBook::read_list()\n"); } pos++; // pos now is set to the beginning of the number value try { gtk_list_store_set(GTK_LIST_STORE(list_store_h.get()), &iter, ModelColumns::number, Utf8::locale_to_utf8(line.substr(pos, line.size() - pos)).c_str(), -1); } catch (Utf8::ConversionError&) { write_error("UTF-8 conversion error in AddressBook::read_list()\n"); } } } } } void AddressBook::save_list(void) { std::string filename(prog_config.working_dir); filename += "/" ADDRESS_FILE; std::ofstream fileout(filename.c_str(), std::ios::out); if (fileout) { gchar* name_p; gchar* number_p; GtkTreeIter iter; bool not_at_end = gtk_tree_model_get_iter_first(list_store_h, &iter); while(not_at_end) { // the try()/catch() blocks here are ultra cautious - something must be // seriously wrong if model_columns.name and model_columns.number are not // in valid UTF-8 format, since they are tested where necessary at input gtk_tree_model_get(list_store_h, &iter, ModelColumns::name, &name_p, ModelColumns::number, &number_p, -1); GcharScopedHandle name_h(name_p); GcharScopedHandle number_h(number_p); try { fileout << Utf8::locale_from_utf8(name_h.get()); fileout << static_cast<char>(ADDRESS_DIVIDER); fileout << Utf8::locale_from_utf8(number_h.get()); fileout << '\n'; } catch (Utf8::ConversionError&) { write_error("UTF-8 conversion error in AddressBook::save_list()\n"); // end the line comprising whatever we have put there fileout << '\n'; } not_at_end = gtk_tree_model_iter_next(list_store_h, &iter); } } } void AddressBook::move_up_impl(void) { GtkTreeIter selected_iter; GtkTreeModel* model_p; GtkTreeSelection* selection_p = gtk_tree_view_get_selection(tree_view_p); if (gtk_tree_selection_get_selected(selection_p, &model_p, &selected_iter)) { TreePathScopedHandle path_h(gtk_tree_model_get_path(model_p, &selected_iter)); if (gtk_tree_path_prev(path_h)) { GtkTreeIter prev_iter; if (!gtk_tree_model_get_iter(model_p, &prev_iter, path_h)) { write_error("Iterator error in AddressBook::move_up_impl()\n"); beep(); } else { gchar* selected_name_p = 0; gchar* selected_number_p = 0; gchar* prev_name_p = 0; gchar* prev_number_p = 0; // just do a swap of values gtk_tree_model_get(model_p, &selected_iter, ModelColumns::name, &selected_name_p, ModelColumns::number, &selected_number_p, -1); gtk_tree_model_get(model_p, &prev_iter, ModelColumns::name, &prev_name_p, ModelColumns::number, &prev_number_p, -1); gtk_list_store_set(GTK_LIST_STORE(model_p), &selected_iter, ModelColumns::name, prev_name_p, ModelColumns::number, prev_number_p, -1); gtk_list_store_set(GTK_LIST_STORE(model_p), &prev_iter, ModelColumns::name, selected_name_p, ModelColumns::number, selected_number_p, -1); // we have not placed the gchar* strings given by gtk_tree_model_get() // in a GcharScopedHandle object so we need to free them by hand g_free(selected_name_p); g_free(selected_number_p); g_free(prev_name_p); g_free(prev_number_p); gtk_tree_selection_select_iter(selection_p, &prev_iter); save_list(); } } else beep(); } else beep(); } void AddressBook::move_down_impl(void) { GtkTreeIter selected_iter; GtkTreeModel* model_p; GtkTreeSelection* selection_p = gtk_tree_view_get_selection(tree_view_p); if (gtk_tree_selection_get_selected(selection_p, &model_p, &selected_iter)) { GtkTreeIter next_iter = selected_iter;; if (gtk_tree_model_iter_next(model_p, &next_iter)) { gchar* selected_name_p = 0; gchar* selected_number_p = 0; gchar* next_name_p = 0; gchar* next_number_p = 0; // just do a swap of values gtk_tree_model_get(model_p, &selected_iter, ModelColumns::name, &selected_name_p, ModelColumns::number, &selected_number_p, -1); gtk_tree_model_get(model_p, &next_iter, ModelColumns::name, &next_name_p, ModelColumns::number, &next_number_p, -1); gtk_list_store_set(GTK_LIST_STORE(model_p), &selected_iter, ModelColumns::name, next_name_p, ModelColumns::number, next_number_p, -1); gtk_list_store_set(GTK_LIST_STORE(model_p), &next_iter, ModelColumns::name, selected_name_p, ModelColumns::number, selected_number_p, -1); // we have not placed the gchar* strings given by gtk_tree_model_get() // in a GcharScopedHandle object so we need to free them by hand g_free(selected_name_p); g_free(selected_number_p); g_free(next_name_p); g_free(next_number_p); gtk_tree_selection_select_iter(selection_p, &next_iter); save_list(); } else beep(); } else beep(); } void AddressDialogCB::addr_dialog_selected(GtkWidget* widget_p, void* data) { AddressDialog* instance_p = static_cast<AddressDialog*>(data); if (widget_p == instance_p->ok_button_p) { if (instance_p->selected_impl()) instance_p->close(); } else if (widget_p == instance_p->cancel_button_p) instance_p->close(); else { write_error("Callback error in AddressDialogCB::addr_dialog_selected()\n"); instance_p->close(); } } gboolean AddressDialogCB::addr_dialog_key_press_event(GtkWidget*, GdkEventKey* event_p, void* data) { AddressDialog* instance_p = static_cast<AddressDialog*>(data); int keycode = event_p->keyval; #if GTK_CHECK_VERSION(2,20,0) bool cancel_focus = gtk_widget_has_focus(instance_p->cancel_button_p); #else bool cancel_focus = GTK_WIDGET_HAS_FOCUS(instance_p->cancel_button_p); #endif #if GTK_CHECK_VERSION(2,99,0) if (keycode == GDK_KEY_Return && !cancel_focus) { if (instance_p->selected_impl()) instance_p->close(); return true; // stop processing here } #else if (keycode == GDK_Return && !cancel_focus) { if (instance_p->selected_impl()) instance_p->close(); return true; // stop processing here } #endif return false; // continue processing key events } AddressDialog::AddressDialog(const int standard_size, GtkWindow* parent_p): WinBase(gettext("efax-gtk: Add address"), prog_config.window_icon_h, true, parent_p) { ok_button_p = gtk_button_new_from_stock(GTK_STOCK_OK); cancel_button_p = gtk_button_new_from_stock(GTK_STOCK_CANCEL); GtkWidget* name_label_p = gtk_label_new(gettext("Name:")); GtkWidget* number_label_p = gtk_label_new(gettext("Number:")); gtk_label_set_justify(GTK_LABEL(name_label_p), GTK_JUSTIFY_RIGHT); gtk_label_set_justify(GTK_LABEL(number_label_p), GTK_JUSTIFY_RIGHT); gtk_misc_set_alignment(GTK_MISC(name_label_p), 1, 0.5); gtk_misc_set_alignment(GTK_MISC(number_label_p), 1, 0.5); name_entry_p = gtk_entry_new(); number_entry_p = gtk_entry_new(); gtk_widget_set_size_request(name_entry_p, standard_size * 8, standard_size); gtk_widget_set_size_request(number_entry_p, standard_size * 8, standard_size); GtkWidget* button_box_p = gtk_hbutton_box_new(); GtkTable* table_p = GTK_TABLE(gtk_table_new(3, 2, false)); gtk_button_box_set_layout(GTK_BUTTON_BOX(button_box_p), GTK_BUTTONBOX_END); gtk_box_set_spacing(GTK_BOX(button_box_p), standard_size/2); gtk_container_add(GTK_CONTAINER(button_box_p), cancel_button_p); gtk_container_add(GTK_CONTAINER(button_box_p), ok_button_p); gtk_table_attach(table_p, name_label_p, 0, 1, 0, 1, GTK_FILL, GTK_SHRINK, standard_size/2, standard_size/4); gtk_table_attach(table_p, name_entry_p, 1, 2, 0, 1, GtkAttachOptions(GTK_FILL | GTK_EXPAND), GTK_SHRINK, standard_size/2, standard_size/4); gtk_table_attach(table_p, number_label_p, 0, 1, 1, 2, GTK_FILL, GTK_SHRINK, standard_size/2, standard_size/4); gtk_table_attach(table_p, number_entry_p, 1, 2, 1, 2, GtkAttachOptions(GTK_FILL | GTK_EXPAND), GTK_SHRINK, standard_size/2, standard_size/4); gtk_table_attach(table_p, button_box_p, 0, 2, 2, 3, GtkAttachOptions(GTK_FILL | GTK_EXPAND), GTK_SHRINK, standard_size/2, standard_size/4); g_signal_connect(G_OBJECT(ok_button_p), "clicked", G_CALLBACK(AddressDialogCB::addr_dialog_selected), this); g_signal_connect(G_OBJECT(cancel_button_p), "clicked", G_CALLBACK(AddressDialogCB::addr_dialog_selected), this); g_signal_connect(G_OBJECT(get_win()), "key_press_event", G_CALLBACK(AddressDialogCB::addr_dialog_key_press_event), this); #if GTK_CHECK_VERSION(2,20,0) gtk_widget_set_can_default(ok_button_p, true); gtk_widget_set_can_default(cancel_button_p, true); #else GTK_WIDGET_SET_FLAGS(ok_button_p, GTK_CAN_DEFAULT); GTK_WIDGET_SET_FLAGS(cancel_button_p, GTK_CAN_DEFAULT); #endif gtk_container_add(GTK_CONTAINER(get_win()), GTK_WIDGET(table_p)); gtk_window_set_type_hint(get_win(), GDK_WINDOW_TYPE_HINT_DIALOG); gtk_container_set_border_width(GTK_CONTAINER(get_win()), standard_size/2); gtk_widget_grab_focus(name_entry_p); gtk_window_set_position(get_win(), GTK_WIN_POS_CENTER_ON_PARENT); gtk_window_set_resizable(get_win(), false); gtk_widget_show_all(GTK_WIDGET(get_win())); } bool AddressDialog::selected_impl(void) { bool return_val = false; const gchar* name_text = gtk_entry_get_text(GTK_ENTRY(name_entry_p)); const gchar* number_text = gtk_entry_get_text(GTK_ENTRY(number_entry_p)); if (!*name_text || !*number_text) beep(); else { std::vector<std::string> out_val; out_val.push_back((const char*)name_text); out_val.push_back((const char*)number_text); accepted(out_val); return_val = true; } return return_val; }
utf-8
1
unknown
unknown
supercollider-sc3-plugins-3.9.1~repack/source/AYUGens/AY_libayemu/include/ayemu_8912.h
/** * AY/YM emulator include file */ #ifndef _AYEMU_ay8912_h #define _AYEMU_ay8912_h #include <stddef.h> BEGIN_C_DECLS /** Types of stereo. The codes of stereo types used for generage sound. */ typedef enum { AYEMU_MONO = 0, AYEMU_ABC, AYEMU_ACB, AYEMU_BAC, AYEMU_BCA, AYEMU_CAB, AYEMU_CBA, AYEMU_STEREO_CUSTOM = 255 } ayemu_stereo_t; /** Sound chip type. Constant for identify used chip for emulation */ typedef enum { AYEMU_AY, /**< default AY chip (lion17 for now) */ AYEMU_YM, /**< default YM chip (lion17 for now) */ AYEMU_AY_LION17, /**< emulate AY with Lion17 table */ AYEMU_YM_LION17, /**< emulate YM with Lion17 table */ AYEMU_AY_KAY, /**< emulate AY with HACKER KAY table */ AYEMU_YM_KAY, /**< emulate YM with HACKER KAY table */ AYEMU_AY_LOG, /**< emulate AY with logariphmic table */ AYEMU_YM_LOG, /**< emulate YM with logariphmic table */ AYEMU_AY_CUSTOM, /**< use AY with custom table. */ AYEMU_YM_CUSTOM /**< use YM with custom table. */ } ayemu_chip_t; /** parsed by #ayemu_set_regs() AY registers data \internal */ typedef struct { int tone_a; /**< R0, R1 */ int tone_b; /**< R2, R3 */ int tone_c; /**< R4, R5 */ int noise; /**< R6 */ int R7_tone_a; /**< R7 bit 0 */ int R7_tone_b; /**< R7 bit 1 */ int R7_tone_c; /**< R7 bit 2 */ int R7_noise_a; /**< R7 bit 3 */ int R7_noise_b; /**< R7 bit 4 */ int R7_noise_c; /**< R7 bit 5 */ int vol_a; /**< R8 bits 3-0 */ int vol_b; /**< R9 bits 3-0 */ int vol_c; /**< R10 bits 3-0 */ int env_a; /**< R8 bit 4 */ int env_b; /**< R9 bit 4 */ int env_c; /**< R10 bit 4 */ int env_freq; /**< R11, R12 */ int env_style; /**< R13 */ } ayemu_regdata_t; /** Output sound format \internal */ typedef struct { int freq; /**< sound freq */ int channels; /**< channels (1-mono, 2-stereo) */ int bpc; /**< bits (8 or 16) */ } ayemu_sndfmt_t; /** * \defgroup libayemu Functions for emulate AY/YM chip */ /*@{*/ /** Data structure for sound chip emulation \internal * */ typedef struct { /* emulator settings */ int table[32]; /**< table of volumes for chip */ ayemu_chip_t type; /**< general chip type (\b AYEMU_AY or \b AYEMU_YM) */ int ChipFreq; /**< chip emulator frequency */ int eq[6]; /**< volumes for channels. Array contains 6 elements: A left, A right, B left, B right, C left and C right; range -100...100 */ ayemu_regdata_t regs; /**< parsed registers data */ ayemu_sndfmt_t sndfmt; /**< output sound format */ /* flags */ int magic; /**< structure initialized flag */ int default_chip_flag; /**< =1 after init, resets in #ayemu_set_chip_type() */ int default_stereo_flag; /**< =1 after init, resets in #ayemu_set_stereo() */ int default_sound_format_flag; /**< =1 after init, resets in #ayemu_set_sound_format() */ int dirty; /**< dirty flag. Sets if any emulator properties changed */ int bit_a; /**< state of channel A generator */ int bit_b; /**< state of channel B generator */ int bit_c; /**< state of channel C generator */ int bit_n; /**< current generator state */ int cnt_a; /**< back counter of A */ int cnt_b; /**< back counter of B */ int cnt_c; /**< back counter of C */ int cnt_n; /**< back counter of noise generator */ int cnt_e; /**< back counter of envelop generator */ int ChipTacts_per_outcount; /**< chip's counts per one sound signal count */ int Amp_Global; /**< scale factor for amplitude */ int vols[6][32]; /**< stereo type (channel volumes) and chip table. This cache calculated by #table and #eq */ int EnvNum; /**< number of current envilopment (0...15) */ int env_pos; /**< current position in envelop (0...127) */ int Cur_Seed; /**< random numbers counter */ } ayemu_ay_t; EXTERN void ayemu_init(ayemu_ay_t *ay); EXTERN void ayemu_reset(ayemu_ay_t *ay); EXTERN int ayemu_set_chip_type(ayemu_ay_t *ay, ayemu_chip_t chip, int *custom_table); EXTERN void ayemu_set_chip_freq(ayemu_ay_t *ay, int chipfreq); EXTERN int ayemu_set_stereo(ayemu_ay_t *ay, ayemu_stereo_t stereo, int *custom_eq); EXTERN int ayemu_set_sound_format (ayemu_ay_t *ay, int freq, int chans, int bits); EXTERN void ayemu_set_regs (ayemu_ay_t *ay, unsigned char *regs); EXTERN void* ayemu_gen_sound (ayemu_ay_t *ay, void *buf, size_t bufsize); /*@}*/ END_C_DECLS #endif
utf-8
1
GPL-2+
2015 SuperCollider Development Team <sc-dev@lists.bham.ac.uk>
linux-5.16.7/drivers/gpu/drm/nouveau/nvkm/subdev/instmem/nv04.c
/* * Copyright 2012 Red Hat Inc. * * Permission is hereby granted, free of charge, to any person obtaining a * copy of this software and associated documentation files (the "Software"), * to deal in the Software without restriction, including without limitation * the rights to use, copy, modify, merge, publish, distribute, sublicense, * and/or sell copies of the Software, and to permit persons to whom the * Software is furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL * THE COPYRIGHT HOLDER(S) OR AUTHOR(S) 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. * * Authors: Ben Skeggs */ #define nv04_instmem(p) container_of((p), struct nv04_instmem, base) #include "priv.h" #include <core/ramht.h> struct nv04_instmem { struct nvkm_instmem base; struct nvkm_mm heap; }; /****************************************************************************** * instmem object implementation *****************************************************************************/ #define nv04_instobj(p) container_of((p), struct nv04_instobj, base.memory) struct nv04_instobj { struct nvkm_instobj base; struct nv04_instmem *imem; struct nvkm_mm_node *node; }; static void nv04_instobj_wr32(struct nvkm_memory *memory, u64 offset, u32 data) { struct nv04_instobj *iobj = nv04_instobj(memory); struct nvkm_device *device = iobj->imem->base.subdev.device; nvkm_wr32(device, 0x700000 + iobj->node->offset + offset, data); } static u32 nv04_instobj_rd32(struct nvkm_memory *memory, u64 offset) { struct nv04_instobj *iobj = nv04_instobj(memory); struct nvkm_device *device = iobj->imem->base.subdev.device; return nvkm_rd32(device, 0x700000 + iobj->node->offset + offset); } static const struct nvkm_memory_ptrs nv04_instobj_ptrs = { .rd32 = nv04_instobj_rd32, .wr32 = nv04_instobj_wr32, }; static void nv04_instobj_release(struct nvkm_memory *memory) { } static void __iomem * nv04_instobj_acquire(struct nvkm_memory *memory) { struct nv04_instobj *iobj = nv04_instobj(memory); struct nvkm_device *device = iobj->imem->base.subdev.device; return device->pri + 0x700000 + iobj->node->offset; } static u64 nv04_instobj_size(struct nvkm_memory *memory) { return nv04_instobj(memory)->node->length; } static u64 nv04_instobj_addr(struct nvkm_memory *memory) { return nv04_instobj(memory)->node->offset; } static enum nvkm_memory_target nv04_instobj_target(struct nvkm_memory *memory) { return NVKM_MEM_TARGET_INST; } static void * nv04_instobj_dtor(struct nvkm_memory *memory) { struct nv04_instobj *iobj = nv04_instobj(memory); mutex_lock(&iobj->imem->base.mutex); nvkm_mm_free(&iobj->imem->heap, &iobj->node); mutex_unlock(&iobj->imem->base.mutex); nvkm_instobj_dtor(&iobj->imem->base, &iobj->base); return iobj; } static const struct nvkm_memory_func nv04_instobj_func = { .dtor = nv04_instobj_dtor, .target = nv04_instobj_target, .size = nv04_instobj_size, .addr = nv04_instobj_addr, .acquire = nv04_instobj_acquire, .release = nv04_instobj_release, }; static int nv04_instobj_new(struct nvkm_instmem *base, u32 size, u32 align, bool zero, struct nvkm_memory **pmemory) { struct nv04_instmem *imem = nv04_instmem(base); struct nv04_instobj *iobj; int ret; if (!(iobj = kzalloc(sizeof(*iobj), GFP_KERNEL))) return -ENOMEM; *pmemory = &iobj->base.memory; nvkm_instobj_ctor(&nv04_instobj_func, &imem->base, &iobj->base); iobj->base.memory.ptrs = &nv04_instobj_ptrs; iobj->imem = imem; mutex_lock(&imem->base.mutex); ret = nvkm_mm_head(&imem->heap, 0, 1, size, size, align ? align : 1, &iobj->node); mutex_unlock(&imem->base.mutex); return ret; } /****************************************************************************** * instmem subdev implementation *****************************************************************************/ static u32 nv04_instmem_rd32(struct nvkm_instmem *imem, u32 addr) { return nvkm_rd32(imem->subdev.device, 0x700000 + addr); } static void nv04_instmem_wr32(struct nvkm_instmem *imem, u32 addr, u32 data) { nvkm_wr32(imem->subdev.device, 0x700000 + addr, data); } static int nv04_instmem_oneinit(struct nvkm_instmem *base) { struct nv04_instmem *imem = nv04_instmem(base); struct nvkm_device *device = imem->base.subdev.device; int ret; /* PRAMIN aperture maps over the end of VRAM, reserve it */ imem->base.reserved = 512 * 1024; ret = nvkm_mm_init(&imem->heap, 0, 0, imem->base.reserved, 1); if (ret) return ret; /* 0x00000-0x10000: reserve for probable vbios image */ ret = nvkm_memory_new(device, NVKM_MEM_TARGET_INST, 0x10000, 0, false, &imem->base.vbios); if (ret) return ret; /* 0x10000-0x18000: reserve for RAMHT */ ret = nvkm_ramht_new(device, 0x08000, 0, NULL, &imem->base.ramht); if (ret) return ret; /* 0x18000-0x18800: reserve for RAMFC (enough for 32 nv30 channels) */ ret = nvkm_memory_new(device, NVKM_MEM_TARGET_INST, 0x00800, 0, true, &imem->base.ramfc); if (ret) return ret; /* 0x18800-0x18a00: reserve for RAMRO */ ret = nvkm_memory_new(device, NVKM_MEM_TARGET_INST, 0x00200, 0, false, &imem->base.ramro); if (ret) return ret; return 0; } static void * nv04_instmem_dtor(struct nvkm_instmem *base) { struct nv04_instmem *imem = nv04_instmem(base); nvkm_memory_unref(&imem->base.ramfc); nvkm_memory_unref(&imem->base.ramro); nvkm_ramht_del(&imem->base.ramht); nvkm_memory_unref(&imem->base.vbios); nvkm_mm_fini(&imem->heap); return imem; } static const struct nvkm_instmem_func nv04_instmem = { .dtor = nv04_instmem_dtor, .oneinit = nv04_instmem_oneinit, .rd32 = nv04_instmem_rd32, .wr32 = nv04_instmem_wr32, .memory_new = nv04_instobj_new, .zero = false, }; int nv04_instmem_new(struct nvkm_device *device, enum nvkm_subdev_type type, int inst, struct nvkm_instmem **pimem) { struct nv04_instmem *imem; if (!(imem = kzalloc(sizeof(*imem), GFP_KERNEL))) return -ENOMEM; nvkm_instmem_ctor(&nv04_instmem, device, type, inst, &imem->base); *pimem = &imem->base; return 0; }
utf-8
1
GPL-2
1991-2012 Linus Torvalds and many others
gpt-1.1/src/modules/PortugolAST.hpp
/*************************************************************************** * Copyright (C) 2003-2006 by Thiago Silva * * thiago.silva@kdemal.net * * * * This program is free software; you can redistribute it and/or modify * * it under the terms of the GNU General Public License as published by * * the Free Software Foundation; either version 2 of the License, or * * (at your option) any later version. * * * * This program is distributed in the hope that it will be useful, * * but WITHOUT ANY WARRANTY; without even the implied warranty of * * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * * GNU General Public License for more details. * * * * You should have received a copy of the GNU General Public License * * along with this program; if not, write to the * * Free Software Foundation, Inc., * * 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. * ***************************************************************************/ #ifndef PORTUGOLAST_HPP #define PORTUGOLAST_HPP #include <antlr/CommonAST.hpp> #include <string> using namespace std; using namespace antlr; class PortugolAST : public CommonAST { public: PortugolAST(); PortugolAST( RefToken t ); PortugolAST( const CommonAST& other ); PortugolAST( const PortugolAST& other ); ~PortugolAST(); void setLine(int line); int getLine(); void setEndLine(int endLine); int getEndLine(); void setEvalType(int type) { eval_type = type; } int getEvalType() { return eval_type; } void setFilename(const string& fname) { filename = fname; } string getFilename() { return filename; } virtual RefAST clone( void ) const; virtual void initialize( RefToken t ); virtual const char* typeName( void ) const; static RefAST factory(); static const char* const TYPE_NAME; protected: int line; int endLine; int eval_type; //evaluated type of expression string filename; }; typedef ASTRefCount<PortugolAST> RefPortugolAST; #endif
utf-8
1
GPL-2
2006-2008 Thiago Silva <tsilva@sourcecraft.info>
libdnf-0.55.2/libdnf/hy-packageset.h
/* -*- Mode: C; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- * * Copyright (C) 2012-2013 Red Hat, Inc. * Copyright (C) 2015 Richard Hughes <richard@hughsie.com> * * 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 */ #ifndef __DNF_PACKAGESET_H #define __DNF_PACKAGESET_H #include "dnf-sack.h" #include "hy-types.h" #ifdef __cplusplus extern "C" { #endif DnfPackageSet *dnf_packageset_new (DnfSack *sack); void dnf_packageset_free (DnfPackageSet *pset); DnfPackageSet *dnf_packageset_clone (DnfPackageSet *pset); void dnf_packageset_add (DnfPackageSet *pset, DnfPackage *pkg); size_t dnf_packageset_count (DnfPackageSet *pset); int dnf_packageset_has (DnfPackageSet *pset, DnfPackage *pkg); DnfPackageSet *dnf_packageset_from_bitmap (DnfSack *sack, Map *m); Map *dnf_packageset_get_map (DnfPackageSet *pset); G_DEFINE_AUTOPTR_CLEANUP_FUNC(DnfPackageSet, dnf_packageset_free) #ifdef __cplusplus } #endif #endif /* __DNF_PACKAGESET_H */
utf-8
1
LGPL-2.1
2012-2020, Red Hat, Inc.
tcptrack-1.4.3/src/SocketPair.cc
#include <unistd.h> #include <assert.h> #include "IPAddress.h" #include "SocketPair.h" SocketPair::SocketPair( IPAddress &naddrA, portnum_t nm_portA, IPAddress &naddrB, portnum_t nm_portB ) : m_portA(nm_portA), m_portB(nm_portB) { m_pAddrA = naddrA.Clone(); m_pAddrB = naddrB.Clone(); } SocketPair::SocketPair( const SocketPair &orig ) : m_portA(orig.m_portA), m_portB(orig.m_portB) { m_pAddrA = orig.m_pAddrA->Clone(); m_pAddrB = orig.m_pAddrB->Clone(); } SocketPair::~SocketPair() { delete m_pAddrA; delete m_pAddrB; } // a socketpair is equal to another SocketPair if their src/dst addrs & ports // are the same, OR if they are just the opposite (ie, if it were for a // packet heading in the opposite direction). // this is so packets heading in either direction will match the same // connection. bool SocketPair::operator==( const SocketPair &sp ) const { if( *(sp.m_pAddrA) == *(m_pAddrA) && *(sp.m_pAddrB) == *(m_pAddrB) && sp.m_portA == m_portA && sp.m_portB == m_portB ) { return true; } else if( *(sp.m_pAddrA) == *(m_pAddrB) && *(sp.m_pAddrB) == *(m_pAddrA) && sp.m_portA == m_portB && sp.m_portB == m_portA ) { return true; } else return false; } bool SocketPair::operator!=( const SocketPair &sp ) const { return !( sp==*this ); } uint32_t SocketPair::hash() const { uint32_t hash = 0; assert( m_portB > 0 ); hash = m_pAddrA->hash() % m_portB; assert( m_portA > 0 ); hash += m_pAddrB->hash() % m_portA; return hash; }
utf-8
1
LGPL-2.1
2003, Steve Benson <steve@rhythm.cx>
ncmpcpp-0.9.2/src/screens/media_library.h
/*************************************************************************** * Copyright (C) 2008-2021 by Andrzej Rybczak * * andrzej@rybczak.net * * * * This program is free software; you can redistribute it and/or modify * * it under the terms of the GNU General Public License as published by * * the Free Software Foundation; either version 2 of the License, or * * (at your option) any later version. * * * * This program is distributed in the hope that it will be useful, * * but WITHOUT ANY WARRANTY; without even the implied warranty of * * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * * GNU General Public License for more details. * * * * You should have received a copy of the GNU General Public License * * along with this program; if not, write to the * * Free Software Foundation, Inc., * * 51 Franklin St, Fifth Floor, Boston, MA 02110-1301, USA. * ***************************************************************************/ #ifndef NCMPCPP_MEDIA_LIBRARY_H #define NCMPCPP_MEDIA_LIBRARY_H #include <boost/date_time/posix_time/posix_time_types.hpp> #include "interfaces.h" #include "regex_filter.h" #include "screens/screen.h" #include "song_list.h" struct MediaLibrary: Screen<NC::Window *>, Filterable, HasColumns, HasSongs, Searchable, Tabbable { MediaLibrary(); virtual void switchTo() override; virtual void resize() override; virtual std::wstring title() override; virtual ScreenType type() override { return ScreenType::MediaLibrary; } virtual void refresh() override; virtual void update() override; virtual int windowTimeout() override; virtual void mouseButtonPressed(MEVENT me) override; virtual bool isLockable() override { return true; } virtual bool isMergable() override { return true; } // Searchable implementation virtual bool allowsSearching() override; virtual const std::string &searchConstraint() override; virtual void setSearchConstraint(const std::string &constraint) override; virtual void clearSearchConstraint() override; virtual bool search(SearchDirection direction, bool wrap, bool skip_current) override; // Filterable implementation virtual bool allowsFiltering() override; virtual std::string currentFilter() override; virtual void applyFilter(const std::string &filter) override; // HasSongs implementation virtual bool itemAvailable() override; virtual bool addItemToPlaylist(bool play) override; virtual std::vector<MPD::Song> getSelectedSongs() override; // HasColumns implementation virtual bool previousColumnAvailable() override; virtual void previousColumn() override; virtual bool nextColumnAvailable() override; virtual void nextColumn() override; // other members void updateTimer(); void toggleColumnsMode(); int columns(); void locateSong(const MPD::Song &s); void toggleSortMode(); void requestTagsUpdate() { m_tags_update_request = true; } void requestAlbumsUpdate() { m_albums_update_request = true; } void requestSongsUpdate() { m_songs_update_request = true; } struct PrimaryTag { PrimaryTag() : m_mtime(0) { } PrimaryTag(std::string tag_, time_t mtime_) : m_tag(std::move(tag_)), m_mtime(mtime_) { } const std::string &tag() const { return m_tag; } time_t mtime() const { return m_mtime; } private: std::string m_tag; time_t m_mtime; }; struct Album { Album(std::string tag_, std::string album_, std::string date_, time_t mtime_) : m_tag(std::move(tag_)), m_album(std::move(album_)) , m_date(std::move(date_)), m_mtime(mtime_) { } const std::string &tag() const { return m_tag; } const std::string &album() const { return m_album; } const std::string &date() const { return m_date; } time_t mtime() const { return m_mtime; } private: std::string m_tag; std::string m_album; std::string m_date; time_t m_mtime; }; struct AlbumEntry { AlbumEntry() : m_all_tracks_entry(false), m_album("", "", "", 0) { } explicit AlbumEntry(Album album_) : m_all_tracks_entry(false), m_album(album_) { } const Album &entry() const { return m_album; } bool isAllTracksEntry() const { return m_all_tracks_entry; } static AlbumEntry mkAllTracksEntry(std::string tag) { auto result = AlbumEntry(Album(tag, "", "", 0)); result.m_all_tracks_entry = true; return result; } private: bool m_all_tracks_entry; Album m_album; }; NC::Menu<PrimaryTag> Tags; NC::Menu<AlbumEntry> Albums; SongMenu Songs; private: bool m_tags_update_request; bool m_albums_update_request; bool m_songs_update_request; boost::posix_time::ptime m_timer; const int m_window_timeout; const boost::posix_time::time_duration m_fetching_delay; Regex::Filter<PrimaryTag> m_tags_search_predicate; Regex::ItemFilter<AlbumEntry> m_albums_search_predicate; Regex::Filter<MPD::Song> m_songs_search_predicate; }; extern MediaLibrary *myLibrary; #endif // NCMPCPP_MEDIA_LIBRARY_H
utf-8
1
GPL-2+
2008-2012 Andrzej Rybczak <electricityispower@gmail.com> 2009-2010 Frank Blendinger <fb@intoxicatedmind.net>
cbmc-5.12/regression/snapshot-harness/arrays_01/main.c
#include <assert.h> int array[] = {1, 2, 3}; int *p; int *q; void initialize() { p = &(array[1]); q = array + 1; array[0] = 4; } void checkpoint() { } int main() { initialize(); checkpoint(); assert(p == &(array[1])); assert(p == q); assert(*p == *q); assert(array[0] != *p); *p = 4; assert(array[0] == *p); }
utf-8
1
BSD-4-clause
2001-2018, Daniel Kroening, Edmund Clarke, Computer Science Department, Oxford University Computer Systems Institute, ETH Zurich Computer Science Department, Carnegie Mellon University
llvm-toolchain-11-11.1.0/clang/test/CXX/temp/temp.spec/temp.explicit/p9-linkage.cpp
// RUN: %clang_cc1 -triple x86_64-apple-darwin -O1 -disable-llvm-passes -emit-llvm -std=c++11 -o - %s | FileCheck %s template<typename T> struct X0 { void f(T &t) { t = 0; } void g(T &t); void h(T &t); static T static_var; }; template<typename T> inline void X0<T>::g(T & t) { t = 0; } template<typename T> void X0<T>::h(T & t) { t = 0; } template<typename T> T X0<T>::static_var = 0; extern template struct X0<int*>; int *&test(X0<int*> xi, int *ip) { // CHECK: define available_externally void @_ZN2X0IPiE1fERS0_ xi.f(ip); // CHECK: define available_externally void @_ZN2X0IPiE1gERS0_ xi.g(ip); // CHECK: declare void @_ZN2X0IPiE1hERS0_ xi.h(ip); return X0<int*>::static_var; } template<typename T> void f0(T& t) { t = 0; } template<typename T> inline void f1(T& t) { t = 0; } extern template void f0<>(int *&); extern template void f1<>(int *&); void test_f0(int *ip, float *fp) { // CHECK: declare void @_Z2f0IPiEvRT_ f0(ip); // CHECK: define linkonce_odr void @_Z2f0IPfEvRT_ f0(fp); } void test_f1(int *ip, float *fp) { // CHECK: define available_externally void @_Z2f1IPiEvRT_ f1(ip); // CHECK: define linkonce_odr void @_Z2f1IPfEvRT_ f1(fp); }
utf-8
1
unknown
unknown
llvm-toolchain-12-12.0.1/clang/test/OpenMP/nvptx_declare_variant_implementation_vendor_codegen.cpp
// RUN: %clang_cc1 -verify -fopenmp -x c++ -triple powerpc64le-unknown-unknown -fopenmp-targets=nvptx64-nvidia-cuda -emit-llvm-bc %s -o %t-ppc-host.bc -fopenmp-version=45 // RUN: %clang_cc1 -verify -fopenmp -x c++ -triple nvptx64-unknown-unknown -aux-triple powerpc64le-unknown-unknown -emit-llvm %s -fopenmp-is-device -fopenmp-host-ir-file-path %t-ppc-host.bc -o - -fopenmp-version=45 | FileCheck %s --implicit-check-not='ret i32 {{6|7|8|9|10|12|13|14|15|17|18|19|20|21|22|23|24|26}}' // RUN: %clang_cc1 -verify -fopenmp -x c++ -triple nvptx64-unknown-unknown -aux-triple powerpc64le-unknown-unknown -emit-llvm %s -fopenmp-is-device -fopenmp-host-ir-file-path %t-ppc-host.bc -emit-pch -o %t -fopenmp-version=45 // RUN: %clang_cc1 -verify -fopenmp -x c++ -triple nvptx64-unknown-unknown -aux-triple powerpc64le-unknown-unknown -emit-llvm %s -fopenmp-is-device -fopenmp-host-ir-file-path %t-ppc-host.bc -include-pch %t -o - -fopenmp-version=45 | FileCheck %s --implicit-check-not='ret i32 {{6|7|8|9|10|12|13|14|15|17|18|19|20|21|22|23|24|26}}' // RUN: %clang_cc1 -verify -fopenmp -x c++ -triple powerpc64le-unknown-unknown -fopenmp-targets=nvptx64-nvidia-cuda -emit-llvm-bc %s -o %t-ppc-host.bc // RUN: %clang_cc1 -verify -fopenmp -x c++ -triple nvptx64-unknown-unknown -aux-triple powerpc64le-unknown-unknown -emit-llvm %s -fopenmp-is-device -fopenmp-host-ir-file-path %t-ppc-host.bc -o - | FileCheck %s --implicit-check-not='ret i32 {{6|7|8|9|10|12|13|14|15|17|18|19|20|21|22|23|24|26}}' // RUN: %clang_cc1 -verify -fopenmp -x c++ -triple nvptx64-unknown-unknown -aux-triple powerpc64le-unknown-unknown -emit-llvm %s -fopenmp-is-device -fopenmp-host-ir-file-path %t-ppc-host.bc -emit-pch -o %t // RUN: %clang_cc1 -verify -fopenmp -x c++ -triple nvptx64-unknown-unknown -aux-triple powerpc64le-unknown-unknown -emit-llvm %s -fopenmp-is-device -fopenmp-host-ir-file-path %t-ppc-host.bc -include-pch %t -o - | FileCheck %s --implicit-check-not='ret i32 {{6|7|8|9|10|12|13|14|15|17|18|19|20|21|22|23|24|26}}' // expected-no-diagnostics // CHECK-DAG: ret i32 2 // CHECK-DAG: ret i32 3 // CHECK-DAG: ret i32 4 // CHECK-DAG: ret i32 5 // CHECK-DAG: ret i32 11 // CHECK-DAG: ret i32 16 // CHECK-DAG: ret i32 19 // CHECK-DAG: ret i32 25 // CHECK-DAG: ret i32 27 // CHECK-DAG: ret i32 28 // CHECK-DAG: ret i32 29 #ifndef HEADER #define HEADER int foo() { return 2; } int bazzz(); int test(); static int stat_unused_(); static int stat_used_(); #pragma omp declare target #pragma omp declare variant(foo) match(implementation = {vendor(llvm)}) int bar() { return 3; } #pragma omp declare variant(bazzz) match(implementation = {vendor(llvm)}) int baz() { return 4; } #pragma omp declare variant(test) match(implementation = {vendor(llvm)}) int call() { return 5; } #pragma omp declare variant(stat_unused_) match(implementation = {vendor(llvm)}) static int stat_unused() { return 6; } #pragma omp declare variant(stat_used_) match(implementation = {vendor(llvm)}) static int stat_used() { return 7; } #pragma omp end declare target int main() { int res; #pragma omp target map(from \ : res) res = bar() + baz() + call(); return res; } int test() { return 8; } static int stat_unused_() { return 9; } static int stat_used_() { return 10; } #pragma omp declare target struct SpecialFuncs { void vd() {} SpecialFuncs(); ~SpecialFuncs(); int method_() { return 11; } #pragma omp declare variant(SpecialFuncs::method_) \ match(implementation = {vendor(llvm)}) int method() { return 12; } #pragma omp declare variant(SpecialFuncs::method_) \ match(implementation = {vendor(llvm)}) int Method(); } s; int SpecialFuncs::Method() { return 13; } struct SpecSpecialFuncs { void vd() {} SpecSpecialFuncs(); ~SpecSpecialFuncs(); int method_(); #pragma omp declare variant(SpecSpecialFuncs::method_) \ match(implementation = {vendor(llvm)}) int method() { return 14; } #pragma omp declare variant(SpecSpecialFuncs::method_) \ match(implementation = {vendor(llvm)}) int Method(); } s1; #pragma omp end declare target int SpecSpecialFuncs::method_() { return 15; } int SpecSpecialFuncs::Method() { return 16; } int prio() { return 17; } int prio1() { return 18; } static int prio2() { return 19; } static int prio3() { return 20; } static int prio4() { return 21; } int fn_linkage_variant() { return 22; } extern "C" int fn_linkage_variant1() { return 23; } int fn_variant2() { return 24; } #pragma omp declare target void xxx() { (void)s.method(); (void)s1.method(); } #pragma omp declare variant(prio) match(implementation = {vendor(llvm)}) #pragma omp declare variant(prio1) match(implementation = {vendor(score(1) \ : llvm)}) int prio_() { return 25; } #pragma omp declare variant(prio4) match(implementation = {vendor(score(3) \ : llvm)}) #pragma omp declare variant(prio2) match(implementation = {vendor(score(5) \ : llvm)}) #pragma omp declare variant(prio3) match(implementation = {vendor(score(1) \ : llvm)}) static int prio1_() { return 26; } int int_fn() { return prio1_(); } extern "C" { #pragma omp declare variant(fn_linkage_variant) match(implementation = {vendor(llvm)}) int fn_linkage() { return 27; } } #pragma omp declare variant(fn_linkage_variant1) match(implementation = {vendor(llvm)}) int fn_linkage1() { return 28; } #pragma omp declare variant(fn_variant2) match(implementation = {vendor(llvm, ibm)}) int fn2() { return 29; } #pragma omp end declare target #endif // HEADER
utf-8
1
unknown
unknown
mpfr4-4.1.0/src/fma.c
/* mpfr_fma -- Floating multiply-add Copyright 2001-2002, 2004, 2006-2020 Free Software Foundation, Inc. Contributed by the AriC and Caramba projects, INRIA. This file is part of the GNU MPFR Library. The GNU MPFR 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 3 of the License, or (at your option) any later version. The GNU MPFR Library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with the GNU MPFR Library; see the file COPYING.LESSER. If not, see https://www.gnu.org/licenses/ or write to the Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301, USA. */ #define MPFR_NEED_LONGLONG_H #include "mpfr-impl.h" /* The fused-multiply-add (fma) of x, y and z is defined by: fma(x,y,z)= x*y + z */ /* this function deals with all cases where inputs are singular, i.e., either NaN, Inf or zero */ static int mpfr_fma_singular (mpfr_ptr s, mpfr_srcptr x, mpfr_srcptr y, mpfr_srcptr z, mpfr_rnd_t rnd_mode) { if (MPFR_IS_NAN(x) || MPFR_IS_NAN(y) || MPFR_IS_NAN(z)) { MPFR_SET_NAN(s); MPFR_RET_NAN; } /* now neither x, y or z is NaN */ else if (MPFR_IS_INF(x) || MPFR_IS_INF(y)) { /* cases Inf*0+z, 0*Inf+z, Inf-Inf */ if ((MPFR_IS_ZERO(y)) || (MPFR_IS_ZERO(x)) || (MPFR_IS_INF(z) && ((MPFR_MULT_SIGN(MPFR_SIGN(x), MPFR_SIGN(y))) != MPFR_SIGN(z)))) { MPFR_SET_NAN(s); MPFR_RET_NAN; } else if (MPFR_IS_INF(z)) /* case Inf-Inf already checked above */ { MPFR_SET_INF(s); MPFR_SET_SAME_SIGN(s, z); MPFR_RET(0); } else /* z is finite */ { MPFR_SET_INF(s); MPFR_SET_SIGN(s, MPFR_MULT_SIGN(MPFR_SIGN(x) , MPFR_SIGN(y))); MPFR_RET(0); } } /* now x and y are finite */ else if (MPFR_IS_INF(z)) { MPFR_SET_INF(s); MPFR_SET_SAME_SIGN(s, z); MPFR_RET(0); } else if (MPFR_IS_ZERO(x) || MPFR_IS_ZERO(y)) { if (MPFR_IS_ZERO(z)) { int sign_p; sign_p = MPFR_MULT_SIGN( MPFR_SIGN(x) , MPFR_SIGN(y) ); MPFR_SET_SIGN(s, (rnd_mode != MPFR_RNDD ? (MPFR_IS_NEG_SIGN(sign_p) && MPFR_IS_NEG(z) ? MPFR_SIGN_NEG : MPFR_SIGN_POS) : (MPFR_IS_POS_SIGN(sign_p) && MPFR_IS_POS(z) ? MPFR_SIGN_POS : MPFR_SIGN_NEG))); MPFR_SET_ZERO(s); MPFR_RET(0); } else return mpfr_set (s, z, rnd_mode); } else /* necessarily z is zero here */ { MPFR_ASSERTD(MPFR_IS_ZERO(z)); return mpfr_mul (s, x, y, rnd_mode); } } /* s <- x*y + z */ int mpfr_fma (mpfr_ptr s, mpfr_srcptr x, mpfr_srcptr y, mpfr_srcptr z, mpfr_rnd_t rnd_mode) { int inexact; mpfr_t u; mp_size_t n; mpfr_exp_t e; mpfr_prec_t precx, precy; MPFR_SAVE_EXPO_DECL (expo); MPFR_GROUP_DECL(group); MPFR_LOG_FUNC (("x[%Pu]=%.*Rg y[%Pu]=%.*Rg z[%Pu]=%.*Rg rnd=%d", mpfr_get_prec (x), mpfr_log_prec, x, mpfr_get_prec (y), mpfr_log_prec, y, mpfr_get_prec (z), mpfr_log_prec, z, rnd_mode), ("s[%Pu]=%.*Rg inexact=%d", mpfr_get_prec (s), mpfr_log_prec, s, inexact)); /* particular cases */ if (MPFR_UNLIKELY( MPFR_IS_SINGULAR(x) || MPFR_IS_SINGULAR(y) || MPFR_IS_SINGULAR(z) )) return mpfr_fma_singular (s, x, y, z, rnd_mode); e = MPFR_GET_EXP (x) + MPFR_GET_EXP (y); precx = MPFR_PREC (x); precy = MPFR_PREC (y); /* First deal with special case where prec(x) = prec(y) and x*y does not overflow nor underflow. Do it only for small sizes since for large sizes x*y is faster using Mulders' algorithm (as a rule of thumb, we assume mpn_mul_n is faster up to 4*MPFR_MUL_THRESHOLD). Since |EXP(x)|, |EXP(y)| < 2^(k-2) on a k-bit computer, |EXP(x)+EXP(y)| < 2^(k-1), thus cannot overflow nor underflow. */ if (precx == precy && e <= __gmpfr_emax && e > __gmpfr_emin) { if (precx < GMP_NUMB_BITS && MPFR_PREC(z) == precx && MPFR_PREC(s) == precx) { mp_limb_t umant[2], zmant[2]; mpfr_t zz; int inex; umul_ppmm (umant[1], umant[0], MPFR_MANT(x)[0], MPFR_MANT(y)[0]); MPFR_PREC(u) = MPFR_PREC(zz) = 2 * precx; MPFR_MANT(u) = umant; MPFR_MANT(zz) = zmant; MPFR_SIGN(u) = MPFR_MULT_SIGN( MPFR_SIGN(x) , MPFR_SIGN(y) ); MPFR_SIGN(zz) = MPFR_SIGN(z); MPFR_EXP(zz) = MPFR_EXP(z); if (MPFR_PREC(zz) <= GMP_NUMB_BITS) /* zz fits in one limb */ { if ((umant[1] & MPFR_LIMB_HIGHBIT) == 0) { umant[0] = umant[1] << 1; MPFR_EXP(u) = e - 1; } else { umant[0] = umant[1]; MPFR_EXP(u) = e; } zmant[0] = MPFR_MANT(z)[0]; } else { zmant[1] = MPFR_MANT(z)[0]; zmant[0] = MPFR_LIMB_ZERO; if ((umant[1] & MPFR_LIMB_HIGHBIT) == 0) { umant[1] = (umant[1] << 1) | (umant[0] >> (GMP_NUMB_BITS - 1)); umant[0] = umant[0] << 1; MPFR_EXP(u) = e - 1; } else MPFR_EXP(u) = e; } inex = mpfr_add (u, u, zz, rnd_mode); /* mpfr_set_1_2 requires PREC(u) = 2*PREC(s), thus we need PREC(s) = PREC(x) = PREC(y) = PREC(z) */ return mpfr_set_1_2 (s, u, rnd_mode, inex); } else if ((n = MPFR_LIMB_SIZE(x)) <= 4 * MPFR_MUL_THRESHOLD) { mpfr_limb_ptr up; mp_size_t un = n + n; MPFR_TMP_DECL(marker); MPFR_TMP_MARK(marker); MPFR_TMP_INIT (up, u, un * GMP_NUMB_BITS, un); up = MPFR_MANT(u); /* multiply x*y exactly into u */ mpn_mul_n (up, MPFR_MANT(x), MPFR_MANT(y), n); if (MPFR_LIMB_MSB (up[un - 1]) == 0) { mpn_lshift (up, up, un, 1); MPFR_EXP(u) = e - 1; } else MPFR_EXP(u) = e; MPFR_SIGN(u) = MPFR_MULT_SIGN( MPFR_SIGN(x) , MPFR_SIGN(y) ); /* The above code does not generate any exception. The exceptions will come only from mpfr_add. */ inexact = mpfr_add (s, u, z, rnd_mode); MPFR_TMP_FREE(marker); return inexact; } } /* If we take prec(u) >= prec(x) + prec(y), the product u <- x*y is exact, except in case of overflow or underflow. */ MPFR_ASSERTN (precx + precy <= MPFR_PREC_MAX); MPFR_GROUP_INIT_1 (group, precx + precy, u); MPFR_SAVE_EXPO_MARK (expo); if (MPFR_UNLIKELY (mpfr_mul (u, x, y, MPFR_RNDN))) { /* overflow or underflow - this case is regarded as rare, thus does not need to be very efficient (even if some tests below could have been done earlier). It is an overflow iff u is an infinity (since MPFR_RNDN was used). Alternatively, we could test the overflow flag, but in this case, mpfr_clear_flags would have been necessary. */ if (MPFR_IS_INF (u)) /* overflow */ { int sign_u = MPFR_SIGN (u); MPFR_LOG_MSG (("Overflow on x*y\n", 0)); MPFR_GROUP_CLEAR (group); /* we no longer need u */ /* Let's eliminate the obvious case where x*y and z have the same sign. No possible cancellation -> real overflow. Also, we know that |z| < 2^emax. If E(x) + E(y) >= emax+3, then |x*y| >= 2^(emax+1), and |x*y + z| > 2^emax. This case is also an overflow. */ if (sign_u == MPFR_SIGN (z) || e >= __gmpfr_emax + 3) { MPFR_SAVE_EXPO_FREE (expo); return mpfr_overflow (s, rnd_mode, sign_u); } } else /* underflow: one has |x*y| < 2^(emin-1). */ { MPFR_LOG_MSG (("Underflow on x*y\n", 0)); /* Easy cases: when 2^(emin-1) <= 1/2 * min(ulp(z),ulp(s)), one can replace x*y by sign(x*y) * 2^(emin-1). Note that this is even true in case of equality for MPFR_RNDN thanks to the even-rounding rule. The + 1 on MPFR_PREC (s) is necessary because the exponent of the result can be EXP(z) - 1. */ if (MPFR_GET_EXP (z) - __gmpfr_emin >= MAX (MPFR_PREC (z), MPFR_PREC (s) + 1)) { MPFR_PREC (u) = MPFR_PREC_MIN; mpfr_setmin (u, __gmpfr_emin); MPFR_SET_SIGN (u, MPFR_MULT_SIGN (MPFR_SIGN (x), MPFR_SIGN (y))); mpfr_clear_flags (); goto add; } MPFR_GROUP_CLEAR (group); /* we no longer need u */ } /* Let's use UBF to resolve the overflow/underflow issues. */ { mpfr_ubf_t uu; mp_size_t un; mpfr_limb_ptr up; MPFR_TMP_DECL(marker); MPFR_LOG_MSG (("Use UBF\n", 0)); MPFR_TMP_MARK (marker); un = MPFR_LIMB_SIZE (x) + MPFR_LIMB_SIZE (y); MPFR_TMP_INIT (up, uu, (mpfr_prec_t) un * GMP_NUMB_BITS, un); mpfr_ubf_mul_exact (uu, x, y); mpfr_clear_flags (); inexact = mpfr_add (s, (mpfr_srcptr) uu, z, rnd_mode); MPFR_UBF_CLEAR_EXP (uu); MPFR_TMP_FREE (marker); } } else { add: inexact = mpfr_add (s, u, z, rnd_mode); MPFR_GROUP_CLEAR (group); } MPFR_SAVE_EXPO_UPDATE_FLAGS (expo, __gmpfr_flags); MPFR_SAVE_EXPO_FREE (expo); return mpfr_check_range (s, inexact, rnd_mode); }
utf-8
1
unknown
unknown
mysql-8.0-8.0.23/plugin/innodb_memcached/daemon_memcached/daemon/topkeys.h
#ifndef TOPKEYS_H #define TOPKEYS_H 1 #include <memcached/engine.h> #include <memcached/genhash.h> /* A list of operations for which we have int stats */ #define TK_OPS(C) C(get_hits) C(get_misses) C(cmd_set) C(incr_hits) \ C(incr_misses) C(decr_hits) C(decr_misses) \ C(delete_hits) C(delete_misses) C(evictions) \ C(cas_hits) C(cas_badval) C(cas_misses) #define TK_MAX_VAL_LEN 250 /* Update the correct stat for a given operation */ #define TK(tk, op, key, nkey, ctime) { \ if (tk) { \ assert(key); \ assert(nkey > 0); \ pthread_mutex_lock(&tk->mutex); \ topkey_item_t *tmp = topkeys_item_get_or_create( \ (tk), (key), (nkey), (ctime)); \ tmp->op++; \ pthread_mutex_unlock(&tk->mutex); \ } \ } typedef struct dlist { struct dlist *next; struct dlist *prev; } dlist_t; typedef struct topkey_item { dlist_t list; /* Must be at the beginning because we downcast! */ int nkey; rel_time_t ctime, atime; /* Time this item was created/last accessed */ #define TK_CUR(name) int name; TK_OPS(TK_CUR) #undef TK_CUR char key[]; /* A variable length array in the struct itself */ } topkey_item_t; typedef struct topkeys { dlist_t list; pthread_mutex_t mutex; genhash_t *hash; int nkeys; int max_keys; } topkeys_t; topkeys_t *topkeys_init(int max_keys); void topkeys_free(topkeys_t *topkeys); topkey_item_t *topkeys_item_get_or_create(topkeys_t *tk, const void *key, size_t nkey, const rel_time_t ctime); ENGINE_ERROR_CODE topkeys_stats(topkeys_t *tk, const void *cookie, const rel_time_t current_time, ADD_STAT add_stat); #endif
utf-8
1
unknown
unknown
gloox-1.0.24/src/message.cpp
/* Copyright (c) 2007-2019 by Jakob Schröter <js@camaya.net> This file is part of the gloox library. http://camaya.net/gloox This software is distributed under a license. The full license agreement can be found in the file LICENSE in this distribution. This software may not be copied, modified, sold or distributed other than expressed in the named license agreement. This software is distributed without any warranty. */ #include "util.h" #include "message.h" namespace gloox { static const char* msgTypeStringValues[] = { "chat", "error", "groupchat", "headline", "normal" }; static inline const std::string typeString( Message::MessageType type ) { return util::lookup2( type, msgTypeStringValues ); } Message::Message( Tag* tag ) : Stanza( tag ), m_subtype( Invalid ), m_bodies( 0 ), m_subjects( 0 ) { if( !tag || tag->name() != "message" ) return; const std::string& typestring = tag->findAttribute( TYPE ); if( typestring.empty() ) m_subtype = Normal; else m_subtype = static_cast<MessageType>( util::lookup2( typestring, msgTypeStringValues ) ); const TagList& c = tag->children(); TagList::const_iterator it = c.begin(); for( ; it != c.end(); ++it ) { if( (*it)->name() == "body" ) setLang( &m_bodies, m_body, (*it) ); else if( (*it)->name() == "subject" ) setLang( &m_subjects, m_subject, (*it) ); else if( (*it)->name() == "thread" ) m_thread = (*it)->cdata(); } } Message::Message( MessageType type, const JID& to, const std::string& body, const std::string& subject, const std::string& thread, const std::string& xmllang ) : Stanza( to ), m_subtype( type ), m_bodies( 0 ), m_subjects( 0 ), m_thread( thread ) { setLang( &m_bodies, m_body, body, xmllang ); setLang( &m_subjects, m_subject, subject, xmllang ); } Message::~Message() { delete m_bodies; delete m_subjects; } Tag* Message::tag() const { if( m_subtype == Invalid ) return 0; Tag* t = new Tag( "message" ); if( m_to ) t->addAttribute( "to", m_to.full() ); if( m_from ) t->addAttribute( "from", m_from.full() ); if( !m_id.empty() ) t->addAttribute( "id", m_id ); t->addAttribute( TYPE, typeString( m_subtype ) ); getLangs( m_bodies, m_body, "body", t ); getLangs( m_subjects, m_subject, "subject", t ); if( !m_thread.empty() ) new Tag( t, "thread", m_thread ); StanzaExtensionList::const_iterator it = m_extensionList.begin(); for( ; it != m_extensionList.end(); ++it ) t->addChild( (*it)->tag() ); return t; } }
utf-8
1
GPL-3.0+ with OpenSSL exception
2004-2015 Jakob Schröter <js@camaya.net>
vpb-driver-4.2.61/src/libvpb/alawmulaw.h
/*---------------------------------------------------------------------------*\ FILE....: COMP.H TYPE....: C Header File AUTHOR..: David Rowe DATE....: 16/10/97 Compression functions. Voicetronix Voice Processing Board (VPB) Software Copyright (C) 1999-2007 Voicetronix www.voicetronix.com.au 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., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA \*---------------------------------------------------------------------------*/ #ifndef _VT_ALAWMULAW_H #define _VT_ALAWMULAW_H /* Scale factors define the number of right shifts to convert a 16 bit word to a format suitable for input to the compression functions. For example, the maximum value for mu-law is 8192, therefore to convert a 16 word (max 32767) to a maximum of 8192 we shift two places to the right. */ #define MULAW_SCALE 2 /* scales linear to mulaw */ #define ALAW_SCALE 3 /* scales linear to alaw */ #define ADPCM_SCALE 4 /* scales linear to ADPCM */ #ifdef __cplusplus extern "C" { #endif void init_alaw_luts(void); void init_mulaw_luts(void); void mulaw_encode(char mulaw[], const short linear[], unsigned short sz); void mulaw_decode(short linear[], const unsigned char mulaw[], unsigned short sz); void alaw_encode(char alaw[], const short linear[], unsigned short sz); void alaw_decode(short linear[], const unsigned char alaw[], unsigned short sz); #ifdef __cplusplus } #endif void adpcmini_open(void **states); void adpcmini_close(void *states); void adpcmini_reset_states(void *states); void adpcm_encode(void *states, unsigned short codes[], short X[], unsigned short n); void adpcm_decode(void *states, short X_[], unsigned short codes[], unsigned short n); void adpcm_pack(unsigned short codes[], unsigned short packed[], unsigned short n); void adpcm_unpack(unsigned short codes[], unsigned short packed[], unsigned short n); #endif /* _VT_ALAWMULAW_H */
utf-8
1
unknown
unknown
libgdiplus-6.0.4+dfsg/src/brush.c
/* * brush.c * * Copyright (c) 2003 Alexandre Pigolkine * Copyright (C) 2007 Novell, Inc. http://www.novell.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. * * Authors: * Alexandre Pigolkine(pigolkine@gmx.de) * Ravindra (rkumar@novell.com) */ #include "brush-private.h" #include "graphics-private.h" void gdip_brush_init (GpBrush *brush, BrushClass* vtable) { brush->vtable = vtable; /* Set the changed state to true, so that we don't miss the * first setup of the brush. */ brush->changed = TRUE; } GpStatus gdip_brush_setup (GpGraphics *graphics, GpBrush *brush) { /* Don't need to setup, if brush is the same as the cached brush and * it is not changed. Just comparing pointers may not be sufficient * to say that the brushes are same. It is possible to have different * brush on the same memory, but probability is very low. We would * need a function to check the equality of the brushes in that case. */ if (brush == graphics->last_brush && !brush->changed) return Ok; else { GpStatus status = brush->vtable->setup (graphics, brush); if (status == Ok) { brush->changed = FALSE; graphics->last_brush = brush; } return status; } } /* coverity[+alloc : arg-*1] */ GpStatus WINGDIPAPI GdipCloneBrush (GpBrush *brush, GpBrush **clonedBrush) { if (!brush || !clonedBrush) return InvalidParameter; return brush->vtable->clone_brush (brush, clonedBrush); } GpStatus WINGDIPAPI GdipDeleteBrush (GpBrush *brush) { GpStatus status; if (!brush) return InvalidParameter; status = brush->vtable->destroy (brush); GdipFree (brush); return status; } GpStatus WINGDIPAPI GdipGetBrushType (GpBrush *brush, GpBrushType *type) { if (!brush || !type) return InvalidParameter; *type = brush->vtable->type; return Ok; }
utf-8
1
unknown
unknown
shibboleth-sp-3.3.0+dfsg1/plugins/plugins.cpp
/** * Licensed to the University Corporation for Advanced Internet * Development, Inc. (UCAID) under one or more contributor license * agreements. See the NOTICE file distributed with this work for * additional information regarding copyright ownership. * * UCAID licenses this file to you under the Apache License, * Version 2.0 (the "License"); you may not use this file except * in compliance with the License. You may obtain a copy of the * License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, * either express or implied. See the License for the specific * language governing permissions and limitations under the License. */ /** * plugins.cpp * * Extension plugins for Shibboleth SP. */ #include "internal.h" #include <shibsp/SPConfig.h> #include <shibsp/util/SPConstants.h> #include <xmltooling/impl/AnyElement.h> using namespace shibsp; using namespace xmltooling; using namespace xercesc; using namespace std; #ifdef WIN32 # define PLUGINS_EXPORTS __declspec(dllexport) #else # define PLUGINS_EXPORTS #endif namespace shibsp { PluginManager<AccessControl,string,const DOMElement*>::Factory TimeAccessControlFactory; PluginManager< Handler,string,pair<const DOMElement*,const char*> >::Factory AttributeResolverHandlerFactory; #ifndef SHIBSP_LITE # if HAVE_DECL_GSS_GET_NAME_ATTRIBUTE PluginManager<AttributeExtractor,string,const DOMElement*>::Factory GSSAPIExtractorFactory; # endif PluginManager<AttributeResolver,string,const DOMElement*>::Factory TemplateAttributeResolverFactory; PluginManager<AttributeResolver,string,const DOMElement*>::Factory TransformAttributeResolverFactory; PluginManager<AttributeResolver,string,const DOMElement*>::Factory UpperCaseAttributeResolverFactory; PluginManager<AttributeResolver,string,const DOMElement*>::Factory LowerCaseAttributeResolverFactory; #endif }; extern "C" int PLUGINS_EXPORTS xmltooling_extension_init(void*) { SPConfig& conf = SPConfig::getConfig(); conf.AccessControlManager.registerFactory("Time", TimeAccessControlFactory); conf.HandlerManager.registerFactory("AttributeResolver", AttributeResolverHandlerFactory); #ifndef SHIBSP_LITE # if HAVE_DECL_GSS_GET_NAME_ATTRIBUTE conf.AttributeExtractorManager.registerFactory("GSSAPI", GSSAPIExtractorFactory); static const XMLCh _GSSAPIName[] = UNICODE_LITERAL_10(G,S,S,A,P,I,N,a,m,e); static const XMLCh _GSSAPIContext[] = UNICODE_LITERAL_13(G,S,S,A,P,I,C,o,n,t,e,x,t); XMLObjectBuilder::registerBuilder(xmltooling::QName(shibspconstants::SHIB2ATTRIBUTEMAP_NS, _GSSAPIName), new AnyElementBuilder()); XMLObjectBuilder::registerBuilder(xmltooling::QName(shibspconstants::SHIB2ATTRIBUTEMAP_NS, _GSSAPIContext), new AnyElementBuilder()); # endif conf.AttributeResolverManager.registerFactory("Template", TemplateAttributeResolverFactory); conf.AttributeResolverManager.registerFactory("Transform", TransformAttributeResolverFactory); conf.AttributeResolverManager.registerFactory("UpperCase", UpperCaseAttributeResolverFactory); conf.AttributeResolverManager.registerFactory("LowerCase", LowerCaseAttributeResolverFactory); #endif return 0; // signal success } extern "C" void PLUGINS_EXPORTS xmltooling_extension_term() { // Factories normally get unregistered during library shutdown, so no work usually required here. }
utf-8
1
Apache-2.0
2001-2018 University Corporation for Advanced Internet Development, Inc. (UCAID)
gcc-arm-none-eabi-10.3-2021.07/libstdc++-v3/testsuite/25_algorithms/none_of/constrained.cc
// Copyright (C) 2020 Free Software Foundation, Inc. // // This file is part of the GNU ISO C++ Library. This library is free // software; you can redistribute it and/or modify it under the // terms of the GNU General Public License as published by the // Free Software Foundation; either version 3, or (at your option) // any later version. // This library is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // You should have received a copy of the GNU General Public License along // with this library; see the file COPYING3. If not see // <http://www.gnu.org/licenses/>. // { dg-options "-std=gnu++2a" } // { dg-do run { target c++2a } } #include <algorithm> #include <testsuite_hooks.h> #include <testsuite_iterators.h> using __gnu_test::test_container; using __gnu_test::test_range; using __gnu_test::input_iterator_wrapper; using __gnu_test::forward_iterator_wrapper; namespace ranges = std::ranges; struct X { int i; }; struct XLess { int val; bool operator()(X& x) const { return x.i < val; } }; struct ILess { int val; bool operator()(int& i) const { return i < val; } }; template<typename T> struct NotZero { bool operator()(T& t) const { return t != 0; } }; void test01() { X x[] = { {2}, {4}, {6}, {8}, {10}, {11} }; VERIFY( !ranges::none_of(x, x+6, XLess{3}) ); VERIFY( !ranges::none_of(x, x+6, ILess{3}, &X::i) ); VERIFY( ranges::none_of(x+1, x+6, XLess{3}) ); VERIFY( ranges::none_of(x+1, x+6, ILess{3}, &X::i) ); VERIFY( !ranges::none_of(x, XLess{5}) ); VERIFY( !ranges::none_of(x, ILess{5}, &X::i) ); test_container<X, forward_iterator_wrapper> c(x); VERIFY( !ranges::none_of(c, NotZero<int>{}, &X::i) ); test_range<X, input_iterator_wrapper> r(x); VERIFY( !ranges::none_of(r, NotZero<int>{}, &X::i) ); VERIFY( !ranges::none_of(r, NotZero<X* const>{}, [](X& x) { return &x; }) ); } struct Y { int i; int j; }; void test02() { static constexpr Y y[] = { {1,2}, {2,4}, {3,6} }; static_assert(!ranges::none_of(y, [](int i) { return i%2 == 0; }, &Y::i)); static_assert(!ranges::none_of(y, [](const Y& y) { return y.i + y.j == 3; })); static_assert(ranges::none_of(y, [](const Y& y) { return y.i == y.j; })); } int main() { test01(); test02(); }
utf-8
1
unknown
unknown
fwbuilder-5.3.7/src/libgui/RuleSetModel.h
/* Firewall Builder Copyright (C) 2009 NetCitadel, LLC Author: Illiya Yalovoy <yalovoy@gmail.com> $Id$ This program is free software which we release under the GNU General Public License. You may redistribute and/or modify this program under the terms of that 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. To get a copy of the GNU General Public License, write to the Free Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA */ #ifndef RULESETMODEL_H #define RULESETMODEL_H #include <QAbstractItemModel> #include <QVector> #include <QVariant> #include <QStringList> #include <QHash> #include "RuleNode.h" #include "ColDesc.h" namespace libfwbuilder { class Firewall; class RuleSet; class RuleElement; class Rule; class FWObject; } class RuleSetModel; //////////////////////////////////////////////////////////////////////// // RuleSetModelIterator //////////////////////////////////////////////////////////////////////// class RuleSetModelIterator { friend class RuleSetModel; public: RuleSetModelIterator(); bool isValid(); bool hasNext(); bool hasPrev(); RuleSetModelIterator& operator= (const RuleSetModelIterator&); RuleSetModelIterator& operator++ (); RuleSetModelIterator& operator-- (); bool operator== ( RuleSetModelIterator& ); bool operator!= ( RuleSetModelIterator& ); QModelIndex index(); private: QAbstractItemModel *model; int row; QModelIndex parent; }; //////////////////////////////////////////////////////////////////////// // ActionDesc //////////////////////////////////////////////////////////////////////// class ActionDesc { public: QString name; QString displayName; QString tooltip; QString argument; }; Q_DECLARE_METATYPE(ActionDesc) //////////////////////////////////////////////////////////////////////// // RuleSetModel //////////////////////////////////////////////////////////////////////// class RuleSetModel : public QAbstractItemModel { Q_OBJECT public: QList<ColDesc> header; RuleSetModel(libfwbuilder::RuleSet* ruleset, QObject *parent = 0); ~RuleSetModel() {delete root;} int rowCount(const QModelIndex &parent) const; int columnCount(const QModelIndex &parent) const; QVariant data(const QModelIndex &index, int role) const; QVariant headerData(int section, Qt::Orientation orientation, int role) const; QModelIndex index(int row, int column, const QModelIndex &parent) const; QModelIndex index(int row, int column, QString groupName) const; QModelIndex index(libfwbuilder::Rule *rule, int col=0) const; QModelIndex index(libfwbuilder::Rule *rule, libfwbuilder::RuleElement *re) const; QModelIndex index(QString groupName) const; QModelIndex indexForPosition(int position) const; QModelIndex parent(const QModelIndex &child) const; bool isEmpty(); bool isGroup(const QModelIndex &index) const; libfwbuilder::RuleSet* getRuleSet() {return ruleset;} libfwbuilder::Firewall* getFirewall() const; libfwbuilder::Rule* insertNewRule(); libfwbuilder::Rule* insertNewRule(QModelIndex &index, bool isAfter = false); libfwbuilder::Rule* insertRule(libfwbuilder::Rule *rule, QModelIndex &index, bool isAfter = false); void insertRule(libfwbuilder::Rule *rule); virtual void initRule(libfwbuilder::Rule *new_rule, libfwbuilder::Rule *old_rule = NULL) = 0; void removeRow(int row,const QModelIndex &parent); bool removeRows(int row, int count, const QModelIndex &parent); void renameGroup(QModelIndex group, const QString &newName); void removeFromGroup(QModelIndex group, int first, int last); QModelIndex createNewGroup(QString groupName, int first, int last); QString addToGroupAbove(int first, int last); QString addToGroupBelow(int first, int last); void moveRuleUp(const QModelIndex &group, int first, int last); void moveRuleDown(const QModelIndex &group, int first, int last); void changeRuleColor(const QList<QModelIndex> &indexes, const QString &c); void changeGroupColor(const QModelIndex index, const QString &c); bool isIndexRule(const QModelIndex index); RuleNode *nodeFromIndex(const QModelIndex &index) const; int getRulePosition(QModelIndex index); libfwbuilder::Rule * findRuleForPosition(int position) const; libfwbuilder::Rule * getRule(QModelIndex index) const; void setEnabled(const QModelIndex &index, bool flag); virtual bool checkRuleType(libfwbuilder::Rule *rule) = 0; void deleteObject(QModelIndex &index, libfwbuilder::FWObject* obj); bool insertObject(QModelIndex &index, libfwbuilder::FWObject *obj); int columnByType(ColDesc::ColumnType type); void rowChanged(const QModelIndex &index); void groupChanged(const QModelIndex &index); void getGroups(QList<QModelIndex> &list); RuleSetModelIterator begin(); RuleSetModelIterator end(); void resetAllSizes(); QString findUniqueNameForGroup(const QString &groupName); void restoreRules(QList<libfwbuilder::Rule*> rules, bool topLevel = true); void restoreRule(libfwbuilder::Rule* rule); void objectChanged(libfwbuilder::FWObject* object); protected: libfwbuilder::RuleElement *getRuleElementByRole(libfwbuilder::Rule* r, std::string roleName) const; void insertRuleToModel(libfwbuilder::Rule *rule, QModelIndex &index, bool isAfter = false); int columnForRuleElementType(QString) const; QString getPositionAsString(RuleNode *node) const; ActionDesc getRuleActionDesc(libfwbuilder::Rule* r) const; void copyRuleWithoutId(libfwbuilder::Rule* fromRule, libfwbuilder::Rule* toRule); private: libfwbuilder::RuleSet *ruleset; RuleNode *root; // QHash<int,libfwbuilder::Rule*> rulesByPosition; void initModel(); QVariant getDecoration(const QModelIndex &index) const; QVariant getDataForDisplayRole(const QModelIndex &index) const; QVariant getGroupDataForDisplayRole(const QModelIndex &index, RuleNode* node) const; virtual QVariant getRuleDataForDisplayRole(const QModelIndex &index, RuleNode* node) const = 0; QVariant getColumnDesc(const QModelIndex &index) const; void moveToGroup(RuleNode *targetGroup, int first, int last, bool append=true); void removeToList(QList<RuleNode*> &list, const QModelIndex &group, int first, int last); void insertFromList(const QList<RuleNode*> &list, const QModelIndex &parent, int position); QModelIndexList findObject (libfwbuilder::FWObject* object); }; //////////////////////////////////////////////////////////////////////// // PolicyModel //////////////////////////////////////////////////////////////////////// class PolicyModel : public RuleSetModel { public: PolicyModel(libfwbuilder::RuleSet* ruleset, QObject *parent = 0) : RuleSetModel(ruleset, parent) {configure();} void initRule(libfwbuilder::Rule *new_rule, libfwbuilder::Rule *old_rule = NULL); bool checkRuleType(libfwbuilder::Rule *rule); private: bool supports_time; bool supports_logging; bool supports_rule_options; QVariant getRuleDataForDisplayRole(const QModelIndex &index, RuleNode* node) const; QString getRuleDirection(libfwbuilder::Rule* r) const; QStringList getRuleOptions(libfwbuilder::Rule* r) const; void configure(); }; //////////////////////////////////////////////////////////////////////// // NatModel //////////////////////////////////////////////////////////////////////// class NatModel : public RuleSetModel { public: NatModel(libfwbuilder::RuleSet* ruleset, QObject *parent = 0) : RuleSetModel(ruleset, parent) {configure();} void initRule(libfwbuilder::Rule *new_rule, libfwbuilder::Rule *old_rule = NULL); bool checkRuleType(libfwbuilder::Rule *rule); private: bool supports_actions; bool supports_inbound_interface; bool supports_outbound_interface; QVariant getRuleDataForDisplayRole(const QModelIndex &index, RuleNode* node) const; QStringList getRuleOptions(libfwbuilder::Rule* r) const; void configure(); }; //////////////////////////////////////////////////////////////////////// // RoutingModel //////////////////////////////////////////////////////////////////////// class RoutingModel : public RuleSetModel { public: RoutingModel(libfwbuilder::RuleSet* ruleset, QObject *parent = 0) : RuleSetModel(ruleset, parent) {configure();} void initRule(libfwbuilder::Rule *new_rule, libfwbuilder::Rule *old_rule = NULL); bool checkRuleType(libfwbuilder::Rule *rule); private: bool supports_routing_itf; bool supports_metric; QVariant getRuleDataForDisplayRole(const QModelIndex &index, RuleNode* node) const; QStringList getRuleOptions(libfwbuilder::Rule* r) const; void configure(); }; #endif // RULESETMODEL_H
utf-8
1
unknown
unknown
llvm-toolchain-14-14.0.0~+rc1/llvm/lib/Target/ARM/ARMLoadStoreOptimizer.cpp
//===- ARMLoadStoreOptimizer.cpp - ARM load / store opt. pass -------------===// // // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. // See https://llvm.org/LICENSE.txt for license information. // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception // //===----------------------------------------------------------------------===// // /// \file This file contains a pass that performs load / store related peephole /// optimizations. This pass should be run after register allocation. // //===----------------------------------------------------------------------===// #include "ARM.h" #include "ARMBaseInstrInfo.h" #include "ARMBaseRegisterInfo.h" #include "ARMISelLowering.h" #include "ARMMachineFunctionInfo.h" #include "ARMSubtarget.h" #include "MCTargetDesc/ARMAddressingModes.h" #include "MCTargetDesc/ARMBaseInfo.h" #include "Utils/ARMBaseInfo.h" #include "llvm/ADT/ArrayRef.h" #include "llvm/ADT/DenseMap.h" #include "llvm/ADT/DenseSet.h" #include "llvm/ADT/STLExtras.h" #include "llvm/ADT/SmallPtrSet.h" #include "llvm/ADT/SmallSet.h" #include "llvm/ADT/SmallVector.h" #include "llvm/ADT/Statistic.h" #include "llvm/ADT/iterator_range.h" #include "llvm/Analysis/AliasAnalysis.h" #include "llvm/CodeGen/LivePhysRegs.h" #include "llvm/CodeGen/MachineBasicBlock.h" #include "llvm/CodeGen/MachineDominators.h" #include "llvm/CodeGen/MachineFunction.h" #include "llvm/CodeGen/MachineFunctionPass.h" #include "llvm/CodeGen/MachineInstr.h" #include "llvm/CodeGen/MachineInstrBuilder.h" #include "llvm/CodeGen/MachineMemOperand.h" #include "llvm/CodeGen/MachineOperand.h" #include "llvm/CodeGen/MachineRegisterInfo.h" #include "llvm/CodeGen/RegisterClassInfo.h" #include "llvm/CodeGen/TargetFrameLowering.h" #include "llvm/CodeGen/TargetInstrInfo.h" #include "llvm/CodeGen/TargetLowering.h" #include "llvm/CodeGen/TargetRegisterInfo.h" #include "llvm/CodeGen/TargetSubtargetInfo.h" #include "llvm/IR/DataLayout.h" #include "llvm/IR/DebugLoc.h" #include "llvm/IR/DerivedTypes.h" #include "llvm/IR/Function.h" #include "llvm/IR/Type.h" #include "llvm/InitializePasses.h" #include "llvm/MC/MCInstrDesc.h" #include "llvm/Pass.h" #include "llvm/Support/Allocator.h" #include "llvm/Support/CommandLine.h" #include "llvm/Support/Debug.h" #include "llvm/Support/ErrorHandling.h" #include "llvm/Support/raw_ostream.h" #include <algorithm> #include <cassert> #include <cstddef> #include <cstdlib> #include <iterator> #include <limits> #include <utility> using namespace llvm; #define DEBUG_TYPE "arm-ldst-opt" STATISTIC(NumLDMGened , "Number of ldm instructions generated"); STATISTIC(NumSTMGened , "Number of stm instructions generated"); STATISTIC(NumVLDMGened, "Number of vldm instructions generated"); STATISTIC(NumVSTMGened, "Number of vstm instructions generated"); STATISTIC(NumLdStMoved, "Number of load / store instructions moved"); STATISTIC(NumLDRDFormed,"Number of ldrd created before allocation"); STATISTIC(NumSTRDFormed,"Number of strd created before allocation"); STATISTIC(NumLDRD2LDM, "Number of ldrd instructions turned back into ldm"); STATISTIC(NumSTRD2STM, "Number of strd instructions turned back into stm"); STATISTIC(NumLDRD2LDR, "Number of ldrd instructions turned back into ldr's"); STATISTIC(NumSTRD2STR, "Number of strd instructions turned back into str's"); /// This switch disables formation of double/multi instructions that could /// potentially lead to (new) alignment traps even with CCR.UNALIGN_TRP /// disabled. This can be used to create libraries that are robust even when /// users provoke undefined behaviour by supplying misaligned pointers. /// \see mayCombineMisaligned() static cl::opt<bool> AssumeMisalignedLoadStores("arm-assume-misaligned-load-store", cl::Hidden, cl::init(false), cl::desc("Be more conservative in ARM load/store opt")); #define ARM_LOAD_STORE_OPT_NAME "ARM load / store optimization pass" namespace { /// Post- register allocation pass the combine load / store instructions to /// form ldm / stm instructions. struct ARMLoadStoreOpt : public MachineFunctionPass { static char ID; const MachineFunction *MF; const TargetInstrInfo *TII; const TargetRegisterInfo *TRI; const ARMSubtarget *STI; const TargetLowering *TL; ARMFunctionInfo *AFI; LivePhysRegs LiveRegs; RegisterClassInfo RegClassInfo; MachineBasicBlock::const_iterator LiveRegPos; bool LiveRegsValid; bool RegClassInfoValid; bool isThumb1, isThumb2; ARMLoadStoreOpt() : MachineFunctionPass(ID) {} bool runOnMachineFunction(MachineFunction &Fn) override; MachineFunctionProperties getRequiredProperties() const override { return MachineFunctionProperties().set( MachineFunctionProperties::Property::NoVRegs); } StringRef getPassName() const override { return ARM_LOAD_STORE_OPT_NAME; } private: /// A set of load/store MachineInstrs with same base register sorted by /// offset. struct MemOpQueueEntry { MachineInstr *MI; int Offset; ///< Load/Store offset. unsigned Position; ///< Position as counted from end of basic block. MemOpQueueEntry(MachineInstr &MI, int Offset, unsigned Position) : MI(&MI), Offset(Offset), Position(Position) {} }; using MemOpQueue = SmallVector<MemOpQueueEntry, 8>; /// A set of MachineInstrs that fulfill (nearly all) conditions to get /// merged into a LDM/STM. struct MergeCandidate { /// List of instructions ordered by load/store offset. SmallVector<MachineInstr*, 4> Instrs; /// Index in Instrs of the instruction being latest in the schedule. unsigned LatestMIIdx; /// Index in Instrs of the instruction being earliest in the schedule. unsigned EarliestMIIdx; /// Index into the basic block where the merged instruction will be /// inserted. (See MemOpQueueEntry.Position) unsigned InsertPos; /// Whether the instructions can be merged into a ldm/stm instruction. bool CanMergeToLSMulti; /// Whether the instructions can be merged into a ldrd/strd instruction. bool CanMergeToLSDouble; }; SpecificBumpPtrAllocator<MergeCandidate> Allocator; SmallVector<const MergeCandidate*,4> Candidates; SmallVector<MachineInstr*,4> MergeBaseCandidates; void moveLiveRegsBefore(const MachineBasicBlock &MBB, MachineBasicBlock::const_iterator Before); unsigned findFreeReg(const TargetRegisterClass &RegClass); void UpdateBaseRegUses(MachineBasicBlock &MBB, MachineBasicBlock::iterator MBBI, const DebugLoc &DL, unsigned Base, unsigned WordOffset, ARMCC::CondCodes Pred, unsigned PredReg); MachineInstr *CreateLoadStoreMulti( MachineBasicBlock &MBB, MachineBasicBlock::iterator InsertBefore, int Offset, unsigned Base, bool BaseKill, unsigned Opcode, ARMCC::CondCodes Pred, unsigned PredReg, const DebugLoc &DL, ArrayRef<std::pair<unsigned, bool>> Regs, ArrayRef<MachineInstr*> Instrs); MachineInstr *CreateLoadStoreDouble( MachineBasicBlock &MBB, MachineBasicBlock::iterator InsertBefore, int Offset, unsigned Base, bool BaseKill, unsigned Opcode, ARMCC::CondCodes Pred, unsigned PredReg, const DebugLoc &DL, ArrayRef<std::pair<unsigned, bool>> Regs, ArrayRef<MachineInstr*> Instrs) const; void FormCandidates(const MemOpQueue &MemOps); MachineInstr *MergeOpsUpdate(const MergeCandidate &Cand); bool FixInvalidRegPairOp(MachineBasicBlock &MBB, MachineBasicBlock::iterator &MBBI); bool MergeBaseUpdateLoadStore(MachineInstr *MI); bool MergeBaseUpdateLSMultiple(MachineInstr *MI); bool MergeBaseUpdateLSDouble(MachineInstr &MI) const; bool LoadStoreMultipleOpti(MachineBasicBlock &MBB); bool MergeReturnIntoLDM(MachineBasicBlock &MBB); bool CombineMovBx(MachineBasicBlock &MBB); }; } // end anonymous namespace char ARMLoadStoreOpt::ID = 0; INITIALIZE_PASS(ARMLoadStoreOpt, "arm-ldst-opt", ARM_LOAD_STORE_OPT_NAME, false, false) static bool definesCPSR(const MachineInstr &MI) { for (const auto &MO : MI.operands()) { if (!MO.isReg()) continue; if (MO.isDef() && MO.getReg() == ARM::CPSR && !MO.isDead()) // If the instruction has live CPSR def, then it's not safe to fold it // into load / store. return true; } return false; } static int getMemoryOpOffset(const MachineInstr &MI) { unsigned Opcode = MI.getOpcode(); bool isAM3 = Opcode == ARM::LDRD || Opcode == ARM::STRD; unsigned NumOperands = MI.getDesc().getNumOperands(); unsigned OffField = MI.getOperand(NumOperands - 3).getImm(); if (Opcode == ARM::t2LDRi12 || Opcode == ARM::t2LDRi8 || Opcode == ARM::t2STRi12 || Opcode == ARM::t2STRi8 || Opcode == ARM::t2LDRDi8 || Opcode == ARM::t2STRDi8 || Opcode == ARM::LDRi12 || Opcode == ARM::STRi12) return OffField; // Thumb1 immediate offsets are scaled by 4 if (Opcode == ARM::tLDRi || Opcode == ARM::tSTRi || Opcode == ARM::tLDRspi || Opcode == ARM::tSTRspi) return OffField * 4; int Offset = isAM3 ? ARM_AM::getAM3Offset(OffField) : ARM_AM::getAM5Offset(OffField) * 4; ARM_AM::AddrOpc Op = isAM3 ? ARM_AM::getAM3Op(OffField) : ARM_AM::getAM5Op(OffField); if (Op == ARM_AM::sub) return -Offset; return Offset; } static const MachineOperand &getLoadStoreBaseOp(const MachineInstr &MI) { return MI.getOperand(1); } static const MachineOperand &getLoadStoreRegOp(const MachineInstr &MI) { return MI.getOperand(0); } static int getLoadStoreMultipleOpcode(unsigned Opcode, ARM_AM::AMSubMode Mode) { switch (Opcode) { default: llvm_unreachable("Unhandled opcode!"); case ARM::LDRi12: ++NumLDMGened; switch (Mode) { default: llvm_unreachable("Unhandled submode!"); case ARM_AM::ia: return ARM::LDMIA; case ARM_AM::da: return ARM::LDMDA; case ARM_AM::db: return ARM::LDMDB; case ARM_AM::ib: return ARM::LDMIB; } case ARM::STRi12: ++NumSTMGened; switch (Mode) { default: llvm_unreachable("Unhandled submode!"); case ARM_AM::ia: return ARM::STMIA; case ARM_AM::da: return ARM::STMDA; case ARM_AM::db: return ARM::STMDB; case ARM_AM::ib: return ARM::STMIB; } case ARM::tLDRi: case ARM::tLDRspi: // tLDMIA is writeback-only - unless the base register is in the input // reglist. ++NumLDMGened; switch (Mode) { default: llvm_unreachable("Unhandled submode!"); case ARM_AM::ia: return ARM::tLDMIA; } case ARM::tSTRi: case ARM::tSTRspi: // There is no non-writeback tSTMIA either. ++NumSTMGened; switch (Mode) { default: llvm_unreachable("Unhandled submode!"); case ARM_AM::ia: return ARM::tSTMIA_UPD; } case ARM::t2LDRi8: case ARM::t2LDRi12: ++NumLDMGened; switch (Mode) { default: llvm_unreachable("Unhandled submode!"); case ARM_AM::ia: return ARM::t2LDMIA; case ARM_AM::db: return ARM::t2LDMDB; } case ARM::t2STRi8: case ARM::t2STRi12: ++NumSTMGened; switch (Mode) { default: llvm_unreachable("Unhandled submode!"); case ARM_AM::ia: return ARM::t2STMIA; case ARM_AM::db: return ARM::t2STMDB; } case ARM::VLDRS: ++NumVLDMGened; switch (Mode) { default: llvm_unreachable("Unhandled submode!"); case ARM_AM::ia: return ARM::VLDMSIA; case ARM_AM::db: return 0; // Only VLDMSDB_UPD exists. } case ARM::VSTRS: ++NumVSTMGened; switch (Mode) { default: llvm_unreachable("Unhandled submode!"); case ARM_AM::ia: return ARM::VSTMSIA; case ARM_AM::db: return 0; // Only VSTMSDB_UPD exists. } case ARM::VLDRD: ++NumVLDMGened; switch (Mode) { default: llvm_unreachable("Unhandled submode!"); case ARM_AM::ia: return ARM::VLDMDIA; case ARM_AM::db: return 0; // Only VLDMDDB_UPD exists. } case ARM::VSTRD: ++NumVSTMGened; switch (Mode) { default: llvm_unreachable("Unhandled submode!"); case ARM_AM::ia: return ARM::VSTMDIA; case ARM_AM::db: return 0; // Only VSTMDDB_UPD exists. } } } static ARM_AM::AMSubMode getLoadStoreMultipleSubMode(unsigned Opcode) { switch (Opcode) { default: llvm_unreachable("Unhandled opcode!"); case ARM::LDMIA_RET: case ARM::LDMIA: case ARM::LDMIA_UPD: case ARM::STMIA: case ARM::STMIA_UPD: case ARM::tLDMIA: case ARM::tLDMIA_UPD: case ARM::tSTMIA_UPD: case ARM::t2LDMIA_RET: case ARM::t2LDMIA: case ARM::t2LDMIA_UPD: case ARM::t2STMIA: case ARM::t2STMIA_UPD: case ARM::VLDMSIA: case ARM::VLDMSIA_UPD: case ARM::VSTMSIA: case ARM::VSTMSIA_UPD: case ARM::VLDMDIA: case ARM::VLDMDIA_UPD: case ARM::VSTMDIA: case ARM::VSTMDIA_UPD: return ARM_AM::ia; case ARM::LDMDA: case ARM::LDMDA_UPD: case ARM::STMDA: case ARM::STMDA_UPD: return ARM_AM::da; case ARM::LDMDB: case ARM::LDMDB_UPD: case ARM::STMDB: case ARM::STMDB_UPD: case ARM::t2LDMDB: case ARM::t2LDMDB_UPD: case ARM::t2STMDB: case ARM::t2STMDB_UPD: case ARM::VLDMSDB_UPD: case ARM::VSTMSDB_UPD: case ARM::VLDMDDB_UPD: case ARM::VSTMDDB_UPD: return ARM_AM::db; case ARM::LDMIB: case ARM::LDMIB_UPD: case ARM::STMIB: case ARM::STMIB_UPD: return ARM_AM::ib; } } static bool isT1i32Load(unsigned Opc) { return Opc == ARM::tLDRi || Opc == ARM::tLDRspi; } static bool isT2i32Load(unsigned Opc) { return Opc == ARM::t2LDRi12 || Opc == ARM::t2LDRi8; } static bool isi32Load(unsigned Opc) { return Opc == ARM::LDRi12 || isT1i32Load(Opc) || isT2i32Load(Opc) ; } static bool isT1i32Store(unsigned Opc) { return Opc == ARM::tSTRi || Opc == ARM::tSTRspi; } static bool isT2i32Store(unsigned Opc) { return Opc == ARM::t2STRi12 || Opc == ARM::t2STRi8; } static bool isi32Store(unsigned Opc) { return Opc == ARM::STRi12 || isT1i32Store(Opc) || isT2i32Store(Opc); } static bool isLoadSingle(unsigned Opc) { return isi32Load(Opc) || Opc == ARM::VLDRS || Opc == ARM::VLDRD; } static unsigned getImmScale(unsigned Opc) { switch (Opc) { default: llvm_unreachable("Unhandled opcode!"); case ARM::tLDRi: case ARM::tSTRi: case ARM::tLDRspi: case ARM::tSTRspi: return 1; case ARM::tLDRHi: case ARM::tSTRHi: return 2; case ARM::tLDRBi: case ARM::tSTRBi: return 4; } } static unsigned getLSMultipleTransferSize(const MachineInstr *MI) { switch (MI->getOpcode()) { default: return 0; case ARM::LDRi12: case ARM::STRi12: case ARM::tLDRi: case ARM::tSTRi: case ARM::tLDRspi: case ARM::tSTRspi: case ARM::t2LDRi8: case ARM::t2LDRi12: case ARM::t2STRi8: case ARM::t2STRi12: case ARM::VLDRS: case ARM::VSTRS: return 4; case ARM::VLDRD: case ARM::VSTRD: return 8; case ARM::LDMIA: case ARM::LDMDA: case ARM::LDMDB: case ARM::LDMIB: case ARM::STMIA: case ARM::STMDA: case ARM::STMDB: case ARM::STMIB: case ARM::tLDMIA: case ARM::tLDMIA_UPD: case ARM::tSTMIA_UPD: case ARM::t2LDMIA: case ARM::t2LDMDB: case ARM::t2STMIA: case ARM::t2STMDB: case ARM::VLDMSIA: case ARM::VSTMSIA: return (MI->getNumOperands() - MI->getDesc().getNumOperands() + 1) * 4; case ARM::VLDMDIA: case ARM::VSTMDIA: return (MI->getNumOperands() - MI->getDesc().getNumOperands() + 1) * 8; } } /// Update future uses of the base register with the offset introduced /// due to writeback. This function only works on Thumb1. void ARMLoadStoreOpt::UpdateBaseRegUses(MachineBasicBlock &MBB, MachineBasicBlock::iterator MBBI, const DebugLoc &DL, unsigned Base, unsigned WordOffset, ARMCC::CondCodes Pred, unsigned PredReg) { assert(isThumb1 && "Can only update base register uses for Thumb1!"); // Start updating any instructions with immediate offsets. Insert a SUB before // the first non-updateable instruction (if any). for (; MBBI != MBB.end(); ++MBBI) { bool InsertSub = false; unsigned Opc = MBBI->getOpcode(); if (MBBI->readsRegister(Base)) { int Offset; bool IsLoad = Opc == ARM::tLDRi || Opc == ARM::tLDRHi || Opc == ARM::tLDRBi; bool IsStore = Opc == ARM::tSTRi || Opc == ARM::tSTRHi || Opc == ARM::tSTRBi; if (IsLoad || IsStore) { // Loads and stores with immediate offsets can be updated, but only if // the new offset isn't negative. // The MachineOperand containing the offset immediate is the last one // before predicates. MachineOperand &MO = MBBI->getOperand(MBBI->getDesc().getNumOperands() - 3); // The offsets are scaled by 1, 2 or 4 depending on the Opcode. Offset = MO.getImm() - WordOffset * getImmScale(Opc); // If storing the base register, it needs to be reset first. Register InstrSrcReg = getLoadStoreRegOp(*MBBI).getReg(); if (Offset >= 0 && !(IsStore && InstrSrcReg == Base)) MO.setImm(Offset); else InsertSub = true; } else if ((Opc == ARM::tSUBi8 || Opc == ARM::tADDi8) && !definesCPSR(*MBBI)) { // SUBS/ADDS using this register, with a dead def of the CPSR. // Merge it with the update; if the merged offset is too large, // insert a new sub instead. MachineOperand &MO = MBBI->getOperand(MBBI->getDesc().getNumOperands() - 3); Offset = (Opc == ARM::tSUBi8) ? MO.getImm() + WordOffset * 4 : MO.getImm() - WordOffset * 4 ; if (Offset >= 0 && TL->isLegalAddImmediate(Offset)) { // FIXME: Swap ADDS<->SUBS if Offset < 0, erase instruction if // Offset == 0. MO.setImm(Offset); // The base register has now been reset, so exit early. return; } else { InsertSub = true; } } else { // Can't update the instruction. InsertSub = true; } } else if (definesCPSR(*MBBI) || MBBI->isCall() || MBBI->isBranch()) { // Since SUBS sets the condition flags, we can't place the base reset // after an instruction that has a live CPSR def. // The base register might also contain an argument for a function call. InsertSub = true; } if (InsertSub) { // An instruction above couldn't be updated, so insert a sub. BuildMI(MBB, MBBI, DL, TII->get(ARM::tSUBi8), Base) .add(t1CondCodeOp(true)) .addReg(Base) .addImm(WordOffset * 4) .addImm(Pred) .addReg(PredReg); return; } if (MBBI->killsRegister(Base) || MBBI->definesRegister(Base)) // Register got killed. Stop updating. return; } // End of block was reached. if (!MBB.succ_empty()) { // FIXME: Because of a bug, live registers are sometimes missing from // the successor blocks' live-in sets. This means we can't trust that // information and *always* have to reset at the end of a block. // See PR21029. if (MBBI != MBB.end()) --MBBI; BuildMI(MBB, MBBI, DL, TII->get(ARM::tSUBi8), Base) .add(t1CondCodeOp(true)) .addReg(Base) .addImm(WordOffset * 4) .addImm(Pred) .addReg(PredReg); } } /// Return the first register of class \p RegClass that is not in \p Regs. unsigned ARMLoadStoreOpt::findFreeReg(const TargetRegisterClass &RegClass) { if (!RegClassInfoValid) { RegClassInfo.runOnMachineFunction(*MF); RegClassInfoValid = true; } for (unsigned Reg : RegClassInfo.getOrder(&RegClass)) if (LiveRegs.available(MF->getRegInfo(), Reg)) return Reg; return 0; } /// Compute live registers just before instruction \p Before (in normal schedule /// direction). Computes backwards so multiple queries in the same block must /// come in reverse order. void ARMLoadStoreOpt::moveLiveRegsBefore(const MachineBasicBlock &MBB, MachineBasicBlock::const_iterator Before) { // Initialize if we never queried in this block. if (!LiveRegsValid) { LiveRegs.init(*TRI); LiveRegs.addLiveOuts(MBB); LiveRegPos = MBB.end(); LiveRegsValid = true; } // Move backward just before the "Before" position. while (LiveRegPos != Before) { --LiveRegPos; LiveRegs.stepBackward(*LiveRegPos); } } static bool ContainsReg(const ArrayRef<std::pair<unsigned, bool>> &Regs, unsigned Reg) { for (const std::pair<unsigned, bool> &R : Regs) if (R.first == Reg) return true; return false; } /// Create and insert a LDM or STM with Base as base register and registers in /// Regs as the register operands that would be loaded / stored. It returns /// true if the transformation is done. MachineInstr *ARMLoadStoreOpt::CreateLoadStoreMulti( MachineBasicBlock &MBB, MachineBasicBlock::iterator InsertBefore, int Offset, unsigned Base, bool BaseKill, unsigned Opcode, ARMCC::CondCodes Pred, unsigned PredReg, const DebugLoc &DL, ArrayRef<std::pair<unsigned, bool>> Regs, ArrayRef<MachineInstr*> Instrs) { unsigned NumRegs = Regs.size(); assert(NumRegs > 1); // For Thumb1 targets, it might be necessary to clobber the CPSR to merge. // Compute liveness information for that register to make the decision. bool SafeToClobberCPSR = !isThumb1 || (MBB.computeRegisterLiveness(TRI, ARM::CPSR, InsertBefore, 20) == MachineBasicBlock::LQR_Dead); bool Writeback = isThumb1; // Thumb1 LDM/STM have base reg writeback. // Exception: If the base register is in the input reglist, Thumb1 LDM is // non-writeback. // It's also not possible to merge an STR of the base register in Thumb1. if (isThumb1 && ContainsReg(Regs, Base)) { assert(Base != ARM::SP && "Thumb1 does not allow SP in register list"); if (Opcode == ARM::tLDRi) Writeback = false; else if (Opcode == ARM::tSTRi) return nullptr; } ARM_AM::AMSubMode Mode = ARM_AM::ia; // VFP and Thumb2 do not support IB or DA modes. Thumb1 only supports IA. bool isNotVFP = isi32Load(Opcode) || isi32Store(Opcode); bool haveIBAndDA = isNotVFP && !isThumb2 && !isThumb1; if (Offset == 4 && haveIBAndDA) { Mode = ARM_AM::ib; } else if (Offset == -4 * (int)NumRegs + 4 && haveIBAndDA) { Mode = ARM_AM::da; } else if (Offset == -4 * (int)NumRegs && isNotVFP && !isThumb1) { // VLDM/VSTM do not support DB mode without also updating the base reg. Mode = ARM_AM::db; } else if (Offset != 0 || Opcode == ARM::tLDRspi || Opcode == ARM::tSTRspi) { // Check if this is a supported opcode before inserting instructions to // calculate a new base register. if (!getLoadStoreMultipleOpcode(Opcode, Mode)) return nullptr; // If starting offset isn't zero, insert a MI to materialize a new base. // But only do so if it is cost effective, i.e. merging more than two // loads / stores. if (NumRegs <= 2) return nullptr; // On Thumb1, it's not worth materializing a new base register without // clobbering the CPSR (i.e. not using ADDS/SUBS). if (!SafeToClobberCPSR) return nullptr; unsigned NewBase; if (isi32Load(Opcode)) { // If it is a load, then just use one of the destination registers // as the new base. Will no longer be writeback in Thumb1. NewBase = Regs[NumRegs-1].first; Writeback = false; } else { // Find a free register that we can use as scratch register. moveLiveRegsBefore(MBB, InsertBefore); // The merged instruction does not exist yet but will use several Regs if // it is a Store. if (!isLoadSingle(Opcode)) for (const std::pair<unsigned, bool> &R : Regs) LiveRegs.addReg(R.first); NewBase = findFreeReg(isThumb1 ? ARM::tGPRRegClass : ARM::GPRRegClass); if (NewBase == 0) return nullptr; } int BaseOpc = isThumb2 ? (BaseKill && Base == ARM::SP ? ARM::t2ADDspImm : ARM::t2ADDri) : (isThumb1 && Base == ARM::SP) ? ARM::tADDrSPi : (isThumb1 && Offset < 8) ? ARM::tADDi3 : isThumb1 ? ARM::tADDi8 : ARM::ADDri; if (Offset < 0) { // FIXME: There are no Thumb1 load/store instructions with negative // offsets. So the Base != ARM::SP might be unnecessary. Offset = -Offset; BaseOpc = isThumb2 ? (BaseKill && Base == ARM::SP ? ARM::t2SUBspImm : ARM::t2SUBri) : (isThumb1 && Offset < 8 && Base != ARM::SP) ? ARM::tSUBi3 : isThumb1 ? ARM::tSUBi8 : ARM::SUBri; } if (!TL->isLegalAddImmediate(Offset)) // FIXME: Try add with register operand? return nullptr; // Probably not worth it then. // We can only append a kill flag to the add/sub input if the value is not // used in the register list of the stm as well. bool KillOldBase = BaseKill && (!isi32Store(Opcode) || !ContainsReg(Regs, Base)); if (isThumb1) { // Thumb1: depending on immediate size, use either // ADDS NewBase, Base, #imm3 // or // MOV NewBase, Base // ADDS NewBase, #imm8. if (Base != NewBase && (BaseOpc == ARM::tADDi8 || BaseOpc == ARM::tSUBi8)) { // Need to insert a MOV to the new base first. if (isARMLowRegister(NewBase) && isARMLowRegister(Base) && !STI->hasV6Ops()) { // thumbv4t doesn't have lo->lo copies, and we can't predicate tMOVSr if (Pred != ARMCC::AL) return nullptr; BuildMI(MBB, InsertBefore, DL, TII->get(ARM::tMOVSr), NewBase) .addReg(Base, getKillRegState(KillOldBase)); } else BuildMI(MBB, InsertBefore, DL, TII->get(ARM::tMOVr), NewBase) .addReg(Base, getKillRegState(KillOldBase)) .add(predOps(Pred, PredReg)); // The following ADDS/SUBS becomes an update. Base = NewBase; KillOldBase = true; } if (BaseOpc == ARM::tADDrSPi) { assert(Offset % 4 == 0 && "tADDrSPi offset is scaled by 4"); BuildMI(MBB, InsertBefore, DL, TII->get(BaseOpc), NewBase) .addReg(Base, getKillRegState(KillOldBase)) .addImm(Offset / 4) .add(predOps(Pred, PredReg)); } else BuildMI(MBB, InsertBefore, DL, TII->get(BaseOpc), NewBase) .add(t1CondCodeOp(true)) .addReg(Base, getKillRegState(KillOldBase)) .addImm(Offset) .add(predOps(Pred, PredReg)); } else { BuildMI(MBB, InsertBefore, DL, TII->get(BaseOpc), NewBase) .addReg(Base, getKillRegState(KillOldBase)) .addImm(Offset) .add(predOps(Pred, PredReg)) .add(condCodeOp()); } Base = NewBase; BaseKill = true; // New base is always killed straight away. } bool isDef = isLoadSingle(Opcode); // Get LS multiple opcode. Note that for Thumb1 this might be an opcode with // base register writeback. Opcode = getLoadStoreMultipleOpcode(Opcode, Mode); if (!Opcode) return nullptr; // Check if a Thumb1 LDM/STM merge is safe. This is the case if: // - There is no writeback (LDM of base register), // - the base register is killed by the merged instruction, // - or it's safe to overwrite the condition flags, i.e. to insert a SUBS // to reset the base register. // Otherwise, don't merge. // It's safe to return here since the code to materialize a new base register // above is also conditional on SafeToClobberCPSR. if (isThumb1 && !SafeToClobberCPSR && Writeback && !BaseKill) return nullptr; MachineInstrBuilder MIB; if (Writeback) { assert(isThumb1 && "expected Writeback only inThumb1"); if (Opcode == ARM::tLDMIA) { assert(!(ContainsReg(Regs, Base)) && "Thumb1 can't LDM ! with Base in Regs"); // Update tLDMIA with writeback if necessary. Opcode = ARM::tLDMIA_UPD; } MIB = BuildMI(MBB, InsertBefore, DL, TII->get(Opcode)); // Thumb1: we might need to set base writeback when building the MI. MIB.addReg(Base, getDefRegState(true)) .addReg(Base, getKillRegState(BaseKill)); // The base isn't dead after a merged instruction with writeback. // Insert a sub instruction after the newly formed instruction to reset. if (!BaseKill) UpdateBaseRegUses(MBB, InsertBefore, DL, Base, NumRegs, Pred, PredReg); } else { // No writeback, simply build the MachineInstr. MIB = BuildMI(MBB, InsertBefore, DL, TII->get(Opcode)); MIB.addReg(Base, getKillRegState(BaseKill)); } MIB.addImm(Pred).addReg(PredReg); for (const std::pair<unsigned, bool> &R : Regs) MIB.addReg(R.first, getDefRegState(isDef) | getKillRegState(R.second)); MIB.cloneMergedMemRefs(Instrs); return MIB.getInstr(); } MachineInstr *ARMLoadStoreOpt::CreateLoadStoreDouble( MachineBasicBlock &MBB, MachineBasicBlock::iterator InsertBefore, int Offset, unsigned Base, bool BaseKill, unsigned Opcode, ARMCC::CondCodes Pred, unsigned PredReg, const DebugLoc &DL, ArrayRef<std::pair<unsigned, bool>> Regs, ArrayRef<MachineInstr*> Instrs) const { bool IsLoad = isi32Load(Opcode); assert((IsLoad || isi32Store(Opcode)) && "Must have integer load or store"); unsigned LoadStoreOpcode = IsLoad ? ARM::t2LDRDi8 : ARM::t2STRDi8; assert(Regs.size() == 2); MachineInstrBuilder MIB = BuildMI(MBB, InsertBefore, DL, TII->get(LoadStoreOpcode)); if (IsLoad) { MIB.addReg(Regs[0].first, RegState::Define) .addReg(Regs[1].first, RegState::Define); } else { MIB.addReg(Regs[0].first, getKillRegState(Regs[0].second)) .addReg(Regs[1].first, getKillRegState(Regs[1].second)); } MIB.addReg(Base).addImm(Offset).addImm(Pred).addReg(PredReg); MIB.cloneMergedMemRefs(Instrs); return MIB.getInstr(); } /// Call MergeOps and update MemOps and merges accordingly on success. MachineInstr *ARMLoadStoreOpt::MergeOpsUpdate(const MergeCandidate &Cand) { const MachineInstr *First = Cand.Instrs.front(); unsigned Opcode = First->getOpcode(); bool IsLoad = isLoadSingle(Opcode); SmallVector<std::pair<unsigned, bool>, 8> Regs; SmallVector<unsigned, 4> ImpDefs; DenseSet<unsigned> KilledRegs; DenseSet<unsigned> UsedRegs; // Determine list of registers and list of implicit super-register defs. for (const MachineInstr *MI : Cand.Instrs) { const MachineOperand &MO = getLoadStoreRegOp(*MI); Register Reg = MO.getReg(); bool IsKill = MO.isKill(); if (IsKill) KilledRegs.insert(Reg); Regs.push_back(std::make_pair(Reg, IsKill)); UsedRegs.insert(Reg); if (IsLoad) { // Collect any implicit defs of super-registers, after merging we can't // be sure anymore that we properly preserved these live ranges and must // removed these implicit operands. for (const MachineOperand &MO : MI->implicit_operands()) { if (!MO.isReg() || !MO.isDef() || MO.isDead()) continue; assert(MO.isImplicit()); Register DefReg = MO.getReg(); if (is_contained(ImpDefs, DefReg)) continue; // We can ignore cases where the super-reg is read and written. if (MI->readsRegister(DefReg)) continue; ImpDefs.push_back(DefReg); } } } // Attempt the merge. using iterator = MachineBasicBlock::iterator; MachineInstr *LatestMI = Cand.Instrs[Cand.LatestMIIdx]; iterator InsertBefore = std::next(iterator(LatestMI)); MachineBasicBlock &MBB = *LatestMI->getParent(); unsigned Offset = getMemoryOpOffset(*First); Register Base = getLoadStoreBaseOp(*First).getReg(); bool BaseKill = LatestMI->killsRegister(Base); Register PredReg; ARMCC::CondCodes Pred = getInstrPredicate(*First, PredReg); DebugLoc DL = First->getDebugLoc(); MachineInstr *Merged = nullptr; if (Cand.CanMergeToLSDouble) Merged = CreateLoadStoreDouble(MBB, InsertBefore, Offset, Base, BaseKill, Opcode, Pred, PredReg, DL, Regs, Cand.Instrs); if (!Merged && Cand.CanMergeToLSMulti) Merged = CreateLoadStoreMulti(MBB, InsertBefore, Offset, Base, BaseKill, Opcode, Pred, PredReg, DL, Regs, Cand.Instrs); if (!Merged) return nullptr; // Determine earliest instruction that will get removed. We then keep an // iterator just above it so the following erases don't invalidated it. iterator EarliestI(Cand.Instrs[Cand.EarliestMIIdx]); bool EarliestAtBegin = false; if (EarliestI == MBB.begin()) { EarliestAtBegin = true; } else { EarliestI = std::prev(EarliestI); } // Remove instructions which have been merged. for (MachineInstr *MI : Cand.Instrs) MBB.erase(MI); // Determine range between the earliest removed instruction and the new one. if (EarliestAtBegin) EarliestI = MBB.begin(); else EarliestI = std::next(EarliestI); auto FixupRange = make_range(EarliestI, iterator(Merged)); if (isLoadSingle(Opcode)) { // If the previous loads defined a super-reg, then we have to mark earlier // operands undef; Replicate the super-reg def on the merged instruction. for (MachineInstr &MI : FixupRange) { for (unsigned &ImpDefReg : ImpDefs) { for (MachineOperand &MO : MI.implicit_operands()) { if (!MO.isReg() || MO.getReg() != ImpDefReg) continue; if (MO.readsReg()) MO.setIsUndef(); else if (MO.isDef()) ImpDefReg = 0; } } } MachineInstrBuilder MIB(*Merged->getParent()->getParent(), Merged); for (unsigned ImpDef : ImpDefs) MIB.addReg(ImpDef, RegState::ImplicitDefine); } else { // Remove kill flags: We are possibly storing the values later now. assert(isi32Store(Opcode) || Opcode == ARM::VSTRS || Opcode == ARM::VSTRD); for (MachineInstr &MI : FixupRange) { for (MachineOperand &MO : MI.uses()) { if (!MO.isReg() || !MO.isKill()) continue; if (UsedRegs.count(MO.getReg())) MO.setIsKill(false); } } assert(ImpDefs.empty()); } return Merged; } static bool isValidLSDoubleOffset(int Offset) { unsigned Value = abs(Offset); // t2LDRDi8/t2STRDi8 supports an 8 bit immediate which is internally // multiplied by 4. return (Value % 4) == 0 && Value < 1024; } /// Return true for loads/stores that can be combined to a double/multi /// operation without increasing the requirements for alignment. static bool mayCombineMisaligned(const TargetSubtargetInfo &STI, const MachineInstr &MI) { // vldr/vstr trap on misaligned pointers anyway, forming vldm makes no // difference. unsigned Opcode = MI.getOpcode(); if (!isi32Load(Opcode) && !isi32Store(Opcode)) return true; // Stack pointer alignment is out of the programmers control so we can trust // SP-relative loads/stores. if (getLoadStoreBaseOp(MI).getReg() == ARM::SP && STI.getFrameLowering()->getTransientStackAlign() >= Align(4)) return true; return false; } /// Find candidates for load/store multiple merge in list of MemOpQueueEntries. void ARMLoadStoreOpt::FormCandidates(const MemOpQueue &MemOps) { const MachineInstr *FirstMI = MemOps[0].MI; unsigned Opcode = FirstMI->getOpcode(); bool isNotVFP = isi32Load(Opcode) || isi32Store(Opcode); unsigned Size = getLSMultipleTransferSize(FirstMI); unsigned SIndex = 0; unsigned EIndex = MemOps.size(); do { // Look at the first instruction. const MachineInstr *MI = MemOps[SIndex].MI; int Offset = MemOps[SIndex].Offset; const MachineOperand &PMO = getLoadStoreRegOp(*MI); Register PReg = PMO.getReg(); unsigned PRegNum = PMO.isUndef() ? std::numeric_limits<unsigned>::max() : TRI->getEncodingValue(PReg); unsigned Latest = SIndex; unsigned Earliest = SIndex; unsigned Count = 1; bool CanMergeToLSDouble = STI->isThumb2() && isNotVFP && isValidLSDoubleOffset(Offset); // ARM errata 602117: LDRD with base in list may result in incorrect base // register when interrupted or faulted. if (STI->isCortexM3() && isi32Load(Opcode) && PReg == getLoadStoreBaseOp(*MI).getReg()) CanMergeToLSDouble = false; bool CanMergeToLSMulti = true; // On swift vldm/vstm starting with an odd register number as that needs // more uops than single vldrs. if (STI->hasSlowOddRegister() && !isNotVFP && (PRegNum % 2) == 1) CanMergeToLSMulti = false; // LDRD/STRD do not allow SP/PC. LDM/STM do not support it or have it // deprecated; LDM to PC is fine but cannot happen here. if (PReg == ARM::SP || PReg == ARM::PC) CanMergeToLSMulti = CanMergeToLSDouble = false; // Should we be conservative? if (AssumeMisalignedLoadStores && !mayCombineMisaligned(*STI, *MI)) CanMergeToLSMulti = CanMergeToLSDouble = false; // vldm / vstm limit are 32 for S variants, 16 for D variants. unsigned Limit; switch (Opcode) { default: Limit = UINT_MAX; break; case ARM::VLDRD: case ARM::VSTRD: Limit = 16; break; } // Merge following instructions where possible. for (unsigned I = SIndex+1; I < EIndex; ++I, ++Count) { int NewOffset = MemOps[I].Offset; if (NewOffset != Offset + (int)Size) break; const MachineOperand &MO = getLoadStoreRegOp(*MemOps[I].MI); Register Reg = MO.getReg(); if (Reg == ARM::SP || Reg == ARM::PC) break; if (Count == Limit) break; // See if the current load/store may be part of a multi load/store. unsigned RegNum = MO.isUndef() ? std::numeric_limits<unsigned>::max() : TRI->getEncodingValue(Reg); bool PartOfLSMulti = CanMergeToLSMulti; if (PartOfLSMulti) { // Register numbers must be in ascending order. if (RegNum <= PRegNum) PartOfLSMulti = false; // For VFP / NEON load/store multiples, the registers must be // consecutive and within the limit on the number of registers per // instruction. else if (!isNotVFP && RegNum != PRegNum+1) PartOfLSMulti = false; } // See if the current load/store may be part of a double load/store. bool PartOfLSDouble = CanMergeToLSDouble && Count <= 1; if (!PartOfLSMulti && !PartOfLSDouble) break; CanMergeToLSMulti &= PartOfLSMulti; CanMergeToLSDouble &= PartOfLSDouble; // Track MemOp with latest and earliest position (Positions are // counted in reverse). unsigned Position = MemOps[I].Position; if (Position < MemOps[Latest].Position) Latest = I; else if (Position > MemOps[Earliest].Position) Earliest = I; // Prepare for next MemOp. Offset += Size; PRegNum = RegNum; } // Form a candidate from the Ops collected so far. MergeCandidate *Candidate = new(Allocator.Allocate()) MergeCandidate; for (unsigned C = SIndex, CE = SIndex + Count; C < CE; ++C) Candidate->Instrs.push_back(MemOps[C].MI); Candidate->LatestMIIdx = Latest - SIndex; Candidate->EarliestMIIdx = Earliest - SIndex; Candidate->InsertPos = MemOps[Latest].Position; if (Count == 1) CanMergeToLSMulti = CanMergeToLSDouble = false; Candidate->CanMergeToLSMulti = CanMergeToLSMulti; Candidate->CanMergeToLSDouble = CanMergeToLSDouble; Candidates.push_back(Candidate); // Continue after the chain. SIndex += Count; } while (SIndex < EIndex); } static unsigned getUpdatingLSMultipleOpcode(unsigned Opc, ARM_AM::AMSubMode Mode) { switch (Opc) { default: llvm_unreachable("Unhandled opcode!"); case ARM::LDMIA: case ARM::LDMDA: case ARM::LDMDB: case ARM::LDMIB: switch (Mode) { default: llvm_unreachable("Unhandled submode!"); case ARM_AM::ia: return ARM::LDMIA_UPD; case ARM_AM::ib: return ARM::LDMIB_UPD; case ARM_AM::da: return ARM::LDMDA_UPD; case ARM_AM::db: return ARM::LDMDB_UPD; } case ARM::STMIA: case ARM::STMDA: case ARM::STMDB: case ARM::STMIB: switch (Mode) { default: llvm_unreachable("Unhandled submode!"); case ARM_AM::ia: return ARM::STMIA_UPD; case ARM_AM::ib: return ARM::STMIB_UPD; case ARM_AM::da: return ARM::STMDA_UPD; case ARM_AM::db: return ARM::STMDB_UPD; } case ARM::t2LDMIA: case ARM::t2LDMDB: switch (Mode) { default: llvm_unreachable("Unhandled submode!"); case ARM_AM::ia: return ARM::t2LDMIA_UPD; case ARM_AM::db: return ARM::t2LDMDB_UPD; } case ARM::t2STMIA: case ARM::t2STMDB: switch (Mode) { default: llvm_unreachable("Unhandled submode!"); case ARM_AM::ia: return ARM::t2STMIA_UPD; case ARM_AM::db: return ARM::t2STMDB_UPD; } case ARM::VLDMSIA: switch (Mode) { default: llvm_unreachable("Unhandled submode!"); case ARM_AM::ia: return ARM::VLDMSIA_UPD; case ARM_AM::db: return ARM::VLDMSDB_UPD; } case ARM::VLDMDIA: switch (Mode) { default: llvm_unreachable("Unhandled submode!"); case ARM_AM::ia: return ARM::VLDMDIA_UPD; case ARM_AM::db: return ARM::VLDMDDB_UPD; } case ARM::VSTMSIA: switch (Mode) { default: llvm_unreachable("Unhandled submode!"); case ARM_AM::ia: return ARM::VSTMSIA_UPD; case ARM_AM::db: return ARM::VSTMSDB_UPD; } case ARM::VSTMDIA: switch (Mode) { default: llvm_unreachable("Unhandled submode!"); case ARM_AM::ia: return ARM::VSTMDIA_UPD; case ARM_AM::db: return ARM::VSTMDDB_UPD; } } } /// Check if the given instruction increments or decrements a register and /// return the amount it is incremented/decremented. Returns 0 if the CPSR flags /// generated by the instruction are possibly read as well. static int isIncrementOrDecrement(const MachineInstr &MI, Register Reg, ARMCC::CondCodes Pred, Register PredReg) { bool CheckCPSRDef; int Scale; switch (MI.getOpcode()) { case ARM::tADDi8: Scale = 4; CheckCPSRDef = true; break; case ARM::tSUBi8: Scale = -4; CheckCPSRDef = true; break; case ARM::t2SUBri: case ARM::t2SUBspImm: case ARM::SUBri: Scale = -1; CheckCPSRDef = true; break; case ARM::t2ADDri: case ARM::t2ADDspImm: case ARM::ADDri: Scale = 1; CheckCPSRDef = true; break; case ARM::tADDspi: Scale = 4; CheckCPSRDef = false; break; case ARM::tSUBspi: Scale = -4; CheckCPSRDef = false; break; default: return 0; } Register MIPredReg; if (MI.getOperand(0).getReg() != Reg || MI.getOperand(1).getReg() != Reg || getInstrPredicate(MI, MIPredReg) != Pred || MIPredReg != PredReg) return 0; if (CheckCPSRDef && definesCPSR(MI)) return 0; return MI.getOperand(2).getImm() * Scale; } /// Searches for an increment or decrement of \p Reg before \p MBBI. static MachineBasicBlock::iterator findIncDecBefore(MachineBasicBlock::iterator MBBI, Register Reg, ARMCC::CondCodes Pred, Register PredReg, int &Offset) { Offset = 0; MachineBasicBlock &MBB = *MBBI->getParent(); MachineBasicBlock::iterator BeginMBBI = MBB.begin(); MachineBasicBlock::iterator EndMBBI = MBB.end(); if (MBBI == BeginMBBI) return EndMBBI; // Skip debug values. MachineBasicBlock::iterator PrevMBBI = std::prev(MBBI); while (PrevMBBI->isDebugInstr() && PrevMBBI != BeginMBBI) --PrevMBBI; Offset = isIncrementOrDecrement(*PrevMBBI, Reg, Pred, PredReg); return Offset == 0 ? EndMBBI : PrevMBBI; } /// Searches for a increment or decrement of \p Reg after \p MBBI. static MachineBasicBlock::iterator findIncDecAfter(MachineBasicBlock::iterator MBBI, Register Reg, ARMCC::CondCodes Pred, Register PredReg, int &Offset, const TargetRegisterInfo *TRI) { Offset = 0; MachineBasicBlock &MBB = *MBBI->getParent(); MachineBasicBlock::iterator EndMBBI = MBB.end(); MachineBasicBlock::iterator NextMBBI = std::next(MBBI); while (NextMBBI != EndMBBI) { // Skip debug values. while (NextMBBI != EndMBBI && NextMBBI->isDebugInstr()) ++NextMBBI; if (NextMBBI == EndMBBI) return EndMBBI; unsigned Off = isIncrementOrDecrement(*NextMBBI, Reg, Pred, PredReg); if (Off) { Offset = Off; return NextMBBI; } // SP can only be combined if it is the next instruction after the original // MBBI, otherwise we may be incrementing the stack pointer (invalidating // anything below the new pointer) when its frame elements are still in // use. Other registers can attempt to look further, until a different use // or def of the register is found. if (Reg == ARM::SP || NextMBBI->readsRegister(Reg, TRI) || NextMBBI->definesRegister(Reg, TRI)) return EndMBBI; ++NextMBBI; } return EndMBBI; } /// Fold proceeding/trailing inc/dec of base register into the /// LDM/STM/VLDM{D|S}/VSTM{D|S} op when possible: /// /// stmia rn, <ra, rb, rc> /// rn := rn + 4 * 3; /// => /// stmia rn!, <ra, rb, rc> /// /// rn := rn - 4 * 3; /// ldmia rn, <ra, rb, rc> /// => /// ldmdb rn!, <ra, rb, rc> bool ARMLoadStoreOpt::MergeBaseUpdateLSMultiple(MachineInstr *MI) { // Thumb1 is already using updating loads/stores. if (isThumb1) return false; LLVM_DEBUG(dbgs() << "Attempting to merge update of: " << *MI); const MachineOperand &BaseOP = MI->getOperand(0); Register Base = BaseOP.getReg(); bool BaseKill = BaseOP.isKill(); Register PredReg; ARMCC::CondCodes Pred = getInstrPredicate(*MI, PredReg); unsigned Opcode = MI->getOpcode(); DebugLoc DL = MI->getDebugLoc(); // Can't use an updating ld/st if the base register is also a dest // register. e.g. ldmdb r0!, {r0, r1, r2}. The behavior is undefined. for (const MachineOperand &MO : llvm::drop_begin(MI->operands(), 2)) if (MO.getReg() == Base) return false; int Bytes = getLSMultipleTransferSize(MI); MachineBasicBlock &MBB = *MI->getParent(); MachineBasicBlock::iterator MBBI(MI); int Offset; MachineBasicBlock::iterator MergeInstr = findIncDecBefore(MBBI, Base, Pred, PredReg, Offset); ARM_AM::AMSubMode Mode = getLoadStoreMultipleSubMode(Opcode); if (Mode == ARM_AM::ia && Offset == -Bytes) { Mode = ARM_AM::db; } else if (Mode == ARM_AM::ib && Offset == -Bytes) { Mode = ARM_AM::da; } else { MergeInstr = findIncDecAfter(MBBI, Base, Pred, PredReg, Offset, TRI); if (((Mode != ARM_AM::ia && Mode != ARM_AM::ib) || Offset != Bytes) && ((Mode != ARM_AM::da && Mode != ARM_AM::db) || Offset != -Bytes)) { // We couldn't find an inc/dec to merge. But if the base is dead, we // can still change to a writeback form as that will save us 2 bytes // of code size. It can create WAW hazards though, so only do it if // we're minimizing code size. if (!STI->hasMinSize() || !BaseKill) return false; bool HighRegsUsed = false; for (const MachineOperand &MO : llvm::drop_begin(MI->operands(), 2)) if (MO.getReg() >= ARM::R8) { HighRegsUsed = true; break; } if (!HighRegsUsed) MergeInstr = MBB.end(); else return false; } } if (MergeInstr != MBB.end()) { LLVM_DEBUG(dbgs() << " Erasing old increment: " << *MergeInstr); MBB.erase(MergeInstr); } unsigned NewOpc = getUpdatingLSMultipleOpcode(Opcode, Mode); MachineInstrBuilder MIB = BuildMI(MBB, MBBI, DL, TII->get(NewOpc)) .addReg(Base, getDefRegState(true)) // WB base register .addReg(Base, getKillRegState(BaseKill)) .addImm(Pred).addReg(PredReg); // Transfer the rest of operands. for (const MachineOperand &MO : llvm::drop_begin(MI->operands(), 3)) MIB.add(MO); // Transfer memoperands. MIB.setMemRefs(MI->memoperands()); LLVM_DEBUG(dbgs() << " Added new load/store: " << *MIB); MBB.erase(MBBI); return true; } static unsigned getPreIndexedLoadStoreOpcode(unsigned Opc, ARM_AM::AddrOpc Mode) { switch (Opc) { case ARM::LDRi12: return ARM::LDR_PRE_IMM; case ARM::STRi12: return ARM::STR_PRE_IMM; case ARM::VLDRS: return Mode == ARM_AM::add ? ARM::VLDMSIA_UPD : ARM::VLDMSDB_UPD; case ARM::VLDRD: return Mode == ARM_AM::add ? ARM::VLDMDIA_UPD : ARM::VLDMDDB_UPD; case ARM::VSTRS: return Mode == ARM_AM::add ? ARM::VSTMSIA_UPD : ARM::VSTMSDB_UPD; case ARM::VSTRD: return Mode == ARM_AM::add ? ARM::VSTMDIA_UPD : ARM::VSTMDDB_UPD; case ARM::t2LDRi8: case ARM::t2LDRi12: return ARM::t2LDR_PRE; case ARM::t2STRi8: case ARM::t2STRi12: return ARM::t2STR_PRE; default: llvm_unreachable("Unhandled opcode!"); } } static unsigned getPostIndexedLoadStoreOpcode(unsigned Opc, ARM_AM::AddrOpc Mode) { switch (Opc) { case ARM::LDRi12: return ARM::LDR_POST_IMM; case ARM::STRi12: return ARM::STR_POST_IMM; case ARM::VLDRS: return Mode == ARM_AM::add ? ARM::VLDMSIA_UPD : ARM::VLDMSDB_UPD; case ARM::VLDRD: return Mode == ARM_AM::add ? ARM::VLDMDIA_UPD : ARM::VLDMDDB_UPD; case ARM::VSTRS: return Mode == ARM_AM::add ? ARM::VSTMSIA_UPD : ARM::VSTMSDB_UPD; case ARM::VSTRD: return Mode == ARM_AM::add ? ARM::VSTMDIA_UPD : ARM::VSTMDDB_UPD; case ARM::t2LDRi8: case ARM::t2LDRi12: return ARM::t2LDR_POST; case ARM::t2LDRBi8: case ARM::t2LDRBi12: return ARM::t2LDRB_POST; case ARM::t2LDRSBi8: case ARM::t2LDRSBi12: return ARM::t2LDRSB_POST; case ARM::t2LDRHi8: case ARM::t2LDRHi12: return ARM::t2LDRH_POST; case ARM::t2LDRSHi8: case ARM::t2LDRSHi12: return ARM::t2LDRSH_POST; case ARM::t2STRi8: case ARM::t2STRi12: return ARM::t2STR_POST; case ARM::t2STRBi8: case ARM::t2STRBi12: return ARM::t2STRB_POST; case ARM::t2STRHi8: case ARM::t2STRHi12: return ARM::t2STRH_POST; case ARM::MVE_VLDRBS16: return ARM::MVE_VLDRBS16_post; case ARM::MVE_VLDRBS32: return ARM::MVE_VLDRBS32_post; case ARM::MVE_VLDRBU16: return ARM::MVE_VLDRBU16_post; case ARM::MVE_VLDRBU32: return ARM::MVE_VLDRBU32_post; case ARM::MVE_VLDRHS32: return ARM::MVE_VLDRHS32_post; case ARM::MVE_VLDRHU32: return ARM::MVE_VLDRHU32_post; case ARM::MVE_VLDRBU8: return ARM::MVE_VLDRBU8_post; case ARM::MVE_VLDRHU16: return ARM::MVE_VLDRHU16_post; case ARM::MVE_VLDRWU32: return ARM::MVE_VLDRWU32_post; case ARM::MVE_VSTRB16: return ARM::MVE_VSTRB16_post; case ARM::MVE_VSTRB32: return ARM::MVE_VSTRB32_post; case ARM::MVE_VSTRH32: return ARM::MVE_VSTRH32_post; case ARM::MVE_VSTRBU8: return ARM::MVE_VSTRBU8_post; case ARM::MVE_VSTRHU16: return ARM::MVE_VSTRHU16_post; case ARM::MVE_VSTRWU32: return ARM::MVE_VSTRWU32_post; default: llvm_unreachable("Unhandled opcode!"); } } /// Fold proceeding/trailing inc/dec of base register into the /// LDR/STR/FLD{D|S}/FST{D|S} op when possible: bool ARMLoadStoreOpt::MergeBaseUpdateLoadStore(MachineInstr *MI) { // Thumb1 doesn't have updating LDR/STR. // FIXME: Use LDM/STM with single register instead. if (isThumb1) return false; LLVM_DEBUG(dbgs() << "Attempting to merge update of: " << *MI); Register Base = getLoadStoreBaseOp(*MI).getReg(); bool BaseKill = getLoadStoreBaseOp(*MI).isKill(); unsigned Opcode = MI->getOpcode(); DebugLoc DL = MI->getDebugLoc(); bool isAM5 = (Opcode == ARM::VLDRD || Opcode == ARM::VLDRS || Opcode == ARM::VSTRD || Opcode == ARM::VSTRS); bool isAM2 = (Opcode == ARM::LDRi12 || Opcode == ARM::STRi12); if (isi32Load(Opcode) || isi32Store(Opcode)) if (MI->getOperand(2).getImm() != 0) return false; if (isAM5 && ARM_AM::getAM5Offset(MI->getOperand(2).getImm()) != 0) return false; // Can't do the merge if the destination register is the same as the would-be // writeback register. if (MI->getOperand(0).getReg() == Base) return false; Register PredReg; ARMCC::CondCodes Pred = getInstrPredicate(*MI, PredReg); int Bytes = getLSMultipleTransferSize(MI); MachineBasicBlock &MBB = *MI->getParent(); MachineBasicBlock::iterator MBBI(MI); int Offset; MachineBasicBlock::iterator MergeInstr = findIncDecBefore(MBBI, Base, Pred, PredReg, Offset); unsigned NewOpc; if (!isAM5 && Offset == Bytes) { NewOpc = getPreIndexedLoadStoreOpcode(Opcode, ARM_AM::add); } else if (Offset == -Bytes) { NewOpc = getPreIndexedLoadStoreOpcode(Opcode, ARM_AM::sub); } else { MergeInstr = findIncDecAfter(MBBI, Base, Pred, PredReg, Offset, TRI); if (MergeInstr == MBB.end()) return false; NewOpc = getPostIndexedLoadStoreOpcode(Opcode, ARM_AM::add); if ((isAM5 && Offset != Bytes) || (!isAM5 && !isLegalAddressImm(NewOpc, Offset, TII))) { NewOpc = getPostIndexedLoadStoreOpcode(Opcode, ARM_AM::sub); if (isAM5 || !isLegalAddressImm(NewOpc, Offset, TII)) return false; } } LLVM_DEBUG(dbgs() << " Erasing old increment: " << *MergeInstr); MBB.erase(MergeInstr); ARM_AM::AddrOpc AddSub = Offset < 0 ? ARM_AM::sub : ARM_AM::add; bool isLd = isLoadSingle(Opcode); if (isAM5) { // VLDM[SD]_UPD, VSTM[SD]_UPD // (There are no base-updating versions of VLDR/VSTR instructions, but the // updating load/store-multiple instructions can be used with only one // register.) MachineOperand &MO = MI->getOperand(0); auto MIB = BuildMI(MBB, MBBI, DL, TII->get(NewOpc)) .addReg(Base, getDefRegState(true)) // WB base register .addReg(Base, getKillRegState(isLd ? BaseKill : false)) .addImm(Pred) .addReg(PredReg) .addReg(MO.getReg(), (isLd ? getDefRegState(true) : getKillRegState(MO.isKill()))) .cloneMemRefs(*MI); (void)MIB; LLVM_DEBUG(dbgs() << " Added new instruction: " << *MIB); } else if (isLd) { if (isAM2) { // LDR_PRE, LDR_POST if (NewOpc == ARM::LDR_PRE_IMM || NewOpc == ARM::LDRB_PRE_IMM) { auto MIB = BuildMI(MBB, MBBI, DL, TII->get(NewOpc), MI->getOperand(0).getReg()) .addReg(Base, RegState::Define) .addReg(Base) .addImm(Offset) .addImm(Pred) .addReg(PredReg) .cloneMemRefs(*MI); (void)MIB; LLVM_DEBUG(dbgs() << " Added new instruction: " << *MIB); } else { int Imm = ARM_AM::getAM2Opc(AddSub, abs(Offset), ARM_AM::no_shift); auto MIB = BuildMI(MBB, MBBI, DL, TII->get(NewOpc), MI->getOperand(0).getReg()) .addReg(Base, RegState::Define) .addReg(Base) .addReg(0) .addImm(Imm) .add(predOps(Pred, PredReg)) .cloneMemRefs(*MI); (void)MIB; LLVM_DEBUG(dbgs() << " Added new instruction: " << *MIB); } } else { // t2LDR_PRE, t2LDR_POST auto MIB = BuildMI(MBB, MBBI, DL, TII->get(NewOpc), MI->getOperand(0).getReg()) .addReg(Base, RegState::Define) .addReg(Base) .addImm(Offset) .add(predOps(Pred, PredReg)) .cloneMemRefs(*MI); (void)MIB; LLVM_DEBUG(dbgs() << " Added new instruction: " << *MIB); } } else { MachineOperand &MO = MI->getOperand(0); // FIXME: post-indexed stores use am2offset_imm, which still encodes // the vestigal zero-reg offset register. When that's fixed, this clause // can be removed entirely. if (isAM2 && NewOpc == ARM::STR_POST_IMM) { int Imm = ARM_AM::getAM2Opc(AddSub, abs(Offset), ARM_AM::no_shift); // STR_PRE, STR_POST auto MIB = BuildMI(MBB, MBBI, DL, TII->get(NewOpc), Base) .addReg(MO.getReg(), getKillRegState(MO.isKill())) .addReg(Base) .addReg(0) .addImm(Imm) .add(predOps(Pred, PredReg)) .cloneMemRefs(*MI); (void)MIB; LLVM_DEBUG(dbgs() << " Added new instruction: " << *MIB); } else { // t2STR_PRE, t2STR_POST auto MIB = BuildMI(MBB, MBBI, DL, TII->get(NewOpc), Base) .addReg(MO.getReg(), getKillRegState(MO.isKill())) .addReg(Base) .addImm(Offset) .add(predOps(Pred, PredReg)) .cloneMemRefs(*MI); (void)MIB; LLVM_DEBUG(dbgs() << " Added new instruction: " << *MIB); } } MBB.erase(MBBI); return true; } bool ARMLoadStoreOpt::MergeBaseUpdateLSDouble(MachineInstr &MI) const { unsigned Opcode = MI.getOpcode(); assert((Opcode == ARM::t2LDRDi8 || Opcode == ARM::t2STRDi8) && "Must have t2STRDi8 or t2LDRDi8"); if (MI.getOperand(3).getImm() != 0) return false; LLVM_DEBUG(dbgs() << "Attempting to merge update of: " << MI); // Behaviour for writeback is undefined if base register is the same as one // of the others. const MachineOperand &BaseOp = MI.getOperand(2); Register Base = BaseOp.getReg(); const MachineOperand &Reg0Op = MI.getOperand(0); const MachineOperand &Reg1Op = MI.getOperand(1); if (Reg0Op.getReg() == Base || Reg1Op.getReg() == Base) return false; Register PredReg; ARMCC::CondCodes Pred = getInstrPredicate(MI, PredReg); MachineBasicBlock::iterator MBBI(MI); MachineBasicBlock &MBB = *MI.getParent(); int Offset; MachineBasicBlock::iterator MergeInstr = findIncDecBefore(MBBI, Base, Pred, PredReg, Offset); unsigned NewOpc; if (Offset == 8 || Offset == -8) { NewOpc = Opcode == ARM::t2LDRDi8 ? ARM::t2LDRD_PRE : ARM::t2STRD_PRE; } else { MergeInstr = findIncDecAfter(MBBI, Base, Pred, PredReg, Offset, TRI); if (MergeInstr == MBB.end()) return false; NewOpc = Opcode == ARM::t2LDRDi8 ? ARM::t2LDRD_POST : ARM::t2STRD_POST; if (!isLegalAddressImm(NewOpc, Offset, TII)) return false; } LLVM_DEBUG(dbgs() << " Erasing old increment: " << *MergeInstr); MBB.erase(MergeInstr); DebugLoc DL = MI.getDebugLoc(); MachineInstrBuilder MIB = BuildMI(MBB, MBBI, DL, TII->get(NewOpc)); if (NewOpc == ARM::t2LDRD_PRE || NewOpc == ARM::t2LDRD_POST) { MIB.add(Reg0Op).add(Reg1Op).addReg(BaseOp.getReg(), RegState::Define); } else { assert(NewOpc == ARM::t2STRD_PRE || NewOpc == ARM::t2STRD_POST); MIB.addReg(BaseOp.getReg(), RegState::Define).add(Reg0Op).add(Reg1Op); } MIB.addReg(BaseOp.getReg(), RegState::Kill) .addImm(Offset).addImm(Pred).addReg(PredReg); assert(TII->get(Opcode).getNumOperands() == 6 && TII->get(NewOpc).getNumOperands() == 7 && "Unexpected number of operands in Opcode specification."); // Transfer implicit operands. for (const MachineOperand &MO : MI.implicit_operands()) MIB.add(MO); MIB.cloneMemRefs(MI); LLVM_DEBUG(dbgs() << " Added new load/store: " << *MIB); MBB.erase(MBBI); return true; } /// Returns true if instruction is a memory operation that this pass is capable /// of operating on. static bool isMemoryOp(const MachineInstr &MI) { unsigned Opcode = MI.getOpcode(); switch (Opcode) { case ARM::VLDRS: case ARM::VSTRS: case ARM::VLDRD: case ARM::VSTRD: case ARM::LDRi12: case ARM::STRi12: case ARM::tLDRi: case ARM::tSTRi: case ARM::tLDRspi: case ARM::tSTRspi: case ARM::t2LDRi8: case ARM::t2LDRi12: case ARM::t2STRi8: case ARM::t2STRi12: break; default: return false; } if (!MI.getOperand(1).isReg()) return false; // When no memory operands are present, conservatively assume unaligned, // volatile, unfoldable. if (!MI.hasOneMemOperand()) return false; const MachineMemOperand &MMO = **MI.memoperands_begin(); // Don't touch volatile memory accesses - we may be changing their order. // TODO: We could allow unordered and monotonic atomics here, but we need to // make sure the resulting ldm/stm is correctly marked as atomic. if (MMO.isVolatile() || MMO.isAtomic()) return false; // Unaligned ldr/str is emulated by some kernels, but unaligned ldm/stm is // not. if (MMO.getAlign() < Align(4)) return false; // str <undef> could probably be eliminated entirely, but for now we just want // to avoid making a mess of it. // FIXME: Use str <undef> as a wildcard to enable better stm folding. if (MI.getOperand(0).isReg() && MI.getOperand(0).isUndef()) return false; // Likewise don't mess with references to undefined addresses. if (MI.getOperand(1).isUndef()) return false; return true; } static void InsertLDR_STR(MachineBasicBlock &MBB, MachineBasicBlock::iterator &MBBI, int Offset, bool isDef, unsigned NewOpc, unsigned Reg, bool RegDeadKill, bool RegUndef, unsigned BaseReg, bool BaseKill, bool BaseUndef, ARMCC::CondCodes Pred, unsigned PredReg, const TargetInstrInfo *TII, MachineInstr *MI) { if (isDef) { MachineInstrBuilder MIB = BuildMI(MBB, MBBI, MBBI->getDebugLoc(), TII->get(NewOpc)) .addReg(Reg, getDefRegState(true) | getDeadRegState(RegDeadKill)) .addReg(BaseReg, getKillRegState(BaseKill)|getUndefRegState(BaseUndef)); MIB.addImm(Offset).addImm(Pred).addReg(PredReg); // FIXME: This is overly conservative; the new instruction accesses 4 // bytes, not 8. MIB.cloneMemRefs(*MI); } else { MachineInstrBuilder MIB = BuildMI(MBB, MBBI, MBBI->getDebugLoc(), TII->get(NewOpc)) .addReg(Reg, getKillRegState(RegDeadKill) | getUndefRegState(RegUndef)) .addReg(BaseReg, getKillRegState(BaseKill)|getUndefRegState(BaseUndef)); MIB.addImm(Offset).addImm(Pred).addReg(PredReg); // FIXME: This is overly conservative; the new instruction accesses 4 // bytes, not 8. MIB.cloneMemRefs(*MI); } } bool ARMLoadStoreOpt::FixInvalidRegPairOp(MachineBasicBlock &MBB, MachineBasicBlock::iterator &MBBI) { MachineInstr *MI = &*MBBI; unsigned Opcode = MI->getOpcode(); // FIXME: Code/comments below check Opcode == t2STRDi8, but this check returns // if we see this opcode. if (Opcode != ARM::LDRD && Opcode != ARM::STRD && Opcode != ARM::t2LDRDi8) return false; const MachineOperand &BaseOp = MI->getOperand(2); Register BaseReg = BaseOp.getReg(); Register EvenReg = MI->getOperand(0).getReg(); Register OddReg = MI->getOperand(1).getReg(); unsigned EvenRegNum = TRI->getDwarfRegNum(EvenReg, false); unsigned OddRegNum = TRI->getDwarfRegNum(OddReg, false); // ARM errata 602117: LDRD with base in list may result in incorrect base // register when interrupted or faulted. bool Errata602117 = EvenReg == BaseReg && (Opcode == ARM::LDRD || Opcode == ARM::t2LDRDi8) && STI->isCortexM3(); // ARM LDRD/STRD needs consecutive registers. bool NonConsecutiveRegs = (Opcode == ARM::LDRD || Opcode == ARM::STRD) && (EvenRegNum % 2 != 0 || EvenRegNum + 1 != OddRegNum); if (!Errata602117 && !NonConsecutiveRegs) return false; bool isT2 = Opcode == ARM::t2LDRDi8 || Opcode == ARM::t2STRDi8; bool isLd = Opcode == ARM::LDRD || Opcode == ARM::t2LDRDi8; bool EvenDeadKill = isLd ? MI->getOperand(0).isDead() : MI->getOperand(0).isKill(); bool EvenUndef = MI->getOperand(0).isUndef(); bool OddDeadKill = isLd ? MI->getOperand(1).isDead() : MI->getOperand(1).isKill(); bool OddUndef = MI->getOperand(1).isUndef(); bool BaseKill = BaseOp.isKill(); bool BaseUndef = BaseOp.isUndef(); assert((isT2 || MI->getOperand(3).getReg() == ARM::NoRegister) && "register offset not handled below"); int OffImm = getMemoryOpOffset(*MI); Register PredReg; ARMCC::CondCodes Pred = getInstrPredicate(*MI, PredReg); if (OddRegNum > EvenRegNum && OffImm == 0) { // Ascending register numbers and no offset. It's safe to change it to a // ldm or stm. unsigned NewOpc = (isLd) ? (isT2 ? ARM::t2LDMIA : ARM::LDMIA) : (isT2 ? ARM::t2STMIA : ARM::STMIA); if (isLd) { BuildMI(MBB, MBBI, MBBI->getDebugLoc(), TII->get(NewOpc)) .addReg(BaseReg, getKillRegState(BaseKill)) .addImm(Pred).addReg(PredReg) .addReg(EvenReg, getDefRegState(isLd) | getDeadRegState(EvenDeadKill)) .addReg(OddReg, getDefRegState(isLd) | getDeadRegState(OddDeadKill)) .cloneMemRefs(*MI); ++NumLDRD2LDM; } else { BuildMI(MBB, MBBI, MBBI->getDebugLoc(), TII->get(NewOpc)) .addReg(BaseReg, getKillRegState(BaseKill)) .addImm(Pred).addReg(PredReg) .addReg(EvenReg, getKillRegState(EvenDeadKill) | getUndefRegState(EvenUndef)) .addReg(OddReg, getKillRegState(OddDeadKill) | getUndefRegState(OddUndef)) .cloneMemRefs(*MI); ++NumSTRD2STM; } } else { // Split into two instructions. unsigned NewOpc = (isLd) ? (isT2 ? (OffImm < 0 ? ARM::t2LDRi8 : ARM::t2LDRi12) : ARM::LDRi12) : (isT2 ? (OffImm < 0 ? ARM::t2STRi8 : ARM::t2STRi12) : ARM::STRi12); // Be extra careful for thumb2. t2LDRi8 can't reference a zero offset, // so adjust and use t2LDRi12 here for that. unsigned NewOpc2 = (isLd) ? (isT2 ? (OffImm+4 < 0 ? ARM::t2LDRi8 : ARM::t2LDRi12) : ARM::LDRi12) : (isT2 ? (OffImm+4 < 0 ? ARM::t2STRi8 : ARM::t2STRi12) : ARM::STRi12); // If this is a load, make sure the first load does not clobber the base // register before the second load reads it. if (isLd && TRI->regsOverlap(EvenReg, BaseReg)) { assert(!TRI->regsOverlap(OddReg, BaseReg)); InsertLDR_STR(MBB, MBBI, OffImm + 4, isLd, NewOpc2, OddReg, OddDeadKill, false, BaseReg, false, BaseUndef, Pred, PredReg, TII, MI); InsertLDR_STR(MBB, MBBI, OffImm, isLd, NewOpc, EvenReg, EvenDeadKill, false, BaseReg, BaseKill, BaseUndef, Pred, PredReg, TII, MI); } else { if (OddReg == EvenReg && EvenDeadKill) { // If the two source operands are the same, the kill marker is // probably on the first one. e.g. // t2STRDi8 killed %r5, %r5, killed %r9, 0, 14, %reg0 EvenDeadKill = false; OddDeadKill = true; } // Never kill the base register in the first instruction. if (EvenReg == BaseReg) EvenDeadKill = false; InsertLDR_STR(MBB, MBBI, OffImm, isLd, NewOpc, EvenReg, EvenDeadKill, EvenUndef, BaseReg, false, BaseUndef, Pred, PredReg, TII, MI); InsertLDR_STR(MBB, MBBI, OffImm + 4, isLd, NewOpc2, OddReg, OddDeadKill, OddUndef, BaseReg, BaseKill, BaseUndef, Pred, PredReg, TII, MI); } if (isLd) ++NumLDRD2LDR; else ++NumSTRD2STR; } MBBI = MBB.erase(MBBI); return true; } /// An optimization pass to turn multiple LDR / STR ops of the same base and /// incrementing offset into LDM / STM ops. bool ARMLoadStoreOpt::LoadStoreMultipleOpti(MachineBasicBlock &MBB) { MemOpQueue MemOps; unsigned CurrBase = 0; unsigned CurrOpc = ~0u; ARMCC::CondCodes CurrPred = ARMCC::AL; unsigned Position = 0; assert(Candidates.size() == 0); assert(MergeBaseCandidates.size() == 0); LiveRegsValid = false; for (MachineBasicBlock::iterator I = MBB.end(), MBBI; I != MBB.begin(); I = MBBI) { // The instruction in front of the iterator is the one we look at. MBBI = std::prev(I); if (FixInvalidRegPairOp(MBB, MBBI)) continue; ++Position; if (isMemoryOp(*MBBI)) { unsigned Opcode = MBBI->getOpcode(); const MachineOperand &MO = MBBI->getOperand(0); Register Reg = MO.getReg(); Register Base = getLoadStoreBaseOp(*MBBI).getReg(); Register PredReg; ARMCC::CondCodes Pred = getInstrPredicate(*MBBI, PredReg); int Offset = getMemoryOpOffset(*MBBI); if (CurrBase == 0) { // Start of a new chain. CurrBase = Base; CurrOpc = Opcode; CurrPred = Pred; MemOps.push_back(MemOpQueueEntry(*MBBI, Offset, Position)); continue; } // Note: No need to match PredReg in the next if. if (CurrOpc == Opcode && CurrBase == Base && CurrPred == Pred) { // Watch out for: // r4 := ldr [r0, #8] // r4 := ldr [r0, #4] // or // r0 := ldr [r0] // If a load overrides the base register or a register loaded by // another load in our chain, we cannot take this instruction. bool Overlap = false; if (isLoadSingle(Opcode)) { Overlap = (Base == Reg); if (!Overlap) { for (const MemOpQueueEntry &E : MemOps) { if (TRI->regsOverlap(Reg, E.MI->getOperand(0).getReg())) { Overlap = true; break; } } } } if (!Overlap) { // Check offset and sort memory operation into the current chain. if (Offset > MemOps.back().Offset) { MemOps.push_back(MemOpQueueEntry(*MBBI, Offset, Position)); continue; } else { MemOpQueue::iterator MI, ME; for (MI = MemOps.begin(), ME = MemOps.end(); MI != ME; ++MI) { if (Offset < MI->Offset) { // Found a place to insert. break; } if (Offset == MI->Offset) { // Collision, abort. MI = ME; break; } } if (MI != MemOps.end()) { MemOps.insert(MI, MemOpQueueEntry(*MBBI, Offset, Position)); continue; } } } } // Don't advance the iterator; The op will start a new chain next. MBBI = I; --Position; // Fallthrough to look into existing chain. } else if (MBBI->isDebugInstr()) { continue; } else if (MBBI->getOpcode() == ARM::t2LDRDi8 || MBBI->getOpcode() == ARM::t2STRDi8) { // ARMPreAllocLoadStoreOpt has already formed some LDRD/STRD instructions // remember them because we may still be able to merge add/sub into them. MergeBaseCandidates.push_back(&*MBBI); } // If we are here then the chain is broken; Extract candidates for a merge. if (MemOps.size() > 0) { FormCandidates(MemOps); // Reset for the next chain. CurrBase = 0; CurrOpc = ~0u; CurrPred = ARMCC::AL; MemOps.clear(); } } if (MemOps.size() > 0) FormCandidates(MemOps); // Sort candidates so they get processed from end to begin of the basic // block later; This is necessary for liveness calculation. auto LessThan = [](const MergeCandidate* M0, const MergeCandidate *M1) { return M0->InsertPos < M1->InsertPos; }; llvm::sort(Candidates, LessThan); // Go through list of candidates and merge. bool Changed = false; for (const MergeCandidate *Candidate : Candidates) { if (Candidate->CanMergeToLSMulti || Candidate->CanMergeToLSDouble) { MachineInstr *Merged = MergeOpsUpdate(*Candidate); // Merge preceding/trailing base inc/dec into the merged op. if (Merged) { Changed = true; unsigned Opcode = Merged->getOpcode(); if (Opcode == ARM::t2STRDi8 || Opcode == ARM::t2LDRDi8) MergeBaseUpdateLSDouble(*Merged); else MergeBaseUpdateLSMultiple(Merged); } else { for (MachineInstr *MI : Candidate->Instrs) { if (MergeBaseUpdateLoadStore(MI)) Changed = true; } } } else { assert(Candidate->Instrs.size() == 1); if (MergeBaseUpdateLoadStore(Candidate->Instrs.front())) Changed = true; } } Candidates.clear(); // Try to fold add/sub into the LDRD/STRD formed by ARMPreAllocLoadStoreOpt. for (MachineInstr *MI : MergeBaseCandidates) MergeBaseUpdateLSDouble(*MI); MergeBaseCandidates.clear(); return Changed; } /// If this is a exit BB, try merging the return ops ("bx lr" and "mov pc, lr") /// into the preceding stack restore so it directly restore the value of LR /// into pc. /// ldmfd sp!, {..., lr} /// bx lr /// or /// ldmfd sp!, {..., lr} /// mov pc, lr /// => /// ldmfd sp!, {..., pc} bool ARMLoadStoreOpt::MergeReturnIntoLDM(MachineBasicBlock &MBB) { // Thumb1 LDM doesn't allow high registers. if (isThumb1) return false; if (MBB.empty()) return false; MachineBasicBlock::iterator MBBI = MBB.getLastNonDebugInstr(); if (MBBI != MBB.begin() && MBBI != MBB.end() && (MBBI->getOpcode() == ARM::BX_RET || MBBI->getOpcode() == ARM::tBX_RET || MBBI->getOpcode() == ARM::MOVPCLR)) { MachineBasicBlock::iterator PrevI = std::prev(MBBI); // Ignore any debug instructions. while (PrevI->isDebugInstr() && PrevI != MBB.begin()) --PrevI; MachineInstr &PrevMI = *PrevI; unsigned Opcode = PrevMI.getOpcode(); if (Opcode == ARM::LDMIA_UPD || Opcode == ARM::LDMDA_UPD || Opcode == ARM::LDMDB_UPD || Opcode == ARM::LDMIB_UPD || Opcode == ARM::t2LDMIA_UPD || Opcode == ARM::t2LDMDB_UPD) { MachineOperand &MO = PrevMI.getOperand(PrevMI.getNumOperands() - 1); if (MO.getReg() != ARM::LR) return false; unsigned NewOpc = (isThumb2 ? ARM::t2LDMIA_RET : ARM::LDMIA_RET); assert(((isThumb2 && Opcode == ARM::t2LDMIA_UPD) || Opcode == ARM::LDMIA_UPD) && "Unsupported multiple load-return!"); PrevMI.setDesc(TII->get(NewOpc)); MO.setReg(ARM::PC); PrevMI.copyImplicitOps(*MBB.getParent(), *MBBI); MBB.erase(MBBI); // We now restore LR into PC so it is not live-out of the return block // anymore: Clear the CSI Restored bit. MachineFrameInfo &MFI = MBB.getParent()->getFrameInfo(); // CSI should be fixed after PrologEpilog Insertion assert(MFI.isCalleeSavedInfoValid() && "CSI should be valid"); for (CalleeSavedInfo &Info : MFI.getCalleeSavedInfo()) { if (Info.getReg() == ARM::LR) { Info.setRestored(false); break; } } return true; } } return false; } bool ARMLoadStoreOpt::CombineMovBx(MachineBasicBlock &MBB) { MachineBasicBlock::iterator MBBI = MBB.getFirstTerminator(); if (MBBI == MBB.begin() || MBBI == MBB.end() || MBBI->getOpcode() != ARM::tBX_RET) return false; MachineBasicBlock::iterator Prev = MBBI; --Prev; if (Prev->getOpcode() != ARM::tMOVr || !Prev->definesRegister(ARM::LR)) return false; for (auto Use : Prev->uses()) if (Use.isKill()) { assert(STI->hasV4TOps()); BuildMI(MBB, MBBI, MBBI->getDebugLoc(), TII->get(ARM::tBX)) .addReg(Use.getReg(), RegState::Kill) .add(predOps(ARMCC::AL)) .copyImplicitOps(*MBBI); MBB.erase(MBBI); MBB.erase(Prev); return true; } llvm_unreachable("tMOVr doesn't kill a reg before tBX_RET?"); } bool ARMLoadStoreOpt::runOnMachineFunction(MachineFunction &Fn) { if (skipFunction(Fn.getFunction())) return false; MF = &Fn; STI = &static_cast<const ARMSubtarget &>(Fn.getSubtarget()); TL = STI->getTargetLowering(); AFI = Fn.getInfo<ARMFunctionInfo>(); TII = STI->getInstrInfo(); TRI = STI->getRegisterInfo(); RegClassInfoValid = false; isThumb2 = AFI->isThumb2Function(); isThumb1 = AFI->isThumbFunction() && !isThumb2; bool Modified = false; for (MachineBasicBlock &MBB : Fn) { Modified |= LoadStoreMultipleOpti(MBB); if (STI->hasV5TOps() && !AFI->shouldSignReturnAddress()) Modified |= MergeReturnIntoLDM(MBB); if (isThumb1) Modified |= CombineMovBx(MBB); } Allocator.DestroyAll(); return Modified; } #define ARM_PREALLOC_LOAD_STORE_OPT_NAME \ "ARM pre- register allocation load / store optimization pass" namespace { /// Pre- register allocation pass that move load / stores from consecutive /// locations close to make it more likely they will be combined later. struct ARMPreAllocLoadStoreOpt : public MachineFunctionPass{ static char ID; AliasAnalysis *AA; const DataLayout *TD; const TargetInstrInfo *TII; const TargetRegisterInfo *TRI; const ARMSubtarget *STI; MachineRegisterInfo *MRI; MachineDominatorTree *DT; MachineFunction *MF; ARMPreAllocLoadStoreOpt() : MachineFunctionPass(ID) {} bool runOnMachineFunction(MachineFunction &Fn) override; StringRef getPassName() const override { return ARM_PREALLOC_LOAD_STORE_OPT_NAME; } void getAnalysisUsage(AnalysisUsage &AU) const override { AU.addRequired<AAResultsWrapperPass>(); AU.addRequired<MachineDominatorTree>(); AU.addPreserved<MachineDominatorTree>(); MachineFunctionPass::getAnalysisUsage(AU); } private: bool CanFormLdStDWord(MachineInstr *Op0, MachineInstr *Op1, DebugLoc &dl, unsigned &NewOpc, Register &EvenReg, Register &OddReg, Register &BaseReg, int &Offset, Register &PredReg, ARMCC::CondCodes &Pred, bool &isT2); bool RescheduleOps(MachineBasicBlock *MBB, SmallVectorImpl<MachineInstr *> &Ops, unsigned Base, bool isLd, DenseMap<MachineInstr*, unsigned> &MI2LocMap); bool RescheduleLoadStoreInstrs(MachineBasicBlock *MBB); bool DistributeIncrements(); bool DistributeIncrements(Register Base); }; } // end anonymous namespace char ARMPreAllocLoadStoreOpt::ID = 0; INITIALIZE_PASS_BEGIN(ARMPreAllocLoadStoreOpt, "arm-prera-ldst-opt", ARM_PREALLOC_LOAD_STORE_OPT_NAME, false, false) INITIALIZE_PASS_DEPENDENCY(MachineDominatorTree) INITIALIZE_PASS_END(ARMPreAllocLoadStoreOpt, "arm-prera-ldst-opt", ARM_PREALLOC_LOAD_STORE_OPT_NAME, false, false) // Limit the number of instructions to be rescheduled. // FIXME: tune this limit, and/or come up with some better heuristics. static cl::opt<unsigned> InstReorderLimit("arm-prera-ldst-opt-reorder-limit", cl::init(8), cl::Hidden); bool ARMPreAllocLoadStoreOpt::runOnMachineFunction(MachineFunction &Fn) { if (AssumeMisalignedLoadStores || skipFunction(Fn.getFunction())) return false; TD = &Fn.getDataLayout(); STI = &static_cast<const ARMSubtarget &>(Fn.getSubtarget()); TII = STI->getInstrInfo(); TRI = STI->getRegisterInfo(); MRI = &Fn.getRegInfo(); DT = &getAnalysis<MachineDominatorTree>(); MF = &Fn; AA = &getAnalysis<AAResultsWrapperPass>().getAAResults(); bool Modified = DistributeIncrements(); for (MachineBasicBlock &MFI : Fn) Modified |= RescheduleLoadStoreInstrs(&MFI); return Modified; } static bool IsSafeAndProfitableToMove(bool isLd, unsigned Base, MachineBasicBlock::iterator I, MachineBasicBlock::iterator E, SmallPtrSetImpl<MachineInstr*> &MemOps, SmallSet<unsigned, 4> &MemRegs, const TargetRegisterInfo *TRI, AliasAnalysis *AA) { // Are there stores / loads / calls between them? SmallSet<unsigned, 4> AddedRegPressure; while (++I != E) { if (I->isDebugInstr() || MemOps.count(&*I)) continue; if (I->isCall() || I->isTerminator() || I->hasUnmodeledSideEffects()) return false; if (I->mayStore() || (!isLd && I->mayLoad())) for (MachineInstr *MemOp : MemOps) if (I->mayAlias(AA, *MemOp, /*UseTBAA*/ false)) return false; for (unsigned j = 0, NumOps = I->getNumOperands(); j != NumOps; ++j) { MachineOperand &MO = I->getOperand(j); if (!MO.isReg()) continue; Register Reg = MO.getReg(); if (MO.isDef() && TRI->regsOverlap(Reg, Base)) return false; if (Reg != Base && !MemRegs.count(Reg)) AddedRegPressure.insert(Reg); } } // Estimate register pressure increase due to the transformation. if (MemRegs.size() <= 4) // Ok if we are moving small number of instructions. return true; return AddedRegPressure.size() <= MemRegs.size() * 2; } bool ARMPreAllocLoadStoreOpt::CanFormLdStDWord( MachineInstr *Op0, MachineInstr *Op1, DebugLoc &dl, unsigned &NewOpc, Register &FirstReg, Register &SecondReg, Register &BaseReg, int &Offset, Register &PredReg, ARMCC::CondCodes &Pred, bool &isT2) { // Make sure we're allowed to generate LDRD/STRD. if (!STI->hasV5TEOps()) return false; // FIXME: VLDRS / VSTRS -> VLDRD / VSTRD unsigned Scale = 1; unsigned Opcode = Op0->getOpcode(); if (Opcode == ARM::LDRi12) { NewOpc = ARM::LDRD; } else if (Opcode == ARM::STRi12) { NewOpc = ARM::STRD; } else if (Opcode == ARM::t2LDRi8 || Opcode == ARM::t2LDRi12) { NewOpc = ARM::t2LDRDi8; Scale = 4; isT2 = true; } else if (Opcode == ARM::t2STRi8 || Opcode == ARM::t2STRi12) { NewOpc = ARM::t2STRDi8; Scale = 4; isT2 = true; } else { return false; } // Make sure the base address satisfies i64 ld / st alignment requirement. // At the moment, we ignore the memoryoperand's value. // If we want to use AliasAnalysis, we should check it accordingly. if (!Op0->hasOneMemOperand() || (*Op0->memoperands_begin())->isVolatile() || (*Op0->memoperands_begin())->isAtomic()) return false; Align Alignment = (*Op0->memoperands_begin())->getAlign(); const Function &Func = MF->getFunction(); Align ReqAlign = STI->hasV6Ops() ? TD->getABITypeAlign(Type::getInt64Ty(Func.getContext())) : Align(8); // Pre-v6 need 8-byte align if (Alignment < ReqAlign) return false; // Then make sure the immediate offset fits. int OffImm = getMemoryOpOffset(*Op0); if (isT2) { int Limit = (1 << 8) * Scale; if (OffImm >= Limit || (OffImm <= -Limit) || (OffImm & (Scale-1))) return false; Offset = OffImm; } else { ARM_AM::AddrOpc AddSub = ARM_AM::add; if (OffImm < 0) { AddSub = ARM_AM::sub; OffImm = - OffImm; } int Limit = (1 << 8) * Scale; if (OffImm >= Limit || (OffImm & (Scale-1))) return false; Offset = ARM_AM::getAM3Opc(AddSub, OffImm); } FirstReg = Op0->getOperand(0).getReg(); SecondReg = Op1->getOperand(0).getReg(); if (FirstReg == SecondReg) return false; BaseReg = Op0->getOperand(1).getReg(); Pred = getInstrPredicate(*Op0, PredReg); dl = Op0->getDebugLoc(); return true; } bool ARMPreAllocLoadStoreOpt::RescheduleOps(MachineBasicBlock *MBB, SmallVectorImpl<MachineInstr *> &Ops, unsigned Base, bool isLd, DenseMap<MachineInstr*, unsigned> &MI2LocMap) { bool RetVal = false; // Sort by offset (in reverse order). llvm::sort(Ops, [](const MachineInstr *LHS, const MachineInstr *RHS) { int LOffset = getMemoryOpOffset(*LHS); int ROffset = getMemoryOpOffset(*RHS); assert(LHS == RHS || LOffset != ROffset); return LOffset > ROffset; }); // The loads / stores of the same base are in order. Scan them from first to // last and check for the following: // 1. Any def of base. // 2. Any gaps. while (Ops.size() > 1) { unsigned FirstLoc = ~0U; unsigned LastLoc = 0; MachineInstr *FirstOp = nullptr; MachineInstr *LastOp = nullptr; int LastOffset = 0; unsigned LastOpcode = 0; unsigned LastBytes = 0; unsigned NumMove = 0; for (MachineInstr *Op : llvm::reverse(Ops)) { // Make sure each operation has the same kind. unsigned LSMOpcode = getLoadStoreMultipleOpcode(Op->getOpcode(), ARM_AM::ia); if (LastOpcode && LSMOpcode != LastOpcode) break; // Check that we have a continuous set of offsets. int Offset = getMemoryOpOffset(*Op); unsigned Bytes = getLSMultipleTransferSize(Op); if (LastBytes) { if (Bytes != LastBytes || Offset != (LastOffset + (int)Bytes)) break; } // Don't try to reschedule too many instructions. if (NumMove == InstReorderLimit) break; // Found a mergable instruction; save information about it. ++NumMove; LastOffset = Offset; LastBytes = Bytes; LastOpcode = LSMOpcode; unsigned Loc = MI2LocMap[Op]; if (Loc <= FirstLoc) { FirstLoc = Loc; FirstOp = Op; } if (Loc >= LastLoc) { LastLoc = Loc; LastOp = Op; } } if (NumMove <= 1) Ops.pop_back(); else { SmallPtrSet<MachineInstr*, 4> MemOps; SmallSet<unsigned, 4> MemRegs; for (size_t i = Ops.size() - NumMove, e = Ops.size(); i != e; ++i) { MemOps.insert(Ops[i]); MemRegs.insert(Ops[i]->getOperand(0).getReg()); } // Be conservative, if the instructions are too far apart, don't // move them. We want to limit the increase of register pressure. bool DoMove = (LastLoc - FirstLoc) <= NumMove*4; // FIXME: Tune this. if (DoMove) DoMove = IsSafeAndProfitableToMove(isLd, Base, FirstOp, LastOp, MemOps, MemRegs, TRI, AA); if (!DoMove) { for (unsigned i = 0; i != NumMove; ++i) Ops.pop_back(); } else { // This is the new location for the loads / stores. MachineBasicBlock::iterator InsertPos = isLd ? FirstOp : LastOp; while (InsertPos != MBB->end() && (MemOps.count(&*InsertPos) || InsertPos->isDebugInstr())) ++InsertPos; // If we are moving a pair of loads / stores, see if it makes sense // to try to allocate a pair of registers that can form register pairs. MachineInstr *Op0 = Ops.back(); MachineInstr *Op1 = Ops[Ops.size()-2]; Register FirstReg, SecondReg; Register BaseReg, PredReg; ARMCC::CondCodes Pred = ARMCC::AL; bool isT2 = false; unsigned NewOpc = 0; int Offset = 0; DebugLoc dl; if (NumMove == 2 && CanFormLdStDWord(Op0, Op1, dl, NewOpc, FirstReg, SecondReg, BaseReg, Offset, PredReg, Pred, isT2)) { Ops.pop_back(); Ops.pop_back(); const MCInstrDesc &MCID = TII->get(NewOpc); const TargetRegisterClass *TRC = TII->getRegClass(MCID, 0, TRI, *MF); MRI->constrainRegClass(FirstReg, TRC); MRI->constrainRegClass(SecondReg, TRC); // Form the pair instruction. if (isLd) { MachineInstrBuilder MIB = BuildMI(*MBB, InsertPos, dl, MCID) .addReg(FirstReg, RegState::Define) .addReg(SecondReg, RegState::Define) .addReg(BaseReg); // FIXME: We're converting from LDRi12 to an insn that still // uses addrmode2, so we need an explicit offset reg. It should // always by reg0 since we're transforming LDRi12s. if (!isT2) MIB.addReg(0); MIB.addImm(Offset).addImm(Pred).addReg(PredReg); MIB.cloneMergedMemRefs({Op0, Op1}); LLVM_DEBUG(dbgs() << "Formed " << *MIB << "\n"); ++NumLDRDFormed; } else { MachineInstrBuilder MIB = BuildMI(*MBB, InsertPos, dl, MCID) .addReg(FirstReg) .addReg(SecondReg) .addReg(BaseReg); // FIXME: We're converting from LDRi12 to an insn that still // uses addrmode2, so we need an explicit offset reg. It should // always by reg0 since we're transforming STRi12s. if (!isT2) MIB.addReg(0); MIB.addImm(Offset).addImm(Pred).addReg(PredReg); MIB.cloneMergedMemRefs({Op0, Op1}); LLVM_DEBUG(dbgs() << "Formed " << *MIB << "\n"); ++NumSTRDFormed; } MBB->erase(Op0); MBB->erase(Op1); if (!isT2) { // Add register allocation hints to form register pairs. MRI->setRegAllocationHint(FirstReg, ARMRI::RegPairEven, SecondReg); MRI->setRegAllocationHint(SecondReg, ARMRI::RegPairOdd, FirstReg); } } else { for (unsigned i = 0; i != NumMove; ++i) { MachineInstr *Op = Ops.pop_back_val(); MBB->splice(InsertPos, MBB, Op); } } NumLdStMoved += NumMove; RetVal = true; } } } return RetVal; } bool ARMPreAllocLoadStoreOpt::RescheduleLoadStoreInstrs(MachineBasicBlock *MBB) { bool RetVal = false; DenseMap<MachineInstr*, unsigned> MI2LocMap; using MapIt = DenseMap<unsigned, SmallVector<MachineInstr *, 4>>::iterator; using Base2InstMap = DenseMap<unsigned, SmallVector<MachineInstr *, 4>>; using BaseVec = SmallVector<unsigned, 4>; Base2InstMap Base2LdsMap; Base2InstMap Base2StsMap; BaseVec LdBases; BaseVec StBases; unsigned Loc = 0; MachineBasicBlock::iterator MBBI = MBB->begin(); MachineBasicBlock::iterator E = MBB->end(); while (MBBI != E) { for (; MBBI != E; ++MBBI) { MachineInstr &MI = *MBBI; if (MI.isCall() || MI.isTerminator()) { // Stop at barriers. ++MBBI; break; } if (!MI.isDebugInstr()) MI2LocMap[&MI] = ++Loc; if (!isMemoryOp(MI)) continue; Register PredReg; if (getInstrPredicate(MI, PredReg) != ARMCC::AL) continue; int Opc = MI.getOpcode(); bool isLd = isLoadSingle(Opc); Register Base = MI.getOperand(1).getReg(); int Offset = getMemoryOpOffset(MI); bool StopHere = false; auto FindBases = [&] (Base2InstMap &Base2Ops, BaseVec &Bases) { MapIt BI = Base2Ops.find(Base); if (BI == Base2Ops.end()) { Base2Ops[Base].push_back(&MI); Bases.push_back(Base); return; } for (unsigned i = 0, e = BI->second.size(); i != e; ++i) { if (Offset == getMemoryOpOffset(*BI->second[i])) { StopHere = true; break; } } if (!StopHere) BI->second.push_back(&MI); }; if (isLd) FindBases(Base2LdsMap, LdBases); else FindBases(Base2StsMap, StBases); if (StopHere) { // Found a duplicate (a base+offset combination that's seen earlier). // Backtrack. --Loc; break; } } // Re-schedule loads. for (unsigned i = 0, e = LdBases.size(); i != e; ++i) { unsigned Base = LdBases[i]; SmallVectorImpl<MachineInstr *> &Lds = Base2LdsMap[Base]; if (Lds.size() > 1) RetVal |= RescheduleOps(MBB, Lds, Base, true, MI2LocMap); } // Re-schedule stores. for (unsigned i = 0, e = StBases.size(); i != e; ++i) { unsigned Base = StBases[i]; SmallVectorImpl<MachineInstr *> &Sts = Base2StsMap[Base]; if (Sts.size() > 1) RetVal |= RescheduleOps(MBB, Sts, Base, false, MI2LocMap); } if (MBBI != E) { Base2LdsMap.clear(); Base2StsMap.clear(); LdBases.clear(); StBases.clear(); } } return RetVal; } // Get the Base register operand index from the memory access MachineInst if we // should attempt to distribute postinc on it. Return -1 if not of a valid // instruction type. If it returns an index, it is assumed that instruction is a // r+i indexing mode, and getBaseOperandIndex() + 1 is the Offset index. static int getBaseOperandIndex(MachineInstr &MI) { switch (MI.getOpcode()) { case ARM::MVE_VLDRBS16: case ARM::MVE_VLDRBS32: case ARM::MVE_VLDRBU16: case ARM::MVE_VLDRBU32: case ARM::MVE_VLDRHS32: case ARM::MVE_VLDRHU32: case ARM::MVE_VLDRBU8: case ARM::MVE_VLDRHU16: case ARM::MVE_VLDRWU32: case ARM::MVE_VSTRB16: case ARM::MVE_VSTRB32: case ARM::MVE_VSTRH32: case ARM::MVE_VSTRBU8: case ARM::MVE_VSTRHU16: case ARM::MVE_VSTRWU32: case ARM::t2LDRHi8: case ARM::t2LDRHi12: case ARM::t2LDRSHi8: case ARM::t2LDRSHi12: case ARM::t2LDRBi8: case ARM::t2LDRBi12: case ARM::t2LDRSBi8: case ARM::t2LDRSBi12: case ARM::t2STRBi8: case ARM::t2STRBi12: case ARM::t2STRHi8: case ARM::t2STRHi12: return 1; case ARM::MVE_VLDRBS16_post: case ARM::MVE_VLDRBS32_post: case ARM::MVE_VLDRBU16_post: case ARM::MVE_VLDRBU32_post: case ARM::MVE_VLDRHS32_post: case ARM::MVE_VLDRHU32_post: case ARM::MVE_VLDRBU8_post: case ARM::MVE_VLDRHU16_post: case ARM::MVE_VLDRWU32_post: case ARM::MVE_VSTRB16_post: case ARM::MVE_VSTRB32_post: case ARM::MVE_VSTRH32_post: case ARM::MVE_VSTRBU8_post: case ARM::MVE_VSTRHU16_post: case ARM::MVE_VSTRWU32_post: case ARM::MVE_VLDRBS16_pre: case ARM::MVE_VLDRBS32_pre: case ARM::MVE_VLDRBU16_pre: case ARM::MVE_VLDRBU32_pre: case ARM::MVE_VLDRHS32_pre: case ARM::MVE_VLDRHU32_pre: case ARM::MVE_VLDRBU8_pre: case ARM::MVE_VLDRHU16_pre: case ARM::MVE_VLDRWU32_pre: case ARM::MVE_VSTRB16_pre: case ARM::MVE_VSTRB32_pre: case ARM::MVE_VSTRH32_pre: case ARM::MVE_VSTRBU8_pre: case ARM::MVE_VSTRHU16_pre: case ARM::MVE_VSTRWU32_pre: return 2; } return -1; } static bool isPostIndex(MachineInstr &MI) { switch (MI.getOpcode()) { case ARM::MVE_VLDRBS16_post: case ARM::MVE_VLDRBS32_post: case ARM::MVE_VLDRBU16_post: case ARM::MVE_VLDRBU32_post: case ARM::MVE_VLDRHS32_post: case ARM::MVE_VLDRHU32_post: case ARM::MVE_VLDRBU8_post: case ARM::MVE_VLDRHU16_post: case ARM::MVE_VLDRWU32_post: case ARM::MVE_VSTRB16_post: case ARM::MVE_VSTRB32_post: case ARM::MVE_VSTRH32_post: case ARM::MVE_VSTRBU8_post: case ARM::MVE_VSTRHU16_post: case ARM::MVE_VSTRWU32_post: return true; } return false; } static bool isPreIndex(MachineInstr &MI) { switch (MI.getOpcode()) { case ARM::MVE_VLDRBS16_pre: case ARM::MVE_VLDRBS32_pre: case ARM::MVE_VLDRBU16_pre: case ARM::MVE_VLDRBU32_pre: case ARM::MVE_VLDRHS32_pre: case ARM::MVE_VLDRHU32_pre: case ARM::MVE_VLDRBU8_pre: case ARM::MVE_VLDRHU16_pre: case ARM::MVE_VLDRWU32_pre: case ARM::MVE_VSTRB16_pre: case ARM::MVE_VSTRB32_pre: case ARM::MVE_VSTRH32_pre: case ARM::MVE_VSTRBU8_pre: case ARM::MVE_VSTRHU16_pre: case ARM::MVE_VSTRWU32_pre: return true; } return false; } // Given a memory access Opcode, check that the give Imm would be a valid Offset // for this instruction (same as isLegalAddressImm), Or if the instruction // could be easily converted to one where that was valid. For example converting // t2LDRi12 to t2LDRi8 for negative offsets. Works in conjunction with // AdjustBaseAndOffset below. static bool isLegalOrConvertableAddressImm(unsigned Opcode, int Imm, const TargetInstrInfo *TII, int &CodesizeEstimate) { if (isLegalAddressImm(Opcode, Imm, TII)) return true; // We can convert AddrModeT2_i12 to AddrModeT2_i8neg. const MCInstrDesc &Desc = TII->get(Opcode); unsigned AddrMode = (Desc.TSFlags & ARMII::AddrModeMask); switch (AddrMode) { case ARMII::AddrModeT2_i12: CodesizeEstimate += 1; return Imm < 0 && -Imm < ((1 << 8) * 1); } return false; } // Given an MI adjust its address BaseReg to use NewBaseReg and address offset // by -Offset. This can either happen in-place or be a replacement as MI is // converted to another instruction type. static void AdjustBaseAndOffset(MachineInstr *MI, Register NewBaseReg, int Offset, const TargetInstrInfo *TII, const TargetRegisterInfo *TRI) { // Set the Base reg unsigned BaseOp = getBaseOperandIndex(*MI); MI->getOperand(BaseOp).setReg(NewBaseReg); // and constrain the reg class to that required by the instruction. MachineFunction *MF = MI->getMF(); MachineRegisterInfo &MRI = MF->getRegInfo(); const MCInstrDesc &MCID = TII->get(MI->getOpcode()); const TargetRegisterClass *TRC = TII->getRegClass(MCID, BaseOp, TRI, *MF); MRI.constrainRegClass(NewBaseReg, TRC); int OldOffset = MI->getOperand(BaseOp + 1).getImm(); if (isLegalAddressImm(MI->getOpcode(), OldOffset - Offset, TII)) MI->getOperand(BaseOp + 1).setImm(OldOffset - Offset); else { unsigned ConvOpcode; switch (MI->getOpcode()) { case ARM::t2LDRHi12: ConvOpcode = ARM::t2LDRHi8; break; case ARM::t2LDRSHi12: ConvOpcode = ARM::t2LDRSHi8; break; case ARM::t2LDRBi12: ConvOpcode = ARM::t2LDRBi8; break; case ARM::t2LDRSBi12: ConvOpcode = ARM::t2LDRSBi8; break; case ARM::t2STRHi12: ConvOpcode = ARM::t2STRHi8; break; case ARM::t2STRBi12: ConvOpcode = ARM::t2STRBi8; break; default: llvm_unreachable("Unhandled convertable opcode"); } assert(isLegalAddressImm(ConvOpcode, OldOffset - Offset, TII) && "Illegal Address Immediate after convert!"); const MCInstrDesc &MCID = TII->get(ConvOpcode); BuildMI(*MI->getParent(), MI, MI->getDebugLoc(), MCID) .add(MI->getOperand(0)) .add(MI->getOperand(1)) .addImm(OldOffset - Offset) .add(MI->getOperand(3)) .add(MI->getOperand(4)) .cloneMemRefs(*MI); MI->eraseFromParent(); } } static MachineInstr *createPostIncLoadStore(MachineInstr *MI, int Offset, Register NewReg, const TargetInstrInfo *TII, const TargetRegisterInfo *TRI) { MachineFunction *MF = MI->getMF(); MachineRegisterInfo &MRI = MF->getRegInfo(); unsigned NewOpcode = getPostIndexedLoadStoreOpcode( MI->getOpcode(), Offset > 0 ? ARM_AM::add : ARM_AM::sub); const MCInstrDesc &MCID = TII->get(NewOpcode); // Constrain the def register class const TargetRegisterClass *TRC = TII->getRegClass(MCID, 0, TRI, *MF); MRI.constrainRegClass(NewReg, TRC); // And do the same for the base operand TRC = TII->getRegClass(MCID, 2, TRI, *MF); MRI.constrainRegClass(MI->getOperand(1).getReg(), TRC); unsigned AddrMode = (MCID.TSFlags & ARMII::AddrModeMask); switch (AddrMode) { case ARMII::AddrModeT2_i7: case ARMII::AddrModeT2_i7s2: case ARMII::AddrModeT2_i7s4: // Any MVE load/store return BuildMI(*MI->getParent(), MI, MI->getDebugLoc(), MCID) .addReg(NewReg, RegState::Define) .add(MI->getOperand(0)) .add(MI->getOperand(1)) .addImm(Offset) .add(MI->getOperand(3)) .add(MI->getOperand(4)) .add(MI->getOperand(5)) .cloneMemRefs(*MI); case ARMII::AddrModeT2_i8: if (MI->mayLoad()) { return BuildMI(*MI->getParent(), MI, MI->getDebugLoc(), MCID) .add(MI->getOperand(0)) .addReg(NewReg, RegState::Define) .add(MI->getOperand(1)) .addImm(Offset) .add(MI->getOperand(3)) .add(MI->getOperand(4)) .cloneMemRefs(*MI); } else { return BuildMI(*MI->getParent(), MI, MI->getDebugLoc(), MCID) .addReg(NewReg, RegState::Define) .add(MI->getOperand(0)) .add(MI->getOperand(1)) .addImm(Offset) .add(MI->getOperand(3)) .add(MI->getOperand(4)) .cloneMemRefs(*MI); } default: llvm_unreachable("Unhandled createPostIncLoadStore"); } } // Given a Base Register, optimise the load/store uses to attempt to create more // post-inc accesses and less register moves. We do this by taking zero offset // loads/stores with an add, and convert them to a postinc load/store of the // same type. Any subsequent accesses will be adjusted to use and account for // the post-inc value. // For example: // LDR #0 LDR_POSTINC #16 // LDR #4 LDR #-12 // LDR #8 LDR #-8 // LDR #12 LDR #-4 // ADD #16 // // At the same time if we do not find an increment but do find an existing // pre/post inc instruction, we can still adjust the offsets of subsequent // instructions to save the register move that would otherwise be needed for the // in-place increment. bool ARMPreAllocLoadStoreOpt::DistributeIncrements(Register Base) { // We are looking for: // One zero offset load/store that can become postinc MachineInstr *BaseAccess = nullptr; MachineInstr *PrePostInc = nullptr; // An increment that can be folded in MachineInstr *Increment = nullptr; // Other accesses after BaseAccess that will need to be updated to use the // postinc value. SmallPtrSet<MachineInstr *, 8> OtherAccesses; for (auto &Use : MRI->use_nodbg_instructions(Base)) { if (!Increment && getAddSubImmediate(Use) != 0) { Increment = &Use; continue; } int BaseOp = getBaseOperandIndex(Use); if (BaseOp == -1) return false; if (!Use.getOperand(BaseOp).isReg() || Use.getOperand(BaseOp).getReg() != Base) return false; if (isPreIndex(Use) || isPostIndex(Use)) PrePostInc = &Use; else if (Use.getOperand(BaseOp + 1).getImm() == 0) BaseAccess = &Use; else OtherAccesses.insert(&Use); } int IncrementOffset; Register NewBaseReg; if (BaseAccess && Increment) { if (PrePostInc || BaseAccess->getParent() != Increment->getParent()) return false; Register PredReg; if (Increment->definesRegister(ARM::CPSR) || getInstrPredicate(*Increment, PredReg) != ARMCC::AL) return false; LLVM_DEBUG(dbgs() << "\nAttempting to distribute increments on VirtualReg " << Base.virtRegIndex() << "\n"); // Make sure that Increment has no uses before BaseAccess. for (MachineInstr &Use : MRI->use_nodbg_instructions(Increment->getOperand(0).getReg())) { if (!DT->dominates(BaseAccess, &Use) || &Use == BaseAccess) { LLVM_DEBUG(dbgs() << " BaseAccess doesn't dominate use of increment\n"); return false; } } // Make sure that Increment can be folded into Base IncrementOffset = getAddSubImmediate(*Increment); unsigned NewPostIncOpcode = getPostIndexedLoadStoreOpcode( BaseAccess->getOpcode(), IncrementOffset > 0 ? ARM_AM::add : ARM_AM::sub); if (!isLegalAddressImm(NewPostIncOpcode, IncrementOffset, TII)) { LLVM_DEBUG(dbgs() << " Illegal addressing mode immediate on postinc\n"); return false; } } else if (PrePostInc) { // If we already have a pre/post index load/store then set BaseAccess, // IncrementOffset and NewBaseReg to the values it already produces, // allowing us to update and subsequent uses of BaseOp reg with the // incremented value. if (Increment) return false; LLVM_DEBUG(dbgs() << "\nAttempting to distribute increments on already " << "indexed VirtualReg " << Base.virtRegIndex() << "\n"); int BaseOp = getBaseOperandIndex(*PrePostInc); IncrementOffset = PrePostInc->getOperand(BaseOp+1).getImm(); BaseAccess = PrePostInc; NewBaseReg = PrePostInc->getOperand(0).getReg(); } else return false; // And make sure that the negative value of increment can be added to all // other offsets after the BaseAccess. We rely on either // dominates(BaseAccess, OtherAccess) or dominates(OtherAccess, BaseAccess) // to keep things simple. // This also adds a simple codesize metric, to detect if an instruction (like // t2LDRBi12) which can often be shrunk to a thumb1 instruction (tLDRBi) // cannot because it is converted to something else (t2LDRBi8). We start this // at -1 for the gain from removing the increment. SmallPtrSet<MachineInstr *, 4> SuccessorAccesses; int CodesizeEstimate = -1; for (auto *Use : OtherAccesses) { if (DT->dominates(BaseAccess, Use)) { SuccessorAccesses.insert(Use); unsigned BaseOp = getBaseOperandIndex(*Use); if (!isLegalOrConvertableAddressImm(Use->getOpcode(), Use->getOperand(BaseOp + 1).getImm() - IncrementOffset, TII, CodesizeEstimate)) { LLVM_DEBUG(dbgs() << " Illegal addressing mode immediate on use\n"); return false; } } else if (!DT->dominates(Use, BaseAccess)) { LLVM_DEBUG( dbgs() << " Unknown dominance relation between Base and Use\n"); return false; } } if (STI->hasMinSize() && CodesizeEstimate > 0) { LLVM_DEBUG(dbgs() << " Expected to grow instructions under minsize\n"); return false; } if (!PrePostInc) { // Replace BaseAccess with a post inc LLVM_DEBUG(dbgs() << "Changing: "; BaseAccess->dump()); LLVM_DEBUG(dbgs() << " And : "; Increment->dump()); NewBaseReg = Increment->getOperand(0).getReg(); MachineInstr *BaseAccessPost = createPostIncLoadStore(BaseAccess, IncrementOffset, NewBaseReg, TII, TRI); BaseAccess->eraseFromParent(); Increment->eraseFromParent(); (void)BaseAccessPost; LLVM_DEBUG(dbgs() << " To : "; BaseAccessPost->dump()); } for (auto *Use : SuccessorAccesses) { LLVM_DEBUG(dbgs() << "Changing: "; Use->dump()); AdjustBaseAndOffset(Use, NewBaseReg, IncrementOffset, TII, TRI); LLVM_DEBUG(dbgs() << " To : "; Use->dump()); } // Remove the kill flag from all uses of NewBaseReg, in case any old uses // remain. for (MachineOperand &Op : MRI->use_nodbg_operands(NewBaseReg)) Op.setIsKill(false); return true; } bool ARMPreAllocLoadStoreOpt::DistributeIncrements() { bool Changed = false; SmallSetVector<Register, 4> Visited; for (auto &MBB : *MF) { for (auto &MI : MBB) { int BaseOp = getBaseOperandIndex(MI); if (BaseOp == -1 || !MI.getOperand(BaseOp).isReg()) continue; Register Base = MI.getOperand(BaseOp).getReg(); if (!Base.isVirtual() || Visited.count(Base)) continue; Visited.insert(Base); } } for (auto Base : Visited) Changed |= DistributeIncrements(Base); return Changed; } /// Returns an instance of the load / store optimization pass. FunctionPass *llvm::createARMLoadStoreOptimizationPass(bool PreAlloc) { if (PreAlloc) return new ARMPreAllocLoadStoreOpt(); return new ARMLoadStoreOpt(); }
utf-8
1
unknown
unknown
linux-5.16.7/sound/pci/ac97/ac97_patch.h
/* SPDX-License-Identifier: GPL-2.0-or-later */ /* * Copyright (c) by Jaroslav Kysela <perex@perex.cz> * Universal interface for Audio Codec '97 * * For more details look to AC '97 component specification revision 2.2 * by Intel Corporation (http://developer.intel.com). */ #define AC97_SINGLE_VALUE(reg,shift,mask,invert) \ ((reg) | ((shift) << 8) | ((shift) << 12) | ((mask) << 16) | \ ((invert) << 24)) #define AC97_PAGE_SINGLE_VALUE(reg,shift,mask,invert,page) \ (AC97_SINGLE_VALUE(reg,shift,mask,invert) | (1<<25) | ((page) << 26)) #define AC97_SINGLE(xname, reg, shift, mask, invert) \ { .iface = SNDRV_CTL_ELEM_IFACE_MIXER, .name = xname, \ .info = snd_ac97_info_volsw, \ .get = snd_ac97_get_volsw, .put = snd_ac97_put_volsw, \ .private_value = AC97_SINGLE_VALUE(reg, shift, mask, invert) } #define AC97_PAGE_SINGLE(xname, reg, shift, mask, invert, page) \ { .iface = SNDRV_CTL_ELEM_IFACE_MIXER, .name = xname, \ .info = snd_ac97_info_volsw, \ .get = snd_ac97_get_volsw, .put = snd_ac97_put_volsw, \ .private_value = AC97_PAGE_SINGLE_VALUE(reg, shift, mask, invert, page) } #define AC97_DOUBLE(xname, reg, shift_left, shift_right, mask, invert) \ { .iface = SNDRV_CTL_ELEM_IFACE_MIXER, .name = (xname), \ .info = snd_ac97_info_volsw, \ .get = snd_ac97_get_volsw, .put = snd_ac97_put_volsw, \ .private_value = (reg) | ((shift_left) << 8) | ((shift_right) << 12) | ((mask) << 16) | ((invert) << 24) } /* enum control */ struct ac97_enum { unsigned char reg; unsigned char shift_l; unsigned char shift_r; unsigned short mask; const char * const *texts; }; #define AC97_ENUM_DOUBLE(xreg, xshift_l, xshift_r, xmask, xtexts) \ { .reg = xreg, .shift_l = xshift_l, .shift_r = xshift_r, \ .mask = xmask, .texts = xtexts } #define AC97_ENUM_SINGLE(xreg, xshift, xmask, xtexts) \ AC97_ENUM_DOUBLE(xreg, xshift, xshift, xmask, xtexts) #define AC97_ENUM(xname, xenum) \ { .iface = SNDRV_CTL_ELEM_IFACE_MIXER, .name = xname, \ .info = snd_ac97_info_enum_double, \ .get = snd_ac97_get_enum_double, .put = snd_ac97_put_enum_double, \ .private_value = (unsigned long)&xenum } /* ac97_codec.c */ static const struct snd_kcontrol_new snd_ac97_controls_3d[]; static const struct snd_kcontrol_new snd_ac97_controls_spdif[]; static struct snd_kcontrol *snd_ac97_cnew(const struct snd_kcontrol_new *_template, struct snd_ac97 * ac97); static int snd_ac97_info_volsw(struct snd_kcontrol *kcontrol, struct snd_ctl_elem_info *uinfo); static int snd_ac97_get_volsw(struct snd_kcontrol *kcontrol, struct snd_ctl_elem_value *ucontrol); static int snd_ac97_put_volsw(struct snd_kcontrol *kcontrol, struct snd_ctl_elem_value *ucontrol); static int snd_ac97_try_bit(struct snd_ac97 * ac97, int reg, int bit); static int snd_ac97_remove_ctl(struct snd_ac97 *ac97, const char *name, const char *suffix); static int snd_ac97_rename_ctl(struct snd_ac97 *ac97, const char *src, const char *dst, const char *suffix); static int snd_ac97_swap_ctl(struct snd_ac97 *ac97, const char *s1, const char *s2, const char *suffix); static void snd_ac97_rename_vol_ctl(struct snd_ac97 *ac97, const char *src, const char *dst); #ifdef CONFIG_PM static void snd_ac97_restore_status(struct snd_ac97 *ac97); static void snd_ac97_restore_iec958(struct snd_ac97 *ac97); #endif static int snd_ac97_info_enum_double(struct snd_kcontrol *kcontrol, struct snd_ctl_elem_info *uinfo); static int snd_ac97_get_enum_double(struct snd_kcontrol *kcontrol, struct snd_ctl_elem_value *ucontrol); static int snd_ac97_put_enum_double(struct snd_kcontrol *kcontrol, struct snd_ctl_elem_value *ucontrol);
utf-8
1
GPL-2
1991-2012 Linus Torvalds and many others
box2d-2.4.1/src/collision/b2_chain_shape.cpp
// MIT License // Copyright (c) 2019 Erin Catto // 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 "box2d/b2_chain_shape.h" #include "box2d/b2_edge_shape.h" #include "box2d/b2_block_allocator.h" #include <new> #include <string.h> b2ChainShape::~b2ChainShape() { Clear(); } void b2ChainShape::Clear() { b2Free(m_vertices); m_vertices = nullptr; m_count = 0; } void b2ChainShape::CreateLoop(const b2Vec2* vertices, int32 count) { b2Assert(m_vertices == nullptr && m_count == 0); b2Assert(count >= 3); if (count < 3) { return; } for (int32 i = 1; i < count; ++i) { b2Vec2 v1 = vertices[i-1]; b2Vec2 v2 = vertices[i]; // If the code crashes here, it means your vertices are too close together. b2Assert(b2DistanceSquared(v1, v2) > b2_linearSlop * b2_linearSlop); } m_count = count + 1; m_vertices = (b2Vec2*)b2Alloc(m_count * sizeof(b2Vec2)); memcpy(m_vertices, vertices, count * sizeof(b2Vec2)); m_vertices[count] = m_vertices[0]; m_prevVertex = m_vertices[m_count - 2]; m_nextVertex = m_vertices[1]; } void b2ChainShape::CreateChain(const b2Vec2* vertices, int32 count, const b2Vec2& prevVertex, const b2Vec2& nextVertex) { b2Assert(m_vertices == nullptr && m_count == 0); b2Assert(count >= 2); for (int32 i = 1; i < count; ++i) { // If the code crashes here, it means your vertices are too close together. b2Assert(b2DistanceSquared(vertices[i-1], vertices[i]) > b2_linearSlop * b2_linearSlop); } m_count = count; m_vertices = (b2Vec2*)b2Alloc(count * sizeof(b2Vec2)); memcpy(m_vertices, vertices, m_count * sizeof(b2Vec2)); m_prevVertex = prevVertex; m_nextVertex = nextVertex; } b2Shape* b2ChainShape::Clone(b2BlockAllocator* allocator) const { void* mem = allocator->Allocate(sizeof(b2ChainShape)); b2ChainShape* clone = new (mem) b2ChainShape; clone->CreateChain(m_vertices, m_count, m_prevVertex, m_nextVertex); return clone; } int32 b2ChainShape::GetChildCount() const { // edge count = vertex count - 1 return m_count - 1; } void b2ChainShape::GetChildEdge(b2EdgeShape* edge, int32 index) const { b2Assert(0 <= index && index < m_count - 1); edge->m_type = b2Shape::e_edge; edge->m_radius = m_radius; edge->m_vertex1 = m_vertices[index + 0]; edge->m_vertex2 = m_vertices[index + 1]; edge->m_oneSided = true; if (index > 0) { edge->m_vertex0 = m_vertices[index - 1]; } else { edge->m_vertex0 = m_prevVertex; } if (index < m_count - 2) { edge->m_vertex3 = m_vertices[index + 2]; } else { edge->m_vertex3 = m_nextVertex; } } bool b2ChainShape::TestPoint(const b2Transform& xf, const b2Vec2& p) const { B2_NOT_USED(xf); B2_NOT_USED(p); return false; } bool b2ChainShape::RayCast(b2RayCastOutput* output, const b2RayCastInput& input, const b2Transform& xf, int32 childIndex) const { b2Assert(childIndex < m_count); b2EdgeShape edgeShape; int32 i1 = childIndex; int32 i2 = childIndex + 1; if (i2 == m_count) { i2 = 0; } edgeShape.m_vertex1 = m_vertices[i1]; edgeShape.m_vertex2 = m_vertices[i2]; return edgeShape.RayCast(output, input, xf, 0); } void b2ChainShape::ComputeAABB(b2AABB* aabb, const b2Transform& xf, int32 childIndex) const { b2Assert(childIndex < m_count); int32 i1 = childIndex; int32 i2 = childIndex + 1; if (i2 == m_count) { i2 = 0; } b2Vec2 v1 = b2Mul(xf, m_vertices[i1]); b2Vec2 v2 = b2Mul(xf, m_vertices[i2]); b2Vec2 lower = b2Min(v1, v2); b2Vec2 upper = b2Max(v1, v2); b2Vec2 r(m_radius, m_radius); aabb->lowerBound = lower - r; aabb->upperBound = upper + r; } void b2ChainShape::ComputeMass(b2MassData* massData, float density) const { B2_NOT_USED(density); massData->mass = 0.0f; massData->center.SetZero(); massData->I = 0.0f; }
utf-8
1
Expat
2006-2020, Erin Catto and contributors 2009-2010, Mikko Mononen
doomsday-2.3.1+ds1/doomsday/apps/plugins/doom/src/d_main.cpp
/** @file d_main.cpp Doom-specific game initialization. * * @authors Copyright © 2003-2017 Jaakko Keränen <jaakko.keranen@iki.fi> * @authors Copyright © 2005-2013 Daniel Swanson <danij@dengine.net> * @authors Copyright © 2006 Jamie Jones <yagisan@dengine.net> * @authors Copyright © 1993-1996 id Software, Inc. * * @par License * GPL: http://www.gnu.org/licenses/gpl.html * * <small>This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by the * Free Software Foundation; either version 2 of the License, or (at your * option) any later version. This program is distributed in the hope that it * will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty * of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General * Public License for more details. You should have received a copy of the GNU * General Public License along with this program; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA</small> */ #include "jdoom.h" #include <de/App> #include <de/CommandLine> #include "d_netsv.h" #include "doomv9mapstatereader.h" #include "g_defs.h" #include "gamesession.h" #include "hu_menu.h" #include "hu_stuff.h" #include "hud/widgets/automapwidget.h" #include "m_argv.h" #include "p_map.h" #include "saveslots.h" #include "r_common.h" using namespace de; using namespace common; gamemode_t gameMode; int gameModeBits; // Default font colors. float defFontRGB[3]; float defFontRGB2[3]; float defFontRGB3[3]; // The patches used in drawing the view border. // Percent-encoded. char const *borderGraphics[] = { "Flats:FLOOR7_2", // Background. "BRDR_T", // Top. "BRDR_R", // Right. "BRDR_B", // Bottom. "BRDR_L", // Left. "BRDR_TL", // Top left. "BRDR_TR", // Top right. "BRDR_BR", // Bottom right. "BRDR_BL" // Bottom left. }; int D_GetInteger(int id) { return Common_GetInteger(id); } void *D_GetVariable(int id) { static float bob[2]; switch(id) { case DD_PLUGIN_NAME: return (void*)PLUGIN_NAMETEXT; case DD_PLUGIN_NICENAME: return (void*)PLUGIN_NICENAME; case DD_PLUGIN_VERSION_SHORT: return (void*)PLUGIN_VERSION_TEXT; case DD_PLUGIN_VERSION_LONG: return (void*)(PLUGIN_VERSION_TEXTLONG "\n" PLUGIN_DETAILS); case DD_PLUGIN_HOMEURL: return (void*)PLUGIN_HOMEURL; case DD_PLUGIN_DOCSURL: return (void*)PLUGIN_DOCSURL; case DD_GAME_CONFIG: return gameConfigString; case DD_ACTION_LINK: return actionlinks; case DD_XGFUNC_LINK: return xgClasses; case DD_PSPRITE_BOB_X: R_GetWeaponBob(DISPLAYPLAYER, &bob[0], 0); return &bob[0]; case DD_PSPRITE_BOB_Y: R_GetWeaponBob(DISPLAYPLAYER, 0, &bob[1]); return &bob[1]; case DD_TM_FLOOR_Z: return (void*) &tmFloorZ; case DD_TM_CEILING_Z: return (void*) &tmCeilingZ; default: break; } return 0; } void D_PreInit() { // Configure default colors: switch(gameMode) { case doom2_hacx: defFontRGB[CR] = .85f; defFontRGB[CG] = 0; defFontRGB[CB] = 0; defFontRGB2[CR] = .2f; defFontRGB2[CG] = .9f; defFontRGB2[CB] = .2f; defFontRGB3[CR] = .2f; defFontRGB3[CG] = .9f; defFontRGB3[CB] = .2f; break; case doom_chex: defFontRGB[CR] = .46f; defFontRGB[CG] = 1; defFontRGB[CB] = .4f; defFontRGB2[CR] = .46f; defFontRGB2[CG] = 1; defFontRGB2[CB] = .4f; defFontRGB3[CR] = 1; defFontRGB3[CG] = 1; defFontRGB3[CB] = .45f; break; default: defFontRGB[CR] = 1; defFontRGB[CG] = 1; defFontRGB[CB] = 1; defFontRGB2[CR] = .85f; defFontRGB2[CG] = 0; defFontRGB2[CB] = 0; defFontRGB3[CR] = 1; defFontRGB3[CG] = .9f; defFontRGB3[CB] = .4f; break; } // Config defaults. The real settings are read from the .cfg files // but these will be used no such files are found. memset(&cfg, 0, sizeof(cfg)); cfg.common.playerMoveSpeed = 1; cfg.common.povLookAround = true; cfg.common.screenBlocks = cfg.common.setBlocks = 10; cfg.common.echoMsg = true; cfg.common.lookSpeed = 3; cfg.common.turnSpeed = 1; cfg.common.menuPatchReplaceMode = PRM_ALLOW_TEXT; cfg.common.menuScale = .9f; cfg.common.menuTextGlitter = .5f; cfg.common.menuShadow = 0.33f; cfg.menuQuitSound = true; cfg.common.menuSlam = false; cfg.common.menuShortcutsEnabled = true; cfg.common.menuGameSaveSuggestDescription = true; cfg.common.menuEffectFlags = MEF_TEXT_TYPEIN | MEF_TEXT_SHADOW | MEF_TEXT_GLITTER; cfg.common.menuTextFlashColor[0] = .7f; cfg.common.menuTextFlashColor[1] = .9f; cfg.common.menuTextFlashColor[2] = 1; cfg.common.menuTextFlashSpeed = 4; if(gameMode != doom_chex) { cfg.common.menuCursorRotate = true; } if(gameMode == doom2_hacx) { cfg.common.menuTextColors[0][CR] = cfg.common.menuTextColors[0][CG] = cfg.common.menuTextColors[0][CB] = 1; memcpy(cfg.common.menuTextColors[1], defFontRGB, sizeof(cfg.common.menuTextColors[1])); cfg.common.menuTextColors[2][CR] = cfg.common.menuTextColors[3][CR] = .2f; cfg.common.menuTextColors[2][CG] = cfg.common.menuTextColors[3][CG] = .2f; cfg.common.menuTextColors[2][CB] = cfg.common.menuTextColors[3][CB] = .9f; } else { memcpy(cfg.common.menuTextColors[0], defFontRGB2, sizeof(cfg.common.menuTextColors[0])); if(gameMode == doom_chex) { cfg.common.menuTextColors[1][CR] = .85f; cfg.common.menuTextColors[1][CG] = .3f; cfg.common.menuTextColors[1][CB] = .3f; } else { cfg.common.menuTextColors[1][CR] = 1.f; cfg.common.menuTextColors[1][CG] = .7f; cfg.common.menuTextColors[1][CB] = .3f; } memcpy(cfg.common.menuTextColors[2], defFontRGB, sizeof(cfg.common.menuTextColors[2])); memcpy(cfg.common.menuTextColors[3], defFontRGB2, sizeof(cfg.common.menuTextColors[3])); } cfg.common.inludePatchReplaceMode = PRM_ALLOW_TEXT; cfg.common.hudPatchReplaceMode = PRM_ALLOW_TEXT; cfg.hudKeysCombine = false; cfg.hudShown[HUD_HEALTH] = true; cfg.hudShown[HUD_ARMOR] = true; cfg.hudShown[HUD_AMMO] = true; cfg.hudShown[HUD_KEYS] = true; cfg.hudShown[HUD_FRAGS] = true; cfg.hudShown[HUD_FACE] = false; cfg.hudShown[HUD_LOG] = true; for(int i = 0; i < NUMHUDUNHIDEEVENTS; ++i) // when the hud/statusbar unhides. { cfg.hudUnHide[i] = 1; } cfg.common.hudScale = .6f; memcpy(cfg.common.hudColor, defFontRGB2, MIN_OF(sizeof(defFontRGB2), sizeof(cfg.common.hudColor))); cfg.common.hudColor[CA] = 1; cfg.common.hudFog = 5; cfg.common.hudIconAlpha = 1; cfg.common.xhairAngle = 0; cfg.common.xhairSize = .5f; cfg.common.xhairLineWidth = 1; cfg.common.xhairVitality = false; cfg.common.xhairColor[0] = 1; cfg.common.xhairColor[1] = 1; cfg.common.xhairColor[2] = 1; cfg.common.xhairColor[3] = 1; cfg.common.filterStrength = .8f; cfg.moveCheckZ = true; cfg.common.jumpPower = 9; cfg.common.airborneMovement = 1; cfg.common.weaponAutoSwitch = 1; // if better cfg.common.noWeaponAutoSwitchIfFiring = false; cfg.common.ammoAutoSwitch = 0; // never cfg.secretMsg = true; cfg.slidingCorpses = false; //cfg.fastMonsters = false; cfg.common.netJumping = true; cfg.common.netEpisode = (char *) ""; cfg.common.netMap = 0; cfg.common.netSkill = SM_MEDIUM; cfg.common.netColor = 4; cfg.netBFGFreeLook = 0; // allow free-aim 0=none 1=not BFG 2=All cfg.common.netMobDamageModifier = 1; cfg.common.netMobHealthModifier = 1; cfg.common.netGravity = -1; // use map default cfg.common.plrViewHeight = DEFAULT_PLAYER_VIEWHEIGHT; cfg.common.mapTitle = true; cfg.common.automapTitleAtBottom = true; cfg.common.hideIWADAuthor = true; cfg.common.hideUnknownAuthor = true; cfg.common.confirmQuickGameSave = true; cfg.common.confirmRebornLoad = true; cfg.common.loadLastSaveOnReborn = false; cfg.maxSkulls = true; cfg.allowSkullsInWalls = false; cfg.anyBossDeath = false; cfg.monstersStuckInDoors = false; cfg.avoidDropoffs = true; cfg.moveBlock = false; cfg.fallOff = true; cfg.fixOuchFace = true; cfg.fixStatusbarOwnedWeapons = true; cfg.common.statusbarScale = 1; cfg.common.statusbarOpacity = 1; cfg.common.statusbarCounterAlpha = 1; cfg.common.automapCustomColors = 0; // Never. cfg.common.automapL0[0] = .4f; // Unseen areas cfg.common.automapL0[1] = .4f; cfg.common.automapL0[2] = .4f; cfg.common.automapL1[0] = 1.f; // onesided lines cfg.common.automapL1[1] = 0.f; cfg.common.automapL1[2] = 0.f; cfg.common.automapL2[0] = .77f; // floor height change lines cfg.common.automapL2[1] = .6f; cfg.common.automapL2[2] = .325f; cfg.common.automapL3[0] = 1.f; // ceiling change lines cfg.common.automapL3[1] = .95f; cfg.common.automapL3[2] = 0.f; cfg.common.automapMobj[0] = 0.f; cfg.common.automapMobj[1] = 1.f; cfg.common.automapMobj[2] = 0.f; cfg.common.automapBack[0] = 0.f; cfg.common.automapBack[1] = 0.f; cfg.common.automapBack[2] = 0.f; cfg.common.automapOpacity = .7f; cfg.common.automapLineAlpha = .7f; cfg.common.automapLineWidth = 3.0f; cfg.common.automapShowDoors = true; cfg.common.automapDoorGlow = 8; cfg.common.automapHudDisplay = 2; cfg.common.automapRotate = true; cfg.common.automapBabyKeys = false; cfg.common.automapZoomSpeed = .1f; cfg.common.automapPanSpeed = .5f; cfg.common.automapPanResetOnOpen = true; cfg.common.automapOpenSeconds = AUTOMAPWIDGET_OPEN_SECONDS; cfg.common.hudCheatCounterScale = .7f; cfg.common.hudCheatCounterShowWithAutomap = true; if(gameMode == doom_chex) { cfg.hudKeysCombine = true; } cfg.common.msgCount = 4; cfg.common.msgScale = .8f; cfg.common.msgUptime = 5; cfg.common.msgAlign = 0; // Left. cfg.common.msgBlink = 5; if(gameMode == doom2_hacx) { cfg.common.msgColor[CR] = .2f; cfg.common.msgColor[CG] = .2f; cfg.common.msgColor[CB] = .9f; } else { memcpy(cfg.common.msgColor, defFontRGB2, sizeof(cfg.common.msgColor)); } cfg.common.chatBeep = true; cfg.killMessages = true; cfg.common.bobWeapon = 1; cfg.common.bobView = 1; cfg.bobWeaponLower = true; cfg.common.cameraNoClip = true; cfg.respawnMonstersNightmare = true; cfg.common.weaponOrder[0] = WT_SIXTH; cfg.common.weaponOrder[1] = WT_NINETH; cfg.common.weaponOrder[2] = WT_FOURTH; cfg.common.weaponOrder[3] = WT_THIRD; cfg.common.weaponOrder[4] = WT_SECOND; cfg.common.weaponOrder[5] = WT_EIGHTH; cfg.common.weaponOrder[6] = WT_FIFTH; cfg.common.weaponOrder[7] = WT_SEVENTH; cfg.common.weaponOrder[8] = WT_FIRST; cfg.common.weaponCycleSequential = true; cfg.berserkAutoSwitch = true; // Use the DOOM transition by default. Con_SetInteger("con-transition", 1); // Do the common pre init routine; G_CommonPreInit(); } void D_PostInit() { CommandLine &cmdLine = DENG2_APP->commandLine(); /// @todo Kludge: Border background is different in DOOM2. /// @todo Do this properly! ::borderGraphics[0] = (::gameModeBits & GM_ANY_DOOM2)? "Flats:GRNROCK" : "Flats:FLOOR7_2"; G_CommonPostInit(); P_InitAmmoInfo(); P_InitWeaponInfo(); IN_Init(); // Game parameters. ::monsterInfight = 0; if(ded_value_t const *infight = Defs().getValueById("AI|Infight")) { ::monsterInfight = String(infight->text).toInt(); } // Get skill / episode / map from parms. gfw_SetDefaultRule(skill, /*startSkill =*/ SM_MEDIUM); if (cmdLine.check("-altdeath")) { ::cfg.common.netDeathmatch = 2; } else if (cmdLine.check("-deathmatch")) { ::cfg.common.netDeathmatch = 1; } gfw_SetDefaultRule(fast, cfg.common.defaultRuleFastMonsters); // Apply these rules. gfw_SetDefaultRule(noMonsters, cmdLine.has("-nomonsters") || gfw_GameProfile()->optionValue("noMonsters").isTrue()); gfw_SetDefaultRule(respawnMonsters, cmdLine.has("-respawn") || gfw_GameProfile()->optionValue("respawn").isTrue()); gfw_SetDefaultRule(fast, cmdLine.has("-fast") || gfw_GameProfile()->optionValue("fast").isTrue()); if (gfw_DefaultRule(deathmatch)) { if (int arg = cmdLine.check("-timer", 1)) { bool isNumber; int mins = cmdLine.at(arg + 1).toInt(&isNumber); if (isNumber) { LOG_NOTE("Maps will end after %i %s") << mins << (mins == 1? "minute" : "minutes"); } } } // Load a saved game? if (int arg = cmdLine.check("-loadgame", 1)) { if (SaveSlot *sslot = G_SaveSlots().slotByUserInput(cmdLine.at(arg + 1))) { if (sslot->isUserWritable() && G_SetGameActionLoadSession(sslot->id())) { // No further initialization is to be done. return; } } } // Change the default skill mode? if (int arg = cmdLine.check("-skill", 1)) { int skillNumber = cmdLine.at(arg + 1).toInt(); gfw_SetDefaultRule(skill, skillmode_t(skillNumber > 0? skillNumber - 1 : skillNumber)); } G_AutoStartOrBeginTitleLoop(); } void D_Shutdown() { IN_Shutdown(); G_CommonShutdown(); }
utf-8
1
GPL-2+
1986, Gary S. Brown 1993-2006, id Software, Inc 1995-2000, Brian Paul 1998-2000, Colin Reed <cph@moria.org.uk> 1998-2000, Lee Killough <killough@rsn.hp.com> 1999, Activision 1999, Chi Hoang, Lee Killough, Jim Flynn, Rand Phares, Ty Halderman (PrBoom 2.2.6) 1999-2000, Jess Haas, Nicolas Kalkhof, Colin Phipps, Florian Schulze (PrBoom 2.2.6) 1999-2013, Jaakko Keränen <jaakko.keranen@iki.fi> 2000-2007, Andrew Apted <ajapted@gmail.com> 2003-2005, Samuel Villarreal <svkaiser@gmail.com> 2003-2012, Deng Team 2004, Lukasz Stelmach 2005, Zachary Keene <zjkeene@bellsouth.net> 2005-2013, Daniel Swanson <danij@dengine.net> 2006, Martin Eyre <martineyre@btinternet.com> 2006-2008, Jamie Jones <jamie_jones_au@yahoo.com.au>
horizon-eda-2.2.0/src/rules/rule_match.hpp
#pragma once #include "nlohmann/json_fwd.hpp" #include "util/uuid.hpp" namespace horizon { using json = nlohmann::json; class RuleMatch { public: RuleMatch(); RuleMatch(const json &j, const class RuleImportMap &import_map); RuleMatch(const json &j); json serialize() const; std::string get_brief(const class Block *block = nullptr) const; void cleanup(const class Block *block); bool can_export() const; enum class Mode { ALL, NET, NET_CLASS, NET_NAME_REGEX, NET_CLASS_REGEX }; Mode mode = Mode::ALL; UUID net; UUID net_class; std::string net_name_regex; std::string net_class_regex; bool match(const class Net *net) const; }; } // namespace horizon
utf-8
1
GPL-3+
2017-2018 Lukas K <lu@0x83.eu>
openssh-ssh1-7.5p1/auth-passwd.c
/* $OpenBSD: auth-passwd.c,v 1.45 2016/07/21 01:39:35 dtucker Exp $ */ /* * Author: Tatu Ylonen <ylo@cs.hut.fi> * Copyright (c) 1995 Tatu Ylonen <ylo@cs.hut.fi>, Espoo, Finland * All rights reserved * Password authentication. This file contains the functions to check whether * the password is valid for the user. * * As far as I am concerned, the code I have written for this software * can be used freely for any purpose. Any derived versions of this * software must be clearly marked as such, and if the derived work is * incompatible with the protocol description in the RFC file, it must be * called by a name other than "ssh" or "Secure Shell". * * Copyright (c) 1999 Dug Song. All rights reserved. * Copyright (c) 2000 Markus Friedl. All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``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 AUTHOR 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 "includes.h" #include <sys/types.h> #include <pwd.h> #include <stdio.h> #include <string.h> #include <stdarg.h> #include "packet.h" #include "buffer.h" #include "log.h" #include "misc.h" #include "servconf.h" #include "key.h" #include "hostfile.h" #include "auth.h" #include "auth-options.h" extern Buffer loginmsg; extern ServerOptions options; #ifdef HAVE_LOGIN_CAP extern login_cap_t *lc; #endif #define DAY (24L * 60 * 60) /* 1 day in seconds */ #define TWO_WEEKS (2L * 7 * DAY) /* 2 weeks in seconds */ #define MAX_PASSWORD_LEN 1024 void disable_forwarding(void) { no_port_forwarding_flag = 1; no_agent_forwarding_flag = 1; no_x11_forwarding_flag = 1; } /* * Tries to authenticate the user using password. Returns true if * authentication succeeds. */ int auth_password(Authctxt *authctxt, const char *password) { struct passwd * pw = authctxt->pw; int result, ok = authctxt->valid; #if defined(USE_SHADOW) && defined(HAS_SHADOW_EXPIRE) static int expire_checked = 0; #endif if (strlen(password) > MAX_PASSWORD_LEN) return 0; #ifndef HAVE_CYGWIN if (pw->pw_uid == 0 && options.permit_root_login != PERMIT_YES) ok = 0; #endif if (*password == '\0' && options.permit_empty_passwd == 0) return 0; #ifdef KRB5 if (options.kerberos_authentication == 1) { int ret = auth_krb5_password(authctxt, password); if (ret == 1 || ret == 0) return ret && ok; /* Fall back to ordinary passwd authentication. */ } #endif #ifdef HAVE_CYGWIN { HANDLE hToken = cygwin_logon_user(pw, password); if (hToken == INVALID_HANDLE_VALUE) return 0; cygwin_set_impersonation_token(hToken); return ok; } #endif #ifdef USE_PAM if (options.use_pam) return (sshpam_auth_passwd(authctxt, password) && ok); #endif #if defined(USE_SHADOW) && defined(HAS_SHADOW_EXPIRE) if (!expire_checked) { expire_checked = 1; if (auth_shadow_pwexpired(authctxt)) authctxt->force_pwchange = 1; } #endif result = sys_auth_passwd(authctxt, password); if (authctxt->force_pwchange) disable_forwarding(); return (result && ok); } #ifdef BSD_AUTH static void warn_expiry(Authctxt *authctxt, auth_session_t *as) { char buf[256]; quad_t pwtimeleft, actimeleft, daysleft, pwwarntime, acwarntime; pwwarntime = acwarntime = TWO_WEEKS; pwtimeleft = auth_check_change(as); actimeleft = auth_check_expire(as); #ifdef HAVE_LOGIN_CAP if (authctxt->valid) { pwwarntime = login_getcaptime(lc, "password-warn", TWO_WEEKS, TWO_WEEKS); acwarntime = login_getcaptime(lc, "expire-warn", TWO_WEEKS, TWO_WEEKS); } #endif if (pwtimeleft != 0 && pwtimeleft < pwwarntime) { daysleft = pwtimeleft / DAY + 1; snprintf(buf, sizeof(buf), "Your password will expire in %lld day%s.\n", daysleft, daysleft == 1 ? "" : "s"); buffer_append(&loginmsg, buf, strlen(buf)); } if (actimeleft != 0 && actimeleft < acwarntime) { daysleft = actimeleft / DAY + 1; snprintf(buf, sizeof(buf), "Your account will expire in %lld day%s.\n", daysleft, daysleft == 1 ? "" : "s"); buffer_append(&loginmsg, buf, strlen(buf)); } } int sys_auth_passwd(Authctxt *authctxt, const char *password) { struct passwd *pw = authctxt->pw; auth_session_t *as; static int expire_checked = 0; as = auth_usercheck(pw->pw_name, authctxt->style, "auth-ssh", (char *)password); if (as == NULL) return (0); if (auth_getstate(as) & AUTH_PWEXPIRED) { auth_close(as); disable_forwarding(); authctxt->force_pwchange = 1; return (1); } else { if (!expire_checked) { expire_checked = 1; warn_expiry(authctxt, as); } return (auth_close(as)); } } #elif !defined(CUSTOM_SYS_AUTH_PASSWD) int sys_auth_passwd(Authctxt *authctxt, const char *password) { struct passwd *pw = authctxt->pw; char *encrypted_password, *salt = NULL; /* Just use the supplied fake password if authctxt is invalid */ char *pw_password = authctxt->valid ? shadow_pw(pw) : pw->pw_passwd; /* Check for users with no password. */ if (strcmp(pw_password, "") == 0 && strcmp(password, "") == 0) return (1); /* * Encrypt the candidate password using the proper salt, or pass a * NULL and let xcrypt pick one. */ if (authctxt->valid && pw_password[0] && pw_password[1]) salt = pw_password; encrypted_password = xcrypt(password, salt); /* * Authentication is accepted if the encrypted passwords * are identical. */ return encrypted_password != NULL && strcmp(encrypted_password, pw_password) == 0; } #endif
utf-8
1
unknown
unknown
foxeye-0.12.1/ui/ui.h
/* * Copyright (C) 2005-2006 Andrej N. Gritsenko <andrej@rep.kiev.ua> * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License along * with this program; if not, write to the Free Software Foundation, Inc., * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. */ #ifndef _UI_H #define _UI_H 1 enum { T_WINNAME, /* select window name for next packet */ T_WINACT, /* select name and activate */ T_OFFSET, /* set offset <val> for text (0 - autoshift) */ T_PRIVTEXT, /* private/highlighted text */ T_GROUPTEXT, /* group/public text */ T_INFO, /* info text */ T_ADDLIST, /* add people list */ T_DELLIST, /* delete people list */ T_SCROLL, /* shift offset by <val> lines */ T_GET, /* get lines from <val1+val2> up to <val1> */ T_HEADER, /* set header for window */ T_TARGET, /* change window target */ T_HISTORY, /* saved input (start <val> is max size) */ T_INPUT, /* put <arg> in input line */ T_PROMPT, /* set prompt for window input */ T_ASK, /* asked for new input with prompt <arg> */ T_CLOSE, /* close window */ T_FRAGMENT /* it's fragment of packet, to be continued */ }; #define UI_PKT_LEN 2048 struct ui_pkt { unsigned short typelen; /* type << 11 + len & 0x7ff */ unsigned char buf[UI_PKT_LEN]; }; #endif
utf-8
1
GPL-2+
1999-2017 Andriy Grytsenko (LStranger) <andrej@rep.kiev.ua>
swami-2.2.2/src/swamigui/SwamiguiMenu.c
/* * SwamiguiMenu.c - Swami GUI Menu object * * Swami * Copyright (C) 1999-2014 Element Green <element@elementsofsound.org> * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; version 2 * of the License only. * * 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 or point your web browser to http://www.gnu.org. */ #include <stdio.h> #include <stdlib.h> #include <string.h> #include <gtk/gtk.h> #include "SwamiguiMenu.h" #include "SwamiguiRoot.h" #include "SwamiguiPref.h" #include "SwamiguiPythonView.h" #include "help.h" #include "patch_funcs.h" #include "i18n.h" #include "icons.h" #include "splash.h" #include "util.h" static void swamigui_menu_class_init(SwamiguiMenuClass *klass); static void swamigui_menu_init(SwamiguiMenu *menubar); static gboolean swamigui_menu_recent_filter_custom_func(const GtkRecentFilterInfo *filter_info, gpointer user_data); static void swamigui_menu_recent_chooser_item_activated(GtkRecentChooser *chooser, gpointer user_data); static void swamigui_menu_realize(GtkWidget *widget); static void swamigui_menu_update_new_type_item(void); static GtkWidget *create_patch_type_menu(SwamiguiMenu *menubar); static int sort_by_type_name(const void *a, const void *b); /* menu callbacks */ static void swamigui_menu_cb_new_patch(GtkWidget *mitem, gpointer data); static void swamigui_menu_cb_load_files(GtkWidget *mitem, gpointer data); static void swamigui_menu_cb_save_all(GtkWidget *mitem, gpointer data); static void swamigui_menu_cb_quit(GtkWidget *mitem, gpointer data); static void swamigui_menu_cb_preferences(GtkWidget *mitem, gpointer data); static void swamigui_menu_cb_swamitips(GtkWidget *mitem, gpointer data); static void swamigui_menu_cb_splash_image(GtkWidget *mitem, gpointer data); #ifdef PYTHON_SUPPORT static void swamigui_menu_cb_python(GtkWidget *mitem, gpointer data); #endif static void swamigui_menu_cb_restart_fluid(GtkWidget *mitem, gpointer data); static GtkWidgetClass *parent_class = NULL; /* the last patch type selected from the NewType menu item */ static GType last_new_type = 0; static GtkWidget *last_new_mitem = NULL; static GtkActionEntry entries[] = { { "FileMenu", NULL, "_File" }, /* name, stock id, label */ { "EditMenu", NULL, "_Edit" }, /* name, stock id, label */ { "PluginsMenu", NULL, "_Plugins" }, /* name, stock id, label */ { "ToolsMenu", NULL, "_Tools" }, /* name, stock id, label */ { "HelpMenu", NULL, "_Help" }, /* name, stock id, label */ /* File Menu */ /* New is not actually on the menu, just used for key accelerator */ { "New", GTK_STOCK_NEW, "_New", /* name, stock id, label */ "<control>N", /* label, accelerator */ NULL, /* tooltip */ G_CALLBACK(swamigui_menu_cb_new_patch) }, { "NewType", GTK_STOCK_NEW, "N_ew...", "", N_("Create a new patch file of type..") }, { "Open", GTK_STOCK_OPEN, /* name, stock id */ "_Open", "<control>O", /* label, accelerator */ NULL, /* tooltip */ G_CALLBACK(swamigui_menu_cb_load_files) }, { "OpenRecent", GTK_STOCK_OPEN, /* name, stock id */ "Open _Recent", "", /* label, accelerator */ NULL, /* tooltip */ NULL }, /* callback */ { "SaveAll", GTK_STOCK_SAVE, /* name, stock id */ "_Save All", "", /* label, accelerator */ NULL, /* tooltip */ G_CALLBACK(swamigui_menu_cb_save_all) }, { "Quit", GTK_STOCK_QUIT, /* name, stock id */ "_Quit", "<control>Q", /* label, accelerator */ NULL, /* tooltip */ G_CALLBACK(swamigui_menu_cb_quit) }, /* Edit Menu */ { "Preferences", GTK_STOCK_PREFERENCES, /* name, stock id */ "_Preferences", "", /* label, accelerator */ NULL, /* tooltip */ G_CALLBACK(swamigui_menu_cb_preferences) }, /* Plugins Menu */ { "RestartFluid", GTK_STOCK_REFRESH, N_("_Restart FluidSynth"), "", N_("Restart FluidSynth plugin"), G_CALLBACK(swamigui_menu_cb_restart_fluid) }, /* Tools Menu */ #ifdef PYTHON_SUPPORT { "Python", SWAMIGUI_STOCK_PYTHON, /* name, stock id */ "_Python", "", /* label, accelerator */ N_("Python script editor and console"), /* tooltip */ G_CALLBACK(swamigui_menu_cb_python) }, #endif /* Help Menu */ { "SwamiTips", GTK_STOCK_HELP, /* name, stock id */ "Swami _Tips", "", /* label, accelerator */ N_("Get helpful tips on using Swami"), /* tooltip */ G_CALLBACK(swamigui_menu_cb_swamitips) }, { "SplashImage", GTK_STOCK_INFO, /* name, stock id */ "_Splash Image", "", /* label, accelerator */ N_("Show splash image"), /* tooltip */ G_CALLBACK(swamigui_menu_cb_splash_image) }, { "About", GTK_STOCK_ABOUT, /* name, stock id */ "_About", "", /* label, accelerator */ N_("About Swami"), /* tooltip */ G_CALLBACK(swamigui_help_about) }, }; static guint n_entries = G_N_ELEMENTS(entries); static const gchar *ui_info = "<ui>" " <menubar name='MenuBar'>" " <menu action='FileMenu'>" " <menuitem action='New'/>" " <menuitem action='NewType'/>" " <menuitem action='Open'/>" " <menuitem action='OpenRecent'/>" " <menuitem action='SaveAll'/>" " <separator/>" " <menuitem action='Quit'/>" " </menu>" " <menu action='EditMenu'>" " <menuitem action='Preferences'/>" " </menu>" " <menu action='PluginsMenu'>" " <menuitem action='RestartFluid'/>" " </menu>" /* FIXME - Python disabled until crashing is fixed and binding is updated */ #if 0 " <menu action='ToolsMenu'>" #ifdef PYTHON_SUPPORT " <menuitem action='Python'/>" #endif " </menu>" #endif " <menu action='HelpMenu'>" " <menuitem action='SwamiTips'/>" " <menuitem action='SplashImage'/>" " <menuitem action='About'/>" " </menu>" " </menubar>" "</ui>"; GType swamigui_menu_get_type(void) { static GType obj_type = 0; if(!obj_type) { static const GTypeInfo obj_info = { sizeof(SwamiguiMenuClass), NULL, NULL, (GClassInitFunc) swamigui_menu_class_init, NULL, NULL, sizeof(SwamiguiMenu), 0, (GInstanceInitFunc) swamigui_menu_init, }; obj_type = g_type_register_static(GTK_TYPE_VBOX, "SwamiguiMenu", &obj_info, 0); } return (obj_type); } static void swamigui_menu_class_init(SwamiguiMenuClass *klass) { GtkWidgetClass *widg_class = GTK_WIDGET_CLASS(klass); parent_class = g_type_class_peek_parent(klass); widg_class->realize = swamigui_menu_realize; } static void swamigui_menu_init(SwamiguiMenu *guimenu) { GtkActionGroup *actions; GtkWidget *new_type_menu; GtkWidget *mitem; GError *error = NULL; GtkWidget *recent_menu; GtkRecentManager *manager; GtkRecentFilter *filter; actions = gtk_action_group_new("Actions"); gtk_action_group_add_actions(actions, entries, n_entries, guimenu); guimenu->ui = gtk_ui_manager_new(); gtk_ui_manager_insert_action_group(guimenu->ui, actions, 0); if(!gtk_ui_manager_add_ui_from_string(guimenu->ui, ui_info, -1, &error)) { g_critical("Building SwamiGuiMenu failed: %s", error->message); g_error_free(error); return; } gtk_box_pack_start(GTK_BOX(guimenu), gtk_ui_manager_get_widget(guimenu->ui, "/MenuBar"), FALSE, FALSE, 0); /* if last_new_type not set assign it from SwamiguiRoot "default-patch-type" property */ if(!last_new_type) { g_object_get(swamigui_root, "default-patch-type", &last_new_type, NULL); /* also not set? Just set it to SoundFont type */ if(last_new_type == G_TYPE_NONE) { last_new_type = IPATCH_TYPE_SF2; } } /* set correct label of "New <Last>" menu item */ last_new_mitem = gtk_ui_manager_get_widget(guimenu->ui, "/MenuBar/FileMenu/New"); swamigui_menu_update_new_type_item(); /* create patch type menu and add to File->"New .." menu item */ new_type_menu = create_patch_type_menu(guimenu); mitem = gtk_ui_manager_get_widget(guimenu->ui, "/MenuBar/FileMenu/NewType"); gtk_menu_item_set_submenu(GTK_MENU_ITEM(mitem), new_type_menu); /* Recent chooser menu */ manager = gtk_recent_manager_get_default(); recent_menu = gtk_recent_chooser_menu_new_for_manager(manager); /* set the limit to unlimited (FIXME - issues?) */ gtk_recent_chooser_set_limit(GTK_RECENT_CHOOSER(recent_menu), -1); /* filter recent items to only include those stored by Swami and in the instrument files group */ filter = gtk_recent_filter_new(); gtk_recent_filter_add_custom(filter, GTK_RECENT_FILTER_APPLICATION | GTK_RECENT_FILTER_GROUP, swamigui_menu_recent_filter_custom_func, NULL, NULL); gtk_recent_chooser_set_filter(GTK_RECENT_CHOOSER(recent_menu), filter); /* Set the sort type to most recent first */ gtk_recent_chooser_set_sort_type(GTK_RECENT_CHOOSER(recent_menu), GTK_RECENT_SORT_MRU); mitem = gtk_ui_manager_get_widget(guimenu->ui, "/MenuBar/FileMenu/OpenRecent"); gtk_menu_item_set_submenu(GTK_MENU_ITEM(mitem), recent_menu); g_signal_connect(recent_menu, "item-activated", G_CALLBACK(swamigui_menu_recent_chooser_item_activated), NULL); } /* Custom filter function to match application name and instrument files group (exclude samples, etc) */ static gboolean swamigui_menu_recent_filter_custom_func(const GtkRecentFilterInfo *filter_info, gpointer user_data) { const char **sp; const char *app_name; if(!filter_info->applications || !filter_info->groups) { return (FALSE); } app_name = g_get_application_name(); for(sp = filter_info->applications; *sp; sp++) if(strcmp(*sp, app_name) == 0) { break; } if(!*sp) { return (FALSE); } for(sp = filter_info->groups; *sp; sp++) if(strcmp(*sp, SWAMIGUI_ROOT_INSTRUMENT_FILES_GROUP) == 0) { break; } return (*sp != NULL); } /* callback for when the user selects a recent file in the recent files menu */ static void swamigui_menu_recent_chooser_item_activated(GtkRecentChooser *chooser, gpointer user_data) { char *file_uri, *fname; file_uri = gtk_recent_chooser_get_current_uri(chooser); if(!file_uri) { return; } fname = g_filename_from_uri(file_uri, NULL, NULL); g_free(file_uri); if(!fname) { g_critical(_("Failed to parse recent file URI '%s'"), file_uri); return; } /* loading patch file and log error on Gtk message dialog */ swamigui_root_patch_load(SWAMI_ROOT(swamigui_root), fname, NULL, GTK_WINDOW(swamigui_root->main_window)); g_free(fname); } static void swamigui_menu_realize(GtkWidget *widget) { SwamiguiMenu *guimenu = SWAMIGUI_MENU(widget); GtkWidget *toplevel; parent_class->realize(widget); toplevel = gtk_widget_get_toplevel(widget); if(toplevel) gtk_window_add_accel_group(GTK_WINDOW(toplevel), gtk_ui_manager_get_accel_group(guimenu->ui)); } static void swamigui_menu_update_new_type_item(void) { char *name, *s; char *free_icon, *icon_name; GtkWidget *icon; gint category; ipatch_type_get(last_new_type, "name", &name, NULL); s = g_strdup_printf(_("_New %s"), name); g_free(name); gtk_label_set_text_with_mnemonic(GTK_LABEL(gtk_bin_get_child (GTK_BIN(last_new_mitem))), s); g_free(s); /* get icon stock name */ ipatch_type_get(last_new_type, "icon", &free_icon, "category", &category, NULL); if(!free_icon) { icon_name = swamigui_icon_get_category_icon(category); } else { icon_name = free_icon; } icon = gtk_image_new_from_stock(icon_name, GTK_ICON_SIZE_MENU); gtk_image_menu_item_set_image(GTK_IMAGE_MENU_ITEM(last_new_mitem), icon); if(free_icon) { g_free(free_icon); } } static GtkWidget * create_patch_type_menu(SwamiguiMenu *guimenu) { GtkWidget *menu; GtkWidget *item; GtkWidget *icon; GType *types, *ptype; char *name; char *free_icon = NULL, *icon_name; guint n_types; gint category; menu = gtk_menu_new(); types = swami_util_get_child_types(IPATCH_TYPE_BASE, &n_types); qsort(types, n_types, sizeof(GType), sort_by_type_name); for(ptype = types; *ptype; ptype++) { ipatch_type_get(*ptype, "name", &name, "icon", &free_icon, "category", &category, NULL); if(!name) { g_free(free_icon); continue; } item = gtk_image_menu_item_new_with_label(name); g_free(name); if(!free_icon) { icon_name = swamigui_icon_get_category_icon(category); } else { icon_name = free_icon; } icon = gtk_image_new_from_stock(icon_name, GTK_ICON_SIZE_MENU); gtk_image_menu_item_set_image(GTK_IMAGE_MENU_ITEM(item), icon); g_free(free_icon); g_object_set_data(G_OBJECT(item), "patch-type", GSIZE_TO_POINTER(*ptype)); gtk_widget_show_all(item); gtk_container_add(GTK_CONTAINER(menu), item); g_signal_connect(item, "activate", G_CALLBACK(swamigui_menu_cb_new_patch), guimenu); } g_free(types); return (menu); } static int sort_by_type_name(const void *a, const void *b) { GType *atype = (GType *)a, *btype = (GType *)b; char *aname, *bname; ipatch_type_get(*atype, "name", &aname, NULL); ipatch_type_get(*btype, "name", &bname, NULL); if(!aname && !bname) { return (0); } else if(!aname) { return (1); } else if(!bname) { return (-1); } else { return (strcmp(aname, bname)); } } /** * swamigui_menu_new: * * Create a Swami main menu object. * * Returns: New Swami menu object. */ GtkWidget * swamigui_menu_new(void) { return (GTK_WIDGET(g_object_new(SWAMIGUI_TYPE_MENU, NULL))); } /* main menu callback to create a new patch objects */ static void swamigui_menu_cb_new_patch(GtkWidget *mitem, gpointer data) { GType patch_type; patch_type = GPOINTER_TO_SIZE(g_object_get_data(G_OBJECT(mitem), "patch-type")); if(patch_type) { last_new_type = patch_type; swamigui_menu_update_new_type_item(); } else { patch_type = last_new_type; } swamigui_new_item(NULL, patch_type); } static void swamigui_menu_cb_load_files(GtkWidget *mitem, gpointer data) { SwamiguiRoot *root = swamigui_get_root(data); IpatchList *selection; if(root) { g_object_get(root, "selection", &selection, NULL); // ++ ref if(selection->items && !selection->items->next) { swamigui_load_files(G_OBJECT(selection->items->data), FALSE); } else { swamigui_load_files(G_OBJECT(root), FALSE); } g_object_unref(selection); // -- unref } } /* main menu callback to save files */ static void swamigui_menu_cb_save_all(GtkWidget *mitem, gpointer data) { IpatchList *patches; /* save them all */ patches = ipatch_container_get_children(IPATCH_CONTAINER(swami_root->patch_root), IPATCH_TYPE_BASE); if(patches) { if(patches->items) { swamigui_save_files(patches, FALSE); } g_object_unref(patches); } } static void swamigui_menu_cb_quit(GtkWidget *mitem, gpointer data) { SwamiguiRoot *root = swamigui_get_root(data); if(root) { swamigui_root_quit(root); } } static void swamigui_menu_cb_preferences(GtkWidget *mitem, gpointer data) { GtkWidget *pref; if(!swamigui_util_activate_unique_dialog("preferences", 0)) { pref = swamigui_pref_new(); /* The dialog is registered and set centered on top of the main window. To get this result the dialog must be hidden beforehand, otherwise gtk_window_set_transient_for() will be ignored. */ swamigui_util_register_unique_dialog(pref, "preferences", 0); gtk_widget_show(pref); } } static void swamigui_menu_cb_swamitips(GtkWidget *mitem, gpointer data) { SwamiguiRoot *root = swamigui_get_root(data); if(root) { swamigui_help_swamitips_create(root); } } static void swamigui_menu_cb_splash_image(GtkWidget *mitem, gpointer data) { swamigui_splash_display(0); } #ifdef PYTHON_SUPPORT static void swamigui_menu_cb_python(GtkWidget *mitem, gpointer data) { GtkWidget *window; GtkWidget *pythonview; window = gtk_window_new(GTK_WINDOW_TOPLEVEL); pythonview = swamigui_python_view_new(); gtk_container_add(GTK_CONTAINER(window), pythonview); gtk_widget_show_all(window); } #endif static void swamigui_menu_cb_restart_fluid(GtkWidget *mitem, gpointer data) { /* FIXME - Should be handled by FluidSynth plugin */ swami_wavetbl_close(swamigui_root->wavetbl); swami_wavetbl_open(swamigui_root->wavetbl, NULL); }
utf-8
1
GPL-2
1999-2021 Joshua "Element" Green
gnome-hwp-support-0.1.6/properties/props-data.c
/* * Copyright (C) 2012 Changwoo Ryu * * This program is free software; you can redistribute it and'or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2, or (at your option) * any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, see <http://www.gnu.org/licenses/>. */ #include "props-data.h" #include <string.h> #include <gsf/gsf-doc-meta-data.h> #include <gsf/gsf-infile-msole.h> #include <gsf/gsf-infile.h> #include <gsf/gsf-input-gio.h> #include <gsf/gsf-input-memory.h> #include <gsf/gsf-input-stdio.h> #include <gsf/gsf-msole-utils.h> #include <gsf/gsf-utils.h> GsfDocMetaData * props_data_read(const char *uri, GError **error) { GsfInput *input; GsfInfile *infile; GsfInput *summary; input = gsf_input_gio_new_for_uri(uri, error); if (! input) return NULL; infile = gsf_infile_msole_new(input, NULL); g_object_unref(input); summary = gsf_infile_child_by_name(infile, "\005HwpSummaryInformation"); g_object_unref(infile); int size = gsf_input_size(summary); guint8 *buf = g_malloc(size); gsf_input_read(summary, size, buf); static guint8 const component_guid [] = { 0xe0, 0x85, 0x9f, 0xf2, 0xf9, 0x4f, 0x68, 0x10, 0xab, 0x91, 0x08, 0x00, 0x2b, 0x27, 0xb3, 0xd9 }; g_object_unref(summary); /* Trick the libgsf's MSOLE property set parser, by changing * its GUID. The \005HwpSummaryInformation is compatible with * the summary property set. */ memcpy(buf + 28, component_guid, sizeof(component_guid)); summary = gsf_input_memory_new(buf, size, TRUE); g_free(buf); GsfDocMetaData *meta; meta = gsf_doc_meta_data_new(); gsf_doc_meta_data_read_from_msole(meta, summary); g_object_unref(summary); /* TODO: workaround buggy HWP */ return meta; }
utf-8
1
GPL-2+
2011-2018 Changwoo Ryu
virtualbox-6.1.32-dfsg/src/VBox/Runtime/r3/linux/semevent-linux.cpp
/* $Id: semevent-linux.cpp $ */ /** @file * IPRT - Event Semaphore, Linux (2.6.x+). */ /* * Copyright (C) 2006-2020 Oracle Corporation * * This file is part of VirtualBox Open Source Edition (OSE), as * available from http://www.virtualbox.org. This file is free software; * you can redistribute it and/or modify it under the terms of the GNU * General Public License (GPL) as published by the Free Software * Foundation, in version 2 as it comes in the "COPYING" file of the * VirtualBox OSE distribution. VirtualBox OSE is distributed in the * hope that it will be useful, but WITHOUT ANY WARRANTY of any kind. * * The contents of this file may alternatively be used under the terms * of the Common Development and Distribution License Version 1.0 * (CDDL) only, as it comes in the "COPYING.CDDL" file of the * VirtualBox OSE distribution, in which case the provisions of the * CDDL are applicable instead of those of the GPL. * * You may elect to license modified versions of this file under the * terms and conditions of either the GPL or the CDDL or both. */ #include <features.h> #if __GLIBC_PREREQ(2,6) && !defined(IPRT_WITH_FUTEX_BASED_SEMS) /* * glibc 2.6 fixed a serious bug in the mutex implementation. We wrote this * linux specific event semaphores code in order to work around the bug. We * will fall back on the pthread-based implementation if glibc is known to * contain the bug fix. * * The external reference to epoll_pwait is a hack which prevents that we link * against glibc < 2.6. */ #include "../posix/semevent-posix.cpp" __asm__ (".global epoll_pwait"); #else /* glibc < 2.6 */ /********************************************************************************************************************************* * Header Files * *********************************************************************************************************************************/ #include <iprt/semaphore.h> #include "internal/iprt.h" #include <iprt/asm.h> #include <iprt/assert.h> #include <iprt/err.h> #include <iprt/lockvalidator.h> #include <iprt/mem.h> #include <iprt/time.h> #include "internal/magics.h" #include "internal/mem.h" #include "internal/strict.h" #include <errno.h> #include <limits.h> #include <pthread.h> #include <unistd.h> #include <sys/time.h> #include <sys/syscall.h> #if 0 /* With 2.6.17 futex.h has become C++ unfriendly. */ # include <linux/futex.h> #else # define FUTEX_WAIT 0 # define FUTEX_WAKE 1 #endif /********************************************************************************************************************************* * Structures and Typedefs * *********************************************************************************************************************************/ /** * Linux (single wakup) event semaphore. */ struct RTSEMEVENTINTERNAL { /** Magic value. */ intptr_t volatile iMagic; /** The futex state variable. * 0 means not signalled. 1 means signalled. */ uint32_t volatile fSignalled; /** The number of waiting threads */ int32_t volatile cWaiters; #ifdef RTSEMEVENT_STRICT /** Signallers. */ RTLOCKVALRECSHRD Signallers; /** Indicates that lock validation should be performed. */ bool volatile fEverHadSignallers; #endif /** The creation flags. */ uint32_t fFlags; }; /** * Wrapper for the futex syscall. */ static long sys_futex(uint32_t volatile *uaddr, int op, int val, struct timespec *utime, int32_t *uaddr2, int val3) { errno = 0; long rc = syscall(__NR_futex, uaddr, op, val, utime, uaddr2, val3); if (rc < 0) { Assert(rc == -1); rc = -errno; } return rc; } RTDECL(int) RTSemEventCreate(PRTSEMEVENT phEventSem) { return RTSemEventCreateEx(phEventSem, 0 /*fFlags*/, NIL_RTLOCKVALCLASS, NULL); } RTDECL(int) RTSemEventCreateEx(PRTSEMEVENT phEventSem, uint32_t fFlags, RTLOCKVALCLASS hClass, const char *pszNameFmt, ...) { AssertReturn(!(fFlags & ~(RTSEMEVENT_FLAGS_NO_LOCK_VAL | RTSEMEVENT_FLAGS_BOOTSTRAP_HACK)), VERR_INVALID_PARAMETER); Assert(!(fFlags & RTSEMEVENT_FLAGS_BOOTSTRAP_HACK) || (fFlags & RTSEMEVENT_FLAGS_NO_LOCK_VAL)); /* * Allocate semaphore handle. */ struct RTSEMEVENTINTERNAL *pThis; if (!(fFlags & RTSEMEVENT_FLAGS_BOOTSTRAP_HACK)) pThis = (struct RTSEMEVENTINTERNAL *)RTMemAlloc(sizeof(struct RTSEMEVENTINTERNAL)); else pThis = (struct RTSEMEVENTINTERNAL *)rtMemBaseAlloc(sizeof(struct RTSEMEVENTINTERNAL)); if (pThis) { pThis->iMagic = RTSEMEVENT_MAGIC; pThis->cWaiters = 0; pThis->fSignalled = 0; pThis->fFlags = fFlags; #ifdef RTSEMEVENT_STRICT if (!pszNameFmt) { static uint32_t volatile s_iSemEventAnon = 0; RTLockValidatorRecSharedInit(&pThis->Signallers, hClass, RTLOCKVAL_SUB_CLASS_ANY, pThis, true /*fSignaller*/, !(fFlags & RTSEMEVENT_FLAGS_NO_LOCK_VAL), "RTSemEvent-%u", ASMAtomicIncU32(&s_iSemEventAnon) - 1); } else { va_list va; va_start(va, pszNameFmt); RTLockValidatorRecSharedInitV(&pThis->Signallers, hClass, RTLOCKVAL_SUB_CLASS_ANY, pThis, true /*fSignaller*/, !(fFlags & RTSEMEVENT_FLAGS_NO_LOCK_VAL), pszNameFmt, va); va_end(va); } pThis->fEverHadSignallers = false; #else RT_NOREF(hClass, pszNameFmt); #endif *phEventSem = pThis; return VINF_SUCCESS; } return VERR_NO_MEMORY; } RTDECL(int) RTSemEventDestroy(RTSEMEVENT hEventSem) { /* * Validate input. */ struct RTSEMEVENTINTERNAL *pThis = hEventSem; if (pThis == NIL_RTSEMEVENT) return VINF_SUCCESS; AssertPtrReturn(pThis, VERR_INVALID_HANDLE); AssertReturn(pThis->iMagic == RTSEMEVENT_MAGIC, VERR_INVALID_HANDLE); /* * Invalidate the semaphore and wake up anyone waiting on it. */ ASMAtomicXchgSize(&pThis->iMagic, RTSEMEVENT_MAGIC | UINT32_C(0x80000000)); if (ASMAtomicXchgS32(&pThis->cWaiters, INT32_MIN / 2) > 0) { sys_futex(&pThis->fSignalled, FUTEX_WAKE, INT_MAX, NULL, NULL, 0); usleep(1000); } /* * Free the semaphore memory and be gone. */ #ifdef RTSEMEVENT_STRICT RTLockValidatorRecSharedDelete(&pThis->Signallers); #endif if (!(pThis->fFlags & RTSEMEVENT_FLAGS_BOOTSTRAP_HACK)) RTMemFree(pThis); else rtMemBaseFree(pThis); return VINF_SUCCESS; } RTDECL(int) RTSemEventSignal(RTSEMEVENT hEventSem) { /* * Validate input. */ struct RTSEMEVENTINTERNAL *pThis = hEventSem; AssertPtrReturn(pThis, VERR_INVALID_HANDLE); AssertReturn(pThis->iMagic == RTSEMEVENT_MAGIC, VERR_INVALID_HANDLE); #ifdef RTSEMEVENT_STRICT if (pThis->fEverHadSignallers) { int rc9 = RTLockValidatorRecSharedCheckSignaller(&pThis->Signallers, NIL_RTTHREAD); if (RT_FAILURE(rc9)) return rc9; } #endif ASMAtomicWriteU32(&pThis->fSignalled, 1); if (ASMAtomicReadS32(&pThis->cWaiters) < 1) return VINF_SUCCESS; /* somebody is waiting, try wake up one of them. */ long cWoken = sys_futex(&pThis->fSignalled, FUTEX_WAKE, 1, NULL, NULL, 0); if (RT_LIKELY(cWoken >= 0)) return VINF_SUCCESS; if (RT_UNLIKELY(pThis->iMagic != RTSEMEVENT_MAGIC)) return VERR_SEM_DESTROYED; return VERR_INVALID_PARAMETER; } static int rtSemEventWait(RTSEMEVENT hEventSem, RTMSINTERVAL cMillies, bool fAutoResume) { #ifdef RTSEMEVENT_STRICT PCRTLOCKVALSRCPOS pSrcPos = NULL; #endif /* * Validate input. */ struct RTSEMEVENTINTERNAL *pThis = hEventSem; AssertPtrReturn(pThis, VERR_INVALID_HANDLE); AssertReturn(pThis->iMagic == RTSEMEVENT_MAGIC, VERR_INVALID_HANDLE); /* * Quickly check whether it's signaled. */ /** @todo this isn't fair if someone is already waiting on it. They should * have the first go at it! * (ASMAtomicReadS32(&pThis->cWaiters) == 0 || !cMillies) && ... */ if (ASMAtomicCmpXchgU32(&pThis->fSignalled, 0, 1)) return VINF_SUCCESS; /* * Convert the timeout value. */ struct timespec ts; struct timespec *pTimeout = NULL; uint64_t u64End = 0; /* shut up gcc */ if (cMillies != RT_INDEFINITE_WAIT) { if (!cMillies) return VERR_TIMEOUT; ts.tv_sec = cMillies / 1000; ts.tv_nsec = (cMillies % 1000) * UINT32_C(1000000); u64End = RTTimeSystemNanoTS() + cMillies * UINT64_C(1000000); pTimeout = &ts; } ASMAtomicIncS32(&pThis->cWaiters); /* * The wait loop. */ #ifdef RTSEMEVENT_STRICT RTTHREAD hThreadSelf = !(pThis->fFlags & RTSEMEVENT_FLAGS_BOOTSTRAP_HACK) ? RTThreadSelfAutoAdopt() : RTThreadSelf(); #else RTTHREAD hThreadSelf = RTThreadSelf(); #endif int rc = VINF_SUCCESS; for (;;) { #ifdef RTSEMEVENT_STRICT if (pThis->fEverHadSignallers) { rc = RTLockValidatorRecSharedCheckBlocking(&pThis->Signallers, hThreadSelf, pSrcPos, false, cMillies, RTTHREADSTATE_EVENT, true); if (RT_FAILURE(rc)) break; } #endif RTThreadBlocking(hThreadSelf, RTTHREADSTATE_EVENT, true); long lrc = sys_futex(&pThis->fSignalled, FUTEX_WAIT, 0, pTimeout, NULL, 0); RTThreadUnblocked(hThreadSelf, RTTHREADSTATE_EVENT); if (RT_UNLIKELY(pThis->iMagic != RTSEMEVENT_MAGIC)) { rc = VERR_SEM_DESTROYED; break; } if (RT_LIKELY(lrc == 0 || lrc == -EWOULDBLOCK)) { /* successful wakeup or fSignalled > 0 in the meantime */ if (ASMAtomicCmpXchgU32(&pThis->fSignalled, 0, 1)) break; } else if (lrc == -ETIMEDOUT) { rc = VERR_TIMEOUT; break; } else if (lrc == -EINTR) { if (!fAutoResume) { rc = VERR_INTERRUPTED; break; } } else { /* this shouldn't happen! */ AssertMsgFailed(("rc=%ld errno=%d\n", lrc, errno)); rc = RTErrConvertFromErrno(lrc); break; } /* adjust the relative timeout */ if (pTimeout) { int64_t i64Diff = u64End - RTTimeSystemNanoTS(); if (i64Diff < 1000) { rc = VERR_TIMEOUT; break; } ts.tv_sec = (uint64_t)i64Diff / UINT32_C(1000000000); ts.tv_nsec = (uint64_t)i64Diff % UINT32_C(1000000000); } } ASMAtomicDecS32(&pThis->cWaiters); return rc; } RTDECL(int) RTSemEventWait(RTSEMEVENT hEventSem, RTMSINTERVAL cMillies) { int rc = rtSemEventWait(hEventSem, cMillies, true); Assert(rc != VERR_INTERRUPTED); Assert(rc != VERR_TIMEOUT || cMillies != RT_INDEFINITE_WAIT); return rc; } RTDECL(int) RTSemEventWaitNoResume(RTSEMEVENT hEventSem, RTMSINTERVAL cMillies) { return rtSemEventWait(hEventSem, cMillies, false); } RTDECL(void) RTSemEventSetSignaller(RTSEMEVENT hEventSem, RTTHREAD hThread) { #ifdef RTSEMEVENT_STRICT struct RTSEMEVENTINTERNAL *pThis = hEventSem; AssertPtrReturnVoid(pThis); AssertReturnVoid(pThis->iMagic == RTSEMEVENT_MAGIC); ASMAtomicWriteBool(&pThis->fEverHadSignallers, true); RTLockValidatorRecSharedResetOwner(&pThis->Signallers, hThread, NULL); #else RT_NOREF(hEventSem, hThread); #endif } RTDECL(void) RTSemEventAddSignaller(RTSEMEVENT hEventSem, RTTHREAD hThread) { #ifdef RTSEMEVENT_STRICT struct RTSEMEVENTINTERNAL *pThis = hEventSem; AssertPtrReturnVoid(pThis); AssertReturnVoid(pThis->iMagic == RTSEMEVENT_MAGIC); ASMAtomicWriteBool(&pThis->fEverHadSignallers, true); RTLockValidatorRecSharedAddOwner(&pThis->Signallers, hThread, NULL); #else RT_NOREF(hEventSem, hThread); #endif } RTDECL(void) RTSemEventRemoveSignaller(RTSEMEVENT hEventSem, RTTHREAD hThread) { #ifdef RTSEMEVENT_STRICT struct RTSEMEVENTINTERNAL *pThis = hEventSem; AssertPtrReturnVoid(pThis); AssertReturnVoid(pThis->iMagic == RTSEMEVENT_MAGIC); RTLockValidatorRecSharedRemoveOwner(&pThis->Signallers, hThread); #else RT_NOREF(hEventSem, hThread); #endif } #endif /* glibc < 2.6 || IPRT_WITH_FUTEX_BASED_SEMS */
utf-8
1
unknown
unknown
r-cran-utf8-1.2.2/src/utf8lite/src/textiter.c
/* * Copyright 2017 Patrick O. Perry. * * 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 <ctype.h> #include "utf8lite.h" /* http://stackoverflow.com/a/11986885 */ #define hextoi(ch) ((ch > '9') ? (ch &~ 0x20) - 'A' + 10 : (ch - '0')) static void iter_retreat_escaped(struct utf8lite_text_iter *it, const uint8_t *begin); static void iter_retreat_raw(struct utf8lite_text_iter *it); void utf8lite_text_iter_make(struct utf8lite_text_iter *it, const struct utf8lite_text *text) { it->ptr = text->ptr; it->end = it->ptr + UTF8LITE_TEXT_SIZE(text); it->text_attr = text->attr; it->current = UTF8LITE_CODE_NONE; } int utf8lite_text_iter_advance(struct utf8lite_text_iter *it) { const uint8_t *ptr = it->ptr; size_t text_attr = it->text_attr; int32_t code; if (it->ptr == it->end) { goto at_end; } code = *ptr++; if (code == '\\' && (text_attr & UTF8LITE_TEXT_ESC_BIT)) { utf8lite_decode_escape(&ptr, &code); } else if (code >= 0x80) { ptr--; utf8lite_decode_utf8(&ptr, &code); } it->ptr = ptr; it->current = code; return 1; at_end: it->current = UTF8LITE_CODE_NONE; return 0; } void utf8lite_text_iter_skip(struct utf8lite_text_iter *it) { it->ptr = it->end; it->current = UTF8LITE_CODE_NONE; } int utf8lite_text_iter_retreat(struct utf8lite_text_iter *it) { const size_t size = (it->text_attr & UTF8LITE_TEXT_SIZE_MASK); const uint8_t *begin = it->end - size; const uint8_t *ptr = it->ptr; const uint8_t *end = it->end; int32_t code = it->current; if (ptr == begin) { return 0; } if (it->text_attr & UTF8LITE_TEXT_ESC_BIT) { iter_retreat_escaped(it, begin); } else { iter_retreat_raw(it); } // we were at the end of the text if (code == UTF8LITE_CODE_NONE) { it->ptr = end; return 1; } // at this point, it->code == code, and it->ptr is the code start ptr = it->ptr; if (ptr == begin) { it->current = UTF8LITE_CODE_NONE; return 0; } // read the previous code if (it->text_attr & UTF8LITE_TEXT_ESC_BIT) { iter_retreat_escaped(it, begin); } else { iter_retreat_raw(it); } // now, it->code is the previous code, and it->ptr is the start // of the previous code // set the pointer to the end of the previous code it->ptr = ptr; return 1; } void utf8lite_text_iter_reset(struct utf8lite_text_iter *it) { const size_t size = (it->text_attr & UTF8LITE_TEXT_SIZE_MASK); const uint8_t *begin = it->end - size; it->ptr = begin; it->current = UTF8LITE_CODE_NONE; } void iter_retreat_raw(struct utf8lite_text_iter *it) { const uint8_t *ptr = it->ptr; int32_t code; code = *(--ptr); if (code < 0x80) { it->ptr = (uint8_t *)ptr; it->current = code; } else { // skip over continuation bytes do { ptr--; } while (*ptr < 0xC0); it->ptr = (uint8_t *)ptr; utf8lite_decode_utf8(&ptr, &it->current); } } // we are at an escape if we are preceded by an odd number of // backslash (\) characters static int at_escape(const uint8_t *begin, const uint8_t *ptr) { int at = 0; uint_fast8_t prev; while (begin < ptr) { prev = *(--ptr); if (prev != '\\') { goto out; } at = !at; } out: return at; } void iter_retreat_escaped(struct utf8lite_text_iter *it, const uint8_t *begin) { const uint8_t *ptr = it->ptr; int32_t code, unesc, hi; int i; code = *(--ptr); // check for 2-byte escape switch (code) { case '"': case '\\': case '/': unesc = code; break; case 'b': unesc = '\b'; break; case 'f': unesc = '\f'; break; case 'n': unesc = '\n'; break; case 'r': unesc = '\r'; break; case 't': unesc = '\t'; break; default: unesc = 0; break; } if (unesc) { if (at_escape(begin, ptr)) { ptr--; code = unesc; } goto out; } // check for 6-byte escape if (isxdigit((int)code)) { if (!(begin + 4 < ptr && ptr[-4] == 'u' && at_escape(begin, ptr - 4))) { goto out; } code = 0; for (i = 0; i < 4; i++) { code = (code << 4) + hextoi(ptr[i - 3]); } ptr -= 5; if (UTF8LITE_IS_UTF16_LOW(code)) { hi = 0; for (i = 0; i < 4; i++) { hi = (hi << 4) + hextoi(ptr[i - 4]); } code = UTF8LITE_DECODE_UTF16_PAIR(hi, code); ptr -= 6; } goto out; } // check for ascii if (code < 0x80) { goto out; } // if we got here, then code is a continuation byte // skip over preceding continuation bytes do { ptr--; } while (*ptr < 0xC0); // decode the utf-8 value it->ptr = (uint8_t *)ptr; utf8lite_decode_utf8(&ptr, &it->current); return; out: it->ptr = (uint8_t *)ptr; it->current = code; }
utf-8
1
Apache-2.0
2013-2018 Patrick O. Perry, Unicode, Inc.
qtcreator-6.0.2/src/plugins/qmldesigner/components/itemlibrary/itemlibraryassetimporter.cpp
/**************************************************************************** ** ** Copyright (C) 2019 The Qt Company Ltd. ** Contact: https://www.qt.io/licensing/ ** ** This file is part of Qt Creator. ** ** Commercial License Usage ** Licensees holding valid commercial Qt licenses may use this file in ** accordance with the commercial license agreement provided with the ** Software or, alternatively, in accordance with the terms contained in ** a written agreement between you and The Qt Company. For licensing terms ** and conditions see https://www.qt.io/terms-conditions. For further ** information use the contact form at https://www.qt.io/contact-us. ** ** GNU General Public License Usage ** Alternatively, this file may be used under the terms of the GNU ** General Public License version 3 as published by the Free Software ** Foundation with exceptions as appearing in the file LICENSE.GPL3-EXCEPT ** included in the packaging of this file. Please review the following ** information to ensure the GNU General Public License requirements will ** be met: https://www.gnu.org/licenses/gpl-3.0.html. ** ****************************************************************************/ #include "itemlibraryassetimporter.h" #include "assetimportupdatedialog.h" #include "qmldesignerplugin.h" #include "qmldesignerconstants.h" #include "rewriterview.h" #include "model.h" #include "puppetcreator.h" #include "rewritertransaction.h" #include "rewritingexception.h" #include <utils/algorithm.h> #include <QApplication> #include <QDir> #include <QDirIterator> #include <QFile> #include <QJsonDocument> #include <QJsonObject> #include <QLoggingCategory> #include <QMessageBox> #include <QPushButton> #include <QSaveFile> #include <QTemporaryDir> namespace { static Q_LOGGING_CATEGORY(importerLog, "qtc.itemlibrary.assetImporter", QtWarningMsg) } namespace QmlDesigner { ItemLibraryAssetImporter::ItemLibraryAssetImporter(QObject *parent) : QObject (parent) { } ItemLibraryAssetImporter::~ItemLibraryAssetImporter() { cancelImport(); delete m_tempDir; }; void ItemLibraryAssetImporter::importQuick3D(const QStringList &inputFiles, const QString &importPath, const QVector<QJsonObject> &options, const QHash<QString, int> &extToImportOptionsMap, const QSet<QString> &preselectedFilesForOverwrite) { if (m_isImporting) cancelImport(); reset(); m_isImporting = true; if (!m_tempDir->isValid()) { addError(tr("Could not create a temporary directory for import.")); notifyFinished(); return; } m_importPath = importPath; parseFiles(inputFiles, options, extToImportOptionsMap, preselectedFilesForOverwrite); if (!isCancelled()) { const auto parseData = m_parseData; for (const auto &pd : parseData) { if (!startImportProcess(pd)) { addError(tr("Failed to start import 3D asset process."), pd.sourceInfo.absoluteFilePath()); m_parseData.remove(pd.importId); } } } if (!isCancelled()) { // Wait for puppet processes to finish if (m_qmlPuppetProcesses.empty()) { postImport(); } else { m_qmlPuppetCount = static_cast<int>(m_qmlPuppetProcesses.size()); const QString progressTitle = tr("Importing 3D assets."); addInfo(progressTitle); notifyProgress(0, progressTitle); } } } bool ItemLibraryAssetImporter::isImporting() const { return m_isImporting; } void ItemLibraryAssetImporter::cancelImport() { m_cancelled = true; if (m_isImporting) notifyFinished(); } void ItemLibraryAssetImporter::addError(const QString &errMsg, const QString &srcPath) const { qCDebug(importerLog) << "Error: "<< errMsg << srcPath; emit errorReported(errMsg, srcPath); } void ItemLibraryAssetImporter::addWarning(const QString &warningMsg, const QString &srcPath) const { qCDebug(importerLog) << "Warning: " << warningMsg << srcPath; emit warningReported(warningMsg, srcPath); } void ItemLibraryAssetImporter::addInfo(const QString &infoMsg, const QString &srcPath) const { qCDebug(importerLog) << "Info: " << infoMsg << srcPath; emit infoReported(infoMsg, srcPath); } void ItemLibraryAssetImporter::importProcessFinished(int exitCode, QProcess::ExitStatus exitStatus) { Q_UNUSED(exitStatus) ++m_qmlImportFinishedCount; m_qmlPuppetProcesses.erase( std::remove_if(m_qmlPuppetProcesses.begin(), m_qmlPuppetProcesses.end(), [&](const auto &entry) { return !entry || entry->state() == QProcess::NotRunning; })); if (m_parseData.contains(-exitCode)) { const ParseData pd = m_parseData.take(-exitCode); addError(tr("Asset import process failed for: \"%1\".").arg(pd.sourceInfo.absoluteFilePath())); } if (m_qmlImportFinishedCount == m_qmlPuppetCount) { notifyProgress(100); QTimer::singleShot(0, this, &ItemLibraryAssetImporter::postImport); } else { notifyProgress(int(100. * (double(m_qmlImportFinishedCount) / double(m_qmlPuppetCount)))); } } void ItemLibraryAssetImporter::iconProcessFinished(int exitCode, QProcess::ExitStatus exitStatus) { Q_UNUSED(exitCode) Q_UNUSED(exitStatus) m_qmlPuppetProcesses.erase( std::remove_if(m_qmlPuppetProcesses.begin(), m_qmlPuppetProcesses.end(), [&](const auto &entry) { return !entry || entry->state() == QProcess::NotRunning; })); if (m_qmlPuppetProcesses.empty()) { notifyProgress(100); QTimer::singleShot(0, this, &ItemLibraryAssetImporter::finalizeQuick3DImport); } else { notifyProgress(int(100. * (1. - (double(m_qmlPuppetProcesses.size()) / double(m_qmlPuppetCount))))); } } void ItemLibraryAssetImporter::notifyFinished() { m_isImporting = false; emit importFinished(); } void ItemLibraryAssetImporter::reset() { m_isImporting = false; m_cancelled = false; delete m_tempDir; m_tempDir = new QTemporaryDir; m_importFiles.clear(); m_overwrittenImports.clear(); m_qmlPuppetProcesses.clear(); m_qmlPuppetCount = 0; m_qmlImportFinishedCount = 0; m_parseData.clear(); m_requiredImports.clear(); } void ItemLibraryAssetImporter::parseFiles(const QStringList &filePaths, const QVector<QJsonObject> &options, const QHash<QString, int> &extToImportOptionsMap, const QSet<QString> &preselectedFilesForOverwrite) { if (isCancelled()) return; const QString progressTitle = tr("Parsing files."); addInfo(progressTitle); notifyProgress(0, progressTitle); uint count = 0; double quota = 100.0 / filePaths.count(); std::function<void(double)> progress = [this, quota, &count, &progressTitle](double value) { notifyProgress(qRound(quota * (count + value)), progressTitle); }; for (const QString &file : filePaths) { int index = extToImportOptionsMap.value(QFileInfo(file).suffix()); ParseData pd; pd.options = options[index]; if (preParseQuick3DAsset(file, pd, preselectedFilesForOverwrite)) { pd.importId = ++m_importIdCounter; m_parseData.insert(pd.importId, pd); } notifyProgress(qRound(++count * quota), progressTitle); } } bool ItemLibraryAssetImporter::preParseQuick3DAsset(const QString &file, ParseData &pd, const QSet<QString> &preselectedFilesForOverwrite) { pd.targetDir = QDir(m_importPath); pd.outDir = QDir(m_tempDir->path()); pd.sourceInfo = QFileInfo(file); pd.assetName = pd.sourceInfo.completeBaseName(); if (!pd.assetName.isEmpty()) { // Fix name so it plays nice with imports for (QChar &currentChar : pd.assetName) { if (!currentChar.isLetter() && !currentChar.isDigit()) currentChar = QLatin1Char('_'); } const QChar firstChar = pd.assetName[0]; if (firstChar.isDigit()) pd.assetName[0] = QLatin1Char('_'); if (firstChar.isLower()) pd.assetName[0] = firstChar.toUpper(); } pd.targetDirPath = pd.targetDir.filePath(pd.assetName); if (pd.outDir.exists(pd.assetName)) { addWarning(tr("Skipped import of duplicate asset: \"%1\".").arg(pd.assetName)); return false; } pd.originalAssetName = pd.assetName; if (pd.targetDir.exists(pd.assetName)) { // If we have a file system with case insensitive filenames, assetName may be // different from the existing name. Modify assetName to ensure exact match to // the overwritten old asset capitalization const QStringList assetDirs = pd.targetDir.entryList({pd.assetName}, QDir::Dirs); if (assetDirs.size() == 1) { pd.assetName = assetDirs[0]; pd.targetDirPath = pd.targetDir.filePath(pd.assetName); } OverwriteResult result = preselectedFilesForOverwrite.isEmpty() ? confirmAssetOverwrite(pd.assetName) : OverwriteResult::Update; if (result == OverwriteResult::Skip) { addWarning(tr("Skipped import of existing asset: \"%1\".").arg(pd.assetName)); return false; } else if (result == OverwriteResult::Update) { // Add generated icons and existing source asset file, as those will always need // to be overwritten QSet<QString> alwaysOverwrite; QString iconPath = pd.targetDirPath + '/' + Constants::QUICK_3D_ASSET_ICON_DIR; // Note: Despite the name, QUICK_3D_ASSET_LIBRARY_ICON_SUFFIX is not a traditional file // suffix. It's guaranteed to be in the generated icon filename, though. QStringList filters {QStringLiteral("*%1*").arg(Constants::QUICK_3D_ASSET_LIBRARY_ICON_SUFFIX)}; QDirIterator iconIt(iconPath, filters, QDir::Files); while (iconIt.hasNext()) { iconIt.next(); alwaysOverwrite.insert(iconIt.fileInfo().absoluteFilePath()); } alwaysOverwrite.insert(sourceSceneTargetFilePath(pd)); alwaysOverwrite.insert(pd.targetDirPath + '/' + Constants::QUICK_3D_ASSET_IMPORT_DATA_NAME); Internal::AssetImportUpdateDialog dlg {pd.targetDirPath, preselectedFilesForOverwrite, alwaysOverwrite, qobject_cast<QWidget *>(parent())}; int exitVal = dlg.exec(); QStringList overwriteFiles; if (exitVal == QDialog::Accepted) overwriteFiles = dlg.selectedFiles(); if (!overwriteFiles.isEmpty()) { overwriteFiles.append(Utils::toList(alwaysOverwrite)); m_overwrittenImports.insert(pd.targetDirPath, overwriteFiles); } else { addWarning(tr("No files selected for overwrite, skipping import: \"%1\".").arg(pd.assetName)); return false; } } else { m_overwrittenImports.insert(pd.targetDirPath, {}); } } pd.outDir.mkpath(pd.assetName); if (!pd.outDir.cd(pd.assetName)) { addError(tr("Could not access temporary asset directory: \"%1\".") .arg(pd.outDir.filePath(pd.assetName))); return false; } return true; } void ItemLibraryAssetImporter::postParseQuick3DAsset(const ParseData &pd) { QDir outDir = pd.outDir; if (pd.originalAssetName != pd.assetName) { // Fix the generated qml file name const QString assetQml = pd.originalAssetName + ".qml"; if (outDir.exists(assetQml)) outDir.rename(assetQml, pd.assetName + ".qml"); } QHash<QString, QString> assetFiles; const int outDirPathSize = outDir.path().size(); auto insertAsset = [&](const QString &filePath) { QString targetPath = filePath.mid(outDirPathSize); targetPath.prepend(pd.targetDirPath); assetFiles.insert(filePath, targetPath); }; // Generate qmldir file if importer doesn't already make one QString qmldirFileName = outDir.absoluteFilePath(QStringLiteral("qmldir")); if (!QFileInfo::exists(qmldirFileName)) { QSaveFile qmldirFile(qmldirFileName); QString version = QStringLiteral("1.0"); // Note: Currently Quick3D importers only generate externally usable qml files on the top // level of the import directory, so we don't search subdirectories. The qml files in // subdirs assume they are used within the context of the toplevel qml files. QDirIterator qmlIt(outDir.path(), {QStringLiteral("*.qml")}, QDir::Files); if (qmlIt.hasNext()) { outDir.mkdir(Constants::QUICK_3D_ASSET_ICON_DIR); if (qmldirFile.open(QIODevice::WriteOnly | QIODevice::Truncate)) { QString qmlInfo; qmlInfo.append("module "); qmlInfo.append(m_importPath.split('/').last()); qmlInfo.append("."); qmlInfo.append(pd.assetName); qmlInfo.append('\n'); m_requiredImports.append(Import::createLibraryImport( QStringLiteral("%1.%2").arg(pd.targetDir.dirName(), pd.assetName), version)); while (qmlIt.hasNext()) { qmlIt.next(); QFileInfo fi = QFileInfo(qmlIt.filePath()); qmlInfo.append(fi.baseName()); qmlInfo.append(' '); qmlInfo.append(version); qmlInfo.append(' '); qmlInfo.append(outDir.relativeFilePath(qmlIt.filePath())); qmlInfo.append('\n'); // Generate item library icon for qml file based on root component QFile qmlFile(qmlIt.filePath()); if (qmlFile.open(QIODevice::ReadOnly)) { QString iconFileName = outDir.path() + '/' + Constants::QUICK_3D_ASSET_ICON_DIR + '/' + fi.baseName() + Constants::QUICK_3D_ASSET_LIBRARY_ICON_SUFFIX; QString iconFileName2x = iconFileName + "@2x"; QByteArray content = qmlFile.readAll(); int braceIdx = content.indexOf('{'); if (braceIdx != -1) { int nlIdx = content.lastIndexOf('\n', braceIdx); QByteArray rootItem = content.mid(nlIdx, braceIdx - nlIdx).trimmed(); if (rootItem == "Node") { // a 3D object // create hints file with proper hints QFile file(outDir.path() + '/' + fi.baseName() + ".hints"); file.open(QIODevice::WriteOnly | QIODevice::Text); QTextStream out(&file); out << "visibleInNavigator: true" << Qt::endl; out << "canBeDroppedInFormEditor: false" << Qt::endl; out << "canBeDroppedInView3D: true" << Qt::endl; file.close(); // Add quick3D import unless it is already added if (m_requiredImports.first().url() != "QtQuick3D") { QByteArray import3dStr{"import QtQuick3D"}; int importIdx = content.indexOf(import3dStr); if (importIdx != -1 && importIdx < braceIdx) { importIdx += import3dStr.size(); int nlIdx = content.indexOf('\n', importIdx); QByteArray versionStr = content.mid(importIdx, nlIdx - importIdx).trimmed(); // There could be 'as abc' after version, so just take first part QList<QByteArray> parts = versionStr.split(' '); QString impVersion; if (parts.size() >= 1) impVersion = QString::fromUtf8(parts[0]); m_requiredImports.prepend(Import::createLibraryImport( "QtQuick3D", impVersion)); } } } if (startIconProcess(24, iconFileName, qmlIt.filePath())) { // Since icon is generated by external process, the file won't be // ready for asset gathering below, so assume its generation succeeds // and add it now. insertAsset(iconFileName); insertAsset(iconFileName2x); } } } } qmldirFile.write(qmlInfo.toUtf8()); qmldirFile.commit(); } else { addError(tr("Failed to create qmldir file for asset: \"%1\".").arg(pd.assetName)); } } } // Generate import metadata file const QString sourcePath = pd.sourceInfo.absoluteFilePath(); QString importDataFileName = outDir.absoluteFilePath(Constants::QUICK_3D_ASSET_IMPORT_DATA_NAME); QSaveFile importDataFile(importDataFileName); if (importDataFile.open(QIODevice::WriteOnly | QIODevice::Truncate)) { QJsonObject optObj; optObj.insert(Constants::QUICK_3D_ASSET_IMPORT_DATA_OPTIONS_KEY, pd.options); optObj.insert(Constants::QUICK_3D_ASSET_IMPORT_DATA_SOURCE_KEY, sourcePath); importDataFile.write(QJsonDocument{optObj}.toJson()); importDataFile.commit(); } // Gather all generated files QDirIterator dirIt(outDir.path(), QDir::Files, QDirIterator::Subdirectories); while (dirIt.hasNext()) { dirIt.next(); insertAsset(dirIt.filePath()); } // Copy the original asset into a subdirectory assetFiles.insert(sourcePath, sourceSceneTargetFilePath(pd)); m_importFiles.insert(assetFiles); } void ItemLibraryAssetImporter::copyImportedFiles() { if (!m_overwrittenImports.isEmpty()) { const QString progressTitle = tr("Removing old overwritten assets."); addInfo(progressTitle); notifyProgress(0, progressTitle); int counter = 0; auto it = m_overwrittenImports.constBegin(); while (it != m_overwrittenImports.constEnd()) { QDir dir(it.key()); if (dir.exists()) { const auto &overwrittenFiles = it.value(); if (overwrittenFiles.isEmpty()) { // Overwrite entire import dir.removeRecursively(); } else { // Overwrite just selected files for (const auto &fileName : overwrittenFiles) QFile::remove(fileName); } } notifyProgress((100 * ++counter) / m_overwrittenImports.size(), progressTitle); ++it; } } if (!m_importFiles.isEmpty()) { const QString progressTitle = tr("Copying asset files."); addInfo(progressTitle); notifyProgress(0, progressTitle); int counter = 0; for (const auto &assetFiles : qAsConst(m_importFiles)) { // Only increase progress between entire assets instead of individual files, because // progress notify leads to processEvents call, which can lead to various filesystem // watchers triggering while library is still incomplete, leading to inconsistent model. // This also speeds up the copying as incomplete folder is not parsed unnecessarily // by filesystem watchers. QHash<QString, QString>::const_iterator it = assetFiles.begin(); while (it != assetFiles.end()) { if (QFileInfo::exists(it.key()) && !QFileInfo::exists(it.value())) { QDir targetDir = QFileInfo(it.value()).dir(); if (!targetDir.exists()) targetDir.mkpath("."); QFile::copy(it.key(), it.value()); } ++it; } notifyProgress((100 * ++counter) / m_importFiles.size(), progressTitle); } notifyProgress(100, progressTitle); } } void ItemLibraryAssetImporter::notifyProgress(int value, const QString &text) { m_progressTitle = text; emit progressChanged(value, m_progressTitle); keepUiAlive(); } void ItemLibraryAssetImporter::notifyProgress(int value) { notifyProgress(value, m_progressTitle); } void ItemLibraryAssetImporter::keepUiAlive() const { QApplication::processEvents(); } ItemLibraryAssetImporter::OverwriteResult ItemLibraryAssetImporter::confirmAssetOverwrite(const QString &assetName) { const QString title = tr("Overwrite Existing Asset?"); const QString question = tr("Asset already exists. Overwrite existing or skip?\n\"%1\"").arg(assetName); QMessageBox msgBox {QMessageBox::Question, title, question, QMessageBox::NoButton, qobject_cast<QWidget *>(parent())}; QPushButton *updateButton = msgBox.addButton(tr("Overwrite Selected Files"), QMessageBox::NoRole); QPushButton *overwriteButton = msgBox.addButton(tr("Overwrite All Files"), QMessageBox::NoRole); QPushButton *skipButton = msgBox.addButton(tr("Skip"), QMessageBox::NoRole); msgBox.setDefaultButton(overwriteButton); msgBox.setEscapeButton(skipButton); msgBox.exec(); if (msgBox.clickedButton() == updateButton) return OverwriteResult::Update; else if (msgBox.clickedButton() == overwriteButton) return OverwriteResult::Overwrite; return OverwriteResult::Skip; } bool ItemLibraryAssetImporter::startImportProcess(const ParseData &pd) { auto doc = QmlDesignerPlugin::instance()->currentDesignDocument(); Model *model = doc ? doc->currentModel() : nullptr; if (model) { PuppetCreator puppetCreator(doc->currentTarget(), model); puppetCreator.createQml2PuppetExecutableIfMissing(); QStringList puppetArgs; QJsonDocument optDoc(pd.options); puppetArgs << "--import3dAsset" << pd.sourceInfo.absoluteFilePath() << pd.outDir.absolutePath() << QString::number(pd.importId) << QString::fromUtf8(optDoc.toJson()); QProcessUniquePointer process = puppetCreator.createPuppetProcess( "custom", {}, std::function<void()>(), [&](int exitCode, QProcess::ExitStatus exitStatus) { importProcessFinished(exitCode, exitStatus); }, puppetArgs); if (process->waitForStarted(5000)) { m_qmlPuppetProcesses.push_back(std::move(process)); return true; } else { process.reset(); } } return false; } bool ItemLibraryAssetImporter::startIconProcess(int size, const QString &iconFile, const QString &iconSource) { auto doc = QmlDesignerPlugin::instance()->currentDesignDocument(); Model *model = doc ? doc->currentModel() : nullptr; if (model) { PuppetCreator puppetCreator(doc->currentTarget(), model); puppetCreator.createQml2PuppetExecutableIfMissing(); QStringList puppetArgs; puppetArgs << "--rendericon" << QString::number(size) << iconFile << iconSource; QProcessUniquePointer process = puppetCreator.createPuppetProcess( "custom", {}, std::function<void()>(), [&](int exitCode, QProcess::ExitStatus exitStatus) { iconProcessFinished(exitCode, exitStatus); }, puppetArgs); if (process->waitForStarted(5000)) { m_qmlPuppetProcesses.push_back(std::move(process)); return true; } else { process.reset(); } } return false; } void ItemLibraryAssetImporter::postImport() { Q_ASSERT(m_qmlPuppetProcesses.empty()); if (!isCancelled()) { for (const auto &pd : qAsConst(m_parseData)) postParseQuick3DAsset(pd); } if (!isCancelled()) { // Wait for icon generation processes to finish if (m_qmlPuppetProcesses.empty()) { finalizeQuick3DImport(); } else { m_qmlPuppetCount = static_cast<int>(m_qmlPuppetProcesses.size()); const QString progressTitle = tr("Generating icons."); addInfo(progressTitle); notifyProgress(0, progressTitle); } } } void ItemLibraryAssetImporter::finalizeQuick3DImport() { if (!isCancelled()) { // Don't allow cancel anymore as existing asset overwrites are not trivially recoverable. // Also, on Windows at least you can't delete a subdirectory of a watched directory, // so complete rollback is no longer possible in any case. emit importNearlyFinished(); copyImportedFiles(); auto doc = QmlDesignerPlugin::instance()->currentDesignDocument(); Model *model = doc ? doc->currentModel() : nullptr; if (model && !m_importFiles.isEmpty()) { const QString progressTitle = tr("Updating data model."); addInfo(progressTitle); notifyProgress(0, progressTitle); // First we have to wait a while to ensure qmljs detects new files and updates its // internal model. Then we make a non-change to the document to trigger qmljs snapshot // update. There is an inbuilt delay before rewriter change actually updates the data // model, so we need to wait for another moment to allow the change to take effect. // Otherwise subsequent subcomponent manager update won't detect new imports properly. QTimer *timer = new QTimer(parent()); static int counter; counter = 0; timer->callOnTimeout([this, timer, progressTitle, model, doc]() { if (!isCancelled()) { notifyProgress(++counter * 5, progressTitle); if (counter < 10) { // Do not proceed while application isn't active as the filesystem // watcher qmljs uses won't trigger unless application is active if (QApplication::applicationState() != Qt::ApplicationActive) --counter; } else if (counter == 10) { model->rewriterView()->textModifier()->replace(0, 0, {}); } else if (counter == 19) { try { const QList<Import> currentImports = model->imports(); QList<Import> newImportsToAdd; for (auto &imp : qAsConst(m_requiredImports)) { if (!currentImports.contains(imp)) newImportsToAdd.append(imp); } if (!newImportsToAdd.isEmpty()) { RewriterTransaction transaction = model->rewriterView()->beginRewriterTransaction( QByteArrayLiteral("ItemLibraryAssetImporter::finalizeQuick3DImport")); model->changeImports(newImportsToAdd, {}); transaction.commit(); } } catch (const RewritingException &e) { addError(tr("Failed to update imports: %1").arg(e.description())); } } else if (counter >= 20) { if (!m_overwrittenImports.isEmpty()) model->rewriterView()->emitCustomNotification("asset_import_update"); timer->stop(); notifyFinished(); } } else { timer->stop(); } }); timer->start(100); } else { notifyFinished(); } } } QString ItemLibraryAssetImporter::sourceSceneTargetFilePath(const ParseData &pd) { return pd.targetDirPath + QStringLiteral("/source scene/") + pd.sourceInfo.fileName(); } bool ItemLibraryAssetImporter::isCancelled() const { keepUiAlive(); return m_cancelled; } } // QmlDesigner
utf-8
1
GPL-3 with Qt-1.0 exception
2008-2020 The Qt Company
qemu-6.2+dfsg/roms/seabios-hppa/vgasrc/stdvga.h
#ifndef __STDVGA_H #define __STDVGA_H #include "types.h" // u8 // VGA registers #define VGAREG_ACTL_ADDRESS 0x3c0 #define VGAREG_ACTL_WRITE_DATA 0x3c0 #define VGAREG_ACTL_READ_DATA 0x3c1 #define VGAREG_INPUT_STATUS 0x3c2 #define VGAREG_WRITE_MISC_OUTPUT 0x3c2 #define VGAREG_VIDEO_ENABLE 0x3c3 #define VGAREG_SEQU_ADDRESS 0x3c4 #define VGAREG_SEQU_DATA 0x3c5 #define VGAREG_PEL_MASK 0x3c6 #define VGAREG_DAC_STATE 0x3c7 #define VGAREG_DAC_READ_ADDRESS 0x3c7 #define VGAREG_DAC_WRITE_ADDRESS 0x3c8 #define VGAREG_DAC_DATA 0x3c9 #define VGAREG_READ_FEATURE_CTL 0x3ca #define VGAREG_READ_MISC_OUTPUT 0x3cc #define VGAREG_GRDC_ADDRESS 0x3ce #define VGAREG_GRDC_DATA 0x3cf #define VGAREG_MDA_CRTC_ADDRESS 0x3b4 #define VGAREG_MDA_CRTC_DATA 0x3b5 #define VGAREG_VGA_CRTC_ADDRESS 0x3d4 #define VGAREG_VGA_CRTC_DATA 0x3d5 #define VGAREG_MDA_WRITE_FEATURE_CTL 0x3ba #define VGAREG_VGA_WRITE_FEATURE_CTL 0x3da #define VGAREG_ACTL_RESET 0x3da #define VGAREG_MDA_MODECTL 0x3b8 #define VGAREG_CGA_MODECTL 0x3d8 #define VGAREG_CGA_PALETTE 0x3d9 /* Video memory */ #define SEG_GRAPH 0xA000 #define SEG_CTEXT 0xB800 #define SEG_MTEXT 0xB000 // stdvga.c void stdvga_set_border_color(u8 color); void stdvga_set_overscan_border_color(u8 color); u8 stdvga_get_overscan_border_color(void); void stdvga_set_palette(u8 palid); void stdvga_set_all_palette_reg(u16 seg, u8 *data_far); void stdvga_get_all_palette_reg(u16 seg, u8 *data_far); void stdvga_toggle_intensity(u8 flag); void stdvga_select_video_dac_color_page(u8 flag, u8 data); void stdvga_read_video_dac_state(u8 *pmode, u8 *curpage); void stdvga_perform_gray_scale_summing(u16 start, u16 count); void stdvga_set_text_block_specifier(u8 spec); void stdvga_planar4_plane(int plane); void stdvga_load_font(u16 seg, void *src_far, u16 count , u16 start, u8 destflags, u8 fontsize); u16 stdvga_get_crtc(void); struct vgamode_s; int stdvga_vram_ratio(struct vgamode_s *vmode_g); void stdvga_set_cursor_shape(u16 cursor_type); void stdvga_set_cursor_pos(int address); void stdvga_set_scan_lines(u8 lines); u16 stdvga_get_vde(void); int stdvga_get_window(struct vgamode_s *vmode_g, int window); int stdvga_set_window(struct vgamode_s *vmode_g, int window, int val); int stdvga_get_linelength(struct vgamode_s *vmode_g); int stdvga_set_linelength(struct vgamode_s *vmode_g, int val); int stdvga_get_displaystart(struct vgamode_s *vmode_g); int stdvga_set_displaystart(struct vgamode_s *vmode_g, int val); int stdvga_get_dacformat(struct vgamode_s *vmode_g); int stdvga_set_dacformat(struct vgamode_s *vmode_g, int val); int stdvga_save_restore(int cmd, u16 seg, void *data); void stdvga_enable_video_addressing(u8 disable); int stdvga_setup(void); #endif // stdvga.h
utf-8
1
unknown
unknown
beignet-1.3.2/benchmark/benchmark_math.cpp
#include "utests/utest_helper.hpp" #include <sys/time.h> #include <cstdint> #include <cstdlib> #include <cstring> #include <iostream> #include "utest_helper.hpp" #include <sys/time.h> double benchmark_generic_math(const char* str_filename, const char* str_kernel) { double elapsed = 0; struct timeval start,stop; const size_t global_size = 1024 * 1024; const size_t local_size = 64; /* Compute math OP, loop times on global size */ cl_float base = 1.000002; cl_float pwr = 1.0102003; uint32_t loop = 1000; /* Input set will be generated */ float* src = (float*)calloc(sizeof(float), global_size); OCL_ASSERT(src != NULL); for(uint32_t i = 0; i < global_size; i++) src[i] = base + i * (base - 1); /* Setup kernel and buffers */ OCL_CALL(cl_kernel_init, str_filename, str_kernel, SOURCE, ""); OCL_CREATE_BUFFER(buf[0], 0, (global_size) * sizeof(float), NULL); OCL_CREATE_BUFFER(buf[1], 0, (global_size) * sizeof(float), NULL); OCL_MAP_BUFFER(0); memcpy(buf_data[0], src, global_size * sizeof(float)); OCL_UNMAP_BUFFER(0); globals[0] = global_size; locals[0] = local_size; OCL_SET_ARG(0, sizeof(cl_mem), &buf[0]); OCL_SET_ARG(1, sizeof(cl_mem), &buf[1]); OCL_SET_ARG(2, sizeof(cl_float), &pwr); OCL_SET_ARG(3, sizeof(cl_uint), &loop); /* Measure performance */ gettimeofday(&start,0); OCL_NDRANGE(1); clFinish(queue); gettimeofday(&stop,0); elapsed = time_subtract(&stop, &start, 0); /* Show compute results */ OCL_MAP_BUFFER(1); for(uint32_t i = 0; i < global_size; i += 8192) printf("\t%.3f", ((float*)buf_data[1])[i]); OCL_UNMAP_BUFFER(1); return BANDWIDTH(global_size * loop, elapsed); } double benchmark_math_pow(void){ return benchmark_generic_math("bench_math.cl", "bench_math_pow"); } MAKE_BENCHMARK_FROM_FUNCTION(benchmark_math_pow, "Mop/s"); double benchmark_math_exp2(void){ return benchmark_generic_math("bench_math.cl", "bench_math_exp2"); } MAKE_BENCHMARK_FROM_FUNCTION(benchmark_math_exp2, "Mop/s"); double benchmark_math_exp(void){ return benchmark_generic_math("bench_math.cl", "bench_math_exp"); } MAKE_BENCHMARK_FROM_FUNCTION(benchmark_math_exp, "Mop/s"); double benchmark_math_exp10(void){ return benchmark_generic_math("bench_math.cl", "bench_math_exp10"); } MAKE_BENCHMARK_FROM_FUNCTION(benchmark_math_exp10, "Mop/s"); double benchmark_math_log2(void){ return benchmark_generic_math("bench_math.cl", "bench_math_log2"); } MAKE_BENCHMARK_FROM_FUNCTION(benchmark_math_log2, "Mop/s"); double benchmark_math_log(void){ return benchmark_generic_math("bench_math.cl", "bench_math_log"); } MAKE_BENCHMARK_FROM_FUNCTION(benchmark_math_log, "Mop/s"); double benchmark_math_log10(void){ return benchmark_generic_math("bench_math.cl", "bench_math_log10"); } MAKE_BENCHMARK_FROM_FUNCTION(benchmark_math_log10, "Mop/s"); double benchmark_math_sqrt(void){ return benchmark_generic_math("bench_math.cl", "bench_math_sqrt"); } MAKE_BENCHMARK_FROM_FUNCTION(benchmark_math_sqrt, "Mop/s"); double benchmark_math_sin(void){ return benchmark_generic_math("bench_math.cl", "bench_math_sin"); } MAKE_BENCHMARK_FROM_FUNCTION(benchmark_math_sin, "Mop/s"); double benchmark_math_cos(void){ return benchmark_generic_math("bench_math.cl", "bench_math_cos"); } MAKE_BENCHMARK_FROM_FUNCTION(benchmark_math_cos, "Mop/s"); double benchmark_math_tan(void){ return benchmark_generic_math("bench_math.cl", "bench_math_tan"); } MAKE_BENCHMARK_FROM_FUNCTION(benchmark_math_tan, "Mop/s"); double benchmark_math_asin(void){ return benchmark_generic_math("bench_math.cl", "bench_math_asin"); } MAKE_BENCHMARK_FROM_FUNCTION(benchmark_math_asin, "Mop/s"); double benchmark_math_acos(void){ return benchmark_generic_math("bench_math.cl", "bench_math_acos"); } MAKE_BENCHMARK_FROM_FUNCTION(benchmark_math_acos, "Mop/s");
utf-8
1
LGPL-2.1+
2012-2017 Intel Corporation
libnetfilter-conntrack-1.0.9/utils/expect_get.c
#include <stdio.h> #include <stdlib.h> #include <string.h> #include <errno.h> #include <arpa/inet.h> #include <libnetfilter_conntrack/libnetfilter_conntrack.h> static int cb(enum nf_conntrack_msg_type type, struct nf_expect *exp, void *data) { char buf[1024]; nfexp_snprintf(buf, 1024, exp, NFCT_T_UNKNOWN, NFCT_O_DEFAULT, 0); printf("%s\n", buf); return NFCT_CB_CONTINUE; } int main(void) { int ret; struct nfct_handle *h; struct nf_conntrack *master; struct nf_expect *exp; master = nfct_new(); if (!master) { perror("nfct_new"); exit(EXIT_FAILURE); } nfct_set_attr_u8(master, ATTR_L3PROTO, AF_INET); nfct_set_attr_u32(master, ATTR_IPV4_SRC, inet_addr("1.1.1.1")); nfct_set_attr_u32(master, ATTR_IPV4_DST, inet_addr("2.2.2.2")); nfct_set_attr_u8(master, ATTR_L4PROTO, IPPROTO_TCP); nfct_set_attr_u16(master, ATTR_PORT_SRC, htons(10240)); nfct_set_attr_u16(master, ATTR_PORT_DST, htons(10241)); exp = nfexp_new(); if (!exp) { perror("nfexp_new"); nfct_destroy(master); exit(EXIT_FAILURE); } nfexp_set_attr(exp, ATTR_EXP_MASTER, master); h = nfct_open(EXPECT, 0); if (!h) { perror("nfct_open"); nfct_destroy(master); return -1; } nfexp_callback_register(h, NFCT_T_ALL, cb, NULL); ret = nfexp_query(h, NFCT_Q_GET, exp); printf("TEST: get expectation "); if (ret == -1) printf("(%d)(%s)\n", ret, strerror(errno)); else printf("(OK)\n"); nfct_close(h); nfct_destroy(master); ret == -1 ? exit(EXIT_FAILURE) : exit(EXIT_SUCCESS); }
utf-8
1
GPL-2+
2005-2011 Pablo Neira Ayuso <pablo@netfilter.org> 2005-2011 Harald Welte <laforge@netfilter.org>
samba-4.13.14+dfsg/lib/util/string_wrappers.h
/* Unix SMB/CIFS implementation. string wrappers, for checking string sizes Copyright (C) Andrew Tridgell 1994-2011 Copyright (C) Andrew Bartlett <abartlet@samba.org> 2003 This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see <http://www.gnu.org/licenses/>. */ #ifndef _STRING_WRAPPERS_H #define _STRING_WRAPPERS_H #define strlcpy_base(dest, src, base, size) \ do { \ const char *_strlcpy_base_src = (const char *)src; \ strlcpy((dest), _strlcpy_base_src? _strlcpy_base_src : "", (size)-PTR_DIFF((dest),(base))); \ } while (0) /* String copy functions - macro hell below adds 'type checking' (limited, but the best we can do in C) */ #define fstrcpy(d,s) \ do { \ const char *_fstrcpy_src = (const char *)(s); \ strlcpy((d),_fstrcpy_src ? _fstrcpy_src : "",sizeof(fstring)); \ } while (0) #define fstrcat(d,s) \ do { \ const char *_fstrcat_src = (const char *)(s); \ strlcat((d),_fstrcat_src ? _fstrcat_src : "",sizeof(fstring)); \ } while (0) #define unstrcpy(d,s) \ do { \ const char *_unstrcpy_src = (const char *)(s); \ strlcpy((d),_unstrcpy_src ? _unstrcpy_src : "",sizeof(unstring)); \ } while (0) #ifdef HAVE_COMPILER_WILL_OPTIMIZE_OUT_FNS /* We need a number of different prototypes for our non-existent fuctions */ char * __unsafe_string_function_usage_here__(void); size_t __unsafe_string_function_usage_here_size_t__(void); NTSTATUS __unsafe_string_function_usage_here_NTSTATUS__(void); #define CHECK_STRING_SIZE(d, len) (sizeof(d) != (len) && sizeof(d) != sizeof(char *)) /* if the compiler will optimize out function calls, then use this to tell if we are have the correct types (this works only where sizeof() returns the size of the buffer, not the size of the pointer). */ #define push_string_check(dest, src, dest_len, flags) \ (CHECK_STRING_SIZE(dest, dest_len) \ ? __unsafe_string_function_usage_here_size_t__() \ : push_string_check_fn(dest, src, dest_len, flags)) #define srvstr_push(base_ptr, smb_flags2, dest, src, dest_len, flags, ret_len) \ (CHECK_STRING_SIZE(dest, dest_len) \ ? __unsafe_string_function_usage_here_NTSTATUS__() \ : srvstr_push_fn(base_ptr, smb_flags2, dest, src, dest_len, flags, ret_len)) /* This allows the developer to choose to check the arguments to strlcpy. if the compiler will optimize out function calls, then use this to tell if we are have the correct size buffer (this works only where sizeof() returns the size of the buffer, not the size of the pointer), so stack and static variables only */ #define checked_strlcpy(dest, src, size) \ (sizeof(dest) != (size) \ ? __unsafe_string_function_usage_here_size_t__() \ : strlcpy(dest, src, size)) #else #define push_string_check push_string_check_fn #define srvstr_push srvstr_push_fn #define checked_strlcpy strlcpy #endif #endif
utf-8
1
GPL-3.0+
1992-2012 Andrew Tridgell and the Samba Team
cryfs-0.11.1/vendor/cryptopp/vendor_cryptopp/config_int.h
// config_int.h - written and placed in public domain by Jeffrey Walton // the bits that make up this source file are from the // library's monolithic config.h. /// \file config_int.h /// \brief Library configuration file /// \details <tt>config_int.h</tt> provides defines and typedefs for fixed /// size integers. The library's choices for fixed size integers predates other /// standard-based integers by about 5 years. After fixed sizes were /// made standard, the library continued to use its own definitions for /// compatibility with previous versions of the library. /// \details <tt>config.h</tt> was split into components in May 2019 to better /// integrate with Autoconf and its feature tests. The splitting occurred so /// users could continue to include <tt>config.h</tt> while allowing Autoconf /// to write new <tt>config_asm.h</tt> and new <tt>config_cxx.h</tt> using /// its feature tests. /// \note You should include <tt>config.h</tt> rather than <tt>config_int.h</tt> /// directly. /// \sa <A HREF="https://github.com/weidai11/cryptopp/issues/835">Issue 835, /// Make config.h more autoconf friendly</A>, /// <A HREF="https://www.cryptopp.com/wiki/Configure.sh">Configure.sh script</A> /// on the Crypto++ wiki /// \since Crypto++ 8.3 #ifndef CRYPTOPP_CONFIG_INT_H #define CRYPTOPP_CONFIG_INT_H #include "config_ns.h" #include "config_ver.h" /// \brief Library byte guard /// \details CRYPTOPP_NO_GLOBAL_BYTE indicates <tt>byte</tt> is in the Crypto++ /// namespace. /// \details The Crypto++ <tt>byte</tt> was originally in global namespace to avoid /// ambiguity with other byte typedefs. <tt>byte</tt> was moved to CryptoPP namespace /// at Crypto++ 6.0 due to C++17, <tt>std::byte</tt> and potential compile problems. /// \sa <A HREF="http://github.com/weidai11/cryptopp/issues/442">Issue 442</A>, /// <A HREF="https://www.cryptopp.com/wiki/Configure.sh">std::byte</A> on the /// Crypto++ wiki /// \since Crypto++ 6.0 #define CRYPTOPP_NO_GLOBAL_BYTE 1 NAMESPACE_BEGIN(CryptoPP) // Signed words added at Issue 609 for early versions of and Visual Studio and // the NaCl gear. Also see https://github.com/weidai11/cryptopp/issues/609. /// \brief 8-bit unsigned datatype /// \details The Crypto++ <tt>byte</tt> was originally in global namespace to avoid /// ambiguity with other byte typedefs. <tt>byte</tt> was moved to CryptoPP namespace /// at Crypto++ 6.0 due to C++17, <tt>std::byte</tt> and potential compile problems. /// \sa CRYPTOPP_NO_GLOBAL_BYTE, <A HREF="http://github.com/weidai11/cryptopp/issues/442">Issue 442</A>, /// <A HREF="https://www.cryptopp.com/wiki/Configure.sh">std::byte</A> on the /// Crypto++ wiki /// \since Crypto++ 1.0, CryptoPP namespace since Crypto++ 6.0 typedef unsigned char byte; /// \brief 16-bit unsigned datatype /// \since Crypto++ 1.0 typedef unsigned short word16; /// \brief 32-bit unsigned datatype /// \since Crypto++ 1.0 typedef unsigned int word32; /// \brief 8-bit signed datatype /// \details The 8-bit signed datatype was added to support constant time /// implementations for curve25519, X25519 key agreement and ed25519 /// signatures. /// \since Crypto++ 8.0 typedef signed char sbyte; /// \brief 16-bit signed datatype /// \details The 32-bit signed datatype was added to support constant time /// implementations for curve25519, X25519 key agreement and ed25519 /// signatures. /// \since Crypto++ 8.0 typedef signed short sword16; /// \brief 32-bit signed datatype /// \details The 32-bit signed datatype was added to support constant time /// implementations for curve25519, X25519 key agreement and ed25519 /// signatures. /// \since Crypto++ 8.0 typedef signed int sword32; #if defined(CRYPTOPP_DOXYGEN_PROCESSING) /// \brief 64-bit unsigned datatype /// \details The typedef for <tt>word64</tt> varies depending on the platform. /// On Microsoft platforms it is <tt>unsigned __int64</tt>. On Unix &amp; Linux /// with LP64 data model it is <tt>unsigned long</tt>. On Unix &amp; Linux with ILP32 /// data model it is <tt>unsigned long long</tt>. /// \since Crypto++ 1.0 typedef unsigned long long word64; /// \brief 64-bit signed datatype /// \details The typedef for <tt>sword64</tt> varies depending on the platform. /// On Microsoft platforms it is <tt>signed __int64</tt>. On Unix &amp; Linux /// with LP64 data model it is <tt>signed long</tt>. On Unix &amp; Linux with ILP32 /// data model it is <tt>signed long long</tt>. /// \since Crypto++ 8.0 typedef signed long long sword64; /// \brief 128-bit unsigned datatype /// \details The typedef for <tt>word128</tt> varies depending on the platform. /// <tt>word128</tt> is only available on 64-bit machines when /// <tt>CRYPTOPP_WORD128_AVAILABLE</tt> is defined. /// On Unix &amp; Linux with LP64 data model it is <tt>__uint128_t</tt>. /// Microsoft platforms do not provide a 128-bit integer type. 32-bit platforms /// do not provide a 128-bit integer type. /// \since Crypto++ 5.6 typedef __uint128_t word128; /// \brief Declare an unsigned word64 /// \details W64LIT is used to portability declare or assign 64-bit literal values. /// W64LIT will append the proper suffix to ensure the compiler accepts the literal. /// \details Use the macro like shown below. /// <pre> /// word64 x = W64LIT(0xffffffffffffffff); /// </pre> /// \since Crypto++ 1.0 #define W64LIT(x) ... /// \brief Declare a signed word64 /// \details SW64LIT is used to portability declare or assign 64-bit literal values. /// SW64LIT will append the proper suffix to ensure the compiler accepts the literal. /// \details Use the macro like shown below. /// <pre> /// sword64 x = SW64LIT(0xffffffffffffffff); /// </pre> /// \since Crypto++ 8.0 #define SW64LIT(x) ... /// \brief Declare ops on word64 are slow /// \details CRYPTOPP_BOOL_SLOW_WORD64 is typically defined to 1 on platforms /// that have a machine word smaller than 64-bits. That is, the define /// is present on 32-bit platforms. The define is also present on platforms /// where the cpu is slow even with a 64-bit cpu. #define CRYPTOPP_BOOL_SLOW_WORD64 ... #elif defined(_MSC_VER) || defined(__BORLANDC__) typedef signed __int64 sword64; typedef unsigned __int64 word64; #define SW64LIT(x) x##i64 #define W64LIT(x) x##ui64 #elif (_LP64 || __LP64__) typedef signed long sword64; typedef unsigned long word64; #define SW64LIT(x) x##L #define W64LIT(x) x##UL #else typedef signed long long sword64; typedef unsigned long long word64; #define SW64LIT(x) x##LL #define W64LIT(x) x##ULL #endif /// \brief Large word type /// \details lword is a typedef for large word types. It is used for file /// offsets and such. typedef word64 lword; /// \brief Large word type max value /// \details LWORD_MAX is the maximum value for large word types. /// Since an <tt>lword</tt> is an unsigned type, the value is /// <tt>0xffffffffffffffff</tt>. W64LIT will append the proper suffix. const lword LWORD_MAX = W64LIT(0xffffffffffffffff); #if defined(CRYPTOPP_DOXYGEN_PROCESSING) /// \brief Half word used for multiprecision integer arithmetic /// \details hword is used for multiprecision integer arithmetic. /// The typedef for <tt>hword</tt> varies depending on the platform. /// On 32-bit platforms it is usually <tt>word16</tt>. On 64-bit platforms /// it is usually <tt>word32</tt>. /// \details Library users typically use byte, word16, word32 and word64. /// \since Crypto++ 2.0 typedef word32 hword; /// \brief Full word used for multiprecision integer arithmetic /// \details word is used for multiprecision integer arithmetic. /// The typedef for <tt>word</tt> varies depending on the platform. /// On 32-bit platforms it is usually <tt>word32</tt>. On 64-bit platforms /// it is usually <tt>word64</tt>. /// \details Library users typically use byte, word16, word32 and word64. /// \since Crypto++ 2.0 typedef word64 word; /// \brief Double word used for multiprecision integer arithmetic /// \details dword is used for multiprecision integer arithmetic. /// The typedef for <tt>dword</tt> varies depending on the platform. /// On 32-bit platforms it is usually <tt>word64</tt>. On 64-bit Unix &amp; /// Linux platforms it is usually <tt>word128</tt>. <tt>word128</tt> is /// not available on Microsoft platforms. <tt>word128</tt> is only available /// when <tt>CRYPTOPP_WORD128_AVAILABLE</tt> is defined. /// \details Library users typically use byte, word16, word32 and word64. /// \sa CRYPTOPP_WORD128_AVAILABLE /// \since Crypto++ 2.0 typedef word128 dword; /// \brief 128-bit word availability /// \details CRYPTOPP_WORD128_AVAILABLE indicates a 128-bit word is /// available from the platform. 128-bit words are usually available on /// 64-bit platforms, but not available 32-bit platforms. /// \details If CRYPTOPP_WORD128_AVAILABLE is not defined, then 128-bit /// words are not available. /// \details GCC and compatible compilers signal 128-bit word availability /// with the preporcessor macro <tt>__SIZEOF_INT128__ >= 16</tt>. /// \since Crypto++ 2.0 #define CRYPTOPP_WORD128_AVAILABLE ... #else // define hword, word, and dword. these are used for multiprecision integer arithmetic // Intel compiler won't have _umul128 until version 10.0. See http://softwarecommunity.intel.com/isn/Community/en-US/forums/thread/30231625.aspx #if (defined(_MSC_VER) && (!defined(__INTEL_COMPILER) || __INTEL_COMPILER >= 1000) && (defined(_M_X64) || defined(_M_IA64))) || (defined(__DECCXX) && defined(__alpha__)) || (defined(__INTEL_COMPILER) && defined(__x86_64__)) || (defined(__SUNPRO_CC) && defined(__x86_64__)) typedef word32 hword; typedef word64 word; #else #define CRYPTOPP_NATIVE_DWORD_AVAILABLE 1 #if defined(__alpha__) || defined(__ia64__) || defined(_ARCH_PPC64) || defined(__x86_64__) || defined(__mips64) || defined(__sparc64__) || defined(__aarch64__) #if ((CRYPTOPP_GCC_VERSION >= 30400) || (CRYPTOPP_LLVM_CLANG_VERSION >= 30000) || (CRYPTOPP_APPLE_CLANG_VERSION >= 40300)) && (__SIZEOF_INT128__ >= 16) // GCC 4.0.1 on MacOS X is missing __umodti3 and __udivti3 // GCC 4.8.3 and bad uint128_t ops on PPC64/POWER7 (Issue 421) // mode(TI) division broken on amd64 with GCC earlier than GCC 3.4 typedef word32 hword; typedef word64 word; typedef __uint128_t dword; typedef __uint128_t word128; #define CRYPTOPP_WORD128_AVAILABLE 1 #else // if we're here, it means we're on a 64-bit CPU but we don't have a way to obtain 128-bit multiplication results typedef word16 hword; typedef word32 word; typedef word64 dword; #endif #else // being here means the native register size is probably 32 bits or less #define CRYPTOPP_BOOL_SLOW_WORD64 1 typedef word16 hword; typedef word32 word; typedef word64 dword; #endif #endif #endif #ifndef CRYPTOPP_BOOL_SLOW_WORD64 # define CRYPTOPP_BOOL_SLOW_WORD64 0 #endif /// \brief Size of a platform word in bytes /// \details The size of a platform word, in bytes const unsigned int WORD_SIZE = sizeof(word); /// \brief Size of a platform word in bits /// \details The size of a platform word, in bits const unsigned int WORD_BITS = WORD_SIZE * 8; NAMESPACE_END #endif // CRYPTOPP_CONFIG_INT_H
utf-8
1
LGPL-3
2016, Sebastian Messmer <messmer@cryfs.org>
knewstuff-5.90.0/src/core/questionlistener.cpp
/* This file is part of KNewStuffCore. SPDX-FileCopyrightText: 2016 Dan Leinir Turthra Jensen <admin@leinir.dk> SPDX-License-Identifier: LGPL-2.1-or-later */ #include "questionlistener.h" #include "questionmanager.h" using namespace KNSCore; QuestionListener::QuestionListener(QObject *parent) : QObject(parent) { connect(QuestionManager::instance(), &QuestionManager::askQuestion, this, &QuestionListener::askQuestion); } QuestionListener::~QuestionListener() { } void QuestionListener::askQuestion(Question *question) { Q_UNUSED(question) }
utf-8
1
LGPL-2.1+
2004, Aaron J. Seigo <aseigo@kde.org> 2020-2021, Alexander Lohnau <alexander.lohnau@gmx.de> 2004-2005, Andras Mantia <amantia@kde.org> 2002, Cornelius Schumacher <schumacher@kde.org> 2016-2021, Dan Leinir Turthra Jensen <admin@leinir.dk> 2007, Dirk Mueller <mueller@kde.org> 2005, Enrico Ros <eros.kde@email.it> 2007-2010, Frederik Gladhorn <gladhorn@kde.org> 2015, Gregor Mi <codestruct@posteo.org> 2007-2009, Jeremy Whiting <jpwhiting@kde.org> 2003-2007, Josef Spillner <spillner@kde.org> 2010, Matthias Fuchs <mat69@gmx.net> 2021, Oleg Solovyov <mcpain@altlinux.org> 2010, Reza Fatahilah Shah <rshah0385@kireihana.com>
gem-0.94/.pc/pd_error.patch/src/Gem/RTE.h
/*----------------------------------------------------------------- LOG GEM - Graphics Environment for Multimedia include Realtime-Environments headers Copyright (c) 2010-2011 IOhannes m zmölnig. forum::für::umläute. IEM. zmoelnig@iem.at For information on usage and redistribution, and for a DISCLAIMER OF ALL WARRANTIES, see the file, "GEM.LICENSE.TERMS" in this distribution. -----------------------------------------------------------------*/ #ifndef _INCLUDE__GEM_GEM_RTE_H_ #define _INCLUDE__GEM_GEM_RTE_H_ #if defined _MSC_VER /* data conversion with possible loss of data */ # pragma warning( push ) # pragma warning( disable : 4091 ) #endif #include "m_pd.h" #ifdef _MSC_VER # pragma warning( pop ) #endif #define GEMMARK() verbose(2, "%s:%d[%s]", __FILE__, __LINE__, __FUNCTION__) #endif /* _INCLUDE__GEM_GEM_RTE_H_ */
utf-8
1
GPL-2+
2001-2019, IOhannes m zmölnig. forum::für::umläute. IEM. zmoelnig@iem.at 1997-2000, Mark Danks Günther Geiger. geiger@epy.co.at 2003 Daniel Heckenberg 2002-2006 James Tittle II. tigital@mac.com 2002-2006 Chris Clepper. cgc@humboldtblvd.com 2006-2011 Cyrille Henry. cyrille.henry@la-kitchen.fr 1997-2019 Gem development team <gem-dev@iem.at>
gcc-arm-none-eabi-10.3-2021.07/gcc/testsuite/gcc.target/aarch64/test_frame_7.c
/* Verify: * -fomit-frame-pointer. * without outgoing. * total frame size > 512. * number of callee-saved reg == 2. * use a single stack adjustment, no writeback. */ /* { dg-do run } */ /* { dg-options "-O2 -fomit-frame-pointer --save-temps" } */ #include "test_frame_common.h" t_frame_pattern (test7, 700, "x19") t_frame_run (test7) /* { dg-final { scan-assembler-times "stp\tx19, x30, \\\[sp]" 1 } } */ /* { dg-final { scan-assembler "ldp\tx19, x30, \\\[sp\\\]" } } */
utf-8
1
unknown
unknown
paraview-5.10.0~rc1/VTK/ThirdParty/vtkm/vtkvtkm/vtk-m/vtkm/rendering/MapperCylinder.cxx
//============================================================================ // Copyright (c) Kitware, Inc. // All rights reserved. // See LICENSE.txt for details. // // This software is distributed WITHOUT ANY WARRANTY; without even // the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR // PURPOSE. See the above copyright notice for more information. //============================================================================ #include <vtkm/rendering/MapperCylinder.h> #include <vtkm/cont/Timer.h> #include <vtkm/cont/TryExecute.h> #include <vtkm/rendering/CanvasRayTracer.h> #include <vtkm/rendering/Cylinderizer.h> #include <vtkm/rendering/raytracing/Camera.h> #include <vtkm/rendering/raytracing/CylinderExtractor.h> #include <vtkm/rendering/raytracing/CylinderIntersector.h> #include <vtkm/rendering/raytracing/Logger.h> #include <vtkm/rendering/raytracing/RayOperations.h> #include <vtkm/rendering/raytracing/RayTracer.h> #include <vtkm/rendering/raytracing/Worklets.h> namespace vtkm { namespace rendering { class CalcDistance : public vtkm::worklet::WorkletMapField { public: VTKM_CONT CalcDistance(const vtkm::Vec3f_32& _eye_pos) : eye_pos(_eye_pos) { } typedef void ControlSignature(FieldIn, FieldOut); typedef void ExecutionSignature(_1, _2); template <typename VecType, typename OutType> VTKM_EXEC inline void operator()(const VecType& pos, OutType& out) const { VecType tmp = eye_pos - pos; out = static_cast<OutType>(vtkm::Sqrt(vtkm::dot(tmp, tmp))); } const vtkm::Vec3f_32 eye_pos; }; //class CalcDistance struct MapperCylinder::InternalsType { vtkm::rendering::CanvasRayTracer* Canvas; vtkm::rendering::raytracing::RayTracer Tracer; vtkm::rendering::raytracing::Camera RayCamera; vtkm::rendering::raytracing::Ray<vtkm::Float32> Rays; bool CompositeBackground; vtkm::Float32 Radius; vtkm::Float32 Delta; bool UseVariableRadius; VTKM_CONT InternalsType() : Canvas(nullptr) , CompositeBackground(true) , Radius(-1.0f) , Delta(0.5) , UseVariableRadius(false) { } }; MapperCylinder::MapperCylinder() : Internals(new InternalsType) { } MapperCylinder::~MapperCylinder() {} void MapperCylinder::SetCanvas(vtkm::rendering::Canvas* canvas) { if (canvas != nullptr) { this->Internals->Canvas = dynamic_cast<CanvasRayTracer*>(canvas); if (this->Internals->Canvas == nullptr) { throw vtkm::cont::ErrorBadValue("Ray Tracer: bad canvas type. Must be CanvasRayTracer"); } } else { this->Internals->Canvas = nullptr; } } vtkm::rendering::Canvas* MapperCylinder::GetCanvas() const { return this->Internals->Canvas; } void MapperCylinder::UseVariableRadius(bool useVariableRadius) { this->Internals->UseVariableRadius = useVariableRadius; } void MapperCylinder::SetRadius(const vtkm::Float32& radius) { if (radius <= 0.f) { throw vtkm::cont::ErrorBadValue("MapperCylinder: radius must be positive"); } this->Internals->Radius = radius; } void MapperCylinder::SetRadiusDelta(const vtkm::Float32& delta) { this->Internals->Delta = delta; } void MapperCylinder::RenderCells(const vtkm::cont::DynamicCellSet& cellset, const vtkm::cont::CoordinateSystem& coords, const vtkm::cont::Field& scalarField, const vtkm::cont::ColorTable& vtkmNotUsed(colorTable), const vtkm::rendering::Camera& camera, const vtkm::Range& scalarRange) { raytracing::Logger* logger = raytracing::Logger::GetInstance(); logger->OpenLogEntry("mapper_cylinder"); vtkm::cont::Timer tot_timer; tot_timer.Start(); vtkm::cont::Timer timer; vtkm::Bounds shapeBounds; raytracing::CylinderExtractor cylExtractor; vtkm::Float32 baseRadius = this->Internals->Radius; if (baseRadius == -1.f) { // set a default radius vtkm::cont::ArrayHandle<vtkm::Float32> dist; vtkm::worklet::DispatcherMapField<CalcDistance>(CalcDistance(camera.GetPosition())) .Invoke(coords, dist); vtkm::Float32 min_dist = vtkm::cont::Algorithm::Reduce(dist, vtkm::Infinity<vtkm::Float32>(), vtkm::Minimum()); baseRadius = 0.576769694f * min_dist - 0.603522029f * vtkm::Pow(vtkm::Float32(min_dist), 2.f) + 0.232171175f * vtkm::Pow(vtkm::Float32(min_dist), 3.f) - 0.038697244f * vtkm::Pow(vtkm::Float32(min_dist), 4.f) + 0.002366979f * vtkm::Pow(vtkm::Float32(min_dist), 5.f); baseRadius /= min_dist; vtkm::worklet::DispatcherMapField<vtkm::rendering::raytracing::MemSet<vtkm::Float32>>( vtkm::rendering::raytracing::MemSet<vtkm::Float32>(baseRadius)) .Invoke(cylExtractor.GetRadii()); } if (this->Internals->UseVariableRadius) { vtkm::Float32 minRadius = baseRadius - baseRadius * this->Internals->Delta; vtkm::Float32 maxRadius = baseRadius + baseRadius * this->Internals->Delta; cylExtractor.ExtractCells(cellset, scalarField, minRadius, maxRadius); } else { cylExtractor.ExtractCells(cellset, baseRadius); } // // Add supported shapes // if (cylExtractor.GetNumberOfCylinders() > 0) { auto cylIntersector = std::make_shared<raytracing::CylinderIntersector>(); cylIntersector->SetData(coords, cylExtractor.GetCylIds(), cylExtractor.GetRadii()); this->Internals->Tracer.AddShapeIntersector(cylIntersector); shapeBounds.Include(cylIntersector->GetShapeBounds()); } // // Create rays // vtkm::Int32 width = (vtkm::Int32)this->Internals->Canvas->GetWidth(); vtkm::Int32 height = (vtkm::Int32)this->Internals->Canvas->GetHeight(); this->Internals->RayCamera.SetParameters(camera, width, height); this->Internals->RayCamera.CreateRays(this->Internals->Rays, shapeBounds); this->Internals->Rays.Buffers.at(0).InitConst(0.f); raytracing::RayOperations::MapCanvasToRays( this->Internals->Rays, camera, *this->Internals->Canvas); this->Internals->Tracer.SetField(scalarField, scalarRange); this->Internals->Tracer.GetCamera() = this->Internals->RayCamera; this->Internals->Tracer.SetColorMap(this->ColorMap); this->Internals->Tracer.Render(this->Internals->Rays); timer.Start(); this->Internals->Canvas->WriteToCanvas( this->Internals->Rays, this->Internals->Rays.Buffers.at(0).Buffer, camera); if (this->Internals->CompositeBackground) { this->Internals->Canvas->BlendBackground(); } vtkm::Float64 time = timer.GetElapsedTime(); logger->AddLogData("write_to_canvas", time); time = tot_timer.GetElapsedTime(); logger->CloseLogEntry(time); } void MapperCylinder::SetCompositeBackground(bool on) { this->Internals->CompositeBackground = on; } vtkm::rendering::Mapper* MapperCylinder::NewCopy() const { return new vtkm::rendering::MapperCylinder(*this); } } } // vtkm::rendering
utf-8
1
BSD-3-clause
2000-2005 Kitware Inc. 28 Corporate Drive, Suite 204, Clifton Park, NY, 12065, USA. 2000-2005 Kitware Inc. 28 Corporate Drive, Suite 204, Clifton Park, NY, 12065, USA.
kannel-1.4.5/wmlscript/ws.c
/* ==================================================================== * The Kannel Software License, Version 1.0 * * Copyright (c) 2001-2018 Kannel Group * Copyright (c) 1998-2001 WapIT Ltd. * 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. The end-user documentation included with the redistribution, * if any, must include the following acknowledgment: * "This product includes software developed by the * Kannel Group (http://www.kannel.org/)." * Alternately, this acknowledgment may appear in the software itself, * if and wherever such third-party acknowledgments normally appear. * * 4. The names "Kannel" and "Kannel Group" must not be used to * endorse or promote products derived from this software without * prior written permission. For written permission, please * contact org@kannel.org. * * 5. Products derived from this software may not be called "Kannel", * nor may "Kannel" appear in their name, without prior written * permission of the Kannel Group. * * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED 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 KANNEL GROUP OR ITS 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. * ==================================================================== * * This software consists of voluntary contributions made by many * individuals on behalf of the Kannel Group. For more information on * the Kannel Group, please see <http://www.kannel.org/>. * * Portions of this software are based upon software originally written at * WapIT Ltd., Helsinki, Finland for the Kannel project. */ /* * * ws.c * * Author: Markku Rossi <mtr@iki.fi> * * Copyright (c) 1999-2000 WAPIT OY LTD. * All rights reserved. * * Public entry points to the WMLScript compiler and the main compile * function. * */ #include "wsint.h" #include "ws.h" #include "wsstree.h" #include "wsasm.h" /********************* Types and definitions ****************************/ #define WS_CHECK_COMPILE_ERROR() \ do { \ if (compiler->errors != 0) { \ if (compiler->errors & WS_ERROR_B_MEMORY) \ result = WS_ERROR_OUT_OF_MEMORY; \ else if (compiler->errors & WS_ERROR_B_SYNTAX) \ result = WS_ERROR_SYNTAX; \ else if (compiler->errors & WS_ERROR_B_SEMANTIC) \ result = WS_ERROR_SEMANTIC; \ else \ /* This shouldn't happen. */ \ result = WS_ERROR; \ goto out; \ } \ } while (0); /********************* Static variables *********************************/ /* Human readable names for the result codes. */ static struct { WsResult code; char *description; } result_codes[] = { { WS_OK, "success" }, { WS_ERROR_OUT_OF_MEMORY, "out of memory" }, { WS_ERROR_SYNTAX, "syntax error" }, { WS_ERROR_SEMANTIC, "compile error" }, { WS_ERROR_IO, "IO error" }, { WS_ERROR, "error" }, { 0, NULL }, }; /********************* Prototypes for static functions ******************/ /* Compile the input stream `input' with the compiler `compiler' and return the byte-code in `output_return' and its length in `output_len_return'. The function returns a WsResult error code describing the success of the compilation. */ static WsResult compile_stream(WsCompilerPtr compiler, const char *input_name, WsStream *input, unsigned char **output_return, size_t *output_len_return); /* The default I/O function to send the output to stdout and stderr. The argument `context' must be a `FILE *' file to which the output is written. */ static void std_io(const char *data, size_t len, void *context); /* A comparison function for functions entries when sorting them by their usage counts. The function is stable maintaining their original order if their usage counts are equal. */ static int sort_functions_cmp(const void *a, const void *b); /********************* Global functions *********************************/ WsCompilerPtr ws_create(WsCompilerParams *params) { WsCompilerPtr compiler = ws_calloc(1, sizeof(*compiler)); if (compiler == NULL) return NULL; /* Store user params if specified. */ if (params) compiler->params = *params; /* Basic initialization. */ compiler->magic = COMPILER_MAGIC; if (compiler->params.stdout_cb == NULL) { compiler->params.stdout_cb = std_io; compiler->params.stdout_cb_context = stdout; } if (compiler->params.stderr_cb == NULL) { compiler->params.stderr_cb = std_io; compiler->params.stderr_cb_context = stderr; } return compiler; } void ws_destroy(WsCompilerPtr compiler) { if (compiler == NULL) return; ws_free(compiler); #if WS_MEM_DEBUG if (ws_has_leaks()) ws_dump_blocks(); #endif /* WS_MEM_DEBUG */ } WsResult ws_compile_file(WsCompilerPtr compiler, const char *input_name, FILE *input, FILE *output) { WsResult result; WsStream *stream; unsigned char *bc; size_t bc_len; /* Initialize the input stream. */ stream = ws_stream_new_file(input, WS_FALSE, WS_FALSE); if (stream == NULL) return WS_ERROR_OUT_OF_MEMORY; result = compile_stream(compiler, input_name, stream, &bc, &bc_len); ws_stream_close(stream); if (result == WS_OK) { /* Store the result to the file. */ if (fwrite(bc, 1, bc_len, output) != bc_len) result = WS_ERROR_IO; ws_bc_data_free(bc); } return result; } WsResult ws_compile_data(WsCompilerPtr compiler, const char *input_name, const unsigned char *input, size_t input_len, unsigned char **output_return, size_t *output_len_return) { WsResult result; WsStream *stream; /* Initialize the input stream. */ stream = ws_stream_new_data_input(input, input_len); if (stream == NULL) return WS_ERROR_OUT_OF_MEMORY; result = compile_stream(compiler, input_name, stream, output_return, output_len_return); ws_stream_close(stream); return result; } void ws_free_byte_code(unsigned char *byte_code) { ws_bc_data_free(byte_code); } const char *ws_result_to_string(WsResult result) { int i; for (i = 0; result_codes[i].description; i++) { if (result_codes[i].code == result) return result_codes[i].description; } return "unknown result code"; } /********************* Lexer's memory handling helpers ******************/ WsBool ws_lexer_register_block(WsCompiler *compiler, void *ptr) { void **n; if (ptr == NULL) return WS_TRUE; n = ws_realloc(compiler->lexer_active_list, ((compiler->lexer_active_list_size + 1) * sizeof(void *))); if (n == NULL) return WS_FALSE; compiler->lexer_active_list = n; compiler->lexer_active_list[compiler->lexer_active_list_size++] = ptr; return WS_TRUE; } WsBool ws_lexer_register_utf8(WsCompiler *compiler, WsUtf8String *string) { if (!ws_lexer_register_block(compiler, string)) return WS_FALSE; if (!ws_lexer_register_block(compiler, string->data)) { compiler->lexer_active_list_size--; return WS_FALSE; } return WS_TRUE; } void ws_lexer_free_block(WsCompiler *compiler, void *ptr) { int i; if (ptr == NULL) return; for (i = compiler->lexer_active_list_size - 1; i >= 0; i--) { if (compiler->lexer_active_list[i] == ptr) { memmove(&compiler->lexer_active_list[i], &compiler->lexer_active_list[i + 1], (compiler->lexer_active_list_size - i - 1) * sizeof(void *)); compiler->lexer_active_list_size--; ws_free(ptr); return; } } ws_fatal("ws_lexer_free_block(): unknown block 0x%lx", (unsigned long) ptr); } void ws_lexer_free_utf8(WsCompiler *compiler, WsUtf8String *string) { if (string == NULL) return; ws_lexer_free_block(compiler, string->data); ws_lexer_free_block(compiler, string); } /********************* Static functions *********************************/ static WsResult compile_stream(WsCompilerPtr compiler, const char *input_name, WsStream *input, unsigned char **output_return, size_t *output_len_return) { WsResult result = WS_OK; WsUInt32 i; WsListItem *li; WsUInt8 findex; WsUInt8 num_locals; WsBcStringEncoding string_encoding = WS_BC_STRING_ENC_UTF8; /* Initialize the compiler context. */ compiler->linenum = 1; compiler->input_name = input_name; compiler->num_errors = 0; compiler->num_warnings = 0; compiler->num_extern_functions = 0; compiler->num_local_functions = 0; compiler->errors = 0; compiler->last_syntax_error_line = 0; /* Allocate fast-malloc pool for the syntax tree. */ compiler->pool_stree = ws_f_create(1024 * 1024); if (compiler->pool_stree == NULL) { result = WS_ERROR_OUT_OF_MEMORY; goto out; } /* Allocate hash tables. */ compiler->pragma_use_hash = ws_pragma_use_hash_create(); if (compiler->pragma_use_hash == NULL) { result = WS_ERROR_OUT_OF_MEMORY; goto out; } compiler->functions_hash = ws_function_hash_create(); if (compiler->functions_hash == NULL) { result = WS_ERROR_OUT_OF_MEMORY; goto out; } /* Allocate a byte-code module. */ if (compiler->params.use_latin1_strings) string_encoding = WS_BC_STRING_ENC_ISO_8859_1; compiler->bc = ws_bc_alloc(string_encoding); if (compiler->bc == NULL) { result = WS_ERROR_OUT_OF_MEMORY; goto out; } /* Save the input stream. */ compiler->input = input; /* Parse the input. */ #if WS_DEBUG global_compiler = compiler; #endif /* WS_DEBUG */ ws_yy_parse(compiler); /* Free all lexer's active not freed blocks. If we have any blocks on the used list, our compilation was not successful. */ { size_t j; for (j = 0; j < compiler->lexer_active_list_size; j++) ws_free(compiler->lexer_active_list[j]); ws_free(compiler->lexer_active_list); compiler->lexer_active_list = NULL; } WS_CHECK_COMPILE_ERROR(); /* Sort functions if allowed and it helps. */ if (!compiler->params.no_opt_sort_bc_functions && compiler->num_functions > 7) { WsUInt32 i; ws_info(compiler, "optimize: sorting functions"); /* Fetch the usage counts from the functions hash. */ for (i = 0; i < compiler->num_functions; i++) { WsFunctionHash *fh = ws_function_hash(compiler, compiler->functions[i].name); compiler->functions[i].usage_count = fh->usage_count; } /* Sort functions. */ qsort(compiler->functions, compiler->num_functions, sizeof(compiler->functions[0]), sort_functions_cmp); /* Patch the function indexes. */ for (i = 0; i < compiler->num_functions; i++) { WsFunctionHash *fh = ws_function_hash(compiler, compiler->functions[i].name); compiler->functions[i].findex = i; fh->findex = i; } } /* Linearize functions */ for (i = 0; i < compiler->num_functions; i++) { WsFunction *func = &compiler->functions[i]; ws_info(compiler, "linearizing function `%s'...", func->name); compiler->pool_asm = ws_f_create(100 * 1024); if (compiler->pool_asm == NULL) { result = WS_ERROR_OUT_OF_MEMORY; goto out; } compiler->next_label = 0; compiler->asm_head = compiler->asm_tail = NULL; /* Create variables namespace. */ compiler->next_vindex = 0; compiler->variables_hash = ws_variable_hash_create(); if (compiler->variables_hash == NULL) { result = WS_ERROR_OUT_OF_MEMORY; goto out; } /* Define the formal arguments to the namespace. */ for (li = func->params->head; li; li = li->next) { WsFormalParm *parm = li->data; ws_variable_define(compiler, parm->line, WS_FALSE, parm->name); } WS_CHECK_COMPILE_ERROR(); /* Linearize it. */ for (li = func->block->head; li; li = li->next) ws_stmt_linearize(compiler, li->data); WS_CHECK_COMPILE_ERROR(); /* Optimize symbolic assembler. This function does nothing if no optimizations were requested. */ ws_asm_optimize(compiler); /* Print the resulting symbolic assembler if requested. */ if (compiler->params.print_symbolic_assembler) ws_asm_print(compiler); WS_CHECK_COMPILE_ERROR(); /* Generate byte-code */ ws_buffer_init(&compiler->byte_code); ws_asm_linearize(compiler); WS_CHECK_COMPILE_ERROR(); /* Disassemble the output if requested. */ if (compiler->params.print_assembler) ws_asm_dasm(compiler, ws_buffer_ptr(&compiler->byte_code), ws_buffer_len(&compiler->byte_code)); /* Calculate the number of local variables */ num_locals = compiler->next_vindex - func->params->num_items; /* Add the function to the byte-code module. */ if (!ws_bc_add_function(compiler->bc, &findex, func->externp ? func->name : NULL, func->params->num_items, num_locals, ws_buffer_len(&compiler->byte_code), ws_buffer_ptr(&compiler->byte_code))) { result = WS_ERROR_OUT_OF_MEMORY; goto out; } /* Cleanup and prepare for the next function. */ ws_buffer_uninit(&compiler->byte_code); ws_hash_destroy(compiler->variables_hash); compiler->variables_hash = NULL; ws_f_destroy(compiler->pool_asm); compiler->pool_asm = NULL; } /* Linearize the byte-code structure. */ if (!ws_bc_encode(compiler->bc, output_return, output_len_return)) result = WS_ERROR_OUT_OF_MEMORY; out: /* Cleanup. */ ws_f_destroy(compiler->pool_stree); compiler->pool_stree = NULL; ws_hash_destroy(compiler->pragma_use_hash); compiler->pragma_use_hash = NULL; /* Free functions. */ for (i = 0; i < compiler->num_functions; i++) ws_free(compiler->functions[i].name); ws_free(compiler->functions); ws_hash_destroy(compiler->functions_hash); compiler->functions_hash = NULL; ws_bc_free(compiler->bc); compiler->bc = NULL; compiler->input = NULL; ws_f_destroy(compiler->pool_asm); compiler->pool_asm = NULL; ws_hash_destroy(compiler->variables_hash); compiler->variables_hash = NULL; ws_buffer_uninit(&compiler->byte_code); /* All done. */ return result; } static void std_io(const char *data, size_t len, void *context) { fwrite(data, 1, len, (FILE *) context); } static int sort_functions_cmp(const void *a, const void *b) { WsFunction *fa = (WsFunction *) a; WsFunction *fb = (WsFunction *) b; if (fa->usage_count > fb->usage_count) return -1; if (fa->usage_count < fb->usage_count) return 1; if (fa->findex < fb->findex) return -1; return 1; }
utf-8
1
KannelSL-1.0
1998-2001, WapIT Ltd 2001-2018, Kannel Group
k3d-0.8.0.6/modules/polyhedron_sources/poly_cylinder.cpp
// K-3D // Copyright (c) 1995-2009, Timothy M. Shead // // Contact: tshead@k-3d.com // // This program is free software; you can redistribute it and/or // modify it under the terms of the GNU General Public // License as published by the Free Software Foundation; either // version 2 of the License, or (at your option) any later version. // // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU // General Public License for more details. // // You should have received a copy of the GNU General Public // License along with this program; if not, write to the Free Software // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA /** \file \author Timothy M. Shead (tshead@k-3d.com) \author Romain Behar (romainbehar@yahoo.com) */ #include <k3d-i18n-config.h> #include <k3dsdk/document_plugin_factory.h> #include <k3dsdk/imaterial.h> #include <k3dsdk/mesh_source.h> #include <k3dsdk/material_sink.h> #include <k3dsdk/measurement.h> #include <k3dsdk/node.h> #include <k3dsdk/polyhedron.h> namespace module { namespace polyhedron { namespace sources { ///////////////////////////////////////////////////////////////////////////// // poly_cylinder class poly_cylinder : public k3d::material_sink<k3d::mesh_source<k3d::node > > { typedef k3d::material_sink<k3d::mesh_source<k3d::node > > base; public: poly_cylinder(k3d::iplugin_factory& Factory, k3d::idocument& Document) : base(Factory, Document), m_u_segments(init_owner(*this) + init_name("u_segments") + init_label(_("U segments")) + init_description(_("Columns")) + init_value(32) + init_constraint(constraint::minimum<k3d::int32_t>(3)) + init_step_increment(1) + init_units(typeid(k3d::measurement::scalar))), m_v_segments(init_owner(*this) + init_name("v_segments") + init_label(_("V segments")) + init_description(_("Rows")) + init_value(5) + init_constraint(constraint::minimum<k3d::int32_t>(1)) + init_step_increment(1) + init_units(typeid(k3d::measurement::scalar))), m_top(init_owner(*this) + init_name("top") + init_label(_("Top")) + init_description(_("Cap cylinder top")) + init_value(true)), m_bottom(init_owner(*this) + init_name("bottom") + init_label(_("Bottom")) + init_description(_("Cap cylinder bottom")) + init_value(true)), m_radius(init_owner(*this) + init_name("radius") + init_label(_("Radius")) + init_description(_("Cylinder radius")) + init_value(5.0) + init_step_increment(0.1) + init_units(typeid(k3d::measurement::distance))), m_zmax(init_owner(*this) + init_name("zmax") + init_label(_("Z max")) + init_description(_("Z max (RenderMan convention)")) + init_value(5.0) + init_step_increment(0.1) + init_units(typeid(k3d::measurement::distance))), m_zmin(init_owner(*this) + init_name("zmin") + init_label(_("Z min")) + init_description(_("Z min (RenderMan convention)")) + init_value(-5.0) + init_step_increment(0.1) + init_units(typeid(k3d::measurement::distance))), m_u_power(init_owner(*this) + init_name("u_power") + init_label(_("U power")) + init_description(_("Radial power")) + init_value(1.0) + init_step_increment(0.1) + init_units(typeid(k3d::measurement::scalar))), m_top_segments(init_owner(*this) + init_name("top_segments") + init_label(_("Top segments")) + init_description(_("0 : single face, >= 1 : segments")) + init_value(0) + init_constraint(constraint::minimum<k3d::int32_t>(0)) + init_step_increment(1) + init_units(typeid(k3d::measurement::scalar))), m_bottom_segments(init_owner(*this) + init_name("bottom_segments") + init_label(_("Bottom segments")) + init_description(_("0 : single face, >= 1 : segments")) + init_value(0) + init_constraint(constraint::minimum<k3d::int32_t>(0)) + init_step_increment(1) + init_units(typeid(k3d::measurement::scalar))) { m_material.changed_signal().connect(k3d::hint::converter< k3d::hint::convert<k3d::hint::any, k3d::hint::none> >(make_update_mesh_slot())); m_u_segments.changed_signal().connect(k3d::hint::converter< k3d::hint::convert<k3d::hint::any, k3d::hint::none> >(make_update_mesh_slot())); m_v_segments.changed_signal().connect(k3d::hint::converter< k3d::hint::convert<k3d::hint::any, k3d::hint::none> >(make_update_mesh_slot())); m_top.changed_signal().connect(k3d::hint::converter< k3d::hint::convert<k3d::hint::any, k3d::hint::none> >(make_update_mesh_slot())); m_bottom.changed_signal().connect(k3d::hint::converter< k3d::hint::convert<k3d::hint::any, k3d::hint::none> >(make_update_mesh_slot())); m_radius.changed_signal().connect(k3d::hint::converter< k3d::hint::convert<k3d::hint::any, k3d::hint::none> >(make_update_mesh_slot())); m_zmax.changed_signal().connect(k3d::hint::converter< k3d::hint::convert<k3d::hint::any, k3d::hint::none> >(make_update_mesh_slot())); m_zmin.changed_signal().connect(k3d::hint::converter< k3d::hint::convert<k3d::hint::any, k3d::hint::none> >(make_update_mesh_slot())); m_u_power.changed_signal().connect(k3d::hint::converter< k3d::hint::convert<k3d::hint::any, k3d::hint::none> >(make_update_mesh_slot())); m_top_segments.changed_signal().connect(k3d::hint::converter< k3d::hint::convert<k3d::hint::any, k3d::hint::none> >(make_update_mesh_slot())); m_bottom_segments.changed_signal().connect(k3d::hint::converter< k3d::hint::convert<k3d::hint::any, k3d::hint::none> >(make_update_mesh_slot())); } void on_update_mesh_topology(k3d::mesh& Output) { Output = k3d::mesh(); k3d::imaterial* const material = m_material.pipeline_value(); const k3d::int32_t u_segments = m_u_segments.pipeline_value(); const k3d::int32_t v_segments = m_v_segments.pipeline_value(); const k3d::double_t radius = m_radius.pipeline_value(); const k3d::double_t zmax = m_zmax.pipeline_value(); const k3d::double_t zmin = m_zmin.pipeline_value(); const k3d::double_t u_power = m_u_power.pipeline_value(); const k3d::double_t inv_u_power = u_power ? 1.0 / u_power : 1.0; const k3d::bool_t top = m_top.pipeline_value(); const k3d::bool_t bottom = m_bottom.pipeline_value(); const k3d::int32_t top_segments = m_top_segments.pipeline_value(); const k3d::int32_t bottom_segments = m_bottom_segments.pipeline_value(); boost::scoped_ptr<k3d::polyhedron::primitive> polyhedron(k3d::polyhedron::create(Output)); polyhedron->shell_types.push_back(k3d::polyhedron::POLYGONS); k3d::polyhedron::add_cylinder(Output, *polyhedron, 0, v_segments, u_segments, material); k3d::mesh::points_t& points = Output.points.writable(); k3d::mesh::selection_t& point_selection = Output.point_selection.writable(); // Shape the cylinder points for(k3d::int32_t v = 0; v <= v_segments; ++v) { const k3d::double_t height = k3d::ratio(v, v_segments); for(k3d::int32_t u = 0; u != u_segments; ++u) { const k3d::double_t theta = k3d::pi_times_2() * k3d::ratio(u, u_segments); k3d::double_t x = cos(theta); k3d::double_t y = -sin(theta); k3d::double_t z = k3d::mix(zmax, zmin, height); x = radius * k3d::sign(x) * std::pow(std::abs(x), inv_u_power); y = radius * k3d::sign(y) * std::pow(std::abs(y), inv_u_power); points[v * u_segments + u] = k3d::point3(x, y, z); } } const k3d::uint_t top_rim_offset = 0; const k3d::uint_t bottom_rim_offset = v_segments * u_segments; // Optionally cap the top of the cylinder ... if(top) { if(!top_segments) { polyhedron->face_shells.push_back(0); polyhedron->face_first_loops.push_back(polyhedron->loop_first_edges.size()); polyhedron->face_loop_counts.push_back(1); polyhedron->face_selections.push_back(0); polyhedron->face_materials.push_back(material); polyhedron->loop_first_edges.push_back(polyhedron->clockwise_edges.size()); for(k3d::int32_t u = 0; u != u_segments; ++u) { polyhedron->clockwise_edges.push_back(polyhedron->clockwise_edges.size() + 1); polyhedron->edge_selections.push_back(0); polyhedron->vertex_points.push_back((u_segments - u) % u_segments); polyhedron->vertex_selections.push_back(0); } polyhedron->clockwise_edges.back() = polyhedron->loop_first_edges.back(); } else { const k3d::uint_t middle_point_index = points.size(); const k3d::point3 middle_point(0, 0, zmax); points.push_back(middle_point); point_selection.push_back(0); // Create segment quads k3d::uint_t last_ring_point_offset = 0; k3d::uint_t current_ring_point_offset = 0; for(k3d::int32_t n = top_segments; n > 1; --n) { current_ring_point_offset = points.size(); const k3d::double_t factor = k3d::ratio(n - 1, top_segments); for(k3d::int32_t u = 0; u < u_segments; ++u) { points.push_back(middle_point + factor * (points[u] - middle_point)); point_selection.push_back(0); } for(k3d::int32_t u = 0; u < u_segments; ++u) { k3d::polyhedron::add_quadrilateral( Output, *polyhedron, 0, last_ring_point_offset + (u + 1) % u_segments, last_ring_point_offset + (u + 0) % u_segments, current_ring_point_offset + (u + 0) % u_segments, current_ring_point_offset + (u + 1) % u_segments, material); } last_ring_point_offset = current_ring_point_offset; } // Create middle triangle fan for(k3d::int32_t u = 0; u != u_segments; ++u) { k3d::polyhedron::add_triangle( Output, *polyhedron, 0, current_ring_point_offset + (u + 1) % u_segments, current_ring_point_offset + (u + 0) % u_segments, middle_point_index, material); } } } // Optionally cap the bottom of the cylinder ... if(bottom) { if(!bottom_segments) { polyhedron->face_shells.push_back(0); polyhedron->face_first_loops.push_back(polyhedron->loop_first_edges.size()); polyhedron->face_loop_counts.push_back(1); polyhedron->face_selections.push_back(0); polyhedron->face_materials.push_back(material); polyhedron->loop_first_edges.push_back(polyhedron->clockwise_edges.size()); for(k3d::int32_t u = 0; u != u_segments; ++u) { polyhedron->clockwise_edges.push_back(polyhedron->clockwise_edges.size() + 1); polyhedron->edge_selections.push_back(0); polyhedron->vertex_points.push_back(bottom_rim_offset + u); polyhedron->vertex_selections.push_back(0); } polyhedron->clockwise_edges.back() = polyhedron->loop_first_edges.back(); } else { const k3d::uint_t middle_point_index = points.size(); const k3d::point3 middle_point(0, 0, zmin); points.push_back(middle_point); point_selection.push_back(0); // Create segment quads k3d::uint_t last_ring_point_offset = v_segments * u_segments; k3d::uint_t current_ring_point_offset = v_segments * u_segments; for(k3d::int32_t n = bottom_segments; n > 1; --n) { current_ring_point_offset = points.size(); const k3d::double_t factor = k3d::ratio(n - 1, bottom_segments); for(k3d::int32_t u = 0; u < u_segments; ++u) { points.push_back(middle_point + factor * (points[(v_segments * u_segments) + u] - middle_point)); point_selection.push_back(0); } for(k3d::int32_t u = 0; u < u_segments; ++u) { k3d::polyhedron::add_quadrilateral( Output, *polyhedron, 0, last_ring_point_offset + (u + 0) % u_segments, last_ring_point_offset + (u + 1) % u_segments, current_ring_point_offset + (u + 1) % u_segments, current_ring_point_offset + (u + 0) % u_segments, material); } last_ring_point_offset = current_ring_point_offset; } // Create middle triangle fan for(k3d::int32_t u = 0; u != u_segments; ++u) { k3d::polyhedron::add_triangle( Output, *polyhedron, 0, current_ring_point_offset + (u + 0) % u_segments, current_ring_point_offset + (u + 1) % u_segments, middle_point_index, material); } } } } void on_update_mesh_geometry(k3d::mesh& Output) { } static k3d::iplugin_factory& get_factory() { static k3d::document_plugin_factory<poly_cylinder, k3d::interface_list<k3d::imesh_source > > factory( k3d::uuid(0xd8c4d9fd, 0x42334a54, 0xa4b48185, 0xd8506489), "PolyCylinder", _("Generates a polygonal cylinder with optional endcaps"), "Polyhedron", k3d::iplugin_factory::STABLE); return factory; } private: k3d_data(k3d::int32_t, immutable_name, change_signal, with_undo, local_storage, with_constraint, measurement_property, with_serialization) m_u_segments; k3d_data(k3d::int32_t, immutable_name, change_signal, with_undo, local_storage, with_constraint, measurement_property, with_serialization) m_v_segments; k3d_data(k3d::bool_t, immutable_name, change_signal, with_undo, local_storage, no_constraint, writable_property, with_serialization) m_top; k3d_data(k3d::bool_t, immutable_name, change_signal, with_undo, local_storage, no_constraint, writable_property, with_serialization) m_bottom; k3d_data(k3d::double_t, immutable_name, change_signal, with_undo, local_storage, no_constraint, measurement_property, with_serialization) m_radius; k3d_data(k3d::double_t, immutable_name, change_signal, with_undo, local_storage, no_constraint, measurement_property, with_serialization) m_zmax; k3d_data(k3d::double_t, immutable_name, change_signal, with_undo, local_storage, no_constraint, measurement_property, with_serialization) m_zmin; k3d_data(k3d::double_t, immutable_name, change_signal, with_undo, local_storage, no_constraint, measurement_property, with_serialization) m_u_power; k3d_data(k3d::int32_t, immutable_name, change_signal, with_undo, local_storage, with_constraint, measurement_property, with_serialization) m_top_segments; k3d_data(k3d::int32_t, immutable_name, change_signal, with_undo, local_storage, with_constraint, measurement_property, with_serialization) m_bottom_segments; }; ///////////////////////////////////////////////////////////////////////////// // poly_cylinder_factory k3d::iplugin_factory& poly_cylinder_factory() { return poly_cylinder::get_factory(); } } // namespace sources } // namespace polyhedron } // namespace module
utf-8
1
unknown
unknown
spades-3.13.1+dfsg/assembler/ext/include/edlib/edlib.h
#ifndef EDLIB_H #define EDLIB_H /** * @file * @author Martin Sosic * @brief Main header file, containing all public functions and structures. */ #ifdef __cplusplus extern "C" { #endif namespace edlib { // Status codes const unsigned int EDLIB_STATUS_OK = 0; const unsigned int EDLIB_STATUS_ERROR = 1; /** * Alignment methods - how should Edlib treat gaps before and after query? */ typedef enum { /** * Global method. This is the standard method. * Useful when you want to find out how similar is first sequence to second sequence. */ EDLIB_MODE_NW, /** * Prefix method. Similar to global method, but with a small twist - gap at query end is not penalized. * What that means is that deleting elements from the end of second sequence is "free"! * For example, if we had "AACT" and "AACTGGC", edit distance would be 0, because removing "GGC" from the end * of second sequence is "free" and does not count into total edit distance. This method is appropriate * when you want to find out how well first sequence fits at the beginning of second sequence. */ EDLIB_MODE_SHW, /** * Infix method. Similar as prefix method, but with one more twist - gaps at query end and start are * not penalized. What that means is that deleting elements from the start and end of second sequence is "free"! * For example, if we had ACT and CGACTGAC, edit distance would be 0, because removing CG from the start * and GAC from the end of second sequence is "free" and does not count into total edit distance. * This method is appropriate when you want to find out how well first sequence fits at any part of * second sequence. * For example, if your second sequence was a long text and your first sequence was a sentence from that text, * but slightly scrambled, you could use this method to discover how scrambled it is and where it fits in * that text. In bioinformatics, this method is appropriate for aligning read to a sequence. */ EDLIB_MODE_HW } EdlibAlignMode; /** * Alignment tasks - what do you want Edlib to do? */ typedef enum { EDLIB_TASK_DISTANCE, //!< Find edit distance and end locations. EDLIB_TASK_LOC, //!< Find edit distance, end locations and start locations. EDLIB_TASK_PATH //!< Find edit distance, end locations and start locations and alignment path. } EdlibAlignTask; /** * Describes cigar format. * @see http://samtools.github.io/hts-specs/SAMv1.pdf * @see http://drive5.com/usearch/manual/cigar.html */ typedef enum { EDLIB_CIGAR_STANDARD, //!< Match: 'M', Insertion: 'I', Deletion: 'D', Mismatch: 'M'. EDLIB_CIGAR_EXTENDED //!< Match: '=', Insertion: 'I', Deletion: 'D', Mismatch: 'X'. } EdlibCigarFormat; // Edit operations. #define EDLIB_EDOP_MATCH 0 //!< Match. #define EDLIB_EDOP_INSERT 1 //!< Insertion to target = deletion from query. #define EDLIB_EDOP_DELETE 2 //!< Deletion from target = insertion to query. #define EDLIB_EDOP_MISMATCH 3 //!< Mismatch. /** * @brief Defines two given characters as equal. */ typedef struct { char first; char second; } EdlibEqualityPair; /** * @brief Configuration object for edlibAlign() function. */ typedef struct { /** * Set k to non-negative value to tell edlib that edit distance is not larger than k. * Smaller k can significantly improve speed of computation. * If edit distance is larger than k, edlib will set edit distance to -1. * Set k to negative value and edlib will internally auto-adjust k until score is found. */ int k; /** * Alignment method. * EDLIB_MODE_NW: global (Needleman-Wunsch) * EDLIB_MODE_SHW: prefix. Gap after query is not penalized. * EDLIB_MODE_HW: infix. Gaps before and after query are not penalized. */ EdlibAlignMode mode; /** * Alignment task - tells Edlib what to calculate. Less to calculate, faster it is. * EDLIB_TASK_DISTANCE - find edit distance and end locations of optimal alignment paths in target. * EDLIB_TASK_LOC - find edit distance and start and end locations of optimal alignment paths in target. * EDLIB_TASK_PATH - find edit distance, alignment path (and start and end locations of it in target). */ EdlibAlignTask task; /** * List of pairs of characters, where each pair defines two characters as equal. * This way you can extend edlib's definition of equality (which is that each character is equal only * to itself). * This can be useful if you have some wildcard characters that should match multiple other characters, * or e.g. if you want edlib to be case insensitive. * Can be set to NULL if there are none. */ EdlibEqualityPair* additionalEqualities; /** * Number of additional equalities, which is non-negative number. * 0 if there are none. */ int additionalEqualitiesLength; } EdlibAlignConfig; /** * Helper method for easy construction of configuration object. * @return Configuration object filled with given parameters. */ EdlibAlignConfig edlibNewAlignConfig(int k, EdlibAlignMode mode, EdlibAlignTask task, EdlibEqualityPair* additionalEqualities, int additionalEqualitiesLength); /** * @return Default configuration object, with following defaults: * k = -1, mode = EDLIB_MODE_NW, task = EDLIB_TASK_DISTANCE, no additional equalities. */ EdlibAlignConfig edlibDefaultAlignConfig(void); /** * Container for results of alignment done by edlibAlign() function. */ typedef struct { /** * EDLIB_STATUS_OK or EDLIB_STATUS_ERROR. If error, all other fields will have undefined values. */ int status; /** * -1 if k is non-negative and edit distance is larger than k. */ int editDistance; /** * Array of zero-based positions in target where optimal alignment paths end. * If gap after query is penalized, gap counts as part of query (NW), otherwise not. * Set to NULL if edit distance is larger than k. * If you do not free whole result object using edlibFreeAlignResult(), do not forget to use free(). */ int* endLocations; /** * Array of zero-based positions in target where optimal alignment paths start, * they correspond to endLocations. * If gap before query is penalized, gap counts as part of query (NW), otherwise not. * Set to NULL if not calculated or if edit distance is larger than k. * If you do not free whole result object using edlibFreeAlignResult(), do not forget to use free(). */ int* startLocations; /** * Number of end (and start) locations. */ int numLocations; /** * Alignment is found for first pair of start and end locations. * Set to NULL if not calculated. * Alignment is sequence of numbers: 0, 1, 2, 3. * 0 stands for match. * 1 stands for insertion to target. * 2 stands for insertion to query. * 3 stands for mismatch. * Alignment aligns query to target from begining of query till end of query. * If gaps are not penalized, they are not in alignment. * If you do not free whole result object using edlibFreeAlignResult(), do not forget to use free(). */ unsigned char* alignment; /** * Length of alignment. */ int alignmentLength; /** * Number of different characters in query and target together. */ int alphabetLength; } EdlibAlignResult; /** * Frees memory in EdlibAlignResult that was allocated by edlib. * If you do not use it, make sure to free needed members manually using free(). */ void edlibFreeAlignResult(EdlibAlignResult result); /** * Aligns two sequences (query and target) using edit distance (levenshtein distance). * Through config parameter, this function supports different alignment methods (global, prefix, infix), * as well as different modes of search (tasks). * It always returns edit distance and end locations of optimal alignment in target. * It optionally returns start locations of optimal alignment in target and alignment path, * if you choose appropriate tasks. * @param [in] query First sequence. * @param [in] queryLength Number of characters in first sequence. * @param [in] target Second sequence. * @param [in] targetLength Number of characters in second sequence. * @param [in] config Additional alignment parameters, like alignment method and wanted results. * @return Result of alignment, which can contain edit distance, start and end locations and alignment path. * Make sure to clean up the object using edlibFreeAlignResult() or by manually freeing needed members. */ EdlibAlignResult edlibAlign(const char* query, int queryLength, const char* target, int targetLength, const EdlibAlignConfig config); /** * Builds cigar string from given alignment sequence. * @param [in] alignment Alignment sequence. * 0 stands for match. * 1 stands for insertion to target. * 2 stands for insertion to query. * 3 stands for mismatch. * @param [in] alignmentLength * @param [in] cigarFormat Cigar will be returned in specified format. * @return Cigar string. * I stands for insertion. * D stands for deletion. * X stands for mismatch. (used only in extended format) * = stands for match. (used only in extended format) * M stands for (mis)match. (used only in standard format) * String is null terminated. * Needed memory is allocated and given pointer is set to it. * Do not forget to free it later using free()! */ char* edlibAlignmentToCigar(const unsigned char* alignment, int alignmentLength, EdlibCigarFormat cigarFormat); } #ifdef __cplusplus } #endif #endif // EDLIB_H
utf-8
1
GPL-2+
2011-2014 Saint-Petersburg Academic University 2015-2017 Saint Petersburg State University
kimageannotator-0.5.3/src/widgets/settingsPicker/ZoomPicker.cpp
/* * Copyright (C) 2020 Damir Porobic <damir.porobic@gmx.com> * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, * Boston, MA 02110-1301, USA. */ #include "ZoomPicker.h" namespace kImageAnnotator { ZoomPicker::ZoomPicker(QWidget *parent) : SettingsPickerWidget(parent), mLayout(new QHBoxLayout), mLabel(new QLabel(this)), mSpinBox(new CustomSpinBox(this)), mZoomInAction(new QAction(this)), mZoomOutAction(new QAction(this)), mResetZoomAction(new QAction(this)) { initGui(); } QWidget *ZoomPicker::expandingWidget() { return mSpinBox; } void ZoomPicker::initGui() { mLayout->setContentsMargins(1, 0, 0, 0); auto icon = IconLoader::load(QLatin1String("zoom.svg")); mLabel->setPixmap(icon.pixmap(ScaledSizeProvider::settingsWidgetIconSize())); mSpinBox->setFocusPolicy(Qt::NoFocus); mSpinBox->setRange(10, 800); mSpinBox->setSingleStep(10); mSpinBox->setSuffix(QLatin1String("%")); mSpinBox->setWrapping(false); mZoomInAction->setShortcut(QKeySequence::ZoomIn); mZoomOutAction->setShortcut(QKeySequence::ZoomOut); mResetZoomAction->setShortcut(Qt::CTRL + Qt::Key_0); setToolTip(getToolTip()); connect(mZoomInAction, &QAction::triggered, this, &ZoomPicker::zoomIn); connect(mZoomOutAction, &QAction::triggered, this, &ZoomPicker::zoomOut); connect(mResetZoomAction, &QAction::triggered, this, &ZoomPicker::resetZoomOut); addAction(mZoomInAction); addAction(mZoomOutAction); addAction(mResetZoomAction); connect(mSpinBox, &CustomSpinBox::valueChanged, this, &ZoomPicker::notifyZoomValueChanged); mLayout->addWidget(mLabel); mLayout->addWidget(mSpinBox); mLayout->setAlignment(Qt::AlignLeft); setLayout(mLayout); } QString ZoomPicker::getToolTip() const { auto newLine = QLatin1String("\n"); auto zoomIn = tr("Zoom In (%1)").arg(mZoomInAction->shortcut().toString()); auto zoomOut = tr("Zoom Out (%1)").arg(mZoomOutAction->shortcut().toString()); auto resetZoom = tr("Reset Zoom (%1)").arg(mResetZoomAction->shortcut().toString()); return zoomIn + newLine + zoomOut + newLine + resetZoom; } void ZoomPicker::setZoomValue(double value) { auto zoomValue = qRound(value * 100); mSpinBox->setValueSilent(zoomValue); } void ZoomPicker::notifyZoomValueChanged(double value) { emit zoomValueChanged(value / 100.0); } void ZoomPicker::zoomIn() { int currentZoom = mSpinBox->value(); notifyZoomValueChanged(currentZoom + 10); } void ZoomPicker::zoomOut() { auto currentZoom = mSpinBox->value(); notifyZoomValueChanged(currentZoom - 10); } void ZoomPicker::resetZoomOut() { notifyZoomValueChanged(100); } } // namespace kImageAnnotator
utf-8
1
LGPL-3+
2018-2020 Damir Porobic <damir.porobic@gmx.com>
pkg-config-0.29.2/glib/glib/gvariant-serialiser.h
/* * Copyright © 2007, 2008 Ryan Lortie * Copyright © 2010 Codethink Limited * * 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 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., 59 Temple Place - Suite 330, * Boston, MA 02111-1307, USA. * * Author: Ryan Lortie <desrt@desrt.ca> */ #ifndef __G_VARIANT_SERIALISER_H__ #define __G_VARIANT_SERIALISER_H__ #include "gvarianttypeinfo.h" typedef struct { GVariantTypeInfo *type_info; guchar *data; gsize size; } GVariantSerialised; /* deserialisation */ GLIB_AVAILABLE_IN_ALL gsize g_variant_serialised_n_children (GVariantSerialised container); GLIB_AVAILABLE_IN_ALL GVariantSerialised g_variant_serialised_get_child (GVariantSerialised container, gsize index); /* serialisation */ typedef void (*GVariantSerialisedFiller) (GVariantSerialised *serialised, gpointer data); GLIB_AVAILABLE_IN_ALL gsize g_variant_serialiser_needed_size (GVariantTypeInfo *info, GVariantSerialisedFiller gsv_filler, const gpointer *children, gsize n_children); GLIB_AVAILABLE_IN_ALL void g_variant_serialiser_serialise (GVariantSerialised container, GVariantSerialisedFiller gsv_filler, const gpointer *children, gsize n_children); /* misc */ GLIB_AVAILABLE_IN_ALL gboolean g_variant_serialised_is_normal (GVariantSerialised value); GLIB_AVAILABLE_IN_ALL void g_variant_serialised_byteswap (GVariantSerialised value); /* validation of strings */ GLIB_AVAILABLE_IN_ALL gboolean g_variant_serialiser_is_string (gconstpointer data, gsize size); GLIB_AVAILABLE_IN_ALL gboolean g_variant_serialiser_is_object_path (gconstpointer data, gsize size); GLIB_AVAILABLE_IN_ALL gboolean g_variant_serialiser_is_signature (gconstpointer data, gsize size); #endif /* __G_VARIANT_SERIALISER_H__ */
utf-8
1
unknown
unknown
mozc-2.26.4220.100+dfsg/src/storage/registry.h
// Copyright 2010-2020, 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. #ifndef MOZC_STORAGE_REGISTRY_H_ #define MOZC_STORAGE_REGISTRY_H_ #include <cstring> #include <string> #include "base/logging.h" #include "base/port.h" namespace mozc { namespace storage { class StorageInterface; // The idea of Registry module is the same as Windows Registry. // You can use it for saving small data like timestamp, auth_token. // DO NOT USE it to save big data or data which are frequently updated. // Lookup() and Insert() do process-wide global lock and it may be slow. // All methods are thread-safe. // // TODO(taku): Currently, Registry won't guarantee that two processes // can con-currently share the same data. We will replace the backend // of Registry (Storage Interface) with sqlite // // Example: // uint64 timestamp = 0; // CHECK(Registry::Lookup<uint64>("timestamp", &timestamp)); // // string value = "hello world"; // CHECK(Registry::Insert<string>("hello", value)); class Registry { public: template <typename T> static bool Lookup(const std::string &key, T *value) { DCHECK(value); std::string tmp; if (!LookupInternal(key, &tmp)) { return false; } if (sizeof(*value) != tmp.size()) { return false; } memcpy(reinterpret_cast<char *>(value), tmp.data(), tmp.size()); return true; } static bool Lookup(const std::string &key, std::string *value) { return LookupInternal(key, value); } static bool Lookup(const std::string &key, bool *value) { uint8 v = 0; const bool result = Lookup<uint8>(key, &v); *value = (v != 0); return result; } // insert key and data // It is not guaranteed that the data is synced to the disk template <typename T> static bool Insert(const std::string &key, const T &value) { std::string tmp(reinterpret_cast<const char *>(&value), sizeof(value)); return InsertInternal(key, tmp); } // Insert key and string value // It is not guaranteed that the data is synced to the disk static bool Insert(const std::string &key, const std::string &value) { return InsertInternal(key, value); } // Insert key and bool value // It is not guaranteed that the data is synced to the disk static bool Insert(const std::string &key, const bool value) { const uint8 tmp = static_cast<uint8>(value); return Insert<uint8>(key, tmp); } // Syncing the data into disk static bool Sync(); // Erase key static bool Erase(const std::string &key); // clear internal keys and values static bool Clear(); // Inject internal storage for unittesting. // TinyStorage is used by default // TODO(taku) replace it with SQLITE static void SetStorage(StorageInterface *handler); private: static bool LookupInternal(const std::string &key, std::string *value); static bool InsertInternal(const std::string &key, const std::string &value); DISALLOW_IMPLICIT_CONSTRUCTORS(Registry); }; } // namespace storage } // namespace mozc #endif // MOZC_STORAGE_REGISTRY_H_
utf-8
1
BSD-3-clause
2010-2018, Google Inc.
openttd-12.1/src/os/windows/font_win32.h
/* * This file is part of OpenTTD. * OpenTTD is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, version 2. * OpenTTD 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 OpenTTD. If not, see <http://www.gnu.org/licenses/>. */ /** @file font_win32.h Functions related to font handling on Win32. */ #ifndef FONT_WIN32_H #define FONT_WIN32_H #include "../../fontcache_internal.h" #include "win32.h" /** Font cache for fonts that are based on a Win32 font. */ class Win32FontCache : public TrueTypeFontCache { private: LOGFONT logfont; ///< Logical font information for selecting the font face. HFONT font = nullptr; ///< The font face associated with this font. HDC dc = nullptr; ///< Cached GDI device context. HGDIOBJ old_font; ///< Old font selected into the GDI context. SIZE glyph_size; ///< Maximum size of regular glyphs. std::string fontname; ///< Cached copy of this->logfont.lfFaceName void SetFontSize(FontSize fs, int pixels); protected: const void *InternalGetFontTable(uint32 tag, size_t &length) override; const Sprite *InternalGetGlyph(GlyphID key, bool aa) override; public: Win32FontCache(FontSize fs, const LOGFONT &logfont, int pixels); ~Win32FontCache(); void ClearFontCache() override; GlyphID MapCharToGlyph(WChar key) override; const char *GetFontName() override { return this->fontname.c_str(); } const void *GetOSHandle() override { return &this->logfont; } }; void LoadWin32Font(FontSize fs); #endif /* FONT_WIN32_H */
utf-8
1
GPL-2.0
© 2004-2012 Ludvig Strigeous and others.
mir-1.8.2+dfsg/src/platforms/mesa/server/x11/input/input_platform.cpp
/* * Copyright © 2015 Canonical Ltd. * * This program is free software: you can redistribute it and/or modify it * under the terms of the GNU General Public License version 2 or 3, * as published by the Free Software Foundation. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. * * Authored by: Cemil Azizoglu <cemil.azizoglu@canonical.com> */ #include "input_platform.h" #include "input_device.h" #include "mir/graphics/display_configuration.h" #include "mir/input/input_device_registry.h" #include "mir/input/input_device_info.h" #include "mir/dispatch/readable_fd.h" #include "../X11_resources.h" #define MIR_LOG_COMPONENT "x11-input" #include "mir/log.h" #include <X11/extensions/Xfixes.h> #include <X11/Xutil.h> #include <X11/Xlib.h> #include <linux/input.h> #include <inttypes.h> #include <signal.h> #include <stdio.h> #include <chrono> // Uncomment for verbose output with log_info. //#define MIR_ON_X11_INPUT_VERBOSE // Due to a bug in Unity when keyboard is grabbed, // client cannot be resized. This helps in debugging. #define GRAB_KBD namespace mi = mir::input; namespace geom = mir::geometry; namespace md = mir::dispatch; namespace mix = mi::X; namespace mx = mir::X; namespace { geom::Point get_pos_on_output(Window x11_window, int x, int y) { auto output = mx::X11Resources::instance.get_output_config_for_win(x11_window); if (output) { return output.value()->top_left + geom::Displacement{x, y}; } else { mir::log_warning("X11 window %d does not map to any known output, not applying input transformation", x11_window); return geom::Point{x, y}; } } } mix::XInputPlatform::XInputPlatform(std::shared_ptr<mi::InputDeviceRegistry> const& input_device_registry, std::shared_ptr<::Display> const& conn) : x11_connection{conn}, xcon_dispatchable(std::make_shared<md::ReadableFd>( mir::Fd{mir::IntOwnedFd{XConnectionNumber(conn.get())}}, [this]() { process_input_event(); })), registry(input_device_registry), core_keyboard(std::make_shared<mix::XInputDevice>( mi::InputDeviceInfo{"x11-keyboard-device", "x11-key-dev-1", mi::DeviceCapability::keyboard})), core_pointer(std::make_shared<mix::XInputDevice>( mi::InputDeviceInfo{"x11-mouse-device", "x11-mouse-dev-1", mi::DeviceCapability::pointer})), kbd_grabbed{false}, ptr_grabbed{false} { } void mix::XInputPlatform::start() { registry->add_device(core_keyboard); registry->add_device(core_pointer); } std::shared_ptr<md::Dispatchable> mix::XInputPlatform::dispatchable() { return xcon_dispatchable; } void mix::XInputPlatform::stop() { registry->remove_device(core_keyboard); registry->remove_device(core_pointer); } void mix::XInputPlatform::pause_for_config() { } void mix::XInputPlatform::continue_after_config() { } void mix::XInputPlatform::process_input_event() { while(XPending(x11_connection.get())) { // This code is based on : // https://tronche.com/gui/x/xlib/events/keyboard-pointer/keyboard-pointer.html XEvent xev; XNextEvent(x11_connection.get(), &xev); if (core_keyboard->started() && core_pointer->started()) { switch (xev.type) { #ifdef GRAB_KBD case FocusIn: { auto const& xfiev = xev.xfocus; if (!kbd_grabbed && (xfiev.mode == NotifyNormal || xfiev.mode == NotifyWhileGrabbed)) { XGrabKeyboard(xfiev.display, xfiev.window, True, GrabModeAsync, GrabModeAsync, CurrentTime); kbd_grabbed = true; } break; } case FocusOut: { auto const& xfoev = xev.xfocus; if (kbd_grabbed && (xfoev.mode == NotifyNormal || xfoev.mode == NotifyWhileGrabbed)) { XUngrabKeyboard(xfoev.display, CurrentTime); kbd_grabbed = false; } break; } #endif case EnterNotify: { if (!ptr_grabbed && kbd_grabbed) { auto const& xenev = xev.xcrossing; XGrabPointer(xenev.display, xenev.window, True, 0, GrabModeAsync, GrabModeAsync, None, None, CurrentTime); XFixesHideCursor(xenev.display, xenev.window); ptr_grabbed = true; } break; } case LeaveNotify: { if (ptr_grabbed) { auto const& xlnev = xev.xcrossing; XUngrabPointer(xlnev.display, CurrentTime); XFixesShowCursor(xlnev.display, xlnev.window); ptr_grabbed = false; } break; } case KeyPress: case KeyRelease: { auto & xkev = xev.xkey; static const int STRMAX = 32; char str[STRMAX]; KeySym keysym; #ifdef MIR_ON_X11_INPUT_VERBOSE mir::log_info("X11 key event :" " type=%s, serial=%u, send_event=%d, display=%p, window=%p," " root=%p, subwindow=%p, time=%d, x=%d, y=%d, x_root=%d," " y_root=%d, state=0x%0X, keycode=%d, same_screen=%d", xkev.type == KeyPress ? "down" : "up", xkev.serial, xkev.send_event, xkev.display, xkev.window, xkev.root, xkev.subwindow, xkev.time, xkev.x, xkev.y, xkev.x_root, xkev.y_root, xkev.state, xkev.keycode, xkev.same_screen); auto count = #endif XLookupString(&xkev, str, STRMAX, &keysym, NULL); auto const event_time = std::chrono::duration_cast<std::chrono::nanoseconds>( std::chrono::milliseconds{xkev.time}); #ifdef MIR_ON_X11_INPUT_VERBOSE for (int i=0; i<count; i++) mir::log_info("buffer[%d]='%c'", i, str[i]); mir::log_info("Mir key event : " "key_code=%d, scan_code=%d, event_time=%" PRId64, keysym, xkev.keycode-8, event_time); #endif if (xkev.type == KeyPress) core_keyboard->key_press(event_time, keysym, xkev.keycode - 8); else core_keyboard->key_release(event_time, keysym, xkev.keycode - 8); break; } case ButtonPress: case ButtonRelease: { auto const& xbev = xev.xbutton; auto const up = Button4, down = Button5, left = 6, right = 7; #ifdef MIR_ON_X11_INPUT_VERBOSE mir::log_info("X11 button event :" " type=%s, serial=%u, send_event=%d, display=%p, window=%p," " root=%p, subwindow=%p, time=%d, x=%d, y=%d, x_root=%d," " y_root=%d, state=0x%0X, button=%d, same_screen=%d", xbev.type == ButtonPress ? "down" : "up", xbev.serial, xbev.send_event, xbev.display, xbev.window, xbev.root, xbev.subwindow, xbev.time, xbev.x, xbev.y, xbev.x_root, xbev.y_root, xbev.state, xbev.button, xbev.same_screen); #endif if (xbev.type == ButtonRelease && xbev.button >= up && xbev.button <= right) { #ifdef MIR_ON_X11_INPUT_VERBOSE mir::log_info("Swallowed"); #endif break; } auto const event_time = std::chrono::duration_cast<std::chrono::nanoseconds>(std::chrono::milliseconds{xbev.time}); auto pos = get_pos_on_output(xbev.window, xbev.x, xbev.y); core_pointer->update_button_state(xbev.state); if (xbev.button >= up && xbev.button <= right) { // scroll event core_pointer->pointer_motion( event_time, pos, geom::Displacement{xbev.button == right ? 1 : xbev.button == left ? -1 : 0, xbev.button == up ? 1 : xbev.button == down ? -1 : 0}); } else { if (xbev.type == ButtonPress) core_pointer->pointer_press( event_time, xbev.button, pos, geom::Displacement{0, 0}); else core_pointer->pointer_release( event_time, xbev.button, pos, geom::Displacement{0, 0}); } break; } case MotionNotify: { auto const& xmev = xev.xmotion; #ifdef MIR_ON_X11_INPUT_VERBOSE mir::log_info("X11 motion event :" " type=motion, serial=%u, send_event=%d, display=%p, window=%p," " root=%p, subwindow=%p, time=%d, x=%d, y=%d, x_root=%d," " y_root=%d, state=0x%0X, is_hint=%s, same_screen=%d", xmev.serial, xmev.send_event, xmev.display, xmev.window, xmev.root, xmev.subwindow, xmev.time, xmev.x, xmev.y, xmev.x_root, xmev.y_root, xmev.state, xmev.is_hint == NotifyNormal ? "no" : "yes", xmev.same_screen); #endif core_pointer->update_button_state(xmev.state); auto pos = get_pos_on_output(xmev.window, xmev.x, xmev.y); core_pointer->pointer_motion( std::chrono::milliseconds{xmev.time}, pos, geom::Displacement{0, 0}); break; } case ConfigureNotify: { #ifdef MIR_ON_X11_INPUT_VERBOSE auto const& xcev = xev.xconfigure; mir::log_info("Window size : %dx%d", xcev.width, xcev.height); #endif break; } case MappingNotify: #ifdef MIR_ON_X11_INPUT_VERBOSE mir::log_info("Keyboard mapping changed at server. Refreshing the cache."); #endif XRefreshKeyboardMapping(&(xev.xmapping)); break; case ClientMessage: mir::log_info("Exiting"); kill(getpid(), SIGTERM); break; default: #ifdef MIR_ON_X11_INPUT_VERBOSE mir::log_info("Uninteresting event : %08X", xev.type); #endif break; } } else mir::log_error("input event received with no sink to handle it"); } }
utf-8
1
unknown
unknown
alpine-2.25+dfsg1/pith/maillist.c
#if !defined(lint) && !defined(DOS) static char rcsid[] = "$Id: maillist.c 769 2007-10-24 00:15:40Z hubert@u.washington.edu $"; #endif /* * ======================================================================== * Copyright 2006-2007 University of Washington * Copyright 2013-2021 Eduardo Chappa * * 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 * * ======================================================================== */ /* * * * * * * * * * RFC 2369 support routines * * * * * * * * */ #include "../pith/headers.h" #include "../pith/maillist.h" #include "../pith/state.h" #include "../pith/url.h" /* * Internal prototypes */ int rfc2369_parse(char *, RFC2369_S *); /* * * NOTE * These have to remain in sync with the MLCMD_* macros * in maillist.h. Sorry. */ static RFC2369FIELD_S rfc2369_fields[] = { {"List-Help", "get information about the list and instructions on how to join", "seek help"}, {"List-Unsubscribe", "remove yourself from the list (Unsubscribe)", "UNsubscribe"}, {"List-Subscribe", "add yourself to the list (Subscribe)", "Subscribe"}, {"List-Post", "send a message to the entire list (Post)", "post a message"}, {"List-Owner", "send a message to the list owner", "contact the list owner"}, {"List-Archive", "view archive of messages sent to the list", "view the archive"} }; char ** rfc2369_hdrs(char **hdrs) { int i; for(i = 0; i < MLCMD_COUNT; i++) hdrs[i] = rfc2369_fields[i].name; hdrs[i] = NULL; return(hdrs); } int rfc2369_parse_fields(char *h, RFC2369_S *data) { char *ep, *nhp, *tp; int i, rv = FALSE; for(i = 0; i < MLCMD_COUNT; i++) data[i].field = rfc2369_fields[i]; for(nhp = h; h; h = nhp){ /* coerce h to start of field */ for(ep = h;;) if((tp = strpbrk(ep, "\015\012")) != NULL){ if(strindex(" \t", *((ep = tp) + 2))){ *ep++ = ' '; /* flatten continuation */ *ep++ = ' '; for(; *ep; ep++) /* advance past whitespace */ if(*ep == '\t') *ep = ' '; else if(*ep != ' ') break; } else{ *ep = '\0'; /* tie off header data */ nhp = ep + 2; /* start of next header */ break; } } else{ while(*ep) /* find the end of this line */ ep++; nhp = NULL; /* no more header fields */ break; } /* if length is within reason, see if we're interested */ if(ep - h < MLCMD_REASON && rfc2369_parse(h, data)) rv = TRUE; } return(rv); } int rfc2369_parse(char *h, RFC2369_S *data) { int l, ifield, idata = 0; char *p, *p1, *url, *comment; /* look for interesting name's */ for(ifield = 0; ifield < MLCMD_COUNT; ifield++) if(!struncmp(h, rfc2369_fields[ifield].name, l = strlen(rfc2369_fields[ifield].name)) && *(h += l) == ':'){ /* unwrap any transport encodings */ if((p = (char *) rfc1522_decode_to_utf8((unsigned char *) tmp_20k_buf, SIZEOF_20KBUF, ++h)) == tmp_20k_buf) strcpy(h, p); /* assumption #383: decoding shrinks */ url = comment = NULL; while(*h){ while(*h == ' ') h++; switch(*h){ case '<' : /* URL */ if((p = strindex(h, '>')) != NULL){ url = ++h; /* remember where it starts */ *p = '\0'; /* tie it off */ h = p + 1; /* advance h */ for(p = p1 = url; (*p1 = *p) != '\0'; p++) if(*p1 != ' ') p1++; /* remove whitespace ala RFC */ } else *h = '\0'; /* tie off junk */ break; case '(' : /* Comment */ comment = rfc822_skip_comment(&h, LONGT); break; case 'N' : /* special case? */ case 'n' : if(ifield == MLCMD_POST && (*(h+1) == 'O' || *(h+1) == 'o') && (!*(h+2) || *(h+2) == ' ')){ ; /* yup! */ url = h; *(h + 2) = '\0'; h += 3; break; } default : removing_trailing_white_space(h); if(!url && (url = rfc1738_scan(h, &l)) && url == h && l == strlen(h)){ removing_trailing_white_space(h); data[ifield].data[idata].value = url; } else data[ifield].data[idata].error = h; return(1); /* return junk */ } while(*h == ' ') h++; switch(*h){ case ',' : h++; case '\0': if(url || (comment && *comment)){ data[ifield].data[idata].value = url; data[ifield].data[idata].comment = comment; url = comment = NULL; } if(++idata == MLCMD_MAXDATA) *h = '\0'; default : break; } } } return(idata); }
utf-8
1
Apache-2.0
1988-2012, University of Washington 2008-2012, Mark Crispin 2013-2020, Eduardo Chappa
curl-7.81.0/lib/curl_threads.h
#ifndef HEADER_CURL_THREADS_H #define HEADER_CURL_THREADS_H /*************************************************************************** * _ _ ____ _ * Project ___| | | | _ \| | * / __| | | | |_) | | * | (__| |_| | _ <| |___ * \___|\___/|_| \_\_____| * * Copyright (C) 1998 - 2020, Daniel Stenberg, <daniel@haxx.se>, et al. * * This software is licensed as described in the file COPYING, which * you should have received as part of this distribution. The terms * are also available at https://curl.se/docs/copyright.html. * * You may opt to use, copy, modify, merge, publish, distribute and/or sell * copies of the Software, and permit persons to whom the Software is * furnished to do so, under the terms of the COPYING file. * * This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY * KIND, either express or implied. * ***************************************************************************/ #include "curl_setup.h" #if defined(USE_THREADS_POSIX) # define CURL_STDCALL # define curl_mutex_t pthread_mutex_t # define curl_thread_t pthread_t * # define curl_thread_t_null (pthread_t *)0 # define Curl_mutex_init(m) pthread_mutex_init(m, NULL) # define Curl_mutex_acquire(m) pthread_mutex_lock(m) # define Curl_mutex_release(m) pthread_mutex_unlock(m) # define Curl_mutex_destroy(m) pthread_mutex_destroy(m) #elif defined(USE_THREADS_WIN32) # define CURL_STDCALL __stdcall # define curl_mutex_t CRITICAL_SECTION # define curl_thread_t HANDLE # define curl_thread_t_null (HANDLE)0 # if !defined(_WIN32_WINNT) || !defined(_WIN32_WINNT_VISTA) || \ (_WIN32_WINNT < _WIN32_WINNT_VISTA) || \ (defined(__MINGW32__) && !defined(__MINGW64_VERSION_MAJOR)) # define Curl_mutex_init(m) InitializeCriticalSection(m) # else # define Curl_mutex_init(m) InitializeCriticalSectionEx(m, 0, 1) # endif # define Curl_mutex_acquire(m) EnterCriticalSection(m) # define Curl_mutex_release(m) LeaveCriticalSection(m) # define Curl_mutex_destroy(m) DeleteCriticalSection(m) #endif #if defined(USE_THREADS_POSIX) || defined(USE_THREADS_WIN32) /* !checksrc! disable SPACEBEFOREPAREN 1 */ curl_thread_t Curl_thread_create(unsigned int (CURL_STDCALL *func) (void *), void *arg); void Curl_thread_destroy(curl_thread_t hnd); int Curl_thread_join(curl_thread_t *hnd); #endif /* USE_THREADS_POSIX || USE_THREADS_WIN32 */ #endif /* HEADER_CURL_THREADS_H */
utf-8
1
curl
1996-2015, Daniel Stenberg <daniel@haxx.se>
chromium-98.0.4758.102/third_party/weston/src/libweston/backend-drm/state-propose.c
/* * Copyright © 2008-2011 Kristian Høgsberg * Copyright © 2011 Intel Corporation * Copyright © 2017, 2018 Collabora, Ltd. * Copyright © 2017, 2018 General Electric Company * Copyright (c) 2018 DisplayLink (UK) Ltd. * * 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 (including the * next paragraph) 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 "config.h" #include <xf86drm.h> #include <xf86drmMode.h> #include <libweston/libweston.h> #include <libweston/backend-drm.h> #include <libweston/pixel-formats.h> #include "drm-internal.h" #include "linux-dmabuf.h" #include "presentation-time-server-protocol.h" enum drm_output_propose_state_mode { DRM_OUTPUT_PROPOSE_STATE_MIXED, /**< mix renderer & planes */ DRM_OUTPUT_PROPOSE_STATE_RENDERER_ONLY, /**< only assign to renderer & cursor */ DRM_OUTPUT_PROPOSE_STATE_PLANES_ONLY, /**< no renderer use, only planes */ }; static const char *const drm_output_propose_state_mode_as_string[] = { [DRM_OUTPUT_PROPOSE_STATE_MIXED] = "mixed state", [DRM_OUTPUT_PROPOSE_STATE_RENDERER_ONLY] = "render-only state", [DRM_OUTPUT_PROPOSE_STATE_PLANES_ONLY] = "plane-only state" }; static const char * drm_propose_state_mode_to_string(enum drm_output_propose_state_mode mode) { if (mode < 0 || mode >= ARRAY_LENGTH(drm_output_propose_state_mode_as_string)) return " unknown compositing mode"; return drm_output_propose_state_mode_as_string[mode]; } static void drm_output_add_zpos_plane(struct drm_plane *plane, struct wl_list *planes) { struct drm_backend *b = plane->backend; struct drm_plane_zpos *h_plane; struct drm_plane_zpos *plane_zpos; plane_zpos = zalloc(sizeof(*plane_zpos)); if (!plane_zpos) return; plane_zpos->plane = plane; drm_debug(b, "\t\t\t\t[plane] plane %d added to candidate list\n", plane->plane_id); if (wl_list_empty(planes)) { wl_list_insert(planes, &plane_zpos->link); return; } h_plane = wl_container_of(planes->next, h_plane, link); if (h_plane->plane->zpos_max >= plane->zpos_max) { wl_list_insert(planes->prev, &plane_zpos->link); } else { struct drm_plane_zpos *p_zpos = NULL; if (wl_list_length(planes) == 1) { wl_list_insert(planes->prev, &plane_zpos->link); return; } wl_list_for_each(p_zpos, planes, link) { if (p_zpos->plane->zpos_max > plane_zpos->plane->zpos_max) break; } wl_list_insert(p_zpos->link.prev, &plane_zpos->link); } } static void drm_output_destroy_zpos_plane(struct drm_plane_zpos *plane_zpos) { wl_list_remove(&plane_zpos->link); free(plane_zpos); } static bool drm_output_check_plane_has_view_assigned(struct drm_plane *plane, struct drm_output_state *output_state) { struct drm_plane_state *ps; wl_list_for_each(ps, &output_state->plane_list, link) { if (ps->plane == plane && ps->fb) return true; } return false; } static bool drm_output_plane_has_valid_format(struct drm_plane *plane, struct drm_output_state *state, struct drm_fb *fb) { struct drm_backend *b = plane->backend; unsigned int i; if (!fb) return false; /* Check whether the format is supported */ for (i = 0; i < plane->count_formats; i++) { unsigned int j; if (plane->formats[i].format != fb->format->format) continue; if (fb->modifier == DRM_FORMAT_MOD_INVALID) return true; for (j = 0; j < plane->formats[i].count_modifiers; j++) { if (plane->formats[i].modifiers[j] == fb->modifier) return true; } } drm_debug(b, "\t\t\t\t[%s] not placing view on %s: " "no free %s planes matching format %s (0x%lx) " "modifier 0x%llx\n", drm_output_get_plane_type_name(plane), drm_output_get_plane_type_name(plane), drm_output_get_plane_type_name(plane), fb->format->drm_format_name, (unsigned long) fb->format, (unsigned long long) fb->modifier); return false; } static bool drm_output_plane_cursor_has_valid_format(struct weston_view *ev) { struct wl_shm_buffer *shmbuf = wl_shm_buffer_get(ev->surface->buffer_ref.buffer->resource); if (shmbuf && wl_shm_buffer_get_format(shmbuf) == WL_SHM_FORMAT_ARGB8888) return true; return false; } static struct drm_plane_state * drm_output_prepare_overlay_view(struct drm_plane *plane, struct drm_output_state *output_state, struct weston_view *ev, enum drm_output_propose_state_mode mode, struct drm_fb *fb, uint64_t zpos) { struct drm_output *output = output_state->output; struct weston_compositor *ec = output->base.compositor; struct drm_backend *b = to_drm_backend(ec); struct drm_plane_state *state = NULL; int ret; assert(!b->sprites_are_broken); assert(b->atomic_modeset); if (!fb) { drm_debug(b, "\t\t\t\t[overlay] not placing view %p on overlay: " " couldn't get fb\n", ev); return NULL; } state = drm_output_state_get_plane(output_state, plane); /* we can't have a 'pending' framebuffer as never set one before reaching here */ assert(!state->fb); state->ev = ev; state->output = output; if (!drm_plane_state_coords_for_view(state, ev, zpos)) { drm_debug(b, "\t\t\t\t[overlay] not placing view %p on overlay: " "unsuitable transform\n", ev); drm_plane_state_put_back(state); state = NULL; goto out; } /* If the surface buffer has an in-fence fd, but the plane * doesn't support fences, we can't place the buffer on this * plane. */ if (ev->surface->acquire_fence_fd >= 0 && plane->props[WDRM_PLANE_IN_FENCE_FD].prop_id == 0) { drm_debug(b, "\t\t\t\t[overlay] not placing view %p on overlay: " "no in-fence support\n", ev); drm_plane_state_put_back(state); state = NULL; goto out; } /* We hold one reference for the lifetime of this function; from * calling drm_fb_get_from_view() in drm_output_prepare_plane_view(), * so, we take another reference here to live within the state. */ state->fb = drm_fb_ref(fb); state->in_fence_fd = ev->surface->acquire_fence_fd; /* In planes-only mode, we don't have an incremental state to * test against, so we just hope it'll work. */ if (mode == DRM_OUTPUT_PROPOSE_STATE_PLANES_ONLY) { drm_debug(b, "\t\t\t[overlay] provisionally placing " "view %p on overlay %lu in planes-only mode\n", ev, (unsigned long) plane->plane_id); goto out; } ret = drm_pending_state_test(output_state->pending_state); if (ret == 0) { drm_debug(b, "\t\t\t[overlay] provisionally placing " "view %p on overlay %d in mixed mode\n", ev, plane->plane_id); goto out; } drm_debug(b, "\t\t\t[overlay] not placing view %p on overlay %lu " "in mixed mode: kernel test failed\n", ev, (unsigned long) plane->plane_id); drm_plane_state_put_back(state); state = NULL; out: return state; } #ifdef BUILD_DRM_GBM /** * Update the image for the current cursor surface * * @param plane_state DRM cursor plane state * @param ev Source view for cursor */ static void cursor_bo_update(struct drm_plane_state *plane_state, struct weston_view *ev) { struct drm_backend *b = plane_state->plane->backend; struct gbm_bo *bo = plane_state->fb->bo; struct weston_buffer *buffer = ev->surface->buffer_ref.buffer; uint32_t buf[b->cursor_width * b->cursor_height]; int32_t stride; uint8_t *s; int i; assert(buffer && buffer->shm_buffer); assert(buffer->shm_buffer == wl_shm_buffer_get(buffer->resource)); assert(buffer->width <= b->cursor_width); assert(buffer->height <= b->cursor_height); memset(buf, 0, sizeof buf); stride = wl_shm_buffer_get_stride(buffer->shm_buffer); s = wl_shm_buffer_get_data(buffer->shm_buffer); wl_shm_buffer_begin_access(buffer->shm_buffer); for (i = 0; i < buffer->height; i++) memcpy(buf + i * b->cursor_width, s + i * stride, buffer->width * 4); wl_shm_buffer_end_access(buffer->shm_buffer); if (gbm_bo_write(bo, buf, sizeof buf) < 0) weston_log("failed update cursor: %s\n", strerror(errno)); } static struct drm_plane_state * drm_output_prepare_cursor_view(struct drm_output_state *output_state, struct weston_view *ev, uint64_t zpos) { struct drm_output *output = output_state->output; struct drm_backend *b = to_drm_backend(output->base.compositor); struct drm_plane *plane = output->cursor_plane; struct drm_plane_state *plane_state; bool needs_update = false; const char *p_name = drm_output_get_plane_type_name(plane); assert(!b->cursors_are_broken); if (!plane) return NULL; if (!plane->state_cur->complete) return NULL; if (plane->state_cur->output && plane->state_cur->output != output) return NULL; /* We use GBM to import SHM buffers. */ if (b->gbm == NULL) return NULL; plane_state = drm_output_state_get_plane(output_state, output->cursor_plane); if (plane_state && plane_state->fb) return NULL; /* We can't scale with the legacy API, and we don't try to account for * simple cropping/translation in cursor_bo_update. */ plane_state->output = output; if (!drm_plane_state_coords_for_view(plane_state, ev, zpos)) { drm_debug(b, "\t\t\t\t[%s] not placing view %p on %s: " "unsuitable transform\n", p_name, ev, p_name); goto err; } if (plane_state->src_x != 0 || plane_state->src_y != 0 || plane_state->src_w > (unsigned) b->cursor_width << 16 || plane_state->src_h > (unsigned) b->cursor_height << 16 || plane_state->src_w != plane_state->dest_w << 16 || plane_state->src_h != plane_state->dest_h << 16) { drm_debug(b, "\t\t\t\t[%s] not assigning view %p to %s plane " "(positioning requires cropping or scaling)\n", p_name, ev, p_name); goto err; } /* Since we're setting plane state up front, we need to work out * whether or not we need to upload a new cursor. We can't use the * plane damage, since the planes haven't actually been calculated * yet: instead try to figure it out directly. KMS cursor planes are * pretty unique here, in that they lie partway between a Weston plane * (direct scanout) and a renderer. */ if (ev != output->cursor_view || pixman_region32_not_empty(&ev->surface->damage)) { output->current_cursor++; output->current_cursor = output->current_cursor % ARRAY_LENGTH(output->gbm_cursor_fb); needs_update = true; } output->cursor_view = ev; plane_state->ev = ev; plane_state->fb = drm_fb_ref(output->gbm_cursor_fb[output->current_cursor]); if (needs_update) { drm_debug(b, "\t\t\t\t[%s] copying new content to cursor BO\n", p_name); cursor_bo_update(plane_state, ev); } /* The cursor API is somewhat special: in cursor_bo_update(), we upload * a buffer which is always cursor_width x cursor_height, even if the * surface we want to promote is actually smaller than this. Manually * mangle the plane state to deal with this. */ plane_state->src_w = b->cursor_width << 16; plane_state->src_h = b->cursor_height << 16; plane_state->dest_w = b->cursor_width; plane_state->dest_h = b->cursor_height; drm_debug(b, "\t\t\t\t[%s] provisionally assigned view %p to cursor\n", p_name, ev); return plane_state; err: drm_plane_state_put_back(plane_state); return NULL; } #else static struct drm_plane_state * drm_output_prepare_cursor_view(struct drm_output_state *output_state, struct weston_view *ev, uint64_t zpos) { return NULL; } #endif static struct drm_plane_state * drm_output_prepare_scanout_view(struct drm_output_state *output_state, struct weston_view *ev, enum drm_output_propose_state_mode mode, struct drm_fb *fb, uint64_t zpos) { struct drm_output *output = output_state->output; struct drm_backend *b = to_drm_backend(output->base.compositor); struct drm_plane *scanout_plane = output->scanout_plane; struct drm_plane_state *state; const char *p_name = drm_output_get_plane_type_name(scanout_plane); assert(!b->sprites_are_broken); assert(b->atomic_modeset); assert(mode == DRM_OUTPUT_PROPOSE_STATE_PLANES_ONLY); /* Check the view spans exactly the output size, calculated in the * logical co-ordinate space. */ if (!weston_view_matches_output_entirely(ev, &output->base)) { drm_debug(b, "\t\t\t\t[%s] not placing view %p on %s: " " view does not match output entirely\n", p_name, ev, p_name); return NULL; } /* If the surface buffer has an in-fence fd, but the plane doesn't * support fences, we can't place the buffer on this plane. */ if (ev->surface->acquire_fence_fd >= 0 && scanout_plane->props[WDRM_PLANE_IN_FENCE_FD].prop_id == 0) { drm_debug(b, "\t\t\t\t[%s] not placing view %p on %s: " "no in-fence support\n", p_name, ev, p_name); return NULL; } if (!fb) { drm_debug(b, "\t\t\t\t[%s] not placing view %p on %s: " " couldn't get fb\n", p_name, ev, p_name); return NULL; } state = drm_output_state_get_plane(output_state, scanout_plane); /* The only way we can already have a buffer in the scanout plane is * if we are in mixed mode, or if a client buffer has already been * placed into scanout. The former case will never call into here, * and in the latter case, the view must have been marked as occluded, * meaning we should never have ended up here. */ assert(!state->fb); /* take another reference here to live within the state */ state->fb = drm_fb_ref(fb); state->ev = ev; state->output = output; if (!drm_plane_state_coords_for_view(state, ev, zpos)) { drm_debug(b, "\t\t\t\t[%s] not placing view %p on %s: " "unsuitable transform\n", p_name, ev, p_name); goto err; } if (state->dest_x != 0 || state->dest_y != 0 || state->dest_w != (unsigned) output->base.current_mode->width || state->dest_h != (unsigned) output->base.current_mode->height) { drm_debug(b, "\t\t\t\t[%s] not placing view %p on %s: " " invalid plane state\n", p_name, ev, p_name); goto err; } state->in_fence_fd = ev->surface->acquire_fence_fd; /* In plane-only mode, we don't need to test the state now, as we * will only test it once at the end. */ return state; err: drm_plane_state_put_back(state); return NULL; } static bool drm_output_plane_view_has_valid_format(struct drm_plane *plane, struct drm_output_state *state, struct weston_view *ev, struct drm_fb *fb) { /* depending on the type of the plane we have different requirements */ switch (plane->type) { case WDRM_PLANE_TYPE_CURSOR: return drm_output_plane_cursor_has_valid_format(ev); case WDRM_PLANE_TYPE_OVERLAY: return drm_output_plane_has_valid_format(plane, state, fb); case WDRM_PLANE_TYPE_PRIMARY: return drm_output_plane_has_valid_format(plane, state, fb); default: assert(0); return false; } return false; } static struct drm_plane_state * drm_output_try_view_on_plane(struct drm_plane *plane, struct drm_output_state *state, struct weston_view *ev, enum drm_output_propose_state_mode mode, struct drm_fb *fb, uint64_t zpos) { struct drm_backend *b = state->pending_state->backend; struct weston_output *wet_output = &state->output->base; bool view_matches_entire_output, scanout_has_view_assigned; struct drm_plane *scanout_plane = state->output->scanout_plane; struct drm_plane_state *ps = NULL; const char *p_name = drm_output_get_plane_type_name(plane); enum { NO_PLANES, /* generic err-handle */ NO_PLANES_ACCEPTED, PLACED_ON_PLANE, } availability = NO_PLANES; /* sanity checks in case we over/underflow zpos or pass incorrect * values */ assert(zpos <= plane->zpos_max || zpos != DRM_PLANE_ZPOS_INVALID_PLANE); switch (plane->type) { case WDRM_PLANE_TYPE_CURSOR: if (b->cursors_are_broken) { availability = NO_PLANES_ACCEPTED; goto out; } ps = drm_output_prepare_cursor_view(state, ev, zpos); if (ps) availability = PLACED_ON_PLANE; break; case WDRM_PLANE_TYPE_OVERLAY: /* do not attempt to place it in the overlay if we don't have * anything in the scanout/primary and the view doesn't cover * the entire output */ view_matches_entire_output = weston_view_matches_output_entirely(ev, wet_output); scanout_has_view_assigned = drm_output_check_plane_has_view_assigned(scanout_plane, state); if (view_matches_entire_output && !scanout_has_view_assigned) { availability = NO_PLANES_ACCEPTED; goto out; } ps = drm_output_prepare_overlay_view(plane, state, ev, mode, fb, zpos); if (ps) availability = PLACED_ON_PLANE; break; case WDRM_PLANE_TYPE_PRIMARY: if (mode != DRM_OUTPUT_PROPOSE_STATE_PLANES_ONLY) { availability = NO_PLANES_ACCEPTED; goto out; } ps = drm_output_prepare_scanout_view(state, ev, mode, fb, zpos); if (ps) availability = PLACED_ON_PLANE; break; default: assert(0); break; } out: switch (availability) { case NO_PLANES: /* set initial to this catch-all case, such that * prepare_cursor/overlay/scanout() should have/contain the * reason for failling */ break; case NO_PLANES_ACCEPTED: drm_debug(b, "\t\t\t\t[plane] plane %d refusing to " "place view %p in %s\n", plane->plane_id, ev, p_name); break; case PLACED_ON_PLANE: break; } return ps; } static void drm_output_check_zpos_plane_states(struct drm_output_state *state) { struct drm_plane_state *ps; wl_list_for_each(ps, &state->plane_list, link) { struct wl_list *next_node = ps->link.next; bool found_dup = false; /* skip any plane that is not enabled */ if (!ps->fb) continue; assert(ps->zpos != DRM_PLANE_ZPOS_INVALID_PLANE); /* find another plane with the same zpos value */ if (next_node == &state->plane_list) break; while (next_node && next_node != &state->plane_list) { struct drm_plane_state *ps_next; ps_next = container_of(next_node, struct drm_plane_state, link); if (ps->zpos == ps_next->zpos) { found_dup = true; break; } next_node = next_node->next; } /* this should never happen so exit hard in case * we screwed up that bad */ assert(!found_dup); } } static struct drm_plane_state * drm_output_prepare_plane_view(struct drm_output_state *state, struct weston_view *ev, enum drm_output_propose_state_mode mode, struct drm_plane_state *scanout_state, uint64_t current_lowest_zpos) { struct drm_output *output = state->output; struct drm_backend *b = to_drm_backend(output->base.compositor); struct drm_plane_state *ps = NULL; struct drm_plane *plane; struct drm_plane_zpos *p_zpos, *p_zpos_next; struct wl_list zpos_candidate_list; struct drm_fb *fb; wl_list_init(&zpos_candidate_list); /* check view for valid buffer, doesn't make sense to even try */ if (!weston_view_has_valid_buffer(ev)) return ps; fb = drm_fb_get_from_view(state, ev); /* assemble a list with possible candidates */ wl_list_for_each(plane, &b->plane_list, link) { if (!drm_plane_is_available(plane, output)) continue; if (drm_output_check_plane_has_view_assigned(plane, state)) { drm_debug(b, "\t\t\t\t[plane] not adding plane %d to" " candidate list: view already assigned " "to a plane\n", plane->plane_id); continue; } if (plane->zpos_min >= current_lowest_zpos) { drm_debug(b, "\t\t\t\t[plane] not adding plane %d to " "candidate list: minium zpos (%"PRIu64") " "plane's above current lowest zpos " "(%"PRIu64")\n", plane->plane_id, plane->zpos_min, current_lowest_zpos); continue; } if (mode == DRM_OUTPUT_PROPOSE_STATE_MIXED) { assert(scanout_state != NULL); if (scanout_state->zpos >= plane->zpos_max) { drm_debug(b, "\t\t\t\t[plane] not adding plane %d to " "candidate list: primary's zpos " "value (%"PRIu64") higher than " "plane's maximum value (%"PRIu64")\n", plane->plane_id, scanout_state->zpos, plane->zpos_max); continue; } } if (mode == DRM_OUTPUT_PROPOSE_STATE_RENDERER_ONLY && (plane->type == WDRM_PLANE_TYPE_OVERLAY || plane->type == WDRM_PLANE_TYPE_PRIMARY)) { drm_debug(b, "\t\t\t\t[plane] not adding plane %d to " "candidate list: renderer-only mode\n", plane->plane_id); continue; } if (plane->type != WDRM_PLANE_TYPE_CURSOR && b->sprites_are_broken) { drm_debug(b, "\t\t\t\t[plane] not adding plane %d, type %s to " "candidate list: sprites are broken!\n", plane->plane_id, drm_output_get_plane_type_name(plane)); continue; } if (!drm_output_plane_view_has_valid_format(plane, state, ev, fb)) { drm_debug(b, "\t\t\t\t[plane] not adding plane %d to " "candidate list: invalid pixel format\n", plane->plane_id); continue; } drm_output_add_zpos_plane(plane, &zpos_candidate_list); } /* go over the potential candidate list and try to find a possible * plane suitable for \c ev; start with the highest zpos value of a * plane to maximize our chances, but do note we pass the zpos value * based on current tracked value by \c current_lowest_zpos_in_use */ while (!wl_list_empty(&zpos_candidate_list)) { struct drm_plane_zpos *head_p_zpos = wl_container_of(zpos_candidate_list.next, head_p_zpos, link); struct drm_plane *plane = head_p_zpos->plane; const char *p_name = drm_output_get_plane_type_name(plane); uint64_t zpos; if (current_lowest_zpos == DRM_PLANE_ZPOS_INVALID_PLANE) zpos = plane->zpos_max; else zpos = MIN(current_lowest_zpos - 1, plane->zpos_max); drm_debug(b, "\t\t\t\t[plane] plane %d picked " "from candidate list, type: %s\n", plane->plane_id, p_name); ps = drm_output_try_view_on_plane(plane, state, ev, mode, fb, zpos); drm_output_destroy_zpos_plane(head_p_zpos); if (ps) { drm_debug(b, "\t\t\t\t[view] view %p has been placed to " "%s plane with computed zpos %"PRIu64"\n", ev, p_name, zpos); break; } } wl_list_for_each_safe(p_zpos, p_zpos_next, &zpos_candidate_list, link) drm_output_destroy_zpos_plane(p_zpos); drm_fb_unref(fb); return ps; } static struct drm_output_state * drm_output_propose_state(struct weston_output *output_base, struct drm_pending_state *pending_state, enum drm_output_propose_state_mode mode) { struct drm_output *output = to_drm_output(output_base); struct drm_backend *b = to_drm_backend(output->base.compositor); struct drm_output_state *state; struct drm_plane_state *scanout_state = NULL; struct weston_view *ev; pixman_region32_t surface_overlap, renderer_region, planes_region; pixman_region32_t occluded_region; bool renderer_ok = (mode != DRM_OUTPUT_PROPOSE_STATE_PLANES_ONLY); int ret; uint64_t current_lowest_zpos = DRM_PLANE_ZPOS_INVALID_PLANE; assert(!output->state_last); state = drm_output_state_duplicate(output->state_cur, pending_state, DRM_OUTPUT_STATE_CLEAR_PLANES); /* We implement mixed mode by progressively creating and testing * incremental states, of scanout + overlay + cursor. Since we * walk our views top to bottom, the scanout plane is last, however * we always need it in our scene for the test modeset to be * meaningful. To do this, we steal a reference to the last * renderer framebuffer we have, if we think it's basically * compatible. If we don't have that, then we conservatively fall * back to only using the renderer for this repaint. */ if (mode == DRM_OUTPUT_PROPOSE_STATE_MIXED) { struct drm_plane *plane = output->scanout_plane; struct drm_fb *scanout_fb = plane->state_cur->fb; if (!scanout_fb || (scanout_fb->type != BUFFER_GBM_SURFACE && scanout_fb->type != BUFFER_PIXMAN_DUMB)) { drm_debug(b, "\t\t[state] cannot propose mixed mode: " "for output %s (%lu): no previous renderer " "fb\n", output->base.name, (unsigned long) output->base.id); drm_output_state_free(state); return NULL; } if (scanout_fb->width != output_base->current_mode->width || scanout_fb->height != output_base->current_mode->height) { drm_debug(b, "\t\t[state] cannot propose mixed mode " "for output %s (%lu): previous fb has " "different size\n", output->base.name, (unsigned long) output->base.id); drm_output_state_free(state); return NULL; } scanout_state = drm_plane_state_duplicate(state, plane->state_cur); /* assign the primary primary the lowest zpos value */ scanout_state->zpos = plane->zpos_min; drm_debug(b, "\t\t[state] using renderer FB ID %lu for mixed " "mode for output %s (%lu)\n", (unsigned long) scanout_fb->fb_id, output->base.name, (unsigned long) output->base.id); drm_debug(b, "\t\t[state] scanout will use for zpos %"PRIu64"\n", scanout_state->zpos); } /* - renderer_region contains the total region which which will be * covered by the renderer * - planes_region contains the total region which has been covered by * hardware planes * - occluded_region contains the total region which which will be * covered by the renderer and hardware planes, where the view's * visible-and-opaque region is added in both cases (the view's * opaque region accumulates there for each view); it is being used * to skip the view, if it is completely occluded; includes the * situation where occluded_region covers entire output's region. */ pixman_region32_init(&renderer_region); pixman_region32_init(&planes_region); pixman_region32_init(&occluded_region); wl_list_for_each(ev, &output_base->compositor->view_list, link) { struct drm_plane_state *ps = NULL; bool force_renderer = false; pixman_region32_t clipped_view; bool totally_occluded = false; drm_debug(b, "\t\t\t[view] evaluating view %p for " "output %s (%lu)\n", ev, output->base.name, (unsigned long) output->base.id); /* If this view doesn't touch our output at all, there's no * reason to do anything with it. */ if (!(ev->output_mask & (1u << output->base.id))) { drm_debug(b, "\t\t\t\t[view] ignoring view %p " "(not on our output)\n", ev); continue; } /* Ignore views we know to be totally occluded. */ pixman_region32_init(&clipped_view); pixman_region32_intersect(&clipped_view, &ev->transform.boundingbox, &output->base.region); pixman_region32_init(&surface_overlap); pixman_region32_subtract(&surface_overlap, &clipped_view, &occluded_region); /* if the view is completely occluded then ignore that * view; includes the case where occluded_region covers * the entire output */ totally_occluded = !pixman_region32_not_empty(&surface_overlap); if (totally_occluded) { drm_debug(b, "\t\t\t\t[view] ignoring view %p " "(occluded on our output)\n", ev); pixman_region32_fini(&surface_overlap); pixman_region32_fini(&clipped_view); continue; } /* We only assign planes to views which are exclusively present * on our output. */ if (ev->output_mask != (1u << output->base.id)) { drm_debug(b, "\t\t\t\t[view] not assigning view %p to plane " "(on multiple outputs)\n", ev); force_renderer = true; } if (!weston_view_has_valid_buffer(ev)) { drm_debug(b, "\t\t\t\t[view] not assigning view %p to plane " "(no buffer available)\n", ev); force_renderer = true; } /* Since we process views from top to bottom, we know that if * the view intersects the calculated renderer region, it must * be part of, or occluded by, it, and cannot go on a plane. */ pixman_region32_intersect(&surface_overlap, &renderer_region, &clipped_view); if (pixman_region32_not_empty(&surface_overlap)) { drm_debug(b, "\t\t\t\t[view] not assigning view %p to plane " "(occluded by renderer views)\n", ev); force_renderer = true; } pixman_region32_fini(&surface_overlap); /* In case of enforced mode of content-protection do not * assign planes for a protected surface on an unsecured output. */ if (ev->surface->protection_mode == WESTON_SURFACE_PROTECTION_MODE_ENFORCED && ev->surface->desired_protection > output_base->current_protection) { drm_debug(b, "\t\t\t\t[view] not assigning view %p to plane " "(enforced protection mode on unsecured output)\n", ev); force_renderer = true; } if (!force_renderer) { drm_debug(b, "\t\t\t[plane] started with zpos %"PRIu64"\n", current_lowest_zpos); ps = drm_output_prepare_plane_view(state, ev, mode, scanout_state, current_lowest_zpos); } if (ps) { current_lowest_zpos = ps->zpos; drm_debug(b, "\t\t\t[plane] next zpos to use %"PRIu64"\n", current_lowest_zpos); /* If we have been assigned to an overlay or scanout * plane, add this area to the occluded region, so * other views are known to be behind it. The cursor * plane, however, is special, in that it blends with * the content underneath it: the area should neither * be added to the renderer region nor the occluded * region. */ if (ps->plane->type != WDRM_PLANE_TYPE_CURSOR) { pixman_region32_union(&planes_region, &planes_region, &clipped_view); if (!weston_view_is_opaque(ev, &clipped_view)) pixman_region32_intersect(&clipped_view, &clipped_view, &ev->transform.opaque); /* the visible-and-opaque region of this view * will occlude views underneath it */ pixman_region32_union(&occluded_region, &occluded_region, &clipped_view); pixman_region32_fini(&clipped_view); } continue; } /* We have been assigned to the primary (renderer) plane: * check if this is OK, and add ourselves to the renderer * region if so. */ if (!renderer_ok) { drm_debug(b, "\t\t[view] failing state generation: " "placing view %p to renderer not allowed\n", ev); pixman_region32_fini(&clipped_view); goto err_region; } pixman_region32_union(&renderer_region, &renderer_region, &clipped_view); if (!weston_view_is_opaque(ev, &clipped_view)) pixman_region32_intersect(&clipped_view, &clipped_view, &ev->transform.opaque); pixman_region32_union(&occluded_region, &occluded_region, &clipped_view); pixman_region32_fini(&clipped_view); drm_debug(b, "\t\t\t\t[view] view %p will be placed " "on the renderer\n", ev); } pixman_region32_fini(&renderer_region); pixman_region32_fini(&planes_region); pixman_region32_fini(&occluded_region); /* In renderer-only mode, we can't test the state as we don't have a * renderer buffer yet. */ if (mode == DRM_OUTPUT_PROPOSE_STATE_RENDERER_ONLY) return state; /* check if we have invalid zpos values, like duplicate(s) */ drm_output_check_zpos_plane_states(state); /* Check to see if this state will actually work. */ ret = drm_pending_state_test(state->pending_state); if (ret != 0) { drm_debug(b, "\t\t[view] failing state generation: " "atomic test not OK\n"); goto err; } /* Counterpart to duplicating scanout state at the top of this * function: if we have taken a renderer framebuffer and placed it in * the pending state in order to incrementally test overlay planes, * remove it now. */ if (mode == DRM_OUTPUT_PROPOSE_STATE_MIXED) { assert(scanout_state->fb->type == BUFFER_GBM_SURFACE || scanout_state->fb->type == BUFFER_PIXMAN_DUMB); drm_plane_state_put_back(scanout_state); } return state; err_region: pixman_region32_fini(&renderer_region); pixman_region32_fini(&occluded_region); err: drm_output_state_free(state); return NULL; } void drm_assign_planes(struct weston_output *output_base, void *repaint_data) { struct drm_backend *b = to_drm_backend(output_base->compositor); struct drm_pending_state *pending_state = repaint_data; struct drm_output *output = to_drm_output(output_base); struct drm_output_state *state = NULL; struct drm_plane_state *plane_state; struct weston_view *ev; struct weston_plane *primary = &output_base->compositor->primary_plane; enum drm_output_propose_state_mode mode = DRM_OUTPUT_PROPOSE_STATE_PLANES_ONLY; drm_debug(b, "\t[repaint] preparing state for output %s (%lu)\n", output_base->name, (unsigned long) output_base->id); if (!b->sprites_are_broken && !output->virtual) { drm_debug(b, "\t[repaint] trying planes-only build state\n"); state = drm_output_propose_state(output_base, pending_state, mode); if (!state) { drm_debug(b, "\t[repaint] could not build planes-only " "state, trying mixed\n"); mode = DRM_OUTPUT_PROPOSE_STATE_MIXED; state = drm_output_propose_state(output_base, pending_state, mode); } if (!state) { drm_debug(b, "\t[repaint] could not build mixed-mode " "state, trying renderer-only\n"); } } else { drm_debug(b, "\t[state] no overlay plane support\n"); } if (!state) { mode = DRM_OUTPUT_PROPOSE_STATE_RENDERER_ONLY; state = drm_output_propose_state(output_base, pending_state, mode); } assert(state); drm_debug(b, "\t[repaint] Using %s composition\n", drm_propose_state_mode_to_string(mode)); wl_list_for_each(ev, &output_base->compositor->view_list, link) { struct drm_plane *target_plane = NULL; /* If this view doesn't touch our output at all, there's no * reason to do anything with it. */ if (!(ev->output_mask & (1u << output->base.id))) continue; /* Test whether this buffer can ever go into a plane: * non-shm, or small enough to be a cursor. * * Also, keep a reference when using the pixman renderer. * That makes it possible to do a seamless switch to the GL * renderer and since the pixman renderer keeps a reference * to the buffer anyway, there is no side effects. */ if (b->use_pixman || (weston_view_has_valid_buffer(ev) && (!wl_shm_buffer_get(ev->surface->buffer_ref.buffer->resource) || (ev->surface->width <= b->cursor_width && ev->surface->height <= b->cursor_height)))) ev->surface->keep_buffer = true; else ev->surface->keep_buffer = false; /* This is a bit unpleasant, but lacking a temporary place to * hang a plane off the view, we have to do a nested walk. * Our first-order iteration has to be planes rather than * views, because otherwise we won't reset views which were * previously on planes to being on the primary plane. */ wl_list_for_each(plane_state, &state->plane_list, link) { if (plane_state->ev == ev) { plane_state->ev = NULL; target_plane = plane_state->plane; break; } } if (target_plane) { drm_debug(b, "\t[repaint] view %p on %s plane %lu\n", ev, plane_type_enums[target_plane->type].name, (unsigned long) target_plane->plane_id); weston_view_move_to_plane(ev, &target_plane->base); } else { drm_debug(b, "\t[repaint] view %p using renderer " "composition\n", ev); weston_view_move_to_plane(ev, primary); } if (!target_plane || target_plane->type == WDRM_PLANE_TYPE_CURSOR) { /* cursor plane & renderer involve a copy */ ev->psf_flags = 0; } else { /* All other planes are a direct scanout of a * single client buffer. */ ev->psf_flags = WP_PRESENTATION_FEEDBACK_KIND_ZERO_COPY; } } /* We rely on output->cursor_view being both an accurate reflection of * the cursor plane's state, but also being maintained across repaints * to avoid unnecessary damage uploads, per the comment in * drm_output_prepare_cursor_view. In the event that we go from having * a cursor view to not having a cursor view, we need to clear it. */ if (output->cursor_view) { plane_state = drm_output_state_get_existing_plane(state, output->cursor_plane); if (!plane_state || !plane_state->fb) output->cursor_view = NULL; } }
utf-8
1
BSD-3-clause
The Chromium Authors. All rights reserved.
yquake2-8.01+ctf1.08~dfsg/src/game/monster/boss3/boss31.c
/* * Copyright (C) 1997-2001 Id Software, Inc. * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or (at * your option) any later version. * * This program is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. * * See the GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA * 02111-1307, USA. * * ======================================================================= * * Final boss, stage 1 (jorg). * * ======================================================================= */ #include "../../header/local.h" #include "boss31.h" extern void SP_monster_makron(edict_t *self); qboolean visible(edict_t *self, edict_t *other); static int sound_pain1; static int sound_pain2; static int sound_pain3; static int sound_idle; static int sound_death; static int sound_search1; static int sound_search2; static int sound_search3; static int sound_attack1; static int sound_attack2; static int sound_firegun; static int sound_step_left; static int sound_step_right; static int sound_death_hit; void BossExplode(edict_t *self); void MakronToss(edict_t *self); void jorg_search(edict_t *self) { float r; if (!self) { return; } r = random(); if (r <= 0.3) { gi.sound(self, CHAN_VOICE, sound_search1, 1, ATTN_NORM, 0); } else if (r <= 0.6) { gi.sound(self, CHAN_VOICE, sound_search2, 1, ATTN_NORM, 0); } else { gi.sound(self, CHAN_VOICE, sound_search3, 1, ATTN_NORM, 0); } } void jorg_dead(edict_t *self); void jorgBFG(edict_t *self); void jorgMachineGun(edict_t *self); void jorg_firebullet(edict_t *self); void jorg_reattack1(edict_t *self); void jorg_attack1(edict_t *self); void jorg_idle(edict_t *self); void jorg_step_left(edict_t *self); void jorg_step_right(edict_t *self); void jorg_death_hit(edict_t *self); mframe_t jorg_frames_stand[] = { {ai_stand, 0, jorg_idle}, {ai_stand, 0, NULL}, {ai_stand, 0, NULL}, {ai_stand, 0, NULL}, {ai_stand, 0, NULL}, {ai_stand, 0, NULL}, {ai_stand, 0, NULL}, {ai_stand, 0, NULL}, {ai_stand, 0, NULL}, {ai_stand, 0, NULL}, /* 10 */ {ai_stand, 0, NULL}, {ai_stand, 0, NULL}, {ai_stand, 0, NULL}, {ai_stand, 0, NULL}, {ai_stand, 0, NULL}, {ai_stand, 0, NULL}, {ai_stand, 0, NULL}, {ai_stand, 0, NULL}, {ai_stand, 0, NULL}, {ai_stand, 0, NULL}, /* 20 */ {ai_stand, 0, NULL}, {ai_stand, 0, NULL}, {ai_stand, 0, NULL}, {ai_stand, 0, NULL}, {ai_stand, 0, NULL}, {ai_stand, 0, NULL}, {ai_stand, 0, NULL}, {ai_stand, 0, NULL}, {ai_stand, 0, NULL}, {ai_stand, 0, NULL}, /* 30 */ {ai_stand, 0, NULL}, {ai_stand, 0, NULL}, {ai_stand, 0, NULL}, {ai_stand, 19, NULL}, {ai_stand, 11, jorg_step_left}, {ai_stand, 0, NULL}, {ai_stand, 0, NULL}, {ai_stand, 6, NULL}, {ai_stand, 9, jorg_step_right}, {ai_stand, 0, NULL}, /* 40 */ {ai_stand, 0, NULL}, {ai_stand, 0, NULL}, {ai_stand, 0, NULL}, {ai_stand, 0, NULL}, {ai_stand, 0, NULL}, {ai_stand, 0, NULL}, {ai_stand, -2, NULL}, {ai_stand, -17, jorg_step_left}, {ai_stand, 0, NULL}, {ai_stand, -12, NULL}, /* 50 */ {ai_stand, -14, jorg_step_right} }; mmove_t jorg_move_stand = { FRAME_stand01, FRAME_stand51, jorg_frames_stand, NULL }; void jorg_idle(edict_t *self) { if (!self) { return; } gi.sound(self, CHAN_VOICE, sound_idle, 1, ATTN_NORM, 0); } void jorg_death_hit(edict_t *self) { if (!self) { return; } gi.sound(self, CHAN_BODY, sound_death_hit, 1, ATTN_NORM, 0); } void jorg_step_left(edict_t *self) { if (!self) { return; } gi.sound(self, CHAN_BODY, sound_step_left, 1, ATTN_NORM, 0); } void jorg_step_right(edict_t *self) { if (!self) { return; } gi.sound(self, CHAN_BODY, sound_step_right, 1, ATTN_NORM, 0); } void jorg_stand(edict_t *self) { if (!self) { return; } self->monsterinfo.currentmove = &jorg_move_stand; } mframe_t jorg_frames_run[] = { {ai_run, 17, jorg_step_left}, {ai_run, 0, NULL}, {ai_run, 0, NULL}, {ai_run, 0, NULL}, {ai_run, 12, NULL}, {ai_run, 8, NULL}, {ai_run, 10, NULL}, {ai_run, 33, jorg_step_right}, {ai_run, 0, NULL}, {ai_run, 0, NULL}, {ai_run, 0, NULL}, {ai_run, 9, NULL}, {ai_run, 9, NULL}, {ai_run, 9, NULL} }; mmove_t jorg_move_run = { FRAME_walk06, FRAME_walk19, jorg_frames_run, NULL }; mframe_t jorg_frames_start_walk[] = { {ai_walk, 5, NULL}, {ai_walk, 6, NULL}, {ai_walk, 7, NULL}, {ai_walk, 9, NULL}, {ai_walk, 15, NULL} }; mmove_t jorg_move_start_walk = { FRAME_walk01, FRAME_walk05, jorg_frames_start_walk, NULL }; mframe_t jorg_frames_walk[] = { {ai_walk, 17, NULL}, {ai_walk, 0, NULL}, {ai_walk, 0, NULL}, {ai_walk, 0, NULL}, {ai_walk, 12, NULL}, {ai_walk, 8, NULL}, {ai_walk, 10, NULL}, {ai_walk, 33, NULL}, {ai_walk, 0, NULL}, {ai_walk, 0, NULL}, {ai_walk, 0, NULL}, {ai_walk, 9, NULL}, {ai_walk, 9, NULL}, {ai_walk, 9, NULL} }; mmove_t jorg_move_walk = { FRAME_walk06, FRAME_walk19, jorg_frames_walk, NULL }; mframe_t jorg_frames_end_walk[] = { {ai_walk, 11, NULL}, {ai_walk, 0, NULL}, {ai_walk, 0, NULL}, {ai_walk, 0, NULL}, {ai_walk, 8, NULL}, {ai_walk, -8, NULL} }; mmove_t jorg_move_end_walk = { FRAME_walk20, FRAME_walk25, jorg_frames_end_walk, NULL }; void jorg_walk(edict_t *self) { if (!self) { return; } self->monsterinfo.currentmove = &jorg_move_walk; } void jorg_run(edict_t *self) { if (!self) { return; } if (self->monsterinfo.aiflags & AI_STAND_GROUND) { self->monsterinfo.currentmove = &jorg_move_stand; } else { self->monsterinfo.currentmove = &jorg_move_run; } } mframe_t jorg_frames_pain3[] = { {ai_move, -28, NULL}, {ai_move, -6, NULL}, {ai_move, -3, jorg_step_left}, {ai_move, -9, NULL}, {ai_move, 0, jorg_step_right}, {ai_move, 0, NULL}, {ai_move, 0, NULL}, {ai_move, 0, NULL}, {ai_move, -7, NULL}, {ai_move, 1, NULL}, {ai_move, -11, NULL}, {ai_move, -4, NULL}, {ai_move, 0, NULL}, {ai_move, 0, NULL}, {ai_move, 10, NULL}, {ai_move, 11, NULL}, {ai_move, 0, NULL}, {ai_move, 10, NULL}, {ai_move, 3, NULL}, {ai_move, 10, NULL}, {ai_move, 7, jorg_step_left}, {ai_move, 17, NULL}, {ai_move, 0, NULL}, {ai_move, 0, NULL}, {ai_move, 0, jorg_step_right} }; mmove_t jorg_move_pain3 = { FRAME_pain301, FRAME_pain325, jorg_frames_pain3, jorg_run }; mframe_t jorg_frames_pain2[] = { {ai_move, 0, NULL}, {ai_move, 0, NULL}, {ai_move, 0, NULL} }; mmove_t jorg_move_pain2 = { FRAME_pain201, FRAME_pain203, jorg_frames_pain2, jorg_run }; mframe_t jorg_frames_pain1[] = { {ai_move, 0, NULL}, {ai_move, 0, NULL}, {ai_move, 0, NULL} }; mmove_t jorg_move_pain1 = { FRAME_pain101, FRAME_pain103, jorg_frames_pain1, jorg_run }; mframe_t jorg_frames_death1[] = { {ai_move, 0, NULL}, {ai_move, 0, NULL}, {ai_move, 0, NULL}, {ai_move, 0, NULL}, {ai_move, 0, NULL}, {ai_move, 0, NULL}, {ai_move, 0, NULL}, {ai_move, 0, NULL}, {ai_move, 0, NULL}, {ai_move, 0, NULL}, /* 10 */ {ai_move, 0, NULL}, {ai_move, 0, NULL}, {ai_move, 0, NULL}, {ai_move, 0, NULL}, {ai_move, 0, NULL}, {ai_move, 0, NULL}, {ai_move, 0, NULL}, {ai_move, 0, NULL}, {ai_move, 0, NULL}, {ai_move, 0, NULL}, /* 20 */ {ai_move, 0, NULL}, {ai_move, 0, NULL}, {ai_move, 0, NULL}, {ai_move, 0, NULL}, {ai_move, 0, NULL}, {ai_move, 0, NULL}, {ai_move, 0, NULL}, {ai_move, 0, NULL}, {ai_move, 0, NULL}, {ai_move, 0, NULL}, /* 30 */ {ai_move, 0, NULL}, {ai_move, 0, NULL}, {ai_move, 0, NULL}, {ai_move, 0, NULL}, {ai_move, 0, NULL}, {ai_move, 0, NULL}, {ai_move, 0, NULL}, {ai_move, 0, NULL}, {ai_move, 0, NULL}, {ai_move, 0, NULL}, /* 40 */ {ai_move, 0, NULL}, {ai_move, 0, NULL}, {ai_move, 0, NULL}, {ai_move, 0, NULL}, {ai_move, 0, NULL}, {ai_move, 0, NULL}, {ai_move, 0, NULL}, {ai_move, 0, NULL}, {ai_move, 0, MakronToss}, {ai_move, 0, BossExplode} /* 50 */ }; mmove_t jorg_move_death = { FRAME_death01, FRAME_death50, jorg_frames_death1, jorg_dead }; mframe_t jorg_frames_attack2[] = { {ai_charge, 0, NULL}, {ai_charge, 0, NULL}, {ai_charge, 0, NULL}, {ai_charge, 0, NULL}, {ai_charge, 0, NULL}, {ai_charge, 0, NULL}, {ai_charge, 0, jorgBFG}, {ai_move, 0, NULL}, {ai_move, 0, NULL}, {ai_move, 0, NULL}, {ai_move, 0, NULL}, {ai_move, 0, NULL}, {ai_move, 0, NULL} }; mmove_t jorg_move_attack2 = { FRAME_attak201, FRAME_attak213, jorg_frames_attack2, jorg_run }; mframe_t jorg_frames_start_attack1[] = { {ai_charge, 0, NULL}, {ai_charge, 0, NULL}, {ai_charge, 0, NULL}, {ai_charge, 0, NULL}, {ai_charge, 0, NULL}, {ai_charge, 0, NULL}, {ai_charge, 0, NULL}, {ai_charge, 0, NULL} }; mmove_t jorg_move_start_attack1 = { FRAME_attak101, FRAME_attak108, jorg_frames_start_attack1, jorg_attack1 }; mframe_t jorg_frames_attack1[] = { {ai_charge, 0, jorg_firebullet}, {ai_charge, 0, jorg_firebullet}, {ai_charge, 0, jorg_firebullet}, {ai_charge, 0, jorg_firebullet}, {ai_charge, 0, jorg_firebullet}, {ai_charge, 0, jorg_firebullet} }; mmove_t jorg_move_attack1 = { FRAME_attak109, FRAME_attak114, jorg_frames_attack1, jorg_reattack1 }; mframe_t jorg_frames_end_attack1[] = { {ai_move, 0, NULL}, {ai_move, 0, NULL}, {ai_move, 0, NULL}, {ai_move, 0, NULL} }; mmove_t jorg_move_end_attack1 = { FRAME_attak115, FRAME_attak118, jorg_frames_end_attack1, jorg_run }; void jorg_reattack1(edict_t *self) { if (!self) { return; } if (visible(self, self->enemy)) { if (random() < 0.9) { self->monsterinfo.currentmove = &jorg_move_attack1; } else { self->s.sound = 0; self->monsterinfo.currentmove = &jorg_move_end_attack1; } } else { self->s.sound = 0; self->monsterinfo.currentmove = &jorg_move_end_attack1; } } void jorg_attack1(edict_t *self) { if (!self) { return; } self->monsterinfo.currentmove = &jorg_move_attack1; } void jorg_pain(edict_t *self, edict_t *other /* unused */, float kick /* unused */, int damage) { if (!self) { return; } if (self->health < (self->max_health / 2)) { self->s.skinnum = 1; } self->s.sound = 0; if (level.time < self->pain_debounce_time) { return; } /* Lessen the chance of him going into his pain frames if he takes little damage */ if (damage <= 40) { if (random() <= 0.6) { return; } } /* If he's entering his attack1 or using attack1, lessen the chance of him going into pain */ if ((self->s.frame >= FRAME_attak101) && (self->s.frame <= FRAME_attak108)) { if (random() <= 0.005) { return; } } if ((self->s.frame >= FRAME_attak109) && (self->s.frame <= FRAME_attak114)) { if (random() <= 0.00005) { return; } } if ((self->s.frame >= FRAME_attak201) && (self->s.frame <= FRAME_attak208)) { if (random() <= 0.005) { return; } } self->pain_debounce_time = level.time + 3; if (skill->value == SKILL_HARDPLUS) { return; /* no pain anims in nightmare */ } if (damage <= 50) { gi.sound(self, CHAN_VOICE, sound_pain1, 1, ATTN_NORM, 0); self->monsterinfo.currentmove = &jorg_move_pain1; } else if (damage <= 100) { gi.sound(self, CHAN_VOICE, sound_pain2, 1, ATTN_NORM, 0); self->monsterinfo.currentmove = &jorg_move_pain2; } else { if (random() <= 0.3) { gi.sound(self, CHAN_VOICE, sound_pain3, 1, ATTN_NORM, 0); self->monsterinfo.currentmove = &jorg_move_pain3; } } } void jorgBFG(edict_t *self) { vec3_t forward, right; vec3_t start; vec3_t dir; vec3_t vec; if (!self) { return; } AngleVectors(self->s.angles, forward, right, NULL); G_ProjectSource(self->s.origin, monster_flash_offset[MZ2_JORG_BFG_1], forward, right, start); VectorCopy(self->enemy->s.origin, vec); vec[2] += self->enemy->viewheight; VectorSubtract(vec, start, dir); VectorNormalize(dir); gi.sound(self, CHAN_VOICE, sound_attack2, 1, ATTN_NORM, 0); monster_fire_bfg(self, start, dir, 50, 300, 100, 200, MZ2_JORG_BFG_1); } void jorg_firebullet_right(edict_t *self) { vec3_t forward, right, target; vec3_t start; if (!self) { return; } AngleVectors(self->s.angles, forward, right, NULL); G_ProjectSource(self->s.origin, monster_flash_offset[MZ2_JORG_MACHINEGUN_R1], forward, right, start); VectorMA(self->enemy->s.origin, -0.2, self->enemy->velocity, target); target[2] += self->enemy->viewheight; VectorSubtract(target, start, forward); VectorNormalize(forward); monster_fire_bullet(self, start, forward, 6, 4, DEFAULT_BULLET_HSPREAD, DEFAULT_BULLET_VSPREAD, MZ2_JORG_MACHINEGUN_R1); } void jorg_firebullet_left(edict_t *self) { vec3_t forward, right, target; vec3_t start; if (!self) { return; } AngleVectors(self->s.angles, forward, right, NULL); G_ProjectSource(self->s.origin, monster_flash_offset[MZ2_JORG_MACHINEGUN_L1], forward, right, start); VectorMA(self->enemy->s.origin, -0.2, self->enemy->velocity, target); target[2] += self->enemy->viewheight; VectorSubtract(target, start, forward); VectorNormalize(forward); monster_fire_bullet(self, start, forward, 6, 4, DEFAULT_BULLET_HSPREAD, DEFAULT_BULLET_VSPREAD, MZ2_JORG_MACHINEGUN_L1); } void jorg_firebullet(edict_t *self) { if (!self) { return; } jorg_firebullet_left(self); jorg_firebullet_right(self); } void jorg_attack(edict_t *self) { if (!self) { return; } if (random() <= 0.75) { gi.sound(self, CHAN_VOICE, sound_attack1, 1, ATTN_NORM, 0); self->s.sound = gi.soundindex("boss3/w_loop.wav"); self->monsterinfo.currentmove = &jorg_move_start_attack1; } else { gi.sound(self, CHAN_VOICE, sound_attack2, 1, ATTN_NORM, 0); self->monsterinfo.currentmove = &jorg_move_attack2; } } void jorg_dead(edict_t *self /* unused */) { /* unused, but removal is PITA */ } void jorg_die(edict_t *self, edict_t *inflictor /* unused */, edict_t *attacker /* unused */, int damage /* unused */, vec3_t point /* unused */) { if (!self) { return; } gi.sound(self, CHAN_VOICE, sound_death, 1, ATTN_NORM, 0); self->deadflag = DEAD_DEAD; self->takedamage = DAMAGE_NO; self->s.sound = 0; self->count = 0; self->monsterinfo.currentmove = &jorg_move_death; } qboolean Jorg_CheckAttack(edict_t *self) { vec3_t spot1, spot2; vec3_t temp; float chance; trace_t tr; int enemy_range; float enemy_yaw; if (!self) { return false; } if (self->enemy->health > 0) { /* see if any entities are in the way of the shot */ VectorCopy(self->s.origin, spot1); spot1[2] += self->viewheight; VectorCopy(self->enemy->s.origin, spot2); spot2[2] += self->enemy->viewheight; tr = gi.trace( spot1, NULL, NULL, spot2, self, CONTENTS_SOLID | CONTENTS_MONSTER | CONTENTS_SLIME | CONTENTS_LAVA); /* do we have a clear shot? */ if (tr.ent != self->enemy) { return false; } } enemy_range = range(self, self->enemy); VectorSubtract(self->enemy->s.origin, self->s.origin, temp); enemy_yaw = vectoyaw(temp); self->ideal_yaw = enemy_yaw; /* melee attack */ if (enemy_range == RANGE_MELEE) { if (self->monsterinfo.melee) { self->monsterinfo.attack_state = AS_MELEE; } else { self->monsterinfo.attack_state = AS_MISSILE; } return true; } /* missile attack */ if (!self->monsterinfo.attack) { return false; } if (level.time < self->monsterinfo.attack_finished) { return false; } if (enemy_range == RANGE_FAR) { return false; } if (self->monsterinfo.aiflags & AI_STAND_GROUND) { chance = 0.4; } else if (enemy_range == RANGE_NEAR) { chance = 0.4; } else if (enemy_range == RANGE_MID) { chance = 0.2; } else { return false; } if (random() < chance) { self->monsterinfo.attack_state = AS_MISSILE; self->monsterinfo.attack_finished = level.time + 2 * random(); return true; } if (self->flags & FL_FLY) { if (random() < 0.3) { self->monsterinfo.attack_state = AS_SLIDING; } else { self->monsterinfo.attack_state = AS_STRAIGHT; } } return false; } void MakronPrecache(void); /* * QUAKED monster_jorg (1 .5 0) (-80 -80 0) (90 90 140) Ambush Trigger_Spawn Sight */ void SP_monster_jorg(edict_t *self) { if (!self) { return; } if (deathmatch->value) { G_FreeEdict(self); return; } sound_pain1 = gi.soundindex("boss3/bs3pain1.wav"); sound_pain2 = gi.soundindex("boss3/bs3pain2.wav"); sound_pain3 = gi.soundindex("boss3/bs3pain3.wav"); sound_death = gi.soundindex("boss3/bs3deth1.wav"); sound_attack1 = gi.soundindex("boss3/bs3atck1.wav"); sound_attack2 = gi.soundindex("boss3/bs3atck2.wav"); sound_search1 = gi.soundindex("boss3/bs3srch1.wav"); sound_search2 = gi.soundindex("boss3/bs3srch2.wav"); sound_search3 = gi.soundindex("boss3/bs3srch3.wav"); sound_idle = gi.soundindex("boss3/bs3idle1.wav"); sound_step_left = gi.soundindex("boss3/step1.wav"); sound_step_right = gi.soundindex("boss3/step2.wav"); sound_firegun = gi.soundindex("boss3/xfire.wav"); sound_death_hit = gi.soundindex("boss3/d_hit.wav"); MakronPrecache(); self->movetype = MOVETYPE_STEP; self->solid = SOLID_BBOX; self->s.modelindex = gi.modelindex("models/monsters/boss3/jorg/tris.md2"); self->s.modelindex2 = gi.modelindex("models/monsters/boss3/rider/tris.md2"); VectorSet(self->mins, -80, -80, 0); VectorSet(self->maxs, 80, 80, 140); self->health = 3000; self->gib_health = -2000; self->mass = 1000; self->pain = jorg_pain; self->die = jorg_die; self->monsterinfo.stand = jorg_stand; self->monsterinfo.walk = jorg_walk; self->monsterinfo.run = jorg_run; self->monsterinfo.dodge = NULL; self->monsterinfo.attack = jorg_attack; self->monsterinfo.search = jorg_search; self->monsterinfo.melee = NULL; self->monsterinfo.sight = NULL; self->monsterinfo.checkattack = Jorg_CheckAttack; gi.linkentity(self); self->monsterinfo.currentmove = &jorg_move_stand; self->monsterinfo.scale = MODEL_SCALE; walkmonster_start(self); }
utf-8
1
GPL-2+
1997-2005, Id Software, Inc 2005, Ryan C. Gordon 2005, Stuart Dalton (badcdev@gmail.com) 2010-2013, Yamagi Burmeister 2010, skuller.net 2011, Knightmare 2013, Alejandro Ricoveri 2015-2017, Daniel Gibson
qtcreator-6.0.2/src/plugins/modeleditor/editordiagramview.h
/**************************************************************************** ** ** Copyright (C) 2016 Jochen Becher ** Contact: https://www.qt.io/licensing/ ** ** This file is part of Qt Creator. ** ** Commercial License Usage ** Licensees holding valid commercial Qt licenses may use this file in ** accordance with the commercial license agreement provided with the ** Software or, alternatively, in accordance with the terms contained in ** a written agreement between you and The Qt Company. For licensing terms ** and conditions see https://www.qt.io/terms-conditions. For further ** information use the contact form at https://www.qt.io/contact-us. ** ** GNU General Public License Usage ** Alternatively, this file may be used under the terms of the GNU ** General Public License version 3 as published by the Free Software ** Foundation with exceptions as appearing in the file LICENSE.GPL3-EXCEPT ** included in the packaging of this file. Please review the following ** information to ensure the GNU General Public License requirements will ** be met: https://www.gnu.org/licenses/gpl-3.0.html. ** ****************************************************************************/ #pragma once #include "qmt/diagram_widgets_ui/diagramview.h" #include <utils/dropsupport.h> namespace ModelEditor { namespace Internal { class PxNodeController; class EditorDiagramView : public qmt::DiagramView { Q_OBJECT class EditorDiagramViewPrivate; public: explicit EditorDiagramView(QWidget *parent = nullptr); ~EditorDiagramView() override; signals: void zoomIn(const QPoint &zoomOrigin); void zoomOut(const QPoint &zoomOrigin); public: void setPxNodeController(PxNodeController *pxNodeController); protected: void wheelEvent(QWheelEvent *wheelEvent) override; private: void dropProjectExplorerNodes(const QList<QVariant> &values, const QPoint &pos); void dropFiles(const QList<Utils::DropSupport::FileSpec> &files, const QPoint &pos); EditorDiagramViewPrivate *d; }; } // namespace Internal } // namespace ModelEditor
utf-8
1
GPL-3 with Qt-1.0 exception
2008-2020 The Qt Company
chromium-98.0.4758.102/third_party/tflite/src/tensorflow/compiler/mlir/tensorflow/ir/tf_structs.cc
/* Copyright 2020 The TensorFlow Authors. All Rights Reserved. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. ==============================================================================*/ #include "tensorflow/compiler/mlir/tensorflow/ir/tf_structs.h" #include "tensorflow/compiler/mlir/tensorflow/ir/tf_structs.cc.inc" namespace mlir { namespace TF { void RuntimeDevices::AddDevice(const ParsedName& device) { device_names_.push_back(device); } void RuntimeDevices::AddGpuDevice(const ParsedName& device, const GpuDeviceMetadata& metadata) { device_names_.push_back(device); gpu_metadata_.insert({DeviceNameUtils::ParsedNameToString(device), metadata}); } llvm::Optional<GpuDeviceMetadata> RuntimeDevices::GetGpuDeviceMetadata( const ParsedName& device) const { auto it = gpu_metadata_.find(DeviceNameUtils::ParsedNameToString(device)); if (it != gpu_metadata_.end()) { return it->second; } else { return llvm::None; } } } // namespace TF } // namespace mlir
utf-8
1
BSD-3-clause
The Chromium Authors. All rights reserved.
saga-7.3.0+dfsg/src/tools/grid/grid_filter/Filter_Sieve.h
/********************************************************** * Version $Id: Filter_Sieve.h 1921 2014-01-09 10:24:11Z oconrad $ *********************************************************/ /////////////////////////////////////////////////////////// // // // SAGA // // // // System for Automated Geoscientific Analyses // // // // Tool Library // // Grid_Filter // // // //-------------------------------------------------------// // // // Filter_Sieve.h // // // // Copyright (C) 2014 by // // Olaf Conrad // // // //-------------------------------------------------------// // // // This file is part of 'SAGA - System for Automated // // Geoscientific Analyses'. SAGA is free software; you // // can redistribute it and/or modify it under the terms // // of the GNU General Public License as published by the // // Free Software Foundation, either version 2 of the // // License, or (at your option) any later version. // // // // SAGA 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/>. // // // //-------------------------------------------------------// // // // e-mail: oconrad@saga-gis.org // // // // contact: Olaf Conrad // // Institute of Geography // // University of Hamburg // // Germany // // // /////////////////////////////////////////////////////////// //--------------------------------------------------------- /////////////////////////////////////////////////////////// // // // // // // /////////////////////////////////////////////////////////// //--------------------------------------------------------- #ifndef HEADER_INCLUDED__Filter_Sieve_H #define HEADER_INCLUDED__Filter_Sieve_H /////////////////////////////////////////////////////////// // // // // // // /////////////////////////////////////////////////////////// //--------------------------------------------------------- #include "MLB_Interface.h" /////////////////////////////////////////////////////////// // // // // // // /////////////////////////////////////////////////////////// //--------------------------------------------------------- class CFilter_Sieve : public CSG_Tool_Grid { public: CFilter_Sieve(void); protected: virtual int On_Parameters_Enable (CSG_Parameters *pParameters, CSG_Parameter *pParameter); virtual bool On_Execute (void); private: int m_Mode, m_Threshold; double m_Class; CSG_Grid *m_pGrid; int Get_Size (int x, int y, int n = 0); void Do_Sieve (int x, int y, bool bSieve); }; /////////////////////////////////////////////////////////// // // // // // // /////////////////////////////////////////////////////////// //--------------------------------------------------------- #endif // #ifndef HEADER_INCLUDED__Filter_Sieve_H
utf-8
1
GPL-2+
SAGA Development Team
qtwebengine-opensource-src-5.15.8+dfsg/src/3rdparty/chromium/third_party/angle/src/compiler/translator/ImmutableString_autogen.cpp
// GENERATED FILE - DO NOT EDIT. // Generated by gen_builtin_symbols.py using data from builtin_variables.json and // builtin_function_declarations.txt. // // Copyright 2020 The ANGLE Project Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. // // ImmutableString_autogen.cpp: Wrapper for static or pool allocated char arrays, that are // guaranteed to be valid and unchanged for the duration of the compilation. Implements // mangledNameHash using perfect hash function from gen_builtin_symbols.py #include "compiler/translator/ImmutableString.h" std::ostream &operator<<(std::ostream &os, const sh::ImmutableString &str) { return os.write(str.data(), str.length()); } #if defined(_MSC_VER) # pragma warning(disable : 4309) // truncation of constant value #endif namespace { constexpr int mangledkT1[] = {3064, 1851, 1414, 3139, 4344, 3861, 2198, 569, 2942, 936, 1011, 2797, 994, 3172, 2246, 1929, 3580, 2059, 3211, 2760, 3315, 3834, 4289, 1359, 1965, 849, 1949, 3923, 2685, 4274, 4060, 2274, 1752, 1405, 743, 2453, 2110}; constexpr int mangledkT2[] = {3974, 952, 3020, 19, 962, 3302, 1369, 968, 2483, 3954, 2409, 949, 1306, 577, 1474, 224, 2913, 2365, 494, 208, 654, 3238, 2268, 54, 1039, 35, 3881, 44, 150, 967, 1157, 2004, 4019, 4114, 1201, 3022, 2477}; constexpr int mangledkG[] = { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 237, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 4415, 0, 0, 1692, 0, 0, 0, 0, 0, 0, 4425, 0, 0, 0, 0, 0, 0, 0, 4034, 1669, 0, 0, 0, 0, 2799, 0, 0, 0, 0, 2968, 0, 294, 0, 3468, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 908, 0, 0, 0, 0, 0, 0, 2400, 0, 2142, 0, 0, 0, 0, 0, 0, 0, 0, 0, 294, 0, 0, 0, 0, 0, 857, 0, 0, 0, 0, 0, 0, 1663, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1876, 0, 0, 0, 0, 225, 0, 0, 0, 0, 0, 640, 810, 0, 3416, 0, 0, 3688, 0, 0, 3802, 4332, 0, 0, 2261, 0, 0, 0, 1719, 0, 0, 0, 0, 0, 1386, 0, 1507, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 356, 0, 0, 0, 0, 0, 0, 432, 0, 0, 0, 1198, 0, 0, 0, 0, 0, 2445, 0, 0, 222, 0, 0, 3859, 0, 0, 0, 0, 0, 0, 0, 0, 0, 3598, 918, 0, 0, 0, 0, 0, 0, 1694, 0, 0, 0, 0, 0, 1161, 0, 0, 0, 0, 0, 381, 0, 222, 0, 3810, 0, 1466, 3945, 0, 3178, 0, 0, 331, 60, 0, 0, 0, 605, 679, 0, 3566, 0, 0, 0, 438, 0, 3807, 0, 0, 0, 1331, 0, 0, 0, 945, 0, 0, 0, 3384, 2673, 0, 0, 0, 4287, 4141, 455, 0, 4098, 0, 0, 0, 0, 0, 0, 685, 1248, 4248, 0, 0, 0, 0, 0, 0, 0, 0, 1704, 0, 0, 0, 0, 204, 0, 0, 3604, 1783, 889, 0, 0, 0, 533, 841, 0, 0, 0, 722, 2641, 0, 0, 0, 3828, 1320, 700, 4165, 0, 2297, 1239, 0, 2147, 0, 0, 0, 0, 0, 75, 0, 0, 0, 2019, 0, 0, 0, 0, 0, 1980, 0, 0, 0, 0, 75, 0, 0, 0, 578, 1657, 0, 0, 0, 0, 2823, 240, 0, 0, 29, 0, 0, 1252, 0, 2306, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1198, 3986, 0, 0, 0, 0, 0, 1984, 0, 0, 0, 1929, 3657, 0, 0, 0, 0, 1516, 0, 0, 593, 0, 0, 0, 0, 0, 0, 0, 0, 478, 0, 883, 0, 0, 0, 0, 0, 1844, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1100, 0, 0, 0, 0, 3867, 559, 0, 0, 0, 0, 4302, 0, 0, 0, 0, 780, 0, 0, 1982, 0, 0, 0, 4234, 0, 0, 0, 0, 0, 0, 0, 2296, 0, 0, 0, 659, 0, 0, 3233, 0, 0, 0, 0, 0, 0, 0, 322, 393, 4384, 1087, 520, 0, 1156, 1940, 0, 0, 0, 662, 866, 3748, 0, 958, 1862, 0, 409, 0, 0, 0, 1528, 0, 0, 0, 0, 0, 0, 0, 3561, 0, 210, 0, 604, 3750, 869, 0, 859, 786, 0, 0, 3852, 0, 0, 0, 0, 667, 4364, 860, 1783, 0, 0, 0, 0, 0, 209, 0, 3492, 4421, 0, 0, 0, 0, 1394, 0, 0, 0, 1002, 0, 0, 0, 0, 0, 0, 1081, 0, 0, 0, 0, 0, 0, 3533, 0, 0, 0, 0, 507, 2504, 0, 0, 0, 0, 0, 0, 0, 1709, 806, 1351, 209, 0, 813, 0, 0, 0, 0, 0, 0, 0, 0, 0, 655, 0, 0, 0, 0, 0, 0, 4319, 0, 0, 111, 656, 0, 255, 0, 0, 315, 4070, 3520, 0, 0, 0, 0, 0, 0, 0, 0, 3079, 967, 1823, 1486, 0, 434, 0, 0, 3856, 0, 0, 4252, 2293, 0, 0, 0, 0, 0, 0, 1117, 0, 0, 1022, 0, 2050, 4188, 0, 3664, 0, 0, 0, 801, 0, 0, 0, 0, 0, 0, 0, 2511, 0, 0, 0, 0, 69, 360, 0, 873, 0, 0, 0, 0, 4049, 4196, 0, 0, 0, 2160, 506, 0, 1160, 0, 0, 0, 0, 0, 1966, 57, 0, 0, 4399, 0, 3118, 0, 0, 3220, 0, 36, 0, 1406, 0, 0, 0, 692, 0, 0, 1501, 0, 0, 4442, 0, 1161, 0, 660, 0, 0, 0, 0, 0, 1589, 0, 0, 0, 0, 0, 0, 847, 0, 0, 0, 536, 0, 1851, 0, 0, 0, 0, 3951, 4010, 0, 0, 1443, 0, 0, 0, 235, 0, 0, 1930, 2635, 0, 1948, 2125, 0, 631, 0, 0, 1625, 0, 0, 4132, 0, 0, 2700, 1001, 0, 0, 947, 2543, 1489, 0, 4346, 0, 0, 150, 0, 0, 2828, 0, 0, 0, 0, 0, 0, 278, 4192, 756, 0, 3986, 0, 0, 380, 0, 1812, 0, 3423, 0, 0, 0, 182, 0, 0, 0, 814, 0, 304, 4449, 0, 646, 0, 0, 95, 0, 0, 1125, 0, 0, 0, 0, 0, 3814, 0, 0, 2261, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 3776, 0, 0, 2770, 0, 0, 0, 782, 3419, 0, 4001, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 986, 0, 1770, 758, 0, 0, 0, 0, 1084, 0, 343, 0, 0, 0, 0, 0, 0, 1935, 0, 0, 1532, 535, 0, 0, 0, 0, 0, 0, 1205, 3609, 0, 0, 0, 0, 0, 1031, 0, 0, 2709, 0, 4085, 0, 3679, 0, 0, 0, 514, 0, 4211, 0, 0, 357, 0, 0, 0, 0, 1866, 0, 2116, 0, 0, 0, 0, 2538, 0, 4146, 0, 0, 0, 0, 0, 1774, 1203, 4192, 0, 37, 0, 0, 4239, 1431, 0, 0, 0, 2085, 3360, 313, 1258, 3044, 1013, 0, 0, 0, 2550, 0, 937, 0, 0, 0, 0, 4097, 0, 0, 0, 2627, 1961, 0, 0, 0, 3686, 3390, 0, 0, 324, 0, 0, 0, 0, 1933, 0, 670, 0, 338, 0, 0, 0, 0, 1111, 0, 0, 0, 0, 1483, 0, 320, 0, 1248, 0, 924, 0, 0, 0, 0, 1072, 0, 0, 0, 0, 4238, 3207, 0, 396, 0, 0, 0, 84, 0, 1418, 127, 0, 1372, 0, 0, 0, 0, 0, 711, 0, 2598, 2053, 4314, 0, 2707, 568, 0, 0, 1248, 0, 0, 1186, 0, 0, 3899, 1893, 0, 0, 0, 1498, 591, 2018, 551, 2649, 911, 0, 2537, 0, 0, 0, 3434, 0, 0, 0, 0, 2339, 0, 0, 461, 0, 0, 0, 0, 0, 4013, 0, 3289, 647, 0, 0, 0, 466, 230, 0, 1544, 0, 1576, 0, 0, 0, 3249, 0, 0, 699, 0, 0, 4205, 0, 0, 0, 0, 0, 653, 0, 2703, 0, 0, 0, 2215, 0, 2015, 0, 0, 0, 0, 0, 0, 0, 0, 1307, 663, 0, 178, 0, 0, 0, 0, 2717, 927, 358, 0, 4142, 1093, 3580, 0, 467, 0, 0, 0, 0, 933, 590, 85, 3482, 1580, 3629, 0, 0, 0, 0, 0, 0, 3354, 0, 0, 165, 0, 0, 1642, 1429, 0, 0, 4427, 0, 0, 0, 0, 328, 0, 0, 0, 0, 0, 857, 0, 0, 751, 0, 0, 4389, 446, 0, 0, 1645, 0, 0, 0, 0, 0, 0, 0, 3076, 0, 0, 1571, 472, 1588, 0, 0, 0, 17, 0, 653, 816, 3016, 400, 0, 0, 0, 0, 0, 0, 4005, 0, 0, 1981, 2016, 0, 934, 0, 0, 0, 0, 0, 0, 4100, 644, 1623, 0, 0, 91, 2506, 0, 1312, 0, 2364, 0, 0, 327, 0, 0, 0, 264, 0, 3166, 3276, 4163, 1593, 0, 0, 733, 0, 0, 0, 4089, 0, 3221, 1135, 0, 0, 0, 0, 867, 2968, 1781, 0, 0, 4039, 2959, 0, 3500, 0, 3383, 1150, 2820, 268, 802, 132, 0, 0, 0, 3176, 0, 1651, 3802, 0, 0, 0, 0, 0, 2732, 0, 0, 0, 150, 0, 0, 1117, 3687, 0, 696, 2045, 0, 814, 0, 0, 0, 0, 3981, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 278, 2734, 0, 686, 853, 349, 0, 575, 2143, 0, 0, 0, 3275, 0, 3086, 0, 0, 0, 0, 563, 1960, 0, 0, 0, 4128, 311, 2688, 4370, 348, 1881, 1648, 1442, 0, 4229, 1609, 0, 0, 387, 2765, 0, 956, 0, 0, 3301, 2280, 812, 0, 0, 66, 0, 0, 0, 0, 0, 0, 3084, 203, 0, 708, 0, 235, 176, 0, 0, 0, 0, 2513, 1450, 0, 3215, 0, 0, 0, 1514, 1008, 1860, 0, 3610, 906, 0, 0, 0, 158, 0, 153, 719, 0, 1185, 396, 256, 0, 0, 517, 4240, 2401, 2210, 0, 4057, 0, 0, 1262, 0, 0, 0, 701, 604, 0, 0, 136, 0, 0, 2102, 3714, 0, 826, 2267, 344, 0, 0, 4015, 0, 3959, 1358, 0, 354, 0, 0, 598, 0, 0, 0, 0, 294, 3552, 0, 1276, 0, 0, 0, 0, 140, 0, 0, 4114, 0, 0, 0, 1945, 0, 3229, 0, 973, 102, 1382, 0, 0, 1012, 3534, 4384, 1312, 124, 2647, 0, 2014, 0, 1867, 0, 0, 3712, 99, 515, 0, 0, 166, 858, 0, 0, 0, 0, 3900, 3591, 0, 0, 0, 0, 0, 0, 0, 1972, 0, 1653, 4379, 1975, 0, 948, 0, 0, 1553, 0, 0, 0, 0, 144, 1095, 1404, 315, 0, 0, 0, 0, 1666, 0, 1042, 0, 2900, 1356, 0, 0, 0, 0, 0, 860, 0, 0, 0, 957, 1889, 0, 0, 0, 0, 3925, 0, 0, 2819, 0, 2639, 0, 0, 2583, 0, 0, 805, 1852, 0, 0, 0, 4051, 0, 3569, 0, 0, 0, 0, 0, 0, 0, 0, 885, 0, 1526, 0, 847, 0, 532, 0, 1212, 3983, 1204, 1023, 664, 1264, 2772, 0, 0, 72, 0, 1553, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 2702, 2088, 811, 339, 0, 2050, 3888, 115, 72, 0, 0, 0, 1749, 1278, 232, 1112, 0, 0, 0, 0, 1421, 369, 589, 0, 0, 0, 0, 0, 3945, 0, 192, 0, 1500, 2057, 0, 3093, 0, 0, 253, 686, 0, 0, 0, 1847, 0, 0, 0, 0, 1529, 0, 222, 0, 0, 1290, 1153, 0, 0, 0, 1423, 0, 0, 91, 1760, 0, 3482, 174, 3016, 0, 0, 0, 2091, 0, 1082, 0, 1332, 2071, 573, 1651, 1903, 0, 0, 358, 3933, 999, 0, 0, 0, 0, 134, 4134, 0, 0, 0, 288, 0, 0, 0, 464, 0, 890, 408, 2369, 978, 0, 2495, 3640, 0, 0, 0, 0, 1013, 1171, 1937, 2472, 0, 0, 0, 84, 518, 0, 1452, 1596, 0, 1521, 0, 3416, 0, 1555, 0, 1997, 4117, 1537, 3658, 0, 0, 444, 451, 2039, 835, 3930, 0, 4098, 1127, 0, 500, 0, 0, 0, 249, 0, 0, 4088, 2388, 629, 0, 801, 0, 0, 1568, 771, 0, 948, 0, 140, 0, 0, 1806, 1568, 0, 0, 2031, 1755, 0, 0, 2075, 0, 2829, 0, 0, 0, 0, 854, 1779, 0, 1021, 2947, 0, 22, 0, 668, 1835, 105, 0, 0, 110, 1656, 1229, 0, 0, 0, 0, 3191, 406, 0, 752, 971, 0, 2872, 73, 0, 4399, 2629, 0, 1194, 399, 0, 949, 0, 429, 0, 4344, 2988, 0, 1480, 3077, 0, 3808, 0, 0, 0, 455, 0, 1267, 0, 0, 0, 1642, 1885, 0, 391, 1478, 1476, 0, 0, 906, 433, 0, 556, 0, 0, 3782, 0, 2578, 2017, 4024, 0, 0, 0, 570, 2699, 1749, 0, 0, 0, 2651, 1491, 0, 0, 0, 0, 905, 0, 0, 488, 1274, 0, 310, 437, 4202, 3962, 0, 255, 2234, 2841, 0, 0, 0, 1666, 263, 1319, 0, 2742, 4376, 0, 0, 1651, 0, 109, 0, 0, 0, 0, 777, 0, 0, 2423, 4124, 0, 1814, 0, 1951, 0, 0, 0, 923, 4000, 0, 1108, 201, 0, 1719, 1045, 230, 0, 1359, 102, 0, 0, 0, 105, 0, 872, 675, 0, 1685, 0, 0, 44, 0, 798, 554, 0, 239, 0, 0, 0, 0, 881, 2691, 0, 4223, 0, 845, 0, 0, 2051, 0, 0, 0, 0, 4292, 0, 1618, 125, 4436, 1169, 491, 0, 0, 3102, 0, 0, 1043, 1499, 1290, 0, 0, 0, 278, 0, 0, 1599, 0, 0, 0, 0, 0, 0, 0, 2903, 0, 0, 0, 0, 683, 471, 0, 742, 2315, 0, 0, 1851, 1386, 1159, 1494, 1859, 0, 3499, 4049, 581, 0, 0, 227, 1737, 0, 0, 0, 354, 0, 3818, 0, 4093, 0, 0, 1895, 0, 1866, 1629, 0, 696, 0, 0, 1811, 0, 0, 0, 0, 0, 0, 0, 3866, 753, 0, 0, 1902, 0, 0, 404, 830, 0, 1268, 0, 0, 0, 0, 2689, 0, 0, 0, 0, 0, 0, 1274, 0, 0, 1799, 968, 0, 0, 0, 471, 465, 110, 0, 0, 4410, 0, 2883, 3928, 724, 0, 0, 0, 1270, 2067, 2790, 1810, 0, 0, 0, 0, 97, 0, 867, 1424, 1558, 1665, 1393, 0, 939, 692, 0, 0, 290, 803, 0, 0, 1839, 0, 3826, 0, 1040, 0, 0, 0, 0, 0, 0, 0, 0, 3660, 1943, 0, 0, 958, 1505, 4211, 238, 0, 0, 0, 119, 0, 0, 0, 407, 0, 0, 0, 0, 3009, 1972, 1308, 0, 775, 0, 3397, 0, 532, 0, 0, 0, 0, 0, 0, 0, 0, 0, 786, 0, 0, 2087, 0, 0, 0, 1648, 0, 0, 841, 3232, 1828, 0, 334, 3195, 0, 13, 0, 779, 0, 1004, 1147, 0, 513, 3955, 0, 0, 154, 567, 0, 0, 0, 1905, 0, 0, 949, 1022, 0, 2350, 1139, 0, 870, 218, 291, 0, 1859, 3041, 708, 1500, 4198, 2385, 0, 0, 2040, 0, 276, 708, 3508, 0, 0, 3581, 0, 0, 183, 219, 1024, 0, 4272, 3737, 0, 2220, 0, 1223, 1984, 4319, 374, 0, 0, 0, 0, 0, 944, 2350, 496, 0, 1757, 0, 0, 0, 425, 2723, 0, 0, 0, 771, 0, 0, 1184, 960, 3976, 0, 0, 0, 0, 0, 0, 935, 0, 1339, 2161, 1198, 0, 0, 0, 0, 109, 850, 0, 0, 0, 0, 541, 2149, 415, 0, 3874, 208, 0, 1655, 495, 1902, 0, 0, 2135, 0, 0, 0, 640, 3196, 0, 0, 0, 3486, 0, 234, 0, 0, 0, 1377, 0, 0, 723, 107, 954, 0, 0, 3310, 0, 3588, 419, 0, 4015, 1633, 2624, 0, 1128, 0, 1348, 2147, 0, 0, 3078, 2173, 1650, 0, 0, 505, 0, 0, 2215, 0, 3567, 1278, 3671, 526, 1355, 0, 1077, 507, 345, 0, 695, 0, 160, 0, 1867, 1923, 0, 528, 0, 0, 555, 0, 0, 0, 0, 2207, 0, 0, 1838, 0, 0, 0, 0, 0, 1923, 1492, 0, 1738, 1336, 0, 903, 0, 691, 1268, 0, 1946, 0, 393, 0, 0, 13, 0, 0, 866, 2299, 1334, 0, 0, 0, 727, 2446, 3227, 3237, 667, 0, 0, 0, 1279, 2776, 0, 0, 0, 434, 4302, 2397, 4103, 671, 1657, 0, 0, 4023, 0, 0, 0, 0, 3357, 0, 0, 1009, 0, 0, 0, 0, 1660, 3425, 0, 0, 0, 616, 372, 0, 1705, 4365, 998, 276, 0, 0, 963, 0, 0, 794, 4047, 1750, 1406, 0, 54, 1751, 0, 0, 0, 0, 0, 0, 0, 0, 739, 0, 649, 0, 0, 0, 3990, 0, 3272, 0, 0, 0, 0, 0, 0, 0, 3295, 0, 1428, 0, 0, 812, 0, 351, 0, 3835, 0, 1564, 0, 0, 1058, 2305, 3303, 1938, 0, 923, 378, 3177, 0, 0, 1468, 0, 286, 0, 3064, 1370, 0, 675, 1708, 0, 0, 1203, 0, 0, 0, 0, 376, 0, 346, 983, 2009, 0, 3790, 27, 247, 821, 0, 836, 1905, 575, 561, 1806, 0, 107, 0, 932, 0, 0, 1154, 87, 0, 2077, 0, 0, 838, 731, 289, 0, 0, 0, 2114, 3726, 1066, 2248, 1546, 1000, 0, 0, 550, 3065, 1987, 0, 0, 0, 0, 202, 0, 1788, 0, 981, 0, 3628, 881, 3968, 1358, 639, 4323, 0, 0, 0, 613, 751, 0, 0, 3915, 326, 4034, 452, 1688, 4105, 4054, 0, 0, 795, 755, 3427, 0, 4057, 0, 0, 0, 512, 3446, 0, 0, 0, 2624, 0, 3564, 1334, 0, 1244, 2280, 301, 0, 0, 946, 0, 0, 0, 3406, 0, 0, 0, 4298, 0, 0, 1612, 311, 1739, 0, 492, 3070, 0, 221, 3974, 1171, 898, 0, 1212, 0, 0, 1075, 2752, 582, 0, 4030, 297, 0, 0, 3208, 0, 2012, 0, 408, 459, 101, 0, 0, 0, 0, 318, 463, 4380, 0, 243, 0, 1065, 3614, 3654, 2871, 3545, 0, 0, 585, 903, 274, 0, 1457, 0, 0, 4057, 692, 15, 0, 1008, 4196, 0, 0, 0, 524, 0, 0, 0, 0, 845, 203, 1783, 2118, 0, 672, 2269, 0, 0, 1907, 0, 0, 4417, 0, 3798, 455, 0, 195, 0, 929, 4167, 480, 744, 4217, 0, 0, 3705, 2915, 2273, 1062, 677, 0, 4420, 2325, 0, 0, 0, 1178, 1725, 0, 0, 3730, 0, 38, 4270, 1585, 0, 1925, 3912, 0, 0, 0, 0, 0, 0, 4274, 0, 824, 0, 970, 0, 0, 0, 0, 1928, 298, 0, 735, 0, 0, 10, 2811, 850, 0, 2730, 1321, 4050, 3210, 0, 4321, 786, 346, 2109, 0, 0, 1919, 0, 0, 1661, 280, 174, 518, 3704, 3169, 0, 0, 3433, 3344, 3829, 3866, 0, 195, 1421, 0, 0, 2369, 483, 1717, 0, 0, 0, 0, 0, 0, 0, 594, 420, 0, 829, 0, 248, 1449, 4229, 0, 190, 0, 3538, 4358, 3070, 0, 1222, 33, 0, 0, 16, 355, 0, 361, 606, 297, 0, 1158, 1532, 0, 486, 0, 0, 0, 60, 749, 462, 861, 0, 4407, 463, 0, 0, 849, 218, 0, 0, 0, 1061, 1411, 0, 1275, 45, 0, 0, 0, 86, 670, 861, 569, 1206, 0, 0, 0, 0, 1367, 162, 352, 2631, 689, 1288, 0, 383, 0, 0, 0, 0, 1901, 1817, 532, 1743, 438, 0, 3197, 0, 1134, 4398, 0, 0, 0, 1458, 499, 253, 1313, 3691, 515, 0, 1730, 0, 1513, 691, 1126, 257, 0, 534, 0, 302, 0, 0, 0, 0, 0, 1192, 50, 0, 314, 0, 0, 332, 4102, 265, 0, 1207, 0, 2236, 0, 0, 0, 916, 0, 0, 2083, 2924, 543, 2492, 3603, 762, 423, 0, 1293, 3453, 0, 2499, 0, 1700, 0, 0, 812, 1928, 1279, 2631, 436, 1423, 0, 0, 1200, 0, 0, 1338, 67, 1873, 4153, 4268, 4239, 0, 1705, 0, 0, 0, 523, 0, 0, 2026, 986, 291, 176, 1381, 1033, 518, 0, 0, 1611, 4312, 3213, 0, 0, 952, 0, 0, 541, 818, 0, 0, 1348, 0, 0, 525, 0, 1457, 0, 1408, 3698, 823, 0, 1883, 546, 4103, 1013, 700, 1048, 1166, 840, 0, 3918, 1405, 0, 2137, 1292, 0, 0, 0, 697, 1168, 45, 0, 579, 0, 3506, 0, 4195, 2147, 0, 0, 228, 519, 0, 0, 4271, 0, 28, 0, 581, 1070, 1434, 0, 268, 0, 0, 408, 3320, 64, 1411, 730, 1394, 0, 0, 2114, 1306, 0, 0, 236, 0, 0, 3602, 4029, 0, 0, 716, 0, 2457, 0, 3916, 4440, 2554, 3643, 0, 628, 1356, 1373, 1008, 0, 0, 3023, 1346, 230, 0, 0, 1991, 430, 100, 0, 0, 0, 0, 1766, 0, 0, 4436, 0, 236, 3880, 0, 1921, 0, 2200, 0, 4411, 0, 1006, 3899, 0, 0, 282, 0, 1362, 1017, 0, 0, 1191, 4441, 0, 0, 1279, 741, 2104, 1910, 0, 0, 394, 4403, 0, 969, 0, 0, 0, 0, 4028, 0, 4148, 94, 3451, 131, 2735, 1448, 0, 228, 3911, 0, 0, 713, 0, 0, 2154, 314, 382, 3165, 157, 1849, 0, 3496, 3767, 179, 0, 0, 0, 912, 0, 0, 0, 596, 1766, 2680, 4277, 591, 0, 4043, 3673, 3883, 0, 1562, 421, 1388, 4120, 4153, 4200, 0, 3910, 95, 3477, 242, 0, 0, 256, 1298, 459, 0, 0, 0, 0, 0, 4255, 0, 0, 440, 0, 0, 1967, 735, 2878, 0, 163, 0, 2812, 3015, 2070, 0, 0, 0, 0, 294, 1999, 1933, 4131, 1509, 2149, 0, 0, 1969, 792, 2383, 2594, 985, 1628, 0, 48, 0, 0, 0, 0, 9, 0, 1126, 49, 0, 0, 51, 0, 1013, 0, 1350, 0, 2061, 2487, 1716, 1425, 0, 3255, 970, 1752, 0, 4326, 0, 639, 0, 1347, 2053, 3757, 1295, 1818, 1805, 0, 0, 0, 4319, 2090, 0, 0, 2321, 0, 0, 3823, 193, 3422, 0, 2160, 0, 1106, 1630, 25, 0, 0, 0, 0, 1436, 3023, 1003, 0, 2324, 0, 0, 682, 1022, 1760, 0, 1894, 16, 778, 1559, 244, 1004, 0, 492, 2069, 4421, 1315, 3755, 764, 0, 0, 29, 0, 466, 1511, 412, 0, 0, 0, 570, 0, 0, 0, 2074, 1627, 0, 0, 2037, 0, 539, 832, 1953, 0, 0, 639, 650, 900, 462, 1215, 0, 1073, 0, 0, 1006, 0, 0, 0, 0, 3391, 1988, 0, 831, 1710, 0, 0, 3855, 2597, 959, 3987, 0, 4209, 0, 772, 0, 0, 4415, 2725, 0, 0, 2165, 771, 0, 0, 2181, 431, 4129, 1508, 48, 790, 3068, 0, 4308, 1596, 0, 0, 857, 0, 823, 3595, 2052, 3140, 0, 4377, 0, 194, 414, 0, 0, 1050, 963, 1533, 0, 0, 1265, 3491, 0, 0, 0, 828, 1504, 0, 1895, 0, 648, 833, 2963, 37, 3225, 1426, 3700, 1202, 1929, 1301, 2167, 0, 992, 1771, 106, 0, 842, 0, 1151, 0, 0, 0, 1605, 0, 1533, 0, 709, 96, 658, 2045, 2865, 618, 0, 3439, 0, 4312, 2084, 371, 0, 1961, 141, 0, 0, 0, 1552, 0, 0, 0, 3073, 0, 1381, 1098, 1423, 0, 2743, 0, 45, 3082, 62, 3153, 0, 3754, 3949, 2255, 808, 0, 0, 1791, 0, 2956, 1335, 152, 0, 1695, 2180, 335, 0, 502, 895, 3490, 0, 924, 441, 465, 0, 0, 3206, 3577, 407, 2564, 2165, 4008, 734, 1520, 765, 0, 0, 586, 0, 1024, 0, 1345, 1, 0, 139, 1355, 1884, 4337, 916, 1410, 0, 0, 0, 75, 0, 1201, 4196, 1720, 1178, 0, 3223, 1724, 785, 0, 0, 44, 0, 1285, 0, 145, 0, 4040, 0, 0, 0, 909, 0, 0, 277, 1485, 1494, 3994, 0, 0, 363, 952, 582, 2391, 1748, 951, 0, 0, 799, 0, 0, 3674, 7, 884, 2132, 0, 498, 702, 0, 0, 0, 1527, 0, 0, 0, 558, 3174, 0, 2887, 20, 0, 863, 0, 1542, 1194, 0, 0, 0, 1530, 0, 1426, 3370, 1183, 1888, 0, 0, 0, 1880, 0, 0, 0, 0, 1373, 0, 0, 3925, 0, 0, 609, 3556, 886, 512, 0, 1443, 1158, 0, 1601, 0, 496, 0, 0, 0, 0, 3981, 316, 0, 3998, 608, 1375, 4451, 2447, 334, 0, 615, 1540, 3032, 3997, 0, 4214, 1469, 0, 1136, 925, 1311, 0, 1763, 0, 2334, 645, 0, 942, 0, 2473, 0, 1213, 1635, 0, 0, 82, 4374, 1992, 207, 292, 1172, 0, 2020, 0, 1194, 0, 540, 0, 641, 0, 0, 0, 1653, 4302, 4209, 1076, 0, 4000, 0, 700, 3918, 3318, 3817, 750, 2117, 3307, 0, 3891, 1426, 3664, 2485, 0, 14, 0, 0, 0, 2064, 0, 0, 0, 0, 1040, 0, 2024, 856, 0, 1671, 879, 684, 683, 0, 846, 0, 1964, 3882, 0, 2652, 0, 0, 0, 3343, 3567, 1574, 0, 1079, 1180, 1637, 482, 0, 2037, 265, 0, 1412, 0, 2269, 1228, 0, 314, 297, 0, 2, 512, 0, 1097, 1346, 0, 4166, 0, 0, 0, 0, 0, 0, 1372, 368, 1293, 0, 0, 0, 2844, 571, 1965, 4451, 1206, 1894, 1973, 2267, 0, 1272, 0, 1584, 1144, 0, 2292, 1717, 3713, 1000, 0, 0, 1007, 834, 346, 1993, 1329, 4270, 2874, 2333, 0, 0, 950, 0, 0, 0, 0, 3963, 1195, 1830, 1537, 3866, 808, 1958, 0, 0, 4321, 0, 0, 0, 2289, 1032, 1592, 0, 340, 444, 3595, 3437, 424, 1916, 0, 12, 181, 1544, 2175, 0, 1535, 1624, 0, 0, 1211, 0, 0, 4223, 0, 0, 618, 2131, 0, 430, 1002, 666, 2643, 2023, 0, 1845, 632, 1055, 1251, 0, 468, 4018, 0, 0, 0, 0, 4173, 1951, 1641, 1372, 0, 0, 0, 4294, 1219, 113, 0, 418, 652, 98, 1014, 4403, 0, 1294, 0, 1339, 3942, 0, 542, 3493, 75, 919, 404, 329, 0, 1438, 300, 956, 0, 0, 602, 373, 0, 4302, 2585, 23, 1959, 293, 3629, 1485, 1241, 0, 0, 0, 1109, 0, 533, 0, 1842, 772, 0, 879, 1239, 0, 1545, 0, 0, 0, 159, 112, 730, 0, 0, 0, 1284, 126, 2537, 2421, 0, 1076, 656, 862, 3395, 3538, 399, 859, 1477, 0, 3064, 0, 0, 1873, 0, 1187, 39, 3292, 397, 0, 0, 1097, 1548, 0, 0, 0, 3, 4273, 3348, 1906, 518, 1258, 1309, 167, 753, 330, 0, 2196, 777, 3060, 0, 1447, 810, 0, 983, 0, 0, 1386, 1266, 0, 0, 0, 1429, 1565, 1976, 3102, 0, 0, 0, 3726, 0, 2404, 0, 0, 3509, 2114, 0, 1146, 0, 1704, 0, 0, 74, 0, 3847, 0, 0, 0, 0, 822, 3349, 4291, 977, 1393, 1631, 0, 4271, 1276, 0, 0, 0, 2093, 774, 0, 3926, 900, 0, 3714, 0, 0, 1582, 0, 1741, 4024, 748, 2962, 1208, 0, 0, 1440, 941, 2827, 0, 797, 2566, 4276, 252, 2841, 3771, 0, 1222, 0, 0, 1900, 0, 3581, 1281, 1111, 0, 1261, 122, 116, 380, 537, 1615, 2427, 1559, 1101, 2474, 1722, 0, 902, 0, 3891, 468, 3629, 338, 0, 887, 4365, 676, 1438, 838, 119, 0, 940, 0, 1869, 353, 1742, 0, 1479, 0, 3561, 0, 1483, 3730, 0, 3009, 0, 0, 0, 1887, 161, 635, 0, 3015, 0, 4170, 0, 0, 946, 0, 118, 1617, 0, 0, 2563, 170, 458, 0, 1046, 1107, 1879, 504, 0, 2102, 0, 1144, 2340, 364, 0, 0, 0, 39, 0, 2062, 282, 0, 744, 4329, 0, 98, 1996, 0, 2710, 1761, 0, 1424, 3704, 0, 0, 0, 0, 1356, 4382, 3326, 0, 0, 3027, 499, 2275, 0, 3230, 0, 922, 0, 0, 4362, 4025, 869, 0, 0, 0, 1528, 0, 222, 915, 0, 0, 4270, 1210, 0, 1802, 0, 0, 2894, 1825, 873, 1052, 1322, 1833, 360, 0, 1586, 1732, 0, 1071, 0, 0, 0, 942, 1379, 0, 3870, 4429, 3155, 1312, 2013, 0, 4231, 1316, 335, 637, 2071, 19, 4384, 0, 832, 0, 3, 0, 0, 0, 1650, 4307, 0, 1869, 0, 0, 4114, 1016, 317, 0, 0, 1842, 0, 1377, 577, 0, 0, 4442, 80, 3850, 0, 1643, 4385, 3916, 1747, 0, 1664, 0, 1216, 367, 0, 0, 937, 0, 207, 2033, 0, 413, 655, 632, 433, 0, 0, 933, 0, 36, 4005, 0, 0, 1536, 342, 0, 0, 667, 363, 117, 4353, 0, 0, 0, 249, 104, 1553, 1547, 19, 0, 493, 1351, 1917, 1691, 0, 1347, 0, 380, 757, 0, 0, 0, 0, 0, 1415, 0, 1644, 0, 0, 241, 3884, 2487, 1276, 0, 0, 714, 0, 1468, 0, 145, 1965, 0, 1115, 0, 2624, 0, 878, 2183, 1566, 1770, 850, 699, 0, 0, 2283, 535, 0, 584, 0, 2002, 242, 0, 3766, 1093, 2006, 0, 0, 0, 4207, 3761, 4353, 1045, 310, 3707, 0, 1252, 1283, 0, 0, 3089, 337, 2235, 161, 4231, 0, 422, 5, 694, 1718, 0, 1853, 1475, 191, 1297, 0, 0, 2917, 4064, 0, 0, 1088, 0, 0, 1309, 2035, 4328, 34, 0, 0, 1853, 0, 4389, 1250, 0, 1094, 1677, 1125, 1034, 1048, 773, 2533, 769, 15, 343, 3631, 768, 539, 0, 1909, 672, 0, 460, 1732, 0, 4192, 0, 1434, 1388, 2036, 0, 0, 2293, 0, 0, 919, 0, 1137, 1125, 0, 0, 0, 1454, 0, 1987, 0, 1289, 77}; int MangledHashG(const char *key, const int *T) { int sum = 0; for (int i = 0; key[i] != '\0'; i++) { sum += T[i] * key[i]; sum %= 4455; } return mangledkG[sum]; } int MangledPerfectHash(const char *key) { if (strlen(key) > 37) return 0; return (MangledHashG(key, mangledkT1) + MangledHashG(key, mangledkT2)) % 4455; } constexpr int unmangledkT1[] = {152, 85, 131, 46, 141, 140, 355, 227, 157, 95, 193, 274, 113, 293, 338, 312, 38, 56, 305, 7, 299, 103, 63, 14, 147, 26}; constexpr int unmangledkT2[] = {16, 254, 132, 341, 351, 23, 144, 38, 280, 327, 291, 81, 145, 376, 164, 258, 319, 373, 246, 29, 53, 104, 148, 299, 8, 288}; constexpr int unmangledkG[] = { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 341, 0, 0, 207, 0, 0, 0, 0, 156, 107, 0, 304, 0, 0, 10, 0, 0, 0, 0, 0, 195, 0, 252, 0, 0, 0, 82, 0, 0, 0, 178, 24, 0, 0, 0, 0, 0, 54, 318, 0, 287, 265, 10, 0, 0, 342, 0, 0, 0, 123, 0, 0, 367, 136, 363, 0, 0, 0, 0, 0, 0, 0, 0, 46, 0, 0, 214, 0, 0, 152, 0, 25, 0, 135, 0, 168, 0, 0, 0, 357, 92, 0, 263, 374, 0, 91, 0, 103, 0, 157, 153, 0, 0, 0, 0, 0, 287, 32, 0, 139, 0, 104, 367, 295, 0, 66, 0, 369, 122, 149, 0, 0, 0, 0, 0, 349, 149, 191, 282, 172, 0, 374, 0, 0, 0, 147, 0, 357, 274, 0, 116, 50, 0, 141, 11, 0, 0, 367, 50, 224, 54, 0, 0, 0, 172, 84, 129, 0, 253, 0, 0, 84, 0, 117, 0, 0, 0, 0, 119, 270, 295, 23, 70, 180, 59, 217, 284, 72, 0, 0, 0, 63, 0, 237, 116, 71, 173, 4, 0, 370, 0, 0, 0, 266, 330, 90, 132, 81, 40, 0, 378, 190, 23, 346, 0, 0, 174, 0, 120, 0, 0, 0, 0, 0, 0, 12, 297, 249, 98, 0, 32, 0, 53, 81, 247, 150, 387, 89, 21, 0, 183, 341, 24, 362, 0, 14, 144, 112, 26, 0, 40, 28, 44, 0, 0, 165, 182, 0, 0, 19, 0, 0, 0, 0, 236, 209, 306, 77, 338, 196, 14, 0, 200, 251, 35, 191, 22, 194, 0, 123, 64, 166, 0, 0, 136, 0, 0, 201, 0, 158, 0, 255, 163, 342, 73, 0, 270, 0, 0, 0, 102, 0, 0, 181, 0, 27, 363, 0, 87, 20, 0, 385, 384, 33, 0, 0, 129, 0, 213, 231, 74, 151, 8, 16, 244, 0, 0, 55, 5, 72, 189, 186, 0, 17, 115, 380, 53, 351, 147, 0, 286, 0, 124, 0, 43, 0, 0, 0, 304, 240, 0, 132, 0, 69, 185, 99, 0, 34, 70, 378, 171, 104, 208, 280, 119, 0, 261, 174, 0, 0, 167, 6, 30, 0, 253, 215, 204, 0, 0, 154, 0, 67, 367, 122, 2, 0, 140, 193, 0, 0, 284, 326, 0, 0, 0, 0, 0, 99}; int UnmangledHashG(const char *key, const int *T) { int sum = 0; for (int i = 0; key[i] != '\0'; i++) { sum += T[i] * key[i]; sum %= 388; } return unmangledkG[sum]; } int UnmangledPerfectHash(const char *key) { if (strlen(key) > 26) return 0; return (UnmangledHashG(key, unmangledkT1) + UnmangledHashG(key, unmangledkT2)) % 388; } } // namespace namespace sh { template <> const size_t ImmutableString::FowlerNollVoHash<4>::kFnvPrime = 16777619u; template <> const size_t ImmutableString::FowlerNollVoHash<4>::kFnvOffsetBasis = 0x811c9dc5u; template <> const size_t ImmutableString::FowlerNollVoHash<8>::kFnvPrime = static_cast<size_t>(1099511628211ull); template <> const size_t ImmutableString::FowlerNollVoHash<8>::kFnvOffsetBasis = static_cast<size_t>(0xcbf29ce484222325ull); uint32_t ImmutableString::mangledNameHash() const { return MangledPerfectHash(data()); } uint32_t ImmutableString::unmangledNameHash() const { return UnmangledPerfectHash(data()); } } // namespace sh
utf-8
1
LGPL-3 or GPL-2
2006-2021 The Chromium Authors 2016-2021 The Qt Company Ltd.
mapserver-7.6.4/renderers/agg/include/agg_color_rgba.h
//---------------------------------------------------------------------------- // Anti-Grain Geometry - Version 2.4 // Copyright (C) 2002-2005 Maxim Shemanarev (http://www.antigrain.com) // // Permission to copy, use, modify, sell and distribute this software // is granted provided this copyright notice appears in all copies. // This software is provided "as is" without express or implied // warranty, and with no claim as to its suitability for any purpose. // //---------------------------------------------------------------------------- // // Adaptation for high precision colors has been sponsored by // Liberty Technology Systems, Inc., visit http://lib-sys.com // // Liberty Technology Systems, Inc. is the provider of // PostScript and PDF technology for software developers. // //---------------------------------------------------------------------------- // Contact: mcseem@antigrain.com // mcseemagg@yahoo.com // http://www.antigrain.com //---------------------------------------------------------------------------- #ifndef AGG_COLOR_RGBA_INCLUDED #define AGG_COLOR_RGBA_INCLUDED #include <math.h> #include "agg_basics.h" namespace mapserver { // Supported byte orders for RGB and RGBA pixel formats //======================================================================= struct order_rgb { enum rgb_e { R=0, G=1, B=2, rgb_tag }; }; //----order_rgb struct order_bgr { enum bgr_e { B=0, G=1, R=2, rgb_tag }; }; //----order_bgr struct order_rgba { enum rgba_e { R=0, G=1, B=2, A=3, rgba_tag }; }; //----order_rgba struct order_argb { enum argb_e { A=0, R=1, G=2, B=3, rgba_tag }; }; //----order_argb struct order_abgr { enum abgr_e { A=0, B=1, G=2, R=3, rgba_tag }; }; //----order_abgr struct order_bgra { enum bgra_e { B=0, G=1, R=2, A=3, rgba_tag }; }; //----order_bgra //====================================================================rgba struct rgba { typedef double value_type; double r; double g; double b; double a; //-------------------------------------------------------------------- rgba() {} //-------------------------------------------------------------------- rgba(double r_, double g_, double b_, double a_=1.0) : r(r_), g(g_), b(b_), a(a_) {} //-------------------------------------------------------------------- rgba(const rgba& c, double a_) : r(c.r), g(c.g), b(c.b), a(a_) {} //-------------------------------------------------------------------- void clear() { r = g = b = a = 0; } //-------------------------------------------------------------------- const rgba& transparent() { a = 0.0; return *this; } //-------------------------------------------------------------------- const rgba& opacity(double a_) { if(a_ < 0.0) a_ = 0.0; if(a_ > 1.0) a_ = 1.0; a = a_; return *this; } //-------------------------------------------------------------------- double opacity() const { return a; } //-------------------------------------------------------------------- const rgba& premultiply() { r *= a; g *= a; b *= a; return *this; } //-------------------------------------------------------------------- const rgba& premultiply(double a_) { if(a <= 0.0 || a_ <= 0.0) { r = g = b = a = 0.0; return *this; } a_ /= a; r *= a_; g *= a_; b *= a_; a = a_; return *this; } //-------------------------------------------------------------------- const rgba& demultiply() { if(a == 0) { r = g = b = 0; return *this; } double a_ = 1.0 / a; r *= a_; g *= a_; b *= a_; return *this; } //-------------------------------------------------------------------- rgba gradient(rgba c, double k) const { rgba ret; ret.r = r + (c.r - r) * k; ret.g = g + (c.g - g) * k; ret.b = b + (c.b - b) * k; ret.a = a + (c.a - a) * k; return ret; } //-------------------------------------------------------------------- static rgba no_color() { return rgba(0,0,0,0); } //-------------------------------------------------------------------- static rgba from_wavelength(double wl, double gamma = 1.0); //-------------------------------------------------------------------- explicit rgba(double wavelen, double gamma=1.0) { *this = from_wavelength(wavelen, gamma); } }; //----------------------------------------------------------------rgba_pre inline rgba rgba_pre(double r, double g, double b, double a=1.0) { return rgba(r, g, b, a).premultiply(); } inline rgba rgba_pre(const rgba& c) { return rgba(c).premultiply(); } inline rgba rgba_pre(const rgba& c, double a) { return rgba(c, a).premultiply(); } //------------------------------------------------------------------------ inline rgba rgba::from_wavelength(double wl, double gamma) { rgba t(0.0, 0.0, 0.0); if(wl >= 380.0 && wl <= 440.0) { t.r = -1.0 * (wl - 440.0) / (440.0 - 380.0); t.b = 1.0; } else if(wl >= 440.0 && wl <= 490.0) { t.g = (wl - 440.0) / (490.0 - 440.0); t.b = 1.0; } else if(wl >= 490.0 && wl <= 510.0) { t.g = 1.0; t.b = -1.0 * (wl - 510.0) / (510.0 - 490.0); } else if(wl >= 510.0 && wl <= 580.0) { t.r = (wl - 510.0) / (580.0 - 510.0); t.g = 1.0; } else if(wl >= 580.0 && wl <= 645.0) { t.r = 1.0; t.g = -1.0 * (wl - 645.0) / (645.0 - 580.0); } else if(wl >= 645.0 && wl <= 780.0) { t.r = 1.0; } double s = 1.0; if(wl > 700.0) s = 0.3 + 0.7 * (780.0 - wl) / (780.0 - 700.0); else if(wl < 420.0) s = 0.3 + 0.7 * (wl - 380.0) / (420.0 - 380.0); t.r = pow(t.r * s, gamma); t.g = pow(t.g * s, gamma); t.b = pow(t.b * s, gamma); return t; } //===================================================================rgba8 struct rgba8 { typedef int8u value_type; typedef int32u calc_type; typedef int32 long_type; enum base_scale_e { base_shift = 8, base_scale = 1 << base_shift, base_mask = base_scale - 1 }; typedef rgba8 self_type; value_type r; value_type g; value_type b; value_type a; //-------------------------------------------------------------------- rgba8() {} //-------------------------------------------------------------------- rgba8(unsigned r_, unsigned g_, unsigned b_, unsigned a_=base_mask) : r(value_type(r_)), g(value_type(g_)), b(value_type(b_)), a(value_type(a_)) {} //-------------------------------------------------------------------- rgba8(const rgba& c, double a_) : r((value_type)uround(c.r * double(base_mask))), g((value_type)uround(c.g * double(base_mask))), b((value_type)uround(c.b * double(base_mask))), a((value_type)uround(a_ * double(base_mask))) {} //-------------------------------------------------------------------- rgba8(const self_type& c, unsigned a_) : r(c.r), g(c.g), b(c.b), a(value_type(a_)) {} //-------------------------------------------------------------------- rgba8(const rgba& c) : r((value_type)uround(c.r * double(base_mask))), g((value_type)uround(c.g * double(base_mask))), b((value_type)uround(c.b * double(base_mask))), a((value_type)uround(c.a * double(base_mask))) {} //-------------------------------------------------------------------- void clear() { r = g = b = a = 0; } //-------------------------------------------------------------------- const self_type& transparent() { a = 0; return *this; } //-------------------------------------------------------------------- const self_type& opacity(double a_) { if(a_ < 0.0) a_ = 0.0; if(a_ > 1.0) a_ = 1.0; a = (value_type)uround(a_ * double(base_mask)); return *this; } //-------------------------------------------------------------------- double opacity() const { return double(a) / double(base_mask); } //-------------------------------------------------------------------- AGG_INLINE const self_type& premultiply() { if(a == base_mask) return *this; if(a == 0) { r = g = b = 0; return *this; } r = value_type((calc_type(r) * a) >> base_shift); g = value_type((calc_type(g) * a) >> base_shift); b = value_type((calc_type(b) * a) >> base_shift); return *this; } //-------------------------------------------------------------------- AGG_INLINE const self_type& premultiply(unsigned a_) { if(a == base_mask && a_ >= base_mask) return *this; if(a == 0 || a_ == 0) { r = g = b = a = 0; return *this; } calc_type r_ = (calc_type(r) * a_) / a; calc_type g_ = (calc_type(g) * a_) / a; calc_type b_ = (calc_type(b) * a_) / a; r = value_type((r_ > a_) ? a_ : r_); g = value_type((g_ > a_) ? a_ : g_); b = value_type((b_ > a_) ? a_ : b_); a = value_type(a_); return *this; } //-------------------------------------------------------------------- AGG_INLINE const self_type& demultiply() { if(a == base_mask) return *this; if(a == 0) { r = g = b = 0; return *this; } calc_type r_ = (calc_type(r) * base_mask) / a; calc_type g_ = (calc_type(g) * base_mask) / a; calc_type b_ = (calc_type(b) * base_mask) / a; r = value_type((r_ > calc_type(base_mask)) ? calc_type(base_mask) : r_); g = value_type((g_ > calc_type(base_mask)) ? calc_type(base_mask) : g_); b = value_type((b_ > calc_type(base_mask)) ? calc_type(base_mask) : b_); return *this; } //-------------------------------------------------------------------- AGG_INLINE self_type gradient(const self_type& c, double k) const { self_type ret; calc_type ik = uround(k * base_scale); ret.r = value_type(calc_type(r) + (((calc_type(c.r) - r) * ik) >> base_shift)); ret.g = value_type(calc_type(g) + (((calc_type(c.g) - g) * ik) >> base_shift)); ret.b = value_type(calc_type(b) + (((calc_type(c.b) - b) * ik) >> base_shift)); ret.a = value_type(calc_type(a) + (((calc_type(c.a) - a) * ik) >> base_shift)); return ret; } //-------------------------------------------------------------------- AGG_INLINE void add(const self_type& c, unsigned cover) { calc_type cr, cg, cb, ca; if(cover == cover_mask) { if(c.a == base_mask) { *this = c; } else { cr = r + c.r; r = (cr > calc_type(base_mask)) ? calc_type(base_mask) : cr; cg = g + c.g; g = (cg > calc_type(base_mask)) ? calc_type(base_mask) : cg; cb = b + c.b; b = (cb > calc_type(base_mask)) ? calc_type(base_mask) : cb; ca = a + c.a; a = (ca > calc_type(base_mask)) ? calc_type(base_mask) : ca; } } else { cr = r + ((c.r * cover + cover_mask/2) >> cover_shift); cg = g + ((c.g * cover + cover_mask/2) >> cover_shift); cb = b + ((c.b * cover + cover_mask/2) >> cover_shift); ca = a + ((c.a * cover + cover_mask/2) >> cover_shift); r = (cr > calc_type(base_mask)) ? calc_type(base_mask) : cr; g = (cg > calc_type(base_mask)) ? calc_type(base_mask) : cg; b = (cb > calc_type(base_mask)) ? calc_type(base_mask) : cb; a = (ca > calc_type(base_mask)) ? calc_type(base_mask) : ca; } } //-------------------------------------------------------------------- template<class GammaLUT> AGG_INLINE void apply_gamma_dir(const GammaLUT& gamma) { r = gamma.dir(r); g = gamma.dir(g); b = gamma.dir(b); } //-------------------------------------------------------------------- template<class GammaLUT> AGG_INLINE void apply_gamma_inv(const GammaLUT& gamma) { r = gamma.inv(r); g = gamma.inv(g); b = gamma.inv(b); } //-------------------------------------------------------------------- static self_type no_color() { return self_type(0,0,0,0); } //-------------------------------------------------------------------- static self_type from_wavelength(double wl, double gamma = 1.0) { return self_type(rgba::from_wavelength(wl, gamma)); } }; //-------------------------------------------------------------rgba8_pre inline rgba8 rgba8_pre(unsigned r, unsigned g, unsigned b, unsigned a = rgba8::base_mask) { return rgba8(r,g,b,a).premultiply(); } inline rgba8 rgba8_pre(const rgba8& c) { return rgba8(c).premultiply(); } inline rgba8 rgba8_pre(const rgba8& c, unsigned a) { return rgba8(c,a).premultiply(); } inline rgba8 rgba8_pre(const rgba& c) { return rgba8(c).premultiply(); } inline rgba8 rgba8_pre(const rgba& c, double a) { return rgba8(c,a).premultiply(); } //-------------------------------------------------------------rgb8_packed inline rgba8 rgb8_packed(unsigned v) { return rgba8((v >> 16) & 0xFF, (v >> 8) & 0xFF, v & 0xFF); } //-------------------------------------------------------------bgr8_packed inline rgba8 bgr8_packed(unsigned v) { return rgba8(v & 0xFF, (v >> 8) & 0xFF, (v >> 16) & 0xFF); } //------------------------------------------------------------argb8_packed inline rgba8 argb8_packed(unsigned v) { return rgba8((v >> 16) & 0xFF, (v >> 8) & 0xFF, v & 0xFF, v >> 24); } //---------------------------------------------------------rgba8_gamma_dir template<class GammaLUT> rgba8 rgba8_gamma_dir(rgba8 c, const GammaLUT& gamma) { return rgba8(gamma.dir(c.r), gamma.dir(c.g), gamma.dir(c.b), c.a); } //---------------------------------------------------------rgba8_gamma_inv template<class GammaLUT> rgba8 rgba8_gamma_inv(rgba8 c, const GammaLUT& gamma) { return rgba8(gamma.inv(c.r), gamma.inv(c.g), gamma.inv(c.b), c.a); } //==================================================================rgba16 struct rgba16 { typedef int16u value_type; typedef int32u calc_type; typedef int64 long_type; enum base_scale_e { base_shift = 16, base_scale = 1 << base_shift, base_mask = base_scale - 1 }; typedef rgba16 self_type; value_type r; value_type g; value_type b; value_type a; //-------------------------------------------------------------------- rgba16() {} //-------------------------------------------------------------------- rgba16(unsigned r_, unsigned g_, unsigned b_, unsigned a_=base_mask) : r(value_type(r_)), g(value_type(g_)), b(value_type(b_)), a(value_type(a_)) {} //-------------------------------------------------------------------- rgba16(const self_type& c, unsigned a_) : r(c.r), g(c.g), b(c.b), a(value_type(a_)) {} //-------------------------------------------------------------------- rgba16(const rgba& c) : r((value_type)uround(c.r * double(base_mask))), g((value_type)uround(c.g * double(base_mask))), b((value_type)uround(c.b * double(base_mask))), a((value_type)uround(c.a * double(base_mask))) {} //-------------------------------------------------------------------- rgba16(const rgba& c, double a_) : r((value_type)uround(c.r * double(base_mask))), g((value_type)uround(c.g * double(base_mask))), b((value_type)uround(c.b * double(base_mask))), a((value_type)uround(a_ * double(base_mask))) {} //-------------------------------------------------------------------- rgba16(const rgba8& c) : r(value_type((value_type(c.r) << 8) | c.r)), g(value_type((value_type(c.g) << 8) | c.g)), b(value_type((value_type(c.b) << 8) | c.b)), a(value_type((value_type(c.a) << 8) | c.a)) {} //-------------------------------------------------------------------- rgba16(const rgba8& c, unsigned a_) : r(value_type((value_type(c.r) << 8) | c.r)), g(value_type((value_type(c.g) << 8) | c.g)), b(value_type((value_type(c.b) << 8) | c.b)), a(value_type(( a_ << 8) | c.a)) {} //-------------------------------------------------------------------- void clear() { r = g = b = a = 0; } //-------------------------------------------------------------------- const self_type& transparent() { a = 0; return *this; } //-------------------------------------------------------------------- AGG_INLINE const self_type& opacity(double a_) { if(a_ < 0.0) a_ = 0.0; if(a_ > 1.0) a_ = 1.0; a = (value_type)uround(a_ * double(base_mask)); return *this; } //-------------------------------------------------------------------- double opacity() const { return double(a) / double(base_mask); } //-------------------------------------------------------------------- AGG_INLINE const self_type& premultiply() { if(a == base_mask) return *this; if(a == 0) { r = g = b = 0; return *this; } r = value_type((calc_type(r) * a) >> base_shift); g = value_type((calc_type(g) * a) >> base_shift); b = value_type((calc_type(b) * a) >> base_shift); return *this; } //-------------------------------------------------------------------- AGG_INLINE const self_type& premultiply(unsigned a_) { if(a == base_mask && a_ >= base_mask) return *this; if(a == 0 || a_ == 0) { r = g = b = a = 0; return *this; } calc_type r_ = (calc_type(r) * a_) / a; calc_type g_ = (calc_type(g) * a_) / a; calc_type b_ = (calc_type(b) * a_) / a; r = value_type((r_ > a_) ? a_ : r_); g = value_type((g_ > a_) ? a_ : g_); b = value_type((b_ > a_) ? a_ : b_); a = value_type(a_); return *this; } //-------------------------------------------------------------------- AGG_INLINE const self_type& demultiply() { if(a == base_mask) return *this; if(a == 0) { r = g = b = 0; return *this; } calc_type r_ = (calc_type(r) * base_mask) / a; calc_type g_ = (calc_type(g) * base_mask) / a; calc_type b_ = (calc_type(b) * base_mask) / a; r = value_type((r_ > calc_type(base_mask)) ? calc_type(base_mask) : r_); g = value_type((g_ > calc_type(base_mask)) ? calc_type(base_mask) : g_); b = value_type((b_ > calc_type(base_mask)) ? calc_type(base_mask) : b_); return *this; } //-------------------------------------------------------------------- AGG_INLINE self_type gradient(const self_type& c, double k) const { self_type ret; calc_type ik = uround(k * base_scale); ret.r = value_type(calc_type(r) + (((calc_type(c.r) - r) * ik) >> base_shift)); ret.g = value_type(calc_type(g) + (((calc_type(c.g) - g) * ik) >> base_shift)); ret.b = value_type(calc_type(b) + (((calc_type(c.b) - b) * ik) >> base_shift)); ret.a = value_type(calc_type(a) + (((calc_type(c.a) - a) * ik) >> base_shift)); return ret; } //-------------------------------------------------------------------- AGG_INLINE void add(const self_type& c, unsigned cover) { calc_type cr, cg, cb, ca; if(cover == cover_mask) { if(c.a == base_mask) { *this = c; } else { cr = r + c.r; r = (cr > calc_type(base_mask)) ? calc_type(base_mask) : cr; cg = g + c.g; g = (cg > calc_type(base_mask)) ? calc_type(base_mask) : cg; cb = b + c.b; b = (cb > calc_type(base_mask)) ? calc_type(base_mask) : cb; ca = a + c.a; a = (ca > calc_type(base_mask)) ? calc_type(base_mask) : ca; } } else { cr = r + ((c.r * cover + cover_mask) >> cover_shift); cg = g + ((c.g * cover + cover_mask) >> cover_shift); cb = b + ((c.b * cover + cover_mask) >> cover_shift); ca = a + ((c.a * cover + cover_mask) >> cover_shift); r = (cr > calc_type(base_mask)) ? calc_type(base_mask) : cr; g = (cg > calc_type(base_mask)) ? calc_type(base_mask) : cg; b = (cb > calc_type(base_mask)) ? calc_type(base_mask) : cb; a = (ca > calc_type(base_mask)) ? calc_type(base_mask) : ca; } } //-------------------------------------------------------------------- template<class GammaLUT> AGG_INLINE void apply_gamma_dir(const GammaLUT& gamma) { r = gamma.dir(r); g = gamma.dir(g); b = gamma.dir(b); } //-------------------------------------------------------------------- template<class GammaLUT> AGG_INLINE void apply_gamma_inv(const GammaLUT& gamma) { r = gamma.inv(r); g = gamma.inv(g); b = gamma.inv(b); } //-------------------------------------------------------------------- static self_type no_color() { return self_type(0,0,0,0); } //-------------------------------------------------------------------- static self_type from_wavelength(double wl, double gamma = 1.0) { return self_type(rgba::from_wavelength(wl, gamma)); } }; //--------------------------------------------------------------rgba16_pre inline rgba16 rgba16_pre(unsigned r, unsigned g, unsigned b, unsigned a = rgba16::base_mask) { return rgba16(r,g,b,a).premultiply(); } inline rgba16 rgba16_pre(const rgba16& c, unsigned a) { return rgba16(c,a).premultiply(); } inline rgba16 rgba16_pre(const rgba& c) { return rgba16(c).premultiply(); } inline rgba16 rgba16_pre(const rgba& c, double a) { return rgba16(c,a).premultiply(); } inline rgba16 rgba16_pre(const rgba8& c) { return rgba16(c).premultiply(); } inline rgba16 rgba16_pre(const rgba8& c, unsigned a) { return rgba16(c,a).premultiply(); } //------------------------------------------------------rgba16_gamma_dir template<class GammaLUT> rgba16 rgba16_gamma_dir(rgba16 c, const GammaLUT& gamma) { return rgba16(gamma.dir(c.r), gamma.dir(c.g), gamma.dir(c.b), c.a); } //------------------------------------------------------rgba16_gamma_inv template<class GammaLUT> rgba16 rgba16_gamma_inv(rgba16 c, const GammaLUT& gamma) { return rgba16(gamma.inv(c.r), gamma.inv(c.g), gamma.inv(c.b), c.a); } } #endif
utf-8
1
MIT
Joyent, Inc. and other Node contributors 2002, Refractions Research 2003, John Novak, Novacell Technologies 2002-2003, Julien-Samuel Lacroix, DM Solutions Group Inc 2000-2005, DM Solutions Group 2004-2005, Sean Gillies <sgillies@frii.com> 2007, IS Consulting (www.mapdotnet.com) 2000-2006, 2008, Y. Assefa, DM Solutions Group inc. 2009-2010, Thomas Bonfort 2008, 2010, Paul Ramsey 2001-2002, 2004, 2007, 2010, Frank Warmerdam <warmerdam@pobox.com> 2000-2010, Daniel Morissette, DM Solutions Group Inc. 2010-2011, EOX IT Services GmbH, Austria 2011, 2013, Alan Boudreault, MapGears 2006-2007, 2017, Tom Kralidis <tomkralidis@gmail.com> 1996-2019, Regents of the University of Minnesota. 2019, Seth Girvin 2013, 2020, Even Rouault 2008-2021, Open Source Geospatial Foundation.
plymouth-0.9.5+git20211018/src/ply-boot-server.c
/* ply-boot-server.c - listens for and processes boot-status events * * Copyright (C) 2007 Red Hat, Inc. * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2, 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. * * Written by: Ray Strode <rstrode@redhat.com> */ #include "config.h" #include "ply-boot-server.h" #include <assert.h> #include <errno.h> #include <stdint.h> #include <stdio.h> #include <stdlib.h> #include <sys/socket.h> #include <sys/stat.h> #include <sys/types.h> #include <unistd.h> #include "ply-buffer.h" #include "ply-event-loop.h" #include "ply-list.h" #include "ply-logger.h" #include "ply-trigger.h" #include "ply-utils.h" typedef struct { int fd; ply_fd_watch_t *watch; ply_boot_server_t *server; uid_t uid; pid_t pid; int reference_count; uint32_t credentials_read : 1; uint32_t disconnected : 1; } ply_boot_connection_t; struct _ply_boot_server { ply_event_loop_t *loop; ply_list_t *connections; ply_list_t *cached_passwords; int socket_fd; ply_boot_server_update_handler_t update_handler; ply_boot_server_change_mode_handler_t change_mode_handler; ply_boot_server_system_update_handler_t system_update_handler; ply_boot_server_newroot_handler_t newroot_handler; ply_boot_server_system_initialized_handler_t system_initialized_handler; ply_boot_server_error_handler_t error_handler; ply_boot_server_show_splash_handler_t show_splash_handler; ply_boot_server_hide_splash_handler_t hide_splash_handler; ply_boot_server_ask_for_password_handler_t ask_for_password_handler; ply_boot_server_ask_question_handler_t ask_question_handler; ply_boot_server_display_message_handler_t display_message_handler; ply_boot_server_hide_message_handler_t hide_message_handler; ply_boot_server_watch_for_keystroke_handler_t watch_for_keystroke_handler; ply_boot_server_ignore_keystroke_handler_t ignore_keystroke_handler; ply_boot_server_progress_pause_handler_t progress_pause_handler; ply_boot_server_progress_unpause_handler_t progress_unpause_handler; ply_boot_server_deactivate_handler_t deactivate_handler; ply_boot_server_reactivate_handler_t reactivate_handler; ply_boot_server_quit_handler_t quit_handler; ply_boot_server_has_active_vt_handler_t has_active_vt_handler; void *user_data; uint32_t is_listening : 1; }; ply_boot_server_t * ply_boot_server_new (ply_boot_server_update_handler_t update_handler, ply_boot_server_change_mode_handler_t change_mode_handler, ply_boot_server_system_update_handler_t system_update_handler, ply_boot_server_ask_for_password_handler_t ask_for_password_handler, ply_boot_server_ask_question_handler_t ask_question_handler, ply_boot_server_display_message_handler_t display_message_handler, ply_boot_server_hide_message_handler_t hide_message_handler, ply_boot_server_watch_for_keystroke_handler_t watch_for_keystroke_handler, ply_boot_server_ignore_keystroke_handler_t ignore_keystroke_handler, ply_boot_server_progress_pause_handler_t progress_pause_handler, ply_boot_server_progress_unpause_handler_t progress_unpause_handler, ply_boot_server_show_splash_handler_t show_splash_handler, ply_boot_server_hide_splash_handler_t hide_splash_handler, ply_boot_server_newroot_handler_t newroot_handler, ply_boot_server_system_initialized_handler_t initialized_handler, ply_boot_server_error_handler_t error_handler, ply_boot_server_deactivate_handler_t deactivate_handler, ply_boot_server_reactivate_handler_t reactivate_handler, ply_boot_server_quit_handler_t quit_handler, ply_boot_server_has_active_vt_handler_t has_active_vt_handler, void *user_data) { ply_boot_server_t *server; server = calloc (1, sizeof(ply_boot_server_t)); server->connections = ply_list_new (); server->cached_passwords = ply_list_new (); server->loop = NULL; server->is_listening = false; server->update_handler = update_handler; server->change_mode_handler = change_mode_handler; server->system_update_handler = system_update_handler; server->ask_for_password_handler = ask_for_password_handler; server->ask_question_handler = ask_question_handler; server->display_message_handler = display_message_handler; server->hide_message_handler = hide_message_handler; server->watch_for_keystroke_handler = watch_for_keystroke_handler; server->ignore_keystroke_handler = ignore_keystroke_handler; server->progress_pause_handler = progress_pause_handler; server->progress_unpause_handler = progress_unpause_handler; server->newroot_handler = newroot_handler; server->error_handler = error_handler; server->system_initialized_handler = initialized_handler; server->show_splash_handler = show_splash_handler; server->hide_splash_handler = hide_splash_handler; server->deactivate_handler = deactivate_handler; server->reactivate_handler = reactivate_handler; server->quit_handler = quit_handler; server->has_active_vt_handler = has_active_vt_handler; server->user_data = user_data; return server; } static void ply_boot_connection_on_hangup (ply_boot_connection_t *connection); void ply_boot_server_free (ply_boot_server_t *server) { ply_list_node_t *node; if (server == NULL) return; while ((node = ply_list_get_first_node (server->connections))) { ply_boot_connection_t *connection = ply_list_node_get_data (node); ply_boot_connection_on_hangup (connection); } ply_list_free (server->connections); ply_list_free (server->cached_passwords); free (server); } static ply_boot_connection_t * ply_boot_connection_new (ply_boot_server_t *server, int fd) { ply_boot_connection_t *connection; connection = calloc (1, sizeof(ply_boot_connection_t)); connection->fd = fd; connection->server = server; connection->watch = NULL; connection->reference_count = 1; return connection; } static void ply_boot_connection_free (ply_boot_connection_t *connection) { if (connection == NULL) return; close (connection->fd); free (connection); } static void ply_boot_connection_take_reference (ply_boot_connection_t *connection) { connection->reference_count++; } static void ply_boot_connection_drop_reference (ply_boot_connection_t *connection) { if (connection == NULL) return; connection->reference_count--; assert (connection->reference_count >= 0); if (connection->reference_count == 0) ply_boot_connection_free (connection); } bool ply_boot_server_listen (ply_boot_server_t *server) { assert (server != NULL); server->socket_fd = ply_listen_to_unix_socket (PLY_BOOT_PROTOCOL_TRIMMED_ABSTRACT_SOCKET_PATH, PLY_UNIX_SOCKET_TYPE_TRIMMED_ABSTRACT); if (server->socket_fd < 0) return false; return true; } void ply_boot_server_stop_listening (ply_boot_server_t *server) { assert (server != NULL); } static bool ply_boot_connection_read_request (ply_boot_connection_t *connection, char **command, char **argument) { uint8_t header[2]; assert (connection != NULL); assert (connection->fd >= 0); connection->credentials_read = false; if (!ply_read (connection->fd, header, sizeof(header))) return false; *command = calloc (2, sizeof(char)); *command[0] = header[0]; *argument = NULL; if (header[1] == '\002') { uint8_t argument_size; if (!ply_read (connection->fd, &argument_size, sizeof(uint8_t))) { free (*command); return false; } *argument = calloc (argument_size, sizeof(char)); if (!ply_read (connection->fd, *argument, argument_size)) { free (*argument); free (*command); return false; } } if (!ply_get_credentials_from_fd (connection->fd, &connection->pid, &connection->uid, NULL)) { ply_trace ("couldn't read credentials from connection: %m"); free (*argument); free (*command); return false; } connection->credentials_read = true; return true; } static bool ply_boot_connection_is_from_root (ply_boot_connection_t *connection) { if (!connection->credentials_read) { ply_trace ("Asked if connection is from root, but haven't checked credentials yet"); return false; } return connection->uid == 0; } static void ply_boot_connection_send_answer (ply_boot_connection_t *connection, const char *answer) { uint32_t size; /* splash plugin isn't able to ask for password, * punt to client */ if (answer == NULL) { if (!ply_write (connection->fd, PLY_BOOT_PROTOCOL_RESPONSE_TYPE_NO_ANSWER, strlen (PLY_BOOT_PROTOCOL_RESPONSE_TYPE_NO_ANSWER))) ply_trace ("could not finish writing no answer reply: %m"); } else { size = strlen (answer); if (!ply_write (connection->fd, PLY_BOOT_PROTOCOL_RESPONSE_TYPE_ANSWER, strlen (PLY_BOOT_PROTOCOL_RESPONSE_TYPE_ANSWER)) || !ply_write_uint32 (connection->fd, size) || !ply_write (connection->fd, answer, size)) ply_trace ("could not finish writing answer: %m"); } } static void ply_boot_connection_on_password_answer (ply_boot_connection_t *connection, const char *password) { ply_trace ("got password answer"); if (!connection->disconnected) ply_boot_connection_send_answer (connection, password); if (password != NULL) ply_list_append_data (connection->server->cached_passwords, strdup (password)); ply_boot_connection_drop_reference (connection); } static void ply_boot_connection_on_deactivated (ply_boot_connection_t *connection) { ply_trace ("deactivated"); if (!connection->disconnected) { if (!ply_write (connection->fd, PLY_BOOT_PROTOCOL_RESPONSE_TYPE_ACK, strlen (PLY_BOOT_PROTOCOL_RESPONSE_TYPE_ACK))) ply_trace ("could not finish writing deactivate reply: %m"); } ply_boot_connection_drop_reference (connection); } static void ply_boot_connection_on_quit_complete (ply_boot_connection_t *connection) { ply_trace ("quit complete"); if (!connection->disconnected) { if (!ply_write (connection->fd, PLY_BOOT_PROTOCOL_RESPONSE_TYPE_ACK, strlen (PLY_BOOT_PROTOCOL_RESPONSE_TYPE_ACK))) ply_trace ("could not finish writing quit reply: %m"); } ply_boot_connection_drop_reference (connection); } static void ply_boot_connection_on_question_answer (ply_boot_connection_t *connection, const char *answer) { ply_trace ("got question answer: %s", answer); if (!connection->disconnected) ply_boot_connection_send_answer (connection, answer); ply_boot_connection_drop_reference (connection); } static void ply_boot_connection_on_keystroke_answer (ply_boot_connection_t *connection, const char *key) { ply_trace ("got key: %s", key); if (!connection->disconnected) ply_boot_connection_send_answer (connection, key); ply_boot_connection_drop_reference (connection); } static void print_connection_process_identity (ply_boot_connection_t *connection) { char *command_line, *parent_command_line; pid_t parent_pid; command_line = ply_get_process_command_line (connection->pid); if (connection->pid == 1) { ply_trace ("connection is from toplevel init process (%s)", command_line); } else { parent_pid = ply_get_process_parent_pid (connection->pid); parent_command_line = ply_get_process_command_line (parent_pid); ply_trace ("connection is from pid %ld (%s) with parent pid %ld (%s)", (long) connection->pid, command_line, (long) parent_pid, parent_command_line); free (parent_command_line); } free (command_line); } static void ply_boot_connection_on_request (ply_boot_connection_t *connection) { ply_boot_server_t *server; char *command, *argument; assert (connection != NULL); assert (connection->fd >= 0); server = connection->server; assert (server != NULL); if (!ply_boot_connection_read_request (connection, &command, &argument)) { ply_trace ("could not read connection request"); return; } if (ply_is_tracing ()) print_connection_process_identity (connection); if (!ply_boot_connection_is_from_root (connection)) { ply_error ("request came from non-root user"); if (!ply_write (connection->fd, PLY_BOOT_PROTOCOL_RESPONSE_TYPE_NAK, strlen (PLY_BOOT_PROTOCOL_RESPONSE_TYPE_NAK))) ply_trace ("could not finish writing is-not-root nak: %m"); free (argument); free (command); return; } if (strcmp (command, PLY_BOOT_PROTOCOL_REQUEST_TYPE_UPDATE) == 0) { if (!ply_write (connection->fd, PLY_BOOT_PROTOCOL_RESPONSE_TYPE_ACK, strlen (PLY_BOOT_PROTOCOL_RESPONSE_TYPE_ACK)) && errno != EPIPE) ply_trace ("could not finish writing update reply: %m"); ply_trace ("got update request"); if (server->update_handler != NULL) server->update_handler (server->user_data, argument, server); free (argument); free (command); return; } else if (strcmp (command, PLY_BOOT_PROTOCOL_REQUEST_TYPE_CHANGE_MODE) == 0) { if (!ply_write (connection->fd, PLY_BOOT_PROTOCOL_RESPONSE_TYPE_ACK, strlen (PLY_BOOT_PROTOCOL_RESPONSE_TYPE_ACK))) ply_trace ("could not finish writing update reply: %m"); ply_trace ("got change mode notification"); if (server->change_mode_handler != NULL) server->change_mode_handler (server->user_data, argument, server); free (argument); free (command); return; } else if (strcmp (command, PLY_BOOT_PROTOCOL_REQUEST_TYPE_SYSTEM_UPDATE) == 0) { long int value; char *endptr = NULL; value = strtol (argument, &endptr, 10); if (endptr == NULL || *endptr != '\0' || value < 0 || value > 100) { ply_error ("failed to parse percentage %s", argument); value = 0; } ply_trace ("got system-update notification %li%%", value); if (!ply_write (connection->fd, PLY_BOOT_PROTOCOL_RESPONSE_TYPE_ACK, strlen (PLY_BOOT_PROTOCOL_RESPONSE_TYPE_ACK))) ply_trace ("could not finish writing update reply: %m"); if (server->system_update_handler != NULL) server->system_update_handler (server->user_data, value, server); free (argument); free (command); return; } else if (strcmp (command, PLY_BOOT_PROTOCOL_REQUEST_TYPE_SYSTEM_INITIALIZED) == 0) { ply_trace ("got system initialized notification"); if (server->system_initialized_handler != NULL) server->system_initialized_handler (server->user_data, server); } else if (strcmp (command, PLY_BOOT_PROTOCOL_REQUEST_TYPE_ERROR) == 0) { ply_trace ("got error notification"); if (server->error_handler != NULL) server->error_handler (server->user_data, server); } else if (strcmp (command, PLY_BOOT_PROTOCOL_REQUEST_TYPE_SHOW_SPLASH) == 0) { ply_trace ("got show splash request"); if (server->show_splash_handler != NULL) server->show_splash_handler (server->user_data, server); } else if (strcmp (command, PLY_BOOT_PROTOCOL_REQUEST_TYPE_HIDE_SPLASH) == 0) { ply_trace ("got hide splash request"); if (server->hide_splash_handler != NULL) server->hide_splash_handler (server->user_data, server); } else if (strcmp (command, PLY_BOOT_PROTOCOL_REQUEST_TYPE_DEACTIVATE) == 0) { ply_trigger_t *deactivate_trigger; ply_trace ("got deactivate request"); deactivate_trigger = ply_trigger_new (NULL); ply_trigger_add_handler (deactivate_trigger, (ply_trigger_handler_t) ply_boot_connection_on_deactivated, connection); ply_boot_connection_take_reference (connection); if (server->deactivate_handler != NULL) server->deactivate_handler (server->user_data, deactivate_trigger, server); else ply_trigger_free (deactivate_trigger); free (argument); free (command); return; } else if (strcmp (command, PLY_BOOT_PROTOCOL_REQUEST_TYPE_REACTIVATE) == 0) { ply_trace ("got reactivate request"); if (server->reactivate_handler != NULL) server->reactivate_handler (server->user_data, server); } else if (strcmp (command, PLY_BOOT_PROTOCOL_REQUEST_TYPE_QUIT) == 0) { bool retain_splash; ply_trigger_t *quit_trigger; retain_splash = (bool) argument[0]; ply_trace ("got quit %srequest", retain_splash ? "--retain-splash " : ""); quit_trigger = ply_trigger_new (NULL); ply_trigger_add_handler (quit_trigger, (ply_trigger_handler_t) ply_boot_connection_on_quit_complete, connection); ply_boot_connection_take_reference (connection); if (server->quit_handler != NULL) server->quit_handler (server->user_data, retain_splash, quit_trigger, server); else ply_trigger_free (quit_trigger); free (argument); free (command); return; } else if (strcmp (command, PLY_BOOT_PROTOCOL_REQUEST_TYPE_PASSWORD) == 0) { ply_trigger_t *answer; ply_trace ("got password request"); answer = ply_trigger_new (NULL); ply_trigger_add_handler (answer, (ply_trigger_handler_t) ply_boot_connection_on_password_answer, connection); ply_boot_connection_take_reference (connection); if (server->ask_for_password_handler != NULL) { server->ask_for_password_handler (server->user_data, argument, answer, server); } else { ply_trigger_free (answer); free (argument); } /* will reply later */ free (command); return; } else if (strcmp (command, PLY_BOOT_PROTOCOL_REQUEST_TYPE_CACHED_PASSWORD) == 0) { ply_list_node_t *node; ply_buffer_t *buffer; size_t buffer_size; uint32_t size; ply_trace ("got cached password request"); buffer = ply_buffer_new (); node = ply_list_get_first_node (server->cached_passwords); ply_trace ("There are %d cached passwords", ply_list_get_length (server->cached_passwords)); /* Add each answer separated by their NUL terminators into * a buffer that we write out to the client */ while (node != NULL) { ply_list_node_t *next_node; const char *password; next_node = ply_list_get_next_node (server->cached_passwords, node); password = (const char *) ply_list_node_get_data (node); ply_buffer_append_bytes (buffer, password, strlen (password) + 1); node = next_node; } buffer_size = ply_buffer_get_size (buffer); /* splash plugin doesn't have any cached passwords */ if (buffer_size == 0) { ply_trace ("Responding with 'no answer' reply since there are currently " "no cached answers"); if (!ply_write (connection->fd, PLY_BOOT_PROTOCOL_RESPONSE_TYPE_NO_ANSWER, strlen (PLY_BOOT_PROTOCOL_RESPONSE_TYPE_NO_ANSWER))) ply_trace ("could not finish writing no answer reply: %m"); } else { size = buffer_size; ply_trace ("writing %d cached answers", ply_list_get_length (server->cached_passwords)); if (!ply_write (connection->fd, PLY_BOOT_PROTOCOL_RESPONSE_TYPE_MULTIPLE_ANSWERS, strlen (PLY_BOOT_PROTOCOL_RESPONSE_TYPE_MULTIPLE_ANSWERS)) || !ply_write_uint32 (connection->fd, size) || !ply_write (connection->fd, ply_buffer_get_bytes (buffer), size)) ply_trace ("could not finish writing cached answer reply: %m"); } ply_buffer_free (buffer); free (command); return; } else if (strcmp (command, PLY_BOOT_PROTOCOL_REQUEST_TYPE_QUESTION) == 0) { ply_trigger_t *answer; ply_trace ("got question request"); answer = ply_trigger_new (NULL); ply_trigger_add_handler (answer, (ply_trigger_handler_t) ply_boot_connection_on_question_answer, connection); ply_boot_connection_take_reference (connection); if (server->ask_question_handler != NULL) { server->ask_question_handler (server->user_data, argument, answer, server); } else { ply_trigger_free (answer); free (argument); } /* will reply later */ free (command); return; } else if (strcmp (command, PLY_BOOT_PROTOCOL_REQUEST_TYPE_SHOW_MESSAGE) == 0) { ply_trace ("got show message request"); if (server->display_message_handler != NULL) server->display_message_handler (server->user_data, argument, server); } else if (strcmp (command, PLY_BOOT_PROTOCOL_REQUEST_TYPE_HIDE_MESSAGE) == 0) { ply_trace ("got hide message request"); if (server->hide_message_handler != NULL) server->hide_message_handler (server->user_data, argument, server); } else if (strcmp (command, PLY_BOOT_PROTOCOL_REQUEST_TYPE_KEYSTROKE) == 0) { ply_trigger_t *answer; ply_trace ("got keystroke request"); answer = ply_trigger_new (NULL); ply_trigger_add_handler (answer, (ply_trigger_handler_t) ply_boot_connection_on_keystroke_answer, connection); ply_boot_connection_take_reference (connection); if (server->watch_for_keystroke_handler != NULL) { server->watch_for_keystroke_handler (server->user_data, argument, answer, server); } else { ply_trigger_free (answer); free (argument); } /* will reply later */ free (command); return; } else if (strcmp (command, PLY_BOOT_PROTOCOL_REQUEST_TYPE_KEYSTROKE_REMOVE) == 0) { ply_trace ("got keystroke remove request"); if (server->ignore_keystroke_handler != NULL) server->ignore_keystroke_handler (server->user_data, argument, server); } else if (strcmp (command, PLY_BOOT_PROTOCOL_REQUEST_TYPE_PROGRESS_PAUSE) == 0) { ply_trace ("got progress pause request"); if (server->progress_pause_handler != NULL) server->progress_pause_handler (server->user_data, server); } else if (strcmp (command, PLY_BOOT_PROTOCOL_REQUEST_TYPE_PROGRESS_UNPAUSE) == 0) { ply_trace ("got progress unpause request"); if (server->progress_unpause_handler != NULL) server->progress_unpause_handler (server->user_data, server); } else if (strcmp (command, PLY_BOOT_PROTOCOL_REQUEST_TYPE_NEWROOT) == 0) { ply_trace ("got newroot request"); if (server->newroot_handler != NULL) server->newroot_handler (server->user_data, argument, server); } else if (strcmp (command, PLY_BOOT_PROTOCOL_REQUEST_TYPE_HAS_ACTIVE_VT) == 0) { bool answer = false; ply_trace ("got has_active vt? request"); if (server->has_active_vt_handler != NULL) answer = server->has_active_vt_handler (server->user_data, server); if (!answer) { if (!ply_write (connection->fd, PLY_BOOT_PROTOCOL_RESPONSE_TYPE_NAK, strlen (PLY_BOOT_PROTOCOL_RESPONSE_TYPE_NAK))) ply_trace ("could not finish writing nak: %m"); free (argument); free (command); return; } } else if (strcmp (command, PLY_BOOT_PROTOCOL_REQUEST_TYPE_PING) != 0) { ply_error ("received unknown command '%s' from client", command); if (!ply_write (connection->fd, PLY_BOOT_PROTOCOL_RESPONSE_TYPE_NAK, strlen (PLY_BOOT_PROTOCOL_RESPONSE_TYPE_NAK))) ply_trace ("could not finish writing ping reply: %m"); free (argument); free (command); return; } if (!ply_write (connection->fd, PLY_BOOT_PROTOCOL_RESPONSE_TYPE_ACK, strlen (PLY_BOOT_PROTOCOL_RESPONSE_TYPE_ACK))) ply_trace ("could not finish writing ack: %m"); free (argument); free (command); } static void ply_boot_connection_on_hangup (ply_boot_connection_t *connection) { ply_list_node_t *node; ply_boot_server_t *server; assert (connection != NULL); assert (connection->server != NULL); connection->disconnected = true; server = connection->server; node = ply_list_find_node (server->connections, connection); assert (node != NULL); ply_boot_connection_drop_reference (connection); ply_list_remove_node (server->connections, node); } static void ply_boot_server_on_new_connection (ply_boot_server_t *server) { ply_boot_connection_t *connection; int fd; assert (server != NULL); fd = accept4 (server->socket_fd, NULL, NULL, SOCK_CLOEXEC); if (fd < 0) return; connection = ply_boot_connection_new (server, fd); connection->watch = ply_event_loop_watch_fd (server->loop, fd, PLY_EVENT_LOOP_FD_STATUS_HAS_DATA, (ply_event_handler_t) ply_boot_connection_on_request, (ply_event_handler_t) ply_boot_connection_on_hangup, connection); ply_list_append_data (server->connections, connection); } static void ply_boot_server_on_hangup (ply_boot_server_t *server) { assert (server != NULL); } static void ply_boot_server_detach_from_event_loop (ply_boot_server_t *server) { assert (server != NULL); server->loop = NULL; } void ply_boot_server_attach_to_event_loop (ply_boot_server_t *server, ply_event_loop_t *loop) { assert (server != NULL); assert (loop != NULL); assert (server->loop == NULL); assert (server->socket_fd >= 0); server->loop = loop; ply_event_loop_watch_fd (loop, server->socket_fd, PLY_EVENT_LOOP_FD_STATUS_HAS_DATA, (ply_event_handler_t) ply_boot_server_on_new_connection, (ply_event_handler_t) ply_boot_server_on_hangup, server); ply_event_loop_watch_for_exit (loop, (ply_event_loop_exit_handler_t) ply_boot_server_detach_from_event_loop, server); } /* vim: set ts=4 sw=4 expandtab autoindent cindent cino={.5s,(0: */
utf-8
1
GPL-2+
2006-2008 Red Hat, Inc. 2007-2008 Ray Strode <halfline@gmail.com> 2003 University of Southern California 2003 Charlie Brej <cbrej@cs.man.ac.uk>
r-base-4.1.2/src/extra/tre/tre-config.h
/* lib/tre-config.h. Generated from tre-config.h.in by configure. */ /* tre-config.h.in. This file has all definitions that are needed in `tre.h'. Note that this file must contain only the bare minimum of definitions without the TRE_ prefix to avoid conflicts between definitions here and definitions included from somewhere else. */ /* Define if you want to enable approximate matching functionality. */ #define TRE_APPROX 1 /* Define to enable multibyte character set support. */ #define TRE_MULTIBYTE 1 /* Define to a field in the regex_t struct where TRE should store a pointer to the internal tre_tnfa_t structure */ #define TRE_REGEX_T_FIELD value /* Define if you want TRE to use alloca() instead of malloc() when allocating memory needed for regexec operations. */ /* #define TRE_USE_ALLOCA 1 */ /* Define to enable wide character (wchar_t) support. */ #define TRE_WCHAR 1 /* TRE version string. */ #define TRE_VERSION "0.8.0"
utf-8
1
unknown
unknown
wiredtiger-3.2.1/src/optrack/optrack.c
/*- * Copyright (c) 2014-2019 MongoDB, Inc. * Copyright (c) 2008-2014 WiredTiger, Inc. * All rights reserved. * * See the file LICENSE for redistribution information. */ #include "wt_internal.h" /* * __wt_optrack_record_funcid -- * Allocate and record optrack function ID. */ void __wt_optrack_record_funcid(WT_SESSION_IMPL *session, const char *func, uint16_t *func_idp) { static uint16_t optrack_uid = 0; /* Unique for the process lifetime. */ WT_CONNECTION_IMPL *conn; WT_DECL_ITEM(tmp); WT_DECL_RET; wt_off_t fsize; bool locked; conn = S2C(session); locked = false; WT_ERR(__wt_scr_alloc(session, strlen(func) + 32, &tmp)); __wt_spin_lock(session, &conn->optrack_map_spinlock); locked = true; if (*func_idp == 0) { *func_idp = ++optrack_uid; WT_ERR(__wt_buf_fmt(session, tmp, "%" PRIu16 " %s\n", *func_idp, func)); WT_ERR(__wt_filesize(session, conn->optrack_map_fh, &fsize)); WT_ERR(__wt_write(session, conn->optrack_map_fh, fsize, tmp->size, tmp->data)); } if (0) { err: WT_PANIC_MSG(session, ret, "operation tracking initialization failure"); } if (locked) __wt_spin_unlock(session, &conn->optrack_map_spinlock); __wt_scr_free(session, &tmp); } /* * __optrack_open_file -- * Open the per-session operation-tracking file. */ static int __optrack_open_file(WT_SESSION_IMPL *session) { struct timespec ts; WT_CONNECTION_IMPL *conn; WT_DECL_ITEM(buf); WT_DECL_RET; WT_OPTRACK_HEADER optrack_header = { WT_OPTRACK_VERSION, 0, (uint32_t)WT_TSC_DEFAULT_RATIO * WT_THOUSAND, 0, 0}; conn = S2C(session); if (!F_ISSET(conn, WT_CONN_OPTRACK)) WT_RET_MSG(session, WT_ERROR, "WT_CONN_OPTRACK not set"); WT_RET(__wt_scr_alloc(session, 0, &buf)); WT_ERR(__wt_filename_construct( session, conn->optrack_path, "optrack", conn->optrack_pid, session->id, buf)); WT_ERR(__wt_open(session, (const char *)buf->data, WT_FS_OPEN_FILE_TYPE_REGULAR, WT_FS_OPEN_CREATE, &session->optrack_fh)); /* Indicate whether this is an internal session */ if (F_ISSET(session, WT_SESSION_INTERNAL)) optrack_header.optrack_session_internal = 1; /* * Record the clock ticks to nanoseconds ratio. Multiply it by one thousand, so we can use a * fixed width integer. */ optrack_header.optrack_tsc_nsec_ratio = (uint32_t)(__wt_process.tsc_nsec_ratio * WT_THOUSAND); /* Record the time in seconds since the Epoch. */ __wt_epoch(session, &ts); optrack_header.optrack_seconds_epoch = (uint64_t)ts.tv_sec; /* Write the header into the operation-tracking file. */ WT_ERR(session->optrack_fh->handle->fh_write(session->optrack_fh->handle, (WT_SESSION *)session, 0, sizeof(WT_OPTRACK_HEADER), &optrack_header)); session->optrack_offset = sizeof(WT_OPTRACK_HEADER); if (0) { err: WT_TRET(__wt_close(session, &session->optrack_fh)); } __wt_scr_free(session, &buf); return (ret); } /* * __wt_optrack_flush_buffer -- * Flush optrack buffer. Returns the number of bytes flushed to the file. */ void __wt_optrack_flush_buffer(WT_SESSION_IMPL *s) { if (s->optrack_fh == NULL && __optrack_open_file(s) != 0) return; /* * We're not using the standard write path deliberately, that's quite a bit of additional code * (including atomic operations), and this work should be as light-weight as possible. */ if (s->optrack_fh->handle->fh_write(s->optrack_fh->handle, (WT_SESSION *)s, (wt_off_t)s->optrack_offset, s->optrackbuf_ptr * sizeof(WT_OPTRACK_RECORD), s->optrack_buf) == 0) s->optrack_offset += s->optrackbuf_ptr * sizeof(WT_OPTRACK_RECORD); }
utf-8
1
GPL-2+
Copyright (C) 2014-2015 MongoDB, Inc., Copyright (C) 2008-2014 WiredTiger, Inc.
plasma-discover-5.23.5/libdiscover/UpdateModel/UpdateModel.cpp
/* * SPDX-FileCopyrightText: 2011 Jonathan Thomas <echidnaman@kubuntu.org> * * SPDX-License-Identifier: GPL-2.0-only OR GPL-3.0-only OR LicenseRef-KDE-Accepted-GPL */ #include "UpdateModel.h" // Qt includes #include "libdiscover_debug.h" #include <QFont> #include <QTimer> // KDE includes #include <KFormat> #include <KLocalizedString> // Own includes #include "UpdateItem.h" #include <resources/AbstractResource.h> #include <resources/ResourcesModel.h> #include <resources/ResourcesUpdatesModel.h> UpdateModel::UpdateModel(QObject *parent) : QAbstractListModel(parent) , m_updateSizeTimer(new QTimer(this)) , m_updates(nullptr) { connect(ResourcesModel::global(), &ResourcesModel::fetchingChanged, this, &UpdateModel::activityChanged); connect(ResourcesModel::global(), &ResourcesModel::updatesCountChanged, this, &UpdateModel::activityChanged); connect(ResourcesModel::global(), &ResourcesModel::resourceDataChanged, this, &UpdateModel::resourceDataChanged); connect(this, &UpdateModel::toUpdateChanged, this, &UpdateModel::updateSizeChanged); m_updateSizeTimer->setInterval(100); m_updateSizeTimer->setSingleShot(true); connect(m_updateSizeTimer, &QTimer::timeout, this, &UpdateModel::updateSizeChanged); } UpdateModel::~UpdateModel() { qDeleteAll(m_updateItems); m_updateItems.clear(); } QHash<int, QByteArray> UpdateModel::roleNames() const { auto ret = QAbstractItemModel::roleNames(); ret.insert(Qt::CheckStateRole, "checked"); ret.insert(ResourceProgressRole, "resourceProgress"); ret.insert(ResourceStateRole, "resourceState"); ret.insert(ResourceRole, "resource"); ret.insert(SizeRole, "size"); ret.insert(SectionRole, "section"); ret.insert(ChangelogRole, "changelog"); ret.insert(UpgradeTextRole, "upgradeText"); return ret; } void UpdateModel::setBackend(ResourcesUpdatesModel *updates) { if (m_updates) { disconnect(m_updates, nullptr, this, nullptr); } m_updates = updates; connect(m_updates, &ResourcesUpdatesModel::progressingChanged, this, &UpdateModel::activityChanged); connect(m_updates, &ResourcesUpdatesModel::resourceProgressed, this, &UpdateModel::resourceHasProgressed); activityChanged(); } void UpdateModel::resourceHasProgressed(AbstractResource *res, qreal progress, AbstractBackendUpdater::State state) { UpdateItem *item = itemFromResource(res); if (!item) return; item->setProgress(progress); item->setState(state); const QModelIndex idx = indexFromItem(item); Q_EMIT dataChanged(idx, idx, {ResourceProgressRole, ResourceStateRole, SectionResourceProgressRole}); } void UpdateModel::activityChanged() { if (m_updates) { if (!m_updates->isProgressing()) { m_updates->prepare(); setResources(m_updates->toUpdate()); for (auto item : qAsConst(m_updateItems)) { item->setProgress(0); } } else setResources(m_updates->toUpdate()); } } QVariant UpdateModel::data(const QModelIndex &index, int role) const { if (!index.isValid()) { return QVariant(); } UpdateItem *item = itemFromIndex(index); switch (role) { case Qt::DisplayRole: return item->name(); case Qt::DecorationRole: return item->icon(); case Qt::CheckStateRole: return item->checked(); case SizeRole: return KFormat().formatByteSize(item->size()); case ResourceRole: return QVariant::fromValue<QObject *>(item->resource()); case ResourceProgressRole: return item->progress(); case ResourceStateRole: return item->state(); case ChangelogRole: return item->changelog(); case SectionRole: { static const QString appUpdatesSection = i18nc("@item:inlistbox", "Application Updates"); static const QString systemUpdateSection = i18nc("@item:inlistbox", "System Updates"); static const QString addonsSection = i18nc("@item:inlistbox", "Addons"); switch (item->resource()->type()) { case AbstractResource::Application: return appUpdatesSection; case AbstractResource::Technical: return systemUpdateSection; case AbstractResource::Addon: return addonsSection; } Q_UNREACHABLE(); } case SectionResourceProgressRole: return (100 - item->progress()) + (101 * item->resource()->type()); default: break; } return QVariant(); } void UpdateModel::checkResources(const QList<AbstractResource *> &resource, bool checked) { if (checked) m_updates->addResources(resource); else m_updates->removeResources(resource); } Qt::ItemFlags UpdateModel::flags(const QModelIndex &index) const { if (!index.isValid()) return Qt::NoItemFlags; return Qt::ItemIsEnabled | Qt::ItemIsSelectable; } int UpdateModel::rowCount(const QModelIndex &parent) const { return !parent.isValid() ? m_updateItems.count() : 0; } bool UpdateModel::setData(const QModelIndex &idx, const QVariant &value, int role) { if (role == Qt::CheckStateRole) { UpdateItem *item = itemFromIndex(idx); const bool newValue = value.toInt() == Qt::Checked; const QList<AbstractResource *> apps = {item->app()}; checkResources(apps, newValue); Q_ASSERT(idx.data(Qt::CheckStateRole) == value); // When un/checking some backends will decide to add or remove a bunch of packages, so refresh it all auto m = idx.model(); Q_EMIT dataChanged(m->index(0, 0), m->index(m->rowCount() - 1, 0), {Qt::CheckStateRole}); Q_EMIT toUpdateChanged(); return true; } return false; } void UpdateModel::fetchUpdateDetails(int row) { UpdateItem *item = itemFromIndex(index(row, 0)); Q_ASSERT(item); if (!item) return; item->app()->fetchUpdateDetails(); } void UpdateModel::integrateChangelog(const QString &changelog) { auto app = qobject_cast<AbstractResource *>(sender()); Q_ASSERT(app); auto item = itemFromResource(app); if (!item) return; item->setChangelog(changelog); const QModelIndex idx = indexFromItem(item); Q_ASSERT(idx.isValid()); Q_EMIT dataChanged(idx, idx, {ChangelogRole}); } void UpdateModel::setResources(const QList<AbstractResource *> &resources) { if (resources == m_resources) { return; } m_resources = resources; beginResetModel(); qDeleteAll(m_updateItems); m_updateItems.clear(); QVector<UpdateItem *> appItems, systemItems, addonItems; for (AbstractResource *res : resources) { connect(res, &AbstractResource::changelogFetched, this, &UpdateModel::integrateChangelog, Qt::UniqueConnection); UpdateItem *updateItem = new UpdateItem(res); switch (res->type()) { case AbstractResource::Technical: systemItems += updateItem; break; case AbstractResource::Application: appItems += updateItem; break; case AbstractResource::Addon: addonItems += updateItem; break; } } const auto sortUpdateItems = [](UpdateItem *a, UpdateItem *b) { return a->name() < b->name(); }; std::sort(appItems.begin(), appItems.end(), sortUpdateItems); std::sort(systemItems.begin(), systemItems.end(), sortUpdateItems); std::sort(addonItems.begin(), addonItems.end(), sortUpdateItems); m_updateItems = (QVector<UpdateItem *>() << appItems << addonItems << systemItems); endResetModel(); Q_EMIT hasUpdatesChanged(!resources.isEmpty()); Q_EMIT toUpdateChanged(); } bool UpdateModel::hasUpdates() const { return rowCount() > 0; } ResourcesUpdatesModel *UpdateModel::backend() const { return m_updates; } int UpdateModel::toUpdateCount() const { int ret = 0; QSet<QString> packages; for (UpdateItem *item : qAsConst(m_updateItems)) { const auto packageName = item->resource()->packageName(); if (packages.contains(packageName)) { continue; } packages.insert(packageName); ret += item->checked() != Qt::Unchecked ? 1 : 0; } return ret; } int UpdateModel::totalUpdatesCount() const { int ret = 0; QSet<QString> packages; for (UpdateItem *item : qAsConst(m_updateItems)) { const auto packageName = item->resource()->packageName(); if (packages.contains(packageName)) { continue; } packages.insert(packageName); ret += 1; } return ret; } UpdateItem *UpdateModel::itemFromResource(AbstractResource *res) { for (UpdateItem *item : qAsConst(m_updateItems)) { if (item->app() == res) return item; } return nullptr; } QString UpdateModel::updateSize() const { return m_updates ? KFormat().formatByteSize(m_updates->updateSize()) : QString(); } QModelIndex UpdateModel::indexFromItem(UpdateItem *item) const { return index(m_updateItems.indexOf(item), 0, {}); } UpdateItem *UpdateModel::itemFromIndex(const QModelIndex &index) const { return m_updateItems[index.row()]; } void UpdateModel::resourceDataChanged(AbstractResource *res, const QVector<QByteArray> &properties) { auto item = itemFromResource(res); if (!item) return; const auto index = indexFromItem(item); if (properties.contains("state")) Q_EMIT dataChanged(index, index, {SizeRole, UpgradeTextRole}); else if (properties.contains("size")) { Q_EMIT dataChanged(index, index, {SizeRole}); m_updateSizeTimer->start(); } } void UpdateModel::checkAll() { for (int i = 0, c = rowCount(); i < c; ++i) if (index(i, 0).data(Qt::CheckStateRole) != Qt::Checked) setData(index(i, 0), Qt::Checked, Qt::CheckStateRole); } void UpdateModel::uncheckAll() { for (int i = 0, c = rowCount(); i < c; ++i) if (index(i, 0).data(Qt::CheckStateRole) != Qt::Unchecked) setData(index(i, 0), Qt::Unchecked, Qt::CheckStateRole); }
utf-8
1
GPL-2+3+KDEeV
2012-2018, Aleix Pol Gonzalez <aleixpol@blue-systems.com> 2010-2013, Jonathan Thomas <echidnaman@kubuntu.org> 2013, Lukas Appelhans <boom1992@chakra-project.org>
cctbx-2021.12+ds1/cctbx/sgtbx/site_symmetry_table.h
#ifndef CCTBX_SGTBX_SITE_SYMMETRY_TABLE_H #define CCTBX_SGTBX_SITE_SYMMETRY_TABLE_H #include <cctbx/sgtbx/site_symmetry.h> namespace cctbx { namespace sgtbx { class site_symmetry_table { public: //! Default constructor. site_symmetry_table() : indices_const_ref_(indices_.const_ref()), table_const_ref_(table_.const_ref()) {} //! Insert new site_symmetry_ops into internal table. /*! The internal table is searched for identical site_symmetry_ops. The indices() for duplicate site_symmetry_ops will point to the same table() entry. */ void process( std::size_t insert_at_index, site_symmetry_ops const& site_symmetry_ops_); //! Add new site_symmetry_ops to internal table. /*! See also: other overload. */ void process(site_symmetry_ops const& site_symmetry_ops_) { process(indices_const_ref_.size(), site_symmetry_ops_); } /*! \brief Compute and process site symmetries for an array of original_sites_frac. */ /*! See also: constructor of class site_symmetry */ void process( uctbx::unit_cell const& unit_cell, sgtbx::space_group const& space_group, af::const_ref<scitbx::vec3<double> > const& original_sites_frac, af::const_ref<bool> const& unconditional_general_position_flags= af::const_ref<bool>(0,0), double min_distance_sym_equiv=0.5, bool assert_min_distance_sym_equiv=true) { CCTBX_ASSERT( unconditional_general_position_flags.size() == 0 || unconditional_general_position_flags.size() == original_sites_frac.size()); bool const* ugpf = unconditional_general_position_flags.begin(); for(std::size_t i_seq=0;i_seq<original_sites_frac.size();i_seq++) { process(site_symmetry( unit_cell, space_group, original_sites_frac[i_seq], (ugpf != 0 && ugpf[i_seq] != 0 ? 0 : min_distance_sym_equiv), assert_min_distance_sym_equiv)); } } //! Shorthand for: indices()[i_seq] != 0. /*! An exception is thrown if i_seq is out of bounds. */ bool is_special_position(std::size_t i_seq) const { CCTBX_ASSERT(i_seq < indices_const_ref_.size()); return indices_const_ref_[i_seq] != 0; } //! Shorthand for: table()[indices()[i_seq]] /*! An exception is thrown if i_seq is out of bounds. */ site_symmetry_ops const& get(std::size_t i_seq) const { CCTBX_ASSERT(i_seq < indices_const_ref_.size()); return table_const_ref_[indices_const_ref_[i_seq]]; } //! Number of sites on special positions. std::size_t n_special_positions() const { return special_position_indices_.size(); } //! Indices of sites on special positions. /*! The indices refer to the order in which the site symmetries were passed to process(). */ af::shared<std::size_t> const& special_position_indices() const { return special_position_indices_; } //! Indices to internal table entries. af::shared<std::size_t> const& indices() const { return indices_; } //! Reference to indices to internal table entries; use for efficiency. /*! Not available in Python. */ af::const_ref<std::size_t> const& indices_const_ref() const { return indices_const_ref_; } //! Number of internal table entries. std::size_t n_unique() const { return table_const_ref_.size(); } //! Internal table of unique site_symmetry_ops. /*! The table is organized such that table()[0].is_point_group_1() is always true after the first call of process(). */ af::shared<site_symmetry_ops> const& table() const { return table_; } /*! \brief Reference to internal table of unique site_symmetry_ops; use for efficiency. */ /*! Not available in Python. */ af::const_ref<site_symmetry_ops> const& table_const_ref() const { return table_const_ref_; } //! Pre-allocates memory for indices(); for efficiency. void reserve(std::size_t n_sites_final) { indices_.reserve(n_sites_final); indices_const_ref_ = indices_.const_ref(); } //! Support for asu_mappings::discard_last(). /*! Not available in Python. */ void discard_last() { if (indices_const_ref_.back() != 0) { special_position_indices_.pop_back(); } indices_.pop_back(); indices_const_ref_ = indices_.const_ref(); } //! Creates independent copy. site_symmetry_table deep_copy() const { site_symmetry_table result; result.indices_ = indices_.deep_copy(); result.indices_const_ref_ = result.indices_.const_ref(); result.table_ = table_.deep_copy(); result.table_const_ref_ = result.table_.const_ref(); result.special_position_indices_=special_position_indices_.deep_copy(); return result; } //! Apply change-of-basis operator. site_symmetry_table change_basis(change_of_basis_op const& cb_op) const { site_symmetry_table result; result.indices_ = indices_.deep_copy(); result.indices_const_ref_ = result.indices_.const_ref(); result.table_.reserve(table_const_ref_.size()); for(std::size_t i_seq=0;i_seq<table_const_ref_.size();i_seq++) { result.table_.push_back(table_const_ref_[i_seq].change_basis(cb_op)); } result.table_const_ref_ = result.table_.const_ref(); result.special_position_indices_=special_position_indices_.deep_copy(); return result; } //! Apply selection. site_symmetry_table select(af::const_ref<std::size_t> const& selection) const { site_symmetry_table result; result.reserve(selection.size()); for(std::size_t i=0;i<selection.size();i++) { result.process(get(selection[i])); } return result; } //! Apply selection. site_symmetry_table select(af::const_ref<bool> const& selection) const { CCTBX_ASSERT(selection.size() == indices_.size()); site_symmetry_table result; for(std::size_t i_seq=0;i_seq<selection.size();i_seq++) { if (selection[i_seq]) { result.process(table_const_ref_[indices_const_ref_[i_seq]]); } } return result; } //! Mainly to support Python's pickle facility. /*! The inputs are NOT checked for consistency. */ site_symmetry_table( af::shared<std::size_t> const& indices, af::shared<site_symmetry_ops> const& table, af::shared<std::size_t> const& special_position_indices) : indices_(indices), table_(table), special_position_indices_(special_position_indices) { indices_const_ref_ = indices_.const_ref(); table_const_ref_ = table_.const_ref(); } void replace( std::size_t replace_at_index, site_symmetry_ops const& site_symmetry_ops_) { CCTBX_ASSERT(indices_const_ref_.end() == indices_.end()); CCTBX_ASSERT(table_const_ref_.end() == table_.end()); CCTBX_ASSERT(replace_at_index <= indices_const_ref_.size()); std::size_t i_tab = 0; bool new_is_pg_1 = site_symmetry_ops_.is_point_group_1(); std::size_t old_i_tab=indices_[replace_at_index]; bool old_is_pg_1 = table_[old_i_tab].is_point_group_1(); indices_[replace_at_index]=0; bool old_sym_used=false; if (!old_is_pg_1) for(std::size_t itr=1;itr<indices_const_ref_.size();itr++) { if (indices_[itr] == old_i_tab) { old_sym_used=true; break; } } // Make changes in table if (!new_is_pg_1) { for(i_tab=1;i_tab<table_const_ref_.size();i_tab++) { if (table_const_ref_[i_tab] == site_symmetry_ops_) { break; } } if (i_tab == table_const_ref_.size()) { if (old_sym_used) table_.push_back(site_symmetry_ops_); else table_[old_i_tab]=site_symmetry_ops_; table_const_ref_ = table_.const_ref(); } } // Make changes in indices and special_position_indices if (!new_is_pg_1 && old_sym_used){ indices_[replace_at_index]=i_tab; } if (new_is_pg_1){ if (!old_is_pg_1){ // Remove from table_ too ? indices_[replace_at_index]=0; std::size_t n = special_position_indices_.size(); std::size_t i = n-1; std::size_t* si = special_position_indices_.begin(); while (i != 0) { i--; if (si[i] < replace_at_index) break; si[i] = si[i+1]; } special_position_indices_.resize(n-1); } } else if (old_is_pg_1){ std::size_t n = special_position_indices_.size(); special_position_indices_.resize(n+1); std::size_t* si = special_position_indices_.begin(); std::size_t i = n; while (i != 0) { i--; if (si[i] < replace_at_index) break; si[i+1] = si[i]; } si[i] = replace_at_index; } indices_const_ref_ = indices_.const_ref(); } protected: af::shared<std::size_t> indices_; af::const_ref<std::size_t> indices_const_ref_; af::shared<site_symmetry_ops> table_; af::const_ref<site_symmetry_ops> table_const_ref_; af::shared<std::size_t> special_position_indices_; }; }} // namespace cctbx::sgtbx #endif // CCTBX_SGTBX_SITE_SYMMETRY_TABLE_H
utf-8
1
BSD-3-clause
2006-2018 The Regents of the University of California, through Lawrence Berkeley National Laboratory 2005 Jacob N. Smith, Erik Mckee, Texas Agricultural 2005 Jacob N. Smith & Erik McKee 2013 Sunset Lake Software 2013-2015 Diamond Light Source 2005-2009 Jim Idle, Temporal Wave LLC 2013 Diamond Light Source, James Parkhurst & Richard Gildea 2016 STFC Rutherford Appleton Laboratory, UK. 1996 John Wiley & Sons, Inc. 2016 Lawrence Berkeley National Laboratory (LBNL) 2007-2011 Jeffrey J. Headd and Robert Immormino 2005-2009 Jim Idle, Temporal Wave LLC 2010 University of California
spring-105.0.1+dfsg/rts/Sim/Units/CommandAI/BuilderCAI.h
/* This file is part of the Spring engine (GPL v2 or later), see LICENSE.html */ #ifndef _BUILDER_CAI_H_ #define _BUILDER_CAI_H_ #include "MobileCAI.h" #include "Sim/Units/BuildInfo.h" #include "System/Misc/BitwiseEnum.h" #include "System/UnorderedSet.hpp" #include <vector> class CUnit; class CBuilder; class CFeature; class CSolidObject; class CWorldObject; struct Command; struct UnitDef; class CBuilderCAI : public CMobileCAI { public: CR_DECLARE_DERIVED(CBuilderCAI) CBuilderCAI(CUnit* owner); CBuilderCAI(); ~CBuilderCAI(); static void InitStatic(); void PostLoad(); int GetDefaultCmd(const CUnit* unit, const CFeature* feature) override; void SlowUpdate() override; void FinishCommand() override; void GiveCommandReal(const Command& c, bool fromSynced = true) override; void BuggerOff(const float3& pos, float radius) override; bool TargetInterceptable(const CUnit* unit, float uspeed); void ExecuteBuildCmd(Command& c); void ExecutePatrol(Command& c) override; void ExecuteFight(Command& c) override; void ExecuteGuard(Command& c) override; void ExecuteStop(Command& c) override; virtual void ExecuteRepair(Command& c); virtual void ExecuteCapture(Command& c); virtual void ExecuteReclaim(Command& c); virtual void ExecuteResurrect(Command& c); virtual void ExecuteRestore(Command& c); bool ReclaimObject(CSolidObject* o); bool ResurrectObject(CFeature* feature); /** * Checks if a unit is being reclaimed by a friendly con. */ static bool IsUnitBeingReclaimed(const CUnit* unit, const CUnit* friendUnit = nullptr); static bool IsFeatureBeingReclaimed(int featureId, const CUnit* friendUnit = nullptr); static bool IsFeatureBeingResurrected(int featureId, const CUnit* friendUnit = nullptr); bool IsInBuildRange(const CWorldObject* obj) const; bool IsInBuildRange(const float3& pos, const float radius) const; public: spring::unordered_set<int> buildOptions; static spring::unordered_set<int> reclaimers; static spring::unordered_set<int> featureReclaimers; static spring::unordered_set<int> resurrecters; static std::vector<int> removees; private: enum ReclaimOptions { REC_NORESCHECK = 1<<0, REC_UNITS = 1<<1, REC_NONREZ = 1<<2, REC_ENEMY = 1<<3, REC_ENEMYONLY = 1<<4, REC_SPECIAL = 1<<5 }; typedef Bitwise::BitwiseEnum<ReclaimOptions> ReclaimOption; private: /** * @param pos position where to reclaim * @param radius radius to search for objects to reclaim * @param cmdopts command options * @param recoptions reclaim optioons */ bool FindReclaimTargetAndReclaim(const float3& pos, float radius, unsigned char cmdopt, ReclaimOption recoptions); /** * @param freshOnly reclaims only corpses that have rez progress or all the metal left */ bool FindResurrectableFeatureAndResurrect(const float3& pos, float radius, unsigned char options, bool freshOnly); /** * @param builtOnly skips units that are under construction */ bool FindRepairTargetAndRepair(const float3& pos, float radius, unsigned char options, bool attackEnemy, bool builtOnly); /** * @param pos position where to search for units to capture * @param radius radius in which are searched units to capture * @param options command options * @param healthyOnly only capture units with capture progress or 100% health remaining */ bool FindCaptureTargetAndCapture(const float3& pos, float radius, unsigned char options, bool healthyOnly); int FindReclaimTarget(const float3& pos, float radius, unsigned char cmdopt, ReclaimOption recoptions, float bestStartDist = 1.0e30f) const; float GetBuildRange(const float targetRadius) const; bool MoveInBuildRange(const CWorldObject* obj, const bool checkMoveTypeForFailed = false); bool MoveInBuildRange(const float3& pos, float radius, const bool checkMoveTypeForFailed = false); bool IsBuildPosBlocked(const BuildInfo& bi, const CUnit** nanoFrame) const; bool IsBuildPosBlocked(const BuildInfo& bi) const { const CUnit* u = nullptr; return IsBuildPosBlocked(build, &u); } void CancelRestrictedUnit(); bool OutOfImmobileRange(const Command& cmd) const; /// add a command to reclaim a feature that is blocking our build-site void ReclaimFeature(CFeature* f); /// fix for patrolling cons repairing/resurrecting stuff that's being reclaimed static void AddUnitToReclaimers(CUnit*); static void RemoveUnitFromReclaimers(CUnit*); /// fix for cons wandering away from their target circle static void AddUnitToFeatureReclaimers(CUnit*); static void RemoveUnitFromFeatureReclaimers(CUnit*); /// fix for patrolling cons reclaiming stuff that is being resurrected static void AddUnitToResurrecters(CUnit*); static void RemoveUnitFromResurrecters(CUnit*); inline float f3Dist(const float3& a, const float3& b) const { return range3D ? a.distance(b) : a.distance2D(b); } inline float f3SqDist(const float3& a, const float3& b) const { return range3D ? a.SqDistance(b) : a.SqDistance2D(b); } //inline float f3Len(const float3& a) const { // return range3D ? a.Length() : a.Length2D(); //} //inline float f3SqLen(const float3& a) const { // return range3D ? a.SqLength() : a.SqLength2D(); //} float GetBuildOptionRadius(const UnitDef* unitdef, int cmdId); private: CBuilder* ownerBuilder; bool building; BuildInfo build; int cachedRadiusId; float cachedRadius; int buildRetries; int randomCounter; ///< used to balance intervals of time intensive ai optimizations int lastPC1; ///< helps avoid infinite loops int lastPC2; int lastPC3; bool range3D; }; #endif // _BUILDER_CAI_H_
utf-8
1
GPL-2+
2006-2021, The Spring Developers 2006,2009, Hugh Perkins 2007, Craig Lawrence, Dave "trepan" Rodgers Alexander Seizinger 2008,2009 Robin Vobruba <hoijui.quaero@gmail.com> 2010, Andreas Löscher 2008, Nicolas Wu 2010, Matthias Ableitner <spam@abma.de> 2009, Wildfire Games 2005, Christopher Han <xiphux@gmail.com> 2007, Dave "trepan" Rodgers Reth / Michael Vadovszk
ntp-4.2.8p15+dfsg/tests/sandbox/smeartest.c
#include <config.h> #include <ntp.h> #include <ntp_fp.h> #include <ntp_assert.h> /* * we want to test a refid format of: * 254.x.y.x * * where x.y.z are 24 bits containing 2 (signed) integer bits * and 22 fractional bits. * * we want functions to convert to/from this format, with unit tests. * * Interesting test cases include: * 254.0.0.0 * 254.0.0.1 * 254.127.255.255 * 254.128.0.0 * 254.255.255.255 */ char *progname = ""; l_fp convertRefIDToLFP(uint32_t r); uint32_t convertLFPToRefID(l_fp num); /* * The smear data in the refid is the bottom 3 bytes of the refid, * 2 bits of integer * 22 bits of fraction */ l_fp convertRefIDToLFP(uint32_t r) { l_fp temp; r = ntohl(r); printf("%03d %08x: ", (r >> 24) & 0xFF, (r & 0x00FFFFFF) ); temp.l_uf = (r << 10); /* 22 fractional bits */ temp.l_ui = (r >> 22) & 0x3; temp.l_ui |= ~(temp.l_ui & 2) + 1; return temp; } uint32_t convertLFPToRefID(l_fp num) { uint32_t temp; /* round the input with the highest bit to shift out from the * fraction, then keep just two bits from the integral part. * * TODO: check for overflows; should we clamp/saturate or just * complain? */ L_ADDUF(&num, 0x200); num.l_ui &= 3; /* combine integral and fractional part to 24 bits */ temp = (num.l_ui << 22) | (num.l_uf >> 10); /* put in the leading 254.0.0.0 */ temp |= UINT32_C(0xFE000000); printf("%03d %08x: ", (temp >> 24) & 0xFF, (temp & 0x00FFFFFF) ); return htonl(temp); } /* Tests start here */ void rtol(uint32_t r); void rtol(uint32_t r) { l_fp l; printf("rtol: "); l = convertRefIDToLFP(htonl(r)); printf("refid %#x, smear %s\n", r, lfptoa(&l, 8)); return; } void rtoltor(uint32_t r); void rtoltor(uint32_t r) { l_fp l; printf("rtoltor: "); l = convertRefIDToLFP(htonl(r)); r = convertLFPToRefID(l); printf("smear %s, refid %#.8x\n", lfptoa(&l, 8), ntohl(r)); return; } void ltor(l_fp l); void ltor(l_fp l) { uint32_t r; printf("ltor: "); r = convertLFPToRefID(l); printf("smear %s, refid %#.8x\n", lfptoa(&l, 8), ntohl(r)); return; } int main() { l_fp l; int rc; init_lib(); rtol(0xfe800000); rtol(0xfe800001); rtol(0xfe8ffffe); rtol(0xfe8fffff); rtol(0xfef00000); rtol(0xfef00001); rtol(0xfefffffe); rtol(0xfeffffff); rtol(0xfe000000); rtol(0xfe000001); rtol(0xfe6ffffe); rtol(0xfe6fffff); rtol(0xfe700000); rtol(0xfe700001); rtol(0xfe7ffffe); rtol(0xfe7fffff); rtoltor(0xfe800000); rtoltor(0xfe800001); rtoltor(0xfe8ffffe); rtoltor(0xfe8fffff); rtoltor(0xfef00000); rtoltor(0xfef00001); rtoltor(0xfefffffe); rtoltor(0xfeffffff); rtoltor(0xfe000000); rtoltor(0xfe000001); rtoltor(0xfe6ffffe); rtoltor(0xfe6fffff); rtoltor(0xfe700000); rtoltor(0xfe700001); rtoltor(0xfe7ffffe); rtoltor(0xfe7fffff); rc = atolfp("-.932087", &l); INSIST(1 == rc); ltor(l); rtol(0xfec458b0); printf("%x -> %d.%d.%d.%d\n", 0xfec458b0, 0xfe, 0xc4, 0x58, 0xb0); return 0; }
utf-8
1
unknown
unknown
vtk7-7.1.1+dfsg2/Interaction/Widgets/vtkDistanceRepresentation.cxx
/*========================================================================= Program: Visualization Toolkit Module: vtkDistanceRepresentation.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 "vtkDistanceRepresentation.h" #include "vtkHandleRepresentation.h" #include "vtkCoordinate.h" #include "vtkRenderer.h" #include "vtkObjectFactory.h" #include "vtkBox.h" #include "vtkInteractorObserver.h" #include "vtkMath.h" #include "vtkWindow.h" vtkCxxSetObjectMacro(vtkDistanceRepresentation,HandleRepresentation,vtkHandleRepresentation); //---------------------------------------------------------------------- vtkDistanceRepresentation::vtkDistanceRepresentation() { this->HandleRepresentation = NULL; this->Point1Representation = NULL; this->Point2Representation = NULL; this->Tolerance = 5; this->Placed = 0; this->LabelFormat = new char[8]; sprintf(this->LabelFormat,"%s","%-#6.3g"); this->Scale = 1.0; this->RulerMode = 0; this->RulerDistance = 1.0; this->NumberOfRulerTicks = 5; } //---------------------------------------------------------------------- vtkDistanceRepresentation::~vtkDistanceRepresentation() { if ( this->HandleRepresentation ) { this->HandleRepresentation->Delete(); } if ( this->Point1Representation ) { this->Point1Representation->Delete(); } if ( this->Point2Representation ) { this->Point2Representation->Delete(); } delete [] this->LabelFormat; this->LabelFormat = NULL; } //---------------------------------------------------------------------- void vtkDistanceRepresentation::InstantiateHandleRepresentation() { if ( ! this->Point1Representation ) { this->Point1Representation = this->HandleRepresentation->NewInstance(); this->Point1Representation->ShallowCopy(this->HandleRepresentation); } if ( ! this->Point2Representation ) { this->Point2Representation = this->HandleRepresentation->NewInstance(); this->Point2Representation->ShallowCopy(this->HandleRepresentation); } } //---------------------------------------------------------------------- void vtkDistanceRepresentation::GetPoint1WorldPosition(double pos[3]) { this->Point1Representation->GetWorldPosition(pos); } //---------------------------------------------------------------------- void vtkDistanceRepresentation::GetPoint2WorldPosition(double pos[3]) { this->Point2Representation->GetWorldPosition(pos); } //---------------------------------------------------------------------- int vtkDistanceRepresentation:: ComputeInteractionState(int vtkNotUsed(X), int vtkNotUsed(Y), int vtkNotUsed(modify)) { if (this->Point1Representation == NULL || this->Point2Representation == NULL) { this->InteractionState = vtkDistanceRepresentation::Outside; return this->InteractionState; } int h1State = this->Point1Representation->GetInteractionState(); int h2State = this->Point2Representation->GetInteractionState(); if ( h1State == vtkHandleRepresentation::Nearby ) { this->InteractionState = vtkDistanceRepresentation::NearP1; } else if ( h2State == vtkHandleRepresentation::Nearby ) { this->InteractionState = vtkDistanceRepresentation::NearP2; } else { this->InteractionState = vtkDistanceRepresentation::Outside; } return this->InteractionState; } //---------------------------------------------------------------------- void vtkDistanceRepresentation::StartWidgetInteraction(double e[2]) { double pos[3]; pos[0] = e[0]; pos[1] = e[1]; pos[2] = 0.0; this->SetPoint1DisplayPosition(pos); this->SetPoint2DisplayPosition(pos); } //---------------------------------------------------------------------- void vtkDistanceRepresentation::WidgetInteraction(double e[2]) { double pos[3]; pos[0] = e[0]; pos[1] = e[1]; pos[2] = 0.0; this->SetPoint2DisplayPosition(pos); } //---------------------------------------------------------------------- void vtkDistanceRepresentation::BuildRepresentation() { // Make sure that tolerance is consistent between handles and this representation if(this->Point1Representation) { this->Point1Representation->SetTolerance(this->Tolerance); } if(this->Point2Representation) { this->Point2Representation->SetTolerance(this->Tolerance); } } //---------------------------------------------------------------------- void vtkDistanceRepresentation::PrintSelf(ostream& os, vtkIndent indent) { //Superclass typedef defined in vtkTypeMacro() found in vtkSetGet.h this->Superclass::PrintSelf(os,indent); os << indent << "Distance: " << this->GetDistance() <<"\n"; os << indent << "Tolerance: " << this->Tolerance <<"\n"; os << indent << "Handle Representation: " << this->HandleRepresentation << "\n"; os << indent << "Label Format: "; if ( this->LabelFormat ) { os << this->LabelFormat << "\n"; } else { os << "(none)\n"; } os << indent << "Scale: " << this->GetScale() << "\n"; os << indent << "Ruler Mode: " << (this->RulerMode ? "On" : "Off") <<"\n"; os << indent << "Ruler Distance: " << this->GetRulerDistance() <<"\n"; os << indent << "Number of Ruler Ticks: " << this->GetNumberOfRulerTicks() <<"\n"; os << indent << "Point1 Representation: "; if ( this->Point1Representation ) { this->Point1Representation->PrintSelf(os,indent.GetNextIndent()); } else { os << "(none)\n"; } os << indent << "Point2 Representation: "; if ( this->Point2Representation ) { this->Point2Representation->PrintSelf(os,indent.GetNextIndent()); } else { os << "(none)\n"; } }
utf-8
1
BSD-3-clause
1993-2015 Ken Martin, Will Schroeder, Bill Lorensen
twolame-0.4.0/libtwolame/psycho_4.c
/* * TwoLAME: an optimized MPEG Audio Layer Two encoder * * Copyright (C) 2001-2004 Michael Cheng * Copyright (C) 2004-2018 The TwoLAME Project * * 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., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA * */ #include <stdio.h> #include <stdlib.h> #include <math.h> #include <string.h> #include "twolame.h" #include "common.h" #include "mem.h" #include "fft.h" #include "ath.h" #include "psycho_4.h" /**************************************************************** PSYCHO_4 by MFC Feb 2003 This is a cleaned up implementation of psy model 2. This is basically because I was sick of the inconsistencies between the notation in the ISO docs and in the sourcecode. I've nicked a bunch of stuff from LAME to make this a bit easier to grok - ATH values (this also overcomes the lack of mpeg-2 tables which meant that LSF never had proper values) - ath_freq2bark() to convert frequencies directly to bark values. - spreading_function() isolated the calculation of the spreading function. Basically the same code as before, just isolated in its own function. LAME seem to does some extra tweaks to the ISO1117s model. Not really sure if they help or hinder, so I've commented them out (#ifdef LAME) NB: Because of some of the tweaks to bark value calculation etc, it is now possible to have 64 CBANDS. There's no real limit on the actual number of paritions. I wonder if it's worth experimenting with really higher numbers? Probably won't make that much difference to the final SNR values, but it's something worth trying Maybe CBANDS should be a dynamic value, calculated by the psycho_init function CBANDS definition has been changed in encoder.h from 63 to 64 ****************************************************************/ /* The static variables "r", "phi_sav", "new", "old" and "oldest" have to be remembered for the unpredictability measure. For "r" and "phi_sav", the first index from the left is the channel select and the second index is the "age" of the data. */ /* NMT is a constant 5.5dB. ISO11172 Sec D.2.4.h */ static const FLOAT NMT = 5.5; /* The index into this array is a bark value This array gives the 'minval' values from ISO11172 Tables D.3.x */ static const FLOAT minval[27] = { 0.0, /* bark = 0 */ 20.0, /* 1 */ 20.0, /* 2 */ 20.0, /* 3 */ 20.0, /* 4 */ 20.0, /* 5 */ 17.0, /* 6 */ 15.0, /* 7 */ 10.0, /* 8 */ 7.0, /* 9 */ 4.4, /* 10 */ 4.5, 4.5, 4.5, 4.5, 4.5, 4.5, 4.5, 4.5, 4.5, 4.5, 4.5, 4.5, 4.5, 4.5, 4.5, /* 11 - 25 */ 3.5 /* 26 */ }; /* Table covers angles from 0 to TRIGTABLESIZE/TRIGTABLESCALE (3.142) radians In steps of 1/TRIGTABLESCALE (0.0005) radians. Largest absolute error: 0.0005 Only create a table for cos, and then use trig to work out sin. sin(theta) = cos(PI/2 - theta) MFC March 2003 */ static void psycho_4_trigtable_init(psycho_4_mem * p4mem) { int i; for (i = 0; i < TRIGTABLESIZE; i++) { p4mem->cos_table[i] = cos((FLOAT) i / TRIGTABLESCALE); } } #ifdef NEWTAN static inline FLOAT psycho_4_cos(psycho_4_mem * p4mem, FLOAT phi) { int index; int sign = 1; index = (int) (fabs(phi) * TRIGTABLESCALE); while (index >= TRIGTABLESIZE) { /* If we're larger than PI, then subtract PI until we aren't each time the sign will flip - Year 11 trig again. MFC March 2003 */ index -= TRIGTABLESIZE; sign *= -1; } return (sign * p4mem->cos_table[index]); } #endif /* The spreading function. Values returned in units of energy Argument 'bark' is the difference in bark values between the centre of two partitions. This has been taken from LAME. MFC Feb 2003 */ static FLOAT psycho_4_spreading_function(FLOAT bark) { FLOAT tempx, x, tempy, temp; tempx = bark; #ifdef LAME /* MP3 standard actually spreads these values a little more */ if (tempx >= 0) tempx *= 3; else tempx *= 1.5; #endif if (tempx >= 0.5 && tempx <= 2.5) { temp = tempx - 0.5; x = 8.0 * (temp * temp - 2.0 * temp); } else x = 0.0; tempx += 0.474; tempy = 15.811389 + 7.5 * tempx - 17.5 * sqrt(1.0 + tempx * tempx); if (tempy <= -60.0) return 0.0; tempx = exp((x + tempy) * LN_TO_LOG10); #ifdef LAME /* I'm not sure where the magic value of 0.6609193 comes from. twolame will just keep using the rnorm to normalise the spreading function MFC Feb 2003 */ /* Normalization. The spreading function should be normalized so that: +inf / | s3 [ bark ] d(bark) = 1 / -inf */ tempx /= .6609193; #endif return tempx; } /******************************** * init psycho model 2 ********************************/ static psycho_4_mem *twolame_psycho_4_init(twolame_options * glopts, int sfreq) { psycho_4_mem *mem; FLOAT *cbval, *rnorm; FLOAT *window; FLOAT bark[HBLKSIZE], *ath; int *numlines; int *partition; FCB *s; FLOAT *tmn; int i, j; { mem = (psycho_4_mem *) TWOLAME_MALLOC(sizeof(psycho_4_mem)); mem->tmn = (FLOAT *) TWOLAME_MALLOC(sizeof(DCB)); mem->s = (FCB *) TWOLAME_MALLOC(sizeof(FCBCB)); mem->lthr = (FHBLK *) TWOLAME_MALLOC(sizeof(F2HBLK)); mem->r = (F2HBLK *) TWOLAME_MALLOC(sizeof(F22HBLK)); mem->phi_sav = (F2HBLK *) TWOLAME_MALLOC(sizeof(F22HBLK)); mem->new = 0; mem->old = 1; mem->oldest = 0; } { cbval = mem->cbval; rnorm = mem->rnorm; window = mem->window; // bark = mem->bark; ath = mem->ath; numlines = mem->numlines; partition = mem->partition; s = mem->s; tmn = mem->tmn; } /* Set up the SIN/COS tables */ psycho_4_trigtable_init(mem); /* calculate HANN window coefficients */ for (i = 0; i < BLKSIZE; i++) window[i] = 0.5 * (1 - cos(2.0 * PI * (i - 0.5) / BLKSIZE)); /* For each FFT line from 0(DC) to 512(Nyquist) calculate - bark : the bark value of this fft line - ath : the absolute threshold of hearing for this line [ATH] Since it is a 1024 point FFT, each line in the fft corresponds to 1/1024 of the total frequency. Line 0 should correspond to DC - which doesn't really have a ATH afaik Line 1 should be 1/1024th of the Sampling Freq Line 512 should be the nyquist freq */ for (i = 0; i < HBLKSIZE; i++) { FLOAT freq = i * (FLOAT) sfreq / (FLOAT) BLKSIZE; bark[i] = twolame_ath_freq2bark(freq); /* The ath tables in the dist10 code seem to be a little out of kilter. they seem to start with index 0 corresponding to (sampling freq)/1024. When in doubt, i'm going to assume that the dist10 code is wrong. MFC Feb2003 */ ath[i] = twolame_ath_energy(freq, glopts->athlevel); // fprintf(stderr,"%.2f ",ath[i]); } /* Work out the partitions Starting from line 0, all lines within 0.33 of the starting bark are added to the same partition. When a line is greater by 0.33 of a bark, start a new partition. */ { int partition_count = 0; /* keep a count of the partitions */ int cbase = 0; /* current base index for the bark range calculation */ for (i = 0; i < HBLKSIZE; i++) { if ((bark[i] - bark[cbase]) > 0.33) { /* 1/3 critical band? */ /* this frequency line is too different from the starting line, (in terms of the bark distance) so close that previous partition, and make this line the first member of the next partition */ cbase = i; /* Start the new partition from this frequency */ partition_count++; } /* partition[i] tells us which partition the i'th frequency line is in */ partition[i] = partition_count; /* keep a count of how many frequency lines are in each partition */ numlines[partition_count]++; } } /* For each partition within the frequency space, calculate the average bark value - cbval [central bark value] */ for (i = 0; i < HBLKSIZE; i++) cbval[partition[i]] += bark[i]; /* sum up all the bark values */ for (i = 0; i < CBANDS; i++) { if (numlines[i] != 0) cbval[i] /= numlines[i]; /* divide by the number of values */ else { cbval[i] = 0; /* this isn't a partition */ } } /* Calculate the spreading function. ISO 11172 Section D.2.3 */ for (i = 0; i < CBANDS; i++) { for (j = 0; j < CBANDS; j++) { s[i][j] = psycho_4_spreading_function(1.05 * (cbval[i] - cbval[j])); rnorm[i] += s[i][j]; /* sum the spreading function values for each partition so that they can be normalised later on */ } } /* Calculate Tone Masking Noise values. ISO 11172 Tables D.3.x */ for (j = 0; j < CBANDS; j++) tmn[j] = MAX(15.5 + cbval[j], 24.5); if (glopts->verbosity > 6) { /* Dump All the Values to STDERR */ int wlow, whigh = 0; int ntot = 0; fprintf(stderr, "psy model 4 init\n"); fprintf(stderr, "index \tnlines \twlow \twhigh \tbval \tminval \ttmn\n"); for (i = 0; i < CBANDS; i++) if (numlines[i] != 0) { wlow = whigh + 1; whigh = wlow + numlines[i] - 1; fprintf(stderr, "%i \t%i \t%i \t%i \t%5.2f \t%4.2f \t%4.2f\n", i + 1, numlines[i], wlow, whigh, cbval[i], minval[(int) cbval[i]], tmn[i]); ntot += numlines[i]; } fprintf(stderr, "total lines %i\n", ntot); } return (mem); } void twolame_psycho_4(twolame_options * glopts, short int buffer[2][1152], short int savebuf[2][1056], FLOAT smr[2][32]) /* to match prototype : FLOAT args are always FLOAT */ { psycho_4_mem *mem; unsigned int run, i, j, k, ch; FLOAT r_prime, phi_prime; FLOAT npart, epart; int new, old, oldest; FLOAT *grouped_c, *grouped_e; FLOAT *nb, *cb, *tb, *ecb, *bc; FLOAT *cbval, *rnorm; FLOAT *wsamp_r, *phi, *energy, *window; FLOAT *ath, *thr, *c; FLOAT *snrtmp[2]; int *numlines; int *partition; FLOAT *tmn; FCB *s; F2HBLK *r, *phi_sav; int nch = glopts->num_channels_out; int sfreq = glopts->samplerate_out; if (!glopts->p4mem) { glopts->p4mem = twolame_psycho_4_init(glopts, sfreq); } mem = glopts->p4mem; { grouped_c = mem->grouped_c; grouped_e = mem->grouped_e; nb = mem->nb; cb = mem->cb; tb = mem->tb; ecb = mem->ecb; bc = mem->bc; rnorm = mem->rnorm; cbval = mem->cbval; wsamp_r = mem->wsamp_r; phi = mem->phi; energy = mem->energy; window = mem->window; ath = mem->ath; thr = mem->thr; c = mem->c; snrtmp[0] = mem->snrtmp[0]; snrtmp[1] = mem->snrtmp[1]; numlines = mem->numlines; partition = mem->partition; tmn = mem->tmn; s = mem->s; r = mem->r; phi_sav = mem->phi_sav; } for (ch = 0; ch < nch; ch++) { for (run = 0; run < 2; run++) { /* Net offset is 480 samples (1056-576) for layer 2; this is because one must stagger input data by 256 samples to synchronize psychoacoustic model with filter bank outputs, then stagger so that center of 1024 FFT window lines up with center of 576 "new" audio samples. flush = 384*3.0/2.0; = 576 syncsize = 1056; sync_flush = syncsize - flush; 480 BLKSIZE = 1024 */ { short int *bufferp = buffer[ch]; for (j = 0; j < 480; j++) { savebuf[ch][j] = savebuf[ch][j + 576]; wsamp_r[j] = window[j] * ((FLOAT) savebuf[ch][j]); } for (; j < 1024; j++) { savebuf[ch][j] = *bufferp++; wsamp_r[j] = window[j] * ((FLOAT) savebuf[ch][j]); } for (; j < 1056; j++) savebuf[ch][j] = *bufferp++; } /* Compute FFT */ twolame_psycho_2_fft(wsamp_r, energy, phi); /* calculate the unpredictability measure, given energy[f] and phi[f] (the age pointers [new/old/oldest] are reset automatically on the second pass */ { if (mem->new == 0) { mem->new = 1; mem->oldest = 1; } else { mem->new = 0; mem->oldest = 0; } if (mem->old == 0) mem->old = 1; else mem->old = 0; } old = mem->old; new = mem->new; oldest = mem->oldest; for (j = 0; j < HBLKSIZE; j++) { #ifdef NEWATAN FLOAT temp1, temp2, temp3; r_prime = 2.0 * r[ch][old][j] - r[ch][oldest][j]; phi_prime = 2.0 * phi_sav[ch][old][j] - phi_sav[ch][oldest][j]; r[ch][new][j] = sqrt((FLOAT) energy[j]); phi_sav[ch][new][j] = phi[j]; { temp1 = r[ch][new][j] * psycho_4_cos(mem, phi[j]) - r_prime * psycho_4_cos(mem, phi_prime); /* Remember your grade 11 trig? sin(theta) = cos(PI/2 - theta) */ temp2 = r[ch][new][j] * psycho_4_cos(mem, PI2 - phi[j]) - r_prime * psycho_4_cos(mem, PI2 - phi_prime); } temp3 = r[ch][new][j] + fabs((FLOAT) r_prime); if (temp3 != 0) c[j] = sqrt(temp1 * temp1 + temp2 * temp2) / temp3; else c[j] = 0; #else FLOAT temp1, temp2, temp3; r_prime = 2.0 * r[ch][old][j] - r[ch][oldest][j]; phi_prime = 2.0 * phi_sav[ch][old][j] - phi_sav[ch][oldest][j]; r[ch][new][j] = sqrt((FLOAT) energy[j]); phi_sav[ch][new][j] = phi[j]; temp1 = r[ch][new][j] * cos((FLOAT) phi[j]) - r_prime * cos((FLOAT) phi_prime); temp2 = r[ch][new][j] * sin((FLOAT) phi[j]) - r_prime * sin((FLOAT) phi_prime); temp3 = r[ch][new][j] + fabs((FLOAT) r_prime); if (temp3 != 0) c[j] = sqrt(temp1 * temp1 + temp2 * temp2) / temp3; else c[j] = 0; #endif } /* For each partition, sum all the energy in that partition - grouped_e and calculated the energy-weighted unpredictability measure - grouped_c ISO 11172 Section D.2.4.e */ for (j = 1; j < CBANDS; j++) { grouped_e[j] = 0; grouped_c[j] = 0; } grouped_e[0] = energy[0]; grouped_c[0] = energy[0] * c[0]; for (j = 1; j < HBLKSIZE; j++) { grouped_e[partition[j]] += energy[j]; grouped_c[partition[j]] += energy[j] * c[j]; } /* convolve the grouped energy-weighted unpredictability measure and the grouped energy with the spreading function ISO 11172 D.2.4.f */ for (j = 0; j < CBANDS; j++) { ecb[j] = 0; cb[j] = 0; for (k = 0; k < CBANDS; k++) { if (s[j][k] != 0.0) { ecb[j] += s[j][k] * grouped_e[k]; cb[j] += s[j][k] * grouped_c[k]; } } if (ecb[j] != 0) cb[j] = cb[j] / ecb[j]; else cb[j] = 0; } /* Convert cb to tb (the tonality index) ISO11172 SecD.2.4.g */ for (i = 0; i < CBANDS; i++) { if (cb[i] < 0.05) cb[i] = 0.05; else if (cb[i] > 0.5) cb[i] = 0.5; tb[i] = -0.301029996 - 0.434294482 * log((FLOAT) cb[i]); } /* Calculate the required SNR for each of the frequency partitions ISO 11172 Sect D.2.4.h */ for (j = 0; j < CBANDS; j++) { FLOAT SNR, SNRtemp; SNRtemp = tmn[j] * tb[j] + NMT * (1.0 - tb[j]); SNR = MAX(SNRtemp, minval[(int) cbval[j]]); bc[j] = exp((FLOAT) - SNR * LN_TO_LOG10); } /* Calculate the permissible noise energy level in each of the frequency partitions. This section used to have pre-echo control but only for LayerI ISO 11172 Sec D.2.4.k - Spread the threshold energy over FFT lines */ for (j = 0; j < CBANDS; j++) { if (rnorm[j] && numlines[j]) nb[j] = ecb[j] * bc[j] / (rnorm[j] * numlines[j]); else nb[j] = 0; } /* ISO11172 Sec D.2.4.l - thr[] the final energy threshold of audibility */ for (j = 0; j < HBLKSIZE; j++) thr[j] = MAX(nb[partition[j]], ath[j]); /* Translate the 512 threshold values to the 32 filter bands of the coder Using ISO 11172 Table D.5 and Section D.2.4.n */ for (j = 0; j < 193; j += 16) { /* WIDTH = 0 */ npart = 60802371420160.0; epart = 0.0; for (k = 0; k < 17; k++) { if (thr[j + k] < npart) npart = thr[j + k]; /* For WIDTH==0, find the minimum noise, and later multiply by the number of indexes i.e. 17 */ epart += energy[j + k]; } snrtmp[run][j / 16] = 4.342944819 * log((FLOAT) (epart / (npart * 17.0))); } for (j = 208; j < (HBLKSIZE - 1); j += 16) { /* WIDTH = 1 */ npart = 0.0; epart = 0.0; for (k = 0; k < 17; k++) { npart += thr[j + k]; /* For WIDTH==1, sum the noise */ epart += energy[j + k]; } snrtmp[run][j / 16] = 4.342944819 * log((FLOAT) (epart / npart)); } } /* Pick the maximum value of the two runs ISO 11172 Sect D.2.1 */ for (i = 0; i < 32; i++) smr[ch][i] = MAX(snrtmp[0][i], snrtmp[1][i]); } // now do other channel } void twolame_psycho_4_deinit(psycho_4_mem ** mem) { if (mem == NULL || *mem == NULL) return; TWOLAME_FREE((*mem)->tmn); TWOLAME_FREE((*mem)->s); TWOLAME_FREE((*mem)->lthr); TWOLAME_FREE((*mem)->r); TWOLAME_FREE((*mem)->phi_sav); TWOLAME_FREE((*mem)); } // vim:ts=4:sw=4:nowrap:
utf-8
1
LGPL-2+
2001-2004 Michael Cheng 2004-2018 The TwoLAME Project
mldemos-0.5.1+git.1.ee5d11f/_3rdParty/LAMP_HMM/initStateProb.h
#ifndef INITSTATEPROB_H #define INITSTATEPROB_H /* ************************************************************************ * * ************************************************************************ * File: initStateProb.h The class CInitStateProb defines operations for the initial state probabilities Pi * ************************************************************************ * Authors: Daniel DeMenthon & Marc Vuilleumier Date: 2-18-99 * ************************************************************************ * Modification Log: * ************************************************************************ * Log for new ideas: * ************************************************************************ * Language and Media Processing Center for Automation Research University of Maryland College Park, MD 20742 * ************************************************************************ * * ************************************************************************ */ //=============================================================================== class CInitStateProb{ public: CInitStateProb(int nbStates); //Addition of Simis for random and "first" initial state vectors CInitStateProb(int nbStates, int mode); CInitStateProb(std::ifstream &hmmFile, int nbStates); ~CInitStateProb(void); void Start(void); void StartIter(void); void BWSum(double *gamma); void SKMSum(int state); double EndIter(void); void End(void); int PickInitialState(void); void Print(std::ostream &outFile); inline double at(int i){return mThisPi[i];}; inline double logAt(int i){return mLogPi[i];}; private: int mN;// nb of states double *mThisPi; double *mNextPi; double *mLogPi; double *mSum; }; //=============================================================================== //=============================================================================== //=============================================================================== #endif
utf-8
1
unknown
unknown
openjdk-18-18~32ea/src/hotspot/share/utilities/ostream.cpp
/* * Copyright (c) 1997, 2021, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License version 2 only, as * published by the Free Software Foundation. * * This code is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License * version 2 for more details (a copy is included in the LICENSE file that * accompanied this code). * * You should have received a copy of the GNU General Public License version * 2 along with this work; if not, write to the Free Software Foundation, * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. * * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA * or visit www.oracle.com if you need additional information or have any * questions. * */ #include "precompiled.hpp" #include "jvm.h" #include "cds/classListWriter.hpp" #include "compiler/compileLog.hpp" #include "memory/allocation.inline.hpp" #include "oops/oop.inline.hpp" #include "runtime/arguments.hpp" #include "runtime/os.inline.hpp" #include "runtime/orderAccess.hpp" #include "runtime/safepoint.hpp" #include "runtime/vm_version.hpp" #include "utilities/defaultStream.hpp" #include "utilities/macros.hpp" #include "utilities/ostream.hpp" #include "utilities/vmError.hpp" #include "utilities/xmlstream.hpp" // Declarations of jvm methods extern "C" void jio_print(const char* s, size_t len); extern "C" int jio_printf(const char *fmt, ...); outputStream::outputStream(int width) { _width = width; _position = 0; _newlines = 0; _precount = 0; _indentation = 0; _scratch = NULL; _scratch_len = 0; } outputStream::outputStream(int width, bool has_time_stamps) { _width = width; _position = 0; _newlines = 0; _precount = 0; _indentation = 0; _scratch = NULL; _scratch_len = 0; if (has_time_stamps) _stamp.update(); } void outputStream::update_position(const char* s, size_t len) { for (size_t i = 0; i < len; i++) { char ch = s[i]; if (ch == '\n') { _newlines += 1; _precount += _position + 1; _position = 0; } else if (ch == '\t') { int tw = 8 - (_position & 7); _position += tw; _precount -= tw-1; // invariant: _precount + _position == total count } else { _position += 1; } } } // Execute a vsprintf, using the given buffer if necessary. // Return a pointer to the formatted string. const char* outputStream::do_vsnprintf(char* buffer, size_t buflen, const char* format, va_list ap, bool add_cr, size_t& result_len) { assert(buflen >= 2, "buffer too small"); const char* result; if (add_cr) buflen--; if (!strchr(format, '%')) { // constant format string result = format; result_len = strlen(result); if (add_cr && result_len >= buflen) result_len = buflen-1; // truncate } else if (format[0] == '%' && format[1] == 's' && format[2] == '\0') { // trivial copy-through format string result = va_arg(ap, const char*); result_len = strlen(result); if (add_cr && result_len >= buflen) result_len = buflen-1; // truncate } else { int required_len = os::vsnprintf(buffer, buflen, format, ap); assert(required_len >= 0, "vsnprintf encoding error"); result = buffer; if ((size_t)required_len < buflen) { result_len = required_len; } else { DEBUG_ONLY(warning("outputStream::do_vsnprintf output truncated -- buffer length is %d bytes but %d bytes are needed.", add_cr ? (int)buflen + 1 : (int)buflen, add_cr ? required_len + 2 : required_len + 1);) result_len = buflen - 1; } } if (add_cr) { if (result != buffer) { memcpy(buffer, result, result_len); result = buffer; } buffer[result_len++] = '\n'; buffer[result_len] = 0; } return result; } void outputStream::do_vsnprintf_and_write_with_automatic_buffer(const char* format, va_list ap, bool add_cr) { char buffer[O_BUFLEN]; size_t len; const char* str = do_vsnprintf(buffer, sizeof(buffer), format, ap, add_cr, len); write(str, len); } void outputStream::do_vsnprintf_and_write_with_scratch_buffer(const char* format, va_list ap, bool add_cr) { size_t len; const char* str = do_vsnprintf(_scratch, _scratch_len, format, ap, add_cr, len); write(str, len); } void outputStream::do_vsnprintf_and_write(const char* format, va_list ap, bool add_cr) { if (_scratch) { do_vsnprintf_and_write_with_scratch_buffer(format, ap, add_cr); } else { do_vsnprintf_and_write_with_automatic_buffer(format, ap, add_cr); } } void outputStream::print(const char* format, ...) { va_list ap; va_start(ap, format); do_vsnprintf_and_write(format, ap, false); va_end(ap); } void outputStream::print_cr(const char* format, ...) { va_list ap; va_start(ap, format); do_vsnprintf_and_write(format, ap, true); va_end(ap); } void outputStream::vprint(const char *format, va_list argptr) { do_vsnprintf_and_write(format, argptr, false); } void outputStream::vprint_cr(const char* format, va_list argptr) { do_vsnprintf_and_write(format, argptr, true); } void outputStream::fill_to(int col) { int need_fill = col - position(); sp(need_fill); } void outputStream::move_to(int col, int slop, int min_space) { if (position() >= col + slop) cr(); int need_fill = col - position(); if (need_fill < min_space) need_fill = min_space; sp(need_fill); } void outputStream::put(char ch) { assert(ch != 0, "please fix call site"); char buf[] = { ch, '\0' }; write(buf, 1); } #define SP_USE_TABS false void outputStream::sp(int count) { if (count < 0) return; if (SP_USE_TABS && count >= 8) { int target = position() + count; while (count >= 8) { this->write("\t", 1); count -= 8; } count = target - position(); } while (count > 0) { int nw = (count > 8) ? 8 : count; this->write(" ", nw); count -= nw; } } void outputStream::cr() { this->write("\n", 1); } void outputStream::cr_indent() { cr(); indent(); } void outputStream::stamp() { if (! _stamp.is_updated()) { _stamp.update(); // start at 0 on first call to stamp() } // outputStream::stamp() may get called by ostream_abort(), use snprintf // to avoid allocating large stack buffer in print(). char buf[40]; jio_snprintf(buf, sizeof(buf), "%.3f", _stamp.seconds()); print_raw(buf); } void outputStream::stamp(bool guard, const char* prefix, const char* suffix) { if (!guard) { return; } print_raw(prefix); stamp(); print_raw(suffix); } void outputStream::date_stamp(bool guard, const char* prefix, const char* suffix) { if (!guard) { return; } print_raw(prefix); static const char error_time[] = "yyyy-mm-ddThh:mm:ss.mmm+zzzz"; static const int buffer_length = 32; char buffer[buffer_length]; const char* iso8601_result = os::iso8601_time(buffer, buffer_length); if (iso8601_result != NULL) { print_raw(buffer); } else { print_raw(error_time); } print_raw(suffix); return; } outputStream& outputStream::indent() { while (_position < _indentation) sp(); return *this; } void outputStream::print_jlong(jlong value) { print(JLONG_FORMAT, value); } void outputStream::print_julong(julong value) { print(JULONG_FORMAT, value); } /** * This prints out hex data in a 'windbg' or 'xxd' form, where each line is: * <hex-address>: 8 * <hex-halfword> <ascii translation (optional)> * example: * 0000000: 7f44 4f46 0102 0102 0000 0000 0000 0000 .DOF............ * 0000010: 0000 0000 0000 0040 0000 0020 0000 0005 .......@... .... * 0000020: 0000 0000 0000 0040 0000 0000 0000 015d .......@.......] * ... * * indent is applied to each line. Ends with a CR. */ void outputStream::print_data(void* data, size_t len, bool with_ascii) { size_t limit = (len + 16) / 16 * 16; for (size_t i = 0; i < limit; ++i) { if (i % 16 == 0) { indent().print(INTPTR_FORMAT_W(07) ":", i); } if (i % 2 == 0) { print(" "); } if (i < len) { print("%02x", ((unsigned char*)data)[i]); } else { print(" "); } if ((i + 1) % 16 == 0) { if (with_ascii) { print(" "); for (size_t j = 0; j < 16; ++j) { size_t idx = i + j - 15; if (idx < len) { char c = ((char*)data)[idx]; print("%c", c >= 32 && c <= 126 ? c : '.'); } } } cr(); } } } stringStream::stringStream(size_t initial_capacity) : outputStream(), _buffer(_small_buffer), _written(0), _capacity(sizeof(_small_buffer)), _is_fixed(false) { if (initial_capacity > _capacity) { grow(initial_capacity); } zero_terminate(); } // useful for output to fixed chunks of memory, such as performance counters stringStream::stringStream(char* fixed_buffer, size_t fixed_buffer_size) : outputStream(), _buffer(fixed_buffer), _written(0), _capacity(fixed_buffer_size), _is_fixed(true) { zero_terminate(); } // Grow backing buffer to desired capacity. Don't call for fixed buffers void stringStream::grow(size_t new_capacity) { assert(!_is_fixed, "Don't call for caller provided buffers"); assert(new_capacity > _capacity, "Sanity"); assert(new_capacity > sizeof(_small_buffer), "Sanity"); if (_buffer == _small_buffer) { _buffer = NEW_C_HEAP_ARRAY(char, new_capacity, mtInternal); _capacity = new_capacity; if (_written > 0) { ::memcpy(_buffer, _small_buffer, _written); } zero_terminate(); } else { _buffer = REALLOC_C_HEAP_ARRAY(char, _buffer, new_capacity, mtInternal); _capacity = new_capacity; } } void stringStream::write(const char* s, size_t len) { assert(_capacity >= _written + 1, "Sanity"); if (len == 0) { return; } const size_t reasonable_max_len = 1 * G; if (len >= reasonable_max_len) { assert(false, "bad length? (" SIZE_FORMAT ")", len); return; } size_t write_len = 0; if (_is_fixed) { write_len = MIN2(len, _capacity - _written - 1); } else { write_len = len; size_t needed = _written + len + 1; if (needed > _capacity) { grow(MAX2(needed, _capacity * 2)); } } assert(_written + write_len + 1 <= _capacity, "stringStream oob"); if (write_len > 0) { ::memcpy(_buffer + _written, s, write_len); _written += write_len; zero_terminate(); } // Note that the following does not depend on write_len. // This means that position and count get updated // even when overflow occurs. update_position(s, len); } void stringStream::zero_terminate() { assert(_buffer != NULL && _written < _capacity, "sanity"); _buffer[_written] = '\0'; } void stringStream::reset() { _written = 0; _precount = 0; _position = 0; _newlines = 0; zero_terminate(); } char* stringStream::as_string(bool c_heap) const { char* copy = c_heap ? NEW_C_HEAP_ARRAY(char, _written + 1, mtInternal) : NEW_RESOURCE_ARRAY(char, _written + 1); ::memcpy(copy, _buffer, _written); copy[_written] = 0; // terminating null if (c_heap) { // Need to ensure our content is written to memory before we return // the pointer to it. OrderAccess::storestore(); } return copy; } stringStream::~stringStream() { if (!_is_fixed && _buffer != _small_buffer) { FREE_C_HEAP_ARRAY(char, _buffer); } } xmlStream* xtty; outputStream* tty; extern Mutex* tty_lock; #define EXTRACHARLEN 32 #define CURRENTAPPX ".current" // convert YYYY-MM-DD HH:MM:SS to YYYY-MM-DD_HH-MM-SS char* get_datetime_string(char *buf, size_t len) { os::local_time_string(buf, len); int i = (int)strlen(buf); while (--i >= 0) { if (buf[i] == ' ') buf[i] = '_'; else if (buf[i] == ':') buf[i] = '-'; } return buf; } static const char* make_log_name_internal(const char* log_name, const char* force_directory, int pid, const char* tms) { const char* basename = log_name; char file_sep = os::file_separator()[0]; const char* cp; char pid_text[32]; for (cp = log_name; *cp != '\0'; cp++) { if (*cp == '/' || *cp == file_sep) { basename = cp + 1; } } const char* nametail = log_name; // Compute buffer length size_t buffer_length; if (force_directory != NULL) { buffer_length = strlen(force_directory) + strlen(os::file_separator()) + strlen(basename) + 1; } else { buffer_length = strlen(log_name) + 1; } const char* pts = strstr(basename, "%p"); int pid_pos = (pts == NULL) ? -1 : (pts - nametail); if (pid_pos >= 0) { jio_snprintf(pid_text, sizeof(pid_text), "pid%u", pid); buffer_length += strlen(pid_text); } pts = strstr(basename, "%t"); int tms_pos = (pts == NULL) ? -1 : (pts - nametail); if (tms_pos >= 0) { buffer_length += strlen(tms); } // File name is too long. if (buffer_length > JVM_MAXPATHLEN) { return NULL; } // Create big enough buffer. char *buf = NEW_C_HEAP_ARRAY(char, buffer_length, mtInternal); strcpy(buf, ""); if (force_directory != NULL) { strcat(buf, force_directory); strcat(buf, os::file_separator()); nametail = basename; // completely skip directory prefix } // who is first, %p or %t? int first = -1, second = -1; const char *p1st = NULL; const char *p2nd = NULL; if (pid_pos >= 0 && tms_pos >= 0) { // contains both %p and %t if (pid_pos < tms_pos) { // case foo%pbar%tmonkey.log first = pid_pos; p1st = pid_text; second = tms_pos; p2nd = tms; } else { // case foo%tbar%pmonkey.log first = tms_pos; p1st = tms; second = pid_pos; p2nd = pid_text; } } else if (pid_pos >= 0) { // contains %p only first = pid_pos; p1st = pid_text; } else if (tms_pos >= 0) { // contains %t only first = tms_pos; p1st = tms; } int buf_pos = (int)strlen(buf); const char* tail = nametail; if (first >= 0) { tail = nametail + first + 2; strncpy(&buf[buf_pos], nametail, first); strcpy(&buf[buf_pos + first], p1st); buf_pos = (int)strlen(buf); if (second >= 0) { strncpy(&buf[buf_pos], tail, second - first - 2); strcpy(&buf[buf_pos + second - first - 2], p2nd); tail = nametail + second + 2; } } strcat(buf, tail); // append rest of name, or all of name return buf; } // log_name comes from -XX:LogFile=log_name or // -XX:DumpLoadedClassList=<file_name> // in log_name, %p => pid1234 and // %t => YYYY-MM-DD_HH-MM-SS const char* make_log_name(const char* log_name, const char* force_directory) { char timestr[32]; get_datetime_string(timestr, sizeof(timestr)); return make_log_name_internal(log_name, force_directory, os::current_process_id(), timestr); } fileStream::fileStream(const char* file_name) { _file = fopen(file_name, "w"); if (_file != NULL) { _need_close = true; } else { warning("Cannot open file %s due to %s\n", file_name, os::strerror(errno)); _need_close = false; } } fileStream::fileStream(const char* file_name, const char* opentype) { _file = fopen(file_name, opentype); if (_file != NULL) { _need_close = true; } else { warning("Cannot open file %s due to %s\n", file_name, os::strerror(errno)); _need_close = false; } } void fileStream::write(const char* s, size_t len) { if (_file != NULL) { // Make an unused local variable to avoid warning from gcc compiler. size_t count = fwrite(s, 1, len, _file); update_position(s, len); } } long fileStream::fileSize() { long size = -1; if (_file != NULL) { long pos = ::ftell(_file); if (pos < 0) return pos; if (::fseek(_file, 0, SEEK_END) == 0) { size = ::ftell(_file); } ::fseek(_file, pos, SEEK_SET); } return size; } char* fileStream::readln(char *data, int count ) { char * ret = NULL; if (_file != NULL) { ret = ::fgets(data, count, _file); // Get rid of annoying \n char only if it is present. size_t len = ::strlen(data); if (len > 0 && data[len - 1] == '\n') { data[len - 1] = '\0'; } } return ret; } fileStream::~fileStream() { if (_file != NULL) { if (_need_close) fclose(_file); _file = NULL; } } void fileStream::flush() { if (_file != NULL) { fflush(_file); } } void fdStream::write(const char* s, size_t len) { if (_fd != -1) { // Make an unused local variable to avoid warning from gcc compiler. size_t count = ::write(_fd, s, (int)len); update_position(s, len); } } defaultStream* defaultStream::instance = NULL; int defaultStream::_output_fd = 1; int defaultStream::_error_fd = 2; FILE* defaultStream::_output_stream = stdout; FILE* defaultStream::_error_stream = stderr; #define LOG_MAJOR_VERSION 160 #define LOG_MINOR_VERSION 1 void defaultStream::init() { _inited = true; if (LogVMOutput || LogCompilation) { init_log(); } } bool defaultStream::has_log_file() { // lazily create log file (at startup, LogVMOutput is false even // if +LogVMOutput is used, because the flags haven't been parsed yet) // For safer printing during fatal error handling, do not init logfile // if a VM error has been reported. if (!_inited && !VMError::is_error_reported()) init(); return _log_file != NULL; } fileStream* defaultStream::open_file(const char* log_name) { const char* try_name = make_log_name(log_name, NULL); if (try_name == NULL) { warning("Cannot open file %s: file name is too long.\n", log_name); return NULL; } fileStream* file = new(ResourceObj::C_HEAP, mtInternal) fileStream(try_name); FREE_C_HEAP_ARRAY(char, try_name); if (file->is_open()) { return file; } // Try again to open the file in the temp directory. delete file; // Note: This feature is for maintainer use only. No need for L10N. jio_printf("Warning: Cannot open log file: %s\n", log_name); try_name = make_log_name(log_name, os::get_temp_directory()); if (try_name == NULL) { warning("Cannot open file %s: file name is too long for directory %s.\n", log_name, os::get_temp_directory()); return NULL; } jio_printf("Warning: Forcing option -XX:LogFile=%s\n", try_name); file = new(ResourceObj::C_HEAP, mtInternal) fileStream(try_name); FREE_C_HEAP_ARRAY(char, try_name); if (file->is_open()) { return file; } delete file; return NULL; } void defaultStream::init_log() { // %%% Need a MutexLocker? const char* log_name = LogFile != NULL ? LogFile : "hotspot_%p.log"; fileStream* file = open_file(log_name); if (file != NULL) { _log_file = file; _outer_xmlStream = new(ResourceObj::C_HEAP, mtInternal) xmlStream(file); start_log(); } else { // and leave xtty as NULL LogVMOutput = false; DisplayVMOutput = true; LogCompilation = false; } } void defaultStream::start_log() { xmlStream*xs = _outer_xmlStream; if (this == tty) xtty = xs; // Write XML header. xs->print_cr("<?xml version='1.0' encoding='UTF-8'?>"); // (For now, don't bother to issue a DTD for this private format.) // Calculate the start time of the log as ms since the epoch: this is // the current time in ms minus the uptime in ms. jlong time_ms = os::javaTimeMillis() - tty->time_stamp().milliseconds(); xs->head("hotspot_log version='%d %d'" " process='%d' time_ms='" INT64_FORMAT "'", LOG_MAJOR_VERSION, LOG_MINOR_VERSION, os::current_process_id(), (int64_t)time_ms); // Write VM version header immediately. xs->head("vm_version"); xs->head("name"); xs->text("%s", VM_Version::vm_name()); xs->cr(); xs->tail("name"); xs->head("release"); xs->text("%s", VM_Version::vm_release()); xs->cr(); xs->tail("release"); xs->head("info"); xs->text("%s", VM_Version::internal_vm_info_string()); xs->cr(); xs->tail("info"); xs->tail("vm_version"); // Record information about the command-line invocation. xs->head("vm_arguments"); // Cf. Arguments::print_on() if (Arguments::num_jvm_flags() > 0) { xs->head("flags"); Arguments::print_jvm_flags_on(xs->text()); xs->tail("flags"); } if (Arguments::num_jvm_args() > 0) { xs->head("args"); Arguments::print_jvm_args_on(xs->text()); xs->tail("args"); } if (Arguments::java_command() != NULL) { xs->head("command"); xs->text()->print_cr("%s", Arguments::java_command()); xs->tail("command"); } if (Arguments::sun_java_launcher() != NULL) { xs->head("launcher"); xs->text()->print_cr("%s", Arguments::sun_java_launcher()); xs->tail("launcher"); } if (Arguments::system_properties() != NULL) { xs->head("properties"); // Print it as a java-style property list. // System properties don't generally contain newlines, so don't bother with unparsing. outputStream *text = xs->text(); for (SystemProperty* p = Arguments::system_properties(); p != NULL; p = p->next()) { assert(p->key() != NULL, "p->key() is NULL"); if (p->is_readable()) { // Print in two stages to avoid problems with long // keys/values. text->print_raw(p->key()); text->put('='); assert(p->value() != NULL, "p->value() is NULL"); text->print_raw_cr(p->value()); } } xs->tail("properties"); } xs->tail("vm_arguments"); // tty output per se is grouped under the <tty>...</tty> element. xs->head("tty"); // All further non-markup text gets copied to the tty: xs->_text = this; // requires friend declaration! } // finish_log() is called during normal VM shutdown. finish_log_on_error() is // called by ostream_abort() after a fatal error. // void defaultStream::finish_log() { xmlStream* xs = _outer_xmlStream; xs->done("tty"); // Other log forks are appended here, at the End of Time: CompileLog::finish_log(xs->out()); // write compile logging, if any, now xs->done("hotspot_log"); xs->flush(); fileStream* file = _log_file; _log_file = NULL; delete _outer_xmlStream; _outer_xmlStream = NULL; file->flush(); delete file; } void defaultStream::finish_log_on_error(char *buf, int buflen) { xmlStream* xs = _outer_xmlStream; if (xs && xs->out()) { xs->done_raw("tty"); // Other log forks are appended here, at the End of Time: CompileLog::finish_log_on_error(xs->out(), buf, buflen); // write compile logging, if any, now xs->done_raw("hotspot_log"); xs->flush(); fileStream* file = _log_file; _log_file = NULL; _outer_xmlStream = NULL; if (file) { file->flush(); // Can't delete or close the file because delete and fclose aren't // async-safe. We are about to die, so leave it to the kernel. // delete file; } } } intx defaultStream::hold(intx writer_id) { bool has_log = has_log_file(); // check before locking if (// impossible, but who knows? writer_id == NO_WRITER || // bootstrap problem tty_lock == NULL || // can't grab a lock if current Thread isn't set Thread::current_or_null() == NULL || // developer hook !SerializeVMOutput || // VM already unhealthy VMError::is_error_reported() || // safepoint == global lock (for VM only) (SafepointSynchronize::is_synchronizing() && Thread::current()->is_VM_thread()) ) { // do not attempt to lock unless we know the thread and the VM is healthy return NO_WRITER; } if (_writer == writer_id) { // already held, no need to re-grab the lock return NO_WRITER; } tty_lock->lock_without_safepoint_check(); // got the lock if (writer_id != _last_writer) { if (has_log) { _log_file->bol(); // output a hint where this output is coming from: _log_file->print_cr("<writer thread='" UINTX_FORMAT "'/>", writer_id); } _last_writer = writer_id; } _writer = writer_id; return writer_id; } void defaultStream::release(intx holder) { if (holder == NO_WRITER) { // nothing to release: either a recursive lock, or we scribbled (too bad) return; } if (_writer != holder) { return; // already unlocked, perhaps via break_tty_lock_for_safepoint } _writer = NO_WRITER; tty_lock->unlock(); } void defaultStream::write(const char* s, size_t len) { intx thread_id = os::current_thread_id(); intx holder = hold(thread_id); if (DisplayVMOutput && (_outer_xmlStream == NULL || !_outer_xmlStream->inside_attrs())) { // print to output stream. It can be redirected by a vfprintf hook jio_print(s, len); } // print to log file if (has_log_file()) { int nl0 = _newlines; xmlTextStream::write(s, len); // flush the log file too, if there were any newlines if (nl0 != _newlines){ flush(); } } else { update_position(s, len); } release(holder); } intx ttyLocker::hold_tty() { if (defaultStream::instance == NULL) return defaultStream::NO_WRITER; intx thread_id = os::current_thread_id(); return defaultStream::instance->hold(thread_id); } void ttyLocker::release_tty(intx holder) { if (holder == defaultStream::NO_WRITER) return; defaultStream::instance->release(holder); } bool ttyLocker::release_tty_if_locked() { intx thread_id = os::current_thread_id(); if (defaultStream::instance->writer() == thread_id) { // release the lock and return true so callers know if was // previously held. release_tty(thread_id); return true; } return false; } void ttyLocker::break_tty_lock_for_safepoint(intx holder) { if (defaultStream::instance != NULL && defaultStream::instance->writer() == holder) { if (xtty != NULL) { xtty->print_cr("<!-- safepoint while printing -->"); } defaultStream::instance->release(holder); } // (else there was no lock to break) } void ostream_init() { if (defaultStream::instance == NULL) { defaultStream::instance = new(ResourceObj::C_HEAP, mtInternal) defaultStream(); tty = defaultStream::instance; // We want to ensure that time stamps in GC logs consider time 0 // the time when the JVM is initialized, not the first time we ask // for a time stamp. So, here, we explicitly update the time stamp // of tty. tty->time_stamp().update_to(1); } } void ostream_init_log() { // Note : this must be called AFTER ostream_init() ClassListWriter::init(); // If we haven't lazily initialized the logfile yet, do it now, // to avoid the possibility of lazy initialization during a VM // crash, which can affect the stability of the fatal error handler. defaultStream::instance->has_log_file(); } // ostream_exit() is called during normal VM exit to finish log files, flush // output and free resource. void ostream_exit() { static bool ostream_exit_called = false; if (ostream_exit_called) return; ostream_exit_called = true; ClassListWriter::delete_classlist(); if (tty != defaultStream::instance) { delete tty; } if (defaultStream::instance != NULL) { delete defaultStream::instance; } tty = NULL; xtty = NULL; defaultStream::instance = NULL; } // ostream_abort() is called by os::abort() when VM is about to die. void ostream_abort() { // Here we can't delete tty, just flush its output if (tty) tty->flush(); if (defaultStream::instance != NULL) { static char buf[4096]; defaultStream::instance->finish_log_on_error(buf, sizeof(buf)); } } bufferedStream::bufferedStream(size_t initial_size, size_t bufmax) : outputStream() { buffer_length = initial_size; buffer = NEW_C_HEAP_ARRAY(char, buffer_length, mtInternal); buffer_pos = 0; buffer_fixed = false; buffer_max = bufmax; truncated = false; } bufferedStream::bufferedStream(char* fixed_buffer, size_t fixed_buffer_size, size_t bufmax) : outputStream() { buffer_length = fixed_buffer_size; buffer = fixed_buffer; buffer_pos = 0; buffer_fixed = true; buffer_max = bufmax; truncated = false; } void bufferedStream::write(const char* s, size_t len) { if (truncated) { return; } if(buffer_pos + len > buffer_max) { flush(); // Note: may be a noop. } size_t end = buffer_pos + len; if (end >= buffer_length) { if (buffer_fixed) { // if buffer cannot resize, silently truncate len = buffer_length - buffer_pos - 1; truncated = true; } else { // For small overruns, double the buffer. For larger ones, // increase to the requested size. if (end < buffer_length * 2) { end = buffer_length * 2; } // Impose a cap beyond which the buffer cannot grow - a size which // in all probability indicates a real error, e.g. faulty printing // code looping, while not affecting cases of just-very-large-but-its-normal // output. const size_t reasonable_cap = MAX2(100 * M, buffer_max * 2); if (end > reasonable_cap) { // In debug VM, assert right away. assert(false, "Exceeded max buffer size for this string."); // Release VM: silently truncate. We do this since these kind of errors // are both difficult to predict with testing (depending on logging content) // and usually not serious enough to kill a production VM for it. end = reasonable_cap; size_t remaining = end - buffer_pos; if (len >= remaining) { len = remaining - 1; truncated = true; } } if (buffer_length < end) { buffer = REALLOC_C_HEAP_ARRAY(char, buffer, end, mtInternal); buffer_length = end; } } } if (len > 0) { memcpy(buffer + buffer_pos, s, len); buffer_pos += len; update_position(s, len); } } char* bufferedStream::as_string() { char* copy = NEW_RESOURCE_ARRAY(char, buffer_pos+1); strncpy(copy, buffer, buffer_pos); copy[buffer_pos] = 0; // terminating null return copy; } bufferedStream::~bufferedStream() { if (!buffer_fixed) { FREE_C_HEAP_ARRAY(char, buffer); } } #ifndef PRODUCT #if defined(LINUX) || defined(AIX) || defined(_ALLBSD_SOURCE) #include <sys/types.h> #include <sys/socket.h> #include <netinet/in.h> #include <arpa/inet.h> #elif defined(_WINDOWS) #include <winsock2.h> #endif // Network access networkStream::networkStream() : bufferedStream(1024*10, 1024*10) { _socket = -1; int result = os::socket(AF_INET, SOCK_STREAM, 0); if (result <= 0) { assert(false, "Socket could not be created!"); } else { _socket = result; } } int networkStream::read(char *buf, size_t len) { return os::recv(_socket, buf, (int)len, 0); } void networkStream::flush() { if (size() != 0) { int result = os::raw_send(_socket, (char *)base(), size(), 0); assert(result != -1, "connection error"); assert(result == (int)size(), "didn't send enough data"); } reset(); } networkStream::~networkStream() { close(); } void networkStream::close() { if (_socket != -1) { flush(); os::socket_close(_socket); _socket = -1; } } bool networkStream::connect(const char *ip, short port) { struct sockaddr_in server; server.sin_family = AF_INET; server.sin_port = htons(port); server.sin_addr.s_addr = inet_addr(ip); if (server.sin_addr.s_addr == (uint32_t)-1) { struct hostent* host = os::get_host_by_name((char*)ip); if (host != NULL) { memcpy(&server.sin_addr, host->h_addr_list[0], host->h_length); } else { return false; } } int result = os::connect(_socket, (struct sockaddr*)&server, sizeof(struct sockaddr_in)); return (result >= 0); } #endif
utf-8
1
unknown
unknown
colmap-3.7/src/ui/thread_control_widget.cc
// Copyright (c) 2018, ETH Zurich and UNC Chapel Hill. // 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 ETH Zurich and UNC Chapel Hill 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 HOLDERS 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. // // Author: Johannes L. Schoenberger (jsch-at-demuc-dot-de) #include "ui/bundle_adjustment_widget.h" namespace colmap { ThreadControlWidget::ThreadControlWidget(QWidget* parent) : QWidget(parent), progress_bar_(nullptr), destructor_(new QAction(this)), thread_(nullptr) { connect(destructor_, &QAction::triggered, this, [this]() { if (thread_) { thread_->Stop(); thread_->Wait(); thread_.reset(); } if (progress_bar_ != nullptr) { progress_bar_->hide(); } }); } void ThreadControlWidget::StartThread(const QString& progress_text, const bool stoppable, Thread* thread) { CHECK(!thread_); CHECK_NOTNULL(thread); thread_.reset(thread); if (progress_bar_ == nullptr) { progress_bar_ = new QProgressDialog(this); progress_bar_->setWindowModality(Qt::ApplicationModal); progress_bar_->setWindowFlags(Qt::Dialog | Qt::WindowTitleHint | Qt::CustomizeWindowHint); // Use a single space to clear the window title on Windows, otherwise it // will contain the name of the executable. progress_bar_->setWindowTitle(" "); progress_bar_->setLabel(new QLabel(this)); progress_bar_->setMaximum(0); progress_bar_->setMinimum(0); progress_bar_->setValue(0); connect(progress_bar_, &QProgressDialog::canceled, [this]() { destructor_->trigger(); }); } // Enable the cancel button if the thread is stoppable. QPushButton* cancel_button = progress_bar_->findChildren<QPushButton*>().at(0); cancel_button->setEnabled(stoppable); progress_bar_->setLabelText(progress_text); // Center the progress bar wrt. the parent widget. const QPoint global = parentWidget()->mapToGlobal(parentWidget()->rect().center()); progress_bar_->move(global.x() - progress_bar_->width() / 2, global.y() - progress_bar_->height() / 2); progress_bar_->show(); progress_bar_->raise(); thread_->AddCallback(Thread::FINISHED_CALLBACK, [this]() { destructor_->trigger(); }); thread_->Start(); } void ThreadControlWidget::StartFunction(const QString& progress_text, const std::function<void()>& func) { class FunctionThread : public Thread { public: explicit FunctionThread(const std::function<void()>& f) : func_(f) {} private: void Run() { func_(); } const std::function<void()> func_; }; StartThread(progress_text, false, new FunctionThread(func)); } } // namespace colmap
utf-8
1
BSD-3-clause-special
2018-2022 ETH Zurich and UNC Chapel Hill. All rights reserved. 2016-2022 Johannes Schönberger <jsch@demuc.de> 2016-2017 Lutz and Frahm 2016-2017 Jan-Michael
insighttoolkit4-4.13.3withdata-dfsg2/Modules/Video/Filtering/include/itkFrameDifferenceVideoFilter.hxx
/*========================================================================= * * Copyright Insight Software Consortium * * 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.txt * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * *=========================================================================*/ #ifndef itkFrameDifferenceVideoFilter_hxx #define itkFrameDifferenceVideoFilter_hxx #include "itkFrameDifferenceVideoFilter.h" #include "itkImageRegionConstIterator.h" #include "itkImageRegionIterator.h" #include "itkNumericTraits.h" namespace itk { // // Constructor // template<typename TInputVideoStream, typename TOutputVideoStream> FrameDifferenceVideoFilter<TInputVideoStream, TOutputVideoStream>:: FrameDifferenceVideoFilter() { // Default to differencing adjacent frames this->TemporalProcessObject::m_UnitInputNumberOfFrames = 2; // Always output one frame this->TemporalProcessObject::m_UnitOutputNumberOfFrames = 1; // Use the frame number of the last frame in the stencil this->TemporalProcessObject::m_InputStencilCurrentFrameIndex = 0; // Move forward one frame of input for every frame of output this->TemporalProcessObject::m_FrameSkipPerOutput = 1; } // // PrintSelf // template<typename TInputVideoStream, typename TOutputVideoStream> void FrameDifferenceVideoFilter<TInputVideoStream, TOutputVideoStream>:: PrintSelf(std::ostream & os, Indent indent) const { Superclass::PrintSelf(os, indent); os << indent << "FrameOffset: " << this->TemporalProcessObject::m_UnitInputNumberOfFrames - 1 << std::endl; } // // SetFrameOffset // template<typename TInputVideoStream, typename TOutputVideoStream> void FrameDifferenceVideoFilter<TInputVideoStream, TOutputVideoStream>:: SetFrameOffset(SizeValueType numFrames) { // Expand the input stencil this->TemporalProcessObject::m_UnitInputNumberOfFrames = numFrames + 1; // Mark modified this->Modified(); } // // GetFrameOffset // template<typename TInputVideoStream, typename TOutputVideoStream> SizeValueType FrameDifferenceVideoFilter<TInputVideoStream, TOutputVideoStream>:: GetFrameOffset() { return this->TemporalProcessObject::m_UnitInputNumberOfFrames - 1; } // // ThreadedGenerateData // template<typename TInputVideoStream, typename TOutputVideoStream> void FrameDifferenceVideoFilter<TInputVideoStream, TOutputVideoStream>:: ThreadedGenerateData(const OutputFrameSpatialRegionType& outputRegionForThread, int itkNotUsed(threadId)) { // Get the input and output video streams const InputVideoStreamType* input = this->GetInput(); OutputVideoStreamType* output = this->GetOutput(); SizeValueType numFrames = this->TemporalProcessObject::m_UnitInputNumberOfFrames; // Get output frame number typename OutputVideoStreamType::TemporalRegionType outReqTempRegion = output->GetRequestedTemporalRegion(); SizeValueType outputFrameNumber = outReqTempRegion.GetFrameStart(); typename InputVideoStreamType::TemporalRegionType inReqTempRegion = input->GetRequestedTemporalRegion(); SizeValueType inputStart = inReqTempRegion.GetFrameStart(); SizeValueType inputDuration = inReqTempRegion.GetFrameDuration(); // Make sure we've got the right duration if (inputDuration != numFrames) { itkExceptionMacro("Incorrect number of input frames"); } // Get iterators for the input frames typedef ImageRegionConstIterator<InputFrameType> ConstIterType; OutputFrameSpatialRegionType inputRegion; inputRegion.SetSize(outputRegionForThread.GetSize()); inputRegion.SetIndex(outputRegionForThread.GetIndex()); ConstIterType I0Iter(input->GetFrame(inputStart), inputRegion); ConstIterType I1Iter(input->GetFrame(inputStart + numFrames - 1), inputRegion); // Get the output frame and its iterator OutputFrameType* outFrame = output->GetFrame(outputFrameNumber); itk::ImageRegionIterator<OutputFrameType> outIter(outFrame, outputRegionForThread); // Average the input frames at each pixel of the output region typedef typename NumericTraits<InputPixelType>::RealType InputPixelRealType; while(!outIter.IsAtEnd()) { // Compute the signed difference as a real value InputPixelRealType val = static_cast<InputPixelRealType>(I0Iter.Get()) - static_cast<InputPixelRealType>(I1Iter.Get()); // Square it val *= val; // Set the output outIter.Set(static_cast<OutputPixelType>(val)); // Update the iterators ++outIter; ++I0Iter; ++I1Iter; } } } // end namespace itk #endif
utf-8
1
unknown
unknown