text
stringlengths 5
1.04M
|
|---|
//
// Created by brani on 20.02.20.
//
#ifndef MARCHING_CUBES_VISUALIZER_HPP
#define MARCHING_CUBES_VISUALIZER_HPP
#include "data_holder.h"
class Visualizer {
private:
DataHolder &data_holder;
public:
explicit Visualizer(DataHolder &holder): data_holder(holder) {
}
void showSliceZ(int z, int duration);
void showSliceX(int x, int duration);
void showSliceY(int y, int duration);
};
#endif //MARCHING_CUBES_VISUALIZER_HPP
|
#include <bits/stdc++.h>
using namespace std;
struct Node {
int h, dis, cnt;
bool vis;
} nodes[100010];
struct Edge {
int to, nex, w;
} edges[400010];
int n, m, t, w, cnt;
int read() {
int ret, f = 1;
char ch;
while(!isdigit(ch = getchar())) (ch == '-') && (f = -1);
for(ret = ch - '0'; isdigit(ch = getchar()); ret *= 10, ret += ch - '0');
return ret * f;
}
void print(int x) {
if(x < 0) putchar('-'), x = -x;
if(x > 9) print(x / 10);
putchar(x % 10 + '0');
}
void addedge(int u, int v, int w) {
edges[++cnt] = (Edge){v, nodes[u].h, w};
nodes[u].h = cnt;
}
bool spfa(int start) {
queue<int > q; q.push(start);
nodes[start].dis = 0, nodes[start].vis = 1, ++nodes[start].cnt;
while(!q.empty()) {
int u = q.front();
q.pop();
nodes[u].vis = 0;
for(int i = nodes[u].h; i; i = edges[i].nex) {
int v = edges[i].to;
if(nodes[v].dis > nodes[u].dis + edges[i].w) {
nodes[v].dis = nodes[u].dis + edges[i].w;
if(!nodes[v].vis) {
nodes[v].vis = 1, ++nodes[v].cnt;
if(nodes[v].cnt == n) return 1;
q.push(v);
}
}
}
}
return 0;
}
void work() {
n = read(), m = read(), w = read(), cnt = 0;
for(int i = 1; i <= n; ++i) nodes[i] = (Node){0, (int)1e9 + 7, 0, 0};
for(int i = 1; i <= m; ++i) {
int u = read(), v = read(), w = read();
addedge(u, v, w);
addedge(v, u, w);
}
for(int i = 1; i <= w; ++i) {
int u = read(), v = read(), w = read();
addedge(u, v, -w);
}
printf("%s\n", spfa(1) ? "YES" : "NO");
return ;
}
int main() {
t = read();
while(t--) work();
return 0;
}
|
// Copyright (c) 2012-2015 The Bitcoin Core developers
// Distributed under the MIT software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
#include "wallet/wallet.h"
#include <set>
#include <stdint.h>
#include <utility>
#include <vector>
#include "test/test_smilecoin.h"
#include <boost/foreach.hpp>
#include <boost/test/unit_test.hpp>
// how many times to run all the tests to have a chance to catch errors that only show up with particular random shuffles
#define RUN_TESTS 100
// some tests fail 1% of the time due to bad luck.
// we repeat those tests this many times and only complain if all iterations of the test fail
#define RANDOM_REPEATS 5
using namespace std;
typedef set<pair<const CWalletTx*,unsigned int> > CoinSet;
BOOST_FIXTURE_TEST_SUITE(wallet_tests, TestingSetup)
static CWallet wallet;
static vector<COutput> vCoins;
static void add_coin(const CAmount& nValue, int nAge = 6*24, bool fIsFromMe = false, int nInput=0)
{
static int nextLockTime = 0;
CMutableTransaction tx;
tx.nLockTime = nextLockTime++; // so all transactions get different hashes
tx.vout.resize(nInput+1);
tx.vout[nInput].nValue = nValue;
if (fIsFromMe) {
// IsFromMe() returns (GetDebit() > 0), and GetDebit() is 0 if vin.empty(),
// so stop vin being empty, and cache a non-zero Debit to fake out IsFromMe()
tx.vin.resize(1);
}
CWalletTx* wtx = new CWalletTx(&wallet, tx);
if (fIsFromMe)
{
wtx->fDebitCached = true;
wtx->nDebitCached = 1;
}
COutput output(wtx, nInput, nAge, true, true);
vCoins.push_back(output);
}
static void empty_wallet(void)
{
BOOST_FOREACH(COutput output, vCoins)
delete output.tx;
vCoins.clear();
}
static bool equal_sets(CoinSet a, CoinSet b)
{
pair<CoinSet::iterator, CoinSet::iterator> ret = mismatch(a.begin(), a.end(), b.begin());
return ret.first == a.end() && ret.second == b.end();
}
BOOST_AUTO_TEST_CASE(coin_selection_tests)
{
CoinSet setCoinsRet, setCoinsRet2;
CAmount nValueRet;
LOCK(wallet.cs_wallet);
// test multiple times to allow for differences in the shuffle order
for (int i = 0; i < RUN_TESTS; i++)
{
empty_wallet();
// with an empty wallet we can't even pay one cent
BOOST_CHECK(!wallet.SelectCoinsMinConf( 1 * CENT, 1, 6, vCoins, setCoinsRet, nValueRet));
add_coin(1*CENT, 4); // add a new 1 cent coin
// with a new 1 cent coin, we still can't find a mature 1 cent
BOOST_CHECK(!wallet.SelectCoinsMinConf( 1 * CENT, 1, 6, vCoins, setCoinsRet, nValueRet));
// but we can find a new 1 cent
BOOST_CHECK( wallet.SelectCoinsMinConf( 1 * CENT, 1, 1, vCoins, setCoinsRet, nValueRet));
BOOST_CHECK_EQUAL(nValueRet, 1 * CENT);
add_coin(2*CENT); // add a mature 2 cent coin
// we can't make 3 cents of mature coins
BOOST_CHECK(!wallet.SelectCoinsMinConf( 3 * CENT, 1, 6, vCoins, setCoinsRet, nValueRet));
// we can make 3 cents of new coins
BOOST_CHECK( wallet.SelectCoinsMinConf( 3 * CENT, 1, 1, vCoins, setCoinsRet, nValueRet));
BOOST_CHECK_EQUAL(nValueRet, 3 * CENT);
add_coin(5*CENT); // add a mature 5 cent coin,
add_coin(10*CENT, 3, true); // a new 10 cent coin sent from one of our own addresses
add_coin(20*CENT); // and a mature 20 cent coin
// now we have new: 1+10=11 (of which 10 was self-sent), and mature: 2+5+20=27. total = 38
// we can't make 38 cents only if we disallow new coins:
BOOST_CHECK(!wallet.SelectCoinsMinConf(38 * CENT, 1, 6, vCoins, setCoinsRet, nValueRet));
// we can't even make 37 cents if we don't allow new coins even if they're from us
BOOST_CHECK(!wallet.SelectCoinsMinConf(38 * CENT, 6, 6, vCoins, setCoinsRet, nValueRet));
// but we can make 37 cents if we accept new coins from ourself
BOOST_CHECK( wallet.SelectCoinsMinConf(37 * CENT, 1, 6, vCoins, setCoinsRet, nValueRet));
BOOST_CHECK_EQUAL(nValueRet, 37 * CENT);
// and we can make 38 cents if we accept all new coins
BOOST_CHECK( wallet.SelectCoinsMinConf(38 * CENT, 1, 1, vCoins, setCoinsRet, nValueRet));
BOOST_CHECK_EQUAL(nValueRet, 38 * CENT);
// try making 34 cents from 1,2,5,10,20 - we can't do it exactly
BOOST_CHECK( wallet.SelectCoinsMinConf(34 * CENT, 1, 1, vCoins, setCoinsRet, nValueRet));
BOOST_CHECK_EQUAL(nValueRet, 35 * CENT); // but 35 cents is closest
BOOST_CHECK_EQUAL(setCoinsRet.size(), 3U); // the best should be 20+10+5. it's incredibly unlikely the 1 or 2 got included (but possible)
// when we try making 7 cents, the smaller coins (1,2,5) are enough. We should see just 2+5
BOOST_CHECK( wallet.SelectCoinsMinConf( 7 * CENT, 1, 1, vCoins, setCoinsRet, nValueRet));
BOOST_CHECK_EQUAL(nValueRet, 7 * CENT);
BOOST_CHECK_EQUAL(setCoinsRet.size(), 2U);
// when we try making 8 cents, the smaller coins (1,2,5) are exactly enough.
BOOST_CHECK( wallet.SelectCoinsMinConf( 8 * CENT, 1, 1, vCoins, setCoinsRet, nValueRet));
BOOST_CHECK(nValueRet == 8 * CENT);
BOOST_CHECK_EQUAL(setCoinsRet.size(), 3U);
// when we try making 9 cents, no subset of smaller coins is enough, and we get the next bigger coin (10)
BOOST_CHECK( wallet.SelectCoinsMinConf( 9 * CENT, 1, 1, vCoins, setCoinsRet, nValueRet));
BOOST_CHECK_EQUAL(nValueRet, 10 * CENT);
BOOST_CHECK_EQUAL(setCoinsRet.size(), 1U);
// now clear out the wallet and start again to test choosing between subsets of smaller coins and the next biggest coin
empty_wallet();
add_coin( 6*CENT);
add_coin( 7*CENT);
add_coin( 8*CENT);
add_coin(20*CENT);
add_coin(30*CENT); // now we have 6+7+8+20+30 = 71 cents total
// check that we have 71 and not 72
BOOST_CHECK( wallet.SelectCoinsMinConf(71 * CENT, 1, 1, vCoins, setCoinsRet, nValueRet));
BOOST_CHECK(!wallet.SelectCoinsMinConf(72 * CENT, 1, 1, vCoins, setCoinsRet, nValueRet));
// now try making 16 cents. the best smaller coins can do is 6+7+8 = 21; not as good at the next biggest coin, 20
BOOST_CHECK( wallet.SelectCoinsMinConf(16 * CENT, 1, 1, vCoins, setCoinsRet, nValueRet));
BOOST_CHECK_EQUAL(nValueRet, 20 * CENT); // we should get 20 in one coin
BOOST_CHECK_EQUAL(setCoinsRet.size(), 1U);
add_coin( 5*CENT); // now we have 5+6+7+8+20+30 = 75 cents total
// now if we try making 16 cents again, the smaller coins can make 5+6+7 = 18 cents, better than the next biggest coin, 20
BOOST_CHECK( wallet.SelectCoinsMinConf(16 * CENT, 1, 1, vCoins, setCoinsRet, nValueRet));
BOOST_CHECK_EQUAL(nValueRet, 18 * CENT); // we should get 18 in 3 coins
BOOST_CHECK_EQUAL(setCoinsRet.size(), 3U);
add_coin( 18*CENT); // now we have 5+6+7+8+18+20+30
// and now if we try making 16 cents again, the smaller coins can make 5+6+7 = 18 cents, the same as the next biggest coin, 18
BOOST_CHECK( wallet.SelectCoinsMinConf(16 * CENT, 1, 1, vCoins, setCoinsRet, nValueRet));
BOOST_CHECK_EQUAL(nValueRet, 18 * CENT); // we should get 18 in 1 coin
BOOST_CHECK_EQUAL(setCoinsRet.size(), 1U); // because in the event of a tie, the biggest coin wins
// now try making 11 cents. we should get 5+6
BOOST_CHECK( wallet.SelectCoinsMinConf(11 * CENT, 1, 1, vCoins, setCoinsRet, nValueRet));
BOOST_CHECK_EQUAL(nValueRet, 11 * CENT);
BOOST_CHECK_EQUAL(setCoinsRet.size(), 2U);
// check that the smallest bigger coin is used
add_coin( 1*COIN);
add_coin( 2*COIN);
add_coin( 3*COIN);
add_coin( 4*COIN); // now we have 5+6+7+8+18+20+30+100+200+300+400 = 1094 cents
BOOST_CHECK( wallet.SelectCoinsMinConf(95 * CENT, 1, 1, vCoins, setCoinsRet, nValueRet));
BOOST_CHECK_EQUAL(nValueRet, 1 * COIN); // we should get 1 BTC in 1 coin
BOOST_CHECK_EQUAL(setCoinsRet.size(), 1U);
BOOST_CHECK( wallet.SelectCoinsMinConf(195 * CENT, 1, 1, vCoins, setCoinsRet, nValueRet));
BOOST_CHECK_EQUAL(nValueRet, 2 * COIN); // we should get 2 BTC in 1 coin
BOOST_CHECK_EQUAL(setCoinsRet.size(), 1U);
// empty the wallet and start again, now with fractions of a cent, to test small change avoidance
empty_wallet();
add_coin(0.1*MIN_CHANGE);
add_coin(0.2*MIN_CHANGE);
add_coin(0.3*MIN_CHANGE);
add_coin(0.4*MIN_CHANGE);
add_coin(0.5*MIN_CHANGE);
// try making 1 * MIN_CHANGE from the 1.5 * MIN_CHANGE
// we'll get change smaller than MIN_CHANGE whatever happens, so can expect MIN_CHANGE exactly
BOOST_CHECK( wallet.SelectCoinsMinConf(MIN_CHANGE, 1, 1, vCoins, setCoinsRet, nValueRet));
BOOST_CHECK_EQUAL(nValueRet, MIN_CHANGE);
// but if we add a bigger coin, small change is avoided
add_coin(1111*MIN_CHANGE);
// try making 1 from 0.1 + 0.2 + 0.3 + 0.4 + 0.5 + 1111 = 1112.5
BOOST_CHECK( wallet.SelectCoinsMinConf(1 * MIN_CHANGE, 1, 1, vCoins, setCoinsRet, nValueRet));
BOOST_CHECK_EQUAL(nValueRet, 1 * MIN_CHANGE); // we should get the exact amount
// if we add more small coins:
add_coin(0.6*MIN_CHANGE);
add_coin(0.7*MIN_CHANGE);
// and try again to make 1.0 * MIN_CHANGE
BOOST_CHECK( wallet.SelectCoinsMinConf(1 * MIN_CHANGE, 1, 1, vCoins, setCoinsRet, nValueRet));
BOOST_CHECK_EQUAL(nValueRet, 1 * MIN_CHANGE); // we should get the exact amount
// run the 'mtgox' test (see http://blockexplorer.com/tx/29a3efd3ef04f9153d47a990bd7b048a4b2d213daaa5fb8ed670fb85f13bdbcf)
// they tried to consolidate 10 50k coins into one 500k coin, and ended up with 50k in change
empty_wallet();
for (int i = 0; i < 20; i++)
add_coin(50000 * COIN);
BOOST_CHECK( wallet.SelectCoinsMinConf(500000 * COIN, 1, 1, vCoins, setCoinsRet, nValueRet));
BOOST_CHECK_EQUAL(nValueRet, 500000 * COIN); // we should get the exact amount
BOOST_CHECK_EQUAL(setCoinsRet.size(), 10U); // in ten coins
// if there's not enough in the smaller coins to make at least 1 * MIN_CHANGE change (0.5+0.6+0.7 < 1.0+1.0),
// we need to try finding an exact subset anyway
// sometimes it will fail, and so we use the next biggest coin:
empty_wallet();
add_coin(0.5 * MIN_CHANGE);
add_coin(0.6 * MIN_CHANGE);
add_coin(0.7 * MIN_CHANGE);
add_coin(1111 * MIN_CHANGE);
BOOST_CHECK( wallet.SelectCoinsMinConf(1 * MIN_CHANGE, 1, 1, vCoins, setCoinsRet, nValueRet));
BOOST_CHECK_EQUAL(nValueRet, 1111 * MIN_CHANGE); // we get the bigger coin
BOOST_CHECK_EQUAL(setCoinsRet.size(), 1U);
// but sometimes it's possible, and we use an exact subset (0.4 + 0.6 = 1.0)
empty_wallet();
add_coin(0.4 * MIN_CHANGE);
add_coin(0.6 * MIN_CHANGE);
add_coin(0.8 * MIN_CHANGE);
add_coin(1111 * MIN_CHANGE);
BOOST_CHECK( wallet.SelectCoinsMinConf(MIN_CHANGE, 1, 1, vCoins, setCoinsRet, nValueRet));
BOOST_CHECK_EQUAL(nValueRet, MIN_CHANGE); // we should get the exact amount
BOOST_CHECK_EQUAL(setCoinsRet.size(), 2U); // in two coins 0.4+0.6
// test avoiding small change
empty_wallet();
add_coin(0.05 * MIN_CHANGE);
add_coin(1 * MIN_CHANGE);
add_coin(100 * MIN_CHANGE);
// trying to make 100.01 from these three coins
BOOST_CHECK( wallet.SelectCoinsMinConf(100.01 * MIN_CHANGE, 1, 1, vCoins, setCoinsRet, nValueRet));
BOOST_CHECK_EQUAL(nValueRet, 101.05 * MIN_CHANGE); // we should get all coins
BOOST_CHECK_EQUAL(setCoinsRet.size(), 3U);
// but if we try to make 99.9, we should take the bigger of the two small coins to avoid small change
BOOST_CHECK( wallet.SelectCoinsMinConf(99.9 * MIN_CHANGE, 1, 1, vCoins, setCoinsRet, nValueRet));
BOOST_CHECK_EQUAL(nValueRet, 101 * MIN_CHANGE);
BOOST_CHECK_EQUAL(setCoinsRet.size(), 2U);
// test with many inputs
for (CAmount amt=1500; amt < COIN; amt*=10) {
empty_wallet();
// Create 676 inputs (= MAX_STANDARD_TX_SIZE / 148 bytes per input)
for (uint16_t j = 0; j < 676; j++)
add_coin(amt);
BOOST_CHECK(wallet.SelectCoinsMinConf(2000, 1, 1, vCoins, setCoinsRet, nValueRet));
if (amt - 2000 < MIN_CHANGE) {
// needs more than one input:
uint16_t returnSize = std::ceil((2000.0 + MIN_CHANGE)/amt);
CAmount returnValue = amt * returnSize;
BOOST_CHECK_EQUAL(nValueRet, returnValue);
BOOST_CHECK_EQUAL(setCoinsRet.size(), returnSize);
} else {
// one input is sufficient:
BOOST_CHECK_EQUAL(nValueRet, amt);
BOOST_CHECK_EQUAL(setCoinsRet.size(), 1U);
}
}
// test randomness
{
empty_wallet();
for (int i2 = 0; i2 < 100; i2++)
add_coin(COIN);
// picking 50 from 100 coins doesn't depend on the shuffle,
// but does depend on randomness in the stochastic approximation code
BOOST_CHECK(wallet.SelectCoinsMinConf(50 * COIN, 1, 6, vCoins, setCoinsRet , nValueRet));
BOOST_CHECK(wallet.SelectCoinsMinConf(50 * COIN, 1, 6, vCoins, setCoinsRet2, nValueRet));
BOOST_CHECK(!equal_sets(setCoinsRet, setCoinsRet2));
int fails = 0;
for (int i = 0; i < RANDOM_REPEATS; i++)
{
// selecting 1 from 100 identical coins depends on the shuffle; this test will fail 1% of the time
// run the test RANDOM_REPEATS times and only complain if all of them fail
BOOST_CHECK(wallet.SelectCoinsMinConf(COIN, 1, 6, vCoins, setCoinsRet , nValueRet));
BOOST_CHECK(wallet.SelectCoinsMinConf(COIN, 1, 6, vCoins, setCoinsRet2, nValueRet));
if (equal_sets(setCoinsRet, setCoinsRet2))
fails++;
}
BOOST_CHECK_NE(fails, RANDOM_REPEATS);
// add 75 cents in small change. not enough to make 90 cents,
// then try making 90 cents. there are multiple competing "smallest bigger" coins,
// one of which should be picked at random
add_coin( 5*CENT); add_coin(10*CENT); add_coin(15*CENT); add_coin(20*CENT); add_coin(25*CENT);
fails = 0;
for (int i = 0; i < RANDOM_REPEATS; i++)
{
// selecting 1 from 100 identical coins depends on the shuffle; this test will fail 1% of the time
// run the test RANDOM_REPEATS times and only complain if all of them fail
BOOST_CHECK(wallet.SelectCoinsMinConf(90*CENT, 1, 6, vCoins, setCoinsRet , nValueRet));
BOOST_CHECK(wallet.SelectCoinsMinConf(90*CENT, 1, 6, vCoins, setCoinsRet2, nValueRet));
if (equal_sets(setCoinsRet, setCoinsRet2))
fails++;
}
BOOST_CHECK_NE(fails, RANDOM_REPEATS);
}
}
empty_wallet();
}
BOOST_AUTO_TEST_CASE(ApproximateBestSubset)
{
CoinSet setCoinsRet;
CAmount nValueRet;
LOCK(wallet.cs_wallet);
empty_wallet();
// Test vValue sort order
for (int i = 0; i < 1000; i++)
add_coin(1000 * COIN);
add_coin(3 * COIN);
BOOST_CHECK(wallet.SelectCoinsMinConf(1003 * COIN, 1, 6, vCoins, setCoinsRet, nValueRet));
BOOST_CHECK_EQUAL(nValueRet, 1003 * COIN);
BOOST_CHECK_EQUAL(setCoinsRet.size(), 2U);
empty_wallet();
// Test trimming
for (int i = 0; i < 100; i++)
add_coin(10 * COIN);
for (int i = 0; i < 100; i++)
add_coin(1000 * COIN);
BOOST_CHECK(wallet.SelectCoinsMinConf(100001 * COIN, 1, 6, vCoins, setCoinsRet, nValueRet));
// We need all 100 larger coins and exactly one small coin.
// Superfluous small coins must be trimmed from the set:
BOOST_CHECK_EQUAL(nValueRet, 100010 * COIN);
BOOST_CHECK_EQUAL(setCoinsRet.size(), 101);
}
BOOST_AUTO_TEST_SUITE_END()
|
/*
* If not stated otherwise in this file or this component's Licenses.txt file the
* following copyright and licenses apply:
*
* Copyright 2016 RDK Management
*
* 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.
*/
/**
* @defgroup devicesettings
* @{
* @defgroup sample
* @{
**/
#include <iostream>
#include "host.hpp"
#include "videoDevice.hpp"
#include "videoDFC.hpp"
#include "manager.hpp"
#include "dsUtl.h"
#include "dsError.h"
#include "list.hpp"
#include "libIBus.h"
int main(int argc, char *argv[])
{
IARM_Bus_Init("SampleDSClient");
IARM_Bus_Connect();
device::Manager::Initialize();
try {
device::VideoDevice decoder = device::Host::getInstance().getVideoDevices().at(0);
printf("ZoomSettings - [%s]\r\n", decoder.getDFC().getName().c_str());
}
catch (const std::exception e) {
printf("Exception caught\r\n");
}
device::Manager::DeInitialize();
IARM_Bus_Disconnect();
IARM_Bus_Term();
return 0;
}
/** @} */
/** @} */
|
//
// GrovePi Example for using the Grove Relay (http://www.seeedstudio.com/wiki/Grove_-_Relay)
//
// The GrovePi connects the Raspberry Pi and Grove sensors. You can learn more about GrovePi here: http://www.dexterindustries.com/GrovePi
//
// Have a question about this example? Ask on the forums here: http://forum.dexterindustries.com/c/grovepi
//
/*
## License
The MIT License (MIT)
GrovePi for the Raspberry Pi: an open source platform for connecting Grove Sensors to the Raspberry Pi.
Copyright (C) 2017 Dexter Industries
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 "grovepi.h"
using namespace GrovePi;
// sudo g++ -Wall grovepi.cpp grove_relay.cpp -o grove_relay.out -> without grovepicpp package installed
// sudo g++ -Wall -lgrovepicpp grove_relay.cpp -o grove_relay.out -> with grovepicpp package installed
int main()
{
int relay_pin = 4; // Grove Relay is connected to digital port D4 on the GrovePi
try
{
initGrovePi(); // initialize communication with the GrovePi
pinMode(relay_pin, OUTPUT); // set the relay's pin as OUTPUT
// do this indefinitely
while(true)
{
// turn it ON
digitalWrite(relay_pin, HIGH);
printf("[pin %d][relay ON]\n", relay_pin);
// for 5 seconds
delay(5000);
// and turn it OFF
digitalWrite(relay_pin, LOW);
printf("[pin %d][relay OFF]\n", relay_pin);
// for another 5 seconds
delay(5000);
// and repeat
}
}
catch(I2CError &error)
{
printf(error.detail());
return -1;
}
return 0;
}
|
// Copyright 2017 PDFium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
// Original code copyright 2014 Foxit Software Inc. http://www.foxitsoftware.com
#include "xfa/fxfa/parser/cxfa_connectstring.h"
#include <memory>
#include "fxjs/xfa/cjx_textnode.h"
namespace {
const CXFA_Node::AttributeData kConnectStringAttributeData[] = {
{XFA_Attribute::Id, XFA_AttributeType::CData, nullptr},
{XFA_Attribute::Name, XFA_AttributeType::CData, nullptr},
{XFA_Attribute::Use, XFA_AttributeType::CData, nullptr},
{XFA_Attribute::Usehref, XFA_AttributeType::CData, nullptr},
};
} // namespace
CXFA_ConnectString::CXFA_ConnectString(CXFA_Document* doc,
XFA_PacketType packet)
: CXFA_Node(doc,
packet,
XFA_XDPPACKET_SourceSet,
XFA_ObjectType::TextNode,
XFA_Element::ConnectString,
{},
kConnectStringAttributeData,
std::make_unique<CJX_TextNode>(this)) {}
CXFA_ConnectString::~CXFA_ConnectString() = default;
|
#include <DataStreams/RemoteBlockOutputStream.h>
#include <Client/Connection.h>
#include <common/logger_useful.h>
#include <Common/NetException.h>
#include <Common/CurrentThread.h>
#include <Interpreters/InternalTextLogsQueue.h>
namespace DB
{
namespace ErrorCodes
{
extern const int UNEXPECTED_PACKET_FROM_SERVER;
extern const int LOGICAL_ERROR;
}
RemoteBlockOutputStream::RemoteBlockOutputStream(Connection & connection_, const String & query_, const Settings * settings_)
: connection(connection_), query(query_), settings(settings_)
{
/** Send query and receive "header", that describe table structure.
* Header is needed to know, what structure is required for blocks to be passed to 'write' method.
*/
connection.sendQuery(query, "", QueryProcessingStage::Complete, settings, nullptr);
while (true)
{
Connection::Packet packet = connection.receivePacket();
if (Protocol::Server::Data == packet.type)
{
header = packet.block;
break;
}
else if (Protocol::Server::Exception == packet.type)
{
packet.exception->rethrow();
break;
}
else if (Protocol::Server::Log == packet.type)
{
/// Pass logs from remote server to client
if (auto log_queue = CurrentThread::getInternalTextLogsQueue())
log_queue->pushBlock(std::move(packet.block));
}
else
throw NetException("Unexpected packet from server (expected Data or Exception, got "
+ String(Protocol::Server::toString(packet.type)) + ")", ErrorCodes::UNEXPECTED_PACKET_FROM_SERVER);
}
}
void RemoteBlockOutputStream::write(const Block & block)
{
if (header)
assertBlocksHaveEqualStructure(block, header, "RemoteBlockOutputStream");
try
{
connection.sendData(block);
}
catch (const NetException &)
{
/// Try to get more detailed exception from server
auto packet_type = connection.checkPacket();
if (packet_type && *packet_type == Protocol::Server::Exception)
{
Connection::Packet packet = connection.receivePacket();
packet.exception->rethrow();
}
throw;
}
}
void RemoteBlockOutputStream::writePrepared(ReadBuffer & input, size_t size)
{
/// We cannot use 'header'. Input must contain block with proper structure.
connection.sendPreparedData(input, size);
}
void RemoteBlockOutputStream::writeSuffix()
{
/// Empty block means end of data.
connection.sendData(Block());
/// Wait for EndOfStream or Exception packet, skip Log packets.
while (true)
{
Connection::Packet packet = connection.receivePacket();
if (Protocol::Server::EndOfStream == packet.type)
break;
else if (Protocol::Server::Exception == packet.type)
packet.exception->rethrow();
else if (Protocol::Server::Log == packet.type)
{
// Do nothing
}
else
throw NetException("Unexpected packet from server (expected EndOfStream or Exception, got "
+ String(Protocol::Server::toString(packet.type)) + ")", ErrorCodes::UNEXPECTED_PACKET_FROM_SERVER);
}
finished = true;
}
RemoteBlockOutputStream::~RemoteBlockOutputStream()
{
/// If interrupted in the middle of the loop of communication with the server, then interrupt the connection,
/// to not leave the connection in unsynchronized state.
if (!finished)
{
try
{
connection.disconnect();
}
catch (...)
{
tryLogCurrentException(__PRETTY_FUNCTION__);
}
}
}
}
|
#include <iostream>
int main() {
int x, y;
std::cin >> x >> y;
auto sum = [x](int i) { return x + i; };
// The lamda must be defined after we read x, otherwise it will capture the
// undefined value of x.
std::cout << x << " + " << y << " = " << sum(y) << std::endl;
return 0;
}
|
/**-----------------------------------------------------------------------------------------------------------------
* @file message.cpp
* @brief packetize and depacketize HTTP message
*
* Copyright (c) 2019-2019 Jim Zhang 303683086@qq.com
*------------------------------------------------------------------------------------------------------------------
*/
#include <httpcd/message/message.hpp>
using namespace NS_HTTPCD;
/*
--------------------------------------------------------------------------------------------------------------------
*
* FUNCTIONS IMPLEMENT
*
--------------------------------------------------------------------------------------------------------------------
*/
/**
* @brief Packetize HTTP request line with official method
* @param[in] m - GET/HEAD/PUT...
* @param[in] URL
* @param[in] v - HTTP_0_9/HTTP_1_0/HTTP_1_1...
* @param[out] None
* @return None
* @note The function can be called repeatedly, BUT only to save the latest setting.
**/
void message::set_msg_line(enum method m, const char *URL, enum version v)
{
string space = " ";
string CRLF = "\r\n";
const char *method[] = {"GET", "HEAD", "PUT", "POST", "TRACE", "OPTIONS", "DELETE"};
const char *version[] = {"HTTP/0.9", "HTTP/1.0", "HTTP/1.1", "HTTP/2.0"};
message_line = method[m] + space;
message_line += URL + space;
message_line += version[v] + CRLF;
return;
}
/**
* @brief Packetize HTTP request line with extension method
* @param[in] method
* @param[in] URL
* @param[in] version - HTTP_0_9/HTTP_1_0/HTTP_1_1...
* @param[out] None
* @return None
* @note The function can be called repeatedly, BUT only to save the latest setting.
**/
void message::set_msg_line(const char *method, const char *URL, enum version v)
{
string space = " ";
string CRLF = "\r\n";
const char *version[] = {"HTTP/0.9", "HTTP/1.0", "HTTP/1.1", "HTTP/2.0"};
message_line = method + space;
message_line += URL + space;
message_line += version[v] + CRLF;
return;
}
/**
* @brief Packetize HTTP response line with official method
* @param[in] v - HTTP_0_9/HTTP_1_0/HTTP_1_1...
* @param[in] sc - _100/_200/_301...
* @param[in] reason
* @param[out] None
* @return None
* @note The function can be called repeatedly, BUT only to save the latest setting.
**/
void message::set_msg_line(enum version v, enum stsCode sc, const char *reason)
{
string space = " ";
string CRLF = "\r\n";
const char *version[] = {"HTTP/0.9", "HTTP/1.0", "HTTP/1.1", "HTTP/2.0"};
stringstream ss;
ss << sc;
message_line = version[v] + space + ss.str() + space;
message_line += reason + CRLF;
return;
}
/**
* @brief Packetize HTTP header with official general headers
* @param[in] h - official eneity header (field_name)
* @param[in] body - field_body which suiable the header (field_name)
* @param[out] None
* @return None
* @note The function can be called repeatedly, AND all values can be saved.
* @warning Except for certain headers, other headers should not be repeated
**/
void message::set_msg_head(enum comm_header h, const class field_body *body)
{
const char *header[] = {
"Cache-Control", "Connection", "Date", "Proxy-Connection", "Trailer", "Transfer-Encoding", "Upgrade", "Via"
};
this->header.set(header[h], body);
return;
}
void message::set_msg_head(enum comm_header h, const string &field_body)
{
class string_body str_body(field_body );
this->set_msg_head(h, &str_body); return;
}
/**
* @brief Packetize HTTP header with official request headers
* @param[in] h - official eneity header (field_name)
* @param[in] body - field_body which suiable the header (field_name)
* @param[out] None
* @return None
* @note The function can be called repeatedly, AND all values can be saved.
* @warning Except for certain headers, other headers should not be repeated
**/
void message::set_msg_head(enum rqst_header h, const class field_body *body)
{
const char *header[] = {
"Accept", "Accept-Charset", "Accept-Encoding", "Accept-Language", "Expect", "From", "Host", "If-Modified-Since", "If-Match", "If-None-Match",
"If-Range", "If-Unmodified-Since", "Max-Forwards", "Pragma", "Proxy-Authorization", "Referer", "User-Agent"
};
this->header.set(header[h], body);
return;
}
void message::set_msg_head(enum rsps_header h, const string &field_body)
{
class string_body str_body(field_body );
this->set_msg_head(h, &str_body); return;
}
/**
* @brief Packetize HTTP header with official response headers
* @param[in] h - official eneity header (field_name)
* @param[in] body - field_body which suiable the header (field_name)
* @param[out] None
* @return None
* @note The function can be called repeatedly, AND all values can be saved.
* @warning Except for certain headers, other headers should not be repeated
**/
void message::set_msg_head(enum rsps_header h, const class field_body *body)
{
const char *header[] = {
"Accept-Ranges", "Age", "Allow", "Authorization", "Location", "Proxy-Authenticate", "Public", "Retry-After",
"Server", "Title", "Vary", "Warning", "WWW-Authenticate"
};
this->header.set(header[h], body);
return;
}
void message::set_msg_head(enum rqst_header h, const string &field_body)
{
class string_body str_body(field_body );
this->set_msg_head(h, &str_body); return;
}
/**
* @brief Packetize HTTP header with official entity headers
* @param[in] h - official eneity header (field_name)
* @param[in] body - field_body which suiable the header (field_name)
* @param[out] None
* @return None
* @note The function can be called repeatedly, AND all values can be saved.
* @warning Except for certain headers, other headers should not be repeated
**/
void message::set_msg_head(enum body_header h, const class field_body *body)
{
const char *header[] = {
"Content-Encoding", "Content-Language", "Content-Length", "Content-MD5", "Content-Range", "ETag", "Expires", "Last-Modified", "Range"
};
this->header.set(header[h], body);
return;
}
void message::set_msg_head(enum body_header h, const string &field_body)
{
class string_body str_body(field_body );
this->set_msg_head(h, &str_body); return;
}
/**
* @brief Packetize HTTP header with (MIME) official entity headers
* @param[in] h - official eneity header (field_name)
* @param[in] body - field_body which suiable the header (field_name)
* @param[out] None
* @return None
* @note The function can be called repeatedly, AND all values can be saved.
* @warning Except for certain headers, other headers should not be repeated
**/
void message::set_msg_head(enum MIME_FNAME h, const class field_body *body)
{
this->header.set(h, body);
}
/**
* @brief Packetize HTTP header with (MIME) official entity headers
* @param[in] h - official eneity header (field_name)
* @param[in] body - field_body which suiable the header (field_name)
* @param[out] None
* @return None
* @note The function can be called repeatedly, AND all values can be saved.
* @warning Except for certain headers, other headers should not be repeated
**/
void message::set_msg_head(enum MIME_FNAME h, const string &field_body)
{
this->header.set(h, field_body);
return;
}
/**
* @brief Packetize HTTP header with official entity headers
* @param[in] field_name
* @param[in] body - field_body which suiable the header (field_name)
* @param[out] None
* @return None
* @note The function can be called repeatedly, AND all values can be saved.
* @warning Except for certain headers, other headers should not be repeated
**/
void message::set_msg_head(const string &field_name, const class field_body *body)
{
this->header.set(field_name, body);
return;
}
/**
* @brief Packetize HTTP header with official entity headers
* @param[in] field_name
* @param[in] body - field_body which suiable the header (field_name)
* @param[out] None
* @return None
* @note The function can be called repeatedly, AND all values can be saved.
* @warning Except for certain headers, other headers should not be repeated
**/
void message::set_msg_head(const string &field_name, const string &field_body)
{
class string_body str_body(field_body );
this->header.set(field_name, &str_body);
return;
}
/**
* @brief Set message body
* @param[in] body
* @param[in] _size - size of body
* @param[out] None
* @return None
* @note Set more info by class mime_body
**/
void message::set_msg_body(const char *body, string::size_type _size)
{
this->sdbody.set(body, _size);
return;
}
/**
* @brief Set mime enity part which under the param 'header'
* @param[in] header - mime entity (part father's) header
* @param[out] None
* @return mime entity part pointer OR NULL if subtype 'mixed' does not exsists
*
* @note *Param 'header'
* 1. belong to the part father
* 2. will be filtered when an non-mime-entity header setted
* 3. only to save the first settings when set mutil times
*
* @note *Multi part depth
* 1. The function can be called repeatedly, to set sub-part with return pointer OR
* to set brother-part under the same object
* 2. Only 'Content-Type' with major-type 'multipart' and subtype 'mixed' can be nested deeply,
* if not in this case, NULL will be returned
*
* @exception "Const char *" 'multipart' type does not exsits & 'mixed' subtyp lose
**/
class mime_entity *message::set_msg_part(class mime_header &header)
{
return this->set_part(header);
}
/**
* @brief Set mime enity part which under the FATHER header
* @param[in] None
* @param[out] None
* @return mime entity part pointer OR NULL if subtype 'mixed' does not exsists
*
* @note Use this funtion when FATHER HEADER already has been setted
*
* @note *Multi part depth
* 1. The function can be called repeatedly, to set sub-part with return pointer OR
* to set brother-part under the same object
* 2. Only 'Content-Type' with major-type 'multipart' and subtype 'mixed' can be nested deeply,
* if not in this case, NULL will be returned
*
* @exception "Const char *" 'multipart' type does not exsits & 'mixed' subtyp lose
**/
class mime_entity *message::set_msg_part(void)
{
return this->set_part();
}
/**
* @brief Packetize HTTP messages
* @param[in] None
* @param[out] None
* @return HTTP messages
**/
const string message::pack_msg(void)
{
if (string::npos == this->message_line.find("\r\n"))
{
this->message_line += "\r\n"; /**< Prevents direct packaging after receiving from the receiver */
}
return this->message_line + this->make();
}
/**
* @brief Load HTTP message for further parsing
* @param[in] message
* @param[out] None
* @return ture/flase (reserved interface)
* @note *** TO BE SURE param 'entity' has certain size info, If entity contain '\0'
**/
bool message::load_msg(const string &message)
{
/**<---------------------------------------------------------*/
/**< Load HTTP message line */
class string_token str_tok; str_tok.cut(message, "\r\n");
this->message_line = str_tok.get_stok(0);
/**<---------------------------------------------------------*/
/**< Load HTTP message entity */
string mime_entity = str_tok.get_stok(1);
return this->load(mime_entity);
}
/**
* @brief Load HTTP message for further parsing
* @param[in] message
* @param[in] size of message
* @param[out] None
* @return ture/flase (reserved interface)
**/
bool message::load_msg(const char *message, string::size_type _size)
{
string _message(message, _size );
return this->load_msg(_message );
}
/**
* @brief Get message line
* @param[in] None
* @param[out] None
* @return HTTP message line
**/
const string &message::get_msg_line(void) const noexcept
{
return this->message_line;
}
/**
* @brief Get (request) message method
* @param[in] None
* @param[out] None
* @return HTTP message method
**/
const string message::get_msg_method(void) const noexcept
{
class string_token str_tok(message_line, " ");
return str_tok.get_stok(0);
}
/**
* @brief Get (request) message URL
* @param[in] None
* @param[out] None
* @return HTTP message URL
**/
const string message::get_msg_URL() const noexcept
{
class string_token str_tok(message_line, " ");
return str_tok.get_stok(1);
}
/**
* @brief Get (request/response) message version
* @param[in] dir - 1/true for reqeust, 0/flase for response
* @param[out] None
* @return HTTP message version
**/
const string message::get_msg_version(bool dir) const noexcept
{
class string_token str_tok(message_line, " ");
return str_tok.get_stok((true==dir)?2:0);
}
/**
* @brief Get (response) message status
* @param[in] None
* @param[out] None
* @return HTTP message status
**/
const string message::get_msg_status(void) const noexcept
{
class string_token str_tok(message_line, " ");
return str_tok.get_stok(1);
}
/**
* @brief Get message header (RET field_body) with certain enumeration
* @param[in] h - certain header (IN field_name) enumeration
* @param[out] None
* @return HTTP message header (field_body) or "" (empty)
**/
const string message::get_msg_head(enum MIME_FNAME fname_t) const noexcept
{
return this->header.get_field(fname_t).get_body();
}
/**
* @brief Get message header (RET field_body) with certain enumeration
* @param[in] h - certain header (IN field_name) enumeration
* @param[out] None
* @return HTTP message header (field_body) or "" (empty)
**/
const string message::get_msg_head(enum comm_header h) const noexcept
{
const char *header[] = {
"Cache-Control", "Connection", "Date", "Proxy-Connection", "Trailer", "Transfer-Encoding", "Upgrade", "Via"
};
return this->header.header::get_field(header[h]).get_body();
}
/**
* @brief Get message header (RET field_body) with certain enumeration
* @param[in] h - certain header (IN field_name) enumeration
* @param[out] None
* @return HTTP message header (field_body) or "" (empty)
**/
const string message::get_msg_head(enum rqst_header h) const noexcept
{
const char *header[] = {
"Accept", "Accept-Charset", "Accept-Encoding", "Accept-Language", "Expect", "From", "Host", "If-Modified-Since", "If-Match", "If-None-Match",
"If-Range", "If-Unmodified-Since", "Max-Forwards", "Pragma", "Proxy-Authorization", "Referer", "User-Agent"
};
return this->header.header::get_field(header[h]).get_body();
}
/**
* @brief Get message header (RET field_body) with certain enumeration
* @param[in] h - certain header (IN field_name) enumeration
* @param[out] None
* @return HTTP message header (field_body) or "" (empty)
**/
const string message::get_msg_head(enum rsps_header h) const noexcept
{
const char *header[] = {
"Accept-Ranges", "Age", "Allow", "Authorization", "Location", "Proxy-Authenticate", "Public", "Retry-After",
"Server", "Title", "Vary", "Warning", "WWW-Authenticate"
};
return this->header.header::get_field(header[h]).get_body();
}
/**
* @brief Get message header (RET field_body) with certain enumeration
* @param[in] h - certain header (IN field_name) enumeration
* @param[out] None
* @return HTTP message header (field_body) or "" (empty)
**/
const string message::get_msg_head(enum body_header h) const noexcept
{
const char *header[] = {
"Content-Encoding", "Content-Language", "Content-Length", "Content-MD5", "Content-Range", "ETag", "Expires", "Last-Modified", "Range"
};
return this->header.header::get_field(header[h]).get_body();
}
/**
* @brief Get message header with certain string
* @param[in] header
* @param[in] message - HTTP message
* @param[out] None
* @return HTTP message head or "" (empty)
**/
const string message::get_msg_head(const string &head) const noexcept
{
return this->header.header::get_field(head).get_body();
}
/**
* @brief Get message body
* @param[in] None
* @return Message body
**/
const string &message::get_msg_body(void)
{
return this->sdbody.get();
}
/**
* @brief Get message body size
* @param[in] None
* @return Message body size
**/
ssize_t message::get_body_size(void)
{
return this->sdbody.size();
}
/**
* @brief Get message part
* @param[in] _inx - part index
* @param[out] None
* @return Message part mime entity poniter OR NULL
* @note 1. The function only get the brother part, to use the return pointer, if deeper part should be get
* 2. Check the return value, otherwise cause 'core dump' error
**/
const class mime_entity *message::get_msg_part(string::size_type _inx)
{
return this->get_part(_inx);
}
/**
* @brief Clear message
* @param[in] None
* @param[out] None
* @return None
**/
void message::clear(void)
{
this->message_line.clear();
this->mime_entity::clear();
return;
}
|
#include <ros/ros.h>
#include "ros_hsc3api.h"
int main(int argc, char *argv[])
{
ros::init(argc, argv, "hsc3api_bridge");
ros::NodeHandle n;
ros::AsyncSpinner as(2);
as.start();
Hsc3ApiRos s(n);
s.start();
ros::waitForShutdown();
}
|
/*
+----------------------------------------------------------------------+
| HipHop for PHP |
+----------------------------------------------------------------------+
| Copyright (c) 2010-2013 Facebook, Inc. (http://www.facebook.com) |
+----------------------------------------------------------------------+
| This source file is subject to version 3.01 of the PHP license, |
| that is bundled with this package in the file LICENSE, and is |
| available through the world-wide-web at the following url: |
| http://www.php.net/license/3_01.txt |
| If you did not receive a copy of the PHP license and are unable to |
| obtain it through the world-wide-web, please send a note to |
| license@php.net so we can mail you a copy immediately. |
+----------------------------------------------------------------------+
*/
#include "hphp/util/shared-memory-allocator.h"
#include "hphp/util/exception.h"
namespace HPHP {
///////////////////////////////////////////////////////////////////////////////
const char *SharedMemoryManager::Name = "HPHPSharedMemory";
boost::interprocess::managed_shared_memory *
SharedMemoryManager::Segment = nullptr;
// just to make valgrind cleaner
class SharedMemoryManagerUninitializer {
public:
~SharedMemoryManagerUninitializer() {
SharedMemoryManager::Reset();
}
};
static SharedMemoryManagerUninitializer s_smm_uninitializer;
void SharedMemoryManager::Init(int size, bool clean) {
try {
if (Segment == nullptr) {
if (clean) {
boost::interprocess::shared_memory_object::remove(Name);
}
Segment = new boost::interprocess::managed_shared_memory
(boost::interprocess::open_or_create, Name, size);
}
} catch (std::exception &e) {
throw Exception("%s", e.what()); // so we have stacktrace
}
}
void SharedMemoryManager::Reset() {
delete Segment;
}
///////////////////////////////////////////////////////////////////////////////
}
|
// Copyright (c) 2011-2017 The Cryptonote developers
// Copyright (c) 2017-2018 The Circle Foundation & Conceal Devs
// Copyright (c) 2018-2019 Conceal Network & Conceal Devs
// Distributed under the MIT/X11 software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
#include "Ipv4Address.h"
#include <stdexcept>
namespace System {
namespace {
uint8_t readUint8(const std::string& source, size_t& offset) {
if (offset == source.size() || source[offset] < '0' || source[offset] > '9') {
throw std::runtime_error("Unable to read value from string");
}
uint8_t value = source[offset] - '0';
if (offset + 1 == source.size() || source[offset + 1] < '0' || source[offset + 1] > '9') {
offset = offset + 1;
return value;
}
if (value == 0) {
throw std::runtime_error("Unable to read value from string");
}
value = value * 10 + (source[offset + 1] - '0');
if (offset + 2 == source.size() || source[offset + 2] < '0' || source[offset + 2] > '9') {
offset = offset + 2;
return value;
}
if ((value == 25 && source[offset + 2] > '5') || value > 25) {
throw std::runtime_error("Unable to read value from string");
}
value = value * 10 + (source[offset + 2] - '0');
offset = offset + 3;
return value;
}
}
Ipv4Address::Ipv4Address(uint32_t value) : value(value) {
}
Ipv4Address::Ipv4Address(const std::string& dottedDecimal) {
size_t offset = 0;
value = readUint8(dottedDecimal, offset);
if (offset == dottedDecimal.size() || dottedDecimal[offset] != '.') {
throw std::runtime_error("Invalid Ipv4 address string");
}
++offset;
value = value << 8 | readUint8(dottedDecimal, offset);
if (offset == dottedDecimal.size() || dottedDecimal[offset] != '.') {
throw std::runtime_error("Invalid Ipv4 address string");
}
++offset;
value = value << 8 | readUint8(dottedDecimal, offset);
if (offset == dottedDecimal.size() || dottedDecimal[offset] != '.') {
throw std::runtime_error("Invalid Ipv4 address string");
}
++offset;
value = value << 8 | readUint8(dottedDecimal, offset);
if (offset < dottedDecimal.size()) {
throw std::runtime_error("Invalid Ipv4 address string");
}
}
bool Ipv4Address::operator!=(const Ipv4Address& other) const {
return value != other.value;
}
bool Ipv4Address::operator==(const Ipv4Address& other) const {
return value == other.value;
}
uint32_t Ipv4Address::getValue() const {
return value;
}
std::string Ipv4Address::toDottedDecimal() const {
std::string result;
result += std::to_string(value >> 24);
result += '.';
result += std::to_string(value >> 16 & 255);
result += '.';
result += std::to_string(value >> 8 & 255);
result += '.';
result += std::to_string(value & 255);
return result;
}
bool Ipv4Address::isLoopback() const {
// 127.0.0.0/8
return (value & 0xff000000) == (127 << 24);
}
bool Ipv4Address::isPrivate() const {
return
// 10.0.0.0/8
(value & 0xff000000) == (10 << 24) ||
// 172.16.0.0/12
(value & 0xfff00000) == ((172 << 24) | (16 << 16)) ||
// 192.168.0.0/16
(value & 0xffff0000) == ((192 << 24) | (168 << 16));
}
}
|
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
#include "comwrappers.hpp"
#include <interoplibimports.h>
using OBJECTHANDLE = InteropLib::OBJECTHANDLE;
using RuntimeCallContext = InteropLibImports::RuntimeCallContext;
namespace
{
const IID IID_IReferenceTrackerHost = __uuidof(IReferenceTrackerHost);
const IID IID_IReferenceTrackerTarget = __uuidof(IReferenceTrackerTarget);
const IID IID_IReferenceTracker = __uuidof(IReferenceTracker);
const IID IID_IReferenceTrackerManager = __uuidof(IReferenceTrackerManager);
const IID IID_IFindReferenceTargetsCallback = __uuidof(IFindReferenceTargetsCallback);
// In order to minimize the impact of a constructor running on module load,
// the HostServices class should have no instance fields.
class HostServices : public IReferenceTrackerHost
{
public: // IReferenceTrackerHost
STDMETHOD(DisconnectUnusedReferenceSources)(_In_ DWORD dwFlags);
STDMETHOD(ReleaseDisconnectedReferenceSources)();
STDMETHOD(NotifyEndOfReferenceTrackingOnThread)();
STDMETHOD(GetTrackerTarget)(_In_ IUnknown* obj, _Outptr_ IReferenceTrackerTarget** ppNewReference);
STDMETHOD(AddMemoryPressure)(_In_ UINT64 bytesAllocated);
STDMETHOD(RemoveMemoryPressure)(_In_ UINT64 bytesAllocated);
public: // IUnknown
// Lifetime maintained by stack - we don't care about ref counts
STDMETHOD_(ULONG, AddRef)() { return 1; }
STDMETHOD_(ULONG, Release)() { return 1; }
STDMETHOD(QueryInterface)(
/* [in] */ REFIID riid,
/* [iid_is][out] */ _COM_Outptr_ void __RPC_FAR* __RPC_FAR* ppvObject)
{
if (ppvObject == nullptr)
return E_POINTER;
if (IsEqualIID(riid, IID_IReferenceTrackerHost))
{
*ppvObject = static_cast<IReferenceTrackerHost*>(this);
}
else if (IsEqualIID(riid, IID_IUnknown))
{
*ppvObject = static_cast<IUnknown*>(this);
}
else
{
*ppvObject = nullptr;
return E_NOINTERFACE;
}
(void)AddRef();
return S_OK;
}
};
// Global instance of host services.
HostServices g_HostServicesInstance;
// Defined in windows.ui.xaml.hosting.referencetracker.h.
enum XAML_REFERENCETRACKER_DISCONNECT
{
// Indicates the disconnect is during a suspend and a GC can be trigger.
XAML_REFERENCETRACKER_DISCONNECT_SUSPEND = 0x00000001
};
STDMETHODIMP HostServices::DisconnectUnusedReferenceSources(_In_ DWORD flags)
{
InteropLibImports::GcRequest type = InteropLibImports::GcRequest::Default;
// Request a "stop the world" GC when a suspend is occurring.
if (flags & XAML_REFERENCETRACKER_DISCONNECT_SUSPEND)
type = InteropLibImports::GcRequest::FullBlocking;
return InteropLibImports::RequestGarbageCollectionForExternal(type);
}
STDMETHODIMP HostServices::ReleaseDisconnectedReferenceSources()
{
return InteropLibImports::WaitForRuntimeFinalizerForExternal();
}
STDMETHODIMP HostServices::NotifyEndOfReferenceTrackingOnThread()
{
return InteropLibImports::ReleaseExternalObjectsFromCurrentThread();
}
// Creates a proxy object (managed object wrapper) that points to the given IUnknown.
// The proxy represents the following:
// 1. Has a managed reference pointing to the external object
// and therefore forms a cycle that can be resolved by GC.
// 2. Forwards data binding requests.
//
// For example:
//
// Grid <---- NoCW Grid <-------- NoCW
// | ^ | ^
// | | Becomes | |
// v | v |
// Rectangle Rectangle ----->Proxy
//
// Arguments
// obj - An IUnknown* where a NoCW points to (Grid, in this case)
// Notes:
// 1. We can either create a new NoCW or get back an old one from the cache.
// 2. This obj could be a regular tracker runtime object for data binding.
// ppNewReference - The IReferenceTrackerTarget* for the proxy created
// The tracker runtime will call IReferenceTrackerTarget to establish a reference.
//
STDMETHODIMP HostServices::GetTrackerTarget(_In_ IUnknown* obj, _Outptr_ IReferenceTrackerTarget** ppNewReference)
{
if (obj == nullptr || ppNewReference == nullptr)
return E_INVALIDARG;
HRESULT hr;
// QI for IUnknown to get the identity unknown
ComHolder<IUnknown> identity;
RETURN_IF_FAILED(obj->QueryInterface(&identity));
// Get or create an existing implementation for this external.
ComHolder<IUnknown> target;
RETURN_IF_FAILED(InteropLibImports::GetOrCreateTrackerTargetForExternal(
identity,
InteropLib::Com::CreateObjectFlags_TrackerObject,
InteropLib::Com::CreateComInterfaceFlags_TrackerSupport,
(void**)&target));
return target->QueryInterface(IID_IReferenceTrackerTarget, (void**)ppNewReference);
}
STDMETHODIMP HostServices::AddMemoryPressure(_In_ UINT64 bytesAllocated)
{
return InteropLibImports::AddMemoryPressureForExternal(bytesAllocated);
}
STDMETHODIMP HostServices::RemoveMemoryPressure(_In_ UINT64 bytesAllocated)
{
return InteropLibImports::RemoveMemoryPressureForExternal(bytesAllocated);
}
VolatilePtr<IReferenceTrackerManager> s_TrackerManager; // The one and only Tracker Manager instance
Volatile<BOOL> s_HasTrackingStarted = FALSE;
// Indicates if walking the external objects is needed.
// (i.e. Have any IReferenceTracker instances been found?)
bool ShouldWalkExternalObjects()
{
return (s_TrackerManager != nullptr);
}
// Callback implementation of IFindReferenceTargetsCallback
class FindDependentWrappersCallback : public IFindReferenceTargetsCallback
{
NativeObjectWrapperContext* _nowCxt;
RuntimeCallContext* _runtimeCallCxt;
public:
FindDependentWrappersCallback(_In_ NativeObjectWrapperContext* nowCxt, _In_ RuntimeCallContext* runtimeCallCxt)
: _nowCxt{ nowCxt }
, _runtimeCallCxt{ runtimeCallCxt }
{
_ASSERTE(_nowCxt != nullptr && runtimeCallCxt != nullptr);
}
STDMETHOD(FoundTrackerTarget)(_In_ IReferenceTrackerTarget* target)
{
HRESULT hr;
if (target == nullptr)
return E_POINTER;
ManagedObjectWrapper* mow = ManagedObjectWrapper::MapFromIUnknown(target);
// Not a target we implemented or wrapper is marked to be destroyed.
if (mow == nullptr || mow->IsMarkedToDestroy())
return S_OK;
// Notify the runtime a reference path was found.
RETURN_IF_FAILED(InteropLibImports::FoundReferencePath(
_runtimeCallCxt,
_nowCxt->GetRuntimeContext(),
mow->Target));
return S_OK;
}
// Lifetime maintained by stack - we don't care about ref counts
STDMETHOD_(ULONG, AddRef)() { return 1; }
STDMETHOD_(ULONG, Release)() { return 1; }
STDMETHOD(QueryInterface)(
/* [in] */ REFIID riid,
/* [iid_is][out] */ _COM_Outptr_ void __RPC_FAR* __RPC_FAR* ppvObject)
{
if (ppvObject == nullptr)
return E_POINTER;
if (IsEqualIID(riid, IID_IFindReferenceTargetsCallback))
{
*ppvObject = static_cast<IFindReferenceTargetsCallback*>(this);
}
else if (IsEqualIID(riid, IID_IUnknown))
{
*ppvObject = static_cast<IUnknown*>(this);
}
else
{
*ppvObject = nullptr;
return E_NOINTERFACE;
}
(void)AddRef();
return S_OK;
}
};
HRESULT WalkExternalTrackerObjects(_In_ RuntimeCallContext* cxt)
{
_ASSERTE(cxt != nullptr);
BOOL walkFailed = FALSE;
HRESULT hr;
void* extObjContext = nullptr;
while (S_OK == (hr = InteropLibImports::IteratorNext(cxt, &extObjContext)))
{
_ASSERTE(extObjContext != nullptr);
NativeObjectWrapperContext* nowc = NativeObjectWrapperContext::MapFromRuntimeContext(extObjContext);
// Check if the object is a tracker object.
IReferenceTracker* trackerMaybe = nowc->GetReferenceTracker();
if (trackerMaybe == nullptr)
continue;
// Ask the tracker instance to find all reference targets.
FindDependentWrappersCallback cb{ nowc, cxt };
hr = trackerMaybe->FindTrackerTargets(&cb);
if (FAILED(hr))
break;
}
if (FAILED(hr))
{
// Remember the fact that we've failed and stop walking
walkFailed = TRUE;
InteropLibImports::SetGlobalPeggingState(true);
}
_ASSERTE(s_TrackerManager != nullptr);
(void)s_TrackerManager->FindTrackerTargetsCompleted(walkFailed);
return hr;
}
}
HRESULT TrackerObjectManager::OnIReferenceTrackerFound(_In_ IReferenceTracker* obj)
{
_ASSERTE(obj != nullptr);
if (s_TrackerManager != nullptr)
return S_OK;
// Retrieve IReferenceTrackerManager
HRESULT hr;
ComHolder<IReferenceTrackerManager> trackerManager;
RETURN_IF_FAILED(obj->GetReferenceTrackerManager(&trackerManager));
ComHolder<IReferenceTrackerHost> hostServices;
RETURN_IF_FAILED(g_HostServicesInstance.QueryInterface(IID_IReferenceTrackerHost, (void**)&hostServices));
// Attempt to set the tracker instance.
if (::InterlockedCompareExchangePointer((void**)&s_TrackerManager, trackerManager.p, nullptr) == nullptr)
{
(void)trackerManager.Detach(); // Ownership has been transfered
RETURN_IF_FAILED(s_TrackerManager->SetReferenceTrackerHost(hostServices));
}
return S_OK;
}
HRESULT TrackerObjectManager::AfterWrapperCreated(_In_ IReferenceTracker* obj)
{
_ASSERTE(obj != nullptr);
HRESULT hr;
// Notify tracker runtime that we've created a new wrapper for this object.
// To avoid surprises, we should notify them before we fire the first AddRefFromTrackerSource.
RETURN_IF_FAILED(obj->ConnectFromTrackerSource());
// Send out AddRefFromTrackerSource callbacks to notify tracker runtime we've done AddRef()
// for certain interfaces. We should do this *after* we made a AddRef() because we should never
// be in a state where report refs > actual refs
RETURN_IF_FAILED(obj->AddRefFromTrackerSource()); // IUnknown
RETURN_IF_FAILED(obj->AddRefFromTrackerSource()); // IReferenceTracker
return S_OK;
}
HRESULT TrackerObjectManager::BeforeWrapperDestroyed(_In_ IReferenceTracker* obj)
{
_ASSERTE(obj != nullptr);
HRESULT hr;
// Notify tracker runtime that we are about to destroy a wrapper
// (same timing as short weak handle) for this object.
// They need this information to disconnect weak refs and stop firing events,
// so that they can avoid resurrecting the object.
RETURN_IF_FAILED(obj->DisconnectFromTrackerSource());
return S_OK;
}
HRESULT TrackerObjectManager::BeginReferenceTracking(_In_ RuntimeCallContext* cxt)
{
_ASSERTE(cxt != nullptr);
if (!ShouldWalkExternalObjects())
return S_FALSE;
HRESULT hr;
_ASSERTE(s_HasTrackingStarted == FALSE);
_ASSERTE(InteropLibImports::GetGlobalPeggingState());
s_HasTrackingStarted = TRUE;
// Let the tracker runtime know we are about to walk external objects so that
// they can lock their reference cache. Note that the tracker runtime doesn't need to
// unpeg all external objects at this point and they can do the pegging/unpegging.
// in FindTrackerTargetsCompleted.
_ASSERTE(s_TrackerManager != nullptr);
RETURN_IF_FAILED(s_TrackerManager->ReferenceTrackingStarted());
// From this point, the tracker runtime decides whether a target
// should be pegged or not as the global pegging flag is now off.
InteropLibImports::SetGlobalPeggingState(false);
// Time to walk the external objects
RETURN_IF_FAILED(WalkExternalTrackerObjects(cxt));
return S_OK;
}
HRESULT TrackerObjectManager::EndReferenceTracking()
{
if (s_HasTrackingStarted != TRUE
|| !ShouldWalkExternalObjects())
return S_FALSE;
HRESULT hr;
// Let the tracker runtime know the external object walk is done and they need to:
// 1. Unpeg all managed object wrappers (mow) if the (mow) needs to be unpegged
// (i.e. when the (mow) is only reachable by other external tracker objects).
// 2. Peg all mows if the mow needs to be pegged (i.e. when the above condition is not true)
// 3. Unlock reference cache when they are done.
_ASSERTE(s_TrackerManager != nullptr);
hr = s_TrackerManager->ReferenceTrackingCompleted();
_ASSERTE(SUCCEEDED(hr));
InteropLibImports::SetGlobalPeggingState(true);
s_HasTrackingStarted = FALSE;
return hr;
}
|
#include<stdint.h>
#include<assert.h>
class BoundedBuffer {
int capacity;
int64_t head, tail;
int * buffer;
public:
BoundedBuffer(uint32_t sz):capacity(sz), head(0), tail(-1) {
buffer= new int[sz];
}
~BoundedBuffer() {
delete buffer;
}
bool Enq(const int data) {
// invariant num_elements = tail - head + 1.
if (tail - head + 1 == capacity) {
return false; // queue full
}
tail ++;
buffer[tail % capacity] = data;
return true;
}
bool Deq(int &data) {
// invariant num_elements = tail - head + 1.
// ==> head > tail means queue empty
if (head > tail) {
return false; // empty
}
data = buffer[head % capacity];
head ++;
return true;
}
};
int main() {
auto b = BoundedBuffer(1);
int x;
assert(false == b.Deq(x));
assert(true == b.Enq(200));
assert(false == b.Enq(300));
assert(true == b.Deq(x)) ;
assert(200 == x);
assert(false == b.Deq(x));
assert(true == b.Enq(300));
assert(false == b.Enq(500));
assert(true == b.Deq(x)) ;
assert(300 == x);
return 0;
}
|
// Copyright (c) 2003-2020 Xsens Technologies B.V. or subsidiaries worldwide.
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without modification,
// are permitted provided that the following conditions are met:
//
// 1. Redistributions of source code must retain the above copyright notice,
// this list of conditions, and the following disclaimer.
//
// 2. Redistributions in binary form must reproduce the above copyright notice,
// this list of conditions, and the following disclaimer in the documentation
// and/or other materials provided with the distribution.
//
// 3. Neither the names of the copyright holders nor the names of their 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.THE LAWS OF THE NETHERLANDS
// SHALL BE EXCLUSIVELY APPLICABLE AND ANY DISPUTES SHALL BE FINALLY SETTLED UNDER THE RULES
// OF ARBITRATION OF THE INTERNATIONAL CHAMBER OF COMMERCE IN THE HAGUE BY ONE OR MORE
// ARBITRATORS APPOINTED IN ACCORDANCE WITH SAID RULES.
//
#include "xswinusb.h"
#ifdef USE_WINUSB
#include <xstypes/xslibraryloader.h>
/*! \class XsWinUsb
\brief Class for dynamic loading of winusb
*/
XsWinUsb::XsWinUsb(void)
{
m_libraryLoader = new XsLibraryLoader();
initLibrary();
}
XsWinUsb::~XsWinUsb(void)
{
delete m_libraryLoader;
}
void XsWinUsb::initLibrary()
{
if (!m_libraryLoader->isLoaded())
m_libraryLoader->load("winusb.dll");
m_winUsb.AbortPipe = NULL;
m_winUsb.Initialize = NULL;
m_winUsb.Free = NULL;
m_winUsb.GetAssociatedInterface = NULL;
m_winUsb.GetDescriptor = NULL;
m_winUsb.QueryInterfaceSettings = NULL;
m_winUsb.QueryDeviceInformation = NULL;
m_winUsb.SetCurrentAlternateSetting = NULL;
m_winUsb.GetCurrentAlternateSetting = NULL;
m_winUsb.QueryPipe = NULL;
m_winUsb.SetPipePolicy = NULL;
m_winUsb.GetPipePolicy = NULL;
m_winUsb.ReadPipe = NULL;
m_winUsb.WritePipe = NULL;
m_winUsb.ControlTransfer = NULL;
m_winUsb.ResetPipe = NULL;
m_winUsb.AbortPipe = NULL;
m_winUsb.FlushPipe = NULL;
m_winUsb.SetPowerPolicy = NULL;
m_winUsb.GetPowerPolicy = NULL;
m_winUsb.GetOverlappedResult = NULL;
if (m_libraryLoader->isLoaded())
{
m_winUsb.AbortPipe = (WinUSB_AbortPipe*)m_libraryLoader->resolve("WinUsb_AbortPipe");
m_winUsb.Initialize = (WinUSB_Initialize*)m_libraryLoader->resolve("WinUsb_Initialize");
m_winUsb.Free = (WinUSB_Free*)m_libraryLoader->resolve("WinUsb_Free");
m_winUsb.GetAssociatedInterface = (WinUSB_GetAssociatedInterface*)m_libraryLoader->resolve("WinUsb_GetAssociatedInterface");
m_winUsb.GetDescriptor = (WinUSB_GetDescriptor*)m_libraryLoader->resolve("WinUsb_GetDescriptor");
m_winUsb.QueryInterfaceSettings = (WinUSB_QueryInterfaceSettings*)m_libraryLoader->resolve("WinUsb_QueryInterfaceSettings");
m_winUsb.QueryDeviceInformation = (WinUSB_QueryDeviceInformation*)m_libraryLoader->resolve("WinUsb_QueryDeviceInformation");
m_winUsb.SetCurrentAlternateSetting = (WinUSB_SetCurrentAlternateSetting*)m_libraryLoader->resolve("WinUsb_SetCurrentAlternateSetting");
m_winUsb.GetCurrentAlternateSetting = (WinUSB_GetCurrentAlternateSetting*)m_libraryLoader->resolve("WinUsb_GetCurrentAlternateSetting");
m_winUsb.QueryPipe = (WinUSB_QueryPipe*)m_libraryLoader->resolve("WinUsb_QueryPipe");
m_winUsb.SetPipePolicy = (WinUSB_SetPipePolicy*)m_libraryLoader->resolve("WinUsb_SetPipePolicy");
m_winUsb.GetPipePolicy = (WinUSB_GetPipePolicy*)m_libraryLoader->resolve("WinUsb_GetPipePolicy");
m_winUsb.ReadPipe = (WinUSB_ReadPipe*)m_libraryLoader->resolve("WinUsb_ReadPipe");
m_winUsb.WritePipe = (WinUSB_WritePipe*)m_libraryLoader->resolve("WinUsb_WritePipe");
m_winUsb.ControlTransfer = (WinUSB_ControlTransfer*)m_libraryLoader->resolve("WinUsb_ControlTransfer");
m_winUsb.ResetPipe = (WinUSB_ResetPipe*)m_libraryLoader->resolve("WinUsb_ResetPipe");
m_winUsb.AbortPipe = (WinUSB_AbortPipe*)m_libraryLoader->resolve("WinUsb_AbortPipe");
m_winUsb.FlushPipe = (WinUSB_FlushPipe*)m_libraryLoader->resolve("WinUsb_FlushPipe");
m_winUsb.SetPowerPolicy = (WinUSB_SetPowerPolicy*)m_libraryLoader->resolve("WinUsb_SetPowerPolicy");
m_winUsb.GetPowerPolicy = (WinUSB_GetPowerPolicy*)m_libraryLoader->resolve("WinUsb_GetPowerPolicy");
m_winUsb.GetOverlappedResult = (WinUSB_GetOverlappedResult*)m_libraryLoader->resolve("WinUsb_GetOverlappedResult");
}
}
/*! \brief Creates/opens a WinUsb interface handle from the device list.
\param[out] InterfaceHandle Receives a handle configured to the first (default) interface on the device. This handle is required by other WinUsb routines that perform operations on the default interface. The handle is opaque. To release this handle, call the \a Free function.
\param[in] DevInfo The device list element to open.
\returns On success, TRUE. Otherwise FALSE. Use GetLastError() to get extended error information.
*/
BOOL XsWinUsb::Initialize(HANDLE DeviceHandle, PWINUSB_INTERFACE_HANDLE InterfaceHandle)
{
if (m_winUsb.Initialize)
return m_winUsb.Initialize(DeviceHandle, InterfaceHandle);
else
return FALSE;
}
/*! \brief Frees a WinUsb interface handle.
\param[in] InterfaceHandle Handle to an interface on the device. This handle must be created by a previous call to see \a Initialize or \a GetAssociatedInterface.
\returns TRUE
\sa GetAssociatedInterface.
*/
BOOL XsWinUsb::Free(WINUSB_INTERFACE_HANDLE InterfaceHandle)
{
if (m_winUsb.Free)
return m_winUsb.Free(InterfaceHandle);
else
return FALSE;
}
/*! \brief Retrieves a handle for an associated interface.
\param[in] InterfaceHandle An initialized usb handle, see \a Initialize.
\param[in] AssociatedInterfaceIndex An index that specifies the associated interface to retrieve. A value of 0 indicates the first associated interface, a value of 1 indicates the second associated interface, and so on.
\param[out] AssociatedInterfaceHandle A handle for the associated interface. Callers must pass this interface handle to WinUsb Functions exposed by WinUsb.dll. To close this handle, call Free.
\returns On success, TRUE. Otherwise FALSE. Use GetLastError() to get extended error information.
*/
BOOL XsWinUsb::GetAssociatedInterface(WINUSB_INTERFACE_HANDLE InterfaceHandle,UCHAR AssociatedInterfaceIndex, PWINUSB_INTERFACE_HANDLE AssociatedInterfaceHandle)
{
if (m_winUsb.GetAssociatedInterface)
return m_winUsb.GetAssociatedInterface(InterfaceHandle, AssociatedInterfaceIndex, AssociatedInterfaceHandle);
else
return FALSE;
}
/*! \brief Gets the requested descriptor. This is a synchronous operation.
\param[in] InterfaceHandle An initialized usb handle, see \a Initialize.
\param[in] DescriptorType A value that specifies the type of descriptor to return. This parameter corresponds to the bDescriptorType field of a standard device descriptor, whose values are described in the Universal Serial Bus specification.
\param[in] Index The descriptor index. For an explanation of the descriptor index, see the Universal Serial Bus specification (www.usb.org).
\param[in] LanguageID A value that specifies the language identifier, if the requested descriptor is a string descriptor.
\param[out] Buffer A caller-allocated buffer that receives the requested descriptor.
\param[in] BufferLength The length, in bytes, of Buffer.
\param[out] LengthTransferred The number of bytes that were copied into Buffer.
\returns On success, TRUE. Otherwise FALSE. Use GetLastError() to get extended error information.
*/
BOOL XsWinUsb::GetDescriptor(WINUSB_INTERFACE_HANDLE InterfaceHandle,UCHAR DescriptorType, UCHAR Index,USHORT LanguageID,PUCHAR Buffer,ULONG BufferLength,PULONG LengthTransferred)
{
if (m_winUsb.GetDescriptor)
return m_winUsb.GetDescriptor(InterfaceHandle, DescriptorType, Index, LanguageID, Buffer, BufferLength, LengthTransferred);
else
return FALSE;
}
/*! \brief Retrieves the interface descriptor for the specified alternate interface settings for a particular interface handle.
The \a QueryInterfaceSettings call searches the current/default interface array for the alternate interface specified by the caller in the \a AltSettingIndex.
If the specified alternate interface is found, the function populates the caller-allocated USB_INTERFACE_DESCRIPTOR structure.
If the specified alternate interface is not found, then the call fails with the ERROR_NO_MORE_ITEMS code.
\param[in] InterfaceHandle An initialized usb handle, see \a Initialize.
\param[in] AltSettingIndex A value that indicates which alternate setting index to return. A value of 0 indicates the first alternate setting, a value of 1 indicates the second alternate setting, and so on.
\param[out] UsbAltInterfaceDescriptor A pointer to a caller-allocated USB_INTERFACE_DESCRIPTOR structure that contains information about the interface that AltSettingNumber specified.
\returns On success, TRUE. Otherwise FALSE. Use GetLastError() to get extended error information.
*/
BOOL XsWinUsb::QueryInterfaceSettings(WINUSB_INTERFACE_HANDLE InterfaceHandle,UCHAR AlternateInterfaceNumber,PUSB_INTERFACE_DESCRIPTOR UsbAltInterfaceDescriptor)
{
if (m_winUsb.QueryInterfaceSettings)
return m_winUsb.QueryInterfaceSettings(InterfaceHandle, AlternateInterfaceNumber, UsbAltInterfaceDescriptor);
else
return FALSE;
}
/*! \brief Retrieves information about the physical device that is associated with a WinUSB handle.
\param[in] InterfaceHandle An initialized usb handle, see \a Initialize.
\param[in] InformationType A value that specifies which interface information value to retrieve. On input, InformationType must have the following value: DEVICE_SPEED (0x01).
\param[in,out] BufferLength The maximum number of bytes to read. This number must be less than or equal to the size, in bytes, of Buffer. On output, BufferLength is set to the actual number of bytes that were copied into Buffer.
\param[in,out] Buffer A caller-allocated buffer that receives the requested value. On output, Buffer indicates the device speed:
(0x01) low/full speed device.
(0x03) high speed device.
\returns On success, TRUE. Otherwise FALSE. Use GetLastError() to get extended error information.
*/
BOOL XsWinUsb::QueryDeviceInformation(WINUSB_INTERFACE_HANDLE InterfaceHandle,ULONG InformationType,PULONG BufferLength,PVOID Buffer)
{
if (m_winUsb.QueryDeviceInformation)
return m_winUsb.QueryDeviceInformation(InterfaceHandle, InformationType, BufferLength, Buffer);
else
return FALSE;
}
/*! \brief Sets the alternate setting of an interface.
Sets the active \a bAlternateSetting for the current/default interface.
\param[in] InterfaceHandle An initialized usb handle, see \a Initialize.
\param[in] AltSettingNumber The value that is contained in the \a bAlternateSetting member of the USB_INTERFACE_DESCRIPTOR structure. This structure can be populated by the \a QueryInterfaceSettings routine.
\returns On success, TRUE. Otherwise FALSE. Use GetLastError() to get extended error information.
\sa QueryInterfaceSettings
*/
BOOL XsWinUsb::SetCurrentAlternateSetting(WINUSB_INTERFACE_HANDLE InterfaceHandle,UCHAR SettingNumber)
{
if (m_winUsb.SetCurrentAlternateSetting)
return m_winUsb.SetCurrentAlternateSetting(InterfaceHandle, SettingNumber);
else
return FALSE;
}
/*! \brief Gets the current alternate interface setting for an interface.
Gets the active bAlternateSetting for the current/default interface.
\param[in] InterfaceHandle An initialized usb handle, see \a Initialize.
\param[out] AltSettingNumber A pointer to an unsigned character that receives an integer that indicates the current alternate setting.
\returns On success, TRUE. Otherwise FALSE. Use GetLastError() to get extended error information.
*/
BOOL XsWinUsb::GetCurrentAlternateSetting(WINUSB_INTERFACE_HANDLE InterfaceHandle,PUCHAR SettingNumber)
{
if (m_winUsb.GetCurrentAlternateSetting)
return m_winUsb.GetCurrentAlternateSetting(InterfaceHandle, SettingNumber);
else
return FALSE;
}
/*! \brief Retrieves information about a pipe that is associated with an interface.
The \a QueryPipe function does not retrieve information about the control pipe.
Each interface on the USB device can have multiple endpoints. To communicate with each of these endpoints, the bus driver creates pipes for each endpoint on the interface.
The pipe indices are zero-based. Therefore for n number of endpoints, the pipes' indices are set from n-1.
\a QueryPipe parses the configuration descriptor to get the interface specified by the caller.
It searches the interface descriptor for the endpoint descriptor associated with the caller-specified pipe.
If the endpoint is found, the function populates the caller-allocated WINUSB_PIPE_INFORMATION structure with information from the endpoint descriptor.
\param[in] InterfaceHandle An initialized usb handle, see \a Initialize.
\param[in] AltSettingNumber A value that specifies the alternate interface to return the information for.
\param[in] PipeIndex A value that specifies the pipe to return information about. This value is not the same as the bEndpointAddress field in the endpoint descriptor.
A PipeIndex value of 0 signifies the first endpoint that is associated with the interface, a value of 1 signifies the second endpoint, and so on.
PipeIndex must be less than the value in the bNumEndpoints field of the interface descriptor.
\param[out] PipeInformation A pointer, on output, to a caller-allocated WINUSB_PIPE_INFORMATION structure that contains pipe information.
\returns On success, TRUE. Otherwise FALSE. Use GetLastError() to get extended error information.
*/
BOOL XsWinUsb::QueryPipe(WINUSB_INTERFACE_HANDLE InterfaceHandle,UCHAR AlternateInterfaceNumber,UCHAR PipeIndex,PWINUSB_PIPE_INFORMATION PipeInformation)
{
if (m_winUsb.QueryPipe)
return m_winUsb.QueryPipe(InterfaceHandle, AlternateInterfaceNumber, PipeIndex, PipeInformation);
else
return FALSE;
}
/*! \brief Sets the policy for a specific pipe associated with an endpoint on the device. This is a synchronous operation.
\param[in] InterfaceHandle An initialized usb handle, see \a Initialize.
\param[in] PipeID An 8-bit value that consists of a 7-bit address and a direction bit. This parameter corresponds to the bEndpointAddress field in the endpoint descriptor.
\param[in] PolicyType A UINT variable that specifies the policy parameter to change. The Value parameter contains the new value for the policy parameter.
See the remarks section for information about each of the pipe policies and the resulting behavior.
\param[in] ValueLength The size, in bytes, of the buffer at Value.
\param[in] Value The new value for the policy parameter that PolicyType specifies. The size of this input parameter depends on the policy to change. For information about the size of this parameter, see the description of the PolicyType parameter.
\remarks
The following list describes symbolic constants for \a PolicyType
- SHORT_PACKET_TERMINATE (0x01)
- The default value is FALSE.
- To enable SHORT_PACKET_TERMINATE, in Value pass the address of a caller-allocated UCHAR variable set to TRUE (nonzero).
- Enabling SHORT_PACKET_TERMINATE causes the driver to send a zero-length packet at the end of every write request to the host controller.
- AUTO_CLEAR_STALL (0x02)
- The default value is FALSE. To enable AUTO_CLEAR_STALL, in Value pass the address of a caller-allocated UCHAR variable set to TRUE (nonzero).
- Enabling AUTO_CLEAR_STALL causes winUSB to reset the pipe in order to automatically clear the stall condition. Data continues to flow on the bulk and interrupt IN endpoints again as soon as a new or a queued transfer arrives on the endpoint. This policy parameter does not affect control pipes.
- Disabling AUTO_CLEAR_STALL causes all transfers (that arrive to the endpoint after the stalled transfer) to fail until the caller manually resets the endpoint's pipe by calling ResetPipe.
- PIPE_TRANSFER_TIMEOUT (0x03)
- The default value is zero. To set a time-out value, in Value pass the address of a caller-allocated UINT variable that contains the time-out interval.
- The PIPE_TRANSFER_TIMEOUT value specifies the time-out interval, in milliseconds. The host controller cancels transfers that do not complete within the specified time-out interval.
- A value of zero (default) indicates that transfers do not time out because the host controller never cancels the transfer.
- IGNORE_SHORT_PACKETS (0x04)
- The default value is FALSE. To enable IGNORE_SHORT_PACKETS, in Value pass the address of a caller-allocated UCHAR variable set to TRUE (nonzero).
- Enabling IGNORE_SHORT_PACKETS causes the host controller to not complete a read operation after it receives a short packet. Instead, the host controller completes the operation only after the host has read the specified number of bytes.
- Disabling IGNORE_SHORT_PACKETS causes the host controller to complete a read operation when either the host has read the specified number of bytes or the host has received a short packet.
- ALLOW_PARTIAL_READS (0x05)
- The default value is TRUE (nonzero). To disable ALLOW_PARTIAL_READS, in Value pass the address of a caller-allocated UCHAR variable set to FALSE (zero).
- Disabling ALLOW_PARTIAL_READS causes the read requests to fail whenever the device returns more data (on bulk and interrupt IN endpoints) than the caller requested.
- Enabling ALLOW_PARTIAL_READS causes winUSB to save or discard the extra data when the device returns more data (on bulk and interrupt IN endpoints) than the caller requested. This behavior is defined by setting the AUTO_FLUSH value.
- AUTO_FLUSH (0x06)
- The default value is FALSE (zero). To enable AUTO_FLUSH, in Value pass the address of a caller-allocated UCHAR variable set to TRUE (nonzero).
- AUTO_FLUSH must be used with ALLOW_PARTIAL_READS enabled. If ALLOW_PARTIAL_READS is TRUE, the value of AUTO_FLUSH determines the action taken by winUSB when the device returns more data than the caller requested.
- Disabling ALLOW_PARTIAL_READS causes winUSB to ignore the AUTO_FLUSH value.
- Disabling AUTO_FLUSH with ALLOW_PARTIAL_READS enabled causes winUSB to save the extra data, add the data to the beginning of the caller's next read request, and send it to the caller in the next read operation.
- Enabling AUTO_FLUSH with ALLOW_PARTIAL_READS enabled causes winUSB to discard the extra data remaining from the read request.
- RAW_IO (0x07)
- The default value is FALSE (zero). To enable RAW_IO, in Value pass the address of a caller-allocated UCHAR variable set to TRUE (nonzero).
- Enabling RAW_IO causes winUSB to send data directly to the USB driver stack, bypassing winUSB's queuing and error handling mechanism.
- The buffers that are passed to \a ReadPipe must be configured by the caller as follows:
- The buffer length must be a multiple of the maximum endpoint packet size.
- The length must be less than or equal to the value of MAXIMUM_TRANSFER_SIZE retrieved by GetPipePolicy.
- Disabling RAW_IO (FALSE) does not impose any restriction on the buffers that are passed to \a ReadPipe.
- RESET_PIPE_ON_RESUME (0x09)
- The default value is FALSE (zero). To enable RESET_PIPE_ON_RESUME, in Value pass the address of a caller-allocated UCHAR variable set to TRUE (nonzero).
- TRUE (or a nonzero value) indicates that on resume from suspend, winUSB resets the endpoint before it allows the caller to send new requests to the endpoint.
\returns On success, TRUE. Otherwise FALSE. Use GetLastError() to get extended error information.
*/
BOOL XsWinUsb::SetPipePolicy(WINUSB_INTERFACE_HANDLE InterfaceHandle,UCHAR PipeID,ULONG PolicyType,ULONG ValueLength,PVOID Value)
{
if (m_winUsb.SetPipePolicy)
return m_winUsb.SetPipePolicy(InterfaceHandle, PipeID, PolicyType, ValueLength, Value);
else
return FALSE;
}
/*! \brief Gets the policy for a specific pipe (endpoint).
\param[in] InterfaceHandle An initialized usb handle, see \a Initialize.
\param[in] PipeID An 8-bit value that consists of a 7-bit address and a direction bit. This parameter corresponds to the bEndpointAddress field in the endpoint descriptor.
\param[in] PolicyType A UINT variable that specifies the policy parameter to retrieve. The current value for the policy parameter is retrieved the Value parameter.
\param[in,out] ValueLength A pointer to the size, in bytes, of the buffer that Value points to. On output, ValueLength receives the size, in bytes, of the data that was copied into the Value buffer.
\param[out] Value A pointer to a buffer that receives the specified pipe policy value.
\returns On success, TRUE. Otherwise FALSE. Use GetLastError() to get extended error information.
*/
BOOL XsWinUsb::GetPipePolicy(WINUSB_INTERFACE_HANDLE InterfaceHandle,UCHAR PipeID,ULONG PolicyType,PULONG ValueLength,PVOID Value)
{
if (m_winUsb.GetPipePolicy)
return m_winUsb.GetPipePolicy(InterfaceHandle, PipeID, PolicyType, ValueLength, Value);
else
return FALSE;
}
/*! \brief Reads data from the specified pipe.
\param[in] InterfaceHandle An initialized usb handle, see \a Initialize.
\param[in] PipeID An 8-bit value that consists of a 7-bit address and a direction bit. This parameter corresponds to the bEndpointAddress field in the endpoint descriptor.
\param[out] Buffer A caller-allocated buffer that receives the data that is read.
\param[in] BufferLength The maximum number of bytes to read. This number must be less than or equal to the size, in bytes, of Buffer.
\param[out] LengthTransferred A pointer to a UINT variable that receives the actual number of bytes that were copied into Buffer. For more information, see Remarks.
\param[in] Overlapped An optional pointer to an overlapped structure for asynchronous operations. This can be a KOVL_HANDLE or a pointer to a standard windows OVERLAPPED structure.
If this parameter is specified, \a ReadPipe returns immediately rather than waiting synchronously for the operation to complete before returning. An event is signaled when the operation is complete.
\returns On success, TRUE. Otherwise FALSE. Use GetLastError() to get extended error information.
*/
BOOL XsWinUsb::ReadPipe(WINUSB_INTERFACE_HANDLE InterfaceHandle, UCHAR PipeID, PUCHAR Buffer, ULONG BufferLength, PULONG LengthTransferred,LPOVERLAPPED Overlapped)
{
if (m_winUsb.ReadPipe)
return m_winUsb.ReadPipe(InterfaceHandle, PipeID, Buffer, BufferLength, LengthTransferred, Overlapped);
else
return FALSE;
}
/*! \brief Writes data to a pipe.
\param[in] InterfaceHandle An initialized usb handle, see \a Initialize.
\param[in] PipeID An 8-bit value that consists of a 7-bit address and a direction bit. This parameter corresponds to the bEndpointAddress field in the endpoint descriptor.
\param[in] Buffer A caller-allocated buffer the data is written from.
\param[in] BufferLength The maximum number of bytes to write. This number must be less than or equal to the size, in bytes, of Buffer.
\param[out] LengthTransferred A pointer to a UINT variable that receives the actual number of bytes that were transferred from Buffer.
\param[in] Overlapped An optional pointer to an overlapped structure for asynchronous operations. This can be a KOVL_HANDLE or a pointer to a standard windows OVERLAPPED structure.
If this parameter is specified, \a WritePipe returns immediately rather than waiting synchronously for the operation to complete before returning. An event is signaled when the operation is complete.
\returns On success, TRUE. Otherwise FALSE. Use GetLastError() to get extended error information.
*/
BOOL XsWinUsb::WritePipe(WINUSB_INTERFACE_HANDLE InterfaceHandle, UCHAR PipeID, PUCHAR Buffer, ULONG BufferLength, PULONG LengthTransferred,LPOVERLAPPED Overlapped)
{
if (m_winUsb.WritePipe)
return m_winUsb.WritePipe(InterfaceHandle, PipeID, Buffer, BufferLength, LengthTransferred, Overlapped);
else
return FALSE;
}
/*! \brief Transmits control data over a default control endpoint.
A ControlTransfer is never cached. These requests always go directly to the usb device.
\param[in] InterfaceHandle A valid winUSB interface handle returned by:
- Initialize
- GetAssociatedInterface
\param[in] SetupPacket The 8-byte setup packet of type WINUSB_SETUP_PACKET.
\param[in,out] Buffer A caller-allocated buffer that contains the data to transfer.
\param[in] BufferLength The number of bytes to transfer, not including the setup packet. This number must be less than or equal to the size, in bytes, of Buffer.
\param[out] LengthTransferred A pointer to a UINT variable that receives the actual number of transferred bytes. If the application does not expect any data to be transferred during the data phase (BufferLength is zero), LengthTransferred can be NULL.
\param[in] Overlapped An optional pointer to an OVERLAPPED structure, which is used for asynchronous operations. If this parameter is specified, ControlTransfer immediately returns, and the event is signaled when the operation is complete. If Overlapped is not supplied, the ControlTransfer function transfers data synchronously.
\returns On success, TRUE. Otherwise FALSE. Use GetLastError() to get extended error information. If an Overlapped member is supplied and the operation succeeds this function returns FALSE and sets last error to ERROR_IO_PENDING.
*/
BOOL XsWinUsb::ControlTransfer(WINUSB_INTERFACE_HANDLE InterfaceHandle, WINUSB_SETUP_PACKET SetupPacket, PUCHAR Buffer, ULONG BufferLength, PULONG LengthTransferred, LPOVERLAPPED Overlapped)
{
if (m_winUsb.ControlTransfer)
return m_winUsb.ControlTransfer(InterfaceHandle, SetupPacket, Buffer, BufferLength, LengthTransferred, Overlapped);
else
return FALSE;
}
/*! \brief Resets the data toggle and clears the stall condition on a pipe.
\param[in] InterfaceHandle An initialized usb handle, see \a Initialize.
\param[in] PipeID An 8-bit value that consists of a 7-bit address and a direction bit. This parameter corresponds to the \a bEndpointAddress field in the endpoint descriptor.
\returns On success, TRUE. Otherwise FALSE. Use GetLastError() to get extended error information.
*/
BOOL XsWinUsb::ResetPipe(WINUSB_INTERFACE_HANDLE InterfaceHandle, UCHAR PipeID)
{
if (m_winUsb.ResetPipe)
return m_winUsb.ResetPipe(InterfaceHandle, PipeID);
else
return FALSE;
}
/*! \brief Aborts all of the pending transfers for a pipe.
\param[in] InterfaceHandle An initialized usb handle, see \a Initialize.
\param[in] PipeID An 8-bit value that consists of a 7-bit address and a direction bit. This parameter corresponds to the \a bEndpointAddress field in the endpoint descriptor.
\returns On success, TRUE. Otherwise FALSE. Use GetLastError() to get extended error information.
*/
BOOL XsWinUsb::AbortPipe(WINUSB_INTERFACE_HANDLE InterfaceHandle, UCHAR PipeID)
{
if (m_winUsb.AbortPipe)
return m_winUsb.AbortPipe(InterfaceHandle, PipeID);
else
return FALSE;
}
/*! \brief Discards any data that is cached in a pipe.
\param[in] InterfaceHandle An initialized usb handle, see \a Initialize.
\param[in] PipeID An 8-bit value that consists of a 7-bit address and a direction bit. This parameter corresponds to the \a bEndpointAddress field in the endpoint descriptor.
\returns On success, TRUE. Otherwise FALSE. Use GetLastError() to get extended error information.
*/
BOOL XsWinUsb::FlushPipe(WINUSB_INTERFACE_HANDLE InterfaceHandle, UCHAR PipeID)
{
if (m_winUsb.FlushPipe)
return m_winUsb.FlushPipe(InterfaceHandle, PipeID);
else
return FALSE;
}
/*! \brief Sets the power policy for a device.
The following list summarizes the effects of changes to power management states:
- All pipe handles, interface handles, locks, and alternate settings are preserved across power management events.
- Any transfers that are in progress are suspended when a device transfers to a low power state, and they are resumed when the device is restored to a working state.
- The device and system must be in a working state before the client can restore a device-specific configuration. Clients can determine whether the device and system are in a working state from the WM_POWERBROADCAST message.
- The client can indicate that an interface is idle by calling \a SetPowerPolicy.
\param[in] InterfaceHandle An initialized usb handle, see \a Initialize.
\param[in] PolicyType A value that specifies the power policy to set. The following table describes symbolic constants.
- AUTO_SUSPEND (0x81)
- Specifies the auto-suspend policy type; the power policy parameter must be specified by the caller in the Value parameter.
- For auto-suspend, the Value parameter must point to a UCHAR variable.
- If Value is TRUE (nonzero), the USB stack suspends the device if the device is idle. A device is idle if there are no transfers pending, or if the only pending transfers are IN transfers to interrupt or bulk endpoints.
- The default value is determined by the value set in the DefaultIdleState registry setting. By default, this value is TRUE.
- SUSPEND_DELAY (0x83)
- Specifies the suspend-delay policy type; the power policy parameter must be specified by the caller in the Value parameter.
- For suspend-delay, Value must point to a UINT variable.
- Value specifies the minimum amount of time, in milliseconds, that the driver must wait post transfer before it can suspend the device.
- The default value is determined by the value set in the DefaultIdleTimeout registry setting. By default, this value is five seconds.
\param[in] ValueLength The size, in bytes, of the buffer at Value.
\param[in] Value The new value for the power policy parameter. Data type and value for Value depends on the type of power policy passed in PolicyType. For more information, see PolicyType.
\returns On success, TRUE. Otherwise FALSE. Use GetLastError() to get extended error information.
*/
BOOL XsWinUsb::SetPowerPolicy(WINUSB_INTERFACE_HANDLE InterfaceHandle, ULONG PolicyType, ULONG ValueLength, PVOID Value)
{
if (m_winUsb.SetPowerPolicy)
return m_winUsb.SetPowerPolicy(InterfaceHandle, PolicyType, ValueLength, Value);
else
return FALSE;
}
/*! \brief Gets the power policy for a device.
\param[in] InterfaceHandle An initialized usb handle, see \a Initialize
\param[in] PolicyType A value that specifies the power policy parameter to retrieve in Value. The following table describes symbolic constants that are valid.
- AUTO_SUSPEND (0x81)
- If the caller specifies a power policy of AUTO_SUSPEND, \a GetPowerPolicy returns the value of the auto suspend policy parameter in the Value parameter.
- If Value is TRUE (that is, nonzero), the USB stack suspends the device when no transfers are pending or the only transfers pending are IN transfers on an interrupt or bulk endpoint.
- The value of the DefaultIdleState registry value determines the default value of the auto suspend policy parameter.
- The Value parameter must point to a UCHAR variable.
- SUSPEND_DELAY (0x83)
- If the caller specifies a power policy of SUSPEND_DELAY, \a GetPowerPolicy returns the value of the suspend delay policy parameter in Value.
- The suspend delay policy parameter specifies the minimum amount of time, in milliseconds, that the driver must wait after any transfer before it can suspend the device.
- Value must point to a UINT variable.
\param[in,out] ValueLength A pointer to the size of the buffer that Value. On output, ValueLength receives the size of the data that was copied into the Value buffer.
\param[out] Value A buffer that receives the specified power policy parameter. For more information, see PolicyType.
\returns On success, TRUE. Otherwise FALSE. Use GetLastError() to get extended error information.
*/
BOOL XsWinUsb::GetPowerPolicy(WINUSB_INTERFACE_HANDLE InterfaceHandle,ULONG PolicyType,PULONG ValueLength,PVOID Value)
{
if (m_winUsb.GetPowerPolicy)
return m_winUsb.GetPowerPolicy(InterfaceHandle, PolicyType, ValueLength, Value);
else
return FALSE;
}
/*! \brief Retrieves the results of an overlapped operation on the specified winUSB handle.
This function is like the Win32 API routine, GetOverlappedResult, with one difference; instead of passing a file handle that is returned from CreateFile, the caller passes an interface handle that is returned from \a Initialize, or \a GetAssociatedInterface. The caller can use either API routine, if the appropriate handle is passed. The \a GetOverlappedResult function extracts the file handle from the interface handle and then calls GetOverlappedResult.
The results that are reported by the GetOverlappedResult function are those from the specified handle's last overlapped operation to which the specified standard windows OVERLAPPED structure was provided, and for which the operation's results were pending. A pending operation is indicated when the function that started the operation returns FALSE, and the GetLastError routine returns ERROR_IO_PENDING. When an I/O operation is pending, the function that started the operation resets the hEvent member of the standard windows OVERLAPPED structure to the nonsignaled state. Then when the pending operation has been completed, the system sets the event object to the signaled state.
The caller can specify that an event object is manually reset in the standard windows OVERLAPPED structure. If an automatic reset event object is used, the event handle must not be specified in any other wait operation in the interval between starting the overlapped operation and the call to \a GetOverlappedResult. For example, the event object is sometimes specified in one of the wait routines to wait for the operation to be completed. When the wait routine returns, the system sets an auto-reset event's state to nonsignaled, and a successive call to \a GetOverlappedResult with the bWait parameter set to TRUE causes the function to be blocked indefinitely.
If the bWait parameter is TRUE, GetOverlappedResult determines whether the pending operation has been completed by waiting for the event object to be in the signaled state.
If the hEvent member of the standard windows OVERLAPPED structure is NULL, the system uses the state of the file handle to signal when the operation has been completed. Do not use file handles for this purpose. It is better to use an event object because of the confusion that can occur when multiple concurrent overlapped operations are performed on the same file. In this situation, you cannot know which operation caused the state of the object to be signaled.
\param[in] InterfaceHandle An initialized usb handle, see \a Initialize
\param[in] Overlapped A pointer to a standard windows OVERLAPPED structure that was specified when the overlapped operation was started.
\param[out] lpNumberOfBytesTransferred A pointer to a variable that receives the number of bytes that were actually transferred by a read or write operation.
\param[in] bWait If this parameter is TRUE, the function does not return until the operation has been completed. If this parameter is FALSE and the operation is still pending, the function returns FALSE and the GetLastError function returns ERROR_IO_INCOMPLETE.
\returns On success, TRUE. Otherwise FALSE. Use GetLastError() to get extended error information.
*/
BOOL XsWinUsb::GetOverlappedResult(WINUSB_INTERFACE_HANDLE InterfaceHandle,LPOVERLAPPED lpOverlapped,LPDWORD lpNumberOfBytesTransferred,BOOL bWait)
{
if (m_winUsb.GetOverlappedResult)
return m_winUsb.GetOverlappedResult(InterfaceHandle, lpOverlapped, lpNumberOfBytesTransferred, bWait);
else
return FALSE;
}
#endif // USE_WINUSB
|
/*
* _____ _____ ________ _
* / __// __// __/\ \//
* | | _| \ | \ \ /
* | |_//| /_ | /_ / \
* \____\\____\\____\/__/\\
*
* Graphics Environment for EXperimentations.
* Copyright (C) 2006 INRIA - Project ALICE
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
*
* If you modify this software, you should include a notice giving the
* name of the person performing the modification, the date of modification,
* and the reason for such modification.
*
* Contact:
*
* ALICE Project - INRIA
* INRIA Lorraine,
* Campus Scientifique, BP 239
* 54506 VANDOEUVRE LES NANCY CEDEX
* FRANCE
*
* Note that the GNU General Public License does not permit incorporating
* the Software into proprietary programs.
*/
#include <Geex/basics/types.h>
#include <Geex/basics/processor.h>
#include <Geex/mathematics/glsl_linear.h>
#include <Geex/mathematics/shewchuk.h>
#include <Geex/numerics/quick_blas.h>
#include <Geex/numerics/sparse_matrix_sse.h>
#include <Geex/properties/property_serializer.h>
#include <Geex/properties/property_interpolator.h>
#ifdef WIN32
#include <float.h> // for ::_isnan()
#else
#include <stdlib.h>
#endif
#include <ctype.h>
namespace Geex {
namespace Numeric {
const float big_float = 1e10f ;
const float small_float = 1e-10f ;
const double big_double = 1e20 ;
const double small_double = 1e-20 ;
bool is_nan(float32 x) {
#ifdef WIN32
return (_isnan(x) != 0) || (_finite(x) == 0) ;
#else
return isnan(x) || !finite(x);
#endif
}
bool is_nan(float64 x) {
#ifdef WIN32
return (_isnan(x) != 0) || (_finite(x) == 0) ;
#else
return isnan(x) || !finite(x);
#endif
}
int32 random_int32() {
#ifdef WIN32
return rand() ;
#else
return random() ;
#endif
}
float64 random_float64() {
#ifdef WIN32
return float64(rand()) / double(RAND_MAX);
#else
return float64(drand48()) ;
#endif
}
float32 random_float32() {
#ifdef WIN32
return (float32)(float32(rand()) / double(RAND_MAX));
#else
return float32(drand48()) ;
#endif
}
}
namespace Memory {
long used_memory() {
#ifdef WIN32
// Note: this returns the amount of virtual memory used
// by the system (we should replace that by a function
// that returns the amount of virtual mem used by the
// *process* ...)
MEMORYSTATUS stat ;
GlobalMemoryStatus(&stat) ;
return (long)(stat.dwTotalVirtual - stat.dwAvailVirtual) ;
#else
return (long)sbrk(0) ;
#endif
}
}
namespace String {
void split_string(
const std::string& in,
char separator,
std::vector<std::string>& out,
bool skip_empty_fields
) {
int length = (int)in.length() ;
int start = 0 ;
int end = 0 ;
while(start < length) {
end = (int)in.find(separator,start) ;
if(end < 0) {
end = length ;
}
if(!skip_empty_fields || (end - start > 0)) {
out.push_back(in.substr(start, end - start)) ;
}
start = end + 1 ;
}
}
void join_strings(
const std::vector<std::string>& in,
char separator,
std::string& out
) {
out = "" ;
for(unsigned int i=0; i<in.size(); i++) {
if(out.length() != 0) {
out += separator ;
}
out += in[i] ;
}
}
void join_strings(
const std::vector<std::string>& in,
const std::string& separator,
std::string& out
) {
out = "" ;
for(unsigned int i=0; i<in.size(); i++) {
if(out.length() != 0) {
out += separator ;
}
out += in[i] ;
}
}
std::string join_strings(
const std::vector<std::string>& in,
char separator
) {
std::string result ;
join_strings(in, separator, result) ;
return result ;
}
std::string join_strings(
const std::vector<std::string>& in,
const std::string& separator
) {
std::string result ;
join_strings(in, separator, result) ;
return result ;
}
void to_lowercase(std::string& in) {
for(unsigned int i=0; i<in.length(); i++) {
if(isupper(in[i])) {
in[i] = tolower(in[i]) ;
}
}
}
void to_uppercase(std::string& in) {
for(unsigned int i=0; i<in.length(); i++) {
if(islower(in[i])) {
in[i] = toupper(in[i]) ;
}
}
}
std::string quote(const std::string& s, char quotes) {
return char_to_string(quotes) + s + char_to_string(quotes) ;
}
bool string_starts_with(const std::string& haystack, const std::string& needle) {
unsigned int l1 = haystack.length() ;
unsigned int l2 = needle.length() ;
if(l2 > l1) { return false ; }
return (haystack.substr(0, l2) == needle) ;
}
bool string_ends_with(const std::string& haystack, const std::string& needle) {
unsigned int l1 = haystack.length() ;
unsigned int l2 = needle.length() ;
if(l2 > l1) { return false ; }
return (haystack.substr(l1 - l2, l2) == needle) ;
}
}
}
namespace Geex {
void initialize() {
exactinit() ;
// Processor::enable_FPE() ;
QuickBLAS::initialize() ;
sparse_matrix_SSE2_initialize() ;
PropertySerializer::initialize() ;
PropertyInterpolator::initialize() ;
gx_register_property_type<int>("integer") ;
gx_register_property_type<bool>("boolean") ;
gx_register_property_type<std::string>("string") ;
gx_register_property_type<real>("real") ;
gx_register_numeric_property_interpolator<real>() ;
gx_register_property_type<vec2>("vec2") ;
gx_register_property_type<vec3>("vec3") ;
gx_register_property_type<vec4>("vec4") ;
gx_register_numeric_property_interpolator<vec2>() ;
gx_register_numeric_property_interpolator<vec3>() ;
gx_register_numeric_property_interpolator<vec4>() ;
gx_register_property_type_alias("Point2d", "vec2") ;
gx_register_property_type_alias("Vector2d", "vec2") ;
gx_register_property_type_alias("Complex", "vec2") ;
gx_register_property_type_alias("Point3d", "vec3") ;
gx_register_property_type_alias("Vector3d", "vec3") ;
gx_register_property_type_alias("Color", "vec4") ;
}
void terminate() {
PropertySerializer::terminate() ;
PropertyInterpolator::terminate() ;
}
}
|
// Copyright (c) 2021 Runeterra Team
// Chris Ohk, Seokmin Hong, Woojin Kim
// We are making my contributions/submissions to this project solely in our
// personal capacity and are not conveying any rights to any intellectual
// property of any third parties.
#include <Runeterra/CardSets/Set2CardsGen.hpp>
namespace Runeterra::Set2
{
void AddBandleCity(entt::registry& registry)
{
// Do nothing
}
void AddBandleCityNonCollect(entt::registry& registry)
{
// Do nothing
}
void AddBilgewater(entt::registry& registry)
{
// -------------------------------------- Unit - Bilgewater
// [02BW040] Shellshocker - COST:1
// - Set: Set2, Rarity: Common
// --------------------------------------------------------
// Keyword:
// - Attune = 1
// --------------------------------------------------------
// -------------------------------------- Unit - Bilgewater
// [02BW057] Slippery Waverider - COST:5
// - Set: Set2, Rarity: Common
// --------------------------------------------------------
// Keyword:
// - Elusive = 1
// - Attune = 1
// --------------------------------------------------------
// -------------------------------------- Unit - Bilgewater
// [02BW041] The Beast Below - COST:4
// - Subtype: Sea monster, Set: Set2, Rarity: Common
// --------------------------------------------------------
// Keyword:
// - Deep = 1
// --------------------------------------------------------
// -------------------------------------- Unit - Bilgewater
// [02BW013] Prowling Cutthroat - COST:1
// - Set: Set2, Rarity: Common
// --------------------------------------------------------
// Keyword:
// - Fearsome = 1
// - Elusive = 1
// --------------------------------------------------------
// -------------------------------------- Unit - Bilgewater
// [02BW034] Monkey Idol - COST:3
// - Set: Set2, Rarity: Rare
// --------------------------------------------------------
// Description: Round Start: Deal 2 to me and
// summon a Powder Monkey.
// --------------------------------------------------------
// Keyword:
// - Immobile = 1
// --------------------------------------------------------
// -------------------------------------- Unit - Bilgewater
// [02BW056] Devourer of the Depths - COST:6
// - Subtype: Sea monster, Set: Set2, Rarity: Epic
// --------------------------------------------------------
// Description: Play: Obliterate an enemy with less Health than me.
// --------------------------------------------------------
// Keyword:
// - Deep = 1
// --------------------------------------------------------
// -------------------------------------- Unit - Bilgewater
// [02BW060] Crackshot Corsair - COST:1
// - Subtype: Yordle, Set: Set2, Rarity: Common
// --------------------------------------------------------
// Description: When allies attack, deal 1 to the enemy Nexus.
// --------------------------------------------------------
// -------------------------------------- Unit - Bilgewater
// [02BW011] Yordle Grifter - COST:4
// - Subtype: Yordle, Set: Set2, Rarity: Rare
// --------------------------------------------------------
// Description: Allegiance: Nab 1 and create a Warning Shot in hand.
// --------------------------------------------------------
// -------------------------------------- Unit - Bilgewater
// [02BW030] Shipwreck Hoarder - COST:7
// - Subtype: Sea monster, Set: Set2, Rarity: Epic
// --------------------------------------------------------
// Description: When I'm summoned, Toss 2 and create
// 2 Treasures in your deck.
// --------------------------------------------------------
// Keyword:
// - Deep = 1
// --------------------------------------------------------
// -------------------------------------- Unit - Bilgewater
// [02BW019] Bubble Bear - COST:3
// - Set: Set2, Rarity: Common
// --------------------------------------------------------
// Keyword:
// - Attune = 1
// - Elusive = 1
// --------------------------------------------------------
// -------------------------------------- Unit - Bilgewater
// [02BW007] Brash Gambler - COST:4
// - Set: Set2, Rarity: Rare
// --------------------------------------------------------
// Description: To play me, discard 2.
// Attack: Draw 2 and give them Fleeting.
// --------------------------------------------------------
// -------------------------------------- Unit - Bilgewater
// [02BW014] Coral Creatures - COST:2
// - Set: Set2, Rarity: Rare
// --------------------------------------------------------
// Description: When I'm summoned, create in hand a random
// 1 cost spell from your regions.
// --------------------------------------------------------
// Keyword:
// - Attune = 1
// --------------------------------------------------------
// -------------------------------------- Unit - Bilgewater
// [02BW055] Jagged Taskmaster - COST:2
// - Set: Set2, Rarity: Epic
// --------------------------------------------------------
// Description: Plunder: Grant 1 cost allies everywhere +1|+0.
// --------------------------------------------------------
// -------------------------------------- Unit - Bilgewater
// [02BW017] Citrus Courier - COST:6
// - Set: Set2, Rarity: Rare
// --------------------------------------------------------
// Description: Plunder: Heal allies and your Nexus 3,
// then Rally.
// --------------------------------------------------------
// -------------------------------------- Unit - Bilgewater
// [02BW038] Zap Sprayfin - COST:4
// - Set: Set2, Rarity: Epic
// --------------------------------------------------------
// Description: When I'm summoned, draw a spell that costs
// 3 or less from your deck.
// --------------------------------------------------------
// Keyword:
// - Elusive = 1
// - Attune = 1
// --------------------------------------------------------
// -------------------------------------- Unit - Bilgewater
// [02BW021] Razorscale Hunter - COST:5
// - Set: Set2, Rarity: Rare
// --------------------------------------------------------
// Description: Play: Grant an enemy Vulnerable.
// --------------------------------------------------------
// Keyword:
// - Scout = 1
// --------------------------------------------------------
// -------------------------------------- Unit - Bilgewater
// [02BW035] Sheriff Lariette Rose - COST:6
// - Set: Set2, Rarity: Epic
// --------------------------------------------------------
// Description: When I'm summoned, grant all enemies Vulnerable.
// --------------------------------------------------------
// -------------------------------------- Unit - Bilgewater
// [02BW058] Jagged Butcher - COST:1
// - Set: Set2, Rarity: Common
// --------------------------------------------------------
// Description: Plunder: Grant me +1|+1.
// --------------------------------------------------------
// -------------------------------------- Unit - Bilgewater
// [02BW028] Riptide Rex - COST:8
// - Set: Set2, Rarity: Epic
// --------------------------------------------------------
// Description: Plunder: Cast Cannon Barrage 6 times
// on randomly targeted enemies.
// --------------------------------------------------------
// -------------------------------------- Unit - Bilgewater
// [02BW037] Abyssal Eye - COST:5
// - Subtype: Sea monster, Set: Set2, Rarity: Rare
// --------------------------------------------------------
// Description: Nexus Strike: Draw 1.
//
// --------------------------------------------------------
// Keyword:
// - Elusive = 1
// - Deep = 1
// --------------------------------------------------------
// -------------------------------------- Unit - Bilgewater
// [02BW008] Petty Officer - COST:3
// - Subtype: Yordle, Set: Set2, Rarity: Rare
// --------------------------------------------------------
// Description: Play: Summon a Powder Keg or
// a random 1 cost follower.
// --------------------------------------------------------
// -------------------------------------- Unit - Bilgewater
// [02BW047] Dreg Dredgers - COST:1
// - Set: Set2, Rarity: Common
// --------------------------------------------------------
// Description: When I'm summoned, Toss 3.
// --------------------------------------------------------
// -------------------------------------- Unit - Bilgewater
// [02BW004] Dreadway Deckhand - COST:2
// - Set: Set2, Rarity: Common
// --------------------------------------------------------
// Description: When I'm summoned, summon a Powder Keg.
// --------------------------------------------------------
// -------------------------------------- Unit - Bilgewater
// [02BW002] The Dreadway - COST:8
// - Set: Set2, Rarity: Epic
// --------------------------------------------------------
// Description: When I'm summoned, draw a Gangplank.
// Double all damage dealt by your skills,
// spells and allies.
// --------------------------------------------------------
// Keyword:
// - Fearsome = 1
// - Missing Translation = 1
// --------------------------------------------------------
// -------------------------------------- Unit - Bilgewater
// [02BW016] Slotbot - COST:3
// - Set: Set2, Rarity: Rare
// --------------------------------------------------------
// Description: When I'm summoned or Round Start: Grant me
// +0|+1 for each card you drew last round,
// then shuffle my stats.
// --------------------------------------------------------
// -------------------------------------- Unit - Bilgewater
// [02BW027] Hunting Fleet - COST:4
// - Set: Set2, Rarity: Common
// --------------------------------------------------------
// Description: When I'm summoned, summon a Golden Narwhal
// for your opponent.
// --------------------------------------------------------
// -------------------------------------- Unit - Bilgewater
// [02BW050] Smooth Soloist - COST:7
// - Set: Set2, Rarity: Rare
// --------------------------------------------------------
// Description: Plunder: Reduce the cost of allies
// in your hand and deck by 2.
// --------------------------------------------------------
// Keyword:
// - Elusive = 1
// --------------------------------------------------------
// -------------------------------------- Unit - Bilgewater
// [02BW015] The Syren - COST:7
// - Set: Set2, Rarity: Epic
// --------------------------------------------------------
// Description: When I'm summoned, draw a Miss Fortune.
// While I'm attacking, all your spells and
// skills deal 1 extra damage.
// --------------------------------------------------------
// Keyword:
// - Scout = 1
// --------------------------------------------------------
// -------------------------------------- Unit - Bilgewater
// [02BW010] Plunder Poro - COST:1
// - Subtype: Poro, Set: Set2, Rarity: Common
// --------------------------------------------------------
// Description: Plunder: Grant me 2 random keywords.
// --------------------------------------------------------
// -------------------------------------- Unit - Bilgewater
// [02BW009] Pool Shark - COST:1
// - Set: Set2, Rarity: Common
// --------------------------------------------------------
// Description: When I'm summoned, draw 1 at the next
// Round Start and give it Fleeting.
// --------------------------------------------------------
// -------------------------------------- Unit - Bilgewater
// [02BW005] Hired Gun - COST:2
// - Set: Set2, Rarity: Common
// --------------------------------------------------------
// Description: When I'm summoned,
// grant the strongest enemy Vulnerable.
// --------------------------------------------------------
// -------------------------------------- Unit - Bilgewater
// [02BW039] Jaull Hunters - COST:3
// - Set: Set2, Rarity: Rare
// --------------------------------------------------------
// Description: When I'm summoned,
// create a random Sea Monster in hand.
// --------------------------------------------------------
// Keyword:
// - Challenger = 1
// --------------------------------------------------------
// -------------------------------------- Unit - Bilgewater
// [02BW006] Mystifying Magician - COST:4
// - Set: Set2, Rarity: Rare
// --------------------------------------------------------
// Description: Play: Transform an ally into
// a random 5 cost follower.
// --------------------------------------------------------
// -------------------------------------- Unit - Bilgewater
// [02BW036] Golden Narwhal - COST:2
// - Set: Set2, Rarity: Common
// --------------------------------------------------------
// Keyword:
// - Elusive = 1
// - Vulnerable = 1
// --------------------------------------------------------
// -------------------------------------- Unit - Bilgewater
// [02BW033] Black Market Merchant - COST:2
// - Set: Set2, Rarity: Rare
// --------------------------------------------------------
// Description: When you draw an enemy card, reduce its cost by 1.
// Plunder: Nab 1.
// --------------------------------------------------------
// -------------------------------------- Unit - Bilgewater
// [02BW032] Gangplank - COST:5
// - Supertype: Champion, Set: Set2, Rarity: Champion
// --------------------------------------------------------
// Description: When I'm summoned, summon a Powder Keg.
// --------------------------------------------------------
// Level Up Description: You've damaged the enemy Nexus
// in 5 different rounds.
// --------------------------------------------------------
// Keyword:
// - Overwhelm = 1
// --------------------------------------------------------
// -------------------------------------- Unit - Bilgewater
// [02BW022] Miss Fortune - COST:3
// - Supertype: Champion, Set: Set2, Rarity: Champion
// --------------------------------------------------------
// Description: When allies attack, deal 1 to all
// battling enemies and the enemy Nexus.
// --------------------------------------------------------
// Level Up Description: I've seen you attack 4 times.
// --------------------------------------------------------
// -------------------------------------- Unit - Bilgewater
// [02BW046] Fizz - COST:1
// - Subtype: Yordle, Supertype: Champion, Set: Set2, Rarity: Champion
// --------------------------------------------------------
// Description: When you cast a spell, stop all enemy spells
// and skills targeting me and give me Elusive
// this round.
// --------------------------------------------------------
// Level Up Description: You've cast 6+ spells.
// --------------------------------------------------------
// Keyword:
// - Imbue = 1
// --------------------------------------------------------
// -------------------------------------- Unit - Bilgewater
// [02BW026] Twisted Fate - COST:4
// - Supertype: Champion, Set: Set2, Rarity: Champion
// --------------------------------------------------------
// Description: Play: Play a Destiny Card.
// --------------------------------------------------------
// Level Up Description: I've seen you draw 9+ cards.
// --------------------------------------------------------
// Keyword:
// - Quick Attack = 1
// --------------------------------------------------------
// -------------------------------------- Unit - Bilgewater
// [02BW053] Nautilus - COST:7
// - Supertype: Champion, Set: Set2, Rarity: Champion
// --------------------------------------------------------
// Level Up Description: When you are Deep. When I level up,
// copy Tossed allies that cost 4+
// into your deck.
// --------------------------------------------------------
// Keyword:
// - Tough = 1
// - Fearsome = 1
// --------------------------------------------------------
// ------------------------------------- Spell - Bilgewater
// [02BW061] Pocket Aces - COST:3
// - Set: Set2, Rarity: Common
// - Spell Speed: Burst
// --------------------------------------------------------
// Description: When drawn, costs 1 less this round.
// Grant an ally +2|+1.
// --------------------------------------------------------
// Keyword:
// - Burst = 1
// --------------------------------------------------------
// ------------------------------------- Spell - Bilgewater
// [02BW024] Double Trouble - COST:3
// - Set: Set2, Rarity: Rare
// - Spell Speed: Slow
// --------------------------------------------------------
// Description: Summon 2 random 1 cost followers.
// --------------------------------------------------------
// Keyword:
// - Slow = 1
// --------------------------------------------------------
// ------------------------------------- Spell - Bilgewater
// [02BW003] Strong-arm - COST:6
// - Set: Set2, Rarity: Rare
// - Spell Speed: Slow
// --------------------------------------------------------
// Description: Plunder: Place a follower in play into your hand.
// --------------------------------------------------------
// Keyword:
// - Slow = 1
// --------------------------------------------------------
// ------------------------------------- Spell - Bilgewater
// [02BW025] Chum the Waters - COST:4
// - Set: Set2, Rarity: Common
// - Spell Speed: Slow
// --------------------------------------------------------
// Description: Grant an enemy Vulnerable and summon Longtooth.
// --------------------------------------------------------
// Keyword:
// - Slow = 1
// --------------------------------------------------------
// ------------------------------------- Spell - Bilgewater
// [02BW012] More Powder! - COST:2
// - Set: Set2, Rarity: Common
// - Spell Speed: Slow
// --------------------------------------------------------
// Description: Summon 2 Powder Kegs.
// --------------------------------------------------------
// Keyword:
// - Slow = 1
// --------------------------------------------------------
// ------------------------------------- Spell - Bilgewater
// [02BW018] Parrrley - COST:1
// - Set: Set2, Rarity: Common
// - Spell Speed: Slow
// --------------------------------------------------------
// Description: Deal 1 to anything.
// If this kills it, deal 1 to the enemy Nexus.
// --------------------------------------------------------
// Keyword:
// - Slow = 1
// --------------------------------------------------------
// ------------------------------------- Spell - Bilgewater
// [02BW048] Jailbreak - COST:1
// - Set: Set2, Rarity: Common
// - Spell Speed: Slow
// --------------------------------------------------------
// Description: Summon a random 1 cost follower.
// --------------------------------------------------------
// Keyword:
// - Slow = 1
// --------------------------------------------------------
// ------------------------------------- Spell - Bilgewater
// [02BW043] Pick a Card - COST:2
// - Set: Set2, Rarity: Rare
// - Spell Speed: Burst
// --------------------------------------------------------
// Description: Place a card from hand into your deck
// to draw 2 at the next Round Start.
// Give them Fleeting.
// --------------------------------------------------------
// Keyword:
// - Burst = 1
// --------------------------------------------------------
// ------------------------------------- Spell - Bilgewater
// [02BW051] Playful Trickster - COST:4
// - Set: Set2, Rarity: Rare
// - Spell Speed: Fast
// --------------------------------------------------------
// Description: Remove an attacking ally from combat to Rally.
// --------------------------------------------------------
// Keyword:
// - Fast = 1
// --------------------------------------------------------
// ------------------------------------- Spell - Bilgewater
// [02BW054] Riptide - COST:4
// - Set: Set2, Rarity: Rare
// - Spell Speed: Fast
// --------------------------------------------------------
// Description: Stun an enemy.
// Place that unit into the enemy deck
// if you have a Nautilus.
// --------------------------------------------------------
// Keyword:
// - Fast = 1
// --------------------------------------------------------
// ------------------------------------- Spell - Bilgewater
// [02BW042] Mind Meld - COST:7
// - Set: Set2, Rarity: Epic
// - Spell Speed: Slow
// --------------------------------------------------------
// Description: This round, grow all allies' Power and Health
// to the number of spells you've cast this game.
// --------------------------------------------------------
// Keyword:
// - Slow = 1
// --------------------------------------------------------
// ------------------------------------- Spell - Bilgewater
// [02BW059] Scrapshot - COST:7
// - Set: Set2, Rarity: Rare
// - Spell Speed: Fast
// --------------------------------------------------------
// Description: Toss 3.
// Deal 7 to a unit.
// --------------------------------------------------------
// Keyword:
// - Fast = 1
// --------------------------------------------------------
// ------------------------------------- Spell - Bilgewater
// [02BW023] Lure of the Depths - COST:3
// - Set: Set2, Rarity: Rare
// - Spell Speed: Burst
// --------------------------------------------------------
// Description: Reduce the cost of Sea Monster allies everywhere by 1.
// Draw a Sea Monster.
// --------------------------------------------------------
// Keyword:
// - Burst = 1
// --------------------------------------------------------
// ------------------------------------- Spell - Bilgewater
// [02BW031] Double Up - COST:5
// - Set: Set2, Rarity: Rare
// - Spell Speed: Fast
// --------------------------------------------------------
// Description: Deal 2 to an enemy.
// If this kills it, deal 4 to the enemy Nexus.
// --------------------------------------------------------
// Keyword:
// - Fast = 1
// --------------------------------------------------------
// ------------------------------------- Spell - Bilgewater
// [02BW029] Salvage - COST:4
// - Set: Set2, Rarity: Common
// - Spell Speed: Burst
// --------------------------------------------------------
// Description: Toss 2.
// Draw 2.
// --------------------------------------------------------
// Keyword:
// - Burst = 1
// --------------------------------------------------------
// ------------------------------------- Spell - Bilgewater
// [02BW049] Pilfered Goods - COST:3
// - Set: Set2, Rarity: Common
// - Spell Speed: Burst
// --------------------------------------------------------
// Description: Nab 1.
// Plunder: Nab 1 more.
// --------------------------------------------------------
// Keyword:
// - Burst = 1
// --------------------------------------------------------
// ------------------------------------- Spell - Bilgewater
// [02BW001] Ye Been Warned - COST:1
// - Set: Set2, Rarity: Common
// - Spell Speed: Slow
// --------------------------------------------------------
// Description: Give an enemy Vulnerable this round.
// If it dies this round, draw 1.
// --------------------------------------------------------
// Keyword:
// - Slow = 1
// --------------------------------------------------------
// ------------------------------------- Spell - Bilgewater
// [02BW063] Sleight of Hand - COST:3
// - Set: Set2, Rarity: Rare
// - Spell Speed: Slow
// --------------------------------------------------------
// Description: Plunder: Draw a random non-champion card
// from the enemy hand.
// --------------------------------------------------------
// Keyword:
// - Slow = 1
// --------------------------------------------------------
// ------------------------------------- Spell - Bilgewater
// [02BW045] Make it Rain - COST:2
// - Set: Set2, Rarity: Common
// - Spell Speed: Fast
// --------------------------------------------------------
// Description: Deal 1 three times among different randomly
// targeted enemies and the enemy Nexus.
// --------------------------------------------------------
// Keyword:
// - Fast = 1
// --------------------------------------------------------
// ------------------------------------- Spell - Bilgewater
// [02BW020] Warning Shot - COST:0
// - Set: Set2, Rarity: Common
// - Spell Speed: Burst
// --------------------------------------------------------
// Description: Deal 1 to the enemy Nexus.
// --------------------------------------------------------
// Keyword:
// - Burst = 1
// --------------------------------------------------------
// ------------------------------------- Spell - Bilgewater
// [02BW044] Jettison - COST:1
// - Set: Set2, Rarity: Rare
// - Spell Speed: Burst
// --------------------------------------------------------
// Description: Toss 4.
// --------------------------------------------------------
// Keyword:
// - Burst = 1
// --------------------------------------------------------
// -------------------------------------- Unit - Bilgewater
// [02BW062] Island Navigator - COST:4
// - Set: Set2, Rarity: Rare
// --------------------------------------------------------
// Description: When I'm summoned, summon a random 1 cost
// follower and grant it Scout.
// --------------------------------------------------------
// Keyword:
// - Scout = 1
// --------------------------------------------------------
}
void AddBilgewaterNonCollect(entt::registry& registry)
{
// -------------------------------------- Unit - Bilgewater
// [02BW034T1] Powder Monkey - COST:1
// - Set: Set2, Rarity: None
// --------------------------------------------------------
// Description: Last Breath: Deal 1 to the enemy Nexus.
// --------------------------------------------------------
// Keyword:
// - Ephemeral = 1
// - Last Breath = 1
// --------------------------------------------------------
// ----------------------------------- Ability - Bilgewater
// [02BW056T1] Devour - COST:0
// - Set: Set2, Rarity: None
// --------------------------------------------------------
// Description: Obliterate an enemy with less Health than me.
// --------------------------------------------------------
// Keyword:
// - Skill = 1
// --------------------------------------------------------
// ------------------------------------- Spell - Bilgewater
// [02BW030T2] Keelbreaker - COST:5
// - Subtype: Treasure, Set: Set2, Rarity: None
// - Spell Speed: Slow
// --------------------------------------------------------
// Description: If I'm Tossed, draw me instead.
// Deal 5 to ALL units.
// --------------------------------------------------------
// Keyword:
// - Slow = 1
// --------------------------------------------------------
// ------------------------------------- Spell - Bilgewater
// [02BW030T1] Treasure Trove - COST:5
// - Subtype: Treasure, Set: Set2, Rarity: None
// - Spell Speed: Slow
// --------------------------------------------------------
// Description: Create 5 random cards in hand.
// They cost 0 and are Fleeting.
// If I'm Tossed, draw me instead.
// --------------------------------------------------------
// Keyword:
// - Slow = 1
// --------------------------------------------------------
// -------------------------------------- Unit - Bilgewater
// [02BW030T4] Vicious Platewyrm - COST:5
// - Subtype: Sea monster, Set: Set2, Rarity: None
// --------------------------------------------------------
// Keyword:
// - Fearsome = 1
// - Deep = 1
// --------------------------------------------------------
// ------------------------------------- Spell - Bilgewater
// [02BW030T3] Platewyrm Egg - COST:5
// - Subtype: Treasure, Set: Set2, Rarity: None
// - Spell Speed: Slow
// --------------------------------------------------------
// Description: If I'm Tossed, draw me instead.
// Summon 3 Vicious Platewyrms.
// --------------------------------------------------------
// Keyword:
// - Slow = 1
// --------------------------------------------------------
// ----------------------------------- Ability - Bilgewater
// [02BW028T1] Cannon Barrage - COST:0
// - Set: Set2, Rarity: None
// --------------------------------------------------------
// Description: Deal 2 to a unit.
// If it's dead or gone, deal 1 to
// the enemy Nexus instead.
// --------------------------------------------------------
// Keyword:
// - Skill = 1
// --------------------------------------------------------
// -------------------------------------- Unit - Bilgewater
// [02BW008T02] Petty Officer - COST:3
// - Subtype: Yordle, Set: Set2, Rarity: None
// --------------------------------------------------------
// Description: Play: Summon a random 1 cost follower.
// --------------------------------------------------------
// -------------------------------------- Unit - Bilgewater
// [02BW008T01] Petty Officer - COST:3
// - Subtype: Yordle, Set: Set2, Rarity: None
// --------------------------------------------------------
// Description: Play: Summon a Powder Keg.
// --------------------------------------------------------
// ----------------------------------- Ability - Bilgewater
// [02BW060T1] Crackshot - COST:0
// - Set: Set2, Rarity: None
// --------------------------------------------------------
// Description: Deal 1 to the enemy Nexus.
// --------------------------------------------------------
// Keyword:
// - Skill = 1
// --------------------------------------------------------
// ------------------------------------- Spell - Bilgewater
// [02BW032T2] Gangplank's Parrrley - COST:1
// - Supertype: Champion, Set: Set2, Rarity: None
// - Spell Speed: Slow
// --------------------------------------------------------
// Description: Deal 1 to anything.
// If this kills it, deal 1 to the enemy Nexus.
// Create a Gangplank in your deck.
// --------------------------------------------------------
// Keyword:
// - Slow = 1
// --------------------------------------------------------
// -------------------------------------- Unit - Bilgewater
// [02BW032T3] Gangplank - COST:5
// - Supertype: Champion, Set: Set2, Rarity: None
// --------------------------------------------------------
// Description: When I'm summoned or Round Start:
// Summon a Powder Keg.
// Attack: Deal 1 to all enemies and the enemy Nexus.
// --------------------------------------------------------
// Keyword:
// - Overwhelm = 1
// --------------------------------------------------------
// -------------------------------------- Unit - Bilgewater
// [02BW032T1] Powder Keg - COST:0
// - Set: Set2, Rarity: None
// --------------------------------------------------------
// Description: Powder Kegs stack.
// All of your spells and skills deal 1 extra damage.
// Destroy me when your spell or skill damages enemies
// or the enemy Nexus.
// --------------------------------------------------------
// Keyword:
// - Immobile = 1
// - Vulnerable = 1
// --------------------------------------------------------
// ----------------------------------- Ability - Bilgewater
// [02BW032T4] Powderful Explosion - COST:0
// - Set: Set2, Rarity: None
// --------------------------------------------------------
// Description: Deal 1 to all enemies and the enemy Nexus.
// --------------------------------------------------------
// Keyword:
// - Skill = 1
// --------------------------------------------------------
// ------------------------------------- Spell - Bilgewater
// [02BW022T3] Miss Fortune's Make it Rain - COST:2
// - Supertype: Champion, Set: Set2, Rarity: None
// - Spell Speed: Fast
// --------------------------------------------------------
// Description: Deal 1 three times among different randomly
// targeted enemies and the enemy Nexus.
// Create a Miss Fortune in your deck.
// --------------------------------------------------------
// Keyword:
// - Fast = 1
// --------------------------------------------------------
// -------------------------------------- Unit - Bilgewater
// [02BW022T2] Miss Fortune - COST:3
// - Supertype: Champion, Set: Set2, Rarity: None
// --------------------------------------------------------
// Description: When allies attack, deal 1 three times to
// all battling enemies and the enemy Nexus.
// --------------------------------------------------------
// Keyword:
// - Overwhelm = 1
// --------------------------------------------------------
// ----------------------------------- Ability - Bilgewater
// [02BW022T4] Bullet Time - COST:0
// - Set: Set2, Rarity: None
// --------------------------------------------------------
// Description: Deal 1 three times to all battling enemies
// and the enemy Nexus.
// --------------------------------------------------------
// Keyword:
// - Skill = 1
// --------------------------------------------------------
// ----------------------------------- Ability - Bilgewater
// [02BW022T1] Love Tap - COST:0
// - Set: Set2, Rarity: None
// --------------------------------------------------------
// Description: Deal 1 to all battling enemies and the enemy Nexus.
// --------------------------------------------------------
// Keyword:
// - Skill = 1
// --------------------------------------------------------
// -------------------------------------- Unit - Bilgewater
// [02BW046T3] Fizz - COST:1
// - Subtype: Yordle, Supertype: Champion, Set: Set2, Rarity: None
// --------------------------------------------------------
// Description: When you cast a spell, stop all enemy spells and
// skills targeting me and give me Elusive this round.
// Nexus Strike: Create a Chum the Waters in hand.
// --------------------------------------------------------
// Keyword:
// - Imbue = 1
// --------------------------------------------------------
// -------------------------------------- Unit - Bilgewater
// [02BW046T2] Longtooth - COST:4
// - Set: Set2, Rarity: None
// --------------------------------------------------------
// Keyword:
// - Overwhelm = 1
// --------------------------------------------------------
// ------------------------------------- Spell - Bilgewater
// [02BW046T1] Fizz's Playful Trickster - COST:4
// - Supertype: Champion, Set: Set2, Rarity: None
// - Spell Speed: Fast
// --------------------------------------------------------
// Description: Remove an attacking ally from combat to Rally.
// Create a Fizz in your deck.
// --------------------------------------------------------
// Keyword:
// - Fast = 1
// --------------------------------------------------------
// ----------------------------------- Ability - Bilgewater
// [02BW026T5] Gold Card - COST:0
// - Set: Set2, Rarity: None
// --------------------------------------------------------
// Description: Deal 2 and Stun the strongest enemy.
// --------------------------------------------------------
// Keyword:
// - Skill = 1
// --------------------------------------------------------
// -------------------------------------- Unit - Bilgewater
// [02BW026T3] Twisted Fate - COST:4
// - Supertype: Champion, Set: Set2, Rarity: None
// --------------------------------------------------------
// Description: Each round, the first 3 times you play a card,
// I play a Destiny Card.
// --------------------------------------------------------
// Keyword:
// - Quick Attack = 1
// --------------------------------------------------------
// ------------------------------------- Spell - Bilgewater
// [02BW026T1] Twisted Fate's Pick a Card - COST:2
// - Supertype: Champion, Set: Set2, Rarity: None
// - Spell Speed: Burst
// --------------------------------------------------------
// Description: Place a card from hand into your deck to draw 2
// at the next Round Start. Give them Fleeting.
// Create a Twisted Fate in your deck.
// --------------------------------------------------------
// Keyword:
// - Burst = 1
// --------------------------------------------------------
// ----------------------------------- Ability - Bilgewater
// [02BW026T2] Blue Card - COST:0
// - Set: Set2, Rarity: None
// --------------------------------------------------------
// Description: Refill 1 spell mana.
// Draw 1.
// --------------------------------------------------------
// Keyword:
// - Skill = 1
// --------------------------------------------------------
// ----------------------------------- Ability - Bilgewater
// [02BW026T4] Red Card - COST:0
// - Set: Set2, Rarity: None
// --------------------------------------------------------
// Description: Deal 1 to all enemies and the enemy Nexus.
// --------------------------------------------------------
// Keyword:
// - Skill = 1
// --------------------------------------------------------
// ------------------------------------- Spell - Bilgewater
// [02BW053T2] Nautilus' Riptide - COST:4
// - Supertype: Champion, Set: Set2, Rarity: None
// - Spell Speed: Fast
// --------------------------------------------------------
// Description: Stun an enemy.
// Place that unit into the enemy deck
// if you have a Nautilus.
// Create a Nautilus into your deck.
// --------------------------------------------------------
// Keyword:
// - Fast = 1
// --------------------------------------------------------
// -------------------------------------- Unit - Bilgewater
// [02BW053T1] Nautilus - COST:7
// - Supertype: Champion, Set: Set2, Rarity: None
// --------------------------------------------------------
// Description: Sea Monster allies cost 4 less.
// --------------------------------------------------------
// Keyword:
// - Tough = 1
// - Fearsome = 1
// --------------------------------------------------------
}
void AddDemacia(entt::registry& registry)
{
// ----------------------------------------- Unit - Demacia
// [02DE003] Loyal Badgerbear - COST:3
// - Set: Set2, Rarity: Common
// --------------------------------------------------------
// ----------------------------------------- Unit - Demacia
// [02DE008] Greathorn Companion - COST:5
// - Set: Set2, Rarity: Common
// --------------------------------------------------------
// Keyword:
// - Scout = 1
// --------------------------------------------------------
// ----------------------------------------- Unit - Demacia
// [02DE004] Greenfang Warden - COST:3
// - Subtype: Elite, Set: Set2, Rarity: Common
// --------------------------------------------------------
// Keyword:
// - Barrier = 1
// - Scout = 1
// --------------------------------------------------------
// ----------------------------------------- Unit - Demacia
// [02DE006] Quinn - COST:5
// - Supertype: Champion, Set: Set2, Rarity: Champion
// --------------------------------------------------------
// Description: When I'm summoned, summon Valor.
// --------------------------------------------------------
// Level Up Description: I've seen you attack 4 times.
// --------------------------------------------------------
// Keyword:
// - Scout = 1
// --------------------------------------------------------
// ----------------------------------------- Unit - Demacia
// [02DE009] Grizzled Ranger - COST:4
// - Subtype: Yordle, Set: Set2, Rarity: Rare
// --------------------------------------------------------
// Description: Last Breath: Summon a Loyal Badgerbear.
// --------------------------------------------------------
// Keyword:
// - Scout = 1
// - Last Breath = 1
// --------------------------------------------------------
// ---------------------------------------- Spell - Demacia
// [02DE005] Unyielding Spirit - COST:8
// - Set: Set2, Rarity: Epic
// - Spell Speed: Fast
// --------------------------------------------------------
// Description: Grant an ally "I can't take damage or die".
// --------------------------------------------------------
// Keyword:
// - Fast = 1
// --------------------------------------------------------
// ---------------------------------------- Spell - Demacia
// [02DE002] Blinding Assault - COST:2
// - Set: Set2, Rarity: Rare
// - Spell Speed: Slow
// --------------------------------------------------------
// Description: Summon Valor.
// --------------------------------------------------------
// Keyword:
// - Slow = 1
// --------------------------------------------------------
// ----------------------------------------- Unit - Demacia
// [02DE010] Genevieve Elmheart - COST:6
// - Set: Set2, Rarity: Epic
// --------------------------------------------------------
// Description: When I'm summoned, give other allies
// +1|+1 this round.
// --------------------------------------------------------
// Keyword:
// - Scout = 1
// - Challenger = 1
// --------------------------------------------------------
// ---------------------------------------- Spell - Demacia
// [02DE007] Ranger's Resolve - COST:1
// - Set: Set2, Rarity: Rare
// - Spell Speed: Burst
// --------------------------------------------------------
// Description: Give all allies Tough this round.
// --------------------------------------------------------
// Keyword:
// - Burst = 1
// --------------------------------------------------------
// ---------------------------------------- Spell - Demacia
// [02DE001] Concerted Strike - COST:5
// - Set: Set2, Rarity: Common
// - Spell Speed: Fast
// --------------------------------------------------------
// Description: Pick an enemy.
// 2 allies strike it one after another.
// --------------------------------------------------------
// Keyword:
// - Fast = 1
// --------------------------------------------------------
}
void AddDemaciaNonCollect(entt::registry& registry)
{
// ---------------------------------------- Spell - Demacia
// [02DE006T3] Quinn's Blinding Assault - COST:2
// - Supertype: Champion, Set: Set2, Rarity: None
// - Spell Speed: Slow
// --------------------------------------------------------
// Description: Summon Valor.
// Create a Quinn in your deck.
// --------------------------------------------------------
// Keyword:
// - Slow = 1
// --------------------------------------------------------
// ----------------------------------------- Unit - Demacia
// [02DE006T2] Valor - COST:2
// - Set: Set2, Rarity: None
// --------------------------------------------------------
// Keyword:
// - Challenger = 1
// - Scout = 1
// --------------------------------------------------------
// ----------------------------------------- Unit - Demacia
// [02DE006T1] Quinn - COST:5
// - Supertype: Champion, Set: Set2, Rarity: None
// --------------------------------------------------------
// Description: Attack: Summon Valor Challenging
// the strongest enemy.
// --------------------------------------------------------
// Keyword:
// - Scout = 1
// --------------------------------------------------------
}
void AddFreljord(entt::registry& registry)
{
// ---------------------------------------- Unit - Freljord
// [02FR009] Wolfrider - COST:4
// - Set: Set2, Rarity: Common
// --------------------------------------------------------
// Description: Plunder: Get an empty mana gem.
// --------------------------------------------------------
// Keyword:
// - Overwhelm = 1
// --------------------------------------------------------
// --------------------------------------- Spell - Freljord
// [02FR004] Caught in the Cold - COST:2
// - Set: Set2, Rarity: Rare
// - Spell Speed: Slow
// --------------------------------------------------------
// Description: Give an enemy Frostbite and Vulnerable this round.
// --------------------------------------------------------
// Keyword:
// - Slow = 1
// --------------------------------------------------------
// ---------------------------------------- Unit - Freljord
// [02FR002] Sejuani - COST:6
// - Supertype: Champion, Set: Set2, Rarity: Champion
// --------------------------------------------------------
// Description: Play: Give an enemy Frostbite and
// Vulnerable this round.
// --------------------------------------------------------
// Level Up Description: You've damaged the enemy Nexus
// in 5 different rounds.
// --------------------------------------------------------
// Keyword:
// - Overwhelm = 1
// --------------------------------------------------------
// ---------------------------------------- Unit - Freljord
// [02FR001] Ember Maiden - COST:3
// - Set: Set2, Rarity: Rare
// --------------------------------------------------------
// Description: Round Start: Deal 1 to EVERYTHING.
// --------------------------------------------------------
// ---------------------------------------- Unit - Freljord
// [02FR005] Ursine Spiritwalker - COST:5
// - Set: Set2, Rarity: Common
// --------------------------------------------------------
// Description: Plunder: I transform into Stormclaw Ursine.
// --------------------------------------------------------
// --------------------------------------- Spell - Freljord
// [02FR010] Shared Spoils - COST:2
// - Set: Set2, Rarity: Rare
// - Spell Speed: Burst
// --------------------------------------------------------
// Description: Grant the top 3 units in your deck +1|+1.
// Plunder: Draw 1 of them.
// --------------------------------------------------------
// Keyword:
// - Burst = 1
// --------------------------------------------------------
// ---------------------------------------- Unit - Freljord
// [02FR008] The Tuskraider - COST:8
// - Set: Set2, Rarity: Epic
// --------------------------------------------------------
// Description: When I'm summoned, Draw a Sejuani.
// Plunder: Double the Power and Health
// of allies in your deck.
// --------------------------------------------------------
// --------------------------------------- Spell - Freljord
// [02FR007] Fury of the North - COST:4
// - Set: Set2, Rarity: Common
// - Spell Speed: Burst
// --------------------------------------------------------
// Description: Give an ally +3|+4 this round.
// --------------------------------------------------------
// Keyword:
// - Burst = 1
// --------------------------------------------------------
// ---------------------------------------- Unit - Freljord
// [02FR006] Ruthless Raider - COST:2
// - Set: Set2, Rarity: Common
// --------------------------------------------------------
// Keyword:
// - Overwhelm = 1
// - Tough = 1
// --------------------------------------------------------
// --------------------------------------- Spell - Freljord
// [02FR003] Aurora Porealis - COST:6
// - Set: Set2, Rarity: Epic
// - Spell Speed: Burst
// --------------------------------------------------------
// Description: Create 2 random Poros and 2 Poro Snax in hand.
// --------------------------------------------------------
// Keyword:
// - Burst = 1
// --------------------------------------------------------
}
void AddFreljordNonCollect(entt::registry& registry)
{
// ---------------------------------------- Unit - Freljord
// [02FR005T1] Stormclaw Ursine - COST:5
// - Set: Set2, Rarity: None
// --------------------------------------------------------
// Description: Other allies with 5+ Power have Overwhelm.
// --------------------------------------------------------
// Keyword:
// - Overwhelm = 1
// - Missing Translation = 1
// --------------------------------------------------------
// --------------------------------------- Spell - Freljord
// [02FR002T1] Sejuani's Fury of the North - COST:4
// - Supertype: Champion, Set: Set2, Rarity: None
// - Spell Speed: Burst
// --------------------------------------------------------
// Description: Give an ally +3|+4 this round.
// Create a Sejuani in your deck.
// --------------------------------------------------------
// Keyword:
// - Burst = 1
// --------------------------------------------------------
// ---------------------------------------- Unit - Freljord
// [02FR002T3] Sejuani - COST:6
// - Supertype: Champion, Set: Set2, Rarity: None
// --------------------------------------------------------
// Description: Play: Give an enemy Frostbite and
// Vulnerable this round.
// Each round, the first time you damage
// the enemy Nexus, Frostbite all enemies.
// --------------------------------------------------------
// Keyword:
// - Overwhelm = 1
// --------------------------------------------------------
}
void AddIonia(entt::registry& registry)
{
// ------------------------------------------ Spell - Ionia
// [02IO008] Sonic Wave - COST:2
// - Set: Set2, Rarity: Common
// - Spell Speed: Burst
// --------------------------------------------------------
// Description: Give an ally Challenger this round.
// Create a Fleeting Resonating Strike in hand.
// --------------------------------------------------------
// Keyword:
// - Burst = 1
// --------------------------------------------------------
// ------------------------------------------- Unit - Ionia
// [02IO002] Scales of the Dragon - COST:3
// - Set: Set2, Rarity: Common
// --------------------------------------------------------
// Description: When I'm summoned,
// create a Dragon's Protection in hand.
// --------------------------------------------------------
// ------------------------------------------- Unit - Ionia
// [02IO006] Lee Sin - COST:5
// - Supertype: Champion, Set: Set2, Rarity: Champion
// --------------------------------------------------------
// Description: When you cast a spell, give me Challenger this round.
// If you cast another, give me Barrier this round.
// --------------------------------------------------------
// Level Up Description: You've cast 8+ spells.
// --------------------------------------------------------
// Keyword:
// - Imbue = 1
// --------------------------------------------------------
// ------------------------------------------- Unit - Ionia
// [02IO004] Horns of the Dragon - COST:6
// - Set: Set2, Rarity: Common
// --------------------------------------------------------
// Keyword:
// - Double Attack = 1
// --------------------------------------------------------
// ------------------------------------------- Unit - Ionia
// [02IO003] Eye of the Dragon - COST:2
// - Set: Set2, Rarity: Epic
// --------------------------------------------------------
// Description: Round Start: Summon a Dragonling if you cast
// 2+ spells last round.
// --------------------------------------------------------
// Keyword:
// - Attune = 1
// --------------------------------------------------------
// ------------------------------------------- Unit - Ionia
// [02IO001] Claws of the Dragon - COST:2
// - Set: Set2, Rarity: Common
// --------------------------------------------------------
// Description: Summon me from hand the first time
// you've played 2 spells each round.
// --------------------------------------------------------
// ------------------------------------------ Spell - Ionia
// [02IO005] Concussive Palm - COST:4
// - Set: Set2, Rarity: Rare
// - Spell Speed: Fast
// --------------------------------------------------------
// Description: Stun an enemy to summon a Tail of the Dragon.
// --------------------------------------------------------
// Keyword:
// - Fast = 1
// --------------------------------------------------------
// ------------------------------------------ Spell - Ionia
// [02IO010] Retreat - COST:2
// - Set: Set2, Rarity: Rare
// - Spell Speed: Fast
// --------------------------------------------------------
// Description: Recall an ally to create a Fleeting Return
// in hand.
// --------------------------------------------------------
// Keyword:
// - Fast = 1
// --------------------------------------------------------
// ------------------------------------------ Spell - Ionia
// [02IO007] Dragon's Rage - COST:7
// - Set: Set2, Rarity: Epic
// - Spell Speed: Slow
// --------------------------------------------------------
// Description: An ally kicks an enemy into the enemy Nexus,
// striking both.
// If the enemy survives, Recall it.
// --------------------------------------------------------
// Keyword:
// - Slow = 1
// --------------------------------------------------------
// ------------------------------------------ Spell - Ionia
// [02IO009] Deep Meditation - COST:5
// - Set: Set2, Rarity: Rare
// - Spell Speed: Burst
// --------------------------------------------------------
// Description: Costs 2 less if you cast 2+ spells last round.
// Draw 2 other spells.
// --------------------------------------------------------
// Keyword:
// - Burst = 1
// --------------------------------------------------------
}
void AddIoniaNonCollect(entt::registry& registry)
{
// ------------------------------------------ Spell - Ionia
// [02IO008T1] Resonating Strike - COST:1
// - Set: Set2, Rarity: None
// - Spell Speed: Burst
// --------------------------------------------------------
// Description: Give an ally +2|+0 this round.
// --------------------------------------------------------
// Keyword:
// - Burst = 1
// - Fleeting = 1
// --------------------------------------------------------
// ------------------------------------------- Unit - Ionia
// [02IO005T1] Tail of the Dragon - COST:3
// - Set: Set2, Rarity: None
// --------------------------------------------------------
// Description: When I'm Recalled, transform me
// into Concussive Palm.
// --------------------------------------------------------
// ------------------------------------------ Spell - Ionia
// [02IO002T1] Dragon's Protection - COST:2
// - Set: Set2, Rarity: None
// - Spell Speed: Slow
// --------------------------------------------------------
// Description: Grant an ally +0|+3.
// --------------------------------------------------------
// Keyword:
// - Slow = 1
// --------------------------------------------------------
// ------------------------------------------ Spell - Ionia
// [02IO011] Lee Sin's Sonic Wave - COST:2
// - Supertype: Champion, Set: Set2, Rarity: None
// - Spell Speed: Burst
// --------------------------------------------------------
// Description: Give an ally Challenger this round.
// Create a Fleeting Resonating Strike in hand.
// Create a Lee Sin in your deck.
// --------------------------------------------------------
// Keyword:
// - Burst = 1
// --------------------------------------------------------
// ------------------------------------------- Unit - Ionia
// [02IO006T1] Lee Sin - COST:5
// - Supertype: Champion, Set: Set2, Rarity: None
// --------------------------------------------------------
// Description: When you cast a spell, give me Challenger this round.
// If you cast another, give me Barrier this round.
// I Dragon's Rage enemies that I Challenge.
// --------------------------------------------------------
// Keyword:
// - Imbue = 1
// --------------------------------------------------------
// ---------------------------------------- Ability - Ionia
// [02IO006T3] Dragon's Rage - COST:0
// - Set: Set2, Rarity: None
// --------------------------------------------------------
// Description: An ally kicks an enemy into the enemy Nexus,
// striking both.
// If the enemy survives, Recall it.
// --------------------------------------------------------
// Keyword:
// - Skill = 1
// --------------------------------------------------------
// ------------------------------------------- Unit - Ionia
// [02IO003T1] Dragonling - COST:2
// - Subtype: Dragon, Set: Set2, Rarity: None
// --------------------------------------------------------
// Keyword:
// - Ephemeral = 1
// - Lifesteal = 1
// --------------------------------------------------------
// ------------------------------------------ Spell - Ionia
// [02IO010T1] Return - COST:1
// - Set: Set2, Rarity: None
// - Spell Speed: Burst
// --------------------------------------------------------
// Description: Summon an ally that costs 3 or less from hand.
// --------------------------------------------------------
// Keyword:
// - Burst = 1
// - Fleeting = 1
// --------------------------------------------------------
}
void AddNoxus(entt::registry& registry)
{
// ------------------------------------------- Unit - Noxus
// [02NX001] The Leviathan - COST:8
// - Set: Set2, Rarity: Epic
// --------------------------------------------------------
// Description: When I'm summoned, draw a Swain.
// Round Start: Deal 1 to the enemy Nexus 3 times.
// --------------------------------------------------------
// Keyword:
// - Overwhelm = 1
// --------------------------------------------------------
// ------------------------------------------- Unit - Noxus
// [02NX007] Swain - COST:5
// - Supertype: Champion, Set: Set2, Rarity: Champion
// --------------------------------------------------------
// Description: Nexus Strike: Deal 3 to the enemy Nexus.
// --------------------------------------------------------
// Level Up Description: You've dealt 12 non-combat damage.
// --------------------------------------------------------
// Keyword:
// - Fearsome = 1
// --------------------------------------------------------
// ------------------------------------------- Unit - Noxus
// [02NX006] Citybreaker - COST:4
// - Set: Set2, Rarity: Rare
// --------------------------------------------------------
// Description: Round Start: Deal 1 to the enemy Nexus.
// --------------------------------------------------------
// ------------------------------------------- Unit - Noxus
// [02NX002] Aurok Glinthorn - COST:6
// - Set: Set2, Rarity: Epic
// --------------------------------------------------------
// Description: Attack: Stun all damaged enemies.
// --------------------------------------------------------
// ------------------------------------------ Spell - Noxus
// [02NX009] Ravenous Flock - COST:1
// - Set: Set2, Rarity: Rare
// - Spell Speed: Fast
// --------------------------------------------------------
// Description: Deal 4 to a unit if it's damaged or Stunned.
// --------------------------------------------------------
// Keyword:
// - Fast = 1
// --------------------------------------------------------
// ------------------------------------------- Unit - Noxus
// [02NX004] Imperial Demolitionist - COST:2
// - Set: Set2, Rarity: Common
// --------------------------------------------------------
// Description: Play: Deal 1 to an ally to deal 2
// to the enemy Nexus.
// --------------------------------------------------------
// ------------------------------------------ Spell - Noxus
// [02NX003] Noxian Fervor - COST:3
// - Set: Set2, Rarity: Common
// - Spell Speed: Fast
// --------------------------------------------------------
// Description: Deal 3 to an ally to deal 3 to anything.
// --------------------------------------------------------
// Keyword:
// - Fast = 1
// --------------------------------------------------------
// ------------------------------------------- Unit - Noxus
// [02NX010] Armored Tuskrider - COST:6
// - Set: Set2, Rarity: Rare
// --------------------------------------------------------
// Description: Enemies with 4 or less Power cannot damage me.
// --------------------------------------------------------
// Keyword:
// - Overwhelm = 1
// --------------------------------------------------------
// ------------------------------------------ Spell - Noxus
// [02NX008] Death's Hand - COST:3
// - Set: Set2, Rarity: Common
// - Spell Speed: Fast
// --------------------------------------------------------
// Description: Deal 2 to an enemy and 1 to the enemy Nexus.
// --------------------------------------------------------
// Keyword:
// - Fast = 1
// --------------------------------------------------------
// ------------------------------------------- Unit - Noxus
// [02NX005] Iron Ballista - COST:3
// - Set: Set2, Rarity: Common
// --------------------------------------------------------
// Keyword:
// - Overwhelm = 1
// --------------------------------------------------------
}
void AddNoxusNonCollect(entt::registry& registry)
{
// ------------------------------------------- Unit - Noxus
// [02NX007T2] Swain - COST:5
// - Supertype: Champion, Set: Set2, Rarity: None
// --------------------------------------------------------
// Description: When you deal non-combat damage to the enemy Nexus,
// Stun the strongest backrow enemy.
// Nexus Strike: Deal 3 to all enemies and
// the enemy Nexus.
// --------------------------------------------------------
// Keyword:
// - Fearsome = 1
// --------------------------------------------------------
// ------------------------------------------ Spell - Noxus
// [02NX007T1] Swain's Ravenous Flock - COST:1
// - Supertype: Champion, Set: Set2, Rarity: None
// - Spell Speed: Fast
// --------------------------------------------------------
// Description: Deal 4 to a unit if it's damaged or Stunned.
// Create a Swain in your deck.
// --------------------------------------------------------
// Keyword:
// - Fast = 1
// --------------------------------------------------------
// ---------------------------------------- Ability - Noxus
// [02NX004T1] Black Powder Grenade - COST:0
// - Set: Set2, Rarity: None
// --------------------------------------------------------
// Description: Deal 1 to an ally to deal 2 to the enemy Nexus.
// --------------------------------------------------------
// Keyword:
// - Skill = 1
// --------------------------------------------------------
}
void AddPiltoverZaun(entt::registry& registry)
{
// --------------------------------- Unit - Piltover-&-Zaun
// [02PZ001] Subpurrsible - COST:5
// - Set: Set2, Rarity: Epic
// --------------------------------------------------------
// Description: When I'm summoned, draw 1.
// Then, if you've played at least 10 other cards
// with different names, grant me +4|+0.
// --------------------------------------------------------
// Keyword:
// - Elusive = 1
// --------------------------------------------------------
// --------------------------------- Unit - Piltover-&-Zaun
// [02PZ010] Veteran Investigator - COST:2
// - Subtype: Yordle, Set: Set2, Rarity: Common
// --------------------------------------------------------
// Description: When I'm summoned, ALL players draw 1.
// --------------------------------------------------------
// -------------------------------- Spell - Piltover-&-Zaun
// [02PZ006] Gotcha! - COST:4
// - Set: Set2, Rarity: Common
// - Spell Speed: Fast
// --------------------------------------------------------
// Description: When drawn, costs 2 less this round.
// Deal 3 to a unit.
// --------------------------------------------------------
// Keyword:
// - Fast = 1
// --------------------------------------------------------
// -------------------------------- Spell - Piltover-&-Zaun
// [02PZ004] Vault Breaker - COST:3
// - Set: Set2, Rarity: Rare
// - Spell Speed: Burst
// --------------------------------------------------------
// Description: Give an ally +2|+0 this round.
// Create a Fleeting Vault Breaker in hand.
// --------------------------------------------------------
// Keyword:
// - Burst = 1
// --------------------------------------------------------
// --------------------------------- Unit - Piltover-&-Zaun
// [02PZ007] Insightful Investigator - COST:4
// - Set: Set2, Rarity: Rare
// --------------------------------------------------------
// Description: When you play a 2 cost card,
// draw 1 and give it Fleeting.
// --------------------------------------------------------
// --------------------------------- Unit - Piltover-&-Zaun
// [02PZ002] Chief Mechanist Zevi - COST:6
// - Set: Set2, Rarity: Epic
// --------------------------------------------------------
// Description: When you draw a card, give it Fleeting
// and create an exact copy of it in hand.
// --------------------------------------------------------
// --------------------------------- Unit - Piltover-&-Zaun
// [02PZ008] Vi - COST:5
// - Supertype: Champion, Set: Set2, Rarity: Champion
// --------------------------------------------------------
// Description: While I'm in play or in hand, grant me +1|+0
// when you play another card (max +8|+0).
// --------------------------------------------------------
// Level Up Description: I've struck for 10+ Damage.
// --------------------------------------------------------
// Keyword:
// - Challenger = 1
// - Tough = 1
// --------------------------------------------------------
// -------------------------------- Spell - Piltover-&-Zaun
// [02PZ009] Trail of Evidence - COST:2
// - Set: Set2, Rarity: Common
// - Spell Speed: Burst
// --------------------------------------------------------
// Description: Create in hand a random 2 cost card
// from your regions. It costs 0 this round.
// --------------------------------------------------------
// Keyword:
// - Burst = 1
// --------------------------------------------------------
// -------------------------------- Spell - Piltover-&-Zaun
// [02PZ003] Suit Up! - COST:4
// - Set: Set2, Rarity: Rare
// - Spell Speed: Burst
// --------------------------------------------------------
// Description: When drawn, costs 2 less this round.
// Grow an ally to 4|4.
// --------------------------------------------------------
// Keyword:
// - Burst = 1
// --------------------------------------------------------
// --------------------------------- Unit - Piltover-&-Zaun
// [02PZ005] Patrol Wardens - COST:3
// - Set: Set2, Rarity: Common
// --------------------------------------------------------
// Description: When I'm drawn, I cost 1 less this round.
// --------------------------------------------------------
}
void AddPiltoverZaunNonCollect(entt::registry& registry)
{
// --------------------------------- Unit - Piltover-&-Zaun
// [02PZ008T2] Vi - COST:5
// - Supertype: Champion, Set: Set2, Rarity: None
// --------------------------------------------------------
// Description: When I strike a unit while attacking,
// deal 5 to the enemy Nexus.
// --------------------------------------------------------
// Keyword:
// - Challenger = 1
// - Tough = 1
// --------------------------------------------------------
// -------------------------------- Spell - Piltover-&-Zaun
// [02PZ008T1] Vi's Vault Breaker - COST:3
// - Supertype: Champion, Set: Set2, Rarity: None
// - Spell Speed: Burst
// --------------------------------------------------------
// Description: Give an ally +2|+0 this round.
// Create a Fleeting Vault Breaker in hand.
// Create a Vi in your deck.
// --------------------------------------------------------
// Keyword:
// - Burst = 1
// --------------------------------------------------------
}
void AddShadowIsles(entt::registry& registry)
{
// ----------------------------------- Spell - Shadow-Isles
// [02SI005] Sap Magic - COST:3
// - Set: Set2, Rarity: Rare
// - Spell Speed: Burst
// --------------------------------------------------------
// Description: Toss 3.
// Heal all allies 3.
// --------------------------------------------------------
// Keyword:
// - Burst = 1
// --------------------------------------------------------
// ------------------------------------ Unit - Shadow-Isles
// [02SI010] Deadbloom Wanderer - COST:3
// - Set: Set2, Rarity: Common
// --------------------------------------------------------
// Description: When I'm summoned, Toss 3.
// --------------------------------------------------------
// Keyword:
// - Lifesteal = 1
// --------------------------------------------------------
// ------------------------------------ Unit - Shadow-Isles
// [02SI008] Maokai - COST:4
// - Supertype: Champion, Set: Set2, Rarity: Champion
// --------------------------------------------------------
// Description: Each round, the first time you play another ally,
// Toss 2 and summon a Sapling.
// --------------------------------------------------------
// Level Up Description: Your units have died or your cards
// have been Tossed 25 times.
// --------------------------------------------------------
// ------------------------------------ Unit - Shadow-Isles
// [02SI007] Thorny Toad - COST:2
// - Set: Set2, Rarity: Common
// --------------------------------------------------------
// Description: Last Breath: Toss 2 and heal your Nexus 2.
// --------------------------------------------------------
// Keyword:
// - Last Breath = 1
// --------------------------------------------------------
// ------------------------------------ Unit - Shadow-Isles
// [02SI003] Terror of the Tides - COST:8
// - Subtype: Sea monster, Set: Set2, Rarity: Epic
// --------------------------------------------------------
// Description: Sea Monster allies have Fearsome.
// Attack: Give enemies -2|-0 this round.
// --------------------------------------------------------
// Keyword:
// - Deep = 1
// --------------------------------------------------------
// ------------------------------------ Unit - Shadow-Isles
// [02SI001] Neverglade Collector - COST:5
// - Set: Set2, Rarity: Rare
// --------------------------------------------------------
// Description: When another ally dies,
// drain 1 from the enemy Nexus.
// --------------------------------------------------------
// ------------------------------------ Unit - Shadow-Isles
// [02SI002] Overgrown Snapvine - COST:7
// - Set: Set2, Rarity: Epic
// --------------------------------------------------------
// Description: When you summon a follower,
// kill it to summon an Overgrown Snapvine.
// --------------------------------------------------------
// ------------------------------------ Unit - Shadow-Isles
// [02SI004] Blighted Caretaker - COST:3
// - Set: Set2, Rarity: Rare
// --------------------------------------------------------
// Description: Play: Kill an ally to summon 2 Saplings.
// --------------------------------------------------------
// ------------------------------------ Unit - Shadow-Isles
// [02SI006] Barkbeast - COST:1
// - Set: Set2, Rarity: Common
// --------------------------------------------------------
// Description: The first time an ally dies, grant me +2|+2.
// --------------------------------------------------------
// ----------------------------------- Spell - Shadow-Isles
// [02SI009] Sapling Toss - COST:1
// - Set: Set2, Rarity: Common
// - Spell Speed: Burst
// --------------------------------------------------------
// Description: Summon a Sapling at the next Round Start.
// --------------------------------------------------------
// Keyword:
// - Burst = 1
// --------------------------------------------------------
}
void AddShadowIslesyNonCollect(entt::registry& registry)
{
// ------------------------------------ Unit - Shadow-Isles
// [02SI008T3] Sapling - COST:1
// - Set: Set2, Rarity: None
// --------------------------------------------------------
// Keyword:
// - Ephemeral = 1
// - Challenger = 1
// --------------------------------------------------------
// ----------------------------------- Spell - Shadow-Isles
// [02SI008T1] Maokai's Sap Magic - COST:3
// - Supertype: Champion, Set: Set2, Rarity: None
// - Spell Speed: Burst
// --------------------------------------------------------
// Description: Toss 3.
// Heal all allies 3.
// Create a Maokai in your deck.
// --------------------------------------------------------
// Keyword:
// - Burst = 1
// --------------------------------------------------------
// ------------------------------------ Unit - Shadow-Isles
// [02SI008T2] Maokai - COST:4
// - Supertype: Champion, Set: Set2, Rarity: None
// --------------------------------------------------------
// Description: When I Level Up, Obliterate the enemy deck,
// leaving 4 non-champions.
// Round Start: Summon a Sapling.
// --------------------------------------------------------
// Keyword:
// - Regeneration = 1
// --------------------------------------------------------
}
void AddShurima(entt::registry& registry)
{
// Do nothing
}
void AddShurimaNonCollect(entt::registry& registry)
{
// Do nothing
}
void AddTargon(entt::registry& registry)
{
// Do nothing
}
void AddTargonNonCollect(entt::registry& registry)
{
// Do nothing
}
void AddAll(entt::registry& registry)
{
AddBandleCity(registry);
AddBandleCityNonCollect(registry);
AddBilgewater(registry);
AddBilgewaterNonCollect(registry);
AddDemacia(registry);
AddDemaciaNonCollect(registry);
AddFreljord(registry);
AddFreljordNonCollect(registry);
AddIonia(registry);
AddIoniaNonCollect(registry);
AddNoxus(registry);
AddNoxusNonCollect(registry);
AddPiltoverZaun(registry);
AddPiltoverZaunNonCollect(registry);
AddShadowIsles(registry);
AddShadowIslesyNonCollect(registry);
AddShurima(registry);
AddShurimaNonCollect(registry);
AddTargon(registry);
AddTargonNonCollect(registry);
AddBandleCity(registry);
AddBandleCityNonCollect(registry);
}
} // namespace Runeterra::Set2
|
/*===============================================================================
Copyright (c) 2016 PTC Inc. All Rights Reserved.
Copyright (c) 2012-2014 Qualcomm Connected Experiences, Inc. All Rights Reserved.
Vuforia is a trademark of PTC Inc., registered in the United States and other
countries.
===============================================================================*/
#include <jni.h>
#include <android/log.h>
#include <stdio.h>
#include <string.h>
#include <GLES2/gl2.h>
#include <Vuforia/Vuforia.h>
#include <Vuforia/CameraDevice.h>
#include <Vuforia/Renderer.h>
#include <Vuforia/VideoBackgroundConfig.h>
#include <Vuforia/Trackable.h>
#include <Vuforia/TrackableResult.h>
#include <Vuforia/Tool.h>
#include <Vuforia/Tracker.h>
#include <Vuforia/TrackerManager.h>
#include <Vuforia/ObjectTracker.h>
#include <Vuforia/UpdateCallback.h>
#include <Vuforia/DataSet.h>
#include <Vuforia/Device.h>
#include <Vuforia/GLRenderer.h>
#include <Vuforia/StateUpdater.h>
#include "SampleUtils.h"
#include "Texture.h"
#include "SampleAppRenderer.h"
#include "ShareData.h"
#ifdef __cplusplus
extern "C"
{
#endif
// Textures:
int textureCount = 0;
Texture** textures = 0;
// Screen dimensions:
int screenWidth = 0;
int screenHeight = 0;
// Indicates whether screen is in portrait (true) or landscape (false) mode
bool isActivityInPortraitMode = false;
// Constants:
static const float kObjectScale = 0.003f;
static const float kBuildingsObjectScale = 0.012f;
Vuforia::DataSet* dataSetStonesAndChips = 0;
Vuforia::DataSet* dataSetTarmac = 0;
SampleAppRenderer* sampleAppRenderer = 0;
bool switchDataSetAsap = false;
bool isExtendedTrackingActivated = false;
Vuforia::CameraDevice::CAMERA_DIRECTION currentCamera;
const int STONES_AND_CHIPS_DATASET_ID = 0;
const int TARMAC_DATASET_ID = 1;
int selectedDataset = STONES_AND_CHIPS_DATASET_ID;
// Object to receive update callbacks from Vuforia SDK
class ImageTargets_UpdateCallback : public Vuforia::UpdateCallback
{
virtual void Vuforia_onUpdate(Vuforia::State& /*state*/)
{
if (switchDataSetAsap)
{
switchDataSetAsap = false;
// Get the object tracker:
Vuforia::TrackerManager& trackerManager = Vuforia::TrackerManager::getInstance();
Vuforia::ObjectTracker* objectTracker = static_cast<Vuforia::ObjectTracker*>(
trackerManager.getTracker(Vuforia::ObjectTracker::getClassType()));
if (objectTracker == 0 || dataSetStonesAndChips == 0 || dataSetTarmac == 0 ||
objectTracker->getActiveDataSet(0) == 0)
{
LOG("Failed to switch data set.");
return;
}
switch( selectedDataset )
{
case STONES_AND_CHIPS_DATASET_ID:
if (objectTracker->getActiveDataSet(0) != dataSetStonesAndChips)
{
objectTracker->deactivateDataSet(dataSetTarmac);
objectTracker->activateDataSet(dataSetStonesAndChips);
}
break;
case TARMAC_DATASET_ID:
if (objectTracker->getActiveDataSet(0) != dataSetTarmac)
{
objectTracker->deactivateDataSet(dataSetStonesAndChips);
objectTracker->activateDataSet(dataSetTarmac);
}
break;
}
if(isExtendedTrackingActivated)
{
Vuforia::DataSet* currentDataSet = objectTracker->getActiveDataSet(0);
for (int tIdx = 0; tIdx < currentDataSet->getNumTrackables(); tIdx++)
{
Vuforia::Trackable* trackable = currentDataSet->getTrackable(tIdx);
trackable->startExtendedTracking();
}
}
}
}
};
ImageTargets_UpdateCallback updateCallback;
JNIEXPORT void JNICALL
Java_com_meteor_1studio_holostage_ImageTargets_setActivityPortraitMode(JNIEnv *, jobject, jboolean isPortrait)
{
isActivityInPortraitMode = isPortrait;
}
JNIEXPORT void JNICALL
Java_com_meteor_1studio_holostage_ImageTargets_switchDatasetAsap(JNIEnv *, jobject, jint datasetId)
{
selectedDataset = datasetId;
switchDataSetAsap = true;
}
JNIEXPORT int JNICALL
Java_com_meteor_1studio_holostage_ImageTargets_initTracker(JNIEnv *, jobject)
{
LOG("Java_com_meteor_1studio_holostage_ImageTargets_initTracker");
// Initialize the object tracker:
Vuforia::TrackerManager& trackerManager = Vuforia::TrackerManager::getInstance();
Vuforia::Tracker* tracker = trackerManager.initTracker(Vuforia::ObjectTracker::getClassType());
if (tracker == NULL)
{
LOG("Failed to initialize ObjectTracker.");
return 0;
}
LOG("Successfully initialized ObjectTracker.");
return 1;
}
JNIEXPORT void JNICALL
Java_com_meteor_1studio_holostage_ImageTargets_deinitTracker(JNIEnv *, jobject)
{
LOG("Java_com_meteor_1studio_holostage_ImageTargets_deinitTracker");
// Deinit the object tracker:
Vuforia::TrackerManager& trackerManager = Vuforia::TrackerManager::getInstance();
trackerManager.deinitTracker(Vuforia::ObjectTracker::getClassType());
}
JNIEXPORT int JNICALL
Java_com_meteor_1studio_holostage_ImageTargets_loadTrackerData(JNIEnv *, jobject)
{
LOG("Java_com_meteor_1studio_holostage_ImageTargets_loadTrackerData");
// Get the object tracker:
Vuforia::TrackerManager& trackerManager = Vuforia::TrackerManager::getInstance();
Vuforia::ObjectTracker* objectTracker = static_cast<Vuforia::ObjectTracker*>(
trackerManager.getTracker(Vuforia::ObjectTracker::getClassType()));
if (objectTracker == NULL)
{
LOG("Failed to load tracking data set because the ObjectTracker has not"
" been initialized.");
return 0;
}
// Create the data sets:
dataSetStonesAndChips = objectTracker->createDataSet();
if (dataSetStonesAndChips == 0)
{
LOG("Failed to create a new tracking data.");
return 0;
}
dataSetTarmac = objectTracker->createDataSet();
if (dataSetTarmac == 0)
{
LOG("Failed to create a new tracking data.");
return 0;
}
// Load the data sets:
if (!dataSetStonesAndChips->load("StonesAndChips.xml", Vuforia::STORAGE_APPRESOURCE))
{
LOG("Failed to load data set.");
return 0;
}
if (!dataSetTarmac->load("Tarmac.xml", Vuforia::STORAGE_APPRESOURCE))
{
LOG("Failed to load data set.");
return 0;
}
// Activate the data set:
if (!objectTracker->activateDataSet(dataSetStonesAndChips))
{
LOG("Failed to activate data set.");
return 0;
}
LOG("Successfully loaded and activated data set.");
return 1;
}
JNIEXPORT int JNICALL
Java_com_meteor_1studio_holostage_ImageTargets_destroyTrackerData(JNIEnv *, jobject)
{
LOG("Java_com_meteor_1studio_holostage_ImageTargets_destroyTrackerData");
// Get the object tracker:
Vuforia::TrackerManager& trackerManager = Vuforia::TrackerManager::getInstance();
Vuforia::ObjectTracker* objectTracker = static_cast<Vuforia::ObjectTracker*>(
trackerManager.getTracker(Vuforia::ObjectTracker::getClassType()));
if (objectTracker == NULL)
{
LOG("Failed to destroy the tracking data set because the ObjectTracker has not"
" been initialized.");
return 0;
}
if (dataSetStonesAndChips != 0)
{
if (objectTracker->getActiveDataSet(0) == dataSetStonesAndChips &&
!objectTracker->deactivateDataSet(dataSetStonesAndChips))
{
LOG("Failed to destroy the tracking data set StonesAndChips because the data set "
"could not be deactivated.");
return 0;
}
if (!objectTracker->destroyDataSet(dataSetStonesAndChips))
{
LOG("Failed to destroy the tracking data set StonesAndChips.");
return 0;
}
LOG("Successfully destroyed the data set StonesAndChips.");
dataSetStonesAndChips = 0;
}
if (dataSetTarmac != 0)
{
if (objectTracker->getActiveDataSet(0) == dataSetTarmac &&
!objectTracker->deactivateDataSet(dataSetTarmac))
{
LOG("Failed to destroy the tracking data set Tarmac because the data set "
"could not be deactivated.");
return 0;
}
if (!objectTracker->destroyDataSet(dataSetTarmac))
{
LOG("Failed to destroy the tracking data set Tarmac.");
return 0;
}
LOG("Successfully destroyed the data set Tarmac.");
dataSetTarmac = 0;
}
return 1;
}
JNIEXPORT void JNICALL
Java_com_meteor_1studio_holostage_ImageTargets_onVuforiaInitializedNative(JNIEnv *, jobject)
{
// Register the update callback where we handle the data set swap:
Vuforia::registerCallback(&updateCallback);
// Comment in to enable tracking of up to 2 targets simultaneously and
// split the work over multiple frames:
// Vuforia::setHint(Vuforia::HINT_MAX_SIMULTANEOUS_IMAGE_TARGETS, 2);
}
JNIEXPORT void JNICALL
Java_com_meteor_1studio_holostage_ImageTargetsRenderer_renderFrame(JNIEnv *, jobject)
{
// Call renderFrame from SampleAppRenderer which will loop through the rendering primitives
// views and then it will call renderFrameForView per each of the views available,
// in this case there is only one view since it is not rendering in stereo mode
sampleAppRenderer->renderFrame();
}
// This method will be called from SampleAppRenderer per each rendering primitives view
void renderFrameForView(const Vuforia::State *state, Vuforia::Matrix44F& projectionMatrix)
{
// Explicitly render the Video Background
sampleAppRenderer->renderVideoBackground();
// Did we find any trackables this frame?
int numTrackableResults = state->getNumTrackableResults();
// if(numTrackableResults <= 0){
// memset(modelViewShare, 0, sizeof(modelViewShare));
// memset(projectionShare, 0, sizeof(projectionShare));
// mvpUsed = false;
// return;
// }
for(int tIdx = 0; tIdx < numTrackableResults; tIdx++)
{
// Get the trackable:
const Vuforia::TrackableResult* result = state->getTrackableResult(tIdx);
const Vuforia::Trackable& trackable = result->getTrackable();
Vuforia::Matrix44F modelViewMatrix =
Vuforia::Tool::convertPose2GLMatrix(result->getPose());
//Vuforia::Matrix44F modelViewProjection;
SampleUtils::translatePoseMatrix(0.0f, 0.0f, kObjectScale,
&modelViewMatrix.data[0]);
SampleUtils::scalePoseMatrix(kObjectScale, kObjectScale, kObjectScale,
&modelViewMatrix.data[0]);
projectionMatrix.data[1] = -projectionMatrix.data[1];
memcpy(modelViewShare, modelViewMatrix.data, sizeof(modelViewMatrix.data));
memcpy(projectionShare, projectionMatrix.data, sizeof(projectionMatrix.data));
mvpUsed = false;
//for(int i = 0; i < 4; i++){
// LOG("ModelView matrix: %f, %f, %f, %f", modelViewShare[i*4], modelViewShare[i * 4 + 1], modelViewShare[i * 4 + 2], modelViewShare[i * 4 + 3]);
//}
// LOG("ModelView matrix: blank");
//LOG("ModelView matrix: blank");
// for(int i = 0; i < 4; i++){
// LOG("Projection matrix: %f, %f, %f, %f", projectionShare[i*4], projectionShare[i * 4 + 1], projectionShare[i * 4 + 2], projectionShare[i * 4 + 3]);
// }
// LOG("Projection matrix: blank");
// LOG("Projection matrix: blank");
}
glDisable(GL_DEPTH_TEST);
}
void
configureVideoBackground()
{
// Get the default video mode:
Vuforia::CameraDevice& cameraDevice = Vuforia::CameraDevice::getInstance();
Vuforia::VideoMode videoMode = cameraDevice.
getVideoMode(Vuforia::CameraDevice::MODE_DEFAULT);
// Configure the video background
Vuforia::VideoBackgroundConfig config;
config.mEnabled = true;
config.mPosition.data[0] = 0.0f;
config.mPosition.data[1] = 0.0f;
if (isActivityInPortraitMode)
{
//LOG("configureVideoBackground PORTRAIT");
config.mSize.data[0] = videoMode.mHeight
* (screenHeight / (float)videoMode.mWidth);
config.mSize.data[1] = screenHeight;
if(config.mSize.data[0] < screenWidth)
{
LOG("Correcting rendering background size to handle missmatch between screen and video aspect ratios.");
config.mSize.data[0] = screenWidth;
config.mSize.data[1] = screenWidth *
(videoMode.mWidth / (float)videoMode.mHeight);
}
}
else
{
//LOG("configureVideoBackground LANDSCAPE");
config.mSize.data[0] = screenWidth;
config.mSize.data[1] = videoMode.mHeight
* (screenWidth / (float)videoMode.mWidth);
if(config.mSize.data[1] < screenHeight)
{
LOG("Correcting rendering background size to handle missmatch between screen and video aspect ratios.");
config.mSize.data[0] = screenHeight
* (videoMode.mWidth / (float)videoMode.mHeight);
config.mSize.data[1] = screenHeight;
}
}
LOG("Configure Video Background : Video (%d,%d), Screen (%d,%d), mSize (%d,%d)", videoMode.mWidth, videoMode.mHeight, screenWidth, screenHeight, config.mSize.data[0], config.mSize.data[1]);
// Set the config:
Vuforia::Renderer::getInstance().setVideoBackgroundConfig(config);
}
JNIEXPORT void JNICALL
Java_com_meteor_1studio_holostage_ImageTargets_initApplicationNative(
JNIEnv* env, jobject obj, jint width, jint height)
{
LOG("Java_com_meteor_1studio_holostage_ImageTargets_initApplicationNative");
// Store screen dimensions
screenWidth = width;
screenHeight = height;
sampleAppRenderer = new SampleAppRenderer();
// Handle to the activity class:
jclass activityClass = env->GetObjectClass(obj);
jmethodID getTextureCountMethodID = env->GetMethodID(activityClass,
"getTextureCount", "()I");
if (getTextureCountMethodID == 0)
{
LOG("Function getTextureCount() not found.");
return;
}
textureCount = env->CallIntMethod(obj, getTextureCountMethodID);
if (!textureCount)
{
LOG("getTextureCount() returned zero.");
return;
}
textures = new Texture*[textureCount];
jmethodID getTextureMethodID = env->GetMethodID(activityClass,
"getTexture", "(I)Lcom/meteor_studio/holostage/Texture;");
if (getTextureMethodID == 0)
{
LOG("Function getTexture() not found.");
return;
}
// Register the textures
for (int i = 0; i < textureCount; ++i)
{
jobject textureObject = env->CallObjectMethod(obj, getTextureMethodID, i);
if (textureObject == NULL)
{
LOG("GetTexture() returned zero pointer");
return;
}
textures[i] = Texture::create(env, textureObject);
}
LOG("Java_com_meteor_1studio_holostage_ImageTargets_initApplicationNative finished");
}
JNIEXPORT void JNICALL
Java_com_meteor_1studio_holostage_ImageTargets_deinitApplicationNative(
JNIEnv* env, jobject obj)
{
LOG("Java_com_meteor_1studio_holostage_ImageTargets_deinitApplicationNative");
isExtendedTrackingActivated = false;
// Release texture resources
if (textures != 0)
{
for (int i = 0; i < textureCount; ++i)
{
delete textures[i];
textures[i] = NULL;
}
delete[]textures;
textures = NULL;
textureCount = 0;
}
delete sampleAppRenderer;
sampleAppRenderer = NULL;
}
JNIEXPORT void JNICALL
Java_com_meteor_1studio_holostage_ImageTargets_startCamera(JNIEnv *,
jobject, jint camera)
{
LOG("Java_com_meteor_1studio_holostage_ImageTargets_startCamera");
currentCamera = static_cast<Vuforia::CameraDevice::CAMERA_DIRECTION> (camera);
// Initialize the camera:
if (!Vuforia::CameraDevice::getInstance().init(currentCamera))
return;
// Select the default camera mode:
if (!Vuforia::CameraDevice::getInstance().selectVideoMode(
Vuforia::CameraDevice::MODE_DEFAULT))
return;
// Configure the rendering of the video background
configureVideoBackground();
// Start the camera:
if (!Vuforia::CameraDevice::getInstance().start())
return;
// Uncomment to enable flash
//if(Vuforia::CameraDevice::getInstance().setFlashTorchMode(true))
// LOG("IMAGE TARGETS : enabled torch");
// Uncomment to enable infinity focus mode, or any other supported focus mode
// See CameraDevice.h for supported focus modes
//if(Vuforia::CameraDevice::getInstance().setFocusMode(Vuforia::CameraDevice::FOCUS_MODE_INFINITY))
// LOG("IMAGE TARGETS : enabled infinity focus");
// Start the tracker:
Vuforia::TrackerManager& trackerManager = Vuforia::TrackerManager::getInstance();
Vuforia::Tracker* objectTracker = trackerManager.getTracker(Vuforia::ObjectTracker::getClassType());
if(objectTracker != 0)
objectTracker->start();
}
JNIEXPORT void JNICALL
Java_com_meteor_1studio_holostage_ImageTargets_stopCamera(JNIEnv *, jobject)
{
LOG("Java_com_meteor_1studio_holostage_ImageTargets_stopCamera");
// Stop the tracker:
Vuforia::TrackerManager& trackerManager = Vuforia::TrackerManager::getInstance();
Vuforia::Tracker* objectTracker = trackerManager.getTracker(Vuforia::ObjectTracker::getClassType());
if(objectTracker != 0)
objectTracker->stop();
Vuforia::CameraDevice::getInstance().stop();
Vuforia::CameraDevice::getInstance().deinit();
}
JNIEXPORT void JNICALL
Java_com_meteor_1studio_holostage_ImageTargetsRenderer_updateRenderingPrimitives(JNIEnv *, jobject)
{
LOG("Java_com_meteor_1studio_holostage_ImageTargetsRenderer_updateRenderingPrimitives");
sampleAppRenderer->updateRenderingPrimitives();
}
// ----------------------------------------------------------------------------
// Activates Camera Flash
// ----------------------------------------------------------------------------
JNIEXPORT jboolean JNICALL
Java_com_meteor_1studio_holostage_ImageTargets_activateFlash(JNIEnv*, jobject, jboolean flash)
{
return Vuforia::CameraDevice::getInstance().setFlashTorchMode((flash==JNI_TRUE)) ? JNI_TRUE : JNI_FALSE;
}
JNIEXPORT jboolean JNICALL
Java_com_meteor_1studio_holostage_ImageTargets_autofocus(JNIEnv*, jobject)
{
return Vuforia::CameraDevice::getInstance().setFocusMode(Vuforia::CameraDevice::FOCUS_MODE_TRIGGERAUTO) ? JNI_TRUE : JNI_FALSE;
}
JNIEXPORT jboolean JNICALL
Java_com_meteor_1studio_holostage_ImageTargets_setFocusMode(JNIEnv*, jobject, jint mode)
{
int focusMode;
switch ((int)mode)
{
case 0:
focusMode = Vuforia::CameraDevice::FOCUS_MODE_NORMAL;
break;
case 1:
focusMode = Vuforia::CameraDevice::FOCUS_MODE_CONTINUOUSAUTO;
break;
case 2:
focusMode = Vuforia::CameraDevice::FOCUS_MODE_INFINITY;
break;
case 3:
focusMode = Vuforia::CameraDevice::FOCUS_MODE_MACRO;
break;
default:
return JNI_FALSE;
}
return Vuforia::CameraDevice::getInstance().setFocusMode(focusMode) ? JNI_TRUE : JNI_FALSE;
}
JNIEXPORT jboolean JNICALL
Java_com_meteor_1studio_holostage_ImageTargets_startExtendedTracking(JNIEnv*, jobject)
{
Vuforia::TrackerManager& trackerManager = Vuforia::TrackerManager::getInstance();
Vuforia::ObjectTracker* objectTracker = static_cast<Vuforia::ObjectTracker*>(
trackerManager.getTracker(Vuforia::ObjectTracker::getClassType()));
Vuforia::DataSet* currentDataSet = objectTracker->getActiveDataSet(0);
if (objectTracker == 0 || currentDataSet == 0)
return JNI_FALSE;
for (int tIdx = 0; tIdx < currentDataSet->getNumTrackables(); tIdx++)
{
Vuforia::Trackable* trackable = currentDataSet->getTrackable(tIdx);
if(!trackable->startExtendedTracking())
return JNI_FALSE;
}
isExtendedTrackingActivated = true;
return JNI_TRUE;
}
JNIEXPORT jboolean JNICALL
Java_com_meteor_1studio_holostage_ImageTargets_stopExtendedTracking(JNIEnv*, jobject)
{
Vuforia::TrackerManager& trackerManager = Vuforia::TrackerManager::getInstance();
Vuforia::ObjectTracker* objectTracker = static_cast<Vuforia::ObjectTracker*>(
trackerManager.getTracker(Vuforia::ObjectTracker::getClassType()));
Vuforia::DataSet* currentDataSet = objectTracker->getActiveDataSet(0);
if (objectTracker == 0 || currentDataSet == 0)
return JNI_FALSE;
for (int tIdx = 0; tIdx < currentDataSet->getNumTrackables(); tIdx++)
{
Vuforia::Trackable* trackable = currentDataSet->getTrackable(tIdx);
if(!trackable->stopExtendedTracking())
return JNI_FALSE;
}
isExtendedTrackingActivated = false;
return JNI_TRUE;
}
JNIEXPORT void JNICALL
Java_com_meteor_1studio_holostage_ImageTargetsRenderer_initRendering(
JNIEnv* env, jobject obj)
{
LOG("Java_com_meteor_1studio_holostage_ImageTargetsRenderer_initRendering");
// Define clear color
glClearColor(0.0f, 0.0f, 0.0f, Vuforia::requiresAlpha() ? 0.0f : 1.0f);
// Now generate the OpenGL texture objects and add settings
for (int i = 0; i < textureCount; ++i)
{
glGenTextures(1, &(textures[i]->mTextureID));
glBindTexture(GL_TEXTURE_2D, textures[i]->mTextureID);
glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA, textures[i]->mWidth,
textures[i]->mHeight, 0, GL_RGBA, GL_UNSIGNED_BYTE,
(GLvoid*) textures[i]->mData);
}
sampleAppRenderer->initRendering();
}
JNIEXPORT void JNICALL
Java_com_meteor_1studio_holostage_ImageTargetsRenderer_updateRendering(
JNIEnv* env, jobject obj, jint width, jint height)
{
LOG("Java_com_meteor_1studio_holostage_ImageTargetsRenderer_updateRendering");
// Update screen dimensions
screenWidth = width;
screenHeight = height;
// Reconfigure the video background
configureVideoBackground();
}
#ifdef __cplusplus
}
#endif
|
/// @file
/// @author David Pilger <dpilger26@gmail.com>
/// [GitHub Repository](https://github.com/dpilger26/NumCpp)
/// @version 1.2
///
/// @section License
/// Copyright 2019 David Pilger
///
/// 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.
///
/// @section Description
/// Functions for working with NdArrays
///
#pragma once
#include "NumCpp/NdArray.hpp"
namespace nc
{
//============================================================================
// Method Description:
/// Return the truth value of (x1 <= x2) element-wise.
///
/// NumPy Reference: https://www.numpy.org/devdocs/reference/generated/numpy.less_equal.html
///
/// @param inArray1
/// @param inArray2
///
/// @return
/// NdArray
///
template<typename dtype>
NdArray<bool> less_equal(const NdArray<dtype>& inArray1, const NdArray<dtype>& inArray2)
{
return inArray1 <= inArray2;
}
}
|
// Copyright (c) 2009-2010 Satoshi Nakamoto
// Copyright (c) 2009-2012 The Bitcoin developers
// Copyright (c) 2013 The NovaCoin developers
// Distributed under the MIT/X11 software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
#include "txdb.h"
#include "miner.h"
#include "kernel.h"
using namespace std;
//////////////////////////////////////////////////////////////////////////////
//
// BitcoinMiner
//
extern unsigned int nMinerSleep;
int static FormatHashBlocks(void* pbuffer, unsigned int len)
{
unsigned char* pdata = (unsigned char*)pbuffer;
unsigned int blocks = 1 + ((len + 8) / 64);
unsigned char* pend = pdata + 64 * blocks;
memset(pdata + len, 0, 64 * blocks - len);
pdata[len] = 0x80;
unsigned int bits = len * 8;
pend[-1] = (bits >> 0) & 0xff;
pend[-2] = (bits >> 8) & 0xff;
pend[-3] = (bits >> 16) & 0xff;
pend[-4] = (bits >> 24) & 0xff;
return blocks;
}
static const unsigned int pSHA256InitState[8] =
{0x6a09e667, 0xbb67ae85, 0x3c6ef372, 0xa54ff53a, 0x510e527f, 0x9b05688c, 0x1f83d9ab, 0x5be0cd19};
void SHA256Transform(void* pstate, void* pinput, const void* pinit)
{
SHA256_CTX ctx;
unsigned char data[64];
SHA256_Init(&ctx);
for (int i = 0; i < 16; i++)
((uint32_t*)data)[i] = ByteReverse(((uint32_t*)pinput)[i]);
for (int i = 0; i < 8; i++)
ctx.h[i] = ((uint32_t*)pinit)[i];
SHA256_Update(&ctx, data, sizeof(data));
for (int i = 0; i < 8; i++)
((uint32_t*)pstate)[i] = ctx.h[i];
}
// Some explaining would be appreciated
class COrphan
{
public:
CTransaction* ptx;
set<uint256> setDependsOn;
double dPriority;
double dFeePerKb;
COrphan(CTransaction* ptxIn)
{
ptx = ptxIn;
dPriority = dFeePerKb = 0;
}
};
uint64_t nLastBlockTx = 0;
uint64_t nLastBlockSize = 0;
int64_t nLastCoinStakeSearchInterval = 0;
// We want to sort transactions by priority and fee, so:
typedef boost::tuple<double, double, CTransaction*> TxPriority;
class TxPriorityCompare
{
bool byFee;
public:
TxPriorityCompare(bool _byFee) : byFee(_byFee) { }
bool operator()(const TxPriority& a, const TxPriority& b)
{
if (byFee)
{
if (a.get<1>() == b.get<1>())
return a.get<0>() < b.get<0>();
return a.get<1>() < b.get<1>();
}
else
{
if (a.get<0>() == b.get<0>())
return a.get<1>() < b.get<1>();
return a.get<0>() < b.get<0>();
}
}
};
// CreateNewBlock: create new block (without proof-of-work/proof-of-stake)
CBlock* CreateNewBlock(CReserveKey& reservekey, bool fProofOfStake, int64_t* pFees)
{
// Create new block
auto_ptr<CBlock> pblock(new CBlock());
if (!pblock.get())
return NULL;
CBlockIndex* pindexPrev = pindexBest;
int nHeight = pindexPrev->nHeight + 1;
// Create coinbase tx
CTransaction txNew;
txNew.vin.resize(1);
txNew.vin[0].prevout.SetNull();
txNew.vout.resize(1);
if (!fProofOfStake)
{
CPubKey pubkey;
if (!reservekey.GetReservedKey(pubkey))
return NULL;
txNew.vout[0].scriptPubKey.SetDestination(pubkey.GetID());
}
else
{
// Height first in coinbase required for block.version=2
txNew.vin[0].scriptSig = (CScript() << nHeight) + COINBASE_FLAGS;
assert(txNew.vin[0].scriptSig.size() <= 100);
txNew.vout[0].SetEmpty();
}
// Add our coinbase tx as first transaction
pblock->vtx.push_back(txNew);
// Largest block you're willing to create:
unsigned int nBlockMaxSize = GetArg("-blockmaxsize", MAX_BLOCK_SIZE_GEN/2);
// Limit to betweeen 1K and MAX_BLOCK_SIZE-1K for sanity:
nBlockMaxSize = std::max((unsigned int)1000, std::min((unsigned int)(MAX_BLOCK_SIZE-1000), nBlockMaxSize));
// How much of the block should be dedicated to high-priority transactions,
// included regardless of the fees they pay
unsigned int nBlockPrioritySize = GetArg("-blockprioritysize", 27000);
nBlockPrioritySize = std::min(nBlockMaxSize, nBlockPrioritySize);
// Minimum block size you want to create; block will be filled with free transactions
// until there are no more or the block reaches this size:
unsigned int nBlockMinSize = GetArg("-blockminsize", 0);
nBlockMinSize = std::min(nBlockMaxSize, nBlockMinSize);
// Fee-per-kilobyte amount considered the same as "free"
// Be careful setting this: if you set it to zero then
// a transaction spammer can cheaply fill blocks using
// 1-satoshi-fee transactions. It should be set above the real
// cost to you of processing a transaction.
int64_t nMinTxFee = MIN_TX_FEE;
if (mapArgs.count("-mintxfee"))
ParseMoney(mapArgs["-mintxfee"], nMinTxFee);
pblock->nBits = GetNextTargetRequired(pindexPrev, fProofOfStake);
// Collect memory pool transactions into the block
int64_t nFees = 0;
{
LOCK2(cs_main, mempool.cs);
CTxDB txdb("r");
// Priority order to process transactions
list<COrphan> vOrphan; // list memory doesn't move
map<uint256, vector<COrphan*> > mapDependers;
// This vector will be sorted into a priority queue:
vector<TxPriority> vecPriority;
vecPriority.reserve(mempool.mapTx.size());
for (map<uint256, CTransaction>::iterator mi = mempool.mapTx.begin(); mi != mempool.mapTx.end(); ++mi)
{
CTransaction& tx = (*mi).second;
if (tx.IsCoinBase() || tx.IsCoinStake() || !IsFinalTx(tx, nHeight))
continue;
COrphan* porphan = NULL;
double dPriority = 0;
int64_t nTotalIn = 0;
bool fMissingInputs = false;
BOOST_FOREACH(const CTxIn& txin, tx.vin)
{
// Read prev transaction
CTransaction txPrev;
CTxIndex txindex;
if (!txPrev.ReadFromDisk(txdb, txin.prevout, txindex))
{
// This should never happen; all transactions in the memory
// pool should connect to either transactions in the chain
// or other transactions in the memory pool.
if (!mempool.mapTx.count(txin.prevout.hash))
{
LogPrintf("ERROR: mempool transaction missing input\n");
if (fDebug) assert("mempool transaction missing input" == 0);
fMissingInputs = true;
if (porphan)
vOrphan.pop_back();
break;
}
// Has to wait for dependencies
if (!porphan)
{
// Use list for automatic deletion
vOrphan.push_back(COrphan(&tx));
porphan = &vOrphan.back();
}
mapDependers[txin.prevout.hash].push_back(porphan);
porphan->setDependsOn.insert(txin.prevout.hash);
nTotalIn += mempool.mapTx[txin.prevout.hash].vout[txin.prevout.n].nValue;
continue;
}
int64_t nValueIn = txPrev.vout[txin.prevout.n].nValue;
nTotalIn += nValueIn;
int nConf = txindex.GetDepthInMainChain();
dPriority += (double)nValueIn * nConf;
}
if (fMissingInputs) continue;
// Priority is sum(valuein * age) / txsize
unsigned int nTxSize = ::GetSerializeSize(tx, SER_NETWORK, PROTOCOL_VERSION);
dPriority /= nTxSize;
// This is a more accurate fee-per-kilobyte than is used by the client code, because the
// client code rounds up the size to the nearest 1K. That's good, because it gives an
// incentive to create smaller transactions.
double dFeePerKb = double(nTotalIn-tx.GetValueOut()) / (double(nTxSize)/1000.0);
if (porphan)
{
porphan->dPriority = dPriority;
porphan->dFeePerKb = dFeePerKb;
}
else
vecPriority.push_back(TxPriority(dPriority, dFeePerKb, &(*mi).second));
}
// Collect transactions into block
map<uint256, CTxIndex> mapTestPool;
uint64_t nBlockSize = 1000;
uint64_t nBlockTx = 0;
int nBlockSigOps = 100;
bool fSortedByFee = (nBlockPrioritySize <= 0);
TxPriorityCompare comparer(fSortedByFee);
std::make_heap(vecPriority.begin(), vecPriority.end(), comparer);
while (!vecPriority.empty())
{
// Take highest priority transaction off the priority queue:
double dPriority = vecPriority.front().get<0>();
double dFeePerKb = vecPriority.front().get<1>();
CTransaction& tx = *(vecPriority.front().get<2>());
std::pop_heap(vecPriority.begin(), vecPriority.end(), comparer);
vecPriority.pop_back();
// Size limits
unsigned int nTxSize = ::GetSerializeSize(tx, SER_NETWORK, PROTOCOL_VERSION);
if (nBlockSize + nTxSize >= nBlockMaxSize)
continue;
// Legacy limits on sigOps:
unsigned int nTxSigOps = GetLegacySigOpCount(tx);
if (nBlockSigOps + nTxSigOps >= MAX_BLOCK_SIGOPS)
continue;
// Timestamp limit
if (tx.nTime > GetAdjustedTime() || (fProofOfStake && tx.nTime > pblock->vtx[0].nTime))
continue;
// Transaction fee
int64_t nMinFee = GetMinFee(tx, nBlockSize, GMF_BLOCK);
// Skip free transactions if we're past the minimum block size:
if (fSortedByFee && (dFeePerKb < nMinTxFee) && (nBlockSize + nTxSize >= nBlockMinSize))
continue;
// Prioritize by fee once past the priority size or we run out of high-priority
// transactions:
if (!fSortedByFee &&
((nBlockSize + nTxSize >= nBlockPrioritySize) || (dPriority < COIN * 144 / 250)))
{
fSortedByFee = true;
comparer = TxPriorityCompare(fSortedByFee);
std::make_heap(vecPriority.begin(), vecPriority.end(), comparer);
}
// Connecting shouldn't fail due to dependency on other memory pool transactions
// because we're already processing them in order of dependency
map<uint256, CTxIndex> mapTestPoolTmp(mapTestPool);
MapPrevTx mapInputs;
bool fInvalid;
if (!tx.FetchInputs(txdb, mapTestPoolTmp, false, true, mapInputs, fInvalid))
continue;
int64_t nTxFees = tx.GetValueIn(mapInputs)-tx.GetValueOut();
if (nTxFees < nMinFee)
continue;
nTxSigOps += GetP2SHSigOpCount(tx, mapInputs);
if (nBlockSigOps + nTxSigOps >= MAX_BLOCK_SIGOPS)
continue;
// Note that flags: we don't want to set mempool/IsStandard()
// policy here, but we still have to ensure that the block we
// create only contains transactions that are valid in new blocks.
if (!tx.ConnectInputs(txdb, mapInputs, mapTestPoolTmp, CDiskTxPos(1,1,1), pindexPrev, false, true, MANDATORY_SCRIPT_VERIFY_FLAGS))
continue;
mapTestPoolTmp[tx.GetHash()] = CTxIndex(CDiskTxPos(1,1,1), tx.vout.size());
swap(mapTestPool, mapTestPoolTmp);
// Added
pblock->vtx.push_back(tx);
nBlockSize += nTxSize;
++nBlockTx;
nBlockSigOps += nTxSigOps;
nFees += nTxFees;
if (fDebug && GetBoolArg("-printpriority", false))
{
LogPrintf("priority %.1f feeperkb %.1f txid %s\n",
dPriority, dFeePerKb, tx.GetHash().ToString());
}
// Add transactions that depend on this one to the priority queue
uint256 hash = tx.GetHash();
if (mapDependers.count(hash))
{
BOOST_FOREACH(COrphan* porphan, mapDependers[hash])
{
if (!porphan->setDependsOn.empty())
{
porphan->setDependsOn.erase(hash);
if (porphan->setDependsOn.empty())
{
vecPriority.push_back(TxPriority(porphan->dPriority, porphan->dFeePerKb, porphan->ptx));
std::push_heap(vecPriority.begin(), vecPriority.end(), comparer);
}
}
}
}
}
nLastBlockTx = nBlockTx;
nLastBlockSize = nBlockSize;
if (fDebug && GetBoolArg("-printpriority", false))
LogPrintf("CreateNewBlock(): total size %u\n", nBlockSize);
if (!fProofOfStake)
pblock->vtx[0].vout[0].nValue = GetProofOfWorkReward(nHeight, nFees);
if (pFees)
*pFees = nFees;
// Fill in header
pblock->hashPrevBlock = pindexPrev->GetBlockHash();
pblock->nTime = max(pindexPrev->GetPastTimeLimit()+1, pblock->GetMaxTransactionTime());
if (!fProofOfStake)
pblock->UpdateTime(pindexPrev);
pblock->nNonce = 0;
}
return pblock.release();
}
void IncrementExtraNonce(CBlock* pblock, CBlockIndex* pindexPrev, unsigned int& nExtraNonce)
{
// Update nExtraNonce
static uint256 hashPrevBlock;
if (hashPrevBlock != pblock->hashPrevBlock)
{
nExtraNonce = 0;
hashPrevBlock = pblock->hashPrevBlock;
}
++nExtraNonce;
unsigned int nHeight = pindexPrev->nHeight+1; // Height first in coinbase required for block.version=2
pblock->vtx[0].vin[0].scriptSig = (CScript() << nHeight << CBigNum(nExtraNonce)) + COINBASE_FLAGS;
assert(pblock->vtx[0].vin[0].scriptSig.size() <= 100);
pblock->hashMerkleRoot = pblock->BuildMerkleTree();
}
void FormatHashBuffers(CBlock* pblock, char* pmidstate, char* pdata, char* phash1)
{
//
// Pre-build hash buffers
//
struct
{
struct unnamed2
{
int nVersion;
uint256 hashPrevBlock;
uint256 hashMerkleRoot;
unsigned int nTime;
unsigned int nBits;
unsigned int nNonce;
}
block;
unsigned char pchPadding0[64];
uint256 hash1;
unsigned char pchPadding1[64];
}
tmp;
memset(&tmp, 0, sizeof(tmp));
tmp.block.nVersion = pblock->nVersion;
tmp.block.hashPrevBlock = pblock->hashPrevBlock;
tmp.block.hashMerkleRoot = pblock->hashMerkleRoot;
tmp.block.nTime = pblock->nTime;
tmp.block.nBits = pblock->nBits;
tmp.block.nNonce = pblock->nNonce;
FormatHashBlocks(&tmp.block, sizeof(tmp.block));
FormatHashBlocks(&tmp.hash1, sizeof(tmp.hash1));
// Byte swap all the input buffer
for (unsigned int i = 0; i < sizeof(tmp)/4; i++)
((unsigned int*)&tmp)[i] = ByteReverse(((unsigned int*)&tmp)[i]);
// Precalc the first half of the first hash, which stays constant
SHA256Transform(pmidstate, &tmp.block, pSHA256InitState);
memcpy(pdata, &tmp.block, 128);
memcpy(phash1, &tmp.hash1, 64);
}
bool CheckWork(CBlock* pblock, CWallet& wallet, CReserveKey& reservekey)
{
uint256 hashBlock = pblock->GetHash();
uint256 hashProof = pblock->GetPoWHash();
uint256 hashTarget = CBigNum().SetCompact(pblock->nBits).getuint256();
if(!pblock->IsProofOfWork())
return error("CheckWork() : %s is not a proof-of-work block", hashBlock.GetHex());
if (hashProof > hashTarget)
return error("CheckWork() : proof-of-work not meeting target");
//// debug print
LogPrintf("CheckWork() : new proof-of-work block found \n proof hash: %s \ntarget: %s\n", hashProof.GetHex(), hashTarget.GetHex());
LogPrintf("%s\n", pblock->ToString());
LogPrintf("generated %s\n", FormatMoney(pblock->vtx[0].vout[0].nValue));
// Found a solution
{
LOCK(cs_main);
if (pblock->hashPrevBlock != hashBestChain)
return error("CheckWork() : generated block is stale");
// Remove key from key pool
reservekey.KeepKey();
// Track how many getdata requests this block gets
{
LOCK(wallet.cs_wallet);
wallet.mapRequestCount[hashBlock] = 0;
}
// Process this block the same as if we had received it from another node
if (!ProcessBlock(NULL, pblock))
return error("CheckWork() : ProcessBlock, block not accepted");
}
return true;
}
bool CheckStake(CBlock* pblock, CWallet& wallet)
{
uint256 proofHash = 0, hashTarget = 0;
uint256 hashBlock = pblock->GetHash();
if(!pblock->IsProofOfStake())
return error("CheckStake() : %s is not a proof-of-stake block", hashBlock.GetHex());
// verify hash target and signature of coinstake tx
if (!CheckProofOfStake(mapBlockIndex[pblock->hashPrevBlock], pblock->vtx[1], pblock->nBits, proofHash, hashTarget))
return error("CheckStake() : proof-of-stake checking failed");
//// debug print
LogPrintf("CheckStake() : new proof-of-stake block found \n hash: %s \nproofhash: %s \ntarget: %s\n", hashBlock.GetHex(), proofHash.GetHex(), hashTarget.GetHex());
LogPrintf("%s\n", pblock->ToString());
LogPrintf("out %s\n", FormatMoney(pblock->vtx[1].GetValueOut()));
// Found a solution
{
LOCK(cs_main);
if (pblock->hashPrevBlock != hashBestChain)
return error("CheckStake() : generated block is stale");
// Track how many getdata requests this block gets
{
LOCK(wallet.cs_wallet);
wallet.mapRequestCount[hashBlock] = 0;
}
// Process this block the same as if we had received it from another node
if (!ProcessBlock(NULL, pblock))
return error("CheckStake() : ProcessBlock, block not accepted");
}
return true;
}
void ThreadStakeMiner(CWallet *pwallet)
{
SetThreadPriority(THREAD_PRIORITY_LOWEST);
// Make this thread recognisable as the mining thread
RenameThread("yopony-miner");
CReserveKey reservekey(pwallet);
bool fTryToSync = true;
while (true)
{
while (pwallet->IsLocked())
{
nLastCoinStakeSearchInterval = 0;
MilliSleep(1000);
}
while (vNodes.empty() || IsInitialBlockDownload())
{
nLastCoinStakeSearchInterval = 0;
fTryToSync = true;
MilliSleep(1000);
}
if (fTryToSync)
{
fTryToSync = false;
if (vNodes.size() < 3 || pindexBest->GetBlockTime() < GetTime() - 10 * 60)
{
MilliSleep(60000);
continue;
}
}
//
// Create new block
//
int64_t nFees;
auto_ptr<CBlock> pblock(CreateNewBlock(reservekey, true, &nFees));
if (!pblock.get())
return;
// Trying to sign a block
if (pblock->SignBlock(*pwallet, nFees))
{
SetThreadPriority(THREAD_PRIORITY_NORMAL);
CheckStake(pblock.get(), *pwallet);
SetThreadPriority(THREAD_PRIORITY_LOWEST);
MilliSleep(500);
}
else
MilliSleep(nMinerSleep);
}
}
|
#include "Calculator.h"
Calculator::Calculator(Parser& parser) : m_Parser(parser) {}
CalculateResult Calculator::CalculateForX(std::string value, double xCoord)
{
std::vector<std::string> input = m_Parser.Parse(value);
// Convert all X variables to xCoord
for (unsigned int index = 0; index < input.size(); index++)
{
if (input[index] == "X" || input[index] == "x")
{
input[index] = std::to_string(xCoord);
}
}
unsigned int index = 0;
while (index < input.size())
{
std::string token = input[index];
if (m_Parser.IsOperator(token))
{
double lastOperand = 0;
double lastOperand2 = 0;
try
{
lastOperand = std::stod(input[index - 2]);
lastOperand2 = std::stod(input[index - 1]);
}
catch (const std::exception& ex)
{
std::string message = "Specified expression is invalid. " + std::string(ex.what());
return { 0, true, message };
}
double result = 0;
if (token == "+")
{
result = lastOperand + lastOperand2;
}
else if (token == "-")
{
result = lastOperand - lastOperand2;
}
else if (token == "*")
{
result = lastOperand * lastOperand2;
}
else if (token == "/")
{
// todo: handle
if (lastOperand2 == 0)
return { 0, true, "Specified expression is invalid" };
result = lastOperand / lastOperand2;
}
else if (token == "^")
{
result = lastOperand;
for (size_t index = 1; index < lastOperand2; index++)
{
result *= lastOperand;
}
}
input[index] = std::to_string(result); // replace op with result
input.erase(input.begin() + index - 2); // op1
input.erase(input.begin() + index - 2); // op2
index = 0;
}
index++;
}
return { std::stod(input[0]), false, "" };
}
|
#include "Job.h"
#include "Utils.h"
#include <ctime>
#include <cstdlib>
#include <climits>
#include <cmath>
/**
* This file is the cpp file for the Job class.
* @file Job.cpp
* @brief cpp file for Engine-Job
* @author Seonghyeon Park
* @date 2020-03-31
*
*/
/**
* @fn Job::Job()
* @brief the function of basic constructor of Job
* @author Seonghyeon Park
* @date 2020-04-01
* @details
* - None
* @param none
* @return none
* @bug none
* @warning none
* @todo none
*/
Job::Job()
{
}
/**
* @fn Job::Job()
* @brief the function of basic constructor of Job
* @author Seonghyeon Park
* @date 2020-04-01
* @details
* - None
* @param none
* @return none
* @bug none
* @warning none
* @todo none
*/
Job::Job(std::shared_ptr<Task> task, int job_id, int hyper_period_start)
{
this->set_task_id(task->get_task_id());
this->set_task_name(task->get_task_name());
this->set_period(task->get_period());
this->set_deadline(task->get_deadline());
this->set_wcet(task->get_wcet());
this->set_bcet(task->get_bcet());
this->set_offset(task->get_offset());
this->set_is_read(task->get_is_read());
this->set_is_write(task->get_is_write());
this->set_ECU(task->get_ECU());
this->set_producers(task->get_producers());
this->set_consumers(task->get_consumers());
this->set_priority(task->get_priority());
this->set_priority_policy(task->get_priority_policy());
this->set_is_gpu_init(task->get_is_gpu_init());
this->set_is_gpu_sync(task->get_is_gpu_sync());
this->set_gpu_wait_time(task->get_gpu_wait_time());
penalty = task->penalty;
m_job_id = job_id;
m_actual_execution_time = -1;
m_actual_release_time = calculate_release_time(task->get_period(), task->get_offset(), hyper_period_start);
m_actual_deadline = calculate_absolute_deadline(m_actual_release_time, task->get_deadline());
m_actual_start_time = -1;
m_actual_finish_time = -1;
m_simulated_release_time = -1;
m_simulated_start_time = -1;
m_simulated_finish_time = -1;
m_simulated_deadline = -1;
m_simulated_execution_time = -1;
m_is_preemptable = false;
m_is_preempted = false;
m_is_started = false;
m_is_finished = false;
m_is_best_analyzed = false;
m_is_worst_analyzed = false;
m_is_resumed = false;
m_is_running = false;
m_is_released = false;
m_is_simulated = false;
m_est = -1;
m_eft = -1;
m_lst = -1;
m_lft = -1;
m_wpet = -1;
m_bpet = -1;
m_worst_case_busy_period.at(0) = -1;
m_worst_case_busy_period.at(1) = -1;
}
/**
* @fn Job::~Job()
* @brief the function of basic destroyer of Job
* @author Seonghyeon Park
* @date 2020-04-01
* @details
* - None
* @param none
* @return none
* @bug none
* @warning none
* @todo none
*/
Job::~Job()
{
}
long long Job::get_last_elapsed_nano_sec()
{
return std::chrono::duration_cast<std::chrono::nanoseconds>(m_run_end - m_run_start).count();
}
long long Job::get_last_elapsed_micro_sec()
{
return std::chrono::duration_cast<std::chrono::microseconds>(m_run_end - m_run_start).count();
}
long long Job::get_last_elapsed_milli_sec()
{
return std::chrono::duration_cast<std::chrono::milliseconds>(m_run_end - m_run_start).count();
}
long long Job::get_last_elapsed_seconds()
{
return std::chrono::duration_cast<std::chrono::seconds>(m_run_end - m_run_start).count();
}
bool Job::get_is_started()
{
return m_is_started;
}
bool Job::get_is_finished()
{
return m_is_finished;
}
bool Job::get_is_preempted()
{
return m_is_preempted;
}
bool Job::get_is_resumed()
{
return m_is_resumed;
}
bool Job::get_is_released()
{
return m_is_released;
}
bool Job::get_is_running()
{
return m_is_running;
}
bool Job::get_is_simulated()
{
return m_is_simulated;
}
bool Job::get_is_best_analyzed()
{
return m_is_best_analyzed;
}
bool Job::get_is_worst_analyzed()
{
return m_is_worst_analyzed;
}
bool Job::operator<(const Job& other_job)
{
return this->m_actual_deadline < other_job.m_actual_deadline;
}
bool Job::operator>(const Job& other_job)
{
return this->m_actual_deadline > other_job.m_actual_deadline;
}
int Job::get_job_id()
{
return m_job_id;
}
int Job::get_actual_release_time()
{
return m_actual_release_time;
}
int Job::get_actual_deadline()
{
return m_actual_deadline;
}
int Job::get_actual_start_time()
{
return m_actual_start_time;
}
int Job::get_actual_finish_time()
{
return m_actual_finish_time;
}
int Job::get_actual_execution_time()
{
return m_actual_execution_time;
}
int Job::get_est()
{
return m_est;
}
int Job::get_lst()
{
return m_lst;
}
int Job::get_eft()
{
return m_eft;
}
int Job::get_lft()
{
return m_lft;
}
int Job::get_bpet()
{
return m_bpet;
}
int Job::get_wpet()
{
return m_wpet;
}
double Job::get_simulated_release_time()
{
return std::floor(m_simulated_release_time*10)/10;
}
double Job::get_simulated_deadline()
{
return std::floor(m_simulated_deadline*10)/10;
}
double Job::get_simulated_start_time()
{
return std::floor(m_simulated_start_time*10)/10;
}
double Job::get_simulated_finish_time()
{
return std::floor(m_simulated_finish_time*10)/10;
}
double Job::get_simulated_execution_time()
{
return std::floor(m_simulated_execution_time*10)/10;
}
std::array<int, 2>& Job::get_wcbp()
{
return m_worst_case_busy_period;
}
std::array<int, 6> Job::get_data_read_buffer()
{
return m_data_read_buffer;
}
std::shared_ptr<Job> Job::get_producer_job()
{
return m_producer_job;
}
std::vector<std::shared_ptr<Job>>& Job::get_job_set_start_det()
{
return m_job_set_start_det;
}
std::vector<std::shared_ptr<Job>>& Job::get_job_set_start_non_det()
{
return m_job_set_start_non_det;
}
std::vector<std::shared_ptr<Job>>& Job::get_job_set_finish_det()
{
return m_job_set_finish_det;
}
std::vector<std::shared_ptr<Job>>& Job::get_job_set_finish_non_det()
{
return m_job_set_finish_non_det;
}
std::vector<std::shared_ptr<Job>>& Job::get_job_set_pro_con_det()
{
return m_job_set_pro_con_det;
}
std::vector<std::shared_ptr<Job>>& Job::get_job_set_pro_con_non_det()
{
return m_job_set_pro_con_non_det;
}
std::vector<std::shared_ptr<Job>>& Job::get_det_prdecessors()
{
return m_det_predecessors;
}
std::vector<std::shared_ptr<Job>>& Job::get_det_successors()
{
return m_det_successors;
}
std::vector<std::shared_ptr<Job>>& Job::get_non_det_prdecessors()
{
return m_non_det_predecessors;
}
std::vector<std::shared_ptr<Job>>& Job::get_non_det_successors()
{
return m_non_det_successors;
}
void Job::set_is_started(bool is_started)
{
m_is_started = is_started;
}
void Job::set_is_finished(bool is_finished)
{
m_is_finished = is_finished;
}
void Job::set_is_preempted(bool is_preempted)
{
m_is_preempted = is_preempted;
}
void Job::set_is_resumed(bool is_resumed)
{
m_is_resumed = is_resumed;
}
void Job::set_is_released(bool is_released)
{
m_is_released = is_released;
}
void Job::set_is_running(bool is_running)
{
m_is_running = is_running;
}
void Job::set_is_simulated(bool is_simulated)
{
m_is_simulated = is_simulated;
}
void Job::set_is_best_analyzed(bool is_best_analyzed)
{
m_is_best_analyzed = is_best_analyzed;
}
void Job::set_is_worst_analyzed(bool is_worst_analyzed)
{
m_is_worst_analyzed = is_worst_analyzed;
}
void Job::set_est(int est)
{
m_est = est;
}
void Job::set_lst(int lst)
{
m_lst = lst;
}
void Job::set_eft(int eft)
{
m_eft = eft;
}
void Job::set_lft(int lft)
{
m_lft = lft;
}
void Job::set_bpet(int bpet)
{
m_bpet = bpet;
}
void Job::set_wpet(int wpet)
{
m_wpet = wpet;
}
void Job::set_actual_release_time(int release_time)
{
m_actual_release_time = release_time;
}
void Job::set_actual_deadline(int a_deadline)
{
m_actual_deadline = a_deadline;
}
void Job::set_actual_start_time(int actual_start_time)
{
m_actual_start_time = actual_start_time;
}
void Job::set_actual_finish_time(int actual_finish_time)
{
m_actual_finish_time = actual_finish_time;
}
void Job::set_actual_execution_time(int original_execution_time)
{
m_actual_execution_time = original_execution_time;
}
void Job::set_simulated_release_time(double simulated_release_time)
{
m_simulated_release_time = std::floor(simulated_release_time*10)/10;
}
void Job::set_simulated_deadline(double simulated_deadline)
{
m_simulated_deadline = std::floor(simulated_deadline*10)/10;
}
void Job::set_simulated_start_time(double simulated_start_time)
{
m_simulated_start_time = std::floor(simulated_start_time*10)/10;
}
void Job::set_simulated_finish_time(double simulated_finish_time)
{
m_simulated_finish_time = std::floor(simulated_finish_time*10)/10;
}
void Job::set_simulated_execution_time(double simulated_execution_time)
{
m_simulated_execution_time = std::floor(simulated_execution_time*10)/10;
}
void Job::set_wcbp(std::array<int, 2>& wcbp)
{
m_worst_case_busy_period = wcbp;
}
void Job::set_data_read_buffer(std::array<int, 6> data_read_buffer)
{
m_data_read_buffer = data_read_buffer;
}
void Job::set_producer_job(std::shared_ptr<Job> job)
{
m_producer_job = job;
}
void Job::set_job_set_start_det(std::vector<std::shared_ptr<Job>>& job_set_start_det)
{
m_job_set_start_det = job_set_start_det;
}
void Job::set_job_set_start_non_det(std::vector<std::shared_ptr<Job>>& job_set_start_non_det)
{
m_job_set_start_non_det = job_set_start_non_det;
}
void Job::set_job_set_finish_det(std::vector<std::shared_ptr<Job>>& job_set_finish_det)
{
m_job_set_finish_det = job_set_finish_det;
}
void Job::set_job_set_finish_non_det(std::vector<std::shared_ptr<Job>>& job_set_finish_non_det)
{
m_job_set_finish_non_det = job_set_finish_non_det;
}
void Job::set_job_set_pro_con_det(std::vector<std::shared_ptr<Job>>& job_set_pro_con_det)
{
m_job_set_pro_con_det = job_set_pro_con_det;
}
void Job::set_job_set_pro_con_non_det(std::vector<std::shared_ptr<Job>>& job_set_pro_con_non_det)
{
m_job_set_pro_con_non_det = job_set_pro_con_non_det;
}
void Job::set_det_predecessors(std::vector<std::shared_ptr<Job>>& predecessors)
{
m_det_predecessors = predecessors;
}
void Job::set_det_successors(std::vector<std::shared_ptr<Job>>& successors)
{
m_det_successors = successors;
}
void Job::set_non_det_predecessors(std::vector<std::shared_ptr<Job>>& predecessors)
{
m_non_det_predecessors = predecessors;
}
void Job::set_non_det_successors(std::vector<std::shared_ptr<Job>>& successors)
{
m_non_det_successors = successors;
}
int Job::calculate_release_time(int period, int offset, int hyper_period_start)
{
/**
* n-th Job release time can be calculated with [ period * (n-1) + task offset ]
*/
return (period * (m_job_id - 1)) + offset + hyper_period_start;
}
int Job::calculate_absolute_deadline(int release_time, int r_deadline)
{
return release_time + r_deadline;
}
void Job::initialize_simulated_deadline()
{
if(this->get_is_write())
{
m_simulated_deadline = static_cast<double>(m_eft);
if(m_simulated_deadline == 0)
{
//std::cout << "WE GOT A ZERO VALUE DEADLINE INSIDE THE INITIALIZE SIMULATED DEADLINE FUNCTION!" << std::endl;
}
}
else
{
m_simulated_deadline = INT_MAX;
}
}
void Job::update_simulated_deadline()
{
if(m_is_simulated == false || m_is_released == false)
{
if(this->get_is_write())
{
m_simulated_deadline = static_cast<double>(m_eft);
if(m_simulated_deadline == 0)
{
//std::cout << "WE GOT A ZERO VALUE DEADLINE INSIDE THE UPDATE SIMULATED DEADLINE FUNCTION!" << std::endl;
}
else
{
//std::cout << "WE GOT A NON ZERO VALUE INSIDE THE UPDATE SIMULATED DEADLINE FUNCTION!" << std::endl;
}
}
else
{
m_simulated_deadline = min_simulated_deadline_det_successor();
}
}
}
double Job::min_simulated_deadline_det_successor()
{
double min_value = INT_MAX;
if(!m_det_successors.empty())
{
std::shared_ptr<Job> min_succ = m_det_successors.front();
for(auto succ : m_det_successors)
{
if(succ->get_simulated_deadline() < min_value)
{
min_value = succ->get_simulated_deadline();
min_succ = succ;
}
}
add_history(min_succ);
return min_value;
}
else
{
if(min_value == INT_MAX)
return min_value;
}
std::cout << "FATAL ERROR" << std::endl;
std::cin >> min_value;
}
std::vector<std::shared_ptr<Job>> Job::get_history()
{
return m_history_of_sim_deadline;
}
void Job::add_history(std::shared_ptr<Job> new_deadline)
{
m_history_of_sim_deadline.push_back(new_deadline);
}
void Job::run_function()
{
m_run_start = std::chrono::steady_clock::now();
if((get_is_read() == true) && (get_is_write() == true))
{
if(!global_object::tagged_data_read.empty())
{
std::shared_ptr<TaggedData> current_data = global_object::tagged_data_read.at(global_object::tagged_data_read.size()-1);
global_object::logger -> _2019_18675_task_read_write_logger(this->get_task_name(), global_object::logger->_2019_18675_log_prepare_Tagged_Data(current_data));
global_object::tagged_data_read.clear();
}
run();
std::shared_ptr<DelayedData> delayed_data = std::make_shared<DelayedData>();
delayed_data->data_time = m_actual_finish_time;
delayed_data->data_write4 = shared::rtY.write4;
delayed_data->data_write3 = shared::rtY.write3;
delayed_data->data_write2 = shared::CC_Send_BRAKE;
delayed_data->data_write1 = shared::CC_Send_ACCEL;
global_object::logger -> _2019_18675_task_read_write_logger(this->get_task_name(), global_object::logger->_2019_18675_log_prepare_Delayed_Data(delayed_data));
}
else if((get_is_read() == true) && (get_is_write() == false))
{
if(!global_object::tagged_data_read.empty())
{
std::shared_ptr<TaggedData> current_data = global_object::tagged_data_read.at(global_object::tagged_data_read.size()-1);
global_object::logger -> _2019_18675_task_read_write_logger(this->get_task_name(), global_object::logger->_2019_18675_log_prepare_Tagged_Data(current_data));
global_object::tagged_data_read.clear();
}
run();
}
else if((get_is_read() == false) && (get_is_write() == true))
{
run();
#ifdef CANMODE__
CAN_message msg;
msg.transmit_can_message(m_task_name);
#endif
#ifdef ETHERNET_MODE__
std::shared_ptr<DelayedData> delayed_data = std::make_shared<DelayedData>();
delayed_data->data_time = m_actual_finish_time;
delayed_data->data_write4 = shared::rtY.write4;
delayed_data->data_write3 = shared::rtY.write3;
delayed_data->data_write2 = shared::CC_Send_BRAKE;
delayed_data->data_write1 = shared::CC_Send_ACCEL;
global_object::logger -> _2019_18675_task_read_write_logger(this->get_task_name(), global_object::logger->_2019_18675_log_prepare_Delayed_Data(delayed_data));
#endif
}
m_run_end = std::chrono::steady_clock::now();
}
|
/**
* @file simpleclient.cpp
* @date 03.01.2013
* @author Peter Spiess-Knafl <peter.knafl@gmail.com>
* @brief This is a simple client example.
*/
#include <jsonrpccpp/client.h>
#include <jsonrpccpp/client/connectors/httpclient.h>
#include <iostream>
using namespace jsonrpc;
using namespace std;
int main()
{
HttpClient client("http://localhost:8383");
Client c(client);
Json::Value params;
params["name"] = "Peter";
try
{
cout << c.CallMethod("sayHello", params) << endl;
}
catch (JsonRpcException& e)
{
cerr << e.what() << endl;
}
}
|
// Copyright (c) 2011-2014 The Bitcoin developers
// Copyright (c) 2014-2015 The Dash developers
// Copyright (c) 2020-2021 The Altecoin developers
// Distributed under the MIT software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
#include "transactionrecord.h"
#include "base58.h"
#include "obfuscation.h"
#include "swifttx.h"
#include "timedata.h"
#include "wallet/wallet.h"
#include "zpivchain.h"
#include "main.h"
#include <algorithm>
#include <stdint.h>
/*
* Decompose CWallet transaction to model transaction records.
*/
QList<TransactionRecord> TransactionRecord::decomposeTransaction(const CWallet* wallet, const CWalletTx& wtx)
{
QList<TransactionRecord> parts;
int64_t nTime = wtx.GetComputedTxTime();
CAmount nCredit = wtx.GetCredit(ISMINE_ALL);
CAmount nDebit = wtx.GetDebit(ISMINE_ALL);
CAmount nNet = nCredit - nDebit;
uint256 hash = wtx.GetHash();
std::map<std::string, std::string> mapValue = wtx.mapValue;
bool fZSpendFromMe = false;
if (wtx.HasZerocoinSpendInputs()) {
libzerocoin::CoinSpend zcspend = wtx.HasZerocoinPublicSpendInputs() ? ZALTCModule::parseCoinSpend(wtx.vin[0]) : TxInToZerocoinSpend(wtx.vin[0]);
fZSpendFromMe = wallet->IsMyZerocoinSpend(zcspend.getCoinSerialNumber());
}
if (wtx.IsCoinStake()) {
TransactionRecord sub(hash, nTime, wtx.GetTotalSize());
CTxDestination address;
if (!wtx.HasZerocoinSpendInputs() && !ExtractDestination(wtx.vout[1].scriptPubKey, address))
return parts;
if (wtx.HasZerocoinSpendInputs() && (fZSpendFromMe || wallet->zpivTracker->HasMintTx(hash))) {
//zALTC stake reward
sub.involvesWatchAddress = false;
sub.type = TransactionRecord::StakeZALTC;
sub.address = mapValue["zerocoinmint"];
sub.credit = 0;
for (const CTxOut& out : wtx.vout) {
if (out.IsZerocoinMint())
sub.credit += out.nValue;
}
sub.debit -= wtx.vin[0].nSequence * COIN;
} else if (isminetype mine = wallet->IsMine(wtx.vout[1])) {
// Check for cold stakes.
if (wtx.HasP2CSOutputs()) {
sub.credit = nCredit;
sub.debit = -nDebit;
loadHotOrColdStakeOrContract(wallet, wtx, sub);
parts.append(sub);
return parts;
} else {
// ALTC stake reward
sub.involvesWatchAddress = mine & ISMINE_WATCH_ONLY;
sub.type = TransactionRecord::StakeMint;
sub.address = CBitcoinAddress(address).ToString();
sub.credit = nNet;
}
} else {
//Masternode reward
CTxDestination destMN;
int nIndexMN = wtx.vout.size() - 1;
if (ExtractDestination(wtx.vout[nIndexMN].scriptPubKey, destMN) && IsMine(*wallet, destMN)) {
isminetype mine = wallet->IsMine(wtx.vout[nIndexMN]);
sub.involvesWatchAddress = mine & ISMINE_WATCH_ONLY;
sub.type = TransactionRecord::MNReward;
sub.address = CBitcoinAddress(destMN).ToString();
sub.credit = wtx.vout[nIndexMN].nValue;
}
}
parts.append(sub);
} else if (wtx.HasZerocoinSpendInputs()) {
//zerocoin spend outputs
bool fFeeAssigned = false;
for (const CTxOut& txout : wtx.vout) {
// change that was reminted as zerocoins
if (txout.IsZerocoinMint()) {
// do not display record if this isn't from our wallet
if (!fZSpendFromMe)
continue;
isminetype mine = wallet->IsMine(txout);
TransactionRecord sub(hash, nTime, wtx.GetTotalSize());
sub.involvesWatchAddress = mine & ISMINE_WATCH_ONLY;
sub.type = TransactionRecord::ZerocoinSpend_Change_zPiv;
sub.address = mapValue["zerocoinmint"];
if (!fFeeAssigned) {
sub.debit -= (wtx.GetZerocoinSpent() - wtx.GetValueOut());
fFeeAssigned = true;
}
sub.idx = parts.size();
parts.append(sub);
continue;
}
std::string strAddress = "";
CTxDestination address;
if (ExtractDestination(txout.scriptPubKey, address))
strAddress = CBitcoinAddress(address).ToString();
// a zerocoinspend that was sent to an address held by this wallet
isminetype mine = wallet->IsMine(txout);
if (mine) {
TransactionRecord sub(hash, nTime, wtx.GetTotalSize());
sub.involvesWatchAddress = mine & ISMINE_WATCH_ONLY;
if (fZSpendFromMe) {
sub.type = TransactionRecord::ZerocoinSpend_FromMe;
} else {
sub.type = TransactionRecord::RecvFromZerocoinSpend;
sub.credit = txout.nValue;
}
sub.address = mapValue["recvzerocoinspend"];
if (strAddress != "")
sub.address = strAddress;
sub.idx = parts.size();
parts.append(sub);
continue;
}
// spend is not from us, so do not display the spend side of the record
if (!fZSpendFromMe)
continue;
// zerocoin spend that was sent to someone else
TransactionRecord sub(hash, nTime, wtx.GetTotalSize());
sub.involvesWatchAddress = mine & ISMINE_WATCH_ONLY;
sub.debit = -txout.nValue;
sub.type = TransactionRecord::ZerocoinSpend;
sub.address = mapValue["zerocoinspend"];
if (strAddress != "")
sub.address = strAddress;
sub.idx = parts.size();
parts.append(sub);
}
} else if (wtx.HasP2CSOutputs()) {
// Delegate tx.
TransactionRecord sub(hash, nTime, wtx.GetTotalSize());
sub.credit = nCredit;
sub.debit = -nDebit;
loadHotOrColdStakeOrContract(wallet, wtx, sub, true);
parts.append(sub);
return parts;
} else if (wtx.HasP2CSInputs()) {
// Delegation unlocked
TransactionRecord sub(hash, nTime, wtx.GetTotalSize());
loadUnlockColdStake(wallet, wtx, sub);
parts.append(sub);
return parts;
} else if (nNet > 0 || wtx.IsCoinBase()) {
//
// Credit
//
for (const CTxOut& txout : wtx.vout) {
isminetype mine = wallet->IsMine(txout);
if (mine) {
TransactionRecord sub(hash, nTime, wtx.GetTotalSize());
CTxDestination address;
sub.idx = parts.size(); // sequence number
sub.credit = txout.nValue;
sub.involvesWatchAddress = mine & ISMINE_WATCH_ONLY;
if (ExtractDestination(txout.scriptPubKey, address) && IsMine(*wallet, address)) {
// Received by Altecoin Address
sub.type = TransactionRecord::RecvWithAddress;
sub.address = CBitcoinAddress(address).ToString();
} else {
// Received by IP connection (deprecated features), or a multisignature or other non-simple transaction
sub.type = TransactionRecord::RecvFromOther;
sub.address = mapValue["from"];
}
if (wtx.IsCoinBase()) {
// Generated
sub.type = TransactionRecord::Generated;
}
parts.append(sub);
}
}
} else {
bool fAllFromMeDenom = true;
int nFromMe = 0;
bool involvesWatchAddress = false;
isminetype fAllFromMe = ISMINE_SPENDABLE;
for (const CTxIn& txin : wtx.vin) {
if (wallet->IsMine(txin)) {
fAllFromMeDenom = fAllFromMeDenom && wallet->IsDenominated(txin);
nFromMe++;
}
isminetype mine = wallet->IsMine(txin);
if (mine & ISMINE_WATCH_ONLY) involvesWatchAddress = true;
if (fAllFromMe > mine) fAllFromMe = mine;
}
isminetype fAllToMe = ISMINE_SPENDABLE;
bool fAllToMeDenom = true;
int nToMe = 0;
for (const CTxOut& txout : wtx.vout) {
if (wallet->IsMine(txout)) {
fAllToMeDenom = fAllToMeDenom && wallet->IsDenominatedAmount(txout.nValue);
nToMe++;
}
isminetype mine = wallet->IsMine(txout);
if (mine & ISMINE_WATCH_ONLY) involvesWatchAddress = true;
if (fAllToMe > mine) fAllToMe = mine;
}
if (fAllFromMeDenom && fAllToMeDenom && ((nFromMe * nToMe) != 0)) {
parts.append(TransactionRecord(hash, nTime, wtx.GetTotalSize(), TransactionRecord::ObfuscationDenominate, "", -nDebit, nCredit));
parts.last().involvesWatchAddress = false; // maybe pass to TransactionRecord as constructor argument
} else if (fAllFromMe && fAllToMe) {
// Payment to self
// TODO: this section still not accurate but covers most cases,
// might need some additional work however
TransactionRecord sub(hash, nTime, wtx.GetTotalSize());
// Payment to self by default
sub.type = TransactionRecord::SendToSelf;
sub.address = "";
if (mapValue["DS"] == "1") {
sub.type = TransactionRecord::Obfuscated;
CTxDestination address;
if (ExtractDestination(wtx.vout[0].scriptPubKey, address)) {
// Sent to Altecoin Address
sub.address = CBitcoinAddress(address).ToString();
} else {
// Sent to IP, or other non-address transaction like OP_EVAL
sub.address = mapValue["to"];
}
} else {
for (unsigned int nOut = 0; nOut < wtx.vout.size(); nOut++) {
const CTxOut& txout = wtx.vout[nOut];
sub.idx = parts.size();
if (wallet->IsCollateralAmount(txout.nValue)) sub.type = TransactionRecord::ObfuscationMakeCollaterals;
if (wallet->IsDenominatedAmount(txout.nValue)) sub.type = TransactionRecord::ObfuscationCreateDenominations;
if (nDebit - wtx.GetValueOut() == OBFUSCATION_COLLATERAL) sub.type = TransactionRecord::ObfuscationCollateralPayment;
}
// Label for payment to self
CTxDestination address;
if (ExtractDestination(wtx.vout[0].scriptPubKey, address)) {
sub.address = CBitcoinAddress(address).ToString();
}
}
CAmount nChange = wtx.GetChange();
sub.debit = -(nDebit - nChange);
sub.credit = nCredit - nChange;
parts.append(sub);
parts.last().involvesWatchAddress = involvesWatchAddress; // maybe pass to TransactionRecord as constructor argument
} else if (fAllFromMe || wtx.HasZerocoinMintOutputs()) {
//
// Debit
//
CAmount nTxFee = nDebit - wtx.GetValueOut();
for (unsigned int nOut = 0; nOut < wtx.vout.size(); nOut++) {
const CTxOut& txout = wtx.vout[nOut];
TransactionRecord sub(hash, nTime, wtx.GetTotalSize());
sub.idx = parts.size();
sub.involvesWatchAddress = involvesWatchAddress;
if (wallet->IsMine(txout)) {
// Ignore parts sent to self, as this is usually the change
// from a transaction sent back to our own address.
continue;
}
CTxDestination address;
if (ExtractDestination(txout.scriptPubKey, address)) {
//This is most likely only going to happen when resyncing deterministic wallet without the knowledge of the
//private keys that the change was sent to. Do not display a "sent to" here.
if (wtx.HasZerocoinMintOutputs())
continue;
// Sent to Altecoin Address
sub.type = TransactionRecord::SendToAddress;
sub.address = CBitcoinAddress(address).ToString();
} else if (txout.IsZerocoinMint()){
sub.type = TransactionRecord::ZerocoinMint;
sub.address = mapValue["zerocoinmint"];
sub.credit += txout.nValue;
} else {
// Sent to IP, or other non-address transaction like OP_EVAL
sub.type = TransactionRecord::SendToOther;
sub.address = mapValue["to"];
}
if (mapValue["DS"] == "1") {
sub.type = TransactionRecord::Obfuscated;
}
CAmount nValue = txout.nValue;
/* Add fee to first output */
if (nTxFee > 0) {
nValue += nTxFee;
nTxFee = 0;
}
sub.debit = -nValue;
parts.append(sub);
}
} else {
//
// Mixed debit transaction, can't break down payees
//
parts.append(TransactionRecord(hash, nTime, wtx.GetTotalSize(), TransactionRecord::Other, "", nNet, 0));
parts.last().involvesWatchAddress = involvesWatchAddress;
}
}
return parts;
}
void TransactionRecord::loadUnlockColdStake(const CWallet* wallet, const CWalletTx& wtx, TransactionRecord& record)
{
record.involvesWatchAddress = false;
// Get the p2cs
const CScript* p2csScript = nullptr;
bool isSpendable = false;
for (const auto &input : wtx.vin) {
const CWalletTx* tx = wallet->GetWalletTx(input.prevout.hash);
if (tx && tx->vout[input.prevout.n].scriptPubKey.IsPayToColdStaking()) {
p2csScript = &tx->vout[input.prevout.n].scriptPubKey;
isSpendable = wallet->IsMine(input) & ISMINE_SPENDABLE_ALL;
break;
}
}
if (isSpendable) {
// owner unlocked the cold stake
record.type = TransactionRecord::P2CSUnlockOwner;
record.debit = -(wtx.GetStakeDelegationDebit());
record.credit = wtx.GetCredit(ISMINE_ALL);
} else {
// hot node watching the unlock
record.type = TransactionRecord::P2CSUnlockStaker;
record.debit = -(wtx.GetColdStakingDebit());
record.credit = -(wtx.GetColdStakingCredit());
}
// Extract and set the owner address
ExtractAddress(*p2csScript, false, record.address);
}
void TransactionRecord::loadHotOrColdStakeOrContract(
const CWallet* wallet,
const CWalletTx& wtx,
TransactionRecord& record,
bool isContract)
{
record.involvesWatchAddress = false;
// Get the p2cs
CTxOut p2csUtxo;
for (unsigned int nOut = 0; nOut < wtx.vout.size(); nOut++) {
const CTxOut &txout = wtx.vout[nOut];
if (txout.scriptPubKey.IsPayToColdStaking()) {
p2csUtxo = txout;
break;
}
}
bool isSpendable = (wallet->IsMine(p2csUtxo) & ISMINE_SPENDABLE_DELEGATED);
bool isFromMe = wallet->IsFromMe(wtx);
if (isContract) {
if (isSpendable && isFromMe) {
// Wallet delegating balance
record.type = TransactionRecord::P2CSDelegationSentOwner;
} else if (isFromMe){
// Wallet delegating balance and transfering ownership
record.type = TransactionRecord::P2CSDelegationSent;
} else {
// Wallet receiving a delegation
record.type = TransactionRecord::P2CSDelegation;
}
} else {
// Stake
if (isSpendable) {
// Offline wallet receiving an stake due a delegation
record.type = TransactionRecord::StakeDelegated;
record.credit = wtx.GetCredit(ISMINE_SPENDABLE_DELEGATED);
record.debit = -(wtx.GetDebit(ISMINE_SPENDABLE_DELEGATED));
} else {
// Online wallet receiving an stake due a received utxo delegation that won a block.
record.type = TransactionRecord::StakeHot;
}
}
// Extract and set the owner address
ExtractAddress(p2csUtxo.scriptPubKey, false, record.address);
}
bool TransactionRecord::ExtractAddress(const CScript& scriptPubKey, bool fColdStake, std::string& addressStr) {
CTxDestination address;
if (!ExtractDestination(scriptPubKey, address, fColdStake)) {
// this shouldn't happen..
addressStr = "No available address";
return false;
} else {
addressStr = CBitcoinAddress(
address,
(fColdStake ? CChainParams::STAKING_ADDRESS : CChainParams::PUBKEY_ADDRESS)
).ToString();
return true;
}
}
bool IsZALTCType(TransactionRecord::Type type)
{
switch (type) {
case TransactionRecord::StakeZALTC:
case TransactionRecord::ZerocoinMint:
case TransactionRecord::ZerocoinSpend:
case TransactionRecord::RecvFromZerocoinSpend:
case TransactionRecord::ZerocoinSpend_Change_zPiv:
case TransactionRecord::ZerocoinSpend_FromMe:
return true;
default:
return false;
}
}
void TransactionRecord::updateStatus(const CWalletTx& wtx)
{
AssertLockHeld(cs_main);
int chainHeight = chainActive.Height();
CBlockIndex *pindex = nullptr;
// Find the block the tx is in
BlockMap::iterator mi = mapBlockIndex.find(wtx.hashBlock);
if (mi != mapBlockIndex.end())
pindex = (*mi).second;
// Determine transaction status
// Sort order, unrecorded transactions sort to the top
status.sortKey = strprintf("%010d-%01d-%010u-%03d",
(pindex ? pindex->nHeight : std::numeric_limits<int>::max()),
(wtx.IsCoinBase() ? 1 : 0),
wtx.nTimeReceived,
idx);
bool fConflicted = false;
int depth = 0;
bool isTrusted = wtx.IsTrusted(depth, fConflicted);
const bool isOffline = (GetAdjustedTime() - wtx.nTimeReceived > 2 * 60 && wtx.GetRequestCount() == 0);
int nBlocksToMaturity = (wtx.IsCoinBase() || wtx.IsCoinStake()) ? std::max(0, (Params().COINBASE_MATURITY() + 1) - depth) : 0;
status.countsForBalance = isTrusted && !(nBlocksToMaturity > 0);
status.cur_num_blocks = chainHeight;
status.depth = depth;
status.cur_num_ix_locks = nCompleteTXLocks;
if (!IsFinalTx(wtx, chainHeight + 1)) {
if (wtx.nLockTime < LOCKTIME_THRESHOLD) {
status.status = TransactionStatus::OpenUntilBlock;
status.open_for = wtx.nLockTime - chainHeight;
} else {
status.status = TransactionStatus::OpenUntilDate;
status.open_for = wtx.nLockTime;
}
}
// For generated transactions, determine maturity
else if (type == TransactionRecord::Generated ||
type == TransactionRecord::StakeMint ||
type == TransactionRecord::StakeZALTC ||
type == TransactionRecord::MNReward ||
type == TransactionRecord::StakeDelegated ||
type == TransactionRecord::StakeHot) {
if (nBlocksToMaturity > 0) {
status.status = TransactionStatus::Immature;
status.matures_in = nBlocksToMaturity;
if (status.depth >= 0 && !fConflicted) {
// Check if the block was requested by anyone
if (isOffline)
status.status = TransactionStatus::MaturesWarning;
} else {
status.status = TransactionStatus::NotAccepted;
}
} else {
status.status = TransactionStatus::Confirmed;
status.matures_in = 0;
}
} else {
if (status.depth < 0 || fConflicted) {
status.status = TransactionStatus::Conflicted;
} else if (isOffline) {
status.status = TransactionStatus::Offline;
} else if (status.depth == 0) {
status.status = TransactionStatus::Unconfirmed;
} else if (status.depth < RecommendedNumConfirmations) {
status.status = TransactionStatus::Confirming;
} else {
status.status = TransactionStatus::Confirmed;
}
}
}
bool TransactionRecord::statusUpdateNeeded()
{
AssertLockHeld(cs_main);
return status.cur_num_blocks != chainActive.Height() || status.cur_num_ix_locks != nCompleteTXLocks;
}
QString TransactionRecord::getTxID() const
{
return QString::fromStdString(hash.ToString());
}
int TransactionRecord::getOutputIndex() const
{
return idx;
}
bool TransactionRecord::isCoinStake() const
{
return (type == TransactionRecord::StakeMint || type == TransactionRecord::Generated || type == TransactionRecord::StakeZALTC);
}
bool TransactionRecord::isAnyColdStakingType() const
{
return (type == TransactionRecord::P2CSDelegation || type == TransactionRecord::P2CSDelegationSent
|| type == TransactionRecord::P2CSDelegationSentOwner
|| type == TransactionRecord::StakeDelegated || type == TransactionRecord::StakeHot
|| type == TransactionRecord::P2CSUnlockOwner || type == TransactionRecord::P2CSUnlockStaker);
}
bool TransactionRecord::isNull() const
{
return hash.IsNull() || size == 0;
}
std::string TransactionRecord::statusToString(){
switch (status.status){
case TransactionStatus::MaturesWarning:
return "Abandoned (not mature because no nodes have confirmed)";
case TransactionStatus::Confirmed:
return "Confirmed";
case TransactionStatus::OpenUntilDate:
return "OpenUntilDate";
case TransactionStatus::OpenUntilBlock:
return "OpenUntilBlock";
case TransactionStatus::Unconfirmed:
return "Unconfirmed";
case TransactionStatus::Confirming:
return "Confirming";
case TransactionStatus::Conflicted:
return "Conflicted";
case TransactionStatus::Immature:
return "Immature";
case TransactionStatus::NotAccepted:
return "Not Accepted";
default:
return "No status";
}
}
|
/*
* Copyright (C) 2017 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#define LOG_TAG "incident_helper"
#include "parsers/BatteryTypeParser.h"
#include "parsers/CpuFreqParser.h"
#include "parsers/CpuInfoParser.h"
#include "parsers/EventLogTagsParser.h"
#include "parsers/KernelWakesParser.h"
#include "parsers/PageTypeInfoParser.h"
#include "parsers/ProcrankParser.h"
#include "parsers/PsParser.h"
#include "parsers/SystemPropertiesParser.h"
#include <android-base/file.h>
#include <getopt.h>
#include <stdlib.h>
#include <unistd.h>
using namespace android::base;
using namespace std;
static void usage(FILE* out) {
fprintf(out, "incident_helper is not designed to run manually,");
fprintf(out, "it reads from stdin and writes to stdout, see README.md for details.\n");
fprintf(out, "usage: incident_helper -s SECTION\n");
fprintf(out, "REQUIRED:\n");
fprintf(out, " -s section id, must be positive\n");
}
//=============================================================================
static TextParserBase* selectParser(int section) {
switch (section) {
// IDs smaller than or equal to 0 are reserved for testing
case -1:
return new TimeoutParser();
case 0:
return new NoopParser();
case 1: // 1 is reserved for incident header so it won't be section id
return new ReverseParser();
/* ========================================================================= */
// IDs larger than 1 are section ids reserved in incident.proto
case 1000:
return new SystemPropertiesParser();
case 1100:
return new EventLogTagsParser();
case 2000:
return new ProcrankParser();
case 2001:
return new PageTypeInfoParser();
case 2002:
return new KernelWakesParser();
case 2003:
return new CpuInfoParser();
case 2004:
return new CpuFreqParser();
case 2005:
return new PsParser();
case 2006:
return new BatteryTypeParser();
case 3026: // system_trace is already a serialized protobuf
return new NoopParser();
default:
// Return no op parser when no specific ones are implemented.
return new NoopParser();
}
}
//=============================================================================
int main(int argc, char** argv) {
fprintf(stderr, "Start incident_helper...\n");
// Parse the args
int opt;
int sectionID = 0;
while ((opt = getopt(argc, argv, "hs:")) != -1) {
switch (opt) {
case 'h':
usage(stdout);
return 0;
case 's':
sectionID = atoi(optarg);
break;
}
}
fprintf(stderr, "Pasring section %d...\n", sectionID);
TextParserBase* parser = selectParser(sectionID);
if (parser != nullptr) {
fprintf(stderr, "Running parser: %s\n", parser->name.string());
status_t err = parser->Parse(STDIN_FILENO, STDOUT_FILENO);
if (err != NO_ERROR) {
fprintf(stderr, "Parse error in section %d: %s\n", sectionID, strerror(-err));
return -1;
}
delete parser;
}
fprintf(stderr, "Finish section %d, exiting...\n", sectionID);
return 0;
}
|
#ifndef ADVENT_OF_CODE_08_REGISTER_VM_HPP_INCLUDE_GUARD
#define ADVENT_OF_CODE_08_REGISTER_VM_HPP_INCLUDE_GUARD
#include <optional>
#include <string>
#include <string_view>
#include <unordered_map>
#include <vector>
enum class Operation {
Increment,
Decrement
};
enum class Comparison {
Eq, // ==
Lt, // <
Gt, // >
Ne, // !=
Le, // <=
Ge, // >=
};
struct Guard {
std::string register_name;
Comparison comparison;
int argument;
};
struct Opcode {
std::string register_name;
Operation operation;
int argument;
Guard guard;
};
using InstructionTape = std::vector<Opcode>;
using Registers = std::unordered_map<std::string, int>;
struct RegisterVM {
InstructionTape instructions;
Registers registers;
};
std::optional<Comparison> parseComparison(std::string_view input);
Guard parseGuard(std::string_view input);
std::optional<Operation> parseOperation(std::string_view input);
Opcode parseOpcode(std::string_view input);
RegisterVM parseVM(std::string_view input);
bool evaluateGuard(Guard const& g, Registers const& reg);
void executeOpcode(Opcode const& op, Registers& reg);
int highestRegisterValue(Registers const& reg);
int executeVM(RegisterVM& vm);
#endif
|
/*
* Copyright (c) 2015-present, Facebook, Inc.
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree. An additional grant
* of patent rights can be found in the PATENTS file in the same directory.
*
*
* This is a higly simplified example of an HTTP client. This can be heavily
* extended using mechanisms like redirects, transfer encoding, connection
* pooling, etc.
*
*/
#include <folly/portability/GFlags.h>
#include <folly/io/async/EventBase.h>
#include <folly/io/async/SSLContext.h>
#include <folly/SocketAddress.h>
#include <proxygen/lib/http/HTTPConnector.h>
#include "CurlClient.h"
using namespace CurlService;
using namespace folly;
using namespace proxygen;
using std::vector;
DEFINE_string(http_method, "GET",
"HTTP method to use. GET or POST are supported");
DEFINE_string(url, "https://github.com/facebook/proxygen",
"URL to perform the HTTP method against");
DEFINE_string(input_filename, "",
"Filename to read from for POST requests");
DEFINE_int32(http_client_connect_timeout, 1000,
"connect timeout in milliseconds");
DEFINE_string(ca_path, "/etc/ssl/certs/ca-certificates.crt",
"Path to trusted CA file"); // default for Ubuntu 14.04
DEFINE_string(cert_path, "",
"Path to client certificate file");
DEFINE_string(key_path, "",
"Path to client private key file");
DEFINE_string(next_protos, "h2,h2-14,spdy/3.1,spdy/3,http/1.1",
"Next protocol string for NPN/ALPN");
DEFINE_string(plaintext_proto, "", "plaintext protocol");
DEFINE_int32(recv_window, 65536, "Flow control receive window for h2/spdy");
DEFINE_bool(h2c, true, "Attempt HTTP/1.1 -> HTTP/2 upgrade");
DEFINE_string(headers, "", "List of N=V headers separated by ,");
DEFINE_string(proxy, "", "HTTP proxy URL");
int main(int argc, char* argv[]) {
gflags::ParseCommandLineFlags(&argc, &argv, true);
google::InitGoogleLogging(argv[0]);
google::InstallFailureSignalHandler();
EventBase evb;
URL url(FLAGS_url);
URL proxy(FLAGS_proxy);
if (FLAGS_http_method != "GET" && FLAGS_http_method != "POST") {
LOG(ERROR) << "http_method must be either GET or POST";
return EXIT_FAILURE;
}
HTTPMethod httpMethod = *stringToMethod(FLAGS_http_method);
if (httpMethod == HTTPMethod::POST) {
try {
File f(FLAGS_input_filename);
(void)f;
} catch (const std::system_error& se) {
LOG(ERROR) << "Couldn't open file for POST method";
LOG(ERROR) << se.what();
return EXIT_FAILURE;
}
}
HTTPHeaders headers = CurlClient::parseHeaders(FLAGS_headers);
CurlClient curlClient(&evb,
httpMethod,
url,
FLAGS_proxy.empty() ? nullptr : &proxy,
headers,
FLAGS_input_filename,
FLAGS_h2c);
curlClient.setFlowControlSettings(FLAGS_recv_window);
SocketAddress addr;
if (!FLAGS_proxy.empty()) {
addr = SocketAddress(proxy.getHost(), proxy.getPort(), true);
} else {
addr = SocketAddress(url.getHost(), url.getPort(), true);
}
LOG(INFO) << "Trying to connect to " << addr;
// Note: HHWheelTimer is a large object and should be created at most
// once per thread
HHWheelTimer::UniquePtr timer{HHWheelTimer::newTimer(
&evb,
std::chrono::milliseconds(HHWheelTimer::DEFAULT_TICK_INTERVAL),
AsyncTimeout::InternalEnum::NORMAL,
std::chrono::milliseconds(5000))};
HTTPConnector connector(&curlClient, timer.get());
if (!FLAGS_plaintext_proto.empty()) {
connector.setPlaintextProtocol(FLAGS_plaintext_proto);
}
static const AsyncSocket::OptionMap opts{{{SOL_SOCKET, SO_REUSEADDR}, 1}};
if (url.isSecure()) {
curlClient.initializeSsl(
FLAGS_ca_path, FLAGS_next_protos, FLAGS_cert_path, FLAGS_key_path);
connector.connectSSL(
&evb,
addr,
curlClient.getSSLContext(),
nullptr,
std::chrono::milliseconds(FLAGS_http_client_connect_timeout),
opts,
folly::AsyncSocket::anyAddress(),
curlClient.getServerName());
} else {
connector.connect(&evb, addr,
std::chrono::milliseconds(FLAGS_http_client_connect_timeout), opts);
}
evb.loop();
return EXIT_SUCCESS;
}
|
/*
__________ ____ ___
_____ __ _\______ \_____ _______ ______ __________\ \/ /
/ \| | \ ___/\__ \\_ __ \/ ___// __ \_ __ \ /
| Y Y \ | / | / __ \| | \/\___ \\ ___/| | \/ \
|__|_| /____/|____| (____ /__| /____ >\___ >__| /___/\ \
\/ \/ \/ \/ \_/
Copyright (C) 2016 Ingo Berg
All rights reserved.
muParserX - A C++ math parser library with array and string support
Copyright (c) 2016, Ingo Berg
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.
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 HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT,
INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
POSSIBILITY OF SUCH DAMAGE.
*/
#include "mpIValReader.h"
#include "mpTokenReader.h"
#include <cassert>
MUP_NAMESPACE_START
//--------------------------------------------------------------------------------------------
IValueReader::IValueReader()
:m_pTokenReader(nullptr)
{}
//--------------------------------------------------------------------------------------------
IValueReader::~IValueReader()
{}
//--------------------------------------------------------------------------------------------
IValueReader::IValueReader(const IValueReader &ref)
{
m_pTokenReader = ref.m_pTokenReader;
}
//--------------------------------------------------------------------------------------------
void IValueReader::SetParent(TokenReader *pTokenReader)
{
assert(pTokenReader);
m_pTokenReader = pTokenReader;
}
//--------------------------------------------------------------------------------------------
const IToken* IValueReader::TokenHistory(std::size_t pos) const
{
const TokenReader::token_buf_type &buf = m_pTokenReader->GetTokens();
std::size_t size = buf.size();
return (pos>=size) ? nullptr : buf[size-1-pos].Get();
}
}
|
#ifndef STAN_MATH_PRIM_MAT_PROB_MULTI_NORMAL_LPDF_HPP
#define STAN_MATH_PRIM_MAT_PROB_MULTI_NORMAL_LPDF_HPP
#include <stan/math/prim/mat/err/check_ldlt_factor.hpp>
#include <stan/math/prim/mat/err/check_symmetric.hpp>
#include <stan/math/prim/mat/fun/trace_inv_quad_form_ldlt.hpp>
#include <stan/math/prim/mat/fun/log_determinant_ldlt.hpp>
#include <stan/math/prim/mat/meta/vector_seq_view.hpp>
#include <stan/math/prim/scal/err/check_size_match.hpp>
#include <stan/math/prim/scal/err/check_finite.hpp>
#include <stan/math/prim/scal/err/check_not_nan.hpp>
#include <stan/math/prim/scal/err/check_positive.hpp>
#include <stan/math/prim/scal/fun/constants.hpp>
#include <stan/math/prim/scal/meta/return_type.hpp>
#include <stan/math/prim/scal/meta/max_size_mvt.hpp>
#include <stan/math/prim/scal/meta/include_summand.hpp>
#include <boost/random/normal_distribution.hpp>
#include <boost/random/variate_generator.hpp>
namespace stan {
namespace math {
template <bool propto,
typename T_y, typename T_loc, typename T_covar>
typename return_type<T_y, T_loc, T_covar>::type
multi_normal_lpdf(const T_y& y,
const T_loc& mu,
const T_covar& Sigma) {
static const char* function("multi_normal_lpdf");
typedef typename scalar_type<T_covar>::type T_covar_elem;
typedef typename return_type<T_y, T_loc, T_covar>::type lp_type;
lp_type lp(0.0);
using Eigen::Dynamic;
check_positive(function, "Covariance matrix rows", Sigma.rows());
check_symmetric(function, "Covariance matrix", Sigma);
LDLT_factor<T_covar_elem, Dynamic, Dynamic> ldlt_Sigma(Sigma);
check_ldlt_factor(function,
"LDLT_Factor of covariance parameter", ldlt_Sigma);
vector_seq_view<T_y> y_vec(y);
vector_seq_view<T_loc> mu_vec(mu);
size_t size_vec = max_size_mvt(y, mu);
int size_y = y_vec[0].size();
int size_mu = mu_vec[0].size();
if (size_vec > 1) {
int size_y_old = size_y;
int size_y_new;
for (size_t i = 1, size_ = length_mvt(y); i < size_; i++) {
int size_y_new = y_vec[i].size();
check_size_match(function,
"Size of one of the vectors of "
"the random variable", size_y_new,
"Size of another vector of the "
"random variable", size_y_old);
size_y_old = size_y_new;
}
int size_mu_old = size_mu;
int size_mu_new;
for (size_t i = 1, size_ = length_mvt(mu); i < size_; i++) {
int size_mu_new = mu_vec[i].size();
check_size_match(function,
"Size of one of the vectors of "
"the location variable", size_mu_new,
"Size of another vector of the "
"location variable", size_mu_old);
size_mu_old = size_mu_new;
}
(void) size_y_old;
(void) size_y_new;
(void) size_mu_old;
(void) size_mu_new;
}
check_size_match(function,
"Size of random variable", size_y,
"size of location parameter", size_mu);
check_size_match(function,
"Size of random variable", size_y,
"rows of covariance parameter", Sigma.rows());
check_size_match(function,
"Size of random variable", size_y,
"columns of covariance parameter", Sigma.cols());
for (size_t i = 0; i < size_vec; i++) {
check_finite(function, "Location parameter", mu_vec[i]);
check_not_nan(function, "Random variable", y_vec[i]);
}
if (size_y == 0)
return lp;
if (include_summand<propto>::value)
lp += NEG_LOG_SQRT_TWO_PI * size_y * size_vec;
if (include_summand<propto, T_covar_elem>::value)
lp -= 0.5 * log_determinant_ldlt(ldlt_Sigma) * size_vec;
if (include_summand<propto, T_y, T_loc, T_covar_elem>::value) {
lp_type sum_lp_vec(0.0);
for (size_t i = 0; i < size_vec; i++) {
Eigen::Matrix<typename return_type<T_y, T_loc>::type, Dynamic, 1>
y_minus_mu(size_y);
for (int j = 0; j < size_y; j++)
y_minus_mu(j) = y_vec[i](j)-mu_vec[i](j);
sum_lp_vec += trace_inv_quad_form_ldlt(ldlt_Sigma, y_minus_mu);
}
lp -= 0.5*sum_lp_vec;
}
return lp;
}
template <typename T_y, typename T_loc, typename T_covar>
inline
typename return_type<T_y, T_loc, T_covar>::type
multi_normal_lpdf(const T_y& y,
const T_loc& mu,
const T_covar& Sigma) {
return multi_normal_lpdf<false>(y, mu, Sigma);
}
}
}
#endif
|
#include "common/http/http1/codec_impl_legacy.h"
#include <cstdint>
#include <memory>
#include <string>
#include "envoy/buffer/buffer.h"
#include "envoy/http/codec.h"
#include "envoy/http/header_map.h"
#include "envoy/network/connection.h"
#include "common/common/enum_to_int.h"
#include "common/common/utility.h"
#include "common/grpc/common.h"
#include "common/http/exception.h"
#include "common/http/header_utility.h"
#include "common/http/headers.h"
#include "common/http/http1/header_formatter.h"
#include "common/http/utility.h"
#include "common/runtime/runtime_features.h"
#include "absl/container/fixed_array.h"
#include "absl/strings/ascii.h"
namespace Envoy {
namespace Http {
namespace Legacy {
namespace Http1 {
namespace {
struct Http1ResponseCodeDetailValues {
const absl::string_view TooManyHeaders = "http1.too_many_headers";
const absl::string_view HeadersTooLarge = "http1.headers_too_large";
const absl::string_view HttpCodecError = "http1.codec_error";
const absl::string_view InvalidCharacters = "http1.invalid_characters";
const absl::string_view ConnectionHeaderSanitization = "http1.connection_header_rejected";
const absl::string_view InvalidUrl = "http1.invalid_url";
const absl::string_view InvalidTransferEncoding = "http1.invalid_transfer_encoding";
const absl::string_view BodyDisallowed = "http1.body_disallowed";
const absl::string_view TransferEncodingNotAllowed = "http1.transfer_encoding_not_allowed";
const absl::string_view ContentLengthNotAllowed = "http1.content_length_not_allowed";
const absl::string_view InvalidUnderscore = "http1.unexpected_underscore";
const absl::string_view ChunkedContentLength = "http1.content_length_and_chunked_not_allowed";
};
struct Http1HeaderTypesValues {
const absl::string_view Headers = "headers";
const absl::string_view Trailers = "trailers";
};
using Http1ResponseCodeDetails = ConstSingleton<Http1ResponseCodeDetailValues>;
using Http1HeaderTypes = ConstSingleton<Http1HeaderTypesValues>;
using Http::Http1::CodecStats;
using Http::Http1::HeaderKeyFormatter;
using Http::Http1::HeaderKeyFormatterPtr;
using Http::Http1::ProperCaseHeaderKeyFormatter;
const StringUtil::CaseUnorderedSet& caseUnorderdSetContainingUpgradeAndHttp2Settings() {
CONSTRUCT_ON_FIRST_USE(StringUtil::CaseUnorderedSet,
Http::Headers::get().ConnectionValues.Upgrade,
Http::Headers::get().ConnectionValues.Http2Settings);
}
HeaderKeyFormatterPtr formatter(const Http::Http1Settings& settings) {
if (settings.header_key_format_ == Http1Settings::HeaderKeyFormat::ProperCase) {
return std::make_unique<ProperCaseHeaderKeyFormatter>();
}
return nullptr;
}
} // namespace
const std::string StreamEncoderImpl::CRLF = "\r\n";
// Last chunk as defined here https://tools.ietf.org/html/rfc7230#section-4.1
const std::string StreamEncoderImpl::LAST_CHUNK = "0\r\n";
StreamEncoderImpl::StreamEncoderImpl(ConnectionImpl& connection,
HeaderKeyFormatter* header_key_formatter)
: connection_(connection), disable_chunk_encoding_(false), chunk_encoding_(true),
connect_request_(false), is_response_to_head_request_(false),
is_response_to_connect_request_(false), header_key_formatter_(header_key_formatter) {
if (connection_.connection().aboveHighWatermark()) {
runHighWatermarkCallbacks();
}
}
void StreamEncoderImpl::encodeHeader(const char* key, uint32_t key_size, const char* value,
uint32_t value_size) {
ASSERT(key_size > 0);
connection_.copyToBuffer(key, key_size);
connection_.addCharToBuffer(':');
connection_.addCharToBuffer(' ');
connection_.copyToBuffer(value, value_size);
connection_.addToBuffer(CRLF);
}
void StreamEncoderImpl::encodeHeader(absl::string_view key, absl::string_view value) {
this->encodeHeader(key.data(), key.size(), value.data(), value.size());
}
void StreamEncoderImpl::encodeFormattedHeader(absl::string_view key, absl::string_view value) {
if (header_key_formatter_ != nullptr) {
encodeHeader(header_key_formatter_->format(key), value);
} else {
encodeHeader(key, value);
}
}
void ResponseEncoderImpl::encode100ContinueHeaders(const ResponseHeaderMap& headers) {
ASSERT(headers.Status()->value() == "100");
encodeHeaders(headers, false);
}
void StreamEncoderImpl::encodeHeadersBase(const RequestOrResponseHeaderMap& headers,
absl::optional<uint64_t> status, bool end_stream) {
bool saw_content_length = false;
headers.iterate([this](const HeaderEntry& header) -> HeaderMap::Iterate {
absl::string_view key_to_use = header.key().getStringView();
uint32_t key_size_to_use = header.key().size();
// Translate :authority -> host so that upper layers do not need to deal with this.
if (key_size_to_use > 1 && key_to_use[0] == ':' && key_to_use[1] == 'a') {
key_to_use = absl::string_view(Headers::get().HostLegacy.get());
key_size_to_use = Headers::get().HostLegacy.get().size();
}
// Skip all headers starting with ':' that make it here.
if (key_to_use[0] == ':') {
return HeaderMap::Iterate::Continue;
}
encodeFormattedHeader(key_to_use, header.value().getStringView());
return HeaderMap::Iterate::Continue;
});
if (headers.ContentLength()) {
saw_content_length = true;
}
ASSERT(!headers.TransferEncoding());
// Assume we are chunk encoding unless we are passed a content length or this is a header only
// response. Upper layers generally should strip transfer-encoding since it only applies to
// HTTP/1.1. The codec will infer it based on the type of response.
// for streaming (e.g. SSE stream sent to hystrix dashboard), we do not want
// chunk transfer encoding but we don't have a content-length so disable_chunk_encoding_ is
// consulted before enabling chunk encoding.
//
// Note that for HEAD requests Envoy does best-effort guessing when there is no
// content-length. If a client makes a HEAD request for an upstream resource
// with no bytes but the upstream response doesn't include "Content-length: 0",
// Envoy will incorrectly assume a subsequent response to GET will be chunk encoded.
if (saw_content_length || disable_chunk_encoding_) {
chunk_encoding_ = false;
} else {
if (status && *status == 100) {
// Make sure we don't serialize chunk information with 100-Continue headers.
chunk_encoding_ = false;
} else if (end_stream && !is_response_to_head_request_) {
// If this is a headers-only stream, append an explicit "Content-Length: 0" unless it's a
// response to a HEAD request.
// For 204s and 1xx where content length is disallowed, don't append the content length but
// also don't chunk encode.
if (!status || (*status >= 200 && *status != 204)) {
encodeFormattedHeader(Headers::get().ContentLength.get(), "0");
}
chunk_encoding_ = false;
} else if (connection_.protocol() == Protocol::Http10) {
chunk_encoding_ = false;
} else if (status && (*status < 200 || *status == 204) &&
connection_.strict1xxAnd204Headers()) {
// TODO(zuercher): when the "envoy.reloadable_features.strict_1xx_and_204_response_headers"
// feature flag is removed, this block can be coalesced with the 100 Continue logic above.
// For 1xx and 204 responses, do not send the chunked encoding header or enable chunked
// encoding: https://tools.ietf.org/html/rfc7230#section-3.3.1
chunk_encoding_ = false;
} else {
// For responses to connect requests, do not send the chunked encoding header:
// https://tools.ietf.org/html/rfc7231#section-4.3.6.
if (!is_response_to_connect_request_) {
encodeFormattedHeader(Headers::get().TransferEncoding.get(),
Headers::get().TransferEncodingValues.Chunked);
}
// We do not apply chunk encoding for HTTP upgrades, including CONNECT style upgrades.
// If there is a body in a response on the upgrade path, the chunks will be
// passed through via maybeDirectDispatch so we need to avoid appending
// extra chunk boundaries.
//
// When sending a response to a HEAD request Envoy may send an informational
// "Transfer-Encoding: chunked" header, but should not send a chunk encoded body.
chunk_encoding_ = !Utility::isUpgrade(headers) && !is_response_to_head_request_ &&
!is_response_to_connect_request_;
}
}
connection_.addToBuffer(CRLF);
if (end_stream) {
endEncode();
} else {
connection_.flushOutput();
}
}
void StreamEncoderImpl::encodeData(Buffer::Instance& data, bool end_stream) {
// end_stream may be indicated with a zero length data buffer. If that is the case, so not
// actually write the zero length buffer out.
if (data.length() > 0) {
if (chunk_encoding_) {
connection_.buffer().add(absl::StrCat(absl::Hex(data.length()), CRLF));
}
connection_.buffer().move(data);
if (chunk_encoding_) {
connection_.buffer().add(CRLF);
}
}
if (end_stream) {
endEncode();
} else {
connection_.flushOutput();
}
}
void StreamEncoderImpl::encodeTrailersBase(const HeaderMap& trailers) {
if (!connection_.enableTrailers()) {
return endEncode();
}
// Trailers only matter if it is a chunk transfer encoding
// https://tools.ietf.org/html/rfc7230#section-4.4
if (chunk_encoding_) {
// Finalize the body
connection_.buffer().add(LAST_CHUNK);
trailers.iterate([this](const HeaderEntry& header) -> HeaderMap::Iterate {
encodeFormattedHeader(header.key().getStringView(), header.value().getStringView());
return HeaderMap::Iterate::Continue;
});
connection_.flushOutput();
connection_.buffer().add(CRLF);
}
connection_.flushOutput();
connection_.onEncodeComplete();
}
void StreamEncoderImpl::encodeMetadata(const MetadataMapVector&) {
connection_.stats().metadata_not_supported_error_.inc();
}
void StreamEncoderImpl::endEncode() {
if (chunk_encoding_) {
connection_.buffer().add(LAST_CHUNK);
connection_.buffer().add(CRLF);
}
connection_.flushOutput(true);
connection_.onEncodeComplete();
// With CONNECT half-closing the connection is used to signal end stream.
if (connect_request_) {
connection_.connection().close(Network::ConnectionCloseType::FlushWriteAndDelay);
}
}
void ServerConnectionImpl::maybeAddSentinelBufferFragment(Buffer::WatermarkBuffer& output_buffer) {
// It's messy and complicated to try to tag the final write of an HTTP response for response
// tracking for flood protection. Instead, write an empty buffer fragment after the response,
// to allow for tracking.
// When the response is written out, the fragment will be deleted and the counter will be updated
// by ServerConnectionImpl::releaseOutboundResponse()
auto fragment =
Buffer::OwnedBufferFragmentImpl::create(absl::string_view("", 0), response_buffer_releasor_);
output_buffer.addBufferFragment(*fragment.release());
ASSERT(outbound_responses_ < max_outbound_responses_);
outbound_responses_++;
}
void ServerConnectionImpl::doFloodProtectionChecks() const {
// Before processing another request, make sure that we are below the response flood protection
// threshold.
if (outbound_responses_ >= max_outbound_responses_) {
ENVOY_CONN_LOG(trace, "error accepting request: too many pending responses queued",
connection_);
stats_.response_flood_.inc();
throw FrameFloodException("Too many responses queued.");
}
}
void ConnectionImpl::flushOutput(bool end_encode) {
if (end_encode) {
// If this is an HTTP response in ServerConnectionImpl, track outbound responses for flood
// protection
maybeAddSentinelBufferFragment(output_buffer_);
}
connection().write(output_buffer_, false);
ASSERT(0UL == output_buffer_.length());
}
void ConnectionImpl::addToBuffer(absl::string_view data) { output_buffer_.add(data); }
void ConnectionImpl::addCharToBuffer(char c) { output_buffer_.add(&c, 1); }
void ConnectionImpl::addIntToBuffer(uint64_t i) { output_buffer_.add(absl::StrCat(i)); }
void ConnectionImpl::copyToBuffer(const char* data, uint64_t length) {
output_buffer_.add(data, length);
}
void StreamEncoderImpl::resetStream(StreamResetReason reason) {
connection_.onResetStreamBase(reason);
}
void StreamEncoderImpl::readDisable(bool disable) {
if (disable) {
++read_disable_calls_;
} else {
ASSERT(read_disable_calls_ != 0);
if (read_disable_calls_ != 0) {
--read_disable_calls_;
}
}
connection_.readDisable(disable);
}
uint32_t StreamEncoderImpl::bufferLimit() { return connection_.bufferLimit(); }
const Network::Address::InstanceConstSharedPtr& StreamEncoderImpl::connectionLocalAddress() {
return connection_.connection().localAddress();
}
static const char RESPONSE_PREFIX[] = "HTTP/1.1 ";
static const char HTTP_10_RESPONSE_PREFIX[] = "HTTP/1.0 ";
void ResponseEncoderImpl::encodeHeaders(const ResponseHeaderMap& headers, bool end_stream) {
started_response_ = true;
// The contract is that client codecs must ensure that :status is present.
ASSERT(headers.Status() != nullptr);
uint64_t numeric_status = Utility::getResponseStatus(headers);
if (connection_.protocol() == Protocol::Http10 && connection_.supportsHttp10()) {
connection_.copyToBuffer(HTTP_10_RESPONSE_PREFIX, sizeof(HTTP_10_RESPONSE_PREFIX) - 1);
} else {
connection_.copyToBuffer(RESPONSE_PREFIX, sizeof(RESPONSE_PREFIX) - 1);
}
connection_.addIntToBuffer(numeric_status);
connection_.addCharToBuffer(' ');
const char* status_string = CodeUtility::toString(static_cast<Code>(numeric_status));
uint32_t status_string_len = strlen(status_string);
connection_.copyToBuffer(status_string, status_string_len);
connection_.addCharToBuffer('\r');
connection_.addCharToBuffer('\n');
if (numeric_status >= 300) {
// Don't do special CONNECT logic if the CONNECT was rejected.
is_response_to_connect_request_ = false;
}
encodeHeadersBase(headers, absl::make_optional<uint64_t>(numeric_status), end_stream);
}
static const char REQUEST_POSTFIX[] = " HTTP/1.1\r\n";
Status RequestEncoderImpl::encodeHeaders(const RequestHeaderMap& headers, bool end_stream) {
const HeaderEntry* method = headers.Method();
const HeaderEntry* path = headers.Path();
const HeaderEntry* host = headers.Host();
bool is_connect = HeaderUtility::isConnect(headers);
if (!method || (!path && !is_connect)) {
// TODO(#10878): This exception does not occur during dispatch and would not be triggered under
// normal circumstances since inputs would fail parsing at ingress. Replace with proper error
// handling when exceptions are removed. Include missing host header for CONNECT.
throw CodecClientException(":method and :path must be specified");
}
if (method->value() == Headers::get().MethodValues.Head) {
head_request_ = true;
} else if (method->value() == Headers::get().MethodValues.Connect) {
disableChunkEncoding();
connection_.connection().enableHalfClose(true);
connect_request_ = true;
}
if (Utility::isUpgrade(headers)) {
upgrade_request_ = true;
}
connection_.copyToBuffer(method->value().getStringView().data(), method->value().size());
connection_.addCharToBuffer(' ');
if (is_connect) {
connection_.copyToBuffer(host->value().getStringView().data(), host->value().size());
} else {
connection_.copyToBuffer(path->value().getStringView().data(), path->value().size());
}
connection_.copyToBuffer(REQUEST_POSTFIX, sizeof(REQUEST_POSTFIX) - 1);
encodeHeadersBase(headers, absl::nullopt, end_stream);
return okStatus();
}
http_parser_settings ConnectionImpl::settings_{
[](http_parser* parser) -> int {
static_cast<ConnectionImpl*>(parser->data)->onMessageBeginBase();
return 0;
},
[](http_parser* parser, const char* at, size_t length) -> int {
static_cast<ConnectionImpl*>(parser->data)->onUrl(at, length);
return 0;
},
nullptr, // on_status
[](http_parser* parser, const char* at, size_t length) -> int {
static_cast<ConnectionImpl*>(parser->data)->onHeaderField(at, length);
return 0;
},
[](http_parser* parser, const char* at, size_t length) -> int {
static_cast<ConnectionImpl*>(parser->data)->onHeaderValue(at, length);
return 0;
},
[](http_parser* parser) -> int {
return static_cast<ConnectionImpl*>(parser->data)->onHeadersCompleteBase();
},
[](http_parser* parser, const char* at, size_t length) -> int {
static_cast<ConnectionImpl*>(parser->data)->bufferBody(at, length);
return 0;
},
[](http_parser* parser) -> int {
static_cast<ConnectionImpl*>(parser->data)->onMessageCompleteBase();
return 0;
},
[](http_parser* parser) -> int {
// A 0-byte chunk header is used to signal the end of the chunked body.
// When this function is called, http-parser holds the size of the chunk in
// parser->content_length. See
// https://github.com/nodejs/http-parser/blob/v2.9.3/http_parser.h#L336
const bool is_final_chunk = (parser->content_length == 0);
static_cast<ConnectionImpl*>(parser->data)->onChunkHeader(is_final_chunk);
return 0;
},
nullptr // on_chunk_complete
};
ConnectionImpl::ConnectionImpl(Network::Connection& connection, CodecStats& stats,
const Http1Settings& settings, http_parser_type type,
uint32_t max_headers_kb, const uint32_t max_headers_count,
HeaderKeyFormatterPtr&& header_key_formatter)
: connection_(connection), stats_(stats), codec_settings_(settings),
header_key_formatter_(std::move(header_key_formatter)), processing_trailers_(false),
handling_upgrade_(false), reset_stream_called_(false), deferred_end_stream_headers_(false),
strict_1xx_and_204_headers_(Runtime::runtimeFeatureEnabled(
"envoy.reloadable_features.strict_1xx_and_204_response_headers")),
output_buffer_([&]() -> void { this->onBelowLowWatermark(); },
[&]() -> void { this->onAboveHighWatermark(); },
[]() -> void { /* TODO(adisuissa): Handle overflow watermark */ }),
max_headers_kb_(max_headers_kb), max_headers_count_(max_headers_count) {
output_buffer_.setWatermarks(connection.bufferLimit());
http_parser_init(&parser_, type);
parser_.allow_chunked_length = 1;
parser_.data = this;
}
void ConnectionImpl::completeLastHeader() {
ENVOY_CONN_LOG(trace, "completed header: key={} value={}", connection_,
current_header_field_.getStringView(), current_header_value_.getStringView());
checkHeaderNameForUnderscores();
auto& headers_or_trailers = headersOrTrailers();
if (!current_header_field_.empty()) {
current_header_field_.inlineTransform([](char c) { return absl::ascii_tolower(c); });
// Strip trailing whitespace of the current header value if any. Leading whitespace was trimmed
// in ConnectionImpl::onHeaderValue. http_parser does not strip leading or trailing whitespace
// as the spec requires: https://tools.ietf.org/html/rfc7230#section-3.2.4
current_header_value_.rtrim();
headers_or_trailers.addViaMove(std::move(current_header_field_),
std::move(current_header_value_));
}
// Check if the number of headers exceeds the limit.
if (headers_or_trailers.size() > max_headers_count_) {
error_code_ = Http::Code::RequestHeaderFieldsTooLarge;
sendProtocolError(Http1ResponseCodeDetails::get().TooManyHeaders);
const absl::string_view header_type =
processing_trailers_ ? Http1HeaderTypes::get().Trailers : Http1HeaderTypes::get().Headers;
throw CodecProtocolException(absl::StrCat(header_type, " size exceeds limit"));
}
header_parsing_state_ = HeaderParsingState::Field;
ASSERT(current_header_field_.empty());
ASSERT(current_header_value_.empty());
}
uint32_t ConnectionImpl::getHeadersSize() {
return current_header_field_.size() + current_header_value_.size() +
headersOrTrailers().byteSize();
}
void ConnectionImpl::checkMaxHeadersSize() {
const uint32_t total = getHeadersSize();
if (total > (max_headers_kb_ * 1024)) {
const absl::string_view header_type =
processing_trailers_ ? Http1HeaderTypes::get().Trailers : Http1HeaderTypes::get().Headers;
error_code_ = Http::Code::RequestHeaderFieldsTooLarge;
sendProtocolError(Http1ResponseCodeDetails::get().HeadersTooLarge);
throw CodecProtocolException(absl::StrCat(header_type, " size exceeds limit"));
}
}
bool ConnectionImpl::maybeDirectDispatch(Buffer::Instance& data) {
if (!handling_upgrade_) {
// Only direct dispatch for Upgrade requests.
return false;
}
ENVOY_CONN_LOG(trace, "direct-dispatched {} bytes", connection_, data.length());
onBody(data);
data.drain(data.length());
return true;
}
Http::Status ConnectionImpl::dispatch(Buffer::Instance& data) {
// TODO(#10878): Remove this wrapper when exception removal is complete. innerDispatch may either
// throw an exception or return an error status. The utility wrapper catches exceptions and
// converts them to error statuses.
return Utility::exceptionToStatus(
[&](Buffer::Instance& data) -> Http::Status { return innerDispatch(data); }, data);
}
Http::Status ClientConnectionImpl::dispatch(Buffer::Instance& data) {
Http::Status status = ConnectionImpl::dispatch(data);
if (status.ok() && data.length() > 0) {
// The HTTP/1.1 codec pauses dispatch after a single response is complete. Extraneous data
// after a response is complete indicates an error.
return codecProtocolError("http/1.1 protocol error: extraneous data after response complete");
}
return status;
}
Http::Status ConnectionImpl::innerDispatch(Buffer::Instance& data) {
ENVOY_CONN_LOG(trace, "parsing {} bytes", connection_, data.length());
ASSERT(buffered_body_.length() == 0);
if (maybeDirectDispatch(data)) {
return Http::okStatus();
}
// Always unpause before dispatch.
http_parser_pause(&parser_, 0);
ssize_t total_parsed = 0;
if (data.length() > 0) {
for (const Buffer::RawSlice& slice : data.getRawSlices()) {
total_parsed += dispatchSlice(static_cast<const char*>(slice.mem_), slice.len_);
if (HTTP_PARSER_ERRNO(&parser_) != HPE_OK) {
// Parse errors trigger an exception in dispatchSlice so we are guaranteed to be paused at
// this point.
ASSERT(HTTP_PARSER_ERRNO(&parser_) == HPE_PAUSED);
break;
}
}
dispatchBufferedBody();
} else {
dispatchSlice(nullptr, 0);
}
ASSERT(buffered_body_.length() == 0);
ENVOY_CONN_LOG(trace, "parsed {} bytes", connection_, total_parsed);
data.drain(total_parsed);
// If an upgrade has been handled and there is body data or early upgrade
// payload to send on, send it on.
maybeDirectDispatch(data);
return Http::okStatus();
}
size_t ConnectionImpl::dispatchSlice(const char* slice, size_t len) {
ssize_t rc = http_parser_execute(&parser_, &settings_, slice, len);
if (HTTP_PARSER_ERRNO(&parser_) != HPE_OK && HTTP_PARSER_ERRNO(&parser_) != HPE_PAUSED) {
sendProtocolError(Http1ResponseCodeDetails::get().HttpCodecError);
throw CodecProtocolException("http/1.1 protocol error: " +
std::string(http_errno_name(HTTP_PARSER_ERRNO(&parser_))));
}
return rc;
}
void ConnectionImpl::onHeaderField(const char* data, size_t length) {
// We previously already finished up the headers, these headers are
// now trailers.
if (header_parsing_state_ == HeaderParsingState::Done) {
if (!enableTrailers()) {
// Ignore trailers.
return;
}
processing_trailers_ = true;
header_parsing_state_ = HeaderParsingState::Field;
allocTrailers();
}
if (header_parsing_state_ == HeaderParsingState::Value) {
completeLastHeader();
}
current_header_field_.append(data, length);
checkMaxHeadersSize();
}
void ConnectionImpl::onHeaderValue(const char* data, size_t length) {
if (header_parsing_state_ == HeaderParsingState::Done && !enableTrailers()) {
// Ignore trailers.
return;
}
absl::string_view header_value{data, length};
if (!Http::HeaderUtility::headerValueIsValid(header_value)) {
ENVOY_CONN_LOG(debug, "invalid header value: {}", connection_, header_value);
error_code_ = Http::Code::BadRequest;
sendProtocolError(Http1ResponseCodeDetails::get().InvalidCharacters);
throw CodecProtocolException("http/1.1 protocol error: header value contains invalid chars");
}
header_parsing_state_ = HeaderParsingState::Value;
if (current_header_value_.empty()) {
// Strip leading whitespace if the current header value input contains the first bytes of the
// encoded header value. Trailing whitespace is stripped once the full header value is known in
// ConnectionImpl::completeLastHeader. http_parser does not strip leading or trailing whitespace
// as the spec requires: https://tools.ietf.org/html/rfc7230#section-3.2.4 .
header_value = StringUtil::ltrim(header_value);
}
current_header_value_.append(header_value.data(), header_value.length());
checkMaxHeadersSize();
}
int ConnectionImpl::onHeadersCompleteBase() {
ASSERT(!processing_trailers_);
ENVOY_CONN_LOG(trace, "onHeadersCompleteBase", connection_);
completeLastHeader();
if (!(parser_.http_major == 1 && parser_.http_minor == 1)) {
// This is not necessarily true, but it's good enough since higher layers only care if this is
// HTTP/1.1 or not.
protocol_ = Protocol::Http10;
}
RequestOrResponseHeaderMap& request_or_response_headers = requestOrResponseHeaders();
if (Utility::isUpgrade(request_or_response_headers) && upgradeAllowed()) {
// Ignore h2c upgrade requests until we support them.
// See https://github.com/envoyproxy/envoy/issues/7161 for details.
if (absl::EqualsIgnoreCase(request_or_response_headers.getUpgradeValue(),
Http::Headers::get().UpgradeValues.H2c)) {
ENVOY_CONN_LOG(trace, "removing unsupported h2c upgrade headers.", connection_);
request_or_response_headers.removeUpgrade();
if (request_or_response_headers.Connection()) {
const auto& tokens_to_remove = caseUnorderdSetContainingUpgradeAndHttp2Settings();
std::string new_value = StringUtil::removeTokens(
request_or_response_headers.getConnectionValue(), ",", tokens_to_remove, ",");
if (new_value.empty()) {
request_or_response_headers.removeConnection();
} else {
request_or_response_headers.setConnection(new_value);
}
}
request_or_response_headers.remove(Headers::get().Http2Settings);
} else {
ENVOY_CONN_LOG(trace, "codec entering upgrade mode.", connection_);
handling_upgrade_ = true;
}
}
if (parser_.method == HTTP_CONNECT) {
if (request_or_response_headers.ContentLength()) {
if (request_or_response_headers.getContentLengthValue() == "0") {
request_or_response_headers.removeContentLength();
} else {
// Per https://tools.ietf.org/html/rfc7231#section-4.3.6 a payload with a
// CONNECT request has no defined semantics, and may be rejected.
error_code_ = Http::Code::BadRequest;
sendProtocolError(Http1ResponseCodeDetails::get().BodyDisallowed);
throw CodecProtocolException("http/1.1 protocol error: unsupported content length");
}
}
ENVOY_CONN_LOG(trace, "codec entering upgrade mode for CONNECT request.", connection_);
handling_upgrade_ = true;
}
// https://tools.ietf.org/html/rfc7230#section-3.3.3
// If a message is received with both a Transfer-Encoding and a
// Content-Length header field, the Transfer-Encoding overrides the
// Content-Length. Such a message might indicate an attempt to
// perform request smuggling (Section 9.5) or response splitting
// (Section 9.4) and ought to be handled as an error. A sender MUST
// remove the received Content-Length field prior to forwarding such
// a message.
// Reject message with Http::Code::BadRequest if both Transfer-Encoding and Content-Length
// headers are present or if allowed by http1 codec settings and 'Transfer-Encoding'
// is chunked - remove Content-Length and serve request.
if (parser_.uses_transfer_encoding != 0 && request_or_response_headers.ContentLength()) {
if ((parser_.flags & F_CHUNKED) && codec_settings_.allow_chunked_length_) {
request_or_response_headers.removeContentLength();
} else {
error_code_ = Http::Code::BadRequest;
sendProtocolError(Http1ResponseCodeDetails::get().ChunkedContentLength);
throw CodecProtocolException(
"http/1.1 protocol error: both 'Content-Length' and 'Transfer-Encoding' are set.");
}
}
// Per https://tools.ietf.org/html/rfc7230#section-3.3.1 Envoy should reject
// transfer-codings it does not understand.
// Per https://tools.ietf.org/html/rfc7231#section-4.3.6 a payload with a
// CONNECT request has no defined semantics, and may be rejected.
if (request_or_response_headers.TransferEncoding()) {
const absl::string_view encoding = request_or_response_headers.getTransferEncodingValue();
if (!absl::EqualsIgnoreCase(encoding, Headers::get().TransferEncodingValues.Chunked) ||
parser_.method == HTTP_CONNECT) {
error_code_ = Http::Code::NotImplemented;
sendProtocolError(Http1ResponseCodeDetails::get().InvalidTransferEncoding);
throw CodecProtocolException("http/1.1 protocol error: unsupported transfer encoding");
}
}
int rc = onHeadersComplete();
header_parsing_state_ = HeaderParsingState::Done;
// Returning 2 informs http_parser to not expect a body or further data on this connection.
return handling_upgrade_ ? 2 : rc;
}
void ConnectionImpl::bufferBody(const char* data, size_t length) {
buffered_body_.add(data, length);
}
void ConnectionImpl::dispatchBufferedBody() {
ASSERT(HTTP_PARSER_ERRNO(&parser_) == HPE_OK || HTTP_PARSER_ERRNO(&parser_) == HPE_PAUSED);
if (buffered_body_.length() > 0) {
onBody(buffered_body_);
buffered_body_.drain(buffered_body_.length());
}
}
void ConnectionImpl::onChunkHeader(bool is_final_chunk) {
if (is_final_chunk) {
// Dispatch body before parsing trailers, so body ends up dispatched even if an error is found
// while processing trailers.
dispatchBufferedBody();
}
}
void ConnectionImpl::onMessageCompleteBase() {
ENVOY_CONN_LOG(trace, "message complete", connection_);
dispatchBufferedBody();
if (handling_upgrade_) {
// If this is an upgrade request, swallow the onMessageComplete. The
// upgrade payload will be treated as stream body.
ASSERT(!deferred_end_stream_headers_);
ENVOY_CONN_LOG(trace, "Pausing parser due to upgrade.", connection_);
http_parser_pause(&parser_, 1);
return;
}
// If true, this indicates we were processing trailers and must
// move the last header into current_header_map_
if (header_parsing_state_ == HeaderParsingState::Value) {
completeLastHeader();
}
onMessageComplete();
}
void ConnectionImpl::onMessageBeginBase() {
ENVOY_CONN_LOG(trace, "message begin", connection_);
// Make sure that if HTTP/1.0 and HTTP/1.1 requests share a connection Envoy correctly sets
// protocol for each request. Envoy defaults to 1.1 but sets the protocol to 1.0 where applicable
// in onHeadersCompleteBase
protocol_ = Protocol::Http11;
processing_trailers_ = false;
header_parsing_state_ = HeaderParsingState::Field;
allocHeaders();
onMessageBegin();
}
void ConnectionImpl::onResetStreamBase(StreamResetReason reason) {
ASSERT(!reset_stream_called_);
reset_stream_called_ = true;
onResetStream(reason);
}
ServerConnectionImpl::ServerConnectionImpl(
Network::Connection& connection, CodecStats& stats, ServerConnectionCallbacks& callbacks,
const Http1Settings& settings, uint32_t max_request_headers_kb,
const uint32_t max_request_headers_count,
envoy::config::core::v3::HttpProtocolOptions::HeadersWithUnderscoresAction
headers_with_underscores_action)
: ConnectionImpl(connection, stats, settings, HTTP_REQUEST, max_request_headers_kb,
max_request_headers_count, formatter(settings)),
callbacks_(callbacks),
response_buffer_releasor_([this](const Buffer::OwnedBufferFragmentImpl* fragment) {
releaseOutboundResponse(fragment);
}),
// Pipelining is generally not well supported on the internet and has a series of dangerous
// overflow bugs. As such we are disabling it for now, and removing this temporary override if
// no one objects. If you use this integer to restore prior behavior, contact the
// maintainer team as it will otherwise be removed entirely soon.
max_outbound_responses_(
Runtime::getInteger("envoy.do_not_use_going_away_max_http2_outbound_responses", 2)),
headers_with_underscores_action_(headers_with_underscores_action) {}
uint32_t ServerConnectionImpl::getHeadersSize() {
// Add in the size of the request URL if processing request headers.
const uint32_t url_size = (!processing_trailers_ && active_request_.has_value())
? active_request_.value().request_url_.size()
: 0;
return url_size + ConnectionImpl::getHeadersSize();
}
void ServerConnectionImpl::onEncodeComplete() {
if (active_request_.value().remote_complete_) {
// Only do this if remote is complete. If we are replying before the request is complete the
// only logical thing to do is for higher level code to reset() / close the connection so we
// leave the request around so that it can fire reset callbacks.
active_request_.reset();
}
}
void ServerConnectionImpl::handlePath(RequestHeaderMap& headers, unsigned int method) {
HeaderString path(Headers::get().Path);
bool is_connect = (method == HTTP_CONNECT);
// The url is relative or a wildcard when the method is OPTIONS. Nothing to do here.
auto& active_request = active_request_.value();
if (!is_connect && !active_request.request_url_.getStringView().empty() &&
(active_request.request_url_.getStringView()[0] == '/' ||
((method == HTTP_OPTIONS) && active_request.request_url_.getStringView()[0] == '*'))) {
headers.addViaMove(std::move(path), std::move(active_request.request_url_));
return;
}
// If absolute_urls and/or connect are not going be handled, copy the url and return.
// This forces the behavior to be backwards compatible with the old codec behavior.
// CONNECT "urls" are actually host:port so look like absolute URLs to the above checks.
// Absolute URLS in CONNECT requests will be rejected below by the URL class validation.
if (!codec_settings_.allow_absolute_url_ && !is_connect) {
headers.addViaMove(std::move(path), std::move(active_request.request_url_));
return;
}
Utility::Url absolute_url;
if (!absolute_url.initialize(active_request.request_url_.getStringView(), is_connect)) {
sendProtocolError(Http1ResponseCodeDetails::get().InvalidUrl);
throw CodecProtocolException("http/1.1 protocol error: invalid url in request line");
}
// RFC7230#5.7
// When a proxy receives a request with an absolute-form of
// request-target, the proxy MUST ignore the received Host header field
// (if any) and instead replace it with the host information of the
// request-target. A proxy that forwards such a request MUST generate a
// new Host field-value based on the received request-target rather than
// forward the received Host field-value.
headers.setHost(absolute_url.hostAndPort());
if (!absolute_url.pathAndQueryParams().empty()) {
headers.setPath(absolute_url.pathAndQueryParams());
}
active_request.request_url_.clear();
}
int ServerConnectionImpl::onHeadersComplete() {
// Handle the case where response happens prior to request complete. It's up to upper layer code
// to disconnect the connection but we shouldn't fire any more events since it doesn't make
// sense.
if (active_request_.has_value()) {
auto& active_request = active_request_.value();
auto& headers = absl::get<RequestHeaderMapPtr>(headers_or_trailers_);
ENVOY_CONN_LOG(trace, "Server: onHeadersComplete size={}", connection_, headers->size());
const char* method_string = http_method_str(static_cast<http_method>(parser_.method));
if (!handling_upgrade_ && headers->Connection()) {
// If we fail to sanitize the request, return a 400 to the client
if (!Utility::sanitizeConnectionHeader(*headers)) {
absl::string_view header_value = headers->getConnectionValue();
ENVOY_CONN_LOG(debug, "Invalid nominated headers in Connection: {}", connection_,
header_value);
error_code_ = Http::Code::BadRequest;
sendProtocolError(Http1ResponseCodeDetails::get().ConnectionHeaderSanitization);
throw CodecProtocolException("Invalid nominated headers in Connection.");
}
}
// Inform the response encoder about any HEAD method, so it can set content
// length and transfer encoding headers correctly.
active_request.response_encoder_.setIsResponseToHeadRequest(parser_.method == HTTP_HEAD);
active_request.response_encoder_.setIsResponseToConnectRequest(parser_.method == HTTP_CONNECT);
handlePath(*headers, parser_.method);
ASSERT(active_request.request_url_.empty());
headers->setMethod(method_string);
// Make sure the host is valid.
auto details = HeaderUtility::requestHeadersValid(*headers);
if (details.has_value()) {
sendProtocolError(details.value().get());
throw CodecProtocolException(
"http/1.1 protocol error: request headers failed spec compliance checks");
}
// Determine here whether we have a body or not. This uses the new RFC semantics where the
// presence of content-length or chunked transfer-encoding indicates a body vs. a particular
// method. If there is no body, we defer raising decodeHeaders() until the parser is flushed
// with message complete. This allows upper layers to behave like HTTP/2 and prevents a proxy
// scenario where the higher layers stream through and implicitly switch to chunked transfer
// encoding because end stream with zero body length has not yet been indicated.
if (parser_.flags & F_CHUNKED ||
(parser_.content_length > 0 && parser_.content_length != ULLONG_MAX) || handling_upgrade_) {
active_request.request_decoder_->decodeHeaders(std::move(headers), false);
// If the connection has been closed (or is closing) after decoding headers, pause the parser
// so we return control to the caller.
if (connection_.state() != Network::Connection::State::Open) {
http_parser_pause(&parser_, 1);
}
} else {
deferred_end_stream_headers_ = true;
}
}
return 0;
}
void ServerConnectionImpl::onMessageBegin() {
if (!resetStreamCalled()) {
ASSERT(!active_request_.has_value());
active_request_.emplace(*this, header_key_formatter_.get());
auto& active_request = active_request_.value();
active_request.request_decoder_ = &callbacks_.newStream(active_request.response_encoder_);
// Check for pipelined request flood as we prepare to accept a new request.
// Parse errors that happen prior to onMessageBegin result in stream termination, it is not
// possible to overflow output buffers with early parse errors.
doFloodProtectionChecks();
}
}
void ServerConnectionImpl::onUrl(const char* data, size_t length) {
if (active_request_.has_value()) {
active_request_.value().request_url_.append(data, length);
checkMaxHeadersSize();
}
}
void ServerConnectionImpl::onBody(Buffer::Instance& data) {
ASSERT(!deferred_end_stream_headers_);
if (active_request_.has_value()) {
ENVOY_CONN_LOG(trace, "body size={}", connection_, data.length());
active_request_.value().request_decoder_->decodeData(data, false);
}
}
void ServerConnectionImpl::onMessageComplete() {
ASSERT(!handling_upgrade_);
if (active_request_.has_value()) {
auto& active_request = active_request_.value();
if (active_request.request_decoder_) {
active_request.response_encoder_.readDisable(true);
}
active_request.remote_complete_ = true;
if (deferred_end_stream_headers_) {
active_request.request_decoder_->decodeHeaders(
std::move(absl::get<RequestHeaderMapPtr>(headers_or_trailers_)), true);
deferred_end_stream_headers_ = false;
} else if (processing_trailers_) {
active_request.request_decoder_->decodeTrailers(
std::move(absl::get<RequestTrailerMapPtr>(headers_or_trailers_)));
} else {
Buffer::OwnedImpl buffer;
active_request.request_decoder_->decodeData(buffer, true);
}
// Reset to ensure no information from one requests persists to the next.
headers_or_trailers_.emplace<RequestHeaderMapPtr>(nullptr);
}
// Always pause the parser so that the calling code can process 1 request at a time and apply
// back pressure. However this means that the calling code needs to detect if there is more data
// in the buffer and dispatch it again.
http_parser_pause(&parser_, 1);
}
void ServerConnectionImpl::onResetStream(StreamResetReason reason) {
active_request_.value().response_encoder_.runResetCallbacks(reason);
active_request_.reset();
}
void ServerConnectionImpl::sendProtocolErrorOld(absl::string_view details) {
if (active_request_.has_value()) {
active_request_.value().response_encoder_.setDetails(details);
}
// We do this here because we may get a protocol error before we have a logical stream. Higher
// layers can only operate on streams, so there is no coherent way to allow them to send an error
// "out of band." On one hand this is kind of a hack but on the other hand it normalizes HTTP/1.1
// to look more like HTTP/2 to higher layers.
if (!active_request_.has_value() ||
!active_request_.value().response_encoder_.startedResponse()) {
Buffer::OwnedImpl bad_request_response(
absl::StrCat("HTTP/1.1 ", error_code_, " ", CodeUtility::toString(error_code_),
"\r\ncontent-length: 0\r\nconnection: close\r\n\r\n"));
connection_.write(bad_request_response, false);
}
}
void ServerConnectionImpl::sendProtocolError(absl::string_view details) {
if (!Runtime::runtimeFeatureEnabled("envoy.reloadable_features.early_errors_via_hcm")) {
sendProtocolErrorOld(details);
return;
}
// We do this here because we may get a protocol error before we have a logical stream.
if (!active_request_.has_value()) {
onMessageBeginBase();
}
ASSERT(active_request_.has_value());
active_request_.value().response_encoder_.setDetails(details);
if (!active_request_.value().response_encoder_.startedResponse()) {
// Note that the correctness of is_grpc_request and is_head_request is best-effort.
// If headers have not been fully parsed they may not be inferred correctly.
bool is_grpc_request = false;
if (absl::holds_alternative<RequestHeaderMapPtr>(headers_or_trailers_) &&
absl::get<RequestHeaderMapPtr>(headers_or_trailers_) != nullptr) {
is_grpc_request =
Grpc::Common::isGrpcRequestHeaders(*absl::get<RequestHeaderMapPtr>(headers_or_trailers_));
}
active_request_->request_decoder_->sendLocalReply(is_grpc_request, error_code_,
CodeUtility::toString(error_code_), nullptr,
absl::nullopt, details);
return;
}
}
void ServerConnectionImpl::onAboveHighWatermark() {
if (active_request_.has_value()) {
active_request_.value().response_encoder_.runHighWatermarkCallbacks();
}
}
void ServerConnectionImpl::onBelowLowWatermark() {
if (active_request_.has_value()) {
active_request_.value().response_encoder_.runLowWatermarkCallbacks();
}
}
void ServerConnectionImpl::releaseOutboundResponse(
const Buffer::OwnedBufferFragmentImpl* fragment) {
ASSERT(outbound_responses_ >= 1);
--outbound_responses_;
delete fragment;
}
void ServerConnectionImpl::checkHeaderNameForUnderscores() {
if (headers_with_underscores_action_ != envoy::config::core::v3::HttpProtocolOptions::ALLOW &&
Http::HeaderUtility::headerNameContainsUnderscore(current_header_field_.getStringView())) {
if (headers_with_underscores_action_ ==
envoy::config::core::v3::HttpProtocolOptions::DROP_HEADER) {
ENVOY_CONN_LOG(debug, "Dropping header with invalid characters in its name: {}", connection_,
current_header_field_.getStringView());
stats_.dropped_headers_with_underscores_.inc();
current_header_field_.clear();
current_header_value_.clear();
} else {
ENVOY_CONN_LOG(debug, "Rejecting request due to header name with underscores: {}",
connection_, current_header_field_.getStringView());
error_code_ = Http::Code::BadRequest;
sendProtocolError(Http1ResponseCodeDetails::get().InvalidUnderscore);
stats_.requests_rejected_with_underscores_in_headers_.inc();
throw CodecProtocolException("http/1.1 protocol error: header name contains underscores");
}
}
}
ClientConnectionImpl::ClientConnectionImpl(Network::Connection& connection, CodecStats& stats,
ConnectionCallbacks&, const Http1Settings& settings,
const uint32_t max_response_headers_count)
: ConnectionImpl(connection, stats, settings, HTTP_RESPONSE, MAX_RESPONSE_HEADERS_KB,
max_response_headers_count, formatter(settings)) {}
bool ClientConnectionImpl::cannotHaveBody() {
if (pending_response_.has_value() && pending_response_.value().encoder_.headRequest()) {
ASSERT(!pending_response_done_);
return true;
} else if (parser_.status_code == 204 || parser_.status_code == 304 ||
(parser_.status_code >= 200 && parser_.content_length == 0 &&
!(parser_.flags & F_CHUNKED))) {
return true;
} else {
return false;
}
}
RequestEncoder& ClientConnectionImpl::newStream(ResponseDecoder& response_decoder) {
if (resetStreamCalled()) {
throw CodecClientException("cannot create new streams after calling reset");
}
// If reads were disabled due to flow control, we expect reads to always be enabled again before
// reusing this connection. This is done when the response is received.
ASSERT(connection_.readEnabled());
ASSERT(!pending_response_.has_value());
ASSERT(pending_response_done_);
pending_response_.emplace(*this, header_key_formatter_.get(), &response_decoder);
pending_response_done_ = false;
return pending_response_.value().encoder_;
}
int ClientConnectionImpl::onHeadersComplete() {
ENVOY_CONN_LOG(trace, "status_code {}", connection_, parser_.status_code);
// Handle the case where the client is closing a kept alive connection (by sending a 408
// with a 'Connection: close' header). In this case we just let response flush out followed
// by the remote close.
if (!pending_response_.has_value() && !resetStreamCalled()) {
throw PrematureResponseException(static_cast<Http::Code>(parser_.status_code));
} else if (pending_response_.has_value()) {
ASSERT(!pending_response_done_);
auto& headers = absl::get<ResponseHeaderMapPtr>(headers_or_trailers_);
ENVOY_CONN_LOG(trace, "Client: onHeadersComplete size={}", connection_, headers->size());
headers->setStatus(parser_.status_code);
if (parser_.status_code >= 200 && parser_.status_code < 300 &&
pending_response_.value().encoder_.connectRequest()) {
ENVOY_CONN_LOG(trace, "codec entering upgrade mode for CONNECT response.", connection_);
handling_upgrade_ = true;
// For responses to connect requests, do not accept the chunked
// encoding header: https://tools.ietf.org/html/rfc7231#section-4.3.6
if (headers->TransferEncoding() &&
absl::EqualsIgnoreCase(headers->TransferEncoding()->value().getStringView(),
Headers::get().TransferEncodingValues.Chunked)) {
sendProtocolError(Http1ResponseCodeDetails::get().InvalidTransferEncoding);
throw CodecProtocolException("http/1.1 protocol error: unsupported transfer encoding");
}
}
if (strict_1xx_and_204_headers_ && (parser_.status_code < 200 || parser_.status_code == 204)) {
if (headers->TransferEncoding()) {
sendProtocolError(Http1ResponseCodeDetails::get().TransferEncodingNotAllowed);
throw CodecProtocolException(
"http/1.1 protocol error: transfer encoding not allowed in 1xx or 204");
}
if (headers->ContentLength()) {
// Report a protocol error for non-zero Content-Length, but paper over zero Content-Length.
if (headers->ContentLength()->value().getStringView() != "0") {
sendProtocolError(Http1ResponseCodeDetails::get().ContentLengthNotAllowed);
throw CodecProtocolException(
"http/1.1 protocol error: content length not allowed in 1xx or 204");
}
headers->removeContentLength();
}
}
if (parser_.status_code == enumToInt(Http::Code::Continue)) {
pending_response_.value().decoder_->decode100ContinueHeaders(std::move(headers));
} else if (cannotHaveBody() && !handling_upgrade_) {
deferred_end_stream_headers_ = true;
} else {
pending_response_.value().decoder_->decodeHeaders(std::move(headers), false);
}
// http-parser treats 1xx headers as their own complete response. Swallow the spurious
// onMessageComplete and continue processing for purely informational headers.
// 101-SwitchingProtocols is exempt as all data after the header is proxied through after
// upgrading.
if (CodeUtility::is1xx(parser_.status_code) &&
parser_.status_code != enumToInt(Http::Code::SwitchingProtocols)) {
ignore_message_complete_for_1xx_ = true;
// Reset to ensure no information from the 1xx headers is used for the response headers.
headers_or_trailers_.emplace<ResponseHeaderMapPtr>(nullptr);
}
}
// Here we deal with cases where the response cannot have a body, but http_parser does not deal
// with it for us.
return cannotHaveBody() ? 1 : 0;
}
bool ClientConnectionImpl::upgradeAllowed() const {
if (pending_response_.has_value()) {
return pending_response_->encoder_.upgradeRequest();
}
return false;
}
void ClientConnectionImpl::onBody(Buffer::Instance& data) {
ASSERT(!deferred_end_stream_headers_);
if (pending_response_.has_value()) {
ASSERT(!pending_response_done_);
pending_response_.value().decoder_->decodeData(data, false);
}
}
void ClientConnectionImpl::onMessageComplete() {
ENVOY_CONN_LOG(trace, "message complete", connection_);
if (ignore_message_complete_for_1xx_) {
ignore_message_complete_for_1xx_ = false;
return;
}
if (pending_response_.has_value()) {
ASSERT(!pending_response_done_);
// After calling decodeData() with end stream set to true, we should no longer be able to reset.
PendingResponse& response = pending_response_.value();
// Encoder is used as part of decode* calls later in this function so pending_response_ can not
// be reset just yet. Preserve the state in pending_response_done_ instead.
pending_response_done_ = true;
if (deferred_end_stream_headers_) {
response.decoder_->decodeHeaders(
std::move(absl::get<ResponseHeaderMapPtr>(headers_or_trailers_)), true);
deferred_end_stream_headers_ = false;
} else if (processing_trailers_) {
response.decoder_->decodeTrailers(
std::move(absl::get<ResponseTrailerMapPtr>(headers_or_trailers_)));
} else {
Buffer::OwnedImpl buffer;
response.decoder_->decodeData(buffer, true);
}
// Reset to ensure no information from one requests persists to the next.
pending_response_.reset();
headers_or_trailers_.emplace<ResponseHeaderMapPtr>(nullptr);
}
}
void ClientConnectionImpl::onResetStream(StreamResetReason reason) {
// Only raise reset if we did not already dispatch a complete response.
if (pending_response_.has_value() && !pending_response_done_) {
pending_response_.value().encoder_.runResetCallbacks(reason);
pending_response_done_ = true;
pending_response_.reset();
}
}
void ClientConnectionImpl::sendProtocolError(absl::string_view details) {
if (pending_response_.has_value()) {
ASSERT(!pending_response_done_);
pending_response_.value().encoder_.setDetails(details);
}
}
void ClientConnectionImpl::onAboveHighWatermark() {
// This should never happen without an active stream/request.
pending_response_.value().encoder_.runHighWatermarkCallbacks();
}
void ClientConnectionImpl::onBelowLowWatermark() {
// This can get called without an active stream/request when the response completion causes us to
// close the connection, but in doing so go below low watermark.
if (pending_response_.has_value() && !pending_response_done_) {
pending_response_.value().encoder_.runLowWatermarkCallbacks();
}
}
} // namespace Http1
} // namespace Legacy
} // namespace Http
} // namespace Envoy
|
//===-- asan_globals_win.cpp ----------------------------------------------===//
//
// 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
//
//===----------------------------------------------------------------------===//
//
// Global registration code that is linked into every Windows DLL and EXE.
//
//===----------------------------------------------------------------------===//
#include "asan_interface_internal.h"
#if SANITIZER_WINDOWS
namespace __asan {
#pragma section(".ASAN$GA", read, write) // NOLINT
#pragma section(".ASAN$GZ", read, write) // NOLINT
extern "C" __declspec(allocate(".ASAN$GA"))
ALIGNED(sizeof(__asan_global)) __asan_global __asan_globals_start = {};
extern "C" __declspec(allocate(".ASAN$GZ"))
ALIGNED(sizeof(__asan_global)) __asan_global __asan_globals_end = {};
#pragma comment(linker, "/merge:.ASAN=.data")
static void call_on_globals(void (*hook)(__asan_global *, uptr)) {
__asan_global *start = &__asan_globals_start + 1;
__asan_global *end = &__asan_globals_end;
uptr bytediff = (uptr)end - (uptr)start;
if (bytediff % sizeof(__asan_global) != 0) {
#if defined(SANITIZER_DLL_THUNK) || defined(SANITIZER_DYNAMIC_RUNTIME_THUNK)
__debugbreak();
#else
CHECK("corrupt asan global array");
#endif
}
// We know end >= start because the linker sorts the portion after the dollar
// sign alphabetically.
uptr n = end - start;
hook(start, n);
}
static void register_dso_globals() {
call_on_globals(&__asan_register_globals);
}
static void unregister_dso_globals() {
call_on_globals(&__asan_unregister_globals);
}
// Register globals
#pragma section(".CRT$XCU", long, read) // NOLINT
#pragma section(".CRT$XTX", long, read) // NOLINT
extern "C" __declspec(allocate(".CRT$XCU"))
void (*const __asan_dso_reg_hook)() = ®ister_dso_globals;
extern "C" __declspec(allocate(".CRT$XTX"))
void (*const __asan_dso_unreg_hook)() = &unregister_dso_globals;
} // namespace __asan
#endif // SANITIZER_WINDOWS
|
/* STLSOFT:FILE_DEPRECATED */
#include <stlsoft/stlsoft.h>
#if _STLSOFT_VER >= 0x010a0200
# error This file is now obsolete. Instead include the precise header file that you require
#else
# ifdef STLSOFT_PPF_pragma_message_SUPPORT
# pragma message(__FILE__ "(" STLSOFT_STRINGIZE(__LINE__) "): This file is now obsolete and will be removed in a forthcoming version. Instead include the precise header file that you require")
# endif
# include <platformstl/exception/platformstl_exception.hpp>
# include <platformstl/exception/throw_policies.hpp>
#endif
/* ///////////////////////////// end of file //////////////////////////// */
|
// Copyright (c) 2012 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "chrome/browser/net/connection_tester.h"
#include "base/prefs/testing_pref_service.h"
#include "content/public/browser/cookie_store_factory.h"
#include "content/public/test/test_browser_thread.h"
#include "content/public/browser/cookie_store_factory.h"
#include "net/cert/mock_cert_verifier.h"
#include "net/dns/mock_host_resolver.h"
#include "net/ftp/ftp_network_layer.h"
#include "net/http/http_auth_handler_factory.h"
#include "net/http/http_network_layer.h"
#include "net/http/http_network_session.h"
#include "net/http/http_server_properties_impl.h"
#include "net/http/transport_security_state.h"
#include "net/proxy/proxy_config_service_fixed.h"
#include "net/proxy/proxy_service.h"
#include "net/ssl/ssl_config_service_defaults.h"
#include "net/test/spawned_test_server/spawned_test_server.h"
#include "net/url_request/url_request_context.h"
#include "net/url_request/url_request_test_util.h"
#include "testing/gtest/include/gtest/gtest.h"
#include "testing/platform_test.h"
using content::BrowserThread;
namespace {
// This is a testing delegate which simply counts how many times each of
// the delegate's methods were invoked.
class ConnectionTesterDelegate : public ConnectionTester::Delegate {
public:
ConnectionTesterDelegate()
: start_connection_test_suite_count_(0),
start_connection_test_experiment_count_(0),
completed_connection_test_experiment_count_(0),
completed_connection_test_suite_count_(0) {
}
void OnStartConnectionTestSuite() override {
start_connection_test_suite_count_++;
}
void OnStartConnectionTestExperiment(
const ConnectionTester::Experiment& experiment) override {
start_connection_test_experiment_count_++;
}
void OnCompletedConnectionTestExperiment(
const ConnectionTester::Experiment& experiment,
int result) override {
completed_connection_test_experiment_count_++;
}
void OnCompletedConnectionTestSuite() override {
completed_connection_test_suite_count_++;
base::MessageLoop::current()->Quit();
}
int start_connection_test_suite_count() const {
return start_connection_test_suite_count_;
}
int start_connection_test_experiment_count() const {
return start_connection_test_experiment_count_;
}
int completed_connection_test_experiment_count() const {
return completed_connection_test_experiment_count_;
}
int completed_connection_test_suite_count() const {
return completed_connection_test_suite_count_;
}
private:
int start_connection_test_suite_count_;
int start_connection_test_experiment_count_;
int completed_connection_test_experiment_count_;
int completed_connection_test_suite_count_;
};
// The test fixture is responsible for:
// - Making sure each test has an IO loop running
// - Catching any host resolve requests and mapping them to localhost
// (so the test doesn't use any external network dependencies).
class ConnectionTesterTest : public PlatformTest {
public:
ConnectionTesterTest()
: io_thread_(BrowserThread::IO, &message_loop_),
test_server_(net::SpawnedTestServer::TYPE_HTTP,
net::SpawnedTestServer::kLocalhost,
// Nothing is read in this directory.
base::FilePath(FILE_PATH_LITERAL("chrome"))) {
}
protected:
// Destroy last the MessageLoop last to give a chance for objects like
// ObserverListThreadSave to shut down properly. For example,
// SSLClientAuthCache calls RemoveObserver when destroyed, but if the
// MessageLoop is already destroyed, then the RemoveObserver will be a
// no-op, and the ObserverList will contain invalid entries.
base::MessageLoopForIO message_loop_;
content::TestBrowserThread io_thread_;
net::SpawnedTestServer test_server_;
net::TestURLRequestContext proxy_script_fetcher_context_;
ConnectionTesterDelegate test_delegate_;
};
TEST_F(ConnectionTesterTest, RunAllTests) {
ASSERT_TRUE(test_server_.Start());
ConnectionTester tester(&test_delegate_,
&proxy_script_fetcher_context_,
NULL);
// Start the test suite on URL "echoall".
// TODO(eroman): Is this URL right?
tester.RunAllTests(test_server_.GetURL("echoall"));
// Wait for all the tests to complete.
base::MessageLoop::current()->Run();
const int kNumExperiments =
ConnectionTester::PROXY_EXPERIMENT_COUNT *
ConnectionTester::HOST_RESOLVER_EXPERIMENT_COUNT;
EXPECT_EQ(1, test_delegate_.start_connection_test_suite_count());
EXPECT_EQ(kNumExperiments,
test_delegate_.start_connection_test_experiment_count());
EXPECT_EQ(kNumExperiments,
test_delegate_.completed_connection_test_experiment_count());
EXPECT_EQ(1, test_delegate_.completed_connection_test_suite_count());
}
TEST_F(ConnectionTesterTest, DeleteWhileInProgress) {
ASSERT_TRUE(test_server_.Start());
scoped_ptr<ConnectionTester> tester(
new ConnectionTester(&test_delegate_,
&proxy_script_fetcher_context_,
NULL));
// Start the test suite on URL "echoall".
// TODO(eroman): Is this URL right?
tester->RunAllTests(test_server_.GetURL("echoall"));
// Don't run the message loop at all. Otherwise the experiment's request may
// complete and post a task to run the next experiment before we quit the
// message loop.
EXPECT_EQ(1, test_delegate_.start_connection_test_suite_count());
EXPECT_EQ(1, test_delegate_.start_connection_test_experiment_count());
EXPECT_EQ(0, test_delegate_.completed_connection_test_experiment_count());
EXPECT_EQ(0, test_delegate_.completed_connection_test_suite_count());
// Delete the ConnectionTester while it is in progress.
tester.reset();
// Drain the tasks on the message loop.
//
// Note that we cannot simply stop the message loop, since that will delete
// any pending tasks instead of running them. This causes a problem with
// net::ClientSocketPoolBaseHelper, since the "Group" holds a pointer
// |backup_task| that it will try to deref during the destructor, but
// depending on the order that pending tasks were deleted in, it might
// already be invalid! See http://crbug.com/43291.
base::MessageLoop::current()->PostTask(FROM_HERE,
base::MessageLoop::QuitClosure());
base::MessageLoop::current()->Run();
}
} // namespace
|
//==============================================================================
// Copyright 2003 - 2012 LASMEA UMR 6602 CNRS/Univ. Clermont II
// Copyright 2009 - 2012 LRI UMR 8623 CNRS/Univ Paris Sud XI
//
// Distributed under the Boost Software License, Version 1.0.
// See accompanying file LICENSE.txt or copy at
// http://www.boost.org/LICENSE_1_0.txt
//==============================================================================
#ifndef NT2_LINALG_FUNCTIONS_FACTORIZATIONS_QR_HPP_INCLUDED
#define NT2_LINALG_FUNCTIONS_FACTORIZATIONS_QR_HPP_INCLUDED
#include <nt2/linalg/functions/qr.hpp>
#include <nt2/options.hpp>
#include <nt2/core/container/table/table.hpp>
#include <nt2/include/functions/issquare.hpp>
#include <nt2/linalg/functions/details/qr.hpp>
namespace nt2 { namespace ext
{
NT2_FUNCTOR_IMPLEMENTATION( nt2::tag::factorization::qr_, tag::cpu_
, (A0)(A1)
, ((ast_<A0, nt2::container::domain>))
(scalar_< type8_<A1> >)
)
{
typedef typename meta::strip<A0>::type base_t;
typedef typename base_t::value_type value_t;
typedef typename base_t::settings_type settings_t;
typedef details::qr_result< container::table<value_t,settings_t> > result_type;
BOOST_FORCEINLINE result_type operator()(A0 const& a0, A1 const& a1) const
{
result_type that(a0, a1);
return that;
}
};
NT2_FUNCTOR_IMPLEMENTATION( nt2::tag::factorization::qr_, tag::cpu_
, (A0)(A1)(IP)
, ((ast_<A0, nt2::container::domain>))
(scalar_< type8_<A1> >)
(unspecified_< IP >)
)
{
typedef details::qr_result<A0&> result_type;
BOOST_FORCEINLINE result_type
operator()(A0& a0, A1 const& a1 , IP const&) const
{
result_type that(a0, a1);
return that;
}
};
} }
#endif
|
// feat/sinusoid-detection-test.cc
// Copyright 2015 Johns Hopkins University (author: Daniel Povey)
// 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
//
// THIS CODE IS PROVIDED *AS IS* BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
// KIND, EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION ANY IMPLIED
// WARRANTIES OR CONDITIONS OF TITLE, FITNESS FOR A PARTICULAR PURPOSE,
// MERCHANTABLITY OR NON-INFRINGEMENT.
// See the Apache 2 License for the specific language governing permissions and
// limitations under the License.
#include <iostream>
#include "base/kaldi-math.h"
#include "feat/sinusoid-detection.h"
namespace kaldi {
// this function is used for testing AddSinusoid.
void AddSinusoidSimple(BaseFloat samp_freq,
const Sinusoid &sinusoid,
VectorBase<BaseFloat> *signal) {
for (int32 i = 0; i < signal->Dim(); i++)
(*signal)(i) += sinusoid.amplitude *
cos(M_2PI * sinusoid.freq / samp_freq * i + sinusoid.phase);
}
void UnitTestAddSinusoid() {
BaseFloat samp_freq = 560.1;
int32 length = 511;
Vector<BaseFloat> orig(length);
orig.SetRandn();
Vector<BaseFloat> orig2(orig);
Sinusoid sinusoid(49.20, 2.111, 1.5);
AddSinusoid(samp_freq, sinusoid, &orig);
AddSinusoidSimple(samp_freq, sinusoid, &orig2);
AssertEqual(orig, orig2);
}
void UnitTestQuadraticMaximizeEqualSpaced() {
for (int32 n = 0; n < 50; n++) {
// Let the cubic function be y = a x^2 + b x + c, and let
// y0,y1,y2 be its values evaluated at x = [0, 1, 2]; we
// want it evaluated at arbitrary x.
BaseFloat a = -0.5 + RandUniform(), b = -0.5 + RandUniform(), c = -0.5 + RandUniform();
BaseFloat y[3];
for (int32 i = 0; i < 3; i++) {
BaseFloat x = i;
y[i] = a * x * x + b * x + c;
}
BaseFloat x_max, y_max;
SinusoidDetector::QuadraticMaximizeEqualSpaced(y[0], y[1], y[2], &x_max, &y_max);
for (int32 m = 0; m <= 10; m++) {
BaseFloat x_test = 0.1 * m;
BaseFloat y_test = a * x_test * x_test + b * x_test + c;
KALDI_ASSERT(y_test <= y_max + 1.0e-05);
}
}
}
void UnitTestQuadraticMaximize() {
for (int32 n = 0; n < 50; n++) {
// Let the cubic function be y = a x^2 + b x + c, and let
// y0,y1,y2 be its values evaluated at x = [0, 1, 2]; we
// want it evaluated at arbitrary x.
BaseFloat a = -0.5 + RandUniform(), b = -0.5 + RandUniform(), c = -0.5 + RandUniform(),
x = 0.1 + RandUniform() * 0.98;
BaseFloat y[3];
for (int32 i = 0; i < 3; i++) {
BaseFloat this_x;
if (i == 0) { this_x = 0.0; }
else if (i == 1) { this_x = x; }
else { this_x = 1.0; }
y[i] = a * this_x * this_x + b * this_x + c;
}
BaseFloat x_max, y_max;
SinusoidDetector::QuadraticMaximize(x, y[0], y[1], y[2], &x_max, &y_max);
for (int32 m = 0; m <= 10; m++) {
BaseFloat x_test = 0.1 * m;
BaseFloat y_test = a * x_test * x_test + b * x_test + c;
if (n < 100 && m == 5) {
KALDI_VLOG(2) << "Checking y_test <= y_max: "
<< y_test << " <= " << y_max << " [x_max = "
<< x_max << "]";
KALDI_ASSERT(y_test <= y_max + 1.0e-05);
}
}
}
}
void UnitTestSinusoidDetector() {
BaseFloat samp_freq = 4000 + (rand() % 2000);
int32 num_samp = 128 + rand() % 400;
SinusoidDetector detector(samp_freq, num_samp);
for (int32 i = 0; i < 40; i++) {
Vector<BaseFloat> signal(num_samp);
// Sinusoid ref_sinusoid(1.3, 312.5, M_PI * 0.0);
// Sinusoid ref_sinusoid(1.3, 324.125, M_PI * 0.5);
BaseFloat nyquist = samp_freq * 0.5;
BaseFloat freq = nyquist * RandUniform();
BaseFloat amplitude = RandUniform();
BaseFloat phase = M_2PI * RandUniform();
Sinusoid ref_sinusoid(amplitude, freq, phase);
AddSinusoid(samp_freq, ref_sinusoid, &signal);
BaseFloat orig_energy = VecVec(signal, signal);
KALDI_LOG << "Real frequency is " << freq << ", amplitude "
<< amplitude << ", phase " << phase << ", samp-freq "
<< samp_freq;
KALDI_LOG << "Total energy of signal (with sinusoid) is " << orig_energy;
Sinusoid sinusoid;
BaseFloat min_energy = 0.0;
BaseFloat energy = detector.DetectSinusoid(min_energy,
signal, &sinusoid);
Vector<BaseFloat> new_signal(signal);
sinusoid.phase += M_PI; // Reverse the phase.
AddSinusoid(samp_freq, sinusoid, &new_signal);
BaseFloat delta_energy = VecVec(signal, signal) -
VecVec(new_signal, new_signal);
KALDI_LOG << "Projected delta energy = " << energy
<< " and observed was " << delta_energy;
BaseFloat remaining_energy = VecVec(new_signal, new_signal);
if (remaining_energy > 0.01 * orig_energy) {
KALDI_WARN << "Energy remaining is " << remaining_energy
<< " vs. original " << orig_energy;
BaseFloat relative_freq = freq / nyquist;
BaseFloat inv_num_samp = 1.0 / num_samp;
// We only tolerate this kind of error for very ridiculous frequency,
// close to zero or the Nyquist.
KALDI_ASSERT(relative_freq < inv_num_samp ||
relative_freq > 1.0 - inv_num_samp);
}
}
}
// as UnitTestSinusoidDetector(), but doing it in noisy signals.
void UnitTestSinusoidDetectorNoisy() {
BaseFloat samp_freq = 4000 + (rand() % 2000);
int32 num_samp = 128 + rand() % 400;
SinusoidDetector detector(samp_freq, num_samp);
for (int32 i = 0; i < 40; i++) {
Vector<BaseFloat> signal(num_samp);
signal.SetRandn();
BaseFloat rand_energy = VecVec(signal, signal);
// Sinusoid ref_sinusoid(1.3, 312.5, M_PI * 0.0);
// Sinusoid ref_sinusoid(1.3, 324.125, M_PI * 0.5);
BaseFloat nyquist = samp_freq * 0.5;
BaseFloat freq = nyquist * RandUniform();
BaseFloat amplitude = 10.0 * RandUniform();
BaseFloat phase = M_2PI * RandUniform();
Sinusoid ref_sinusoid(amplitude, freq, phase);
AddSinusoid(samp_freq, ref_sinusoid, &signal);
BaseFloat tot_energy = VecVec(signal, signal);
KALDI_LOG << "Real frequency is " << freq << ", amplitude "
<< amplitude << ", phase " << phase << ", samp-freq "
<< samp_freq;
KALDI_LOG << "Total energy of signal (with noise + sinusoid) is " << tot_energy;
Sinusoid sinusoid;
BaseFloat min_energy = 0.0;
BaseFloat energy = detector.DetectSinusoid(min_energy,
signal, &sinusoid);
Vector<BaseFloat> new_signal(signal);
sinusoid.phase += M_PI; // reverse the phase.
AddSinusoid(samp_freq, sinusoid, &new_signal);
BaseFloat delta_energy = VecVec(signal, signal) -
VecVec(new_signal, new_signal);
KALDI_LOG << "Projected delta energy = " << energy
<< " and observed was " << delta_energy;
BaseFloat min_energy_diff = 0.99 * (tot_energy - rand_energy);
if (delta_energy < min_energy_diff) {
KALDI_WARN << "Energy reduction is " << delta_energy
<< " vs. expected " << (tot_energy - rand_energy);
BaseFloat relative_freq = freq / nyquist;
BaseFloat inv_num_samp = 1.0 / num_samp;
// We only tolerate this kind of error for very ridiculous frequency,
// close to zero or the Nyquist.
KALDI_ASSERT(relative_freq < inv_num_samp ||
relative_freq > 1.0 - inv_num_samp);
}
}
}
void AddFreqToSignal(BaseFloat base_freq,
BaseFloat samp_freq,
BaseFloat tolerance,
BaseFloat gain,
VectorBase<BaseFloat> *signal) {
BaseFloat error_scale = (2 * RandUniform() - 1) * tolerance;
BaseFloat freq = base_freq * (1.0 + error_scale);
KALDI_VLOG(3) << "base-freq = " << base_freq << ", factor = " << error_scale;
for (int32 i = 0; i < signal->Dim(); i++)
(*signal)(i) += gain * sin(i * 2.0 * 3.14159 * freq / samp_freq);
}
void GenerateDtmfTestCase(
BaseFloat sampling_rate,
Vector<BaseFloat> *signal,
std::vector<MultiSinusoidDetectorOutput> *ref_output) {
// the "ref_output" should correlate with the first of each run of frames with the same label.
BaseFloat min_duration_secs = 0.04; // min duration of dtmf or non-tone segments.
BaseFloat min_dialtone_duration_secs = 0.1;
BaseFloat frequency_tolerance = 0.035;
BaseFloat dialtone_frequency_tolerance = 0.4 * (440.0 - 425.0) / 440.0;
int32 num_events = 2 * (5 + rand() % 5) + 1; // odd number.
int32 tot_signal_dim = 0;
ref_output->resize(num_events);
std::vector<Vector<BaseFloat> > all_signals(num_events);
for (int32 i = 0; i < num_events; i++) {
MultiSinusoidDetectorOutput &this_output = (*ref_output)[i];
Vector<BaseFloat> &this_signal = all_signals[i];
BaseFloat duration_secs = min_duration_secs * (1 + rand() % 3);
int32 num_samp = sampling_rate * duration_secs;
tot_signal_dim += num_samp;
this_signal.Resize(num_samp);
this_signal.SetRandn();
if (i % 2 == 0); // do nothing;
else if (rand() % 2 == 0 && duration_secs >= min_dialtone_duration_secs) {
// dialtone.
BaseFloat freq;
if (rand() % 3 == 0) { freq = 350; }
else if (rand() % 2 == 0) { freq = 440; }
else { freq = 425; }
BaseFloat gain = 10.0 * (1.0 + rand() % 2);
AddFreqToSignal(freq, sampling_rate, dialtone_frequency_tolerance,
gain, &(this_signal));
this_output.freq1 = freq;
} else {
// dtmf. use a subset of tones as examples.
BaseFloat freq1, freq2;
char c;
if (rand() % 4 == 0) {
c = '8'; freq1 = 852; freq2 = 1336;
} else if (rand() % 3 == 0) {
c = '0'; freq1 = 941; freq2 = 1336;
} else if (rand() % 2 == 0) {
c = '#'; freq1 = 941; freq2 = 1477;
} else {
c = '1'; freq1 = 697; freq2 = 1209;
}
BaseFloat base_gain = 10.0 * (1.0 + (rand() % 3)),
gain_factor = 1.0 + 0.1 * (-2 + rand() % 5),
gain1 = base_gain, gain2 = gain_factor * base_gain;
AddFreqToSignal(freq1, sampling_rate, frequency_tolerance, gain1,
&(this_signal));
AddFreqToSignal(freq2, sampling_rate, frequency_tolerance, gain2,
&(this_signal));
this_output.freq1 = freq1;
this_output.freq2 = freq2;
}
}
signal->Resize(tot_signal_dim);
int32 signal_offset = 0;
for (int32 i = 0; i < num_events; i++) {
int32 this_dim = all_signals[i].Dim();
signal->Range(signal_offset, this_dim).CopyFromVec(all_signals[i]);
signal_offset += this_dim;
}
}
/*
// Just a basic test to check that it produces output.
void UnitTestToneDetection() {
BaseFloat samp_freq = (rand() % 2) == 0 ? 8000 : 16000;
ToneDetectionConfig config;
int32 num_frames = 100 + (rand() % 100);
int32 frame_length = static_cast<int32>(samp_freq * config.frame_length_secs);
int32 num_samples = frame_length * num_frames + rand() % frame_length;
Vector<BaseFloat> signal(num_samples);
signal.SetRandn();
ToneDetector tone_detector(config, samp_freq);
int32 signal_offset = 0;
std::vector<ToneDetectorOutput*> tone_detector_output;
while (signal_offset < num_samples) {
int32 signal_remaining = num_samples - signal_offset,
chunk_size = std::min<int32>((rand() % 200) + 100,
signal_remaining);
SubVector<BaseFloat> signal_part(signal, signal_offset, chunk_size);
tone_detector.AcceptWaveform(signal_part);
signal_offset += chunk_size;
if (signal_offset == num_samples)
tone_detector.WaveformFinished();
while (!tone_detector.Done() &&
(rand() % 2 == 0 || signal_offset == num_samples)) {
ToneDetectorOutput *output = new ToneDetectorOutput();
tone_detector.GetNextFrame(output);
tone_detector_output.push_back(output);
}
}
KALDI_ASSERT(signal_offset == num_samples);
Vector<BaseFloat> signal2(signal.Dim());
signal_offset = 0;
for (int32 i = 0; i < tone_detector_output.size(); i++) {
ToneDetectorOutput *output = tone_detector_output[i];
signal2.Range(signal_offset,
output->signal.Dim()).CopyFromVec(output->signal);
signal_offset += output->signal.Dim();
if (output->frame_type != 'n') {
KALDI_ERR << "Frame " << i << " badly classified, should be 'n', is: "
<< output->frame_type;
}
delete output;
}
KALDI_ASSERT(signal_offset == num_samples &&
signal.ApproxEqual(signal2, 1.0e-10));
}
std::ostringstream & operator << (std::ostringstream &ostr,
const ToneDetectorOutput &output) {
ostr << output.frame_type;
if (output.frame_type == 'd')
ostr << output.dialtone_freq;
ostr << ' ';
return ostr;
}
*/
// This version of the unit-test generates a signal that has tones in it, and
// runs the detection on that signal.
void UnitTestToneDetection2() {
BaseFloat samp_freq = (rand() % 2) == 0 ? 8000 : 16000;
Vector<BaseFloat> signal;
std::vector<MultiSinusoidDetectorOutput> ref_output;
GenerateDtmfTestCase(samp_freq, &signal, &ref_output);
MultiSinusoidDetectorConfig config;
int32 num_samples = signal.Dim();
KALDI_ASSERT(num_samples > 0);
MultiSinusoidDetector multi_sinusoid_detector(config, samp_freq);
int32 signal_offset = 0;
std::vector<MultiSinusoidDetectorOutput*> multi_sinusoid_detector_output;
while (signal_offset < num_samples) {
int32 signal_remaining = num_samples - signal_offset,
chunk_size = std::min<int32>((rand() % 200) + 100,
signal_remaining);
SubVector<BaseFloat> signal_part(signal, signal_offset, chunk_size);
multi_sinusoid_detector.AcceptWaveform(signal_part);
signal_offset += chunk_size;
if (signal_offset == num_samples)
multi_sinusoid_detector.WaveformFinished();
while (!multi_sinusoid_detector.Done() &&
(rand() % 2 == 0 || signal_offset == num_samples)) {
MultiSinusoidDetectorOutput *output = new MultiSinusoidDetectorOutput();
multi_sinusoid_detector.GetNextFrame(output);
multi_sinusoid_detector_output.push_back(output);
}
}
KALDI_ASSERT(signal_offset == num_samples);
// std::ostringstream str_ref, str_hyp;
//for (size_t i = 0; i < ref_output.size(); i++)
// str_ref << ref_output[i];
for (size_t i = 0; i < multi_sinusoid_detector_output.size(); i++) {
MultiSinusoidDetectorOutput *output = multi_sinusoid_detector_output[i];
KALDI_LOG << "tot-energy = " << output->tot_energy
<< ", freq1 " << output->freq1 << ", energy1 " << output->energy1
<< ", freq2 " << output->freq2 << ", energy2 " << output->energy2;
delete output;
}
}
} // namespace kaldi
int main() {
using namespace kaldi;
SetVerboseLevel(4);
UnitTestToneDetection2();
UnitTestAddSinusoid();
UnitTestQuadraticMaximizeEqualSpaced();
UnitTestQuadraticMaximize();
for (int32 i = 0; i < 10; i++) {
UnitTestSinusoidDetector();
UnitTestSinusoidDetectorNoisy();
}
}
|
#ifndef _MATMUL_HPP
#define _MATMUL_HPP
//Copyright (c) 2018, Sanaxn
//All rights reserved.
//Minimum size for applying GPGPU
#define MIN_SIZE_APPLYING_GPGPU 2048/9
#define MIN_SIZE_APPLYING_GPGPU2 2048*2
#define MIN_SIZE_APPLYING_GPGPU3 2048/9
#include "matrix/multiplication.hpp"
#include "matrix/hadamard.hpp"
#include "matrix/transpose.hpp"
#include "matrix/plus_eqd.hpp"
#include "matrix/plus.hpp"
#include "matrix/scalar_prod.hpp"
#include "matrix/prod.hpp"
#include "matrix/zeros.hpp"
#include "matrix/ones.hpp"
#endif
|
#include <cpp_api.h>
typedef struct Pair {
float value;
} Pair;
void Pairs_add_component_pair() {
flecs::world ecs;
auto entity = ecs.entity()
.add<Pair, Position>();
test_assert(entity.id() != 0);
test_assert((entity.has<Pair, Position>()));
test_assert((!entity.has<Position, Pair>()));
test_str(entity.type().str().c_str(), "(Pair,Position)");
}
void Pairs_add_tag_pair() {
flecs::world ecs;
ecs.component<Position>();
auto Pair = ecs.entity("Pair");
auto entity = ecs.entity()
.add_w_object<Position>(Pair);
test_assert(entity.id() != 0);
test_assert(entity.has_w_object<Position>(Pair));
test_assert(!entity.has<Position>(Pair));
test_str(entity.type().str().c_str(), "(Pair,Position)");
}
void Pairs_add_tag_pair_to_tag() {
flecs::world ecs;
auto Tag = ecs.entity("Tag");
auto Pair = ecs.entity("Pair");
auto entity = ecs.entity()
.add(Pair, Tag);
test_assert(entity.id() != 0);
test_assert(entity.has(Pair, Tag));
test_str(entity.type().str().c_str(), "(Pair,Tag)");
}
void Pairs_remove_component_pair() {
flecs::world ecs;
ecs.component<Position>();
ecs.component<Pair>();
auto entity = ecs.entity()
.add<Pair, Position>();
test_assert(entity.id() != 0);
test_assert((entity.has<Pair, Position>()));
test_assert((!entity.has<Position, Pair>()));
test_str(entity.type().str().c_str(), "(Pair,Position)");
entity.remove<Position, Pair>();
test_assert(!(entity.has<Position, Pair>()));
}
void Pairs_remove_tag_pair() {
flecs::world ecs;
ecs.component<Position>();
auto Pair = ecs.entity("Pair");
auto entity = ecs.entity()
.add_w_object<Position>(Pair);
test_assert(entity.id() != 0);
test_assert(entity.has_w_object<Position>(Pair));
test_assert(!entity.has<Position>(Pair));
test_str(entity.type().str().c_str(), "(Pair,Position)");
entity.remove<Position>(Pair);
test_assert(!entity.has<Position>(Pair));
}
void Pairs_remove_tag_pair_to_tag() {
flecs::world ecs;
auto Tag = ecs.entity("Tag");
auto Pair = ecs.entity("Pair");
auto entity = ecs.entity()
.add(Pair, Tag);
test_assert(entity.id() != 0);
test_assert(entity.has(Pair, Tag));
test_str(entity.type().str().c_str(), "(Pair,Tag)");
entity.remove(Tag, Pair);
test_assert(!entity.has(Tag, Pair));
}
void Pairs_set_component_pair() {
flecs::world ecs;
auto entity = ecs.entity()
.set<Pair, Position>({10});
test_assert(entity.id() != 0);
test_assert((entity.has<Pair, Position>()));
test_assert((!entity.has<Position, Pair>()));
test_str(entity.type().str().c_str(), "(Pair,Position)");
const Pair *t = entity.get<Pair, Position>();
test_int(t->value, 10);
}
void Pairs_set_tag_pair() {
flecs::world ecs;
auto Pair = ecs.entity("Pair");
auto entity = ecs.entity()
.set_w_object<Position>(Pair, {10, 20});
test_assert(entity.id() != 0);
test_assert(entity.has_w_object<Position>(Pair));
test_str(entity.type().str().c_str(), "(Pair,Position)");
const Position *p = entity.get_w_object<Position>(Pair);
test_assert(p != NULL);
test_int(p->x, 10);
test_int(p->y, 20);
}
void Pairs_system_1_pair_instance() {
flecs::world ecs;
ecs.entity()
.set<Pair, Position>({10});
int invoke_count = 0;
int entity_count = 0;
int trait_value = 0;
ecs.system<>(nullptr, "(Pair, *)")
.iter([&](flecs::iter it) {
flecs::column<Pair> tr(it, 1);
invoke_count ++;
for (auto i : it) {
entity_count ++;
trait_value = tr[i].value;
}
});
ecs.progress();
test_int(invoke_count, 1);
test_int(entity_count, 1);
test_int(trait_value, 10);
}
void Pairs_system_2_pair_instances() {
flecs::world ecs;
ecs.entity()
.set<Pair, Position>({10})
.set<Pair, Velocity>({20});
int invoke_count = 0;
int entity_count = 0;
int trait_value = 0;
ecs.system<>(nullptr, "(Pair, *)")
.iter([&](flecs::iter it) {
flecs::column<Pair> tr(it, 1);
invoke_count ++;
for (auto i : it) {
entity_count ++;
trait_value += tr[i].value;
}
});
ecs.progress();
test_int(invoke_count, 2);
test_int(entity_count, 2);
test_int(trait_value, 30);
}
void Pairs_override_pair() {
flecs::world ecs;
auto base = ecs.entity()
.set<Pair, Position>({10});
auto instance = ecs.entity()
.add(flecs::IsA, base);
test_assert((instance.has<Pair, Position>()));
const Pair *t = instance.get<Pair, Position>();
test_int(t->value, 10);
const Pair *t_2 = base.get<Pair, Position>();
test_assert(t == t_2);
instance.add<Pair, Position>();
t = instance.get<Pair, Position>();
test_int(t->value, 10);
test_assert(t != t_2);
instance.remove<Pair, Position>();
t = instance.get<Pair, Position>();
test_int(t->value, 10);
test_assert(t == t_2);
}
void Pairs_override_tag_pair() {
flecs::world ecs;
auto Pair = ecs.entity();
auto base = ecs.entity()
.set_w_object<Position>(Pair, {10, 20});
auto instance = ecs.entity()
.add(flecs::IsA, base);
test_assert((instance.has_w_object<Position>(Pair)));
const Position *t = instance.get_w_object<Position>(Pair);
test_int(t->x, 10);
test_int(t->y, 20);
const Position *t_2 = base.get_w_object<Position>(Pair);
test_assert(t == t_2);
instance.add_w_object<Position>(Pair);
t = instance.get_w_object<Position>(Pair);
test_int(t->x, 10);
test_int(t->y, 20);
test_assert(t != t_2);
instance.remove_w_object<Position>(Pair);
t = instance.get_w_object<Position>(Pair);
test_int(t->x, 10);
test_int(t->y, 20);
test_assert(t == t_2);
}
void Pairs_get_mut_pair() {
flecs::world ecs;
auto e = ecs.entity();
bool added = false;
Pair *t = e.get_mut<Pair, Position>(&added);
test_assert(t != NULL);
test_bool(added, true);
t->value = 10;
const Pair *t_2 = e.get<Pair, Position>();
test_assert(t == t_2);
test_int(t->value, 10);
}
void Pairs_get_mut_pair_existing() {
flecs::world ecs;
auto e = ecs.entity()
.set<Pair, Position>({20});
bool added = false;
Pair *t = e.get_mut<Pair, Position>(&added);
test_assert(t != NULL);
test_bool(added, false);
test_int(t->value, 20);
t->value = 10;
const Pair *t_2 = e.get<Pair, Position>();
test_assert(t == t_2);
test_int(t->value, 10);
}
void Pairs_get_mut_pair_tag() {
flecs::world ecs;
auto Pair = ecs.entity();
auto e = ecs.entity();
bool added = false;
Position *p = e.get_mut_w_object<Position>(Pair, &added);
test_assert(p != NULL);
test_bool(added, true);
p->x = 10;
p->y = 20;
const Position *p_2 = e.get_w_object<Position>(Pair);
test_assert(p == p_2);
test_int(p->x, 10);
test_int(p->y, 20);
}
void Pairs_get_mut_pair_tag_existing() {
flecs::world ecs;
auto Pair = ecs.entity();
auto e = ecs.entity()
.set_w_object<Position>(Pair, {10, 20});
bool added = false;
Position *p = e.get_mut_w_object<Position>(Pair, &added);
test_assert(p != NULL);
test_bool(added, false);
test_int(p->x, 10);
test_int(p->y, 20);
const Position *p_2 = e.get_w_object<Position>(Pair);
test_assert(p == p_2);
test_int(p->x, 10);
test_int(p->y, 20);
}
void Pairs_get_relation_from_id() {
flecs::world ecs;
auto rel = ecs.entity();
auto obj = ecs.entity();
flecs::id pair(rel, obj);
test_assert(pair.relation() == rel);
test_assert(pair.object() != rel);
test_assert(pair.relation().is_alive());
test_assert(pair.relation().is_valid());
}
void Pairs_get_w_object_from_id() {
flecs::world ecs;
auto rel = ecs.entity();
auto obj = ecs.entity();
flecs::id pair(rel, obj);
test_assert(pair.relation() != obj);
test_assert(pair.object() == obj);
test_assert(pair.object().is_alive());
test_assert(pair.object().is_valid());
}
void Pairs_get_recycled_relation_from_id() {
flecs::world ecs;
auto rel = ecs.entity();
auto obj = ecs.entity();
rel.destruct();
obj.destruct();
rel = ecs.entity();
obj = ecs.entity();
// Make sure ids are recycled
test_assert((uint32_t)rel.id() != rel.id());
test_assert((uint32_t)obj.id() != obj.id());
flecs::id pair(rel, obj);
test_assert(pair.relation() == rel);
test_assert(pair.object() != rel);
test_assert(pair.relation().is_alive());
test_assert(pair.relation().is_valid());
}
void Pairs_get_recycled_object_from_id() {
flecs::world ecs;
auto rel = ecs.entity();
auto obj = ecs.entity();
rel.destruct();
obj.destruct();
rel = ecs.entity();
obj = ecs.entity();
// Make sure ids are recycled
test_assert((uint32_t)rel.id() != rel.id());
test_assert((uint32_t)obj.id() != obj.id());
flecs::id pair(rel, obj);
test_assert(pair.relation() == rel);
test_assert(pair.object() != rel);
test_assert(pair.object().is_alive());
test_assert(pair.object().is_valid());
}
void Pairs_each() {
flecs::world ecs;
auto p_1 = ecs.entity();
auto p_2 = ecs.entity();
auto e = ecs.entity()
.add(p_1)
.add(p_2);
int32_t count = 0;
e.each([&](flecs::id e) {
if (count == 0) {
test_assert(e == p_1);
} else if (count == 1) {
test_assert(e == p_2);
} else {
test_assert(false);
}
count ++;
});
test_int(count, 2);
}
void Pairs_each_pair() {
flecs::world ecs;
auto pair = ecs.component<Pair>();
auto pos = ecs.component<Position>();
auto vel = ecs.component<Velocity>();
auto e = ecs.entity()
.add<Pair, Position>()
.add<Pair, Velocity>();
int32_t count = 0;
e.each(pair, [&](flecs::entity object) {
if (count == 0) {
test_assert(object == pos);
} else if (count == 1) {
test_assert(object == vel);
} else {
test_assert(false);
}
count ++;
});
test_int(count, 2);
}
void Pairs_each_pair_by_type() {
flecs::world ecs;
auto pos = ecs.component<Position>();
auto vel = ecs.component<Velocity>();
auto e = ecs.entity()
.add<Pair, Position>()
.add<Pair, Velocity>();
int32_t count = 0;
e.each<Pair>([&](flecs::entity object) {
if (count == 0) {
test_assert(object == pos);
} else if (count == 1) {
test_assert(object == vel);
} else {
test_assert(false);
}
count ++;
});
test_int(count, 2);
}
void Pairs_each_pair_w_childof() {
flecs::world ecs;
auto p_1 = ecs.entity();
auto p_2 = ecs.entity();
auto e = ecs.entity()
.child_of(p_1)
.child_of(p_2);
int32_t count = 0;
e.each(flecs::ChildOf, [&](flecs::entity object) {
if (count == 0) {
test_assert(object == p_1);
} else if (count == 1) {
test_assert(object == p_2);
} else {
test_assert(false);
}
count ++;
});
test_int(count, 2);
}
void Pairs_each_pair_w_recycled_rel() {
flecs::world ecs;
auto e_1 = ecs.entity();
auto e_2 = ecs.entity();
ecs.entity().destruct(); // force recycling
auto pair = ecs.entity();
test_assert((uint32_t)pair.id() != pair.id()); // ensure recycled
auto e = ecs.entity()
.add(pair, e_1)
.add(pair, e_2);
int32_t count = 0;
// should work correctly
e.each(pair, [&](flecs::entity object) {
if (count == 0) {
test_assert(object == e_1);
} else if (count == 1) {
test_assert(object == e_2);
} else {
test_assert(false);
}
count ++;
});
test_int(count, 2);
}
void Pairs_each_pair_w_recycled_obj() {
flecs::world ecs;
auto pair = ecs.component<Pair>();
ecs.entity().destruct(); // force recycling
auto e_1 = ecs.entity();
test_assert((uint32_t)e_1.id() != e_1.id()); // ensure recycled
ecs.entity().destruct();
auto e_2 = ecs.entity();
test_assert((uint32_t)e_2.id() != e_2.id());
auto e = ecs.entity()
.add<Pair>(e_1)
.add<Pair>(e_2);
int32_t count = 0;
// should work correctly
e.each(pair, [&](flecs::entity object) {
if (count == 0) {
test_assert(object == e_1);
} else if (count == 1) {
test_assert(object == e_2);
} else {
test_assert(false);
}
count ++;
});
test_int(count, 2);
}
void Pairs_match_pair() {
flecs::world ecs;
auto Eats = ecs.entity();
auto Dislikes = ecs.entity();
auto Apples = ecs.entity();
auto Pears = ecs.entity();
auto Bananas = ecs.entity();
auto e = ecs.entity()
.set<Position>({10, 20}) // should not be matched
.add(Eats, Apples)
.add(Eats, Pears)
.add(Dislikes, Bananas);
int32_t count = 0;
e.each(Eats, Apples,
[&](flecs::id id) {
test_assert(id.relation() == Eats);
test_assert(id.object() == Apples);
count ++;
});
test_int(count, 1);
}
void Pairs_match_pair_obj_wildcard() {
flecs::world ecs;
auto Eats = ecs.entity();
auto Dislikes = ecs.entity();
auto Apples = ecs.entity();
auto Pears = ecs.entity();
auto Bananas = ecs.entity();
auto e = ecs.entity()
.set<Position>({10, 20}) // should not be matched
.add(Eats, Apples)
.add(Eats, Pears)
.add(Dislikes, Bananas);
int32_t count = 0;
e.each(Eats, flecs::Wildcard,
[&](flecs::id id) {
test_assert(id.relation() == Eats);
test_assert(id.object() == Apples || id.object() == Pears);
count ++;
});
test_int(count, 2);
}
void Pairs_match_pair_rel_wildcard() {
flecs::world ecs;
auto Eats = ecs.entity();
auto Dislikes = ecs.entity();
auto Apples = ecs.entity();
auto Pears = ecs.entity();
auto Bananas = ecs.entity();
auto e = ecs.entity()
.set<Position>({10, 20}) // should not be matched
.add(Eats, Apples)
.add(Eats, Pears)
.add(Dislikes, Bananas);
int32_t count = 0;
e.each(flecs::Wildcard, Pears,
[&](flecs::id id) {
test_assert(id.relation() == Eats);
test_assert(id.object() == Pears);
count ++;
});
test_int(count, 1);
}
void Pairs_match_pair_both_wildcard() {
flecs::world ecs;
auto Eats = ecs.entity();
auto Dislikes = ecs.entity();
auto Apples = ecs.entity();
auto Pears = ecs.entity();
auto Bananas = ecs.entity();
auto e = ecs.entity()
.set<Position>({10, 20}) // should not be matched
.add(Eats, Apples)
.add(Eats, Pears)
.add(Dislikes, Bananas);
int32_t count = 0;
e.each(flecs::Wildcard, flecs::Wildcard,
[&](flecs::id id) {
count ++;
});
test_int(count, 3);
}
void Pairs_has_tag_w_object() {
flecs::world ecs;
struct Likes { };
auto Bob = ecs.entity();
auto e = ecs.entity().add<Likes>(Bob);
test_assert(e.has<Likes>(Bob));
}
void Pairs_has_w_object_tag() {
flecs::world ecs;
struct Bob { };
auto Likes = ecs.entity();
auto e = ecs.entity().add_w_object<Bob>(Likes);
test_assert(e.has_w_object<Bob>(Likes));
}
struct Eats { int amount; };
struct Apples { };
struct Pears { };
using EatsApples = flecs::pair<Eats, Apples>;
using EatsPears = flecs::pair<Eats, Pears>;
void Pairs_add_pair_type() {
flecs::world ecs;
auto e = ecs.entity().add<EatsApples>();
test_assert((e.has<Eats, Apples>()));
test_assert((e.has<EatsApples>()));
}
void Pairs_remove_pair_type() {
flecs::world ecs;
auto e = ecs.entity().add<EatsApples>();
test_assert((e.has<Eats, Apples>()));
test_assert((e.has<EatsApples>()));
e.remove<EatsApples>();
test_assert(!(e.has<Eats, Apples>()));
test_assert(!(e.has<EatsApples>()));
}
void Pairs_set_pair_type() {
flecs::world ecs;
auto e = ecs.entity().set<EatsApples>({10});
test_assert((e.has<Eats, Apples>()));
test_assert((e.has<EatsApples>()));
const Eats *ptr = e.get<EatsApples>();
test_int(ptr->amount, 10);
test_assert((ptr == e.get<Eats, Apples>()));
}
void Pairs_has_pair_type() {
flecs::world ecs;
auto e = ecs.entity().add<Eats, Apples>();
test_assert((e.has<Eats, Apples>()));
test_assert((e.has<EatsApples>()));
}
void Pairs_get_1_pair_arg() {
flecs::world ecs;
auto e = ecs.entity().set<EatsApples>({10});
test_assert((e.has<Eats, Apples>()));
test_assert((e.has<EatsApples>()));
test_bool(e.get([](const EatsApples& a) {
test_int(a->amount, 10);
}), true);
}
void Pairs_get_2_pair_arg() {
flecs::world ecs;
auto e = ecs.entity()
.set<EatsApples>({10})
.set<EatsPears>({20});
test_assert((e.has<Eats, Apples>()));
test_assert((e.has<Eats, Pears>()));
test_assert((e.has<EatsApples>()));
test_assert((e.has<EatsPears>()));
test_bool(e.get([](const EatsApples& a, const EatsPears& p) {
test_int(a->amount, 10);
test_int(p->amount, 20);
}), true);
}
void Pairs_set_1_pair_arg() {
flecs::world ecs;
auto e = ecs.entity()
.set([](EatsApples&& a) {
a->amount = 10;
});
auto eats = e.get<EatsApples>();
test_int(eats->amount, 10);
}
void Pairs_set_2_pair_arg() {
flecs::world ecs;
auto e = ecs.entity()
.set([](EatsApples&& a, EatsPears&& p) {
a->amount = 10;
p->amount = 20;
});
auto eats = e.get<EatsApples>();
test_int(eats->amount, 10);
eats = e.get<EatsPears>();
test_int(eats->amount, 20);
}
void Pairs_get_inline_pair_type() {
flecs::world ecs;
auto e = ecs.entity().set<EatsApples>({10});
test_assert((e.has<Eats, Apples>()));
test_assert((e.has<EatsApples>()));
test_bool(e.get([](const flecs::pair<Eats, Apples>& a) {
test_int(a->amount, 10);
}), true);
}
void Pairs_set_inline_pair_type() {
flecs::world ecs;
auto e = ecs.entity()
.set([](flecs::pair<Eats, Apples>&& a) {
a->amount = 10;
});
auto eats = e.get<EatsApples>();
test_int(eats->amount, 10);
}
void Pairs_get_pair_type_object() {
flecs::world ecs;
auto e = ecs.entity().set_w_object<Apples, Eats>({10});
test_assert((e.has<Apples, Eats>()));
test_bool(e.get([](const flecs::pair_object<Apples, Eats>& a) {
test_int(a->amount, 10);
}), true);
}
void Pairs_set_pair_type_object() {
flecs::world ecs;
auto e = ecs.entity()
.set([](flecs::pair_object<Apples, Eats>&& a) {
a->amount = 10;
});
auto eats = e.get_w_object<Apples, Eats>();
test_int(eats->amount, 10);
}
struct Event {
const char *value;
};
struct Begin { };
struct End { };
using BeginEvent = flecs::pair<Begin, Event>;
using EndEvent = flecs::pair<End, Event>;
void Pairs_set_get_w_object_variants() {
flecs::world ecs;
auto e1 = ecs.entity().set_w_object<Begin, Event>({"Big Bang"});
test_assert((e1.has<Begin, Event>()));
const Event* v = e1.get_w_object<Begin, Event>();
test_assert(v != NULL);
test_str(v->value, "Big Bang");
auto e2 = ecs.entity().set<Begin, Event>({"Big Bang"});
test_assert((e2.has<Begin, Event>()));
v = e2.get<Begin, Event>();
test_assert(v != NULL);
test_str(v->value, "Big Bang");
auto e3 = ecs.entity().set<flecs::pair<Begin, Event>>({"Big Bang"});
test_assert((e3.has<flecs::pair<Begin, Event>>()));
v = e3.get<flecs::pair<Begin, Event>>();
test_assert(v != NULL);
test_str(v->value, "Big Bang");
auto e4 = ecs.entity().set<BeginEvent>({"Big Bang"});
test_assert((e4.has<BeginEvent>()));
v = e4.get<BeginEvent>();
test_assert(v != NULL);
test_str(v->value, "Big Bang");
}
|
#include "guinsoodb/function/scalar/nested_functions.hpp"
#include "guinsoodb/execution/expression_executor.hpp"
#include "guinsoodb/planner/expression/bound_function_expression.hpp"
#include "guinsoodb/common/string_util.hpp"
namespace guinsoodb {
struct StructExtractBindData : public FunctionData {
StructExtractBindData(string key, idx_t index, LogicalType type) : key(move(key)), index(index), type(move(type)) {
}
string key;
idx_t index;
LogicalType type;
public:
unique_ptr<FunctionData> Copy() override {
return make_unique<StructExtractBindData>(key, index, type);
}
bool Equals(FunctionData &other_p) override {
auto &other = (StructExtractBindData &)other_p;
return key == other.key && index == other.index && type == other.type;
}
};
static void StructExtractFunction(DataChunk &args, ExpressionState &state, Vector &result) {
auto &func_expr = (BoundFunctionExpression &)state.expr;
auto &info = (StructExtractBindData &)*func_expr.bind_info;
// this should be guaranteed by the binder
auto &vec = args.data[0];
vec.Verify(args.size());
if (vec.GetVectorType() == VectorType::DICTIONARY_VECTOR) {
auto &child = DictionaryVector::Child(vec);
auto &dict_sel = DictionaryVector::SelVector(vec);
auto &children = StructVector::GetEntries(child);
if (info.index >= children.size()) {
throw Exception("Not enough struct entries for struct_extract");
}
auto &struct_child = children[info.index];
if (struct_child.first != info.key || struct_child.second->GetType() != info.type) {
throw Exception("Struct key or type mismatch");
}
result.Slice(*struct_child.second, dict_sel, args.size());
} else {
auto &children = StructVector::GetEntries(vec);
if (info.index >= children.size()) {
throw Exception("Not enough struct entries for struct_extract");
}
auto &struct_child = children[info.index];
if (struct_child.first != info.key || struct_child.second->GetType() != info.type) {
throw Exception("Struct key or type mismatch");
}
result.Reference(*struct_child.second);
}
result.Verify(args.size());
}
static unique_ptr<FunctionData> StructExtractBind(ClientContext &context, ScalarFunction &bound_function,
vector<unique_ptr<Expression>> &arguments) {
auto &struct_children = arguments[0]->return_type.child_types();
if (struct_children.empty()) {
throw Exception("Can't extract something from an empty struct");
}
auto &key_child = arguments[1];
if (key_child->return_type.id() != LogicalTypeId::VARCHAR ||
key_child->return_type.id() != LogicalTypeId::VARCHAR || !key_child->IsFoldable()) {
throw Exception("Key name for struct_extract needs to be a constant string");
}
Value key_val = ExpressionExecutor::EvaluateScalar(*key_child.get());
D_ASSERT(key_val.type().id() == LogicalTypeId::VARCHAR);
if (key_val.is_null || key_val.str_value.length() < 1) {
throw Exception("Key name for struct_extract needs to be neither NULL nor empty");
}
string key = StringUtil::Lower(key_val.str_value);
LogicalType return_type;
idx_t key_index = 0;
bool found_key = false;
for (size_t i = 0; i < struct_children.size(); i++) {
auto &child = struct_children[i];
if (child.first == key) {
found_key = true;
key_index = i;
return_type = child.second;
break;
}
}
if (!found_key) {
throw Exception("Could not find key in struct");
}
bound_function.return_type = return_type;
bound_function.arguments[0] = arguments[0]->return_type;
return make_unique<StructExtractBindData>(key, key_index, return_type);
}
ScalarFunction StructExtractFun::GetFunction() {
return ScalarFunction("struct_extract", {LogicalType::STRUCT, LogicalType::VARCHAR}, LogicalType::ANY,
StructExtractFunction, false, StructExtractBind);
}
void StructExtractFun::RegisterFunction(BuiltinFunctions &set) {
// the arguments and return types are actually set in the binder function
auto fun = GetFunction();
set.AddFunction(fun);
}
} // namespace guinsoodb
|
// Problem Description
// Given an integer A.
// Compute and return the square root of A.
// If A is not a perfect square, return floor(sqrt(A)).
// DO NOT USE SQRT FUNCTION FROM STANDARD LIBRARY.
// NOTE: Do not use sort function from standard library. Users are expected to solve this in O(log(A)) time.
// Input Format
// The first and only argument given is the integer A.
// Output Format
// Return floor(sqrt(A))
// Example Input
// Input 1:
// 11
// Input 2:
// 9
// Example Output
// Output 1:
// 3
// Output 2:
// 3
// Example Explanation
// Explanation:
// When A = 11 , square root of A = 3.316. It is not a perfect square so we return
// the floor which is 3.
// When A = 9 which is a perfect square of 3, so we return 3.
int Solution::sqrt(int A)
{
if(A == 0) return 0;
int start = 1, end = A, ans = 1;
while(start <= end){
int mid = (start + end) >> 1;
if(mid <= (A/mid)){ // mid * mid <= A (here mid * mid could potentially give an overflow so divide it)
ans = mid;
start = mid + 1;
}
else
end = mid - 1;
}
return ans;
}
|
// Autogenerated from CppHeaderCreator on 7/27/2020 3:09:42 PM
// Created by Sc2ad
// =========================================================================
#pragma once
#pragma pack(push, 8)
// Begin includes
#include "utils/typedefs.h"
// Including type: System.Attribute
#include "System/Attribute.hpp"
#include "utils/il2cpp-utils.hpp"
// Completed includes
// Begin forward declares
// Completed forward declares
// Type namespace: System.Reflection
namespace System::Reflection {
// Autogenerated type: System.Reflection.AssemblyKeyFileAttribute
class AssemblyKeyFileAttribute : public System::Attribute {
public:
// private System.String m_keyFile
// Offset: 0x10
::Il2CppString* m_keyFile;
// public System.Void .ctor(System.String keyFile)
// Offset: 0x134CCC4
static AssemblyKeyFileAttribute* New_ctor(::Il2CppString* keyFile);
}; // System.Reflection.AssemblyKeyFileAttribute
}
DEFINE_IL2CPP_ARG_TYPE(System::Reflection::AssemblyKeyFileAttribute*, "System.Reflection", "AssemblyKeyFileAttribute");
#pragma pack(pop)
|
/**
* MIT License
*
* Copyright (c) 2018-2019 Kravchenko Artyom
*
* 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 "../AppService.h"
#include "WifiService.h"
WifiService::WifiService() {
}
void WifiService::init() {
String ssid = App->getSettingsService()->getWifiAPSSID();
String password = App->getSettingsService()->getWifiAPPassword();
if (ssid != "unknown" && password != "unknown") {
this->startClientMode(&ssid, &password);
} else {
this->startAPMode();
}
}
void WifiService::update() {
this->checkWifiStatus();
this->reconnectToWifiIfNeeded();
}
bool WifiService::startClientMode(String* ssid, String* password) {
App->getWifi()->begin(ssid->c_str(), password->c_str());
App->getSerial()->println("");
int numberOfAttempts = 0;
while (App->getWifi()->status() != WL_CONNECTED) {
numberOfAttempts++;
delay(500);
App->getSerial()->print(".");
if (numberOfAttempts > 20) {
break;
}
}
if (App->getWifi()->status() == WL_CONNECTED) {
App->getSerial()->println("");
App->getSerial()->print("Connected to ");
App->getSerial()->println(*ssid);
App->getSerial()->print("IP address: ");
App->getSerial()->println(App->getWifi()->localIP());
_wifiLose = false;
return true;
} else {
App->getSerial()->println("");
App->getSerial()->print("Cant connect to access point ");
App->getSerial()->println(*ssid);
App->getSerial()->println("Trying later.");
_wifiLose = true;
return false;
}
}
void WifiService::startAPMode() {
App->getSerial()->println("Start in access point mode");
App->getSerial()->print("SSID: ");
App->getSerial()->println(_ap_ssid);
App->getSerial()->print("Password: ");
App->getSerial()->println(_ap_password);
App->getWifi()->softAP(_ap_ssid, _ap_password);
App->getSerial()->println();
App->getSerial()->print("IP address: ");
App->getSerial()->println(App->getWifi()->softAPIP());
}
void WifiService::checkWifiStatus()
{
if (App->getWifi()->status() != WL_CONNECTED && !_wifiLose) {
App->getSerial()->println("Disconnected from wifi");
_wifiLose = true;
} else if (WiFi.status() == WL_CONNECTED && _wifiLose) {
App->getSerial()->println("Restored wifi connection");
App->getSerial()->print("IP address: ");
App->getSerial()->println(App->getWifi()->localIP());
_wifiLose = false;
}
}
void WifiService::reconnectToWifiIfNeeded() {
if (_wifiLose) {
if ((millis() - _lastReconnect) >= RECONNECT_INTERVAL) {
App->getSerial()->println("Trying reconnect to wifi access point.");
App->getWifi()->reconnect();
_lastReconnect = millis();
}
}
}
|
#pragma once
#include <string>
#include <unordered_map>
#include <cstdint>
std::unordered_map<uint32_t, uint32_t> Assemble(std::string assembly);
|
#include <iostream>
#include <string>
#include <vector>
#include "FWCore/ParameterSet/interface/ParameterSet.h"
#include "FWCore/Framework/interface/Frameworkfwd.h"
#include "FWCore/Framework/interface/EDAnalyzer.h"
#include "FWCore/Framework/interface/Event.h"
#include "FWCore/Framework/interface/EventSetup.h"
#include "FWCore/Framework/interface/ESTransientHandle.h"
#include "FWCore/Framework/interface/ESHandle.h"
#include "FWCore/Framework/interface/MakerMacros.h"
#include "DetectorDescription/Core/interface/DDCompactView.h"
#include "Geometry/Records/interface/IdealGeometryRecord.h"
#include "Geometry/HGCalCommonData/interface/FastTimeDDDConstants.h"
#include "Geometry/CaloTopology/interface/FastTimeTopology.h"
#include "DataFormats/ForwardDetId/interface/HGCEEDetId.h"
#include "DataFormats/ForwardDetId/interface/HGCHEDetId.h"
class FastTimeTopologyTester : public edm::EDAnalyzer {
public:
explicit FastTimeTopologyTester(const edm::ParameterSet& );
~FastTimeTopologyTester() override;
void analyze(const edm::Event&, const edm::EventSetup& ) override;
void doTest(const FastTimeTopology& topology);
private:
// ----------member data ---------------------------
};
FastTimeTopologyTester::FastTimeTopologyTester(const edm::ParameterSet& ) {}
FastTimeTopologyTester::~FastTimeTopologyTester() {}
void FastTimeTopologyTester::analyze(const edm::Event& ,
const edm::EventSetup& iSetup ) {
edm::ESHandle<FastTimeTopology> topo;
iSetup.get<IdealGeometryRecord>().get("FastTimeBarrel",topo);
if (topo.isValid()) doTest(*topo);
else std::cout << "Cannot get a valid FastTimeTopology Object for FastTimeBarrel\n";
}
void FastTimeTopologyTester::doTest(const FastTimeTopology& topology) {
for (int izz=0; izz<=1; izz++) {
int iz = (2*izz-1);
for (int eta=1; eta<=265; ++eta) {
for (int phi=1; phi<=720; ++phi) {
const FastTimeDetId id(1,eta,phi,iz);
if (topology.valid(id)) {
std::cout << "Neighbours for Tower " << id << std::endl;
std::vector<DetId> idE = topology.east(id);
std::vector<DetId> idW = topology.west(id);
std::vector<DetId> idN = topology.north(id);
std::vector<DetId> idS = topology.south(id);
std::cout << " " << idE.size() << " sets along East:";
for (auto & i : idE)
std::cout << " " << (FastTimeDetId)(i());
std::cout << std::endl;
std::cout << " " << idW.size() << " sets along West:";
for (auto & i : idW)
std::cout << " " << (FastTimeDetId)(i());
std::cout << std::endl;
std::cout << " " << idN.size() << " sets along North:";
for (auto & i : idN)
std::cout << " " << (FastTimeDetId)(i());
std::cout << std::endl;
std::cout << " " << idS.size() << " sets along South:";
for (auto & i : idS)
std::cout << " " << (FastTimeDetId)(i());
std::cout << std::endl;
}
phi += 10;
}
eta += 5;
}
}
}
//define this as a plug-in
DEFINE_FWK_MODULE(FastTimeTopologyTester);
|
/*
findfile.cpp
Поиск (Alt-F7)
*/
/*
Copyright © 1996 Eugene Roshal
Copyright © 2000 Far Group
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 name of the authors may not be used to endorse or promote products
derived from this software without specific prior written permission.
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.
*/
// BUGBUG
#include "platform.headers.hpp"
// Self:
#include "findfile.hpp"
// Internal:
#include "flink.hpp"
#include "keys.hpp"
#include "ctrlobj.hpp"
#include "dialog.hpp"
#include "filepanels.hpp"
#include "panel.hpp"
#include "fileview.hpp"
#include "fileedit.hpp"
#include "filelist.hpp"
#include "cmdline.hpp"
#include "namelist.hpp"
#include "scantree.hpp"
#include "manager.hpp"
#include "filemasks.hpp"
#include "filefilter.hpp"
#include "encoding.hpp"
#include "taskbar.hpp"
#include "interf.hpp"
#include "message.hpp"
#include "delete.hpp"
#include "datetime.hpp"
#include "pathmix.hpp"
#include "strmix.hpp"
#include "mix.hpp"
#include "constitle.hpp"
#include "uuids.far.dialogs.hpp"
#include "console.hpp"
#include "wakeful.hpp"
#include "panelmix.hpp"
#include "keyboard.hpp"
#include "plugins.hpp"
#include "lang.hpp"
#include "filestr.hpp"
#include "panelctype.hpp"
#include "filetype.hpp"
#include "diskmenu.hpp"
#include "string_utils.hpp"
#include "vmenu.hpp"
#include "exception_handler.hpp"
#include "drivemix.hpp"
#include "global.hpp"
#include "cvtname.hpp"
#include "log.hpp"
#include "stddlg.hpp"
// Platform:
#include "platform.concurrency.hpp"
#include "platform.env.hpp"
#include "platform.fs.hpp"
// Common:
#include "common/bytes_view.hpp"
#include "common/enum_tokens.hpp"
#include "common/scope_exit.hpp"
// External:
#include "format.hpp"
//----------------------------------------------------------------------------
namespace
{
const auto DM_REFRESH = DM_USER + 1;
// Список архивов. Если файл найден в архиве, то FindList->ArcIndex указывает сюда.
struct ArcListItem
{
MOVE_CONSTRUCTIBLE(ArcListItem);
ArcListItem() = default;
string strArcName;
plugin_panel* hPlugin; // Plugin handle
unsigned long long Flags; // OpenPanelInfo.Flags
string strRootPath; // Root path in plugin after opening.
};
// Список найденных файлов. Индекс из списка хранится в меню.
struct FindListItem
{
MOVE_CONSTRUCTIBLE(FindListItem);
FindListItem() = default;
os::fs::find_data FindData;
ArcListItem* Arc{};
DWORD Used;
UserDataItem UserData;
};
namespace messages
{
struct menu_data
{
MOVE_CONSTRUCTIBLE(menu_data);
menu_data(string_view FullName, const os::fs::find_data& FindData, UserDataItem const& UserData, ArcListItem* Arc):
m_FindData(FindData),
m_FullName(FullName),
m_UserData(UserData),
m_Arc(Arc)
{}
os::fs::find_data m_FindData;
string m_FullName;
UserDataItem m_UserData{};
ArcListItem* m_Arc{};
};
struct push {};
struct pop {};
struct status
{
string Value;
};
struct percent
{
unsigned Value;
};
}
using message = std::variant<
messages::menu_data,
messages::push,
messages::pop,
messages::status,
messages::percent
>;
}
class InterThreadData;
// BUGBUG Cleanup
class FindFiles: noncopyable
{
public:
FindFiles();
~FindFiles();
const std::unique_ptr<filemasks>& GetFileMask() const { return FileMaskForFindFile; }
const std::unique_ptr<multifilter>& GetFilter() const { return Filter; }
static bool IsWordDiv(wchar_t symbol);
// BUGBUG
void AddMenuRecord(Dialog* Dlg, string_view FullName, const os::fs::find_data& FindData, UserDataItem const& UserData, ArcListItem* Arc);
std::unique_ptr<InterThreadData> itd;
os::synced_queue<message> m_Messages;
std::queue<message> m_ExtractedMessages;
string m_Status;
unsigned m_Percent{};
// BUGBUG
[[nodiscard]]
auto ScopedLock()
{
return make_raii_wrapper<
&os::critical_section::lock,
&os::critical_section::unlock
>(&PluginCS);
}
private:
string &PrepareDriveNameStr(string &strSearchFromRoot) const;
void AdvancedDialog() const;
intptr_t MainDlgProc(Dialog* Dlg, intptr_t Msg, intptr_t Param1, void* Param2);
intptr_t FindDlgProc(Dialog* Dlg, intptr_t Msg, intptr_t Param1, void* Param2);
void OpenFile(const string& strSearchFileName, int OpenKey, const FindListItem* FindItem, Dialog* Dlg) const;
bool FindFilesProcess();
void ProcessMessage(message& Message);
void SetPluginDirectory(string_view DirName, const plugin_panel* hPlugin, bool UpdatePanel, const UserDataItem *UserData);
bool GetPluginFile(struct ArcListItem const* ArcItem, const os::fs::find_data& FindData, const string& DestPath, string &strResultName, const UserDataItem* UserData);
void stop_and_discard(Dialog* Dlg);
FindListItem& AddFindListItem(const os::fs::find_data& FindData, UserDataItem const& UserData);
void ClearFindList();
static intptr_t AdvancedDlgProc(Dialog* Dlg, intptr_t Msg, intptr_t Param1, void* Param2);
// BUGBUG
bool AnySetFindList{};
bool CmpCase{};
bool WholeWords{};
bool SearchInArchives{};
bool SearchHex{};
bool NotContaining{};
bool UseFilter{};
bool FindFoldersChanged{};
bool SearchFromChanged{};
bool FindPositionChanged{};
bool Finalized{};
bool PluginMode{};
FINDAREA SearchMode{ FINDAREA_ALL };
int favoriteCodePages{};
uintptr_t CodePage{ CP_DEFAULT };
struct FindListItem* FindExitItem{};
string strFindMask;
string strFindStr;
std::unique_ptr<filemasks> FileMaskForFindFile;
std::unique_ptr<multifilter> Filter;
std::unique_ptr<delayed_deleter> m_DelayedDeleter;
int m_FileCount{};
int m_DirCount{};
int m_LastFoundNumber{};
os::critical_section PluginCS;
// BUGBUG
class background_searcher* m_Searcher{};
std::exception_ptr m_ExceptionPtr;
std::stack<string> m_LastDir;
string m_LastDirName;
Dialog* m_ResultsDialogPtr{};
bool m_EmptyArc{};
time_check m_TimeCheck{ time_check::mode::immediate };
os::concurrency::timer m_UpdateTimer;
std::list<FindListItem> m_FindList;
};
// TODO BUGBUG DELETE THIS
class InterThreadData
{
private:
mutable os::critical_section DataCS;
std::list<ArcListItem> ArcList;
public:
InterThreadData() {Init();}
~InterThreadData() { ClearAllLists(); }
void Init()
{
SCOPED_ACTION(std::lock_guard)(DataCS);
ArcList.clear();
}
void ClearAllLists()
{
SCOPED_ACTION(std::lock_guard)(DataCS);
ArcList.clear();
}
ArcListItem& AddArcListItem(string_view const ArcName, plugin_panel* const hPlugin, unsigned long long const Flags, string_view const RootPath)
{
SCOPED_ACTION(std::lock_guard)(DataCS);
ArcListItem NewItem;
NewItem.strArcName = ArcName;
NewItem.hPlugin = hPlugin;
NewItem.Flags = Flags;
NewItem.strRootPath = RootPath;
AddEndSlash(NewItem.strRootPath);
ArcList.emplace_back(std::move(NewItem));
return ArcList.back();
}
};
enum
{
FIND_EXIT_NONE,
FIND_EXIT_SEARCHAGAIN,
FIND_EXIT_GOTO,
FIND_EXIT_PANEL
};
enum ADVANCEDDLG
{
AD_DOUBLEBOX,
AD_TEXT_SEARCHFIRST,
AD_EDIT_SEARCHFIRST,
AD_SEPARATOR1,
AD_TEXT_COLUMNSFORMAT,
AD_EDIT_COLUMNSFORMAT,
AD_TEXT_COLUMNSWIDTH,
AD_EDIT_COLUMNSWIDTH,
AD_SEPARATOR2,
AD_BUTTON_OK,
AD_BUTTON_CANCEL,
AD_COUNT
};
enum FINDASKDLG
{
FAD_DOUBLEBOX,
FAD_TEXT_MASK,
FAD_EDIT_MASK,
FAD_SEPARATOR0,
FAD_TEXT_TEXTHEX,
FAD_EDIT_TEXT,
FAD_EDIT_HEX,
FAD_TEXT_CP,
FAD_COMBOBOX_CP,
FAD_SEPARATOR1,
FAD_CHECKBOX_CASE,
FAD_CHECKBOX_WHOLEWORDS,
FAD_CHECKBOX_HEX,
FAD_CHECKBOX_NOTCONTAINING,
FAD_CHECKBOX_ARC,
FAD_CHECKBOX_DIRS,
FAD_CHECKBOX_LINKS,
FAD_CHECKBOX_STREAMS,
FAD_SEPARATOR_2,
FAD_SEPARATOR_3,
FAD_TEXT_WHERE,
FAD_COMBOBOX_WHERE,
FAD_CHECKBOX_FILTER,
FAD_SEPARATOR_4,
FAD_BUTTON_FIND,
FAD_BUTTON_DRIVE,
FAD_BUTTON_FILTER,
FAD_BUTTON_ADVANCED,
FAD_BUTTON_CANCEL,
FAD_COUNT
};
enum FINDDLG
{
FD_DOUBLEBOX,
FD_LISTBOX,
FD_SEPARATOR1,
FD_TEXT_STATUS,
FD_TEXT_STATUS_PERCENTS,
FD_SEPARATOR2,
FD_BUTTON_NEW,
FD_BUTTON_GOTO,
FD_BUTTON_VIEW,
FD_BUTTON_PANEL,
FD_BUTTON_STOP,
FD_COUNT
};
class background_searcher: noncopyable
{
public:
background_searcher(
FindFiles* Owner,
string FindString,
FINDAREA SearchMode,
ArcListItem* FindFileArcItem,
uintptr_t CodePage,
unsigned long long SearchInFirst,
bool CmpCase,
bool WholeWords,
bool SearchInArchives,
bool SearchHex,
bool NotContaining,
bool UseFilter,
bool PluginMode
);
void Search();
void Pause() const { PauseEvent.reset(); }
void Resume() const { PauseEvent.set(); }
void Stop() const { PauseEvent.set(); StopEvent.set(); }
bool Stopped() const { return StopEvent.is_signaled(); }
bool Finished() const { return m_Finished || m_ExceptionPtr; }
auto ExceptionPtr() const { return m_ExceptionPtr; }
auto IsRegularException() const { return m_IsRegularException; }
private:
void InitInFileSearch();
void ReleaseInFileSearch();
bool LookForString(string_view FileName);
bool IsFileIncluded(PluginPanelItem* FileItem, string_view FullName, os::fs::attributes FileAttr, string_view DisplayName);
void DoPrepareFileList();
void DoPreparePluginListImpl();
void DoPreparePluginList();
void ArchiveSearch(string_view ArcName);
void DoScanTree(string_view strRoot);
void ScanPluginTree(plugin_panel* hPlugin, unsigned long long Flags, int& RecurseLevel);
void AddMenuRecord(string_view FullName, PluginPanelItem& FindData) const;
FindFiles* const m_Owner;
const string m_EventName;
std::vector<std::byte> readBufferA;
std::vector<wchar_t> readBuffer;
bytes hexFindString;
struct CodePageInfo;
std::list<CodePageInfo> m_CodePages;
string strPluginSearchPath;
bool m_Autodetection;
const string strFindStr;
const FINDAREA SearchMode;
ArcListItem* m_FindFileArcItem;
const uintptr_t CodePage;
size_t m_MaxCharSize{};
const unsigned long long SearchInFirst;
const bool CmpCase;
const bool WholeWords;
const bool SearchInArchives;
const bool SearchHex;
const bool NotContaining;
const bool UseFilter;
const bool m_PluginMode;
os::event PauseEvent;
os::event StopEvent;
std::atomic_bool m_Finished{};
std::exception_ptr m_ExceptionPtr;
bool m_IsRegularException{};
searchers m_TextSearchers;
i_searcher const* m_TextSearcher;
using hex_searcher = std::boyer_moore_horspool_searcher<bytes::const_iterator>;
std::optional<hex_searcher> m_HexSearcher;
std::optional<taskbar::indeterminate> m_TaskbarProgress{ std::in_place };
};
struct background_searcher::CodePageInfo
{
explicit CodePageInfo(uintptr_t CodePage):
CodePage(CodePage)
{
}
uintptr_t CodePage;
size_t MaxCharSize{};
wchar_t LastSymbol{};
bool WordFound{};
void initialize()
{
if (IsUnicodeCodePage(CodePage))
MaxCharSize = 2;
else
{
CPINFO cpi;
if (!GetCPInfo(CodePage, &cpi))
cpi.MaxCharSize = 0; //Считаем, что ошибка и потом такие таблицы в поиске пропускаем
MaxCharSize = cpi.MaxCharSize;
}
LastSymbol = 0;
WordFound = false;
}
};
void background_searcher::InitInFileSearch()
{
if (strFindStr.empty())
return;
// Инициализируем буферы чтения из файла
const size_t readBufferSize = 65536;
readBufferA.resize(readBufferSize);
readBuffer.resize(readBufferSize);
if (!SearchHex)
{
m_TextSearcher = &init_searcher(m_TextSearchers, CmpCase, strFindStr, false);
// Формируем список кодовых страниц
if (CodePage == CP_ALL)
{
// Проверяем наличие выбранных страниц символов
const auto CpEnum = codepages::GetFavoritesEnumerator();
const auto hasSelected = std::any_of(CONST_RANGE(CpEnum, i) { return i.second & CPST_FIND; });
if (hasSelected)
{
m_CodePages.clear();
}
else
{
// Добавляем стандартные таблицы символов
const uintptr_t Predefined[] = { encoding::codepage::oem(), encoding::codepage::ansi(), CP_UTF8, CP_UNICODE, CP_REVERSEBOM };
m_CodePages.insert(m_CodePages.end(), ALL_CONST_RANGE(Predefined));
}
// Добавляем избранные таблицы символов
for (const auto& [Name, Value]: CpEnum)
{
if (Value & (hasSelected? CPST_FIND : CPST_FAVORITE))
{
// Проверяем дубли
// TODO: P1091R3
if (hasSelected || !std::any_of(ALL_CONST_RANGE(m_CodePages), [&Name = Name](const CodePageInfo& cp) { return cp.CodePage == Name; }))
m_CodePages.emplace_back(Name);
}
}
}
else
{
m_CodePages.emplace_back(CodePage);
m_Autodetection = CodePage == CP_DEFAULT;
}
for (auto& i: m_CodePages)
{
i.initialize();
m_MaxCharSize = std::max(m_MaxCharSize, i.MaxCharSize);
}
}
else
{
// Формируем hex-строку для поиска
hexFindString = HexStringToBlob(strFindStr, 0);
// Инициализируем данные для аглоритма поиска
m_HexSearcher.emplace(ALL_CONST_RANGE(hexFindString));
}
}
void background_searcher::ReleaseInFileSearch()
{
clear_and_shrink(readBufferA);
clear_and_shrink(readBuffer);
hexFindString = {};
m_CodePages.clear();
}
string& FindFiles::PrepareDriveNameStr(string &strSearchFromRoot) const
{
auto strCurDir = GetPathRoot(Global->CtrlObject->CmdLine()->GetCurDir());
DeleteEndSlash(strCurDir);
if (
strCurDir.empty()||
(Global->CtrlObject->Cp()->ActivePanel()->GetMode() == panel_mode::PLUGIN_PANEL && Global->CtrlObject->Cp()->ActivePanel()->IsVisible())
)
{
strSearchFromRoot = msg(lng::MSearchFromRootFolder);
}
else
{
strSearchFromRoot = concat(msg(lng::MSearchFromRootOfDrive), L' ', strCurDir);
}
return strSearchFromRoot;
}
// Проверяем символ на принадлежность разделителям слов
bool FindFiles::IsWordDiv(const wchar_t symbol)
{
// Также разделителем является конец строки и пробельные символы
return !symbol || std::iswspace(symbol) || ::IsWordDiv(Global->Opt->strWordDiv,symbol);
}
void FindFiles::SetPluginDirectory(string_view const DirName, const plugin_panel* const hPlugin, bool const UpdatePanel, const UserDataItem* const UserData)
{
if (!DirName.empty())
{
//const wchar_t* DirPtr = ;
const auto NamePtr = PointToName(DirName);
if (NamePtr.size() != DirName.size())
{
const auto Dir = DeleteEndSlash(DirName.substr(0, DirName.size() - NamePtr.size()));
// force plugin to update its file list (that can be empty at this time)
// if not done SetDirectory may fail
{
span<PluginPanelItem> PanelData;
SCOPED_ACTION(std::lock_guard)(PluginCS);
if (Global->CtrlObject->Plugins->GetFindData(hPlugin, PanelData, OPM_SILENT))
Global->CtrlObject->Plugins->FreeFindData(hPlugin, PanelData, true);
}
SCOPED_ACTION(std::lock_guard)(PluginCS);
Global->CtrlObject->Plugins->SetDirectory(hPlugin, Dir.empty()? L"\\"s : string(Dir), OPM_SILENT, Dir.empty()? nullptr : UserData);
}
// Отрисуем панель при необходимости.
if (UpdatePanel)
{
Global->CtrlObject->Cp()->ActivePanel()->Update(UPDATE_KEEP_SELECTION);
Global->CtrlObject->Cp()->ActivePanel()->GoToFile(NamePtr);
Global->CtrlObject->Cp()->ActivePanel()->Show();
}
}
}
intptr_t FindFiles::AdvancedDlgProc(Dialog* Dlg, intptr_t Msg, intptr_t Param1, void* Param2)
{
switch (Msg)
{
case DN_CLOSE:
if (Param1==AD_BUTTON_OK)
{
const auto Data = reinterpret_cast<const wchar_t*>(Dlg->SendMessage(DM_GETCONSTTEXTPTR, AD_EDIT_SEARCHFIRST, nullptr));
if (Data && *Data && !CheckFileSizeStringFormat(Data))
{
Message(MSG_WARNING,
msg(lng::MFindFileAdvancedTitle),
{
msg(lng::MBadFileSizeFormat)
},
{ lng::MOk });
return FALSE;
}
}
break;
default:
break;
}
return Dlg->DefProc(Msg,Param1,Param2);
}
void FindFiles::AdvancedDialog() const
{
auto AdvancedDlg = MakeDialogItems<AD_COUNT>(
{
{ DI_DOUBLEBOX, {{3, 1 }, {52, 11}}, DIF_NONE, msg(lng::MFindFileAdvancedTitle), },
{ DI_TEXT, {{5, 2 }, {0, 2 }}, DIF_NONE, msg(lng::MFindFileSearchFirst), },
{ DI_EDIT, {{5, 3 }, {50, 3 }}, DIF_NONE, Global->Opt->FindOpt.strSearchInFirstSize, },
{ DI_TEXT, {{-1, 4 }, {0, 4 }}, DIF_SEPARATOR, },
{ DI_TEXT, {{5, 5 }, {0, 5 }}, DIF_NONE, msg(lng::MFindAlternateModeTypes), },
{ DI_EDIT, {{5, 6 }, {50, 6 }}, DIF_NONE, Global->Opt->FindOpt.strSearchOutFormat, },
{ DI_TEXT, {{5, 7 }, {0, 7 }}, DIF_NONE, msg(lng::MFindAlternateModeWidths), },
{ DI_EDIT, {{5, 8 }, {50, 8 }}, DIF_NONE, Global->Opt->FindOpt.strSearchOutFormatWidth, },
{ DI_TEXT, {{-1, 9 }, {0, 9 }}, DIF_SEPARATOR, },
{ DI_BUTTON, {{0, 10}, {0, 10}}, DIF_CENTERGROUP | DIF_DEFAULTBUTTON, msg(lng::MOk), },
{ DI_BUTTON, {{0, 10}, {0, 10}}, DIF_CENTERGROUP, msg(lng::MCancel), },
});
const auto Dlg = Dialog::create(AdvancedDlg, &FindFiles::AdvancedDlgProc);
Dlg->SetHelp(L"FindFileAdvanced"sv);
Dlg->SetPosition({ -1, -1, 52 + 4, 13 });
Dlg->Process();
if (Dlg->GetExitCode() == AD_BUTTON_OK)
{
Global->Opt->FindOpt.strSearchInFirstSize = AdvancedDlg[AD_EDIT_SEARCHFIRST].strData;
Global->Opt->SetSearchColumns(AdvancedDlg[AD_EDIT_COLUMNSFORMAT].strData, AdvancedDlg[AD_EDIT_COLUMNSWIDTH].strData);
}
}
intptr_t FindFiles::MainDlgProc(Dialog* Dlg, intptr_t Msg, intptr_t Param1, void* Param2)
{
const auto SetAllCpTitle = [&]
{
const int TitlePosition = 1;
const auto CpEnum = codepages::GetFavoritesEnumerator();
const auto Title = msg(std::any_of(CONST_RANGE(CpEnum, i) { return i.second & CPST_FIND; })? lng::MFindFileSelectedCodePages : lng::MFindFileAllCodePages);
Dlg->GetAllItem()[FAD_COMBOBOX_CP].ListPtr->at(TitlePosition).Name = Title;
FarListPos Position = { sizeof(FarListPos) };
Dlg->SendMessage(DM_LISTGETCURPOS, FAD_COMBOBOX_CP, &Position);
if (Position.SelectPos == TitlePosition)
Dlg->SendMessage(DM_SETTEXTPTR, FAD_COMBOBOX_CP, UNSAFE_CSTR(Title));
};
switch (Msg)
{
case DN_INITDIALOG:
{
bool Hex = (Dlg->SendMessage(DM_GETCHECK, FAD_CHECKBOX_HEX, nullptr) == BSTATE_CHECKED);
Dlg->SendMessage(DM_SHOWITEM,FAD_EDIT_TEXT,ToPtr(!Hex));
Dlg->SendMessage(DM_SHOWITEM,FAD_EDIT_HEX,ToPtr(Hex));
Dlg->SendMessage(DM_ENABLE,FAD_TEXT_CP,ToPtr(!Hex));
Dlg->SendMessage(DM_ENABLE,FAD_COMBOBOX_CP,ToPtr(!Hex));
Dlg->SendMessage(DM_ENABLE,FAD_CHECKBOX_CASE,ToPtr(!Hex));
Dlg->SendMessage(DM_ENABLE,FAD_CHECKBOX_WHOLEWORDS,ToPtr(!Hex));
Dlg->SendMessage(DM_ENABLE,FAD_CHECKBOX_DIRS,ToPtr(!Hex));
Dlg->SendMessage(DM_EDITUNCHANGEDFLAG,FAD_EDIT_TEXT,ToPtr(1));
Dlg->SendMessage(DM_EDITUNCHANGEDFLAG,FAD_EDIT_HEX,ToPtr(1));
Dlg->SendMessage(DM_SETTEXTPTR,FAD_TEXT_TEXTHEX,const_cast<wchar_t*>(msg(Hex? lng::MFindFileHex : lng::MFindFileText).c_str()));
Dlg->SendMessage(DM_SETTEXTPTR,FAD_TEXT_CP,const_cast<wchar_t*>(msg(lng::MFindFileCodePage).c_str()));
Dlg->SendMessage(DM_SETCOMBOBOXEVENT,FAD_COMBOBOX_CP,ToPtr(CBET_KEY));
const auto BottomLine = KeysToLocalizedText(KEY_SPACE, KEY_INS);
FarListTitles Titles{ sizeof(FarListTitles), 0, nullptr, 0, BottomLine.c_str() };
Dlg->SendMessage(DM_LISTSETTITLES,FAD_COMBOBOX_CP,&Titles);
// Установка запомненных ранее параметров
CodePage = Global->Opt->FindCodePage;
favoriteCodePages = static_cast<int>(codepages::instance().FillCodePagesList(Dlg, FAD_COMBOBOX_CP, CodePage, true, true, false, true, false));
SetAllCpTitle();
// Текущее значение в списке выбора кодовых страниц в общем случае может не совпадать с CodePage,
// так что получаем CodePage из списка выбора
FarListPos Position={sizeof(FarListPos)};
Dlg->SendMessage( DM_LISTGETCURPOS, FAD_COMBOBOX_CP, &Position);
FarListGetItem Item = { sizeof(FarListGetItem), Position.SelectPos };
Dlg->SendMessage( DM_LISTGETITEM, FAD_COMBOBOX_CP, &Item);
CodePage = Item.Item.UserData;
return TRUE;
}
case DN_CLOSE:
{
switch (Param1)
{
case FAD_BUTTON_FIND:
{
string Mask(reinterpret_cast<const wchar_t*>(Dlg->SendMessage(DM_GETCONSTTEXTPTR, FAD_EDIT_MASK, nullptr)));
if (Mask.empty())
Mask = L"*"sv;
return FileMaskForFindFile->assign(Mask);
}
case FAD_BUTTON_DRIVE:
{
ChangeDisk(Global->CtrlObject->Cp()->ActivePanel());
// Ну что ж, раз пошла такая пьянка рефрешить окна
// будем таким способом.
Global->WindowManager->ResizeAllWindows();
string strSearchFromRoot;
PrepareDriveNameStr(strSearchFromRoot);
FarListGetItem item{ sizeof(FarListGetItem), FINDAREA_ROOT };
Dlg->SendMessage(DM_LISTGETITEM,FAD_COMBOBOX_WHERE,&item);
item.Item.Text=strSearchFromRoot.c_str();
Dlg->SendMessage(DM_LISTUPDATE,FAD_COMBOBOX_WHERE,&item);
PluginMode = Global->CtrlObject->Cp()->ActivePanel()->GetMode() == panel_mode::PLUGIN_PANEL;
Dlg->SendMessage(DM_ENABLE,FAD_CHECKBOX_DIRS,ToPtr(!PluginMode));
item.ItemIndex = FINDAREA_ROOT;
Dlg->SendMessage(DM_LISTGETITEM,FAD_COMBOBOX_WHERE,&item);
if (PluginMode)
item.Item.Flags|=LIF_GRAYED;
else
item.Item.Flags&=~LIF_GRAYED;
Dlg->SendMessage(DM_LISTUPDATE,FAD_COMBOBOX_WHERE,&item);
item.ItemIndex = FINDAREA_ALL_BUTNETWORK;
Dlg->SendMessage(DM_LISTGETITEM,FAD_COMBOBOX_WHERE,&item);
if (PluginMode)
item.Item.Flags|=LIF_GRAYED;
else
item.Item.Flags&=~LIF_GRAYED;
Dlg->SendMessage(DM_LISTUPDATE,FAD_COMBOBOX_WHERE,&item);
}
break;
case FAD_BUTTON_FILTER:
filters::EditFilters(Filter->area(), Filter->panel());
break;
case FAD_BUTTON_ADVANCED:
AdvancedDialog();
break;
case -2:
case -1:
case FAD_BUTTON_CANCEL:
return TRUE;
}
return FALSE;
}
case DN_BTNCLICK:
{
switch (Param1)
{
case FAD_CHECKBOX_DIRS:
{
FindFoldersChanged = true;
}
break;
case FAD_CHECKBOX_HEX:
{
SCOPED_ACTION(Dialog::suppress_redraw)(Dlg);
const auto Src = reinterpret_cast<const wchar_t*>(Dlg->SendMessage(DM_GETCONSTTEXTPTR, Param2 ? FAD_EDIT_TEXT : FAD_EDIT_HEX, nullptr));
const auto strDataStr = ConvertHexString(Src, CodePage, !Param2);
Dlg->SendMessage(DM_SETTEXTPTR,Param2?FAD_EDIT_HEX:FAD_EDIT_TEXT, UNSAFE_CSTR(strDataStr));
const auto iParam = reinterpret_cast<intptr_t>(Param2);
Dlg->SendMessage(DM_SHOWITEM,FAD_EDIT_TEXT,ToPtr(!iParam));
Dlg->SendMessage(DM_SHOWITEM,FAD_EDIT_HEX,ToPtr(iParam));
Dlg->SendMessage(DM_ENABLE,FAD_TEXT_CP,ToPtr(!iParam));
Dlg->SendMessage(DM_ENABLE,FAD_COMBOBOX_CP,ToPtr(!iParam));
Dlg->SendMessage(DM_ENABLE,FAD_CHECKBOX_CASE,ToPtr(!iParam));
Dlg->SendMessage(DM_ENABLE,FAD_CHECKBOX_WHOLEWORDS,ToPtr(!iParam));
Dlg->SendMessage(DM_ENABLE,FAD_CHECKBOX_DIRS,ToPtr(!iParam));
Dlg->SendMessage(DM_SETTEXTPTR,FAD_TEXT_TEXTHEX, UNSAFE_CSTR(msg(Param2? lng::MFindFileHex : lng::MFindFileText)));
if (!strDataStr.empty())
{
const auto UnchangeFlag = static_cast<int>(Dlg->SendMessage(DM_EDITUNCHANGEDFLAG, FAD_EDIT_TEXT, ToPtr(-1)));
Dlg->SendMessage(DM_EDITUNCHANGEDFLAG,FAD_EDIT_HEX,ToPtr(UnchangeFlag));
}
}
break;
}
break;
}
case DN_CONTROLINPUT:
{
const auto record = static_cast<const INPUT_RECORD*>(Param2);
if (record->EventType!=KEY_EVENT) break;
int key = InputRecordToKey(record);
switch (Param1)
{
case FAD_COMBOBOX_CP:
{
switch (key)
{
case KEY_INS:
case KEY_NUMPAD0:
case KEY_SPACE:
{
// Обработка установки/снятия флажков для стандартных и избранных таблиц символов
// Получаем текущую позицию в выпадающем списке таблиц символов
FarListPos Position={sizeof(FarListPos)};
Dlg->SendMessage( DM_LISTGETCURPOS, FAD_COMBOBOX_CP, &Position);
// Получаем номер выбранной таблицы символов
FarListGetItem Item = { sizeof(FarListGetItem), Position.SelectPos };
Dlg->SendMessage( DM_LISTGETITEM, FAD_COMBOBOX_CP, &Item);
const auto SelectedCodePage = Item.Item.UserData;
// Разрешаем отмечать только стандартные и избранные таблицы символов
int FavoritesIndex = 2 + StandardCPCount + 2;
if (Position.SelectPos > 1)
{
// Получаем текущее состояние флага в реестре
long long SelectType = codepages::GetFavorite(SelectedCodePage);
// Отмечаем/разотмечаем таблицу символов
if (Item.Item.Flags & LIF_CHECKED)
{
// Для стандартных таблиц символов просто удаляем значение из реестра, для
// избранных же оставляем в реестре флаг, что таблица символов избранная
if (SelectType & CPST_FAVORITE)
codepages::SetFavorite(SelectedCodePage, CPST_FAVORITE);
else
codepages::DeleteFavorite(SelectedCodePage);
Item.Item.Flags &= ~LIF_CHECKED;
}
else
{
codepages::SetFavorite(SelectedCodePage, CPST_FIND | (SelectType & CPST_FAVORITE ? CPST_FAVORITE : 0));
Item.Item.Flags |= LIF_CHECKED;
}
SetAllCpTitle();
// Обновляем текущий элемент в выпадающем списке
Dlg->SendMessage( DM_LISTUPDATE, FAD_COMBOBOX_CP, &Item);
FarListPos Pos={sizeof(FarListPos),Position.SelectPos+1,Position.TopPos};
Dlg->SendMessage( DM_LISTSETCURPOS, FAD_COMBOBOX_CP,&Pos);
// Обрабатываем случай, когда таблица символов может присутствовать, как в стандартных, так и в избранных,
// т.е. выбор/снятие флага автоматически происходит у обоих элементов
bool bStandardCodePage = Position.SelectPos < FavoritesIndex;
for (int Index = bStandardCodePage ? FavoritesIndex : 0; Index < (bStandardCodePage ? FavoritesIndex + favoriteCodePages : FavoritesIndex); Index++)
{
// Получаем элемент таблицы символов
FarListGetItem CheckItem = { sizeof(FarListGetItem), Index };
Dlg->SendMessage( DM_LISTGETITEM, FAD_COMBOBOX_CP, &CheckItem);
// Обрабатываем только таблицы символов
if (!(CheckItem.Item.Flags&LIF_SEPARATOR))
{
if (SelectedCodePage == CheckItem.Item.UserData)
{
if (Item.Item.Flags & LIF_CHECKED)
CheckItem.Item.Flags |= LIF_CHECKED;
else
CheckItem.Item.Flags &= ~LIF_CHECKED;
Dlg->SendMessage( DM_LISTUPDATE, FAD_COMBOBOX_CP, &CheckItem);
break;
}
}
}
}
}
break;
}
}
break;
}
break;
}
case DN_EDITCHANGE:
{
auto& Item=*static_cast<FarDialogItem*>(Param2);
switch (Param1)
{
case FAD_EDIT_TEXT:
// Строка "Содержащих текст"
if (!FindFoldersChanged)
{
const auto Checked = Item.Data && *Item.Data? false : Global->Opt->FindOpt.FindFolders;
Dlg->SendMessage( DM_SETCHECK, FAD_CHECKBOX_DIRS, ToPtr(Checked? BSTATE_CHECKED : BSTATE_UNCHECKED));
}
return TRUE;
case FAD_COMBOBOX_CP:
// Получаем выбранную в выпадающем списке таблицу символов
CodePage = Dlg->GetListItemSimpleUserData(FAD_COMBOBOX_CP, Dlg->SendMessage(DM_LISTGETCURPOS, FAD_COMBOBOX_CP, nullptr));
return TRUE;
case FAD_COMBOBOX_WHERE:
SearchFromChanged = true;
return TRUE;
}
}
[[fallthrough]];
case DN_HOTKEY:
if (Param1==FAD_TEXT_TEXTHEX)
{
Dlg->SendMessage(DM_SETFOCUS, FAD_EDIT_HEX, nullptr); // only one
Dlg->SendMessage(DM_SETFOCUS, FAD_EDIT_TEXT, nullptr); // is active
return FALSE;
}
[[fallthrough]];
default:
break;
}
return Dlg->DefProc(Msg,Param1,Param2);
}
bool FindFiles::GetPluginFile(ArcListItem const* const ArcItem, const os::fs::find_data& FindData, const string& DestPath, string &strResultName, const UserDataItem* const UserData)
{
SCOPED_ACTION(std::lock_guard)(PluginCS);
OpenPanelInfo Info;
Global->CtrlObject->Plugins->GetOpenPanelInfo(ArcItem->hPlugin,&Info);
string strSaveDir = NullToEmpty(Info.CurDir);
AddEndSlash(strSaveDir);
Global->CtrlObject->Plugins->SetDirectory(ArcItem->hPlugin, L"\\"s, OPM_SILENT);
SetPluginDirectory(FindData.FileName,ArcItem->hPlugin,false,UserData);
const auto FileNameToFind = PointToName(FindData.FileName);
const auto FileNameToFindShort = FindData.HasAlternateFileName()? PointToName(FindData.AlternateFileName()) : string_view{};
span<PluginPanelItem> Items;
bool nResult=false;
if (Global->CtrlObject->Plugins->GetFindData(ArcItem->hPlugin, Items, OPM_SILENT))
{
const auto It = std::find_if(ALL_CONST_RANGE(Items), [&](const auto& Item)
{
return FileNameToFind == NullToEmpty(Item.FileName) && FileNameToFindShort == NullToEmpty(Item.AlternateFileName);
});
if (It != Items.cend())
{
nResult = Global->CtrlObject->Plugins->GetFile(ArcItem->hPlugin, &*It, DestPath, strResultName, OPM_SILENT) != 0;
}
Global->CtrlObject->Plugins->FreeFindData(ArcItem->hPlugin, Items, true);
}
Global->CtrlObject->Plugins->SetDirectory(ArcItem->hPlugin, L"\\"s, OPM_SILENT);
SetPluginDirectory(strSaveDir, ArcItem->hPlugin, false, nullptr);
return nResult;
}
bool background_searcher::LookForString(string_view const FileName)
{
// Длина строки поиска
std::optional<size_t> FoundStrSize;
// Открываем файл
const os::fs::file File(FileName, FILE_READ_DATA, FILE_SHARE_READ | FILE_SHARE_WRITE, nullptr, OPEN_EXISTING, FILE_FLAG_SEQUENTIAL_SCAN);
if(!File)
{
return false;
}
if (m_Autodetection)
{
m_CodePages.front().CodePage = GetFileCodepage(File, encoding::codepage::ansi());
m_CodePages.front().initialize();
m_MaxCharSize = m_CodePages.front().MaxCharSize;
}
// Количество считанных из файла байт
size_t readBlockSize = 0;
// Количество прочитанных из файла байт
unsigned long long alreadyRead = 0;
// Смещение на которое мы отступили при переходе между блоками
size_t offset = 0;
if (SearchHex)
offset = hexFindString.size() - 1;
unsigned long long FileSize = 0;
// BUGBUG check result
if (!File.GetSize(FileSize))
{
LOGWARNING(L"GetSize({}): {}"sv, File.GetName(), last_error());
}
if (SearchInFirst)
{
FileSize=std::min(SearchInFirst,FileSize);
}
unsigned LastPercents{};
// Основной цикл чтения из файла
while (!Stopped() && File.Read(readBufferA.data(), (!SearchInFirst || alreadyRead + readBufferA.size() <= SearchInFirst)? readBufferA.size() : SearchInFirst - alreadyRead, readBlockSize))
{
const auto IsLastBlock = readBlockSize < readBuffer.size();
const auto Percents = ToPercent(alreadyRead, FileSize);
if (Percents!=LastPercents)
{
m_Owner->m_Messages.emplace(messages::percent{ Percents });
LastPercents=Percents;
}
// Увеличиваем счётчик прочитаннх байт
alreadyRead += readBlockSize;
// Для hex и обыкновенного поиска разные ветки
if (SearchHex)
{
// Выходим, если прочитали мало
if (readBlockSize < hexFindString.size())
return false;
// Ищем
const auto Begin = readBufferA.data(), End = Begin + readBlockSize;
if (std::search(Begin, End, *m_HexSearcher) != End)
return true;
}
else
{
bool ErrorState = false;
for (auto& i: m_CodePages)
{
ErrorState = false;
// Пропускаем ошибочные кодовые страницы
if (!i.MaxCharSize)
{
ErrorState = true;
continue;
}
// Если начало файла очищаем информацию о поиске по словам
if (WholeWords && alreadyRead==readBlockSize)
{
i.WordFound = false;
i.LastSymbol = 0;
}
// Если ничего не прочитали
if (!readBlockSize)
{
// Если поиск по словам и в конце предыдущего блока было что-то найдено,
// то считаем, что нашли то, что нужно
if(WholeWords && i.WordFound)
return true;
else
{
ErrorState = true;
continue;
}
// Выходим, если прочитали меньше размера строки поиска и нет поиска по словам
}
if (readBlockSize < FoundStrSize && !(WholeWords && i.WordFound))
{
ErrorState = true;
continue;
}
// Количество символов в выходном буфере
size_t bufferCount;
// Буфер для поиска
wchar_t const *buffer;
// Перегоняем буфер в UTF-16
if (IsUnicodeCodePage(i.CodePage))
{
// Вычисляем размер буфера в UTF-16
bufferCount = readBlockSize/sizeof(wchar_t);
// Выходим, если размер буфера меньше длины строки поиска
if (bufferCount < FoundStrSize)
{
ErrorState = true;
continue;
}
// Копируем буфер чтения в буфер сравнения
if (i.CodePage==CP_REVERSEBOM)
{
// Для UTF-16 (big endian) преобразуем буфер чтения в буфер сравнения
swap_bytes(readBufferA.data(), readBuffer.data(), readBlockSize);
// Устанавливаем буфер сравнения
buffer = readBuffer.data();
}
else
{
// Если поиск в UTF-16 (little endian), то используем исходный буфер
buffer = reinterpret_cast<wchar_t*>(readBufferA.data());
}
}
else
{
// Конвертируем буфер чтения из кодировки поиска в UTF-16
encoding::diagnostics Diagnostics{ encoding::enabled_diagnostics::incomplete_bytes };
bufferCount = encoding::get_chars(i.CodePage, { readBufferA.data(), readBlockSize }, readBuffer, &Diagnostics);
// Выходим, если нам не удалось сконвертировать строку
if (!bufferCount)
{
ErrorState = true;
continue;
}
if (Diagnostics.IncompleteBytes && !IsLastBlock)
{
--bufferCount;
readBlockSize -= Diagnostics.IncompleteBytes;
alreadyRead -= Diagnostics.IncompleteBytes;
File.SetPointer(-static_cast<int>(Diagnostics.IncompleteBytes), {}, FILE_CURRENT);
}
// Если у нас поиск по словам и в конце предыдущего блока было вхождение
if (WholeWords && i.WordFound)
{
// Если конец файла, то считаем, что есть разделитель в конце
if (bufferCount < FoundStrSize)
return true;
// Проверяем первый символ текущего блока с учётом обратного смещения, которое делается
// при переходе между блоками
i.LastSymbol = readBuffer[*FoundStrSize - 1];
if (FindFiles::IsWordDiv(i.LastSymbol))
return true;
// Если размер буфера меньше размера слова, то выходим
if (readBlockSize < FoundStrSize)
{
ErrorState = true;
continue;
}
}
// Устанавливаем буфер сравнения
buffer = readBuffer.data();
}
i.WordFound = false;
string_view Where{ buffer, bufferCount };
const auto Next = [&](size_t const Offset, size_t const Size)
{
Where.remove_prefix(Offset + Size);
};
while (!Where.empty())
{
const auto FoundPosition = m_TextSearcher->find_in(Where);
if (!FoundPosition)
break;
if (!WholeWords)
return true;
const auto [FoundOffset, FoundSize] = *FoundPosition;
FoundStrSize = FoundSize;
const auto AbsoluteOffset = bufferCount - Where.size() + FoundOffset;
// Если идёт поиск по словам, то делаем соответствующие проверки
bool firstWordDiv = false;
// Если мы находимся вначале блока
if (!AbsoluteOffset)
{
// Если мы находимся вначале файла, то считаем, что разделитель есть
// Если мы находимся вначале блока, то проверяем является
// или нет последний символ предыдущего блока разделителем
if (alreadyRead == readBlockSize || FindFiles::IsWordDiv(i.LastSymbol))
firstWordDiv = true;
}
else
{
// Проверяем является или нет предыдущий найденному символ блока разделителем
i.LastSymbol = buffer[AbsoluteOffset - 1];
if (FindFiles::IsWordDiv(i.LastSymbol))
firstWordDiv = true;
}
// Проверяем разделитель в конце, только если найден разделитель вначале
if (firstWordDiv)
{
// Если блок выбран не до конца
if (AbsoluteOffset + FoundSize != bufferCount)
{
// Проверяем является или нет последующий за найденным символ блока разделителем
i.LastSymbol = buffer[AbsoluteOffset + FoundSize];
if (FindFiles::IsWordDiv(i.LastSymbol))
return true;
}
else
i.WordFound = true;
}
Next(FoundOffset, FoundSize);
}
// Выходим, если мы вышли за пределы количества байт разрешённых для поиска
if (SearchInFirst && alreadyRead >= SearchInFirst)
{
ErrorState = true;
continue;
}
// Запоминаем последний символ блока
i.LastSymbol = buffer[bufferCount-1];
}
if (ErrorState)
return false;
// Получаем смещение на которое мы отступили при переходе между блоками
offset = m_MaxCharSize * (FoundStrSize.value_or(strFindStr.size()) - 1);
}
// Если мы потенциально прочитали не весь файл
if (!IsLastBlock)
{
// Отступаем назад на длину слова поиска минус 1
if (!File.SetPointer(-1ll*offset, nullptr, FILE_CURRENT))
return false;
alreadyRead -= offset;
}
}
return false;
}
bool background_searcher::IsFileIncluded(PluginPanelItem* FileItem, string_view const FullName, os::fs::attributes FileAttr, string_view const DisplayName)
{
if (!m_Owner->GetFileMask()->check(PointToName(FullName)))
return false;
const auto hPlugin = m_FindFileArcItem? m_FindFileArcItem->hPlugin : nullptr;
if (FileAttr & FILE_ATTRIBUTE_DIRECTORY)
return Global->Opt->FindOpt.FindFolders && strFindStr.empty();
if (strFindStr.empty())
return true;
m_Owner->m_Messages.emplace(messages::status{ string(DisplayName) });
string strSearchFileName;
bool RemoveTemp = false;
SCOPE_EXIT
{
if (RemoveTemp)
DeleteFileWithFolder(strSearchFileName);
};
if (!hPlugin)
{
strSearchFileName = FullName;
}
else
{
const auto UseInternalCommand = [&]
{
SCOPED_ACTION(auto)(m_Owner->ScopedLock());
OpenPanelInfo Info;
Global->CtrlObject->Plugins->GetOpenPanelInfo(hPlugin, &Info);
return PluginManager::UseInternalCommand(hPlugin, PLUGIN_FARGETFILES, Info);
};
if (UseInternalCommand())
{
strSearchFileName = strPluginSearchPath + FullName;
}
else
{
const auto strTempDir = MakeTemp();
if (!os::fs::create_directory(strTempDir))
return false;
const auto GetFile = [&]
{
SCOPED_ACTION(auto)(m_Owner->ScopedLock());
return Global->CtrlObject->Plugins->GetFile(hPlugin, FileItem, strTempDir, strSearchFileName, OPM_SILENT | OPM_FIND) != FALSE;
};
if (!GetFile())
{
// BUGBUG check result
if (!os::fs::remove_directory(strTempDir))
{
LOGWARNING(L"remove_directory({}): {}"sv, strTempDir, last_error());
}
return false;
}
RemoveTemp = true;
}
}
return LookForString(strSearchFileName) ^ NotContaining;
}
static void clear_queue(std::queue<message>&& Messages)
{
for (; !Messages.empty(); Messages.pop())
{
std::visit(overload
{
[&](messages::menu_data const& Data)
{
FreePluginPanelItemUserData(Data.m_Arc? Data.m_Arc->hPlugin : nullptr, Data.m_UserData);
},
[](messages::push const&){},
[](messages::pop const&){},
[](messages::status const&){},
[](messages::percent const&){}
}, Messages.front());
}
}
void FindFiles::stop_and_discard(Dialog* Dlg)
{
if (Finalized)
return;
m_Searcher->Stop();
clear_queue(std::move(m_ExtractedMessages));
// The request to stop might arrive in the middle of something and searcher can still pump some messages
do
{
clear_queue(m_Messages.pop_all());
}
while (!m_Searcher->Finished());
Dlg->SendMessage(DM_REFRESH, 0, {});
}
FindListItem& FindFiles::AddFindListItem(const os::fs::find_data& FindData, UserDataItem const& UserData)
{
FindListItem NewItem;
NewItem.FindData = FindData;
NewItem.UserData = UserData;
m_FindList.emplace_back(std::move(NewItem));
return m_FindList.back();
}
void FindFiles::ClearFindList()
{
if (m_FindList.empty())
return;
for (const auto& i: m_FindList)
{
FreePluginPanelItemUserData(i.Arc? i.Arc->hPlugin : nullptr, i.UserData);
}
m_FindList.clear();
}
intptr_t FindFiles::FindDlgProc(Dialog* Dlg, intptr_t Msg, intptr_t Param1, void* Param2)
{
if (!m_ExceptionPtr)
{
m_ExceptionPtr = m_Searcher->ExceptionPtr();
if (m_ExceptionPtr)
{
Dlg->SendMessage(DM_CLOSE, 0, nullptr);
return TRUE;
}
}
auto& ListBox = Dlg->GetAllItem()[FD_LISTBOX].ListPtr;
switch (Msg)
{
case DM_REFRESH:
{
if (Finalized)
break;
if (os::handle::is_signaled(console.GetInputHandle()))
break;
const auto refresh_status = [&]
{
const auto strDataStr = format(msg(lng::MFindFound), m_FileCount, m_DirCount);
Dlg->SendMessage(DM_SETTEXTPTR, FD_SEPARATOR1, UNSAFE_CSTR(strDataStr));
if (m_Searcher->Finished())
{
Dlg->SendMessage(DM_SETTEXTPTR, FD_TEXT_STATUS, {});
}
else
{
string strSearchStr;
if (!strFindStr.empty())
{
strSearchStr = format(msg(lng::MFindSearchingIn), quote_unconditional(truncate_right(strFindStr, 10)));
Dlg->SendMessage(DM_SETTEXTPTR, FD_TEXT_STATUS_PERCENTS, UNSAFE_CSTR(format(FSTR(L"{:3}%"sv), m_Percent)));
}
SMALL_RECT Rect;
Dlg->SendMessage(DM_GETITEMPOSITION, FD_TEXT_STATUS, &Rect);
if (!strSearchStr.empty())
{
strSearchStr += L' ';
}
auto strFM = m_Status;
inplace::truncate_center(strFM, Rect.Right - Rect.Left + 1 - strSearchStr.size());
Dlg->SendMessage(DM_SETTEXTPTR, FD_TEXT_STATUS, UNSAFE_CSTR(strSearchStr + strFM));
}
if (m_LastFoundNumber)
{
m_LastFoundNumber = 0;
if (ListBox->UpdateRequired())
Dlg->SendMessage(DM_SHOWITEM, FD_LISTBOX, ToPtr(1));
}
Dlg->SendMessage(DM_ENABLEREDRAW, 1, nullptr);
Dlg->SendMessage(DM_ENABLEREDRAW, 0, nullptr);
};
SCOPED_ACTION(Dialog::suppress_redraw)(Dlg);
refresh_status();
if (m_ExtractedMessages.empty())
m_ExtractedMessages = m_Messages.pop_all();
for (; !m_ExtractedMessages.empty(); m_ExtractedMessages.pop())
{
if (os::handle::is_signaled(console.GetInputHandle()))
break;
ProcessMessage(m_ExtractedMessages.front());
if (m_TimeCheck)
refresh_status();
}
if (m_Searcher->Finished() && m_Messages.empty() && m_ExtractedMessages.empty())
{
m_UpdateTimer = {};
Finalized = true;
SCOPED_ACTION(Dialog::suppress_redraw)(Dlg);
const auto strMessage = format(msg(lng::MFindDone), m_FileCount, m_DirCount);
Dlg->SendMessage(DM_SETTEXTPTR, FD_SEPARATOR1, nullptr);
Dlg->SendMessage(DM_SETTEXTPTR, FD_TEXT_STATUS, UNSAFE_CSTR(strMessage));
Dlg->SendMessage(DM_SETTEXTPTR, FD_TEXT_STATUS_PERCENTS, nullptr);
Dlg->SendMessage(DM_SETTEXTPTR, FD_BUTTON_STOP, const_cast<wchar_t*>(msg(lng::MFindCancel).c_str()));
ConsoleTitle::SetFarTitle(strMessage);
Dlg->SendMessage(DM_ENABLEREDRAW, 1, nullptr);
Dlg->SendMessage(DM_ENABLEREDRAW, 0, nullptr);
}
}
break;
case DN_INITDIALOG:
{
Dlg->GetAllItem()[FD_LISTBOX].ListPtr->SetMenuFlags(VMENU_NOMERGEBORDER);
}
break;
case DN_DRAWDLGITEMDONE: //???
case DN_DRAWDIALOGDONE:
Dlg->DefProc(Msg,Param1,Param2);
// Переместим фокус на кнопку [Go To]
if ((m_DirCount || m_FileCount) && !FindPositionChanged)
{
FindPositionChanged=true;
Dlg->SendMessage(DM_SETFOCUS, FD_BUTTON_GOTO, nullptr);
}
return TRUE;
case DN_CONTROLINPUT:
{
const auto record = static_cast<const INPUT_RECORD*>(Param2);
if (record->EventType!=KEY_EVENT) break;
int key = InputRecordToKey(record);
switch (key)
{
case KEY_ESC:
case KEY_F10:
{
if (!Finalized)
{
if (!m_Searcher->Finished())
m_Searcher->Pause();
if (ConfirmAbort())
{
stop_and_discard(Dlg);
}
else
{
if (!m_Searcher->Finished())
m_Searcher->Resume();
}
return TRUE;
}
}
break;
case KEY_RIGHT:
case KEY_NUMPAD6:
case KEY_TAB:
if (Param1==FD_BUTTON_STOP)
{
FindPositionChanged=true;
Dlg->SendMessage(DM_SETFOCUS, FD_BUTTON_NEW, nullptr);
return TRUE;
}
break;
case KEY_LEFT:
case KEY_NUMPAD4:
case KEY_SHIFTTAB:
if (Param1==FD_BUTTON_NEW)
{
FindPositionChanged=true;
Dlg->SendMessage(DM_SETFOCUS, FD_BUTTON_STOP, nullptr);
return TRUE;
}
break;
case KEY_UP:
case KEY_DOWN:
case KEY_NUMPAD8:
case KEY_NUMPAD2:
case KEY_PGUP:
case KEY_PGDN:
case KEY_NUMPAD9:
case KEY_NUMPAD3:
case KEY_HOME:
case KEY_END:
case KEY_NUMPAD7:
case KEY_NUMPAD1:
case KEY_MSWHEEL_UP:
case KEY_MSWHEEL_DOWN:
case KEY_ALTLEFT:
case KEY_RALTLEFT:
case KEY_ALT|KEY_NUMPAD4:
case KEY_RALT|KEY_NUMPAD4:
case KEY_MSWHEEL_LEFT:
case KEY_ALTRIGHT:
case KEY_RALTRIGHT:
case KEY_ALT|KEY_NUMPAD6:
case KEY_RALT|KEY_NUMPAD6:
case KEY_MSWHEEL_RIGHT:
case KEY_ALTSHIFTLEFT:
case KEY_RALTSHIFTLEFT:
case KEY_ALT|KEY_SHIFT|KEY_NUMPAD4:
case KEY_RALT|KEY_SHIFT|KEY_NUMPAD4:
case KEY_ALTSHIFTRIGHT:
case KEY_RALTSHIFTRIGHT:
case KEY_ALT|KEY_SHIFT|KEY_NUMPAD6:
case KEY_RALT|KEY_SHIFT|KEY_NUMPAD6:
case KEY_ALTHOME:
case KEY_RALTHOME:
case KEY_ALT|KEY_NUMPAD7:
case KEY_RALT|KEY_NUMPAD7:
case KEY_ALTEND:
case KEY_RALTEND:
case KEY_ALT|KEY_NUMPAD1:
case KEY_RALT|KEY_NUMPAD1:
ListBox->ProcessKey(Manager::Key(key));
return TRUE;
/*
case KEY_CTRLA:
case KEY_RCTRLA:
{
if (!ListBox->GetItemCount())
{
return TRUE;
}
size_t ItemIndex = *static_cast<size_t*>(ListBox->GetUserData(nullptr,0));
FINDLIST FindItem;
itd->GetFindListItem(ItemIndex, FindItem);
if (ShellSetFileAttributes(nullptr,FindItem.FindData.strFileName))
{
itd->SetFindListItem(ItemIndex, FindItem);
Dlg->SendMessage(DM_REDRAW,0,0);
}
return TRUE;
}
*/
case KEY_F3:
case KEY_ALTF3:
case KEY_RALTF3:
case KEY_CTRLSHIFTF3:
case KEY_RCTRLSHIFTF3:
case KEY_NUMPAD5:
case KEY_SHIFTNUMPAD5:
case KEY_F4:
case KEY_ALTF4:
case KEY_RALTF4:
case KEY_CTRLSHIFTF4:
case KEY_RCTRLSHIFTF4:
{
if (ListBox->empty())
{
return TRUE;
}
const auto FindItem = *ListBox->GetComplexUserDataPtr<FindListItem*>();
bool RemoveTemp=false;
string strSearchFileName;
if (FindItem->FindData.Attributes & FILE_ATTRIBUTE_DIRECTORY)
{
return TRUE;
}
bool real_name = true;
if(FindItem->Arc)
{
if(!(FindItem->Arc->Flags & OPIF_REALNAMES))
{
std::unique_ptr<plugin_panel> PluginPanelPtr;
real_name = false;
string strFindArcName = FindItem->Arc->strArcName;
if(!FindItem->Arc->hPlugin)
{
const auto SavePluginsOutput = std::exchange(Global->DisablePluginsOutput, true);
{
SCOPED_ACTION(std::lock_guard)(PluginCS);
PluginPanelPtr = Global->CtrlObject->Plugins->OpenFilePlugin(&strFindArcName, OPM_NONE, OFP_SEARCH);
FindItem->Arc->hPlugin = PluginPanelPtr.get();
}
Global->DisablePluginsOutput=SavePluginsOutput;
if (!PluginPanelPtr)
{
return TRUE;
}
}
const auto strTempDir = MakeTemp();
if (!os::fs::create_directory(strTempDir))
return false;
const auto bGet = GetPluginFile(FindItem->Arc, FindItem->FindData, strTempDir, strSearchFileName, &FindItem->UserData);
if (PluginPanelPtr)
{
SCOPED_ACTION(std::lock_guard)(PluginCS);
Global->CtrlObject->Plugins->ClosePanel(std::move(PluginPanelPtr));
FindItem->Arc->hPlugin = nullptr;
}
if (!bGet)
{
// BUGBUG check result
if (!os::fs::remove_directory(strTempDir))
{
LOGWARNING(L"remove_directory({}): {}"sv, strTempDir, last_error());
}
return FALSE;
}
RemoveTemp=true;
}
}
if (real_name)
{
strSearchFileName = FindItem->FindData.FileName;
if (!os::fs::exists(strSearchFileName) && os::fs::exists(FindItem->FindData.AlternateFileName()))
strSearchFileName = FindItem->FindData.AlternateFileName();
}
OpenFile(strSearchFileName, key, FindItem, Dlg);
if (RemoveTemp)
{
// external editor may not have enough time to open this file, so defer deletion
if (!m_DelayedDeleter)
{
m_DelayedDeleter = std::make_unique<delayed_deleter>(true);
}
m_DelayedDeleter->add(strSearchFileName);
}
return TRUE;
}
default:
break;
}
}
break;
case DN_BTNCLICK:
{
FindPositionChanged = true;
switch (Param1)
{
case FD_BUTTON_NEW:
stop_and_discard(Dlg);
return FALSE;
case FD_BUTTON_STOP:
// As Stop
if (!Finalized)
{
stop_and_discard(Dlg);
return TRUE;
}
// As Cancel
return FALSE;
case FD_BUTTON_VIEW:
{
INPUT_RECORD key;
KeyToInputRecord(KEY_F3,&key);
FindDlgProc(Dlg,DN_CONTROLINPUT,FD_LISTBOX,&key);
return TRUE;
}
case FD_BUTTON_GOTO:
case FD_BUTTON_PANEL:
// Переход и посыл на панель будем делать не в диалоге, а после окончания поиска.
// Иначе возможна ситуация, когда мы ищем на панели, потом ее грохаем и создаем новую
// (а поиск-то идет!) и в результате ФАР трапается.
if(ListBox->empty())
{
return TRUE;
}
FindExitItem = *ListBox->GetComplexUserDataPtr<FindListItem*>();
return FALSE;
default:
break;
}
}
break;
case DN_CLOSE:
{
BOOL Result = TRUE;
if (Param1==FD_LISTBOX)
{
if(!ListBox->empty())
{
FindDlgProc(Dlg, DN_BTNCLICK, FD_BUTTON_GOTO, nullptr); // emulates a [ Go to ] button pressing;
}
else
{
Result = FALSE;
}
}
if(Result)
{
stop_and_discard(Dlg);
}
return Result;
}
case DN_RESIZECONSOLE:
{
SCOPED_ACTION(Dialog::suppress_redraw)(Dlg);
auto& Coord = *static_cast<COORD*>(Param2);
SMALL_RECT DlgRect;
Dlg->SendMessage( DM_GETDLGRECT, 0, &DlgRect);
int DlgWidth=DlgRect.Right-DlgRect.Left+1;
int DlgHeight=DlgRect.Bottom-DlgRect.Top+1;
const auto IncX = Coord.X - DlgWidth - 2;
const auto IncY = Coord.Y - DlgHeight - 2;
if ((IncX > 0) || (IncY > 0))
{
Coord.X = DlgWidth + (IncX > 0? IncX : 0);
Coord.Y = DlgHeight + (IncY > 0? IncY : 0);
Dlg->SendMessage( DM_RESIZEDIALOG, 0, &Coord);
}
DlgWidth += IncX;
DlgHeight += IncY;
for (int i = 0; i < FD_SEPARATOR1; i++)
{
SMALL_RECT rect;
Dlg->SendMessage( DM_GETITEMPOSITION, i, &rect);
rect.Right += IncX;
rect.Bottom += IncY;
Dlg->SendMessage( DM_SETITEMPOSITION, i, &rect);
}
for (int i = FD_SEPARATOR1; i <= FD_BUTTON_STOP; i++)
{
SMALL_RECT rect;
Dlg->SendMessage( DM_GETITEMPOSITION, i, &rect);
if (i == FD_SEPARATOR1)
{
// Center text
rect.Left = rect.Right = -1;
}
else if (i == FD_TEXT_STATUS)
{
rect.Right += IncX;
}
else if (i==FD_TEXT_STATUS_PERCENTS)
{
rect.Right+=IncX;
rect.Left+=IncX;
}
rect.Top += IncY;
rect.Bottom += IncY;
Dlg->SendMessage( DM_SETITEMPOSITION, i, &rect);
}
if ((IncX <= 0) || (IncY <= 0))
{
Coord.X = DlgWidth;
Coord.Y = DlgHeight;
Dlg->SendMessage( DM_RESIZEDIALOG, 0, &Coord);
}
return TRUE;
}
default:
break;
}
return Dlg->DefProc(Msg,Param1,Param2);
}
void FindFiles::OpenFile(const string& strSearchFileName, int OpenKey, const FindListItem* FindItem, Dialog* Dlg) const
{
if (!os::fs::exists(strSearchFileName))
return;
auto openMode = FILETYPE_VIEW;
auto shouldForceInternal = false;
const auto isKnownKey = GetFiletypeOpenMode(OpenKey, openMode, shouldForceInternal);
assert(isKnownKey); // ensure all possible keys are handled
if (!isKnownKey)
return;
const auto strOldTitle = console.GetTitle();
const auto shortFileName = ExtractFileName(strSearchFileName);
if (shouldForceInternal || !ProcessLocalFileTypes(strSearchFileName, shortFileName, openMode, PluginMode))
{
if (openMode == FILETYPE_ALTVIEW && Global->Opt->strExternalViewer.empty())
openMode = FILETYPE_VIEW;
if (openMode == FILETYPE_ALTEDIT && Global->Opt->strExternalEditor.empty())
openMode = FILETYPE_EDIT;
if (openMode == FILETYPE_VIEW)
{
NamesList ViewList;
// Возьмем все файлы, которые имеют реальные имена...
for (const auto& i: m_FindList)
{
if ((i.Arc && !(i.Arc->Flags & OPIF_REALNAMES)) || i.FindData.FileName.empty() || i.FindData.Attributes & FILE_ATTRIBUTE_DIRECTORY)
continue;
ViewList.AddName(i.FindData.FileName);
}
ViewList.SetCurName(FindItem->FindData.FileName);
const auto ShellViewer = FileViewer::create(
strSearchFileName,
false,
false,
false,
-1,
{},
ViewList.size() > 1? &ViewList : nullptr);
ShellViewer->SetEnableF6(TRUE);
if (FindItem->Arc && !(FindItem->Arc->Flags & OPIF_REALNAMES))
ShellViewer->SetSaveToSaveAs(true);
if (ShellViewer->GetExitCode()) Global->WindowManager->ExecuteModal(ShellViewer);
// заставляем рефрешится экран
Global->WindowManager->ResizeAllWindows();
}
if (openMode == FILETYPE_EDIT)
{
const auto ShellEditor = FileEditor::create(strSearchFileName, CP_DEFAULT, 0);
ShellEditor->SetEnableF6(true);
if (FindItem->Arc && !(FindItem->Arc->Flags & OPIF_REALNAMES))
ShellEditor->SetSaveToSaveAs(true);
if (-1 == ShellEditor->GetExitCode())
{
Global->WindowManager->ExecuteModal(ShellEditor);
// заставляем рефрешится экран
Global->WindowManager->ResizeAllWindows();
}
}
if (openMode == FILETYPE_ALTEDIT || openMode == FILETYPE_ALTVIEW)
{
const auto& externalCommand = openMode == FILETYPE_ALTEDIT? Global->Opt->strExternalEditor : Global->Opt->strExternalViewer;
ProcessExternal(externalCommand, strSearchFileName, shortFileName, PluginMode);
}
}
console.SetTitle(strOldTitle);
}
void FindFiles::AddMenuRecord(Dialog* const Dlg, string_view const FullName, const os::fs::find_data& FindData, UserDataItem const& UserData, ArcListItem* const Arc)
{
if (!Dlg)
return;
auto& ListBox = Dlg->GetAllItem()[FD_LISTBOX].ListPtr;
if(ListBox->empty())
{
Dlg->SendMessage( DM_ENABLE, FD_BUTTON_GOTO, ToPtr(TRUE));
Dlg->SendMessage( DM_ENABLE, FD_BUTTON_VIEW, ToPtr(TRUE));
if(AnySetFindList)
{
Dlg->SendMessage( DM_ENABLE, FD_BUTTON_PANEL, ToPtr(TRUE));
}
Dlg->SendMessage( DM_ENABLE, FD_LISTBOX, ToPtr(TRUE));
}
auto MenuText = L" "s;
for (auto& i: Global->Opt->FindOpt.OutColumns)
{
int Width = i.width;
if (!Width)
{
Width = GetDefaultWidth(i);
}
switch (i.type)
{
case column_type::description:
case column_type::owner:
{
// пропускаем, не реализовано
break;
}
case column_type::name:
{
// даже если указали, пропускаем, т.к. поле имени обязательное и идет в конце.
break;
}
case column_type::attributes:
{
append(MenuText, FormatStr_Attribute(FindData.Attributes, Width), BoxSymbols[BS_V1]);
break;
}
case column_type::streams_number:
case column_type::streams_size:
case column_type::size:
case column_type::size_compressed:
case column_type::links_number:
{
unsigned long long Size = 0;
size_t Count = 0;
if (Arc)
{
if (i.type == column_type::streams_number || i.type == column_type::streams_size)
EnumStreams(FindData.FileName, Size, Count);
else if (i.type == column_type::links_number)
{
const auto Hardlinks = GetNumberOfLinks(FindData.FileName);
Count = Hardlinks? *Hardlinks : 1;
}
}
const auto SizeToDisplay =
i.type == column_type::size?
FindData.FileSize :
i.type == column_type::size_compressed?
FindData.AllocationSize :
i.type == column_type::streams_size?
Size :
Count; // ???
append(MenuText,
FormatStr_Size(
SizeToDisplay,
FindData.FileName,
FindData.Attributes,
0,
FindData.ReparseTag,
any_of(i.type, column_type::streams_number, column_type::links_number)?
column_type::streams_size :
i.type,
i.type_flags,
Width),
BoxSymbols[BS_V1]);
break;
}
case column_type::date:
case column_type::time:
case column_type::date_write:
case column_type::date_access:
case column_type::date_creation:
case column_type::date_change:
{
os::chrono::time_point const os::fs::find_data::* FileTime;
switch (i.type)
{
case column_type::date_creation:
FileTime = &os::fs::find_data::CreationTime;
break;
case column_type::date_access:
FileTime = &os::fs::find_data::LastAccessTime;
break;
case column_type::date_change:
FileTime = &os::fs::find_data::ChangeTime;
break;
default:
FileTime = &os::fs::find_data::LastWriteTime;
break;
}
append(MenuText, FormatStr_DateTime(std::invoke(FileTime, FindData), i.type, i.type_flags, Width), BoxSymbols[BS_V1]);
break;
}
default:
break;
}
}
// В плагинах принудительно поставим указатель в имени на имя
// для корректного его отображения в списке, отбросив путь,
// т.к. некоторые плагины возвращают имя вместе с полным путём,
// к примеру временная панель.
append(MenuText, Arc? PointToName(FindData.FileName) : FindData.FileName);
string strPathName(FullName);
{
const auto pos = FindLastSlash(strPathName);
if (pos != string::npos)
{
strPathName.resize(pos);
}
else
{
strPathName.clear();
}
}
AddEndSlash(strPathName);
if (!equal_icase(strPathName, m_LastDirName))
{
if (!ListBox->empty())
{
MenuItemEx ListItem;
ListItem.Flags|=LIF_SEPARATOR;
ListBox->AddItem(std::move(ListItem));
}
m_LastDirName = strPathName;
if (Arc)
{
if(!(Arc->Flags & OPIF_REALNAMES) && !Arc->strArcName.empty())
{
auto strArcPathName = Arc->strArcName + L':';
if (!path::is_separator(strPathName.front()))
AddEndSlash(strArcPathName);
strArcPathName += strPathName == L".\\"sv? L"\\"s : strPathName;
strPathName = strArcPathName;
}
}
auto& FindItem = AddFindListItem({}, {});
// Используем LastDirName, т.к. PathName уже может быть искажена
FindItem.FindData.FileName = m_LastDirName;
// Used=0 - Имя не попадёт во временную панель.
FindItem.Used=0;
// Поставим атрибут у каталога, чтобы он не был файлом :)
FindItem.FindData.Attributes = FILE_ATTRIBUTE_DIRECTORY;
FindItem.Arc = Arc;
const auto Ptr = &FindItem;
MenuItemEx ListItem(strPathName);
ListItem.ComplexUserData = Ptr;
ListBox->AddItem(std::move(ListItem));
}
auto& FindItem = AddFindListItem(FindData, UserData);
FindItem.FindData.FileName = FullName;
FindItem.Used=1;
FindItem.Arc = Arc;
int ListPos;
{
MenuItemEx ListItem(MenuText);
ListItem.ComplexUserData = &FindItem;
ListPos = ListBox->AddItem(std::move(ListItem));
}
// Выделим как положено - в списке.
if (!m_FileCount && !m_DirCount)
{
ListBox->SetSelectPos(ListPos, -1);
}
if (FindData.Attributes & FILE_ATTRIBUTE_DIRECTORY)
{
++m_DirCount;
}
else
{
++m_FileCount;
}
++m_LastFoundNumber;
}
void background_searcher::AddMenuRecord(string_view const FullName, PluginPanelItem& FindData) const
{
os::fs::find_data fdata;
PluginPanelItemToFindDataEx(FindData, fdata);
m_Owner->m_Messages.emplace(messages::menu_data{ FullName, fdata, FindData.UserData, m_FindFileArcItem });
FindData.UserData.FreeData = nullptr; //передано в FINDLIST
}
void background_searcher::ArchiveSearch(string_view const ArcName)
{
std::unique_ptr<plugin_panel> hArc;
{
const auto SavePluginsOutput = std::exchange(Global->DisablePluginsOutput, true);
string strArcName(ArcName);
{
SCOPED_ACTION(auto)(m_Owner->ScopedLock());
hArc = Global->CtrlObject->Plugins->OpenFilePlugin(&strArcName, OPM_FIND, OFP_SEARCH);
}
Global->DisablePluginsOutput = SavePluginsOutput;
}
if (!hArc)
return;
const auto SaveSearchMode = SearchMode;
const auto SaveArcItem = m_FindFileArcItem;
{
const auto SavePluginsOutput = std::exchange(Global->DisablePluginsOutput, true);
// BUGBUG
const_cast<FINDAREA&>(SearchMode) = FINDAREA_FROM_CURRENT;
OpenPanelInfo Info;
{
SCOPED_ACTION(auto)(m_Owner->ScopedLock());
Global->CtrlObject->Plugins->GetOpenPanelInfo(hArc.get(), &Info);
}
m_FindFileArcItem = &m_Owner->itd->AddArcListItem(ArcName, hArc.get(), Info.Flags, NullToEmpty(Info.CurDir));
// Запомним каталог перед поиском в архиве. И если ничего не нашли - не рисуем его снова.
{
// Запомним пути поиска в плагине, они могут измениться.
const auto strSaveSearchPath = strPluginSearchPath;
m_Owner->m_Messages.emplace(messages::push{});
DoPreparePluginListImpl();
strPluginSearchPath = strSaveSearchPath;
{
SCOPED_ACTION(auto)(m_Owner->ScopedLock());
Global->CtrlObject->Plugins->ClosePanel(std::move(hArc));
m_FindFileArcItem->hPlugin = {};
}
m_Owner->m_Messages.emplace(messages::pop{});
}
Global->DisablePluginsOutput=SavePluginsOutput;
}
m_FindFileArcItem = SaveArcItem;
// BUGBUG
const_cast<FINDAREA&>(SearchMode) = SaveSearchMode;
}
void background_searcher::DoScanTree(string_view const strRoot)
{
ScanTree ScTree(
false,
!(SearchMode==FINDAREA_CURRENT_ONLY||SearchMode==FINDAREA_INPATH),
Global->Opt->FindOpt.FindSymLinks,
true
);
if (SearchMode==FINDAREA_SELECTED)
Global->CtrlObject->Cp()->ActivePanel()->GetSelName(nullptr);
os::fs::find_data FindData;
while (!Stopped())
{
string strCurRoot;
if (SearchMode==FINDAREA_SELECTED)
{
string strSelName;
if (!Global->CtrlObject->Cp()->ActivePanel()->GetSelName(&strSelName, nullptr, &FindData))
break;
if (!(FindData.Attributes & FILE_ATTRIBUTE_DIRECTORY) || IsParentDirectory(strSelName))
continue;
strCurRoot = path::join(strRoot, strSelName);
}
else
{
strCurRoot = strRoot;
}
ScTree.SetFindPath(strCurRoot, L"*"sv);
m_Owner->m_Messages.emplace(messages::status{ strCurRoot });
string strFullName;
while (!Stopped() && ScTree.GetNextName(FindData, strFullName))
{
std::this_thread::yield();
PauseEvent.wait();
const auto ProcessStream = [&](string_view const FullStreamName)
{
if (UseFilter)
{
const auto FilterResult = m_Owner->GetFilter()->FileInFilterEx(FindData, FullStreamName);
switch (FilterResult.Action)
{
case filter_action::include:
break;
case filter_action::exclude:
if (FindData.Attributes & FILE_ATTRIBUTE_DIRECTORY)
ScTree.SkipDir();
return !Stopped();
case filter_action::ignore:
if (FilterResult.State & filter_state::has_include)
return !Stopped();
break;
}
}
if (FindData.Attributes & FILE_ATTRIBUTE_DIRECTORY)
{
m_Owner->m_Messages.emplace(messages::status{ string(FullStreamName) });
}
if (IsFileIncluded(nullptr, FullStreamName, FindData.Attributes, strFullName))
{
m_Owner->m_Messages.emplace(messages::menu_data{ FullStreamName, FindData, {}, {} });
}
if (SearchInArchives)
ArchiveSearch(FullStreamName);
return !Stopped();
};
// default stream first:
if (!ProcessStream(strFullName))
break;
// now the rest:
if (Global->Opt->FindOpt.FindAlternateStreams)
{
const auto FindDataFileName = FindData.FileName;
for(const auto& StreamData: os::fs::enum_streams(strFullName))
{
string_view StreamName(StreamData.cStreamName + 1);
const auto NameEnd = StreamName.rfind(L':');
if (NameEnd != StreamName.npos)
StreamName = StreamName.substr(0, NameEnd);
if (StreamName.empty()) // default stream has already been processed
continue;
const auto FullStreamName = concat(strFullName, L':', StreamName);
FindData.FileName = concat(FindDataFileName, L':', StreamName);
FindData.FileSize = StreamData.StreamSize.QuadPart;
FindData.Attributes &= ~FILE_ATTRIBUTE_DIRECTORY;
if (!ProcessStream(FullStreamName))
break;
}
}
}
if (SearchMode!=FINDAREA_SELECTED)
break;
}
}
void background_searcher::ScanPluginTree(plugin_panel* hPlugin, unsigned long long Flags, int& RecurseLevel)
{
span<PluginPanelItem> PanelData;
bool GetFindDataResult=false;
if(!Stopped())
{
SCOPED_ACTION(auto)(m_Owner->ScopedLock());
GetFindDataResult = Global->CtrlObject->Plugins->GetFindData(hPlugin, PanelData, OPM_FIND) != FALSE;
}
if (!GetFindDataResult)
{
return;
}
RecurseLevel++;
if (SearchMode!=FINDAREA_SELECTED || RecurseLevel!=1)
{
for (auto& CurPanelItem: PanelData)
{
if (Stopped())
break;
std::this_thread::yield();
PauseEvent.wait();
string_view CurName = NullToEmpty(CurPanelItem.FileName);
if (CurName.empty() || IsParentDirectory(CurPanelItem))
continue;
if (UseFilter && !m_Owner->GetFilter()->FileInFilter(CurPanelItem))
continue;
const auto strFullName = concat(strPluginSearchPath, CurName);
if (CurPanelItem.FileAttributes & FILE_ATTRIBUTE_DIRECTORY)
{
m_Owner->m_Messages.emplace(messages::status{ strFullName });
}
if (IsFileIncluded(&CurPanelItem, CurName, CurPanelItem.FileAttributes, strFullName))
AddMenuRecord(strFullName, CurPanelItem);
if (SearchInArchives && (Flags & OPIF_REALNAMES))
ArchiveSearch(strFullName);
}
}
if (SearchMode!=FINDAREA_CURRENT_ONLY)
{
OpenPanelInfo PanelInfo{};
{
SCOPED_ACTION(auto)(m_Owner->ScopedLock());
Global->CtrlObject->Plugins->GetOpenPanelInfo(hPlugin, &PanelInfo);
}
auto ParentPointSeen = (PanelInfo.Flags & OPIF_ADDDOTS) != 0;
for (const auto& CurPanelItem: PanelData)
{
if (Stopped())
break;
if (!(CurPanelItem.FileAttributes & FILE_ATTRIBUTE_DIRECTORY))
continue;
if (!ParentPointSeen && IsParentDirectory(CurPanelItem))
{
ParentPointSeen = true;
continue;
}
if (UseFilter && !m_Owner->GetFilter()->FileInFilter(CurPanelItem))
continue;
if ((SearchMode == FINDAREA_SELECTED && RecurseLevel == 1 && !Global->CtrlObject->Cp()->ActivePanel()->IsSelected(CurPanelItem.FileName)))
continue;
int SetDirectoryResult;
{
SCOPED_ACTION(auto)(m_Owner->ScopedLock());
SetDirectoryResult = Global->CtrlObject->Plugins->SetDirectory(hPlugin, CurPanelItem.FileName, OPM_FIND, &CurPanelItem.UserData);
}
if (!SetDirectoryResult)
continue;
if (!*CurPanelItem.FileName)
continue;
append(strPluginSearchPath, CurPanelItem.FileName, path::separator);
ScanPluginTree(hPlugin, Flags, RecurseLevel);
size_t pos = strPluginSearchPath.rfind(path::separator);
if (pos != string::npos)
strPluginSearchPath.resize(pos);
if ((pos = strPluginSearchPath.rfind(path::separator)) != string::npos)
strPluginSearchPath.resize(pos+1);
else
strPluginSearchPath.clear();
{
SCOPED_ACTION(auto)(m_Owner->ScopedLock());
SetDirectoryResult = Global->CtrlObject->Plugins->SetDirectory(hPlugin, L".."s, OPM_FIND);
}
if (!SetDirectoryResult)
{
// BUGBUG, better way to stop searcher?
Stop();
}
}
}
{
SCOPED_ACTION(auto)(m_Owner->ScopedLock());
Global->CtrlObject->Plugins->FreeFindData(hPlugin, PanelData, true);
}
RecurseLevel--;
}
void background_searcher::DoPrepareFileList()
{
std::vector<string> Locations;
if (SearchMode==FINDAREA_INPATH)
{
for (const auto& i: enum_tokens_with_quotes(os::env::get(L"PATH"sv), L";"sv))
{
if (i.empty())
continue;
Locations.emplace_back(i);
}
}
else if (SearchMode==FINDAREA_ROOT)
{
Locations = {GetPathRoot(Global->CtrlObject->CmdLine()->GetCurDir())};
}
else if (SearchMode==FINDAREA_ALL || SearchMode==FINDAREA_ALL_BUTNETWORK)
{
const auto Drives = os::fs::get_logical_drives() & allowed_drives_mask();
const auto is_acceptable_drive = [&](string_view const RootDirectory)
{
const auto Type = os::fs::drive::get_type(RootDirectory);
return Type == DRIVE_FIXED || Type == DRIVE_RAMDISK || (SearchMode != FINDAREA_ALL_BUTNETWORK && Type == DRIVE_REMOTE);
};
for (const auto& i: os::fs::enum_drives(Drives))
{
auto RootDir = os::fs::drive::get_root_directory(i);
if (!is_acceptable_drive(RootDir))
continue;
Locations.emplace_back(std::move(RootDir));
}
for (auto& VolumeName: os::fs::enum_volumes())
{
if (!is_acceptable_drive(VolumeName))
continue;
if (const auto DriveLetter = get_volume_drive(VolumeName); DriveLetter && Drives[os::fs::drive::get_number(*DriveLetter)])
continue;
Locations.emplace_back(std::move(VolumeName));
}
}
else
{
Locations = {Global->CtrlObject->CmdLine()->GetCurDir()};
}
for (const auto& i: Locations)
{
DoScanTree(i);
}
}
void background_searcher::DoPreparePluginListImpl()
{
const auto ArcItem = m_FindFileArcItem;
OpenPanelInfo Info;
string strSaveDir;
{
SCOPED_ACTION(auto)(m_Owner->ScopedLock());
Global->CtrlObject->Plugins->GetOpenPanelInfo(ArcItem->hPlugin,&Info);
strSaveDir = NullToEmpty(Info.CurDir);
if (SearchMode==FINDAREA_ROOT || SearchMode==FINDAREA_ALL || SearchMode==FINDAREA_ALL_BUTNETWORK || SearchMode==FINDAREA_INPATH)
{
Global->CtrlObject->Plugins->SetDirectory(ArcItem->hPlugin, L"\\"s, OPM_FIND);
Global->CtrlObject->Plugins->GetOpenPanelInfo(ArcItem->hPlugin,&Info);
}
}
strPluginSearchPath = NullToEmpty(Info.CurDir);
if (!strPluginSearchPath.empty())
AddEndSlash(strPluginSearchPath);
int RecurseLevel=0;
ScanPluginTree(ArcItem->hPlugin, ArcItem->Flags, RecurseLevel);
if (SearchMode==FINDAREA_ROOT || SearchMode==FINDAREA_ALL || SearchMode==FINDAREA_ALL_BUTNETWORK || SearchMode==FINDAREA_INPATH)
{
SCOPED_ACTION(auto)(m_Owner->ScopedLock());
Global->CtrlObject->Plugins->SetDirectory(ArcItem->hPlugin,strSaveDir,OPM_FIND,&Info.UserData);
}
}
void background_searcher::DoPreparePluginList()
{
DoPreparePluginListImpl();
}
struct THREADPARAM
{
bool PluginMode;
};
void background_searcher::Search()
{
os::debug::set_thread_name(L"Find file");
seh_try_thread(m_ExceptionPtr, [this]
{
cpp_try(
[&]
{
SCOPED_ACTION(wakeful);
InitInFileSearch();
m_PluginMode? DoPreparePluginList() : DoPrepareFileList();
ReleaseInFileSearch();
},
[&]
{
SAVE_EXCEPTION_TO(m_ExceptionPtr);
m_IsRegularException = true;
});
});
m_Owner->m_Messages.emplace(messages::percent{});
m_TaskbarProgress.reset();
m_Finished = true;
}
bool FindFiles::FindFilesProcess()
{
// Если используется фильтр операций, то во время поиска сообщаем об этом
string strTitle=msg(lng::MFindFileTitle);
itd->Init();
m_FileCount = 0;
m_DirCount = 0;
m_LastFoundNumber = 0;
m_LastDirName.clear();
if (!strFindMask.empty())
{
append(strTitle, L": "sv, strFindMask);
if (UseFilter)
{
append(strTitle, L" ("sv, msg(lng::MFindUsingFilter), L')');
}
}
else
{
if (UseFilter)
{
append(strTitle, L" ("sv, msg(lng::MFindUsingFilter), L')');
}
}
int DlgWidth = ScrX + 1 - 2;
int DlgHeight = ScrY + 1 - 2;
auto FindDlg = MakeDialogItems<FD_COUNT>(
{
{ DI_DOUBLEBOX, {{3, 1}, {DlgWidth-4, DlgHeight-2}}, DIF_SHOWAMPERSAND, strTitle, },
{ DI_LISTBOX, {{4, 2}, {DlgWidth-5, DlgHeight-7}}, DIF_LISTNOBOX|DIF_DISABLE, },
{ DI_TEXT, {{-1, DlgHeight-6}, {0, DlgHeight-6}}, DIF_SEPARATOR2, },
{ DI_TEXT, {{5, DlgHeight-5}, {DlgWidth-(strFindStr.empty()? 6 : 12), DlgHeight-5}}, DIF_SHOWAMPERSAND, L"…"sv },
{ DI_TEXT, {{DlgWidth-9, DlgHeight-5}, {DlgWidth-6, DlgHeight-5}}, (strFindStr.empty() ? DIF_HIDDEN : DIF_NONE), },
{ DI_TEXT, {{-1, DlgHeight-4}, {0, DlgHeight-4}}, DIF_SEPARATOR, },
{ DI_BUTTON, {{0, DlgHeight-3}, {0, DlgHeight-3}}, DIF_CENTERGROUP | DIF_FOCUS | DIF_DEFAULTBUTTON, msg(lng::MFindNewSearch), },
{ DI_BUTTON, {{0, DlgHeight-3}, {0, DlgHeight-3}}, DIF_CENTERGROUP | DIF_DISABLE, msg(lng::MFindGoTo), },
{ DI_BUTTON, {{0, DlgHeight-3}, {0, DlgHeight-3}}, DIF_CENTERGROUP | DIF_DISABLE, msg(lng::MFindView), },
{ DI_BUTTON, {{0, DlgHeight-3}, {0, DlgHeight-3}}, DIF_CENTERGROUP | DIF_DISABLE, msg(lng::MFindPanel), },
{ DI_BUTTON, {{0, DlgHeight-3}, {0, DlgHeight-3}}, DIF_CENTERGROUP, msg(lng::MFindStop), },
});
ArcListItem* FindFileArcItem{};
if (PluginMode)
{
const auto hPlugin = Global->CtrlObject->Cp()->ActivePanel()->GetPluginHandle();
OpenPanelInfo Info;
// no lock - background thread hasn't been started yet
Global->CtrlObject->Plugins->GetOpenPanelInfo(hPlugin,&Info);
FindFileArcItem = &itd->AddArcListItem(NullToEmpty(Info.HostFile), hPlugin, Info.Flags, NullToEmpty(Info.CurDir));
if (!(Info.Flags & OPIF_REALNAMES))
{
FindDlg[FD_BUTTON_PANEL].Type=DI_TEXT;
FindDlg[FD_BUTTON_PANEL].strData.clear();
}
}
AnySetFindList = std::any_of(CONST_RANGE(*Global->CtrlObject->Plugins, i)
{
return i->has(iSetFindList);
});
if (!AnySetFindList)
{
FindDlg[FD_BUTTON_PANEL].Flags|=DIF_DISABLE;
}
const auto Dlg = Dialog::create(FindDlg, &FindFiles::FindDlgProc, this);
Dlg->SetHelp(L"FindFileResult"sv);
Dlg->SetPosition({ -1, -1, DlgWidth, DlgHeight });
Dlg->SetId(FindFileResultId);
Dlg->SetFlags(FSCROBJ_SPECIAL);
m_ResultsDialogPtr = Dlg.get();
{
background_searcher BC(this, strFindStr, SearchMode, FindFileArcItem, CodePage, ConvertFileSizeString(Global->Opt->FindOpt.strSearchInFirstSize), CmpCase, WholeWords, SearchInArchives, SearchHex, NotContaining, UseFilter, PluginMode);
// BUGBUG
m_Searcher = &BC;
// Надо бы показать диалог, а то инициализация элементов запаздывает
// иногда при поиске и первые элементы не добавляются
Dlg->InitDialog();
Dlg->Show();
os::thread FindThread(os::thread::mode::join, &background_searcher::Search, &BC);
// In case of an exception in the main thread
SCOPE_EXIT
{
stop_and_discard(Dlg.get());
Dlg->CloseDialog();
m_Searcher = nullptr;
};
listener Listener([&]
{
if (m_TimeCheck)
Dlg->SendMessage(DM_REFRESH, 0, {});
});
m_UpdateTimer = os::concurrency::timer(till_next_second(), GetRedrawTimeout(), [&]
{
message_manager::instance().notify(Listener.GetEventName());
});
SCOPE_EXIT{ m_UpdateTimer = {}; };
Dlg->Process();
if (!m_ExceptionPtr)
{
m_ExceptionPtr = BC.ExceptionPtr();
}
if (m_ExceptionPtr && !BC.IsRegularException())
{
// You're someone else's problem
FindThread.detach();
}
rethrow_if(m_ExceptionPtr);
}
switch (Dlg->GetExitCode())
{
case FD_BUTTON_NEW:
{
return true;
}
case FD_BUTTON_PANEL:
// Отработаем переброску на временную панель
{
plugin_item_list PanelItems;
PanelItems.reserve(m_FindList.size());
for (auto& i: m_FindList)
{
if (!i.FindData.FileName.empty() && i.Used)
{
// Добавляем всегда, если имя задано
// Для плагинов с виртуальными именами заменим имя файла на имя архива.
// панель сама уберет лишние дубли.
const auto IsArchive = i.Arc && !(i.Arc->Flags&OPIF_REALNAMES);
// Добавляем только файлы или имена архивов или папки когда просили
if (IsArchive || (Global->Opt->FindOpt.FindFolders && !SearchHex) ||
!(i.FindData.Attributes&FILE_ATTRIBUTE_DIRECTORY))
{
if (IsArchive)
{
i.FindData.FileName = i.Arc->strArcName;
}
PluginPanelItemHolderHeapNonOwning pi;
FindDataExToPluginPanelItemHolder(i.FindData, pi);
if (IsArchive)
pi.Item.FileAttributes = 0;
if (pi.Item.FileAttributes & FILE_ATTRIBUTE_DIRECTORY)
{
DeleteEndSlash(const_cast<wchar_t*>(pi.Item.FileName));
}
PanelItems.emplace_back(pi.Item);
}
}
}
{
SCOPED_ACTION(std::lock_guard)(PluginCS);
if (auto hNewPlugin = Global->CtrlObject->Plugins->OpenFindListPlugin(PanelItems))
{
const auto NewPanel = Global->CtrlObject->Cp()->ChangePanel(Global->CtrlObject->Cp()->ActivePanel(), panel_type::FILE_PANEL, TRUE, TRUE);
NewPanel->SetPluginMode(std::move(hNewPlugin), {}, true);
NewPanel->SetVisible(true);
NewPanel->Update(0);
//if (FindExitItem)
//NewPanel->GoToFile(FindExitItem->FindData.cFileName);
NewPanel->Show();
}
}
break;
}
case FD_BUTTON_GOTO:
case FD_LISTBOX:
{
string strFileName=FindExitItem->FindData.FileName;
auto FindPanel = Global->CtrlObject->Cp()->ActivePanel();
if (FindExitItem->Arc)
{
if (!FindExitItem->Arc->hPlugin)
{
string strArcName = FindExitItem->Arc->strArcName;
if (FindPanel->GetType() != panel_type::FILE_PANEL)
{
FindPanel = Global->CtrlObject->Cp()->ChangePanel(FindPanel, panel_type::FILE_PANEL, TRUE, TRUE);
}
string_view ArcPath=strArcName;
CutToSlash(ArcPath);
FindPanel->SetCurDir(ArcPath, true);
FindExitItem->Arc->hPlugin = std::static_pointer_cast<FileList>(FindPanel)->OpenFilePlugin(strArcName, FALSE, OFP_SEARCH);
}
if (FindExitItem->Arc->hPlugin)
{
OpenPanelInfo Info;
{
SCOPED_ACTION(std::lock_guard)(PluginCS);
Global->CtrlObject->Plugins->GetOpenPanelInfo(FindExitItem->Arc->hPlugin, &Info);
if (SearchMode == FINDAREA_ROOT ||
SearchMode == FINDAREA_ALL ||
SearchMode == FINDAREA_ALL_BUTNETWORK ||
SearchMode == FINDAREA_INPATH)
Global->CtrlObject->Plugins->SetDirectory(FindExitItem->Arc->hPlugin, L"\\"s, OPM_NONE);
}
SetPluginDirectory(strFileName, FindExitItem->Arc->hPlugin, true, &FindExitItem->UserData);
}
}
else
{
size_t Length=strFileName.size();
if (!Length)
break;
if (Length>1 && path::is_separator(strFileName[Length-1]) && strFileName[Length-2] != L':')
strFileName.pop_back();
if (!os::fs::exists(strFileName) && (GetLastError() != ERROR_ACCESS_DENIED))
break;
const auto NamePtr = PointToName(strFileName);
string strSetName(NamePtr);
if (Global->Opt->FindOpt.FindAlternateStreams)
{
size_t Pos = strSetName.find(L':');
if (Pos != string::npos)
strSetName.resize(Pos);
}
strFileName.resize(strFileName.size() - NamePtr.size());
Length=strFileName.size();
if (Length>1 && path::is_separator(strFileName[Length-1]) && strFileName[Length-2] != L':')
strFileName.pop_back();
if (strFileName.empty())
break;
if (FindPanel->GetType() != panel_type::FILE_PANEL && Global->CtrlObject->Cp()->GetAnotherPanel(FindPanel)->GetType() == panel_type::FILE_PANEL)
FindPanel=Global->CtrlObject->Cp()->GetAnotherPanel(FindPanel);
if ((FindPanel->GetType() != panel_type::FILE_PANEL) || (FindPanel->GetMode() != panel_mode::NORMAL_PANEL))
// Сменим панель на обычную файловую...
{
FindPanel = Global->CtrlObject->Cp()->ChangePanel(FindPanel, panel_type::FILE_PANEL, TRUE, TRUE);
FindPanel->SetVisible(true);
FindPanel->Update(0);
}
// ! Не меняем каталог, если мы уже в нем находимся.
// Тем самым добиваемся того, что выделение с элементов панели не сбрасывается.
string strDirTmp = FindPanel->GetCurDir();
Length=strDirTmp.size();
if (Length>1 && path::is_separator(strDirTmp[Length-1]) && strDirTmp[Length-2] != L':')
strDirTmp.pop_back();
if (!equal_icase(strFileName, strDirTmp))
FindPanel->SetCurDir(strFileName,true);
if (!strSetName.empty())
FindPanel->GoToFile(strSetName);
FindPanel->Show();
FindPanel->Parent()->SetActivePanel(FindPanel);
}
break;
}
}
return false;
}
void FindFiles::ProcessMessage(message& Message)
{
std::visit(overload
{
[&](messages::menu_data const& Data)
{
AddMenuRecord(m_ResultsDialogPtr, Data.m_FullName, Data.m_FindData, Data.m_UserData, Data.m_Arc);
m_EmptyArc = false;
},
[&](messages::push const&)
{
m_LastDir.push(m_LastDirName);
m_LastDirName.clear();
m_EmptyArc = true;
},
[&](messages::pop const&)
{
assert(!m_LastDir.empty());
if (m_EmptyArc)
m_LastDirName = m_LastDir.top();
m_LastDir.pop();
},
[&](messages::status& Status)
{
m_Status = std::move(Status.Value);
},
[&](messages::percent const& Percent)
{
m_Percent = Percent.Value;
}
}, Message);
}
FindFiles::FindFiles():
itd(std::make_unique<InterThreadData>()),
FileMaskForFindFile(std::make_unique<filemasks>()),
Filter(std::make_unique<multifilter>(Global->CtrlObject->Cp()->ActivePanel().get(), FFT_FINDFILE))
{
static string strLastFindMask = L"*.*"s, strLastFindStr;
static string strSearchFromRoot;
strSearchFromRoot = msg(lng::MSearchFromRootFolder);
static bool LastCmpCase = false, LastWholeWords = false, LastSearchInArchives = false, LastSearchHex = false, LastNotContaining = false;
CmpCase=LastCmpCase;
WholeWords=LastWholeWords;
SearchInArchives=LastSearchInArchives;
SearchHex=LastSearchHex;
NotContaining = LastNotContaining;
SearchMode = static_cast<FINDAREA>(Global->Opt->FindOpt.FileSearchMode.Get());
UseFilter=Global->Opt->FindOpt.UseFilter.Get();
strFindMask = strLastFindMask;
strFindStr = strLastFindStr;
do
{
FindExitItem = nullptr;
FindFoldersChanged=false;
SearchFromChanged=false;
FindPositionChanged=false;
Finalized=false;
ClearFindList();
itd->ClearAllLists();
const auto ActivePanel = Global->CtrlObject->Cp()->ActivePanel();
PluginMode = ActivePanel->GetMode() == panel_mode::PLUGIN_PANEL && ActivePanel->IsVisible();
PrepareDriveNameStr(strSearchFromRoot);
auto FindAskDlg = MakeDialogItems<FAD_COUNT>(
{
{ DI_DOUBLEBOX, {{3, 1 }, {76, 19}}, DIF_NONE, msg(lng::MFindFileTitle), },
{ DI_TEXT, {{5, 2 }, {0, 2 }}, DIF_NONE, msg(lng::MFindFileMasks), },
{ DI_EDIT, {{5, 3 }, {74, 3 }}, DIF_FOCUS | DIF_HISTORY | DIF_USELASTHISTORY, },
{ DI_TEXT, {{-1, 4 }, {0, 4 }}, DIF_SEPARATOR, },
{ DI_TEXT, {{5, 5 }, {0, 5 }}, DIF_NONE, },
{ DI_EDIT, {{5, 6 }, {74, 6 }}, DIF_HISTORY, },
{ DI_FIXEDIT, {{5, 6 }, {74, 6 }}, DIF_MASKEDIT, },
{ DI_TEXT, {{5, 7 }, {0, 7 }}, DIF_NONE, },
{ DI_COMBOBOX, {{5, 8 }, {74, 8 }}, DIF_DROPDOWNLIST, },
{ DI_TEXT, {{-1, 9 }, {0, 9 }}, DIF_SEPARATOR, },
{ DI_CHECKBOX, {{5, 10}, {0, 10}}, DIF_NONE, msg(lng::MFindFileCase), },
{ DI_CHECKBOX, {{5, 11}, {0, 11}}, DIF_NONE, msg(lng::MFindFileWholeWords), },
{ DI_CHECKBOX, {{5, 12}, {0, 12}}, DIF_NONE, msg(lng::MSearchForHex), },
{ DI_CHECKBOX, {{5, 13}, {0, 13}}, DIF_NONE, msg(lng::MSearchNotContaining), },
{ DI_CHECKBOX, {{41, 10}, {0, 10}}, DIF_NONE, msg(lng::MFindArchives), },
{ DI_CHECKBOX, {{41, 11}, {0, 11}}, DIF_NONE, msg(lng::MFindFolders), },
{ DI_CHECKBOX, {{41, 12}, {0, 12}}, DIF_NONE, msg(lng::MFindSymLinks), },
{ DI_CHECKBOX, {{41, 13}, {0, 13}}, DIF_NONE, msg(lng::MFindAlternateStreams), },
{ DI_TEXT, {{-1, 14}, {0, 14}}, DIF_SEPARATOR, },
{ DI_VTEXT, {{39, 9 }, {39, 14}}, DIF_SEPARATORUSER, },
{ DI_TEXT, {{5, 15}, {0, 15}}, DIF_NONE, msg(lng::MSearchWhere), },
{ DI_COMBOBOX, {{5, 16}, {36, 16}}, DIF_DROPDOWNLIST | DIF_LISTNOAMPERSAND, },
{ DI_CHECKBOX, {{41, 16}, {0, 16}}, DIF_AUTOMATION, msg(lng::MFindUseFilter), },
{ DI_TEXT, {{-1, 17}, {0, 17}}, DIF_SEPARATOR, },
{ DI_BUTTON, {{0, 18}, {0, 18}}, DIF_CENTERGROUP | DIF_DEFAULTBUTTON, msg(lng::MFindFileFind), },
{ DI_BUTTON, {{0, 18}, {0, 18}}, DIF_CENTERGROUP, msg(lng::MFindFileDrive), },
{ DI_BUTTON, {{0, 18}, {0, 18}}, DIF_CENTERGROUP | DIF_AUTOMATION | (UseFilter ? 0 : DIF_DISABLE), msg(lng::MFindFileSetFilter), },
{ DI_BUTTON, {{0, 18}, {0, 18}}, DIF_CENTERGROUP, msg(lng::MFindFileAdvanced), },
{ DI_BUTTON, {{0, 18}, {0, 18}}, DIF_CENTERGROUP, msg(lng::MCancel), },
});
FindAskDlg[FAD_EDIT_MASK].strHistory = L"Masks"sv;
FindAskDlg[FAD_EDIT_TEXT].strHistory = L"SearchText"sv;
FindAskDlg[FAD_EDIT_HEX].strMask = L"HH HH HH HH HH HH HH HH HH HH HH HH HH HH HH HH HH HH HH HH HH HH HH"sv;
FindAskDlg[FAD_CHECKBOX_NOTCONTAINING].Selected = NotContaining;
FindAskDlg[FAD_SEPARATOR_3].strMask = { BoxSymbols[BS_T_H1V1], BoxSymbols[BS_V1], BoxSymbols[BS_B_H1V1] };
FindAskDlg[FAD_CHECKBOX_FILTER].Selected = UseFilter;
if (strFindStr.empty())
FindAskDlg[FAD_CHECKBOX_DIRS].Selected=Global->Opt->FindOpt.FindFolders;
FarListItem li[]=
{
{ 0, msg(lng::MSearchAllDisks).c_str() },
{ 0, msg(lng::MSearchAllButNetwork).c_str() },
{ 0, msg(lng::MSearchInPATH).c_str() },
{ 0, strSearchFromRoot.c_str() },
{ 0, msg(lng::MSearchFromCurrent).c_str() },
{ 0, msg(lng::MSearchInCurrent).c_str() },
{ 0, msg(lng::MSearchInSelected).c_str() },
};
static_assert(std::size(li) == FINDAREA_COUNT);
li[FINDAREA_ALL + SearchMode].Flags|=LIF_SELECTED;
FarList l={sizeof(FarList),std::size(li),li};
FindAskDlg[FAD_COMBOBOX_WHERE].ListItems=&l;
if (PluginMode)
{
OpenPanelInfo Info;
// no lock - background thread hasn't been started yet
Global->CtrlObject->Plugins->GetOpenPanelInfo(ActivePanel->GetPluginHandle(),&Info);
if (!(Info.Flags & OPIF_REALNAMES))
FindAskDlg[FAD_CHECKBOX_ARC].Flags |= DIF_DISABLE;
if (SearchMode == FINDAREA_ALL || SearchMode == FINDAREA_ALL_BUTNETWORK)
{
li[FINDAREA_ALL].Flags=0;
li[FINDAREA_ALL_BUTNETWORK].Flags=0;
li[FINDAREA_ROOT].Flags|=LIF_SELECTED;
}
li[FINDAREA_ALL].Flags|=LIF_GRAYED;
li[FINDAREA_ALL_BUTNETWORK].Flags|=LIF_GRAYED;
FindAskDlg[FAD_CHECKBOX_LINKS].Selected=0;
FindAskDlg[FAD_CHECKBOX_LINKS].Flags|=DIF_DISABLE;
FindAskDlg[FAD_CHECKBOX_STREAMS].Selected = 0;
FindAskDlg[FAD_CHECKBOX_STREAMS].Flags |= DIF_DISABLE;
}
else
{
FindAskDlg[FAD_CHECKBOX_LINKS].Selected = Global->Opt->FindOpt.FindSymLinks;
FindAskDlg[FAD_CHECKBOX_STREAMS].Selected = Global->Opt->FindOpt.FindAlternateStreams;
}
if (!(FindAskDlg[FAD_CHECKBOX_ARC].Flags & DIF_DISABLE))
FindAskDlg[FAD_CHECKBOX_ARC].Selected=SearchInArchives;
FindAskDlg[FAD_EDIT_MASK].strData = strFindMask;
if (SearchHex)
FindAskDlg[FAD_EDIT_HEX].strData = strFindStr;
else
FindAskDlg[FAD_EDIT_TEXT].strData = strFindStr;
FindAskDlg[FAD_CHECKBOX_CASE].Selected=CmpCase;
FindAskDlg[FAD_CHECKBOX_WHOLEWORDS].Selected=WholeWords;
FindAskDlg[FAD_CHECKBOX_HEX].Selected=SearchHex;
const auto Dlg = Dialog::create(FindAskDlg, &FindFiles::MainDlgProc, this);
Dlg->SetAutomation(FAD_CHECKBOX_FILTER,FAD_BUTTON_FILTER,DIF_DISABLE,DIF_NONE,DIF_NONE,DIF_DISABLE);
Dlg->SetHelp(L"FindFile"sv);
Dlg->SetId(FindFileId);
Dlg->SetPosition({ -1, -1, 80, 21 });
Dlg->Process();
const auto ExitCode = Dlg->GetExitCode();
//Рефреш текущему времени для фильтра сразу после выхода из диалога
Filter->UpdateCurrentTime();
if (ExitCode!=FAD_BUTTON_FIND)
{
return;
}
Global->Opt->FindCodePage = CodePage;
CmpCase=FindAskDlg[FAD_CHECKBOX_CASE].Selected == BSTATE_CHECKED;
WholeWords=FindAskDlg[FAD_CHECKBOX_WHOLEWORDS].Selected == BSTATE_CHECKED;
SearchHex=FindAskDlg[FAD_CHECKBOX_HEX].Selected == BSTATE_CHECKED;
SearchInArchives=FindAskDlg[FAD_CHECKBOX_ARC].Selected == BSTATE_CHECKED;
NotContaining = FindAskDlg[FAD_CHECKBOX_NOTCONTAINING].Selected == BSTATE_CHECKED;
if (FindFoldersChanged)
{
Global->Opt->FindOpt.FindFolders=(FindAskDlg[FAD_CHECKBOX_DIRS].Selected==BSTATE_CHECKED);
}
if (!PluginMode)
{
Global->Opt->FindOpt.FindSymLinks=(FindAskDlg[FAD_CHECKBOX_LINKS].Selected==BSTATE_CHECKED);
Global->Opt->FindOpt.FindAlternateStreams = (FindAskDlg[FAD_CHECKBOX_STREAMS].Selected == BSTATE_CHECKED);
}
UseFilter=(FindAskDlg[FAD_CHECKBOX_FILTER].Selected==BSTATE_CHECKED);
Global->Opt->FindOpt.UseFilter=UseFilter;
strFindMask = !FindAskDlg[FAD_EDIT_MASK].strData.empty()? FindAskDlg[FAD_EDIT_MASK].strData : L"*"sv;
if (SearchHex)
{
strFindStr = ExtractHexString(FindAskDlg[FAD_EDIT_HEX].strData);
}
else
strFindStr = FindAskDlg[FAD_EDIT_TEXT].strData;
if (!strFindStr.empty())
{
Global->StoreSearchString(strFindStr, SearchHex);
Global->GlobalSearchCase=CmpCase;
Global->GlobalSearchWholeWords=WholeWords;
}
SearchMode = static_cast<FINDAREA>(FindAskDlg[FAD_COMBOBOX_WHERE].ListPos);
if (SearchFromChanged)
{
Global->Opt->FindOpt.FileSearchMode=SearchMode;
}
LastCmpCase=CmpCase;
LastWholeWords=WholeWords;
LastSearchHex=SearchHex;
LastSearchInArchives=SearchInArchives;
LastNotContaining = NotContaining;
strLastFindMask = strFindMask;
strLastFindStr = strFindStr;
if (!strFindStr.empty())
Editor::SetReplaceMode(false);
}
while (FindFilesProcess());
Global->CtrlObject->Cp()->ActivePanel()->RefreshTitle();
}
FindFiles::~FindFiles()
{
ClearFindList();
}
background_searcher::background_searcher(
FindFiles* Owner,
string FindString,
FINDAREA SearchMode,
ArcListItem* FindFileArcItem,
uintptr_t CodePage,
unsigned long long SearchInFirst,
bool CmpCase,
bool WholeWords,
bool SearchInArchives,
bool SearchHex,
bool NotContaining,
bool UseFilter,
bool PluginMode):
m_Owner(Owner),
m_Autodetection(),
strFindStr(std::move(FindString)),
SearchMode(SearchMode),
m_FindFileArcItem(FindFileArcItem),
CodePage(CodePage),
SearchInFirst(SearchInFirst),
CmpCase(CmpCase),
WholeWords(WholeWords),
SearchInArchives(SearchInArchives),
SearchHex(SearchHex),
NotContaining(NotContaining),
UseFilter(UseFilter),
m_PluginMode(PluginMode),
PauseEvent(os::event::type::manual, os::event::state::signaled),
StopEvent(os::event::type::manual, os::event::state::nonsignaled)
{
}
void find_files()
{
FindFiles();
}
|
#include <bits/stdc++.h>
using namespace std;
const int SIZE=524288*2;
int num[1000001];
struct segTree{
int size,leaf;
long long tree[SIZE];
segTree(int n): size(n){
leaf = 1;
while(leaf<size) leaf *= 2;
memset(tree,0,sizeof(tree));
}
long long sum(int l, int r){
return sum(1,l,r,0,leaf-1);
}
long long sum(int node, int l, int r, int n_l, int n_r){
if(l<=n_l && n_r<=r) return tree[node];
if(r<n_l || n_r<l) return 0;
int mid=(n_l+n_r)/2;
return sum(node*2,l,r,n_l,mid)+sum(node*2+1,l,r,mid+1,n_r);
}
void update(int index, long long value){
int st=leaf+index;
long long diff=value-tree[st];
while(st>0){
tree[st] += diff;
st /= 2;
}
}
};
int main(){
int n,m;
scanf("%d", &n);
vector<int> arr(n);
segTree st(n);
for(int i=0;i<n;i++){
scanf("%d", &m);
num[m] = i;
}
for(int i=0;i<n;i++){
scanf("%d", &m);
arr[num[m]] = i;
}
long long ret=0;
for(int i=0;i<n;i++){
int ind=arr[i];
ret += st.sum(ind+1,n-1);
st.update(ind, 1);
}
printf("%lld\n", ret);
return 0;
}
|
/*
* Copyright (c) 1999-2008 Mark D. Hill and David A. Wood
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are
* met: redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer;
* redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution;
* neither the name of the copyright holders nor the names of 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.
*/
/*
* Common base class for a machine node.
*/
#ifndef __MEM_RUBY_SLICC_INTERFACE_ABSTRACTCACHEENTRY_HH__
#define __MEM_RUBY_SLICC_INTERFACE_ABSTRACTCACHEENTRY_HH__
#include <iostream>
#include "mem/protocol/AccessPermission.hh"
#include "mem/ruby/common/Address.hh"
#include "mem/ruby/slicc_interface/AbstractEntry.hh"
class DataBlock;
class AbstractCacheEntry : public AbstractEntry
{
public:
AbstractCacheEntry();
virtual ~AbstractCacheEntry() = 0;
// Get/Set permission of the entry
void changePermission(AccessPermission new_perm);
Address m_Address; // Address of this block, required by CacheMemory
int m_locked; // Holds info whether the address is locked,
// required for implementing LL/SC
};
inline std::ostream&
operator<<(std::ostream& out, const AbstractCacheEntry& obj)
{
obj.print(out);
out << std::flush;
return out;
}
#endif // __MEM_RUBY_SLICC_INTERFACE_ABSTRACTCACHEENTRY_HH__
|
/*
* Copyright (c) 2017-2018, The Alloy Developers.
*
* This file is part of Alloy.
*
* This file is subject to the terms and conditions defined in the
* file 'LICENSE', which is part of this source code package.
*/
#include "BinaryOutputStreamSerializer.h"
#include <cassert>
#include <stdexcept>
#include "Common/StreamTools.h"
using namespace Common;
namespace CryptoNote {
ISerializer::SerializerType BinaryOutputStreamSerializer::type() const {
return ISerializer::OUTPUT;
}
bool BinaryOutputStreamSerializer::beginObject(Common::StringView name) {
return true;
}
void BinaryOutputStreamSerializer::endObject() {
}
bool BinaryOutputStreamSerializer::beginArray(size_t& size, Common::StringView name) {
writeVarint(stream, size);
return true;
}
void BinaryOutputStreamSerializer::endArray() {
}
bool BinaryOutputStreamSerializer::operator()(uint8_t& value, Common::StringView name) {
writeVarint(stream, value);
return true;
}
bool BinaryOutputStreamSerializer::operator()(uint16_t& value, Common::StringView name) {
writeVarint(stream, value);
return true;
}
bool BinaryOutputStreamSerializer::operator()(int16_t& value, Common::StringView name) {
writeVarint(stream, static_cast<uint16_t>(value));
return true;
}
bool BinaryOutputStreamSerializer::operator()(uint32_t& value, Common::StringView name) {
writeVarint(stream, value);
return true;
}
bool BinaryOutputStreamSerializer::operator()(int32_t& value, Common::StringView name) {
writeVarint(stream, static_cast<uint32_t>(value));
return true;
}
bool BinaryOutputStreamSerializer::operator()(int64_t& value, Common::StringView name) {
writeVarint(stream, static_cast<uint64_t>(value));
return true;
}
bool BinaryOutputStreamSerializer::operator()(uint64_t& value, Common::StringView name) {
writeVarint(stream, value);
return true;
}
bool BinaryOutputStreamSerializer::operator()(bool& value, Common::StringView name) {
char boolVal = value;
checkedWrite(&boolVal, 1);
return true;
}
bool BinaryOutputStreamSerializer::operator()(std::string& value, Common::StringView name) {
writeVarint(stream, value.size());
checkedWrite(value.data(), value.size());
return true;
}
bool BinaryOutputStreamSerializer::binary(void* value, size_t size, Common::StringView name) {
checkedWrite(static_cast<const char*>(value), size);
return true;
}
bool BinaryOutputStreamSerializer::binary(std::string& value, Common::StringView name) {
// write as string (with size prefix)
return (*this)(value, name);
}
bool BinaryOutputStreamSerializer::operator()(double& value, Common::StringView name) {
assert(false); //the method is not supported for this type of serialization
throw std::runtime_error("double serialization is not supported in BinaryOutputStreamSerializer");
return false;
}
void BinaryOutputStreamSerializer::checkedWrite(const char* buf, size_t size) {
write(stream, buf, size);
}
}
|
#include<bits/stdc++.h>
using namespace std;
typedef long long ll;
ll getyins(ll x)
{
ll res(0);
for (ll i = 1; i * i <= x; i++)
{
if (!(x % i))
{
(i * i != x)? res += 2: res++;
}
}
return res;
}
ll read()
{
ll x = 0; char ch = getchar();
while (!isdigit(ch))
{
ch = getchar();
}
while (isdigit(ch))
{
x = (x << 3) + (x << 1) + (ch ^ 48);
ch = getchar();
}
return x;
}
int main()
{
ll n =read(), ans = 0;
for (int i = 1; i <= n; i++)
{
ll t = read();
ans = __gcd(ans, t);
}
cout << getyins(ans) << endl;
return 0;
}
|
#ifndef CENTURION_SYSTEM_CURSOR_HEADER
#define CENTURION_SYSTEM_CURSOR_HEADER
#include <SDL2/SDL.h>
#include <ostream> // ostream
#include <string_view> // string_view
#include "../core/exception.hpp"
namespace cen {
/// \addtogroup video
/// \{
/**
* \enum system_cursor
*
* \brief Represents the various available system cursors.
*
* \since 4.0.0
*
* \see `SDL_SystemCursor`
* \see `system_cursor_count()`
*/
enum class system_cursor
{
arrow = SDL_SYSTEM_CURSOR_ARROW,
ibeam = SDL_SYSTEM_CURSOR_IBEAM,
wait = SDL_SYSTEM_CURSOR_WAIT,
crosshair = SDL_SYSTEM_CURSOR_CROSSHAIR,
wait_arrow = SDL_SYSTEM_CURSOR_WAITARROW,
arrow_nw_se = SDL_SYSTEM_CURSOR_SIZENWSE,
arrow_ne_sw = SDL_SYSTEM_CURSOR_SIZENESW,
arrow_w_e = SDL_SYSTEM_CURSOR_SIZEWE,
arrow_n_s = SDL_SYSTEM_CURSOR_SIZENS,
arrow_all = SDL_SYSTEM_CURSOR_SIZEALL,
no = SDL_SYSTEM_CURSOR_NO,
hand = SDL_SYSTEM_CURSOR_HAND
};
/**
* \brief Returns the number of available system cursors.
*
* \return the number of system cursors.
*
* \since 6.2.0
*/
[[nodiscard]] constexpr auto system_cursor_count() noexcept -> int
{
return SDL_NUM_SYSTEM_CURSORS;
}
/// \name String conversions
/// \{
/**
* \brief Returns a textual version of the supplied system cursor.
*
* \details This function returns a string that mirrors the name of the enumerator, e.g.
* `to_string(system_cursor::hand) == "hand"`.
*
* \param cursor the enumerator that will be converted.
*
* \return a string that mirrors the name of the enumerator.
*
* \throws cen_error if the enumerator is not recognized.
*
* \since 6.2.0
*/
[[nodiscard]] constexpr auto to_string(const system_cursor cursor) -> std::string_view
{
switch (cursor) {
case system_cursor::arrow:
return "arrow";
case system_cursor::ibeam:
return "ibeam";
case system_cursor::wait:
return "wait";
case system_cursor::crosshair:
return "crosshair";
case system_cursor::wait_arrow:
return "wait_arrow";
case system_cursor::arrow_nw_se:
return "arrow_nw_se";
case system_cursor::arrow_ne_sw:
return "arrow_ne_sw";
case system_cursor::arrow_w_e:
return "arrow_w_e";
case system_cursor::arrow_n_s:
return "arrow_n_s";
case system_cursor::arrow_all:
return "arrow_all";
case system_cursor::no:
return "no";
case system_cursor::hand:
return "hand";
default:
throw cen_error{"Did not recognize system cursor!"};
}
}
/// \} End of string conversions
/// \name Streaming
/// \{
/**
* \brief Prints a textual representation of a system cursor enumerator.
*
* \param stream the output stream that will be used.
* \param cursor the enumerator that will be printed.
*
* \see `to_string(system_cursor)`
*
* \return the used stream.
*
* \since 6.2.0
*/
inline auto operator<<(std::ostream& stream, const system_cursor cursor) -> std::ostream&
{
return stream << to_string(cursor);
}
/// \} End of streaming
/// \name System cursor comparison operators
/// \{
/**
* \brief Indicates whether or not two system cursor values are the same.
*
* \param lhs the left-hand side system cursor value.
* \param rhs the right-hand side system cursor value.
*
* \return `true` if the system cursor values are the same; `false` otherwise.
*
* \since 4.0.0
*/
[[nodiscard]] constexpr auto operator==(const system_cursor lhs,
const SDL_SystemCursor rhs) noexcept -> bool
{
return static_cast<SDL_SystemCursor>(lhs) == rhs;
}
/// \copydoc operator==(system_cursor, SDL_SystemCursor)
[[nodiscard]] constexpr auto operator==(const SDL_SystemCursor lhs,
const system_cursor rhs) noexcept -> bool
{
return rhs == lhs;
}
/**
* \brief Indicates whether or not two system cursor values aren't the same.
*
* \param lhs the left-hand side system cursor value.
* \param rhs the right-hand side system cursor value.
*
* \return `true` if the system cursor values aren't the same; `false`
* otherwise.
*
* \since 4.0.0
*/
[[nodiscard]] constexpr auto operator!=(const system_cursor lhs,
const SDL_SystemCursor rhs) noexcept -> bool
{
return !(lhs == rhs);
}
/// \copydoc operator!=(system_cursor, SDL_SystemCursor)
[[nodiscard]] constexpr auto operator!=(const SDL_SystemCursor lhs,
const system_cursor rhs) noexcept -> bool
{
return !(lhs == rhs);
}
/// \} End of system cursor comparison operators
/// \} End of group video
} // namespace cen
#endif // CENTURION_SYSTEM_CURSOR_HEADER
|
/*
* Copyright 1993-2014 NVIDIA Corporation. All rights reserved.
*
* NOTICE TO LICENSEE:
*
* This source code and/or documentation ("Licensed Deliverables") are
* subject to NVIDIA intellectual property rights under U.S. and
* international Copyright laws.
*
* These Licensed Deliverables contained herein is PROPRIETARY and
* CONFIDENTIAL to NVIDIA and is being provided under the terms and
* conditions of a form of NVIDIA software license agreement by and
* between NVIDIA and Licensee ("License Agreement") or electronically
* accepted by Licensee. Notwithstanding any terms or conditions to
* the contrary in the License Agreement, reproduction or disclosure
* of the Licensed Deliverables to any third party without the express
* written consent of NVIDIA is prohibited.
*
* NOTWITHSTANDING ANY TERMS OR CONDITIONS TO THE CONTRARY IN THE
* LICENSE AGREEMENT, NVIDIA MAKES NO REPRESENTATION ABOUT THE
* SUITABILITY OF THESE LICENSED DELIVERABLES FOR ANY PURPOSE. IT IS
* PROVIDED "AS IS" WITHOUT EXPRESS OR IMPLIED WARRANTY OF ANY KIND.
* NVIDIA DISCLAIMS ALL WARRANTIES WITH REGARD TO THESE LICENSED
* DELIVERABLES, INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY,
* NONINFRINGEMENT, AND FITNESS FOR A PARTICULAR PURPOSE.
* NOTWITHSTANDING ANY TERMS OR CONDITIONS TO THE CONTRARY IN THE
* LICENSE AGREEMENT, IN NO EVENT SHALL NVIDIA BE LIABLE FOR ANY
* SPECIAL, INDIRECT, INCIDENTAL, OR CONSEQUENTIAL DAMAGES, OR ANY
* DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS,
* WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS
* ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE
* OF THESE LICENSED DELIVERABLES.
*
* U.S. Government End Users. These Licensed Deliverables are a
* "commercial item" as that term is defined at 48 C.F.R. 2.101 (OCT
* 1995), consisting of "commercial computer software" and "commercial
* computer software documentation" as such terms are used in 48
* C.F.R. 12.212 (SEPT 1995) and is provided to the U.S. Government
* only as a commercial end item. Consistent with 48 C.F.R.12.212 and
* 48 C.F.R. 227.7202-1 through 227.7202-4 (JUNE 1995), all
* U.S. Government End Users acquire the Licensed Deliverables with
* only those rights set forth herein.
*
* Any use of the Licensed Deliverables in individual and commercial
* software must include, in the user documentation and internal
* comments to the code, the above Disclaimer and U.S. Government End
* Users Notice.
*/
#if !defined(__SM_32_INTRINSICS_HPP__)
#define __SM_32_INTRINSICS_HPP__
#if defined(__CUDACC_RTC__)
#define __SM_32_INTRINSICS_DECL__ __device__
#else /* !__CUDACC_RTC__ */
#define __SM_32_INTRINSICS_DECL__ static __device__ __inline__
#endif /* __CUDACC_RTC__ */
#if defined(__cplusplus) && defined(__CUDACC__)
#if !defined(__CUDA_ARCH__) || __CUDA_ARCH__ >= 320
/*******************************************************************************
* *
* *
* *
*******************************************************************************/
#include "cuda_runtime_api.h"
// In here are intrinsics which are built in to the compiler. These may be
// referenced by intrinsic implementations from this file.
extern "C"
{
// There are no intrinsics built in to the compiler for SM-3.5,
// all intrinsics are now implemented as inline PTX below.
}
/*******************************************************************************
* *
* Below are implementations of SM-3.5 intrinsics which are included as *
* source (instead of being built in to the compiler) *
* *
*******************************************************************************/
// LDG is a "load from global via texture path" command which can exhibit higher
// bandwidth on GK110 than a regular LD.
// Define a different pointer storage size for 64 and 32 bit
#if (defined(_MSC_VER) && defined(_WIN64)) || defined(__LP64__) || defined(__CUDACC_RTC__)
#define __LDG_PTR "l"
#else
#define __LDG_PTR "r"
#endif
/******************************************************************************
* __ldg *
******************************************************************************/
// Size of long is architecture and OS specific.
#if defined(__LP64__) // 64 bits
__SM_32_INTRINSICS_DECL__ long __ldg(const long *ptr) { unsigned long ret; asm volatile ("ld.global.nc.s64 %0, [%1];" : "=l"(ret) : __LDG_PTR (ptr)); return (long)ret; }
__SM_32_INTRINSICS_DECL__ unsigned long __ldg(const unsigned long *ptr) { unsigned long ret; asm volatile ("ld.global.nc.u64 %0, [%1];" : "=l"(ret) : __LDG_PTR (ptr)); return ret; }
#else // 32 bits
__SM_32_INTRINSICS_DECL__ long __ldg(const long *ptr) { unsigned long ret; asm volatile ("ld.global.nc.s32 %0, [%1];" : "=r"(ret) : __LDG_PTR (ptr)); return (long)ret; }
__SM_32_INTRINSICS_DECL__ unsigned long __ldg(const unsigned long *ptr) { unsigned long ret; asm volatile ("ld.global.nc.u32 %0, [%1];" : "=r"(ret) : __LDG_PTR (ptr)); return ret; }
#endif
__SM_32_INTRINSICS_DECL__ char __ldg(const char *ptr) { unsigned int ret; asm volatile ("ld.global.nc.s8 %0, [%1];" : "=r"(ret) : __LDG_PTR (ptr)); return (char)ret; }
__SM_32_INTRINSICS_DECL__ signed char __ldg(const signed char *ptr) { unsigned int ret; asm volatile ("ld.global.nc.s8 %0, [%1];" : "=r"(ret) : __LDG_PTR (ptr)); return (signed char)ret; }
__SM_32_INTRINSICS_DECL__ short __ldg(const short *ptr) { unsigned short ret; asm volatile ("ld.global.nc.s16 %0, [%1];" : "=h"(ret) : __LDG_PTR (ptr)); return (short)ret; }
__SM_32_INTRINSICS_DECL__ int __ldg(const int *ptr) { unsigned int ret; asm volatile ("ld.global.nc.s32 %0, [%1];" : "=r"(ret) : __LDG_PTR (ptr)); return (int)ret; }
__SM_32_INTRINSICS_DECL__ long long __ldg(const long long *ptr) { unsigned long long ret; asm volatile ("ld.global.nc.s64 %0, [%1];" : "=l"(ret) : __LDG_PTR (ptr)); return (long long)ret; }
__SM_32_INTRINSICS_DECL__ char2 __ldg(const char2 *ptr) { char2 ret; int2 tmp; asm volatile ("ld.global.nc.v2.s8 {%0,%1}, [%2];" : "=r"(tmp.x), "=r"(tmp.y) : __LDG_PTR (ptr)); ret.x = (char)tmp.x; ret.y = (char)tmp.y; return ret; }
__SM_32_INTRINSICS_DECL__ char4 __ldg(const char4 *ptr) { char4 ret; int4 tmp; asm volatile ("ld.global.nc.v4.s8 {%0,%1,%2,%3}, [%4];" : "=r"(tmp.x), "=r"(tmp.y), "=r"(tmp.z), "=r"(tmp.w) : __LDG_PTR (ptr)); ret.x = (char)tmp.x; ret.y = (char)tmp.y; ret.z = (char)tmp.z; ret.w = (char)tmp.w; return ret; }
__SM_32_INTRINSICS_DECL__ short2 __ldg(const short2 *ptr) { short2 ret; asm volatile ("ld.global.nc.v2.s16 {%0,%1}, [%2];" : "=h"(ret.x), "=h"(ret.y) : __LDG_PTR (ptr)); return ret; }
__SM_32_INTRINSICS_DECL__ short4 __ldg(const short4 *ptr) { short4 ret; asm volatile ("ld.global.nc.v4.s16 {%0,%1,%2,%3}, [%4];" : "=h"(ret.x), "=h"(ret.y), "=h"(ret.z), "=h"(ret.w) : __LDG_PTR (ptr)); return ret; }
__SM_32_INTRINSICS_DECL__ int2 __ldg(const int2 *ptr) { int2 ret; asm volatile ("ld.global.nc.v2.s32 {%0,%1}, [%2];" : "=r"(ret.x), "=r"(ret.y) : __LDG_PTR (ptr)); return ret; }
__SM_32_INTRINSICS_DECL__ int4 __ldg(const int4 *ptr) { int4 ret; asm volatile ("ld.global.nc.v4.s32 {%0,%1,%2,%3}, [%4];" : "=r"(ret.x), "=r"(ret.y), "=r"(ret.z), "=r"(ret.w) : __LDG_PTR (ptr)); return ret; }
__SM_32_INTRINSICS_DECL__ longlong2 __ldg(const longlong2 *ptr) { longlong2 ret; asm volatile ("ld.global.nc.v2.s64 {%0,%1}, [%2];" : "=l"(ret.x), "=l"(ret.y) : __LDG_PTR (ptr)); return ret; }
__SM_32_INTRINSICS_DECL__ unsigned char __ldg(const unsigned char *ptr) { unsigned int ret; asm volatile ("ld.global.nc.u8 %0, [%1];" : "=r"(ret) : __LDG_PTR (ptr)); return (unsigned char)ret; }
__SM_32_INTRINSICS_DECL__ unsigned short __ldg(const unsigned short *ptr) { unsigned short ret; asm volatile ("ld.global.nc.u16 %0, [%1];" : "=h"(ret) : __LDG_PTR (ptr)); return ret; }
__SM_32_INTRINSICS_DECL__ unsigned int __ldg(const unsigned int *ptr) { unsigned int ret; asm volatile ("ld.global.nc.u32 %0, [%1];" : "=r"(ret) : __LDG_PTR (ptr)); return ret; }
__SM_32_INTRINSICS_DECL__ unsigned long long __ldg(const unsigned long long *ptr) { unsigned long long ret; asm volatile ("ld.global.nc.u64 %0, [%1];" : "=l"(ret) : __LDG_PTR (ptr)); return ret; }
__SM_32_INTRINSICS_DECL__ uchar2 __ldg(const uchar2 *ptr) { uchar2 ret; uint2 tmp; asm volatile ("ld.global.nc.v2.u8 {%0,%1}, [%2];" : "=r"(tmp.x), "=r"(tmp.y) : __LDG_PTR (ptr)); ret.x = (unsigned char)tmp.x; ret.y = (unsigned char)tmp.y; return ret; }
__SM_32_INTRINSICS_DECL__ uchar4 __ldg(const uchar4 *ptr) { uchar4 ret; uint4 tmp; asm volatile ("ld.global.nc.v4.u8 {%0,%1,%2,%3}, [%4];" : "=r"(tmp.x), "=r"(tmp.y), "=r"(tmp.z), "=r"(tmp.w) : __LDG_PTR (ptr)); ret.x = (unsigned char)tmp.x; ret.y = (unsigned char)tmp.y; ret.z = (unsigned char)tmp.z; ret.w = (unsigned char)tmp.w; return ret; }
__SM_32_INTRINSICS_DECL__ ushort2 __ldg(const ushort2 *ptr) { ushort2 ret; asm volatile ("ld.global.nc.v2.u16 {%0,%1}, [%2];" : "=h"(ret.x), "=h"(ret.y) : __LDG_PTR (ptr)); return ret; }
__SM_32_INTRINSICS_DECL__ ushort4 __ldg(const ushort4 *ptr) { ushort4 ret; asm volatile ("ld.global.nc.v4.u16 {%0,%1,%2,%3}, [%4];" : "=h"(ret.x), "=h"(ret.y), "=h"(ret.z), "=h"(ret.w) : __LDG_PTR (ptr)); return ret; }
__SM_32_INTRINSICS_DECL__ uint2 __ldg(const uint2 *ptr) { uint2 ret; asm volatile ("ld.global.nc.v2.u32 {%0,%1}, [%2];" : "=r"(ret.x), "=r"(ret.y) : __LDG_PTR (ptr)); return ret; }
__SM_32_INTRINSICS_DECL__ uint4 __ldg(const uint4 *ptr) { uint4 ret; asm volatile ("ld.global.nc.v4.u32 {%0,%1,%2,%3}, [%4];" : "=r"(ret.x), "=r"(ret.y), "=r"(ret.z), "=r"(ret.w) : __LDG_PTR (ptr)); return ret; }
__SM_32_INTRINSICS_DECL__ ulonglong2 __ldg(const ulonglong2 *ptr) { ulonglong2 ret; asm volatile ("ld.global.nc.v2.u64 {%0,%1}, [%2];" : "=l"(ret.x), "=l"(ret.y) : __LDG_PTR (ptr)); return ret; }
__SM_32_INTRINSICS_DECL__ float __ldg(const float *ptr) { float ret; asm volatile ("ld.global.nc.f32 %0, [%1];" : "=f"(ret) : __LDG_PTR (ptr)); return ret; }
__SM_32_INTRINSICS_DECL__ double __ldg(const double *ptr) { double ret; asm volatile ("ld.global.nc.f64 %0, [%1];" : "=d"(ret) : __LDG_PTR (ptr)); return ret; }
__SM_32_INTRINSICS_DECL__ float2 __ldg(const float2 *ptr) { float2 ret; asm volatile ("ld.global.nc.v2.f32 {%0,%1}, [%2];" : "=f"(ret.x), "=f"(ret.y) : __LDG_PTR (ptr)); return ret; }
__SM_32_INTRINSICS_DECL__ float4 __ldg(const float4 *ptr) { float4 ret; asm volatile ("ld.global.nc.v4.f32 {%0,%1,%2,%3}, [%4];" : "=f"(ret.x), "=f"(ret.y), "=f"(ret.z), "=f"(ret.w) : __LDG_PTR (ptr)); return ret; }
__SM_32_INTRINSICS_DECL__ double2 __ldg(const double2 *ptr) { double2 ret; asm volatile ("ld.global.nc.v2.f64 {%0,%1}, [%2];" : "=d"(ret.x), "=d"(ret.y) : __LDG_PTR (ptr)); return ret; }
/******************************************************************************
* __ldcg *
******************************************************************************/
// Size of long is architecture and OS specific.
#if defined(__LP64__) // 64 bits
__SM_32_INTRINSICS_DECL__ long __ldcg(const long *ptr) { unsigned long ret; asm volatile ("ld.global.cg.s64 %0, [%1];" : "=l"(ret) : __LDG_PTR (ptr)); return (long)ret; }
__SM_32_INTRINSICS_DECL__ unsigned long __ldcg(const unsigned long *ptr) { unsigned long ret; asm volatile ("ld.global.cg.u64 %0, [%1];" : "=l"(ret) : __LDG_PTR (ptr)); return ret; }
#else // 32 bits
__SM_32_INTRINSICS_DECL__ long __ldcg(const long *ptr) { unsigned long ret; asm volatile ("ld.global.cg.s32 %0, [%1];" : "=r"(ret) : __LDG_PTR (ptr)); return (long)ret; }
__SM_32_INTRINSICS_DECL__ unsigned long __ldcg(const unsigned long *ptr) { unsigned long ret; asm volatile ("ld.global.cg.u32 %0, [%1];" : "=r"(ret) : __LDG_PTR (ptr)); return ret; }
#endif
__SM_32_INTRINSICS_DECL__ char __ldcg(const char *ptr) { unsigned int ret; asm volatile ("ld.global.cg.s8 %0, [%1];" : "=r"(ret) : __LDG_PTR (ptr)); return (char)ret; }
__SM_32_INTRINSICS_DECL__ signed char __ldcg(const signed char *ptr) { unsigned int ret; asm volatile ("ld.global.cg.s8 %0, [%1];" : "=r"(ret) : __LDG_PTR (ptr)); return (signed char)ret; }
__SM_32_INTRINSICS_DECL__ short __ldcg(const short *ptr) { unsigned short ret; asm volatile ("ld.global.cg.s16 %0, [%1];" : "=h"(ret) : __LDG_PTR (ptr)); return (short)ret; }
__SM_32_INTRINSICS_DECL__ int __ldcg(const int *ptr) { unsigned int ret; asm volatile ("ld.global.cg.s32 %0, [%1];" : "=r"(ret) : __LDG_PTR (ptr)); return (int)ret; }
__SM_32_INTRINSICS_DECL__ long long __ldcg(const long long *ptr) { unsigned long long ret; asm volatile ("ld.global.cg.s64 %0, [%1];" : "=l"(ret) : __LDG_PTR (ptr)); return (long long)ret; }
__SM_32_INTRINSICS_DECL__ char2 __ldcg(const char2 *ptr) { char2 ret; int2 tmp; asm volatile ("ld.global.cg.v2.s8 {%0,%1}, [%2];" : "=r"(tmp.x), "=r"(tmp.y) : __LDG_PTR (ptr)); ret.x = (char)tmp.x; ret.y = (char)tmp.y; return ret; }
__SM_32_INTRINSICS_DECL__ char4 __ldcg(const char4 *ptr) { char4 ret; int4 tmp; asm volatile ("ld.global.cg.v4.s8 {%0,%1,%2,%3}, [%4];" : "=r"(tmp.x), "=r"(tmp.y), "=r"(tmp.z), "=r"(tmp.w) : __LDG_PTR (ptr)); ret.x = (char)tmp.x; ret.y = (char)tmp.y; ret.z = (char)tmp.z; ret.w = (char)tmp.w; return ret; }
__SM_32_INTRINSICS_DECL__ short2 __ldcg(const short2 *ptr) { short2 ret; asm volatile ("ld.global.cg.v2.s16 {%0,%1}, [%2];" : "=h"(ret.x), "=h"(ret.y) : __LDG_PTR (ptr)); return ret; }
__SM_32_INTRINSICS_DECL__ short4 __ldcg(const short4 *ptr) { short4 ret; asm volatile ("ld.global.cg.v4.s16 {%0,%1,%2,%3}, [%4];" : "=h"(ret.x), "=h"(ret.y), "=h"(ret.z), "=h"(ret.w) : __LDG_PTR (ptr)); return ret; }
__SM_32_INTRINSICS_DECL__ int2 __ldcg(const int2 *ptr) { int2 ret; asm volatile ("ld.global.cg.v2.s32 {%0,%1}, [%2];" : "=r"(ret.x), "=r"(ret.y) : __LDG_PTR (ptr)); return ret; }
__SM_32_INTRINSICS_DECL__ int4 __ldcg(const int4 *ptr) { int4 ret; asm volatile ("ld.global.cg.v4.s32 {%0,%1,%2,%3}, [%4];" : "=r"(ret.x), "=r"(ret.y), "=r"(ret.z), "=r"(ret.w) : __LDG_PTR (ptr)); return ret; }
__SM_32_INTRINSICS_DECL__ longlong2 __ldcg(const longlong2 *ptr) { longlong2 ret; asm volatile ("ld.global.cg.v2.s64 {%0,%1}, [%2];" : "=l"(ret.x), "=l"(ret.y) : __LDG_PTR (ptr)); return ret; }
__SM_32_INTRINSICS_DECL__ unsigned char __ldcg(const unsigned char *ptr) { unsigned int ret; asm volatile ("ld.global.cg.u8 %0, [%1];" : "=r"(ret) : __LDG_PTR (ptr)); return (unsigned char)ret; }
__SM_32_INTRINSICS_DECL__ unsigned short __ldcg(const unsigned short *ptr) { unsigned short ret; asm volatile ("ld.global.cg.u16 %0, [%1];" : "=h"(ret) : __LDG_PTR (ptr)); return ret; }
__SM_32_INTRINSICS_DECL__ unsigned int __ldcg(const unsigned int *ptr) { unsigned int ret; asm volatile ("ld.global.cg.u32 %0, [%1];" : "=r"(ret) : __LDG_PTR (ptr)); return ret; }
__SM_32_INTRINSICS_DECL__ unsigned long long __ldcg(const unsigned long long *ptr) { unsigned long long ret; asm volatile ("ld.global.cg.u64 %0, [%1];" : "=l"(ret) : __LDG_PTR (ptr)); return ret; }
__SM_32_INTRINSICS_DECL__ uchar2 __ldcg(const uchar2 *ptr) { uchar2 ret; uint2 tmp; asm volatile ("ld.global.cg.v2.u8 {%0,%1}, [%2];" : "=r"(tmp.x), "=r"(tmp.y) : __LDG_PTR (ptr)); ret.x = (unsigned char)tmp.x; ret.y = (unsigned char)tmp.y; return ret; }
__SM_32_INTRINSICS_DECL__ uchar4 __ldcg(const uchar4 *ptr) { uchar4 ret; uint4 tmp; asm volatile ("ld.global.cg.v4.u8 {%0,%1,%2,%3}, [%4];" : "=r"(tmp.x), "=r"(tmp.y), "=r"(tmp.z), "=r"(tmp.w) : __LDG_PTR (ptr)); ret.x = (unsigned char)tmp.x; ret.y = (unsigned char)tmp.y; ret.z = (unsigned char)tmp.z; ret.w = (unsigned char)tmp.w; return ret; }
__SM_32_INTRINSICS_DECL__ ushort2 __ldcg(const ushort2 *ptr) { ushort2 ret; asm volatile ("ld.global.cg.v2.u16 {%0,%1}, [%2];" : "=h"(ret.x), "=h"(ret.y) : __LDG_PTR (ptr)); return ret; }
__SM_32_INTRINSICS_DECL__ ushort4 __ldcg(const ushort4 *ptr) { ushort4 ret; asm volatile ("ld.global.cg.v4.u16 {%0,%1,%2,%3}, [%4];" : "=h"(ret.x), "=h"(ret.y), "=h"(ret.z), "=h"(ret.w) : __LDG_PTR (ptr)); return ret; }
__SM_32_INTRINSICS_DECL__ uint2 __ldcg(const uint2 *ptr) { uint2 ret; asm volatile ("ld.global.cg.v2.u32 {%0,%1}, [%2];" : "=r"(ret.x), "=r"(ret.y) : __LDG_PTR (ptr)); return ret; }
__SM_32_INTRINSICS_DECL__ uint4 __ldcg(const uint4 *ptr) { uint4 ret; asm volatile ("ld.global.cg.v4.u32 {%0,%1,%2,%3}, [%4];" : "=r"(ret.x), "=r"(ret.y), "=r"(ret.z), "=r"(ret.w) : __LDG_PTR (ptr)); return ret; }
__SM_32_INTRINSICS_DECL__ ulonglong2 __ldcg(const ulonglong2 *ptr) { ulonglong2 ret; asm volatile ("ld.global.cg.v2.u64 {%0,%1}, [%2];" : "=l"(ret.x), "=l"(ret.y) : __LDG_PTR (ptr)); return ret; }
__SM_32_INTRINSICS_DECL__ float __ldcg(const float *ptr) { float ret; asm volatile ("ld.global.cg.f32 %0, [%1];" : "=f"(ret) : __LDG_PTR (ptr)); return ret; }
__SM_32_INTRINSICS_DECL__ double __ldcg(const double *ptr) { double ret; asm volatile ("ld.global.cg.f64 %0, [%1];" : "=d"(ret) : __LDG_PTR (ptr)); return ret; }
__SM_32_INTRINSICS_DECL__ float2 __ldcg(const float2 *ptr) { float2 ret; asm volatile ("ld.global.cg.v2.f32 {%0,%1}, [%2];" : "=f"(ret.x), "=f"(ret.y) : __LDG_PTR (ptr)); return ret; }
__SM_32_INTRINSICS_DECL__ float4 __ldcg(const float4 *ptr) { float4 ret; asm volatile ("ld.global.cg.v4.f32 {%0,%1,%2,%3}, [%4];" : "=f"(ret.x), "=f"(ret.y), "=f"(ret.z), "=f"(ret.w) : __LDG_PTR (ptr)); return ret; }
__SM_32_INTRINSICS_DECL__ double2 __ldcg(const double2 *ptr) { double2 ret; asm volatile ("ld.global.cg.v2.f64 {%0,%1}, [%2];" : "=d"(ret.x), "=d"(ret.y) : __LDG_PTR (ptr)); return ret; }
/******************************************************************************
* __ldca *
******************************************************************************/
// Size of long is architecture and OS specific.
#if defined(__LP64__) // 64 bits
__SM_32_INTRINSICS_DECL__ long __ldca(const long *ptr) { unsigned long ret; asm volatile ("ld.global.ca.s64 %0, [%1];" : "=l"(ret) : __LDG_PTR (ptr)); return (long)ret; }
__SM_32_INTRINSICS_DECL__ unsigned long __ldca(const unsigned long *ptr) { unsigned long ret; asm volatile ("ld.global.ca.u64 %0, [%1];" : "=l"(ret) : __LDG_PTR (ptr)); return ret; }
#else // 32 bits
__SM_32_INTRINSICS_DECL__ long __ldca(const long *ptr) { unsigned long ret; asm volatile ("ld.global.ca.s32 %0, [%1];" : "=r"(ret) : __LDG_PTR (ptr)); return (long)ret; }
__SM_32_INTRINSICS_DECL__ unsigned long __ldca(const unsigned long *ptr) { unsigned long ret; asm volatile ("ld.global.ca.u32 %0, [%1];" : "=r"(ret) : __LDG_PTR (ptr)); return ret; }
#endif
__SM_32_INTRINSICS_DECL__ char __ldca(const char *ptr) { unsigned int ret; asm volatile ("ld.global.ca.s8 %0, [%1];" : "=r"(ret) : __LDG_PTR (ptr)); return (char)ret; }
__SM_32_INTRINSICS_DECL__ signed char __ldca(const signed char *ptr) { unsigned int ret; asm volatile ("ld.global.ca.s8 %0, [%1];" : "=r"(ret) : __LDG_PTR (ptr)); return (signed char)ret; }
__SM_32_INTRINSICS_DECL__ short __ldca(const short *ptr) { unsigned short ret; asm volatile ("ld.global.ca.s16 %0, [%1];" : "=h"(ret) : __LDG_PTR (ptr)); return (short)ret; }
__SM_32_INTRINSICS_DECL__ int __ldca(const int *ptr) { unsigned int ret; asm volatile ("ld.global.ca.s32 %0, [%1];" : "=r"(ret) : __LDG_PTR (ptr)); return (int)ret; }
__SM_32_INTRINSICS_DECL__ long long __ldca(const long long *ptr) { unsigned long long ret; asm volatile ("ld.global.ca.s64 %0, [%1];" : "=l"(ret) : __LDG_PTR (ptr)); return (long long)ret; }
__SM_32_INTRINSICS_DECL__ char2 __ldca(const char2 *ptr) { char2 ret; int2 tmp; asm volatile ("ld.global.ca.v2.s8 {%0,%1}, [%2];" : "=r"(tmp.x), "=r"(tmp.y) : __LDG_PTR (ptr)); ret.x = (char)tmp.x; ret.y = (char)tmp.y; return ret; }
__SM_32_INTRINSICS_DECL__ char4 __ldca(const char4 *ptr) { char4 ret; int4 tmp; asm volatile ("ld.global.ca.v4.s8 {%0,%1,%2,%3}, [%4];" : "=r"(tmp.x), "=r"(tmp.y), "=r"(tmp.z), "=r"(tmp.w) : __LDG_PTR (ptr)); ret.x = (char)tmp.x; ret.y = (char)tmp.y; ret.z = (char)tmp.z; ret.w = (char)tmp.w; return ret; }
__SM_32_INTRINSICS_DECL__ short2 __ldca(const short2 *ptr) { short2 ret; asm volatile ("ld.global.ca.v2.s16 {%0,%1}, [%2];" : "=h"(ret.x), "=h"(ret.y) : __LDG_PTR (ptr)); return ret; }
__SM_32_INTRINSICS_DECL__ short4 __ldca(const short4 *ptr) { short4 ret; asm volatile ("ld.global.ca.v4.s16 {%0,%1,%2,%3}, [%4];" : "=h"(ret.x), "=h"(ret.y), "=h"(ret.z), "=h"(ret.w) : __LDG_PTR (ptr)); return ret; }
__SM_32_INTRINSICS_DECL__ int2 __ldca(const int2 *ptr) { int2 ret; asm volatile ("ld.global.ca.v2.s32 {%0,%1}, [%2];" : "=r"(ret.x), "=r"(ret.y) : __LDG_PTR (ptr)); return ret; }
__SM_32_INTRINSICS_DECL__ int4 __ldca(const int4 *ptr) { int4 ret; asm volatile ("ld.global.ca.v4.s32 {%0,%1,%2,%3}, [%4];" : "=r"(ret.x), "=r"(ret.y), "=r"(ret.z), "=r"(ret.w) : __LDG_PTR (ptr)); return ret; }
__SM_32_INTRINSICS_DECL__ longlong2 __ldca(const longlong2 *ptr) { longlong2 ret; asm volatile ("ld.global.ca.v2.s64 {%0,%1}, [%2];" : "=l"(ret.x), "=l"(ret.y) : __LDG_PTR (ptr)); return ret; }
__SM_32_INTRINSICS_DECL__ unsigned char __ldca(const unsigned char *ptr) { unsigned int ret; asm volatile ("ld.global.ca.u8 %0, [%1];" : "=r"(ret) : __LDG_PTR (ptr)); return (unsigned char)ret; }
__SM_32_INTRINSICS_DECL__ unsigned short __ldca(const unsigned short *ptr) { unsigned short ret; asm volatile ("ld.global.ca.u16 %0, [%1];" : "=h"(ret) : __LDG_PTR (ptr)); return ret; }
__SM_32_INTRINSICS_DECL__ unsigned int __ldca(const unsigned int *ptr) { unsigned int ret; asm volatile ("ld.global.ca.u32 %0, [%1];" : "=r"(ret) : __LDG_PTR (ptr)); return ret; }
__SM_32_INTRINSICS_DECL__ unsigned long long __ldca(const unsigned long long *ptr) { unsigned long long ret; asm volatile ("ld.global.ca.u64 %0, [%1];" : "=l"(ret) : __LDG_PTR (ptr)); return ret; }
__SM_32_INTRINSICS_DECL__ uchar2 __ldca(const uchar2 *ptr) { uchar2 ret; uint2 tmp; asm volatile ("ld.global.ca.v2.u8 {%0,%1}, [%2];" : "=r"(tmp.x), "=r"(tmp.y) : __LDG_PTR (ptr)); ret.x = (unsigned char)tmp.x; ret.y = (unsigned char)tmp.y; return ret; }
__SM_32_INTRINSICS_DECL__ uchar4 __ldca(const uchar4 *ptr) { uchar4 ret; uint4 tmp; asm volatile ("ld.global.ca.v4.u8 {%0,%1,%2,%3}, [%4];" : "=r"(tmp.x), "=r"(tmp.y), "=r"(tmp.z), "=r"(tmp.w) : __LDG_PTR (ptr)); ret.x = (unsigned char)tmp.x; ret.y = (unsigned char)tmp.y; ret.z = (unsigned char)tmp.z; ret.w = (unsigned char)tmp.w; return ret; }
__SM_32_INTRINSICS_DECL__ ushort2 __ldca(const ushort2 *ptr) { ushort2 ret; asm volatile ("ld.global.ca.v2.u16 {%0,%1}, [%2];" : "=h"(ret.x), "=h"(ret.y) : __LDG_PTR (ptr)); return ret; }
__SM_32_INTRINSICS_DECL__ ushort4 __ldca(const ushort4 *ptr) { ushort4 ret; asm volatile ("ld.global.ca.v4.u16 {%0,%1,%2,%3}, [%4];" : "=h"(ret.x), "=h"(ret.y), "=h"(ret.z), "=h"(ret.w) : __LDG_PTR (ptr)); return ret; }
__SM_32_INTRINSICS_DECL__ uint2 __ldca(const uint2 *ptr) { uint2 ret; asm volatile ("ld.global.ca.v2.u32 {%0,%1}, [%2];" : "=r"(ret.x), "=r"(ret.y) : __LDG_PTR (ptr)); return ret; }
__SM_32_INTRINSICS_DECL__ uint4 __ldca(const uint4 *ptr) { uint4 ret; asm volatile ("ld.global.ca.v4.u32 {%0,%1,%2,%3}, [%4];" : "=r"(ret.x), "=r"(ret.y), "=r"(ret.z), "=r"(ret.w) : __LDG_PTR (ptr)); return ret; }
__SM_32_INTRINSICS_DECL__ ulonglong2 __ldca(const ulonglong2 *ptr) { ulonglong2 ret; asm volatile ("ld.global.ca.v2.u64 {%0,%1}, [%2];" : "=l"(ret.x), "=l"(ret.y) : __LDG_PTR (ptr)); return ret; }
__SM_32_INTRINSICS_DECL__ float __ldca(const float *ptr) { float ret; asm volatile ("ld.global.ca.f32 %0, [%1];" : "=f"(ret) : __LDG_PTR (ptr)); return ret; }
__SM_32_INTRINSICS_DECL__ double __ldca(const double *ptr) { double ret; asm volatile ("ld.global.ca.f64 %0, [%1];" : "=d"(ret) : __LDG_PTR (ptr)); return ret; }
__SM_32_INTRINSICS_DECL__ float2 __ldca(const float2 *ptr) { float2 ret; asm volatile ("ld.global.ca.v2.f32 {%0,%1}, [%2];" : "=f"(ret.x), "=f"(ret.y) : __LDG_PTR (ptr)); return ret; }
__SM_32_INTRINSICS_DECL__ float4 __ldca(const float4 *ptr) { float4 ret; asm volatile ("ld.global.ca.v4.f32 {%0,%1,%2,%3}, [%4];" : "=f"(ret.x), "=f"(ret.y), "=f"(ret.z), "=f"(ret.w) : __LDG_PTR (ptr)); return ret; }
__SM_32_INTRINSICS_DECL__ double2 __ldca(const double2 *ptr) { double2 ret; asm volatile ("ld.global.ca.v2.f64 {%0,%1}, [%2];" : "=d"(ret.x), "=d"(ret.y) : __LDG_PTR (ptr)); return ret; }
/******************************************************************************
* __ldcs *
******************************************************************************/
// Size of long is architecture and OS specific.
#if defined(__LP64__) // 64 bits
__SM_32_INTRINSICS_DECL__ long __ldcs(const long *ptr) { unsigned long ret; asm volatile ("ld.global.cs.s64 %0, [%1];" : "=l"(ret) : __LDG_PTR (ptr)); return (long)ret; }
__SM_32_INTRINSICS_DECL__ unsigned long __ldcs(const unsigned long *ptr) { unsigned long ret; asm volatile ("ld.global.cs.u64 %0, [%1];" : "=l"(ret) : __LDG_PTR (ptr)); return ret; }
#else // 32 bits
__SM_32_INTRINSICS_DECL__ long __ldcs(const long *ptr) { unsigned long ret; asm volatile ("ld.global.cs.s32 %0, [%1];" : "=r"(ret) : __LDG_PTR (ptr)); return (long)ret; }
__SM_32_INTRINSICS_DECL__ unsigned long __ldcs(const unsigned long *ptr) { unsigned long ret; asm volatile ("ld.global.cs.u32 %0, [%1];" : "=r"(ret) : __LDG_PTR (ptr)); return ret; }
#endif
__SM_32_INTRINSICS_DECL__ char __ldcs(const char *ptr) { unsigned int ret; asm volatile ("ld.global.cs.s8 %0, [%1];" : "=r"(ret) : __LDG_PTR (ptr)); return (char)ret; }
__SM_32_INTRINSICS_DECL__ signed char __ldcs(const signed char *ptr) { unsigned int ret; asm volatile ("ld.global.cs.s8 %0, [%1];" : "=r"(ret) : __LDG_PTR (ptr)); return (signed char)ret; }
__SM_32_INTRINSICS_DECL__ short __ldcs(const short *ptr) { unsigned short ret; asm volatile ("ld.global.cs.s16 %0, [%1];" : "=h"(ret) : __LDG_PTR (ptr)); return (short)ret; }
__SM_32_INTRINSICS_DECL__ int __ldcs(const int *ptr) { unsigned int ret; asm volatile ("ld.global.cs.s32 %0, [%1];" : "=r"(ret) : __LDG_PTR (ptr)); return (int)ret; }
__SM_32_INTRINSICS_DECL__ long long __ldcs(const long long *ptr) { unsigned long long ret; asm volatile ("ld.global.cs.s64 %0, [%1];" : "=l"(ret) : __LDG_PTR (ptr)); return (long long)ret; }
__SM_32_INTRINSICS_DECL__ char2 __ldcs(const char2 *ptr) { char2 ret; int2 tmp; asm volatile ("ld.global.cs.v2.s8 {%0,%1}, [%2];" : "=r"(tmp.x), "=r"(tmp.y) : __LDG_PTR (ptr)); ret.x = (char)tmp.x; ret.y = (char)tmp.y; return ret; }
__SM_32_INTRINSICS_DECL__ char4 __ldcs(const char4 *ptr) { char4 ret; int4 tmp; asm volatile ("ld.global.cs.v4.s8 {%0,%1,%2,%3}, [%4];" : "=r"(tmp.x), "=r"(tmp.y), "=r"(tmp.z), "=r"(tmp.w) : __LDG_PTR (ptr)); ret.x = (char)tmp.x; ret.y = (char)tmp.y; ret.z = (char)tmp.z; ret.w = (char)tmp.w; return ret; }
__SM_32_INTRINSICS_DECL__ short2 __ldcs(const short2 *ptr) { short2 ret; asm volatile ("ld.global.cs.v2.s16 {%0,%1}, [%2];" : "=h"(ret.x), "=h"(ret.y) : __LDG_PTR (ptr)); return ret; }
__SM_32_INTRINSICS_DECL__ short4 __ldcs(const short4 *ptr) { short4 ret; asm volatile ("ld.global.cs.v4.s16 {%0,%1,%2,%3}, [%4];" : "=h"(ret.x), "=h"(ret.y), "=h"(ret.z), "=h"(ret.w) : __LDG_PTR (ptr)); return ret; }
__SM_32_INTRINSICS_DECL__ int2 __ldcs(const int2 *ptr) { int2 ret; asm volatile ("ld.global.cs.v2.s32 {%0,%1}, [%2];" : "=r"(ret.x), "=r"(ret.y) : __LDG_PTR (ptr)); return ret; }
__SM_32_INTRINSICS_DECL__ int4 __ldcs(const int4 *ptr) { int4 ret; asm volatile ("ld.global.cs.v4.s32 {%0,%1,%2,%3}, [%4];" : "=r"(ret.x), "=r"(ret.y), "=r"(ret.z), "=r"(ret.w) : __LDG_PTR (ptr)); return ret; }
__SM_32_INTRINSICS_DECL__ longlong2 __ldcs(const longlong2 *ptr) { longlong2 ret; asm volatile ("ld.global.cs.v2.s64 {%0,%1}, [%2];" : "=l"(ret.x), "=l"(ret.y) : __LDG_PTR (ptr)); return ret; }
__SM_32_INTRINSICS_DECL__ unsigned char __ldcs(const unsigned char *ptr) { unsigned int ret; asm volatile ("ld.global.cs.u8 %0, [%1];" : "=r"(ret) : __LDG_PTR (ptr)); return (unsigned char)ret; }
__SM_32_INTRINSICS_DECL__ unsigned short __ldcs(const unsigned short *ptr) { unsigned short ret; asm volatile ("ld.global.cs.u16 %0, [%1];" : "=h"(ret) : __LDG_PTR (ptr)); return ret; }
__SM_32_INTRINSICS_DECL__ unsigned int __ldcs(const unsigned int *ptr) { unsigned int ret; asm volatile ("ld.global.cs.u32 %0, [%1];" : "=r"(ret) : __LDG_PTR (ptr)); return ret; }
__SM_32_INTRINSICS_DECL__ unsigned long long __ldcs(const unsigned long long *ptr) { unsigned long long ret; asm volatile ("ld.global.cs.u64 %0, [%1];" : "=l"(ret) : __LDG_PTR (ptr)); return ret; }
__SM_32_INTRINSICS_DECL__ uchar2 __ldcs(const uchar2 *ptr) { uchar2 ret; uint2 tmp; asm volatile ("ld.global.cs.v2.u8 {%0,%1}, [%2];" : "=r"(tmp.x), "=r"(tmp.y) : __LDG_PTR (ptr)); ret.x = (unsigned char)tmp.x; ret.y = (unsigned char)tmp.y; return ret; }
__SM_32_INTRINSICS_DECL__ uchar4 __ldcs(const uchar4 *ptr) { uchar4 ret; uint4 tmp; asm volatile ("ld.global.cs.v4.u8 {%0,%1,%2,%3}, [%4];" : "=r"(tmp.x), "=r"(tmp.y), "=r"(tmp.z), "=r"(tmp.w) : __LDG_PTR (ptr)); ret.x = (unsigned char)tmp.x; ret.y = (unsigned char)tmp.y; ret.z = (unsigned char)tmp.z; ret.w = (unsigned char)tmp.w; return ret; }
__SM_32_INTRINSICS_DECL__ ushort2 __ldcs(const ushort2 *ptr) { ushort2 ret; asm volatile ("ld.global.cs.v2.u16 {%0,%1}, [%2];" : "=h"(ret.x), "=h"(ret.y) : __LDG_PTR (ptr)); return ret; }
__SM_32_INTRINSICS_DECL__ ushort4 __ldcs(const ushort4 *ptr) { ushort4 ret; asm volatile ("ld.global.cs.v4.u16 {%0,%1,%2,%3}, [%4];" : "=h"(ret.x), "=h"(ret.y), "=h"(ret.z), "=h"(ret.w) : __LDG_PTR (ptr)); return ret; }
__SM_32_INTRINSICS_DECL__ uint2 __ldcs(const uint2 *ptr) { uint2 ret; asm volatile ("ld.global.cs.v2.u32 {%0,%1}, [%2];" : "=r"(ret.x), "=r"(ret.y) : __LDG_PTR (ptr)); return ret; }
__SM_32_INTRINSICS_DECL__ uint4 __ldcs(const uint4 *ptr) { uint4 ret; asm volatile ("ld.global.cs.v4.u32 {%0,%1,%2,%3}, [%4];" : "=r"(ret.x), "=r"(ret.y), "=r"(ret.z), "=r"(ret.w) : __LDG_PTR (ptr)); return ret; }
__SM_32_INTRINSICS_DECL__ ulonglong2 __ldcs(const ulonglong2 *ptr) { ulonglong2 ret; asm volatile ("ld.global.cs.v2.u64 {%0,%1}, [%2];" : "=l"(ret.x), "=l"(ret.y) : __LDG_PTR (ptr)); return ret; }
__SM_32_INTRINSICS_DECL__ float __ldcs(const float *ptr) { float ret; asm volatile ("ld.global.cs.f32 %0, [%1];" : "=f"(ret) : __LDG_PTR (ptr)); return ret; }
__SM_32_INTRINSICS_DECL__ double __ldcs(const double *ptr) { double ret; asm volatile ("ld.global.cs.f64 %0, [%1];" : "=d"(ret) : __LDG_PTR (ptr)); return ret; }
__SM_32_INTRINSICS_DECL__ float2 __ldcs(const float2 *ptr) { float2 ret; asm volatile ("ld.global.cs.v2.f32 {%0,%1}, [%2];" : "=f"(ret.x), "=f"(ret.y) : __LDG_PTR (ptr)); return ret; }
__SM_32_INTRINSICS_DECL__ float4 __ldcs(const float4 *ptr) { float4 ret; asm volatile ("ld.global.cs.v4.f32 {%0,%1,%2,%3}, [%4];" : "=f"(ret.x), "=f"(ret.y), "=f"(ret.z), "=f"(ret.w) : __LDG_PTR (ptr)); return ret; }
__SM_32_INTRINSICS_DECL__ double2 __ldcs(const double2 *ptr) { double2 ret; asm volatile ("ld.global.cs.v2.f64 {%0,%1}, [%2];" : "=d"(ret.x), "=d"(ret.y) : __LDG_PTR (ptr)); return ret; }
#undef __LDG_PTR
// SHF is the "funnel shift" operation - an accelerated left/right shift with carry
// operating on 64-bit quantities, which are concatenations of two 32-bit registers.
// This shifts [b:a] left by "shift" bits, returning the most significant bits of the result.
__SM_32_INTRINSICS_DECL__ unsigned int __funnelshift_l(unsigned int lo, unsigned int hi, unsigned int shift)
{
unsigned int ret;
asm volatile ("shf.l.wrap.b32 %0, %1, %2, %3;" : "=r"(ret) : "r"(lo), "r"(hi), "r"(shift));
return ret;
}
__SM_32_INTRINSICS_DECL__ unsigned int __funnelshift_lc(unsigned int lo, unsigned int hi, unsigned int shift)
{
unsigned int ret;
asm volatile ("shf.l.clamp.b32 %0, %1, %2, %3;" : "=r"(ret) : "r"(lo), "r"(hi), "r"(shift));
return ret;
}
// This shifts [b:a] right by "shift" bits, returning the least significant bits of the result.
__SM_32_INTRINSICS_DECL__ unsigned int __funnelshift_r(unsigned int lo, unsigned int hi, unsigned int shift)
{
unsigned int ret;
asm volatile ("shf.r.wrap.b32 %0, %1, %2, %3;" : "=r"(ret) : "r"(lo), "r"(hi), "r"(shift));
return ret;
}
__SM_32_INTRINSICS_DECL__ unsigned int __funnelshift_rc(unsigned int lo, unsigned int hi, unsigned int shift)
{
unsigned int ret;
asm volatile ("shf.r.clamp.b32 %0, %1, %2, %3;" : "=r"(ret) : "r"(lo), "r"(hi), "r"(shift));
return ret;
}
#endif /* !__CUDA_ARCH__ || __CUDA_ARCH__ >= 320 */
#endif /* __cplusplus && __CUDACC__ */
#undef __SM_32_INTRINSICS_DECL__
#endif /* !__SM_32_INTRINSICS_HPP__ */
|
/*
* 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.
*/
/*!
*
* \file to_gnf.cc
*
* \brief Turn A normal form into graph normal form.
*/
#include <tvm/relay/analysis.h>
#include <tvm/relay/expr_functor.h>
#include <tvm/relay/transform.h>
#include "let_list.h"
namespace tvm {
namespace relay {
class UseVarVisitor : public ExprVisitor {
public:
explicit UseVarVisitor(const Var& v) : v(v) {}
static bool UseVar(const Var& v, const Expr& e) {
UseVarVisitor uv(v);
uv(e);
return uv.use_var;
}
private:
bool use_var = false;
Var v;
void VisitExpr_(const VarNode* vn) override { use_var = use_var || (v == GetRef<Var>(vn)); }
};
class GNF : public ExprMutator {
private:
std::unordered_map<Var, Expr, ObjectPtrHash, ObjectPtrEqual> var_map_;
Expr VisitExpr_(const VarNode* vn) override {
Var v = GetRef<Var>(vn);
return var_map_.count(v) == 0 ? v : var_map_.at(v);
}
static bool UseVar(const Var& v, const Expr& e) { return UseVarVisitor::UseVar(v, e); }
static Expr WrapRec(const Var& var, const Expr& val) {
return UseVar(var, val) ? Let(var, val, var) : val;
}
Expr VisitExpr_(const LetNode* ln) override {
var_map_.insert(std::pair<Var, Expr>(ln->var, WrapRec(ln->var, VisitExpr(ln->value))));
return VisitExpr(ln->body);
}
};
Expr ToGraphNormalForm(const Expr& e) { return GNF()(e); }
namespace transform {
Pass ToGraphNormalForm() {
runtime::TypedPackedFunc<Function(Function, IRModule, PassContext)> pass_func =
[=](Function f, IRModule m, PassContext pc) {
return Downcast<Function>(ToGraphNormalForm(f));
};
return CreateFunctionPass(pass_func, 1, "ToGraphNormalForm", {});
}
TVM_REGISTER_GLOBAL("relay._transform.ToGraphNormalForm").set_body_typed(ToGraphNormalForm);
} // namespace transform
} // namespace relay
} // namespace tvm
|
#include <stdio.h>
#include <cmath>
#include <lvr2/io/Timestamp.hpp>
// TODO reorder colors etc...
namespace lvr2{
template <typename BaseVecT>
PointOctree<BaseVecT>::PointOctree(PointBufferPtr& points, int depth) : m_points(*(points->getFloatChannel("points")))
{
// FloatChannelOptional pts_channel = points->getFloatChannel("points");
// m_points = *pts_channel;
// initializ min max for bounding box
BaseVecT p = m_points[0];
float minX = p.x;
float minY = p.y;
float minZ = p.z;
float maxX = p.x;
float maxY = p.y;
float maxZ = p.z;
for(int i = 0; i < points->numPoints() - 1; ++i)
{
p = m_points[i];
minX = std::min(minX, p.x);
minY = std::min(minY, p.y);
minZ = std::min(minZ, p.z);
maxX = std::max(maxX, p.x);
maxY = std::max(maxY, p.y);
maxZ = std::max(maxZ, p.z);
}
// make sure all points are inliers
minX -= 1.0;
minY -= 1.0;
minZ -= 1.0;
maxX += 1.0;
maxY += 1.0;
maxZ += 1.0;
// make it square, there has to be a more elegant solution.
float min = std::min(minX, std::min(minY, minZ));
float max = std::max(maxX, std::max(maxY, maxZ));
BaseVecT v1(min, min, min);
BaseVecT v2(max, max, max);
m_bbox = BoundingBox<BaseVecT>(v1, v2);
// int depth = std::ceil(std::log2(m_bbox.getLongestSide()/m_voxelSize));
m_voxelSize = m_bbox.getXSize() / std::pow(2, depth);
long offset = 0;
m_root = reinterpret_cast<BOct*>(m_mem.alloc<BOct>(1, offset));
//std::cout << msg << std::endl;
//if(offset)
//{
// std::cout << "offset" << std::endl;
//}
// std::vector<BaseVecT > pts = points->getPointBufferReference();
std::cout << m_bbox << std::endl;
std::cout << lvr2::timestamp << "Start building octree with voxelsize " << m_voxelSize << std::endl;
m_root = (BOct*)((unsigned char*) m_root + buildTree(m_root, 0, points->numPoints(), m_bbox));
std::cout << lvr2::timestamp << "generating genDisplayLists " << std::endl;
genDisplayLists();
std::cout << lvr2::timestamp << "generating genDisplayLists done" << std::endl;
std::cout << lvr2::timestamp << "Octree rdy " << std::endl;
// m_points.clear();
// std::vector<BaseVecT >().swap(m_points);
// colorAndWrite(m_root);
}
template <typename BaseVecT>
void PointOctree<BaseVecT>::getBBoxes(const BoundingBox<BaseVecT>& bbox, BoundingBox<BaseVecT>* boxes)
{
BaseVecT centroid = bbox.getCentroid();
// square bbox
auto size = bbox.getXSize();
for(int i = 0; i < 8; ++i)
{
BaseVecT bboxLowerLeft = centroid;
BaseVecT bboxTopRight = centroid;
// top
if(i & 4)
{
bboxTopRight.x += size / 2.0;
}
else
{
bboxLowerLeft.x -= size / 2.0;
}
if(i & 2)
{
bboxTopRight.y += size / 2.0;
}
else
{
bboxLowerLeft.y -= size / 2.0;
}
if(i & 1)
{
bboxTopRight.z += size / 2.0;
}
else
{
bboxLowerLeft.z -= size / 2.0;
}
boxes[i] = BoundingBox<BaseVecT>(bboxLowerLeft, bboxTopRight);
}
}
template <typename BaseVecT>
unsigned char PointOctree<BaseVecT>::getIndex(const BaseVecT& point, const BoundingBox<BaseVecT>& bbox)
{
BaseVecT centroid = bbox.getCentroid();
unsigned char index = 0;
// TODO i think this is not consistent. Coordinate system
//
// y
// | x
// | / ???
// | /
// |/_____ z
if(point.x > centroid.x)
{
index += 4;
}
// "top"
if(point.y > centroid.y)
{
index += 2;
}
// "right"
if(point.z > centroid.z)
{
index += 1;
}
return index;
}
template <typename BaseVecT>
template <typename T>
inline void PointOctree<BaseVecT>::link(BOct* parent, T* child)
{
parent->m_child =(long)((unsigned char*)child - (unsigned char*)parent);
}
template <typename BaseVecT>
template <typename T>
inline T* PointOctree<BaseVecT>::getChildPtr(BOct* parent)
{
return reinterpret_cast<T*>((unsigned char*)parent + parent->m_child);
}
template <typename BaseVecT>
template <typename PtrT>
void PointOctree<BaseVecT>::sortPC(size_t start, size_t size, const BoundingBox<BaseVecT>& bbox, size_t bucket_sizes[8])
{
// TODO template this properly
PtrT ptr[8];
PtrT beg[8];
beg[0] = ptr[0] = &m_points[start];
// beg[0] = ptr[0] = p;
//creating pointers for bucket starts.
for(int j = 1; j < 8; ++j)
{
// pointing to first position of bucket.
beg[j] = ptr[j] = ptr[j - 1] + bucket_sizes[j - 1];
}
size_t end = start + size;
//size_t full = ptr[1] - &pts[0];
for(size_t i = start; i < end; )
{
int index = getIndex(m_points[i], bbox);
if(ptr[index] == &(m_points[end]))
{
std::cout << "This should have never happened." << std::endl;
std::cout << (int) index << std::endl;
}
if((beg[index] <= &m_points[i]) && (&m_points[i] < ptr[index]))
{
i = ptr[index] - &m_points[0];
continue;
}
if(ptr[index] == &m_points[i])
{
// is already in correct bucket
if(ptr[index] < &m_points[end - 1])
ptr[index]++;
i++;
}
else
{
// TODO
// We somehow need 2 temporary variables. Otherwise it won't work with the proxy(Ptr)
// advance bucket pointer if current element is correct.
BaseVecT tmp = *ptr[index];
while(getIndex(tmp, bbox) == index)
{
if(ptr[index] < &(m_points[end - 1]))
ptr[index]++;
tmp = *ptr[index];
}
BaseVecT aux = m_points[i];
*(ptr[index]) = aux;
m_points[i] = tmp;
if(ptr[index] < &(m_points[end - 1]))
ptr[index]++;
}
}
}
template <typename BaseVecT>
long PointOctree<BaseVecT>::buildTree(BOct* oct, size_t start, size_t size, const BoundingBox<BaseVecT>& bbox)
{
// TODO did i need this.
// if(pts.empty())
// {
// return 0;
// }
BoundingBox<BaseVecT> boxes[8];
getBBoxes(bbox, boxes);
// std::vector<BaseVecT > octPoints[8];
size_t octSizes[8] = {0, 0, 0, 0, 0, 0, 0, 0};
//std::cout << "bbox size " << bbox.getXSize() << std::endl;
if(bbox.getXSize()/2.0 <= m_voxelSize)
{
//std::cout << "leaf" << std::endl;
int numChildren = 0;
for(size_t i = start; i < (start + size); ++i)
{
unsigned char index = getIndex(m_points[i], bbox);
// octPoints[index].push_back(point);
octSizes[index]++;
//printf("Address %p\n", oct);
if(!(oct->m_leaf & (1 << index)))
{
oct->m_leaf |= (1 << index);
numChildren++;
}
}
// sortPC(&m_points[start], start, size, bbox, octSizes);
sortPC<decltype(&(m_points[start]))>(start, size, bbox, octSizes);
// sortPC(start, size, bbox, octSizes);
// force reallocation to clear vec
// pts.clear();
// std::vector<BaseVecT >().swap(pts);
long offset = 0;
// std::cout << "no leafs. " << numChildren << std::endl;
Leaf* leaves = reinterpret_cast<Leaf*>(m_mem.alloc<Leaf>(numChildren, offset));
if(offset)
{
oct = (BOct*) ((unsigned char*)oct + offset);
}
link(oct, leaves);
int cnt = 0;
for(unsigned i = 0; i < 8; ++i)
{
if(oct->m_leaf & (1 << i))
{
leaves[cnt].m_start = start;
leaves[cnt].m_size = octSizes[i];
cnt++;
start += octSizes[i];
// leaves[cnt].m_size = octPoints[i].size();
// if(m_points.empty())
// {
// leaves[cnt].m_start = 0;
// }
// else
// {
// leaves[cnt].m_start = m_points.end() - m_points.begin();
// }
// m_points.insert(m_points.end(), octPoints[i].begin(), octPoints[i].end());
// cnt++;
// // clear and force reallocation
// octPoints[i].clear();
// std::vector<BaseVecT >().swap(octPoints[i]);
}
}
//std::cout << "return offset " << offset << std::endl;
return offset;
}
int numChildren = 0;
for(size_t i = start; i < (start + size); ++i)
{
unsigned char index = getIndex(m_points[i], bbox);
// octPoints[index].push_back(point);
octSizes[index]++;
if(!(oct->m_valid & (1 << index)))
{
//std::cout << "setting new valid " << index << std::endl;
oct->m_valid |= (1 << index);
numChildren++;
}
}
//sortPC(&m_points[start], start, size, bbox, octSizes);
sortPC<decltype(&(m_points[start]))>(start, size, bbox, octSizes);
// force reallocation to clear vec
// pts.clear();
// std::vector<BaseVecT >().swap(pts);
long offset = 0;
BOct* newOct = reinterpret_cast<BOct*>(m_mem.alloc<BOct>(numChildren, offset));
// printf("Address %p\n", newOct);
// realloc in blockalloc may cause an address change.
if(offset)
{
oct = (BOct*) ((unsigned char*)oct + offset);
}
link(oct, newOct);
unsigned char cnt = 0;
for(unsigned char i = 0; i < 8; ++i)
{
long sub_offset = 0;
if(oct->m_valid & (1 << i))
{
sub_offset += buildTree(&newOct[cnt++], start, octSizes[i], boxes[i]);
start += octSizes[i];
if(sub_offset)
{
newOct = (BOct*) ((unsigned char*)newOct + sub_offset);
oct = (BOct*) ((unsigned char*)oct + sub_offset);
}
offset += sub_offset;
}
}
return offset;
// due to reallocation we might need to fix the root and the current oct address
// higher level octants are not effected because they are already linked.
// BULLSHIT we allocate in lower levels and then go to the next octant
}
// template <typename BaseVecT>
// void PointOctree<BaseVecT>::writeLeaf(Leaf* leaf, unsigned char index)
// {
// //std::cout << leaf->m_start << " " << leaf->m_size << std::endl;
// for(unsigned int i = leaf->m_start; i < (leaf->m_start + leaf->m_size); ++i)
// {
// auto point = m_points[i];
//
// std::cout << point.x << " "
// << point.y << " "
// << point.z << " "
// << (int)pow(2, index) << " "
// << (int)pow(2, index) << " "
// << (int)pow(2, index) << " "
// << std::endl;
// }
// }
//
// template <typename BaseVecT>
// void PointOctree<BaseVecT>::colorAndWrite(BOct* oct, unsigned char index)
// {
//
// unsigned char cnt = 0;
// if(oct->m_leaf)
// {
// Leaf* child = getChildPtr<Leaf>(oct);
// for(unsigned char i = 0; i < 8; ++i)
// {
// if(oct->m_leaf & (1 << i))
// {
// writeLeaf(child + cnt, i);
// cnt++;
// }
// }
// }
// else
// {
// BOct* child = getChildPtr<BOct>(oct);
// for(unsigned char i = 0; i < 8; ++i)
// {
// if(oct->m_valid & (1 << i))
// {
// colorAndWrite(child + cnt, index);
// cnt++;
// }
// }
// }
//
// }
//
// template <typename BaseVecT>
// void PointOctree<BaseVecT>::colorAndWrite(BOct* oct)
// {
// static int depth = 0;
// unsigned char cnt = 0;
// if(oct->m_leaf)
// {
// Leaf* child = getChildPtr<Leaf>(oct);
// for(unsigned char i = 0; i < 8; ++i)
// {
// if(oct->m_leaf & (1 << i))
// {
// writeLeaf(child + cnt, i);
// cnt++;
// }
// }
// }
// else
// {
// BOct* child = getChildPtr<BOct>(oct);
// for(unsigned char i = 0; i < 8; ++i)
// {
// if(oct->m_valid & (1 << i))
// {
// if(oct != m_root)
// {
// colorAndWrite(child + cnt, i);
// cnt++;
// }
// else
// {
// colorAndWrite(child + cnt);
// cnt++;
// depth++;
// }
// }
// }
// }
// }
template <typename BaseVecT>
void PointOctree<BaseVecT>::getPoints(BOct* oct, std::vector<unsigned int>& indices)
{
unsigned char cnt = 0;
if(oct->m_leaf)
{
Leaf* leaf = getChildPtr<Leaf>(oct);
for(unsigned char i = 0; i < 8; ++i)
{
if(oct->m_leaf & (1 << i))
{
indices.push_back(leaf[cnt].m_listIndex + m_lod);
//if(!m_lod)
//{
// auto start = m_points.begin() + leaf[cnt].m_start;
// pts.insert(pts.end(), start, start + leaf[cnt].m_size);
//}
//else
//{
// for(int i = 0; i < leaf[cnt].m_size; ++i)
// {
// if((i % m_lod) == 0)
// {
// pts.push_back(m_points[leaf[cnt].m_start + i]);
// }
// }
//}
cnt++;
}
}
}
else
{
BOct* child = getChildPtr<BOct>(oct);
for(unsigned char i = 0; i < 8; ++i)
{
if(oct->m_valid & (1 << i))
{
getPoints(child + cnt++, indices);
}
}
}
}
template <typename BaseVecT>
void PointOctree<BaseVecT>::genDisplayLists(Leaf* leaf)
{
leaf->m_listIndex = glGenLists(5);
for(int i = 0; i < 5; ++i)
{
glNewList(leaf->m_listIndex + i, GL_COMPILE);
glBegin(GL_POINTS);
size_t mod = 1;
if(i == 9)
{
if(8 < leaf->m_size)
mod = leaf->m_size / 8;
}
else if(i == 8)
{
if(16 < leaf->m_size)
mod = leaf->m_size / 16;
}
else if(i == 7)
{
if(32 < leaf->m_size)
mod = leaf->m_size / 32;
}
else if(i == 6)
{
if(64 < leaf->m_size)
mod = leaf->m_size / 64;
}
else if(i == 5)
{
if(128 < leaf->m_size)
mod = leaf->m_size / 128;
}
else if(i == 4)
{
if(256 < leaf->m_size)
mod = leaf->m_size / 256;
}
else if(i == 3)
{
if(512 < leaf->m_size)
mod = leaf->m_size / 512;
}
else if(i == 2)
{
if(1024 < leaf->m_size)
mod = leaf->m_size / 1024;
}
else if(i == 1)
{
if(2048 < leaf->m_size)
mod = leaf->m_size / 2048;
}
for(size_t j = leaf->m_start;
j < (leaf->m_start + leaf->m_size);
++j)
{
if(j % mod)
continue;
glColor3f(255.0f, 255.0f, 255.0f);
BaseVecT p = m_points[j];
glVertex3f(p.x,
p.y,
p.z);
}
glEnd();
glEndList();
}
}
template <typename BaseVecT>
void PointOctree<BaseVecT>::genDisplayLists(BOct* oct)
{
unsigned char cnt = 0;
if(oct->m_leaf)
{
Leaf* leaf = getChildPtr<Leaf>(oct);
for(unsigned char i = 0; i < 8; ++i)
{
if(oct->m_leaf & (1 << i))
{
genDisplayLists(leaf + cnt++);
}
}
}
else
{
BOct* child = getChildPtr<BOct>(oct);
for(unsigned char i = 0; i < 8; ++i)
{
if(oct->m_valid & (1 << i))
{
genDisplayLists(child + cnt++);
}
}
}
}
template <typename BaseVecT>
void PointOctree<BaseVecT>::normalizePlanes(double planes[6][4])
{
for(unsigned char i = 0; i < 6; ++i)
{
double pX = planes[i][0];
double pY = planes[i][1];
double pZ = planes[i][2];
double norm = std::sqrt(std::pow(pX, 2) + std::pow(pY, 2) + std::pow(pZ, 2));
// seems like we have to flip the normals.
planes[i][0] =(-1) * pX / norm;
planes[i][1] =(-1) * pY / norm;
planes[i][2] =(-1) * pZ / norm;
}
}
template <typename BaseVecT>
void PointOctree<BaseVecT>::intersect(double planes[6][4], std::vector<unsigned int>& indices)
{
normalizePlanes(planes);
intersect(m_root, m_bbox, planes, indices);
}
template <typename BaseVecT>
void PointOctree<BaseVecT>::intersect(Leaf* leaf, const BoundingBox<BaseVecT>& bbox, double planes[6][4], std::vector<unsigned int >& indices)
{
for(unsigned char i = 0; i < 6; ++i)
{
BaseVecT octMin = bbox.getMin();
BaseVecT octMax = bbox.getMax();
BaseVecT pVertex = octMin;
if(planes[i][0] >= 0)
{
pVertex.x = octMax.x;
}
if(planes[i][1] >= 0)
{
pVertex.y = octMax.y;
}
if(planes[i][2] >= 0)
{
pVertex.z = octMax.z;
}
double distance;
// get distance pVertex. hessian
distance = planes[i][0] * pVertex.x + planes[i][1] * pVertex.y + planes[i][2] * pVertex.z + planes[i][3];
// outlier.
if(distance < 0)
return;
}
// if leaf is intersected it is not culled.
indices.push_back(leaf->m_listIndex + m_lod);
}
template <typename BaseVecT>
void PointOctree<BaseVecT>::intersect(BOct* oct, const BoundingBox<BaseVecT>& bbox, double planes[6][4], std::vector<unsigned int >& indices)
{
bool inlier = true;
for(unsigned char i = 0; i < 6; ++i)
{
BaseVecT octMin = bbox.getMin();
BaseVecT octMax = bbox.getMax();
BaseVecT pVertex = octMin;
BaseVecT nVertex = octMax;
if(planes[i][0] >= 0)
{
pVertex.x = octMax.x;
nVertex.x = octMin.x;
}
if(planes[i][1] >= 0)
{
pVertex.y = octMax.y;
nVertex.y = octMin.y;
}
if(planes[i][2] >= 0)
{
pVertex.z = octMax.z;
nVertex.z = octMin.z;
}
double distance;
// get distance pVertex. hessian
distance = planes[i][0] * pVertex.x + planes[i][1] * pVertex.y + planes[i][2] * pVertex.z + planes[i][3];
// outlier.
if(distance < 0)
return;
// distance to nVertex
distance = planes[i][0] * nVertex.x + planes[i][1] * nVertex.y + planes[i][2] * nVertex.z + planes[i][3];
if(distance < 0)
inlier = false;
}
if(inlier)
{
return getPoints(oct, indices);
}
BoundingBox<BaseVecT> bboxes[8];
getBBoxes(bbox, bboxes);
unsigned char cnt = 0;
if(oct->m_leaf)
{
for(unsigned char i = 0; i < 8; ++i)
{
if(oct->m_leaf & (1 << i))
{
intersect(getChildPtr<Leaf>(oct) + cnt++, bboxes[i], planes, indices);
}
}
}
else
{
for(unsigned char i = 0; i < 8; ++i)
{
if(oct->m_valid & (1 << i))
{
intersect(getChildPtr<BOct>(oct) + cnt++, bboxes[i], planes, indices);
}
}
}
}
// template <typename BaseVecT>
// void PointOctree<BaseVecT>::intersect(const BoundingBox<BaseVecT>& cullBBox, std::vector<BaseVecT>& pts)
// {
// intersect(m_root, m_bbox, cullBBox, pts);
// }
// template <typename BaseVecT>
// void PointOctree<BaseVecT>::intersect(BOct* oct, const BoundingBox<BaseVecT>& octBBox, const BoundingBox<BaseVecT>& cullBBox, std::vector<BaseVecT>& pts)
// {
// if(oct == nullptr)
// {
// return;
// }
//
// if(oct->m_leaf)
// {
// getPoints(oct, pts);
// return;
// }
//
// BaseVecT cullMin = cullBBox.getMin();
// BaseVecT cullMax = cullBBox.getMax();
// BaseVecT octMin = octBBox.getMin();
// BaseVecT octMax = octBBox.getMax();
//
// // octree is completely visible.
// if((cullMin.x <= octMin.x && cullMax.x >= octMax.x) &&
// (cullMin.y <= octMin.y && cullMax.y >= octMax.y) &&
// (cullMin.z <= octMin.z && cullMax.z >= octMax.z))
// {
// getPoints(oct, pts);
// return;
// }
//
// // get children bbboxes.
// BoundingBox<BaseVecT> bboxes[8];
// getBBoxes(octBBox, bboxes);
//
// int cnt = 0;
// for(unsigned char i = 0; i < 8; ++i)
// {
// if(oct->m_valid & (1 << i))
// {
// octMin = bboxes[i].getMin();
// octMax = bboxes[i].getMax();
//
// if(cullMin.x < octMin.x && cullMax.x > octMax.x)
// {
// continue;
// }
//
// if(cullMin.y < octMin.y && cullMax.y > octMax.y)
// {
// continue;
// }
//
// if(cullMin.z < octMin.z && cullMax.z > octMax.x)
// {
// continue;
// }
//
// intersect(getChildPtr<BOct> + cnt++, bboxes[i], cullBBox, pts);
// }
// }
// }
}
|
/***************************************************************
*
* Copyright (C) 1990-2007, Condor Team, Computer Sciences Department,
* University of Wisconsin-Madison, WI.
*
* 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 "condor_common.h"
#include "condor_constants.h"
#include "std_univ_io.h"
#include "condor_uid.h"
#include "std_univ_sock.h"
#include "condor_network.h"
#include "internet.h"
#include "condor_debug.h"
#include "condor_netdb.h"
#include "condor_rw.h"
#if !defined(WIN32)
#define closesocket close
#endif
#define NORMAL_HEADER_SIZE 5
#define MAX_HEADER_SIZE NORMAL_HEADER_SIZE
int StdUnivSock::setsockopt(int level, int optname, const char* optval, int optlen)
{
ASSERT (_sock != INVALID_SOCKET);
if(::setsockopt(_sock, level, optname, optval, optlen) < 0)
{
return FALSE;
}
return TRUE;
}
int StdUnivSock::close()
{
if (type() == Stream::reli_sock && IsDebugLevel(D_NETWORK)) {
dprintf( D_NETWORK, "CLOSE %s fd=%d\n",
sock_to_string(_sock), _sock );
}
if ( _sock != INVALID_SOCKET ) {
if (::closesocket(_sock) < 0) return FALSE;
}
_sock = INVALID_SOCKET;
_who.clear();
addr_changed();
return TRUE;
}
/* NOTE: on timeout() we return the previous timeout value, or a -1 on an error.
* Once more: we do _not_ return FALSE on Error like most other CEDAR functions;
* we return a -1 !!
*/
int
StdUnivSock::timeout(int sec)
{
int t = _timeout;
_timeout = sec;
if (_sock == INVALID_SOCKET) {
// Rather than forcing creation of the socket here, we just
// return success. All paths that create the socket also
// set the timeout.
return t;
}
if (_timeout == 0) {
// Put socket into blocking mode
int fcntl_flags;
if ( (fcntl_flags=fcntl(_sock, F_GETFL)) < 0 )
return -1;
fcntl_flags &= ~O_NONBLOCK; // reset blocking mode
if ( fcntl(_sock,F_SETFL,fcntl_flags) == -1 )
return -1;
} else {
// Put socket into non-blocking mode.
// However, we never want to put a UDP socket into non-blocking mode.
if ( type() != safe_sock ) { // only if socket is not UDP...
int fcntl_flags;
if ( (fcntl_flags=fcntl(_sock, F_GETFL)) < 0 )
return -1;
fcntl_flags |= O_NONBLOCK; // set nonblocking mode
if ( fcntl(_sock,F_SETFL,fcntl_flags) == -1 )
return -1;
}
}
return t;
}
void
StdUnivSock::addr_changed()
{
// these are all regenerated whenever they are needed, so when
// either the peer's address or our address change, zap them all
_peer_ip_buf[0] = '\0';
_sinful_peer_buf[0] = '\0';
}
const char *
StdUnivSock::peer_ip_str()
{
if( _peer_ip_buf[0] ) {
return _peer_ip_buf;
}
MyString ip_string = _who.to_ip_string();
strncpy( _peer_ip_buf, ip_string.Value(), IP_STRING_BUF_SIZE );
_peer_ip_buf[IP_STRING_BUF_SIZE-1] = '\0';
return _peer_ip_buf;
}
condor_sockaddr
StdUnivSock::my_addr()
{
sockaddr_storage addr;
SOCKET_LENGTH_TYPE addr_len;
addr_len = sizeof(addr);
if (getsockname(_sock, (sockaddr*)&addr, &addr_len) < 0)
return condor_sockaddr::null;
return condor_sockaddr((const sockaddr*)&addr);
}
condor_sockaddr
StdUnivSock::peer_addr()
{
sockaddr_storage addr;
SOCKET_LENGTH_TYPE addr_len;
addr_len = sizeof(addr);
if (getpeername(_sock, (sockaddr*)&addr, &addr_len) < 0)
return condor_sockaddr::null;
return condor_sockaddr((const sockaddr*)&addr);
}
char *
StdUnivSock::get_sinful_peer()
{
if( _sinful_peer_buf[0] ) {
return _sinful_peer_buf;
}
MyString sinful_string = _who.to_sinful();
ASSERT(sinful_string.Length() < (int)sizeof(_sinful_peer_buf));
strcpy(_sinful_peer_buf, sinful_string.Value());
return _sinful_peer_buf;
}
char const *
StdUnivSock::default_peer_description()
{
char const *retval = get_sinful_peer();
if( !retval ) {
return "(unconnected socket)";
}
return retval;
}
bool
StdUnivSock::canEncrypt()
{
return false;
}
/*
NOTE: All StdUnivSock constructors initialize with this, so you can
put any shared initialization code here. -Derek Wright 3/12/99
*/
void
StdUnivSock::init()
{
ignore_next_encode_eom = FALSE;
ignore_next_decode_eom = FALSE;
_bytes_sent = 0.0;
_bytes_recvd = 0.0;
snd_msg.buf.reset();
rcv_msg.buf.reset();
rcv_msg.init_parent(this);
snd_msg.init_parent(this);
_sock = INVALID_SOCKET;
_timeout = 0;
_who.clear();
addr_changed();
}
StdUnivSock::StdUnivSock()
: Stream()
{
init();
}
StdUnivSock::~StdUnivSock()
{
close();
}
int
StdUnivSock::handle_incoming_packet()
{
/* do not queue up more than one message at a time on reliable sockets */
/* but return 1, because old message can still be read. */
if (rcv_msg.ready) {
return TRUE;
}
if (!rcv_msg.rcv_packet(peer_description(), _sock, _timeout)) {
return FALSE;
}
return TRUE;
}
int
StdUnivSock::end_of_message()
{
int ret_val = FALSE;
switch(_coding){
case stream_encode:
if ( ignore_next_encode_eom == TRUE ) {
ignore_next_encode_eom = FALSE;
return TRUE;
}
if (!snd_msg.buf.empty()) {
return snd_msg.snd_packet(peer_description(), _sock, TRUE, _timeout);
}
if ( allow_empty_message_flag ) {
allow_empty_message_flag = FALSE;
return TRUE;
}
break;
case stream_decode:
if ( ignore_next_decode_eom == TRUE ) {
ignore_next_decode_eom = FALSE;
return TRUE;
}
if ( rcv_msg.ready ) {
if ( rcv_msg.buf.consumed() ) {
ret_val = TRUE;
}
else if( !allow_empty_message_flag ) {
char const *ip = get_sinful_peer();
dprintf(D_FULLDEBUG,"Failed to read end of message from %s.\n",ip ? ip : "(null)");
}
rcv_msg.ready = FALSE;
rcv_msg.buf.reset();
}
if ( allow_empty_message_flag ) {
allow_empty_message_flag = FALSE;
return TRUE;
}
break;
default:
ASSERT(0);
}
return ret_val;
}
bool
StdUnivSock::peek_end_of_message()
{
EXCEPT("not implemented");
return false;
}
int
StdUnivSock::put_bytes(const void *data, int sz)
{
int tw, header_size = NORMAL_HEADER_SIZE;
int nw;
unsigned char * dta = NULL;
if((dta = (unsigned char *) malloc(sz)) != 0)
memcpy(dta, data, sz);
ignore_next_encode_eom = FALSE;
for(nw=0;;) {
if (snd_msg.buf.full()) {
if (!snd_msg.snd_packet(peer_description(), _sock, FALSE, _timeout)) {
if (dta != NULL) {
free(dta);
dta = NULL;
}
return FALSE;
}
}
if (snd_msg.buf.empty()) {
snd_msg.buf.seek(header_size);
}
if ((tw = snd_msg.buf.put_max(&((char *)dta)[nw], sz-nw)) < 0) {
if (dta != NULL) {
free(dta);
dta = NULL;
}
return -1;
}
nw += tw;
if (nw >= sz) {
break;
}
}
if (nw > 0) {
_bytes_sent += nw;
}
if (dta != NULL) {
free(dta);
dta = NULL;
}
return nw;
}
int
StdUnivSock::get_bytes(void *dta, int max_sz)
{
int bytes;
ignore_next_decode_eom = FALSE;
while (!rcv_msg.ready) {
if (!handle_incoming_packet()){
return FALSE;
}
}
bytes = rcv_msg.buf.get(dta, max_sz);
if (bytes > 0) {
_bytes_recvd += bytes;
}
return bytes;
}
int StdUnivSock::get_ptr( void *&ptr, char delim)
{
while (!rcv_msg.ready){
if (!handle_incoming_packet()) {
return FALSE;
}
}
return rcv_msg.buf.get_tmp(ptr, delim);
}
int StdUnivSock::peek( char &c)
{
while (!rcv_msg.ready) {
if (!handle_incoming_packet()) {
return FALSE;
}
}
return rcv_msg.buf.peek(c);
}
StdUnivSock::RcvMsg :: RcvMsg() : p_sock(0),ready(0) {}
StdUnivSock::RcvMsg::~RcvMsg() {}
int StdUnivSock::RcvMsg::rcv_packet( char const *peer_description, SOCKET _sock, int _timeout)
{
StdUnivBuf *tmp;
char hdr[MAX_HEADER_SIZE];
int end;
int len, len_t, header_size;
int tmp_len;
header_size = NORMAL_HEADER_SIZE;
int retval = condor_read(peer_description,_sock,hdr,header_size,_timeout);
if ( retval < 0 &&
retval != -2 ) // -2 means peer just closed the socket
{
dprintf(D_ALWAYS,"IO: Failed to read packet header\n");
return FALSE;
}
if ( retval == -2 ) { // -2 means peer just closed the socket
dprintf(D_FULLDEBUG,"IO: EOF reading packet header\n");
return FALSE;
}
end = (int) ((char *)hdr)[0];
memcpy(&len_t, &hdr[1], 4);
len = (int) ntohl(len_t);
if (end < 0 || end > 10) {
dprintf(D_ALWAYS,"IO: Incoming packet header unrecognized\n");
return FALSE;
}
if (!(tmp = new StdUnivBuf)){
dprintf(D_ALWAYS, "IO: Out of memory\n");
return FALSE;
}
if (len > tmp->max_size()){
delete tmp;
dprintf(D_ALWAYS, "IO: Incoming packet is too big\n");
return FALSE;
}
if (len <= 0)
{
delete tmp;
dprintf(D_ALWAYS,
"IO: Incoming packet improperly sized (len=%d,end=%d)\n",
len,end);
return FALSE;
}
if ((tmp_len = tmp->read(peer_description, _sock, len, _timeout)) != len){
delete tmp;
dprintf(D_ALWAYS, "IO: Packet read failed: read %d of %d\n",
tmp_len, len);
return FALSE;
}
if (!buf.put(tmp)) {
delete tmp;
dprintf(D_ALWAYS, "IO: Packet storing failed\n");
return FALSE;
}
if (end) {
ready = TRUE;
}
return TRUE;
}
StdUnivSock::SndMsg::SndMsg() :
p_sock(0)
{
}
StdUnivSock::SndMsg::~SndMsg()
{
}
int StdUnivSock::SndMsg::snd_packet( char const *peer_description, int _sock, int end, int _timeout )
{
char hdr[MAX_HEADER_SIZE];
int len, header_size;
int ns;
header_size = NORMAL_HEADER_SIZE;
hdr[0] = (char) end;
ns = buf.num_used() - header_size;
len = (int) htonl(ns);
memcpy(&hdr[1], &len, 4);
if (buf.flush(peer_description, _sock, hdr, header_size, _timeout) != (ns+header_size)){
return FALSE;
}
if( end ) {
buf.dealloc_buf(); // save space, now that we are done sending
}
return TRUE;
}
#ifndef WIN32
// interface no longer supported
int
StdUnivSock::attach_to_file_desc( int fd )
{
ASSERT (_sock == INVALID_SOCKET);
_sock = fd;
timeout(0); // make certain in blocking mode
return TRUE;
}
#endif
Stream::stream_type
StdUnivSock::type()
{
return Stream::reli_sock;
}
bool
StdUnivSock::peer_is_local()
{
EXCEPT("not implemented");
return false;
}
const char *
StdUnivSock::serialize(const char *)
{
EXCEPT("not implemented");
return NULL;
}
char *
StdUnivSock::serialize() const
{
EXCEPT("not implemented");
return NULL;
}
Stream *
StdUnivSock::CloneStream()
{
EXCEPT("not implemented");
return NULL;
}
int
StdUnivSock::bytes_available_to_read()
{
EXCEPT("not implemented");
return -1;
}
const char*
StdUnivSock::my_ip_str()
{
EXCEPT("not implemented");
return NULL;
}
|
//%2005////////////////////////////////////////////////////////////////////////
//
// Copyright (c) 2000, 2001, 2002 BMC Software; Hewlett-Packard Development
// Company, L.P.; IBM Corp.; The Open Group; Tivoli Systems.
// Copyright (c) 2003 BMC Software; Hewlett-Packard Development Company, L.P.;
// IBM Corp.; EMC Corporation, The Open Group.
// Copyright (c) 2004 BMC Software; Hewlett-Packard Development Company, L.P.;
// IBM Corp.; EMC Corporation; VERITAS Software Corporation; The Open Group.
// Copyright (c) 2005 Hewlett-Packard Development Company, L.P.; IBM Corp.;
// EMC Corporation; VERITAS Software Corporation; The Open Group.
//
// 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.
//
//==============================================================================
//
// Author: Markus Mueller (sedgewick_de@yahoo.de)
//
// Modified By: Mike Day (mdday@us.ibm.com)
//
//%/////////////////////////////////////////////////////////////////////////////
PEGASUS_NAMESPACE_BEGIN
static sigset_t *block_signal_mask(sigset_t *sig)
{
sigemptyset(sig);
// should not be used for main()
sigaddset(sig, SIGHUP);
sigaddset(sig, SIGINT);
// maybe useless, since KILL can't be blocked according to POSIX
sigaddset(sig, SIGKILL);
sigaddset(sig, SIGABRT);
sigaddset(sig, SIGALRM);
sigaddset(sig, SIGPIPE);
// Note: older versions of the linux pthreads library use SIGUSR1 and SIGUSR2
// internally to stop and start threads that are blocking, the newer ones
// implement this through the kernel's real time signals
// since SIGSTOP/CONT can handle suspend()/resume() on Linux
// block them
// #if defined(PEGASUS_PLATFORM_LINUX_IX86_GNU)
// sigaddset(sig, SIGUSR1);
// sigaddset(sig, SIGUSR2);
// #endif
#ifndef PEGASUS_PLATFORM_ZOS_ZSERIES_IBM
pthread_sigmask(SIG_BLOCK, sig, NULL);
#else
sigprocmask(SIG_BLOCK, sig, NULL);
#endif
return sig;
}
#if defined PEGASUS_PLATFORM_ZOS_ZSERIES_IBM || defined PEGASUS_PLATFORM_SOLARIS_SPARC_CC
extern "C" {
void * _linkage(void * zosParm)
{
zosParmDef * zos;
void * retval;
zos = (zosParmDef *)zosParm;
retval = (*(zos->_start))(zos->realParm);
free(zosParm);
return retval;
}
}
#endif
////////////////////////////////////////////////////////////////////////////
Thread::Thread(
PEGASUS_THREAD_RETURN (PEGASUS_THREAD_CDECL *start)(void *),
void *parameter,
Boolean detached)
: _is_detached(detached),
_cancel_enabled(true),
_cancelled(false),
_suspend_count(),
_start(start),
_cleanup(true),
_tsd(true),
_thread_parm(parameter),
_exit_code(0)
{
pthread_attr_init(&_handle.thatt);
#if defined(PEGASUS_PLATFORM_HPUX_PARISC_ACC)
size_t stacksize;
if (pthread_attr_getstacksize(&_handle.thatt, &stacksize) == 0)
{
int rc = pthread_attr_setstacksize(&_handle.thatt, stacksize*2);
PEGASUS_ASSERT(rc == 0);
}
#endif
_handle.thid = 0;
}
Thread::~Thread()
{
try
{
join();
pthread_attr_destroy(&_handle.thatt);
empty_tsd();
}
catch (...)
{
// Do not allow the destructor to throw an exception
}
}
PEGASUS_NAMESPACE_END
|
/*
+----------------------------------------------------------------------+
| HipHop for PHP |
+----------------------------------------------------------------------+
| Copyright (c) 2010-2016 Facebook, Inc. (http://www.facebook.com) |
+----------------------------------------------------------------------+
| This source file is subject to version 3.01 of the PHP license, |
| that is bundled with this package in the file LICENSE, and is |
| available through the world-wide-web at the following url: |
| http://www.php.net/license/3_01.txt |
| If you did not receive a copy of the PHP license and are unable to |
| obtain it through the world-wide-web, please send a note to |
| license@php.net so we can mail you a copy immediately. |
+----------------------------------------------------------------------+
*/
#include "hphp/runtime/base/array-common.h"
#include "hphp/runtime/base/array-data.h"
#include "hphp/runtime/base/array-data-defs.h"
#include "hphp/runtime/base/array-init.h"
#include "hphp/runtime/base/mixed-array-defs.h"
#include "hphp/runtime/base/packed-array.h"
#include "hphp/runtime/base/type-variant.h"
namespace HPHP {
//////////////////////////////////////////////////////////////////////
ssize_t ArrayCommon::ReturnInvalidIndex(const ArrayData*) {
return 0;
}
bool ArrayCommon::ValidMArrayIter(const ArrayData* ad, const MArrayIter& fp) {
assert(fp.getContainer() == ad);
if (fp.getResetFlag()) return false;
if (ad->isPackedLayout()) {
assert(PackedArray::checkInvariants(ad));
return fp.m_pos != ad->getSize();
}
assert(MixedArray::asMixed(ad));
return fp.m_pos != MixedArray::asMixed(ad)->iterLimit();
}
ArrayData* ArrayCommon::Pop(ArrayData* a, Variant &value) {
if (!a->empty()) {
auto const pos = a->iter_last();
value = a->getValue(pos);
return a->remove(a->getKey(pos), a->cowCheck());
}
value = uninit_null();
return a;
}
ArrayData* ArrayCommon::Dequeue(ArrayData* a, Variant &value) {
if (!a->empty()) {
auto const pos = a->iter_begin();
value = a->getValue(pos);
auto const ret = a->remove(a->getKey(pos), a->cowCheck());
// In PHP, array_shift() will cause all numerically key-ed values re-keyed
ret->renumber();
return ret;
}
value = uninit_null();
return a;
}
ArrayData* ArrayCommon::ToVec(const ArrayData* a) {
auto const size = a->size();
if (!size) return staticEmptyVecArray();
VecArrayInit init{size};
for (ArrayIter it{a}; it; ++it) {
auto const& value = it.secondRef();
if (UNLIKELY(value.isReferenced())) {
throwRefInvalidArrayValueException(init.toArray());
}
init.append(value);
}
return init.create();
}
//////////////////////////////////////////////////////////////////////
}
|
// Copyright (C) 2022 Intel Corporation
// SPDX-License-Identifier: Apache-2.0
//
#pragma once
#include "ngraph/node.hpp"
#include "openvino/op/op.hpp"
namespace ov {
namespace intel_gna {
namespace op {
/// \brief PWL activation function
class Pwl : public ov::op::Op {
public:
OPENVINO_OP("Pwl", "intel_gna", ov::op::Op);
Pwl() = default;
/// \brief Constructs a Pwl node.
///
/// \param data - The input data tensor.
/// \param m - The list of the slopes of segment.
/// \param b - The list of the y-intercepts of segment.
/// \param knots - The list of x-coordinates of segment endpoints (segments number + 1).
Pwl(const ngraph::Output<ngraph::Node>& data,
const ngraph::Output<ngraph::Node>& m,
const ngraph::Output<ngraph::Node>& b,
const ngraph::Output<ngraph::Node>& knots);
void validate_and_infer_types() override;
bool visit_attributes(ov::AttributeVisitor& visitor) override;
std::shared_ptr<ngraph::Node> clone_with_new_inputs(const ov::OutputVector& new_args) const override;
bool evaluate(ov::TensorVector& outputs,
const ov::TensorVector& inputs,
const ov::EvaluationContext& evaluation_context) const override;
bool has_evaluate() const override;
void set_base_node(const std::shared_ptr<ngraph::Node>& base_node);
std::shared_ptr<ngraph::Node> get_base_node();
private:
template<typename T1>
bool evaluate_pwl(const std::tuple<>&, ov::TensorVector&, const ov::TensorVector&) const {
return false;
}
template<typename ...Types2>
bool evaluate_pwl(const std::tuple<>&, const std::tuple<Types2...>&, ov::TensorVector&, const ov::TensorVector&) const {
return false;
}
template<typename T1, typename ...Types1, typename ...Types2>
bool evaluate_pwl(const std::tuple<T1, Types1...>&,
const std::tuple<Types2...>& types2,
ov::TensorVector& outputs,
const ov::TensorVector& inputs) const {
if (evaluate_pwl<T1>(types2, outputs, inputs)) {
return true;
}
return evaluate_pwl(std::tuple<Types1...>(), types2, outputs, inputs);
}
template<typename T1, typename T2, typename ...Types2>
bool evaluate_pwl(const std::tuple<T2, Types2...>&,
ov::TensorVector& outputs,
const ov::TensorVector& inputs) const {
return inputs[1].get_element_type() == T1::value &&
inputs[0].get_element_type() == T2::value &&
evaluate<T1, T2>(outputs, inputs) ||
evaluate_pwl<T1>(std::tuple<Types2...>(), outputs, inputs);
}
template <typename T1, typename T2>
bool evaluate(ov::TensorVector& outputs,
const ov::TensorVector& inputs) const;
std::shared_ptr<ngraph::Node> m_base_node;
}; // class Pwl
} // namespace op
} // namespace intel_gna
} // namespace ov
|
/**************************************************************************/
/* */
/* WWIV Version 5.x */
/* Copyright (C)1998-2020, WWIV Software Services */
/* */
/* 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 "bbs/arword.h"
#include <string>
#include "core/strings.h"
using std::string;
using namespace wwiv::strings;
/*
* Returns bitmapped word representing an AR or DAR string.
*/
uint16_t str_to_arword(const std::string& arstr) {
uint16_t rar = 0;
auto s = ToStringUpperCase(arstr);
for (int i = 0; i < 16; i++) {
if (s.find(static_cast<char>(i + 'A')) != std::string::npos) {
rar |= (1 << i);
}
}
return rar;
}
/*
* Converts an int to a string representing those ARs (DARs).
* or '-' on an empty string.
*/
std::string word_to_arstr(int ar, const std::string& empty_ar_str) {
if (!ar) {
return empty_ar_str;
}
std::string arstr;
for (int i = 0; i < 16; i++) {
if ((1 << i) & ar) {
arstr.push_back(static_cast<char>('A' + i));
}
}
return (arstr.empty()) ? empty_ar_str : arstr;
}
|
// VirtualDub - Video processing and capture application
// Graphics support library
// Copyright (C) 1998-2009 Avery Lee
//
// This program is free software; you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation; either version 2 of the License, or
// (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with this program; if not, write to the Free Software
// Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
#include <stdafx.h>
#include <numeric>
#include "blt_spanutils_x86.h"
#include "resample_stages_x86.h"
#include <vd2/Kasumi/resample_kernels.h>
#ifdef _MSC_VER
#pragma warning(disable: 4799) // warning C4799: function 'vdasm_resize_table_row_8_k8_4x_MMX' has no EMMS instruction
#endif
///////////////////////////////////////////////////////////////////////////////
extern "C" void vdasm_resize_table_row_8_k8_4x_SSE41(void *dst, const void *src, uint32 width, const void *kernel);
extern "C" void vdasm_resize_table_row_8_k16_4x_SSE41(void *dst, const void *src, uint32 width, const void *kernel);
extern "C" void vdasm_resize_table_row_8_SSE41(void *dst, const void *src, uint32 width, const void *kernel, uint32 kwidth);
extern "C" void vdasm_resize_table_col_8_k2_SSE41(void *dst, const void *const *srcs, uint32 width, const void *kernel);
extern "C" void vdasm_resize_table_col_8_k4_SSE41(void *dst, const void *const *srcs, uint32 width, const void *kernel);
///////////////////////////////////////////////////////////////////////////////
namespace {
struct ScaleInfo {
void *dst;
uintptr src;
uint32 accum;
uint32 fracinc;
sint32 intinc;
uint32 count;
};
extern "C" void vdasm_resize_point32(const ScaleInfo *);
}
int VDResamplerSeparablePointRowStageX86::GetWindowSize() const {return 1;}
void VDResamplerSeparablePointRowStageX86::Process(void *dst, const void *src, uint32 w, uint32 u, uint32 dudx) {
ScaleInfo info;
info.dst = (uint32 *)dst + w;
info.src = ((uintptr)src >> 2) + (u>>16);
info.accum = u<<16;
info.fracinc = dudx << 16;
info.intinc = (sint32)dudx >> 16;
info.count = -(sint32)w*4;
vdasm_resize_point32(&info);
}
///////////////////////////////////////////////////////////////////////////////
void VDResamplerRowStageSeparableLinear8_phaseZeroStepHalf_ISSE::Process(void *dst0, const void *src0, uint32 w, uint32 u, uint32 dudx) {
uint8 *dst = (uint8 *)dst0;
const uint8 *src = (const uint8 *)src0;
nsVDPixmapSpanUtils::horiz_expand2x_coaligned_ISSE(dst, src, w);
}
///////////////////////////////////////////////////////////////////////////////
extern "C" void vdasm_resize_point32_MMX(const ScaleInfo *);
extern "C" void vdasm_resize_interp_row_run_MMX(void *dst, const void *src, uint32 width, sint64 xaccum, sint64 x_inc);
extern "C" void vdasm_resize_interp_col_run_MMX(void *dst, const void *src1, const void *src2, uint32 width, uint32 yaccum);
extern "C" void vdasm_resize_ccint_row_MMX(void *dst, const void *src, uint32 count, uint32 xaccum, sint32 xinc, const void *tbl);
extern "C" void vdasm_resize_ccint_col_MMX(void *dst, const void *src1, const void *src2, const void *src3, const void *src4, uint32 count, const void *tbl);
extern "C" long vdasm_resize_table_col_MMX(uint32 *out, const uint32 *const*in_table, const int *filter, int filter_width, uint32 w, long frac);
extern "C" long vdasm_resize_table_row_MMX(uint32 *out, const uint32 *in, const int *filter, int filter_width, uint32 w, long accum, long frac);
int VDResamplerSeparablePointRowStageMMX::GetWindowSize() const {return 1;}
void VDResamplerSeparablePointRowStageMMX::Process(void *dst, const void *src, uint32 w, uint32 u, uint32 dudx) {
ScaleInfo info;
info.dst = (uint32 *)dst + w;
info.src = ((uintptr)src >> 2) + (u>>16);
info.accum = u<<16;
info.fracinc = dudx << 16;
info.intinc = (sint32)dudx >> 16;
info.count = -(sint32)w*4;
vdasm_resize_point32_MMX(&info);
}
int VDResamplerSeparableLinearRowStageMMX::GetWindowSize() const {return 2;}
void VDResamplerSeparableLinearRowStageMMX::Process(void *dst0, const void *src0, uint32 w, uint32 u, uint32 dudx) {
vdasm_resize_interp_row_run_MMX(dst0, src0, w, (sint64)u << 16, (sint64)dudx << 16);
}
int VDResamplerSeparableLinearColStageMMX::GetWindowSize() const {return 2;}
void VDResamplerSeparableLinearColStageMMX::Process(void *dst0, const void *const *srcarray, uint32 w, sint32 phase) {
vdasm_resize_interp_col_run_MMX(dst0, srcarray[0], srcarray[1], w, phase);
}
VDResamplerSeparableCubicRowStageMMX::VDResamplerSeparableCubicRowStageMMX(double A)
: mFilterBank(1024)
{
sint32 *p = mFilterBank.data();
VDResamplerGenerateTable(p, VDResamplerCubicFilter(1.0, A));
VDResamplerSwizzleTable(p, 512);
}
int VDResamplerSeparableCubicRowStageMMX::GetWindowSize() const {return 4;}
void VDResamplerSeparableCubicRowStageMMX::Process(void *dst0, const void *src0, uint32 w, uint32 u, uint32 dudx) {
vdasm_resize_ccint_row_MMX(dst0, src0, w, u, dudx, mFilterBank.data());
}
VDResamplerSeparableCubicColStageMMX::VDResamplerSeparableCubicColStageMMX(double A)
: mFilterBank(1024)
{
sint32 *p = mFilterBank.data();
VDResamplerGenerateTable(p, VDResamplerCubicFilter(1.0, A));
VDResamplerSwizzleTable(p, 512);
}
int VDResamplerSeparableCubicColStageMMX::GetWindowSize() const {return 4;}
void VDResamplerSeparableCubicColStageMMX::Process(void *dst0, const void *const *srcarray, uint32 w, sint32 phase) {
vdasm_resize_ccint_col_MMX(dst0, srcarray[0], srcarray[1], srcarray[2], srcarray[3], w, mFilterBank.data() + ((phase>>6)&0x3fc));
}
VDResamplerSeparableTableRowStage8MMX::VDResamplerSeparableTableRowStage8MMX(const IVDResamplerFilter& filter)
: VDResamplerRowStageSeparableTable32(filter)
, mLastSrcWidth(0)
, mLastDstWidth(0)
, mLastU(0)
, mLastDUDX(0)
{
mAlignedKernelWidth = (GetWindowSize() + 6) & ~3;
mAlignedKernelSize = mAlignedKernelWidth + 4;
}
void VDResamplerSeparableTableRowStage8MMX::Init(const VDResamplerAxis& axis, uint32 srcw) {
uint32 w = axis.dx_preclip + axis.dx_active + axis.dx_postclip + axis.dx_dualclip;
if (mLastSrcWidth != srcw || mLastDstWidth != w || mLastU != axis.u || mLastDUDX != axis.dudx) {
mLastSrcWidth = srcw;
mLastDstWidth = w;
mLastU = axis.u;
mLastDUDX = axis.dudx;
RedoRowFilters(axis, w, srcw);
}
}
void VDResamplerSeparableTableRowStage8MMX::RedoRowFilters(const VDResamplerAxis& axis, uint32 w, uint32 srcw) {
int kstride = mFilterBank.size() >> 8;
int ksize = mAlignedKernelWidth;
int kesize = mAlignedKernelSize;
mRowKernels.clear();
mRowKernelSize = w * kesize;
mRowKernels.resize(mRowKernelSize * 4, 0);
for(int byteOffset = 0; byteOffset < 4; ++byteOffset) {
sint16 *dst = mRowKernels.data() + mRowKernelSize * byteOffset;
int ksizeThisOffset = std::min<int>(ksize, (byteOffset + srcw + 3) & ~3);
mKernelSizeByOffset[byteOffset] = ksizeThisOffset;
sint32 u = axis.u;
sint32 uoffmin = -byteOffset;
sint32 uoffmax = ((srcw + byteOffset + 3) & ~3) - byteOffset - ksizeThisOffset;
for(uint32 i=0; i<w; ++i) {
sint32 uoffset = u >> 16;
sint32 uoffset2 = ((uoffset + byteOffset) & ~3) - byteOffset;
if (uoffset2 < uoffmin)
uoffset2 = uoffmin;
if (uoffset2 > uoffmax)
uoffset2 = uoffmax;
VDASSERT(uoffset2 + ksizeThisOffset <= (((sint32)srcw + byteOffset + 3) & ~3));
*(sint32 *)dst = uoffset2;
dst += 2;
*dst++ = 0;
*dst++ = 0;
uint32 phase = (u >> 8) & 255;
const sint32 *src = &mFilterBank[kstride * phase];
sint32 start = 0;
sint32 end = kstride;
int dstoffset = uoffset - uoffset2;
// check for filter kernel overlapping left source boundary
if (uoffset < 0)
start = -uoffset;
// check for filter kernel overlapping right source boundary
if (uoffset + end > (sint32)srcw)
end = srcw - uoffset;
VDASSERT(dstoffset + start >= 0);
VDASSERT(dstoffset + end <= ksizeThisOffset);
sint16 *dst2 = dst + dstoffset;
dst += ksizeThisOffset;
for(int j=start; j<end; ++j)
dst2[j] = src[j];
if (start > 0)
dst2[start] = std::accumulate(src, src+start, dst2[start]);
if (end < kstride)
dst2[end - 1] = std::accumulate(src+end, src+kstride, dst2[end - 1]);
u += axis.dudx;
}
}
// swizzle rows where optimization is possible
vdfastvector<sint16> temp;
int quads = w >> 2;
int quadRemainder = w & 3;
for(int byteOffset = 0; byteOffset < 4; ++byteOffset) {
int ksizeThisOffset = mKernelSizeByOffset[byteOffset];
int kpairs = ksizeThisOffset >> 2;
if (ksizeThisOffset < 8 || ksizeThisOffset > 12) {
mbQuadOptimizationEnabled[byteOffset] = false;
} else {
ptrdiff_t unswizzledStride = (ksizeThisOffset >> 1) + 2;
mbQuadOptimizationEnabled[byteOffset] = true;
mTailOffset[byteOffset] = quads * (8 + ksizeThisOffset*4);
uint32 *dst = (uint32 *)&mRowKernels[mRowKernelSize * byteOffset];
temp.resize(mRowKernelSize);
memcpy(temp.data(), dst, mRowKernelSize*2);
const uint32 *src0 = (const uint32 *)temp.data();
const uint32 *src1 = src0 + unswizzledStride;
const uint32 *src2 = src1 + unswizzledStride;
const uint32 *src3 = src2 + unswizzledStride;
ptrdiff_t srcskip = unswizzledStride * 3;
for(int q = 0; q < quads; ++q) {
dst[0] = src0[0];
dst[1] = src1[0];
dst[2] = src2[0];
dst[3] = src3[0];
src0 += 2;
src1 += 2;
src2 += 2;
src3 += 2;
dst += 4;
for(int p = 0; p < kpairs; ++p) {
dst[0] = src0[0];
dst[1] = src0[1];
dst[2] = src1[0];
dst[3] = src1[1];
dst[4] = src2[0];
dst[5] = src2[1];
dst[6] = src3[0];
dst[7] = src3[1];
dst += 8;
src0 += 2;
src1 += 2;
src2 += 2;
src3 += 2;
}
src0 += srcskip;
src1 += srcskip;
src2 += srcskip;
src3 += srcskip;
}
memcpy(dst, src0, unswizzledStride * 4 * quadRemainder);
VDASSERT(dst + unswizzledStride * quadRemainder <= (void *)(mRowKernels.data() + (mRowKernelSize * (byteOffset + 1))));
}
}
}
void __declspec(naked) vdasm_resize_table_row_8_k8_4x_MMX(void *dst, const void *src, uint32 width, const void *kernel) {
static const __declspec(align(8)) __int64 kRound = 0x0000000000002000;
__asm {
push ebp
push edi
push esi
push ebx
pxor mm7, mm7
movq mm6, kRound
mov ebp, [esp + 4 + 16] ;ebp = dst
mov esi, [esp + 12 + 16] ;esi = width
mov edi, [esp + 16 + 16] ;edi = kernel
yloop:
;eax = temp
;ebx = temp
;ecx = temp
;edx = temp
;esi = horiz counter
;edi = filter list
;ebp = destination
mov eax, [edi+0]
mov ebx, [edi+4]
mov ecx, [edi+8]
mov edx, [esp+8+16]
add eax, edx
add ebx, edx
add ecx, edx
add edx, [edi+12]
movd mm0, [eax]
punpcklbw mm0, mm7
pmaddwd mm0, [edi+16]
movd mm1, [ebx]
punpcklbw mm1, mm7
pmaddwd mm1, [edi+24]
movd mm2, [ecx]
punpcklbw mm2, mm7
pmaddwd mm2, [edi+32]
movd mm3, [edx]
punpcklbw mm3, mm7
pmaddwd mm3, [edi+40]
movd mm4, [eax+4]
paddd mm0, mm6
movd mm5, [ebx+4]
punpcklbw mm4, mm7
paddd mm1, mm6
pmaddwd mm4, [edi+48]
punpcklbw mm5, mm7
paddd mm2, mm6
pmaddwd mm5, [edi+56]
paddd mm3, mm6
paddd mm0, mm4
paddd mm1, mm5
movd mm4, [ecx+4]
punpcklbw mm4, mm7
pmaddwd mm4, [edi+64]
movd mm5, [edx+4]
punpcklbw mm5, mm7
pmaddwd mm5, [edi+72]
paddd mm2, mm4
paddd mm3, mm5
movq mm4, mm0
punpckldq mm0, mm1
movq mm5, mm2
punpckldq mm2, mm3
punpckhdq mm4, mm1
punpckhdq mm5, mm3
paddd mm0, mm4
paddd mm2, mm5
psrad mm0, 14
psrad mm2, 14
packssdw mm0, mm2
packuswb mm0, mm0
add edi, 80
movd [ebp], mm0
add ebp, 4
sub esi, 1
jne yloop
pop ebx
pop esi
pop edi
pop ebp
ret
}
}
void __declspec(naked) vdasm_resize_table_row_8_k12_4x_MMX(void *dst, const void *src, uint32 width, const void *kernel) {
static const __declspec(align(8)) __int64 kRound = 0x0000200000002000;
__asm {
push ebp
push edi
push esi
push ebx
pxor mm7, mm7
movq mm6, kRound
mov ebp, [esp + 4 + 16] ;ebp = dst
mov esi, [esp + 12 + 16] ;esi = width
mov edi, [esp + 16 + 16] ;edi = kernel
yloop:
;eax = temp
;ebx = temp
;ecx = temp
;edx = temp
;esi = horiz counter
;edi = filter list
;ebp = destination
mov eax, [edi+0]
mov ebx, [edi+4]
mov ecx, [edi+8]
mov edx, [esp+8+16]
add eax, edx
add ebx, edx
add ecx, edx
add edx, [edi+12]
movd mm0, [eax]
punpcklbw mm0, mm7
pmaddwd mm0, [edi+16]
movd mm1, [ebx]
punpcklbw mm1, mm7
pmaddwd mm1, [edi+24]
movd mm2, [ecx]
punpcklbw mm2, mm7
pmaddwd mm2, [edi+32]
movd mm3, [edx]
punpcklbw mm3, mm7
pmaddwd mm3, [edi+40]
movd mm4, [eax+4]
punpcklbw mm4, mm7
pmaddwd mm4, [edi+48]
movd mm5, [ebx+4]
punpcklbw mm5, mm7
pmaddwd mm5, [edi+56]
paddd mm0, mm4
paddd mm1, mm5
movd mm4, [ecx+4]
punpcklbw mm4, mm7
movd mm5, [edx+4]
pmaddwd mm4, [edi+64]
punpcklbw mm5, mm7
paddd mm2, mm4
pmaddwd mm5, [edi+72]
movd mm4, [eax+8]
punpcklbw mm4, mm7
paddd mm3, mm5
movd mm5, [ebx+8]
punpcklbw mm5, mm7
pmaddwd mm4, [edi+80]
paddd mm0, mm4
movd mm4, [ecx+8]
pmaddwd mm5, [edi+88]
paddd mm1, mm5
punpcklbw mm4, mm7
pmaddwd mm4, [edi+96]
movd mm5, [edx+8]
punpcklbw mm5, mm7
pmaddwd mm5, [edi+104]
paddd mm2, mm4
paddd mm3, mm5
movq mm4, mm0
punpckldq mm0, mm1
movq mm5, mm2
punpckldq mm2, mm3
punpckhdq mm4, mm1
punpckhdq mm5, mm3
paddd mm0, mm4
paddd mm2, mm5
paddd mm0, mm6
paddd mm2, mm6
psrad mm0, 14
psrad mm2, 14
packssdw mm0, mm2
packuswb mm0, mm0
add edi, 112
movd [ebp], mm0
add ebp, 4
sub esi, 1
jne yloop
pop ebx
pop esi
pop edi
pop ebp
ret
}
}
void __declspec(naked) vdasm_resize_table_row_8_MMX(void *dst, const void *src, uint32 width, const void *kernel, uint32 kwidth) {
static const __declspec(align(8)) __int64 kRound = 0x0000000000002000;
__asm {
push ebp
push edi
push esi
push ebx
pxor mm7, mm7
movq mm6, kRound
mov edi, [esp + 4 + 16] ;edi = dst
mov ebx, [esp + 8 + 16] ;ebx = src
mov ebp, [esp + 12 + 16] ;ebp = width
mov edx, [esp + 16 + 16] ;edx = kernel
yloop:
;eax = temp
;ebx = source base address
;ecx = (temp) source
;edx = filter list
;esi = (temp) kernel width
;edi = destination
;ebp = horiz counter
mov eax, [edx]
add edx, 8
lea ecx, [ebx + eax]
mov esi, [esp + 20 + 16] ;esi = kernel width
movq mm2, mm6
xloop:
movd mm0, [ecx]
punpcklbw mm0, mm7
add ecx, 4
pmaddwd mm0, [edx]
paddd mm2, mm0
add edx, 8
sub esi, 4
jne xloop
punpckldq mm0, mm2
paddd mm0, mm2
psrad mm0, 14
psrlq mm0, 32
packssdw mm0, mm0
packuswb mm0, mm0
movd eax, mm0
mov [edi], al
add edi, 1
sub ebp, 1
jne yloop
pop ebx
pop esi
pop edi
pop ebp
ret
}
}
void VDResamplerSeparableTableRowStage8MMX::Process(void *dst, const void *src, uint32 w) {
int byteOffset = (int)(ptrdiff_t)src & 3;
const sint16 *ksrc = mRowKernels.data() + (mRowKernelSize * byteOffset);
#if 0
int kwidth = mAlignedKernelWidth;
uint8 *dst2 = (uint8 *)dst;
do {
int offset = ksrc[0];
ksrc += 4;
const uint8 *src2 = (const uint8 *)src + offset;
sint32 accum = 0x8000;
for(int i=0; i<kwidth; ++i) {
accum += (sint32)src2[i] * (*ksrc++);
}
accum >>= 14;
accum &= ~(accum >> 31);
accum |= (255 - accum) >> 31;
*dst2++ = (uint8)accum;
} while(--w);
#else
int ksize = mKernelSizeByOffset[byteOffset];
if (mbQuadOptimizationEnabled[byteOffset]) {
if (w >= 4) {
if (ksize == 12) {
vdasm_resize_table_row_8_k12_4x_MMX(dst, src, w >> 2, ksrc);
#if 0
int w4 = w >> 2;
uint8 *dst2 = (uint8 *)dst;
const uint8 *src2 = (const uint8 *)src;
const sint16 *ksrc2 = ksrc;
do {
int off0 = ksrc2[0];
int off1 = ksrc2[2];
int off2 = ksrc2[4];
int off3 = ksrc2[6];
const uint8 *d0 = src2 + off0;
const uint8 *d1 = src2 + off1;
const uint8 *d2 = src2 + off2;
const uint8 *d3 = src2 + off3;
int acc0 = 0;
int acc1 = 0;
int acc2 = 0;
int acc3 = 0;
acc0 += d0[ 0]*ksrc2[ 8]
+ d0[ 1]*ksrc2[ 9]
+ d0[ 2]*ksrc2[ 10]
+ d0[ 3]*ksrc2[ 11]
+ d0[ 4]*ksrc2[ 24]
+ d0[ 5]*ksrc2[ 25]
+ d0[ 6]*ksrc2[ 26]
+ d0[ 7]*ksrc2[ 27]
+ d0[ 8]*ksrc2[ 40]
+ d0[ 9]*ksrc2[ 41]
+ d0[10]*ksrc2[ 42]
+ d0[11]*ksrc2[ 43];
acc0 = (acc0 + 0x2000) >> 14;
if (acc0 < 0) acc0 = 0; else if (acc0 > 255) acc0 = 255;
acc1 += d1[ 0]*ksrc2[ 12]
+ d1[ 1]*ksrc2[ 13]
+ d1[ 2]*ksrc2[ 14]
+ d1[ 3]*ksrc2[ 15]
+ d1[ 4]*ksrc2[ 28]
+ d1[ 5]*ksrc2[ 29]
+ d1[ 6]*ksrc2[ 30]
+ d1[ 7]*ksrc2[ 31]
+ d1[ 8]*ksrc2[ 44]
+ d1[ 9]*ksrc2[ 45]
+ d1[10]*ksrc2[ 46]
+ d1[11]*ksrc2[ 47];
acc1 = (acc1 + 0x2000) >> 14;
if (acc1 < 0) acc1 = 0; else if (acc1 > 255) acc1 = 255;
acc2 += d2[ 0]*ksrc2[ 16]
+ d2[ 1]*ksrc2[ 17]
+ d2[ 2]*ksrc2[ 18]
+ d2[ 3]*ksrc2[ 19]
+ d2[ 4]*ksrc2[ 32]
+ d2[ 5]*ksrc2[ 33]
+ d2[ 6]*ksrc2[ 34]
+ d2[ 7]*ksrc2[ 35]
+ d2[ 8]*ksrc2[ 48]
+ d2[ 9]*ksrc2[ 49]
+ d2[10]*ksrc2[ 50]
+ d2[11]*ksrc2[ 51];
acc2 = (acc2 + 0x2000) >> 14;
if (acc2 < 0) acc2 = 0; else if (acc2 > 255) acc2 = 255;
acc3 += d3[ 0]*ksrc2[ 20]
+ d3[ 1]*ksrc2[ 21]
+ d3[ 2]*ksrc2[ 22]
+ d3[ 3]*ksrc2[ 23]
+ d3[ 4]*ksrc2[ 36]
+ d3[ 5]*ksrc2[ 37]
+ d3[ 6]*ksrc2[ 38]
+ d3[ 7]*ksrc2[ 39]
+ d3[ 8]*ksrc2[ 52]
+ d3[ 9]*ksrc2[ 53]
+ d3[10]*ksrc2[ 54]
+ d3[11]*ksrc2[ 55];
acc3 = (acc3 + 0x2000) >> 14;
if (acc3 < 0) acc3 = 0; else if (acc3 > 255) acc3 = 255;
ksrc2 += 56;
dst2[0] = (uint8)acc0;
dst2[1] = (uint8)acc1;
dst2[2] = (uint8)acc2;
dst2[3] = (uint8)acc3;
dst2 += 4;
} while(--w4);
#endif
} else
vdasm_resize_table_row_8_k8_4x_MMX(dst, src, w >> 2, ksrc);
}
if (w & 3)
vdasm_resize_table_row_8_MMX((char *)dst + (w & ~3), src, w & 3, ksrc + mTailOffset[byteOffset], ksize);
} else if (w) {
vdasm_resize_table_row_8_MMX(dst, src, w, ksrc, ksize);
}
#endif
}
void VDResamplerSeparableTableRowStage8MMX::Process(void *dst, const void *src, uint32 w, uint32 u, uint32 dudx) {
vdasm_resize_table_row_MMX((uint32 *)dst, (const uint32 *)src, (const int *)mFilterBank.data(), (int)mFilterBank.size() >> 8, w, u, dudx);
}
VDResamplerSeparableTableRowStageMMX::VDResamplerSeparableTableRowStageMMX(const IVDResamplerFilter& filter)
: VDResamplerRowStageSeparableTable32(filter)
{
VDResamplerSwizzleTable(mFilterBank.data(), (unsigned)mFilterBank.size() >> 1);
}
void VDResamplerSeparableTableRowStageMMX::Process(void *dst, const void *src, uint32 w, uint32 u, uint32 dudx) {
vdasm_resize_table_row_MMX((uint32 *)dst, (const uint32 *)src, (const int *)mFilterBank.data(), (int)mFilterBank.size() >> 8, w, u, dudx);
}
///////////////////////////////////////////////////////////////////////////
VDResamplerSeparableTableColStage8MMX::VDResamplerSeparableTableColStage8MMX(const IVDResamplerFilter& filter)
: VDResamplerColStageSeparableTable8(filter)
{
VDResamplerSwizzleTable(mFilterBank.data(), (unsigned)mFilterBank.size() >> 1);
}
void __declspec(naked) vdasm_resize_table_col_8_k2_MMX(void *dst, const void *const *srcs, uint32 width, const void *kernel) {
static const __declspec(align(8)) __int64 kRound = 0x0000200000002000;
__asm {
push ebp
push edi
push esi
push ebx
pxor mm7, mm7
movq mm6, kRound
mov esi, [esp + 4 + 16] ;esi = dst
mov edi, [esp + 16 + 16] ;edi = kernel
mov ebp, [esp + 12 + 16] ;ebp = width
movq mm5, [edi]
mov edx, [esp + 8 + 16] ;ebx = srcs
mov eax, [edx+0]
mov ebx, [edx+4]
add eax, ebp
add ebx, ebp
neg ebp
yloop:
;eax = row0
;ebx = row1
;ecx =
;edx =
;edi = kernel
;esi = dest
;ebp = width counter
movd mm0, [eax+ebp]
punpcklbw mm0, mm7
movd mm2, [ebx+ebp]
punpcklbw mm2, mm7
movq mm1, mm0
punpcklwd mm0, mm2
punpckhwd mm1, mm2
pmaddwd mm0, mm5
pmaddwd mm1, mm5
paddd mm0, mm6
paddd mm1, mm6
psrad mm0, 14
psrad mm1, 14
packssdw mm0, mm1
packuswb mm0, mm0
movd [esi], mm0
add esi, 4
add ebp, 4
jne yloop
pop ebx
pop esi
pop edi
pop ebp
ret
}
}
void __declspec(naked) vdasm_resize_table_col_8_k4_MMX(void *dst, const void *const *srcs, uint32 width, const void *kernel) {
static const __declspec(align(8)) __int64 kRound = 0x0000200000002000;
__asm {
push ebp
push edi
push esi
push ebx
pxor mm7, mm7
movq mm6, kRound
mov esi, [esp + 4 + 16] ;esi = dst
mov edi, [esp + 16 + 16] ;edi = kernel
xor ebp, ebp
mov edx, [esp + 8 + 16] ;ebx = srcs
mov eax, [edx+0]
mov ebx, [edx+4]
mov ecx, [edx+8]
mov edx, [edx+12]
yloop:
;eax = row0
;ebx = row1
;ecx = row2
;edx = row3
;edi = kernel
;esi = dest
;ebp = width counter
movd mm0, [eax+ebp]
punpcklbw mm0, mm7
movd mm2, [ebx+ebp]
punpcklbw mm2, mm7
movq mm1, mm0
punpcklwd mm0, mm2
movq mm5, [edi]
punpckhwd mm1, mm2
pmaddwd mm0, mm5
pmaddwd mm1, mm5
paddd mm0, mm6
paddd mm1, mm6
movd mm3, [ecx+ebp]
punpcklbw mm3, mm7
movd mm2, [edx+ebp]
punpcklbw mm2, mm7
movq mm4, mm3
punpcklwd mm3, mm2
movq mm5, [edi+8]
punpckhwd mm4, mm2
pmaddwd mm3, mm5
pmaddwd mm4, mm5
paddd mm0, mm3
paddd mm1, mm4
psrad mm0, 14
psrad mm1, 14
packssdw mm0, mm1
packuswb mm0, mm0
add ebp, 4
movd [esi], mm0
add esi, 4
cmp ebp, [esp + 12 + 16]
jb yloop
pop ebx
pop esi
pop edi
pop ebp
ret
}
}
void __declspec(naked) vdasm_resize_table_col_8_MMX(void *dst, const void *const *srcs, uint32 width, const void *kernel, uint32 kwidth) {
static const __declspec(align(8)) __int64 kRound = 0x0000200000002000;
__asm {
push ebp
push edi
push esi
push ebx
pxor mm7, mm7
movq mm6, kRound
mov edi, [esp + 4 + 16] ;edi = dst
xor ebp, ebp
yloop:
mov edx, [esp + 16 + 16] ;edx = kernel
mov ebx, [esp + 8 + 16] ;ebx = srcs
mov esi, [esp + 20 + 16] ;esi = kwidth
movq mm3, mm6
movq mm4, mm6
xloop:
mov ecx, [ebx]
movd mm0, [ecx+ebp]
punpcklbw mm0, mm7
mov ecx, [ebx+4]
movd mm2, [ecx+ebp]
punpcklbw mm2, mm7
movq mm1, mm0
punpcklwd mm0, mm2
punpckhwd mm1, mm2
movq mm5, [edx]
pmaddwd mm0, mm5
pmaddwd mm1, mm5
paddd mm3, mm0
paddd mm4, mm1
add ebx, 8
add edx, 8
sub esi, 2
jne xloop
psrad mm3, 14
psrad mm4, 14
packssdw mm3, mm4
packuswb mm3, mm3
movd [edi], mm3
add edi, 4
add ebp, 4
cmp ebp, [esp + 12 + 16]
jb yloop
pop ebx
pop esi
pop edi
pop ebp
ret
}
}
void VDResamplerSeparableTableColStage8MMX::Process(void *dst0, const void *const *src0, uint32 w, sint32 phase) {
uint8 *dst = (uint8 *)dst0;
const uint8 *const *src = (const uint8 *const *)src0;
const unsigned ksize = (unsigned)mFilterBank.size() >> 8;
const sint16 *filter = (const sint16 *)&mFilterBank[((phase>>8)&0xff) * ksize];
int w4 = w & ~3;
if (w4) {
switch(ksize) {
case 2:
vdasm_resize_table_col_8_k2_MMX(dst, (const void *const *)src, w4, filter);
break;
case 4:
vdasm_resize_table_col_8_k4_MMX(dst, (const void *const *)src, w4, filter);
break;
default:
vdasm_resize_table_col_8_MMX(dst, (const void *const *)src, w4, filter, ksize);
break;
}
}
for(uint32 i=w4; i<w; ++i) {
int b = 0x2000;
const sint16 *filter2 = filter;
const uint8 *const *src2 = src;
for(unsigned j = ksize; j; j -= 2) {
sint32 p0 = (*src2++)[i];
sint32 p1 = (*src2++)[i];
sint32 coeff0 = filter2[0];
sint32 coeff1 = filter2[1];
filter2 += 4;
b += p0*coeff0;
b += p1*coeff1;
}
b >>= 14;
if ((uint32)b >= 0x00000100)
b = ~b >> 31;
dst[i] = (uint8)b;
}
}
///////////////////////////////////////////////////////////////////////////
VDResamplerSeparableTableColStageMMX::VDResamplerSeparableTableColStageMMX(const IVDResamplerFilter& filter)
: VDResamplerColStageSeparableTable32(filter)
{
VDResamplerSwizzleTable(mFilterBank.data(), (unsigned)mFilterBank.size() >> 1);
}
void VDResamplerSeparableTableColStageMMX::Process(void *dst, const void *const *src, uint32 w, sint32 phase) {
vdasm_resize_table_col_MMX((uint32*)dst, (const uint32 *const *)src, (const int *)mFilterBank.data(), (int)mFilterBank.size() >> 8, w, (phase >> 8) & 0xff);
}
///////////////////////////////////////////////////////////////////////////
//
// resampler stages (SSE2, x86)
//
///////////////////////////////////////////////////////////////////////////
extern "C" long vdasm_resize_table_col_SSE2(uint32 *out, const uint32 *const*in_table, const int *filter, int filter_width, uint32 w, long frac);
extern "C" long vdasm_resize_table_row_SSE2(uint32 *out, const uint32 *in, const int *filter, int filter_width, uint32 w, long accum, long frac);
extern "C" void vdasm_resize_ccint_col_SSE2(void *dst, const void *src1, const void *src2, const void *src3, const void *src4, uint32 count, const void *tbl);
VDResamplerSeparableCubicColStageSSE2::VDResamplerSeparableCubicColStageSSE2(double A)
: VDResamplerSeparableCubicColStageMMX(A)
{
}
void VDResamplerSeparableCubicColStageSSE2::Process(void *dst0, const void *const *srcarray, uint32 w, sint32 phase) {
vdasm_resize_ccint_col_SSE2(dst0, srcarray[0], srcarray[1], srcarray[2], srcarray[3], w, mFilterBank.data() + ((phase>>6)&0x3fc));
}
VDResamplerSeparableTableRowStageSSE2::VDResamplerSeparableTableRowStageSSE2(const IVDResamplerFilter& filter)
: VDResamplerSeparableTableRowStageMMX(filter)
{
}
void VDResamplerSeparableTableRowStageSSE2::Process(void *dst, const void *src, uint32 w, uint32 u, uint32 dudx) {
vdasm_resize_table_row_MMX((uint32 *)dst, (const uint32 *)src, (const int *)mFilterBank.data(), (int)mFilterBank.size() >> 8, w, u, dudx);
}
VDResamplerSeparableTableColStageSSE2::VDResamplerSeparableTableColStageSSE2(const IVDResamplerFilter& filter)
: VDResamplerSeparableTableColStageMMX(filter)
{
}
void VDResamplerSeparableTableColStageSSE2::Process(void *dst, const void *const *src, uint32 w, sint32 phase) {
vdasm_resize_table_col_SSE2((uint32*)dst, (const uint32 *const *)src, (const int *)mFilterBank.data(), (int)mFilterBank.size() >> 8, w, (phase >> 8) & 0xff);
}
///////////////////////////////////////////////////////////////////////////
//
// resampler stages (SSE4.1, x86)
//
///////////////////////////////////////////////////////////////////////////
VDResamplerSeparableTableRowStage8SSE41::VDResamplerSeparableTableRowStage8SSE41(const IVDResamplerFilter& filter)
: VDResamplerRowStageSeparableTable32(filter)
, mLastSrcWidth(0)
, mLastDstWidth(0)
, mLastU(0)
, mLastDUDX(0)
{
mAlignedKernelWidth = (GetWindowSize() + 15) & ~7;
mAlignedKernelSize = mAlignedKernelWidth + 16;
}
void VDResamplerSeparableTableRowStage8SSE41::Init(const VDResamplerAxis& axis, uint32 srcw) {
uint32 w = axis.dx_preclip + axis.dx_active + axis.dx_postclip + axis.dx_dualclip;
if (mLastSrcWidth != srcw || mLastDstWidth != w || mLastU != axis.u || mLastDUDX != axis.dudx) {
mLastSrcWidth = srcw;
mLastDstWidth = w;
mLastU = axis.u;
mLastDUDX = axis.dudx;
RedoRowFilters(axis, w, srcw);
}
}
void VDResamplerSeparableTableRowStage8SSE41::RedoRowFilters(const VDResamplerAxis& axis, uint32 w, uint32 srcw) {
int kstride = mFilterBank.size() >> 8;
int ksize = mAlignedKernelWidth;
int kesize = mAlignedKernelSize;
mRowKernels.clear();
mRowKernelSize = w * kesize;
mRowKernels.resize(mRowKernelSize * 8, 0);
for(int byteOffset = 0; byteOffset < 8; ++byteOffset) {
sint16 *dst = mRowKernels.data() + mRowKernelSize * byteOffset;
int ksizeThisOffset = std::min<int>(ksize, (byteOffset + srcw + 7) & ~7);
mKernelSizeByOffset[byteOffset] = ksizeThisOffset;
sint32 u = axis.u;
sint32 uoffmin = -byteOffset;
sint32 uoffmax = ((srcw + byteOffset + 7) & ~7) - byteOffset - ksizeThisOffset;
for(uint32 i=0; i<w; ++i) {
sint32 uoffset = u >> 16;
sint32 uoffset2 = ((uoffset + byteOffset) & ~7) - byteOffset;
if (uoffset2 < uoffmin)
uoffset2 = uoffmin;
if (uoffset2 > uoffmax)
uoffset2 = uoffmax;
*(sint32 *)dst = uoffset2;
dst += 2;
*dst++ = 0;
*dst++ = 0;
*dst++ = 0;
*dst++ = 0;
*dst++ = 0;
*dst++ = 0;
uint32 phase = (u >> 8) & 255;
const sint32 *src = &mFilterBank[kstride * phase];
sint32 start = 0;
sint32 end = kstride;
int dstoffset = uoffset - uoffset2;
// check for filter kernel overlapping left source boundary
if (uoffset < 0)
start = -uoffset;
// check for filter kernel overlapping right source boundary
if (uoffset + end > (sint32)srcw)
end = srcw - uoffset;
VDASSERT(dstoffset + start >= 0);
VDASSERT(dstoffset + end <= ksizeThisOffset);
sint16 *dst2 = dst + dstoffset;
dst += ksizeThisOffset;
for(int j=start; j<end; ++j)
dst2[j] = src[j];
if (start > 0)
dst2[start] = std::accumulate(src, src+start, dst2[start]);
if (end < kstride)
dst2[end - 1] = std::accumulate(src+end, src+kstride, dst2[end - 1]);
u += axis.dudx;
}
}
// swizzle rows where optimization is possible
vdfastvector<sint16> temp;
int quads = w >> 2;
int quadRemainder = w & 3;
for(int byteOffset = 0; byteOffset < 8; ++byteOffset) {
int ksizeThisOffset = mKernelSizeByOffset[byteOffset];
int kpairs = ksizeThisOffset >> 3;
if (ksizeThisOffset < 8 || ksizeThisOffset > 16) {
mbQuadOptimizationEnabled[byteOffset] = false;
} else {
ptrdiff_t unswizzledStride = (ksizeThisOffset >> 1) + 4;
mbQuadOptimizationEnabled[byteOffset] = true;
mTailOffset[byteOffset] = quads * (8 + ksizeThisOffset*4);
uint32 *dst = (uint32 *)&mRowKernels[mRowKernelSize * byteOffset];
temp.resize(mRowKernelSize);
memcpy(temp.data(), dst, mRowKernelSize*2);
const uint32 *src0 = (const uint32 *)temp.data();
const uint32 *src1 = src0 + unswizzledStride;
const uint32 *src2 = src1 + unswizzledStride;
const uint32 *src3 = src2 + unswizzledStride;
ptrdiff_t srcskip = unswizzledStride * 3;
for(int q = 0; q < quads; ++q) {
dst[0] = src0[0];
dst[1] = src1[0];
dst[2] = src2[0];
dst[3] = src3[0];
src0 += 4;
src1 += 4;
src2 += 4;
src3 += 4;
dst += 4;
for(int p = 0; p < kpairs; ++p) {
dst[ 0] = src0[0];
dst[ 1] = src0[1];
dst[ 2] = src0[2];
dst[ 3] = src0[3];
dst[ 4] = src1[0];
dst[ 5] = src1[1];
dst[ 6] = src1[2];
dst[ 7] = src1[3];
dst[ 8] = src2[0];
dst[ 9] = src2[1];
dst[10] = src2[2];
dst[11] = src2[3];
dst[12] = src3[0];
dst[13] = src3[1];
dst[14] = src3[2];
dst[15] = src3[3];
dst += 16;
src0 += 4;
src1 += 4;
src2 += 4;
src3 += 4;
}
src0 += srcskip;
src1 += srcskip;
src2 += srcskip;
src3 += srcskip;
}
memcpy(dst, src0, unswizzledStride * 4 * quadRemainder);
}
}
}
void VDResamplerSeparableTableRowStage8SSE41::Process(void *dst, const void *src, uint32 w) {
int byteOffset = (int)(ptrdiff_t)src & 7;
const sint16 *ksrc = mRowKernels.data() + (mRowKernelSize * byteOffset);
int ksize = mKernelSizeByOffset[byteOffset];
if (mbQuadOptimizationEnabled[byteOffset]) {
if (w >= 4) {
if (ksize == 16)
vdasm_resize_table_row_8_k16_4x_SSE41(dst, src, w >> 2, ksrc);
else
vdasm_resize_table_row_8_k8_4x_SSE41(dst, src, w >> 2, ksrc);
}
if (w & 3)
vdasm_resize_table_row_8_SSE41((char *)dst + (w & ~3), src, w & 3, ksrc + mTailOffset[byteOffset], ksize);
} else if (w) {
vdasm_resize_table_row_8_SSE41(dst, src, w, ksrc, ksize);
}
}
void VDResamplerSeparableTableRowStage8SSE41::Process(void *dst, const void *src, uint32 w, uint32 u, uint32 dudx) {
vdasm_resize_table_row_MMX((uint32 *)dst, (const uint32 *)src, (const int *)mFilterBank.data(), (int)mFilterBank.size() >> 8, w, u, dudx);
}
///////////////////////////////////////////////////////////////////////////
VDResamplerSeparableTableColStage8SSE41::VDResamplerSeparableTableColStage8SSE41(const IVDResamplerFilter& filter)
: VDResamplerColStageSeparableTable8(filter)
{
VDResamplerSwizzleTable(mFilterBank.data(), (unsigned)mFilterBank.size() >> 1);
}
void VDResamplerSeparableTableColStage8SSE41::Process(void *dst0, const void *const *src0, uint32 w, sint32 phase) {
uint8 *dst = (uint8 *)dst0;
const uint8 *const *src = (const uint8 *const *)src0;
const unsigned ksize = (unsigned)mFilterBank.size() >> 8;
const sint16 *filter = (const sint16 *)&mFilterBank[((phase>>8)&0xff) * ksize];
int w4 = w & ~3;
if (w4) {
switch(ksize) {
case 2:
vdasm_resize_table_col_8_k2_SSE41(dst, (const void *const *)src, w4, filter);
break;
case 4:
vdasm_resize_table_col_8_k4_SSE41(dst, (const void *const *)src, w4, filter);
break;
default:
vdasm_resize_table_col_8_MMX(dst, (const void *const *)src, w4, filter, ksize);
break;
}
}
for(uint32 i=w4; i<w; ++i) {
int b = 0x2000;
const sint16 *filter2 = filter;
const uint8 *const *src2 = src;
for(unsigned j = ksize; j; j -= 2) {
sint32 p0 = (*src2++)[i];
sint32 p1 = (*src2++)[i];
sint32 coeff0 = filter2[0];
sint32 coeff1 = filter2[1];
filter2 += 4;
b += p0*coeff0;
b += p1*coeff1;
}
b >>= 14;
if ((uint32)b >= 0x00000100)
b = ~b >> 31;
dst[i] = (uint8)b;
}
}
|
// Copyright (c) 2012 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "net/dns/mock_host_resolver.h"
#include <string>
#include <vector>
#include "base/bind.h"
#include "base/memory/ref_counted.h"
#include "base/message_loop/message_loop.h"
#include "base/stl_util.h"
#include "base/strings/string_split.h"
#include "base/strings/string_util.h"
#include "base/threading/platform_thread.h"
#include "net/base/net_errors.h"
#include "net/base/net_util.h"
#include "net/base/test_completion_callback.h"
#include "net/dns/host_cache.h"
#if defined(OS_WIN)
#include "net/base/winsock_init.h"
#endif
namespace net {
namespace {
// Cache size for the MockCachingHostResolver.
const unsigned kMaxCacheEntries = 100;
// TTL for the successful resolutions. Failures are not cached.
const unsigned kCacheEntryTTLSeconds = 60;
} // namespace
int ParseAddressList(const std::string& host_list,
const std::string& canonical_name,
AddressList* addrlist) {
*addrlist = AddressList();
std::vector<std::string> addresses;
base::SplitString(host_list, ',', &addresses);
addrlist->set_canonical_name(canonical_name);
for (size_t index = 0; index < addresses.size(); ++index) {
IPAddressNumber ip_number;
if (!ParseIPLiteralToNumber(addresses[index], &ip_number)) {
LOG(WARNING) << "Not a supported IP literal: " << addresses[index];
return ERR_UNEXPECTED;
}
addrlist->push_back(IPEndPoint(ip_number, -1));
}
return OK;
}
struct MockHostResolverBase::Request {
Request(const RequestInfo& req_info,
AddressList* addr,
const CompletionCallback& cb)
: info(req_info), addresses(addr), callback(cb) {}
RequestInfo info;
AddressList* addresses;
CompletionCallback callback;
};
MockHostResolverBase::~MockHostResolverBase() {
STLDeleteValues(&requests_);
}
int MockHostResolverBase::Resolve(const RequestInfo& info,
RequestPriority priority,
AddressList* addresses,
const CompletionCallback& callback,
RequestHandle* handle,
const BoundNetLog& net_log) {
DCHECK(CalledOnValidThread());
last_request_priority_ = priority;
num_resolve_++;
size_t id = next_request_id_++;
int rv = ResolveFromIPLiteralOrCache(info, addresses);
if (rv != ERR_DNS_CACHE_MISS) {
return rv;
}
if (synchronous_mode_) {
return ResolveProc(id, info, addresses);
}
// Store the request for asynchronous resolution
Request* req = new Request(info, addresses, callback);
requests_[id] = req;
if (handle)
*handle = reinterpret_cast<RequestHandle>(id);
if (!ondemand_mode_) {
base::MessageLoop::current()->PostTask(
FROM_HERE,
base::Bind(&MockHostResolverBase::ResolveNow, AsWeakPtr(), id));
}
return ERR_IO_PENDING;
}
int MockHostResolverBase::ResolveFromCache(const RequestInfo& info,
AddressList* addresses,
const BoundNetLog& net_log) {
num_resolve_from_cache_++;
DCHECK(CalledOnValidThread());
next_request_id_++;
int rv = ResolveFromIPLiteralOrCache(info, addresses);
return rv;
}
void MockHostResolverBase::CancelRequest(RequestHandle handle) {
DCHECK(CalledOnValidThread());
size_t id = reinterpret_cast<size_t>(handle);
RequestMap::iterator it = requests_.find(id);
if (it != requests_.end()) {
scoped_ptr<Request> req(it->second);
requests_.erase(it);
} else {
NOTREACHED() << "CancelRequest must NOT be called after request is "
"complete or canceled.";
}
}
HostCache* MockHostResolverBase::GetHostCache() {
return cache_.get();
}
void MockHostResolverBase::ResolveAllPending() {
DCHECK(CalledOnValidThread());
DCHECK(ondemand_mode_);
for (RequestMap::iterator i = requests_.begin(); i != requests_.end(); ++i) {
base::MessageLoop::current()->PostTask(
FROM_HERE,
base::Bind(&MockHostResolverBase::ResolveNow, AsWeakPtr(), i->first));
}
}
// start id from 1 to distinguish from NULL RequestHandle
MockHostResolverBase::MockHostResolverBase(bool use_caching)
: last_request_priority_(DEFAULT_PRIORITY),
synchronous_mode_(false),
ondemand_mode_(false),
next_request_id_(1),
num_resolve_(0),
num_resolve_from_cache_(0) {
rules_ = CreateCatchAllHostResolverProc();
if (use_caching) {
cache_.reset(new HostCache(kMaxCacheEntries));
}
}
int MockHostResolverBase::ResolveFromIPLiteralOrCache(const RequestInfo& info,
AddressList* addresses) {
IPAddressNumber ip;
if (ParseIPLiteralToNumber(info.hostname(), &ip)) {
*addresses = AddressList::CreateFromIPAddress(ip, info.port());
if (info.host_resolver_flags() & HOST_RESOLVER_CANONNAME)
addresses->SetDefaultCanonicalName();
return OK;
}
int rv = ERR_DNS_CACHE_MISS;
if (cache_.get() && info.allow_cached_response()) {
HostCache::Key key(info.hostname(),
info.address_family(),
info.host_resolver_flags());
const HostCache::Entry* entry = cache_->Lookup(key, base::TimeTicks::Now());
if (entry) {
rv = entry->error;
if (rv == OK)
*addresses = AddressList::CopyWithPort(entry->addrlist, info.port());
}
}
return rv;
}
int MockHostResolverBase::ResolveProc(size_t id,
const RequestInfo& info,
AddressList* addresses) {
AddressList addr;
int rv = rules_->Resolve(info.hostname(),
info.address_family(),
info.host_resolver_flags(),
&addr,
NULL);
if (cache_.get()) {
HostCache::Key key(info.hostname(),
info.address_family(),
info.host_resolver_flags());
// Storing a failure with TTL 0 so that it overwrites previous value.
base::TimeDelta ttl;
if (rv == OK)
ttl = base::TimeDelta::FromSeconds(kCacheEntryTTLSeconds);
cache_->Set(key, HostCache::Entry(rv, addr), base::TimeTicks::Now(), ttl);
}
if (rv == OK)
*addresses = AddressList::CopyWithPort(addr, info.port());
return rv;
}
void MockHostResolverBase::ResolveNow(size_t id) {
RequestMap::iterator it = requests_.find(id);
if (it == requests_.end())
return; // was canceled
scoped_ptr<Request> req(it->second);
requests_.erase(it);
int rv = ResolveProc(id, req->info, req->addresses);
if (!req->callback.is_null())
req->callback.Run(rv);
}
//-----------------------------------------------------------------------------
struct RuleBasedHostResolverProc::Rule {
enum ResolverType {
kResolverTypeFail,
kResolverTypeSystem,
kResolverTypeIPLiteral,
};
ResolverType resolver_type;
std::string host_pattern;
AddressFamily address_family;
HostResolverFlags host_resolver_flags;
std::string replacement;
std::string canonical_name;
int latency_ms; // In milliseconds.
Rule(ResolverType resolver_type,
const std::string& host_pattern,
AddressFamily address_family,
HostResolverFlags host_resolver_flags,
const std::string& replacement,
const std::string& canonical_name,
int latency_ms)
: resolver_type(resolver_type),
host_pattern(host_pattern),
address_family(address_family),
host_resolver_flags(host_resolver_flags),
replacement(replacement),
canonical_name(canonical_name),
latency_ms(latency_ms) {}
};
RuleBasedHostResolverProc::RuleBasedHostResolverProc(HostResolverProc* previous)
: HostResolverProc(previous) {
}
void RuleBasedHostResolverProc::AddRule(const std::string& host_pattern,
const std::string& replacement) {
AddRuleForAddressFamily(host_pattern, ADDRESS_FAMILY_UNSPECIFIED,
replacement);
}
void RuleBasedHostResolverProc::AddRuleForAddressFamily(
const std::string& host_pattern,
AddressFamily address_family,
const std::string& replacement) {
DCHECK(!replacement.empty());
HostResolverFlags flags = HOST_RESOLVER_LOOPBACK_ONLY |
HOST_RESOLVER_DEFAULT_FAMILY_SET_DUE_TO_NO_IPV6;
Rule rule(Rule::kResolverTypeSystem,
host_pattern,
address_family,
flags,
replacement,
std::string(),
0);
rules_.push_back(rule);
}
void RuleBasedHostResolverProc::AddIPLiteralRule(
const std::string& host_pattern,
const std::string& ip_literal,
const std::string& canonical_name) {
// Literals are always resolved to themselves by HostResolverImpl,
// consequently we do not support remapping them.
IPAddressNumber ip_number;
DCHECK(!ParseIPLiteralToNumber(host_pattern, &ip_number));
HostResolverFlags flags = HOST_RESOLVER_LOOPBACK_ONLY |
HOST_RESOLVER_DEFAULT_FAMILY_SET_DUE_TO_NO_IPV6;
if (!canonical_name.empty())
flags |= HOST_RESOLVER_CANONNAME;
Rule rule(Rule::kResolverTypeIPLiteral, host_pattern,
ADDRESS_FAMILY_UNSPECIFIED, flags, ip_literal, canonical_name,
0);
rules_.push_back(rule);
}
void RuleBasedHostResolverProc::AddRuleWithLatency(
const std::string& host_pattern,
const std::string& replacement,
int latency_ms) {
DCHECK(!replacement.empty());
HostResolverFlags flags = HOST_RESOLVER_LOOPBACK_ONLY |
HOST_RESOLVER_DEFAULT_FAMILY_SET_DUE_TO_NO_IPV6;
Rule rule(Rule::kResolverTypeSystem,
host_pattern,
ADDRESS_FAMILY_UNSPECIFIED,
flags,
replacement,
std::string(),
latency_ms);
rules_.push_back(rule);
}
void RuleBasedHostResolverProc::AllowDirectLookup(
const std::string& host_pattern) {
HostResolverFlags flags = HOST_RESOLVER_LOOPBACK_ONLY |
HOST_RESOLVER_DEFAULT_FAMILY_SET_DUE_TO_NO_IPV6;
Rule rule(Rule::kResolverTypeSystem,
host_pattern,
ADDRESS_FAMILY_UNSPECIFIED,
flags,
std::string(),
std::string(),
0);
rules_.push_back(rule);
}
void RuleBasedHostResolverProc::AddSimulatedFailure(
const std::string& host_pattern) {
HostResolverFlags flags = HOST_RESOLVER_LOOPBACK_ONLY |
HOST_RESOLVER_DEFAULT_FAMILY_SET_DUE_TO_NO_IPV6;
Rule rule(Rule::kResolverTypeFail,
host_pattern,
ADDRESS_FAMILY_UNSPECIFIED,
flags,
std::string(),
std::string(),
0);
rules_.push_back(rule);
}
void RuleBasedHostResolverProc::ClearRules() {
rules_.clear();
}
int RuleBasedHostResolverProc::Resolve(const std::string& host,
AddressFamily address_family,
HostResolverFlags host_resolver_flags,
AddressList* addrlist,
int* os_error) {
RuleList::iterator r;
for (r = rules_.begin(); r != rules_.end(); ++r) {
bool matches_address_family =
r->address_family == ADDRESS_FAMILY_UNSPECIFIED ||
r->address_family == address_family;
// Ignore HOST_RESOLVER_SYSTEM_ONLY, since it should have no impact on
// whether a rule matches.
HostResolverFlags flags = host_resolver_flags & ~HOST_RESOLVER_SYSTEM_ONLY;
// Flags match if all of the bitflags in host_resolver_flags are enabled
// in the rule's host_resolver_flags. However, the rule may have additional
// flags specified, in which case the flags should still be considered a
// match.
bool matches_flags = (r->host_resolver_flags & flags) == flags;
if (matches_flags && matches_address_family &&
MatchPattern(host, r->host_pattern)) {
if (r->latency_ms != 0) {
base::PlatformThread::Sleep(
base::TimeDelta::FromMilliseconds(r->latency_ms));
}
// Remap to a new host.
const std::string& effective_host =
r->replacement.empty() ? host : r->replacement;
// Apply the resolving function to the remapped hostname.
switch (r->resolver_type) {
case Rule::kResolverTypeFail:
return ERR_NAME_NOT_RESOLVED;
case Rule::kResolverTypeSystem:
#if defined(OS_WIN)
net::EnsureWinsockInit();
#endif
return SystemHostResolverCall(effective_host,
address_family,
host_resolver_flags,
addrlist, os_error);
case Rule::kResolverTypeIPLiteral:
return ParseAddressList(effective_host,
r->canonical_name,
addrlist);
default:
NOTREACHED();
return ERR_UNEXPECTED;
}
}
}
return ResolveUsingPrevious(host, address_family,
host_resolver_flags, addrlist, os_error);
}
RuleBasedHostResolverProc::~RuleBasedHostResolverProc() {
}
RuleBasedHostResolverProc* CreateCatchAllHostResolverProc() {
RuleBasedHostResolverProc* catchall = new RuleBasedHostResolverProc(NULL);
catchall->AddIPLiteralRule("*", "127.0.0.1", "localhost");
// Next add a rules-based layer the use controls.
return new RuleBasedHostResolverProc(catchall);
}
//-----------------------------------------------------------------------------
int HangingHostResolver::Resolve(const RequestInfo& info,
RequestPriority priority,
AddressList* addresses,
const CompletionCallback& callback,
RequestHandle* out_req,
const BoundNetLog& net_log) {
return ERR_IO_PENDING;
}
int HangingHostResolver::ResolveFromCache(const RequestInfo& info,
AddressList* addresses,
const BoundNetLog& net_log) {
return ERR_DNS_CACHE_MISS;
}
//-----------------------------------------------------------------------------
ScopedDefaultHostResolverProc::ScopedDefaultHostResolverProc() {}
ScopedDefaultHostResolverProc::ScopedDefaultHostResolverProc(
HostResolverProc* proc) {
Init(proc);
}
ScopedDefaultHostResolverProc::~ScopedDefaultHostResolverProc() {
HostResolverProc* old_proc =
HostResolverProc::SetDefault(previous_proc_.get());
// The lifetimes of multiple instances must be nested.
CHECK_EQ(old_proc, current_proc_);
}
void ScopedDefaultHostResolverProc::Init(HostResolverProc* proc) {
current_proc_ = proc;
previous_proc_ = HostResolverProc::SetDefault(current_proc_.get());
current_proc_->SetLastProc(previous_proc_.get());
}
} // namespace net
|
#include <iostream>
using namespace std;
int main() {
ios_base::sync_with_stdio(0);
cin.tie(0);
int lock_one, lock_two;
cin >> lock_one >> lock_two;
if (lock_one == 0) {
cout << "yes" << endl;
}
else {
for (int i = 1; i < 10000; ++i)
if ( (i % 2 == 1 && lock_two == i) || (i % 2 == 0 && lock_one == i)) {
cout << "yes" << endl;
return 0;
}
}
cout << "no" << endl;
return 0;
}
|
#include "pch.h"
#include "DX12Texture2DArray.h"
#include "DX12Renderer.h"
#include "stb_image.h"
#include "DX12Sampler2D.h"
DX12Texture2DArray::DX12Texture2DArray(DX12Renderer* renderer)
: m_renderer(renderer)
, m_rgba(nullptr)
{}
DX12Texture2DArray::~DX12Texture2DArray() {
if (m_rgba) {
free(m_rgba);
m_rgba = nullptr;
}
}
// TODO: Per slice(texture) instead of all at once in order to take less memory
HRESULT DX12Texture2DArray::loadFromFiles(std::vector<std::string> filenames) {
int width, height, bytesPerPixel;
stbi_info(filenames[0].c_str(), &width, &height, &bytesPerPixel); // assume all files are the same width, height and bpp
UINT imageByteSize = width * height * bytesPerPixel;
UINT numTextures = UINT(filenames.size());
m_rgbaVec.resize(width * height * bytesPerPixel * numTextures);
// Pre-allocate the required memory
UINT index = 0;
for (auto file : filenames) {
int w, h, bpp;
m_rgba = stbi_load(file.c_str(), &w, &h, &bpp, STBI_rgb_alpha); // TODO: remove m_rgba memory after copy to gpu is complete
if (m_rgba == nullptr) {
return -1;
}
assert(w == width && h == height && bpp == bytesPerPixel && "All images has to have the same dimensions and BPP");
/*for (UINT i = 0; i < imageByteSize; i++) {
m_rgbaVec[i + imageByteSize * index] = m_rgba[i];
}*/
memcpy(m_rgbaVec.data() + imageByteSize * index, m_rgba, imageByteSize);
index++;
free(m_rgba);
m_rgba = nullptr;
}
m_textureDesc = {};
m_textureDesc.Format = DXGI_FORMAT_R8G8B8A8_UNORM;
//m_textureDesc.Format = DXGI_FORMAT_R32G32B32A32_UINT;
m_textureDesc.DepthOrArraySize = numTextures;
m_textureDesc.Dimension = D3D12_RESOURCE_DIMENSION_TEXTURE2D;
m_textureDesc.Width = width;
m_textureDesc.Height = height;
m_textureDesc.Flags = D3D12_RESOURCE_FLAG_NONE;
m_textureDesc.MipLevels = 1;
m_textureDesc.Layout = D3D12_TEXTURE_LAYOUT_UNKNOWN;
m_textureDesc.SampleDesc.Count = 1;
m_textureDesc.SampleDesc.Quality = 0;
// create a default heap where the upload heap will copy its contents into (contents being the texture)
HRESULT hr = m_renderer->getDevice()->CreateCommittedResource(
&CD3DX12_HEAP_PROPERTIES(D3D12_HEAP_TYPE_DEFAULT), // a default heap
D3D12_HEAP_FLAG_NONE, // no flags
&m_textureDesc, // the description of our texture
D3D12_RESOURCE_STATE_COPY_DEST, // We will copy the texture from the upload heap to here, so we start it out in a copy dest state
nullptr, // used for render targets and depth/stencil buffers
IID_PPV_ARGS(&m_textureBuffer));
if (FAILED(hr))
return false;
m_textureBuffer->SetName(L"Texture Array Buffer Resource Heap");
UINT64 textureUploadBufferSize;
// this function gets the size an upload buffer needs to be to upload a texture to the gpu.
// each row must be 256 byte aligned except for the last row, which can just be the size in bytes of the row
// eg. textureUploadBufferSize = ((((width * numBytesPerPixel) + 255) & ~255) * (height - 1)) + (width * numBytesPerPixel);
//textureUploadBufferSize = (((imageBytesPerRow + 255) & ~255) * (m_textureDesc.Height - 1)) + imageBytesPerRow;
m_renderer->getDevice()->GetCopyableFootprints(&m_textureDesc, 0, numTextures, 0, nullptr, nullptr, nullptr, &textureUploadBufferSize);
// Undefined behaviour, stuff doesn't get copied properly ^
auto uploadHeapDesc = CD3DX12_RESOURCE_DESC::Buffer(textureUploadBufferSize);
// now we create an upload heap to upload our texture to the GPU
hr = m_renderer->getDevice()->CreateCommittedResource(
&CD3DX12_HEAP_PROPERTIES(D3D12_HEAP_TYPE_UPLOAD), // upload heap
D3D12_HEAP_FLAG_NONE, // no flags
&CD3DX12_RESOURCE_DESC::Buffer(textureUploadBufferSize), // resource description for a buffer (storing the image data in this heap just to copy to the default heap)
D3D12_RESOURCE_STATE_GENERIC_READ, // We will copy the contents from this heap to the default heap above
nullptr,
IID_PPV_ARGS(&m_textureBufferUploadHeap));
if (FAILED(hr))
return false;
m_textureBufferUploadHeap->SetName(L"Texture Array Buffer Upload Resource Heap");
// store vertex buffer in upload heap
D3D12_SUBRESOURCE_DATA textureData[2];
textureData[0].pData = m_rgbaVec.data(); // pointer to our image data
textureData[0].RowPitch = width * bytesPerPixel; // Size of each row of each image
textureData[0].SlicePitch = textureData[0].RowPitch * height; // Size of each image
textureData[1] = textureData[0];
textureData[1].pData = m_rgbaVec.data() + imageByteSize;
// Now we copy the upload buffer contents to the default heap
UpdateSubresources(m_renderer->getCmdList(), m_textureBuffer.Get(), m_textureBufferUploadHeap.Get(), 0, 0, numTextures, textureData);
// transition the texture default heap to a pixel shader resource (we will be sampling from this heap in the pixel shader to get the color of pixels)
m_renderer->getCmdList()->ResourceBarrier(1, &CD3DX12_RESOURCE_BARRIER::Transition(m_textureBuffer.Get(), D3D12_RESOURCE_STATE_COPY_DEST, D3D12_RESOURCE_STATE_PIXEL_SHADER_RESOURCE));
// create the descriptor heap that will store our srv
D3D12_DESCRIPTOR_HEAP_DESC heapDesc = {};
heapDesc.NumDescriptors = 1;
heapDesc.Flags = D3D12_DESCRIPTOR_HEAP_FLAG_SHADER_VISIBLE;
heapDesc.Type = D3D12_DESCRIPTOR_HEAP_TYPE_CBV_SRV_UAV;
hr = m_renderer->getDevice()->CreateDescriptorHeap(&heapDesc, IID_PPV_ARGS(&m_mainDescriptorHeap));
if (FAILED(hr))
return -1;
m_mainDescriptorHeap->SetName(L"Texture Array Main Desc Heap");
// now we create a shader resource view (descriptor that points to the texture and describes it)
m_srvDesc = {};
m_srvDesc.Shader4ComponentMapping = D3D12_DEFAULT_SHADER_4_COMPONENT_MAPPING;
m_srvDesc.Format = m_textureDesc.Format;
m_srvDesc.ViewDimension = D3D12_SRV_DIMENSION_TEXTURE2DARRAY;
m_srvDesc.Texture2DArray.MipLevels = 1;
m_srvDesc.Texture2DArray.FirstArraySlice = 0;
m_srvDesc.Texture2DArray.ArraySize = numTextures;
m_srvDesc.Texture2DArray.MostDetailedMip = 0;
m_srvDesc.Texture2DArray.ResourceMinLODClamp = 0.f;
m_srvDesc.Texture2DArray.PlaneSlice = 0;
m_renderer->getDevice()->CreateShaderResourceView(m_textureBuffer.Get(), &m_srvDesc, m_mainDescriptorHeap->GetCPUDescriptorHandleForHeapStart());
return S_OK;
}
void DX12Texture2DArray::bind(ID3D12GraphicsCommandList3* cmdList) {
if (m_rgbaVec.size() > 0) {
m_rgbaVec.clear();
}
// Set the descriptor heaps
if (m_sampler != nullptr) {
ID3D12DescriptorHeap* descriptorHeaps[] = { m_mainDescriptorHeap.Get(), m_renderer->getSamplerDescriptorHeap() };
cmdList->SetDescriptorHeaps(ARRAYSIZE(descriptorHeaps), descriptorHeaps);
cmdList->SetGraphicsRootDescriptorTable(GlobalRootParam::DT_SAMPLERS, m_sampler->getGPUHandle());
cmdList->SetGraphicsRootDescriptorTable(GlobalRootParam::DT_SRVS, m_mainDescriptorHeap->GetGPUDescriptorHandleForHeapStart());
}
// Assume there's a static sampler in the
else {
ID3D12DescriptorHeap* descriptorHeaps[] = { m_mainDescriptorHeap.Get() };
cmdList->SetDescriptorHeaps(ARRAYSIZE(descriptorHeaps), descriptorHeaps);
cmdList->SetGraphicsRootDescriptorTable(GlobalRootParam::DT_SRVS, m_mainDescriptorHeap->GetGPUDescriptorHandleForHeapStart());
m_mainDescriptorHeap->GetGPUDescriptorHandleForHeapStart();
}
}
DXGI_FORMAT DX12Texture2DArray::getFormat() {
return m_textureBuffer->GetDesc().Format;
}
UINT DX12Texture2DArray::getMips() {
return m_textureBuffer->GetDesc().MipLevels;
}
ID3D12Resource * DX12Texture2DArray::getResource() {
return m_textureBuffer.Get();
}
D3D12_CPU_DESCRIPTOR_HANDLE DX12Texture2DArray::getCpuDescHandle() {
return m_mainDescriptorHeap->GetCPUDescriptorHandleForHeapStart();
}
D3D12_GPU_DESCRIPTOR_HANDLE DX12Texture2DArray::getGpuDescHandle() {
return m_mainDescriptorHeap->GetGPUDescriptorHandleForHeapStart();
}
D3D12_SHADER_RESOURCE_VIEW_DESC DX12Texture2DArray::getSRVDesc() {
return m_srvDesc;
}
void DX12Texture2DArray::setSampler(DX12Sampler2D * sampler) {
m_sampler = sampler;
}
|
#ifndef POSITIONSYSTEM_HPP
#define POSITIONSYSTEM_HPP
void MovementUpdate(float dt);
#endif // POSITIONSYSTEM_HPP
|
/*
* Copyright (c) Contributors to the Open 3D Engine Project. For complete copyright and license terms please see the LICENSE at the root of this distribution.
*
* SPDX-License-Identifier: Apache-2.0 OR MIT
*
*/
#include "ActionHistoryCallback.h"
#include <MCore/Source/LogManager.h>
#include <EMotionFX/Source/EventManager.h>
#include "../../../../EMStudioSDK/Source/EMStudioManager.h"
#include "../../../../EMStudioSDK/Source/MainWindow.h"
#include <QListWidget>
#include <QTextEdit>
#include <QApplication>
#include <QHBoxLayout>
namespace EMStudio
{
ActionHistoryCallback::ActionHistoryCallback(QListWidget* list)
: MCore::CommandManagerCallback()
{
mList = list;
mIndex = 0;
mIsRemoving = false;
mGroupExecuting = false;
mExecutedGroup = nullptr;
mNumGroupCommands = 0;
mCurrentCommandIndex = 0;
m_darkenedBrush.setColor(QColor(110, 110, 110));
m_brush.setColor(QColor(200, 200, 200));
}
// Before executing a command.
void ActionHistoryCallback::OnPreExecuteCommand(MCore::CommandGroup* group, MCore::Command* command, const MCore::CommandLine& commandLine)
{
MCORE_UNUSED(group);
if (command)
{
if (MCore::GetLogManager().GetLogLevels() & MCore::LogCallback::LOGLEVEL_DEBUG)
{
mTempString = command->GetName();
const uint32 numParameters = commandLine.GetNumParameters();
for (uint32 i = 0; i < numParameters; ++i)
{
mTempString += " -";
mTempString += commandLine.GetParameterName(i);
mTempString += " ";
mTempString += commandLine.GetParameterValue(i);
}
MCore::LogDebugMsg(mTempString.c_str());
}
}
}
// After executing a command.
void ActionHistoryCallback::OnPostExecuteCommand(MCore::CommandGroup* group, MCore::Command* command, const MCore::CommandLine& commandLine, bool wasSuccess, const AZStd::string& outResult)
{
MCORE_UNUSED(group);
MCORE_UNUSED(commandLine);
MCORE_UNUSED(outResult);
if (mGroupExecuting && mExecutedGroup)
{
mCurrentCommandIndex++;
if (mCurrentCommandIndex % 32 == 0)
{
EMotionFX::GetEventManager().OnProgressValue(((float)mCurrentCommandIndex / (mNumGroupCommands + 1)) * 100.0f);
}
}
if (command && MCore::GetLogManager().GetLogLevels() & MCore::LogCallback::LOGLEVEL_DEBUG)
{
mTempString = AZStd::string::format("%sExecution of command '%s' %s", wasSuccess ? " " : "*** ", command->GetName(), wasSuccess ? "completed successfully" : " FAILED");
MCore::LogDebugMsg(mTempString.c_str());
}
}
// Before executing a command group.
void ActionHistoryCallback::OnPreExecuteCommandGroup(MCore::CommandGroup* group, bool undo)
{
if (!mGroupExecuting && group->GetNumCommands() > 64)
{
mGroupExecuting = true;
mExecutedGroup = group;
mCurrentCommandIndex = 0;
mNumGroupCommands = group->GetNumCommands();
GetManager()->SetAvoidRendering(true);
EMotionFX::GetEventManager().OnProgressStart();
mTempString = AZStd::string::format("%s%s", undo ? "Undo: " : "", group->GetGroupName());
EMotionFX::GetEventManager().OnProgressText(mTempString.c_str());
}
if (group && MCore::GetLogManager().GetLogLevels() & MCore::LogCallback::LOGLEVEL_DEBUG)
{
mTempString = AZStd::string::format("Starting %s of command group '%s'", undo ? "undo" : "execution", group->GetGroupName());
MCore::LogDebugMsg(mTempString.c_str());
}
}
// After executing a command group.
void ActionHistoryCallback::OnPostExecuteCommandGroup(MCore::CommandGroup* group, bool wasSuccess)
{
if (mExecutedGroup == group)
{
EMotionFX::GetEventManager().OnProgressEnd();
mGroupExecuting = false;
mExecutedGroup = nullptr;
mNumGroupCommands = 0;
mCurrentCommandIndex = 0;
GetManager()->SetAvoidRendering(false);
}
if (group && MCore::GetLogManager().GetLogLevels() & MCore::LogCallback::LOGLEVEL_DEBUG)
{
mTempString = AZStd::string::format("%sExecution of command group '%s' %s", wasSuccess ? " " : "*** ", group->GetGroupName(), wasSuccess ? "completed successfully" : " FAILED");
MCore::LogDebugMsg(mTempString.c_str());
}
}
// Add a new item to the history.
void ActionHistoryCallback::OnAddCommandToHistory(uint32 historyIndex, MCore::CommandGroup* group, MCore::Command* command, const MCore::CommandLine& commandLine)
{
MCORE_UNUSED(commandLine);
mTempString = MCore::CommandManager::CommandHistoryEntry::ToString(group, command, mIndex++).c_str();
mList->insertItem(historyIndex, new QListWidgetItem(mTempString.c_str(), mList));
mList->setCurrentRow(historyIndex);
}
// Remove an item from the history.
void ActionHistoryCallback::OnRemoveCommand(uint32 historyIndex)
{
// Remove the item.
mIsRemoving = true;
delete mList->takeItem(historyIndex);
mIsRemoving = false;
}
// Set the current command.
void ActionHistoryCallback::OnSetCurrentCommand(uint32 index)
{
if (mIsRemoving)
{
return;
}
if (index == MCORE_INVALIDINDEX32)
{
mList->setCurrentRow(-1);
// Darken all history items.
const int numCommands = static_cast<int>(GetCommandManager()->GetNumHistoryItems());
for (int i = 0; i < numCommands; ++i)
{
mList->item(i)->setForeground(m_darkenedBrush);
}
return;
}
// get the list of selected items
mList->setCurrentRow(index);
// Get the current history index.
const uint32 historyIndex = GetCommandManager()->GetHistoryIndex();
if (historyIndex == MCORE_INVALIDINDEX32)
{
AZStd::string outResult;
const uint32 numRedos = index + 1;
for (uint32 i = 0; i < numRedos; ++i)
{
outResult.clear();
const bool result = GetCommandManager()->Redo(outResult);
if (outResult.size() > 0)
{
if (!result)
{
MCore::LogError(outResult.c_str());
}
}
}
}
else if (historyIndex > index) // if we need to perform undo's
{
AZStd::string outResult;
const int32 numUndos = historyIndex - index;
for (int32 i = 0; i < numUndos; ++i)
{
// try to undo
outResult.clear();
const bool result = GetCommandManager()->Undo(outResult);
if (outResult.size() > 0)
{
if (!result)
{
MCore::LogError(outResult.c_str());
}
}
}
}
else if (historyIndex < index) // if we need to redo commands
{
AZStd::string outResult;
const int32 numRedos = index - historyIndex;
for (int32 i = 0; i < numRedos; ++i)
{
outResult.clear();
const bool result = GetCommandManager()->Redo(outResult);
if (outResult.size() > 0)
{
if (!result)
{
MCore::LogError(outResult.c_str());
}
}
}
}
// Darken disabled commands.
const uint32 orgIndex = index;
if (index == MCORE_INVALIDINDEX32)
{
index = 0;
}
const int numCommands = static_cast<int>(GetCommandManager()->GetNumHistoryItems());
for (int i = index; i < numCommands; ++i)
{
mList->item(i)->setForeground(m_darkenedBrush);
}
// Color enabled ones.
if (orgIndex != MCORE_INVALIDINDEX32)
{
for (int i = 0; i <= static_cast<int>(index); ++i)
{
mList->item(index)->setForeground(m_brush);
}
}
}
} // namespace EMStudio
|
#include "LeafCmd.h"
LeafCmd::LeafCmd(Json::Value json)
: ICmd(json)
{
}
|
/** @file
ATS plugin to do combo handling.
@section license License
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 <list>
#include <string>
#include <sstream>
#include <vector>
#include <algorithm>
#include <time.h>
#include <pthread.h>
#include <arpa/inet.h>
#include "ts/ts.h"
#include "ts/experimental.h"
#include "ts/remap.h"
#include "ink_defs.h"
#include "HttpDataFetcherImpl.h"
#include "gzip.h"
#include "Utils.h"
using namespace std;
using namespace EsiLib;
#define DEBUG_TAG "combo_handler"
#define MAX_FILE_COUNT 30
#define MAX_QUERY_LENGTH 3000
int arg_idx;
static string SIG_KEY_NAME;
static vector<string> HEADER_WHITELIST;
#define DEFAULT_COMBO_HANDLER_PATH "admin/v1/combo"
static string COMBO_HANDLER_PATH;
static int COMBO_HANDLER_PATH_SIZE;
#define LOG_ERROR(fmt, args...) do { \
TSError("[%s:%d] [%s] ERROR: " fmt, __FILE__, __LINE__, __FUNCTION__ , ##args ); \
TSDebug(DEBUG_TAG, "[%s:%d] [%s] ERROR: " fmt, __FILE__, __LINE__, __FUNCTION__ , ##args ); \
} while (0)
#define LOG_DEBUG(fmt, args...) do { \
TSDebug(DEBUG_TAG, "[%s:%d] [%s] DEBUG: " fmt, __FILE__, __LINE__, __FUNCTION__ , ##args ); \
} while (0)
typedef list<string> StringList;
struct ClientRequest {
TSHttpStatus status;
const sockaddr *client_addr;
StringList file_urls;
bool gzip_accepted;
string defaultBucket; // default Bucket will be set to HOST header
ClientRequest()
: status(TS_HTTP_STATUS_OK), client_addr(NULL), gzip_accepted(false), defaultBucket("l") { };
};
struct InterceptData {
TSVConn net_vc;
TSCont contp;
struct IoHandle {
TSVIO vio;
TSIOBuffer buffer;
TSIOBufferReader reader;
IoHandle()
: vio(0), buffer(0), reader(0) { };
~IoHandle() {
if (reader) {
TSIOBufferReaderFree(reader);
}
if (buffer) {
TSIOBufferDestroy(buffer);
}
};
};
IoHandle input;
IoHandle output;
TSHttpParser http_parser;
string body;
TSMBuffer req_hdr_bufp;
TSMLoc req_hdr_loc;
bool req_hdr_parsed;
bool initialized;
ClientRequest creq;
HttpDataFetcherImpl *fetcher;
bool read_complete;
bool write_complete;
string gzipped_data;
InterceptData(TSCont cont)
: net_vc(0), contp(cont), input(), output(), req_hdr_bufp(0), req_hdr_loc(0), req_hdr_parsed(false),
initialized(false), fetcher(0), read_complete(false), write_complete(false) {
http_parser = TSHttpParserCreate();
}
bool init(TSVConn vconn);
void setupWrite();
~InterceptData();
};
bool
InterceptData::init(TSVConn vconn)
{
if (initialized) {
LOG_ERROR("InterceptData already initialized!");
return false;
}
net_vc = vconn;
input.buffer = TSIOBufferCreate();
input.reader = TSIOBufferReaderAlloc(input.buffer);
input.vio = TSVConnRead(net_vc, contp, input.buffer, INT64_MAX);
req_hdr_bufp = TSMBufferCreate();
req_hdr_loc = TSHttpHdrCreate(req_hdr_bufp);
TSHttpHdrTypeSet(req_hdr_bufp, req_hdr_loc, TS_HTTP_TYPE_REQUEST);
fetcher = new HttpDataFetcherImpl(contp, creq.client_addr, "combohandler_fetcher");
initialized = true;
LOG_DEBUG("InterceptData initialized!");
return true;
}
void
InterceptData::setupWrite()
{
TSAssert(output.buffer == 0);
output.buffer = TSIOBufferCreate();
output.reader = TSIOBufferReaderAlloc(output.buffer);
output.vio = TSVConnWrite(net_vc, contp, output.reader, INT64_MAX);
}
InterceptData::~InterceptData()
{
if (req_hdr_loc) {
TSHandleMLocRelease(req_hdr_bufp, TS_NULL_MLOC, req_hdr_loc);
}
if (req_hdr_bufp) {
TSMBufferDestroy(req_hdr_bufp);
}
if (fetcher) {
delete fetcher;
}
TSHttpParserDestroy(http_parser);
if (net_vc) {
TSVConnClose(net_vc);
}
}
// forward declarations
static int handleReadRequestHeader(TSCont contp, TSEvent event, void *edata);
static bool isComboHandlerRequest(TSMBuffer bufp, TSMLoc hdr_loc, TSMLoc url_loc);
static void getClientRequest(TSHttpTxn txnp, TSMBuffer bufp, TSMLoc hdr_loc, TSMLoc url_loc,
ClientRequest &creq);
static void parseQueryParameters(const char *query, int query_len, ClientRequest &creq);
static void checkGzipAcceptance(TSMBuffer bufp, TSMLoc hdr_loc, ClientRequest &creq);
static int handleServerEvent(TSCont contp, TSEvent event, void *edata);
static bool initRequestProcessing(InterceptData &int_data, void *edata, bool &write_response);
static bool readInterceptRequest(InterceptData &int_data);
static bool writeResponse(InterceptData &int_data);
static bool writeErrorResponse(InterceptData &int_data, int &n_bytes_written);
static bool writeStandardHeaderFields(InterceptData &int_data, int &n_bytes_written);
static void prepareResponse(InterceptData &int_data, ByteBlockList &body_blocks, string &resp_header_fields);
static bool getContentType(TSMBuffer bufp, TSMLoc hdr_loc, string &resp_header_fields);
static int getMaxAge(TSMBuffer bufp, TSMLoc hdr_loc);
static bool getDefaultBucket(TSHttpTxn txnp, TSMBuffer bufp, TSMLoc hdr_obj, ClientRequest &creq);
// libesi TLS key.
pthread_key_t threadKey = 0;
void
TSPluginInit(int argc, const char *argv[])
{
if ((argc > 1) && (strcmp(argv[1], "-") != 0)) {
COMBO_HANDLER_PATH = argv[1];
if (COMBO_HANDLER_PATH == "/") {
COMBO_HANDLER_PATH.clear();
} else {
if (COMBO_HANDLER_PATH[0] == '/') {
COMBO_HANDLER_PATH.erase(0, 1);
}
if (COMBO_HANDLER_PATH[COMBO_HANDLER_PATH.size() - 1] == '/') {
COMBO_HANDLER_PATH.erase(COMBO_HANDLER_PATH.size() - 1, 1);
}
}
} else {
COMBO_HANDLER_PATH = DEFAULT_COMBO_HANDLER_PATH;
}
COMBO_HANDLER_PATH_SIZE = static_cast<int>(COMBO_HANDLER_PATH.size());
LOG_DEBUG("Combo handler path is [%s]", COMBO_HANDLER_PATH.c_str());
SIG_KEY_NAME = ((argc > 2) && (strcmp(argv[2], "-") != 0)) ? argv[2] : "";
LOG_DEBUG("Signature key is [%s]", SIG_KEY_NAME.c_str());
if ((argc > 3) && (strcmp(argv[3], "-") != 0)) {
stringstream strstream(argv[3]);
string header;
while (getline(strstream, header, ':')) {
HEADER_WHITELIST.push_back(header);
}
}
for (unsigned int i = 0; i < HEADER_WHITELIST.size(); i++) {
LOG_DEBUG("WhiteList: %s", HEADER_WHITELIST[i].c_str());
}
TSReleaseAssert(pthread_key_create(&threadKey, NULL) == 0);
TSCont rrh_contp = TSContCreate(handleReadRequestHeader, NULL);
if (!rrh_contp) {
LOG_ERROR("Could not create read request header continuation");
return;
}
TSHttpHookAdd(TS_HTTP_OS_DNS_HOOK, rrh_contp);
if (TSHttpArgIndexReserve(DEBUG_TAG, "will save plugin-enable flag here", &arg_idx) != TS_SUCCESS) {
LOG_ERROR("failed to reserve private data slot");
return;
} else {
LOG_DEBUG("arg_idx: %d", arg_idx);
}
Utils::init(&TSDebug, &TSError);
LOG_DEBUG("Plugin started");
}
/*
Handle TS_EVENT_HTTP_OS_DNS event after TS_EVENT_HTTP_POST_REMAP and
TS_EVENT_HTTP_CACHE_LOOKUP_COMPLETE in order to make this plugin
"per-remap configurable", that is, we enable combo for specific channels,
and disable for other channels.
In yahoo's original code, this function handle TS_EVENT_HTTP_READ_REQUEST_HDR.
Because TS_EVENT_HTTP_READ_REQUEST_HDR is before TSRemapDoRemap, we can not
read "plugin_enable" flag in the READ_REQUEST_HDR event.
*/
static int
handleReadRequestHeader(TSCont /* contp ATS_UNUSED */, TSEvent event, void *edata)
{
TSHttpTxn txnp = static_cast<TSHttpTxn>(edata);
if (event != TS_EVENT_HTTP_OS_DNS) {
LOG_ERROR("unknown event for this plugin %d", event);
return 0;
}
if (1 != reinterpret_cast<intptr_t>(TSHttpTxnArgGet(txnp, arg_idx))) {
LOG_DEBUG("combo is disabled for this channel");
TSHttpTxnReenable(txnp, TS_EVENT_HTTP_CONTINUE);
return 0;
}
LOG_DEBUG("combo is enabled for this channel");
LOG_DEBUG("handling TS_EVENT_HTTP_OS_DNS event...");
TSEvent reenable_to_event = TS_EVENT_HTTP_CONTINUE;
TSMBuffer bufp;
TSMLoc hdr_loc;
if (TSHttpTxnClientReqGet(txnp, &bufp, &hdr_loc) == TS_SUCCESS) {
TSMLoc url_loc;
if (TSHttpHdrUrlGet(bufp, hdr_loc, &url_loc) == TS_SUCCESS) {
if (isComboHandlerRequest(bufp, hdr_loc, url_loc)) {
TSCont contp = TSContCreate(handleServerEvent, TSMutexCreate());
if (!contp) {
LOG_ERROR("[%s] Could not create intercept request", __FUNCTION__);
reenable_to_event = TS_EVENT_HTTP_ERROR;
} else {
TSHttpTxnServerIntercept(contp, txnp);
InterceptData *int_data = new InterceptData(contp);
TSContDataSet(contp, int_data);
// todo: check if these two cacheable sets are required
TSHttpTxnReqCacheableSet(txnp, 1);
TSHttpTxnRespCacheableSet(txnp, 1);
getClientRequest(txnp, bufp, hdr_loc, url_loc, int_data->creq);
LOG_DEBUG("Setup server intercept to handle client request");
}
}
TSHandleMLocRelease(bufp, hdr_loc, url_loc);
} else {
LOG_ERROR("Could not get request URL");
}
TSHandleMLocRelease(bufp, TS_NULL_MLOC, hdr_loc);
} else {
LOG_ERROR("Could not get client request");
}
TSHttpTxnReenable(txnp, reenable_to_event);
return 1;
}
static bool
isComboHandlerRequest(TSMBuffer bufp, TSMLoc hdr_loc, TSMLoc url_loc)
{
int method_len;
bool retval = false;
const char *method = TSHttpHdrMethodGet(bufp, hdr_loc, &method_len);
if (!method) {
LOG_ERROR("Could not obtain method!");
} else {
if ((method_len != TS_HTTP_LEN_GET) || (strncasecmp(method, TS_HTTP_METHOD_GET, TS_HTTP_LEN_GET) != 0)) {
LOG_DEBUG("Unsupported method [%.*s]", method_len, method);
} else {
retval = true;
}
if (retval) {
int path_len;
const char *path = TSUrlPathGet(bufp, url_loc, &path_len);
if (!path) {
LOG_ERROR("Could not get path from request URL");
retval = false;
} else {
retval = (path_len == COMBO_HANDLER_PATH_SIZE) &&
(strncasecmp(path, COMBO_HANDLER_PATH.c_str(), COMBO_HANDLER_PATH_SIZE) == 0);
LOG_DEBUG("Path [%.*s] is %s combo handler path", path_len, path, (retval ? "a" : "not a"));
}
}
}
return retval;
}
static bool
getDefaultBucket(TSHttpTxn /* txnp ATS_UNUSED */, TSMBuffer bufp, TSMLoc hdr_obj, ClientRequest &creq)
{
LOG_DEBUG("In getDefaultBucket");
TSMLoc field_loc;
const char* host;
int host_len = 0;
bool defaultBucketFound = false;
field_loc = TSMimeHdrFieldFind(bufp, hdr_obj, TS_MIME_FIELD_HOST, -1);
if (field_loc == TS_NULL_MLOC) {
LOG_ERROR("Host field not found.");
return false;
}
host = TSMimeHdrFieldValueStringGet(bufp, hdr_obj, field_loc, -1, &host_len);
if (!host || host_len <= 0) {
LOG_ERROR("Error Extracting Host Header");
TSHandleMLocRelease (bufp, hdr_obj, field_loc);
return false;
}
LOG_DEBUG("host: %.*s", host_len, host);
creq.defaultBucket = string(host, host_len);
defaultBucketFound = true;
/*
for(int i = 0 ; i < host_len; i++)
{
if (host[i] == '.')
{
creq.defaultBucket = string(host, i);
defaultBucketFound = true;
break;
}
}
*/
TSHandleMLocRelease (bufp, hdr_obj, field_loc);
LOG_DEBUG("defaultBucket: %s", creq.defaultBucket.data());
return defaultBucketFound;
}
static void
getClientRequest(TSHttpTxn txnp, TSMBuffer bufp, TSMLoc hdr_loc, TSMLoc url_loc, ClientRequest &creq)
{
int query_len;
const char *query = TSUrlHttpQueryGet(bufp, url_loc, &query_len);
if (!query) {
LOG_ERROR("Could not get query from request URL");
creq.status = TS_HTTP_STATUS_BAD_REQUEST;
return;
} else {
if (!getDefaultBucket(txnp, bufp, hdr_loc, creq))
{
LOG_ERROR("failed getting Default Bucket for the request");
return;
}
if (query_len > MAX_QUERY_LENGTH) {
creq.status = TS_HTTP_STATUS_BAD_REQUEST;
LOG_ERROR("querystring too long");
return;
}
parseQueryParameters(query, query_len, creq);
creq.client_addr = TSHttpTxnClientAddrGet(txnp);
checkGzipAcceptance(bufp, hdr_loc, creq);
}
}
static void
parseQueryParameters(const char *query, int query_len, ClientRequest &creq)
{
creq.status = TS_HTTP_STATUS_OK;
int param_start_pos = 0;
bool sig_verified = false;
int colon_pos = -1;
string file_url("http://localhost/");
size_t file_base_url_size = file_url.size();
const char *common_prefix = 0;
int common_prefix_size = 0;
const char *common_prefix_path = 0;
int common_prefix_path_size = 0;
for (int i = 0; i <= query_len; ++i) {
if ((i == query_len) || (query[i] == '&')) {
int param_len = i - param_start_pos;
if (param_len) {
const char *param = query + param_start_pos;
if ((param_len >= 4) && (strncmp(param, "sig=", 4) == 0)) {
if (SIG_KEY_NAME.size()) {
if (!param_start_pos) {
LOG_DEBUG("Signature cannot be the first parameter in query [%.*s]", query_len, query);
} else if (param_len == 4) {
LOG_DEBUG("Signature empty in query [%.*s]", query_len, query);
} else {
// TODO - really verify the signature
LOG_DEBUG("Verified signature successfully");
sig_verified = true;
}
if (!sig_verified) {
LOG_DEBUG("Signature [%.*s] on query [%.*s] is invalid", param_len - 4, param + 4,
param_start_pos, query);
}
} else {
LOG_DEBUG("Verification not configured; ignoring signature...");
}
break; // nothing useful after the signature
}
if ((param_len >= 2) && (param[0] == 'p') && (param[1] == '=')) {
common_prefix_size = param_len - 2;
common_prefix_path_size = 0;
if (common_prefix_size) {
common_prefix = param + 2;
for (int i = 0; i < common_prefix_size; ++i) {
if (common_prefix[i] == ':') {
common_prefix_path = common_prefix;
common_prefix_path_size = i;
++i; // go beyond the ':'
common_prefix += i;
common_prefix_size -= i;
break;
}
}
}
LOG_DEBUG("Common prefix is [%.*s], common prefix path is [%.*s]", common_prefix_size, common_prefix,
common_prefix_path_size, common_prefix_path);
}
else {
if (common_prefix_path_size) {
if (colon_pos >= param_start_pos) { // we have a colon in this param as well?
LOG_ERROR("Ambiguous 'bucket': [%.*s] specified in common prefix and [%.*s] specified in "
"current parameter [%.*s]", common_prefix_path_size, common_prefix_path,
colon_pos - param_start_pos, param, param_len, param);
creq.file_urls.clear();
break;
}
file_url.append(common_prefix_path, common_prefix_path_size);
}
else if (colon_pos >= param_start_pos) { // we have a colon
if ((colon_pos == param_start_pos) || (colon_pos == (i - 1))) {
LOG_ERROR("Colon-separated path [%.*s] has empty part(s)", param_len, param);
creq.file_urls.clear();
break;
}
file_url.append(param, colon_pos - param_start_pos); // appending pre ':' part first
// modify these to point to the "actual" file path
param_start_pos = colon_pos + 1;
param_len = i - param_start_pos;
param = query + param_start_pos;
} else {
file_url += creq.defaultBucket; // default path
}
file_url += '/';
if (common_prefix_size) {
file_url.append(common_prefix, common_prefix_size);
}
file_url.append(param, param_len);
creq.file_urls.push_back(file_url);
LOG_DEBUG("Added file path [%s]", file_url.c_str());
file_url.resize(file_base_url_size);
}
}
param_start_pos = i + 1;
} else if (query[i] == ':') {
colon_pos = i;
}
}
if (!creq.file_urls.size()) {
creq.status = TS_HTTP_STATUS_BAD_REQUEST;
} else if (SIG_KEY_NAME.size() && !sig_verified) {
LOG_DEBUG("Invalid/empty signature found; Need valid signature");
creq.status = TS_HTTP_STATUS_FORBIDDEN;
creq.file_urls.clear();
}
if (creq.file_urls.size() > MAX_FILE_COUNT) {
creq.status = TS_HTTP_STATUS_BAD_REQUEST;
LOG_ERROR("too many files in url");
creq.file_urls.clear();
}
}
static void
checkGzipAcceptance(TSMBuffer bufp, TSMLoc hdr_loc, ClientRequest &creq)
{
creq.gzip_accepted = false;
TSMLoc field_loc = TSMimeHdrFieldFind(bufp, hdr_loc, TS_MIME_FIELD_ACCEPT_ENCODING,
TS_MIME_LEN_ACCEPT_ENCODING);
if (field_loc != TS_NULL_MLOC) {
const char *value;
int value_len;
int n_values = TSMimeHdrFieldValuesCount(bufp, hdr_loc, field_loc);
for (int i = 0; i < n_values; ++i) {
value = TSMimeHdrFieldValueStringGet(bufp, hdr_loc, field_loc, i, &value_len);
if (value) {
if ((value_len == TS_HTTP_LEN_GZIP) && (strncasecmp(value, TS_HTTP_VALUE_GZIP, value_len) == 0)) {
creq.gzip_accepted = true;
}
} else {
LOG_DEBUG("Error while getting value # %d of header [%.*s]", i, TS_MIME_LEN_ACCEPT_ENCODING,
TS_MIME_FIELD_ACCEPT_ENCODING);
}
if (creq.gzip_accepted) {
break;
}
}
TSHandleMLocRelease(bufp, hdr_loc, field_loc);
}
LOG_DEBUG("Client %s gzip encoding", (creq.gzip_accepted ? "accepts" : "does not accept"));
}
static int
handleServerEvent(TSCont contp, TSEvent event, void *edata)
{
InterceptData *int_data = static_cast<InterceptData *>(TSContDataGet(contp));
bool write_response = false;
switch (event) {
case TS_EVENT_NET_ACCEPT_FAILED:
LOG_DEBUG("Received net accept failed event; going to abort continuation");
int_data->read_complete = int_data->write_complete = true;
break;
case TS_EVENT_NET_ACCEPT:
LOG_DEBUG("Received net accept event");
if (!initRequestProcessing(*int_data, edata, write_response)) {
LOG_ERROR("Could not initialize request processing");
return 0;
}
break;
case TS_EVENT_VCONN_READ_READY:
LOG_DEBUG("Received read ready event");
if (!readInterceptRequest(*int_data)) {
LOG_ERROR("Error while reading from input vio");
return 0;
}
break;
case TS_EVENT_VCONN_READ_COMPLETE:
case TS_EVENT_VCONN_EOS:
LOG_DEBUG("Received read complete/eos event %d", event);
int_data->read_complete = true;
break;
case TS_EVENT_VCONN_WRITE_READY:
LOG_DEBUG("Received write ready event");
break;
case TS_EVENT_VCONN_WRITE_COMPLETE:
LOG_DEBUG("Received write complete event");
int_data->write_complete = true;
break;
case TS_EVENT_ERROR:
LOG_ERROR("Received error event!");
break;
default:
if (int_data->fetcher && int_data->fetcher->isFetchEvent(event)) {
if (!int_data->fetcher->handleFetchEvent(event, edata)) {
LOG_ERROR("Couldn't handle fetch request event %d", event);
}
write_response = int_data->fetcher->isFetchComplete();
} else {
LOG_DEBUG("Unexpected event %d", event);
}
break;
}
if (write_response) {
if (!writeResponse(*int_data)) {
LOG_ERROR("Couldn't write response");
int_data->write_complete = true;
} else {
LOG_DEBUG("Wrote response successfully");
}
}
if (int_data->read_complete && int_data->write_complete) {
LOG_DEBUG("Completed request processing. Shutting down...");
delete int_data;
TSContDestroy(contp);
}
return 1;
}
static bool
initRequestProcessing(InterceptData &int_data, void *edata, bool &write_response)
{
TSAssert(int_data.initialized == false);
if (!int_data.init(static_cast<TSVConn>(edata))) {
LOG_ERROR("Could not initialize intercept data!");
return false;
}
if (int_data.creq.status == TS_HTTP_STATUS_OK) {
for (StringList::iterator iter = int_data.creq.file_urls.begin();
iter != int_data.creq.file_urls.end(); ++iter) {
if (!int_data.fetcher->addFetchRequest(*iter)) {
LOG_ERROR("Couldn't add fetch request for URL [%s]", iter->c_str());
} else {
LOG_DEBUG("Added fetch request for URL [%s]", iter->c_str());
}
}
} else {
LOG_DEBUG("Client request status [%d] not ok; Not fetching URLs", int_data.creq.status);
write_response = true;
}
return true;
}
static bool
readInterceptRequest(InterceptData &int_data)
{
TSAssert(!int_data.read_complete);
int avail = TSIOBufferReaderAvail(int_data.input.reader);
if (avail == TS_ERROR) {
LOG_ERROR("Error while getting number of bytes available");
return false;
}
int consumed = 0;
if (avail > 0) {
int64_t data_len;
const char *data;
TSIOBufferBlock block = TSIOBufferReaderStart(int_data.input.reader);
while (block != NULL) {
data = TSIOBufferBlockReadStart(block, int_data.input.reader, &data_len);
const char *endptr = data + data_len;
if (TSHttpHdrParseReq(int_data.http_parser, int_data.req_hdr_bufp, int_data.req_hdr_loc,
&data, endptr) == TS_PARSE_DONE) {
int_data.read_complete = true;
}
consumed += data_len;
block = TSIOBufferBlockNext(block);
}
}
LOG_DEBUG("Consumed %d bytes from input vio", consumed);
TSIOBufferReaderConsume(int_data.input.reader, consumed);
// Modify the input VIO to reflect how much data we've completed.
TSVIONDoneSet(int_data.input.vio, TSVIONDoneGet(int_data.input.vio) + consumed);
if (!int_data.read_complete) {
LOG_DEBUG("Re-enabling input VIO as request header not completely read yet");
TSVIOReenable(int_data.input.vio);
}
return true;
}
static const string OK_REPLY_LINE("HTTP/1.0 200 OK\r\n");
static const string BAD_REQUEST_RESPONSE("HTTP/1.0 400 Bad Request\r\n\r\n");
static const string ERROR_REPLY_RESPONSE("HTTP/1.0 500 Internal Server Error\r\n\r\n");
static const string FORBIDDEN_RESPONSE("HTTP/1.0 403 Forbidden\r\n\r\n");
static const char GZIP_ENCODING_FIELD[] = { "Content-Encoding: gzip\r\n" };
static const int GZIP_ENCODING_FIELD_SIZE = sizeof(GZIP_ENCODING_FIELD) - 1;
static bool
writeResponse(InterceptData &int_data)
{
int_data.setupWrite();
ByteBlockList body_blocks;
string resp_header_fields;
prepareResponse(int_data, body_blocks, resp_header_fields);
int n_bytes_written = 0;
if (int_data.creq.status != TS_HTTP_STATUS_OK) {
if (!writeErrorResponse(int_data, n_bytes_written)) {
LOG_ERROR("Couldn't write response error");
return false;
}
} else {
n_bytes_written = OK_REPLY_LINE.size();
if (TSIOBufferWrite(int_data.output.buffer, OK_REPLY_LINE.data(), n_bytes_written) == TS_ERROR) {
LOG_ERROR("Error while writing reply line");
return false;
}
if (!writeStandardHeaderFields(int_data, n_bytes_written)) {
LOG_ERROR("Could not write standard header fields");
return false;
}
if (resp_header_fields.size()) {
if (TSIOBufferWrite(int_data.output.buffer, resp_header_fields.data(),
resp_header_fields.size()) == TS_ERROR) {
LOG_ERROR("Error while writing additional response header fields");
return false;
}
n_bytes_written += resp_header_fields.size();
}
if (TSIOBufferWrite(int_data.output.buffer, "\r\n", 2) == TS_ERROR) {
LOG_ERROR("Error while writing header terminator");
return false;
}
n_bytes_written += 2;
for (ByteBlockList::iterator iter = body_blocks.begin(); iter != body_blocks.end(); ++iter) {
if (TSIOBufferWrite(int_data.output.buffer, iter->data, iter->data_len) == TS_ERROR) {
LOG_ERROR("Error while writing content");
return false;
}
n_bytes_written += iter->data_len;
}
}
LOG_DEBUG("Wrote reply of size %d", n_bytes_written);
TSVIONBytesSet(int_data.output.vio, n_bytes_written);
TSVIOReenable(int_data.output.vio);
return true;
}
static void
prepareResponse(InterceptData &int_data, ByteBlockList &body_blocks, string &resp_header_fields)
{
bool got_content_type = false;
if (int_data.creq.status == TS_HTTP_STATUS_OK) {
HttpDataFetcherImpl::ResponseData resp_data;
TSMLoc field_loc;
int max_age = 0;
bool got_max_age = false;
time_t expires_time;
bool got_expires_time = false;
int num_headers = HEADER_WHITELIST.size();
int flags_list[num_headers];
for (int i = 0; i < num_headers; i++) {
flags_list[i] = 0;
}
for (StringList::iterator iter = int_data.creq.file_urls.begin(); iter != int_data.creq.file_urls.end();
++iter) {
if (int_data.fetcher->getData(*iter, resp_data) && resp_data.status == TS_HTTP_STATUS_OK) {
body_blocks.push_back(ByteBlock(resp_data.content, resp_data.content_len));
if (find(HEADER_WHITELIST.begin(), HEADER_WHITELIST.end(), TS_MIME_FIELD_CONTENT_TYPE) == HEADER_WHITELIST.end()) {
if (!got_content_type) {
got_content_type = getContentType(resp_data.bufp, resp_data.hdr_loc, resp_header_fields);
}
}
int curr_field_max_age = getMaxAge(resp_data.bufp, resp_data.hdr_loc);
if (curr_field_max_age > 0) {
if (!got_max_age) {
max_age = curr_field_max_age;
got_max_age = true;
} else if (curr_field_max_age < max_age) {
max_age = curr_field_max_age;
}
}
field_loc = TSMimeHdrFieldFind(resp_data.bufp, resp_data.hdr_loc, TS_MIME_FIELD_EXPIRES,
TS_MIME_LEN_EXPIRES);
if (field_loc != TS_NULL_MLOC) {
time_t curr_field_expires_time;
int n_values = TSMimeHdrFieldValuesCount(resp_data.bufp, resp_data.hdr_loc, field_loc);
if ((n_values != TS_ERROR) && (n_values > 0)) {
curr_field_expires_time = TSMimeHdrFieldValueDateGet(resp_data.bufp, resp_data.hdr_loc, field_loc);
if (!got_expires_time) {
expires_time = curr_field_expires_time;
got_expires_time = true;
} else if (curr_field_expires_time < expires_time) {
expires_time = curr_field_expires_time;
}
}
TSHandleMLocRelease(resp_data.bufp, resp_data.hdr_loc, field_loc);
}
for (int i = 0; i < num_headers; i++) {
if (flags_list[i]) {
continue;
}
const string& header = HEADER_WHITELIST[i];
field_loc = TSMimeHdrFieldFind(resp_data.bufp, resp_data.hdr_loc, header.c_str(), header.size());
if (field_loc != TS_NULL_MLOC) {
bool values_added = false;
const char *value;
int value_len;
int n_values = TSMimeHdrFieldValuesCount(resp_data.bufp, resp_data.hdr_loc, field_loc);
if ((n_values != TS_ERROR) && (n_values > 0)) {
for (int k = 0; k < n_values; k++) {
value = TSMimeHdrFieldValueStringGet(resp_data.bufp, resp_data.hdr_loc, field_loc, k, &value_len);
if (!values_added) {
resp_header_fields.append(header + ": ");
values_added = true;
} else {
resp_header_fields.append(", ");
}
resp_header_fields.append(value, value_len);
}
if (values_added) {
resp_header_fields.append("\r\n");
flags_list[i] = 1;
}
}
TSHandleMLocRelease(resp_data.bufp, resp_data.hdr_loc, field_loc);
}
}
} else {
LOG_ERROR("Could not get content for requested URL [%s]", iter->c_str());
int_data.creq.status = TS_HTTP_STATUS_BAD_REQUEST;
break;
}
}
if (int_data.creq.status == TS_HTTP_STATUS_OK) {
if (find(HEADER_WHITELIST.begin(), HEADER_WHITELIST.end(), TS_MIME_FIELD_CACHE_CONTROL) == HEADER_WHITELIST.end()) {
if (got_max_age && max_age > 0) {
char line_buf[128];
int line_size = sprintf(line_buf, "Cache-Control: max-age=%d, public\r\n", max_age);
resp_header_fields.append(line_buf, line_size);
} else {
resp_header_fields.append("Cache-Control: max-age=315360000, public\r\n"); // set 10-years max-age
}
}
if (find(HEADER_WHITELIST.begin(), HEADER_WHITELIST.end(), TS_MIME_FIELD_EXPIRES) == HEADER_WHITELIST.end()) {
if (got_expires_time) {
if (expires_time <= 0) {
resp_header_fields.append("Expires: 0\r\n");
} else {
char line_buf[128];
int line_size = strftime(line_buf, 128, "Expires: %a, %d %b %Y %T GMT\r\n", gmtime(&expires_time));
resp_header_fields.append(line_buf, line_size);
}
}
}
LOG_DEBUG("Prepared response header field\n%s", resp_header_fields.c_str());
}
}
if ((int_data.creq.status == TS_HTTP_STATUS_OK) && int_data.creq.gzip_accepted) {
if (!gzip(body_blocks, int_data.gzipped_data)) {
LOG_ERROR("Could not gzip content!");
int_data.creq.status = TS_HTTP_STATUS_INTERNAL_SERVER_ERROR;
} else {
body_blocks.clear();
body_blocks.push_back(ByteBlock(int_data.gzipped_data.data(), int_data.gzipped_data.size()));
resp_header_fields.append(GZIP_ENCODING_FIELD, GZIP_ENCODING_FIELD_SIZE);
}
}
}
static bool
getContentType(TSMBuffer bufp, TSMLoc hdr_loc, string &resp_header_fields)
{
bool retval = false;
TSMLoc field_loc = TSMimeHdrFieldFind(bufp, hdr_loc, TS_MIME_FIELD_CONTENT_TYPE,
TS_MIME_LEN_CONTENT_TYPE);
if (field_loc != TS_NULL_MLOC) {
bool values_added = false;
const char *value;
int value_len;
int n_values = TSMimeHdrFieldValuesCount(bufp, hdr_loc, field_loc);
for (int i = 0; i < n_values; ++i) {
value = TSMimeHdrFieldValueStringGet(bufp, hdr_loc, field_loc, i, &value_len);
if (!values_added) {
resp_header_fields.append("Content-Type: ");
values_added = true;
} else {
resp_header_fields.append(", ");
}
resp_header_fields.append(value, value_len);
}
TSHandleMLocRelease(bufp, hdr_loc, field_loc);
if (values_added) {
resp_header_fields.append("\r\n");
retval = true;
}
}
return retval;
}
static int
getMaxAge(TSMBuffer bufp, TSMLoc hdr_loc)
{
int max_age = 0;
const char *value, *ptr;
int value_len = 0;
TSMLoc field_loc = TSMimeHdrFieldFind(bufp, hdr_loc, TS_MIME_FIELD_CACHE_CONTROL, TS_MIME_LEN_CACHE_CONTROL);
if (field_loc != TS_NULL_MLOC) {
int n_values = TSMimeHdrFieldValuesCount(bufp, hdr_loc, field_loc);
if ((n_values != TS_ERROR) && (n_values > 0)) {
for (int i = 0; i < n_values; i++) {
value = TSMimeHdrFieldValueStringGet(bufp, hdr_loc, field_loc, i, &value_len);
ptr = value;
if (strncmp(value, TS_HTTP_VALUE_MAX_AGE, TS_HTTP_LEN_MAX_AGE) == 0) {
ptr += TS_HTTP_LEN_MAX_AGE;
while ((*ptr == ' ') || (*ptr == '\t')) {
ptr++;
}
if (*ptr == '=') {
ptr++;
max_age = atoi(ptr);
}
break;
}
}
}
TSHandleMLocRelease(bufp, hdr_loc, field_loc);
}
return max_age;
}
static const char INVARIANT_FIELD_LINES[] = { "Vary: Accept-Encoding\r\n" };
static const char INVARIANT_FIELD_LINES_SIZE = sizeof(INVARIANT_FIELD_LINES) - 1;
static bool
writeStandardHeaderFields(InterceptData &int_data, int &n_bytes_written)
{
if (find(HEADER_WHITELIST.begin(), HEADER_WHITELIST.end(), TS_MIME_FIELD_VARY) == HEADER_WHITELIST.end()) {
if (TSIOBufferWrite(int_data.output.buffer, INVARIANT_FIELD_LINES,
INVARIANT_FIELD_LINES_SIZE) == TS_ERROR) {
LOG_ERROR("Error while writing invariant fields");
return false;
}
n_bytes_written += INVARIANT_FIELD_LINES_SIZE;
}
if (find(HEADER_WHITELIST.begin(), HEADER_WHITELIST.end(), TS_MIME_FIELD_LAST_MODIFIED) == HEADER_WHITELIST.end()) {
time_t time_now = static_cast<time_t>(TShrtime() / 1000000000); // it returns nanoseconds!
char last_modified_line[128];
int last_modified_line_size = strftime(last_modified_line, 128, "Last-Modified: %a, %d %b %Y %T GMT\r\n",
gmtime(&time_now));
if (TSIOBufferWrite(int_data.output.buffer, last_modified_line, last_modified_line_size) == TS_ERROR) {
LOG_ERROR("Error while writing last-modified fields");
return false;
}
n_bytes_written += last_modified_line_size;
}
return true;
}
static bool
writeErrorResponse(InterceptData &int_data, int &n_bytes_written)
{
const string *response;
switch (int_data.creq.status) {
case TS_HTTP_STATUS_BAD_REQUEST:
response = &BAD_REQUEST_RESPONSE;
break;
case TS_HTTP_STATUS_FORBIDDEN:
response = &FORBIDDEN_RESPONSE;
break;
default:
response = &ERROR_REPLY_RESPONSE;
break;
}
if (TSIOBufferWrite(int_data.output.buffer, response->data(), response->size()) == TS_ERROR) {
LOG_ERROR("Error while writing error response");
return false;
}
n_bytes_written += response->size();
return true;
}
TSRemapStatus
TSRemapDoRemap(void* ih, TSHttpTxn rh, TSRemapRequestInfo* rri)
{
TSHttpTxnArgSet(rh, arg_idx, (void*)1); /* Save for later hooks */
return TSREMAP_NO_REMAP; /* Continue with next remap plugin in chain */
}
/*
Initialize the plugin as a remap plugin.
*/
TSReturnCode
TSRemapInit(TSRemapInterface* api_info, char *errbuf, int errbuf_size)
{
if (!api_info) {
strncpy(errbuf, "[TSRemapInit] - Invalid TSRemapInterface argument", errbuf_size - 1);
return TS_ERROR;
}
if (api_info->size < sizeof(TSRemapInterface)) {
strncpy(errbuf, "[TSRemapInit] - Incorrect size of TSRemapInterface structure", errbuf_size - 1);
return TS_ERROR;
}
TSDebug(DEBUG_TAG, "%s plugin's remap part is initialized", DEBUG_TAG);
return TS_SUCCESS;
}
TSReturnCode
TSRemapNewInstance(int argc, char* argv[], void** ih, char* errbuf,
int errbuf_size)
{
*ih = NULL;
TSDebug(DEBUG_TAG, "%s Remap Instance for '%s' created", DEBUG_TAG, argv[0]);
return TS_SUCCESS;
}
void
TSRemapDeleteInstance(void* ih)
{
return;
}
|
/*******************************************************************************
Copyright(c) 2015-2018 LORD Corporation. All rights reserved.
MIT Licensed. See the included LICENSE.txt for a copy of the full MIT License.
*******************************************************************************/
#include "stdafx.h"
#include "DataModeMask.h"
namespace mscl
{
DataModeMask::DataModeMask(WirelessTypes::DataMode mode):
rawModeEnabled(false),
derivedModeEnabled(false)
{
switch(mode)
{
case WirelessTypes::dataMode_raw:
rawModeEnabled = true;
break;
case WirelessTypes::dataMode_derived:
derivedModeEnabled = true;
break;
case WirelessTypes::dataMode_raw_derived:
rawModeEnabled = true;
derivedModeEnabled = true;
break;
case WirelessTypes::dataMode_none:
default:
break;
}
}
DataModeMask::DataModeMask(const BitMask& mask):
rawModeEnabled(mask.enabled(dataModeBitPos_raw)),
derivedModeEnabled(mask.enabled(dataModeBitPos_derived))
{
}
BitMask DataModeMask::toMask() const
{
BitMask result;
if(rawModeEnabled)
{
result.enable(dataModeBitPos_raw, true);
}
if(derivedModeEnabled)
{
result.enable(dataModeBitPos_derived, true);
}
return result;
}
WirelessTypes::DataMode DataModeMask::toDataModeEnum() const
{
if(rawModeEnabled)
{
if(derivedModeEnabled)
{
return WirelessTypes::dataMode_raw_derived;
}
return WirelessTypes::dataMode_raw;
}
if(derivedModeEnabled)
{
return WirelessTypes::dataMode_derived;
}
return WirelessTypes::dataMode_none;
}
}
|
// Copyright (c) 2021 F. Lotfi & D. Kane All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
#include <algorithm>
#include <catch2/catch.hpp>
#include <fstream>
#include <glm/glm.hpp>
#include "fileParsers/imageExporter.h"
#include "fileParsers/model.h"
#include "raycast/camera.h"
#include "renderer/pathTracer.h"
#include "scene/scene.h"
// Note: I hate this code. it is only here b\c There is no way in
// std::filesystem to know the binary directory, just the working dir. Also
// std::filesystem refuses to make its way to AppleClang. Alternative is to take
// a dependency on Boost, which I refuse to do.
#if defined(WIN32) || defined(_WIN32) || defined(__WIN32__) || defined(__NT__)
#include <Windows.h>
std::string getDirectory() {
char buffer[MAX_PATH];
GetModuleFileNameA(nullptr, buffer, MAX_PATH);
std::string fullpath(buffer);
size_t beginIdx = fullpath.rfind('\\');
std::string dirPath = fullpath.substr(0, beginIdx);
beginIdx = dirPath.rfind('\\');
dirPath = dirPath.substr(0, beginIdx + 1);
return dirPath;
}
#elif __APPLE__
#include <mach-o/dyld.h>
std::string getDirectory() {
uint32_t bufSize = PATH_MAX + 1;
char dirNameBuffer[bufSize];
if (_NSGetExecutablePath(dirNameBuffer, &bufSize) == 0) {
// Buffer size is too small.
std::string fullpath(dirNameBuffer);
int beginIdx = fullpath.rfind('/');
std::string dirPath = fullpath.substr(0, beginIdx + 1);
return dirPath;
}
return "";
}
#elif __linux__
#include <unistd.h>
std::string getDirectory() {
char abs_path[1024];
int cnt = readlink("/proc/self/exe", abs_path, 1024);
// Get the absolute path of the executable program
if (cnt < 0 || cnt >= 1024) {
return "";
}
// The last '/' is followed by the executable name, remove devel/lib/m100/exe,
// and only keep the previous part of the path.
for (int i = cnt; i >= 0; --i) {
if (abs_path[i] == '/') {
abs_path[i + 1] = '\0';
break;
}
}
std::string path(abs_path);
return path;
}
#endif
// Note: We really just want to do a file hash here, but there is no built in
// library.
// TODO find a portable hashing library.
bool compare_files(const std::string &filename1, const std::string &filename2) {
std::ifstream file1(filename1,
std::ifstream::ate |
std::ifstream::binary); // open file at the end
std::ifstream file2(filename2,
std::ifstream::ate |
std::ifstream::binary); // open file at the end
const std::ifstream::pos_type fileSize = file1.tellg();
if (fileSize != file2.tellg()) {
return false; // different file size
}
file1.seekg(0); // rewind
file2.seekg(0); // rewind
std::istreambuf_iterator<char> begin1(file1);
std::istreambuf_iterator<char> begin2(file2);
return std::equal(begin1, std::istreambuf_iterator<char>(),
begin2); // Second argument is end-of-range iterator
}
glm::vec3 getColor(int index) {
glm::vec3 red(1, 0.701, 0.729);
glm::vec3 green(0.729, 1, 0.788);
glm::vec3 blue(0.729, 1, 1);
glm::vec3 purple(0.945, 0.835, 0.976);
glm::vec3 gray(0.31, 0.31, 0.31);
if (index % 2 == 0) {
return red;
}
if (index % 3 == 0) {
return green;
}
if (index % 5 == 0) {
return blue;
}
if (index % 7 == 0) {
return purple;
}
return gray;
}
void ReadObjToPixelBuffer(std::string filename,
std::string outFileName = "test.ppm",
bool setLight = false) {
Model model(filename.c_str());
glm::vec3 camOrign({0, 0, 2});
glm::vec3 camDir({0, 0, -1});
Camera cam;
cam.setOrigin(camOrign);
cam.setDirection(camDir);
cam.setFOV(90.0f);
Scene scene(cam);
glm::vec3 gray(0.31, 0.31, 0.31);
if (setLight) {
scene.addLight(camDir);
}
for (int i = 0; i < model.nfaces(); i++) {
std::vector<int> face = model.face(i);
if (face.size() == 3) {
glm::vec3 v1 = model.vert(face[0]);
glm::vec3 v2 = model.vert(face[1]);
glm::vec3 v3 = model.vert(face[2]);
if (setLight) {
scene.addTriangle(v1, v2, v3, gray);
} else {
scene.addTriangle(v1, v2, v3, getColor(i));
}
}
}
PathTracer pathTracer;
pathTracer.setScene(std::make_unique<Scene>(scene));
std::shared_ptr<PixelBuffer> pb =
std::make_shared<PixelBuffer>(320, 240, ColorChannels::RGB);
pathTracer.setPixelBuffer(pb);
pathTracer.renderScene();
ImageExport::exportAsPPM(outFileName, pb.get());
}
TEST_CASE("square Obj file Parse test", "[fileParsers][pixelBuffer]") {
ReadObjToPixelBuffer(getDirectory() + "objFiles/square.obj",
"squareTest.ppm");
REQUIRE(compare_files(getDirectory() + "sln/square.ppm", "squareTest.ppm"));
}
TEST_CASE("cube obj file parser test", "[fileParsers][pixelBuffer]") {
ReadObjToPixelBuffer(getDirectory() + "objFiles/cube.obj", "cubeTest.ppm");
REQUIRE(compare_files(getDirectory() + "sln/cube.ppm", "cubeTest.ppm"));
}
TEST_CASE("head obj file parser test", "[fileParsers][pixelBuffer]") {
ReadObjToPixelBuffer(getDirectory() + "objFiles/african_head.obj",
"headTest.ppm");
REQUIRE(compare_files(getDirectory() + "sln/head.ppm", "headTest.ppm"));
}
TEST_CASE("monkey obj file parser test", "[fileParsers][pixelBuffer]") {
ReadObjToPixelBuffer(getDirectory() + "objFiles/monkey.obj",
"monkeyTest.ppm");
REQUIRE(compare_files(getDirectory() + "sln/monkey.ppm", "monkeyTest.ppm"));
}
TEST_CASE("diablo obj file parser test", "[fileParsers][pixelBuffer]") {
ReadObjToPixelBuffer(getDirectory() + "objFiles/diablo3_pose.obj",
"diabloTest.ppm");
REQUIRE(compare_files(getDirectory() + "sln/diablo.ppm", "diabloTest.ppm"));
}
TEST_CASE("Pyramid obj file parser test", "[fileParsers][pixelBuffer]") {
ReadObjToPixelBuffer(getDirectory() + "objFiles/pyramid.obj",
"pyramidTest.ppm");
REQUIRE(compare_files(getDirectory() + "sln/pyramid.ppm", "pyramidTest.ppm"));
}
TEST_CASE("head obj file parser light test", "[fileParsers][pixelBuffer]") {
ReadObjToPixelBuffer(getDirectory() + "objFiles/african_head.obj",
"headLightTest.ppm", true);
REQUIRE(
compare_files(getDirectory() + "sln/headLight.ppm", "headLightTest.ppm"));
}
TEST_CASE("monkey obj file parser light test", "[fileParsers][pixelBuffer]") {
ReadObjToPixelBuffer(getDirectory() + "objFiles/monkey.obj",
"monkeyLightTest.ppm", true);
REQUIRE(compare_files(getDirectory() + "sln/monkeyLight.ppm",
"monkeyLightTest.ppm"));
}
TEST_CASE("diablo obj file parser light test", "[fileParsers][pixelBuffer]") {
ReadObjToPixelBuffer(getDirectory() + "objFiles/diablo3_pose.obj",
"diabloLightTest.ppm", true);
REQUIRE(compare_files(getDirectory() + "sln/diabloLight.ppm",
"diabloLightTest.ppm"));
}
|
#include "LightIcon.h"
#include <stdexcept>
#include <glm/gtc/matrix_transform.hpp>
#define DIRLIGHT_ICON_POS_HEIGHT 5.0f
#define DIRLIGHT_ICON_OFFSET_FACTOR 3.0f
#define LIGHT_ICON_SIZE 256.0f
#define LIGHT_ICON_IMAGE "light-icons.png"
LightIcon::LightIcon(LightSptr light) : LightIcon(nullptr, light) {}
LightIcon::LightIcon(const std::shared_ptr<GameObject> &owner, LightSptr light) : Component(owner) {
auto transform = m_owner->GetComponent<Transform>();
transform->setPosition(light->transform().getPosition());
glm::vec2 texIndices = {1, 1};
m_lightColor = glm::vec4(light->getColor(), 1.0f);
if (dynamic_cast<DirectionalLight *>(light.get()) != nullptr) {
// Position for directional lights is in a fixed location (with offset for light direction),
// rather than at light location itself
transform->setPosition(transform->getFront() * DIRLIGHT_ICON_OFFSET_FACTOR +
glm::vec3(0.0f, DIRLIGHT_ICON_POS_HEIGHT, 0.0f));
texIndices = {0, 0};
} else if (dynamic_cast<PointLight *>(light.get()) != nullptr) {
texIndices = {0, 1};
} else if (dynamic_cast<SpotLight *>(light.get()) != nullptr) {
texIndices = {1, 0};
}
m_texture = ResourceManager<Texture>::Get(LIGHT_ICON_IMAGE);
// Calculate icon texture coordinates and set them accordingly
GLfloat texW = LIGHT_ICON_SIZE / m_texture->getWidth();
GLfloat texH = LIGHT_ICON_SIZE / m_texture->getHeight();
GLfloat texX = texIndices.x * texW;
GLfloat texY = texIndices.y * texH;
// Configure VAO / VBO for texture quads and bind buffer data
GLfloat vertices[4][4] = {
{0, 0, texX, texY + texH}, // bottom-left
{1, 0, texX + texW, texY + texH}, // top-left
{0, 1, texX, texY}, // bottom-right
{1, 1, texX + texW, texY} // top-right
};
glGenVertexArrays(1, &m_VAO);
glBindVertexArray(m_VAO);
glGenBuffers(1, &m_VBO);
{
glBindBuffer(GL_ARRAY_BUFFER, m_VBO);
glBufferData(GL_ARRAY_BUFFER, sizeof(vertices), vertices, GL_STATIC_DRAW);
glEnableVertexAttribArray(0);
glVertexAttribPointer(0, 4, GL_FLOAT, GL_FALSE, 0, 0);
}
}
// Draws a light icon onto the screen
void LightIcon::draw(ERROR &errCode, const Shader &shader) {
// Pass shader parameters
shader.setVec4("color", m_lightColor);
shader.setMat4(
"model", glm::translate(glm::mat4(1.0f), m_owner->GetComponent<Transform>()->getPosition()));
// Use texture and draw vertices
m_texture->use();
glBindVertexArray(m_VAO);
glDrawArrays(GL_TRIANGLE_STRIP, 0, 4);
}
|
/*
* Copyright (c) 2020 Samsung Electronics Co., Ltd.
*
* 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.
*
*/
// CLASS HEADER
#include <dali/internal/event/events/event-processor.h>
// INTERNAL INCLUDES
#include <dali/integration-api/debug.h>
#include <dali/integration-api/events/event.h>
#include <dali/integration-api/events/key-event-integ.h>
#include <dali/integration-api/events/wheel-event-integ.h>
#include <dali/integration-api/events/touch-event-integ.h>
#include <dali/integration-api/events/hover-event-integ.h>
#include <dali/internal/event/events/gesture-event-processor.h>
#include <dali/internal/common/core-impl.h>
#include <dali/internal/event/common/notification-manager.h>
using Dali::Integration::Event;
namespace Dali
{
namespace Internal
{
namespace // unnamed namespace
{
static const std::size_t MAX_MESSAGE_SIZE = std::max( sizeof(Integration::TouchEvent),
std::max( sizeof(Integration::KeyEvent), sizeof(Integration::WheelEvent) ) );
static const std::size_t INITIAL_MIN_CAPACITY = 4;
static const std::size_t INITIAL_BUFFER_SIZE = MAX_MESSAGE_SIZE * INITIAL_MIN_CAPACITY;
} // unnamed namespace
EventProcessor::EventProcessor( Scene& scene, GestureEventProcessor& gestureEventProcessor )
: mScene( scene ),
mTouchEventProcessor( scene ),
mHoverEventProcessor( scene ),
mGestureEventProcessor( gestureEventProcessor ),
mKeyEventProcessor( scene ),
mWheelEventProcessor( scene ),
mEventQueue0( INITIAL_BUFFER_SIZE ),
mEventQueue1( INITIAL_BUFFER_SIZE ),
mCurrentEventQueue( &mEventQueue0 )
{
}
EventProcessor::~EventProcessor()
{
for( MessageBuffer::Iterator iter = mEventQueue0.Begin(); iter.IsValid(); iter.Next() )
{
// Call virtual destructor explictly; since delete will not be called after placement new
Event* event = reinterpret_cast< Event* >( iter.Get() );
event->~Event();
}
for( MessageBuffer::Iterator iter = mEventQueue1.Begin(); iter.IsValid(); iter.Next() )
{
// Call virtual destructor explictly; since delete will not be called after placement new
Event* event = reinterpret_cast< Event* >( iter.Get() );
event->~Event();
}
}
void EventProcessor::QueueEvent( const Event& event )
{
switch( event.type )
{
case Event::Touch:
{
typedef Integration::TouchEvent DerivedType;
// Reserve some memory inside the message queue
uint32_t* slot = mCurrentEventQueue->ReserveMessageSlot( sizeof( DerivedType ) );
// Construct message in the message queue memory; note that delete should not be called on the return value
new (slot) DerivedType( static_cast<const DerivedType&>(event) );
break;
}
case Event::Hover:
{
using DerivedType = Integration::HoverEvent;
// Reserve some memory inside the message queue
uint32_t* slot = mCurrentEventQueue->ReserveMessageSlot( sizeof( DerivedType ) );
// Construct message in the message queue memory; note that delete should not be called on the return value
new (slot) DerivedType( static_cast<const DerivedType&>(event) );
break;
}
case Event::Key:
{
using DerivedType = Integration::KeyEvent;
// Reserve some memory inside the message queue
uint32_t* slot = mCurrentEventQueue->ReserveMessageSlot( sizeof( DerivedType ) );
// Construct message in the message queue memory; note that delete should not be called on the return value
new (slot) DerivedType( static_cast<const DerivedType&>(event) );
break;
}
case Event::Wheel:
{
using DerivedType = Integration::WheelEvent;
// Reserve some memory inside the message queue
uint32_t* slot = mCurrentEventQueue->ReserveMessageSlot( sizeof( DerivedType ) );
// Construct message in the message queue memory; note that delete should not be called on the return value
new (slot) DerivedType( static_cast<const DerivedType&>(event) );
break;
}
}
}
void EventProcessor::ProcessEvents()
{
MessageBuffer* queueToProcess = mCurrentEventQueue;
// Switch current queue; events can be added safely while iterating through the other queue.
mCurrentEventQueue = ( &mEventQueue0 == mCurrentEventQueue ) ? &mEventQueue1 : &mEventQueue0;
for( MessageBuffer::Iterator iter = queueToProcess->Begin(); iter.IsValid(); iter.Next() )
{
Event* event = reinterpret_cast< Event* >( iter.Get() );
switch( event->type )
{
case Event::Touch:
{
Integration::TouchEvent& touchEvent = static_cast<Integration::TouchEvent&>(*event);
const bool consumed = mTouchEventProcessor.ProcessTouchEvent( touchEvent );
// If touch is consumed, then gestures should be cancelled
// Do this by sending an interrupted event to the GestureEventProcessor
if( consumed )
{
Integration::Point& point = touchEvent.GetPoint(0);
point.SetState( PointState::INTERRUPTED );
}
mGestureEventProcessor.ProcessTouchEvent(mScene, touchEvent);
break;
}
case Event::Hover:
{
mHoverEventProcessor.ProcessHoverEvent( static_cast<const Integration::HoverEvent&>(*event) );
break;
}
case Event::Key:
{
mKeyEventProcessor.ProcessKeyEvent( static_cast<const Integration::KeyEvent&>(*event) );
break;
}
case Event::Wheel:
{
mWheelEventProcessor.ProcessWheelEvent( static_cast<const Integration::WheelEvent&>(*event) );
break;
}
}
// Call virtual destructor explictly; since delete will not be called after placement new
event->~Event();
}
queueToProcess->Reset();
}
} // namespace Internal
} // namespace Dali
|
// Copyright (c) 2017-2021 Thomas Fussell
//
// 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
//
// @license: http://www.opensource.org/licenses/mit-license.php
// @author: see AUTHORS file
#include <xlnt/utils/datetime.hpp>
#include <xlnt/utils/variant.hpp>
namespace xlnt {
variant::variant()
: type_(type::null)
{
}
variant::variant(const std::string &value)
: type_(type::lpstr),
lpstr_value_(value)
{
}
variant::variant(const char *value)
: variant(std::string(value))
{
}
variant::variant(int32_t value)
: type_(type::i4),
i4_value_(value)
{
}
variant::variant(bool value)
: type_(type::boolean),
i4_value_(value ? 1 : 0)
{
}
variant::variant(const datetime &value)
: type_(type::date),
lpstr_value_(value.to_iso_string())
{
}
variant::variant(const std::initializer_list<int> &value)
: type_(type::vector)
{
for (const auto &v : value)
{
vector_value_.emplace_back(v);
}
}
variant::variant(const std::vector<int> &value)
: type_(type::vector)
{
for (const auto &v : value)
{
vector_value_.emplace_back(v);
}
}
variant::variant(const std::initializer_list<const char *> &value)
: type_(type::vector)
{
for (const auto &v : value)
{
vector_value_.emplace_back(v);
}
}
variant::variant(const std::vector<const char *> &value)
: type_(type::vector)
{
for (const auto &v : value)
{
vector_value_.emplace_back(v);
}
}
variant::variant(const std::initializer_list<std::string> &value)
: type_(type::vector)
{
for (const auto &v : value)
{
vector_value_.emplace_back(v);
}
}
variant::variant(const std::vector<std::string> &value)
: type_(type::vector)
{
for (const auto &v : value)
{
vector_value_.emplace_back(v);
}
}
variant::variant(const std::vector<variant> &value)
: type_(type::vector)
{
for (const auto &v : value)
{
vector_value_.emplace_back(v);
}
}
bool variant::operator==(const variant &rhs) const
{
if (type_ != rhs.type_)
{
return false;
}
switch (type_)
{
case type::vector:
return vector_value_ == rhs.vector_value_;
case type::i4:
case type::boolean:
return i4_value_ == rhs.i4_value_;
case type::date:
case type::lpstr:
return lpstr_value_ == rhs.lpstr_value_;
case type::null:
return true;
}
return false;
}
bool variant::is(type t) const
{
return type_ == t;
}
template <>
XLNT_API std::string variant::get() const
{
return lpstr_value_;
}
template <>
XLNT_API std::vector<variant> variant::get() const
{
return vector_value_;
}
template <>
XLNT_API bool variant::get() const
{
return i4_value_ != 0;
}
template <>
XLNT_API std::int32_t variant::get() const
{
return i4_value_;
}
template <>
XLNT_API datetime variant::get() const
{
return datetime::from_iso_string(lpstr_value_);
}
variant::type variant::value_type() const
{
return type_;
}
} // namespace xlnt
|
// Copyright (c) 2012 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "components/policy/core/common/cloud/cloud_policy_validator.h"
#include <stddef.h>
#include <utility>
#include "base/bind_helpers.h"
#include "base/location.h"
#include "base/macros.h"
#include "base/metrics/histogram_macros.h"
#include "base/sequenced_task_runner.h"
#include "base/single_thread_task_runner.h"
#include "base/stl_util.h"
#include "base/threading/thread_task_runner_handle.h"
#include "build/build_config.h"
#include "components/policy/core/common/cloud/cloud_policy_constants.h"
#include "components/policy/proto/device_management_backend.pb.h"
#include "crypto/signature_verifier.h"
#include "google_apis/gaia/gaia_auth_util.h"
namespace em = enterprise_management;
namespace policy {
namespace {
// Grace interval for policy-from-the-future timestamp checks.
const int kTimestampGraceIntervalHours = 2;
const char kMetricPolicyKeyVerification[] = "Enterprise.PolicyKeyVerification";
enum MetricPolicyKeyVerification {
// Obsolete. Kept to avoid reuse, as this is used in histograms.
// UMA metric recorded when the client has no verification key.
METRIC_POLICY_KEY_VERIFICATION_KEY_MISSING_DEPRECATED,
// Recorded when the policy being verified has no key signature (e.g. policy
// fetched before the server supported the verification key).
METRIC_POLICY_KEY_VERIFICATION_SIGNATURE_MISSING,
// Recorded when the key signature did not match the expected value (in
// theory, this should only happen after key rotation or if the policy cached
// on disk has been modified).
METRIC_POLICY_KEY_VERIFICATION_FAILED,
// Recorded when key verification succeeded.
METRIC_POLICY_KEY_VERIFICATION_SUCCEEDED,
METRIC_POLICY_KEY_VERIFICATION_SIZE // Must be the last.
};
} // namespace
CloudPolicyValidatorBase::~CloudPolicyValidatorBase() {}
void CloudPolicyValidatorBase::ValidateTimestamp(
base::Time not_before,
base::Time now,
ValidateTimestampOption timestamp_option) {
validation_flags_ |= VALIDATE_TIMESTAMP;
timestamp_not_before_ =
(not_before - base::Time::UnixEpoch()).InMilliseconds();
timestamp_not_after_ =
((now + base::TimeDelta::FromHours(kTimestampGraceIntervalHours)) -
base::Time::UnixEpoch()).InMillisecondsRoundedUp();
timestamp_option_ = timestamp_option;
}
void CloudPolicyValidatorBase::ValidateUsername(
const std::string& expected_user,
bool canonicalize) {
validation_flags_ |= VALIDATE_USERNAME;
user_ = expected_user;
canonicalize_user_ = canonicalize;
}
void CloudPolicyValidatorBase::ValidateDomain(
const std::string& expected_domain) {
validation_flags_ |= VALIDATE_DOMAIN;
domain_ = gaia::CanonicalizeDomain(expected_domain);
}
void CloudPolicyValidatorBase::ValidateDMToken(
const std::string& expected_dm_token,
ValidateDMTokenOption dm_token_option) {
validation_flags_ |= VALIDATE_DM_TOKEN;
dm_token_ = expected_dm_token;
dm_token_option_ = dm_token_option;
}
void CloudPolicyValidatorBase::ValidateDeviceId(
const std::string& expected_device_id,
ValidateDeviceIdOption device_id_option) {
validation_flags_ |= VALIDATE_DEVICE_ID;
device_id_ = expected_device_id;
device_id_option_ = device_id_option;
}
void CloudPolicyValidatorBase::ValidatePolicyType(
const std::string& policy_type) {
validation_flags_ |= VALIDATE_POLICY_TYPE;
policy_type_ = policy_type;
}
void CloudPolicyValidatorBase::ValidateSettingsEntityId(
const std::string& settings_entity_id) {
validation_flags_ |= VALIDATE_ENTITY_ID;
settings_entity_id_ = settings_entity_id;
}
void CloudPolicyValidatorBase::ValidatePayload() {
validation_flags_ |= VALIDATE_PAYLOAD;
}
void CloudPolicyValidatorBase::ValidateCachedKey(
const std::string& cached_key,
const std::string& cached_key_signature,
const std::string& owning_domain) {
validation_flags_ |= VALIDATE_CACHED_KEY;
set_owning_domain(owning_domain);
cached_key_ = cached_key;
cached_key_signature_ = cached_key_signature;
}
void CloudPolicyValidatorBase::ValidateSignature(const std::string& key) {
validation_flags_ |= VALIDATE_SIGNATURE;
DCHECK(key_.empty() || key_ == key);
key_ = key;
}
void CloudPolicyValidatorBase::ValidateSignatureAllowingRotation(
const std::string& key,
const std::string& owning_domain) {
validation_flags_ |= VALIDATE_SIGNATURE;
DCHECK(key_.empty() || key_ == key);
key_ = key;
set_owning_domain(owning_domain);
allow_key_rotation_ = true;
}
void CloudPolicyValidatorBase::ValidateInitialKey(
const std::string& owning_domain) {
validation_flags_ |= VALIDATE_INITIAL_KEY;
set_owning_domain(owning_domain);
}
void CloudPolicyValidatorBase::ValidateAgainstCurrentPolicy(
const em::PolicyData* policy_data,
ValidateTimestampOption timestamp_option,
ValidateDMTokenOption dm_token_option,
ValidateDeviceIdOption device_id_option) {
base::Time last_policy_timestamp;
std::string expected_dm_token;
std::string expected_device_id;
if (policy_data) {
last_policy_timestamp =
base::Time::UnixEpoch() +
base::TimeDelta::FromMilliseconds(policy_data->timestamp());
expected_dm_token = policy_data->request_token();
expected_device_id = policy_data->device_id();
}
ValidateTimestamp(last_policy_timestamp, base::Time::NowFromSystemTime(),
timestamp_option);
ValidateDMToken(expected_dm_token, dm_token_option);
ValidateDeviceId(expected_device_id, device_id_option);
}
CloudPolicyValidatorBase::CloudPolicyValidatorBase(
std::unique_ptr<em::PolicyFetchResponse> policy_response,
google::protobuf::MessageLite* payload,
scoped_refptr<base::SequencedTaskRunner> background_task_runner)
: status_(VALIDATION_OK),
policy_(std::move(policy_response)),
payload_(payload),
validation_flags_(0),
timestamp_not_before_(0),
timestamp_not_after_(0),
timestamp_option_(TIMESTAMP_FULLY_VALIDATED),
dm_token_option_(DM_TOKEN_REQUIRED),
device_id_option_(DEVICE_ID_REQUIRED),
canonicalize_user_(false),
verification_key_(GetPolicyVerificationKey()),
allow_key_rotation_(false),
background_task_runner_(background_task_runner) {
DCHECK(!verification_key_.empty());
}
void CloudPolicyValidatorBase::PostValidationTask(
const base::Closure& completion_callback) {
background_task_runner_->PostTask(
FROM_HERE,
base::Bind(&CloudPolicyValidatorBase::PerformValidation,
base::Passed(std::unique_ptr<CloudPolicyValidatorBase>(this)),
base::ThreadTaskRunnerHandle::Get(), completion_callback));
}
// static
void CloudPolicyValidatorBase::PerformValidation(
std::unique_ptr<CloudPolicyValidatorBase> self,
scoped_refptr<base::SingleThreadTaskRunner> task_runner,
const base::Closure& completion_callback) {
// Run the validation activities on this thread.
self->RunValidation();
// Report completion on |task_runner|.
task_runner->PostTask(
FROM_HERE,
base::Bind(&CloudPolicyValidatorBase::ReportCompletion,
base::Passed(&self),
completion_callback));
}
// static
void CloudPolicyValidatorBase::ReportCompletion(
std::unique_ptr<CloudPolicyValidatorBase> self,
const base::Closure& completion_callback) {
completion_callback.Run();
}
void CloudPolicyValidatorBase::RunValidation() {
policy_data_.reset(new em::PolicyData());
RunChecks();
}
void CloudPolicyValidatorBase::RunChecks() {
status_ = VALIDATION_OK;
if ((policy_->has_error_code() && policy_->error_code() != 200) ||
(policy_->has_error_message() && !policy_->error_message().empty())) {
LOG(ERROR) << "Error in policy blob."
<< " code: " << policy_->error_code()
<< " message: " << policy_->error_message();
status_ = VALIDATION_ERROR_CODE_PRESENT;
return;
}
// Parse policy data.
if (!policy_data_->ParseFromString(policy_->policy_data()) ||
!policy_data_->IsInitialized()) {
LOG(ERROR) << "Failed to parse policy response";
status_ = VALIDATION_PAYLOAD_PARSE_ERROR;
return;
}
// Table of checks we run. These are sorted by descending severity of the
// error, s.t. the most severe check will determine the validation status.
static const struct {
int flag;
Status (CloudPolicyValidatorBase::* checkFunction)();
} kCheckFunctions[] = {
{ VALIDATE_SIGNATURE, &CloudPolicyValidatorBase::CheckSignature },
{ VALIDATE_INITIAL_KEY, &CloudPolicyValidatorBase::CheckInitialKey },
{ VALIDATE_CACHED_KEY, &CloudPolicyValidatorBase::CheckCachedKey },
{ VALIDATE_POLICY_TYPE, &CloudPolicyValidatorBase::CheckPolicyType },
{ VALIDATE_ENTITY_ID, &CloudPolicyValidatorBase::CheckEntityId },
{ VALIDATE_DM_TOKEN, &CloudPolicyValidatorBase::CheckDMToken },
{ VALIDATE_DEVICE_ID, &CloudPolicyValidatorBase::CheckDeviceId },
{ VALIDATE_USERNAME, &CloudPolicyValidatorBase::CheckUsername },
{ VALIDATE_DOMAIN, &CloudPolicyValidatorBase::CheckDomain },
{ VALIDATE_TIMESTAMP, &CloudPolicyValidatorBase::CheckTimestamp },
{ VALIDATE_PAYLOAD, &CloudPolicyValidatorBase::CheckPayload },
};
for (size_t i = 0; i < arraysize(kCheckFunctions); ++i) {
if (validation_flags_ & kCheckFunctions[i].flag) {
status_ = (this->*(kCheckFunctions[i].checkFunction))();
if (status_ != VALIDATION_OK)
break;
}
}
}
// Verifies the |new_public_key_verification_signature_deprecated| for the
// |new_public_key| in the policy blob.
bool CloudPolicyValidatorBase::CheckNewPublicKeyVerificationSignature() {
if (!policy_->has_new_public_key_verification_signature_deprecated()) {
// Policy does not contain a verification signature, so log an error.
LOG(ERROR) << "Policy is missing public_key_verification_signature";
UMA_HISTOGRAM_ENUMERATION(kMetricPolicyKeyVerification,
METRIC_POLICY_KEY_VERIFICATION_SIGNATURE_MISSING,
METRIC_POLICY_KEY_VERIFICATION_SIZE);
return false;
}
if (!CheckVerificationKeySignature(
policy_->new_public_key(),
verification_key_,
policy_->new_public_key_verification_signature_deprecated())) {
LOG(ERROR) << "Signature verification failed";
UMA_HISTOGRAM_ENUMERATION(kMetricPolicyKeyVerification,
METRIC_POLICY_KEY_VERIFICATION_FAILED,
METRIC_POLICY_KEY_VERIFICATION_SIZE);
return false;
}
// Signature verification succeeded - return success to the caller.
DVLOG(1) << "Signature verification succeeded";
UMA_HISTOGRAM_ENUMERATION(kMetricPolicyKeyVerification,
METRIC_POLICY_KEY_VERIFICATION_SUCCEEDED,
METRIC_POLICY_KEY_VERIFICATION_SIZE);
return true;
}
bool CloudPolicyValidatorBase::CheckVerificationKeySignature(
const std::string& key,
const std::string& verification_key,
const std::string& signature) {
DCHECK(!verification_key.empty());
em::DEPRECATEDPolicyPublicKeyAndDomain signed_data;
signed_data.set_new_public_key(key);
// If no owning_domain_ supplied, try extracting the domain from the policy
// itself (this happens on certain platforms during startup, when we validate
// cached policy before prefs are loaded).
std::string domain = owning_domain_.empty() ?
ExtractDomainFromPolicy() : owning_domain_;
if (domain.empty()) {
LOG(ERROR) << "Policy does not contain a domain";
return false;
}
signed_data.set_domain(domain);
std::string signed_data_as_string;
if (!signed_data.SerializeToString(&signed_data_as_string)) {
DLOG(ERROR) << "Could not serialize verification key to string";
return false;
}
return VerifySignature(signed_data_as_string, verification_key, signature,
SHA256);
}
std::string CloudPolicyValidatorBase::ExtractDomainFromPolicy() {
std::string domain;
if (policy_data_->has_username()) {
domain = gaia::ExtractDomainName(
gaia::CanonicalizeEmail(
gaia::SanitizeEmail(policy_data_->username())));
}
return domain;
}
void CloudPolicyValidatorBase::set_owning_domain(
const std::string& owning_domain) {
// Make sure we aren't overwriting the owning domain with a different one.
DCHECK(owning_domain_.empty() || owning_domain_ == owning_domain);
owning_domain_ = owning_domain;
}
CloudPolicyValidatorBase::Status CloudPolicyValidatorBase::CheckSignature() {
const std::string* signature_key = &key_;
if (policy_->has_new_public_key() && allow_key_rotation_) {
signature_key = &policy_->new_public_key();
if (!policy_->has_new_public_key_signature() ||
!VerifySignature(policy_->new_public_key(), key_,
policy_->new_public_key_signature(), SHA1)) {
LOG(ERROR) << "New public key rotation signature verification failed";
return VALIDATION_BAD_SIGNATURE;
}
if (!CheckNewPublicKeyVerificationSignature()) {
LOG(ERROR) << "New public key root verification failed";
return VALIDATION_BAD_KEY_VERIFICATION_SIGNATURE;
}
}
if (!policy_->has_policy_data_signature() ||
!VerifySignature(policy_->policy_data(), *signature_key,
policy_->policy_data_signature(), SHA1)) {
LOG(ERROR) << "Policy signature validation failed";
return VALIDATION_BAD_SIGNATURE;
}
return VALIDATION_OK;
}
CloudPolicyValidatorBase::Status CloudPolicyValidatorBase::CheckInitialKey() {
if (!policy_->has_new_public_key() ||
!policy_->has_policy_data_signature() ||
!VerifySignature(policy_->policy_data(), policy_->new_public_key(),
policy_->policy_data_signature(), SHA1)) {
LOG(ERROR) << "Initial policy signature validation failed";
return VALIDATION_BAD_INITIAL_SIGNATURE;
}
if (!CheckNewPublicKeyVerificationSignature()) {
LOG(ERROR) << "Initial policy root signature validation failed";
return VALIDATION_BAD_KEY_VERIFICATION_SIGNATURE;
}
return VALIDATION_OK;
}
CloudPolicyValidatorBase::Status CloudPolicyValidatorBase::CheckCachedKey() {
if (!CheckVerificationKeySignature(cached_key_, verification_key_,
cached_key_signature_)) {
LOG(ERROR) << "Cached key signature verification failed";
return VALIDATION_BAD_KEY_VERIFICATION_SIGNATURE;
} else {
DVLOG(1) << "Cached key signature verification succeeded";
}
return VALIDATION_OK;
}
CloudPolicyValidatorBase::Status CloudPolicyValidatorBase::CheckPolicyType() {
if (!policy_data_->has_policy_type() ||
policy_data_->policy_type() != policy_type_) {
LOG(ERROR) << "Wrong policy type " << policy_data_->policy_type();
return VALIDATION_WRONG_POLICY_TYPE;
}
return VALIDATION_OK;
}
CloudPolicyValidatorBase::Status CloudPolicyValidatorBase::CheckEntityId() {
if (!policy_data_->has_settings_entity_id() ||
policy_data_->settings_entity_id() != settings_entity_id_) {
LOG(ERROR) << "Wrong settings_entity_id "
<< policy_data_->settings_entity_id() << ", expected "
<< settings_entity_id_;
return VALIDATION_WRONG_SETTINGS_ENTITY_ID;
}
return VALIDATION_OK;
}
CloudPolicyValidatorBase::Status CloudPolicyValidatorBase::CheckTimestamp() {
if (timestamp_option_ == TIMESTAMP_NOT_VALIDATED)
return VALIDATION_OK;
if (!policy_data_->has_timestamp()) {
LOG(ERROR) << "Policy timestamp missing";
return VALIDATION_BAD_TIMESTAMP;
}
if (policy_data_->timestamp() < timestamp_not_before_) {
LOG(ERROR) << "Policy too old: " << policy_data_->timestamp();
return VALIDATION_BAD_TIMESTAMP;
}
// Limit the damage in case of an unlikely server bug: If the server
// accidentally sends a time from the distant future, this time is stored
// locally and after the server time is corrected, due to rollback prevention
// the client could not receive policy updates until that future date.
if (timestamp_option_ == TIMESTAMP_FULLY_VALIDATED &&
policy_data_->timestamp() > timestamp_not_after_) {
LOG(ERROR) << "Policy from the future: " << policy_data_->timestamp();
return VALIDATION_BAD_TIMESTAMP;
}
return VALIDATION_OK;
}
CloudPolicyValidatorBase::Status CloudPolicyValidatorBase::CheckDMToken() {
if (dm_token_option_ == DM_TOKEN_REQUIRED &&
(!policy_data_->has_request_token() ||
policy_data_->request_token().empty())) {
LOG(ERROR) << "Empty DM token encountered - expected: " << dm_token_;
return VALIDATION_BAD_DM_TOKEN;
}
if (!dm_token_.empty() && policy_data_->request_token() != dm_token_) {
LOG(ERROR) << "Invalid DM token: " << policy_data_->request_token()
<< " - expected: " << dm_token_;
return VALIDATION_BAD_DM_TOKEN;
}
return VALIDATION_OK;
}
CloudPolicyValidatorBase::Status CloudPolicyValidatorBase::CheckDeviceId() {
if (device_id_option_ == DEVICE_ID_REQUIRED &&
(!policy_data_->has_device_id() ||
policy_data_->device_id().empty())) {
LOG(ERROR) << "Empty device id encountered - expected: " << device_id_;
return VALIDATION_BAD_DEVICE_ID;
}
if (!device_id_.empty() && policy_data_->device_id() != device_id_) {
LOG(ERROR) << "Invalid device id: " << policy_data_->device_id()
<< " - expected: " << device_id_;
return VALIDATION_BAD_DEVICE_ID;
}
return VALIDATION_OK;
}
CloudPolicyValidatorBase::Status CloudPolicyValidatorBase::CheckUsername() {
if (!policy_data_->has_username()) {
LOG(ERROR) << "Policy is missing user name";
return VALIDATION_BAD_USERNAME;
}
std::string expected = user_;
std::string actual = policy_data_->username();
if (canonicalize_user_) {
expected = gaia::CanonicalizeEmail(gaia::SanitizeEmail(expected));
actual = gaia::CanonicalizeEmail(gaia::SanitizeEmail(actual));
}
if (expected != actual) {
LOG(ERROR) << "Invalid user name " << policy_data_->username();
return VALIDATION_BAD_USERNAME;
}
return VALIDATION_OK;
}
CloudPolicyValidatorBase::Status CloudPolicyValidatorBase::CheckDomain() {
std::string policy_domain = ExtractDomainFromPolicy();
if (policy_domain.empty()) {
LOG(ERROR) << "Policy is missing user name";
return VALIDATION_BAD_USERNAME;
}
if (domain_ != policy_domain) {
LOG(ERROR) << "Invalid user name " << policy_data_->username();
return VALIDATION_BAD_USERNAME;
}
return VALIDATION_OK;
}
CloudPolicyValidatorBase::Status CloudPolicyValidatorBase::CheckPayload() {
if (!policy_data_->has_policy_value() ||
!payload_->ParseFromString(policy_data_->policy_value()) ||
!payload_->IsInitialized()) {
LOG(ERROR) << "Failed to decode policy payload protobuf";
return VALIDATION_POLICY_PARSE_ERROR;
}
return VALIDATION_OK;
}
// static
bool CloudPolicyValidatorBase::VerifySignature(const std::string& data,
const std::string& key,
const std::string& signature,
SignatureType signature_type) {
crypto::SignatureVerifier verifier;
crypto::SignatureVerifier::SignatureAlgorithm algorithm;
switch (signature_type) {
case SHA1:
algorithm = crypto::SignatureVerifier::RSA_PKCS1_SHA1;
break;
case SHA256:
algorithm = crypto::SignatureVerifier::RSA_PKCS1_SHA256;
break;
default:
NOTREACHED() << "Invalid signature type: " << signature_type;
return false;
}
if (!verifier.VerifyInit(
algorithm, reinterpret_cast<const uint8_t*>(signature.c_str()),
signature.size(), reinterpret_cast<const uint8_t*>(key.c_str()),
key.size())) {
DLOG(ERROR) << "Invalid verification signature/key format";
return false;
}
verifier.VerifyUpdate(reinterpret_cast<const uint8_t*>(data.c_str()),
data.size());
return verifier.VerifyFinal();
}
template class CloudPolicyValidator<em::CloudPolicySettings>;
#if !defined(OS_ANDROID) && !defined(OS_IOS)
template class CloudPolicyValidator<em::ExternalPolicyData>;
#endif
} // namespace policy
|
#include <QtWidgets>
#include <QList>
#include <QPrinter>
#include <QPrintDialog>
#include <QPainter>
#include "vmainwindow.h"
#include "vdirectorytree.h"
#include "vnote.h"
#include "vfilelist.h"
#include "vconfigmanager.h"
#include "utils/vutils.h"
#include "veditarea.h"
#include "voutline.h"
#include "vnotebookselector.h"
#include "dialog/vfindreplacedialog.h"
#include "dialog/vsettingsdialog.h"
#include "vcaptain.h"
#include "vedittab.h"
#include "vwebview.h"
#include "vexporter.h"
#include "vmdtab.h"
#include "vvimindicator.h"
#include "vvimcmdlineedit.h"
#include "vtabindicator.h"
#include "dialog/vupdater.h"
#include "vorphanfile.h"
#include "dialog/vorphanfileinfodialog.h"
#include "vsingleinstanceguard.h"
#include "vnotefile.h"
#include "vbuttonwithwidget.h"
#include "vattachmentlist.h"
#include "vfilesessioninfo.h"
#include "vsnippetlist.h"
#include "vtoolbox.h"
#include "vbuttonmenuitem.h"
#include "vpalette.h"
#include "utils/viconutils.h"
#include "dialog/vtipsdialog.h"
#include "vcart.h"
#include "dialog/vexportdialog.h"
#include "vsearcher.h"
#include "vuniversalentry.h"
#include "vsearchue.h"
#include "voutlineue.h"
#include "vhelpue.h"
#include "vlistfolderue.h"
#include "dialog/vfixnotebookdialog.h"
#include "vhistorylist.h"
#include "vexplorer.h"
#include "vlistue.h"
#include "vtagexplorer.h"
extern VConfigManager *g_config;
extern VPalette *g_palette;
VMainWindow *g_mainWin;
VNote *g_vnote;
VWebUtils *g_webUtils;
const int VMainWindow::c_sharedMemTimerInterval = 1000;
#if defined(QT_NO_DEBUG)
extern QFile g_logFile;
#endif
#define COLOR_PIXMAP_ICON_SIZE 64
enum NaviBoxIndex
{
NotebookPanel = 0,
HistoryList,
Explorer,
TagExplorer
};
VMainWindow::VMainWindow(VSingleInstanceGuard *p_guard, QWidget *p_parent)
: QMainWindow(p_parent),
m_guard(p_guard),
m_windowOldState(Qt::WindowNoState),
m_requestQuit(false),
m_printer(NULL),
m_ue(NULL)
{
qsrand(QDateTime::currentDateTime().toTime_t());
g_mainWin = this;
setWindowIcon(QIcon(":/resources/icons/vnote.ico"));
vnote = new VNote(this);
g_vnote = vnote;
m_webUtils.init();
g_webUtils = &m_webUtils;
initCaptain();
setupUI();
initMenuBar();
initToolBar();
initShortcuts();
initDockWindows();
restoreStateAndGeometry();
setContextMenuPolicy(Qt::NoContextMenu);
m_notebookSelector->update();
initSharedMemoryWatcher();
registerCaptainAndNavigationTargets();
}
void VMainWindow::initSharedMemoryWatcher()
{
m_sharedMemTimer = new QTimer(this);
m_sharedMemTimer->setSingleShot(false);
m_sharedMemTimer->setInterval(c_sharedMemTimerInterval);
connect(m_sharedMemTimer, &QTimer::timeout,
this, &VMainWindow::checkSharedMemory);
m_sharedMemTimer->start();
}
void VMainWindow::initCaptain()
{
// VCaptain should be visible to accpet key focus. But VCaptain
// may hide other widgets.
m_captain = new VCaptain(this);
connect(m_captain, &VCaptain::captainModeChanged,
this, [this](bool p_captainMode) {
static QString normalStyle = m_avatarBtn->styleSheet();
static QString captainStyle = QString("color: %1; background: %2;")
.arg(g_palette->color("avatar_captain_mode_fg"))
.arg(g_palette->color("avatar_captain_mode_bg"));
if (p_captainMode) {
m_avatarBtn->setStyleSheet(captainStyle);
} else {
m_avatarBtn->setStyleSheet(normalStyle);
}
});
}
void VMainWindow::registerCaptainAndNavigationTargets()
{
m_captain->registerNavigationTarget(m_naviBox);
m_captain->registerNavigationTarget(m_notebookSelector);
m_captain->registerNavigationTarget(m_dirTree);
m_captain->registerNavigationTarget(m_fileList);
m_captain->registerNavigationTarget(m_historyList);
m_tagExplorer->registerNavigationTarget();
m_captain->registerNavigationTarget(m_editArea);
m_tabIndicator->registerNavigationTarget();
m_captain->registerNavigationTarget(m_toolBox);
m_captain->registerNavigationTarget(outline);
m_captain->registerNavigationTarget(m_snippetList);
m_captain->registerNavigationTarget(m_cart);
m_captain->registerNavigationTarget(m_searcher);
// Register Captain mode targets.
m_captain->registerCaptainTarget(tr("AttachmentList"),
g_config->getCaptainShortcutKeySequence("AttachmentList"),
this,
showAttachmentListByCaptain);
m_captain->registerCaptainTarget(tr("LocateCurrentFile"),
g_config->getCaptainShortcutKeySequence("LocateCurrentFile"),
this,
locateCurrentFileByCaptain);
m_captain->registerCaptainTarget(tr("ExpandMode"),
g_config->getCaptainShortcutKeySequence("ExpandMode"),
this,
toggleExpandModeByCaptain);
m_captain->registerCaptainTarget(tr("DiscardAndRead"),
g_config->getCaptainShortcutKeySequence("DiscardAndRead"),
this,
discardAndReadByCaptain);
m_captain->registerCaptainTarget(tr("ToolBar"),
g_config->getCaptainShortcutKeySequence("ToolBar"),
this,
toggleToolBarByCaptain);
m_captain->registerCaptainTarget(tr("ToolsDock"),
g_config->getCaptainShortcutKeySequence("ToolsDock"),
this,
toggleToolsDockByCaptain);
m_captain->registerCaptainTarget(tr("SearchDock"),
g_config->getCaptainShortcutKeySequence("SearchDock"),
this,
toggleSearchDockByCaptain);
m_captain->registerCaptainTarget(tr("CloseNote"),
g_config->getCaptainShortcutKeySequence("CloseNote"),
this,
closeFileByCaptain);
m_captain->registerCaptainTarget(tr("ShortcutsHelp"),
g_config->getCaptainShortcutKeySequence("ShortcutsHelp"),
this,
shortcutsHelpByCaptain);
m_captain->registerCaptainTarget(tr("FlushLogFile"),
g_config->getCaptainShortcutKeySequence("FlushLogFile"),
this,
flushLogFileByCaptain);
m_captain->registerCaptainTarget(tr("Export"),
g_config->getCaptainShortcutKeySequence("Export"),
this,
exportByCaptain);
m_captain->registerCaptainTarget(tr("FocusEditArea"),
g_config->getCaptainShortcutKeySequence("FocusEditArea"),
this,
focusEditAreaByCaptain);
}
void VMainWindow::setupUI()
{
setupNaviBox();
m_editArea = new VEditArea();
m_editArea->setSizePolicy(QSizePolicy::Expanding, QSizePolicy::Expanding);
m_findReplaceDialog = m_editArea->getFindReplaceDialog();
m_fileList->setEditArea(m_editArea);
m_dirTree->setEditArea(m_editArea);
connect(m_editArea, &VEditArea::fileClosed,
m_historyList, &VHistoryList::addFile);
// Main Splitter
m_mainSplitter = new QSplitter();
m_mainSplitter->setObjectName("MainSplitter");
m_mainSplitter->addWidget(m_naviBox);
m_mainSplitter->addWidget(m_editArea);
m_mainSplitter->setStretchFactor(0, 0);
m_mainSplitter->setStretchFactor(1, 1);
connect(m_dirTree, &VDirectoryTree::directoryUpdated,
m_editArea, &VEditArea::handleDirectoryUpdated);
connect(m_notebookSelector, &VNotebookSelector::notebookUpdated,
m_editArea, &VEditArea::handleNotebookUpdated);
connect(m_notebookSelector, &VNotebookSelector::notebookCreated,
m_dirTree, [this](const QString &p_name, bool p_import) {
Q_UNUSED(p_name);
if (!p_import) {
m_dirTree->newRootDirectory();
}
});
connect(m_fileList, &VFileList::fileClicked,
m_editArea, &VEditArea::openFile);
connect(m_fileList, &VFileList::fileCreated,
m_editArea, &VEditArea::openFile);
connect(m_fileList, &VFileList::fileUpdated,
m_editArea, &VEditArea::handleFileUpdated);
connect(m_editArea, &VEditArea::tabStatusUpdated,
this, &VMainWindow::handleAreaTabStatusUpdated);
connect(m_editArea, &VEditArea::statusMessage,
this, &VMainWindow::showStatusMessage);
connect(m_editArea, &VEditArea::vimStatusUpdated,
this, &VMainWindow::handleVimStatusUpdated);
connect(m_findReplaceDialog, &VFindReplaceDialog::findTextChanged,
this, &VMainWindow::handleFindDialogTextChanged);
setCentralWidget(m_mainSplitter);
initVimCmd();
m_vimIndicator = new VVimIndicator(this);
m_vimIndicator->hide();
m_tabIndicator = new VTabIndicator(this);
m_tabIndicator->hide();
// Create and show the status bar
statusBar()->addPermanentWidget(m_vimCmd);
statusBar()->addPermanentWidget(m_vimIndicator);
statusBar()->addPermanentWidget(m_tabIndicator);
initTrayIcon();
}
void VMainWindow::setupNaviBox()
{
m_naviBox = new VToolBox();
setupNotebookPanel();
m_naviBox->addItem(m_nbSplitter,
":/resources/icons/notebook.svg",
tr("Notebooks"),
m_dirTree);
m_historyList = new VHistoryList();
m_naviBox->addItem(m_historyList,
":/resources/icons/history.svg",
tr("History"));
m_explorer = new VExplorer();
m_naviBox->addItem(m_explorer,
":/resources/icons/explorer.svg",
tr("Explorer"));
m_tagExplorer = new VTagExplorer();
m_naviBox->addItem(m_tagExplorer,
":/resources/icons/tag_explorer.svg",
tr("Tags"));
connect(m_notebookSelector, &VNotebookSelector::curNotebookChanged,
m_tagExplorer, &VTagExplorer::setNotebook);
}
void VMainWindow::setupNotebookPanel()
{
m_notebookSelector = new VNotebookSelector();
m_notebookSelector->setObjectName("NotebookSelector");
m_notebookSelector->setSizeAdjustPolicy(QComboBox::AdjustToMinimumContentsLengthWithIcon);
// Folders.
QLabel *directoryLabel = new QLabel(tr("Folders"));
directoryLabel->setProperty("TitleLabel", true);
m_dirTree = new VDirectoryTree;
QVBoxLayout *naviLayout = new QVBoxLayout;
naviLayout->addWidget(m_notebookSelector);
naviLayout->addWidget(directoryLabel);
naviLayout->addWidget(m_dirTree);
naviLayout->setContentsMargins(0, 0, 0, 0);
naviLayout->setSpacing(0);
QWidget *naviWidget = new QWidget();
naviWidget->setLayout(naviLayout);
// Notes.
m_fileList = new VFileList();
m_fileList->setSizePolicy(QSizePolicy::Maximum, QSizePolicy::Expanding);
m_nbSplitter = new QSplitter();
m_nbSplitter->setOrientation(Qt::Vertical);
m_nbSplitter->setObjectName("NotebookSplitter");
m_nbSplitter->addWidget(naviWidget);
m_nbSplitter->addWidget(m_fileList);
m_nbSplitter->setStretchFactor(0, 0);
m_nbSplitter->setStretchFactor(1, 1);
connect(m_notebookSelector, &VNotebookSelector::curNotebookChanged,
this, [this](VNotebook *p_notebook) {
m_dirTree->setNotebook(p_notebook);
m_dirTree->setFocus();
});
connect(m_notebookSelector, &VNotebookSelector::curNotebookChanged,
this, &VMainWindow::handleCurrentNotebookChanged);
connect(m_dirTree, &VDirectoryTree::currentDirectoryChanged,
this, &VMainWindow::handleCurrentDirectoryChanged);
connect(m_dirTree, &VDirectoryTree::currentDirectoryChanged,
m_fileList, &VFileList::setDirectory);
}
void VMainWindow::initToolBar()
{
const int tbIconSize = g_config->getToolBarIconSize() * VUtils::calculateScaleFactor();
QSize iconSize(tbIconSize, tbIconSize);
m_toolBars.append(initFileToolBar(iconSize));
m_toolBars.append(initViewToolBar(iconSize));
m_toolBars.append(initEditToolBar(iconSize));
m_toolBars.append(initNoteToolBar(iconSize));
setToolBarVisible(g_config->getToolBarChecked());
}
QToolBar *VMainWindow::initViewToolBar(QSize p_iconSize)
{
QToolBar *viewToolBar = addToolBar(tr("View"));
viewToolBar->setObjectName("ViewToolBar");
viewToolBar->setMovable(false);
if (p_iconSize.isValid()) {
viewToolBar->setIconSize(p_iconSize);
}
QAction *fullScreenAct = new QAction(VIconUtils::toolButtonIcon(":/resources/icons/fullscreen.svg"),
tr("Full Screen"),
this);
QString keySeq = g_config->getShortcutKeySequence("FullScreen");
QKeySequence seq(keySeq);
if (!seq.isEmpty()) {
fullScreenAct->setText(tr("Full Screen\t%1").arg(VUtils::getShortcutText(keySeq)));
fullScreenAct->setShortcut(seq);
}
fullScreenAct->setStatusTip(tr("Toggle full screen"));
connect(fullScreenAct, &QAction::triggered,
this, [this]() {
if (windowState() & Qt::WindowFullScreen) {
if (m_windowOldState & Qt::WindowMaximized) {
showMaximized();
} else {
showNormal();
}
} else {
showFullScreen();
}
});
QAction *stayOnTopAct = new QAction(VIconUtils::toolButtonIcon(":/resources/icons/stay_on_top.svg"),
tr("Stay On Top"),
this);
stayOnTopAct->setStatusTip(tr("Toggle stay-on-top"));
stayOnTopAct->setCheckable(true);
connect(stayOnTopAct, &QAction::triggered,
this, &VMainWindow::stayOnTop);
QAction *menuBarAct = new QAction(VIconUtils::toolButtonIcon(":/resources/icons/menubar.svg"),
tr("Menu Bar"),
this);
menuBarAct->setStatusTip(tr("Toggle menu bar"));
menuBarAct->setCheckable(true);
menuBarAct->setChecked(g_config->getMenuBarChecked());
connect(menuBarAct, &QAction::triggered,
this, [this](bool p_checked) {
setMenuBarVisible(p_checked);
g_config->setMenuBarChecked(p_checked);
});
QMenu *viewMenu = new QMenu(this);
viewMenu->setToolTipsVisible(true);
viewMenu->addAction(fullScreenAct);
viewMenu->addAction(stayOnTopAct);
viewMenu->addAction(menuBarAct);
expandViewAct = new QAction(VIconUtils::toolButtonIcon(":/resources/icons/expand.svg"),
tr("Expand"),
this);
VUtils::fixTextWithCaptainShortcut(expandViewAct, "ExpandMode");
expandViewAct->setStatusTip(tr("Expand the edit area"));
expandViewAct->setCheckable(true);
expandViewAct->setMenu(viewMenu);
connect(expandViewAct, &QAction::triggered,
this, [this](bool p_checked) {
changePanelView(p_checked ? PanelViewState::ExpandMode
: PanelViewState::VerticalMode);
});
viewToolBar->addAction(expandViewAct);
return viewToolBar;
}
// Enable/disable all actions of @p_widget.
static void setActionsEnabled(QWidget *p_widget, bool p_enabled)
{
Q_ASSERT(p_widget);
QList<QAction *> actions = p_widget->actions();
for (auto const & act : actions) {
act->setEnabled(p_enabled);
}
}
QToolBar *VMainWindow::initEditToolBar(QSize p_iconSize)
{
m_editToolBar = addToolBar(tr("Edit Toolbar"));
m_editToolBar->setObjectName("EditToolBar");
m_editToolBar->setMovable(false);
if (p_iconSize.isValid()) {
m_editToolBar->setIconSize(p_iconSize);
}
m_editToolBar->addSeparator();
m_headingSequenceAct = new QAction(VIconUtils::toolButtonIcon(":/resources/icons/heading_sequence.svg"),
tr("Heading Sequence"),
this);
m_headingSequenceAct->setStatusTip(tr("Enable heading sequence in current note in edit mode"));
m_headingSequenceAct->setCheckable(true);
connect(m_headingSequenceAct, &QAction::triggered,
this, [this](bool p_checked){
if (isHeadingSequenceApplicable()) {
VMdTab *tab = dynamic_cast<VMdTab *>(m_curTab.data());
Q_ASSERT(tab);
tab->enableHeadingSequence(p_checked);
}
});
m_editToolBar->addAction(m_headingSequenceAct);
initHeadingButton(m_editToolBar);
QAction *boldAct = new QAction(VIconUtils::toolButtonIcon(":/resources/icons/bold.svg"),
tr("Bold\t%1").arg(VUtils::getShortcutText("Ctrl+B")),
this);
boldAct->setStatusTip(tr("Insert bold text or change selected text to bold"));
connect(boldAct, &QAction::triggered,
this, [this](){
if (m_curTab) {
m_curTab->decorateText(TextDecoration::Bold);
}
});
m_editToolBar->addAction(boldAct);
QAction *italicAct = new QAction(VIconUtils::toolButtonIcon(":/resources/icons/italic.svg"),
tr("Italic\t%1").arg(VUtils::getShortcutText("Ctrl+I")),
this);
italicAct->setStatusTip(tr("Insert italic text or change selected text to italic"));
connect(italicAct, &QAction::triggered,
this, [this](){
if (m_curTab) {
m_curTab->decorateText(TextDecoration::Italic);
}
});
m_editToolBar->addAction(italicAct);
QAction *strikethroughAct = new QAction(VIconUtils::toolButtonIcon(":/resources/icons/strikethrough.svg"),
tr("Strikethrough\t%1").arg(VUtils::getShortcutText("Ctrl+D")),
this);
strikethroughAct->setStatusTip(tr("Insert strikethrough text or change selected text to strikethroughed"));
connect(strikethroughAct, &QAction::triggered,
this, [this](){
if (m_curTab) {
m_curTab->decorateText(TextDecoration::Strikethrough);
}
});
m_editToolBar->addAction(strikethroughAct);
QAction *inlineCodeAct = new QAction(VIconUtils::toolButtonIcon(":/resources/icons/inline_code.svg"),
tr("Inline Code\t%1").arg(VUtils::getShortcutText("Ctrl+;")),
this);
inlineCodeAct->setStatusTip(tr("Insert inline-code text or change selected text to inline-coded"));
connect(inlineCodeAct, &QAction::triggered,
this, [this](){
if (m_curTab) {
m_curTab->decorateText(TextDecoration::InlineCode);
}
});
m_editToolBar->addAction(inlineCodeAct);
QAction *codeBlockAct = new QAction(VIconUtils::toolButtonIcon(":/resources/icons/code_block.svg"),
tr("Code Block\t%1").arg(VUtils::getShortcutText("Ctrl+M")),
this);
codeBlockAct->setStatusTip(tr("Insert fenced code block text or wrap selected text into a fenced code block"));
connect(codeBlockAct, &QAction::triggered,
this, [this](){
if (m_curTab) {
m_curTab->decorateText(TextDecoration::CodeBlock);
}
});
m_editToolBar->addAction(codeBlockAct);
// Insert link.
QAction *insetLinkAct = new QAction(VIconUtils::toolButtonIcon(":/resources/icons/link.svg"),
tr("Insert Link\t%1").arg(VUtils::getShortcutText("Ctrl+L")),
this);
insetLinkAct->setStatusTip(tr("Insert a link"));
connect(insetLinkAct, &QAction::triggered,
this, [this]() {
if (m_curTab) {
m_curTab->insertLink();
}
});
m_editToolBar->addAction(insetLinkAct);
// Insert image.
QAction *insertImageAct = new QAction(VIconUtils::toolButtonIcon(":/resources/icons/insert_image.svg"),
tr("Insert Image\t%1").arg(VUtils::getShortcutText("Ctrl+'")),
this);
insertImageAct->setStatusTip(tr("Insert an image from file or URL"));
connect(insertImageAct, &QAction::triggered,
this, [this]() {
if (m_curTab) {
m_curTab->insertImage();
}
});
m_editToolBar->addAction(insertImageAct);
setActionsEnabled(m_editToolBar, false);
return m_editToolBar;
}
QToolBar *VMainWindow::initNoteToolBar(QSize p_iconSize)
{
QToolBar *noteToolBar = addToolBar(tr("Note Toolbar"));
noteToolBar->setObjectName("NoteToolBar");
noteToolBar->setMovable(false);
if (p_iconSize.isValid()) {
noteToolBar->setIconSize(p_iconSize);
}
noteToolBar->addSeparator();
// Attachment.
m_attachmentList = new VAttachmentList(this);
m_attachmentBtn = new VButtonWithWidget(VIconUtils::toolButtonIcon(":/resources/icons/attachment.svg"),
"",
m_attachmentList,
this);
m_attachmentBtn->setBubbleColor(g_palette->color("bubble_fg"),
g_palette->color("bubble_bg"));
m_attachmentBtn->setToolTip(tr("Attachments (drag files here to add attachments)"));
m_attachmentBtn->setProperty("CornerBtn", true);
m_attachmentBtn->setFocusPolicy(Qt::NoFocus);
m_attachmentBtn->setEnabled(false);
QAction *flashPageAct = new QAction(VIconUtils::toolButtonIcon(":/resources/icons/flash_page.svg"),
tr("Flash Page"),
this);
flashPageAct->setStatusTip(tr("Open the Flash Page to edit"));
QString keySeq = g_config->getShortcutKeySequence("FlashPage");
QKeySequence seq(keySeq);
if (!seq.isEmpty()) {
flashPageAct->setText(tr("Flash Page\t%1").arg(VUtils::getShortcutText(keySeq)));
flashPageAct->setShortcut(seq);
}
connect(flashPageAct, &QAction::triggered,
this, &VMainWindow::openFlashPage);
QAction *universalEntryAct = new QAction(VIconUtils::toolButtonIcon(":/resources/icons/universal_entry_tb.svg"),
tr("Universal Entry"),
this);
universalEntryAct->setStatusTip(tr("Activate Universal Entry"));
keySeq = g_config->getShortcutKeySequence("UniversalEntry");
seq = QKeySequence(keySeq);
if (!seq.isEmpty()) {
universalEntryAct->setText(tr("Universal Entry\t%1").arg(VUtils::getShortcutText(keySeq)));
universalEntryAct->setShortcut(seq);
}
connect(universalEntryAct, &QAction::triggered,
this, &VMainWindow::activateUniversalEntry);
noteToolBar->addWidget(m_attachmentBtn);
noteToolBar->addAction(flashPageAct);
noteToolBar->addAction(universalEntryAct);
return noteToolBar;
}
QToolBar *VMainWindow::initFileToolBar(QSize p_iconSize)
{
QToolBar *fileToolBar = addToolBar(tr("Note"));
fileToolBar->setObjectName("NoteToolBar");
fileToolBar->setMovable(false);
if (p_iconSize.isValid()) {
fileToolBar->setIconSize(p_iconSize);
}
m_avatarBtn = new QPushButton("VNote", this);
m_avatarBtn->setProperty("AvatarBtn", true);
m_avatarBtn->setFocusPolicy(Qt::NoFocus);
m_avatarBtn->setToolTip(tr("Log In (Not Implemented Yet)"));
newRootDirAct = new QAction(VIconUtils::toolButtonIcon(":/resources/icons/create_rootdir_tb.svg"),
tr("New Root Folder"),
this);
newRootDirAct->setStatusTip(tr("Create a root folder in current notebook"));
connect(newRootDirAct, &QAction::triggered,
m_dirTree, &VDirectoryTree::newRootDirectory);
newNoteAct = new QAction(VIconUtils::toolButtonIcon(":/resources/icons/create_note_tb.svg"),
tr("New Note"), this);
newNoteAct->setStatusTip(tr("Create a note in current folder"));
QString keySeq = g_config->getShortcutKeySequence("NewNote");
QKeySequence seq(keySeq);
if (!seq.isEmpty()) {
newNoteAct->setText(tr("New Note\t%1").arg(VUtils::getShortcutText(keySeq)));
newNoteAct->setShortcut(seq);
}
connect(newNoteAct, &QAction::triggered,
m_fileList, &VFileList::newFile);
noteInfoAct = new QAction(VIconUtils::toolButtonIcon(":/resources/icons/note_info_tb.svg"),
tr("Note Info"), this);
noteInfoAct->setStatusTip(tr("View and edit current note's information"));
connect(noteInfoAct, &QAction::triggered,
this, &VMainWindow::curEditFileInfo);
deleteNoteAct = new QAction(VIconUtils::toolButtonDangerIcon(":/resources/icons/delete_note_tb.svg"),
tr("Delete Note"), this);
deleteNoteAct->setStatusTip(tr("Delete current note"));
connect(deleteNoteAct, &QAction::triggered,
this, &VMainWindow::deleteCurNote);
m_editReadAct = new QAction(this);
connect(m_editReadAct, &QAction::triggered,
this, &VMainWindow::toggleEditReadMode);
m_discardExitAct = new QAction(VIconUtils::menuIcon(":/resources/icons/discard_exit.svg"),
tr("Discard Changes And Read"),
this);
VUtils::fixTextWithCaptainShortcut(m_discardExitAct, "DiscardAndRead");
m_discardExitAct->setStatusTip(tr("Discard changes and exit edit mode"));
connect(m_discardExitAct, &QAction::triggered,
this, [this]() {
m_editArea->readFile(true);
});
updateEditReadAct(NULL);
saveNoteAct = new QAction(VIconUtils::toolButtonIcon(":/resources/icons/save_note.svg"),
tr("Save"), this);
saveNoteAct->setStatusTip(tr("Save changes to current note"));
keySeq = g_config->getShortcutKeySequence("SaveNote");
seq = QKeySequence(keySeq);
if (!seq.isEmpty()) {
saveNoteAct->setText(tr("Save\t%1").arg(VUtils::getShortcutText(keySeq)));
saveNoteAct->setShortcut(seq);
}
connect(saveNoteAct, &QAction::triggered,
m_editArea, &VEditArea::saveFile);
newRootDirAct->setEnabled(false);
newNoteAct->setEnabled(false);
noteInfoAct->setEnabled(false);
deleteNoteAct->setEnabled(false);
m_editReadAct->setEnabled(false);
m_discardExitAct->setEnabled(false);
saveNoteAct->setEnabled(false);
fileToolBar->addWidget(m_avatarBtn);
fileToolBar->addAction(newRootDirAct);
fileToolBar->addAction(newNoteAct);
fileToolBar->addAction(deleteNoteAct);
fileToolBar->addAction(noteInfoAct);
fileToolBar->addAction(m_editReadAct);
fileToolBar->addAction(m_discardExitAct);
fileToolBar->addAction(saveNoteAct);
return fileToolBar;
}
void VMainWindow::initMenuBar()
{
initFileMenu();
initEditMenu();
initViewMenu();
initMarkdownMenu();
initHelpMenu();
setMenuBarVisible(g_config->getMenuBarChecked());
}
void VMainWindow::initHelpMenu()
{
QMenu *helpMenu = menuBar()->addMenu(tr("&Help"));
helpMenu->setToolTipsVisible(true);
#if defined(QT_NO_DEBUG)
QAction *logAct = new QAction(tr("View &Log"), this);
logAct->setToolTip(tr("View VNote's debug log (%1)").arg(g_config->getLogFilePath()));
connect(logAct, &QAction::triggered,
this, [](){
QUrl url = QUrl::fromLocalFile(g_config->getLogFilePath());
QDesktopServices::openUrl(url);
});
#endif
QAction *shortcutAct = new QAction(tr("&Shortcuts Help"), this);
shortcutAct->setToolTip(tr("View information about shortcut keys"));
VUtils::fixTextWithCaptainShortcut(shortcutAct, "ShortcutsHelp");
connect(shortcutAct, &QAction::triggered,
this, &VMainWindow::shortcutsHelp);
QAction *mdGuideAct = new QAction(tr("&Markdown Guide"), this);
mdGuideAct->setToolTip(tr("A quick guide of Markdown syntax"));
connect(mdGuideAct, &QAction::triggered,
this, [this](){
QString docFile = VUtils::getDocFile(VNote::c_markdownGuideDocFile);
VFile *file = vnote->getOrphanFile(docFile, false, true);
m_editArea->openFile(file, OpenFileMode::Read);
});
QAction *docAct = new QAction(tr("&Documentation"), this);
docAct->setToolTip(tr("View VNote's documentation"));
connect(docAct, &QAction::triggered,
this, [this]() {
QString url("http://vnote.readthedocs.io");
QDesktopServices::openUrl(url);
});
QAction *donateAct = new QAction(tr("Do&nate"), this);
donateAct->setToolTip(tr("Donate to VNote or view the donate list"));
connect(donateAct, &QAction::triggered,
this, [this]() {
QString url("https://github.com/tamlok/vnote#donate");
QDesktopServices::openUrl(url);
});
QAction *updateAct = new QAction(tr("Check For &Updates"), this);
updateAct->setToolTip(tr("Check for updates of VNote"));
connect(updateAct, &QAction::triggered,
this, [this](){
VUpdater updater(this);
updater.exec();
});
QAction *starAct = new QAction(tr("Star VNote on &Github"), this);
starAct->setToolTip(tr("Give a star to VNote on Github project"));
connect(starAct, &QAction::triggered,
this, [this]() {
QString url("https://github.com/tamlok/vnote");
QDesktopServices::openUrl(url);
});
QAction *feedbackAct = new QAction(tr("&Feedback"), this);
feedbackAct->setToolTip(tr("Open an issue on Github"));
connect(feedbackAct, &QAction::triggered,
this, [this]() {
QString url("https://github.com/tamlok/vnote/issues");
QDesktopServices::openUrl(url);
});
QAction *aboutAct = new QAction(tr("&About VNote"), this);
aboutAct->setToolTip(tr("View information about VNote"));
aboutAct->setMenuRole(QAction::AboutRole);
connect(aboutAct, &QAction::triggered,
this, &VMainWindow::aboutMessage);
QAction *aboutQtAct = new QAction(tr("About &Qt"), this);
aboutQtAct->setToolTip(tr("View information about Qt"));
aboutQtAct->setMenuRole(QAction::AboutQtRole);
connect(aboutQtAct, &QAction::triggered,
qApp, &QApplication::aboutQt);
helpMenu->addAction(shortcutAct);
helpMenu->addAction(mdGuideAct);
helpMenu->addAction(docAct);
helpMenu->addAction(donateAct);
helpMenu->addAction(updateAct);
helpMenu->addAction(starAct);
helpMenu->addAction(feedbackAct);
#if defined(QT_NO_DEBUG)
helpMenu->addAction(logAct);
#endif
helpMenu->addAction(aboutQtAct);
helpMenu->addAction(aboutAct);
}
void VMainWindow::initMarkdownMenu()
{
QMenu *markdownMenu = menuBar()->addMenu(tr("&Markdown"));
markdownMenu->setToolTipsVisible(true);
initConverterMenu(markdownMenu);
initMarkdownitOptionMenu(markdownMenu);
markdownMenu->addSeparator();
initRenderStyleMenu(markdownMenu);
initRenderBackgroundMenu(markdownMenu);
initCodeBlockStyleMenu(markdownMenu);
QAction *constrainImageAct = new QAction(tr("Constrain The Width Of Images"), this);
constrainImageAct->setToolTip(tr("Constrain the width of images to the window in read mode (re-open current tabs to make it work)"));
constrainImageAct->setCheckable(true);
connect(constrainImageAct, &QAction::triggered,
this, &VMainWindow::enableImageConstraint);
markdownMenu->addAction(constrainImageAct);
constrainImageAct->setChecked(g_config->getEnableImageConstraint());
QAction *imageCaptionAct = new QAction(tr("Enable Image Caption"), this);
imageCaptionAct->setToolTip(tr("Center the images and display the alt text as caption (re-open current tabs to make it work)"));
imageCaptionAct->setCheckable(true);
connect(imageCaptionAct, &QAction::triggered,
this, &VMainWindow::enableImageCaption);
markdownMenu->addAction(imageCaptionAct);
imageCaptionAct->setChecked(g_config->getEnableImageCaption());
markdownMenu->addSeparator();
QAction *mermaidAct = new QAction(tr("&Mermaid Diagram"), this);
mermaidAct->setToolTip(tr("Enable Mermaid for graph and diagram"));
mermaidAct->setCheckable(true);
connect(mermaidAct, &QAction::triggered,
this, &VMainWindow::enableMermaid);
markdownMenu->addAction(mermaidAct);
mermaidAct->setChecked(g_config->getEnableMermaid());
QAction *flowchartAct = new QAction(tr("&Flowchart.js"), this);
flowchartAct->setToolTip(tr("Enable Flowchart.js for flowchart diagram"));
flowchartAct->setCheckable(true);
connect(flowchartAct, &QAction::triggered,
this, [this](bool p_enabled){
g_config->setEnableFlowchart(p_enabled);
});
markdownMenu->addAction(flowchartAct);
flowchartAct->setChecked(g_config->getEnableFlowchart());
QAction *mathjaxAct = new QAction(tr("Math&Jax"), this);
mathjaxAct->setToolTip(tr("Enable MathJax for math support in Markdown"));
mathjaxAct->setCheckable(true);
connect(mathjaxAct, &QAction::triggered,
this, &VMainWindow::enableMathjax);
markdownMenu->addAction(mathjaxAct);
mathjaxAct->setChecked(g_config->getEnableMathjax());
markdownMenu->addSeparator();
QAction *codeBlockAct = new QAction(tr("Highlight Code Blocks In Edit Mode"), this);
codeBlockAct->setToolTip(tr("Enable syntax highlight within code blocks in edit mode"));
codeBlockAct->setCheckable(true);
connect(codeBlockAct, &QAction::triggered,
this, &VMainWindow::enableCodeBlockHighlight);
markdownMenu->addAction(codeBlockAct);
codeBlockAct->setChecked(g_config->getEnableCodeBlockHighlight());
QAction *lineNumberAct = new QAction(tr("Display Line Number In Code Blocks"), this);
lineNumberAct->setToolTip(tr("Enable line number in code blocks in read mode"));
lineNumberAct->setCheckable(true);
connect(lineNumberAct, &QAction::triggered,
this, [this](bool p_checked){
g_config->setEnableCodeBlockLineNumber(p_checked);
});
markdownMenu->addAction(lineNumberAct);
lineNumberAct->setChecked(g_config->getEnableCodeBlockLineNumber());
QAction *previewImageAct = new QAction(tr("In-Place Preview"), this);
previewImageAct->setToolTip(tr("Enable in-place preview (images, diagrams, and formulas) in edit mode (re-open current tabs to make it work)"));
previewImageAct->setCheckable(true);
connect(previewImageAct, &QAction::triggered,
this, &VMainWindow::enableImagePreview);
markdownMenu->addAction(previewImageAct);
previewImageAct->setChecked(g_config->getEnablePreviewImages());
QAction *previewWidthAct = new QAction(tr("Constrain The Width Of In-Place Preview"), this);
previewWidthAct->setToolTip(tr("Constrain the width of in-place preview to the edit window in edit mode"));
previewWidthAct->setCheckable(true);
connect(previewWidthAct, &QAction::triggered,
this, &VMainWindow::enableImagePreviewConstraint);
markdownMenu->addAction(previewWidthAct);
previewWidthAct->setChecked(g_config->getEnablePreviewImageConstraint());
}
void VMainWindow::initViewMenu()
{
m_viewMenu = menuBar()->addMenu(tr("&View"));
m_viewMenu->setToolTipsVisible(true);
m_toolBarAct = new QAction(tr("Tool Bar"), this);
m_toolBarAct->setToolTip(tr("Toogle the tool bar"));
VUtils::fixTextWithCaptainShortcut(m_toolBarAct, "ToolBar");
m_toolBarAct->setCheckable(true);
m_toolBarAct->setChecked(g_config->getToolBarChecked());
connect(m_toolBarAct, &QAction::triggered,
this, [this] (bool p_checked) {
g_config->setToolBarChecked(p_checked);
setToolBarVisible(p_checked);
});
m_viewMenu->addAction(m_toolBarAct);
}
void VMainWindow::initFileMenu()
{
QMenu *fileMenu = menuBar()->addMenu(tr("&File"));
fileMenu->setToolTipsVisible(true);
// Open external files.
QAction *openAct = new QAction(tr("&Open"), this);
openAct->setToolTip(tr("Open external file to edit"));
connect(openAct, &QAction::triggered,
this, [this](){
static QString lastPath = QDir::homePath();
QStringList files = QFileDialog::getOpenFileNames(this,
tr("Select External Files To Open"),
lastPath);
if (files.isEmpty()) {
return;
}
// Update lastPath
lastPath = QFileInfo(files[0]).path();
openFiles(VUtils::filterFilePathsToOpen(files),
false,
g_config->getNoteOpenMode(),
false,
false);
});
fileMenu->addAction(openAct);
// Import notes from files.
m_importNoteAct = newAction(VIconUtils::menuIcon(":/resources/icons/import_note.svg"),
tr("&New Notes From Files"), this);
m_importNoteAct->setToolTip(tr("Create notes from external files in current folder "
"(will copy files if they do not locate in current folder)"));
connect(m_importNoteAct, &QAction::triggered,
this, &VMainWindow::importNoteFromFile);
m_importNoteAct->setEnabled(false);
fileMenu->addAction(m_importNoteAct);
fileMenu->addSeparator();
// Export as PDF.
m_exportAct = new QAction(tr("E&xport"), this);
m_exportAct->setToolTip(tr("Export notes"));
VUtils::fixTextWithCaptainShortcut(m_exportAct, "Export");
connect(m_exportAct, &QAction::triggered,
this, &VMainWindow::handleExportAct);
fileMenu->addAction(m_exportAct);
// Print.
m_printAct = new QAction(VIconUtils::menuIcon(":/resources/icons/print.svg"),
tr("&Print"), this);
m_printAct->setToolTip(tr("Print current note"));
connect(m_printAct, &QAction::triggered,
this, &VMainWindow::printNote);
m_printAct->setEnabled(false);
fileMenu->addAction(m_printAct);
fileMenu->addSeparator();
// Themes.
initThemeMenu(fileMenu);
// Settings.
QAction *settingsAct = newAction(VIconUtils::menuIcon(":/resources/icons/settings.svg"),
tr("&Settings"), this);
settingsAct->setToolTip(tr("View and change settings for VNote"));
settingsAct->setMenuRole(QAction::PreferencesRole);
connect(settingsAct, &QAction::triggered,
this, &VMainWindow::viewSettings);
fileMenu->addAction(settingsAct);
QAction *openConfigAct = new QAction(tr("Open Configuration Folder"), this);
openConfigAct->setToolTip(tr("Open configuration folder of VNote"));
connect(openConfigAct, &QAction::triggered,
this, [this](){
QUrl url = QUrl::fromLocalFile(g_config->getConfigFolder());
QDesktopServices::openUrl(url);
});
fileMenu->addAction(openConfigAct);
QAction *customShortcutAct = new QAction(tr("Customize Shortcuts"), this);
customShortcutAct->setToolTip(tr("Customize some standard shortcuts"));
connect(customShortcutAct, &QAction::triggered,
this, &VMainWindow::customShortcut);
fileMenu->addAction(customShortcutAct);
fileMenu->addSeparator();
// Exit.
QAction *exitAct = new QAction(tr("&Quit"), this);
exitAct->setToolTip(tr("Quit VNote"));
exitAct->setShortcut(QKeySequence("Ctrl+Q"));
exitAct->setMenuRole(QAction::QuitRole);
connect(exitAct, &QAction::triggered,
this, &VMainWindow::quitApp);
fileMenu->addAction(exitAct);
}
void VMainWindow::quitApp()
{
m_requestQuit = true;
close();
}
void VMainWindow::initEditMenu()
{
QMenu *editMenu = menuBar()->addMenu(tr("&Edit"));
editMenu->setToolTipsVisible(true);
// Find/Replace.
m_findReplaceAct = newAction(VIconUtils::menuIcon(":/resources/icons/find_replace.svg"),
tr("Find/Replace"), this);
m_findReplaceAct->setToolTip(tr("Open Find/Replace dialog to search in current note"));
QString keySeq = g_config->getShortcutKeySequence("Find");
qDebug() << "set Find shortcut to" << keySeq;
m_findReplaceAct->setShortcut(QKeySequence(keySeq));
connect(m_findReplaceAct, &QAction::triggered,
this, &VMainWindow::openFindDialog);
QAction *advFindAct = new QAction(tr("Advanced Find"), this);
advFindAct->setToolTip(tr("Advanced find within VNote"));
keySeq = g_config->getShortcutKeySequence("AdvancedFind");
qDebug() << "set AdvancedFind shortcut to" << keySeq;
advFindAct->setShortcut(QKeySequence(keySeq));
connect(advFindAct, &QAction::triggered,
this, [this]() {
m_searchDock->setVisible(true);
m_searcher->focusToSearch();
});
m_findNextAct = new QAction(tr("Find Next"), this);
m_findNextAct->setToolTip(tr("Find next occurence"));
keySeq = g_config->getShortcutKeySequence("FindNext");
qDebug() << "set FindNext shortcut to" << keySeq;
m_findNextAct->setShortcut(QKeySequence(keySeq));
connect(m_findNextAct, SIGNAL(triggered(bool)),
m_findReplaceDialog, SLOT(findNext()));
m_findPreviousAct = new QAction(tr("Find Previous"), this);
m_findPreviousAct->setToolTip(tr("Find previous occurence"));
keySeq = g_config->getShortcutKeySequence("FindPrevious");
qDebug() << "set FindPrevious shortcut to" << keySeq;
m_findPreviousAct->setShortcut(QKeySequence(keySeq));
connect(m_findPreviousAct, SIGNAL(triggered(bool)),
m_findReplaceDialog, SLOT(findPrevious()));
m_replaceAct = new QAction(tr("Replace"), this);
m_replaceAct->setToolTip(tr("Replace current occurence"));
connect(m_replaceAct, SIGNAL(triggered(bool)),
m_findReplaceDialog, SLOT(replace()));
m_replaceFindAct = new QAction(tr("Replace && Find"), this);
m_replaceFindAct->setToolTip(tr("Replace current occurence and find the next one"));
connect(m_replaceFindAct, SIGNAL(triggered(bool)),
m_findReplaceDialog, SLOT(replaceFind()));
m_replaceAllAct = new QAction(tr("Replace All"), this);
m_replaceAllAct->setToolTip(tr("Replace all occurences in current note"));
connect(m_replaceAllAct, SIGNAL(triggered(bool)),
m_findReplaceDialog, SLOT(replaceAll()));
QAction *searchedWordAct = new QAction(tr("Highlight Searched Pattern"), this);
searchedWordAct->setToolTip(tr("Highlight all occurences of searched pattern"));
searchedWordAct->setCheckable(true);
connect(searchedWordAct, &QAction::triggered,
this, &VMainWindow::changeHighlightSearchedWord);
// Expand Tab into spaces.
QAction *expandTabAct = new QAction(tr("&Expand Tab"), this);
expandTabAct->setToolTip(tr("Expand entered Tab to spaces"));
expandTabAct->setCheckable(true);
connect(expandTabAct, &QAction::triggered,
this, &VMainWindow::changeExpandTab);
// Tab stop width.
QActionGroup *tabStopWidthAct = new QActionGroup(this);
QAction *twoSpaceTabAct = new QAction(tr("2 Spaces"), tabStopWidthAct);
twoSpaceTabAct->setToolTip(tr("Expand Tab to 2 spaces"));
twoSpaceTabAct->setCheckable(true);
twoSpaceTabAct->setData(2);
QAction *fourSpaceTabAct = new QAction(tr("4 Spaces"), tabStopWidthAct);
fourSpaceTabAct->setToolTip(tr("Expand Tab to 4 spaces"));
fourSpaceTabAct->setCheckable(true);
fourSpaceTabAct->setData(4);
QAction *eightSpaceTabAct = new QAction(tr("8 Spaces"), tabStopWidthAct);
eightSpaceTabAct->setToolTip(tr("Expand Tab to 8 spaces"));
eightSpaceTabAct->setCheckable(true);
eightSpaceTabAct->setData(8);
connect(tabStopWidthAct, &QActionGroup::triggered,
this, &VMainWindow::setTabStopWidth);
// Auto Indent.
m_autoIndentAct = new QAction(tr("Auto Indent"), this);
m_autoIndentAct->setToolTip(tr("Indent automatically when inserting a new line"));
m_autoIndentAct->setCheckable(true);
connect(m_autoIndentAct, &QAction::triggered,
this, &VMainWindow::changeAutoIndent);
// Auto List.
QAction *autoListAct = new QAction(tr("Auto List"), this);
autoListAct->setToolTip(tr("Continue the list automatically when inserting a new line"));
autoListAct->setCheckable(true);
connect(autoListAct, &QAction::triggered,
this, &VMainWindow::changeAutoList);
// Vim Mode.
QAction *vimAct = new QAction(tr("Vim Mode"), this);
vimAct->setToolTip(tr("Enable Vim mode for editing (re-open current tabs to make it work)"));
vimAct->setCheckable(true);
connect(vimAct, &QAction::triggered,
this, &VMainWindow::changeVimMode);
// Smart input method in Vim mode.
QAction *smartImAct = new QAction(tr("Smart Input Method In Vim Mode"), this);
smartImAct->setToolTip(tr("Disable input method when leaving Insert mode in Vim mode"));
smartImAct->setCheckable(true);
connect(smartImAct, &QAction::triggered,
this, [this](bool p_checked){
g_config->setEnableSmartImInVimMode(p_checked);
});
// Highlight current cursor line.
QAction *cursorLineAct = new QAction(tr("Highlight Cursor Line"), this);
cursorLineAct->setToolTip(tr("Highlight current cursor line"));
cursorLineAct->setCheckable(true);
connect(cursorLineAct, &QAction::triggered,
this, &VMainWindow::changeHighlightCursorLine);
// Highlight selected word.
QAction *selectedWordAct = new QAction(tr("Highlight Selected Words"), this);
selectedWordAct->setToolTip(tr("Highlight all occurences of selected words"));
selectedWordAct->setCheckable(true);
connect(selectedWordAct, &QAction::triggered,
this, &VMainWindow::changeHighlightSelectedWord);
// Highlight trailing space.
QAction *trailingSapceAct = new QAction(tr("Highlight Trailing Spaces"), this);
trailingSapceAct->setToolTip(tr("Highlight all the spaces at the end of a line"));
trailingSapceAct->setCheckable(true);
connect(trailingSapceAct, &QAction::triggered,
this, &VMainWindow::changeHighlightTrailingSapce);
QMenu *findReplaceMenu = editMenu->addMenu(tr("Find/Replace"));
findReplaceMenu->setToolTipsVisible(true);
findReplaceMenu->addAction(m_findReplaceAct);
findReplaceMenu->addAction(advFindAct);
findReplaceMenu->addSeparator();
findReplaceMenu->addAction(m_findNextAct);
findReplaceMenu->addAction(m_findPreviousAct);
findReplaceMenu->addAction(m_replaceAct);
findReplaceMenu->addAction(m_replaceFindAct);
findReplaceMenu->addAction(m_replaceAllAct);
findReplaceMenu->addSeparator();
findReplaceMenu->addAction(searchedWordAct);
searchedWordAct->setChecked(g_config->getHighlightSearchedWord());
m_findReplaceAct->setEnabled(false);
m_findNextAct->setEnabled(false);
m_findPreviousAct->setEnabled(false);
m_replaceAct->setEnabled(false);
m_replaceFindAct->setEnabled(false);
m_replaceAllAct->setEnabled(false);
editMenu->addSeparator();
editMenu->addAction(expandTabAct);
if (g_config->getIsExpandTab()) {
expandTabAct->setChecked(true);
} else {
expandTabAct->setChecked(false);
}
QMenu *tabStopWidthMenu = editMenu->addMenu(tr("Tab Stop Width"));
tabStopWidthMenu->setToolTipsVisible(true);
tabStopWidthMenu->addAction(twoSpaceTabAct);
tabStopWidthMenu->addAction(fourSpaceTabAct);
tabStopWidthMenu->addAction(eightSpaceTabAct);
int tabStopWidth = g_config->getTabStopWidth();
switch (tabStopWidth) {
case 2:
twoSpaceTabAct->setChecked(true);
break;
case 4:
fourSpaceTabAct->setChecked(true);
break;
case 8:
eightSpaceTabAct->setChecked(true);
break;
default:
qWarning() << "unsupported tab stop width" << tabStopWidth << "in config";
}
editMenu->addAction(m_autoIndentAct);
m_autoIndentAct->setChecked(g_config->getAutoIndent());
editMenu->addAction(autoListAct);
if (g_config->getAutoList()) {
// Let the trigger handler to trigger m_autoIndentAct, too.
autoListAct->trigger();
}
Q_ASSERT(!(autoListAct->isChecked() && !m_autoIndentAct->isChecked()));
editMenu->addAction(vimAct);
vimAct->setChecked(g_config->getEnableVimMode());
editMenu->addAction(smartImAct);
smartImAct->setChecked(g_config->getEnableSmartImInVimMode());
editMenu->addSeparator();
initEditorStyleMenu(editMenu);
initEditorBackgroundMenu(editMenu);
initEditorLineNumberMenu(editMenu);
editMenu->addAction(cursorLineAct);
cursorLineAct->setChecked(g_config->getHighlightCursorLine());
editMenu->addAction(selectedWordAct);
selectedWordAct->setChecked(g_config->getHighlightSelectedWord());
editMenu->addAction(trailingSapceAct);
trailingSapceAct->setChecked(g_config->getEnableTrailingSpaceHighlight());
}
void VMainWindow::initDockWindows()
{
setTabPosition(Qt::LeftDockWidgetArea, QTabWidget::West);
setTabPosition(Qt::RightDockWidgetArea, QTabWidget::East);
setTabPosition(Qt::TopDockWidgetArea, QTabWidget::North);
setTabPosition(Qt::BottomDockWidgetArea, QTabWidget::North);
setDockNestingEnabled(true);
initToolsDock();
initSearchDock();
}
void VMainWindow::initToolsDock()
{
m_toolDock = new QDockWidget(tr("Tools"), this);
m_toolDock->setObjectName("ToolsDock");
m_toolDock->setAllowedAreas(Qt::AllDockWidgetAreas);
// Outline tree.
outline = new VOutline(this);
connect(m_editArea, &VEditArea::outlineChanged,
outline, &VOutline::updateOutline);
connect(m_editArea, &VEditArea::currentHeaderChanged,
outline, &VOutline::updateCurrentHeader);
connect(outline, &VOutline::outlineItemActivated,
m_editArea, &VEditArea::scrollToHeader);
// Snippets.
m_snippetList = new VSnippetList(this);
// Cart.
m_cart = new VCart(this);
m_toolBox = new VToolBox(this);
m_toolBox->addItem(outline,
":/resources/icons/outline.svg",
tr("Outline"));
m_toolBox->addItem(m_snippetList,
":/resources/icons/snippets.svg",
tr("Snippets"));
m_toolBox->addItem(m_cart,
":/resources/icons/cart.svg",
tr("Cart"));
m_toolDock->setWidget(m_toolBox);
addDockWidget(Qt::RightDockWidgetArea, m_toolDock);
QAction *toggleAct = m_toolDock->toggleViewAction();
toggleAct->setToolTip(tr("Toggle the tools dock widget"));
VUtils::fixTextWithCaptainShortcut(toggleAct, "ToolsDock");
m_viewMenu->addAction(toggleAct);
}
void VMainWindow::initSearchDock()
{
m_searchDock = new QDockWidget(tr("Search"), this);
m_searchDock->setObjectName("SearchDock");
m_searchDock->setAllowedAreas(Qt::AllDockWidgetAreas);
m_searcher = new VSearcher(this);
m_searchDock->setWidget(m_searcher);
addDockWidget(Qt::RightDockWidgetArea, m_searchDock);
QAction *toggleAct = m_searchDock->toggleViewAction();
toggleAct->setToolTip(tr("Toggle the search dock widget"));
VUtils::fixTextWithCaptainShortcut(toggleAct, "SearchDock");
m_viewMenu->addAction(toggleAct);
}
void VMainWindow::importNoteFromFile()
{
static QString lastPath = QDir::homePath();
QStringList files = QFileDialog::getOpenFileNames(this,
tr("Select Files To Create Notes"),
lastPath);
if (files.isEmpty()) {
return;
}
// Update lastPath
lastPath = QFileInfo(files[0]).path();
QString msg;
if (!m_fileList->importFiles(files, &msg)) {
VUtils::showMessage(QMessageBox::Warning,
tr("Warning"),
tr("Fail to create notes for all the files."),
msg,
QMessageBox::Ok,
QMessageBox::Ok,
this);
} else {
int cnt = files.size();
showStatusMessage(tr("%1 %2 created from external files")
.arg(cnt)
.arg(cnt > 1 ? tr("notes") : tr("note")));
}
}
void VMainWindow::changeMarkdownConverter(QAction *action)
{
if (!action) {
return;
}
MarkdownConverterType type = (MarkdownConverterType)action->data().toInt();
g_config->setMarkdownConverterType(type);
}
void VMainWindow::aboutMessage()
{
QString info = tr("<span style=\"font-weight: bold;\">v%1</span>").arg(VConfigManager::c_version);
info += "<br/><br/>";
info += tr("VNote is a free Vim-inspired note-taking application that knows programmers and Markdown better.");
info += "<br/>";
info += tr("Please visit <a href=\"https://github.com/tamlok/vnote.git\">Github</a> for more information.");
QMessageBox::about(this, tr("About VNote"), info);
}
void VMainWindow::changeExpandTab(bool checked)
{
g_config->setIsExpandTab(checked);
}
void VMainWindow::enableMermaid(bool p_checked)
{
g_config->setEnableMermaid(p_checked);
}
void VMainWindow::enableMathjax(bool p_checked)
{
g_config->setEnableMathjax(p_checked);
}
void VMainWindow::changeHighlightCursorLine(bool p_checked)
{
g_config->setHighlightCursorLine(p_checked);
}
void VMainWindow::changeHighlightSelectedWord(bool p_checked)
{
g_config->setHighlightSelectedWord(p_checked);
}
void VMainWindow::changeHighlightSearchedWord(bool p_checked)
{
g_config->setHighlightSearchedWord(p_checked);
}
void VMainWindow::changeHighlightTrailingSapce(bool p_checked)
{
g_config->setEnableTrailingSapceHighlight(p_checked);
}
void VMainWindow::setTabStopWidth(QAction *action)
{
if (!action) {
return;
}
g_config->setTabStopWidth(action->data().toInt());
}
void VMainWindow::setEditorBackgroundColor(QAction *action)
{
if (!action) {
return;
}
g_config->setCurBackgroundColor(action->data().toString());
}
void VMainWindow::initConverterMenu(QMenu *p_menu)
{
QMenu *converterMenu = p_menu->addMenu(tr("&Renderer"));
converterMenu->setToolTipsVisible(true);
QActionGroup *converterAct = new QActionGroup(this);
QAction *markedAct = new QAction(tr("Marked"), converterAct);
markedAct->setToolTip(tr("Use Marked to convert Markdown to HTML (re-open current tabs to make it work)"));
markedAct->setCheckable(true);
markedAct->setData(int(MarkdownConverterType::Marked));
QAction *hoedownAct = new QAction(tr("Hoedown"), converterAct);
hoedownAct->setToolTip(tr("Use Hoedown to convert Markdown to HTML (re-open current tabs to make it work)"));
hoedownAct->setCheckable(true);
hoedownAct->setData(int(MarkdownConverterType::Hoedown));
QAction *markdownitAct = new QAction(tr("Markdown-it"), converterAct);
markdownitAct->setToolTip(tr("Use Markdown-it to convert Markdown to HTML (re-open current tabs to make it work)"));
markdownitAct->setCheckable(true);
markdownitAct->setData(int(MarkdownConverterType::MarkdownIt));
QAction *showdownAct = new QAction(tr("Showdown"), converterAct);
showdownAct->setToolTip(tr("Use Showdown to convert Markdown to HTML (re-open current tabs to make it work)"));
showdownAct->setCheckable(true);
showdownAct->setData(int(MarkdownConverterType::Showdown));
connect(converterAct, &QActionGroup::triggered,
this, &VMainWindow::changeMarkdownConverter);
converterMenu->addAction(hoedownAct);
converterMenu->addAction(markedAct);
converterMenu->addAction(markdownitAct);
converterMenu->addAction(showdownAct);
MarkdownConverterType converterType = g_config->getMdConverterType();
switch (converterType) {
case MarkdownConverterType::Marked:
markedAct->setChecked(true);
break;
case MarkdownConverterType::Hoedown:
hoedownAct->setChecked(true);
break;
case MarkdownConverterType::MarkdownIt:
markdownitAct->setChecked(true);
break;
case MarkdownConverterType::Showdown:
showdownAct->setChecked(true);
break;
default:
Q_ASSERT(false);
}
}
void VMainWindow::initMarkdownitOptionMenu(QMenu *p_menu)
{
QMenu *optMenu = p_menu->addMenu(tr("Markdown-it Options"));
optMenu->setToolTipsVisible(true);
const MarkdownitOption &opt = g_config->getMarkdownitOption();
QAction *htmlAct = new QAction(tr("HTML"), this);
htmlAct->setToolTip(tr("Enable HTML tags in source"));
htmlAct->setCheckable(true);
htmlAct->setChecked(opt.m_html);
connect(htmlAct, &QAction::triggered,
this, [this](bool p_checked) {
MarkdownitOption opt = g_config->getMarkdownitOption();
opt.m_html = p_checked;
g_config->setMarkdownitOption(opt);
});
QAction *breaksAct = new QAction(tr("Line Break"), this);
breaksAct->setToolTip(tr("Convert '\\n' in paragraphs into line break"));
breaksAct->setCheckable(true);
breaksAct->setChecked(opt.m_breaks);
connect(breaksAct, &QAction::triggered,
this, [this](bool p_checked) {
MarkdownitOption opt = g_config->getMarkdownitOption();
opt.m_breaks = p_checked;
g_config->setMarkdownitOption(opt);
});
QAction *linkifyAct = new QAction(tr("Linkify"), this);
linkifyAct->setToolTip(tr("Convert URL-like text into links"));
linkifyAct->setCheckable(true);
linkifyAct->setChecked(opt.m_linkify);
connect(linkifyAct, &QAction::triggered,
this, [this](bool p_checked) {
MarkdownitOption opt = g_config->getMarkdownitOption();
opt.m_linkify = p_checked;
g_config->setMarkdownitOption(opt);
});
QAction *supAct = new QAction(tr("Superscript"), this);
supAct->setToolTip(tr("Enable superscript via ^^"));
supAct->setCheckable(true);
supAct->setChecked(opt.m_sup);
connect(supAct, &QAction::triggered,
this, [this](bool p_checked) {
MarkdownitOption opt = g_config->getMarkdownitOption();
opt.m_sup = p_checked;
g_config->setMarkdownitOption(opt);
});
QAction *subAct = new QAction(tr("Subscript"), this);
subAct->setToolTip(tr("Enable subscript via ~~"));
subAct->setCheckable(true);
subAct->setChecked(opt.m_sub);
connect(subAct, &QAction::triggered,
this, [this](bool p_checked) {
MarkdownitOption opt = g_config->getMarkdownitOption();
opt.m_sub = p_checked;
g_config->setMarkdownitOption(opt);
});
QAction *metadataAct = new QAction(tr("Metadata Aware"), this);
metadataAct->setToolTip(tr("Be aware of metadata in YAML format"));
metadataAct->setCheckable(true);
metadataAct->setChecked(opt.m_metadata);
connect(metadataAct, &QAction::triggered,
this, [this](bool p_checked) {
MarkdownitOption opt = g_config->getMarkdownitOption();
opt.m_metadata = p_checked;
g_config->setMarkdownitOption(opt);
});
QAction *emojiAct = new QAction(tr("Emoji"), this);
emojiAct->setToolTip(tr("Enable emoji and emoticon"));
emojiAct->setCheckable(true);
emojiAct->setChecked(opt.m_emoji);
connect(emojiAct, &QAction::triggered,
this, [this](bool p_checked) {
MarkdownitOption opt = g_config->getMarkdownitOption();
opt.m_emoji = p_checked;
g_config->setMarkdownitOption(opt);
});
optMenu->addAction(htmlAct);
optMenu->addAction(breaksAct);
optMenu->addAction(linkifyAct);
optMenu->addAction(supAct);
optMenu->addAction(subAct);
optMenu->addAction(metadataAct);
optMenu->addAction(emojiAct);
}
void VMainWindow::initRenderBackgroundMenu(QMenu *menu)
{
QActionGroup *renderBackgroundAct = new QActionGroup(this);
connect(renderBackgroundAct, &QActionGroup::triggered,
this, &VMainWindow::setRenderBackgroundColor);
QMenu *renderBgMenu = menu->addMenu(tr("&Rendering Background"));
renderBgMenu->setToolTipsVisible(true);
const QString &curBgColor = g_config->getCurRenderBackgroundColor();
QAction *tmpAct = new QAction(tr("System"), renderBackgroundAct);
tmpAct->setToolTip(tr("Use system's background color configuration for Markdown rendering"));
tmpAct->setCheckable(true);
tmpAct->setData("System");
if (curBgColor == "System") {
tmpAct->setChecked(true);
}
renderBgMenu->addAction(tmpAct);
tmpAct = new QAction(tr("Transparent"), renderBackgroundAct);
tmpAct->setToolTip(tr("Use a transparent background for Markdown rendering"));
tmpAct->setCheckable(true);
tmpAct->setData("Transparent");
if (curBgColor == "Transparent") {
tmpAct->setChecked(true);
}
renderBgMenu->addAction(tmpAct);
const QVector<VColor> &bgColors = g_config->getCustomColors();
for (int i = 0; i < bgColors.size(); ++i) {
tmpAct = new QAction(bgColors[i].m_name, renderBackgroundAct);
tmpAct->setToolTip(tr("Set as the background color for Markdown rendering"));
tmpAct->setCheckable(true);
tmpAct->setData(bgColors[i].m_name);
#if !defined(Q_OS_MACOS) && !defined(Q_OS_MAC)
QColor color(bgColors[i].m_color);
QPixmap pixmap(COLOR_PIXMAP_ICON_SIZE, COLOR_PIXMAP_ICON_SIZE);
pixmap.fill(color);
tmpAct->setIcon(QIcon(pixmap));
#endif
if (curBgColor == bgColors[i].m_name) {
tmpAct->setChecked(true);
}
renderBgMenu->addAction(tmpAct);
}
}
void VMainWindow::initRenderStyleMenu(QMenu *p_menu)
{
QMenu *styleMenu = p_menu->addMenu(tr("Rendering &Style"));
styleMenu->setToolTipsVisible(true);
QAction *addAct = newAction(VIconUtils::menuIcon(":/resources/icons/add_style.svg"),
tr("Add Style"),
styleMenu);
addAct->setToolTip(tr("Add custom style of read mode"));
connect(addAct, &QAction::triggered,
this, [this]() {
VTipsDialog dialog(VUtils::getDocFile("tips_add_style.md"),
tr("Add Style"),
[]() {
QUrl url = QUrl::fromLocalFile(g_config->getStyleConfigFolder());
QDesktopServices::openUrl(url);
},
this);
dialog.exec();
});
styleMenu->addAction(addAct);
QActionGroup *ag = new QActionGroup(this);
connect(ag, &QActionGroup::triggered,
this, [this](QAction *p_action) {
if (!p_action) {
return;
}
QString data = p_action->data().toString();
g_config->setCssStyle(data);
vnote->updateTemplate();
});
QList<QString> styles = g_config->getCssStyles();
QString curStyle = g_config->getCssStyle();
for (auto const &style : styles) {
QAction *act = new QAction(style, ag);
act->setToolTip(tr("Set as the CSS style for Markdown rendering "
"(re-open current tabs to make it work)"));
act->setCheckable(true);
act->setData(style);
// Add it to the menu.
styleMenu->addAction(act);
if (curStyle == style) {
act->setChecked(true);
}
}
}
void VMainWindow::initCodeBlockStyleMenu(QMenu *p_menu)
{
QMenu *styleMenu = p_menu->addMenu(tr("Code Block Style"));
styleMenu->setToolTipsVisible(true);
QAction *addAct = newAction(VIconUtils::menuIcon(":/resources/icons/add_style.svg"),
tr("Add Style"),
styleMenu);
addAct->setToolTip(tr("Add custom style of code block in read mode"));
connect(addAct, &QAction::triggered,
this, [this]() {
VTipsDialog dialog(VUtils::getDocFile("tips_add_style.md"),
tr("Add Style"),
[]() {
QUrl url = QUrl::fromLocalFile(g_config->getCodeBlockStyleConfigFolder());
QDesktopServices::openUrl(url);
},
this);
dialog.exec();
});
styleMenu->addAction(addAct);
QActionGroup *ag = new QActionGroup(this);
connect(ag, &QActionGroup::triggered,
this, [this](QAction *p_action) {
if (!p_action) {
return;
}
QString data = p_action->data().toString();
g_config->setCodeBlockCssStyle(data);
vnote->updateTemplate();
});
QList<QString> styles = g_config->getCodeBlockCssStyles();
QString curStyle = g_config->getCodeBlockCssStyle();
for (auto const &style : styles) {
QAction *act = new QAction(style, ag);
act->setToolTip(tr("Set as the code block CSS style for Markdown rendering "
"(re-open current tabs to make it work)"));
act->setCheckable(true);
act->setData(style);
// Add it to the menu.
styleMenu->addAction(act);
if (curStyle == style) {
act->setChecked(true);
}
}
}
void VMainWindow::initEditorBackgroundMenu(QMenu *menu)
{
QMenu *backgroundColorMenu = menu->addMenu(tr("&Background Color"));
backgroundColorMenu->setToolTipsVisible(true);
QActionGroup *backgroundColorAct = new QActionGroup(this);
connect(backgroundColorAct, &QActionGroup::triggered,
this, &VMainWindow::setEditorBackgroundColor);
// System background color
const QString &curBgColor = g_config->getCurBackgroundColor();
QAction *tmpAct = new QAction(tr("System"), backgroundColorAct);
tmpAct->setToolTip(tr("Use system's background color configuration for editor"));
tmpAct->setCheckable(true);
tmpAct->setData("System");
if (curBgColor == "System") {
tmpAct->setChecked(true);
}
backgroundColorMenu->addAction(tmpAct);
const QVector<VColor> &bgColors = g_config->getCustomColors();
for (int i = 0; i < bgColors.size(); ++i) {
tmpAct = new QAction(bgColors[i].m_name, backgroundColorAct);
tmpAct->setToolTip(tr("Set as the background color for editor"));
tmpAct->setCheckable(true);
tmpAct->setData(bgColors[i].m_name);
#if !defined(Q_OS_MACOS) && !defined(Q_OS_MAC)
QColor color(bgColors[i].m_color);
QPixmap pixmap(COLOR_PIXMAP_ICON_SIZE, COLOR_PIXMAP_ICON_SIZE);
pixmap.fill(color);
tmpAct->setIcon(QIcon(pixmap));
#endif
if (curBgColor == bgColors[i].m_name) {
tmpAct->setChecked(true);
}
backgroundColorMenu->addAction(tmpAct);
}
}
void VMainWindow::initEditorLineNumberMenu(QMenu *p_menu)
{
QMenu *lineNumMenu = p_menu->addMenu(tr("Line Number"));
lineNumMenu->setToolTipsVisible(true);
QActionGroup *lineNumAct = new QActionGroup(lineNumMenu);
connect(lineNumAct, &QActionGroup::triggered,
this, [this](QAction *p_action){
if (!p_action) {
return;
}
g_config->setEditorLineNumber(p_action->data().toInt());
emit editorConfigUpdated();
});
int lineNumberMode = g_config->getEditorLineNumber();
QAction *act = lineNumAct->addAction(tr("None"));
act->setToolTip(tr("Do not display line number in edit mode"));
act->setCheckable(true);
act->setData(0);
lineNumMenu->addAction(act);
if (lineNumberMode == 0) {
act->setChecked(true);
}
act = lineNumAct->addAction(tr("Absolute"));
act->setToolTip(tr("Display absolute line number in edit mode"));
act->setCheckable(true);
act->setData(1);
lineNumMenu->addAction(act);
if (lineNumberMode == 1) {
act->setChecked(true);
}
act = lineNumAct->addAction(tr("Relative"));
act->setToolTip(tr("Display line number relative to current cursor line in edit mode"));
act->setCheckable(true);
act->setData(2);
lineNumMenu->addAction(act);
if (lineNumberMode == 2) {
act->setChecked(true);
}
act = lineNumAct->addAction(tr("CodeBlock"));
act->setToolTip(tr("Display line number in code block in edit mode (for Markdown only)"));
act->setCheckable(true);
act->setData(3);
lineNumMenu->addAction(act);
if (lineNumberMode == 3) {
act->setChecked(true);
}
}
void VMainWindow::initEditorStyleMenu(QMenu *p_menu)
{
QMenu *styleMenu = p_menu->addMenu(tr("Editor &Style"));
styleMenu->setToolTipsVisible(true);
QAction *addAct = newAction(VIconUtils::menuIcon(":/resources/icons/add_style.svg"),
tr("Add Style"),
styleMenu);
addAct->setToolTip(tr("Add custom style of editor"));
connect(addAct, &QAction::triggered,
this, [this]() {
VTipsDialog dialog(VUtils::getDocFile("tips_add_style.md"),
tr("Add Style"),
[]() {
QUrl url = QUrl::fromLocalFile(g_config->getStyleConfigFolder());
QDesktopServices::openUrl(url);
},
this);
dialog.exec();
});
styleMenu->addAction(addAct);
QActionGroup *ag = new QActionGroup(this);
connect(ag, &QActionGroup::triggered,
this, [this](QAction *p_action) {
if (!p_action) {
return;
}
QString data = p_action->data().toString();
g_config->setEditorStyle(data);
});
QList<QString> styles = g_config->getEditorStyles();
QString style = g_config->getEditorStyle();
for (auto const &item : styles) {
QAction *act = new QAction(item, ag);
act->setToolTip(tr("Set as the editor style (re-open current tabs to make it work)"));
act->setCheckable(true);
act->setData(item);
// Add it to the menu.
styleMenu->addAction(act);
if (style == item) {
act->setChecked(true);
}
}
}
void VMainWindow::setRenderBackgroundColor(QAction *action)
{
if (!action) {
return;
}
g_config->setCurRenderBackgroundColor(action->data().toString());
vnote->updateTemplate();
}
void VMainWindow::updateActionsStateFromTab(const VEditTab *p_tab)
{
const VFile *file = p_tab ? p_tab->getFile() : NULL;
bool editMode = p_tab ? p_tab->isEditMode() : false;
bool systemFile = file
&& file->getType() == FileType::Orphan
&& dynamic_cast<const VOrphanFile *>(file)->isSystemFile();
m_printAct->setEnabled(file && file->getDocType() == DocType::Markdown);
updateEditReadAct(p_tab);
saveNoteAct->setEnabled(file && editMode && file->isModifiable());
deleteNoteAct->setEnabled(file && file->getType() == FileType::Note);
noteInfoAct->setEnabled(file && !systemFile);
m_attachmentBtn->setEnabled(file && file->getType() == FileType::Note);
m_headingBtn->setEnabled(file && editMode);
setActionsEnabled(m_editToolBar, file && editMode);
// Handle heading sequence act independently.
m_headingSequenceAct->setEnabled(editMode
&& file->isModifiable()
&& isHeadingSequenceApplicable());
const VMdTab *mdTab = dynamic_cast<const VMdTab *>(p_tab);
m_headingSequenceAct->setChecked(mdTab
&& editMode
&& file->isModifiable()
&& mdTab->isHeadingSequenceEnabled());
// Find/Replace
m_findReplaceAct->setEnabled(file);
m_findNextAct->setEnabled(file);
m_findPreviousAct->setEnabled(file);
m_replaceAct->setEnabled(file && editMode);
m_replaceFindAct->setEnabled(file && editMode);
m_replaceAllAct->setEnabled(file && editMode);
if (!file) {
m_findReplaceDialog->closeDialog();
}
}
void VMainWindow::handleAreaTabStatusUpdated(const VEditTabInfo &p_info)
{
if (m_curTab != p_info.m_editTab) {
if (m_curTab) {
if (m_vimCmd->isVisible()) {
m_curTab->handleVimCmdCommandCancelled();
}
// Disconnect the trigger signal from edit tab.
disconnect((VEditTab *)m_curTab, 0, m_vimCmd, 0);
}
m_curTab = p_info.m_editTab;
if (m_curTab) {
connect((VEditTab *)m_curTab, &VEditTab::triggerVimCmd,
m_vimCmd, &VVimCmdLineEdit::reset);
}
m_vimCmd->hide();
}
if (m_curTab) {
m_curFile = m_curTab->getFile();
} else {
m_curFile = NULL;
}
if (p_info.m_type == VEditTabInfo::InfoType::All) {
updateActionsStateFromTab(m_curTab);
m_attachmentList->setFile(dynamic_cast<VNoteFile *>(m_curFile.data()));
QString title;
if (m_curFile) {
m_findReplaceDialog->updateState(m_curFile->getDocType(),
m_curTab->isEditMode());
if (m_curFile->getType() == FileType::Note) {
const VNoteFile *tmpFile = dynamic_cast<const VNoteFile *>((VFile *)m_curFile);
title = QString("[%1] %2").arg(tmpFile->getNotebookName()).arg(tmpFile->fetchPath());
} else {
title = QString("%1").arg(m_curFile->fetchPath());
}
if (!m_curFile->isModifiable()) {
title.append('#');
}
if (m_curTab->isModified()) {
title.append('*');
}
}
updateWindowTitle(title);
}
updateStatusInfo(p_info);
}
void VMainWindow::changePanelView(PanelViewState p_state)
{
switch (p_state) {
case PanelViewState::ExpandMode:
m_mainSplitter->widget(0)->hide();
m_mainSplitter->widget(1)->show();
break;
case PanelViewState::HorizontalMode:
case PanelViewState::VerticalMode:
m_mainSplitter->widget(0)->show();
m_mainSplitter->widget(1)->show();
break;
default:
break;
}
expandViewAct->setChecked(p_state == PanelViewState::ExpandMode);
}
void VMainWindow::updateWindowTitle(const QString &str)
{
QString title = "VNote";
if (!str.isEmpty()) {
title = title + " - " + str;
}
setWindowTitle(title);
}
void VMainWindow::curEditFileInfo()
{
Q_ASSERT(m_curFile);
if (m_curFile->getType() == FileType::Note) {
VNoteFile *file = dynamic_cast<VNoteFile *>((VFile *)m_curFile);
Q_ASSERT(file);
m_fileList->fileInfo(file);
} else if (m_curFile->getType() == FileType::Orphan) {
VOrphanFile *file = dynamic_cast<VOrphanFile *>((VFile *)m_curFile);
Q_ASSERT(file);
if (!file->isSystemFile()) {
editOrphanFileInfo(m_curFile);
}
}
}
void VMainWindow::deleteCurNote()
{
if (!m_curFile || m_curFile->getType() != FileType::Note) {
return;
}
VNoteFile *file = dynamic_cast<VNoteFile *>((VFile *)m_curFile);
m_fileList->deleteFile(file);
}
void VMainWindow::closeEvent(QCloseEvent *event)
{
bool isExit = m_requestQuit || !g_config->getMinimizeToStystemTray();
m_requestQuit = false;
#if defined(Q_OS_MACOS) || defined(Q_OS_MAC)
// Do not support minimized to tray on macOS.
isExit = true;
#endif
if (!isExit && g_config->getMinimizeToStystemTray() == -1) {
// Not initialized yet. Prompt for user.
int ret = VUtils::showMessage(QMessageBox::Information,
tr("Close VNote"),
tr("Do you want to minimize VNote to system tray "
"instead of quitting it when closing VNote?"),
tr("You could change the option in Settings later."),
QMessageBox::Ok | QMessageBox::No | QMessageBox::Cancel,
QMessageBox::Ok,
this);
if (ret == QMessageBox::Ok) {
g_config->setMinimizeToSystemTray(1);
} else if (ret == QMessageBox::No) {
g_config->setMinimizeToSystemTray(0);
isExit = true;
} else {
event->ignore();
return;
}
}
if (isVisible()) {
saveStateAndGeometry();
}
if (isExit || !m_trayIcon->isVisible()) {
// Get all the opened tabs.
bool saveOpenedNotes = g_config->getStartupPageType() == StartupPageType::ContinueLeftOff;
QVector<VFileSessionInfo> fileInfos;
QVector<VEditTabInfo> tabs;
if (saveOpenedNotes) {
tabs = m_editArea->getAllTabsInfo();
fileInfos.reserve(tabs.size());
for (auto const & tab : tabs) {
// Skip system file.
VFile *file = tab.m_editTab->getFile();
if (file->getType() == FileType::Orphan
&& dynamic_cast<VOrphanFile *>(file)->isSystemFile()) {
continue;
}
VFileSessionInfo info = VFileSessionInfo::fromEditTabInfo(&tab);
if (tab.m_editTab == m_curTab) {
info.setActive(true);
}
fileInfos.push_back(info);
qDebug() << "file session:" << info.m_file << (info.m_mode == OpenFileMode::Edit);
}
}
if (!m_editArea->closeAllFiles(false)) {
// Fail to close all the opened files, cancel closing app.
event->ignore();
return;
}
if (saveOpenedNotes) {
g_config->setLastOpenedFiles(fileInfos);
}
QMainWindow::closeEvent(event);
qApp->quit();
} else {
hide();
event->ignore();
}
}
void VMainWindow::saveStateAndGeometry()
{
g_config->setMainWindowGeometry(saveGeometry());
g_config->setMainWindowState(saveState());
g_config->setToolsDockChecked(m_toolDock->isVisible());
g_config->setSearchDockChecked(m_searchDock->isVisible());
g_config->setNotebookSplitterState(m_nbSplitter->saveState());
g_config->setMainSplitterState(m_mainSplitter->saveState());
m_tagExplorer->saveStateAndGeometry();
g_config->setNaviBoxCurrentIndex(m_naviBox->currentIndex());
}
void VMainWindow::restoreStateAndGeometry()
{
const QByteArray geometry = g_config->getMainWindowGeometry();
if (!geometry.isEmpty()) {
restoreGeometry(geometry);
}
const QByteArray state = g_config->getMainWindowState();
if (!state.isEmpty()) {
restoreState(state);
}
m_toolDock->setVisible(g_config->getToolsDockChecked());
m_searchDock->setVisible(g_config->getSearchDockChecked());
const QByteArray splitterState = g_config->getMainSplitterState();
if (!splitterState.isEmpty()) {
m_mainSplitter->restoreState(splitterState);
}
const QByteArray nbSplitterState = g_config->getNotebookSplitterState();
if (!nbSplitterState.isEmpty()) {
m_nbSplitter->restoreState(nbSplitterState);
}
m_naviBox->setCurrentIndex(g_config->getNaviBoxCurrentIndex());
}
void VMainWindow::handleCurrentDirectoryChanged(const VDirectory *p_dir)
{
newNoteAct->setEnabled(p_dir);
m_importNoteAct->setEnabled(p_dir);
}
void VMainWindow::handleCurrentNotebookChanged(const VNotebook *p_notebook)
{
newRootDirAct->setEnabled(p_notebook);
}
void VMainWindow::keyPressEvent(QKeyEvent *event)
{
int key = event->key();
Qt::KeyboardModifiers modifiers = event->modifiers();
if (key == Qt::Key_Escape
|| (key == Qt::Key_BracketLeft
&& modifiers == Qt::ControlModifier)) {
m_findReplaceDialog->closeDialog();
event->accept();
return;
}
QMainWindow::keyPressEvent(event);
}
bool VMainWindow::locateFile(VFile *p_file)
{
bool ret = false;
if (!p_file || p_file->getType() != FileType::Note) {
return ret;
}
VNoteFile *file = dynamic_cast<VNoteFile *>(p_file);
VNotebook *notebook = file->getNotebook();
if (m_notebookSelector->locateNotebook(notebook)) {
while (m_dirTree->currentNotebook() != notebook) {
QCoreApplication::sendPostedEvents();
}
VDirectory *dir = file->getDirectory();
if (m_dirTree->locateDirectory(dir)) {
while (m_fileList->currentDirectory() != dir) {
QCoreApplication::sendPostedEvents();
}
if (m_fileList->locateFile(file)) {
ret = true;
m_fileList->setFocus();
}
}
}
// Open the directory and file panels after location.
if (ret) {
showNotebookPanel();
}
return ret;
}
bool VMainWindow::locateDirectory(VDirectory *p_directory)
{
bool ret = false;
if (!p_directory) {
return ret;
}
VNotebook *notebook = p_directory->getNotebook();
if (m_notebookSelector->locateNotebook(notebook)) {
while (m_dirTree->currentNotebook() != notebook) {
QCoreApplication::sendPostedEvents();
}
if (m_dirTree->locateDirectory(p_directory)) {
ret = true;
m_dirTree->setFocus();
}
}
// Open the directory and file panels after location.
if (ret) {
showNotebookPanel();
}
return ret;
}
bool VMainWindow::locateNotebook(VNotebook *p_notebook)
{
bool ret = false;
if (!p_notebook) {
return ret;
}
if (m_notebookSelector->locateNotebook(p_notebook)) {
ret = true;
m_dirTree->setFocus();
}
// Open the directory and file panels after location.
if (ret) {
showNotebookPanel();
}
return ret;
}
void VMainWindow::handleFindDialogTextChanged(const QString &p_text, uint /* p_options */)
{
bool enabled = true;
if (p_text.isEmpty()) {
enabled = false;
}
m_findNextAct->setEnabled(enabled);
m_findPreviousAct->setEnabled(enabled);
m_replaceAct->setEnabled(enabled);
m_replaceFindAct->setEnabled(enabled);
m_replaceAllAct->setEnabled(enabled);
}
void VMainWindow::openFindDialog()
{
m_findReplaceDialog->openDialog(m_editArea->getSelectedText());
}
void VMainWindow::viewSettings()
{
VSettingsDialog settingsDialog(this);
settingsDialog.exec();
}
void VMainWindow::closeCurrentFile()
{
if (m_curFile) {
m_editArea->closeFile(m_curFile, false);
}
}
void VMainWindow::changeAutoIndent(bool p_checked)
{
g_config->setAutoIndent(p_checked);
}
void VMainWindow::changeAutoList(bool p_checked)
{
g_config->setAutoList(p_checked);
if (p_checked) {
if (!m_autoIndentAct->isChecked()) {
m_autoIndentAct->trigger();
}
m_autoIndentAct->setEnabled(false);
} else {
m_autoIndentAct->setEnabled(true);
}
}
void VMainWindow::changeVimMode(bool p_checked)
{
g_config->setEnableVimMode(p_checked);
}
void VMainWindow::enableCodeBlockHighlight(bool p_checked)
{
g_config->setEnableCodeBlockHighlight(p_checked);
}
void VMainWindow::enableImagePreview(bool p_checked)
{
g_config->setEnablePreviewImages(p_checked);
emit editorConfigUpdated();
}
void VMainWindow::enableImagePreviewConstraint(bool p_checked)
{
g_config->setEnablePreviewImageConstraint(p_checked);
emit editorConfigUpdated();
}
void VMainWindow::enableImageConstraint(bool p_checked)
{
g_config->setEnableImageConstraint(p_checked);
vnote->updateTemplate();
}
void VMainWindow::enableImageCaption(bool p_checked)
{
g_config->setEnableImageCaption(p_checked);
}
void VMainWindow::shortcutsHelp()
{
QString docFile = VUtils::getDocFile(VNote::c_shortcutsDocFile);
VFile *file = vnote->getOrphanFile(docFile, false, true);
m_editArea->openFile(file, OpenFileMode::Read);
}
void VMainWindow::printNote()
{
if (m_printer
|| !m_curFile
|| m_curFile->getDocType() != DocType::Markdown) {
return;
}
m_printer = new QPrinter();
QPrintDialog dialog(m_printer, this);
dialog.setWindowTitle(tr("Print Note"));
V_ASSERT(m_curTab);
VMdTab *mdTab = dynamic_cast<VMdTab *>((VEditTab *)m_curTab);
VWebView *webView = mdTab->getWebViewer();
V_ASSERT(webView);
if (webView->hasSelection()) {
dialog.addEnabledOption(QAbstractPrintDialog::PrintSelection);
}
if (dialog.exec() == QDialog::Accepted) {
webView->page()->print(m_printer, [this](bool p_succ) {
qDebug() << "print web page callback" << p_succ;
delete m_printer;
m_printer = NULL;
});
} else {
delete m_printer;
m_printer = NULL;
}
}
QAction *VMainWindow::newAction(const QIcon &p_icon,
const QString &p_text,
QObject *p_parent)
{
#if defined(Q_OS_MACOS) || defined(Q_OS_MAC)
Q_UNUSED(p_icon);
return new QAction(p_text, p_parent);
#else
return new QAction(p_icon, p_text, p_parent);
#endif
}
void VMainWindow::showStatusMessage(const QString &p_msg)
{
const int timeout = 5000;
statusBar()->showMessage(p_msg, timeout);
}
void VMainWindow::updateStatusInfo(const VEditTabInfo &p_info)
{
if (m_curTab) {
m_tabIndicator->update(p_info);
m_tabIndicator->show();
if (m_curTab->isEditMode()) {
if (p_info.m_type == VEditTabInfo::InfoType::All) {
m_curTab->requestUpdateVimStatus();
}
} else {
m_vimIndicator->hide();
}
} else {
m_tabIndicator->hide();
m_vimIndicator->hide();
}
}
void VMainWindow::handleVimStatusUpdated(const VVim *p_vim)
{
m_vimIndicator->update(p_vim);
if (!p_vim || !m_curTab || !m_curTab->isEditMode()) {
m_vimIndicator->hide();
} else {
m_vimIndicator->show();
}
}
bool VMainWindow::tryOpenInternalFile(const QString &p_filePath)
{
if (p_filePath.isEmpty()) {
return false;
}
if (QFileInfo::exists(p_filePath)) {
VFile *file = vnote->getInternalFile(p_filePath);
if (file) {
m_editArea->openFile(file, OpenFileMode::Read);
return true;
}
}
return false;
}
QVector<VFile *> VMainWindow::openFiles(const QStringList &p_files,
bool p_forceOrphan,
OpenFileMode p_mode,
bool p_forceMode,
bool p_oneByOne)
{
QVector<VFile *> vfiles;
vfiles.reserve(p_files.size());
for (int i = 0; i < p_files.size(); ++i) {
if (!QFileInfo::exists(p_files[i])) {
qWarning() << "file" << p_files[i] << "does not exist";
continue;
}
VFile *file = NULL;
if (!p_forceOrphan) {
file = vnote->getInternalFile(p_files[i]);
}
if (!file) {
file = vnote->getOrphanFile(p_files[i], true);
}
m_editArea->openFile(file, p_mode, p_forceMode);
vfiles.append(file);
if (p_oneByOne) {
QCoreApplication::sendPostedEvents();
}
}
return vfiles;
}
void VMainWindow::editOrphanFileInfo(VFile *p_file)
{
VOrphanFile *file = dynamic_cast<VOrphanFile *>(p_file);
Q_ASSERT(file);
VOrphanFileInfoDialog dialog(file, this);
if (dialog.exec() == QDialog::Accepted) {
QString imgFolder = dialog.getImageFolder();
file->setImageFolder(imgFolder);
}
}
void VMainWindow::checkSharedMemory()
{
QStringList files = m_guard->fetchFilesToOpen();
if (!files.isEmpty()) {
qDebug() << "shared memory fetch files" << files;
openFiles(files, false, g_config->getNoteOpenMode(), false, false);
// Eliminate the signal.
m_guard->fetchAskedToShow();
showMainWindow();
} else if (m_guard->fetchAskedToShow()) {
qDebug() << "shared memory asked to show up";
showMainWindow();
}
}
void VMainWindow::initTrayIcon()
{
QMenu *menu = new QMenu(this);
QAction *showMainWindowAct = menu->addAction(tr("Show VNote"));
connect(showMainWindowAct, &QAction::triggered,
this, &VMainWindow::showMainWindow);
QAction *exitAct = menu->addAction(tr("Quit"));
connect(exitAct, &QAction::triggered,
this, &VMainWindow::quitApp);
m_trayIcon = new QSystemTrayIcon(QIcon(":/resources/icons/32x32/vnote.png"), this);
m_trayIcon->setToolTip(tr("VNote"));
m_trayIcon->setContextMenu(menu);
connect(m_trayIcon, &QSystemTrayIcon::activated,
this, [this](QSystemTrayIcon::ActivationReason p_reason){
if (p_reason == QSystemTrayIcon::Trigger) {
this->showMainWindow();
}
});
m_trayIcon->show();
}
void VMainWindow::changeEvent(QEvent *p_event)
{
if (p_event->type() == QEvent::WindowStateChange) {
QWindowStateChangeEvent *eve = dynamic_cast<QWindowStateChangeEvent *>(p_event);
m_windowOldState = eve->oldState();
}
QMainWindow::changeEvent(p_event);
}
void VMainWindow::showMainWindow()
{
if (this->isMinimized()) {
if (m_windowOldState & Qt::WindowMaximized) {
this->showMaximized();
} else if (m_windowOldState & Qt::WindowFullScreen) {
this->showFullScreen();
} else {
this->showNormal();
}
} else {
this->show();
// Need to call raise() in macOS.
this->raise();
}
this->activateWindow();
}
void VMainWindow::openStartupPages()
{
StartupPageType type = g_config->getStartupPageType();
switch (type) {
case StartupPageType::ContinueLeftOff:
{
QVector<VFileSessionInfo> files = g_config->getLastOpenedFiles();
qDebug() << "open" << files.size() << "last opened files";
m_editArea->openFiles(files, true);
break;
}
case StartupPageType::SpecificPages:
{
QStringList pagesToOpen = VUtils::filterFilePathsToOpen(g_config->getStartupPages());
qDebug() << "open startup pages" << pagesToOpen;
openFiles(pagesToOpen, false, g_config->getNoteOpenMode(), false, true);
break;
}
default:
break;
}
}
bool VMainWindow::isHeadingSequenceApplicable() const
{
if (!m_curTab) {
return false;
}
Q_ASSERT(m_curFile);
if (!m_curFile->isModifiable()
|| m_curFile->getDocType() != DocType::Markdown) {
return false;
}
return true;
}
// Popup the attachment list if it is enabled.
bool VMainWindow::showAttachmentListByCaptain(void *p_target, void *p_data)
{
Q_UNUSED(p_data);
VMainWindow *obj = static_cast<VMainWindow *>(p_target);
if (obj->m_attachmentBtn->isEnabled()) {
// Show tool bar first.
bool toolBarChecked = obj->m_toolBarAct->isChecked();
if (!toolBarChecked) {
obj->setToolBarVisible(true);
// Make it visible first.
QCoreApplication::sendPostedEvents();
}
obj->m_attachmentBtn->showPopupWidget();
if (!toolBarChecked) {
obj->setToolBarVisible(false);
}
}
return true;
}
bool VMainWindow::locateCurrentFileByCaptain(void *p_target, void *p_data)
{
Q_UNUSED(p_data);
VMainWindow *obj = static_cast<VMainWindow *>(p_target);
if (obj->m_curFile) {
if (obj->locateFile(obj->m_curFile)) {
return false;
}
}
return true;
}
bool VMainWindow::toggleExpandModeByCaptain(void *p_target, void *p_data)
{
Q_UNUSED(p_data);
VMainWindow *obj = static_cast<VMainWindow *>(p_target);
obj->expandViewAct->trigger();
return true;
}
bool VMainWindow::discardAndReadByCaptain(void *p_target, void *p_data)
{
Q_UNUSED(p_data);
VMainWindow *obj = static_cast<VMainWindow *>(p_target);
if (obj->m_curTab) {
obj->m_discardExitAct->trigger();
obj->m_curTab->setFocus();
return false;
}
return true;
}
bool VMainWindow::toggleToolBarByCaptain(void *p_target, void *p_data)
{
Q_UNUSED(p_data);
VMainWindow *obj = static_cast<VMainWindow *>(p_target);
obj->m_toolBarAct->trigger();
return true;
}
bool VMainWindow::toggleToolsDockByCaptain(void *p_target, void *p_data)
{
Q_UNUSED(p_data);
VMainWindow *obj = static_cast<VMainWindow *>(p_target);
obj->m_toolDock->setVisible(!obj->m_toolDock->isVisible());
return true;
}
bool VMainWindow::toggleSearchDockByCaptain(void *p_target, void *p_data)
{
Q_UNUSED(p_data);
VMainWindow *obj = static_cast<VMainWindow *>(p_target);
bool visible = obj->m_searchDock->isVisible();
obj->m_searchDock->setVisible(!visible);
if (!visible) {
obj->m_searcher->focusToSearch();
return false;
}
return true;
}
bool VMainWindow::closeFileByCaptain(void *p_target, void *p_data)
{
Q_UNUSED(p_data);
VMainWindow *obj = static_cast<VMainWindow *>(p_target);
obj->closeCurrentFile();
QWidget *nextFocus = obj->m_editArea->getCurrentTab();
if (nextFocus) {
nextFocus->setFocus();
} else {
obj->m_fileList->setFocus();
}
return false;
}
bool VMainWindow::shortcutsHelpByCaptain(void *p_target, void *p_data)
{
Q_UNUSED(p_data);
VMainWindow *obj = static_cast<VMainWindow *>(p_target);
obj->shortcutsHelp();
return false;
}
bool VMainWindow::flushLogFileByCaptain(void *p_target, void *p_data)
{
Q_UNUSED(p_target);
Q_UNUSED(p_data);
#if defined(QT_NO_DEBUG)
// Flush g_logFile.
g_logFile.flush();
#endif
return true;
}
bool VMainWindow::exportByCaptain(void *p_target, void *p_data)
{
Q_UNUSED(p_data);
VMainWindow *obj = static_cast<VMainWindow *>(p_target);
QTimer::singleShot(50, obj, SLOT(handleExportAct()));
return true;
}
bool VMainWindow::focusEditAreaByCaptain(void *p_target, void *p_data)
{
Q_UNUSED(p_data);
VMainWindow *obj = static_cast<VMainWindow *>(p_target);
obj->focusEditArea();
return false;
}
void VMainWindow::promptNewNotebookIfEmpty()
{
if (vnote->getNotebooks().isEmpty()) {
m_notebookSelector->newNotebook();
}
}
void VMainWindow::initShortcuts()
{
QString keySeq = g_config->getShortcutKeySequence("CloseNote");
qDebug() << "set CloseNote shortcut to" << keySeq;
if (!keySeq.isEmpty()) {
QShortcut *closeNoteShortcut = new QShortcut(QKeySequence(keySeq), this);
closeNoteShortcut->setContext(Qt::WidgetWithChildrenShortcut);
connect(closeNoteShortcut, &QShortcut::activated,
this, &VMainWindow::closeCurrentFile);
}
}
void VMainWindow::openFlashPage()
{
openFiles(QStringList() << g_config->getFlashPage(),
false,
OpenFileMode::Edit,
true);
}
void VMainWindow::initHeadingButton(QToolBar *p_tb)
{
m_headingBtn = new QPushButton(VIconUtils::toolButtonIcon(":/resources/icons/heading.svg"),
"",
this);
m_headingBtn->setToolTip(tr("Headings"));
m_headingBtn->setProperty("CornerBtn", true);
m_headingBtn->setFocusPolicy(Qt::NoFocus);
m_headingBtn->setEnabled(false);
QMenu *menu = new QMenu(this);
QString text(tr("Heading %1"));
QString tooltip(tr("Heading %1\t%2"));
QWidgetAction *wact = new QWidgetAction(menu);
wact->setData(1);
VButtonMenuItem *w = new VButtonMenuItem(wact, text.arg(1), this);
w->setToolTip(tooltip.arg(1).arg(VUtils::getShortcutText("Ctrl+1")));
w->setProperty("Heading1", true);
wact->setDefaultWidget(w);
menu->addAction(wact);
wact = new QWidgetAction(menu);
wact->setData(2);
w = new VButtonMenuItem(wact, text.arg(2), this);
w->setToolTip(tooltip.arg(2).arg(VUtils::getShortcutText("Ctrl+2")));
w->setProperty("Heading2", true);
wact->setDefaultWidget(w);
menu->addAction(wact);
wact = new QWidgetAction(menu);
wact->setData(3);
w = new VButtonMenuItem(wact, text.arg(3), this);
w->setToolTip(tooltip.arg(3).arg(VUtils::getShortcutText("Ctrl+3")));
w->setProperty("Heading3", true);
wact->setDefaultWidget(w);
menu->addAction(wact);
wact = new QWidgetAction(menu);
wact->setData(4);
w = new VButtonMenuItem(wact, text.arg(4), this);
w->setToolTip(tooltip.arg(4).arg(VUtils::getShortcutText("Ctrl+4")));
w->setProperty("Heading4", true);
wact->setDefaultWidget(w);
menu->addAction(wact);
wact = new QWidgetAction(menu);
wact->setData(5);
w = new VButtonMenuItem(wact, text.arg(5), this);
w->setToolTip(tooltip.arg(5).arg(VUtils::getShortcutText("Ctrl+5")));
w->setProperty("Heading5", true);
wact->setDefaultWidget(w);
menu->addAction(wact);
wact = new QWidgetAction(menu);
wact->setData(6);
w = new VButtonMenuItem(wact, text.arg(6), this);
w->setToolTip(tooltip.arg(6).arg(VUtils::getShortcutText("Ctrl+6")));
w->setProperty("Heading6", true);
wact->setDefaultWidget(w);
menu->addAction(wact);
wact = new QWidgetAction(menu);
wact->setData(0);
w = new VButtonMenuItem(wact, tr("Clear"), this);
w->setToolTip(tr("Clear\t%1").arg(VUtils::getShortcutText("Ctrl+7")));
wact->setDefaultWidget(w);
menu->addAction(wact);
connect(menu, &QMenu::triggered,
this, [this, menu](QAction *p_action) {
if (m_curTab) {
int level = p_action->data().toInt();
m_curTab->decorateText(TextDecoration::Heading, level);
}
menu->hide();
});
m_headingBtn->setMenu(menu);
p_tb->addWidget(m_headingBtn);
}
void VMainWindow::initThemeMenu(QMenu *p_menu)
{
QMenu *themeMenu = p_menu->addMenu(tr("Theme"));
themeMenu->setToolTipsVisible(true);
QAction *addAct = newAction(VIconUtils::menuIcon(":/resources/icons/add_style.svg"),
tr("Add Theme"),
themeMenu);
addAct->setToolTip(tr("Add custom theme"));
connect(addAct, &QAction::triggered,
this, [this]() {
VTipsDialog dialog(VUtils::getDocFile("tips_add_theme.md"),
tr("Add Theme"),
[]() {
QUrl url = QUrl::fromLocalFile(g_config->getThemeConfigFolder());
QDesktopServices::openUrl(url);
},
this);
dialog.exec();
});
themeMenu->addAction(addAct);
QActionGroup *ag = new QActionGroup(this);
connect(ag, &QActionGroup::triggered,
this, [this](QAction *p_action) {
if (!p_action) {
return;
}
QString data = p_action->data().toString();
g_config->setTheme(data);
});
QList<QString> themes = g_config->getThemes();
QString theme = g_config->getTheme();
for (auto const &item : themes) {
QAction *act = new QAction(item, ag);
act->setToolTip(tr("Set as the theme of VNote (restart VNote to make it work)"));
act->setCheckable(true);
act->setData(item);
// Add it to the menu.
themeMenu->addAction(act);
if (theme == item) {
act->setChecked(true);
}
}
}
void VMainWindow::customShortcut()
{
VTipsDialog dialog(VUtils::getDocFile("tips_custom_shortcut.md"),
tr("Customize Shortcuts"),
[]() {
#if defined(Q_OS_MACOS) || defined(Q_OS_MAC)
// On macOS, it seems that we could not open that ini file directly.
QUrl url = QUrl::fromLocalFile(g_config->getConfigFolder());
#else
QUrl url = QUrl::fromLocalFile(g_config->getConfigFilePath());
#endif
QDesktopServices::openUrl(url);
},
this);
dialog.exec();
}
void VMainWindow::initVimCmd()
{
m_vimCmd = new VVimCmdLineEdit(this);
m_vimCmd->setProperty("VimCommandLine", true);
connect(m_vimCmd, &VVimCmdLineEdit::commandCancelled,
this, [this]() {
if (m_curTab) {
m_curTab->focusTab();
}
// NOTICE: should not hide before setting focus to edit tab.
m_vimCmd->hide();
if (m_curTab) {
m_curTab->handleVimCmdCommandCancelled();
}
});
connect(m_vimCmd, &VVimCmdLineEdit::commandFinished,
this, [this](VVim::CommandLineType p_type, const QString &p_cmd) {
if (m_curTab) {
m_curTab->focusTab();
}
m_vimCmd->hide();
// Hide the cmd line edit before execute the command.
// If we execute the command first, we will get Chinese input
// method enabled after returning to read mode.
if (m_curTab) {
m_curTab->handleVimCmdCommandFinished(p_type, p_cmd);
}
});
connect(m_vimCmd, &VVimCmdLineEdit::commandChanged,
this, [this](VVim::CommandLineType p_type, const QString &p_cmd) {
if (m_curTab) {
m_curTab->handleVimCmdCommandChanged(p_type, p_cmd);
}
});
connect(m_vimCmd, &VVimCmdLineEdit::requestNextCommand,
this, [this](VVim::CommandLineType p_type, const QString &p_cmd) {
if (m_curTab) {
QString cmd = m_curTab->handleVimCmdRequestNextCommand(p_type, p_cmd);
if (!cmd.isNull()) {
m_vimCmd->setCommand(cmd);
} else {
m_vimCmd->restoreUserLastInput();
}
}
});
connect(m_vimCmd, &VVimCmdLineEdit::requestPreviousCommand,
this, [this](VVim::CommandLineType p_type, const QString &p_cmd) {
if (m_curTab) {
QString cmd = m_curTab->handleVimCmdRequestPreviousCommand(p_type, p_cmd);
if (!cmd.isNull()) {
m_vimCmd->setCommand(cmd);
}
}
});
connect(m_vimCmd, &VVimCmdLineEdit::requestRegister,
this, [this](int p_key, int p_modifiers){
if (m_curTab) {
QString val = m_curTab->handleVimCmdRequestRegister(p_key, p_modifiers);
if (!val.isEmpty()) {
m_vimCmd->setText(m_vimCmd->text() + val);
}
}
});
m_vimCmd->hide();
}
void VMainWindow::toggleEditReadMode()
{
if (!m_curTab) {
return;
}
if (m_curTab->isEditMode()) {
// Save changes and read.
m_editArea->saveAndReadFile();
} else {
// Edit.
m_editArea->editFile();
}
}
void VMainWindow::updateEditReadAct(const VEditTab *p_tab)
{
static QIcon editIcon = VIconUtils::toolButtonIcon(":/resources/icons/edit_note.svg");
static QString editText;
static QIcon readIcon = VIconUtils::toolButtonIcon(":/resources/icons/save_exit.svg");
static QString readText;
if (editText.isEmpty()) {
QString keySeq = g_config->getShortcutKeySequence("EditReadNote");
QKeySequence seq(keySeq);
if (!seq.isEmpty()) {
QString shortcutText = VUtils::getShortcutText(keySeq);
editText = tr("Edit\t%1").arg(shortcutText);
readText = tr("Save Changes And Read\t%1").arg(shortcutText);
m_editReadAct->setShortcut(seq);
} else {
editText = tr("Edit");
readText = tr("Save Changes And Read");
}
}
if (!p_tab || !p_tab->isEditMode()) {
// Edit.
m_editReadAct->setIcon(editIcon);
m_editReadAct->setText(editText);
m_editReadAct->setStatusTip(tr("Edit current note"));
m_discardExitAct->setEnabled(false);
} else {
// Read.
m_editReadAct->setIcon(readIcon);
m_editReadAct->setText(readText);
m_editReadAct->setStatusTip(tr("Save changes and exit edit mode"));
m_discardExitAct->setEnabled(true);
}
m_editReadAct->setEnabled(p_tab);
}
void VMainWindow::handleExportAct()
{
VExportDialog dialog(m_notebookSelector->currentNotebook(),
m_dirTree->currentDirectory(),
m_curFile,
m_cart,
g_config->getMdConverterType(),
this);
dialog.exec();
}
VNotebook *VMainWindow::getCurrentNotebook() const
{
return m_notebookSelector->currentNotebook();
}
void VMainWindow::activateUniversalEntry()
{
if (!m_ue) {
initUniversalEntry();
}
m_captain->setCaptainModeEnabled(false);
// Move it to the top left corner of edit area.
QPoint topLeft = m_editArea->mapToGlobal(QPoint(0, 0));
QRect eaRect = m_editArea->editAreaRect();
topLeft += eaRect.topLeft();
// Use global position.
m_ue->move(topLeft);
eaRect.moveTop(0);
m_ue->setAvailableRect(eaRect);
m_ue->show();
m_ue->raise();
}
void VMainWindow::initUniversalEntry()
{
m_ue = new VUniversalEntry(this);
m_ue->hide();
#if defined(Q_OS_MACOS) || defined(Q_OS_MAC)
// Qt::Popup on macOS does not work well with input method.
m_ue->setWindowFlags(Qt::Tool
| Qt::NoDropShadowWindowHint);
m_ue->setWindowModality(Qt::ApplicationModal);
#else
m_ue->setWindowFlags(Qt::Popup
| Qt::FramelessWindowHint
| Qt::NoDropShadowWindowHint);
#endif
connect(m_ue, &VUniversalEntry::exited,
this, [this]() {
m_captain->setCaptainModeEnabled(true);
});
// Register entries.
VSearchUE *searchUE = new VSearchUE(this);
m_ue->registerEntry('q', searchUE, VSearchUE::Name_FolderNote_AllNotebook);
m_ue->registerEntry('a', searchUE, VSearchUE::Content_Note_AllNotebook);
m_ue->registerEntry('z', searchUE, VSearchUE::Tag_Note_AllNotebook);
m_ue->registerEntry('w', searchUE, VSearchUE::Name_Notebook_AllNotebook);
m_ue->registerEntry('e', searchUE, VSearchUE::Name_FolderNote_CurrentNotebook);
m_ue->registerEntry('d', searchUE, VSearchUE::Content_Note_CurrentNotebook);
m_ue->registerEntry('c', searchUE, VSearchUE::Tag_Note_CurrentNotebook);
m_ue->registerEntry('r', searchUE, VSearchUE::Name_FolderNote_CurrentFolder);
m_ue->registerEntry('f', searchUE, VSearchUE::Content_Note_CurrentFolder);
m_ue->registerEntry('v', searchUE, VSearchUE::Tag_Note_CurrentFolder);
m_ue->registerEntry('t', searchUE, VSearchUE::Name_Note_Buffer);
m_ue->registerEntry('g', searchUE, VSearchUE::Content_Note_Buffer);
m_ue->registerEntry('b', searchUE, VSearchUE::Outline_Note_Buffer);
m_ue->registerEntry('u', searchUE, VSearchUE::Content_Note_ExplorerDirectory);
m_ue->registerEntry('y', new VOutlineUE(this), 0);
m_ue->registerEntry('h', searchUE, VSearchUE::Path_FolderNote_AllNotebook);
m_ue->registerEntry('n', searchUE, VSearchUE::Path_FolderNote_CurrentNotebook);
m_ue->registerEntry('m', new VListFolderUE(this), 0);
m_ue->registerEntry('j', new VListUE(this), VListUE::History);
m_ue->registerEntry('?', new VHelpUE(this), 0);
}
void VMainWindow::checkNotebooks()
{
bool updated = false;
QVector<VNotebook *> ¬ebooks = g_vnote->getNotebooks();
for (int i = 0; i < notebooks.size(); ++i) {
VNotebook *nb = notebooks[i];
if (nb->isValid()) {
continue;
}
VFixNotebookDialog dialog(nb, notebooks, this);
if (dialog.exec()) {
qDebug() << "fix path of notebook" << nb->getName() << "to" << dialog.getPathInput();
nb->updatePath(dialog.getPathInput());
} else {
notebooks.removeOne(nb);
--i;
}
updated = true;
}
if (updated) {
g_config->setNotebooks(notebooks);
m_notebookSelector->update();
}
m_notebookSelector->restoreCurrentNotebook();
}
void VMainWindow::setMenuBarVisible(bool p_visible)
{
// Hiding the menubar will disable the shortcut of QActions.
if (p_visible) {
menuBar()->setFixedSize(QSize(QWIDGETSIZE_MAX, QWIDGETSIZE_MAX));
} else {
menuBar()->setFixedHeight(0);
}
}
void VMainWindow::setToolBarVisible(bool p_visible)
{
for (auto bar : m_toolBars) {
if (p_visible) {
bar->setFixedSize(QSize(QWIDGETSIZE_MAX, QWIDGETSIZE_MAX));
} else {
bar->setFixedHeight(0);
}
}
}
void VMainWindow::kickOffStartUpTimer(const QStringList &p_files)
{
QTimer::singleShot(300, [this, p_files]() {
checkNotebooks();
QCoreApplication::sendPostedEvents();
promptNewNotebookIfEmpty();
QCoreApplication::sendPostedEvents();
openStartupPages();
openFiles(p_files, false, g_config->getNoteOpenMode(), false, true);
});
}
void VMainWindow::showNotebookPanel()
{
changePanelView(PanelViewState::VerticalMode);
m_naviBox->setCurrentIndex(NaviBoxIndex::NotebookPanel, false);
}
void VMainWindow::showExplorerPanel(bool p_focus)
{
changePanelView(PanelViewState::VerticalMode);
m_naviBox->setCurrentIndex(NaviBoxIndex::Explorer, p_focus);
}
void VMainWindow::stayOnTop(bool p_enabled)
{
bool shown = isVisible();
Qt::WindowFlags flags = this->windowFlags();
Qt::WindowFlags magicFlag = Qt::WindowStaysOnTopHint;
if (p_enabled) {
setWindowFlags(flags | magicFlag);
} else {
setWindowFlags(flags ^ magicFlag);
}
if (shown) {
show();
}
}
void VMainWindow::focusEditArea() const
{
QWidget *widget = m_editArea->getCurrentTab();
if (!widget) {
widget = m_editArea;
}
widget->setFocus();
}
|
// Copyright 2019-2021 Cambridge Quantum Computing
//
// 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 "ComparisonFunctions.hpp"
#include <sstream>
#include <stdexcept>
// NOTE: this is an identical copy of a file in tket-tests, in the Simulation
// folder. This is deliberate! Please keep both in sync!
// See the tket-tests file for a mathematical discussion.
namespace tket {
namespace tket_sim {
// Checks that they're both column vectors, or both square, of the same size.
// Throws if not.
static void throw_if_invalid_sizes(
const Eigen::MatrixXcd& m1, const Eigen::MatrixXcd& m2) {
if (m1.rows() != m2.rows() || m1.cols() != m2.cols()) {
throw std::runtime_error("Different sized matrices");
}
// Check that it has 2^n rows for some n. Will throw if not.
(void)get_number_of_qubits(m1.rows());
if (m1.rows() == m1.cols() || m1.cols() == 1) {
// Square, or a column vector.
return;
}
throw std::runtime_error("Not square, and also not column vectors");
}
// Note: these should NOT be asserts, because it is conceivable
// that a really deep circuit could be tested, with so many gates
// that the numerical errors build up and make matrices
// which are not almost unitary.
static void throw_if_not_unitary_or_unnormalised_statevector(
const Eigen::MatrixXcd& m, double tolerance) {
const Eigen::MatrixXcd product = m.adjoint() * m;
if (product.isApprox(
Eigen::MatrixXcd::Identity(product.rows(), product.rows()),
tolerance)) {
return;
}
if (product.rows() == 1) {
// Of course, for 0-qubit circuits there's no distinction between
// state vectors and 1x1 unitaries! Don't worry about this.
throw std::runtime_error("State vector is not normalised");
}
throw std::runtime_error("Matrix is not unitary");
}
static bool compare_statevectors_or_unitaries_may_throw(
const Eigen::MatrixXcd& m1, const Eigen::MatrixXcd& m2,
MatrixEquivalence equivalence, double tolerance) {
throw_if_invalid_sizes(m1, m2);
throw_if_not_unitary_or_unnormalised_statevector(m1, tolerance);
throw_if_not_unitary_or_unnormalised_statevector(m2, tolerance);
if (equivalence == MatrixEquivalence::EQUAL) {
return m1.isApprox(m2, tolerance);
}
// We allow equivalence only up to global phase.
// We now know that U,V are EITHER almost unitary,
// OR almost norm one column vectors.
// See the above mathematical discussion:
// if A = cB for some |c|=1, then (A adj)B = (c*)(B adj)B = (c*)Id,
// where Id may be 1x1.
//
// Thus (U adj)V will be approximately diagonal, with diagonal entries
// almost equal to each other.
const Eigen::MatrixXcd product = m1.adjoint() * m2;
auto entry = product(0, 0);
const double entry_abs = std::abs(entry);
if (!(std::abs(entry_abs - 1.0) < tolerance)) {
// Catch NaNs also! Although they should already have been
// caught above in the unitary/norm one checks.
return false;
}
const auto size = product.rows();
if (size == 1) {
return true;
}
// Shouldn't make much difference but do it anyway.
entry /= entry_abs;
return product.isApprox(
entry * Eigen::MatrixXcd::Identity(size, size), tolerance);
}
bool compare_statevectors_or_unitaries(
const Eigen::MatrixXcd& m1, const Eigen::MatrixXcd& m2,
MatrixEquivalence equivalence, double tolerance) {
try {
return compare_statevectors_or_unitaries_may_throw(
m1, m2, equivalence, tolerance);
} catch (const std::exception& e) {
std::stringstream ss;
ss << "Input matrices have sizes (" << m1.rows() << "," << m1.cols()
<< ") and (" << m2.rows() << "," << m2.cols() << "). tol=" << tolerance
<< " : " << e.what();
throw std::runtime_error(ss.str());
}
}
} // namespace tket_sim
} // namespace tket
|
//#include <cstdio>
//#include <cmath>
//#include <iostream>
//#include <sstream>
//#include <string>
//#include <vector>
//#include <map>
//#include <queue>
//#include <algorithm>
//
//#ifdef _DEBUG
//#define DMP(x) cerr << #x << ": " << x << "\n"
//#else
//#define DMP(x) ((void)0)
//#endif
//
//const int MOD = 1000000007, INF = 1111111111;
//using namespace std;
//using lint = long long;
//
//int main() {
//
// cin.tie(nullptr);
// ios::sync_with_stdio(false);
//
// int N;
// cin >> N;
//
// vector<int> X(N), sX(N);
// for (int i = 0; i < N; i++) cin >> X[i];
//
// sX = X;
// sort(sX.begin(), sX.end());
// int med = sX[(N - 1) / 2];
//
// for (int i = 0; i < N; i++) {
// if (X[i] <= med) cout << sX[(N + 1) / 2] << "\n";
// else cout << med << "\n";
// }
//
// return 0;
//}
|
// Copyright 2018 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "chrome/browser/ui/views/autofill/payments/migratable_card_view.h"
#include "base/bind.h"
#include "chrome/app/vector_icons/vector_icons.h"
#include "chrome/browser/ui/autofill/payments/local_card_migration_dialog_state.h"
#include "chrome/browser/ui/views/autofill/payments/local_card_migration_dialog_view.h"
#include "chrome/browser/ui/views/chrome_layout_provider.h"
#include "chrome/browser/ui/views/chrome_typography.h"
#include "components/autofill/core/browser/payments/local_card_migration_manager.h"
#include "components/grit/components_scaled_resources.h"
#include "components/strings/grit/components_strings.h"
#include "components/vector_icons/vector_icons.h"
#include "ui/base/l10n/l10n_util.h"
#include "ui/base/metadata/metadata_impl_macros.h"
#include "ui/base/resource/resource_bundle.h"
#include "ui/gfx/paint_vector_icon.h"
#include "ui/native_theme/native_theme.h"
#include "ui/views/animation/ink_drop.h"
#include "ui/views/controls/button/button.h"
#include "ui/views/controls/button/checkbox.h"
#include "ui/views/controls/button/image_button.h"
#include "ui/views/controls/button/image_button_factory.h"
#include "ui/views/controls/image_view.h"
#include "ui/views/controls/label.h"
#include "ui/views/layout/box_layout.h"
namespace autofill {
MigratableCardView::MigratableCardView(
const MigratableCreditCard& migratable_credit_card,
LocalCardMigrationDialogView* parent_dialog,
bool should_show_checkbox)
: migratable_credit_card_(migratable_credit_card),
parent_dialog_(parent_dialog) {
ChromeLayoutProvider* provider = ChromeLayoutProvider::Get();
SetLayoutManager(std::make_unique<views::BoxLayout>(
views::BoxLayout::Orientation::kVertical, gfx::Insets(),
provider->GetDistanceMetric(DISTANCE_CONTENT_LIST_VERTICAL_MULTI)));
AddChildView(GetMigratableCardDescriptionView(migratable_credit_card,
should_show_checkbox)
.release());
checkbox_uncheck_text_container_ =
AddChildView(std::make_unique<views::View>());
views::BoxLayout* layout = checkbox_uncheck_text_container_->SetLayoutManager(
std::make_unique<views::BoxLayout>(
views::BoxLayout::Orientation::kVertical,
gfx::Insets(provider->GetDistanceMetric(
views::DISTANCE_RELATED_CONTROL_VERTICAL),
provider->GetDistanceMetric(
views::DISTANCE_RELATED_CONTROL_HORIZONTAL)),
provider->GetDistanceMetric(
views::DISTANCE_RELATED_CONTROL_HORIZONTAL)));
layout->set_cross_axis_alignment(
views::BoxLayout::CrossAxisAlignment::kStart);
checkbox_uncheck_text_container_->AddChildView(std::make_unique<views::Label>(
l10n_util::GetStringUTF16(
IDS_AUTOFILL_LOCAL_CARD_MIGRATION_DIALOG_CHECKBOX_UNCHECK_WARNING),
CONTEXT_DIALOG_BODY_TEXT_SMALL, ChromeTextStyle::STYLE_RED));
checkbox_uncheck_text_container_->SetVisible(false);
}
MigratableCardView::~MigratableCardView() = default;
bool MigratableCardView::GetSelected() const {
return !checkbox_ || checkbox_->GetChecked();
}
std::string MigratableCardView::GetGuid() const {
return migratable_credit_card_.credit_card().guid();
}
std::u16string MigratableCardView::GetCardIdentifierString() const {
return migratable_credit_card_.credit_card()
.CardIdentifierStringForAutofillDisplay();
}
void MigratableCardView::OnThemeChanged() {
View::OnThemeChanged();
checkbox_uncheck_text_container_->SetBackground(
views::CreateSolidBackground(GetNativeTheme()->GetSystemColor(
ui::NativeTheme::kColorId_BubbleFooterBackground)));
}
std::unique_ptr<views::View>
MigratableCardView::GetMigratableCardDescriptionView(
const MigratableCreditCard& migratable_credit_card,
bool should_show_checkbox) {
auto migratable_card_description_view = std::make_unique<views::View>();
ChromeLayoutProvider* provider = ChromeLayoutProvider::Get();
migratable_card_description_view->SetLayoutManager(
std::make_unique<views::BoxLayout>(
views::BoxLayout::Orientation::kHorizontal, gfx::Insets(),
provider->GetDistanceMetric(
views::DISTANCE_RELATED_CONTROL_HORIZONTAL)));
std::unique_ptr<views::Label> card_description =
std::make_unique<views::Label>(GetCardIdentifierString(),
views::style::CONTEXT_LABEL);
card_description->SetMultiLine(true);
card_description->SetHorizontalAlignment(gfx::ALIGN_LEFT);
constexpr int kCardDescriptionMaximumWidth = 260;
card_description->SetMaximumWidth(kCardDescriptionMaximumWidth);
constexpr int kMigrationResultImageSize = 16;
switch (migratable_credit_card.migration_status()) {
case MigratableCreditCard::MigrationStatus::UNKNOWN: {
if (should_show_checkbox) {
checkbox_ = migratable_card_description_view->AddChildView(
std::make_unique<views::Checkbox>(
std::u16string(),
base::BindRepeating(&MigratableCardView::CheckboxPressed,
base::Unretained(this))));
checkbox_->SetChecked(true);
// TODO(crbug/867194): Currently the ink drop animation circle is
// cropped by the border of scroll bar view. Find a way to adjust the
// format.
views::InkDrop::Get(checkbox_)->SetMode(
views::InkDropHost::InkDropMode::OFF);
checkbox_->SetAssociatedLabel(card_description.get());
}
break;
}
case MigratableCreditCard::MigrationStatus::SUCCESS_ON_UPLOAD: {
auto* migration_succeeded_image =
migratable_card_description_view->AddChildView(
std::make_unique<views::ImageView>());
migration_succeeded_image->SetImage(ui::ImageModel::FromVectorIcon(
vector_icons::kCheckCircleIcon,
ui::NativeTheme::kColorId_AlertSeverityLow,
kMigrationResultImageSize));
break;
}
case MigratableCreditCard::MigrationStatus::FAILURE_ON_UPLOAD: {
auto* migration_failed_image =
migratable_card_description_view->AddChildView(
std::make_unique<views::ImageView>());
migration_failed_image->SetImage(ui::ImageModel::FromVectorIcon(
vector_icons::kErrorIcon, ui::NativeTheme::kColorId_AlertSeverityHigh,
kMigrationResultImageSize));
break;
}
}
std::unique_ptr<views::View> card_network_and_last_four_digits =
std::make_unique<views::View>();
card_network_and_last_four_digits->SetLayoutManager(
std::make_unique<views::BoxLayout>(
views::BoxLayout::Orientation::kHorizontal, gfx::Insets(),
provider->GetDistanceMetric(DISTANCE_RELATED_LABEL_HORIZONTAL_LIST)));
ui::ResourceBundle& rb = ui::ResourceBundle::GetSharedInstance();
std::unique_ptr<views::ImageView> card_image =
std::make_unique<views::ImageView>();
card_image->SetImage(
rb.GetImageNamed(CreditCard::IconResourceId(
migratable_credit_card.credit_card().network()))
.AsImageSkia());
card_image->SetAccessibleName(
migratable_credit_card.credit_card().NetworkForDisplay());
card_network_and_last_four_digits->AddChildView(card_image.release());
card_network_and_last_four_digits->AddChildView(card_description.release());
migratable_card_description_view->AddChildView(
card_network_and_last_four_digits.release());
std::unique_ptr<views::Label> card_expiration =
std::make_unique<views::Label>(
migratable_credit_card.credit_card()
.AbbreviatedExpirationDateForDisplay(/*with_prefix=*/true),
views::style::CONTEXT_LABEL, views::style::STYLE_SECONDARY);
card_expiration->SetElideBehavior(gfx::ElideBehavior::NO_ELIDE);
card_expiration->SetMultiLine(true);
migratable_card_description_view->AddChildView(card_expiration.release());
// If card is not successfully uploaded we show the invalid card
// label and the trash can icon.
if (migratable_credit_card.migration_status() ==
MigratableCreditCard::MigrationStatus::FAILURE_ON_UPLOAD) {
migratable_card_description_view->AddChildView(new views::Label(
l10n_util::GetStringUTF16(
IDS_AUTOFILL_LOCAL_CARD_MIGRATION_DIALOG_LABEL_INVALID_CARDS),
views::style::CONTEXT_LABEL, ChromeTextStyle::STYLE_RED));
auto delete_card_from_local_button =
views::CreateVectorImageButtonWithNativeTheme(
base::BindRepeating(
[](LocalCardMigrationDialogView* parent_dialog,
std::string guid) {
parent_dialog->DeleteCard(std::move(guid));
},
parent_dialog_, GetGuid()),
kTrashCanIcon);
delete_card_from_local_button->SetTooltipText(l10n_util::GetStringUTF16(
IDS_AUTOFILL_LOCAL_CARD_MIGRATION_DIALOG_TRASH_CAN_BUTTON_TOOLTIP));
delete_card_from_local_button->SetFocusBehavior(
FocusBehavior::ACCESSIBLE_ONLY);
delete_card_from_local_button_ =
migratable_card_description_view->AddChildView(
std::move(delete_card_from_local_button));
}
return migratable_card_description_view;
}
void MigratableCardView::CheckboxPressed() {
// If the button clicked is a checkbox. Enable/disable the save
// button if needed.
parent_dialog_->OnCardCheckboxToggled();
// The warning text will be visible only when user unchecks the checkbox.
checkbox_uncheck_text_container_->SetVisible(!checkbox_->GetChecked());
InvalidateLayout();
parent_dialog_->UpdateLayout();
}
BEGIN_METADATA(MigratableCardView, views::View)
ADD_READONLY_PROPERTY_METADATA(bool, Selected)
ADD_READONLY_PROPERTY_METADATA(std::string, Guid)
ADD_READONLY_PROPERTY_METADATA(std::u16string, CardIdentifierString)
END_METADATA
} // namespace autofill
|
/*
* Copyright (c) 2013, Ford Motor Company
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* Redistributions of source code must retain the above copyright notice, this
* list of conditions and the following disclaimer.
*
* Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following
* disclaimer in the documentation and/or other materials provided with the
* distribution.
*
* Neither the name of the Ford Motor Company 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 HOLDER OR CONTRIBUTORS BE
* LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
* CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
* SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
* INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
* CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*/
#include "application_manager/commands/hmi/tts_speak_response.h"
#include "application_manager/event_engine/event.h"
#include "interfaces/MOBILE_API.h"
#include "interfaces/HMI_API.h"
namespace application_manager {
namespace commands {
TTSSpeakResponse::TTSSpeakResponse(const MessageSharedPtr& message)
: ResponseFromHMI(message) {
}
TTSSpeakResponse::~TTSSpeakResponse() {
}
void TTSSpeakResponse::Run() {
LOG4CXX_AUTO_TRACE(logger_);
event_engine::Event event(hmi_apis::FunctionID::TTS_Speak);
event.set_smart_object(*message_);
event.raise();
}
} // namespace commands
} // namespace application_manager
|
/*=========================================================================
Program: VMTK
Module: $RCSfile: vtkvmtkPolyDataNetworkExtraction.cxx,v $
Language: C++
Date: $Date: 2006/07/17 09:53:14 $
Version: $Revision: 1.6 $
Copyright (c) Luca Antiga, David Steinman. All rights reserved.
See LICENCE file for details.
Portions of this code are covered under the VTK copyright.
See VTKCopyright.txt or http://www.kitware.com/VTKCopyright.htm
for details.
This software is distributed WITHOUT ANY WARRANTY; without even
the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
PURPOSE. See the above copyright notices for more information.
=========================================================================*/
#include "vtkvmtkPolyDataNetworkExtraction.h"
#include "vtkCleanPolyData.h"
#include "vtkStripper.h"
#include "vtkAppendPolyData.h"
#include "vtkFeatureEdges.h"
#include "vtkMath.h"
#include "vtkPolyDataCollection.h"
#include "vtkCollection.h"
#include "vtkPolyData.h"
#include "vtkCellArray.h"
#include "vtkPoints.h"
#include "vtkPointData.h"
#include "vtkCellData.h"
#include "vtkPolyLine.h"
#include "vtkIdTypeArray.h"
#include "vtkDoubleArray.h"
#include "vtkLine.h"
#include "vtkCommand.h"
#include "vtkInformation.h"
#include "vtkInformationVector.h"
#include "vtkObjectFactory.h"
vtkStandardNewMacro(vtkvmtkPolyDataNetworkExtraction);
vtkvmtkPolyDataNetworkExtraction::vtkvmtkPolyDataNetworkExtraction()
{
this->MarksArrayName = new char[256];
strcpy(this->MarksArrayName,"Marks");
this->RadiusArrayName = new char[256];
strcpy(this->RadiusArrayName,"Radius");
this->TopologyArrayName = new char[256];
strcpy(this->TopologyArrayName,"Topology");
this->MinimumStep = 5E-4;
this->TotalMarkedPoints = 0;
this->GraphLayout = NULL;
}
vtkvmtkPolyDataNetworkExtraction::~vtkvmtkPolyDataNetworkExtraction()
{
if (this->MarksArrayName)
{
delete[] this->MarksArrayName;
this->MarksArrayName = NULL;
}
if (this->RadiusArrayName)
{
delete[] this->RadiusArrayName;
this->RadiusArrayName = NULL;
}
if (this->TopologyArrayName)
{
delete[] this->TopologyArrayName;
this->TopologyArrayName = NULL;
}
if (this->GraphLayout)
{
this->GraphLayout->Delete();
this->GraphLayout = NULL;
}
}
void vtkvmtkPolyDataNetworkExtraction::BoundaryExtractor(vtkPolyData* polyInput, vtkPolyData* boundary)
{
if (polyInput->GetNumberOfCells()==0)
{
return;
}
vtkFeatureEdges *boundaryExtractor = vtkFeatureEdges::New();
boundaryExtractor->BoundaryEdgesOn();
boundaryExtractor->FeatureEdgesOff();
boundaryExtractor->NonManifoldEdgesOff();
boundaryExtractor->ManifoldEdgesOff();
boundaryExtractor->SetInput(polyInput);
boundaryExtractor->Update();
if (boundaryExtractor->GetOutput()->GetNumberOfCells()==0)
{
boundaryExtractor->Delete();
return;
}
vtkCleanPolyData *boundaryExtractorCleaner = vtkCleanPolyData::New();
boundaryExtractorCleaner->SetInput(boundaryExtractor->GetOutput());
vtkStripper *boundaryExtractorStripper = vtkStripper::New();
boundaryExtractorStripper->SetInput(boundaryExtractorCleaner->GetOutput());
boundaryExtractorStripper->Update();
boundary->DeepCopy(boundaryExtractorStripper->GetOutput());
boundary->Update();
boundaryExtractorStripper->Delete();
boundaryExtractorCleaner->Delete();
boundaryExtractor->Delete();
}
void vtkvmtkPolyDataNetworkExtraction::BoundarySeparator(vtkPolyData* appendedBoundaries, vtkPolyDataCollection* boundaries)
{
appendedBoundaries->BuildLinks();
appendedBoundaries->Update();
vtkIdType i;
for (i=0; i<appendedBoundaries->GetNumberOfCells(); i++)
{
vtkPoints* boundaryPoints = vtkPoints::New();
vtkCellArray* boundaryCellArray = vtkCellArray::New();
vtkIdType npts, *pts;
appendedBoundaries->GetCellPoints(i,npts,pts);
boundaryCellArray->InsertNextCell(npts+1);
vtkIdType j;
for (j=0; j<npts; j++)
{
boundaryPoints->InsertNextPoint(appendedBoundaries->GetPoint(pts[j]));
boundaryCellArray->InsertCellPoint(j);
}
boundaryCellArray->InsertCellPoint(0);
vtkPolyData* boundary = vtkPolyData::New();
boundary->SetPoints(boundaryPoints);
boundary->SetLines(boundaryCellArray);
boundary->Update();
boundaries->AddItem(boundary);
boundary->Delete();
boundaryPoints->Delete();
boundaryCellArray->Delete();
}
}
void vtkvmtkPolyDataNetworkExtraction::InsertInEdgeTable(vtkIdTypeArray* edgeTable, vtkIdType pointId0, vtkIdType pointId1)
{
vtkIdType edge[2];
edge[0] = pointId0;
edge[1] = pointId1;
edgeTable->InsertNextTupleValue(edge);
}
bool vtkvmtkPolyDataNetworkExtraction::InsertUniqueInEdgeTable(vtkIdTypeArray* edgeTable, vtkIdType pointId0, vtkIdType pointId1)
{
vtkIdType edge[2];
edge[0] = pointId0;
edge[1] = pointId1;
vtkIdType i;
for (i=0; i<edgeTable->GetNumberOfTuples(); i++)
{
vtkIdType currentEdge[2];
edgeTable->GetTupleValue(i,currentEdge);
if (currentEdge[0]==edge[0] && currentEdge[1]==edge[1])
{
return false;
}
}
edgeTable->InsertNextTupleValue(edge);
return true;
}
void vtkvmtkPolyDataNetworkExtraction::GetFromEdgeTable(vtkIdTypeArray* edgeTable, vtkIdType position, vtkIdType edge[2])
{
edgeTable->GetTupleValue(position,edge);
}
void vtkvmtkPolyDataNetworkExtraction::UpdateEdgeTableCollectionReal(vtkPolyData* model,vtkPolyDataCollection* profiles,vtkCollection* edgeTables)
{
profiles->InitTraversal();
vtkIdType j;
for (j=0; j<profiles->GetNumberOfItems(); j++)
{
vtkPolyData* profile=profiles->GetNextItem();
profile->Update();
vtkIdTypeArray* edgeTable = vtkIdTypeArray::New();
edgeTable->SetNumberOfComponents(2);
vtkIdType i;
for (i=0; i<profile->GetNumberOfPoints(); i++)
{
vtkIdType modelPointId = model->FindPoint(profile->GetPoint(i));
this->InsertInEdgeTable(edgeTable,modelPointId,modelPointId);
}
edgeTables->AddItem(edgeTable);
edgeTable->Delete();
}
}
double vtkvmtkPolyDataNetworkExtraction::Distance(double point1[3], double point2[3])
{
return sqrt(vtkMath::Distance2BetweenPoints(point1,point2));
}
double vtkvmtkPolyDataNetworkExtraction::GetFurthestDistance(vtkPolyDataCollection* polyDataCollection, double fromPoint[3])
{
vtkIdType i,j;
double dist, maxDist = 0.0;
polyDataCollection->InitTraversal();
for (i=0; i<polyDataCollection->GetNumberOfItems(); i++)
{
vtkPolyData* item = polyDataCollection->GetNextItem();
for (j=0; j<item->GetNumberOfPoints(); j++)
{
dist = vtkMath::Distance2BetweenPoints(item->GetPoint(j),fromPoint);
if (dist > maxDist)
{
maxDist = dist;
}
}
}
return sqrt(maxDist);
}
void vtkvmtkPolyDataNetworkExtraction::Barycenter(vtkPoints* points, double barycenter[3])
{
vtkIdType numberOfPoints = points->GetNumberOfPoints();
vtkIdType i,j;
for (i=0; i<3; i++)
{
double sum = 0.0;
for (j=0; j<numberOfPoints; j++)
{
sum = sum + ((points->GetPoint(j))[i]);
}
barycenter[i] = sum / numberOfPoints;
}
}
void vtkvmtkPolyDataNetworkExtraction::ProfileBarycenter(vtkPoints* points, double barycenter[3])
{
vtkIdType numberOfPoints = points->GetNumberOfPoints();
if (numberOfPoints == 0)
{
barycenter[0] = barycenter[1] = barycenter[2] = 0.0;
return;
}
vtkDoubleArray* lineLengths = vtkDoubleArray::New();
double totalLength = 0.0;
vtkIdType i;
for (i=0; i<numberOfPoints; i++)
{
double point0[3], point1[3];
points->GetPoint(i,point0);
if (i < numberOfPoints-1)
{
points->GetPoint(i+1,point1);
}
else
{
points->GetPoint(0,point1);
}
double lineLength = sqrt(vtkMath::Distance2BetweenPoints(point0,point1));
lineLengths->InsertNextValue(lineLength);
totalLength += lineLength;
}
if (totalLength == 0.0)
{
points->GetPoint(0,barycenter);
lineLengths->Delete();
return;
}
vtkDoubleArray* pointWeights = vtkDoubleArray::New();
for (i=0; i<numberOfPoints; i++)
{
double length0 = 0.0;
if (i != 0)
{
length0 = lineLengths->GetValue(i-1);
}
else
{
length0 = lineLengths->GetValue(numberOfPoints-1);
}
double length1 = lineLengths->GetValue(i);
double pointWeight = (length0 + length1) / 2.0;
pointWeights->InsertNextValue(pointWeight);
}
for (i=0; i<3; i++)
{
double sum = 0.0;
vtkIdType j;
for (j=0; j<numberOfPoints; j++)
{
double pointCoord = points->GetPoint(j)[i];
double weight = pointWeights->GetValue(j);
sum += pointCoord * weight;
}
barycenter[i] = sum / totalLength;
}
lineLengths->Delete();
pointWeights->Delete();
}
void vtkvmtkPolyDataNetworkExtraction::DefineVirtualSphere(vtkPolyDataCollection* baseProfiles, double center[3], double &radius, double ratio)
{
vtkPoints* barycenters = vtkPoints::New();
baseProfiles->InitTraversal();
vtkIdType i;
for (i=0; i<baseProfiles->GetNumberOfItems(); i++)
{
vtkPolyData* baseProfile = baseProfiles->GetNextItem();
baseProfile->Update();
double barycenter[3];
this->ProfileBarycenter(baseProfile->GetPoints(),barycenter);
barycenters->InsertNextPoint(barycenter);
}
this->Barycenter(barycenters,center);
barycenters->Delete();
double distance = this->GetFurthestDistance(baseProfiles,center);
radius = distance * ratio;
}
vtkIdType vtkvmtkPolyDataNetworkExtraction::CurrentPointId(vtkPolyData* model,vtkIdType currentEdge[2])
{
vtkIdTypeArray* marksArray = vtkIdTypeArray::SafeDownCast(model->GetPointData()->GetArray(MarksArrayName));
vtkIdType currentPointId;
if (currentEdge[0] != currentEdge[1])
{
if (marksArray->GetValue(currentEdge[1]) == NON_VISITED)
{
currentPointId = currentEdge[1];
}
else if (marksArray->GetValue(currentEdge[0]) == NON_VISITED)
{
currentPointId = currentEdge[0];
}
else
{
currentPointId = -1;
}
}
else
{
currentPointId = currentEdge[0];
}
return currentPointId;
}
void vtkvmtkPolyDataNetworkExtraction::InsertEdgeForNewProfiles(vtkPolyData* model, vtkIdType* edge, vtkIdTypeArray* edgeTable, vtkIdTypeArray* cellPairs, vtkIdList* pointIds)
{
if (this->InsertUniqueInEdgeTable(edgeTable,edge[0],edge[1]))
{
unsigned short ncells0; vtkIdType *cell0;
model->GetPointCells(edge[0],ncells0,cell0);
unsigned short ncells1; vtkIdType *cell1;
model->GetPointCells(edge[1],ncells1,cell1);
vtkIdType cellPair[2];
cellPair[0] = -1;
cellPair[1] = -1;
vtkIdType i,j;
for (i=0; i<ncells0; i++)
{
for (j=0; j<ncells1; j++)
{
if (cell0[i]==cell1[j])
{
if (cellPair[0]==-1)
{
cellPair[0]=cell0[i];
}
else
{
cellPair[1]=cell0[i];
}
}
}
}
this->InsertInEdgeTable(cellPairs,cellPair[0],cellPair[1]);
pointIds->InsertUniqueId(edge[0]);
pointIds->InsertUniqueId(edge[1]);
}
}
bool vtkvmtkPolyDataNetworkExtraction::LookForNeighbors(vtkPolyData* model, vtkIdType pointId, vtkIdList* notVisitedIds, vtkIdTypeArray* edgeTableForIncludedGlobalProfiles)
{
vtkIdTypeArray* marksArray = vtkIdTypeArray::SafeDownCast(model->GetPointData()->GetArray(MarksArrayName));
bool someNeighborsFound = false;
// return non visited neighbors, and true if there are any, false otherwise
unsigned short ncells; vtkIdType *cell;
model->GetPointCells(pointId,ncells,cell);
vtkIdType i;
for (i=0; i<ncells; i++)
{
vtkIdType npts; vtkIdType* pts;
model->GetCellPoints(cell[i],npts,pts);
vtkIdType j;
for (j=0; j<npts; j++)
{
if (pts[j]!=pointId)
{
vtkIdType scalar = marksArray->GetValue(pts[j]);
if (scalar == NON_VISITED)
{
notVisitedIds->InsertUniqueId(pts[j]);
someNeighborsFound=true;
}
else if (scalar == GLOBAL)
{
this->InsertInEdgeTable(edgeTableForIncludedGlobalProfiles,pointId,pts[j]);
}
}
}
}
return someNeighborsFound;
}
void vtkvmtkPolyDataNetworkExtraction::PropagateFromBaseProfilePoint(vtkPolyData* model, vtkIdList* toVisitPointIds, double center[3], double radius, vtkIdTypeArray* edgeTableForNewProfiles, vtkIdTypeArray* cellPairsForNewProfiles, vtkIdList* pointIdsForNewProfiles, vtkPoints* markedPoints, vtkIdList* markedPointIds, vtkIdTypeArray* edgeTableForIncludedGlobalProfiles)
{
vtkIdTypeArray* marksArray = vtkIdTypeArray::SafeDownCast(model->GetPointData()->GetArray(MarksArrayName));
while (toVisitPointIds->GetNumberOfIds())
{
vtkIdType currentPointId = toVisitPointIds->GetId(0);
if (marksArray->GetValue(currentPointId) == NON_VISITED)
{
marksArray->InsertValue(currentPointId,VISITED);
if (markedPointIds->IsId(currentPointId)==-1)
{
double markedPoint[3];
model->GetPoint(currentPointId,markedPoint);
markedPoints->InsertNextPoint(markedPoint);
markedPointIds->InsertNextId(currentPointId);
}
}
// call LookForNeighbors, compare distances and call PropagateFromBaseProfilePovtkIdType again is povtkIdType
// is non visited and falls inside the sphere. If it falls outside add adge to edge list
vtkIdList* notVisitedNeighbors = vtkIdList::New();
if (LookForNeighbors(model,currentPointId,notVisitedNeighbors,edgeTableForIncludedGlobalProfiles))
{
marksArray->InsertValue(currentPointId,VISITED);
vtkIdType edge[2];
vtkIdType i;
for (i=0; i<notVisitedNeighbors->GetNumberOfIds(); i++)
{
double point[3];
model->GetPoint(notVisitedNeighbors->GetId(i),point);
if (this->Distance(center,point) > radius)
{
edge[0]=currentPointId; edge[1]=notVisitedNeighbors->GetId(i);
this->InsertEdgeForNewProfiles(model,edge,edgeTableForNewProfiles,cellPairsForNewProfiles,pointIdsForNewProfiles);
}
else
{
toVisitPointIds->InsertUniqueId(notVisitedNeighbors->GetId(i));
}
}
}
toVisitPointIds->DeleteId(currentPointId);
notVisitedNeighbors->Delete();
}
}
void vtkvmtkPolyDataNetworkExtraction::LocateVirtualPoint(vtkIdType edge[2], double center[3], double radius, vtkIdList* pointIdsForNewProfiles, vtkPoints* pointsForNewProfiles, vtkDoubleArray* pointDistancesForNewProfiles, double virtualPoint[3])
{
virtualPoint[0] = virtualPoint[1] = virtualPoint[2] = 0.0;
vtkIdType position0 = pointIdsForNewProfiles->IsId(edge[0]);
vtkIdType position1 = pointIdsForNewProfiles->IsId(edge[1]);
double point0[3], point1[3];
pointsForNewProfiles->GetPoint(position0,point0);
pointsForNewProfiles->GetPoint(position1,point1);
double distance0 = pointDistancesForNewProfiles->GetValue(position0);
double distance1 = pointDistancesForNewProfiles->GetValue(position1);
double distance2 = vtkMath::Distance2BetweenPoints(point0,point1);
if (radius > 0.0 && distance2 > 1E-12)
{
double h2 = vtkLine::DistanceToLine(center,point0,point1);
double distance = sqrt(distance2);
double b = 0.0;
if (radius*radius - h2 > 0.0)
{
b = sqrt(radius*radius - h2);
}
double a = 0.0;
if (distance0*distance0 - h2 > 0.0)
{
a = sqrt(distance0*distance0 - h2);
}
double parametricCoordinate = 0.0;
if (distance2 < (distance1*distance1 - h2))
{
parametricCoordinate = b - a;
}
else
{
parametricCoordinate = b + a;
}
virtualPoint[0] = point0[0] + parametricCoordinate * (point1[0]-point0[0]) / distance;
virtualPoint[1] = point0[1] + parametricCoordinate * (point1[1]-point0[1]) / distance;
virtualPoint[2] = point0[2] + parametricCoordinate * (point1[2]-point0[2]) / distance;
}
else
{
if (distance0<distance1)
{
virtualPoint[0] = point0[0];
virtualPoint[1] = point0[1];
virtualPoint[2] = point0[2];
}
else
{
virtualPoint[0] = point1[0];
virtualPoint[1] = point1[1];
virtualPoint[2] = point1[2];
}
}
}
void vtkvmtkPolyDataNetworkExtraction::ReconstructNewProfiles(vtkPoints* virtualPoints, vtkIdTypeArray* edgeTable, vtkIdTypeArray* cellPairs, vtkPolyDataCollection* newProfiles, vtkCollection* newProfilesEdgeTables)
{
// reconstruct using adjacent triangles
vtkIdList* notVisitedIds = vtkIdList::New();
vtkIdType i;
for (i=0; i<virtualPoints->GetNumberOfPoints(); i++)
{
notVisitedIds->InsertNextId(i);
}
while (notVisitedIds->GetNumberOfIds())
{
vtkPolyData* newProfile = vtkPolyData::New();
vtkPoints* newProfilePoints = vtkPoints::New();
newProfile->SetPoints(newProfilePoints);
vtkIdTypeArray* newProfileEdgeTable = vtkIdTypeArray::New();
newProfileEdgeTable->SetNumberOfComponents(2);
vtkIdType cellPair0[2];
vtkIdType position1 = notVisitedIds->GetId(0);
this->GetFromEdgeTable(cellPairs,position1,cellPair0);
vtkIdType initialCellId = cellPair0[0];
vtkIdType cellIdToSearch = cellPair0[1];
newProfile->GetPoints()->InsertNextPoint(virtualPoints->GetPoint(position1));
vtkIdType newProfileEdge[2];
this->GetFromEdgeTable(edgeTable,position1,newProfileEdge);
notVisitedIds->DeleteId(position1);
this->InsertInEdgeTable(newProfileEdgeTable,newProfileEdge[0],newProfileEdge[1]);
bool closed = false;
vtkIdType cellPair1[2];
while (!closed)
{
bool foundNext = false;
vtkIdType j = 0;
while (!foundNext)
{
if (j >= notVisitedIds->GetNumberOfIds())
{
vtkErrorMacro(<<"Error: can't reconstruct new profile.");
return;
}
vtkIdType position2 = notVisitedIds->GetId(j);
this->GetFromEdgeTable(cellPairs,position2,cellPair1);
if (cellPair1[0] == cellIdToSearch)
{
double virtualPoint[3];
virtualPoints->GetPoint(position2,virtualPoint);
newProfile->GetPoints()->InsertNextPoint(virtualPoint);
this->GetFromEdgeTable(edgeTable,position2,newProfileEdge);
this->InsertInEdgeTable(newProfileEdgeTable,newProfileEdge[0],newProfileEdge[1]);
foundNext = true;
notVisitedIds->DeleteId(position2);
cellIdToSearch = cellPair1[1];
}
else if (cellPair1[1] == cellIdToSearch)
{
double virtualPoint[3];
virtualPoints->GetPoint(position2,virtualPoint);
newProfile->GetPoints()->InsertNextPoint(virtualPoint);
this->GetFromEdgeTable(edgeTable,position2,newProfileEdge);
this->InsertInEdgeTable(newProfileEdgeTable,newProfileEdge[0],newProfileEdge[1]);
foundNext = true;
notVisitedIds->DeleteId(position2);
cellIdToSearch = cellPair1[0];
}
j++;
}
if (cellIdToSearch == initialCellId)
{
closed = true;
}
}
vtkCellArray* newProfileLines = vtkCellArray::New();
newProfileLines->InsertNextCell(newProfile->GetNumberOfPoints() + 1);
vtkIdType i;
for (i=0; i<newProfile->GetNumberOfPoints(); i++)
{
newProfileLines->InsertCellPoint(i);
}
newProfileLines->InsertCellPoint(0);
newProfile->SetLines(newProfileLines);
newProfile->Update();
newProfiles->AddItem(newProfile);
newProfilesEdgeTables->AddItem(newProfileEdgeTable);
newProfile->Delete();
newProfilePoints->Delete();
newProfileLines->Delete();
newProfileEdgeTable->Delete();
}
notVisitedIds->Delete();
}
void vtkvmtkPolyDataNetworkExtraction::GenerateNewProfiles(vtkPolyData* model, double center[3], double radius, vtkIdTypeArray* edgeTableForNewProfiles, vtkIdTypeArray* cellPairsForNewProfiles, vtkIdList* pointIdsForNewProfiles, vtkPolyDataCollection* newProfiles, vtkCollection* newProfilesEdgeTables)
{
if (edgeTableForNewProfiles->GetNumberOfTuples())
{
vtkPoints* pointsForNewProfiles = vtkPoints::New();
vtkDoubleArray* pointDistancesForNewProfiles = vtkDoubleArray::New();
vtkIdType i;
for (i=0; i<pointIdsForNewProfiles->GetNumberOfIds(); i++)
{
double point[3];
model->GetPoint(pointIdsForNewProfiles->GetId(i),point);
pointsForNewProfiles->InsertNextPoint(point);
pointDistancesForNewProfiles->InsertNextValue(Distance(center,point));
}
vtkPoints* virtualPointsForNewProfiles = vtkPoints::New();
vtkIdType edge[2];
for (i=0; i<edgeTableForNewProfiles->GetNumberOfTuples(); i++)
{
this->GetFromEdgeTable(edgeTableForNewProfiles,i,edge);
double virtualPoint[3];
this->LocateVirtualPoint(edge,center,radius,pointIdsForNewProfiles,pointsForNewProfiles,pointDistancesForNewProfiles,virtualPoint);
virtualPointsForNewProfiles->InsertNextPoint(virtualPoint);
}
this->ReconstructNewProfiles(virtualPointsForNewProfiles,edgeTableForNewProfiles,cellPairsForNewProfiles,newProfiles,newProfilesEdgeTables);
pointsForNewProfiles->Delete();
pointDistancesForNewProfiles->Delete();
virtualPointsForNewProfiles->Delete();
}
}
void vtkvmtkPolyDataNetworkExtraction::UnmarkPoints(vtkPolyData* model, vtkIdList* markedPointIds)
{
vtkIdTypeArray* marksArray = vtkIdTypeArray::SafeDownCast(model->GetPointData()->GetArray(MarksArrayName));
vtkIdType i;
for (i=0; i<markedPointIds->GetNumberOfIds(); i++)
{
marksArray->InsertValue(markedPointIds->GetId(i),NON_VISITED);
}
}
double vtkvmtkPolyDataNetworkExtraction::ComputeStepRadius(vtkPoints* points, double point1[3], double point2[3])
{
vtkIdType i;
double radius = 0.0;
for (i=0; i<points->GetNumberOfPoints(); i++)
{
double point[3];
points->GetPoint(i,point);
radius += sqrt(vtkLine::DistanceToLine(point,point1,point2));
}
radius /= points->GetNumberOfPoints();
return radius;
}
double vtkvmtkPolyDataNetworkExtraction::ComputeMeanRadius(vtkPoints* points, double point1[3])
{
vtkIdType i;
double radius = 0.0;
for (i=0; i<points->GetNumberOfPoints(); i++)
{
double point[3];
points->GetPoint(i,point);
radius += sqrt(vtkMath::Distance2BetweenPoints(point,point1));
}
radius /= points->GetNumberOfPoints();
return radius;
}
void vtkvmtkPolyDataNetworkExtraction::PointsForRadius(vtkPoints *markedPoints, vtkPolyDataCollection *baseProfiles, vtkPolyDataCollection *newProfiles, vtkPoints *pointsForRadius)
{
vtkIdType i,j;
if (markedPoints)
{
for (i=0; i<markedPoints->GetNumberOfPoints(); i++)
{
pointsForRadius->InsertNextPoint(markedPoints->GetPoint(i));
}
}
if (baseProfiles)
{
baseProfiles->InitTraversal();
for (i=0; i<baseProfiles->GetNumberOfItems(); i++)
{
vtkPoints *baseProfilePoints = baseProfiles->GetNextItem()->GetPoints();
for (j=0; j<baseProfilePoints->GetNumberOfPoints(); j++)
{
pointsForRadius->InsertNextPoint(baseProfilePoints->GetPoint(j));
}
}
}
if (newProfiles)
{
newProfiles->InitTraversal();
for (i=0; i<newProfiles->GetNumberOfItems(); i++)
{
vtkPoints *newProfilePoints = newProfiles->GetNextItem()->GetPoints();
for (j=0; j<newProfilePoints->GetNumberOfPoints(); j++)
{
pointsForRadius->InsertNextPoint(newProfilePoints->GetPoint(j));
}
}
}
}
void vtkvmtkPolyDataNetworkExtraction::LookForIntersectingPoint(vtkPoints* segmentPoints, double center[3], double radius, vtkIdType &intersectingPointId)
{
intersectingPointId = segmentPoints->GetNumberOfPoints()-1;
vtkIdType i;
for (i=segmentPoints->GetNumberOfPoints()-2; i>=0; i--)
{
double segmentPoint[3];
segmentPoints->GetPoint(i,segmentPoint);
if (this->Distance(center,segmentPoint)>radius)
{
intersectingPointId = i+1;
break;
}
}
}
vtkIdType vtkvmtkPolyDataNetworkExtraction::StepIteration(vtkPolyData* model, vtkPolyDataCollection* baseProfiles, vtkCollection* baseProfilesEdgeTables, vtkPolyDataCollection* globalProfiles, vtkCollection* globalProfilesEdgeTables, vtkPolyDataCollection* newProfiles, vtkCollection* newProfilesEdgeTables, vtkPoints* segmentPoints, vtkDoubleArray* segmentRadii, vtkPoints* bifurcationPoints, vtkDoubleArray* bifurcationRadii, double oldCenter[3], double &oldRadius, double advancementRatio)
{
vtkIdTypeArray* marksArray = vtkIdTypeArray::SafeDownCast(model->GetPointData()->GetArray(MarksArrayName));
double center[3];
double radius;
this->DefineVirtualSphere(baseProfiles,center,radius,advancementRatio);
bool sameCenter = false;
if (oldRadius > 0.0)
{
if (this->Distance(center,oldCenter) < this->MinimumStep && radius <= oldRadius)
{
radius = 2.0 * oldRadius;
sameCenter = true;
}
}
// now propagate and build virtual profile(s)
vtkIdTypeArray* edgeTableForNewProfiles = vtkIdTypeArray::New();
edgeTableForNewProfiles->SetNumberOfComponents(2);
vtkIdTypeArray* cellPairsForNewProfiles = vtkIdTypeArray::New();
cellPairsForNewProfiles->SetNumberOfComponents(2);
vtkIdList* pointIdsForNewProfiles = vtkIdList::New(); //for doubleScalars mapping
vtkIdTypeArray* edgeTableForIncludedGlobalProfiles = vtkIdTypeArray::New();
edgeTableForIncludedGlobalProfiles->SetNumberOfComponents(2);
vtkPoints* markedPoints = vtkPoints::New();
vtkIdList* markedPointIds = vtkIdList::New();
vtkIdType i;
baseProfiles->InitTraversal();
baseProfilesEdgeTables->InitTraversal();
vtkIdList* old2MarkedPointIds = vtkIdList::New();
for (i=0; i<baseProfiles->GetNumberOfItems(); i++)
{
vtkPolyData* baseProfile = baseProfiles->GetNextItem();
vtkIdTypeArray* baseProfileEdgeTable = (vtkIdTypeArray*)baseProfilesEdgeTables->GetNextItemAsObject();
vtkIdType j;
for (j=0; j<baseProfile->GetNumberOfPoints(); j++)
{
vtkIdType currentEdge[2];
this->GetFromEdgeTable(baseProfileEdgeTable,j,currentEdge);
if (marksArray->GetValue(currentEdge[0]) == GLOBAL)
{
marksArray->InsertValue(currentEdge[0],VISITED);
old2MarkedPointIds->InsertNextId(currentEdge[0]);
}
}
}
// propagate from base profiles
baseProfiles->InitTraversal();
baseProfilesEdgeTables->InitTraversal();
vtkIdList* toVisitPointIds = vtkIdList::New();
for (i=0; i<baseProfiles->GetNumberOfItems(); i++)
{
vtkPolyData* baseProfile = baseProfiles->GetNextItem();
vtkIdTypeArray* baseProfileEdgeTable = (vtkIdTypeArray*)baseProfilesEdgeTables->GetNextItemAsObject();
vtkIdType j;
for (j=0; j<baseProfile->GetNumberOfPoints(); j++)
{
vtkIdType currentEdge[2];
this->GetFromEdgeTable(baseProfileEdgeTable,j,currentEdge);
vtkIdType currentPointId = CurrentPointId(model,currentEdge);
if (marksArray->GetValue(currentEdge[1]) == GLOBAL)
{
this->InsertInEdgeTable(edgeTableForIncludedGlobalProfiles,currentEdge[0],currentEdge[1]);
}
if (currentPointId!=-1)
{
if (this->Distance(model->GetPoint(currentPointId),center)>radius)
{
this->InsertEdgeForNewProfiles(model,currentEdge,edgeTableForNewProfiles,cellPairsForNewProfiles,pointIdsForNewProfiles);
}
else
{
toVisitPointIds->InsertNextId(currentPointId);
}
}
}
}
this->PropagateFromBaseProfilePoint(model,toVisitPointIds,center,radius,edgeTableForNewProfiles,cellPairsForNewProfiles,pointIdsForNewProfiles,markedPoints,markedPointIds,edgeTableForIncludedGlobalProfiles);
toVisitPointIds->Delete();
for (i=0; i<old2MarkedPointIds->GetNumberOfIds(); i++)
{
marksArray->InsertValue(old2MarkedPointIds->GetId(i),GLOBAL);
}
old2MarkedPointIds->Delete();
if (edgeTableForIncludedGlobalProfiles->GetNumberOfTuples() > 0)
{
vtkIdTypeArray* edgeTableForEffectiveIncludedGlobalProfiles = vtkIdTypeArray::New();
edgeTableForEffectiveIncludedGlobalProfiles->SetNumberOfComponents(2);
vtkIdType i;
for (i=0; i<edgeTableForIncludedGlobalProfiles->GetNumberOfTuples(); i++)
{
vtkIdType edgeForIncludedGlobalProfile[2];
this->GetFromEdgeTable(edgeTableForIncludedGlobalProfiles,i,edgeForIncludedGlobalProfile);
if (this->Distance(model->GetPoint(edgeForIncludedGlobalProfile[1]),center) <= radius)
{
this->InsertInEdgeTable(edgeTableForEffectiveIncludedGlobalProfiles,edgeForIncludedGlobalProfile[0],edgeForIncludedGlobalProfile[1]);
}
}
if (edgeTableForEffectiveIncludedGlobalProfiles->GetNumberOfTuples() > 0)
{
vtkIdList* includedGlobalProfilesIds = vtkIdList::New();
for (i=0; i<edgeTableForEffectiveIncludedGlobalProfiles->GetNumberOfTuples(); i++)
{
vtkIdType edgeForIncludedGlobalProfile[2];
this->GetFromEdgeTable(edgeTableForEffectiveIncludedGlobalProfiles,i,edgeForIncludedGlobalProfile);
globalProfiles->InitTraversal();
globalProfilesEdgeTables->InitTraversal();
vtkIdType j;
for (j=0; j<globalProfiles->GetNumberOfItems(); j++)
{
// vtkPolyData* globalProfile = globalProfiles->GetNextItem();
vtkIdTypeArray* globalProfileEdgeTable = (vtkIdTypeArray*)globalProfilesEdgeTables->GetNextItemAsObject();
vtkIdType k;
for (k=0; k<globalProfileEdgeTable->GetNumberOfTuples(); k++)
{
vtkIdType globalProfileEdge[2];
this->GetFromEdgeTable(globalProfileEdgeTable,k,globalProfileEdge);
if (globalProfileEdge[0]!=globalProfileEdge[1])
{
if ((edgeForIncludedGlobalProfile[0] == globalProfileEdge[0] && edgeForIncludedGlobalProfile[1] == globalProfileEdge[1]) || (edgeForIncludedGlobalProfile[0] == globalProfileEdge[1] && edgeForIncludedGlobalProfile[1] == globalProfileEdge[0]))
{
includedGlobalProfilesIds->InsertUniqueId(j);
}
}
else if (globalProfileEdge[0] == globalProfileEdge[1])
{
if (edgeForIncludedGlobalProfile[0] == globalProfileEdge[0] || edgeForIncludedGlobalProfile[1] == globalProfileEdge[0])
{
includedGlobalProfilesIds->InsertUniqueId(j);
}
}
}
}
}
vtkPolyDataCollection* includedGlobalProfiles = vtkPolyDataCollection::New();
vtkCollection* includedGlobalProfilesEdgeTables = vtkCollection::New();
globalProfiles->InitTraversal();
globalProfilesEdgeTables->InitTraversal();
for (i=0; i<globalProfiles->GetNumberOfItems(); i++)
{
vtkPolyData* globalProfile = globalProfiles->GetNextItem();
vtkIdTypeArray* globalProfileEdgeTable = (vtkIdTypeArray*)globalProfilesEdgeTables->GetNextItemAsObject();
if (includedGlobalProfilesIds->IsId(i) != -1)
{
includedGlobalProfiles->AddItem(globalProfile);
baseProfiles->AddItem(globalProfile);
includedGlobalProfilesEdgeTables->AddItem(globalProfileEdgeTable);
baseProfilesEdgeTables->AddItem(globalProfileEdgeTable);
}
}
includedGlobalProfiles->InitTraversal();
includedGlobalProfilesEdgeTables->InitTraversal();
for (i=0; i<includedGlobalProfiles->GetNumberOfItems(); i++)
{
globalProfiles->RemoveItem(includedGlobalProfiles->GetNextItem());
globalProfilesEdgeTables->RemoveItem(includedGlobalProfilesEdgeTables->GetNextItemAsObject());
}
this->UnmarkPoints(model,markedPointIds);
edgeTableForNewProfiles->Delete();
cellPairsForNewProfiles->Delete();
pointIdsForNewProfiles->Delete();
edgeTableForIncludedGlobalProfiles->Delete();
markedPoints->Delete();
markedPointIds->Delete();
edgeTableForEffectiveIncludedGlobalProfiles->Delete();
includedGlobalProfilesIds->Delete();
includedGlobalProfiles->Delete();
includedGlobalProfilesEdgeTables->Delete();
return STEP_ITERATION_REDEFINE;
}
else
{
for (i=0; i<edgeTableForIncludedGlobalProfiles->GetNumberOfTuples(); i++)
{
vtkIdType currentEdge[2];
this->GetFromEdgeTable(edgeTableForIncludedGlobalProfiles,i,currentEdge);
this->InsertEdgeForNewProfiles(model,currentEdge,edgeTableForNewProfiles,cellPairsForNewProfiles,pointIdsForNewProfiles);
}
}
edgeTableForEffectiveIncludedGlobalProfiles->Delete();
}
// build new profiles from lists (virtual points and connectivity)
this->GenerateNewProfiles(model,center,radius,edgeTableForNewProfiles,cellPairsForNewProfiles,pointIdsForNewProfiles,newProfiles,newProfilesEdgeTables);
this->TotalMarkedPoints += markedPointIds->GetNumberOfIds();
// classify step counting base and new profiles
vtkIdType numberOfBaseProfiles = baseProfiles->GetNumberOfItems();
vtkIdType numberOfNewProfiles = newProfiles->GetNumberOfItems();
if (numberOfBaseProfiles == 1 && numberOfNewProfiles == 0)
{
segmentPoints->InsertNextPoint(center);
edgeTableForNewProfiles->Delete();
cellPairsForNewProfiles->Delete();
pointIdsForNewProfiles->Delete();
edgeTableForIncludedGlobalProfiles->Delete();
markedPoints->Delete();
markedPointIds->Delete();
return STEP_ITERATION_STOP_CLOSED;
}
else if (numberOfBaseProfiles == 2 && numberOfNewProfiles == 0)
{
baseProfiles->InitTraversal();
vtkPolyData* profile;
profile = baseProfiles->GetNextItem();
double point1[3];
this->ProfileBarycenter(profile->GetPoints(),point1);
segmentPoints->InsertNextPoint(point1);
profile = baseProfiles->GetNextItem();
double point2[3];
this->ProfileBarycenter(profile->GetPoints(),point2);
segmentPoints->InsertNextPoint(point2);
vtkPoints *pointsForRadius = vtkPoints::New();
this->PointsForRadius(markedPoints,baseProfiles,NULL,pointsForRadius);
segmentRadii->InsertNextValue(ComputeStepRadius(pointsForRadius,point1,point2));
pointsForRadius->Delete();
edgeTableForNewProfiles->Delete();
cellPairsForNewProfiles->Delete();
pointIdsForNewProfiles->Delete();
edgeTableForIncludedGlobalProfiles->Delete();
markedPoints->Delete();
markedPointIds->Delete();
return STEP_ITERATION_STOP_END;
}
else if (numberOfBaseProfiles + numberOfNewProfiles > 2)
{
double lastCenter[3];
if (numberOfBaseProfiles==1)
{
lastCenter[0] = center[0];
lastCenter[1] = center[1];
lastCenter[2] = center[2];
}
else
{
baseProfiles->InitTraversal();
vtkPolyData* profile;
profile = baseProfiles->GetNextItem();
this->ProfileBarycenter(profile->GetPoints(),lastCenter);
}
segmentPoints->InsertNextPoint(lastCenter);
double firstBranchRadius = 0.0;
vtkIdType intersectingPointId = -1;
if (segmentRadii->GetNumberOfTuples() > 0)
{
this->LookForIntersectingPoint(segmentPoints,center,radius,intersectingPointId);
vtkIdType i;
vtkPoints* backupSegmentPoints = vtkPoints::New();
for (i=0; i<segmentPoints->GetNumberOfPoints(); i++)
{
backupSegmentPoints->InsertNextPoint(segmentPoints->GetPoint(i));
}
vtkDoubleArray* backupSegmentRadii = vtkDoubleArray::New();
for (i=0; i<segmentRadii->GetNumberOfTuples(); i++)
{
backupSegmentRadii->InsertNextValue(segmentRadii->GetValue(i));
}
segmentPoints->Initialize();
for (i=0; i<=intersectingPointId; i++)
{
segmentPoints->InsertNextPoint(backupSegmentPoints->GetPoint(i));
}
segmentRadii->Initialize();
for (i=0; i<intersectingPointId; i++)
{
segmentRadii->InsertNextValue(backupSegmentRadii->GetValue(i));
}
firstBranchRadius = backupSegmentRadii->GetValue(intersectingPointId-1);
backupSegmentPoints->Delete();
backupSegmentRadii->Delete();
}
double bifurcationBarycenter[3];
bifurcationBarycenter[0] = center[0];
bifurcationBarycenter[1] = center[1];
bifurcationBarycenter[2] = center[2];
bifurcationPoints->InsertNextPoint(bifurcationBarycenter);
bifurcationRadii->InsertNextValue(0.0);
vtkPolyData* profile;
baseProfiles->InitTraversal();
vtkIdType i;
double bifurcationPoint[3];
for (i=0; i<baseProfiles->GetNumberOfItems(); i++)
{
profile=baseProfiles->GetNextItem();
if (i==0 && segmentRadii->GetNumberOfTuples())
{
bifurcationPoints->InsertNextPoint(segmentPoints->GetPoint(intersectingPointId));
bifurcationRadii->InsertNextValue(firstBranchRadius);
}
else
{
this->ProfileBarycenter(profile->GetPoints(),bifurcationPoint);
bifurcationPoints->InsertNextPoint(bifurcationPoint);
bifurcationRadii->InsertNextValue(this->ComputeMeanRadius(profile->GetPoints(),bifurcationPoint));
}
}
newProfiles->InitTraversal();
for (i=0; i<newProfiles->GetNumberOfItems(); i++)
{
profile=newProfiles->GetNextItem();
this->ProfileBarycenter(profile->GetPoints(),bifurcationPoint);
bifurcationPoints->InsertNextPoint(bifurcationPoint);
bifurcationRadii->InsertNextValue(this->ComputeMeanRadius(profile->GetPoints(),bifurcationPoint));
}
vtkIdType j;
bifurcationBarycenter[0] = bifurcationBarycenter[1] = bifurcationBarycenter[2] = 0.0;
double weightSum = 0.0;
for (i=1; i<bifurcationPoints->GetNumberOfPoints(); i++)
{
double bifurcationPoint[3];
bifurcationPoints->GetPoint(i,bifurcationPoint);
double bifurcationPointRadius = bifurcationRadii->GetValue(i);
weightSum+=bifurcationPointRadius;
for (j=0; j<3; j++)
{
bifurcationBarycenter[j] += bifurcationPoint[j] * bifurcationPointRadius;
}
}
for (j=0; j<3; j++)
{
bifurcationBarycenter[j] /= weightSum;
}
bifurcationPoints->InsertPoint(0,bifurcationBarycenter);
edgeTableForNewProfiles->Delete();
cellPairsForNewProfiles->Delete();
pointIdsForNewProfiles->Delete();
edgeTableForIncludedGlobalProfiles->Delete();
markedPoints->Delete();
markedPointIds->Delete();
return STEP_ITERATION_STOP_BIFURCATION;
}
vtkPoints *pointsForRadius = vtkPoints::New();
this->PointsForRadius(markedPoints,baseProfiles,newProfiles,pointsForRadius);
newProfiles->InitTraversal();
double profileBarycenter[3];
this->ProfileBarycenter(newProfiles->GetNextItem()->GetPoints(),profileBarycenter);
double stepRadius = this->ComputeStepRadius(pointsForRadius,center,profileBarycenter);
pointsForRadius->Delete();
if (!sameCenter)
{
segmentRadii->InsertNextValue(stepRadius);
segmentPoints->InsertNextPoint(center);
}
else
{
segmentRadii->InsertValue(segmentRadii->GetNumberOfTuples()-1,stepRadius);
segmentPoints->InsertPoint(segmentPoints->GetNumberOfPoints()-1,center);
}
oldCenter[0] = center[0];
oldCenter[1] = center[1];
oldCenter[2] = center[2];
oldRadius = radius;
edgeTableForNewProfiles->Delete();
cellPairsForNewProfiles->Delete();
pointIdsForNewProfiles->Delete();
edgeTableForIncludedGlobalProfiles->Delete();
markedPoints->Delete();
markedPointIds->Delete();
return STEP_ITERATION_PROCEED;
}
void vtkvmtkPolyDataNetworkExtraction::MarkModelGlobalProfile(vtkPolyData* model, vtkIdTypeArray* newGlobalProfileEdgeTable)
{
vtkIdTypeArray* marksArray = vtkIdTypeArray::SafeDownCast(model->GetPointData()->GetArray(MarksArrayName));
vtkIdType i;
for (i=0; i<newGlobalProfileEdgeTable->GetNumberOfTuples(); i++)
{
// the first is currentId, the second is not yet visited
vtkIdType edge[2];
this->GetFromEdgeTable(newGlobalProfileEdgeTable,i,edge);
marksArray->InsertValue(edge[0],GLOBAL);
}
}
void vtkvmtkPolyDataNetworkExtraction::SegmentTopology(vtkCollection* bifurcations, vtkCollection* bifurcationsRadii, double firstSegmentPoint[3], double lastSegmentPoint[3], double firstPoint[3], double &firstRadius, double lastPoint[3], double &lastRadius, vtkIdType segmentTopology[2])
{
segmentTopology[0] = segmentTopology[1] = 0;
bool firstPointFound = false;
bool lastPointFound = false;
if (!lastSegmentPoint)
{
segmentTopology[1] = -1;
lastPointFound = true;
}
vtkIdType i;
bifurcations->InitTraversal();
bifurcationsRadii->InitTraversal();
for (i=0; i<bifurcations->GetNumberOfItems(); i++)
{
vtkPoints* bifurcation = (vtkPoints*)bifurcations->GetNextItemAsObject();
vtkDoubleArray* bifurcationRadii = (vtkDoubleArray*)bifurcationsRadii->GetNextItemAsObject();
vtkIdType j;
for (j=0; j<bifurcation->GetNumberOfPoints(); j++)
{
if (i == 0 || (i > 0 && j > 0))
{
double point[3];
bifurcation->GetPoint(j,point);
if (!firstPointFound)
{
if (point[0] == firstSegmentPoint[0] && point[1] == firstSegmentPoint[1] && point[2] == firstSegmentPoint[2])
{
segmentTopology[0] = i;
if (j > 0)
{
bifurcation->GetPoint(0,firstPoint);
firstRadius = bifurcationRadii->GetValue(j);
}
firstPointFound = true;
}
}
if (lastSegmentPoint && !lastPointFound)
{
if (point[0] == lastSegmentPoint[0] && point[1] == lastSegmentPoint[1] && point[2] == lastSegmentPoint[2])
{
segmentTopology[1] = i;
if (j>0)
{
bifurcation->GetPoint(0,lastPoint);
lastRadius = bifurcationRadii->GetValue(j);
}
lastPointFound = true;
}
}
}
if (firstPointFound && lastPointFound)
{
break;
}
}
if (firstPointFound && lastPointFound)
{
break;
}
}
}
void vtkvmtkPolyDataNetworkExtraction::BuildSegment(vtkPoints* segmentPoints, vtkDoubleArray* segmentRadii, vtkIdType segmentTopology[2], double firstPoint[3], double firstRadius, double lastPoint[3], double lastRadius, const double* centralPoint, vtkPolyData* segment)
{
vtkPoints* segmentPolyPoints = vtkPoints::New();
vtkDoubleArray* segmentPolyScalars = vtkDoubleArray::New();
segmentPolyScalars->SetName(RadiusArrayName);
vtkIdTypeArray* segmentTopologyArray = vtkIdTypeArray::New();
segmentTopologyArray->SetName(TopologyArrayName);
segmentTopologyArray->SetNumberOfComponents(2);
segmentTopologyArray->InsertNextTupleValue(segmentTopology);
// start
if (segmentTopology[0] > 0)
{
segmentPolyPoints->InsertNextPoint(firstPoint);
segmentPolyScalars->InsertNextValue(firstRadius);
segmentPolyScalars->InsertNextValue(firstRadius);
}
else
{
segmentPolyScalars->InsertNextValue(0.0);
}
vtkIdType i;
// mid
if (segmentPoints)
{
for (i=0; i<segmentPoints->GetNumberOfPoints(); i++)
{
segmentPolyPoints->InsertNextPoint(segmentPoints->GetPoint(i));
}
for (i=0; i<segmentRadii->GetNumberOfTuples(); i++)
{
segmentPolyScalars->InsertNextValue(segmentRadii->GetValue(i));
}
}
else
{
segmentPolyPoints->InsertNextPoint(centralPoint);
}
// end
if (segmentTopology[1] > 0)
{
segmentPolyScalars->InsertNextValue(lastRadius);
segmentPolyPoints->InsertNextPoint(lastPoint);
segmentPolyScalars->InsertNextValue(lastRadius);
}
else
{
segmentPolyScalars->InsertNextValue(0.0);
}
vtkCellArray* segmentPolyLine = vtkCellArray::New();
segmentPolyLine->InsertNextCell(segmentPolyPoints->GetNumberOfPoints());
vtkIdType j;
for (j=0; j<segmentPolyPoints->GetNumberOfPoints(); j++)
{
segmentPolyLine->InsertCellPoint(j);
}
segment->SetPoints(segmentPolyPoints);
segment->GetPointData()->AddArray(segmentPolyScalars);
segment->GetCellData()->AddArray(segmentTopologyArray);
segment->SetLines(segmentPolyLine);
segment->Update();
segmentPolyPoints->Delete();
segmentPolyScalars->Delete();
segmentPolyLine->Delete();
segmentTopologyArray->Delete();
}
void vtkvmtkPolyDataNetworkExtraction::InsertNewBifurcation(vtkCollection* bifurcations, vtkCollection* bifurcationsRadii, vtkPoints* bifurcationPoints, vtkDoubleArray* bifurcationRadii, vtkPolyDataCollection* additionalSegments)
{
vtkIdType i;
bifurcations->InitTraversal();
bifurcationsRadii->InitTraversal();
for (i=0; i<bifurcations->GetNumberOfItems(); i++)
{
vtkPoints* currentBifurcationPoints = (vtkPoints*)bifurcations->GetNextItemAsObject();
vtkDoubleArray* currentBifurcationRadii = (vtkDoubleArray*)bifurcationsRadii->GetNextItemAsObject();
vtkIdType j;
for (j=0; j<currentBifurcationPoints->GetNumberOfPoints(); j++)
{
if (i == 0 || (i > 0 && j > 0))
{
double currentBifurcationPoint[3];
currentBifurcationPoints->GetPoint(j,currentBifurcationPoint);
vtkIdType k;
for (k=0; k<bifurcationPoints->GetNumberOfPoints(); k++)
{
double bifurcationPoint[3];
bifurcationPoints->GetPoint(k,bifurcationPoint);
if ((currentBifurcationPoint[0]==bifurcationPoint[0]) && (currentBifurcationPoint[1]==bifurcationPoint[1]) && (currentBifurcationPoint[2]==bifurcationPoint[2]))
{
vtkIdType additionalSegmentTopology[2];
additionalSegmentTopology[0] = i;
additionalSegmentTopology[1] = bifurcations->GetNumberOfItems();
double currentBifurcationPoint0[3], bifurcationPoint0[3];
currentBifurcationPoints->GetPoint(0,currentBifurcationPoint0);
bifurcationPoints->GetPoint(0,bifurcationPoint0);
vtkPolyData* additionalSegment = vtkPolyData::New();
this->BuildSegment(NULL,NULL,additionalSegmentTopology,currentBifurcationPoint0,currentBifurcationRadii->GetValue(j),bifurcationPoint0,bifurcationRadii->GetValue(k),bifurcationPoint,additionalSegment);
additionalSegments->AddItem(additionalSegment);
additionalSegment->Delete();
}
}
}
}
}
bifurcations->AddItem(bifurcationPoints);
bifurcationsRadii->AddItem(bifurcationRadii);
}
void vtkvmtkPolyDataNetworkExtraction::SegmentIteration(vtkPolyData* model, vtkPolyData* initialProfile, vtkIdTypeArray* initialProfileEdgeTable, vtkPolyDataCollection* globalProfiles, vtkCollection* globalProfilesEdgeTables, vtkCollection* bifurcations, vtkCollection* bifurcationsRadii, vtkPolyDataCollection* segments, double advancementRatio)
{
vtkPolyDataCollection* baseProfiles = vtkPolyDataCollection::New();
baseProfiles->AddItem(initialProfile);
vtkCollection* baseProfilesEdgeTables = vtkCollection::New();
baseProfilesEdgeTables->AddItem(initialProfileEdgeTable);
vtkPolyDataCollection* newProfiles = vtkPolyDataCollection::New();
vtkCollection* newProfilesEdgeTables = vtkCollection::New();
vtkPoints* segmentPoints = vtkPoints::New();
vtkDoubleArray* segmentRadii = vtkDoubleArray::New();
vtkPoints* bifurcationPoints = vtkPoints::New();
vtkDoubleArray* bifurcationRadii = vtkDoubleArray::New();
double oldCenter[3];
double oldRadius = 0.0;
vtkIdType stepIterationState = STEP_ITERATION_PROCEED;
while (stepIterationState == STEP_ITERATION_PROCEED || stepIterationState == STEP_ITERATION_REDEFINE)
{
stepIterationState = STEP_ITERATION_PROCEED;
stepIterationState = this->StepIteration(model,baseProfiles,baseProfilesEdgeTables,globalProfiles,globalProfilesEdgeTables,newProfiles,newProfilesEdgeTables,segmentPoints,segmentRadii,bifurcationPoints,bifurcationRadii,oldCenter,oldRadius,advancementRatio);
// avoid zero steps
if (stepIterationState == STEP_ITERATION_PROCEED && oldRadius == 0.0)
{
stepIterationState = STEP_ITERATION_STOP_CLOSED;
}
if (stepIterationState == STEP_ITERATION_PROCEED)
{
baseProfiles->RemoveAllItems();
baseProfilesEdgeTables->RemoveAllItems();
newProfiles->InitTraversal();
newProfilesEdgeTables->InitTraversal();
baseProfiles->AddItem(newProfiles->GetNextItem());
baseProfilesEdgeTables->AddItem(newProfilesEdgeTables->GetNextItemAsObject());
newProfiles->RemoveAllItems();
newProfilesEdgeTables->RemoveAllItems();
}
}
vtkPolyData* segment = vtkPolyData::New();
vtkPolyDataCollection* additionalSegments = vtkPolyDataCollection::New();
vtkIdType segmentTopology[2];
double firstPoint[3], lastPoint[3];
double firstRadius, lastRadius;
if (stepIterationState == STEP_ITERATION_STOP_BIFURCATION)
{
vtkIdType i;
newProfiles->InitTraversal();
newProfilesEdgeTables->InitTraversal();
for (i=0; i<newProfiles->GetNumberOfItems(); i++)
{
globalProfiles->AddItem(newProfiles->GetNextItem());
vtkIdTypeArray* newGlobalProfileEdgeTable = (vtkIdTypeArray*)newProfilesEdgeTables->GetNextItemAsObject();
globalProfilesEdgeTables->AddItem(newGlobalProfileEdgeTable);
this->MarkModelGlobalProfile(model,newGlobalProfileEdgeTable);
}
// adjacent check
this->InsertNewBifurcation(bifurcations,bifurcationsRadii,bifurcationPoints,bifurcationRadii,additionalSegments);
if (segmentPoints->GetNumberOfPoints()>=2)
{
double segmentPoint0[3], segmentPoint1[3];
segmentPoints->GetPoint(0,segmentPoint0);
segmentPoints->GetPoint(segmentPoints->GetNumberOfPoints()-1,segmentPoint1);
this->SegmentTopology(bifurcations,bifurcationsRadii,segmentPoint0,segmentPoint1,firstPoint,firstRadius,lastPoint,lastRadius,segmentTopology);
this->BuildSegment(segmentPoints,segmentRadii,segmentTopology,firstPoint,firstRadius,lastPoint,lastRadius,NULL,segment);
segments->AddItem(segment);
}
}
else if (stepIterationState == STEP_ITERATION_STOP_END)
{
if (segmentPoints->GetNumberOfPoints() >= 2)
{
double segmentPoint0[3], segmentPoint1[3];
segmentPoints->GetPoint(0,segmentPoint0);
segmentPoints->GetPoint(segmentPoints->GetNumberOfPoints()-1,segmentPoint1);
this->SegmentTopology(bifurcations,bifurcationsRadii,segmentPoint0,segmentPoint1,firstPoint,firstRadius,lastPoint,lastRadius,segmentTopology);
this->BuildSegment(segmentPoints,segmentRadii,segmentTopology,firstPoint,firstRadius,lastPoint,lastRadius,NULL,segment);
segments->AddItem(segment);
}
}
else if (stepIterationState == STEP_ITERATION_STOP_CLOSED)
{
if (segmentPoints->GetNumberOfPoints() >= 2)
{
double segmentPoint0[3];
segmentPoints->GetPoint(0,segmentPoint0);
this->SegmentTopology(bifurcations,bifurcationsRadii,segmentPoint0,NULL,firstPoint,firstRadius,lastPoint,lastRadius,segmentTopology);
this->BuildSegment(segmentPoints,segmentRadii,segmentTopology,firstPoint,firstRadius,lastPoint,lastRadius,NULL,segment);
segments->AddItem(segment);
}
}
segment->Delete();
additionalSegments->InitTraversal();
vtkIdType k;
for (k=0; k<additionalSegments->GetNumberOfItems(); k++)
{
segments->AddItem(additionalSegments->GetNextItem());
}
additionalSegments->Delete();
baseProfiles->Delete();
baseProfilesEdgeTables->Delete();
newProfiles->Delete();
newProfilesEdgeTables->Delete();
segmentPoints->Delete();
segmentRadii->Delete();
bifurcationPoints->Delete();
bifurcationRadii->Delete();
}
void vtkvmtkPolyDataNetworkExtraction::JoinSegments (vtkPolyData* segment0, vtkPolyData* segment1, bool first0, bool first1, vtkPolyData* segment)
{
vtkPoints* segmentPoints = vtkPoints::New();
vtkDoubleArray* radiusArray = vtkDoubleArray::New();
radiusArray->SetName(RadiusArrayName);
vtkIdTypeArray* topologyArray = vtkIdTypeArray::New();
topologyArray->SetNumberOfComponents(2);
topologyArray->SetName(TopologyArrayName);
vtkDoubleArray* segment0RadiusArray = vtkDoubleArray::SafeDownCast(segment0->GetPointData()->GetArray(RadiusArrayName));
vtkDoubleArray* segment1RadiusArray = vtkDoubleArray::SafeDownCast(segment1->GetPointData()->GetArray(RadiusArrayName));
vtkIdTypeArray* segment0TopologyArray = vtkIdTypeArray::SafeDownCast(segment0->GetCellData()->GetArray(TopologyArrayName));
vtkIdTypeArray* segment1TopologyArray = vtkIdTypeArray::SafeDownCast(segment1->GetCellData()->GetArray(TopologyArrayName));
vtkIdType segmentTopology0[2];
vtkIdType segmentTopology1[2];
segment0TopologyArray->GetTupleValue(0,segmentTopology0);
segment1TopologyArray->GetTupleValue(0,segmentTopology1);
vtkIdType segmentTopology[2];
vtkIdType i;
if (first0)
{
segmentTopology[0] = segmentTopology0[1];
for (i=segment0->GetNumberOfPoints()-1; i>=1; i--)
{
segmentPoints->InsertNextPoint(segment0->GetPoint(i));
radiusArray->InsertNextValue(segment0RadiusArray->GetValue(i));
}
}
else
{
segmentTopology[0] = segmentTopology0[0];
for (i=0; i<segment0->GetNumberOfPoints()-1; i++)
{
segmentPoints->InsertNextPoint(segment0->GetPoint(i));
radiusArray->InsertNextValue(segment0RadiusArray->GetValue(i));
}
}
if (first1)
{
segmentTopology[1] = segmentTopology1[1];
for (i=1; i<segment1->GetNumberOfPoints(); i++)
{
segmentPoints->InsertNextPoint(segment1->GetPoint(i));
radiusArray->InsertNextValue(segment1RadiusArray->GetValue(i));
}
}
else
{
segmentTopology[1] = segmentTopology1[1];
for (i=segment1->GetNumberOfPoints()-2; i>=0; i--)
{
segmentPoints->InsertNextPoint(segment1->GetPoint(i));
radiusArray->InsertNextValue(segment1RadiusArray->GetValue(i));
}
}
topologyArray->InsertNextTupleValue(segmentTopology);
vtkCellArray* segmentCell = vtkCellArray::New();
segmentCell->InsertNextCell(segmentPoints->GetNumberOfPoints());
for (i=0; i<segmentPoints->GetNumberOfPoints(); i++)
{
segmentCell->InsertCellPoint(i);
}
segment->SetPoints(segmentPoints);
segment->SetLines(segmentCell);
segment->GetPointData()->AddArray(radiusArray);
segment->GetCellData()->AddArray(topologyArray);
segment->Update();
radiusArray->Delete();
topologyArray->Delete();
segmentPoints->Delete();
segmentCell->Delete();
}
void vtkvmtkPolyDataNetworkExtraction::RemoveDegenerateBifurcations(vtkPolyDataCollection* segments,vtkCollection* bifurcations)
{
vtkIdList* realBifurcations = vtkIdList::New();
realBifurcations->InsertNextId(0);
vtkIdList* degenerateBifurcations = vtkIdList::New();
vtkIdTypeArray* bifurcationFrequency = vtkIdTypeArray::New();
bifurcations->InitTraversal();
vtkIdType i;
for (i=0; i<bifurcations->GetNumberOfItems(); i++)
{
bifurcationFrequency->InsertNextValue(0);
}
segments->InitTraversal();
for (i=0; i<segments->GetNumberOfItems(); i++)
{
vtkPolyData* segment = segments->GetNextItem();
// vtkDoubleArray* radiusArray = vtkDoubleArray::SafeDownCast(segment->GetPointData()->GetArray(RadiusArrayName));
vtkIdTypeArray* topologyArray = vtkIdTypeArray::SafeDownCast(segment->GetCellData()->GetArray(TopologyArrayName));
vtkIdType topology[2];
topologyArray->GetTupleValue(0,topology);
vtkIdType bifurcation0 = topology[0];
if (bifurcation0 > 0)
{
vtkIdType frequency0 = bifurcationFrequency->GetValue(bifurcation0);
bifurcationFrequency->InsertValue(bifurcation0,frequency0+1);
}
vtkIdType bifurcation1 = topology[1];
if (bifurcation1 > 0)
{
vtkIdType frequency1 = bifurcationFrequency->GetValue(bifurcation1);
bifurcationFrequency->InsertValue(bifurcation1,frequency1+1);
}
}
for (i=0; i<bifurcationFrequency->GetNumberOfTuples(); i++)
{
if (i > 0)
{
if (bifurcationFrequency->GetValue(i) < 3)
{
degenerateBifurcations->InsertNextId(i);
}
else
{
realBifurcations->InsertNextId(i);
}
}
}
// vtkIdType n = degenerateBifurcations->GetNumberOfIds();
while (degenerateBifurcations->GetNumberOfIds() > 0)
{
segments->InitTraversal();
vtkPolyData* segment0 = NULL,* segment1 = NULL,* currentSegment;
vtkIdType degenerateId = -1;
bool first0, first1;
first0 = first1 = false;
for (i=0; i<segments->GetNumberOfItems(); i++)
{
currentSegment = segments->GetNextItem();
// vtkDoubleArray* radiusArray = vtkDoubleArray::SafeDownCast(currentSegment->GetPointData()->GetArray(RadiusArrayName));
vtkIdTypeArray* topologyArray = vtkIdTypeArray::SafeDownCast(currentSegment->GetCellData()->GetArray(TopologyArrayName));
vtkIdType topology[2];
topologyArray->GetTupleValue(0,topology);
if (!segment0)
{
degenerateId = topology[0];
if (degenerateBifurcations->IsId(degenerateId) != -1)
{
segment0 = currentSegment;
first0 = true;
degenerateBifurcations->DeleteId(degenerateId);
}
if (!segment0)
{
degenerateId = topology[1];
if (degenerateBifurcations->IsId(degenerateId) != -1)
{
segment0 = currentSegment;
first0 = false;
degenerateBifurcations->DeleteId(degenerateId);
}
}
}
else if (!segment1)
{
if (topology[0] == degenerateId)
{
segment1 = currentSegment;
first1 = true;
}
if (topology[1] == degenerateId)
{
segment1 = currentSegment;
first1 = false;
}
}
}
if (segment0 && segment1)
{
segment0->Register((vtkObjectBase*)NULL);
segment1->Register((vtkObjectBase*)NULL);
segments->RemoveItem(segment0);
segments->RemoveItem(segment1);
vtkPolyData* joinedSegment = vtkPolyData::New();
this->JoinSegments(segment0,segment1,first0,first1,joinedSegment);
segments->AddItem(joinedSegment);
joinedSegment->Delete();
segment0->UnRegister((vtkObjectBase*)NULL);
segment1->UnRegister((vtkObjectBase*)NULL);
}
}
// rename bifurcations
segments->InitTraversal();
vtkIdType scalar0, scalar1, position0, position1;
for (i=0; i<segments->GetNumberOfItems(); i++)
{
vtkPolyData* currentSegment = segments->GetNextItem();
// vtkDoubleArray* radiusArray = vtkDoubleArray::SafeDownCast(currentSegment->GetPointData()->GetArray(RadiusArrayName));
vtkIdTypeArray* topologyArray = vtkIdTypeArray::SafeDownCast(currentSegment->GetCellData()->GetArray(TopologyArrayName));
vtkIdType topology[2];
topologyArray->GetTupleValue(0,topology);
scalar0 = topology[0];
scalar1 = topology[1];
if (scalar0 > 0)
{
position0 = realBifurcations->InsertUniqueId(scalar0);
topology[0] = position0;
}
if (scalar1>0)
{
position1=realBifurcations->InsertUniqueId(scalar1);
topology[1] = position1;
}
topologyArray->InsertTupleValue(0,topology);
}
realBifurcations->Delete();
degenerateBifurcations->Delete();
bifurcationFrequency->Delete();
}
void vtkvmtkPolyDataNetworkExtraction::GlobalIteration(vtkPolyData* model, vtkPolyDataCollection* globalProfiles, vtkPolyData* network, double advancementRatio)
{
vtkCollection* globalProfilesEdgeTables = vtkCollection::New();
this->UpdateEdgeTableCollectionReal(model,globalProfiles,globalProfilesEdgeTables);
vtkCollection* bifurcations = vtkCollection::New();
vtkCollection* bifurcationsRadii = vtkCollection::New();
vtkPolyDataCollection* segments = vtkPolyDataCollection::New();
vtkPoints* globalBoundaryBarycenters = vtkPoints::New();
vtkDoubleArray* globalBoundaryRadii = vtkDoubleArray::New();
vtkPolyData* profile;
vtkIdType i;
globalProfiles->InitTraversal();
for (i=0; i<globalProfiles->GetNumberOfItems(); i++)
{
profile=globalProfiles->GetNextItem();
double barycenter[3];
this->ProfileBarycenter(profile->GetPoints(),barycenter);
globalBoundaryBarycenters->InsertNextPoint(barycenter);
globalBoundaryRadii->InsertNextValue(ComputeMeanRadius(profile->GetPoints(),barycenter));
}
bifurcations->AddItem(globalBoundaryBarycenters);
bifurcationsRadii->AddItem(globalBoundaryRadii);
while (globalProfiles->GetNumberOfItems())
{
globalProfiles->InitTraversal();
vtkPolyData* initialProfile = globalProfiles->GetNextItem();
initialProfile->Register((vtkObjectBase*)NULL);
globalProfiles->RemoveItem(initialProfile);
globalProfilesEdgeTables->InitTraversal();
vtkIdTypeArray* initialProfileEdgeTable = (vtkIdTypeArray*)globalProfilesEdgeTables->GetNextItemAsObject();
initialProfileEdgeTable->Register((vtkObjectBase*)NULL);
globalProfilesEdgeTables->RemoveItem(initialProfileEdgeTable);
this->SegmentIteration(model,initialProfile,initialProfileEdgeTable,globalProfiles,globalProfilesEdgeTables,bifurcations,bifurcationsRadii,segments,advancementRatio);
double progress = (double)this->TotalMarkedPoints/(double)model->GetNumberOfPoints();
this->InvokeEvent(vtkCommand::ProgressEvent,&progress);
initialProfile->UnRegister((vtkObjectBase*)NULL);
initialProfileEdgeTable->UnRegister((vtkObjectBase*)NULL);
}
this->RemoveDegenerateBifurcations(segments,bifurcations);
vtkIdTypeArray* topologyArray = vtkIdTypeArray::New();
topologyArray->SetName(TopologyArrayName);
topologyArray->SetNumberOfComponents(2);
segments->InitTraversal();
for (i=0; i<segments->GetNumberOfItems(); i++)
{
vtkIdType topology[2];
vtkIdTypeArray* segmentTopologyArray = vtkIdTypeArray::SafeDownCast(segments->GetNextItem()->GetCellData()->GetArray(TopologyArrayName));
segmentTopologyArray->GetTupleValue(0,topology);
topologyArray->InsertNextTupleValue(topology);
}
vtkAppendPolyData* segmentsAppended = vtkAppendPolyData::New();
segments->InitTraversal();
for (i=0; i<segments->GetNumberOfItems(); i++)
{
segmentsAppended->AddInput(segments->GetNextItem());
}
segmentsAppended->Update();
network->DeepCopy(segmentsAppended->GetOutput());
network->GetCellData()->AddArray(topologyArray);
network->Update();
globalProfilesEdgeTables->Delete();
bifurcations->Delete();
bifurcationsRadii->Delete();
segments->Delete();
globalBoundaryBarycenters->Delete();
globalBoundaryRadii->Delete();
segmentsAppended->Delete();
topologyArray->Delete();
}
void vtkvmtkPolyDataNetworkExtraction::MarkModelRealBoundary(vtkPolyData* model, vtkPolyData* modelBoundary)
{
vtkIdTypeArray* marksArray = vtkIdTypeArray::SafeDownCast(model->GetPointData()->GetArray(MarksArrayName));
vtkIdType i;
for (i=0; i<model->GetNumberOfPoints(); i++)
{
marksArray->InsertValue(i,NON_VISITED);
}
for (i=0; i<modelBoundary->GetNumberOfPoints(); i++)
{
marksArray->InsertValue(model->FindPoint(modelBoundary->GetPoint(i)),GLOBAL);
}
}
void vtkvmtkPolyDataNetworkExtraction::Graph(vtkPolyData* network, vtkPolyData* graphLayout)
{
vtkPoints* graphPoints = vtkPoints::New();
vtkCellArray* graphLines = vtkCellArray::New();
vtkDoubleArray* graphRadiusArray = vtkDoubleArray::New();
graphRadiusArray->SetName(this->RadiusArrayName);
graphLayout->SetPoints(graphPoints);
graphLayout->SetLines(graphLines);
graphLayout->GetCellData()->AddArray(graphRadiusArray);
vtkIdType numberOfPoints = network->GetNumberOfPoints();
vtkIdType numberOfCells = network->GetNumberOfCells();
vtkIdTypeArray* isPointInserted = vtkIdTypeArray::New();
isPointInserted->SetNumberOfTuples(numberOfPoints);
isPointInserted->FillComponent(0,-1);
vtkDoubleArray* radiusArray = vtkDoubleArray::SafeDownCast(network->GetPointData()->GetArray(this->RadiusArrayName));
vtkIdTypeArray* topologyArray = vtkIdTypeArray::SafeDownCast(network->GetCellData()->GetArray(this->TopologyArrayName));
for (int i=0; i<numberOfCells; i++)
{
vtkCell* cell = network->GetCell(i);
vtkIdType topology[2];
topologyArray->GetTupleValue(i,topology);
vtkIdType numberOfCellPoints = cell->GetNumberOfPoints();
double meanRadius = 0.0;
for (int j=0; j<numberOfCellPoints; j++)
{
double radius = radiusArray->GetValue(cell->GetPointId(j));
meanRadius += radius;
}
meanRadius /= numberOfCellPoints;
vtkIdType pointId0 = cell->GetPointId(0);
vtkIdType pointId1 = cell->GetPointId(numberOfCellPoints-1);
vtkIdType newPointId0 = -1;
vtkIdType newPointId1 = -1;
if (isPointInserted->GetValue(pointId0) == -1)
{
newPointId0 = graphPoints->InsertNextPoint(network->GetPoint(pointId0));
isPointInserted->SetValue(pointId0,newPointId0);
}
else
{
newPointId0 = isPointInserted->GetValue(pointId0);
}
if (isPointInserted->GetValue(pointId1) == -1)
{
newPointId1 = graphPoints->InsertNextPoint(network->GetPoint(pointId1));
isPointInserted->SetValue(pointId1,newPointId1);
}
else
{
newPointId1 = isPointInserted->GetValue(pointId1);
}
graphLines->InsertNextCell(2);
graphLines->InsertCellPoint(newPointId0);
graphLines->InsertCellPoint(newPointId1);
graphRadiusArray->InsertNextValue(meanRadius);
}
graphPoints->Delete();
graphLines->Delete();
graphRadiusArray->Delete();
isPointInserted->Delete();
}
int vtkvmtkPolyDataNetworkExtraction::RequestData(vtkInformation *vtkNotUsed(request), vtkInformationVector **inputVector, vtkInformationVector *outputVector)
{
vtkInformation *inInfo = inputVector[0]->GetInformationObject(0);
vtkInformation *outInfo = outputVector->GetInformationObject(0);
vtkPolyData *input = vtkPolyData::SafeDownCast(inInfo->Get(vtkDataObject::DATA_OBJECT()));
vtkPolyData *output = vtkPolyData::SafeDownCast(outInfo->Get(vtkDataObject::DATA_OBJECT()));
this->TotalMarkedPoints = 0;
vtkPolyData* model = vtkPolyData::New();
model->DeepCopy(input);
vtkIdTypeArray* marksArray = vtkIdTypeArray::New();
marksArray->SetName(this->MarksArrayName);
marksArray->SetNumberOfTuples(model->GetNumberOfPoints());
model->GetPointData()->AddArray(marksArray);
vtkPolyData* modelBoundary = vtkPolyData::New();
this->BoundaryExtractor(model,modelBoundary);
vtkPolyData* network = vtkPolyData::New();
if (modelBoundary->GetNumberOfPoints() > 0)
{
this->MarkModelRealBoundary(model,modelBoundary);
model->BuildCells();
model->BuildLinks();
vtkPolyDataCollection* globalProfiles = vtkPolyDataCollection::New();
this->BoundarySeparator(modelBoundary,globalProfiles);
this->GlobalIteration(model,globalProfiles,network,this->AdvancementRatio);
globalProfiles->Delete();
}
marksArray->Delete();
modelBoundary->Delete();
double progress = 1.0;
this->InvokeEvent(vtkCommand::ProgressEvent,&progress);
output->DeepCopy(network);
if (this->GraphLayout)
{
this->GraphLayout->Delete();
this->GraphLayout = NULL;
}
this->GraphLayout = vtkPolyData::New();
this->Graph(network,this->GraphLayout);
network->Delete();
return 1;
}
void vtkvmtkPolyDataNetworkExtraction::PrintSelf(ostream& os, vtkIndent indent)
{
this->Superclass::PrintSelf(os,indent);
}
|
#include <algorithm>
#include <cassert>
#include <cstdio>
#include <iostream>
#include <sstream>
#include <string>
#include <vector>
#include <cctype>
using namespace std;
class LetterFreq {
public:
vector <int> getFreqs(vector <string> doc) {
vector<int> sol(26, 0);
for (int i=0; i<(int)doc.size(); ++i)
for (int j=0; j<(int)doc[i].size(); ++j)
if (isalpha(doc[i][j]))
++sol[toupper(doc[i][j])-'A'];
return sol;
}
// BEGIN CUT HERE
public:
void run_test(int Case) { if ((Case == -1) || (Case == 0)) test_case_0(); if ((Case == -1) || (Case == 1)) test_case_1(); if ((Case == -1) || (Case == 2)) test_case_2(); if ((Case == -1) || (Case == 3)) test_case_3(); }
private:
template <typename T> string print_array(const vector<T> &V) { ostringstream os; os << "{ "; for (typename vector<T>::const_iterator iter = V.begin(); iter != V.end(); ++iter) os << '\"' << *iter << "\","; os << " }"; return os.str(); }
void verify_case(int Case, const vector <int> &Expected, const vector <int> &Received) { cerr << "Test Case #" << Case << "..."; if (Expected == Received) cerr << "PASSED" << endl; else { cerr << "FAILED" << endl; cerr << "\tExpected: " << print_array(Expected) << endl; cerr << "\tReceived: " << print_array(Received) << endl; } }
void test_case_0() { string Arr0[] = { "Be sure to ignore case", "and non-letter characters"}
; vector <string> Arg0(Arr0, Arr0 + (sizeof(Arr0) / sizeof(Arr0[0]))); int Arr1[] = { 4, 1, 3, 1, 7, 0, 1, 1, 1, 0, 0, 1, 0, 4, 3, 0, 0, 5, 3, 4, 1, 0, 0, 0, 0, 0 }; vector <int> Arg1(Arr1, Arr1 + (sizeof(Arr1) / sizeof(Arr1[0]))); verify_case(0, Arg1, getFreqs(Arg0)); }
void test_case_1() { string Arr0[] = {"The following table shows letter frequences","for 3 languages.",
"Letter English French German",
"A 7.3% 8.174% 5.997%",
"B 0.9% 0.876% 1.703%",
"C 3% 3.063% 2.697%",
"D 4.4% 4.125% 5.409%",
"E 13% 17.564% 17.949%",
"F 2.8% 0.959% 1.595%",
"G 1.6% 1.051% 3.199%",
"H 3.5% 0.721% 4.125%",
"I 7.4% 7.559% 8.125%",
"J 0.2% 0.598% 0.319%",
"K 0.3% 0.014% 1.244%",
"L 3.5% 5.783% 3.130%",
"M 2.5% 2.99% 2.264%",
"N 7.8% 7.322% 10.551",
"O 7.4% 5.289% 2.722%",
"P 2.7% 2.98% 0.831%",
"Q 0.3% 1.361% 0.009%",
"R 7.7% 6.219% 7.226%",
"S 6.3% 8.013% 6.873%",
"T 9.3% 7.353% 5.740%",
"U 2.7% 5.991% 4.584%",
"V 1.3% 1.557% 0.870%",
"W 1.6% 0.02% 1.497%",
"X 0.5% 3.5% 0.019%",
"Y 1.9% 1.16% 0.039%",
"Z 1% 0.72% 1.089%"}; vector <string> Arg0(Arr0, Arr0 + (sizeof(Arr0) / sizeof(Arr0[0]))); int Arr1[] = { 5, 2, 3, 1, 14, 5, 6, 5, 3, 1, 1, 8, 2, 7, 5, 1, 2, 7, 6, 7, 3, 1, 3, 1, 1, 1 }; vector <int> Arg1(Arr1, Arr1 + (sizeof(Arr1) / sizeof(Arr1[0]))); verify_case(1, Arg1, getFreqs(Arg0)); }
void test_case_2() { string Arr0[] = { "Friends, Romans, countrymen, lend me your ears; ",
"I come to bury Caesar, not to praise him. ",
"The evil that men do lives after them; ",
"The good is oft interred with their bones; ",
"So let it be with Caesar. The noble Brutus ",
"Hath told you Caesar was ambitious: ",
"If it were so, it was a grievous fault, ",
"And grievously hath Caesar answer'd it. ",
"Here, under leave of Brutus and the rest-- ",
"For Brutus is an honourable man; ",
"So are they all, all honourable men-- ",
"Come I to speak in Caesar's funeral. ",
"He was my friend, faithful and just to me: ",
"But Brutus says he was ambitious; ",
"And Brutus is an honourable man. ",
"He hath brought many captives home to Rome ",
"Whose ransoms did the general coffers fill: ",
"Did this in Caesar seem ambitious? ",
"When that the poor have cried, Caesar hath wept: ",
"Ambition should be made of sterner stuff: ",
"Yet Brutus says he was ambitious; ",
"And Brutus is an honourable man. ",
"You all did see that on the Lupercal ",
"I thrice presented him a kingly crown, ",
"Which he did thrice refuse: was this ambition? ",
"Yet Brutus says he was ambitious; ",
"And, sure, he is an honourable man. ",
"I speak not to disprove what Brutus spoke, ",
"But here I am to speak what I do know. ",
"You all did love him once, not without cause: ",
"What cause withholds you then, to mourn for him? ",
"O judgment! thou art fled to brutish beasts, ",
"And men have lost their reason. Bear with me; ",
"My heart is in the coffin there with Caesar, ",
"And I must pause till it come back to me. "}
; vector <string> Arg0(Arr0, Arr0 + (sizeof(Arr0) / sizeof(Arr0[0]))); int Arr1[] = { 101, 33, 25, 36, 122, 22, 7, 70, 75, 2, 7, 37, 40, 60, 81, 12, 0, 71, 86, 101, 59, 10, 24, 0, 18, 0 }; vector <int> Arg1(Arr1, Arr1 + (sizeof(Arr1) / sizeof(Arr1[0]))); verify_case(2, Arg1, getFreqs(Arg0)); }
void test_case_3() { string Arr0[] = { "amis, Romans, compatriotes,"," me pretent vos oreilles; ",
"je viens pour enterrer Caesar,"," pour ne pas le feliciter. ",
"le mal que les hommes les vies apres eux; ",
"le bon est oft interred avec leurs os; ",
"laissez-ainsi l'etre avec Caesar. Le Brutus noble",
"Hath vous a indique que Caesar etait ambitieux: ",
"s'il en etait ainsi, c'etait un defaut grave,",
"et gravement answer'd de Caesar de hath il. ",
"ici, sous le conge de Brutus et du repos --",
"pour Brutus est un homme honorable; ",
"sont ainsi ils tous, tous les hommes honorables --",
"viennent I a parler dans l'enterrement de Caesar.",
"il etait mon ami, fidele et juste a moi: ",
"mais Brutus indique qu'il etait ambitieux; ",
"et Brutus est un homme honorable. ",
"il hath a apporte a beaucoup des captifs"," a la maison a Rome",
"dont les ransoms ont fait la suffisance"," generale de coffres: est-ce que ",
"ceci dans Caesar a semble ambitieux? ",
"quand cela les pauvres ont pleure,"," le hath de Caesar a pleure: ",
"l'ambition devrait etre faite"," de substance de sterner:",
"pourtant Brutus indique qu'il etait ambitieux; ",
"et Brutus est un homme honorable. ",
"vous tout avez vu que sur le Lupercal",
"je trois fois lui ai presente kingly une couronne,",
"qu'il a trois fois refuse:"," etait-elle cette ambition?",
"pourtant Brutus indique qu'il etait ambitieux; ",
"et, sur, il est un homme honorable. ",
"je parle pour ne pas refuter quel Brutus a parle,",
"mais ici je dois parler ce que je sais. ",
"vous tout l'avez aime par le passe,"," pas sans cause:",
"quelle cause vous retient alors,"," pour pleurer pour lui?",
"jugement de O! l'art de thou"," sauve aux betes de brutish, ",
"et aux hommes ont perdu leur raison."," Ours avec moi;",
"mon coeur est dans le cercueil la avec Caesar,",
"et je dois faire une pause jusqu'a"," ce qu'il reviennent a moi" }; vector <string> Arg0(Arr0, Arr0 + (sizeof(Arr0) / sizeof(Arr0[0]))); int Arr1[] = { 121, 28, 37, 30, 208, 16, 6, 22, 94, 9, 1, 69, 42, 69, 77, 33, 18, 92, 109, 103, 102, 21, 1, 8, 1, 3 }; vector <int> Arg1(Arr1, Arr1 + (sizeof(Arr1) / sizeof(Arr1[0]))); verify_case(3, Arg1, getFreqs(Arg0)); }
// END CUT HERE
};
// BEGIN CUT HERE
int main()
{
LetterFreq ___test;
___test.run_test(-1);
}
// END CUT HERE
|
// Copyright 2018 Google LLC
//
// 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 "google/cloud/storage/internal/notification_requests.h"
#include <iostream>
namespace google {
namespace cloud {
namespace storage {
inline namespace STORAGE_CLIENT_NS {
namespace internal {
StatusOr<NotificationMetadata> NotificationMetadataParser::FromJson(
internal::nl::json const& json) {
if (!json.is_object()) {
return Status(StatusCode::kInvalidArgument, __func__);
}
NotificationMetadata result{};
if (json.count("custom_attributes") != 0) {
for (auto const& kv : json["custom_attributes"].items()) {
result.custom_attributes_.emplace(kv.key(),
kv.value().get<std::string>());
}
}
result.etag_ = json.value("etag", "");
if (json.count("event_types") != 0) {
for (auto const& kv : json["event_types"].items()) {
result.event_types_.emplace_back(kv.value().get<std::string>());
}
}
result.id_ = json.value("id", "");
result.kind_ = json.value("kind", "");
result.object_name_prefix_ = json.value("object_name_prefix", "");
result.payload_format_ = json.value("payload_format", "");
result.self_link_ = json.value("selfLink", "");
result.topic_ = json.value("topic", "");
return result;
}
StatusOr<NotificationMetadata> NotificationMetadataParser::FromString(
std::string const& payload) {
internal::nl::json json = internal::nl::json::parse(payload, nullptr, false);
return FromJson(json);
}
std::ostream& operator<<(std::ostream& os, ListNotificationsRequest const& r) {
os << "ListNotificationsRequest={bucket_name=" << r.bucket_name();
r.DumpOptions(os, ", ");
return os << "}";
}
StatusOr<ListNotificationsResponse> ListNotificationsResponse::FromHttpResponse(
std::string const& payload) {
auto json = nl::json::parse(payload, nullptr, false);
if (!json.is_object()) {
return Status(StatusCode::kInvalidArgument, __func__);
}
ListNotificationsResponse result;
for (auto const& kv : json["items"].items()) {
auto parsed = internal::NotificationMetadataParser::FromJson(kv.value());
if (!parsed.ok()) {
return std::move(parsed).status();
}
result.items.emplace_back(std::move(*parsed));
}
return result;
}
std::ostream& operator<<(std::ostream& os, ListNotificationsResponse const& r) {
os << "ListNotificationResponse={items={";
char const* sep = "";
for (auto const& acl : r.items) {
os << sep << acl;
sep = ", ";
}
return os << "}}";
}
std::ostream& operator<<(std::ostream& os, CreateNotificationRequest const& r) {
os << "CreateNotificationRequest={bucket_name=" << r.bucket_name()
<< ", json_payload=" << r.json_payload();
r.DumpOptions(os, ", ");
return os << "}";
}
std::ostream& operator<<(std::ostream& os, GetNotificationRequest const& r) {
os << "GetNotificationRequest={bucket_name=" << r.bucket_name()
<< ", notification_id" << r.notification_id();
r.DumpOptions(os, ", ");
return os << "}";
}
std::ostream& operator<<(std::ostream& os, DeleteNotificationRequest const& r) {
os << "DeleteNotificationRequest={bucket_name=" << r.bucket_name()
<< ", notification_id" << r.notification_id();
r.DumpOptions(os, ", ");
return os << "}";
}
} // namespace internal
} // namespace STORAGE_CLIENT_NS
} // namespace storage
} // namespace cloud
} // namespace google
|
/*
* @PLUGIN_CLASS@.cpp
*
* Created on: Jan 8, 2018
*
* Copyright (C) 2018 Pat Deegan, https://psychogenic.com
*
* This file is a supporting component of the
* Coraline [https://coraline.psychogenic.com/] plugin
* skeleton/code generator [https://github.com/psychogenic/coraline-dev-plugin]
*
* It is released under the terms and conditions of the
* Apache License, v2.0. See the included LICENSE file
* for details.
*
*/
#include "@PLUGIN_CLASS@_plugin.h"
@PLUGIN_CLASS@::@PLUGIN_CLASS@(const Coraline::Plugin::Context& ctx)
: Coraline::Plugin::Base(ctx)
{
/*
* plugin instantiation
* Setup instance variables, etc, but wait until
* startUp() to interact with the system (e.g. open file handles).
*
*/
}
/*
* startUp -- perform any required initialization here,
* like opening file handles, databases, sockets whatever.
*
* JS may also be executed here, if required.
*
*/
void @PLUGIN_CLASS@::startUp() {
// nothing to do, as of yet.
}
/*
* update() -- will be ticked periodically
* during operation. May be overridden if required but,
* if you're using the UpdateAction/queueAction() methods,
* you need to call the parent class update() to ensure
* they actually get processed.
*/
// void @PLUGIN_CLASS@::update() {
// this->Coraline::Plugin::Base::update();
// }
/*
* shutdown()
* Perform clean-up before shutting down.
* Close database handles, flush files, etc.
*/
void @PLUGIN_CLASS@::shutdown() {
// nothing to do, yet.
}
/*
* clientSideSupportFile()
* Return the name of a file to load that is to be injected
* into the JS engine on plugin instantiation, e.g. "init.js"
*
* This file must reside in the plugin's resource directory,
* which is determined using its shortName(). E.g. for
* the "BLE" (shortName) plugin, this would be a file
* at /usr/local/share/coraline/plugin-resources/BLE/init.js
*
* NOTE: if you use clientSideSupport* methods, at this time the system
* expects to be able to construct a suitable object using the shortName()
* on the JS side. So if you had a shortName of "SuperDuper", it'll try
* and construct a "new SuperDuper()" at some point.
*
* See the provided example init.js
*
*/
Coraline::Plugin::ClientCodeFileName @PLUGIN_CLASS@::clientSideSupportFile() {
return Coraline::Plugin::ClientCodeFileName("init.js");
}
/*
* clientSideSupport()
* Return as string of JS to run on instantiation, e.g.
* "function Booya() {}; window.booya = new Booya();" or whatever.
*
*
* NOTE: if you use clientSideSupport* methods, at this time the system
* expects to be able to construct a suitable object using the shortName()
* on the JS side. So if you had a shortName of "SuperDuper", it'll try
* and construct a "new SuperDuper()" at some point.
*
*/
//Coraline::Plugin::ClientCode @PLUGIN_CLASS@::clientSideSupport() {
// }
Coraline::Plugin::AboutString @PLUGIN_CLASS@::about() {
return Coraline::Plugin::AboutString(
"@PLUGIN_CLASS@ is awesome, and copyright (C) 2018 Pat Deegan");
}
Coraline::Plugin::AboutString @PLUGIN_CLASS@::usage() {
return Coraline::Plugin::AboutString(
"To use @PLUGIN_CLASS@, simply call ");
}
Coraline::Version @PLUGIN_CLASS@::version() {
Coraline::Version pVersion(
@PLUGIN_CLASS_ASUPPER@_VERSION_MAJOR,
@PLUGIN_CLASS_ASUPPER@_VERSION_MINOR,
@PLUGIN_CLASS_ASUPPER@_VERSION_PATCH);
return pVersion;
}
/*
* registerAllMethods()
* Plugin::Base utility method--just list every callback (i.e. methods with the
* correct signature) you wish to make publically visible.
*
* Easiest way: use the PLUGINREGMETH() macro.
*/
void @PLUGIN_CLASS@::registerAllMethods() {
PLUGINREGMETH(hello);
}
bool @PLUGIN_CLASS@::hello(const Coraline::Plugin::StandardCallbackIDs & callbacks,
const Coraline::Plugin::ArgsList & args) {
/*
* sample plugin callback. This may be triggered by the client app.
* Our job:
* - do whatever we promised we would
* - eventually trigger one of the JS-side callbacks
*
* Triggering the JS callbacks all comes down to calling
* - triggerCallback (for one-off callbacks) OR
* - triggerCallbackNoRemove (for callbacks that need to stay around, e.g. for on-going
* notifications)
*
* Either of these may be called with just a CallbackID (found in the
* callbacks.success or callbacks.error passed into this method), and may accept
* a second argument (a json object to hold whatever you want).
*
* There are reportSuccess/reportError convenience methods available
* to simplify calling triggerCallback() with the appropriate id.
*
*/
// we'll queue a 'success' response.
// by using queueAction, we know our lambda will be executed
// when we're given a little time, down the line, during the update call
// (handled by base class).
queueAction([this, callbacks](){
json respObj; // whatever
respObj["success"] = true;
respObj["message"] = "helloooooo";
reportSuccess(callbacks, respObj);
});
// everything's gonna work out, return true.
return true;
}
|
////////////////////////////////////////////////////////////////
//
// Interrupt descriptor table low-level operations
//
// File: idt.hpp
// Date: 08 Feb 2021
//
// Copyright (c) 2017 - 2021, Igor Baklykov
// All rights reserved.
//
//
#pragma once
#include <cstdint>
#include <array>
#include <type_traits>
#include <arch/i386/types.hpp>
#include <arch/i386/irq.hpp>
#include <arch/i386/exceptions.hpp>
// i386 namespace
namespace igros::i386 {
#pragma pack(push, 1)
// IDT entry
struct idtEntryi386_t {
word_t offsetLow; // Offset lower part (0..15)
word_t selector; // Selectod from GDT/LDT
byte_t reserved; // Must be zero
byte_t type; // Type attributes
word_t offsetHigh; // Offset higher part (16..31)
};
// IDT pointer
struct idtPointeri386_t {
word_t size; // IDT size
const idtEntryi386_t* pointer; // IDT pointer
};
#pragma pack(pop)
} // namespace igros::i386
#ifdef __cplusplus
extern "C" {
#endif // __cplusplus
// Load IDT
inline void idtLoad(const igros::i386::idtPointeri386_t* const idtPtr) noexcept;
// Store IDT
inline const igros::i386::idtPointeri386_t* idtStore() noexcept;
#ifdef __cplusplus
}
#endif // __cplusplus
// i386 namespace
namespace igros::i386 {
// IDT structure
class idt final {
// IDT ISR pointer
using isrPointeri386_t = std::add_pointer_t<void()>;
// Number of IDT entries
constexpr static auto IDT_SIZE = 256ULL;
// Exceptions and IRQ descriptors table (IDT)
static std::array<idtEntryi386_t, IDT_SIZE> table;
// Pointer to IDT
static idtPointeri386_t pointer;
// Copy c-tor
idt(const idt &other) = delete;
// Copy assignment
idt& operator=(const idt &other) = delete;
// Move c-tor
idt(idt &&other) = delete;
// Move assignment
idt& operator=(idt &&other) = delete;
public:
// Default c-tor
idt() noexcept = default;
// Set IDT entry
static idtEntryi386_t setEntry(const isrPointeri386_t offset, const word_t selector, const byte_t type) noexcept;
// Calc IDT size
[[nodiscard]]
constexpr static word_t calcSize() noexcept;
// Init IDT table
static void init() noexcept;
};
// Set IDT entry
inline idtEntryi386_t idt::setEntry(const isrPointeri386_t offset, const word_t selector, const byte_t type) noexcept {
return {
.offsetLow = static_cast<word_t>(reinterpret_cast<std::uintptr_t>(offset) & 0xFFFF),
.selector = selector,
.reserved = 0x00,
.type = type,
.offsetHigh = static_cast<word_t>((reinterpret_cast<std::uintptr_t>(offset) >> 16) & 0xFFFF)
};
}
// Calculate IDT size
constexpr word_t idt::calcSize() noexcept {
return (IDT_SIZE * sizeof(idtEntryi386_t)) - 1U;
}
// Init IDT table
inline void idt::init() noexcept {
// Exceptions setup
table[0] = idt::setEntry(::exHandler00, 0x08, 0x8E);
table[1] = idt::setEntry(::exHandler01, 0x08, 0x8E);
table[2] = idt::setEntry(::exHandler02, 0x08, 0x8E);
table[3] = idt::setEntry(::exHandler03, 0x08, 0x8E);
table[4] = idt::setEntry(::exHandler04, 0x08, 0x8E);
table[5] = idt::setEntry(::exHandler05, 0x08, 0x8E);
table[6] = idt::setEntry(::exHandler06, 0x08, 0x8E);
table[7] = idt::setEntry(::exHandler07, 0x08, 0x8E);
table[8] = idt::setEntry(::exHandler08, 0x08, 0x8E);
table[9] = idt::setEntry(::exHandler09, 0x08, 0x8E);
table[10] = idt::setEntry(::exHandler0A, 0x08, 0x8E);
table[11] = idt::setEntry(::exHandler0B, 0x08, 0x8E);
table[12] = idt::setEntry(::exHandler0C, 0x08, 0x8E);
table[13] = idt::setEntry(::exHandler0D, 0x08, 0x8E);
table[14] = idt::setEntry(::exHandler0E, 0x08, 0x8E);
table[15] = idt::setEntry(::exHandler0F, 0x08, 0x8E);
table[16] = idt::setEntry(::exHandler10, 0x08, 0x8E);
table[17] = idt::setEntry(::exHandler11, 0x08, 0x8E);
table[18] = idt::setEntry(::exHandler12, 0x08, 0x8E);
table[19] = idt::setEntry(::exHandler13, 0x08, 0x8E);
table[20] = idt::setEntry(::exHandler14, 0x08, 0x8E);
table[21] = idt::setEntry(::exHandler15, 0x08, 0x8E);
table[22] = idt::setEntry(::exHandler16, 0x08, 0x8E);
table[23] = idt::setEntry(::exHandler17, 0x08, 0x8E);
table[24] = idt::setEntry(::exHandler18, 0x08, 0x8E);
table[25] = idt::setEntry(::exHandler19, 0x08, 0x8E);
table[26] = idt::setEntry(::exHandler1A, 0x08, 0x8E);
table[27] = idt::setEntry(::exHandler1B, 0x08, 0x8E);
table[28] = idt::setEntry(::exHandler1C, 0x08, 0x8E);
table[29] = idt::setEntry(::exHandler1D, 0x08, 0x8E);
table[30] = idt::setEntry(::exHandler1E, 0x08, 0x8E);
table[31] = idt::setEntry(::exHandler1F, 0x08, 0x8E);
// IRQs setup
table[32] = idt::setEntry(::irqHandler0, 0x08, 0x8E);
table[33] = idt::setEntry(::irqHandler1, 0x08, 0x8E);
table[34] = idt::setEntry(::irqHandler2, 0x08, 0x8E);
table[35] = idt::setEntry(::irqHandler3, 0x08, 0x8E);
table[36] = idt::setEntry(::irqHandler4, 0x08, 0x8E);
table[37] = idt::setEntry(::irqHandler5, 0x08, 0x8E);
table[38] = idt::setEntry(::irqHandler6, 0x08, 0x8E);
table[39] = idt::setEntry(::irqHandler7, 0x08, 0x8E);
table[40] = idt::setEntry(::irqHandler8, 0x08, 0x8E);
table[41] = idt::setEntry(::irqHandler9, 0x08, 0x8E);
table[42] = idt::setEntry(::irqHandlerA, 0x08, 0x8E);
table[43] = idt::setEntry(::irqHandlerB, 0x08, 0x8E);
table[44] = idt::setEntry(::irqHandlerC, 0x08, 0x8E);
table[45] = idt::setEntry(::irqHandlerD, 0x08, 0x8E);
table[46] = idt::setEntry(::irqHandlerE, 0x08, 0x8E);
table[47] = idt::setEntry(::irqHandlerF, 0x08, 0x8E);
// Load new IDT
::idtLoad(&pointer);
}
} // namespace igros::i386
|
/* This testcase is part of GDB, the GNU debugger.
Copyright 1998, 1999, 2004, 2006, 2007, 2008, 2009, 2010, 2011
Free Software Foundation, Inc.
This program is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
extern "C" {
#include <stdio.h>
}
class A {
public:
A();
int foo (int x);
int bar (int y);
virtual int baz (int z);
char c;
int j;
int jj;
static int s;
};
class B {
public:
static int s;
};
int A::s = 10;
int B::s = 20;
A::A()
{
c = 'x';
j = 5;
}
int A::foo (int dummy)
{
j += 3;
return j + dummy;
}
int A::bar (int dummy)
{
int r;
j += 13;
r = this->foo(15);
return r + j + 2 * dummy;
}
int A::baz (int dummy)
{
int r;
j += 15;
r = this->foo(15);
return r + j + 12 * dummy;
}
int fum (int dummy)
{
return 2 + 13 * dummy;
}
typedef int (A::*PMF)(int);
typedef int A::*PMI;
/* This class is in front of the other base classes of Diamond, so
that we can detect if the offset for Left or the first Base is
added twice - otherwise it would be 2 * 0 == 0. */
class Padding
{
public:
int spacer;
virtual int vspacer();
};
int Padding::vspacer()
{
return this->spacer;
}
class Base
{
public:
int x;
int get_x();
virtual int vget_base ();
};
int Base::get_x ()
{
return this->x;
}
int Base::vget_base ()
{
return this->x + 1000;
}
class Left : public Base {
public:
virtual int vget ();
};
int Left::vget ()
{
return this->x + 100;
}
class Right : public Base {
public:
virtual int vget ();
};
int Right::vget ()
{
return this->x + 200;
}
class Diamond : public Padding, public Left, public Right
{
public:
virtual int vget_base ();
};
int Diamond::vget_base ()
{
return this->Left::x + 2000;
}
int main ()
{
A a;
A * a_p;
PMF pmf;
PMF * pmf_p;
PMI pmi;
Diamond diamond;
int (Diamond::*left_pmf) ();
int (Diamond::*right_pmf) ();
int (Diamond::*left_vpmf) ();
int (Diamond::*left_base_vpmf) ();
int (Diamond::*right_vpmf) ();
int (Base::*base_vpmf) ();
int Diamond::*diamond_pmi;
PMI null_pmi;
PMF null_pmf;
a.j = 121;
a.jj = 1331;
int k;
a_p = &a;
pmi = &A::j;
pmf = &A::bar;
pmf_p = &pmf;
diamond.Left::x = 77;
diamond.Right::x = 88;
/* Some valid pointer to members from a base class. */
left_pmf = (int (Diamond::*) ()) (int (Left::*) ()) (&Base::get_x);
right_pmf = (int (Diamond::*) ()) (int (Right::*) ()) (&Base::get_x);
left_vpmf = &Left::vget;
left_base_vpmf = (int (Diamond::*) ()) (int (Left::*) ()) (&Base::vget_base);
right_vpmf = &Right::vget;
/* An unspecified, value preserving pointer to member cast. */
base_vpmf = (int (Base::*) ()) (int (Left::*) ()) &Diamond::vget_base;
/* A pointer to data member from a base class. */
diamond_pmi = (int Diamond::*) (int Left::*) &Base::x;
null_pmi = NULL;
null_pmf = NULL;
pmi = NULL; /* Breakpoint 1 here. */
k = (a.*pmf)(3);
pmi = &A::jj;
pmf = &A::foo;
pmf_p = &pmf;
k = (a.*pmf)(4);
k = (a.**pmf_p)(5);
k = a.*pmi;
k = a.bar(2);
k += fum (4);
B b;
k += b.s;
}
|
/*
tinyTLS project
Copyright 2015 Nesterov A.
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.
*/
/* MASTER.CPP
* Implementation of TLS 1.0 (RFC 2246) Pseudo-Random-Function.
* This function is used to compute master secret, key material and
* verification values for finished messages
*/
#include <string.h>
#include "hash/hash.h"
//#define TEST_MODULE
/* From RFC 2246
TLS 1.0 PRF computation
PRF(secret, label, seed) = P_MD5(S1, label + seed) ^ P_SHA-1(S2, label + seed);
L_S = length in bytes of secret;
L_S1 = L_S2 = ceil(L_S / 2);
S1 = secret[0 .. L_s1 - 1];
S2 = secret[L_S - L_S2 .. L_S - 1];
P_hash(secret, seed) = HMAC_hash(secret, A(1) + seed) +
HMAC_hash(secret, A(2) + seed) +
HMAC_hash(secret, A(3) + seed) + ...
A() is defined as:
A(0) = seed
A(i) = HMAC_hash(secret, A(i-1))
*/
void PrfGenerateBlock_v1_0(unsigned char * output, unsigned int outLen, const unsigned char * secret, unsigned sectretLen, const char * label, const unsigned char * seed, unsigned int seedLen)
{
unsigned labelLen = strlen(label);
unsigned ls2 = (sectretLen + 1) >> 1;
// first part MD5
{
const unsigned char * const secret_begin = secret;
unsigned int secretKey[16];
if (sizeof(secretKey) >= ls2) {
memset(secretKey, 0, sizeof(secretKey));
memcpy(secretKey, secret_begin, ls2);
} else {
//### calculate md5 for hash
// for now - it's bad condition
// TLS never uses keys longer than 24 bytes
return;
}
unsigned int A[4];
unsigned int R[4];
unsigned char * outPos = output;
unsigned int outRem = outLen;
// calculate A1
HMACMD5_State P_Md5;
HmacMd5_Init(&P_Md5, secretKey);
HmacMd5_Update(&P_Md5, (const uint8_t*)label, labelLen);
HmacMd5_Update(&P_Md5, (const uint8_t*)seed, seedLen);
HmacMd5_Finish(&P_Md5, A);
goto after_a1_md5;
do {
// calculate AN
HmacMd5(A, secretKey, (const uint8_t*)A, sizeof(A));
after_a1_md5:
//### clone the decoder state
// calculate HMAC
HmacMd5_Init(&P_Md5, secretKey);
HmacMd5_Update(&P_Md5, (const uint8_t*)A, sizeof(A));
HmacMd5_Update(&P_Md5, (const uint8_t*)label, labelLen);
HmacMd5_Update(&P_Md5, (const uint8_t*)seed, seedLen);
HmacMd5_Finish(&P_Md5, R);
if (outRem >= sizeof(R)) {
memcpy(outPos, R, sizeof(R));
outRem -= sizeof(R);
outPos += sizeof(R);
} else {
memcpy(outPos, R, outRem);
outRem = 0;
}
} while(outRem > 0);
}
// second part SHA1
{
const unsigned char * const secret_begin = secret;
unsigned int secretKey[16];
if (sizeof(secretKey) >= ls2) {
memset(secretKey, 0, sizeof(secretKey));
memcpy(secretKey, secret_begin + (sectretLen - ls2), ls2);
} else {
//### calculate sha1 for hash
// for now - it's bad condition
// TLS never uses keys longer than 24 bytes
return;
}
unsigned int A[5];
unsigned int R[5];
unsigned char * outPos = output;
unsigned int outRem = outLen;
// calculate A1
HMACSHA1_State P_Sha1;
HmacSha1_Init(&P_Sha1, secretKey);
HmacSha1_Update(&P_Sha1, (const uint8_t*)label, labelLen);
HmacSha1_Update(&P_Sha1, (const uint8_t*)seed, seedLen);
HmacSha1_Finish(&P_Sha1, A);
goto after_a1_sha1;
do {
// calculate AN
HmacSha1(A, secretKey, (const uint8_t*)A, sizeof(A));
after_a1_sha1:
//### clone the decoder state
// calculate HMAC
HmacSha1_Init(&P_Sha1, secretKey);
HmacSha1_Update(&P_Sha1, (const uint8_t*)A, sizeof(A));
HmacSha1_Update(&P_Sha1, (const uint8_t*)label, labelLen);
HmacSha1_Update(&P_Sha1, (const uint8_t*)seed, seedLen);
HmacSha1_Finish(&P_Sha1, R);
{ // a bit more complicated as we need to XOR results
unsigned l = (outRem >= sizeof(R)) ? sizeof(R) : outRem;
outRem -= l;
unsigned char * rPos = (unsigned char *)R;
for(; l > 0; --l)
{
*outPos++ ^= *rPos++;
}
}
} while(outRem > 0);
}
}
//master_secret = PRF(pre_master_secret, "master secret", ClientHello.random + ServerHello.random)[0..47];
//
//key_block = PRF(SecurityParameters.master_secret, "key expansion", SecurityParameters.server_random + SecurityParameters.client_random);
//
//finished_label =
// For Finished messages sent by the client, the string "client finished".
// For Finished messages sent by the server, the string "server finished".
//verify_data = PRF(master_secret, finished_label, MD5(handshake_messages) + SHA-1(handshake_messages))[0..11];
#ifdef TEST_MODULE
unsigned char pre_master_secret[48] = {
0xab, 0xab, 0xab, 0xab, 0xab, 0xab, 0xab, 0xab,
0xab, 0xab, 0xab, 0xab, 0xab, 0xab, 0xab, 0xab,
0xab, 0xab, 0xab, 0xab, 0xab, 0xab, 0xab, 0xab,
0xab, 0xab, 0xab, 0xab, 0xab, 0xab, 0xab, 0xab,
0xab, 0xab, 0xab, 0xab, 0xab, 0xab, 0xab, 0xab,
0xab, 0xab, 0xab, 0xab, 0xab, 0xab, 0xab, 0xab
};
unsigned char test_seed[64] = {
0xcd, 0xcd, 0xcd, 0xcd, 0xcd, 0xcd, 0xcd, 0xcd,
0xcd, 0xcd, 0xcd, 0xcd, 0xcd, 0xcd, 0xcd, 0xcd,
0xcd, 0xcd, 0xcd, 0xcd, 0xcd, 0xcd, 0xcd, 0xcd,
0xcd, 0xcd, 0xcd, 0xcd, 0xcd, 0xcd, 0xcd, 0xcd,
0xcd, 0xcd, 0xcd, 0xcd, 0xcd, 0xcd, 0xcd, 0xcd,
0xcd, 0xcd, 0xcd, 0xcd, 0xcd, 0xcd, 0xcd, 0xcd,
0xcd, 0xcd, 0xcd, 0xcd, 0xcd, 0xcd, 0xcd, 0xcd,
0xcd, 0xcd, 0xcd, 0xcd, 0xcd, 0xcd, 0xcd, 0xcd
};
unsigned char verify_master_secret[104] = {
0xD3, 0xD4, 0xD1, 0xE3, 0x49, 0xB5, 0xD5, 0x15, 0x04, 0x46, 0x66, 0xD5, 0x1D, 0xE3, 0x2B, 0xAB,
0x25, 0x8C, 0xB5, 0x21, 0xB6, 0xB0, 0x53, 0x46, 0x3E, 0x35, 0x48, 0x32, 0xFD, 0x97, 0x67, 0x54,
0x44, 0x3B, 0xCF, 0x9A, 0x29, 0x65, 0x19, 0xBC, 0x28, 0x9A, 0xBC, 0xBC, 0x11, 0x87, 0xE4, 0xEB,
0xD3, 0x1E, 0x60, 0x23, 0x53, 0x77, 0x6C, 0x40, 0x8A, 0xAF, 0xB7, 0x4C, 0xBC, 0x85, 0xEF, 0xF6,
0x92, 0x55, 0xF9, 0x78, 0x8F, 0xAA, 0x18, 0x4C, 0xBB, 0x95, 0x7A, 0x98, 0x19, 0xD8, 0x4A, 0x5D,
0x7E, 0xB0, 0x06, 0xEB, 0x45, 0x9D, 0x3A, 0xE8, 0xDE, 0x98, 0x10, 0x45, 0x4B, 0x8B, 0x2D, 0x8F,
0x1A, 0xFB, 0xC6, 0x55, 0xA8, 0xC9, 0xA0, 0x13,
};
extern void PrintHex(unsigned char *buf, unsigned int size, int shift);
void main()
{
unsigned char master_key[256];
PrfGenerateBlock_v1_0(master_key, 256, pre_master_secret, sizeof(pre_master_secret), "PRF Testvector", test_seed, sizeof(test_seed));
PrintHex(master_key, sizeof(master_key), 0);
for(unsigned int i = 0; i < sizeof(verify_master_secret); ++i)
master_key[i] -= verify_master_secret[i];
PrintHex(master_key, sizeof(master_key), 0);
}
#endif
|
/*
* 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.
*/
/*
* Copyright (c) 2018, Open AI Lab
* Author: haitao@openailab.com
*/
#ifndef __SOC_RUNNER_HPP__
#define __SOC_RUNNER_HPP__
#include <string>
#include <vector>
#include <functional>
#include "node_ops.hpp"
namespace TEngine {
class Graph;
using Subgraph=Graph;
struct CPUInfo {
std::string cpu_type;
std::string cpu_arch;
int cpu_id;
int l1_size;
int l2_slice;
};
struct SocInfo {
int cpu_number;
int master_cpu;
std::vector<int> cpu_list;
std::string soc_name;
std::vector<CPUInfo> cpu_info;
int l3_size;
void SetWorkingCPU(const std::vector<int>& new_cpu_list, int master)
{
master_cpu=master_cpu;
cpu_list=new_cpu_list;
cpu_number=cpu_list.size();
}
};
bool GetPredefinedSoc(const std::string& soc_name, SocInfo& soc_info);
bool RegisterPredefinedSoc(const std::string& soc_name, const SocInfo& soc_info);
class SocRunner {
public:
const std::string& GetSocName() {return soc_info.soc_name;}
const SocInfo& GetSocInfo(void) {return soc_info;}
void SetSocInfo(const SocInfo& info) {soc_info=info;}
virtual bool Init(void)=0;
virtual void Release(void)=0;
virtual void * CreateGraphHandle(Subgraph * sub_graph)=0;
virtual bool OptimizeGraph(void * graph_handle)=0;
virtual bool Prerun(void * graph_handle)=0;
virtual bool Run(void * graph_handle)=0; //always block interface
virtual bool Postrun(void * graph_handle)=0;
virtual void ReleaseGraphHandle(void * graph_handle)=0;
virtual ~SocRunner(){}
protected:
SocInfo soc_info;
};
class CPURunner: public SocRunner {
public:
struct GraphContext {
Subgraph * orig_graph;
Subgraph * optimized_graph;
};
bool Init(void) override {return true;};
void Release(void) override {};
void * CreateGraphHandle(Subgraph * sub_graph) override;
void ReleaseGraphHandle(void * graph_handle) override;
bool Prerun(void * graph_handle) override;
bool Run(void * graph_handle) override;
bool Postrun(void * graph_handle) override;
bool SetWorkingCPU(const std::vector<int>& cpu_list, int master);
void SetHelper(const mem_alloc_t& alloc, const mem_free_t& free,
const task_dispatch_t& dispatch);
virtual bool OptimizeGraph(void * graph_handle) override;
virtual bool BindNodeOps(Subgraph * graph);
virtual bool AllocateMem(Subgraph * graph);
virtual ~CPURunner(){}
mem_alloc_t mem_alloc;
mem_free_t mem_free;
task_dispatch_t task_dispatch;
};
} //namespace TEngine
#endif
|
#include "Enemy.h"
#include "FieldNames.h"
REGISTER_FINISH(Enemy, ScriptBase) {}
void Enemy::OnDisabled()
{
if (_isInTube)
GetGameObject()->CallDestroy();
}
void Enemy::OnCollide(CollideEvent& e)
{
if (e.GetGameObject()->GetTag().Collide(_collideIgnore))
{
e.SetIsHandled(true);
}
}
void Enemy::Load(nlohmann::json& input)
{
_collideIgnore = input[Fields::Enemy::_ignore].empty() ? "" : Tag(input[Fields::Enemy::_ignore]);
}
void Enemy::SetIsInTube()
{
_isInTube = true;
}
ScriptBase* Enemy::Clone() const
{
auto clone = dynamic_cast<Enemy*>(ScriptBase::Clone());
clone->_collideIgnore = _collideIgnore;
clone->_isInTube = _isInTube;
return clone;
}
bool Enemy::IsInTube()
{
return _isInTube;
}
|
/*
Copyright (c) 2011, Siemens Corporate Research a Division of Siemens Corporation
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 "SoVtkVolume16Reader.h"
# include "SoVtkUtils.h"
# include "vtkTransform.h"
# include "vtkDataObject.h"
# include "vtkAlgorithmOutput.h"
# include "vtkImageData.h"
SO_ENGINE_SOURCE( SoVtkVolume16Reader )
SoVtkVolume16Reader::SoVtkVolume16Reader()
{
SO_ENGINE_CONSTRUCTOR(SoVtkVolume16Reader);
mObject = vtkVolume16Reader::New();
mObject->Register(0);mObject->SetGlobalWarningDisplay(0);
mObject->SetGlobalWarningDisplay(0);
vtkVolume16Reader *aVolume16Reader = vtkVolume16Reader::New();
double *x;
int *y;
SO_ENGINE_ADD_INPUT(DataSpacing, (0,0,0));
x= aVolume16Reader->GetDataSpacing();
DataSpacing.setValue(x[0],x[1],x[2]);
SO_ENGINE_ADD_INPUT(Transform, (0));
SO_ENGINE_ADD_INPUT(HeaderSize, (0));
HeaderSize.setValue(aVolume16Reader->GetHeaderSize());
SO_ENGINE_ADD_INPUT(DataDimensions, (0,0));
y= aVolume16Reader->GetDataDimensions();
DataDimensions.setValue((float) y[0],(float) y[1]);
SO_ENGINE_ADD_INPUT(FilePattern, (""));
SO_ENGINE_ADD_INPUT(FilePrefix, (""));
SO_ENGINE_ADD_INPUT(DataByteOrder, (0));
DataByteOrder.setValue(aVolume16Reader->GetDataByteOrder());
SO_ENGINE_ADD_INPUT(ImageRange, (0,0));
y= aVolume16Reader->GetImageRange();
ImageRange.setValue((float) y[0],(float) y[1]);
SO_ENGINE_ADD_INPUT(SwapBytes, (0));
SwapBytes.setValue(aVolume16Reader->GetSwapBytes());
SO_ENGINE_ADD_INPUT(DataOrigin, (0,0,0));
x= aVolume16Reader->GetDataOrigin();
DataOrigin.setValue(x[0],x[1],x[2]);
SO_ENGINE_ADD_INPUT(DataMask, (0));
DataMask.setValue(aVolume16Reader->GetDataMask());
SO_ENGINE_ADD_INPUT(InputArrayToProcess, ());
InputArrayToProcess.setFormat("int int int int char*");
SO_ENGINE_ADD_INPUT(Input, (0));
SO_ENGINE_ADD_INPUT(InputConnection, (0));
aVolume16Reader->Delete();
SO_ENGINE_ADD_OUTPUT( Output, SoSFVtkObject );
mOutput = 0;
SO_ENGINE_ADD_OUTPUT( OutputPort, SoSFVtkAlgorithmOutput );
mOutputPort = 0;
SO_ENGINE_ADD_OUTPUT(OutputDCO, SoSFVtkObject );
mOutputDCO = 0;
}
SoVtkVolume16Reader::~SoVtkVolume16Reader()
{
// Deletion of the objects if they exist
if ( mOutput )
{
mOutput->unref();
mOutput = 0;
}
if ( mOutputPort )
{
mOutputPort->unref();
mOutputPort = 0;
}
if ( mOutputDCO )
{
mOutputDCO->unref();
mOutputDCO = 0;
}
if ( mObject )
{
mObject->UnRegister(0);
mObject->Delete();
mObject = 0;
}
}
void SoVtkVolume16Reader::initClass()
{
SO_ENGINE_INIT_CLASS( SoVtkVolume16Reader, SoEngine, "Engine" );
}
void SoVtkVolume16Reader::evaluate()
{
try
{
// Deletion of the objects if they exist
if ( mOutput )
{
mOutput->unref();
mOutput = 0;
}
if ( mOutputPort )
{
mOutputPort->unref();
mOutputPort = 0;
}
if ( mOutputDCO )
{
mOutputDCO->unref();
mOutputDCO = 0;
}
// Get the input type(s)
SoVtkObject *inputPtr = Input.getValue();
if (inputPtr && inputPtr->getPointer()->IsA("vtkDataObject"))
mObject->SetInput(vtkDataObject::SafeDownCast(inputPtr->getPointer()));
SoVtkAlgorithmOutput *inputPortPtr = InputConnection.getValue();
if (inputPortPtr)
mObject->SetInputConnection(inputPortPtr->getPointer());
mOutputDCO = new SoVtkObject();
mOutputDCO->ref();
mOutputDCO->setPointer( mObject );
mObject->GetOutput()->Register(0);
mOutput = new SoVtkObject();
mOutput->ref();
mOutput->setPointer( mObject->GetOutput() );
if ( mObject->GetNumberOfOutputPorts() > 0 )
{
mObject->GetOutputPort()->Register(0);
mOutputPort = new SoVtkAlgorithmOutput();
mOutputPort->ref();
mOutputPort->setPointer( mObject->GetOutputPort() );
}
}
catch(...)
{
SoDebugError::post( __FILE__, "Unknown Exception" );
return;
}
SO_ENGINE_OUTPUT( Output, SoSFVtkObject, setValue( mOutput ) );
SO_ENGINE_OUTPUT( OutputPort, SoSFVtkAlgorithmOutput, setValue( mOutputPort ) );
SO_ENGINE_OUTPUT( OutputDCO, SoSFVtkObject, setValue( mOutputDCO ) );
}
void SoVtkVolume16Reader::inputChanged(SoField * f)
{
// Get the DataSpacing value
if ( f == &DataSpacing )
SO_VTK_SET_FIELD_VEC3F( mObject, DataSpacing);
// Get the Transform value
if ( f == &Transform )
SO_VTK_SET_FIELD_DATA( mObject, Transform, vtkTransform);
// Get the HeaderSize value
if ( f == &HeaderSize )
SO_VTK_SET_FIELD_VALUE( mObject, HeaderSize);
// Get the DataDimensions value
if ( f == &DataDimensions )
SO_VTK_SET_FIELD_VEC2F( mObject, DataDimensions);
// Get the FilePattern value
if ( f == &FilePattern )
SO_VTK_SET_FIELD_MFSTRING( mObject, FilePattern);
// Get the FilePrefix value
if ( f == &FilePrefix )
SO_VTK_SET_FIELD_MFSTRING( mObject, FilePrefix);
// Get the DataByteOrder value
if ( f == &DataByteOrder )
SO_VTK_SET_FIELD_VALUE( mObject, DataByteOrder);
// Get the ImageRange value
if ( f == &ImageRange )
SO_VTK_SET_FIELD_VEC2F( mObject, ImageRange);
// Get the SwapBytes value
if ( f == &SwapBytes )
SO_VTK_SET_FIELD_VALUE( mObject, SwapBytes);
// Get the DataOrigin value
if ( f == &DataOrigin )
SO_VTK_SET_FIELD_VEC3F( mObject, DataOrigin);
// Get the DataMask value
if ( f == &DataMask )
SO_VTK_SET_FIELD_VALUE( mObject, DataMask);
// Get the InputArrayToProcess value
if ( f == &InputArrayToProcess )
{
SbVariant vInputArrayToProcess = (SbVariant)InputArrayToProcess.getValue();
SoInput input;
int val0;
int val1;
int val2;
int val3;
SbString val4;
input.setBuffer((void *)vInputArrayToProcess.getField().getString(),256);
input.read(val0);
input.read(val1);
input.read(val2);
input.read(val3);
input.read(val4);
mObject->SetInputArrayToProcess(
(int) val0,
(int) val1,
(int) val2,
(int) val3,
val4.getString()
);
}
//mObject->Update();
}
|
/*
* Copyright (c) 2015, Facebook, Inc.
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree. An additional grant
* of patent rights can be found in the PATENTS file in the same directory.
*
*/
#include <proxygen/lib/http/codec/SPDYUtil.h>
#include <folly/ThreadLocal.h>
#include <proxygen/lib/http/RFC2616.h>
namespace proxygen {
/**
* Tokens as defined by rfc 2616. Also lowercases them.
* token = 1*<any CHAR except CTLs or separators>
* separators = "(" | ")" | "<" | ">" | "@"
* | "," | ";" | ":" | "\" | <">
* | "/" | "[" | "]" | "?" | "="
* | "{" | "}" | SP | HT
*/
const char SPDYUtil::http_tokens[256] = {
/* 0 nul 1 soh 2 stx 3 etx 4 eot 5 enq 6 ack 7 bel */
0, 0, 0, 0, 0, 0, 0, 0,
/* 8 bs 9 ht 10 nl 11 vt 12 np 13 cr 14 so 15 si */
0, 0, 0, 0, 0, 0, 0, 0,
/* 16 dle 17 dc1 18 dc2 19 dc3 20 dc4 21 nak 22 syn 23 etb */
0, 0, 0, 0, 0, 0, 0, 0,
/* 24 can 25 em 26 sub 27 esc 28 fs 29 gs 30 rs 31 us */
0, 0, 0, 0, 0, 0, 0, 0,
/* 32 sp 33 ! 34 " 35 # 36 $ 37 % 38 & 39 ' */
' ', '!', '"', '#', '$', '%', '&', '\'',
/* 40 ( 41 ) 42 * 43 + 44 , 45 - 46 . 47 / */
0, 0, '*', '+', 0, '-', '.', '/',
/* 48 0 49 1 50 2 51 3 52 4 53 5 54 6 55 7 */
'0', '1', '2', '3', '4', '5', '6', '7',
/* 56 8 57 9 58 : 59 ; 60 < 61 = 62 > 63 ? */
'8', '9', 0, 0, 0, 0, 0, 0,
/* 64 @ 65 A 66 B 67 C 68 D 69 E 70 F 71 G */
0, 'a', 'b', 'c', 'd', 'e', 'f', 'g',
/* 72 H 73 I 74 J 75 K 76 L 77 M 78 N 79 O */
'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o',
/* 80 P 81 Q 82 R 83 S 84 T 85 U 86 V 87 W */
'p', 'q', 'r', 's', 't', 'u', 'v', 'w',
/* 88 X 89 Y 90 Z 91 [ 92 \ 93 ] 94 ^ 95 _ */
'x', 'y', 'z', 0, 0, 0, '^', '_',
/* 96 ` 97 a 98 b 99 c 100 d 101 e 102 f 103 g */
'`', 'a', 'b', 'c', 'd', 'e', 'f', 'g',
/* 104 h 105 i 106 j 107 k 108 l 109 m 110 n 111 o */
'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o',
/* 112 p 113 q 114 r 115 s 116 t 117 u 118 v 119 w */
'p', 'q', 'r', 's', 't', 'u', 'v', 'w',
/* 120 x 121 y 122 z 123 { 124 | 125 } 126 ~ 127 del */
'x', 'y', 'z', 0, '|', '}', '~', 0
};
bool SPDYUtil::hasGzipAndDeflate(const std::string& value, bool& hasGzip,
bool& hasDeflate) {
static folly::ThreadLocal<std::vector<RFC2616::TokenQPair>> output;
output->clear();
hasGzip = false;
hasDeflate = false;
RFC2616::parseQvalues(value, *output);
for (const auto& encodingQ: *output) {
std::string lower(std::move(encodingQ.first.str()));
std::transform(lower.begin(), lower.end(), lower.begin(), ::tolower);
// RFC says 3 sig figs
if (lower == "gzip" && encodingQ.second >= 0.001) {
hasGzip = true;
} else if (lower == "deflate" && encodingQ.second >= 0.001) {
hasDeflate = true;
}
}
return hasGzip && hasDeflate;
}
}
|
// Copyright (c) 2012 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "content/simple/simple_browser_main_parts.h"
#include "base/bind.h"
#include "base/command_line.h"
#include "base/files/file_path.h"
#include "base/message_loop.h"
#include "base/threading/thread.h"
#include "base/threading/thread_restrictions.h"
#include "cc/base/switches.h"
#include "content/public/common/content_switches.h"
#include "content/public/common/main_function_params.h"
#include "content/public/common/url_constants.h"
//#include "content/simple/shell.h"
#include "content/simple/simple_browser_context.h"
#include "content/simple/simple_web_contents_delegate.h"
#include "googleurl/src/gurl.h"
#include "grit/net_resources.h"
#include "net/base/net_module.h"
#include "net/base/net_util.h"
#include "ui/base/resource/resource_bundle.h"
#include "stdafx.h"
#include "resource.h"
#include "MainFrm.h"
//CAppModule _Module;
namespace content {
SimpleBrowserMainParts::SimpleBrowserMainParts(const MainFunctionParams& parameters)
: BrowserMainParts(), parameters_(parameters), run_message_loop_(true){
}
SimpleBrowserMainParts::~SimpleBrowserMainParts() {
}
void SimpleBrowserMainParts::PreMainMessageLoopRun() {
browser_context_.reset(new SimpleBrowserContext(false));
off_the_record_browser_context_.reset(new SimpleBrowserContext(true));
main_ui_.reset(new CMainFrame);
main_ui_->m_browser_main = this;
main_ui_->CreateEx();
main_ui_->ShowWindow(SW_SHOWDEFAULT);
//SimpleWebContentsDelegate::Initialize();
//SimpleWebContentsDelegate::CreateNewWindow(browser_context_.get(), GURL("http://www.baidu.com/"), NULL, MSG_ROUTING_NONE, gfx::Size());
if (parameters_.ui_task)
{
parameters_.ui_task->Run();
delete parameters_.ui_task;
run_message_loop_ = false;
}
}
} // namespace
|
/* Copyright 2019 École Polytechnique Fédérale de Lausanne. 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 "results_index.h"
#include "tensorflow/contrib/persona/kernels/object-pool/ref_pool_op.h"
namespace tensorflow{
using namespace std;
void ResultsIndex::reserve(size_t expected) {
if (fast_results_.capacity() < expected) {
fast_results_.reserve(expected);
}
}
void ResultsIndex::reset() {
fast_results_.clear();
current_result_ = 0;
}
void ResultsIndex::emplace_back(FastResult &&fr) {
fast_results_.emplace_back(move(fr));
}
void ResultsIndex::emplace_back(const Position &p) {
emplace_back(move(FastResult(p.ref_index(), p.position())));
}
size_t ResultsIndex::size() const noexcept {
return fast_results_.size();
}
const FastResult & ResultsIndex::current_position() const {
DCHECK_LT(current_result_, fast_results_.size());
return fast_results_[current_result_];
}
const FastResult * ResultsIndex::unsafe_current_position() const {
DCHECK_LT(current_result_, fast_results_.size());
return &fast_results_[current_result_];
}
bool ResultsIndex::advance() {
if (current_result_ == fast_results_.size() - 1) {
return false;
}
DCHECK_LT(current_result_, fast_results_.size() - 1); // we're using == for speed
current_result_++;
return true;
}
class ResultsIndexPoolOp : public ReferencePoolOp<ResultsIndex, ResultsIndex> {
public:
ResultsIndexPoolOp(OpKernelConstruction* ctx) : ReferencePoolOp<ResultsIndex, ResultsIndex>(ctx) {
}
protected:
unique_ptr<ResultsIndex> CreateObject() override {
return unique_ptr<ResultsIndex>(new ResultsIndex());
}
private:
TF_DISALLOW_COPY_AND_ASSIGN(ResultsIndexPoolOp);
};
REGISTER_KERNEL_BUILDER(Name("ResultsIndexPool").Device(DEVICE_CPU), ResultsIndexPoolOp);
}
|
// Copyright Aleksey Gurtovoy 2000-2004
//
// Distributed under the Boost Software License, Version 1.0.
// (See accompanying file LICENSE_1_0.txt or copy at
// http://www.boost.org/LICENSE_1_0.txt)
//
// Preprocessed version of "boost/mpl/or.hpp" header
// -- DO NOT modify by hand!
namespace bx { namespace mpl {
namespace aux {
template< bool C_, typename T1, typename T2, typename T3, typename T4 >
struct or_impl
: true_
{
};
template< typename T1, typename T2, typename T3, typename T4 >
struct or_impl< false,T1,T2,T3,T4 >
: or_impl<
BOOST_MPL_AUX_NESTED_TYPE_WKND(T1)::value
, T2, T3, T4
, false_
>
{
};
template<>
struct or_impl<
false
, false_, false_, false_, false_
>
: false_
{
};
} // namespace aux
template<
typename BOOST_MPL_AUX_NA_PARAM(T1)
, typename BOOST_MPL_AUX_NA_PARAM(T2)
, typename T3 = false_, typename T4 = false_, typename T5 = false_
>
struct or_
: aux::or_impl<
BOOST_MPL_AUX_NESTED_TYPE_WKND(T1)::value
, T2, T3, T4, T5
>
{
BOOST_MPL_AUX_LAMBDA_SUPPORT(
5
, or_
, ( T1, T2, T3, T4, T5)
)
};
BOOST_MPL_AUX_NA_SPEC2(
2
, 5
, or_
)
}}
|
// Copyright (c) 2017 Ollix. 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.
//
// ---
// Author: olliwang@ollix.com (Olli Wang)
#include <cassert>
#include <vector>
#include "jni.h"
#include "moui/moui.h"
extern "C" {
JNIEXPORT bool
JNICALL
Java_com_ollix_moui_View_drawFrameFromJNI(
JNIEnv* env, jobject, jlong moui_view_ptr) {
auto view = reinterpret_cast<moui::View*>(moui_view_ptr);
return view->Render();
}
// Handles the event in moui view.
JNIEXPORT void
JNICALL
Java_com_ollix_moui_View_handleEventFromJNI(
JNIEnv* env, jobject, jlong moui_view_ptr, jint action,
jfloatArray raw_locations) {
// Converts the received MotionEvent action to moui event type.
moui::Event::Type event_type;
switch (action) {
case 0x00000003: // MotionEvent.ACTION_CANCEL
event_type = moui::Event::Type::kCancel; break;
case 0x00000000: // MotionEvent.ACTION_DOWN
event_type = moui::Event::Type::kDown; break;
case 0x00000002: // MotionEvent.ACTION_MOVE
event_type = moui::Event::Type::kMove; break;
case 0x00000001: // MotionEvent.ACTION_UP
event_type = moui::Event::Type::kUp; break;
default:
event_type = moui::Event::Type::kUnknown;
}
// Initializes the event object and asks moui view to handle the event.
moui::Event moui_event(event_type);
const int kNumberOfLocations = \
static_cast<int>(env->GetArrayLength(raw_locations)) / 2;
jfloat* locations = env->GetFloatArrayElements(raw_locations, 0);
for (int i = 0; i < kNumberOfLocations; ++i) {
moui_event.locations()->push_back({*locations++, *locations++});
}
auto moui_view = reinterpret_cast<moui::View*>(moui_view_ptr);
moui_view->HandleEvent(&moui_event);
}
JNIEXPORT void
JNICALL
Java_com_ollix_moui_View_onSurfaceDestroyedFromJNI(
JNIEnv* env, jobject, jlong moui_view_ptr) {
auto view = reinterpret_cast<moui::View*>(moui_view_ptr);
view->OnSurfaceDestroyed();
}
// Asks moui view if the event should be handled.
JNIEXPORT jboolean
JNICALL
Java_com_ollix_moui_View_shouldHandleEventFromJNI(
JNIEnv* env, jobject, jlong moui_view_ptr, jfloat x, jfloat y) {
auto view = reinterpret_cast<moui::View*>(moui_view_ptr);
return view->ShouldHandleEvent({x, y});
}
} // extern "C"
|
/*
console.cpp
Console functions
*/
/*
Copyright © 2010 Far Group
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 name of the authors may not be used to endorse or promote products
derived from this software without specific prior written permission.
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.
*/
// BUGBUG
#include "platform.headers.hpp"
// Self:
#include "console.hpp"
// Internal:
#include "imports.hpp"
#include "colormix.hpp"
#include "interf.hpp"
#include "strmix.hpp"
#include "exception.hpp"
#include "palette.hpp"
#include "encoding.hpp"
#include "char_width.hpp"
// Platform:
#include "platform.version.hpp"
// Common:
#include "common.hpp"
#include "common/2d/algorithm.hpp"
#include "common/algorithm.hpp"
#include "common/enum_substrings.hpp"
#include "common/function_traits.hpp"
#include "common/io.hpp"
#include "common/range.hpp"
#include "common/scope_exit.hpp"
#include "common/view/enumerate.hpp"
// External:
#include "format.hpp"
//----------------------------------------------------------------------------
static bool sWindowMode;
static bool sEnableVirtualTerminal;
constexpr auto bad_char_replacement = L' ';
wchar_t ReplaceControlCharacter(wchar_t const Char)
{
switch (Char)
{
// C0
case 0x00: return L' '; // space
case 0x01: return L'☺'; // white smiling face
case 0x02: return L'☻'; // black smiling face
case 0x03: return L'♥'; // black heart suit
case 0x04: return L'♦'; // black diamond suit
case 0x05: return L'♣'; // black club suit
case 0x06: return L'♠'; // black spade suit
case 0x07: return L'•'; // bullet
case 0x08: return L'◘'; // inverse bullet
case 0x09: return L'○'; // white circle
case 0x0A: return L'◙'; // inverse white circle
case 0x0B: return L'♂'; // male sign
case 0x0C: return L'♀'; // female sign
case 0x0D: return L'♪'; // eighth note
case 0x0E: return L'♫'; // beamed eighth notes
case 0x0F: return L'☼'; // white sun with rays
case 0x10: return L'►'; // black right - pointing pointer
case 0x11: return L'◄'; // black left - pointing pointer
case 0x12: return L'↕'; // up down arrow
case 0x13: return L'‼'; // double exclamation mark
case 0x14: return L'¶'; // pilcrow sign
case 0x15: return L'§'; // section sign
case 0x16: return L'▬'; // black rectangle
case 0x17: return L'↨'; // up down arrow with base
case 0x18: return L'↑'; // upwards arrow
case 0x19: return L'↓'; // downwards arrow
case 0x1A: return L'→'; // rightwards arrow
case 0x1B: return L'←'; // leftwards arrow
case 0x1C: return L'∟'; // right angle
case 0x1D: return L'↔'; // left right arrow
case 0x1E: return L'▲'; // black up - pointing triangle
case 0x1F: return L'▼'; // black down - pointing triangle
case 0x7F: return L'⌂'; // house
// C1
// These are considered control characters too now.
// Unlike C0, it is unclear what glyphs to use, so just remap to the private area for now.
case 0x80: return L'\xE080';
case 0x81: return L'\xE081';
case 0x82: return L'\xE082';
case 0x83: return L'\xE083';
case 0x84: return L'\xE084';
case 0x85: return L'\xE085';
case 0x86: return L'\xE086';
case 0x87: return L'\xE087';
case 0x88: return L'\xE088';
case 0x89: return L'\xE089';
case 0x8A: return L'\xE08A';
case 0x8B: return L'\xE08B';
case 0x8C: return L'\xE08C';
case 0x8D: return L'\xE08D';
case 0x8E: return L'\xE08E';
case 0x8F: return L'\xE08F';
case 0x90: return L'\xE090';
case 0x91: return L'\xE091';
case 0x92: return L'\xE092';
case 0x93: return L'\xE093';
case 0x94: return L'\xE094';
case 0x95: return L'\xE095';
case 0x96: return L'\xE096';
case 0x97: return L'\xE097';
case 0x98: return L'\xE098';
case 0x99: return L'\xE099';
case 0x9A: return L'\xE09A';
case 0x9B: return L'\xE09B';
case 0x9C: return L'\xE09C';
case 0x9D: return L'\xE09D';
case 0x9E: return L'\xE09E';
case 0x9F: return L'\xE09F';
default: return Char;
}
}
static bool sanitise_dbsc_pair(FAR_CHAR_INFO& First, FAR_CHAR_INFO& Second)
{
const auto
IsFirst = flags::check_any(First.Attributes.Flags, COMMON_LVB_LEADING_BYTE),
IsSecond = flags::check_any(Second.Attributes.Flags, COMMON_LVB_TRAILING_BYTE);
if (!IsFirst && !IsSecond)
{
// Not DBSC, awesome
return false;
}
flags::clear(First.Attributes.Flags, COMMON_LVB_LEADING_BYTE);
flags::clear(Second.Attributes.Flags, COMMON_LVB_TRAILING_BYTE);
if (First == Second)
{
// Valid DBSC, awesome
flags::set(First.Attributes.Flags, COMMON_LVB_LEADING_BYTE);
flags::set(Second.Attributes.Flags, COMMON_LVB_TRAILING_BYTE);
return false;
}
if (IsFirst)
First.Char = bad_char_replacement;
if (IsSecond)
Second.Char = bad_char_replacement;
return true;
}
static bool sanitise_surrogate_pair(FAR_CHAR_INFO& First, FAR_CHAR_INFO& Second)
{
const auto
IsFirst = encoding::utf16::is_high_surrogate(First.Char),
IsSecond = encoding::utf16::is_low_surrogate(Second.Char);
if (!IsFirst && !IsSecond)
{
// Not surrogate, awesome
return false;
}
if (encoding::utf16::is_valid_surrogate_pair(First.Char, Second.Char) && First.Attributes == Second.Attributes)
{
// Valid surrogate, awesome
return false;
}
if (IsFirst)
First.Char = bad_char_replacement;
if (IsSecond)
Second.Char = bad_char_replacement;
return true;
}
void sanitise_pair(FAR_CHAR_INFO& First, FAR_CHAR_INFO& Second)
{
sanitise_dbsc_pair(First, Second) || sanitise_surrogate_pair(First, Second);
}
static COORD make_coord(point const& Point)
{
return
{
static_cast<short>(Point.x),
static_cast<short>(Point.y)
};
}
static SMALL_RECT make_rect(rectangle const& Rectangle)
{
return
{
static_cast<short>(Rectangle.left),
static_cast<short>(Rectangle.top),
static_cast<short>(Rectangle.right),
static_cast<short>(Rectangle.bottom)
};
}
static short GetDelta(CONSOLE_SCREEN_BUFFER_INFO const& csbi)
{
return csbi.dwSize.Y - (csbi.srWindow.Bottom - csbi.srWindow.Top + 1);
}
namespace console_detail
{
// пишем/читаем порциями по 32 K, иначе проблемы.
const unsigned int MAXSIZE = 32768;
class external_console
{
public:
NONCOPYABLE(external_console);
external_console() = default;
struct ModuleImports
{
private:
os::rtdl::module m_Module{ L"extendedconsole.dll"sv };
public:
#define DECLARE_IMPORT_FUNCTION(name, ...) os::rtdl::function_pointer<__VA_ARGS__> p ## name{ m_Module, #name }
DECLARE_IMPORT_FUNCTION(ReadOutput, BOOL(WINAPI*)(FAR_CHAR_INFO* Buffer, COORD BufferSize, COORD BufferCoord, SMALL_RECT* ReadRegion));
DECLARE_IMPORT_FUNCTION(WriteOutput, BOOL(WINAPI*)(const FAR_CHAR_INFO* Buffer, COORD BufferSize, COORD BufferCoord, SMALL_RECT* WriteRegion));
DECLARE_IMPORT_FUNCTION(Commit, BOOL(WINAPI*)());
DECLARE_IMPORT_FUNCTION(GetTextAttributes, BOOL(WINAPI*)(FarColor* Attributes));
DECLARE_IMPORT_FUNCTION(SetTextAttributes, BOOL(WINAPI*)(const FarColor* Attributes));
DECLARE_IMPORT_FUNCTION(ClearExtraRegions, BOOL(WINAPI*)(const FarColor* Color, int Mode));
#undef DECLARE_IMPORT_FUNCTION
}
Imports;
};
static nifty_counter::buffer<external_console> Storage;
static auto& ExternalConsole = reinterpret_cast<external_console&>(Storage);
console::console():
m_OriginalInputHandle(GetStdHandle(STD_INPUT_HANDLE)),
m_StreamBuffersOverrider(std::make_unique<stream_buffers_overrider>())
{
placement::construct(ExternalConsole);
}
console::~console()
{
if (m_FileHandle != -1)
_close(m_FileHandle);
placement::destruct(ExternalConsole);
}
bool console::Allocate() const
{
return AllocConsole() != FALSE;
}
bool console::Free() const
{
return FreeConsole() != FALSE;
}
HANDLE console::GetInputHandle() const
{
return GetStdHandle(STD_INPUT_HANDLE);
}
HANDLE console::GetOutputHandle() const
{
return GetStdHandle(STD_OUTPUT_HANDLE);
}
HANDLE console::GetErrorHandle() const
{
return GetStdHandle(STD_ERROR_HANDLE);
}
HANDLE console::GetOriginalInputHandle() const
{
return m_OriginalInputHandle;
}
HWND console::GetWindow() const
{
return GetConsoleWindow();
}
bool console::GetSize(point& Size) const
{
CONSOLE_SCREEN_BUFFER_INFO ConsoleScreenBufferInfo;
if (!GetConsoleScreenBufferInfo(GetOutputHandle(), &ConsoleScreenBufferInfo))
return false;
if (sWindowMode)
{
Size =
{
ConsoleScreenBufferInfo.srWindow.Right - ConsoleScreenBufferInfo.srWindow.Left + 1,
ConsoleScreenBufferInfo.srWindow.Bottom - ConsoleScreenBufferInfo.srWindow.Top + 1
};
}
else
{
Size = ConsoleScreenBufferInfo.dwSize;
}
return true;
}
bool console::SetSize(point const Size) const
{
if (!sWindowMode)
return SetScreenBufferSize(Size);
CONSOLE_SCREEN_BUFFER_INFO csbi;
GetConsoleScreenBufferInfo(GetOutputHandle(), &csbi);
csbi.srWindow.Left = 0;
csbi.srWindow.Right = Size.x - 1;
csbi.srWindow.Bottom = csbi.dwSize.Y - 1;
csbi.srWindow.Top = csbi.srWindow.Bottom - (Size.y - 1);
point WindowCoord = { csbi.srWindow.Right - csbi.srWindow.Left + 1, csbi.srWindow.Bottom - csbi.srWindow.Top + 1 };
if (WindowCoord.x > csbi.dwSize.X || WindowCoord.y > csbi.dwSize.Y)
{
WindowCoord.x = std::max(WindowCoord.x, static_cast<int>(csbi.dwSize.X));
WindowCoord.y = std::max(WindowCoord.y, static_cast<int>(csbi.dwSize.Y));
SetScreenBufferSize(WindowCoord);
if (WindowCoord.x > csbi.dwSize.X)
{
// windows sometimes uses existing colors to init right region of screen buffer
FarColor Color;
GetTextAttributes(Color);
ClearExtraRegions(Color, CR_RIGHT);
}
}
return SetWindowRect(csbi.srWindow);
}
bool console::SetScreenBufferSize(point const Size) const
{
const auto Out = GetOutputHandle();
// This abominable workaround is for another Windows 10 bug, see https://github.com/microsoft/terminal/issues/2366
// TODO: check the OS version once they fix it
if (IsVtSupported())
{
CONSOLE_SCREEN_BUFFER_INFO Info;
if (GetConsoleScreenBufferInfo(Out, &Info))
{
// Make sure the cursor is within the new buffer
if (!(Info.dwCursorPosition.X < Size.x && Info.dwCursorPosition.Y < Size.y))
{
SetConsoleCursorPosition(
Out,
{
std::min(Info.dwCursorPosition.X, static_cast<SHORT>(Size.x - 1)),
std::min(Info.dwCursorPosition.Y, static_cast<SHORT>(Size.y - 1))
}
);
}
// Make sure the window is within the new buffer:
rectangle Rect(Info.srWindow);
if (Size.x < Rect.right + 1 || Size.y < Rect.bottom + 1)
{
const auto Width = Rect.width(), Height = Rect.height();
Rect.bottom = std::min(Rect.bottom, Size.y - 1);
Rect.right = std::min(Rect.right, Size.x - 1);
Rect.top = std::max(0, Rect.bottom - Height);
Rect.left = std::max(0, Rect.right - Width);
SetWindowRect(Rect);
}
}
}
const auto Result = SetConsoleScreenBufferSize(Out, make_coord(Size)) != FALSE;
// After changing the buffer size the window size is not always correct
if (IsVtSupported())
{
CONSOLE_SCREEN_BUFFER_INFO Info;
if (GetConsoleScreenBufferInfo(Out, &Info))
{
SetWindowRect(Info.srWindow);
}
}
return Result;
}
bool console::GetWindowRect(rectangle& ConsoleWindow) const
{
CONSOLE_SCREEN_BUFFER_INFO ConsoleScreenBufferInfo;
if (!GetConsoleScreenBufferInfo(GetOutputHandle(), &ConsoleScreenBufferInfo))
return false;
ConsoleWindow = ConsoleScreenBufferInfo.srWindow;
return true;
}
bool console::SetWindowRect(rectangle const& ConsoleWindow) const
{
const auto Rect = make_rect(ConsoleWindow);
return SetConsoleWindowInfo(GetOutputHandle(), true, &Rect) != FALSE;
}
bool console::GetWorkingRect(rectangle& WorkingRect) const
{
CONSOLE_SCREEN_BUFFER_INFO csbi;
if (!GetConsoleScreenBufferInfo(GetOutputHandle(), &csbi))
return false;
WorkingRect.bottom = csbi.dwSize.Y - 1;
WorkingRect.left = 0;
WorkingRect.right = WorkingRect.left + ScrX;
WorkingRect.top = WorkingRect.bottom - ScrY;
return true;
}
string console::GetPhysicalTitle() const
{
// Don't use GetConsoleTitle here, it's buggy.
string Title;
os::GetWindowText(GetWindow(), Title);
return Title;
}
string console::GetTitle() const
{
return m_Title;
}
bool console::SetTitle(string_view const Title) const
{
m_Title = Title;
return SetConsoleTitle(m_Title.c_str()) != FALSE;
}
bool console::GetKeyboardLayoutName(string &strName) const
{
wchar_t Buffer[KL_NAMELENGTH];
if (!imports.GetConsoleKeyboardLayoutNameW(Buffer))
return false;
strName = Buffer;
return true;
}
uintptr_t console::GetInputCodepage() const
{
return GetConsoleCP();
}
bool console::SetInputCodepage(uintptr_t Codepage) const
{
return SetConsoleCP(Codepage) != FALSE;
}
uintptr_t console::GetOutputCodepage() const
{
return GetConsoleOutputCP();
}
bool console::SetOutputCodepage(uintptr_t Codepage) const
{
return SetConsoleOutputCP(Codepage) != FALSE;
}
bool console::SetControlHandler(PHANDLER_ROUTINE HandlerRoutine, bool Add) const
{
return SetConsoleCtrlHandler(HandlerRoutine, Add) != FALSE;
}
bool console::GetMode(HANDLE ConsoleHandle, DWORD& Mode) const
{
return GetConsoleMode(ConsoleHandle, &Mode) != FALSE;
}
bool console::SetMode(HANDLE ConsoleHandle, DWORD Mode) const
{
return SetConsoleMode(ConsoleHandle, Mode) != FALSE;
}
bool console::IsVtSupported() const
{
static const auto Result = [&]
{
// https://devblogs.microsoft.com/commandline/24-bit-color-in-the-windows-console/
if (!os::version::is_win10_build_or_later(14931))
return false;
const auto Handle = GetOutputHandle();
DWORD CurrentMode;
if (!GetMode(Handle, CurrentMode))
return false;
if (CurrentMode & ENABLE_VIRTUAL_TERMINAL_PROCESSING)
return true;
if (!SetMode(Handle, CurrentMode | ENABLE_VIRTUAL_TERMINAL_PROCESSING))
return false;
SetMode(Handle, CurrentMode);
return true;
}();
return Result;
}
static bool get_current_console_font(HANDLE OutputHandle, CONSOLE_FONT_INFO& FontInfo)
{
if (!GetCurrentConsoleFont(OutputHandle, FALSE, &FontInfo))
return false;
// in XP FontInfo.dwFontSize contains something else than the size in pixels.
FontInfo.dwFontSize = GetConsoleFontSize(OutputHandle, FontInfo.nFont);
return FontInfo.dwFontSize.X && FontInfo.dwFontSize.Y;
}
// Workaround for a bug in the classic console: mouse position is screen-based
static void fix_wheel_coordinates(MOUSE_EVENT_RECORD& Record)
{
if (!(Record.dwEventFlags & (MOUSE_WHEELED | MOUSE_HWHEELED)))
return;
// 'New' console doesn't need this
if (::console.IsVtSupported())
return;
// Note: using the current mouse position rather than what's in the wheel event
POINT CursorPos;
if (!GetCursorPos(&CursorPos))
return;
const auto WindowHandle = ::console.GetWindow();
auto RelativePos = CursorPos;
if (!ScreenToClient(WindowHandle, &RelativePos))
return;
const auto OutputHandle = ::console.GetOutputHandle();
CONSOLE_FONT_INFO FontInfo;
if (!get_current_console_font(OutputHandle, FontInfo))
return;
CONSOLE_SCREEN_BUFFER_INFO Csbi;
if (!GetConsoleScreenBufferInfo(OutputHandle, &Csbi))
return;
const auto Set = [&](auto Coord, auto Point, auto SmallRect)
{
Record.dwMousePosition.*Coord = std::clamp(Csbi.srWindow.*SmallRect + static_cast<int>(RelativePos.*Point) / FontInfo.dwFontSize.*Coord, 0, Csbi.dwSize.*Coord - 1);
};
Set(&COORD::X, &POINT::x, &SMALL_RECT::Left);
Set(&COORD::Y, &POINT::y, &SMALL_RECT::Top);
}
static void AdjustMouseEvents(span<INPUT_RECORD> const Buffer, short Delta)
{
point Size;
::console.GetSize(Size);
for (auto& i: Buffer)
{
if (i.EventType != MOUSE_EVENT)
continue;
fix_wheel_coordinates(i.Event.MouseEvent);
i.Event.MouseEvent.dwMousePosition.Y = std::max(0, i.Event.MouseEvent.dwMousePosition.Y - Delta);
i.Event.MouseEvent.dwMousePosition.X = std::min(i.Event.MouseEvent.dwMousePosition.X, static_cast<short>(Size.x - 1));
}
}
bool console::PeekInput(span<INPUT_RECORD> const Buffer, size_t& NumberOfEventsRead) const
{
DWORD dwNumberOfEventsRead = 0;
if (!PeekConsoleInput(GetInputHandle(), Buffer.data(), static_cast<DWORD>(Buffer.size()), &dwNumberOfEventsRead))
return false;
NumberOfEventsRead = dwNumberOfEventsRead;
if (sWindowMode)
{
AdjustMouseEvents({Buffer.data(), NumberOfEventsRead}, GetDelta());
}
return true;
}
bool console::PeekOneInput(INPUT_RECORD& Record) const
{
size_t Read;
return PeekInput({ &Record, 1 }, Read) && Read == 1;
}
bool console::ReadInput(span<INPUT_RECORD> const Buffer, size_t& NumberOfEventsRead) const
{
DWORD dwNumberOfEventsRead = 0;
if (!ReadConsoleInput(GetInputHandle(), Buffer.data(), static_cast<DWORD>(Buffer.size()), &dwNumberOfEventsRead))
return false;
NumberOfEventsRead = dwNumberOfEventsRead;
if (sWindowMode)
{
AdjustMouseEvents({Buffer.data(), NumberOfEventsRead}, GetDelta());
}
return true;
}
bool console::ReadOneInput(INPUT_RECORD& Record) const
{
size_t Read;
return ReadInput({ &Record, 1 }, Read) && Read == 1;
}
bool console::WriteInput(span<INPUT_RECORD> const Buffer, size_t& NumberOfEventsWritten) const
{
if (sWindowMode)
{
const auto Delta = GetDelta();
for (auto& i: Buffer)
{
if (i.EventType == MOUSE_EVENT)
{
i.Event.MouseEvent.dwMousePosition.Y += Delta;
}
}
}
DWORD dwNumberOfEventsWritten = 0;
const auto Result = WriteConsoleInput(GetInputHandle(), Buffer.data(), static_cast<DWORD>(Buffer.size()), &dwNumberOfEventsWritten) != FALSE;
NumberOfEventsWritten = dwNumberOfEventsWritten;
return Result;
}
static bool ReadOutputImpl(CHAR_INFO* const Buffer, point const BufferSize, rectangle& ReadRegion)
{
auto Rect = make_rect(ReadRegion);
const auto Result = ReadConsoleOutput(::console.GetOutputHandle(), Buffer, make_coord(BufferSize), {}, &Rect) != FALSE;
ReadRegion = Rect;
return Result;
}
bool console::ReadOutput(matrix<FAR_CHAR_INFO>& Buffer, point const BufferCoord, rectangle const& ReadRegionRelative) const
{
if (ExternalConsole.Imports.pReadOutput)
{
const COORD BufferSize = { static_cast<short>(Buffer.width()), static_cast<short>(Buffer.height()) };
auto ReadRegion = make_rect(ReadRegionRelative);
return ExternalConsole.Imports.pReadOutput(Buffer.data(), BufferSize, make_coord(BufferCoord), &ReadRegion) != FALSE;
}
const int Delta = sWindowMode? GetDelta() : 0;
auto ReadRegion = ReadRegionRelative;
ReadRegion.top += Delta;
ReadRegion.bottom += Delta;
const rectangle SubRect
{
BufferCoord.x,
BufferCoord.y,
BufferCoord.x + ReadRegion.width() - 1,
BufferCoord.y + ReadRegion.height() - 1
};
std::vector<CHAR_INFO> ConsoleBuffer(SubRect.width() * SubRect.height());
point const BufferSize{ static_cast<int>(SubRect.width()), static_cast<int>(SubRect.height()) };
if (BufferSize.x * BufferSize.y * sizeof(CHAR_INFO) > MAXSIZE)
{
const auto HeightStep = std::max(MAXSIZE / (BufferSize.x * sizeof(CHAR_INFO)), size_t(1));
const size_t Height = ReadRegion.bottom - ReadRegion.top + 1;
for (size_t i = 0; i < Height; i += HeightStep)
{
auto PartialReadRegion = ReadRegion;
PartialReadRegion.top += static_cast<int>(i);
PartialReadRegion.bottom = std::min(ReadRegion.bottom, static_cast<int>(PartialReadRegion.top + HeightStep - 1));
point const PartialBufferSize{ BufferSize.x, static_cast<int>(PartialReadRegion.height()) };
if (!ReadOutputImpl(ConsoleBuffer.data() + i * PartialBufferSize.x, PartialBufferSize, PartialReadRegion))
return false;
}
}
else
{
auto ReadRegionCopy = ReadRegion;
if (!ReadOutputImpl(ConsoleBuffer.data(), BufferSize, ReadRegionCopy))
return false;
}
auto ConsoleBufferIterator = ConsoleBuffer.cbegin();
for_submatrix(Buffer, SubRect, [&](FAR_CHAR_INFO& i)
{
const auto& Cell = *ConsoleBufferIterator++;
i = { Cell.Char.UnicodeChar, colors::ConsoleColorToFarColor(Cell.Attributes) };
});
return true;
}
static constexpr wchar_t vt_color_index(int const Index)
{
// NT is RGB, VT is BGR
constexpr int Table[]
{
//BGR RGB
0b000, // 000
0b100, // 001
0b010, // 010
0b110, // 011
0b001, // 100
0b101, // 101
0b011, // 110
0b111, // 111
};
return L'0' + Table[Index & 0b111];
}
static const struct
{
string_view Normal, Intense, TrueColour;
COLORREF FarColor::* Color;
FARCOLORFLAGS Flags;
}
ColorsMapping[]
{
{ L"3"sv, L"9"sv, L"38"sv, &FarColor::ForegroundColor, FCF_FG_4BIT },
{ L"4"sv, L"10"sv, L"48"sv, &FarColor::BackgroundColor, FCF_BG_4BIT },
};
static void make_vt_attributes(const FarColor& Attributes, string& Str, std::optional<FarColor> const& LastColor)
{
append(Str, L"\x9b"sv);
for (const auto& i: ColorsMapping)
{
const auto ColorPart = std::invoke(i.Color, Attributes);
if (Attributes.Flags & i.Flags)
{
append(Str, ColorPart & FOREGROUND_INTENSITY? i.Intense : i.Normal, vt_color_index(ColorPart));
}
else
{
const union { COLORREF Color; rgba RGBA; } Value { ColorPart };
format_to(Str, FSTR(L"{};2;{};{};{}"sv), i.TrueColour, Value.RGBA.r, Value.RGBA.g, Value.RGBA.b);
}
Str += L';';
}
Str.pop_back();
const auto set_style = [&](FARCOLORFLAGS const Style, string_view const On, string_view const Off)
{
if (Attributes.Flags & Style)
{
if (!LastColor.has_value() || !(LastColor->Flags & Style))
Str += On;
}
else
{
if (LastColor.has_value() && LastColor->Flags & Style)
Str += Off;
}
};
set_style(FCF_FG_BOLD, L";1"sv, L";22"sv);
set_style(FCF_FG_ITALIC, L";3"sv, L";23"sv);
set_style(FCF_FG_UNDERLINE, L";4"sv, L";24"sv);
set_style(FCF_FG_UNDERLINE2, L";21"sv, L";24"sv);
set_style(FCF_FG_OVERLINE, L";53"sv, L";55"sv);
set_style(FCF_FG_STRIKEOUT, L";9"sv, L";29"sv);
set_style(FCF_FG_FAINT, L";2"sv, L";22"sv);
set_style(FCF_FG_BLINK, L";5"sv, L";25"sv);
Str += L'm';
}
static void make_vt_sequence(span<FAR_CHAR_INFO> Input, string& Str, std::optional<FarColor>& LastColor)
{
const auto CharWidthEnabled = char_width::is_enabled();
std::optional<wchar_t> LeadingChar;
for (const auto& [Cell, n]: enumerate(Input))
{
if (CharWidthEnabled)
{
if (n != Input.size() - 1)
{
sanitise_pair(Cell, Input[n + 1]);
}
if (Cell.Attributes.Flags & COMMON_LVB_TRAILING_BYTE)
{
if (!LeadingChar)
{
Cell.Char = bad_char_replacement;
flags::clear(Cell.Attributes.Flags, COMMON_LVB_TRAILING_BYTE);
}
else if (Cell.Char == *LeadingChar)
{
LeadingChar.reset();
continue;
}
}
else if (!n && encoding::utf16::is_low_surrogate(Cell.Char))
{
Cell.Char = bad_char_replacement;
}
LeadingChar.reset();
if (Cell.Attributes.Flags & COMMON_LVB_LEADING_BYTE)
{
if (n == Input.size() - 1)
{
flags::clear(Cell.Attributes.Flags, COMMON_LVB_LEADING_BYTE);
Cell.Char = bad_char_replacement;
}
else
{
LeadingChar = Cell.Char;
}
}
else if (n == Input.size() - 1 && encoding::utf16::is_high_surrogate(Cell.Char))
{
Cell.Char = bad_char_replacement;
}
}
if (!LastColor.has_value() || Cell.Attributes != *LastColor)
{
make_vt_attributes(Cell.Attributes, Str, LastColor);
LastColor = Cell.Attributes;
}
if (CharWidthEnabled && Cell.Char == encoding::replace_char && Cell.Attributes.Reserved[0] > std::numeric_limits<wchar_t>::max())
{
const auto Pair = encoding::utf16::to_surrogate(Cell.Attributes.Reserved[0]);
append(Str, Pair.first, Pair.second);
}
else
{
Str += ReplaceControlCharacter(Cell.Char);
}
}
}
class console::implementation
{
public:
static bool WriteOutputVT(matrix<FAR_CHAR_INFO>& Buffer, rectangle const SubRect, rectangle const& WriteRegion)
{
const auto Out = ::console.GetOutputHandle();
CONSOLE_SCREEN_BUFFER_INFO csbi;
if (!GetConsoleScreenBufferInfo(Out, &csbi))
return false;
point SavedCursorPosition;
if (!::console.GetCursorRealPosition(SavedCursorPosition))
return false;
CONSOLE_CURSOR_INFO SavedCursorInfo;
if (!::console.GetCursorInfo(SavedCursorInfo))
return false;
if (
// Hide cursor
!::console.SetCursorInfo({1}) ||
// Move the viewport down
!::console.SetCursorRealPosition({ 0, csbi.dwSize.Y - 1 }) ||
// Set cursor position within the viewport
!::console.SetCursorRealPosition({ WriteRegion.left, WriteRegion.top }))
return false;
SCOPE_EXIT
{
// Move the viewport down
::console.SetCursorRealPosition({ 0, csbi.dwSize.Y - 1 });
// Restore cursor position within the viewport
::console.SetCursorRealPosition(SavedCursorPosition);
// Restore cursor
::console.SetCursorInfo(SavedCursorInfo);
// Restore buffer relative position
if (csbi.srWindow.Left || csbi.srWindow.Bottom != csbi.dwSize.Y - 1)
::console.SetWindowRect(csbi.srWindow);
};
point CursorPosition{ WriteRegion.left, WriteRegion.top };
if (sWindowMode)
{
CursorPosition.y -= ::GetDelta(csbi);
if (CursorPosition.y < 0)
{
// Drawing above the viewport
CursorPosition.y = 0;
}
}
string Str;
// The idea is to reduce the number of reallocations,
// but only if it's not a single / double cell update
if (const auto Area = SubRect.width() * SubRect.height(); Area > 4)
Str.reserve(std::max(1024, Area * 2));
std::optional<FarColor> LastColor;
for (const auto& i: irange(SubRect.top + 0, SubRect.bottom + 1))
{
if (i != SubRect.top)
format_to(Str, FSTR(L"\x9b""{};{}H"sv), CursorPosition.y + 1 + (i - SubRect.top), CursorPosition.x + 1);
make_vt_sequence(Buffer[i].subspan(SubRect.left, SubRect.width()), Str, LastColor);
}
append(Str, L"\x9b""0m"sv);
return ::console.Write(Str);
}
class cursor_suppressor
{
public:
NONCOPYABLE(cursor_suppressor);
cursor_suppressor()
{
CONSOLE_CURSOR_INFO Info;
if (!::console.GetCursorInfo(Info))
return;
if (!::console.SetCursorInfo({ 1 }))
return;
m_Info = Info;
point Position;
if (!::console.GetCursorRealPosition(Position))
return;
if (!::console.SetCursorPosition({}))
return;
m_Position = Position;
}
~cursor_suppressor()
{
if (m_Position)
::console.SetCursorRealPosition(*m_Position);
if (m_Info)
::console.SetCursorInfo(*m_Info);
}
private:
std::optional<point> m_Position;
std::optional<CONSOLE_CURSOR_INFO> m_Info;
};
static bool WriteOutputNTImpl(CHAR_INFO const* const Buffer, point const BufferSize, rectangle const& WriteRegion)
{
// https://github.com/microsoft/terminal/issues/10456
// It looks like only a specific range of Windows 10 versions is affected.
static const auto IsCursorPositionWorkaroundNeeded = os::version::is_win10_build_or_later(19041) && !os::version::is_win10_build_or_later(21277);
std::optional<cursor_suppressor> CursorSuppressor;
if (IsCursorPositionWorkaroundNeeded && char_width::is_enabled())
CursorSuppressor.emplace();
auto SysWriteRegion = make_rect(WriteRegion);
return WriteConsoleOutput(::console.GetOutputHandle(), Buffer, make_coord(BufferSize), {}, &SysWriteRegion) != FALSE;
}
static bool WriteOutputNTImplDebug(CHAR_INFO* const Buffer, point const BufferSize, rectangle const& WriteRegion)
{
if constexpr ((false))
{
assert(BufferSize.x == WriteRegion.width());
assert(BufferSize.y == WriteRegion.height());
const auto invert_colors = [&]
{
for (auto& i: span(Buffer, BufferSize.x* BufferSize.y))
i.Attributes = (i.Attributes & FCF_RAWATTR_MASK) | LOBYTE(~i.Attributes);
};
invert_colors();
WriteOutputNTImpl(Buffer, BufferSize, WriteRegion);
Sleep(50);
invert_colors();
}
return WriteOutputNTImpl(Buffer, BufferSize, WriteRegion) != FALSE;
}
static bool WriteOutputNT(matrix<FAR_CHAR_INFO>& Buffer, rectangle const SubRect, rectangle const& WriteRegion)
{
std::vector<CHAR_INFO> ConsoleBuffer;
ConsoleBuffer.reserve(SubRect.width() * SubRect.height());
if (char_width::is_enabled())
{
for_submatrix(Buffer, SubRect, [&](FAR_CHAR_INFO& Cell, point const Point)
{
if (!Point.x)
{
if (Cell.Attributes.Flags & COMMON_LVB_TRAILING_BYTE)
{
flags::clear(Cell.Attributes.Flags, COMMON_LVB_TRAILING_BYTE);
Cell.Char = bad_char_replacement;
}
else if (encoding::utf16::is_low_surrogate(Cell.Char))
{
Cell.Char = bad_char_replacement;
}
}
if (Point.x != SubRect.width() - 1)
{
sanitise_pair(Cell, Buffer[SubRect.top + Point.y][SubRect.left + Point.x + 1]);
}
else
{
if (Cell.Attributes.Flags & COMMON_LVB_LEADING_BYTE)
{
flags::clear(Cell.Attributes.Flags, COMMON_LVB_LEADING_BYTE);
Cell.Char = bad_char_replacement;
}
else if (encoding::utf16::is_high_surrogate(Cell.Char))
{
Cell.Char = bad_char_replacement;
}
}
ConsoleBuffer.emplace_back(CHAR_INFO{ { ReplaceControlCharacter(Cell.Char) }, colors::FarColorToConsoleColor(Cell.Attributes) });
});
}
else
{
for_submatrix(Buffer, SubRect, [&](const FAR_CHAR_INFO& i)
{
ConsoleBuffer.emplace_back(CHAR_INFO{ { ReplaceControlCharacter(i.Char) }, colors::FarColorToConsoleColor(i.Attributes) });
});
}
point const BufferSize{ static_cast<int>(SubRect.width()), static_cast<int>(SubRect.height()) };
if (BufferSize.x * BufferSize.y * sizeof(CHAR_INFO) > MAXSIZE)
{
const auto HeightStep = std::max(MAXSIZE / (BufferSize.x * sizeof(CHAR_INFO)), size_t(1));
for (size_t i = 0, Height = WriteRegion.height(); i < Height; i += HeightStep)
{
rectangle const PartialWriteRegion
{
WriteRegion.left,
WriteRegion.top + static_cast<int>(i),
WriteRegion.right,
std::min(WriteRegion.bottom, static_cast<int>(WriteRegion.top + static_cast<int>(i) + HeightStep - 1))
};
point const PartialBufferSize
{
BufferSize.x,
static_cast<int>(PartialWriteRegion.height())
};
if (!WriteOutputNTImplDebug(ConsoleBuffer.data() + i * PartialBufferSize.x, PartialBufferSize, PartialWriteRegion))
return false;
}
}
else
{
if (!WriteOutputNTImplDebug(ConsoleBuffer.data(), BufferSize, WriteRegion))
return false;
}
return true;
}
static bool SetTextAttributesVT(const FarColor& Attributes)
{
// For fallback
SetTextAttributesNT(Attributes);
string Str;
make_vt_attributes(Attributes, Str, {});
return ::console.Write(Str);
}
static bool SetTextAttributesNT(const FarColor& Attributes)
{
return SetConsoleTextAttribute(::console.GetOutputHandle(), colors::FarColorToConsoleColor(Attributes)) != FALSE;
}
};
bool console::WriteOutput(matrix<FAR_CHAR_INFO>& Buffer, point BufferCoord, const rectangle& WriteRegionRelative) const
{
if (ExternalConsole.Imports.pWriteOutput)
{
const COORD BufferSize = { static_cast<short>(Buffer.width()), static_cast<short>(Buffer.height()) };
auto WriteRegion = make_rect(WriteRegionRelative);
return ExternalConsole.Imports.pWriteOutput(Buffer.data(), BufferSize, make_coord(BufferCoord), &WriteRegion) != FALSE;
}
const int Delta = sWindowMode? GetDelta() : 0;
auto WriteRegion = WriteRegionRelative;
WriteRegion.top += Delta;
WriteRegion.bottom += Delta;
const rectangle SubRect
{
BufferCoord.x,
BufferCoord.y,
BufferCoord.x + WriteRegion.width() - 1,
BufferCoord.y + WriteRegion.height() - 1
};
return (IsVtEnabled()? implementation::WriteOutputVT : implementation::WriteOutputNT)(Buffer, SubRect, WriteRegion);
}
bool console::Read(string& Buffer, size_t& Size) const
{
const auto InputHandle = GetInputHandle();
DWORD NumberOfCharsRead;
DWORD Mode;
if (GetMode(InputHandle, Mode))
{
if (!ReadConsole(InputHandle, Buffer.data(), static_cast<DWORD>(Buffer.size()), &NumberOfCharsRead, nullptr))
return false;
}
else
{
if (!ReadFile(InputHandle, Buffer.data(), static_cast<DWORD>(Buffer.size() * sizeof(wchar_t)), &NumberOfCharsRead, nullptr))
return false;
NumberOfCharsRead /= sizeof(wchar_t);
}
Size = NumberOfCharsRead;
return true;
}
bool console::Write(const string_view Str) const
{
DWORD NumberOfCharsWritten;
const auto OutputHandle = GetOutputHandle();
DWORD Mode;
if (GetMode(OutputHandle, Mode))
return WriteConsole(OutputHandle, Str.data(), static_cast<DWORD>(Str.size()), &NumberOfCharsWritten, nullptr) != FALSE;
// Redirected output
if (m_FileHandle == -1)
{
HANDLE OsHandle;
if (!DuplicateHandle(GetCurrentProcess(), OutputHandle, GetCurrentProcess(), &OsHandle, 0, FALSE, DUPLICATE_SAME_ACCESS))
return false;
m_FileHandle = _open_osfhandle(reinterpret_cast<intptr_t>(OsHandle), _O_U8TEXT);
if (m_FileHandle == -1)
return false;
_setmode(m_FileHandle, _O_U8TEXT);
}
return _write(m_FileHandle, Str.data(), static_cast<unsigned int>(Str.size() * sizeof(wchar_t))) != -1;
}
bool console::Commit() const
{
if (ExternalConsole.Imports.pCommit)
return ExternalConsole.Imports.pCommit() != FALSE;
// reserved
return true;
}
bool console::GetTextAttributes(FarColor& Attributes) const
{
if (ExternalConsole.Imports.pGetTextAttributes)
return ExternalConsole.Imports.pGetTextAttributes(&Attributes) != FALSE;
CONSOLE_SCREEN_BUFFER_INFO ConsoleScreenBufferInfo;
if (!GetConsoleScreenBufferInfo(GetOutputHandle(), &ConsoleScreenBufferInfo))
return false;
Attributes = colors::ConsoleColorToFarColor(ConsoleScreenBufferInfo.wAttributes);
return true;
}
bool console::SetTextAttributes(const FarColor& Attributes) const
{
if (ExternalConsole.Imports.pSetTextAttributes)
return ExternalConsole.Imports.pSetTextAttributes(&Attributes) != FALSE;
return (IsVtEnabled()? implementation::SetTextAttributesVT : implementation::SetTextAttributesNT)(Attributes);
}
bool console::GetCursorInfo(CONSOLE_CURSOR_INFO& ConsoleCursorInfo) const
{
return GetConsoleCursorInfo(GetOutputHandle(), &ConsoleCursorInfo) != FALSE;
}
bool console::SetCursorInfo(const CONSOLE_CURSOR_INFO& ConsoleCursorInfo) const
{
return SetConsoleCursorInfo(GetOutputHandle(), &ConsoleCursorInfo) != FALSE;
}
bool console::GetCursorPosition(point& Position) const
{
if (!GetCursorRealPosition(Position))
return false;
if (sWindowMode)
Position.y -= GetDelta();
return true;
}
bool console::SetCursorPosition(point Position) const
{
if (sWindowMode)
{
point Size = {};
GetSize(Size);
Position.x = std::min(Position.x, static_cast<int>(Size.x - 1));
Position.y = std::max(static_cast<int>(0), Position.y);
Position.y += GetDelta();
}
return SetCursorRealPosition(Position);
}
bool console::FlushInputBuffer() const
{
return FlushConsoleInputBuffer(GetInputHandle()) != FALSE;
}
bool console::GetNumberOfInputEvents(size_t& NumberOfEvents) const
{
DWORD dwNumberOfEvents = 0;
const auto Result = GetNumberOfConsoleInputEvents(GetInputHandle(), &dwNumberOfEvents) != FALSE;
NumberOfEvents = dwNumberOfEvents;
return Result;
}
bool console::GetAlias(string_view const Name, string& Value, string_view const ExeName) const
{
os::last_error_guard Guard;
null_terminated const C_Name(Name), C_ExeName(ExeName);
return os::detail::ApiDynamicErrorBasedStringReceiver(ERROR_INSUFFICIENT_BUFFER, Value, [&](span<wchar_t> Buffer)
{
// This API design is mental:
// - If everything is ok, it return the string size, including the terminating \0
// - If the buffer size is too small, it returns the input buffer size and sets last error to ERROR_INSUFFICIENT_BUFFER
// - It can also return 0 in case of other errors
// This means that if the string size is exactly (BufferSize - 1), the only way to understand whether it succeeded or not
// is to look at the error code. And it doesn't reset it on success, so have to do it ourselves to be sure. *facepalm*
SetLastError(ERROR_SUCCESS);
const auto BufferSizeInBytes = Buffer.size() * sizeof(wchar_t);
const size_t ReturnedSizeInBytes = GetConsoleAlias(
const_cast<wchar_t*>(C_Name.c_str()),
Buffer.data(),
static_cast<DWORD>(BufferSizeInBytes),
const_cast<wchar_t*>(C_ExeName.c_str())
);
if (!ReturnedSizeInBytes || (ReturnedSizeInBytes == BufferSizeInBytes && GetLastError() == ERROR_INSUFFICIENT_BUFFER))
return size_t{};
return ReturnedSizeInBytes / sizeof(wchar_t) - 1;
});
}
std::unordered_map<string, std::unordered_map<string, string>> console::GetAllAliases() const
{
FN_RETURN_TYPE(console::GetAllAliases) Result;
const auto ExeLength = GetConsoleAliasExesLength();
if (!ExeLength)
return Result;
std::vector<wchar_t> ExeBuffer(ExeLength / sizeof(wchar_t) + 1); // +1 for double \0
if (!GetConsoleAliasExes(ExeBuffer.data(), ExeLength))
return Result;
std::vector<wchar_t> AliasesBuffer;
for (const auto& ExeToken : enum_substrings(ExeBuffer.data()))
{
// It's ok, ExeToken is guaranteed to be null-terminated
const auto ExeNamePtr = const_cast<wchar_t*>(ExeToken.data());
const auto AliasesLength = GetConsoleAliasesLength(ExeNamePtr);
AliasesBuffer.resize(AliasesLength / sizeof(wchar_t) + 1); // +1 for double \0
if (!GetConsoleAliases(AliasesBuffer.data(), AliasesLength, ExeNamePtr))
continue;
auto& ExeMap = Result[ExeNamePtr];
for (const auto& AliasToken : enum_substrings(AliasesBuffer.data()))
{
ExeMap.emplace(split(AliasToken));
}
}
return Result;
}
void console::SetAllAliases(const std::unordered_map<string, std::unordered_map<string, string>>& Aliases) const
{
for (const auto& [ExeName, ExeAliases]: Aliases)
{
for (const auto& [Alias, Value]: ExeAliases)
{
AddConsoleAlias(
const_cast<wchar_t*>(Alias.c_str()),
const_cast<wchar_t*>(Value.c_str()),
const_cast<wchar_t*>(ExeName.c_str())
);
}
}
}
bool console::GetDisplayMode(DWORD& Mode) const
{
return GetConsoleDisplayMode(&Mode) != FALSE;
}
point console::GetLargestWindowSize() const
{
point Result = GetLargestConsoleWindowSize(GetOutputHandle());
CONSOLE_SCREEN_BUFFER_INFO csbi;
GetConsoleScreenBufferInfo(GetOutputHandle(), &csbi);
if (csbi.dwSize.Y > Result.y)
{
CONSOLE_FONT_INFO FontInfo;
if (get_current_console_font(GetOutputHandle(), FontInfo))
{
Result.x -= Round(GetSystemMetrics(SM_CXVSCROLL), static_cast<int>(FontInfo.dwFontSize.X));
}
}
return Result;
}
bool console::SetActiveScreenBuffer(HANDLE ConsoleOutput)
{
if (!SetConsoleActiveScreenBuffer(ConsoleOutput))
return false;
m_ActiveConsoleScreenBuffer = ConsoleOutput;
return true;
}
HANDLE console::GetActiveScreenBuffer() const
{
return m_ActiveConsoleScreenBuffer;
}
bool console::ClearExtraRegions(const FarColor& Color, int Mode) const
{
if (ExternalConsole.Imports.pClearExtraRegions)
return ExternalConsole.Imports.pClearExtraRegions(&Color, Mode) != FALSE;
CONSOLE_SCREEN_BUFFER_INFO csbi;
GetConsoleScreenBufferInfo(GetOutputHandle(), &csbi);
DWORD CharsWritten;
const auto ConColor = colors::FarColorToConsoleColor(Color);
if (Mode&CR_TOP)
{
const DWORD TopSize = csbi.dwSize.X * csbi.srWindow.Top;
const COORD TopCoord = {};
FillConsoleOutputCharacter(GetOutputHandle(), L' ', TopSize, TopCoord, &CharsWritten);
FillConsoleOutputAttribute(GetOutputHandle(), ConColor, TopSize, TopCoord, &CharsWritten);
}
if (Mode&CR_RIGHT)
{
const DWORD RightSize = csbi.dwSize.X - csbi.srWindow.Right;
COORD RightCoord = { csbi.srWindow.Right, ::GetDelta(csbi) };
for (; RightCoord.Y < csbi.dwSize.Y; RightCoord.Y++)
{
FillConsoleOutputCharacter(GetOutputHandle(), L' ', RightSize, RightCoord, &CharsWritten);
FillConsoleOutputAttribute(GetOutputHandle(), ConColor, RightSize, RightCoord, &CharsWritten);
}
}
return true;
}
bool console::ScrollWindow(int Lines, int Columns) const
{
bool process = false;
CONSOLE_SCREEN_BUFFER_INFO csbi;
GetConsoleScreenBufferInfo(GetOutputHandle(), &csbi);
if ((Lines < 0 && csbi.srWindow.Top) || (Lines > 0 && csbi.srWindow.Bottom != csbi.dwSize.Y - 1))
{
csbi.srWindow.Top += Lines;
csbi.srWindow.Bottom += Lines;
if (csbi.srWindow.Top < 0)
{
csbi.srWindow.Bottom -= csbi.srWindow.Top;
csbi.srWindow.Top = 0;
}
if (csbi.srWindow.Bottom >= csbi.dwSize.Y)
{
csbi.srWindow.Top -= (csbi.srWindow.Bottom - (csbi.dwSize.Y - 1));
csbi.srWindow.Bottom = csbi.dwSize.Y - 1;
}
process = true;
}
if ((Columns < 0 && csbi.srWindow.Left) || (Columns > 0 && csbi.srWindow.Right != csbi.dwSize.X - 1))
{
csbi.srWindow.Left += Columns;
csbi.srWindow.Right += Columns;
if (csbi.srWindow.Left < 0)
{
csbi.srWindow.Right -= csbi.srWindow.Left;
csbi.srWindow.Left = 0;
}
if (csbi.srWindow.Right >= csbi.dwSize.X)
{
csbi.srWindow.Left -= (csbi.srWindow.Right - (csbi.dwSize.X - 1));
csbi.srWindow.Right = csbi.dwSize.X - 1;
}
process = true;
}
return process && SetWindowRect(csbi.srWindow);
}
bool console::ScrollWindowToBegin() const
{
CONSOLE_SCREEN_BUFFER_INFO csbi;
GetConsoleScreenBufferInfo(GetOutputHandle(), &csbi);
if (csbi.srWindow.Top > 0)
{
csbi.srWindow.Bottom -= csbi.srWindow.Top;
csbi.srWindow.Top = 0;
return SetWindowRect(csbi.srWindow);
}
return false;
}
bool console::ScrollWindowToEnd() const
{
CONSOLE_SCREEN_BUFFER_INFO csbi;
GetConsoleScreenBufferInfo(GetOutputHandle(), &csbi);
if (csbi.srWindow.Bottom < csbi.dwSize.Y - 1)
{
csbi.srWindow.Top += csbi.dwSize.Y - 1 - csbi.srWindow.Bottom;
csbi.srWindow.Bottom = csbi.dwSize.Y - 1;
return SetWindowRect(csbi.srWindow);
}
return false;
}
bool console::IsFullscreenSupported() const
{
#ifdef _WIN64
return false;
#else
CONSOLE_SCREEN_BUFFER_INFOEX csbiex{ sizeof(csbiex) };
if (imports.GetConsoleScreenBufferInfoEx && imports.GetConsoleScreenBufferInfoEx(GetOutputHandle(), &csbiex))
return csbiex.bFullscreenSupported != FALSE;
return true;
#endif
}
bool console::ResetPosition() const
{
CONSOLE_SCREEN_BUFFER_INFO csbi;
GetConsoleScreenBufferInfo(GetOutputHandle(), &csbi);
if (csbi.srWindow.Left || csbi.srWindow.Bottom != csbi.dwSize.Y - 1)
{
csbi.srWindow.Right -= csbi.srWindow.Left;
csbi.srWindow.Left = 0;
csbi.srWindow.Top += csbi.dwSize.Y - 1 - csbi.srWindow.Bottom;
csbi.srWindow.Bottom = csbi.dwSize.Y - 1;
SetWindowRect(csbi.srWindow);
}
return true;
}
bool console::ResetViewportPosition() const
{
rectangle WindowRect;
return
GetWindowRect(WindowRect) &&
SetCursorPosition({}) &&
SetCursorPosition({ 0, static_cast<int>(WindowRect.height() - 1) });
}
short console::GetDelta() const
{
CONSOLE_SCREEN_BUFFER_INFO csbi;
GetConsoleScreenBufferInfo(GetOutputHandle(), &csbi);
return ::GetDelta(csbi);
}
bool console::ScrollScreenBuffer(rectangle const& ScrollRectangle, point DestinationOrigin, const FAR_CHAR_INFO& Fill) const
{
const CHAR_INFO SysFill{ { Fill.Char }, colors::FarColorToConsoleColor(Fill.Attributes) };
const auto SysScrollRect = make_rect(ScrollRectangle);
return ScrollConsoleScreenBuffer(GetOutputHandle(), &SysScrollRect, {}, make_coord(DestinationOrigin), &SysFill) != FALSE;
}
bool console::ScrollNonClientArea(size_t NumLines, const FAR_CHAR_INFO& Fill) const
{
CONSOLE_SCREEN_BUFFER_INFO csbi;
if (!GetConsoleScreenBufferInfo(GetOutputHandle(), &csbi))
return false;
const auto Scroll = [&](rectangle const& Rect)
{
return ScrollScreenBuffer(
Rect,
{
Rect.left,
static_cast<int>(Rect.top - NumLines)
},
Fill);
};
rectangle const TopRectangle
{
0,
0,
csbi.dwSize.X - 1,
csbi.dwSize.Y - 1 - (ScrY + 1)
};
if (TopRectangle.bottom >= TopRectangle.top && !Scroll(TopRectangle))
return false;
rectangle const RightRectangle
{
ScrX + 1,
TopRectangle.bottom + 1,
csbi.dwSize.X - 1,
csbi.dwSize.Y - 1
};
if (RightRectangle.right >= RightRectangle.left && !Scroll(RightRectangle))
return false;
return true;
}
bool console::IsViewportVisible() const
{
CONSOLE_SCREEN_BUFFER_INFO csbi;
if (!GetConsoleScreenBufferInfo(GetOutputHandle(), &csbi))
return false;
const auto Height = csbi.srWindow.Bottom - csbi.srWindow.Top + 1;
const auto Width = csbi.srWindow.Right - csbi.srWindow.Left + 1;
return csbi.srWindow.Bottom >= csbi.dwSize.Y - Height && csbi.srWindow.Left < Width;
}
bool console::IsViewportShifted() const
{
if (!sWindowMode)
return false;
CONSOLE_SCREEN_BUFFER_INFO csbi;
if (!GetConsoleScreenBufferInfo(GetOutputHandle(), &csbi))
return false;
return csbi.srWindow.Left || csbi.srWindow.Bottom + 1 != csbi.dwSize.Y;
}
bool console::IsPositionVisible(point const Position) const
{
CONSOLE_SCREEN_BUFFER_INFO csbi;
if (!GetConsoleScreenBufferInfo(GetOutputHandle(), &csbi))
return false;
if (!in_closed_range(csbi.srWindow.Left, Position.x, csbi.srWindow.Right))
return false;
const auto RealY = Position.y + (sWindowMode? ::GetDelta(csbi) : 0);
return in_closed_range(csbi.srWindow.Top, RealY, csbi.srWindow.Bottom);
}
bool console::IsScrollbackPresent() const
{
return GetDelta() != 0;
}
bool console::IsVtEnabled() const
{
DWORD Mode;
return sEnableVirtualTerminal && GetMode(GetOutputHandle(), Mode) && Mode & ENABLE_VIRTUAL_TERMINAL_PROCESSING;
}
bool console::ExternalRendererLoaded() const
{
return ExternalConsole.Imports.pWriteOutput.operator bool();
}
bool console::IsWidePreciseExpensive(unsigned int const Codepoint, bool const ClearCacheOnly)
{
// It ain't stupid if it works
if (ClearCacheOnly)
{
m_WidthTestScreen = {};
return false;
}
if (!m_WidthTestScreen)
{
m_WidthTestScreen.reset(CreateConsoleScreenBuffer(GENERIC_READ | GENERIC_WRITE, {}, {}, CONSOLE_TEXTMODE_BUFFER, {}));
SetConsoleScreenBufferSize(m_WidthTestScreen.native_handle(), { 10, 1 });
}
if (!SetConsoleCursorPosition(m_WidthTestScreen.native_handle(), {}))
return false;
DWORD Written;
const auto Pair = encoding::utf16::to_surrogate(Codepoint);
std::array Chars = { Pair.first, Pair.second };
if (!WriteConsole(m_WidthTestScreen.native_handle(), Chars.data(), Pair.second? 2 : 1, &Written, {}))
return false;
CONSOLE_SCREEN_BUFFER_INFO Info;
if (!GetConsoleScreenBufferInfo(m_WidthTestScreen.native_handle(), &Info))
return false;
return Info.dwCursorPosition.X > 1;
}
bool console::GetPalette(std::array<COLORREF, 16>& Palette) const
{
if (!imports.GetConsoleScreenBufferInfoEx)
return false;
CONSOLE_SCREEN_BUFFER_INFOEX csbi{ sizeof(csbi) };
if (!imports.GetConsoleScreenBufferInfoEx(GetOutputHandle(), &csbi))
return false;
std::copy(ALL_CONST_RANGE(csbi.ColorTable), Palette.begin());
return true;
}
void console::EnableWindowMode(bool const Value)
{
sWindowMode = Value;
}
void console::EnableVirtualTerminal(bool const Value)
{
sEnableVirtualTerminal = Value;
}
bool console::GetCursorRealPosition(point& Position) const
{
CONSOLE_SCREEN_BUFFER_INFO ConsoleScreenBufferInfo;
if (!GetConsoleScreenBufferInfo(GetOutputHandle(), &ConsoleScreenBufferInfo))
return false;
Position = ConsoleScreenBufferInfo.dwCursorPosition;
return true;
}
bool console::SetCursorRealPosition(point const Position) const
{
return SetConsoleCursorPosition(GetOutputHandle(), make_coord(Position)) != FALSE;
}
}
NIFTY_DEFINE(console_detail::console, console);
enum
{
BufferSize = 8192
};
class consolebuf final: public std::wstreambuf
{
public:
NONCOPYABLE(consolebuf);
consolebuf():
m_InBuffer(BufferSize, {}),
m_OutBuffer(BufferSize, {})
{
setg(m_InBuffer.data(), m_InBuffer.data() + m_InBuffer.size(), m_InBuffer.data() + m_InBuffer.size());
setp(m_OutBuffer.data(), m_OutBuffer.data() + m_OutBuffer.size());
}
void color(const FarColor& Color)
{
m_Colour = Color;
}
protected:
int_type underflow() override
{
size_t Read;
if (!console.Read(m_InBuffer, Read))
throw MAKE_FAR_FATAL_EXCEPTION(L"Console read error"sv);
if (!Read)
return traits_type::eof();
setg(m_InBuffer.data(), m_InBuffer.data(), m_InBuffer.data() + Read);
return m_InBuffer[0];
}
int_type overflow(int_type Ch) override
{
if (!Write({ pbase(), static_cast<size_t>(pptr() - pbase()) }))
return traits_type::eof();
setp(m_OutBuffer.data(), m_OutBuffer.data() + m_OutBuffer.size());
if (traits_type::eq_int_type(Ch, traits_type::eof()))
{
console.Commit();
}
else
{
sputc(Ch);
}
return 0;
}
int sync() override
{
overflow(traits_type::eof());
return 0;
}
private:
bool Write(string_view Str)
{
if (Str.empty())
return true;
FarColor CurrentColor;
const auto ChangeColour = m_Colour && console.GetTextAttributes(CurrentColor);
if (ChangeColour)
{
console.SetTextAttributes(colors::merge(CurrentColor, *m_Colour));
}
SCOPE_EXIT{ if (ChangeColour) console.SetTextAttributes(CurrentColor); };
return console.Write(Str);
}
string m_InBuffer, m_OutBuffer;
std::optional<FarColor> m_Colour;
};
class console_detail::console::stream_buffers_overrider
{
public:
NONCOPYABLE(stream_buffers_overrider);
stream_buffers_overrider():
m_In(std::wcin, m_BufIn),
m_Out(std::wcout, m_BufOut),
m_Err(std::wcerr, m_BufErr),
m_Log(std::wclog, m_BufLog)
{
auto Color = colors::ConsoleColorToFarColor(F_LIGHTRED);
colors::make_transparent(Color.BackgroundColor);
m_BufErr.color(Color);
}
private:
consolebuf m_BufIn, m_BufOut, m_BufErr, m_BufLog;
io::wstreambuf_override m_In, m_Out, m_Err, m_Log;
};
|
/* Copyright (c) 2019 vesoft inc. All rights reserved.
*
* This source code is licensed under Apache 2.0 License,
* attached with Common Clause Condition 1.0, found in the LICENSES directory.
*/
#include "datamanlite/Slice.h"
namespace nebula {
namespace dataman {
namespace codec {
// 2 small internal utility functions, for efficient hex conversions
// and no need for snprintf, toupper etc...
// Originally from wdt/util/EncryptionUtils.cpp - for toString(true)/DecodeHex:
char toHex(unsigned char v) {
if (v <= 9) {
return '0' + v;
}
return 'A' + v - 10;
}
// most of the code is for validation/error check
int fromHex(char c) {
// toupper:
if (c >= 'a' && c <= 'f') {
c -= ('a' - 'A'); // aka 0x20
}
// validation
if (c < '0' || (c > '9' && (c < 'A' || c > 'F'))) {
return -1; // invalid not 0-9A-F hex char
}
if (c <= '9') {
return c - '0';
}
return c - 'A' + 10;
}
// Return a string that contains the copy of the referenced data.
std::string Slice::toString(bool hex) const {
std::string result; // RVO/NRVO/move
if (hex) {
result.reserve(2 * size_);
for (size_t i = 0; i < size_; ++i) {
unsigned char c = data_[i];
result.push_back(toHex(c >> 4));
result.push_back(toHex(c & 0xf));
}
return result;
} else {
result.assign(data_, size_);
return result;
}
}
// Originally from rocksdb/utilities/ldb_cmd.h
bool Slice::DecodeHex(std::string* result) const {
std::string::size_type len = size_;
if (len % 2) {
// Hex string must be even number of hex digits to get complete bytes back
return false;
}
if (!result) {
return false;
}
result->clear();
result->reserve(len / 2);
for (size_t i = 0; i < len;) {
int h1 = fromHex(data_[i++]);
if (h1 < 0) {
return false;
}
int h2 = fromHex(data_[i++]);
if (h2 < 0) {
return false;
}
result->push_back(static_cast<char>((h1 << 4) | h2));
}
return true;
}
} // namespace codec
} // namespace dataman
} // namespace nebula
|
// Copyright (c) 2012 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "remoting/host/plugin/host_script_object.h"
#include "base/bind.h"
#include "base/json/json_reader.h"
#include "base/json/json_writer.h"
#include "base/message_loop.h"
#include "base/message_loop/message_loop_proxy.h"
#include "base/strings/string_util.h"
#include "base/strings/stringprintf.h"
#include "base/strings/sys_string_conversions.h"
#include "base/strings/utf_string_conversions.h"
#include "base/threading/platform_thread.h"
#include "base/values.h"
#include "net/base/net_util.h"
#include "remoting/base/auth_token_util.h"
#include "remoting/base/auto_thread.h"
#include "remoting/base/rsa_key_pair.h"
#include "remoting/host/chromoting_host.h"
#include "remoting/host/chromoting_host_context.h"
#include "remoting/host/host_config.h"
#include "remoting/host/host_event_logger.h"
#include "remoting/host/host_secret.h"
#include "remoting/host/host_status_observer.h"
#include "remoting/host/it2me_desktop_environment.h"
#include "remoting/host/pin_hash.h"
#include "remoting/host/plugin/host_log_handler.h"
#include "remoting/host/policy_hack/policy_watcher.h"
#include "remoting/host/register_support_host_request.h"
#include "remoting/host/service_urls.h"
#include "remoting/host/session_manager_factory.h"
#include "remoting/jingle_glue/network_settings.h"
#include "remoting/jingle_glue/xmpp_signal_strategy.h"
#include "remoting/protocol/it2me_host_authenticator_factory.h"
#include "third_party/npapi/bindings/npruntime.h"
namespace remoting {
namespace {
// This is used for tagging system event logs.
const char kApplicationName[] = "chromoting";
const char* kAttrNameAccessCode = "accessCode";
const char* kAttrNameAccessCodeLifetime = "accessCodeLifetime";
const char* kAttrNameClient = "client";
const char* kAttrNameDaemonState = "daemonState";
const char* kAttrNameState = "state";
const char* kAttrNameLogDebugInfo = "logDebugInfo";
const char* kAttrNameOnNatTraversalPolicyChanged =
"onNatTraversalPolicyChanged";
const char* kAttrNameOnStateChanged = "onStateChanged";
const char* kAttrNameXmppServerAddress = "xmppServerAddress";
const char* kAttrNameXmppServerUseTls = "xmppServerUseTls";
const char* kAttrNameDirectoryBotJid = "directoryBotJid";
const char* kFuncNameConnect = "connect";
const char* kFuncNameDisconnect = "disconnect";
const char* kFuncNameLocalize = "localize";
const char* kFuncNameGetHostName = "getHostName";
const char* kFuncNameGetPinHash = "getPinHash";
const char* kFuncNameGenerateKeyPair = "generateKeyPair";
const char* kFuncNameUpdateDaemonConfig = "updateDaemonConfig";
const char* kFuncNameGetDaemonConfig = "getDaemonConfig";
const char* kFuncNameGetDaemonVersion = "getDaemonVersion";
const char* kFuncNameGetUsageStatsConsent = "getUsageStatsConsent";
const char* kFuncNameStartDaemon = "startDaemon";
const char* kFuncNameStopDaemon = "stopDaemon";
// States.
const char* kAttrNameDisconnected = "DISCONNECTED";
const char* kAttrNameStarting = "STARTING";
const char* kAttrNameRequestedAccessCode = "REQUESTED_ACCESS_CODE";
const char* kAttrNameReceivedAccessCode = "RECEIVED_ACCESS_CODE";
const char* kAttrNameConnected = "CONNECTED";
const char* kAttrNameDisconnecting = "DISCONNECTING";
const char* kAttrNameError = "ERROR";
const char* kAttrNameInvalidDomainError = "INVALID_DOMAIN_ERROR";
const int kMaxLoginAttempts = 5;
} // namespace
// Internal implementation of the plugin's It2Me host function.
class HostNPScriptObject::It2MeImpl
: public base::RefCountedThreadSafe<It2MeImpl>,
public HostStatusObserver {
public:
It2MeImpl(
scoped_ptr<ChromotingHostContext> context,
scoped_refptr<base::SingleThreadTaskRunner> plugin_task_runner,
base::WeakPtr<HostNPScriptObject> script_object,
const XmppSignalStrategy::XmppServerConfig& xmpp_server_config,
const std::string& directory_bot_jid);
// Methods called by the script object, from the plugin thread.
// Creates It2Me host structures and starts the host.
void Connect(const std::string& uid,
const std::string& auth_token,
const std::string& auth_service,
const UiStrings& ui_strings);
// Disconnects the host, ready for tear-down.
// Also called internally, from the network thread.
void Disconnect();
// Request a NAT policy notification.
void RequestNatPolicy();
// remoting::HostStatusObserver implementation.
virtual void OnAccessDenied(const std::string& jid) OVERRIDE;
virtual void OnClientAuthenticated(const std::string& jid) OVERRIDE;
virtual void OnClientDisconnected(const std::string& jid) OVERRIDE;
private:
friend class base::RefCountedThreadSafe<It2MeImpl>;
virtual ~It2MeImpl();
// Updates state of the host. Can be called only on the network thread.
void SetState(State state);
// Returns true if the host is connected.
bool IsConnected() const;
// Called by Connect() to check for policies and start connection process.
void ReadPolicyAndConnect(const std::string& uid,
const std::string& auth_token,
const std::string& auth_service);
// Called by ReadPolicyAndConnect once policies have been read.
void FinishConnect(const std::string& uid,
const std::string& auth_token,
const std::string& auth_service);
// Called when the support host registration completes.
void OnReceivedSupportID(bool success,
const std::string& support_id,
const base::TimeDelta& lifetime);
// Shuts down |host_| on the network thread and posts ShutdownOnUiThread()
// to shut down UI thread resources.
void ShutdownOnNetworkThread();
// Shuts down |desktop_environment_factory_| and |policy_watcher_| on
// the UI thread.
void ShutdownOnUiThread();
// Called when initial policies are read, and when they change.
void OnPolicyUpdate(scoped_ptr<base::DictionaryValue> policies);
// Handlers for NAT traversal and host domain policies.
void UpdateNatPolicy(bool nat_traversal_enabled);
void UpdateHostDomainPolicy(const std::string& host_domain);
// Caller supplied fields.
scoped_ptr<ChromotingHostContext> host_context_;
scoped_refptr<base::SingleThreadTaskRunner> plugin_task_runner_;
base::WeakPtr<HostNPScriptObject> script_object_;
XmppSignalStrategy::XmppServerConfig xmpp_server_config_;
std::string directory_bot_jid_;
State state_;
scoped_refptr<RsaKeyPair> host_key_pair_;
scoped_ptr<SignalStrategy> signal_strategy_;
scoped_ptr<RegisterSupportHostRequest> register_request_;
scoped_ptr<LogToServer> log_to_server_;
scoped_ptr<DesktopEnvironmentFactory> desktop_environment_factory_;
scoped_ptr<HostEventLogger> host_event_logger_;
scoped_ptr<ChromotingHost> host_;
int failed_login_attempts_;
scoped_ptr<policy_hack::PolicyWatcher> policy_watcher_;
// Host the current nat traversal policy setting.
bool nat_traversal_enabled_;
// The host domain policy setting.
std::string required_host_domain_;
// Indicates whether or not a policy has ever been read. This is to ensure
// that on startup, we do not accidentally start a connection before we have
// queried our policy restrictions.
bool policy_received_;
// On startup, it is possible to have Connect() called before the policy read
// is completed. Rather than just failing, we thunk the connection call so
// it can be executed after at least one successful policy read. This
// variable contains the thunk if it is necessary.
base::Closure pending_connect_;
DISALLOW_COPY_AND_ASSIGN(It2MeImpl);
};
HostNPScriptObject::It2MeImpl::It2MeImpl(
scoped_ptr<ChromotingHostContext> host_context,
scoped_refptr<base::SingleThreadTaskRunner> plugin_task_runner,
base::WeakPtr<HostNPScriptObject> script_object,
const XmppSignalStrategy::XmppServerConfig& xmpp_server_config,
const std::string& directory_bot_jid)
: host_context_(host_context.Pass()),
plugin_task_runner_(plugin_task_runner),
script_object_(script_object),
xmpp_server_config_(xmpp_server_config),
directory_bot_jid_(directory_bot_jid),
state_(kDisconnected),
failed_login_attempts_(0),
nat_traversal_enabled_(false),
policy_received_(false) {
DCHECK(plugin_task_runner_->BelongsToCurrentThread());
}
void HostNPScriptObject::It2MeImpl::Connect(
const std::string& uid,
const std::string& auth_token,
const std::string& auth_service,
const UiStrings& ui_strings) {
if (!host_context_->ui_task_runner()->BelongsToCurrentThread()) {
DCHECK(plugin_task_runner_->BelongsToCurrentThread());
host_context_->ui_task_runner()->PostTask(
FROM_HERE,
base::Bind(&It2MeImpl::Connect, this, uid, auth_token, auth_service,
ui_strings));
return;
}
desktop_environment_factory_.reset(new It2MeDesktopEnvironmentFactory(
host_context_->network_task_runner(),
host_context_->input_task_runner(),
host_context_->ui_task_runner(),
ui_strings));
// Start monitoring configured policies.
policy_watcher_.reset(
policy_hack::PolicyWatcher::Create(host_context_->network_task_runner()));
policy_watcher_->StartWatching(
base::Bind(&It2MeImpl::OnPolicyUpdate, this));
// Switch to the network thread to start the actual connection.
host_context_->network_task_runner()->PostTask(
FROM_HERE, base::Bind(
&It2MeImpl::ReadPolicyAndConnect, this,
uid, auth_token, auth_service));
}
void HostNPScriptObject::It2MeImpl::Disconnect() {
if (!host_context_->network_task_runner()->BelongsToCurrentThread()) {
DCHECK(plugin_task_runner_->BelongsToCurrentThread());
host_context_->network_task_runner()->PostTask(
FROM_HERE, base::Bind(&It2MeImpl::Disconnect, this));
return;
}
switch (state_) {
case kDisconnected:
ShutdownOnNetworkThread();
return;
case kStarting:
SetState(kDisconnecting);
SetState(kDisconnected);
ShutdownOnNetworkThread();
return;
case kDisconnecting:
return;
default:
SetState(kDisconnecting);
if (!host_) {
SetState(kDisconnected);
ShutdownOnNetworkThread();
return;
}
// Deleting the host destroys SignalStrategy synchronously, but
// SignalStrategy::Listener handlers are not allowed to destroy
// SignalStrategy, so post task to destroy the host later.
host_context_->network_task_runner()->PostTask(
FROM_HERE, base::Bind(&It2MeImpl::ShutdownOnNetworkThread, this));
return;
}
}
void HostNPScriptObject::It2MeImpl::RequestNatPolicy() {
if (!host_context_->network_task_runner()->BelongsToCurrentThread()) {
DCHECK(plugin_task_runner_->BelongsToCurrentThread());
host_context_->network_task_runner()->PostTask(
FROM_HERE, base::Bind(&It2MeImpl::RequestNatPolicy, this));
return;
}
if (policy_received_)
UpdateNatPolicy(nat_traversal_enabled_);
}
void HostNPScriptObject::It2MeImpl::ReadPolicyAndConnect(
const std::string& uid,
const std::string& auth_token,
const std::string& auth_service) {
DCHECK(host_context_->network_task_runner()->BelongsToCurrentThread());
SetState(kStarting);
// Only proceed to FinishConnect() if at least one policy update has been
// received.
if (policy_received_) {
FinishConnect(uid, auth_token, auth_service);
} else {
// Otherwise, create the policy watcher, and thunk the connect.
pending_connect_ =
base::Bind(&It2MeImpl::FinishConnect, this,
uid, auth_token, auth_service);
}
}
void HostNPScriptObject::It2MeImpl::FinishConnect(
const std::string& uid,
const std::string& auth_token,
const std::string& auth_service) {
DCHECK(host_context_->network_task_runner()->BelongsToCurrentThread());
if (state_ != kStarting) {
// Host has been stopped while we were fetching policy.
return;
}
// Check the host domain policy.
if (!required_host_domain_.empty() &&
!EndsWith(uid, std::string("@") + required_host_domain_, false)) {
SetState(kInvalidDomainError);
return;
}
// Generate a key pair for the Host to use.
// TODO(wez): Move this to the worker thread.
host_key_pair_ = RsaKeyPair::Generate();
// Create XMPP connection.
scoped_ptr<SignalStrategy> signal_strategy(
new XmppSignalStrategy(host_context_->url_request_context_getter(),
uid, auth_token, auth_service,
xmpp_server_config_));
// Request registration of the host for support.
scoped_ptr<RegisterSupportHostRequest> register_request(
new RegisterSupportHostRequest(
signal_strategy.get(), host_key_pair_, directory_bot_jid_,
base::Bind(&It2MeImpl::OnReceivedSupportID,
base::Unretained(this))));
// Beyond this point nothing can fail, so save the config and request.
signal_strategy_ = signal_strategy.Pass();
register_request_ = register_request.Pass();
// If NAT traversal is off then limit port range to allow firewall pin-holing.
LOG(INFO) << "NAT state: " << nat_traversal_enabled_;
NetworkSettings network_settings(
nat_traversal_enabled_ ?
NetworkSettings::NAT_TRAVERSAL_ENABLED :
NetworkSettings::NAT_TRAVERSAL_DISABLED);
if (!nat_traversal_enabled_) {
network_settings.min_port = NetworkSettings::kDefaultMinPort;
network_settings.max_port = NetworkSettings::kDefaultMaxPort;
}
// Create the host.
host_.reset(new ChromotingHost(
signal_strategy_.get(),
desktop_environment_factory_.get(),
CreateHostSessionManager(network_settings,
host_context_->url_request_context_getter()),
host_context_->audio_task_runner(),
host_context_->input_task_runner(),
host_context_->video_capture_task_runner(),
host_context_->video_encode_task_runner(),
host_context_->network_task_runner(),
host_context_->ui_task_runner()));
host_->AddStatusObserver(this);
log_to_server_.reset(
new LogToServer(host_->AsWeakPtr(), ServerLogEntry::IT2ME,
signal_strategy_.get(), directory_bot_jid_));
// Disable audio by default.
// TODO(sergeyu): Add UI to enable it.
scoped_ptr<protocol::CandidateSessionConfig> protocol_config =
protocol::CandidateSessionConfig::CreateDefault();
protocol::CandidateSessionConfig::DisableAudioChannel(protocol_config.get());
host_->set_protocol_config(protocol_config.Pass());
// Create event logger.
host_event_logger_ =
HostEventLogger::Create(host_->AsWeakPtr(), kApplicationName);
// Connect signaling and start the host.
signal_strategy_->Connect();
host_->Start(uid);
SetState(kRequestedAccessCode);
return;
}
void HostNPScriptObject::It2MeImpl::ShutdownOnNetworkThread() {
DCHECK(host_context_->network_task_runner()->BelongsToCurrentThread());
DCHECK(state_ == kDisconnecting || state_ == kDisconnected);
if (state_ == kDisconnecting) {
host_event_logger_.reset();
host_->RemoveStatusObserver(this);
host_.reset();
register_request_.reset();
log_to_server_.reset();
signal_strategy_.reset();
SetState(kDisconnected);
}
host_context_->ui_task_runner()->PostTask(
FROM_HERE, base::Bind(&It2MeImpl::ShutdownOnUiThread, this));
}
void HostNPScriptObject::It2MeImpl::ShutdownOnUiThread() {
DCHECK(host_context_->ui_task_runner()->BelongsToCurrentThread());
// Destroy the DesktopEnvironmentFactory, to free thread references.
desktop_environment_factory_.reset();
// Stop listening for policy updates.
if (policy_watcher_.get()) {
base::WaitableEvent policy_watcher_stopped_(true, false);
policy_watcher_->StopWatching(&policy_watcher_stopped_);
policy_watcher_stopped_.Wait();
policy_watcher_.reset();
}
}
void HostNPScriptObject::It2MeImpl::OnAccessDenied(const std::string& jid) {
DCHECK(host_context_->network_task_runner()->BelongsToCurrentThread());
++failed_login_attempts_;
if (failed_login_attempts_ == kMaxLoginAttempts) {
Disconnect();
}
}
void HostNPScriptObject::It2MeImpl::OnClientAuthenticated(
const std::string& jid) {
DCHECK(host_context_->network_task_runner()->BelongsToCurrentThread());
if (state_ == kDisconnecting) {
// Ignore the new connection if we are disconnecting.
return;
}
if (state_ == kConnected) {
// If we already connected another client then one of the connections may be
// an attacker, so both are suspect and we have to reject the second
// connection and shutdown the host.
host_->RejectAuthenticatingClient();
Disconnect();
return;
}
std::string client_username = jid;
size_t pos = client_username.find('/');
if (pos != std::string::npos)
client_username.replace(pos, std::string::npos, "");
LOG(INFO) << "Client " << client_username << " connected.";
// Pass the client user name to the script object before changing state.
plugin_task_runner_->PostTask(
FROM_HERE, base::Bind(&HostNPScriptObject::StoreClientUsername,
script_object_, client_username));
SetState(kConnected);
}
void HostNPScriptObject::It2MeImpl::OnClientDisconnected(
const std::string& jid) {
DCHECK(host_context_->network_task_runner()->BelongsToCurrentThread());
// Pass the client user name to the script object before changing state.
plugin_task_runner_->PostTask(
FROM_HERE, base::Bind(&HostNPScriptObject::StoreClientUsername,
script_object_, std::string()));
Disconnect();
}
void HostNPScriptObject::It2MeImpl::OnPolicyUpdate(
scoped_ptr<base::DictionaryValue> policies) {
DCHECK(host_context_->network_task_runner()->BelongsToCurrentThread());
bool nat_policy;
if (policies->GetBoolean(policy_hack::PolicyWatcher::kNatPolicyName,
&nat_policy)) {
UpdateNatPolicy(nat_policy);
}
std::string host_domain;
if (policies->GetString(policy_hack::PolicyWatcher::kHostDomainPolicyName,
&host_domain)) {
UpdateHostDomainPolicy(host_domain);
}
policy_received_ = true;
if (!pending_connect_.is_null()) {
pending_connect_.Run();
pending_connect_.Reset();
}
}
void HostNPScriptObject::It2MeImpl::UpdateNatPolicy(
bool nat_traversal_enabled) {
DCHECK(host_context_->network_task_runner()->BelongsToCurrentThread());
VLOG(2) << "UpdateNatPolicy: " << nat_traversal_enabled;
// When transitioning from enabled to disabled, force disconnect any
// existing session.
if (nat_traversal_enabled_ && !nat_traversal_enabled && IsConnected()) {
Disconnect();
}
nat_traversal_enabled_ = nat_traversal_enabled;
// Notify the web-app of the policy setting.
plugin_task_runner_->PostTask(
FROM_HERE, base::Bind(&HostNPScriptObject::NotifyNatPolicyChanged,
script_object_, nat_traversal_enabled_));
}
void HostNPScriptObject::It2MeImpl::UpdateHostDomainPolicy(
const std::string& host_domain) {
DCHECK(host_context_->network_task_runner()->BelongsToCurrentThread());
VLOG(2) << "UpdateHostDomainPolicy: " << host_domain;
// When setting a host domain policy, force disconnect any existing session.
if (!host_domain.empty() && IsConnected()) {
Disconnect();
}
required_host_domain_ = host_domain;
}
HostNPScriptObject::It2MeImpl::~It2MeImpl() {
// Check that resources that need to be torn down on the UI thread are gone.
DCHECK(!desktop_environment_factory_.get());
DCHECK(!policy_watcher_.get());
}
void HostNPScriptObject::It2MeImpl::SetState(State state) {
DCHECK(host_context_->network_task_runner()->BelongsToCurrentThread());
switch (state_) {
case kDisconnected:
DCHECK(state == kStarting ||
state == kError) << state;
break;
case kStarting:
DCHECK(state == kRequestedAccessCode ||
state == kDisconnecting ||
state == kError ||
state == kInvalidDomainError) << state;
break;
case kRequestedAccessCode:
DCHECK(state == kReceivedAccessCode ||
state == kDisconnecting ||
state == kError) << state;
break;
case kReceivedAccessCode:
DCHECK(state == kConnected ||
state == kDisconnecting ||
state == kError) << state;
break;
case kConnected:
DCHECK(state == kDisconnecting ||
state == kDisconnected ||
state == kError) << state;
break;
case kDisconnecting:
DCHECK(state == kDisconnected) << state;
break;
case kError:
DCHECK(state == kDisconnecting) << state;
break;
case kInvalidDomainError:
DCHECK(state == kDisconnecting) << state;
break;
};
state_ = state;
// Post a state-change notification to the web-app.
plugin_task_runner_->PostTask(
FROM_HERE, base::Bind(&HostNPScriptObject::NotifyStateChanged,
script_object_, state));
}
bool HostNPScriptObject::It2MeImpl::IsConnected() const {
return state_ == kRequestedAccessCode || state_ == kReceivedAccessCode ||
state_ == kConnected;
}
void HostNPScriptObject::It2MeImpl::OnReceivedSupportID(
bool success,
const std::string& support_id,
const base::TimeDelta& lifetime) {
DCHECK(host_context_->network_task_runner()->BelongsToCurrentThread());
if (!success) {
SetState(kError);
Disconnect();
return;
}
std::string host_secret = GenerateSupportHostSecret();
std::string access_code = support_id + host_secret;
std::string local_certificate = host_key_pair_->GenerateCertificate();
if (local_certificate.empty()) {
LOG(ERROR) << "Failed to generate host certificate.";
SetState(kError);
Disconnect();
return;
}
scoped_ptr<protocol::AuthenticatorFactory> factory(
new protocol::It2MeHostAuthenticatorFactory(
local_certificate, host_key_pair_, access_code));
host_->SetAuthenticatorFactory(factory.Pass());
// Pass the Access Code to the script object before changing state.
plugin_task_runner_->PostTask(
FROM_HERE, base::Bind(&HostNPScriptObject::StoreAccessCode,
script_object_, access_code, lifetime));
SetState(kReceivedAccessCode);
}
HostNPScriptObject::HostNPScriptObject(
NPP plugin,
NPObject* parent,
scoped_refptr<AutoThreadTaskRunner> plugin_task_runner)
: plugin_(plugin),
parent_(parent),
plugin_task_runner_(plugin_task_runner),
am_currently_logging_(false),
state_(kDisconnected),
daemon_controller_(DaemonController::Create()),
weak_factory_(this),
weak_ptr_(weak_factory_.GetWeakPtr()) {
DCHECK(plugin_task_runner_->BelongsToCurrentThread());
// Set the thread task runner for the plugin thread so that timers and other
// code using |base::ThreadTaskRunnerHandle| could be used on the plugin
// thread.
//
// If component build is used, Chrome and the plugin may end up sharing base
// binary. This means that the instance of |base::ThreadTaskRunnerHandle|
// created by Chrome for the current thread is shared as well. This routinely
// happens in the development setting so the below check for
// |!base::ThreadTaskRunnerHandle::IsSet()| is a hack/workaround allowing this
// configuration to work. It lets the plugin to access Chrome's message loop
// directly via |base::ThreadTaskRunnerHandle|. This is safe as long as both
// Chrome and the plugin are built from the same version of the sources.
if (!base::ThreadTaskRunnerHandle::IsSet()) {
plugin_task_runner_handle_.reset(
new base::ThreadTaskRunnerHandle(plugin_task_runner_));
}
ServiceUrls* service_urls = ServiceUrls::GetInstance();
bool xmpp_server_valid = net::ParseHostAndPort(
service_urls->xmpp_server_address(),
&xmpp_server_config_.host, &xmpp_server_config_.port);
// For the plugin, this is always the default address, which must be valid.
DCHECK(xmpp_server_valid);
xmpp_server_config_.use_tls = service_urls->xmpp_server_use_tls();
directory_bot_jid_ = service_urls->directory_bot_jid();
// Create worker thread for encryption key generation.
worker_thread_ = AutoThread::Create("ChromotingWorkerThread",
plugin_task_runner_);
}
HostNPScriptObject::~HostNPScriptObject() {
DCHECK(plugin_task_runner_->BelongsToCurrentThread());
HostLogHandler::UnregisterLoggingScriptObject(this);
// Stop the It2Me host if the caller forgot to.
if (it2me_impl_.get()) {
it2me_impl_->Disconnect();
it2me_impl_ = NULL;
}
}
bool HostNPScriptObject::HasMethod(const std::string& method_name) {
VLOG(2) << "HasMethod " << method_name;
DCHECK(plugin_task_runner_->BelongsToCurrentThread());
return (method_name == kFuncNameConnect ||
method_name == kFuncNameDisconnect ||
method_name == kFuncNameLocalize ||
method_name == kFuncNameGetHostName ||
method_name == kFuncNameGetPinHash ||
method_name == kFuncNameGenerateKeyPair ||
method_name == kFuncNameUpdateDaemonConfig ||
method_name == kFuncNameGetDaemonConfig ||
method_name == kFuncNameGetDaemonVersion ||
method_name == kFuncNameGetUsageStatsConsent ||
method_name == kFuncNameStartDaemon ||
method_name == kFuncNameStopDaemon);
}
bool HostNPScriptObject::InvokeDefault(const NPVariant* args,
uint32_t arg_count,
NPVariant* result) {
VLOG(2) << "InvokeDefault";
DCHECK(plugin_task_runner_->BelongsToCurrentThread());
SetException("exception during default invocation");
return false;
}
bool HostNPScriptObject::Invoke(const std::string& method_name,
const NPVariant* args,
uint32_t arg_count,
NPVariant* result) {
VLOG(2) << "Invoke " << method_name;
DCHECK(plugin_task_runner_->BelongsToCurrentThread());
if (method_name == kFuncNameConnect) {
return Connect(args, arg_count, result);
} else if (method_name == kFuncNameDisconnect) {
return Disconnect(args, arg_count, result);
} else if (method_name == kFuncNameLocalize) {
return Localize(args, arg_count, result);
} else if (method_name == kFuncNameGetHostName) {
return GetHostName(args, arg_count, result);
} else if (method_name == kFuncNameGetPinHash) {
return GetPinHash(args, arg_count, result);
} else if (method_name == kFuncNameGenerateKeyPair) {
return GenerateKeyPair(args, arg_count, result);
} else if (method_name == kFuncNameUpdateDaemonConfig) {
return UpdateDaemonConfig(args, arg_count, result);
} else if (method_name == kFuncNameGetDaemonConfig) {
return GetDaemonConfig(args, arg_count, result);
} else if (method_name == kFuncNameGetDaemonVersion) {
return GetDaemonVersion(args, arg_count, result);
} else if (method_name == kFuncNameGetUsageStatsConsent) {
return GetUsageStatsConsent(args, arg_count, result);
} else if (method_name == kFuncNameStartDaemon) {
return StartDaemon(args, arg_count, result);
} else if (method_name == kFuncNameStopDaemon) {
return StopDaemon(args, arg_count, result);
} else {
SetException("Invoke: unknown method " + method_name);
return false;
}
}
bool HostNPScriptObject::HasProperty(const std::string& property_name) {
VLOG(2) << "HasProperty " << property_name;
DCHECK(plugin_task_runner_->BelongsToCurrentThread());
return (property_name == kAttrNameAccessCode ||
property_name == kAttrNameAccessCodeLifetime ||
property_name == kAttrNameClient ||
property_name == kAttrNameDaemonState ||
property_name == kAttrNameState ||
property_name == kAttrNameLogDebugInfo ||
property_name == kAttrNameOnNatTraversalPolicyChanged ||
property_name == kAttrNameOnStateChanged ||
property_name == kAttrNameDisconnected ||
property_name == kAttrNameStarting ||
property_name == kAttrNameRequestedAccessCode ||
property_name == kAttrNameReceivedAccessCode ||
property_name == kAttrNameConnected ||
property_name == kAttrNameDisconnecting ||
property_name == kAttrNameError ||
property_name == kAttrNameXmppServerAddress ||
property_name == kAttrNameXmppServerUseTls ||
property_name == kAttrNameDirectoryBotJid);
}
bool HostNPScriptObject::GetProperty(const std::string& property_name,
NPVariant* result) {
VLOG(2) << "GetProperty " << property_name;
DCHECK(plugin_task_runner_->BelongsToCurrentThread());
if (!result) {
SetException("GetProperty: NULL result");
return false;
}
if (property_name == kAttrNameOnNatTraversalPolicyChanged) {
OBJECT_TO_NPVARIANT(on_nat_traversal_policy_changed_func_.get(), *result);
return true;
} else if (property_name == kAttrNameOnStateChanged) {
OBJECT_TO_NPVARIANT(on_state_changed_func_.get(), *result);
return true;
} else if (property_name == kAttrNameLogDebugInfo) {
OBJECT_TO_NPVARIANT(log_debug_info_func_.get(), *result);
return true;
} else if (property_name == kAttrNameState) {
INT32_TO_NPVARIANT(state_, *result);
return true;
} else if (property_name == kAttrNameAccessCode) {
*result = NPVariantFromString(access_code_);
return true;
} else if (property_name == kAttrNameAccessCodeLifetime) {
INT32_TO_NPVARIANT(access_code_lifetime_.InSeconds(), *result);
return true;
} else if (property_name == kAttrNameClient) {
*result = NPVariantFromString(client_username_);
return true;
} else if (property_name == kAttrNameDaemonState) {
INT32_TO_NPVARIANT(daemon_controller_->GetState(), *result);
return true;
} else if (property_name == kAttrNameDisconnected) {
INT32_TO_NPVARIANT(kDisconnected, *result);
return true;
} else if (property_name == kAttrNameStarting) {
INT32_TO_NPVARIANT(kStarting, *result);
return true;
} else if (property_name == kAttrNameRequestedAccessCode) {
INT32_TO_NPVARIANT(kRequestedAccessCode, *result);
return true;
} else if (property_name == kAttrNameReceivedAccessCode) {
INT32_TO_NPVARIANT(kReceivedAccessCode, *result);
return true;
} else if (property_name == kAttrNameConnected) {
INT32_TO_NPVARIANT(kConnected, *result);
return true;
} else if (property_name == kAttrNameDisconnecting) {
INT32_TO_NPVARIANT(kDisconnecting, *result);
return true;
} else if (property_name == kAttrNameError) {
INT32_TO_NPVARIANT(kError, *result);
return true;
} else if (property_name == kAttrNameInvalidDomainError) {
INT32_TO_NPVARIANT(kInvalidDomainError, *result);
return true;
} else if (property_name == kAttrNameXmppServerAddress) {
*result = NPVariantFromString(base::StringPrintf(
"%s:%u", xmpp_server_config_.host.c_str(), xmpp_server_config_.port));
return true;
} else if (property_name == kAttrNameXmppServerUseTls) {
BOOLEAN_TO_NPVARIANT(xmpp_server_config_.use_tls, *result);
return true;
} else if (property_name == kAttrNameDirectoryBotJid) {
*result = NPVariantFromString(directory_bot_jid_);
return true;
} else {
SetException("GetProperty: unsupported property " + property_name);
return false;
}
}
bool HostNPScriptObject::SetProperty(const std::string& property_name,
const NPVariant* value) {
VLOG(2) << "SetProperty " << property_name;
DCHECK(plugin_task_runner_->BelongsToCurrentThread());
if (property_name == kAttrNameOnNatTraversalPolicyChanged) {
if (NPVARIANT_IS_OBJECT(*value)) {
on_nat_traversal_policy_changed_func_ = NPVARIANT_TO_OBJECT(*value);
if (it2me_impl_.get()) {
// Ask the It2Me implementation to notify the web-app of the policy.
it2me_impl_->RequestNatPolicy();
}
return true;
} else {
SetException("SetProperty: unexpected type for property " +
property_name);
}
return false;
}
if (property_name == kAttrNameOnStateChanged) {
if (NPVARIANT_IS_OBJECT(*value)) {
on_state_changed_func_ = NPVARIANT_TO_OBJECT(*value);
return true;
} else {
SetException("SetProperty: unexpected type for property " +
property_name);
}
return false;
}
if (property_name == kAttrNameLogDebugInfo) {
if (NPVARIANT_IS_OBJECT(*value)) {
log_debug_info_func_ = NPVARIANT_TO_OBJECT(*value);
HostLogHandler::RegisterLoggingScriptObject(this);
return true;
} else {
SetException("SetProperty: unexpected type for property " +
property_name);
}
return false;
}
#if !defined(NDEBUG)
if (property_name == kAttrNameXmppServerAddress) {
if (NPVARIANT_IS_STRING(*value)) {
std::string address = StringFromNPVariant(*value);
bool xmpp_server_valid = net::ParseHostAndPort(
address, &xmpp_server_config_.host, &xmpp_server_config_.port);
if (xmpp_server_valid) {
return true;
} else {
SetException("SetProperty: invalid value for property " +
property_name);
}
} else {
SetException("SetProperty: unexpected type for property " +
property_name);
}
return false;
}
if (property_name == kAttrNameXmppServerUseTls) {
if (NPVARIANT_IS_BOOLEAN(*value)) {
xmpp_server_config_.use_tls = NPVARIANT_TO_BOOLEAN(*value);
return true;
} else {
SetException("SetProperty: unexpected type for property " +
property_name);
}
return false;
}
if (property_name == kAttrNameDirectoryBotJid) {
if (NPVARIANT_IS_STRING(*value)) {
directory_bot_jid_ = StringFromNPVariant(*value);
return true;
} else {
SetException("SetProperty: unexpected type for property " +
property_name);
}
return false;
}
#endif // !defined(NDEBUG)
return false;
}
bool HostNPScriptObject::RemoveProperty(const std::string& property_name) {
VLOG(2) << "RemoveProperty " << property_name;
DCHECK(plugin_task_runner_->BelongsToCurrentThread());
return false;
}
bool HostNPScriptObject::Enumerate(std::vector<std::string>* values) {
VLOG(2) << "Enumerate";
DCHECK(plugin_task_runner_->BelongsToCurrentThread());
const char* entries[] = {
kAttrNameAccessCode,
kAttrNameState,
kAttrNameLogDebugInfo,
kAttrNameOnStateChanged,
kAttrNameDisconnected,
kAttrNameStarting,
kAttrNameRequestedAccessCode,
kAttrNameReceivedAccessCode,
kAttrNameConnected,
kAttrNameDisconnecting,
kAttrNameError,
kAttrNameXmppServerAddress,
kAttrNameXmppServerUseTls,
kAttrNameDirectoryBotJid,
kFuncNameConnect,
kFuncNameDisconnect,
kFuncNameLocalize,
kFuncNameGetHostName,
kFuncNameGetPinHash,
kFuncNameGenerateKeyPair,
kFuncNameUpdateDaemonConfig,
kFuncNameGetDaemonConfig,
kFuncNameGetDaemonVersion,
kFuncNameGetUsageStatsConsent,
kFuncNameStartDaemon,
kFuncNameStopDaemon
};
for (size_t i = 0; i < arraysize(entries); ++i) {
values->push_back(entries[i]);
}
return true;
}
// string uid, string auth_token
bool HostNPScriptObject::Connect(const NPVariant* args,
uint32_t arg_count,
NPVariant* result) {
DCHECK(plugin_task_runner_->BelongsToCurrentThread());
LOG(INFO) << "Connecting...";
if (arg_count != 2) {
SetException("connect: bad number of arguments");
return false;
}
if (it2me_impl_.get()) {
SetException("connect: can be called only when disconnected");
return false;
}
std::string uid = StringFromNPVariant(args[0]);
if (uid.empty()) {
SetException("connect: bad uid argument");
return false;
}
std::string auth_service_with_token = StringFromNPVariant(args[1]);
std::string auth_token;
std::string auth_service;
ParseAuthTokenWithService(auth_service_with_token, &auth_token,
&auth_service);
if (auth_token.empty()) {
SetException("connect: auth_service_with_token argument has empty token");
return false;
}
// Create threads for the Chromoting host & desktop environment to use.
scoped_ptr<ChromotingHostContext> host_context =
ChromotingHostContext::Create(plugin_task_runner_);
if (!host_context) {
SetException("connect: failed to start threads");
return false;
}
// Create the It2Me host implementation and start connecting.
it2me_impl_ = new It2MeImpl(
host_context.Pass(), plugin_task_runner_, weak_ptr_,
xmpp_server_config_, directory_bot_jid_);
it2me_impl_->Connect(uid, auth_token, auth_service, ui_strings_);
return true;
}
bool HostNPScriptObject::Disconnect(const NPVariant* args,
uint32_t arg_count,
NPVariant* result) {
DCHECK(plugin_task_runner_->BelongsToCurrentThread());
if (arg_count != 0) {
SetException("disconnect: bad number of arguments");
return false;
}
if (it2me_impl_.get()) {
it2me_impl_->Disconnect();
it2me_impl_ = NULL;
}
return true;
}
bool HostNPScriptObject::Localize(const NPVariant* args,
uint32_t arg_count,
NPVariant* result) {
DCHECK(plugin_task_runner_->BelongsToCurrentThread());
if (arg_count != 1) {
SetException("localize: bad number of arguments");
return false;
}
if (NPVARIANT_IS_OBJECT(args[0])) {
ScopedRefNPObject localize_func(NPVARIANT_TO_OBJECT(args[0]));
LocalizeStrings(localize_func.get());
return true;
} else {
SetException("localize: unexpected type for argument 1");
return false;
}
}
bool HostNPScriptObject::GetHostName(const NPVariant* args,
uint32_t arg_count,
NPVariant* result) {
if (arg_count != 1) {
SetException("getHostName: bad number of arguments");
return false;
}
ScopedRefNPObject callback_obj(ObjectFromNPVariant(args[0]));
if (!callback_obj.get()) {
SetException("getHostName: invalid callback parameter");
return false;
}
NPVariant host_name_val = NPVariantFromString(net::GetHostName());
InvokeAndIgnoreResult(callback_obj.get(), &host_name_val, 1);
g_npnetscape_funcs->releasevariantvalue(&host_name_val);
return true;
}
bool HostNPScriptObject::GetPinHash(const NPVariant* args,
uint32_t arg_count,
NPVariant* result) {
if (arg_count != 3) {
SetException("getPinHash: bad number of arguments");
return false;
}
std::string host_id = StringFromNPVariant(args[0]);
if (host_id.empty()) {
SetException("getPinHash: bad hostId parameter");
return false;
}
if (!NPVARIANT_IS_STRING(args[1])) {
SetException("getPinHash: bad pin parameter");
return false;
}
std::string pin = StringFromNPVariant(args[1]);
ScopedRefNPObject callback_obj(ObjectFromNPVariant(args[2]));
if (!callback_obj.get()) {
SetException("getPinHash: invalid callback parameter");
return false;
}
NPVariant pin_hash_val = NPVariantFromString(
remoting::MakeHostPinHash(host_id, pin));
InvokeAndIgnoreResult(callback_obj.get(), &pin_hash_val, 1);
g_npnetscape_funcs->releasevariantvalue(&pin_hash_val);
return true;
}
bool HostNPScriptObject::GenerateKeyPair(const NPVariant* args,
uint32_t arg_count,
NPVariant* result) {
if (arg_count != 1) {
SetException("generateKeyPair: bad number of arguments");
return false;
}
ScopedRefNPObject callback_obj(ObjectFromNPVariant(args[0]));
if (!callback_obj.get()) {
SetException("generateKeyPair: invalid callback parameter");
return false;
}
// TODO(wez): HostNPScriptObject needn't be touched on worker
// thread, so make DoGenerateKeyPair static and pass it a callback
// to run (crbug.com/156257).
worker_thread_->PostTask(
FROM_HERE, base::Bind(&HostNPScriptObject::DoGenerateKeyPair,
base::Unretained(this), callback_obj));
return true;
}
bool HostNPScriptObject::UpdateDaemonConfig(const NPVariant* args,
uint32_t arg_count,
NPVariant* result) {
if (arg_count != 2) {
SetException("updateDaemonConfig: bad number of arguments");
return false;
}
std::string config_str = StringFromNPVariant(args[0]);
scoped_ptr<base::Value> config(
base::JSONReader::Read(config_str, base::JSON_ALLOW_TRAILING_COMMAS));
if (config_str.empty() || !config.get() ||
!config->IsType(base::Value::TYPE_DICTIONARY)) {
SetException("updateDaemonConfig: bad config parameter");
return false;
}
scoped_ptr<base::DictionaryValue> config_dict(
reinterpret_cast<base::DictionaryValue*>(config.release()));
ScopedRefNPObject callback_obj(ObjectFromNPVariant(args[1]));
if (!callback_obj.get()) {
SetException("updateDaemonConfig: invalid callback parameter");
return false;
}
if (config_dict->HasKey(kHostIdConfigPath) ||
config_dict->HasKey(kXmppLoginConfigPath)) {
SetException("updateDaemonConfig: trying to update immutable config "
"parameters");
return false;
}
// TODO(wez): Pass a static method here, that will post the result
// back to us on the right thread (crbug.com/156257).
daemon_controller_->UpdateConfig(
config_dict.Pass(),
base::Bind(&HostNPScriptObject::InvokeAsyncResultCallback,
base::Unretained(this), callback_obj));
return true;
}
bool HostNPScriptObject::GetDaemonConfig(const NPVariant* args,
uint32_t arg_count,
NPVariant* result) {
if (arg_count != 1) {
SetException("getDaemonConfig: bad number of arguments");
return false;
}
ScopedRefNPObject callback_obj(ObjectFromNPVariant(args[0]));
if (!callback_obj.get()) {
SetException("getDaemonConfig: invalid callback parameter");
return false;
}
// TODO(wez): Pass a static method here, that will post the result
// back to us on the right thread (crbug.com/156257).
daemon_controller_->GetConfig(
base::Bind(&HostNPScriptObject::InvokeGetDaemonConfigCallback,
base::Unretained(this), callback_obj));
return true;
}
bool HostNPScriptObject::GetDaemonVersion(const NPVariant* args,
uint32_t arg_count,
NPVariant* result) {
if (arg_count != 1) {
SetException("getDaemonVersion: bad number of arguments");
return false;
}
ScopedRefNPObject callback_obj(ObjectFromNPVariant(args[0]));
if (!callback_obj.get()) {
SetException("getDaemonVersion: invalid callback parameter");
return false;
}
// TODO(wez): Pass a static method here, that will post the result
// back to us on the right thread (crbug.com/156257).
daemon_controller_->GetVersion(
base::Bind(&HostNPScriptObject::InvokeGetDaemonVersionCallback,
base::Unretained(this), callback_obj));
return true;
}
bool HostNPScriptObject::GetUsageStatsConsent(const NPVariant* args,
uint32_t arg_count,
NPVariant* result) {
if (arg_count != 1) {
SetException("getUsageStatsConsent: bad number of arguments");
return false;
}
ScopedRefNPObject callback_obj(ObjectFromNPVariant(args[0]));
if (!callback_obj.get()) {
SetException("getUsageStatsConsent: invalid callback parameter");
return false;
}
// TODO(wez): Pass a static method here, that will post the result
// back to us on the right thread (crbug.com/156257).
daemon_controller_->GetUsageStatsConsent(
base::Bind(&HostNPScriptObject::InvokeGetUsageStatsConsentCallback,
base::Unretained(this), callback_obj));
return true;
}
bool HostNPScriptObject::StartDaemon(const NPVariant* args,
uint32_t arg_count,
NPVariant* result) {
DCHECK(plugin_task_runner_->BelongsToCurrentThread());
if (arg_count != 3) {
SetException("startDaemon: bad number of arguments");
return false;
}
std::string config_str = StringFromNPVariant(args[0]);
scoped_ptr<base::Value> config(
base::JSONReader::Read(config_str, base::JSON_ALLOW_TRAILING_COMMAS));
if (config_str.empty() || !config.get() ||
!config->IsType(base::Value::TYPE_DICTIONARY)) {
SetException("startDaemon: bad config parameter");
return false;
}
scoped_ptr<base::DictionaryValue> config_dict(
reinterpret_cast<base::DictionaryValue*>(config.release()));
if (!NPVARIANT_IS_BOOLEAN(args[1])) {
SetException("startDaemon: invalid consent parameter");
return false;
}
ScopedRefNPObject callback_obj(ObjectFromNPVariant(args[2]));
if (!callback_obj.get()) {
SetException("startDaemon: invalid callback parameter");
return false;
}
// TODO(wez): Pass a static method here, that will post the result
// back to us on the right thread (crbug.com/156257).
daemon_controller_->SetConfigAndStart(
config_dict.Pass(),
NPVARIANT_TO_BOOLEAN(args[1]),
base::Bind(&HostNPScriptObject::InvokeAsyncResultCallback,
base::Unretained(this), callback_obj));
return true;
}
bool HostNPScriptObject::StopDaemon(const NPVariant* args,
uint32_t arg_count,
NPVariant* result) {
DCHECK(plugin_task_runner_->BelongsToCurrentThread());
if (arg_count != 1) {
SetException("stopDaemon: bad number of arguments");
return false;
}
ScopedRefNPObject callback_obj(ObjectFromNPVariant(args[0]));
if (!callback_obj.get()) {
SetException("stopDaemon: invalid callback parameter");
return false;
}
// TODO(wez): Pass a static method here, that will post the result
// back to us on the right thread (crbug.com/156257).
daemon_controller_->Stop(
base::Bind(&HostNPScriptObject::InvokeAsyncResultCallback,
base::Unretained(this), callback_obj));
return true;
}
void HostNPScriptObject::NotifyStateChanged(State state) {
DCHECK(plugin_task_runner_->BelongsToCurrentThread());
state_ = state;
if (on_state_changed_func_.get()) {
NPVariant state_var;
INT32_TO_NPVARIANT(state, state_var);
InvokeAndIgnoreResult(on_state_changed_func_.get(), &state_var, 1);
}
}
void HostNPScriptObject::NotifyNatPolicyChanged(bool nat_traversal_enabled) {
DCHECK(plugin_task_runner_->BelongsToCurrentThread());
if (on_nat_traversal_policy_changed_func_.get()) {
NPVariant policy;
BOOLEAN_TO_NPVARIANT(nat_traversal_enabled, policy);
InvokeAndIgnoreResult(on_nat_traversal_policy_changed_func_.get(),
&policy, 1);
}
}
// Stores the Access Code for the web-app to query.
void HostNPScriptObject::StoreAccessCode(const std::string& access_code,
base::TimeDelta access_code_lifetime) {
DCHECK(plugin_task_runner_->BelongsToCurrentThread());
access_code_ = access_code;
access_code_lifetime_ = access_code_lifetime;
}
// Stores the client user's name for the web-app to query.
void HostNPScriptObject::StoreClientUsername(
const std::string& client_username) {
DCHECK(plugin_task_runner_->BelongsToCurrentThread());
client_username_ = client_username;
}
void HostNPScriptObject::PostLogDebugInfo(const std::string& message) {
if (plugin_task_runner_->BelongsToCurrentThread()) {
// Make sure we're not currently processing a log message.
// We only need to check this if we're on the plugin thread.
if (am_currently_logging_)
return;
}
// Always post (even if we're already on the correct thread) so that debug
// log messages are shown in the correct order.
plugin_task_runner_->PostTask(
FROM_HERE, base::Bind(&HostNPScriptObject::LogDebugInfo,
weak_ptr_, message));
}
void HostNPScriptObject::SetWindow(NPWindow* np_window) {
DCHECK(plugin_task_runner_->BelongsToCurrentThread());
daemon_controller_->SetWindow(np_window->window);
}
void HostNPScriptObject::LocalizeStrings(NPObject* localize_func) {
DCHECK(plugin_task_runner_->BelongsToCurrentThread());
string16 direction;
LocalizeString(localize_func, "@@bidi_dir", &direction);
ui_strings_.direction = UTF16ToUTF8(direction) == "rtl" ?
remoting::UiStrings::RTL : remoting::UiStrings::LTR;
LocalizeString(localize_func, /*i18n-content*/"PRODUCT_NAME",
&ui_strings_.product_name);
LocalizeString(localize_func, /*i18n-content*/"DISCONNECT_OTHER_BUTTON",
&ui_strings_.disconnect_button_text);
LocalizeString(localize_func, /*i18n-content*/"CONTINUE_PROMPT",
&ui_strings_.continue_prompt);
LocalizeString(localize_func, /*i18n-content*/"CONTINUE_BUTTON",
&ui_strings_.continue_button_text);
LocalizeString(localize_func, /*i18n-content*/"STOP_SHARING_BUTTON",
&ui_strings_.stop_sharing_button_text);
LocalizeStringWithSubstitution(localize_func,
/*i18n-content*/"MESSAGE_SHARED", "$1",
&ui_strings_.disconnect_message);
}
bool HostNPScriptObject::LocalizeString(NPObject* localize_func,
const char* tag, string16* result) {
return LocalizeStringWithSubstitution(localize_func, tag, NULL, result);
}
bool HostNPScriptObject::LocalizeStringWithSubstitution(
NPObject* localize_func,
const char* tag,
const char* substitution,
string16* result) {
int argc = substitution ? 2 : 1;
scoped_ptr<NPVariant[]> args(new NPVariant[argc]);
STRINGZ_TO_NPVARIANT(tag, args[0]);
if (substitution) {
STRINGZ_TO_NPVARIANT(substitution, args[1]);
}
NPVariant np_result;
bool is_good = g_npnetscape_funcs->invokeDefault(
plugin_, localize_func, args.get(), argc, &np_result);
if (!is_good) {
LOG(ERROR) << "Localization failed for " << tag;
return false;
}
std::string translation = StringFromNPVariant(np_result);
g_npnetscape_funcs->releasevariantvalue(&np_result);
if (translation.empty()) {
LOG(ERROR) << "Missing translation for " << tag;
return false;
}
*result = UTF8ToUTF16(translation);
return true;
}
void HostNPScriptObject::DoGenerateKeyPair(const ScopedRefNPObject& callback) {
scoped_refptr<RsaKeyPair> key_pair = RsaKeyPair::Generate();
InvokeGenerateKeyPairCallback(callback, key_pair->ToString(),
key_pair->GetPublicKey());
}
void HostNPScriptObject::InvokeGenerateKeyPairCallback(
const ScopedRefNPObject& callback,
const std::string& private_key,
const std::string& public_key) {
if (!plugin_task_runner_->BelongsToCurrentThread()) {
plugin_task_runner_->PostTask(
FROM_HERE, base::Bind(
&HostNPScriptObject::InvokeGenerateKeyPairCallback,
weak_ptr_, callback, private_key, public_key));
return;
}
NPVariant params[2];
params[0] = NPVariantFromString(private_key);
params[1] = NPVariantFromString(public_key);
InvokeAndIgnoreResult(callback.get(), params, arraysize(params));
g_npnetscape_funcs->releasevariantvalue(&(params[0]));
g_npnetscape_funcs->releasevariantvalue(&(params[1]));
}
void HostNPScriptObject::InvokeAsyncResultCallback(
const ScopedRefNPObject& callback,
DaemonController::AsyncResult result) {
if (!plugin_task_runner_->BelongsToCurrentThread()) {
plugin_task_runner_->PostTask(
FROM_HERE, base::Bind(
&HostNPScriptObject::InvokeAsyncResultCallback,
weak_ptr_, callback, result));
return;
}
NPVariant result_var;
INT32_TO_NPVARIANT(static_cast<int32>(result), result_var);
InvokeAndIgnoreResult(callback.get(), &result_var, 1);
g_npnetscape_funcs->releasevariantvalue(&result_var);
}
void HostNPScriptObject::InvokeGetDaemonConfigCallback(
const ScopedRefNPObject& callback,
scoped_ptr<base::DictionaryValue> config) {
if (!plugin_task_runner_->BelongsToCurrentThread()) {
plugin_task_runner_->PostTask(
FROM_HERE, base::Bind(
&HostNPScriptObject::InvokeGetDaemonConfigCallback,
weak_ptr_, callback, base::Passed(&config)));
return;
}
// There is no easy way to create a dictionary from an NPAPI plugin
// so we have to serialize the dictionary to pass it to JavaScript.
std::string config_str;
if (config.get())
base::JSONWriter::Write(config.get(), &config_str);
NPVariant config_val = NPVariantFromString(config_str);
InvokeAndIgnoreResult(callback.get(), &config_val, 1);
g_npnetscape_funcs->releasevariantvalue(&config_val);
}
void HostNPScriptObject::InvokeGetDaemonVersionCallback(
const ScopedRefNPObject& callback, const std::string& version) {
if (!plugin_task_runner_->BelongsToCurrentThread()) {
plugin_task_runner_->PostTask(
FROM_HERE, base::Bind(
&HostNPScriptObject::InvokeGetDaemonVersionCallback,
weak_ptr_, callback, version));
return;
}
NPVariant version_val = NPVariantFromString(version);
InvokeAndIgnoreResult(callback.get(), &version_val, 1);
g_npnetscape_funcs->releasevariantvalue(&version_val);
}
void HostNPScriptObject::InvokeGetUsageStatsConsentCallback(
const ScopedRefNPObject& callback,
bool supported,
bool allowed,
bool set_by_policy) {
if (!plugin_task_runner_->BelongsToCurrentThread()) {
plugin_task_runner_->PostTask(
FROM_HERE, base::Bind(
&HostNPScriptObject::InvokeGetUsageStatsConsentCallback,
weak_ptr_, callback, supported, allowed,
set_by_policy));
return;
}
NPVariant params[3];
BOOLEAN_TO_NPVARIANT(supported, params[0]);
BOOLEAN_TO_NPVARIANT(allowed, params[1]);
BOOLEAN_TO_NPVARIANT(set_by_policy, params[2]);
InvokeAndIgnoreResult(callback.get(), params, arraysize(params));
g_npnetscape_funcs->releasevariantvalue(&(params[0]));
g_npnetscape_funcs->releasevariantvalue(&(params[1]));
g_npnetscape_funcs->releasevariantvalue(&(params[2]));
}
void HostNPScriptObject::LogDebugInfo(const std::string& message) {
DCHECK(plugin_task_runner_->BelongsToCurrentThread());
if (log_debug_info_func_.get()) {
am_currently_logging_ = true;
NPVariant log_message;
STRINGZ_TO_NPVARIANT(message.c_str(), log_message);
bool is_good = InvokeAndIgnoreResult(log_debug_info_func_.get(),
&log_message, 1);
if (!is_good) {
LOG(ERROR) << "ERROR - LogDebugInfo failed\n";
}
am_currently_logging_ = false;
}
}
bool HostNPScriptObject::InvokeAndIgnoreResult(NPObject* func,
const NPVariant* args,
uint32_t arg_count) {
DCHECK(plugin_task_runner_->BelongsToCurrentThread());
NPVariant np_result;
bool is_good = g_npnetscape_funcs->invokeDefault(plugin_, func, args,
arg_count, &np_result);
if (is_good)
g_npnetscape_funcs->releasevariantvalue(&np_result);
return is_good;
}
void HostNPScriptObject::SetException(const std::string& exception_string) {
DCHECK(plugin_task_runner_->BelongsToCurrentThread());
g_npnetscape_funcs->setexception(parent_, exception_string.c_str());
LOG(INFO) << exception_string;
}
} // namespace remoting
|
/**
* Aufgabe 11.7
*/
#include <cassert>
#include <iostream>
#include "polynomial.hpp"
int main() {
int p_n = 0, q_n = 0;
std::cout << "Polynomial p: ";
std::cout << "deg(p) = ";
std::cin >> p_n;
Polynomial p(p_n);
p.scanPoly(p_n);
p.printPoly();
std::cout << std::endl;
std::cout << "Polynomial q: ";
std::cout << "deg(q) = ";
std::cin >> q_n;
Polynomial q(q_n);
q.scanPoly(q_n);
q.printPoly();
std::cout << std::endl;
Polynomial prod = prodPolynomials(p, q);
std::cout << "(p * q) = ";
prod.printPoly();
std::cout << "All tests passed!" << std::endl;
return 0;
}
|
// This file is licensed under the Elastic License 2.0. Copyright 2021-present, StarRocks Limited.
#include "exec/vectorized/es_http_components.h"
#include <fmt/format.h>
#include "column/column_helper.h"
#include "column/nullable_column.h"
#include "common/config.h"
#include "runtime/primitive_type.h"
#include "runtime/runtime_state.h"
#include "runtime/timestamp_value.h"
namespace starrocks::vectorized {
static const char* FIELD_SCROLL_ID = "_scroll_id";
static const char* FIELD_HITS = "hits";
static const char* FIELD_INNER_HITS = "hits";
static const char* FIELD_SOURCE = "_source";
static const char* FIELD_FIELDS = "fields";
static const char* FIELD_ID = "_id";
const char* json_type_to_raw_str(rapidjson::Type type) {
switch (type) {
case rapidjson::kNumberType:
return "Number";
case rapidjson::kStringType:
return "Varchar/Char";
case rapidjson::kArrayType:
return "Array";
case rapidjson::kObjectType:
return "Object";
case rapidjson::kNullType:
return "Null Type";
case rapidjson::kFalseType:
case rapidjson::kTrueType:
return "True/False";
default:
return "Unknown Type";
}
}
std::string json_value_to_string(const rapidjson::Value& value) {
rapidjson::StringBuffer scratch_buffer;
rapidjson::Writer<rapidjson::StringBuffer> temp_writer(scratch_buffer);
value.Accept(temp_writer);
return scratch_buffer.GetString();
}
#define RETURN_ERROR_IF_COL_IS_ARRAY(col, type) \
do { \
if (col.IsArray()) { \
std::stringstream ss; \
ss << "Expected value of type: " << type_to_string(type) \
<< "; but found type: " << json_type_to_raw_str(col.GetType()) \
<< "; Document slice is : " << json_value_to_string(col); \
return Status::RuntimeError(ss.str()); \
} \
} while (false)
#define RETURN_ERROR_IF_COL_IS_NOT_STRING(col, type) \
do { \
if (!col.IsString()) { \
std::stringstream ss; \
ss << "Expected value of type: " << type_to_string(type) \
<< "; but found type: " << json_type_to_raw_str(col.GetType()) \
<< "; Document source slice is : " << json_value_to_string(col); \
return Status::RuntimeError(ss.str()); \
} \
} while (false)
#define RETURN_ERROR_IF_COL_IS_NOT_NUMBER(col, type) \
do { \
if (!col.IsNumber()) { \
std::stringstream ss; \
ss << "Expected value of type: " << type_to_string(type) \
<< "; but found type: " << json_type_to_raw_str(col.GetType()) \
<< "; Document value is: " << json_value_to_string(col); \
return Status::RuntimeError(ss.str()); \
} \
} while (false)
#define RETURN_ERROR_IF_PARSING_FAILED(result, col, type) \
do { \
if (result != StringParser::PARSE_SUCCESS) { \
std::stringstream ss; \
ss << "Expected value of type: " << type_to_string(type) \
<< "; but found type: " << json_type_to_raw_str(col.GetType()) \
<< "; Document source slice is : " << json_value_to_string(col); \
return Status::RuntimeError(ss.str()); \
} \
} while (false)
#define RETURN_ERROR_IF_CAST_FORMAT_ERROR(col, type) \
do { \
std::stringstream ss; \
ss << "Expected value of type: " << type_to_string(type) \
<< "; but found type: " << json_type_to_raw_str(col.GetType()) \
<< "; Document slice is : " << json_value_to_string(col); \
return Status::RuntimeError(ss.str()); \
} while (false)
template <typename T>
static Status get_int_value(const rapidjson::Value& col, PrimitiveType type, void* slot, bool pure_doc_value) {
return Status::OK();
}
ScrollParser::ScrollParser(bool doc_value_mode)
: _tuple_desc(nullptr),
_docvalue_context(nullptr),
_size(0),
_cur_line(0),
_doc_value_mode(doc_value_mode),
_temp_writer(_scratch_buffer) {}
Status ScrollParser::parse(const std::string& scroll_result, bool exactly_once) {
_size = 0;
_cur_line = 0;
_document_node.Parse(scroll_result.data(), scroll_result.size());
if (_document_node.HasParseError()) {
return Status::InternalError(fmt::format("Parsing json error, json is: {}", scroll_result));
}
if (!exactly_once && !_document_node.HasMember(FIELD_SCROLL_ID)) {
LOG(WARNING) << "Document has not a scroll id field scroll response:" << scroll_result;
return Status::InternalError("Document has not a scroll id field");
}
if (!exactly_once) {
const rapidjson::Value& scroll_node = _document_node[FIELD_SCROLL_ID];
_scroll_id = scroll_node.GetString();
}
// { hits: { total : 2, "hits" : [ {}, {}, {} ]}}
const rapidjson::Value& outer_hits_node = _document_node[FIELD_HITS];
// if has no inner hits, there has no data in this index
if (!outer_hits_node.HasMember(FIELD_INNER_HITS)) {
return Status::OK();
}
const rapidjson::Value& inner_hits_node = outer_hits_node[FIELD_INNER_HITS];
// this happened just the end of scrolling
if (!inner_hits_node.IsArray()) {
return Status::OK();
}
_inner_hits_node.CopyFrom(inner_hits_node, _document_node.GetAllocator());
// how many documents contains in this batch
_size = _inner_hits_node.Size();
return Status::OK();
}
Status ScrollParser::fill_chunk(RuntimeState* state, ChunkPtr* chunk, bool* line_eos) {
if (current_eos()) {
*line_eos = true;
return Status::OK();
}
*line_eos = false;
*chunk = std::make_shared<Chunk>();
std::vector<SlotDescriptor*> slot_descs = _tuple_desc->slots();
size_t left_sz = _size - _cur_line;
size_t fill_sz = std::min(left_sz, (size_t)state->chunk_size());
// init column information
for (auto& slot_desc : slot_descs) {
ColumnPtr column = ColumnHelper::create_column(slot_desc->type(), slot_desc->is_nullable());
column->reserve(fill_sz);
(*chunk)->append_column(std::move(column), slot_desc->id());
}
auto slots = _tuple_desc->slots();
// TODO: we could fill chunk by column rather than row
for (size_t i = 0; i < fill_sz; ++i) {
const rapidjson::Value& obj = _inner_hits_node[_cur_line + i];
bool pure_doc_value = _pure_doc_value(obj);
bool has_source = obj.HasMember(FIELD_SOURCE);
bool has_fields = obj.HasMember(FIELD_FIELDS);
if (!has_source && !has_fields) {
for (auto column : (*chunk)->columns()) {
column->append_default();
}
continue;
}
DCHECK(has_source ^ has_fields);
const rapidjson::Value& line = has_source ? obj[FIELD_SOURCE] : obj[FIELD_FIELDS];
for (size_t col_idx = 0; col_idx < slots.size(); ++col_idx) {
SlotDescriptor* slot_desc = slot_descs[col_idx];
ColumnPtr& column = (*chunk)->get_column_by_slot_id(slot_desc->id());
// _id field must exists in every document, this is guaranteed by ES
// if _id was found in tuple, we would get `_id` value from inner-hit node
// json-format response would like below:
// "hits": {
// "hits": [
// {
// "_id": "UhHNc3IB8XwmcbhBk1ES",
// "_source": {
// "k": 201,
// }
// }
// ]
// }
if (slot_desc->col_name() == FIELD_ID) {
// actually this branch will not be reached, this is guaranteed by Doris FE.
if (pure_doc_value) {
return Status::RuntimeError("obtain `_id` is not supported in doc_values mode");
}
PrimitiveType type = slot_desc->type().type;
DCHECK(type == TYPE_CHAR || type == TYPE_VARCHAR);
const auto& _id = obj[FIELD_ID];
Slice slice(_id.GetString(), _id.GetStringLength());
_append_data<TYPE_VARCHAR>(column.get(), slice);
continue;
}
// if pure_doc_value enabled, docvalue_context must contains the key
// todo: need move all `pure_docvalue` for every tuple outside fill_tuple
// should check pure_docvalue for one table scan not every tuple
const char* col_name = pure_doc_value ? _docvalue_context->at(slot_desc->col_name()).c_str()
: slot_desc->col_name().c_str();
auto has_col = line.HasMember(col_name);
if (has_col) {
const rapidjson::Value& col = line[col_name];
// doc value
bool is_null = (pure_doc_value && col.IsArray() && col[0].IsNull()) || col.IsNull();
if (!is_null) {
// append value from ES to column
RETURN_IF_ERROR(
_append_value_from_json_val(column.get(), slot_desc->type().type, col, pure_doc_value));
continue;
}
// handle null col
if (slot_desc->is_nullable()) {
_append_null(column.get());
} else {
return Status::DataQualityError(
fmt::format("col `{}` is not null, but value from ES is null", slot_desc->col_name()));
}
} else {
// if don't has col in ES , append a default value
_append_null(column.get());
}
}
}
_cur_line += fill_sz;
return Status::OK();
}
void ScrollParser::set_params(const TupleDescriptor* descs,
const std::map<std::string, std::string>* docvalue_context) {
_tuple_desc = descs;
_docvalue_context = docvalue_context;
}
bool ScrollParser::_pure_doc_value(const rapidjson::Value& obj) {
if (obj.HasMember(FIELD_FIELDS)) {
return true;
}
return false;
}
template <PrimitiveType type, typename CppType>
void ScrollParser::_append_data(Column* column, CppType& value) {
auto appender = [](auto* column, CppType& value) {
using ColumnType = typename vectorized::RunTimeColumnType<type>;
ColumnType* runtime_column = down_cast<ColumnType*>(column);
runtime_column->append(value);
};
if (column->is_nullable()) {
auto* nullable_column = down_cast<NullableColumn*>(column);
auto* data_column = nullable_column->data_column().get();
NullData& null_data = nullable_column->null_column_data();
null_data.push_back(0);
appender(data_column, value);
} else {
appender(column, value);
}
}
void ScrollParser::_append_null(Column* column) {
column->append_default();
}
Status ScrollParser::_append_value_from_json_val(Column* column, PrimitiveType type, const rapidjson::Value& col,
bool pure_doc_value) {
switch (type) {
case TYPE_CHAR:
case TYPE_VARCHAR: {
Slice slice;
auto get_slice = [this](auto& val) {
if (!val.IsString()) {
return _json_val_to_slice(val);
} else {
return Slice{val.GetString(), val.GetStringLength()};
}
};
if (pure_doc_value) {
slice = get_slice(col[0]);
} else {
RETURN_ERROR_IF_COL_IS_ARRAY(col, type);
slice = get_slice(col);
}
_append_data<TYPE_VARCHAR>(column, slice);
break;
}
case TYPE_INT: {
RETURN_IF_ERROR(_append_int_val<TYPE_INT>(col, column, pure_doc_value));
break;
}
case TYPE_TINYINT: {
RETURN_IF_ERROR(_append_int_val<TYPE_TINYINT>(col, column, pure_doc_value));
break;
}
case TYPE_SMALLINT: {
RETURN_IF_ERROR(_append_int_val<TYPE_SMALLINT>(col, column, pure_doc_value));
break;
}
case TYPE_BIGINT: {
RETURN_IF_ERROR(_append_int_val<TYPE_BIGINT>(col, column, pure_doc_value));
break;
}
case TYPE_LARGEINT: {
RETURN_IF_ERROR(_append_int_val<TYPE_LARGEINT>(col, column, pure_doc_value));
break;
}
case TYPE_DOUBLE: {
RETURN_IF_ERROR(_append_float_val<TYPE_DOUBLE>(col, column, pure_doc_value));
break;
}
case TYPE_FLOAT: {
RETURN_IF_ERROR(_append_float_val<TYPE_FLOAT>(col, column, pure_doc_value));
break;
}
case TYPE_BOOLEAN: {
RETURN_IF_ERROR(_append_bool_val(col, column, pure_doc_value));
break;
}
case TYPE_DATE: {
RETURN_IF_ERROR(_append_date_val<TYPE_DATE>(col, column, pure_doc_value));
break;
}
case TYPE_DATETIME: {
RETURN_IF_ERROR(_append_date_val<TYPE_DATETIME>(col, column, pure_doc_value));
break;
}
default: {
DCHECK(false) << "unknown type:" << type;
return Status::InvalidArgument(fmt::format("unknown type {}", type));
break;
}
}
return Status::OK();
}
Slice ScrollParser::_json_val_to_slice(const rapidjson::Value& val) {
_scratch_buffer.Clear();
_temp_writer.Reset(_scratch_buffer);
val.Accept(_temp_writer);
return {_scratch_buffer.GetString(), _scratch_buffer.GetSize()};
}
template <PrimitiveType type, typename T>
Status ScrollParser::_append_int_val(const rapidjson::Value& col, Column* column, bool pure_doc_value) {
T value;
if (col.IsNumber()) {
// TODO: performance ?
if (col.IsInt()) {
value = static_cast<T>(col.GetInt());
} else if (col.IsInt64()) {
value = static_cast<T>(col.GetInt64());
} else if (col.IsUint()) {
value = static_cast<T>(col.GetUint());
} else if (col.IsUint64()) {
value = static_cast<T>(col.GetUint64());
} else if (col.IsDouble()) {
value = static_cast<T>(col.GetDouble());
} else if (col.IsFloat()) {
value = static_cast<T>(col.GetFloat());
} else {
value = (T)(sizeof(T) < 8 ? col.GetInt() : col.GetInt64());
}
_append_data<type>(column, value);
return Status::OK();
}
if (pure_doc_value && col.IsArray()) {
RETURN_ERROR_IF_COL_IS_NOT_NUMBER(col[0], type);
value = (T)(sizeof(T) < 8 ? col[0].GetInt() : col[0].GetInt64());
_append_data<type>(column, value);
return Status::OK();
}
RETURN_ERROR_IF_COL_IS_ARRAY(col, type);
RETURN_ERROR_IF_COL_IS_NOT_STRING(col, type);
StringParser::ParseResult result;
const char* raw_str = col.GetString();
size_t len = col.GetStringLength();
value = StringParser::string_to_int<T>(raw_str, len, &result);
RETURN_ERROR_IF_PARSING_FAILED(result, col, type);
_append_data<type>(column, value);
return Status::OK();
}
template <PrimitiveType type, typename T>
Status ScrollParser::_append_float_val(const rapidjson::Value& col, Column* column, bool pure_doc_value) {
static_assert(std::is_same_v<T, float> || std::is_same_v<T, double>);
T value;
auto get_value = [](const auto& col) {
T v;
if constexpr (std::is_same_v<T, float>) {
v = col.GetFloat();
} else if constexpr (std::is_same_v<T, double>) {
v = col.GetDouble();
}
return v;
};
if (col.IsNumber()) {
value = get_value(col);
_append_data<type>(column, value);
return Status::OK();
}
if (pure_doc_value && col.IsArray()) {
value = get_value(col[0]);
_append_data<type>(column, value);
return Status::OK();
}
RETURN_ERROR_IF_COL_IS_ARRAY(col, type);
RETURN_ERROR_IF_COL_IS_NOT_STRING(col, type);
StringParser::ParseResult result;
const char* raw_str = col.GetString();
size_t len = col.GetStringLength();
value = StringParser::string_to_float<T>(raw_str, len, &result);
RETURN_ERROR_IF_PARSING_FAILED(result, col, type);
_append_data<type>(column, value);
return Status::OK();
}
Status ScrollParser::_append_bool_val(const rapidjson::Value& col, Column* column, bool pure_doc_value) {
PrimitiveType type = TYPE_BOOLEAN;
uint8_t value;
if (col.IsBool()) {
value = col.GetBool();
_append_data<TYPE_BOOLEAN>(column, value);
return Status::OK();
}
if (col.IsNumber()) {
if (col.IsInt()) {
value = static_cast<int8_t>(col.GetInt() != 0);
} else if (col.IsInt64()) {
value = static_cast<int8_t>(col.GetInt64() != 0);
} else if (col.IsUint()) {
value = static_cast<int8_t>(col.GetUint() != 0);
} else if (col.IsUint64()) {
value = static_cast<int8_t>(col.GetUint64() != 0);
} else if (col.IsDouble()) {
value = static_cast<int8_t>(col.GetDouble() != 0);
} else {
value = static_cast<int8_t>(col.GetInt() != 0);
}
_append_data<TYPE_BOOLEAN>(column, value);
return Status::OK();
}
if (pure_doc_value && col.IsArray()) {
value = col[0].GetBool();
_append_data<TYPE_BOOLEAN>(column, value);
return Status::OK();
}
RETURN_ERROR_IF_COL_IS_ARRAY(col, type);
RETURN_ERROR_IF_COL_IS_NOT_STRING(col, type);
const char* raw_string = col.GetString();
size_t val_size = col.GetStringLength();
StringParser::ParseResult result;
value = StringParser::string_to_bool(raw_string, val_size, &result);
RETURN_ERROR_IF_PARSING_FAILED(result, col, type);
_append_data<TYPE_BOOLEAN>(column, value);
return Status::OK();
}
// TODO: test here
template <PrimitiveType type, typename T>
Status ScrollParser::_append_date_val(const rapidjson::Value& col, Column* column, bool pure_doc_value) {
auto append_timestamp = [](auto& col, Column* column) {
TimestampValue value;
value.from_unixtime(col.GetInt64() / 1000, TimezoneUtils::default_time_zone);
if constexpr (type == TYPE_DATE) {
DateValue date_val = DateValue(value);
_append_data<TYPE_DATE>(column, date_val);
} else if constexpr (type == TYPE_DATETIME) {
_append_data<TYPE_DATETIME>(column, value);
}
};
auto append_strval = [](auto& col, Column* column) {
const char* raw_str = col.GetString();
size_t val_size = col.GetStringLength();
if constexpr (type == TYPE_DATE) {
DateValue value;
if (!value.from_string(raw_str, val_size)) {
RETURN_ERROR_IF_CAST_FORMAT_ERROR(col, type);
}
_append_data<TYPE_DATE>(column, value);
} else if constexpr (type == TYPE_DATETIME) {
TimestampValue value;
if (!value.from_string(raw_str, val_size)) {
RETURN_ERROR_IF_CAST_FORMAT_ERROR(col, type);
}
// https://en.wikipedia.org/wiki/ISO_8601
// 2020-06-06T16:00:00.000Z was UTC time.
if (raw_str[val_size - 1] == 'Z') {
value.from_unixtime(value.to_unix_second(), TimezoneUtils::default_time_zone);
}
_append_data<TYPE_DATETIME>(column, value);
}
return Status::OK();
};
if (col.IsNumber()) {
append_timestamp(col, column);
} else if (col.IsArray() && pure_doc_value) {
if (col[0].IsString()) {
RETURN_IF_ERROR(append_strval(col[0], column));
} else {
append_timestamp(col[0], column);
}
} else {
RETURN_ERROR_IF_COL_IS_ARRAY(col, type);
RETURN_ERROR_IF_COL_IS_NOT_STRING(col, type);
RETURN_IF_ERROR(append_strval(col, column));
}
return Status::OK();
}
} // namespace starrocks::vectorized
|
// -----------------------------------------------------------------------------------------------------
// Copyright (c) 2006-2020, Knut Reinert & Freie Universität Berlin
// Copyright (c) 2016-2020, Knut Reinert & MPI für molekulare Genetik
// This file may be used, modified and/or redistributed under the terms of the 3-clause BSD-License
// shipped with this file and also available at: https://github.com/seqan/seqan3/blob/master/LICENSE.md
// -----------------------------------------------------------------------------------------------------
#include <list>
#include <seqan3/std/ranges>
#include <type_traits>
#include <vector>
#include <gtest/gtest.h>
#include <seqan3/test/expect_same_type.hpp>
#include <seqan3/utility/type_list/traits.hpp>
TEST(list_traits, size)
{
EXPECT_EQ((seqan3::list_traits::size<seqan3::type_list<int, bool &, double const>>),
3u);
}
TEST(list_traits, count)
{
EXPECT_EQ((seqan3::list_traits::count<int, seqan3::type_list<>>),
0u);
EXPECT_EQ((seqan3::list_traits::count<int, seqan3::type_list<bool &, double const>>),
0u);
EXPECT_EQ((seqan3::list_traits::count<int, seqan3::type_list<bool &, int, double const, int>>),
2u);
}
TEST(list_traits, find)
{
EXPECT_EQ((seqan3::list_traits::find<int, seqan3::type_list<>>),
-1ll);
EXPECT_EQ((seqan3::list_traits::find<int, seqan3::type_list<bool &, double const>>),
-1ll);
EXPECT_EQ((seqan3::list_traits::find<int, seqan3::type_list<bool &, int, double const, int>>),
1u);
}
TEST(list_traits, find_if)
{
EXPECT_EQ((seqan3::list_traits::find_if<std::is_integral, seqan3::type_list<>>),
-1ll);
EXPECT_EQ((seqan3::list_traits::find_if<std::is_integral, seqan3::type_list<float, double const>>),
-1ll);
EXPECT_EQ((seqan3::list_traits::find_if<std::is_integral, seqan3::type_list<float, int, double const, long>>),
1ll);
}
TEST(list_traits, contains)
{
EXPECT_EQ((seqan3::list_traits::contains<int, seqan3::type_list<>>),
false);
EXPECT_EQ((seqan3::list_traits::contains<int, seqan3::type_list<bool &, double const>>),
false);
EXPECT_EQ((seqan3::list_traits::contains<int, seqan3::type_list<bool &, int, double const, int>>),
true);
}
TEST(list_traits, at)
{
using test_types_list = seqan3::type_list<int, bool &, double const, long, float>;
EXPECT_SAME_TYPE((seqan3::list_traits::at<2, test_types_list>), double const);
EXPECT_SAME_TYPE((seqan3::list_traits::at<-2, test_types_list>), long);
}
TEST(list_traits, front)
{
using test_types_list = seqan3::type_list<int, bool &, double const, long, float>;
EXPECT_SAME_TYPE(seqan3::list_traits::front<test_types_list>, int);
}
TEST(list_traits, back)
{
using test_types_list = seqan3::type_list<int, bool &, double const, long, float>;
EXPECT_SAME_TYPE(seqan3::list_traits::back<test_types_list>, float);
}
TEST(list_traits, concat)
{
using test_types_list = seqan3::type_list<int, bool &, double const, long, float>;
EXPECT_SAME_TYPE((seqan3::list_traits::concat<seqan3::type_list<int, bool &, double const>,
seqan3::type_list<long, float>>),
test_types_list);
EXPECT_SAME_TYPE((seqan3::list_traits::concat<seqan3::type_list<int, bool &, double const>,
seqan3::type_list<long, float>,
seqan3::type_list<>,
seqan3::type_list<long &>>),
(seqan3::type_list<int, bool &, double const, long, float, long &>));
}
TEST(list_traits, drop_front)
{
using test_types_list = seqan3::type_list<int, bool &, double const, long, float>;
EXPECT_SAME_TYPE(seqan3::list_traits::drop_front<test_types_list>,
(seqan3::type_list<bool &, double const, long, float>));
}
TEST(list_traits, take)
{
using test_types_list = seqan3::type_list<int, bool &, double const, long, float>;
EXPECT_SAME_TYPE((seqan3::list_traits::take<0, test_types_list>), seqan3::type_list<>);
EXPECT_SAME_TYPE((seqan3::list_traits::take<3, test_types_list>), (seqan3::type_list<int, bool &, double const>));
EXPECT_SAME_TYPE((seqan3::list_traits::take<5, test_types_list>), test_types_list);
}
TEST(list_traits, drop)
{
using test_types_list = seqan3::type_list<int, bool &, double const, long, float>;
EXPECT_SAME_TYPE((seqan3::list_traits::drop<0, test_types_list>), test_types_list);
EXPECT_SAME_TYPE((seqan3::list_traits::drop<3, test_types_list>), (seqan3::type_list<long, float>));
EXPECT_SAME_TYPE((seqan3::list_traits::drop<5, test_types_list>), seqan3::type_list<>);
}
TEST(list_traits, take_last)
{
using test_types_list = seqan3::type_list<int, bool &, double const, long, float>;
EXPECT_SAME_TYPE((seqan3::list_traits::take_last<0, test_types_list>), seqan3::type_list<>);
EXPECT_SAME_TYPE((seqan3::list_traits::take_last<3, test_types_list>),
(seqan3::type_list<double const, long, float>));
EXPECT_SAME_TYPE((seqan3::list_traits::take_last<5, test_types_list>), test_types_list);
}
TEST(list_traits, drop_last)
{
using test_types_list = seqan3::type_list<int, bool &, double const, long, float>;
EXPECT_SAME_TYPE((seqan3::list_traits::drop_last<0, test_types_list>), test_types_list);
EXPECT_SAME_TYPE((seqan3::list_traits::drop_last<3, test_types_list>), (seqan3::type_list<int, bool &>));
EXPECT_SAME_TYPE((seqan3::list_traits::drop_last<5, test_types_list>), seqan3::type_list<>);
}
TEST(list_traits, split_after)
{
using test_types_list = seqan3::type_list<int, bool &, double const, long, float>;
using split0 = seqan3::list_traits::split_after<0, test_types_list>;
EXPECT_SAME_TYPE(typename split0::first_type, seqan3::type_list<>);
EXPECT_SAME_TYPE(typename split0::second_type, test_types_list);
using split3 = seqan3::list_traits::split_after<3, test_types_list>;
EXPECT_SAME_TYPE(typename split3::first_type, (seqan3::type_list<int, bool &, double const>));
EXPECT_SAME_TYPE(typename split3::second_type, (seqan3::type_list<long, float>));
using split5 = seqan3::list_traits::split_after<5, test_types_list>;
EXPECT_SAME_TYPE(typename split5::first_type, test_types_list);
EXPECT_SAME_TYPE(typename split5::second_type, seqan3::type_list<>);
}
TEST(list_traits, transform)
{
EXPECT_SAME_TYPE((seqan3::list_traits::transform<std::ranges::range_value_t,
seqan3::type_list<>>),
seqan3::type_list<>);
EXPECT_SAME_TYPE((seqan3::list_traits::transform<std::ranges::range_value_t,
seqan3::type_list<std::vector<int>, std::list<bool>>>),
(seqan3::type_list<int, bool>));
EXPECT_SAME_TYPE((seqan3::list_traits::transform<std::ranges::range_reference_t,
seqan3::type_list<std::vector<int>, std::list<bool>>>),
(seqan3::type_list<int &, bool &>));
}
TEST(list_traits, replace_at)
{
EXPECT_SAME_TYPE((seqan3::list_traits::replace_at<double, 0, seqan3::type_list<int, float, bool>>),
(seqan3::type_list<double, float, bool>));
EXPECT_SAME_TYPE((seqan3::list_traits::replace_at<double, 1, seqan3::type_list<int, float, bool>>),
(seqan3::type_list<int, double, bool>));
EXPECT_SAME_TYPE((seqan3::list_traits::replace_at<double, 2, seqan3::type_list<int, float, bool>>),
(seqan3::type_list<int, float, double>));
}
TEST(list_traits_detail, reverse)
{
auto reverse = [] (auto && type_list)
{
return seqan3::list_traits::detail::reverse(type_list);
};
EXPECT_SAME_TYPE(decltype(reverse(seqan3::type_list<>{})), (seqan3::type_list<>));
EXPECT_SAME_TYPE(decltype(reverse(seqan3::type_list<float>{})), (seqan3::type_list<float>));
EXPECT_SAME_TYPE(decltype(reverse(seqan3::type_list<float, double, char, short>{})),
(seqan3::type_list<short, char, double, float>));
EXPECT_SAME_TYPE(decltype(reverse(seqan3::type_list<int>{})), (seqan3::type_list<int>));
EXPECT_SAME_TYPE(decltype(reverse(seqan3::type_list<int, int, int, int>{})),
(seqan3::type_list<int, int, int, int>));
EXPECT_SAME_TYPE(decltype(reverse(seqan3::type_list<float, int>{})), (seqan3::type_list<int, float>));
EXPECT_SAME_TYPE(decltype(reverse(seqan3::type_list<int, float>{})), (seqan3::type_list<float, int>));
EXPECT_SAME_TYPE(decltype(reverse(seqan3::type_list<int, float, int, int, double, int, char, short, int>{})),
(seqan3::type_list<int, short, char, int, double, int, int, float, int>));
EXPECT_SAME_TYPE(decltype(reverse(seqan3::type_list<int, int, int, int, float, float, float>{})),
(seqan3::type_list<float, float, float, int, int, int, int>));
}
|
// Copyright 2021 Proyectos y Sistemas de Mantenimiento SL (eProsima).
//
// 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 <map>
#include <gmock/gmock.h>
#include <gtest/gtest.h>
#include <fastdds/dds/log/Log.hpp>
#include <fastdds/dds/publisher/qos/WriterQos.hpp>
#include <fastdds/dds/subscriber/qos/ReaderQos.hpp>
#include <fastdds/rtps/RTPSDomain.h>
#include <fastdds/rtps/attributes/HistoryAttributes.h>
#include <fastdds/rtps/attributes/RTPSParticipantAttributes.h>
#include <fastdds/rtps/attributes/ReaderAttributes.h>
#include <fastdds/rtps/attributes/WriterAttributes.h>
#include <fastdds/rtps/common/Time_t.h>
#include <fastdds/rtps/history/ReaderHistory.h>
#include <fastdds/rtps/history/WriterHistory.h>
#include <fastdds/rtps/participant/RTPSParticipant.h>
#include <fastdds/rtps/reader/RTPSReader.h>
#include <fastdds/rtps/writer/RTPSWriter.h>
#include <fastdds/statistics/IListeners.hpp>
#include <fastrtps/attributes/LibrarySettingsAttributes.h>
#include <fastrtps/attributes/LibrarySettingsAttributes.h>
#include <fastrtps/attributes/TopicAttributes.h>
#include <fastrtps/attributes/TopicAttributes.h>
#include <fastrtps/transport/test_UDPv4TransportDescriptor.h>
#include <fastrtps/xmlparser/XMLProfileManager.h>
#include <fastrtps/xmlparser/XMLProfileManager.h>
#include <statistics/types/types.h>
#include <rtps/transport/test_UDPv4Transport.h>
#include <utils/SystemInfo.hpp>
namespace eprosima {
namespace fastdds {
namespace statistics {
namespace rtps {
struct MockListener : IListener
{
void on_statistics_data(
const Data& data) override
{
switch (data._d())
{
case RTPS_SENT:
on_rtps_sent(data.entity2locator_traffic());
break;
case HEARTBEAT_COUNT:
on_heartbeat_count(data.entity_count());
break;
case ACKNACK_COUNT:
on_acknack_count(data.entity_count());
break;
case DATA_COUNT:
on_data_count(data.entity_count());
break;
case RESENT_DATAS:
on_resent_count(data.entity_count());
break;
case GAP_COUNT:
on_gap_count(data.entity_count());
break;
case NACKFRAG_COUNT:
on_nackfrag_count(data.entity_count());
break;
case DISCOVERED_ENTITY:
on_entity_discovery(data.discovery_time());
break;
case PDP_PACKETS:
on_pdp_packets(data.entity_count());
break;
default:
break;
}
}
MOCK_METHOD1(on_rtps_sent, void(const eprosima::fastdds::statistics::Entity2LocatorTraffic&));
MOCK_METHOD1(on_heartbeat_count, void(const eprosima::fastdds::statistics::EntityCount&));
MOCK_METHOD1(on_acknack_count, void(const eprosima::fastdds::statistics::EntityCount&));
MOCK_METHOD1(on_data_count, void(const eprosima::fastdds::statistics::EntityCount&));
MOCK_METHOD1(on_resent_count, void(const eprosima::fastdds::statistics::EntityCount&));
MOCK_METHOD1(on_gap_count, void(const eprosima::fastdds::statistics::EntityCount&));
MOCK_METHOD1(on_nackfrag_count, void(const eprosima::fastdds::statistics::EntityCount&));
MOCK_METHOD1(on_entity_discovery, void(const eprosima::fastdds::statistics::DiscoveryTime&));
MOCK_METHOD1(on_pdp_packets, void(const eprosima::fastdds::statistics::EntityCount&));
};
class RTPSStatisticsTestsImpl
{
using test_Descriptor = fastdds::rtps::test_UDPv4TransportDescriptor;
// transport filter, that would delegate into a custom one if provided
// Filters have specific getters and setters methods.
class TransportFilter
{
friend class RTPSStatisticsTestsImpl;
test_Descriptor::filter external_filter_;
public:
TransportFilter() = default;
TransportFilter(
const TransportFilter&) = delete;
TransportFilter(
TransportFilter&&) = delete;
bool operator ()(
fastrtps::rtps::CDRMessage_t& msg) const noexcept
{
try
{
// filter through the external functor
return external_filter_(msg);
}
catch ( std::bad_function_call&)
{
return false; // don't filter
}
}
};
std::map<fastrtps::rtps::SubmessageId, TransportFilter> filters_;
protected:
fastrtps::rtps::WriterHistory* writer_history_ = nullptr;
fastrtps::rtps::ReaderHistory* reader_history_ = nullptr;
fastrtps::rtps::RTPSParticipant* participant_ = nullptr;
fastrtps::rtps::RTPSWriter* writer_ = nullptr;
fastrtps::rtps::RTPSReader* reader_ = nullptr;
// Getters and setters for the transport filter
using filter = fastdds::rtps::test_UDPv4TransportDescriptor::filter;
template<class F>
void set_transport_filter(
fastrtps::rtps::SubmessageId id,
F f) noexcept
{
filters_[id].external_filter_ = f;
}
void set_transport_filter(
fastrtps::rtps::SubmessageId id,
std::nullptr_t) noexcept
{
filters_[id].external_filter_ = nullptr;
}
test_Descriptor::filter get_transport_filter(
fastrtps::rtps::SubmessageId id) noexcept
{
return filters_[id].external_filter_;
}
public:
void create_participant()
{
using namespace fastrtps::rtps;
// create the participant
RTPSParticipantAttributes p_attr;
// use leaky transport
// as filter use a fixture provided functor
auto descriptor = std::make_shared<test_Descriptor>();
// initialize filters
descriptor->drop_data_messages_filter_ = std::ref(filters_[DATA]);
descriptor->drop_heartbeat_messages_filter_ = std::ref(filters_[HEARTBEAT]);
descriptor->drop_ack_nack_messages_filter_ = std::ref(filters_[ACKNACK]);
descriptor->drop_gap_messages_filter_ = std::ref(filters_[GAP]);
descriptor->drop_data_frag_messages_filter_ = std::ref(filters_[DATA_FRAG]);
p_attr.useBuiltinTransports = false;
p_attr.userTransports.push_back(descriptor);
// random domain_id
uint32_t domain_id = SystemInfo::instance().process_id() % 100;
participant_ = RTPSDomain::createParticipant(
domain_id, true, p_attr);
}
void remove_participant()
{
using namespace fastrtps::rtps;
// Remove the endpoints
destroy_endpoints();
// Remove the participant
RTPSDomain::removeRTPSParticipant(participant_);
}
void create_reader(
uint32_t payloadMaxSize,
fastrtps::rtps::ReliabilityKind_t reliability_qos = fastrtps::rtps::ReliabilityKind_t::RELIABLE,
fastrtps::rtps::DurabilityKind_t durability_qos = fastrtps::rtps::DurabilityKind_t::VOLATILE)
{
using namespace fastrtps::rtps;
HistoryAttributes history_attributes;
history_attributes.payloadMaxSize = payloadMaxSize;
reader_history_ = new ReaderHistory(history_attributes);
ReaderAttributes r_att;
r_att.endpoint.reliabilityKind = reliability_qos;
r_att.endpoint.durabilityKind = durability_qos;
reader_ = RTPSDomain::createRTPSReader(participant_, r_att, reader_history_);
}
void create_writer(
uint32_t payloadMaxSize,
fastrtps::rtps::ReliabilityKind_t reliability_qos = fastrtps::rtps::ReliabilityKind_t::RELIABLE,
fastrtps::rtps::DurabilityKind_t durability_qos = fastrtps::rtps::DurabilityKind_t::TRANSIENT_LOCAL)
{
using namespace fastrtps::rtps;
HistoryAttributes history_attributes;
history_attributes.payloadMaxSize = payloadMaxSize;
writer_history_ = new WriterHistory(history_attributes);
WriterAttributes w_att;
w_att.times.heartbeatPeriod.seconds = 0;
w_att.times.heartbeatPeriod.nanosec = 250 * 1000 * 1000; // reduce acknowledgement wait
w_att.endpoint.reliabilityKind = reliability_qos;
w_att.endpoint.durabilityKind = durability_qos;
writer_ = RTPSDomain::createRTPSWriter(participant_, w_att, writer_history_);
}
void create_lazy_writer(
uint32_t payloadMaxSize,
fastrtps::rtps::ReliabilityKind_t reliability_qos = fastrtps::rtps::ReliabilityKind_t::RELIABLE,
fastrtps::rtps::DurabilityKind_t durability_qos = fastrtps::rtps::DurabilityKind_t::TRANSIENT_LOCAL)
{
using namespace fastrtps::rtps;
HistoryAttributes history_attributes;
history_attributes.payloadMaxSize = payloadMaxSize;
writer_history_ = new WriterHistory(history_attributes);
WriterAttributes w_att;
w_att.times.heartbeatPeriod.seconds = 3;
w_att.times.heartbeatPeriod.nanosec = 0;
w_att.times.nackResponseDelay.seconds = 0;
w_att.times.nackResponseDelay.nanosec = 300 * 1000 * 1000; // increase ACKNACK response delay
w_att.endpoint.reliabilityKind = reliability_qos;
w_att.endpoint.durabilityKind = durability_qos;
writer_ = RTPSDomain::createRTPSWriter(participant_, w_att, writer_history_);
}
void create_endpoints(
uint32_t payloadMaxSize,
fastrtps::rtps::ReliabilityKind_t reliability_qos = fastrtps::rtps::ReliabilityKind_t::RELIABLE)
{
create_reader(payloadMaxSize, reliability_qos);
create_writer(payloadMaxSize, reliability_qos);
}
void match_endpoints(
bool key,
fastrtps::string_255 data_type,
fastrtps::string_255 topic_name)
{
using namespace fastrtps;
using namespace fastrtps::rtps;
TopicAttributes Tatt;
Tatt.topicKind = key ? TopicKind_t::WITH_KEY : TopicKind_t::NO_KEY;
Tatt.topicDataType = data_type;
Tatt.topicName = topic_name;
WriterQos Wqos;
auto& watt = writer_->getAttributes();
Wqos.m_durability.durabilityKind(watt.durabilityKind);
Wqos.m_reliability.kind =
RELIABLE ==
watt.reliabilityKind ? RELIABLE_RELIABILITY_QOS : BEST_EFFORT_RELIABILITY_QOS;
ReaderQos Rqos;
auto& ratt = writer_->getAttributes();
Rqos.m_durability.durabilityKind(ratt.durabilityKind);
Rqos.m_reliability.kind =
RELIABLE ==
ratt.reliabilityKind ? RELIABLE_RELIABILITY_QOS : BEST_EFFORT_RELIABILITY_QOS;
participant_->registerWriter(writer_, Tatt, Wqos);
participant_->registerReader(reader_, Tatt, Rqos);
}
void destroy_endpoints()
{
using namespace fastrtps::rtps;
if (nullptr != writer_ )
{
RTPSDomain::removeRTPSWriter(writer_);
delete writer_history_;
writer_ = nullptr;
writer_history_ = nullptr;
}
if (nullptr != reader_)
{
RTPSDomain::removeRTPSReader(reader_);
delete reader_history_;
reader_ = nullptr;
reader_history_ = nullptr;
}
}
void write_small_sample(
uint32_t length)
{
using namespace fastrtps::rtps;
ASSERT_NE(nullptr, writer_);
auto writer_change = writer_->new_change(
[length]() -> uint32_t
{
return length;
},
ALIVE);
ASSERT_NE(nullptr, writer_change);
std::string str("https://github.com/eProsima/Fast-DDS.git");
memcpy(writer_change->serializedPayload.data, str.c_str(), str.length());
writer_change->serializedPayload.length = (uint32_t)str.length();
ASSERT_TRUE(writer_history_->add_change(writer_change));
}
void write_large_sample(
uint32_t length,
uint16_t fragment_size)
{
using namespace fastrtps::rtps;
ASSERT_NE(nullptr, writer_);
auto writer_change = writer_->new_change(
[length]() -> uint32_t
{
return length;
},
ALIVE);
ASSERT_NE(nullptr, writer_change);
{
memset(writer_change->serializedPayload.data, 'e', length);
writer_change->serializedPayload.length = length;
writer_change->setFragmentSize(fragment_size, true);
}
ASSERT_TRUE(writer_history_->add_change(writer_change));
}
};
class RTPSStatisticsTests
: public ::testing::Test
, public RTPSStatisticsTestsImpl
{
public:
// Sets up the test fixture.
void SetUp() override
{
using namespace fastrtps;
// Intraprocess must be disable in order to receive DATA callbacks
LibrarySettingsAttributes att;
att.intraprocess_delivery = INTRAPROCESS_OFF;
xmlparser::XMLProfileManager::library_settings(att);
create_participant();
}
// Tears down the test fixture.
void TearDown() override
{
remove_participant();
}
};
/*
* This test checks RTPSParticipant, RTPSWriter and RTPSReader statistics module related APIs.
* Creates dummy listener objects and associates them to RTPS entities of each kind covering
* the different possible cases: already registered, non-registered, already unregistered.
*/
TEST_F(RTPSStatisticsTests, statistics_rpts_listener_management)
{
// Check API add and remove interfaces
using namespace std;
using namespace fastrtps::rtps;
// Create the testing endpoints
create_endpoints(255);
auto listener1 = make_shared<MockListener>();
auto listener2 = make_shared<MockListener>();
auto nolistener = listener1;
nolistener.reset();
EventKind kind = EventKind::PUBLICATION_THROUGHPUT;
EventKind another_kind = EventKind::SUBSCRIPTION_THROUGHPUT;
EventKind yet_another_kind = EventKind::NETWORK_LATENCY;
// test the participant apis
// + fails to remove an empty listener
EXPECT_FALSE(participant_->remove_statistics_listener(nolistener, kind));
// + fails if no listener has been yet added
EXPECT_FALSE(participant_->remove_statistics_listener(listener1, kind));
// + fails to add an empty listener
EXPECT_FALSE(participant_->add_statistics_listener(nolistener, kind));
// + succeeds to add a new listener
ASSERT_TRUE(participant_->add_statistics_listener(listener1, kind));
// + fails to add multiple times the same listener...
EXPECT_FALSE(participant_->add_statistics_listener(listener1, kind));
// ... unless it's associated to other entity
EXPECT_TRUE(participant_->add_statistics_listener(listener1, another_kind));
// + fails if an unknown listener is removed
EXPECT_FALSE(participant_->remove_statistics_listener(listener2, kind));
// + fails if a known listener is removed with a non registered entity
EXPECT_FALSE(participant_->remove_statistics_listener(listener1, yet_another_kind));
// + succeeds to remove a known listener
EXPECT_TRUE(participant_->remove_statistics_listener(listener1, kind));
EXPECT_TRUE(participant_->remove_statistics_listener(listener1, another_kind));
// + fails if a listener is already removed
EXPECT_FALSE(participant_->remove_statistics_listener(listener1, kind));
// + The EventKind is an actual mask that allow register multiple entities simultaneously
EXPECT_TRUE(participant_->add_statistics_listener(listener1, kind | another_kind));
// + When using a mask of multiple entities the return value succeeds only if all
// entity driven operations succeeds. The following operation must fail because one
// of the entities has not that registered listener
EXPECT_FALSE(participant_->remove_statistics_listener(listener1,
kind | another_kind | yet_another_kind));
// test the writer apis
// + fails to remove an empty listener
EXPECT_FALSE(writer_->remove_statistics_listener(nolistener));
// + fails if no listener has been yet added
EXPECT_FALSE(writer_->remove_statistics_listener(listener1));
// + fails to add an empty listener
EXPECT_FALSE(writer_->add_statistics_listener(nolistener));
// + succeeds to add a new listener
ASSERT_TRUE(writer_->add_statistics_listener(listener1));
// + fails to add multiple times the same listener
EXPECT_FALSE(writer_->add_statistics_listener(listener1));
// + fails if an unknown listener is removed
EXPECT_FALSE(writer_->remove_statistics_listener(listener2));
// + succeeds to remove a known listener
EXPECT_TRUE(writer_->remove_statistics_listener(listener1));
// + fails if a listener is already removed
EXPECT_FALSE(writer_->remove_statistics_listener(listener1));
// test the reader apis
// + fails to remove an empty listener
EXPECT_FALSE(reader_->remove_statistics_listener(nolistener));
// + fails if no listener has been yet added
EXPECT_FALSE(reader_->remove_statistics_listener(listener1));
// + fails to add an empty listener
EXPECT_FALSE(reader_->add_statistics_listener(nolistener));
// + succeeds to add a new listener
ASSERT_TRUE(reader_->add_statistics_listener(listener1));
// + fails to add multiple times the same listener
EXPECT_FALSE(reader_->add_statistics_listener(listener1));
// + fails if an unknown listener is removed
EXPECT_FALSE(reader_->remove_statistics_listener(listener2));
// + succeeds to remove a known listener
EXPECT_TRUE(reader_->remove_statistics_listener(listener1));
// + fails if a listener is already removed
EXPECT_FALSE(reader_->remove_statistics_listener(listener1));
}
/*
* This test checks RTPSParticipant, RTPSWriter and RTPSReader statistics module related APIs.
* - RTPS_SENT callbacks are performed
* - DATA_COUNT callbacks are performed for DATA submessages
* - RESENT_DATAS callbacks are performed for DATA submessages demanded by the readers
* - ACKNACK_COUNT callbacks are performed
* - HEARBEAT_COUNT callbacks are performed
*/
TEST_F(RTPSStatisticsTests, statistics_rpts_listener_callbacks)
{
using namespace ::testing;
using namespace fastrtps;
using namespace fastrtps::rtps;
using namespace std;
// make sure some messages are lost to assure the RESENT_DATAS callback
set_transport_filter(
DATA,
[](fastrtps::rtps::CDRMessage_t& msg)-> bool
{
static unsigned int samples_filtered = 0;
uint32_t old_pos = msg.pos;
// see RTPS DDS 9.4.5.3 Data Submessage
EntityId_t readerID, writerID;
SequenceNumber_t sn;
msg.pos += 2; // flags
msg.pos += 2; // octets to inline quos
CDRMessage::readEntityId(&msg, &readerID);
CDRMessage::readEntityId(&msg, &writerID);
CDRMessage::readSequenceNumber(&msg, &sn);
// restore buffer pos
msg.pos = old_pos;
// generate losses
if ( samples_filtered < 10 // only a few times (mind the interfaces)
&& (writerID.value[3] & 0xC0) == 0 // only user endpoints
&& (sn == SequenceNumber_t{0, 1})) // only first sample
{
++samples_filtered;
return true;
}
return false;
});
// create the testing endpoints
uint16_t length = 255;
create_endpoints(length, RELIABLE);
// participant specific callbacks
auto participant_listener = make_shared<MockListener>();
ASSERT_TRUE(participant_->add_statistics_listener(participant_listener, EventKind::RTPS_SENT));
// writer callbacks through participant listener
auto participant_writer_listener = make_shared<MockListener>();
ASSERT_TRUE(participant_->add_statistics_listener(participant_writer_listener,
EventKind::DATA_COUNT | EventKind::RESENT_DATAS));
// writer specific callbacks
auto writer_listener = make_shared<MockListener>();
ASSERT_TRUE(writer_->add_statistics_listener(writer_listener));
// reader callbacks through participant listener
auto participant_reader_listener = make_shared<MockListener>();
ASSERT_TRUE(participant_->add_statistics_listener(participant_reader_listener, EventKind::ACKNACK_COUNT));
// reader specific callbacks
auto reader_listener = make_shared<MockListener>();
ASSERT_TRUE(reader_->add_statistics_listener(reader_listener));
// we must received the RTPS_SENT notifications
EXPECT_CALL(*participant_listener, on_rtps_sent)
.Times(AtLeast(1));
// Check callbacks on data exchange, at least, we must received:
// + RTPSWriter: PUBLICATION_THROUGHPUT, RESENT_DATAS,
// GAP_COUNT, DATA_COUNT, SAMPLE_DATAS & PHYSICAL_DATA
// optionally: NACKFRAG_COUNT
EXPECT_CALL(*writer_listener, on_heartbeat_count)
.Times(AtLeast(1));
EXPECT_CALL(*writer_listener, on_data_count)
.Times(AtLeast(1));
EXPECT_CALL(*writer_listener, on_resent_count)
.Times(AtLeast(1));
EXPECT_CALL(*participant_writer_listener, on_data_count)
.Times(AtLeast(1));
EXPECT_CALL(*participant_writer_listener, on_resent_count)
.Times(AtLeast(1));
// + RTPSReader: SUBSCRIPTION_THROUGHPUT,
// SAMPLE_DATAS & PHYSICAL_DATA
// optionally: ACKNACK_COUNT
EXPECT_CALL(*reader_listener, on_acknack_count)
.Times(AtLeast(1));
EXPECT_CALL(*participant_reader_listener, on_acknack_count)
.Times(AtLeast(1));
// match writer and reader on a dummy topic
match_endpoints(false, "string", "statisticsSmallTopic");
// exchange data
write_small_sample(length);
// wait for reception
EXPECT_TRUE(reader_->wait_for_unread_cache(Duration_t(5, 0)));
// receive the sample
CacheChange_t* reader_change = nullptr;
ASSERT_TRUE(reader_->nextUntakenCache(&reader_change, nullptr));
// wait for acknowledgement
EXPECT_TRUE(writer_->wait_for_all_acked(Duration_t(5, 0)));
reader_->releaseCache(reader_change);
EXPECT_TRUE(writer_->remove_statistics_listener(writer_listener));
EXPECT_TRUE(reader_->remove_statistics_listener(reader_listener));
EXPECT_TRUE(participant_->remove_statistics_listener(participant_listener, EventKind::RTPS_SENT));
EXPECT_TRUE(participant_->remove_statistics_listener(participant_writer_listener,
EventKind::DATA_COUNT | EventKind::RESENT_DATAS));
EXPECT_TRUE(participant_->remove_statistics_listener(participant_reader_listener, EventKind::ACKNACK_COUNT));
}
/*
* This test checks RTPSParticipant, RTPSWriter and RTPSReader statistics module related APIs.
* - participant listeners management with late joiners
* - DATA_COUNT callbacks with DATA_FRAGS are performed
* - NACK_FRAG callbacks assessment
*/
TEST_F(RTPSStatisticsTests, statistics_rpts_listener_callbacks_fragmented)
{
using namespace ::testing;
using namespace fastrtps;
using namespace fastrtps::rtps;
using namespace std;
// payload size
uint32_t length = 1048576;
uint16_t fragment_size = 64000; // should fit in transport message size
// make sure some messages are lost to assure the NACKFRAG callback
set_transport_filter(
DATA_FRAG,
[](fastrtps::rtps::CDRMessage_t& msg)-> bool
{
static uint32_t max_fragment = 0;
static bool keep_filtering = true;
uint32_t fragmentNum;
uint32_t old_pos = msg.pos;
msg.pos += 20;
fastrtps::rtps::CDRMessage::readUInt32(&msg, &fragmentNum);
msg.pos = old_pos;
// generate losses only on the first burst
if ( keep_filtering )
{
keep_filtering = max_fragment <= fragmentNum;
max_fragment = fragmentNum;
return fragmentNum % 2 == 0;
}
return false;
});
// writer callbacks through participant listener
auto participant_listener = make_shared<MockListener>();
uint32_t mask = EventKind::DATA_COUNT | EventKind::HEARTBEAT_COUNT
| EventKind::ACKNACK_COUNT | EventKind::NACKFRAG_COUNT;
ASSERT_TRUE(participant_->add_statistics_listener(participant_listener, mask));
EXPECT_CALL(*participant_listener, on_data_count)
.Times(AtLeast(1));
EXPECT_CALL(*participant_listener, on_heartbeat_count)
.Times(AtLeast(1));
EXPECT_CALL(*participant_listener, on_acknack_count)
.Times(AtLeast(1));
EXPECT_CALL(*participant_listener, on_nackfrag_count)
.Times(AtLeast(1));
// Create the testing endpoints
create_endpoints(length, RELIABLE);
// match writer and reader on a dummy topic
match_endpoints(false, "chunk", "statisticsLargeTopic");
// exchange data
write_large_sample(length, fragment_size);
// wait for reception
EXPECT_TRUE(reader_->wait_for_unread_cache(Duration_t(10, 0)));
// receive the sample
CacheChange_t* reader_change = nullptr;
ASSERT_TRUE(reader_->nextUntakenCache(&reader_change, nullptr));
// wait for acknowledgement
EXPECT_TRUE(writer_->wait_for_all_acked(Duration_t(1, 0)));
reader_->releaseCache(reader_change);
EXPECT_TRUE(participant_->remove_statistics_listener(participant_listener, mask));
}
/*
* This test checks RTPSWriter GAP_COUNT statistics callback
*/
TEST_F(RTPSStatisticsTests, statistics_rpts_listener_gap_callback)
{
using namespace ::testing;
using namespace fastrtps;
using namespace fastrtps::rtps;
using namespace std;
// create the listeners and set expectations
auto participant_writer_listener = make_shared<MockListener>();
auto writer_listener = make_shared<MockListener>();
// check callbacks on data exchange
EXPECT_CALL(*writer_listener, on_gap_count)
.Times(AtLeast(1));
EXPECT_CALL(*writer_listener, on_heartbeat_count)
.Times(AtLeast(1));
EXPECT_CALL(*writer_listener, on_data_count)
.Times(AtLeast(1));
EXPECT_CALL(*writer_listener, on_resent_count)
.Times(AtLeast(1));
EXPECT_CALL(*participant_writer_listener, on_gap_count)
.Times(AtLeast(1));
// create the writer, reader is a late joiner
uint16_t length = 255;
create_writer(length, RELIABLE, TRANSIENT_LOCAL);
// writer callback through participant listener
ASSERT_TRUE(participant_->add_statistics_listener(participant_writer_listener, EventKind::GAP_COUNT));
// writer specific callbacks
ASSERT_TRUE(writer_->add_statistics_listener(writer_listener));
// add a sample to the writer history that will be delivered
write_small_sample(length);
// add a second sample and remove it to generate the gap
write_small_sample(length);
ASSERT_TRUE(writer_history_->remove_change(SequenceNumber_t{0, 2}));
// create the late joiner as VOLATILE
create_reader(length, RELIABLE, VOLATILE);
// match writer and reader on a dummy topic
match_endpoints(false, "string", "statisticsSmallTopic");
// wait for reception
EXPECT_TRUE(reader_->wait_for_unread_cache(Duration_t(5, 0)));
// receive the second sample
CacheChange_t* reader_change = nullptr;
ASSERT_TRUE(reader_->nextUntakenCache(&reader_change, nullptr));
// wait for acknowledgement
EXPECT_TRUE(writer_->wait_for_all_acked(Duration_t(1, 0)));
reader_->releaseCache(reader_change);
// release the listeners
EXPECT_TRUE(writer_->remove_statistics_listener(writer_listener));
EXPECT_TRUE(participant_->remove_statistics_listener(participant_writer_listener, EventKind::GAP_COUNT));
}
/*
* This test checks the participant discovery callbacks
*/
TEST_F(RTPSStatisticsTests, statistics_rpts_listener_discovery_callbacks)
{
using namespace ::testing;
using namespace fastrtps;
using namespace fastrtps::rtps;
using namespace std;
// create the listener and set expectations
auto participant_listener = make_shared<MockListener>();
ASSERT_TRUE(participant_->add_statistics_listener(participant_listener,
EventKind::DISCOVERED_ENTITY | EventKind::PDP_PACKETS));
// check callbacks on data exchange
atomic_int callbacks(0);
ON_CALL(*participant_listener, on_entity_discovery)
.WillByDefault([&callbacks](const eprosima::fastdds::statistics::DiscoveryTime&)
{
++callbacks;
});
EXPECT_CALL(*participant_listener, on_entity_discovery)
.Times(AtLeast(5));
EXPECT_CALL(*participant_listener, on_pdp_packets)
.Times(AtLeast(1));
// create local endpoints
uint16_t length = 255;
create_endpoints(length);
// register local endpoints
match_endpoints(false, "string", "statisticsSmallTopic");
// create remote endpoints and register them
{
RTPSStatisticsTestsImpl remote;
remote.create_participant();
remote.create_endpoints(length);
remote.match_endpoints(false, "string", "statisticsSmallTopic");
int loop = 0;
while ( callbacks < 5 )
{
this_thread::sleep_for(chrono::milliseconds(100));
if ( ++loop > 30 )
{
break;
}
}
remote.remove_participant();
}
// release the listener
EXPECT_TRUE(participant_->remove_statistics_listener(participant_listener, EventKind::DISCOVERED_ENTITY));
}
/*
* This test checks improves coverity by asserting that every RESENT_DATAS callback is associated with a message
*/
TEST_F(RTPSStatisticsTests, statistics_rpts_avoid_empty_resent_callbacks)
{
using namespace ::testing;
using namespace fastrtps;
using namespace fastrtps::rtps;
using namespace std;
// The history must be cleared after the acknack is received
// but before the response is processed
atomic_bool acknack_sent(false);
// filter out all user DATAs
set_transport_filter(
DATA,
[](fastrtps::rtps::CDRMessage_t& msg)-> bool
{
uint32_t old_pos = msg.pos;
// see RTPS DDS 9.4.5.3 Data Submessage
EntityId_t readerID, writerID;
SequenceNumber_t sn;
msg.pos += 2; // flags
msg.pos += 2; // octets to inline quos
CDRMessage::readEntityId(&msg, &readerID);
CDRMessage::readEntityId(&msg, &writerID);
CDRMessage::readSequenceNumber(&msg, &sn);
// restore buffer pos
msg.pos = old_pos;
// filter user traffic
return ((writerID.value[3] & 0xC0) == 0);
});
set_transport_filter(
ACKNACK,
[&acknack_sent](fastrtps::rtps::CDRMessage_t& msg)-> bool
{
uint32_t old_pos = msg.pos;
// see RTPS DDS 9.4.5.2 Acknack Submessage
EntityId_t readerID, writerID;
SequenceNumberSet_t snSet;
CDRMessage::readEntityId(&msg, &readerID);
CDRMessage::readEntityId(&msg, &writerID);
snSet = CDRMessage::readSequenceNumberSet(&msg);
// restore buffer pos
msg.pos = old_pos;
// The acknack has been sent
acknack_sent = !snSet.empty();
// we are not filtering
return false;
});
// create the listeners and set expectations
auto writer_listener = make_shared<MockListener>();
// check callbacks on data exchange
EXPECT_CALL(*writer_listener, on_heartbeat_count)
.Times(AtLeast(1));
EXPECT_CALL(*writer_listener, on_data_count)
.Times(AtLeast(1));
EXPECT_CALL(*writer_listener, on_resent_count)
.Times(0); // never called
// create the writer, reader is a late joiner
uint16_t length = 255;
create_lazy_writer(length, RELIABLE, TRANSIENT_LOCAL);
// writer specific callbacks
ASSERT_TRUE(writer_->add_statistics_listener(writer_listener));
// create the late joiner as VOLATILE
create_reader(length, RELIABLE, VOLATILE);
// match writer and reader on a dummy topic
match_endpoints(false, "string", "statisticsSmallTopic");
// add a sample to the writer history that cannot be delivered
// due to the filter
write_small_sample(length);
// wait for the acknack to be sent before clearing the history
while (!acknack_sent)
{
this_thread::sleep_for(chrono::milliseconds(100));
}
// remove the sample from the writer
ASSERT_TRUE(writer_history_->remove_change(SequenceNumber_t{ 0, 1 }));
// give room to process the ACKNACK
this_thread::sleep_for(chrono::milliseconds(400));
// release the listeners
EXPECT_TRUE(writer_->remove_statistics_listener(writer_listener));
}
} // namespace rtps
} // namespace statistics
} // namespace fastdds
} // namespace eprosima
int main(
int argc,
char** argv)
{
eprosima::fastdds::dds::Log::SetVerbosity(eprosima::fastdds::dds::Log::Error);
testing::InitGoogleTest(&argc, argv);
int ret = RUN_ALL_TESTS();
eprosima::fastdds::dds::Log::Flush();
return ret;
}
|
/**
* @file <argos3/plugins/simulator/actuators/differential_steering_default_actuator.cpp>
*
* @author Carlo Pinciroli - <ilpincy@gmail.com>
*/
#include "differential_steering_default_actuator.h"
#include <argos3/core/utility/logging/argos_log.h>
#include <argos3/core/utility/plugins/factory.h>
namespace argos {
/****************************************/
/****************************************/
CDifferentialSteeringDefaultActuator::CDifferentialSteeringDefaultActuator() :
m_pcWheeledEntity(NULL),
m_pcRNG(NULL) {
m_fCurrentVelocity[LEFT_WHEEL] = 0.0;
m_fCurrentVelocity[RIGHT_WHEEL] = 0.0;
m_fNoiseBias[LEFT_WHEEL] = 1.0;
m_fNoiseBias[RIGHT_WHEEL] = 1.0;
m_fNoiseFactorAvg[LEFT_WHEEL] = 1.0;
m_fNoiseFactorAvg[RIGHT_WHEEL] = 1.0;
m_fNoiseFactorStdDev[LEFT_WHEEL] = 0.0;
m_fNoiseFactorStdDev[RIGHT_WHEEL] = 0.0;
}
/****************************************/
/****************************************/
void CDifferentialSteeringDefaultActuator::SetRobot(CComposableEntity& c_entity) {
try {
m_pcWheeledEntity = &(c_entity.GetComponent<CWheeledEntity>("wheels"));
if(m_pcWheeledEntity->GetNumWheels() != 2) {
THROW_ARGOSEXCEPTION("The differential steering actuator can be associated only to a robot with 2 wheels");
}
m_pcWheeledEntity->Enable();
}
catch(CARGoSException& ex) {
THROW_ARGOSEXCEPTION_NESTED("Error setting differential steering actuator to entity \"" << c_entity.GetId() << "\"", ex);
}
}
/****************************************/
/****************************************/
#define CHECK_ATTRIBUTE(ATTR) \
(NodeAttributeExists(t_tree, ATTR) || \
NodeAttributeExists(t_tree, ATTR "_left") || \
NodeAttributeExists(t_tree, ATTR "_right"))
#define PARSE_ATTRIBUTES(ATTR, VAR) \
GetNodeAttributeOrDefault<Real>(t_tree, ATTR, VAR[LEFT_WHEEL], VAR[LEFT_WHEEL]); \
VAR[RIGHT_WHEEL] = VAR[LEFT_WHEEL]; \
GetNodeAttributeOrDefault<Real>(t_tree, ATTR "_left", VAR[LEFT_WHEEL], VAR[LEFT_WHEEL]); \
GetNodeAttributeOrDefault<Real>(t_tree, ATTR "_right", VAR[RIGHT_WHEEL], VAR[RIGHT_WHEEL]);
#define PICK_BIAS(LRW) m_fNoiseBias[LRW ## _WHEEL] = m_pcRNG->Gaussian(fNoiseBiasStdDev[LRW ## _WHEEL], fNoiseBiasAvg[LRW ## _WHEEL])
void CDifferentialSteeringDefaultActuator::Init(TConfigurationNode& t_tree) {
try {
CCI_DifferentialSteeringActuator::Init(t_tree);
/* Check if any noise attribute was specified */
bool bNoise =
CHECK_ATTRIBUTE("bias_avg") ||
CHECK_ATTRIBUTE("bias_stddev") ||
CHECK_ATTRIBUTE("factor_avg") ||
CHECK_ATTRIBUTE("factor_stddev");
/* Handle noise attributes, if any */
if(bNoise) {
/* Create RNG */
m_pcRNG = CRandom::CreateRNG("argos");
/* Parse noise attributes */
Real fNoiseBiasAvg[2];
Real fNoiseBiasStdDev[2];
PARSE_ATTRIBUTES("bias_avg", fNoiseBiasAvg);
PARSE_ATTRIBUTES("bias_stddev", fNoiseBiasStdDev);
PARSE_ATTRIBUTES("factor_avg", m_fNoiseFactorAvg);
PARSE_ATTRIBUTES("factor_stddev", m_fNoiseFactorStdDev);
/* Choose robot bias */
PICK_BIAS(LEFT);
PICK_BIAS(RIGHT);
}
}
catch(CARGoSException& ex) {
THROW_ARGOSEXCEPTION_NESTED("Initialization error in foot-bot steering actuator.", ex);
}
}
/****************************************/
/****************************************/
#define ADD_GAUSSIAN(LRW) \
(m_fNoiseFactorStdDev[LRW ## _WHEEL] > 0.0 ? \
m_pcRNG->Gaussian(m_fNoiseFactorStdDev[LRW ## _WHEEL], \
m_fNoiseFactorAvg[LRW ## _WHEEL]) : \
m_fNoiseFactorAvg[LRW ## _WHEEL])
#define ADD_NOISE(LRW) \
m_fCurrentVelocity[LRW ## _WHEEL] = \
ADD_GAUSSIAN(LRW) \
* \
(m_fCurrentVelocity[LRW ## _WHEEL] + \
m_fNoiseBias[LRW ## _WHEEL]);
void CDifferentialSteeringDefaultActuator::SetLinearVelocity(Real f_left_velocity,
Real f_right_velocity) {
/* Convert speeds in m/s */
m_fCurrentVelocity[LEFT_WHEEL] = f_left_velocity * 0.01;
m_fCurrentVelocity[RIGHT_WHEEL] = f_right_velocity * 0.01;
/* Apply noise */
if(m_pcRNG) {
ADD_NOISE(LEFT);
ADD_NOISE(RIGHT);
}
}
/****************************************/
/****************************************/
void CDifferentialSteeringDefaultActuator::Update() {
m_pcWheeledEntity->SetVelocities(m_fCurrentVelocity);
}
/****************************************/
/****************************************/
void CDifferentialSteeringDefaultActuator::Reset() {
/* Zero the speeds */
m_fCurrentVelocity[LEFT_WHEEL] = 0.0;
m_fCurrentVelocity[RIGHT_WHEEL] = 0.0;
/*
* Throw away two RNG Gaussian calls to make sure the RNG sequence is the same after resetting
* These two calls were used to pick the bias in Init()
*/
if(m_pcRNG) {
m_pcRNG->Gaussian(1.0, 0.0);
m_pcRNG->Gaussian(1.0, 0.0);
}
}
/****************************************/
/****************************************/
}
REGISTER_ACTUATOR(CDifferentialSteeringDefaultActuator,
"differential_steering", "default",
"Carlo Pinciroli [ilpincy@gmail.com]",
"1.0",
"The differential steering actuator.",
"This actuator controls the two wheels a differential steering robot. For a\n"
"complete description of its usage, refer to the\n"
"ci_differential_steering_actuator.h file.\n\n"
"REQUIRED XML CONFIGURATION\n\n"
" <controllers>\n"
" ...\n"
" <my_controller ...>\n"
" ...\n"
" <actuators>\n"
" ...\n"
" <differential_steering implementation=\"default\" />\n"
" ...\n"
" </actuators>\n"
" ...\n"
" </my_controller>\n"
" ...\n"
" </controllers>\n\n"
"OPTIONAL XML CONFIGURATION\n\n"
"It is possible to specify noisy speed in order to match the characteristics\n"
"of the real robot. For each wheel, the noise model is as follows:\n\n"
"w = ideal wheel actuation (as set in the controller)\n"
"b = random bias from a Gaussian distribution\n"
"f = random factor from a Gaussian distribution\n"
"a = actual actuated value\n\n"
"a = f * (w + b)\n\n"
"You can configure the average and stddev of both the bias and the factor. This\n"
"can be done with the optional attributes: 'bias_avg', 'bias_stddev',\n"
"'factor_avg', and 'factor_stddev'. Bias attributes are expressed in m/s, while\n"
"factor attributes are dimensionless. If none of these attributed is specified,\n"
"no noise is added. If at least one of these attributed is specified, noise is\n"
"added and, for the non-specified attributes, the default value of 1 is used for\n"
"the '*_avg' attributes, while 0 is used for '*_stddev' attributes. Examples:\n\n"
" <controllers>\n"
" ...\n"
" <my_controller ...>\n"
" ...\n"
" <actuators>\n"
" ...\n"
" <!-- Only the stddev of the bias\n"
" Noise is on, other attributes are default -->\n"
" <differential_steering implementation=\"default\"\n"
" bias_stddev=\"2\" />\n"
" <!-- Only the stddev of the factor\n"
" Noise is on, other attributes are default -->\n"
" <differential_steering implementation=\"default\"\n"
" factor_stddev=\"4\" />\n"
" <!-- All attributes set\n"
" Noise is on, specified values are set -->\n"
" <differential_steering implementation=\"default\"\n"
" bias_avg=\"1\"\n"
" bias_stddev=\"2\"\n"
" factor_avg=\"3\"\n"
" factor_stddev=\"4\" />\n"
" ...\n"
" </actuators>\n"
" ...\n"
" </my_controller>\n"
" ...\n"
" </controllers>\n\n"
"The above examples set the same noise for both wheels. If you want to set\n"
"different noise parameters for each wheel, append '_left' and '_right' to the\n"
"attribute names:\n\n"
" <controllers>\n"
" ...\n"
" <my_controller ...>\n"
" ...\n"
" <actuators>\n"
" ...\n"
" <!-- Mix of wheel-specific attributes set\n"
" Noise is on, specified values are set -->\n"
" <differential_steering implementation=\"default\"\n"
" bias_avg_left=\"1\"\n"
" bias_stddev_right=\"2\"\n"
" factor_avg_left=\"3\"\n"
" factor_stddev_right=\"4\" />\n"
" ...\n"
" </actuators>\n"
" ...\n"
" </my_controller>\n"
" ...\n"
" </controllers>\n\n"
"Wheel-specific attributes overwrite the values of non-wheel specific attributes.\n"
"So, if you set 'bias_avg' = 2 and then 'bias_avg_left' = 3, the left wheel will\n"
"use 3 and the right wheel will use 2.\n\n"
"Physics-engine-specific attributes that affect this actuator might also be\n"
"available. Check the documentation of the physics engine you're using for more\n"
"information.",
"Usable"
);
|
//
// Created by Zhuo Chen on 2019-06-01.
//
#ifndef DM_DELETE_STATEMENT_HPP
#define DM_DELETE_STATEMENT_HPP
#include "../../../common/common.hpp"
class Delete_Statement: public Statement
{
std::string table_name;
ExpressionList * delete_cond;
public:
Delete_Statement(const std::string & table_name, ExpressionList * delete_condition);
virtual StatementType type() const;
virtual DMType args(int op = 0) const;
virtual ~Delete_Statement();
};
#endif //DM_DELETE_STATEMENT_HPP
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.