text
stringlengths 8
6.88M
|
|---|
// Copyright 2017 Elias Kosunen
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// https://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
// This file is a part of scnlib:
// https://github.com/eliaskosunen/scnlib
#if defined(SCN_HEADER_ONLY) && SCN_HEADER_ONLY
#define SCN_FILE_CPP
#endif
#include <scn/detail/error.h>
#include <scn/detail/file.h>
#include <scn/util/expected.h>
#include <cstdio>
#if SCN_POSIX
#include <fcntl.h>
#include <sys/mman.h>
#include <sys/stat.h>
#include <sys/types.h>
#include <unistd.h>
#elif SCN_WINDOWS
#ifdef WIN32_LEAN_AND_MEAN
#define SCN_WIN32_LEAN_DEFINED 1
#else
#define WIN32_LEAN_AND_MEAN
#define SCN_WIN32_LEAN_DEFINED 0
#endif
#ifdef NOMINMAX
#define SCN_NOMINMAX_DEFINED 1
#else
#define NOMINMAX
#define SCN_NOMINMAX_DEFINED 0
#endif
#include <Windows.h>
#if !SCN_NOMINMAX_DEFINED
#undef NOMINMAX
#endif
#if !SCN_WIN32_LEAN_DEFINED
#undef WIN32_LEAN_AND_MEAN
#endif
#endif
namespace scn {
SCN_BEGIN_NAMESPACE
namespace detail {
SCN_FUNC native_file_handle native_file_handle::invalid()
{
#if SCN_WINDOWS
return {INVALID_HANDLE_VALUE};
#else
return {-1};
#endif
}
SCN_FUNC byte_mapped_file::byte_mapped_file(const char* filename)
{
#if SCN_POSIX
int fd = open(filename, O_RDONLY);
if (fd == -1) {
return;
}
struct stat s {
};
int status = fstat(fd, &s);
if (status == -1) {
close(fd);
return;
}
auto size = s.st_size;
auto ptr =
static_cast<char*>(mmap(nullptr, static_cast<size_t>(size),
PROT_READ, MAP_PRIVATE, fd, 0));
if (ptr == MAP_FAILED) {
close(fd);
return;
}
m_file.handle = fd;
m_map = span<char>{ptr, static_cast<size_t>(size)};
#elif SCN_WINDOWS
auto f = ::CreateFileA(
filename, GENERIC_READ, FILE_SHARE_READ | FILE_SHARE_WRITE,
nullptr, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, nullptr);
if (f == INVALID_HANDLE_VALUE) {
return;
}
LARGE_INTEGER _size;
if (::GetFileSizeEx(f, &_size) == 0) {
::CloseHandle(f);
return;
}
auto size = static_cast<size_t>(_size.QuadPart);
auto h = ::CreateFileMappingA(
f, nullptr, PAGE_READONLY,
#ifdef _WIN64
static_cast<DWORD>(size >> 32ull),
#else
DWORD{0},
#endif
static_cast<DWORD>(size & 0xffffffffull), nullptr);
if (h == INVALID_HANDLE_VALUE || h == nullptr) {
::CloseHandle(f);
return;
}
auto start = ::MapViewOfFile(h, FILE_MAP_READ, 0, 0, size);
if (!start) {
::CloseHandle(h);
::CloseHandle(f);
return;
}
m_file.handle = f;
m_map_handle.handle = h;
m_map = span<char>{static_cast<char*>(start), size};
#else
SCN_UNUSED(filename);
#endif
}
SCN_FUNC void byte_mapped_file::_destruct()
{
#if SCN_POSIX
munmap(m_map.data(), m_map.size());
close(m_file.handle);
#elif SCN_WINDOWS
::CloseHandle(m_map_handle.handle);
::CloseHandle(m_file.handle);
m_map_handle = native_file_handle::invalid();
#endif
m_file = native_file_handle::invalid();
m_map = span<char>{};
SCN_ENSURE(!valid());
}
} // namespace detail
namespace detail {
template <typename CharT>
struct basic_file_iterator_access {
using iterator = typename basic_file<CharT>::iterator;
basic_file_iterator_access(const iterator& it) : self(it) {}
SCN_NODISCARD expected<CharT> deref() const
{
SCN_EXPECT(self.m_file);
if (self.m_file->m_buffer.empty()) {
// no chars have been read
return self.m_file->_read_single();
}
if (!self.m_last_error) {
// last read failed
return self.m_last_error;
}
return self.m_file->_get_char_at(self.m_current);
}
SCN_NODISCARD bool eq(const iterator& o) const
{
if (self.m_file && (self.m_file == o.m_file || !o.m_file)) {
if (self.m_file->_is_at_end(self.m_current) &&
self.m_last_error.code() != error::end_of_range &&
!o.m_file) {
self.m_last_error = error{};
auto r = self.m_file->_read_single();
if (!r) {
self.m_last_error = r.error();
return !o.m_file || self.m_current == o.m_current ||
o.m_last_error.code() == error::end_of_range;
}
}
}
// null file == null file
if (!self.m_file && !o.m_file) {
return true;
}
// null file == eof file
if (!self.m_file && o.m_file) {
// lhs null, rhs potentially eof
return o.m_last_error.code() == error::end_of_range;
}
// eof file == null file
if (self.m_file && !o.m_file) {
// rhs null, lhs potentially eof
return self.m_last_error.code() == error::end_of_range;
}
// eof file == eof file
if (self.m_last_error == o.m_last_error &&
self.m_last_error.code() == error::end_of_range) {
return true;
}
return self.m_file == o.m_file && self.m_current == o.m_current;
}
const iterator& self;
};
} // namespace detail
template <>
SCN_FUNC expected<char> basic_file<char>::iterator::operator*() const
{
return detail::basic_file_iterator_access<char>(*this).deref();
}
template <>
SCN_FUNC expected<wchar_t> basic_file<wchar_t>::iterator::operator*() const
{
return detail::basic_file_iterator_access<wchar_t>(*this).deref();
}
template <>
SCN_FUNC bool basic_file<char>::iterator::operator==(
const basic_file<char>::iterator& o) const
{
return detail::basic_file_iterator_access<char>(*this).eq(o);
}
template <>
SCN_FUNC bool basic_file<wchar_t>::iterator::operator==(
const basic_file<wchar_t>::iterator& o) const
{
return detail::basic_file_iterator_access<wchar_t>(*this).eq(o);
}
template <>
SCN_FUNC expected<char> file::_read_single() const
{
SCN_EXPECT(valid());
int tmp = std::fgetc(m_file);
if (tmp == EOF) {
if (std::feof(m_file) != 0) {
return error(error::end_of_range, "EOF");
}
if (std::ferror(m_file) != 0) {
return error(error::source_error, "fgetc error");
}
return error(error::unrecoverable_source_error,
"Unknown fgetc error");
}
auto ch = static_cast<char>(tmp);
m_buffer.push_back(ch);
return ch;
}
template <>
SCN_FUNC expected<wchar_t> wfile::_read_single() const
{
SCN_EXPECT(valid());
wint_t tmp = std::fgetwc(m_file);
if (tmp == WEOF) {
if (std::feof(m_file) != 0) {
return error(error::end_of_range, "EOF");
}
if (std::ferror(m_file) != 0) {
return error(error::source_error, "fgetc error");
}
return error(error::unrecoverable_source_error,
"Unknown fgetc error");
}
auto ch = static_cast<wchar_t>(tmp);
m_buffer.push_back(ch);
return ch;
}
template <>
SCN_FUNC void file::_sync_until(std::size_t pos) noexcept
{
for (auto it = m_buffer.rbegin();
it != m_buffer.rend() - static_cast<std::ptrdiff_t>(pos); ++it) {
std::ungetc(static_cast<unsigned char>(*it), m_file);
}
}
template <>
SCN_FUNC void wfile::_sync_until(std::size_t pos) noexcept
{
for (auto it = m_buffer.rbegin();
it != m_buffer.rend() - static_cast<std::ptrdiff_t>(pos); ++it) {
std::ungetwc(static_cast<wint_t>(*it), m_file);
}
}
SCN_END_NAMESPACE
} // namespace scn
|
#include <iostream>
#include <vector>
#include <iterator>
#include <algorithm>
#include <list>
#include <sequtils.h>
using namespace std;
int main(int argc, char *argv[])
{
list<int> col;
for (int i = 1; i <= 6; ++i) {
col.push_front(i);
col.push_back(i);
}
print_seq(col, "pre\t");
list<int>::iterator end = remove(col.begin(), col.end(), 3);
cout << "Number of removed elements " << distance(end, col.end()) << endl;
print_seq(col, "rem\t");
col.erase(end, col.end());
print_seq(col, "post\t");
return 0;
}
|
#include "SLAM.hpp"
using namespace std;
using namespace cv;
SLAM::LineFeature::LineFeature(const Mat_<imtype> & im, const CameraState & state,
const Point2f & pt2d, int rx, int ry)
:descriptor(im(Range(max(0, iround(pt2d.y-ry)),
min(im.size().height, iround(pt2d.y+ry+1))),
Range(max(0, iround(pt2d.x-rx)),
min(im.size().width, iround(pt2d.x+rx+1)))).clone()),
cone(state.getLocalCoordinatesPoint(pt2d), state.t, 3.f, state.f, 5,
100, 20, 3) /*TODO: cone parameters*/,
timeSinceLastSeen(1) {
}
void SLAM::LineFeature::newView(const CameraState & state, const matf & pt2d) {
FCone newCone(state.getLocalCoordinatesPoint(pt2d), state.t,
3./*TODO, other too*/, state.f);
cone.intersect(newCone);
}
Point2i SLAM::LineFeature::track(const ImagePyramid<imtype> & pyramid,
const CameraState & state, float threshold,
int stride, float & response, Mat* disp) const {
++timeSinceLastSeen;
int nSubs = pyramid.nSubs();
float maxWidth = 300, maxHeight = 300;//TODO
// compute tracking area (at lowest resolution)
float areaRes = 1.f / pyramid.subsamples[nSubs-1];
vector<int> relevantBins;
vector<Point2i> binCenters;
vector<float> binProjRads;
Point3i nBinsDims = cone.getNBins();
float nBins = nBinsDims.x*nBinsDims.y*nBinsDims.z;
float relevantThreshold = 0.2/nBins;
assert(nBinsDims.x > 1); // TODO: handle this case
int nBinLayer = nBinsDims.y*nBinsDims.z;
int xmin=1000000000, xmax=-1, ymin=1000000000, ymax=-1;
matf p;
for (int di = 0; di < nBinsDims.x; ++di)
for (int xi = 0; xi < nBinsDims.y; ++xi)
for (int yi = 0; yi < nBinsDims.z; ++yi) {
bool isRelevant = cone.getProba(di, xi, yi) > relevantThreshold;
if (isRelevant)
relevantBins.push_back(binCenters.size());
// center
matf binCenter = cone.getBinCenterGlobalCoord(di, xi, yi);
p = state.project(binCenter);
Point2i scaledPt(round(p(0)*areaRes), round(p(1)*areaRes));
binCenters.push_back(scaledPt);
// radius
if (di == 0) {
binProjRads.push_back(0);
} else {
const Point2i & ptprev = *(binCenters.end()-nBinLayer);
float projRad = norm(scaledPt-ptprev);
binProjRads.push_back(projRad);
if (isRelevant) {
xmin = min(xmin, (int)floor((p(0)-projRad)*areaRes));
ymin = min(ymin, (int)floor((p(1)-projRad)*areaRes));
xmax = max(xmax, (int)ceil ((p(0)+projRad+1)*areaRes));
ymax = max(ymax, (int)ceil ((p(1)+projRad+1)*areaRes));
}
}
}
for (int xi = 0, k = 0; xi < nBinsDims.y; ++xi)
for (int yi = 0; yi < nBinsDims.z; ++yi, ++k) {
const Point2i & c = binCenters[k];
float projRad = binProjRads[k+nBinLayer];
binProjRads[k] = projRad;
if (cone.getProba(0, xi, yi) > relevantThreshold) {
xmin = min(xmin, (int)floor((c.x-projRad)*areaRes));
ymin = min(ymin, (int)floor((c.y-projRad)*areaRes));
xmax = max(xmax, (int)ceil ((c.x+projRad+1)*areaRes));
ymax = max(ymax, (int)ceil ((c.y+projRad+1)*areaRes));
}
}
// if the area is too big, don't try to match
// TODO: if that happens several times, drop the point
if ((xmax-xmin > maxWidth) || (ymax-ymin > maxHeight)) {
response = -1;
return Point2i(-1,-1);
}
Rect areaRect = Rect(xmin, ymin, xmax-xmin, ymax-ymin);
matb areaMask(ymax-ymin, xmax-xmin, (byte)0);
for (size_t i0 = 0; i0 < relevantBins.size(); ++i0) {
size_t i = relevantBins[i0];
Point2i & pt = binCenters[i];
pt.x -= xmin;
pt.y -= ymin; //Careful, it is modified in binCenters!
const int radius = round(binProjRads[i]);
//line(areaMask, pt, pt, Scalar(255), diameter);
circle(areaMask, pt, radius, Scalar(255), -1);
}
//namedWindow("debug");
//imshow("debug", areaMask);
//cvWaitKey(0);
//exit(0);
/*
if (disp) {
matf imdisp = disp[0];
cvCopyToCrop(matf(areaRect.height/areaRes, areaRect.width/areaRes, 0.5f),
imdisp, Rect(areaRect.x/areaRes, areaRect.y/areaRes,
areaRect.width/areaRes, areaRect.height/areaRes));
for (int i = 0; i < areaRect.width; ++i)
for (int j = 0; j < areaRect.height; ++j) {
if (areaMask(j,i)) {
int y = (areaRect.y+j)/areaRes, x = (areaRect.x+i)/areaRes;
if ((x >= 0) && (y >= 0) && (x < imdisp.size().width) &&
(y < imdisp.size().height))
imdisp(y, x) = 1.f;
}
}
}
*/
// multi resolution tracking
Mat_<imtype> totrack;
float desch = descriptor.size().height, descw = descriptor.size().width;
// 1) track in the area at lowest resolution
resize(descriptor, totrack, Size(round(descw*areaRes), round(desch*areaRes)));
Point2i trackedPoint = matchFeatureInArea(pyramid.images[nSubs-1],
totrack, NULL, areaRect,
&areaMask, stride, response);
cout << "Tracked " << trackedPoint*(1./areaRes) << " response=" << response<< endl;
trackedPoint *= 1./areaRes;
if (disp) {
int dh = descriptor.size().height, dw = descriptor.size().width;
Rect dstrect(trackedPoint.x-dw/2, trackedPoint.y-dh/2, dw, dh);
Rect dstrectC(max(dstrect.x, 0), max(dstrect.y, 0), 0, 0);
dstrectC.width = min(dstrect.width , disp[0].size().width - dstrectC.x);
dstrectC.height = min(dstrect.height, disp[0].size().height - dstrectC.y);
disp[1](dstrectC) *= 0.5;
disp[2](dstrectC) *= 0.5;
cvConvertToCrop(descriptor, disp[0], dstrect, CV_32F, 1.f/255.f);
}
// 2) refine tracking
if (response > threshold * 0.67) {
for (int iSub = nSubs-2; iSub >= 0; --iSub) {
float lastsub = pyramid.subsamples[iSub+1];
float sub = pyramid.subsamples[iSub];
int laststride = stride;
int newstride = (iSub == 0) ? 1 : stride;
int searchRad = sub/lastsub*laststride/newstride;
Rect areaRect(trackedPoint.x/sub-searchRad, trackedPoint.y/sub-searchRad,
2*searchRad+1, 2*searchRad+1);
resize(descriptor, totrack, Size(descw/sub, desch/sub));
trackedPoint = SLAM::matchFeatureInArea(pyramid.images[iSub], totrack,
NULL, areaRect, NULL, newstride,
response);
trackedPoint *= sub;
if (response < threshold * 0.67)
break;
}
}
if (response > threshold)
timeSinceLastSeen = 1;
return trackedPoint;
}
|
#include <iostream>
#include <vector>
#include <map>
using namespace std;
int m, res = 0;
map< pair<int, int>, int> flagMap;
bool isNotOver(vector< vector< pair<int, int> > > &inputVec)
{
int len = inputVec.size();
for(int i = 0; i < len; i++)
{
for(int j = 0; j < len; j++)
{
if(inputVec[i][j].second == 0)
{
return true;
}
}
}
return false;
}
void dealWithPoint(int i, int j, vector< vector< pair<int, int> > > &inputVec, pair<int, int> flagPair)
{
inputVec[i][j].second = 1;
if(inputVec[i][j].first == 0 || flagMap[flagPair] == 1)
{
return;
}
if(((i < m - 1) && (inputVec[i + 1][j].second == 0 && inputVec[i + 1][j].first == 1)) ||
((j < m - 1) && (inputVec[i][j + 1].second == 0 && inputVec[i][j + 1].first == 1)) )
{
if(inputVec[i + 1][j].second == 0 && inputVec[i + 1][j].first == 1)
{
dealWithPoint(i + 1, j, inputVec, flagPair);
}
if(inputVec[i][j + 1].second == 0 && inputVec[i][j + 1].first == 1)
{
dealWithPoint(i, j + 1, inputVec, flagPair);
}
}
else
{
res++;
flagMap[flagPair] = 1;
return;
}
}
int main()
{
int temp;
vector< vector< pair<int, int> > > inputVec;
vector< pair<int, int> > tempVec;
// input
cin>>m;
for(int i = 0; i < m; i++)
{
for(int j = 0; j < m; j++)
{
cin>>temp;
tempVec.push_back(make_pair(temp, 0));
}
inputVec.push_back(tempVec);
tempVec.clear();
}
while(isNotOver(inputVec))
{
for(int i = 0; i < m; i++)
{
for(int j = 0; j < m; j++)
{
if(inputVec[i][j].second == 0)
{
dealWithPoint(i, j, inputVec, make_pair(i, j));
}
}
}
}
cout<<res<<endl;
}
|
//Convert Binary tree to doubly linked list - sorted
//lowest will be the left most leaf
//Get some basic objects to work with
//BinaryTreeNode (value, ptr to left, ptr to right)
//BinaryTreeNode* - pointer to root of tree usually
//DLList (value, ptr back, ptr forward)
//DLList* - pointer to first element of list
//make sure solution doesn't lose its nodes
//for leaf nodes left = back, right = forward
//for non-leaf nodes - need to point back to child's
void convertNode(BinaryTreeNode* current)
{
//null case - come back to it, not important
if(has children - need to change things)
{
}
if(no children - can leave links the same)
}
|
// Copyright 2012 Yandex
#include "ltr/scorers/decision_tree_scorer.h"
|
#include "mainwindow.h"
MainWindow::MainWindow(QWidget *parent)
: QMainWindow(parent)
{
qApp->installEventFilter(this);
my_mainWidget = new QWidget(this);
setCentralWidget(my_mainWidget);
setWindowTitle("M580 IHM");
my_mainWidget->setStyleSheet("background-color: rgb(254, 245, 231)");
my_Vlayout0 = new QVBoxLayout;
my_Hlayout = new QHBoxLayout;
my_Vlayout = new QVBoxLayout;
my_Vlayout2 = new QVBoxLayout;
my_diode = new Diode(my_mainWidget);
my_sender = new Sender();
QSpacerItem * horizontalSpacer = new QSpacerItem(5, 10, QSizePolicy::Expanding, QSizePolicy::Minimum);
M580_button * diode_button = new M580_button(tr("&Power Diode"), my_mainWidget);
M580_button * shbutton = new M580_button(tr("&Launch M580"), my_mainWidget);
M580_button * stopbutton = new M580_button(tr("&Stop M580"), my_mainWidget);
ValveUsecase* my_usecase = new ValveUsecase();
connect(diode_button, SIGNAL(clicked()), my_diode, SLOT(setPower()));
connect(shbutton , SIGNAL(clicked()), this , SLOT(launchbash()));
connect(stopbutton , SIGNAL(clicked()), this , SLOT(killM580()));
my_Vlayout0->addLayout(my_Hlayout);
my_Vlayout0->addWidget(my_usecase);
my_Vlayout ->addWidget(my_diode);
my_Vlayout ->addItem(horizontalSpacer);
my_Vlayout ->addWidget(diode_button);
my_Vlayout2->addWidget(shbutton);
my_Vlayout2->addWidget(stopbutton);
my_Hlayout->addLayout(my_Vlayout);
my_Hlayout->addWidget(my_sender);
my_Hlayout->addLayout(my_Vlayout2);
my_mainWidget->setLayout(my_Vlayout0);
}
void MainWindow::launchbash()
{
my_sender->WriteText("<em>M580 launching...</em> \r");
my_sender->setroot(1);
process = new QProcess(this);
process->start("/bin/sh", QStringList()<< path);
id = process->processId() + 1; //Je ne sais pas pourquoi j'ai un décalage de 1
}
void MainWindow::killM580()
{
if(my_sender->getroot())
{
my_sender->WriteText("<em>M580 closing...</em> \r");
my_sender->setroot(0);
QString ID = QString::number(id); //conversion Qstring
QString cmd = "kill " + ID;
qDebug() << "cmd :" << cmd;
QByteArray ba = cmd.toLocal8Bit(); //conversion char*
system( ba.data() );
my_sender->WriteText("<em>Process end succeeds</em> \r");
}
}
MainWindow::~MainWindow()
{
killM580();
qDebug() << "Exit!" ;
}
|
// Copyright 2017 Google Inc. All rights reserved.
//
// 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 "FirebaseStorageScene.h"
#include <stdarg.h>
#if (CC_TARGET_PLATFORM == CC_PLATFORM_ANDROID)
#include <android/log.h>
#include <jni.h>
#include "platform/android/jni/JniHelper.h"
#endif
#include "FirebaseCocos.h"
#include "firebase/auth.h"
#include "firebase/storage.h"
#include "firebase/future.h"
USING_NS_CC;
/// Padding for the UI elements.
static const float kUIElementPadding = 10.0;
/// Placeholder labels for the text fields.
static const char* kKeyPlaceholderText = "Key";
static const char* kValuePlaceholderText = "Value";
static const char* kTestAppData = "test_app_data";
void StorageListener::OnPaused(firebase::storage::Controller*) {}
void StorageListener::OnProgress(firebase::storage::Controller* controller) {
int transferred = controller->bytes_transferred();
int total = controller->total_byte_count();
if (total > 0) {
int percent = 100 * transferred / total;
scene_->logMessage("Transfer %i%% (%i/%i)", percent, transferred, total);
}
}
/// Creates the Firebase scene.
Scene* CreateFirebaseScene() {
return FirebaseStorageScene::createScene();
}
/// Creates the FirebaseStorageScene.
Scene* FirebaseStorageScene::createScene() {
// Create the scene.
auto scene = Scene::create();
// Create the layer.
auto layer = FirebaseStorageScene::create();
// Add the layer to the scene.
scene->addChild(layer);
return scene;
}
/// Initializes the FirebaseScene.
bool FirebaseStorageScene::init() {
if (!Layer::init()) {
return false;
}
listener_.set_scene(this);
auto visibleSize = Director::getInstance()->getVisibleSize();
cocos2d::Vec2 origin = Director::getInstance()->getVisibleOrigin();
// Create the Firebase label.
auto firebaseLabel =
Label::createWithTTF("Firebase Storage", "fonts/Marker Felt.ttf", 20);
nextYPosition =
origin.y + visibleSize.height - firebaseLabel->getContentSize().height;
firebaseLabel->setPosition(
cocos2d::Vec2(origin.x + visibleSize.width / 2, nextYPosition));
this->addChild(firebaseLabel, 1);
const float scrollViewYPosition = nextYPosition -
firebaseLabel->getContentSize().height -
kUIElementPadding * 2;
// Create the ScrollView on the Cocos2d thread.
cocos2d::Director::getInstance()
->getScheduler()
->performFunctionInCocosThread(
[=]() { this->createScrollView(scrollViewYPosition); });
// Use ModuleInitializer to initialize both Auth and Storage, ensuring no
// dependencies are missing.
void* initialize_targets[] = {&auth_, &storage_};
CCLOG("Initializing the Storage with Firebase API.");
const firebase::ModuleInitializer::InitializerFn initializers[] = {
[](firebase::App* app, void* data) {
void** targets = reinterpret_cast<void**>(data);
firebase::InitResult result;
*reinterpret_cast<firebase::auth::Auth**>(targets[0]) =
firebase::auth::Auth::GetAuth(app, &result);
return result;
},
[](firebase::App* app, void* data) {
void** targets = reinterpret_cast<void**>(data);
firebase::InitResult result;
*reinterpret_cast<firebase::storage::Storage**>(targets[1]) =
firebase::storage::Storage::GetInstance(app, &result);
return result;
}};
// There are two ways to track long running operations: (1) retrieve the
// future using a LastResult function or (2) Cache the future manually.
//
// Here we use method 1: the future is not cached but will be later retrieved
// using InitializeLastResult. Which method is best for your app depends on
// your use case.
initializer_.Initialize(
firebase::App::GetInstance(), initialize_targets, initializers,
sizeof(initializers) / sizeof(initializers[0]));
logMessage("Created the Storage %x class for the Firebase app.",
static_cast<int>(reinterpret_cast<intptr_t>(storage_)));
key_text_field_ = createTextField(kKeyPlaceholderText);
this->addChild(key_text_field_);
value_text_field_ = createTextField(kValuePlaceholderText);
this->addChild(value_text_field_);
get_bytes_button_ = createButton(false, "Query");
get_bytes_button_->addTouchEventListener(
[this](Ref* /*sender*/, cocos2d::ui::Widget::TouchEventType type) {
switch (type) {
case cocos2d::ui::Widget::TouchEventType::ENDED: {
const char* key = key_text_field_->getString().c_str();
firebase::storage::StorageReference reference =
this->storage_->GetReference(kTestAppData).Child(key);
this->logMessage("Querying key `%s`.", key);
// There are two ways to track long running operations:
// (1) retrieve the future using a LastResult function or (2) Cache
// the future manually.
//
// Here (and below in the put_bytes_button_) we use method 2:
// caching the future. Which method is best for your app depends on
// your use case.
get_bytes_future_ = reference.GetBytes(
this->byte_buffer_, kBufferSize, &this->listener_);
this->get_bytes_button_->setEnabled(false);
this->put_bytes_button_->setEnabled(false);
break;
}
default: {
break;
}
}
});
this->addChild(get_bytes_button_);
put_bytes_button_ = createButton(false, "Set");
put_bytes_button_->addTouchEventListener(
[this](Ref* /*sender*/, cocos2d::ui::Widget::TouchEventType type) {
switch (type) {
case cocos2d::ui::Widget::TouchEventType::ENDED: {
const char* key = key_text_field_->getString().c_str();
const char* value = value_text_field_->getString().c_str();
size_t value_size = value_text_field_->getString().size();
firebase::storage::StorageReference reference =
this->storage_->GetReference(kTestAppData).Child(key);
this->logMessage("Setting key `%s` to `%s`.", key, value);
this->put_bytes_future_ = reference.PutBytes(value, value_size,
&this->listener_);
this->get_bytes_button_->setEnabled(false);
this->put_bytes_button_->setEnabled(false);
break;
}
default: {
break;
}
}
});
this->addChild(put_bytes_button_);
// Create the close app menu item.
auto closeAppItem = MenuItemImage::create(
"CloseNormal.png", "CloseSelected.png",
CC_CALLBACK_1(FirebaseScene::menuCloseAppCallback, this));
closeAppItem->setContentSize(cocos2d::Size(25, 25));
// Position the close app menu item on the top-right corner of the screen.
closeAppItem->setPosition(cocos2d::Vec2(
origin.x + visibleSize.width - closeAppItem->getContentSize().width / 2,
origin.y + visibleSize.height -
closeAppItem->getContentSize().height / 2));
// Create the Menu for touch handling.
auto menu = Menu::create(closeAppItem, NULL);
menu->setPosition(cocos2d::Vec2::ZERO);
this->addChild(menu, 1);
state_ = kStateInitialize;
// Schedule the update method for this scene.
this->scheduleUpdate();
return true;
}
FirebaseStorageScene::State FirebaseStorageScene::updateInitialize() {
firebase::Future<void> initialize_future =
initializer_.InitializeLastResult();
if (initialize_future.status() != firebase::kFutureStatusComplete) {
return kStateInitialize;
}
if (initialize_future.error() != 0) {
logMessage("Failed to initialize Firebase libraries: %s",
initialize_future.error_message());
return kStateRun;
}
logMessage("Successfully initialized Firebase Auth and Firebase Storage.");
auth_->SignInAnonymously();
return kStateLogin;
}
FirebaseStorageScene::State FirebaseStorageScene::updateLogin() {
// Sign in using Auth before accessing the storage.
//
// The default Storage permissions allow anonymous user access. However,
// Firebase Auth does not allow anonymous user login by default. This setting
// can be changed in the Auth settings page for your project in the Firebase
// Console under the "Sign-In Method" tab.
firebase::Future<firebase::auth::User*> sign_in_future =
auth_->SignInAnonymouslyLastResult();
if (sign_in_future.status() != firebase::kFutureStatusComplete) {
return kStateLogin;
}
if (sign_in_future.error() != firebase::auth::kAuthErrorNone) {
logMessage("ERROR: Could not sign in anonymously. Error %d: %s",
sign_in_future.error(), sign_in_future.error_message());
logMessage(
"Ensure your application has the Anonymous sign-in provider enabled in "
"the Firebase Console.");
return kStateRun;
}
logMessage("Auth: Signed in anonymously.");
get_bytes_button_->setEnabled(true);
put_bytes_button_->setEnabled(true);
return kStateRun;
}
FirebaseStorageScene::State FirebaseStorageScene::updateRun() {
if (get_bytes_future_.status() == firebase::kFutureStatusComplete) {
if (get_bytes_future_.error() == firebase::storage::kErrorNone) {
logMessage("GetBytes complete");
const size_t* length = get_bytes_future_.result();
logMessage("Got %i bytes: %s", static_cast<int>(*length), byte_buffer_);
} else {
logMessage("ERROR: Could not get bytes. Error %d: %s",
get_bytes_future_.error(), get_bytes_future_.error_message());
}
get_bytes_button_->setEnabled(true);
put_bytes_button_->setEnabled(true);
get_bytes_future_.Release();
}
if (put_bytes_future_.status() == firebase::kFutureStatusComplete) {
if (put_bytes_future_.error() == firebase::storage::kErrorNone) {
logMessage("PutBytes complete.");
const firebase::storage::Metadata* metadata = put_bytes_future_.result();
logMessage("Put %i bytes", static_cast<int>(metadata->size_bytes()));
} else {
logMessage("ERROR: Could not put bytes. Error %d: %s",
put_bytes_future_.error(), put_bytes_future_.error_message());
}
get_bytes_button_->setEnabled(true);
put_bytes_button_->setEnabled(true);
put_bytes_future_.Release();
}
return kStateRun;
}
// Called automatically every frame. The update is scheduled in `init()`.
void FirebaseStorageScene::update(float /*delta*/) {
switch (state_) {
case kStateInitialize: state_ = updateInitialize(); break;
case kStateLogin: state_ = updateLogin(); break;
case kStateRun: state_ = updateRun(); break;
default: assert(0);
}
}
/// Handles the user tapping on the close app menu item.
void FirebaseStorageScene::menuCloseAppCallback(Ref* pSender) {
CCLOG("Cleaning up Storage C++ resources.");
// Close the cocos2d-x game scene and quit the application.
Director::getInstance()->end();
#if (CC_TARGET_PLATFORM == CC_PLATFORM_IOS)
exit(0);
#endif
}
|
#ifndef _VERTEX_POSITION_H_
#define _VERTEX_POSITION_H_
#include "vertex.h"
#include "spriteaiengine.h"
class Position : VertexInterface
{
public:
explicit Position(int, int, int);
~Position();
virtual int getx();
virtual int gety();
virtual int getz();
virtual void setx(int);
virtual void sety(int);
virtual void setz(int);
virtual void acceptAI(SpriteAIengine*);
private:
Vertex _vertex;
public:
bool operator==(Position);
};
#endif
|
#include "myqpushbutton.h"
MyQPushButton::MyQPushButton(const QString &text, QWidget * parent) : QPushButton(parent)
{
setText(text);
connect(this, SIGNAL(clicked()), this, SLOT(buttonClicked()));
}
|
/*
* Copyright (c) Meta Platforms, Inc. and affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/
#include <quic/api/test/Mocks.h>
#include <folly/portability/GMock.h>
#include <folly/portability/GTest.h>
#include <quic/api/QuicSocket.h>
#include <quic/api/QuicTransportBase.h>
#include <quic/codec/DefaultConnectionIdAlgo.h>
#include <quic/common/test/TestUtils.h>
#include <quic/fizz/server/handshake/FizzServerQuicHandshakeContext.h>
#include <quic/server/state/ServerStateMachine.h>
#include <quic/state/DatagramHandlers.h>
#include <quic/state/QuicStreamFunctions.h>
#include <quic/state/QuicStreamUtilities.h>
#include <quic/state/stream/StreamReceiveHandlers.h>
#include <quic/state/stream/StreamSendHandlers.h>
#include <quic/state/test/Mocks.h>
#include <folly/io/async/test/MockAsyncUDPSocket.h>
using namespace testing;
using namespace folly;
namespace quic {
namespace test {
constexpr uint8_t kStreamIncrement = 0x04;
using ByteEvent = QuicTransportBase::ByteEvent;
using ByteEventCancellation = QuicTransportBase::ByteEventCancellation;
enum class TestFrameType : uint8_t {
STREAM,
CRYPTO,
EXPIRED_DATA,
REJECTED_DATA,
MAX_STREAMS,
DATAGRAM,
STREAM_GROUP
};
// A made up encoding decoding of a stream.
Buf encodeStreamBuffer(
StreamId id,
StreamBuffer data,
folly::Optional<StreamGroupId> groupId = folly::none) {
auto buf = IOBuf::create(10);
folly::io::Appender appender(buf.get(), 10);
if (!groupId) {
appender.writeBE(static_cast<uint8_t>(TestFrameType::STREAM));
} else {
appender.writeBE(static_cast<uint8_t>(TestFrameType::STREAM_GROUP));
}
appender.writeBE(id);
if (groupId) {
appender.writeBE(*groupId);
}
auto dataBuf = data.data.move();
dataBuf->coalesce();
appender.writeBE<uint32_t>(dataBuf->length());
appender.push(dataBuf->coalesce());
appender.writeBE<uint64_t>(data.offset);
appender.writeBE<uint8_t>(data.eof);
return buf;
}
Buf encodeCryptoBuffer(StreamBuffer data) {
auto buf = IOBuf::create(10);
folly::io::Appender appender(buf.get(), 10);
appender.writeBE(static_cast<uint8_t>(TestFrameType::CRYPTO));
auto dataBuf = data.data.move();
dataBuf->coalesce();
appender.writeBE<uint32_t>(dataBuf->length());
appender.push(dataBuf->coalesce());
appender.writeBE<uint64_t>(data.offset);
return buf;
}
// A made up encoding of a MaxStreamsFrame.
Buf encodeMaxStreamsFrame(const MaxStreamsFrame& frame) {
auto buf = IOBuf::create(25);
folly::io::Appender appender(buf.get(), 25);
appender.writeBE(static_cast<uint8_t>(TestFrameType::MAX_STREAMS));
appender.writeBE<uint8_t>(frame.isForBidirectionalStream() ? 1 : 0);
appender.writeBE<uint64_t>(frame.maxStreams);
return buf;
}
// Build a datagram frame
Buf encodeDatagramFrame(BufQueue data) {
auto buf = IOBuf::create(10);
folly::io::Appender appender(buf.get(), 10);
appender.writeBE(static_cast<uint8_t>(TestFrameType::DATAGRAM));
auto dataBuf = data.move();
dataBuf->coalesce();
appender.writeBE<uint32_t>(dataBuf->length());
appender.push(dataBuf->coalesce());
return buf;
}
std::pair<Buf, uint32_t> decodeDatagramFrame(folly::io::Cursor& cursor) {
Buf outData;
auto len = cursor.readBE<uint32_t>();
cursor.clone(outData, len);
return std::make_pair(std::move(outData), len);
}
std::pair<Buf, uint64_t> decodeDataBuffer(folly::io::Cursor& cursor) {
Buf outData;
auto len = cursor.readBE<uint32_t>();
cursor.clone(outData, len);
uint64_t offset = cursor.readBE<uint64_t>();
return std::make_pair(std::move(outData), offset);
}
std::pair<StreamId, StreamBuffer> decodeStreamBuffer(
folly::io::Cursor& cursor) {
auto streamId = cursor.readBE<StreamId>();
auto dataBuffer = decodeDataBuffer(cursor);
bool eof = (bool)cursor.readBE<uint8_t>();
return std::make_pair(
streamId,
StreamBuffer(std::move(dataBuffer.first), dataBuffer.second, eof));
}
struct StreamGroupIdBuf {
StreamId id;
StreamGroupId groupId;
StreamBuffer buf;
};
StreamGroupIdBuf decodeStreamGroupBuffer(folly::io::Cursor& cursor) {
auto streamId = cursor.readBE<StreamId>();
auto groupId = cursor.readBE<StreamGroupId>();
auto dataBuffer = decodeDataBuffer(cursor);
bool eof = (bool)cursor.readBE<uint8_t>();
return StreamGroupIdBuf{
streamId,
groupId,
StreamBuffer(std::move(dataBuffer.first), dataBuffer.second, eof)};
}
StreamBuffer decodeCryptoBuffer(folly::io::Cursor& cursor) {
auto dataBuffer = decodeDataBuffer(cursor);
return StreamBuffer(std::move(dataBuffer.first), dataBuffer.second, false);
}
MaxStreamsFrame decodeMaxStreamsFrame(folly::io::Cursor& cursor) {
bool isBidi = cursor.readBE<uint8_t>();
auto maxStreams = cursor.readBE<uint64_t>();
return MaxStreamsFrame(maxStreams, isBidi);
}
class TestPingCallback : public QuicSocket::PingCallback {
public:
void pingAcknowledged() noexcept override {}
void pingTimeout() noexcept override {}
void onPing() noexcept override {}
};
class TestByteEventCallback : public QuicSocket::ByteEventCallback {
public:
using HashFn = std::function<size_t(const ByteEvent&)>;
using ComparatorFn = std::function<bool(const ByteEvent&, const ByteEvent&)>;
enum class Status { REGISTERED = 1, RECEIVED = 2, CANCELLED = 3 };
void onByteEventRegistered(ByteEvent event) override {
EXPECT_TRUE(byteEventTracker_.find(event) == byteEventTracker_.end());
byteEventTracker_[event] = Status::REGISTERED;
}
void onByteEvent(ByteEvent event) override {
EXPECT_TRUE(byteEventTracker_.find(event) != byteEventTracker_.end());
byteEventTracker_[event] = Status::RECEIVED;
}
void onByteEventCanceled(ByteEventCancellation cancellation) override {
const ByteEvent& event = cancellation;
EXPECT_TRUE(byteEventTracker_.find(event) != byteEventTracker_.end());
byteEventTracker_[event] = Status::CANCELLED;
}
std::unordered_map<ByteEvent, Status, HashFn, ComparatorFn>
getByteEventTracker() const {
return byteEventTracker_;
}
private:
// Custom hash and comparator functions that use only id, offset and types
// (not the srtt)
HashFn hash = [](const ByteEvent& e) {
return folly::hash::hash_combine(e.id, e.offset, e.type);
};
ComparatorFn comparator = [](const ByteEvent& lhs, const ByteEvent& rhs) {
return (
(lhs.id == rhs.id) && (lhs.offset == rhs.offset) &&
(lhs.type == rhs.type));
};
std::unordered_map<ByteEvent, Status, HashFn, ComparatorFn> byteEventTracker_{
/* bucket count */ 4,
hash,
comparator};
};
static auto
getByteEventMatcher(ByteEvent::Type type, StreamId id, uint64_t offset) {
return AllOf(
testing::Field(&ByteEvent::type, testing::Eq(type)),
testing::Field(&ByteEvent::id, testing::Eq(id)),
testing::Field(&ByteEvent::offset, testing::Eq(offset)));
}
static auto getByteEventTrackerMatcher(
ByteEvent event,
TestByteEventCallback::Status status) {
return Pair(getByteEventMatcher(event.type, event.id, event.offset), status);
}
class TestQuicTransport
: public QuicTransportBase,
public std::enable_shared_from_this<TestQuicTransport> {
public:
TestQuicTransport(
folly::EventBase* evb,
std::unique_ptr<QuicAsyncUDPSocketType> socket,
ConnectionSetupCallback* connSetupCb,
ConnectionCallback* connCb)
: QuicTransportBase(evb, std::move(socket)),
observerContainer_(std::make_shared<SocketObserverContainer>(this)) {
setConnectionSetupCallback(connSetupCb);
setConnectionCallback(connCb);
auto conn = std::make_unique<QuicServerConnectionState>(
FizzServerQuicHandshakeContext::Builder().build());
conn->clientConnectionId = ConnectionId({10, 9, 8, 7});
conn->version = QuicVersion::MVFST;
conn->observerContainer = observerContainer_;
transportConn = conn.get();
conn_.reset(conn.release());
aead = test::createNoOpAead();
headerCipher = test::createNoOpHeaderCipher();
connIdAlgo_ = std::make_unique<DefaultConnectionIdAlgo>();
}
~TestQuicTransport() override {
resetConnectionCallbacks();
// we need to call close in the derived class.
resetConnectionCallbacks();
closeImpl(
QuicError(
QuicErrorCode(LocalErrorCode::SHUTTING_DOWN),
std::string("shutdown")),
false /* drainConnection */);
// closeImpl may have been called earlier with drain = true, so force close.
closeUdpSocket();
}
std::chrono::milliseconds getLossTimeoutRemainingTime() const {
return lossTimeout_.getTimeRemaining();
}
void onReadData(const folly::SocketAddress&, NetworkDataSingle&& data)
override {
if (!data.data) {
return;
}
folly::io::Cursor cursor(data.data.get());
while (!cursor.isAtEnd()) {
// create server chosen connId with processId = 0 and workerId = 0
ServerConnectionIdParams params(0, 0, 0);
conn_->serverConnectionId = *connIdAlgo_->encodeConnectionId(params);
auto type = static_cast<TestFrameType>(cursor.readBE<uint8_t>());
if (type == TestFrameType::CRYPTO) {
auto cryptoBuffer = decodeCryptoBuffer(cursor);
appendDataToReadBuffer(
conn_->cryptoState->initialStream, std::move(cryptoBuffer));
} else if (type == TestFrameType::MAX_STREAMS) {
auto maxStreamsFrame = decodeMaxStreamsFrame(cursor);
if (maxStreamsFrame.isForBidirectionalStream()) {
conn_->streamManager->setMaxLocalBidirectionalStreams(
maxStreamsFrame.maxStreams);
} else {
conn_->streamManager->setMaxLocalUnidirectionalStreams(
maxStreamsFrame.maxStreams);
}
} else if (type == TestFrameType::DATAGRAM) {
auto buffer = decodeDatagramFrame(cursor);
auto frame = DatagramFrame(buffer.second, std::move(buffer.first));
handleDatagram(*conn_, frame, data.receiveTimePoint);
} else if (type == TestFrameType::STREAM_GROUP) {
auto res = decodeStreamGroupBuffer(cursor);
QuicStreamState* stream =
conn_->streamManager->getStream(res.id, res.groupId);
if (!stream) {
continue;
}
appendDataToReadBuffer(*stream, std::move(res.buf));
conn_->streamManager->updateReadableStreams(*stream);
conn_->streamManager->updatePeekableStreams(*stream);
} else {
auto buffer = decodeStreamBuffer(cursor);
QuicStreamState* stream = conn_->streamManager->getStream(buffer.first);
if (!stream) {
continue;
}
appendDataToReadBuffer(*stream, std::move(buffer.second));
conn_->streamManager->updateReadableStreams(*stream);
conn_->streamManager->updatePeekableStreams(*stream);
}
}
}
void writeData() override {
writeQuicDataToSocket(
*socket_,
*conn_,
*conn_->serverConnectionId,
*conn_->clientConnectionId,
*aead,
*headerCipher,
*conn_->version,
conn_->transportSettings.writeConnectionDataPacketsLimit);
}
bool hasWriteCipher() const {
return conn_->oneRttWriteCipher != nullptr;
}
std::shared_ptr<QuicTransportBase> sharedGuard() override {
return shared_from_this();
}
QuicConnectionStateBase& getConnectionState() {
return *conn_;
}
void closeTransport() {
transportClosed = true;
}
void AckTimeout() {
ackTimeoutExpired();
}
void setIdleTimeout() {
setIdleTimer();
}
void invokeIdleTimeout() {
idleTimeout_.timeoutExpired();
}
void invokeAckTimeout() {
ackTimeout_.timeoutExpired();
}
void invokeSendPing(std::chrono::milliseconds interval) {
sendPing(interval);
}
void invokeCancelPingTimeout() {
pingTimeout_.cancelTimeout();
}
void invokeHandlePingCallbacks() {
handlePingCallbacks();
}
void invokeHandleKnobCallbacks() {
handleKnobCallbacks();
}
bool isPingTimeoutScheduled() {
if (pingTimeout_.isScheduled()) {
return true;
}
return false;
}
auto& writeLooper() {
return writeLooper_;
}
auto& readLooper() {
return readLooper_;
}
void unbindConnection() {}
void onReadError(const folly::AsyncSocketException&) noexcept {}
void addDataToStream(
StreamId id,
StreamBuffer data,
folly::Optional<StreamGroupId> groupId = folly::none) {
auto buf = encodeStreamBuffer(id, std::move(data), std::move(groupId));
SocketAddress addr("127.0.0.1", 1000);
onNetworkData(addr, NetworkData(std::move(buf), Clock::now()));
}
void addCryptoData(StreamBuffer data) {
auto buf = encodeCryptoBuffer(std::move(data));
SocketAddress addr("127.0.0.1", 1000);
onNetworkData(addr, NetworkData(std::move(buf), Clock::now()));
}
void addMaxStreamsFrame(MaxStreamsFrame frame) {
auto buf = encodeMaxStreamsFrame(frame);
SocketAddress addr("127.0.0.1", 1000);
onNetworkData(addr, NetworkData(std::move(buf), Clock::now()));
}
void addStreamReadError(StreamId id, QuicErrorCode ex) {
QuicStreamState* stream = conn_->streamManager->getStream(id);
stream->streamReadError = ex;
conn_->streamManager->updateReadableStreams(*stream);
conn_->streamManager->updatePeekableStreams(*stream);
// peekableStreams is updated to contain streams with streamReadError
updatePeekLooper();
updateReadLooper();
}
void addDatagram(Buf data, TimePoint recvTime = Clock::now()) {
auto buf = encodeDatagramFrame(std::move(data));
SocketAddress addr("127.0.0.1", 1000);
onNetworkData(addr, NetworkData(std::move(buf), recvTime));
}
void closeStream(StreamId id) {
QuicStreamState* stream = conn_->streamManager->getStream(id);
stream->sendState = StreamSendState::Closed;
stream->recvState = StreamRecvState::Closed;
conn_->streamManager->addClosed(id);
auto deliveryCb = deliveryCallbacks_.find(id);
if (deliveryCb != deliveryCallbacks_.end()) {
for (auto& cbs : deliveryCb->second) {
ByteEvent event = {};
event.id = id;
event.offset = cbs.offset;
event.type = ByteEvent::Type::ACK;
event.srtt = stream->conn.lossState.srtt;
cbs.callback->onByteEvent(event);
if (closeState_ != CloseState::OPEN) {
break;
}
}
deliveryCallbacks_.erase(deliveryCb);
}
auto txCallbacksForStream = txCallbacks_.find(id);
if (txCallbacksForStream != txCallbacks_.end()) {
for (auto& cbs : txCallbacksForStream->second) {
ByteEvent event = {};
event.id = id;
event.offset = cbs.offset;
event.type = ByteEvent::Type::TX;
cbs.callback->onByteEvent(event);
if (closeState_ != CloseState::OPEN) {
break;
}
}
txCallbacks_.erase(txCallbacksForStream);
}
SocketAddress addr("127.0.0.1", 1000);
// some fake data to trigger close behavior.
auto buf = encodeStreamBuffer(
id,
StreamBuffer(IOBuf::create(0), stream->maxOffsetObserved + 1, true));
auto networkData = NetworkData(std::move(buf), Clock::now());
onNetworkData(addr, std::move(networkData));
}
QuicStreamState* getStream(StreamId id) {
return conn_->streamManager->getStream(id);
}
void setServerConnectionId() {
// create server chosen connId with processId = 0 and workerId = 0
ServerConnectionIdParams params(0, 0, 0);
conn_->serverConnectionId = *connIdAlgo_->encodeConnectionId(params);
}
void driveReadCallbacks() {
getEventBase()->loopOnce();
}
QuicErrorCode getConnectionError() {
return conn_->localConnectionError->code;
}
bool isClosed() const noexcept {
return closeState_ == CloseState::CLOSED;
}
void closeWithoutWrite() {
closeImpl(folly::none, false, false);
}
void invokeWriteSocketData() {
writeSocketData();
}
void invokeProcessCallbacksAfterNetworkData() {
processCallbacksAfterNetworkData();
}
// Simulates the delivery of a Byte Event callback, similar to the way it
// happens in QuicTransportBase::processCallbacksAfterNetworkData() or
// in the runOnEvbAsync lambda in
// QuicTransportBase::registerByteEventCallback()
bool deleteRegisteredByteEvent(
StreamId id,
uint64_t offset,
ByteEventCallback* cb,
ByteEvent::Type type) {
auto& byteEventMap = getByteEventMap(type);
auto streamByteEventCbIt = byteEventMap.find(id);
if (streamByteEventCbIt == byteEventMap.end()) {
return false;
}
auto pos = std::find_if(
streamByteEventCbIt->second.begin(),
streamByteEventCbIt->second.end(),
[offset, cb](const ByteEventDetail& p) {
return ((p.offset == offset) && (p.callback == cb));
});
if (pos == streamByteEventCbIt->second.end()) {
return false;
}
streamByteEventCbIt->second.erase(pos);
return true;
}
void enableDatagram() {
// Note: the RFC says to use 65535 to enable the datagram extension.
// We are using +1 in tests to make sure that we avoid representing this
// value with an uint16
conn_->datagramState.maxReadFrameSize = 65536;
conn_->datagramState.maxReadBufferSize = 10;
}
SocketObserverContainer* getSocketObserverContainer() const override {
return observerContainer_.get();
}
QuicServerConnectionState* transportConn;
std::unique_ptr<Aead> aead;
std::unique_ptr<PacketNumberCipher> headerCipher;
std::unique_ptr<ConnectionIdAlgo> connIdAlgo_;
bool transportClosed{false};
PacketNum packetNum_{0};
// Container of observers for the socket / transport.
//
// This member MUST be last in the list of members to ensure it is destroyed
// first, before any other members are destroyed. This ensures that observers
// can inspect any socket / transport state available through public methods
// when destruction of the transport begins.
const std::shared_ptr<SocketObserverContainer> observerContainer_;
};
class QuicTransportImplTest : public Test {
public:
void SetUp() override {
backingEvb = std::make_unique<folly::EventBase>();
evb = std::make_unique<QuicEventBase>(backingEvb.get());
auto socket = std::make_unique<NiceMock<folly::test::MockAsyncUDPSocket>>(
backingEvb.get());
socketPtr = socket.get();
transport = std::make_shared<TestQuicTransport>(
evb->getBackingEventBase(),
std::move(socket),
&connSetupCallback,
&connCallback);
auto& conn = *transport->transportConn;
conn.flowControlState.peerAdvertisedInitialMaxStreamOffsetBidiLocal =
kDefaultStreamFlowControlWindow;
conn.flowControlState.peerAdvertisedInitialMaxStreamOffsetBidiRemote =
kDefaultStreamFlowControlWindow;
conn.flowControlState.peerAdvertisedInitialMaxStreamOffsetUni =
kDefaultStreamFlowControlWindow;
conn.flowControlState.peerAdvertisedMaxOffset =
kDefaultConnectionFlowControlWindow;
conn.streamManager->setMaxLocalBidirectionalStreams(
kDefaultMaxStreamsBidirectional);
conn.streamManager->setMaxLocalUnidirectionalStreams(
kDefaultMaxStreamsUnidirectional);
maybeSetNotifyOnNewStreamsExplicitly();
}
virtual void maybeSetNotifyOnNewStreamsExplicitly() {}
auto getTxMatcher(StreamId id, uint64_t offset) {
return MockByteEventCallback::getTxMatcher(id, offset);
}
auto getAckMatcher(StreamId id, uint64_t offset) {
return MockByteEventCallback::getAckMatcher(id, offset);
}
protected:
std::unique_ptr<folly::EventBase> backingEvb;
std::unique_ptr<QuicEventBase> evb;
NiceMock<MockConnectionSetupCallback> connSetupCallback;
NiceMock<MockConnectionCallback> connCallback;
TestByteEventCallback byteEventCallback;
std::shared_ptr<TestQuicTransport> transport;
folly::test::MockAsyncUDPSocket* socketPtr;
};
class QuicTransportImplTestClose : public QuicTransportImplTest,
public testing::WithParamInterface<bool> {};
INSTANTIATE_TEST_SUITE_P(
QuicTransportImplTest,
QuicTransportImplTestClose,
Values(true, false));
struct DelayedStreamNotifsTestParam {
bool notifyOnNewStreamsExplicitly;
};
class QuicTransportImplTestBase
: public QuicTransportImplTest,
public WithParamInterface<DelayedStreamNotifsTestParam> {
void maybeSetNotifyOnNewStreamsExplicitly() override {
auto transportSettings = transport->getTransportSettings();
transportSettings.notifyOnNewStreamsExplicitly =
GetParam().notifyOnNewStreamsExplicitly;
transport->setTransportSettings(transportSettings);
}
};
INSTANTIATE_TEST_SUITE_P(
QuicTransportImplTestBase,
QuicTransportImplTestBase,
::testing::Values(
DelayedStreamNotifsTestParam{false},
DelayedStreamNotifsTestParam{true}));
TEST_P(QuicTransportImplTestBase, AckTimeoutExpiredWillResetTimeoutFlag) {
transport->invokeAckTimeout();
EXPECT_FALSE(transport->transportConn->pendingEvents.scheduleAckTimeout);
}
TEST_P(QuicTransportImplTestBase, IdleTimeoutExpiredDestroysTransport) {
EXPECT_CALL(connSetupCallback, onConnectionSetupError(_))
.WillOnce(Invoke([&](auto) { transport = nullptr; }));
transport->invokeIdleTimeout();
}
TEST_P(QuicTransportImplTestBase, IdleTimeoutStreamMaessage) {
auto stream1 = transport->createBidirectionalStream().value();
auto stream2 = transport->createBidirectionalStream().value();
auto stream3 = transport->createUnidirectionalStream().value();
transport->setControlStream(stream3);
NiceMock<MockReadCallback> readCb1;
NiceMock<MockReadCallback> readCb2;
transport->setReadCallback(stream1, &readCb1);
transport->setReadCallback(stream2, &readCb2);
transport->addDataToStream(
stream1, StreamBuffer(folly::IOBuf::copyBuffer("actual stream data"), 0));
transport->addDataToStream(
stream2,
StreamBuffer(folly::IOBuf::copyBuffer("actual stream data"), 10));
EXPECT_CALL(readCb1, readError(stream1, _))
.Times(1)
.WillOnce(Invoke([](auto, auto error) {
EXPECT_EQ("Idle timeout, num non control streams: 2", error.message);
}));
transport->invokeIdleTimeout();
}
TEST_P(QuicTransportImplTestBase, StopSendingClosesIngress) {
// update transport settings
auto transportSettings = transport->getTransportSettings();
transportSettings.dropIngressOnStopSending = true;
transport->setTransportSettings(transportSettings);
auto& streamManager = *transport->transportConn->streamManager;
auto unknownErrorCode = GenericApplicationErrorCode::UNKNOWN;
std::string ingressData = "some ingress stream data";
auto ingressDataLen = ingressData.size();
StreamId streamID;
QuicStreamState* stream;
// create bidirectional stream
streamID = transport->createBidirectionalStream().value();
NiceMock<MockReadCallback> readCb1;
transport->setReadCallback(streamID, &readCb1);
// add ingress & egress data to stream
transport->addDataToStream(
streamID, StreamBuffer(folly::IOBuf::copyBuffer(ingressData), 0));
transport->writeChain(
streamID, folly::IOBuf::copyBuffer("some egress stream data"), false);
transport->driveReadCallbacks();
stream = CHECK_NOTNULL(transport->getStream(streamID));
// check stream has readable data and SM is open
EXPECT_TRUE(stream->hasReadableData());
EXPECT_EQ(stream->sendState, StreamSendState::Open);
EXPECT_EQ(stream->recvState, StreamRecvState::Open);
// send stop sending to peer – this and later invoking reset stream should not
// invoke ReadCallback::readError()
EXPECT_CALL(readCb1, readError(streamID, _)).Times(0);
transport->stopSending(streamID, GenericApplicationErrorCode::NO_ERROR);
// check that we've discarded any ingress data and ingress SM is closed
EXPECT_FALSE(stream->hasReadableData());
EXPECT_FALSE(streamManager.readableStreams().contains(streamID));
EXPECT_EQ(stream->sendState, StreamSendState::Open);
EXPECT_EQ(stream->recvState, StreamRecvState::Closed);
// suppose we tx a rst stream (and rx its corresponding ack), expect
// terminal state and queued in closed streams
transport->resetStream(streamID, GenericApplicationErrorCode::NO_ERROR);
sendRstAckSMHandler(*stream);
EXPECT_TRUE(stream->inTerminalStates());
EXPECT_TRUE(streamManager.closedStreams().contains(streamID));
transport->driveReadCallbacks();
// now if we rx a rst_stream we should deliver ReadCallback::readError()
EXPECT_TRUE(streamManager.streamExists(streamID));
EXPECT_CALL(readCb1, readError(streamID, QuicError(unknownErrorCode)))
.Times(1);
receiveRstStreamSMHandler(
*stream, RstStreamFrame(streamID, unknownErrorCode, ingressDataLen));
transport->readLooper()->runLoopCallback();
// same test as above, but we tx a rst stream first followed by send stop
// sending second to validate that .stopSending() queues stream to be closed
NiceMock<MockReadCallback> readCb2;
streamID = transport->createBidirectionalStream().value();
transport->setReadCallback(streamID, &readCb2);
// add ingress & egress data to new stream
transport->addDataToStream(
streamID, StreamBuffer(folly::IOBuf::copyBuffer(ingressData), 0));
transport->writeChain(
streamID, folly::IOBuf::copyBuffer("some egress stream data"), false);
transport->driveReadCallbacks();
stream = CHECK_NOTNULL(transport->getStream(streamID));
// check stream has readable data and SM is open
EXPECT_TRUE(stream->hasReadableData());
EXPECT_EQ(stream->sendState, StreamSendState::Open);
EXPECT_EQ(stream->recvState, StreamRecvState::Open);
// suppose we tx a rst stream (and rx its corresponding ack)
transport->resetStream(streamID, GenericApplicationErrorCode::NO_ERROR);
sendRstAckSMHandler(*stream);
EXPECT_EQ(stream->sendState, StreamSendState::Closed);
EXPECT_EQ(stream->recvState, StreamRecvState::Open);
transport->driveReadCallbacks();
// send stop sending to peer – does not deliver an error to the read callback
// even tho the stream is in terminal state and queued for closing
EXPECT_CALL(readCb2, readError(streamID, _)).Times(0);
transport->stopSending(streamID, GenericApplicationErrorCode::NO_ERROR);
// check that we've discarded any ingress data and ingress SM is closed,
// expect terminal state and queued in closed streams
EXPECT_FALSE(stream->hasReadableData());
EXPECT_FALSE(streamManager.readableStreams().contains(streamID));
EXPECT_TRUE(stream->inTerminalStates());
EXPECT_TRUE(streamManager.closedStreams().contains(streamID));
// we need to rx a rst stream before queue stream to be closed to allow
// delivering callback to application
EXPECT_CALL(readCb2, readError(streamID, QuicError(unknownErrorCode)))
.Times(1);
receiveRstStreamSMHandler(
*stream, RstStreamFrame(streamID, unknownErrorCode, ingressDataLen));
EXPECT_TRUE(stream->inTerminalStates());
EXPECT_TRUE(streamManager.closedStreams().contains(streamID));
transport->readLooper()->runLoopCallback();
transport.reset();
}
TEST_P(QuicTransportImplTestBase, NoopStopSendingIngressClosed) {
// create bidi stream
auto streamID = transport->createBidirectionalStream().value();
auto* stream = CHECK_NOTNULL(transport->getStream(streamID));
EXPECT_EQ(stream->sendState, StreamSendState::Open);
EXPECT_EQ(stream->recvState, StreamRecvState::Open);
// suppose we rx a reset from peer which closes our ingress SM
receiveRstStreamSMHandler(
*stream,
RstStreamFrame(stream->id, GenericApplicationErrorCode::NO_ERROR, 0));
EXPECT_EQ(stream->sendState, StreamSendState::Open);
EXPECT_EQ(stream->recvState, StreamRecvState::Closed);
// send stop sending to peer should no-op
transport->stopSending(streamID, GenericApplicationErrorCode::NO_ERROR);
EXPECT_EQ(transport->transportConn->pendingEvents.frames.size(), 0);
// now test ingress uni-directional stream
auto& streamManager = *transport->transportConn->streamManager;
auto nextPeerUniStream =
streamManager.nextAcceptablePeerUnidirectionalStreamId();
EXPECT_TRUE(nextPeerUniStream.has_value());
stream = streamManager.getStream(*nextPeerUniStream);
EXPECT_EQ(stream->sendState, StreamSendState::Invalid);
EXPECT_EQ(stream->recvState, StreamRecvState::Open);
// suppose we rx a reset from peer which closes our ingress SM
receiveRstStreamSMHandler(
*stream,
RstStreamFrame(stream->id, GenericApplicationErrorCode::NO_ERROR, 0));
EXPECT_EQ(stream->sendState, StreamSendState::Invalid);
EXPECT_EQ(stream->recvState, StreamRecvState::Closed);
EXPECT_TRUE(stream->inTerminalStates());
// send stop sending to peer should no-op
transport->stopSending(stream->id, GenericApplicationErrorCode::NO_ERROR);
EXPECT_EQ(transport->transportConn->pendingEvents.frames.size(), 0);
transport.reset();
}
TEST_P(QuicTransportImplTestBase, WriteAckPacketUnsetsLooper) {
// start looper in running state first
transport->writeLooper()->run(true);
// Write data which will be acked immediately.
PacketNum packetSeen = 10;
bool pktHasRetransmittableData = true;
bool pktHasCryptoData = true;
updateAckState(
*transport->transportConn,
PacketNumberSpace::Initial,
packetSeen,
pktHasRetransmittableData,
pktHasCryptoData,
Clock::now());
ASSERT_TRUE(transport->transportConn->ackStates.initialAckState
->needsToSendAckImmediately);
// Trigger the loop callback. This will trigger writes and we assume this will
// write the acks since we have nothing else to write.
transport->writeLooper()->runLoopCallback();
EXPECT_FALSE(transport->transportConn->pendingEvents.scheduleAckTimeout);
EXPECT_FALSE(transport->writeLooper()->isLoopCallbackScheduled());
}
TEST_P(QuicTransportImplTestBase, ReadCallbackDataAvailable) {
auto stream1 = transport->createBidirectionalStream().value();
auto stream2 = transport->createBidirectionalStream().value();
StreamId stream3 = 0x6;
NiceMock<MockReadCallback> readCb1;
NiceMock<MockReadCallback> readCb2;
NiceMock<MockReadCallback> readCb3;
transport->setReadCallback(stream1, &readCb1);
transport->setReadCallback(stream2, &readCb2);
transport->addDataToStream(
stream1, StreamBuffer(folly::IOBuf::copyBuffer("actual stream data"), 0));
transport->addDataToStream(
stream2,
StreamBuffer(folly::IOBuf::copyBuffer("actual stream data"), 10));
transport->addDataToStream(
stream3, StreamBuffer(folly::IOBuf::copyBuffer("actual stream data"), 0));
transport->setReadCallback(stream3, &readCb3);
EXPECT_CALL(readCb1, readAvailable(stream1));
EXPECT_CALL(readCb3, readAvailable(stream3));
transport->driveReadCallbacks();
transport->addDataToStream(
stream2, StreamBuffer(folly::IOBuf::copyBuffer("actual stream data"), 0));
EXPECT_CALL(readCb1, readAvailable(stream1));
EXPECT_CALL(readCb2, readAvailable(stream2));
EXPECT_CALL(readCb3, readAvailable(stream3));
transport->driveReadCallbacks();
EXPECT_CALL(readCb1, readAvailable(stream1));
EXPECT_CALL(readCb2, readAvailable(stream2));
EXPECT_CALL(readCb3, readAvailable(stream3));
transport->driveReadCallbacks();
EXPECT_CALL(readCb2, readAvailable(stream2));
EXPECT_CALL(readCb3, readAvailable(stream3));
transport->setReadCallback(stream1, nullptr);
transport->driveReadCallbacks();
transport.reset();
}
TEST_P(QuicTransportImplTestBase, ReadCallbackDataAvailableNoReap) {
auto stream1 = transport->createBidirectionalStream().value();
auto stream2 = transport->createBidirectionalStream().value();
StreamId stream3 = 0x6;
NiceMock<MockReadCallback> readCb1;
NiceMock<MockReadCallback> readCb2;
NiceMock<MockReadCallback> readCb3;
transport->setReadCallback(stream1, &readCb1);
transport->setReadCallback(stream2, &readCb2);
transport->addDataToStream(
stream1, StreamBuffer(folly::IOBuf::copyBuffer("actual stream data"), 0));
transport->addDataToStream(
stream2,
StreamBuffer(folly::IOBuf::copyBuffer("actual stream data"), 10));
transport->addDataToStream(
stream3, StreamBuffer(folly::IOBuf::copyBuffer("actual stream data"), 0));
EXPECT_CALL(readCb1, readAvailable(stream1));
transport->driveReadCallbacks();
transport->setReadCallback(stream3, &readCb3);
transport->addDataToStream(
stream2, StreamBuffer(folly::IOBuf::copyBuffer("actual stream data"), 0));
EXPECT_CALL(readCb1, readAvailable(stream1));
EXPECT_CALL(readCb2, readAvailable(stream2));
EXPECT_CALL(readCb3, readAvailable(stream3));
transport->driveReadCallbacks();
EXPECT_CALL(readCb1, readAvailable(stream1));
EXPECT_CALL(readCb2, readAvailable(stream2));
EXPECT_CALL(readCb3, readAvailable(stream3));
transport->driveReadCallbacks();
EXPECT_CALL(readCb2, readAvailable(stream2));
EXPECT_CALL(readCb3, readAvailable(stream3));
transport->setReadCallback(stream1, nullptr);
transport->driveReadCallbacks();
transport.reset();
}
TEST_P(QuicTransportImplTestBase, ReadCallbackDataAvailableOrdered) {
auto transportSettings = transport->getTransportSettings();
transportSettings.orderedReadCallbacks = true;
transport->setTransportSettings(transportSettings);
auto stream1 = transport->createBidirectionalStream().value();
auto stream2 = transport->createBidirectionalStream().value();
StreamId stream3 = 0x6;
InSequence s;
NiceMock<MockReadCallback> readCb1;
NiceMock<MockReadCallback> readCb2;
NiceMock<MockReadCallback> readCb3;
transport->setReadCallback(stream1, &readCb1);
transport->setReadCallback(stream2, &readCb2);
transport->addDataToStream(
stream1, StreamBuffer(folly::IOBuf::copyBuffer("actual stream data"), 0));
transport->addDataToStream(
stream2,
StreamBuffer(folly::IOBuf::copyBuffer("actual stream data"), 10));
transport->addDataToStream(
stream3, StreamBuffer(folly::IOBuf::copyBuffer("actual stream data"), 0));
transport->setReadCallback(stream3, &readCb3);
EXPECT_CALL(readCb1, readAvailable(stream1));
EXPECT_CALL(readCb3, readAvailable(stream3));
transport->driveReadCallbacks();
transport->addDataToStream(
stream2, StreamBuffer(folly::IOBuf::copyBuffer("actual stream data"), 0));
EXPECT_CALL(readCb1, readAvailable(stream1));
EXPECT_CALL(readCb2, readAvailable(stream2));
EXPECT_CALL(readCb3, readAvailable(stream3));
transport->driveReadCallbacks();
EXPECT_CALL(readCb1, readAvailable(stream1));
EXPECT_CALL(readCb2, readAvailable(stream2));
EXPECT_CALL(readCb3, readAvailable(stream3));
transport->driveReadCallbacks();
EXPECT_CALL(readCb2, readAvailable(stream2));
EXPECT_CALL(readCb3, readAvailable(stream3));
transport->setReadCallback(stream1, nullptr);
transport->driveReadCallbacks();
transport.reset();
}
TEST_P(QuicTransportImplTestBase, ReadCallbackChangeReadCallback) {
auto stream1 = transport->createBidirectionalStream().value();
NiceMock<MockReadCallback> readCb1;
NiceMock<MockReadCallback> readCb2;
EXPECT_TRUE(transport->setReadCallback(stream1, nullptr).hasError());
transport->setReadCallback(stream1, &readCb1);
transport->addDataToStream(
stream1, StreamBuffer(folly::IOBuf::copyBuffer("actual stream data"), 0));
EXPECT_CALL(readCb1, readAvailable(stream1));
transport->driveReadCallbacks();
transport->setReadCallback(stream1, &readCb2);
EXPECT_CALL(readCb2, readAvailable(stream1));
transport->driveReadCallbacks();
auto& conn = transport->getConnectionState();
EXPECT_EQ(conn.pendingEvents.frames.size(), 0);
transport->setReadCallback(stream1, nullptr);
EXPECT_EQ(conn.pendingEvents.frames.size(), 1);
EXPECT_CALL(readCb2, readAvailable(_)).Times(0);
transport->driveReadCallbacks();
EXPECT_TRUE(transport->setReadCallback(stream1, &readCb2).hasError());
transport.reset();
}
TEST_P(QuicTransportImplTestBase, ReadCallbackUnsetAll) {
auto stream1 = transport->createBidirectionalStream().value();
auto stream2 = transport->createBidirectionalStream().value();
NiceMock<MockReadCallback> readCb1;
NiceMock<MockReadCallback> readCb2;
// Set the read callbacks, and then add data to the stream, and see that the
// callbacks are, in fact, called.
transport->setReadCallback(stream1, &readCb1);
transport->setReadCallback(stream2, &readCb2);
EXPECT_CALL(readCb1, readAvailable(stream1));
EXPECT_CALL(readCb2, readAvailable(stream2));
transport->addDataToStream(
stream1, StreamBuffer(folly::IOBuf::copyBuffer("actual stream data"), 0));
transport->addDataToStream(
stream2, StreamBuffer(folly::IOBuf::copyBuffer("actual stream data"), 0));
transport->driveReadCallbacks();
// Unset all of the read callbacks, then add data to the stream, and see that
// the read callbacks are not called.
transport->unsetAllReadCallbacks();
EXPECT_CALL(readCb1, readAvailable(stream1)).Times(0);
EXPECT_CALL(readCb2, readAvailable(stream2)).Times(0);
transport->addDataToStream(
stream1, StreamBuffer(folly::IOBuf::copyBuffer("actual stream data"), 0));
transport->addDataToStream(
stream2, StreamBuffer(folly::IOBuf::copyBuffer("actual stream data"), 0));
transport->driveReadCallbacks();
transport.reset();
}
TEST_P(QuicTransportImplTestBase, ReadCallbackPauseResume) {
auto stream1 = transport->createBidirectionalStream().value();
auto stream2 = transport->createBidirectionalStream().value();
NiceMock<MockReadCallback> readCb1;
NiceMock<MockReadCallback> readCb2;
transport->setReadCallback(stream1, &readCb1);
transport->setReadCallback(stream2, &readCb2);
transport->addDataToStream(
stream1, StreamBuffer(folly::IOBuf::copyBuffer("actual stream data"), 0));
transport->addDataToStream(
stream2, StreamBuffer(folly::IOBuf::copyBuffer("actual stream data"), 0));
auto res = transport->pauseRead(stream1);
EXPECT_TRUE(res);
EXPECT_CALL(readCb1, readAvailable(stream1)).Times(0);
EXPECT_CALL(readCb2, readAvailable(stream2));
transport->driveReadCallbacks();
res = transport->resumeRead(stream1);
EXPECT_TRUE(res);
res = transport->pauseRead(stream2);
EXPECT_CALL(readCb1, readAvailable(stream1));
EXPECT_CALL(readCb2, readAvailable(stream2)).Times(0);
transport->driveReadCallbacks();
auto stream3 = transport->createBidirectionalStream().value();
res = transport->pauseRead(stream3);
EXPECT_FALSE(res);
EXPECT_EQ(LocalErrorCode::APP_ERROR, res.error());
transport.reset();
}
TEST_P(QuicTransportImplTestBase, ReadCallbackNoCallbackSet) {
auto stream1 = transport->createBidirectionalStream().value();
transport->addDataToStream(
stream1,
StreamBuffer(folly::IOBuf::copyBuffer("actual stream data"), 10));
transport->driveReadCallbacks();
transport->addDataToStream(
stream1, StreamBuffer(folly::IOBuf::copyBuffer("actual stream data"), 0));
transport->driveReadCallbacks();
transport.reset();
}
TEST_P(QuicTransportImplTestBase, ReadCallbackInvalidStream) {
NiceMock<MockReadCallback> readCb1;
StreamId invalidStream = 10;
EXPECT_TRUE(transport->setReadCallback(invalidStream, &readCb1).hasError());
transport.reset();
}
TEST_P(QuicTransportImplTestBase, ReadData) {
auto stream1 = transport->createBidirectionalStream().value();
NiceMock<MockReadCallback> readCb1;
auto readData = folly::IOBuf::copyBuffer("actual stream data");
transport->setReadCallback(stream1, &readCb1);
EXPECT_CALL(readCb1, readAvailable(stream1));
transport->addDataToStream(stream1, StreamBuffer(readData->clone(), 0));
transport->driveReadCallbacks();
transport->read(stream1, 10).thenOrThrow([&](std::pair<Buf, bool> data) {
IOBufEqualTo eq;
auto expected = readData->clone();
expected->trimEnd(expected->length() - 10);
EXPECT_TRUE(eq(*data.first, *expected));
});
EXPECT_CALL(readCb1, readAvailable(stream1));
transport->driveReadCallbacks();
transport->read(stream1, 100).thenOrThrow([&](std::pair<Buf, bool> data) {
IOBufEqualTo eq;
auto expected = readData->clone();
expected->trimStart(10);
EXPECT_TRUE(eq(*data.first, *expected));
});
transport->driveReadCallbacks();
transport.reset();
}
// TODO The finest copypasta around. We need a better story for parameterizing
// unidirectional vs. bidirectional.
TEST_P(QuicTransportImplTestBase, UnidirectionalReadData) {
auto stream1 = 0x6;
NiceMock<MockReadCallback> readCb1;
auto readData = folly::IOBuf::copyBuffer("actual stream data");
transport->addDataToStream(stream1, StreamBuffer(readData->clone(), 0));
transport->setReadCallback(stream1, &readCb1);
EXPECT_CALL(readCb1, readAvailable(stream1));
transport->driveReadCallbacks();
transport->read(stream1, 10).thenOrThrow([&](std::pair<Buf, bool> data) {
IOBufEqualTo eq;
auto expected = readData->clone();
expected->trimEnd(expected->length() - 10);
EXPECT_TRUE(eq(*data.first, *expected));
});
EXPECT_CALL(readCb1, readAvailable(stream1));
transport->driveReadCallbacks();
transport->read(stream1, 100).thenOrThrow([&](std::pair<Buf, bool> data) {
IOBufEqualTo eq;
auto expected = readData->clone();
expected->trimStart(10);
EXPECT_TRUE(eq(*data.first, *expected));
});
transport->driveReadCallbacks();
transport.reset();
}
TEST_P(QuicTransportImplTestBase, ReadDataUnsetReadCallbackInCallback) {
auto stream1 = transport->createBidirectionalStream().value();
auto readData = folly::IOBuf::copyBuffer("actual stream data");
NiceMock<MockReadCallback> readCb1;
transport->setReadCallback(stream1, &readCb1);
transport->addDataToStream(stream1, StreamBuffer(readData->clone(), 0, true));
EXPECT_CALL(readCb1, readAvailable(stream1))
.WillOnce(Invoke(
[&](StreamId id) { transport->setReadCallback(id, nullptr); }));
transport->driveReadCallbacks();
transport->driveReadCallbacks();
transport->getEventBase()->loop();
transport.reset();
}
TEST_P(QuicTransportImplTestBase, ReadDataNoCallback) {
auto stream1 = transport->createBidirectionalStream().value();
auto readData = folly::IOBuf::copyBuffer("actual stream data");
transport->addDataToStream(stream1, StreamBuffer(readData->clone(), 0, true));
transport->driveReadCallbacks();
transport->read(stream1, 100).thenOrThrow([&](std::pair<Buf, bool> data) {
IOBufEqualTo eq;
EXPECT_TRUE(eq(*data.first, *readData));
EXPECT_TRUE(data.second);
});
transport.reset();
}
TEST_P(QuicTransportImplTestBase, ReadCallbackForClientOutOfOrderStream) {
auto const notifyOnNewStreamsExplicitly =
transport->getTransportSettings().notifyOnNewStreamsExplicitly;
InSequence dummy;
StreamId clientOutOfOrderStream = 96;
StreamId clientOutOfOrderStream2 = 76;
auto readData = folly::IOBuf::copyBuffer("actual stream data");
NiceMock<MockReadCallback> streamRead;
if (notifyOnNewStreamsExplicitly) {
EXPECT_CALL(connCallback, onNewBidirectionalStream(clientOutOfOrderStream))
.WillOnce(Invoke(
[&](StreamId id) { transport->setReadCallback(id, &streamRead); }));
} else {
for (StreamId start = 0x00; start <= clientOutOfOrderStream;
start += kStreamIncrement) {
EXPECT_CALL(connCallback, onNewBidirectionalStream(start))
.WillOnce(Invoke([&](StreamId id) {
transport->setReadCallback(id, &streamRead);
}));
}
}
EXPECT_CALL(streamRead, readAvailable(clientOutOfOrderStream))
.WillOnce(Invoke([&](StreamId id) {
transport->read(id, 100).thenOrThrow([&](std::pair<Buf, bool> data) {
IOBufEqualTo eq;
EXPECT_TRUE(eq(*data.first, *readData));
EXPECT_TRUE(data.second);
});
}));
transport->addDataToStream(
clientOutOfOrderStream, StreamBuffer(readData->clone(), 0, true));
transport->driveReadCallbacks();
if (notifyOnNewStreamsExplicitly) {
EXPECT_CALL(connCallback, onNewBidirectionalStream(clientOutOfOrderStream2))
.WillOnce(Invoke(
[&](StreamId id) { transport->setReadCallback(id, &streamRead); }));
}
transport->addDataToStream(
clientOutOfOrderStream2, StreamBuffer(readData->clone(), 0, true));
EXPECT_CALL(streamRead, readAvailable(clientOutOfOrderStream2))
.WillOnce(Invoke([&](StreamId id) {
transport->read(id, 100).thenOrThrow([&](std::pair<Buf, bool> data) {
IOBufEqualTo eq;
EXPECT_TRUE(eq(*data.first, *readData));
EXPECT_TRUE(data.second);
});
}));
transport->driveReadCallbacks();
transport.reset();
}
TEST_P(QuicTransportImplTestBase, ReadDataInvalidStream) {
StreamId invalidStream = 10;
EXPECT_THROW(
transport->read(invalidStream, 100).thenOrThrow([&](auto) {}),
folly::BadExpectedAccess<LocalErrorCode>);
transport.reset();
}
TEST_P(QuicTransportImplTestBase, ReadError) {
auto stream1 = transport->createBidirectionalStream().value();
NiceMock<MockReadCallback> readCb1;
auto readData = folly::IOBuf::copyBuffer("actual stream data");
transport->setReadCallback(stream1, &readCb1);
EXPECT_CALL(
readCb1, readError(stream1, IsError(LocalErrorCode::STREAM_CLOSED)));
transport->addStreamReadError(stream1, LocalErrorCode::STREAM_CLOSED);
transport->driveReadCallbacks();
transport.reset();
}
TEST_P(QuicTransportImplTestBase, ReadCallbackDeleteTransport) {
auto stream1 = transport->createBidirectionalStream().value();
auto stream2 = transport->createBidirectionalStream().value();
NiceMock<MockReadCallback> readCb1;
NiceMock<MockReadCallback> readCb2;
transport->setReadCallback(stream1, &readCb1);
transport->setReadCallback(stream2, &readCb2);
transport->addStreamReadError(stream1, LocalErrorCode::NO_ERROR);
transport->addDataToStream(
stream2, StreamBuffer(folly::IOBuf::copyBuffer("actual stream data"), 0));
EXPECT_CALL(readCb1, readError(stream1, _)).WillOnce(Invoke([&](auto, auto) {
transport.reset();
}));
EXPECT_CALL(readCb2, readAvailable(stream2));
transport->driveReadCallbacks();
transport.reset();
}
TEST_P(QuicTransportImplTestBase, onNewBidirectionalStreamCallback) {
auto const notifyOnNewStreamsExplicitly =
transport->getTransportSettings().notifyOnNewStreamsExplicitly;
auto readData = folly::IOBuf::copyBuffer("actual stream data");
StreamId stream2 = 0x00;
EXPECT_CALL(connCallback, onNewBidirectionalStream(stream2));
transport->addDataToStream(stream2, StreamBuffer(readData->clone(), 0, true));
StreamId stream3 = 0x04;
EXPECT_CALL(connCallback, onNewBidirectionalStream(stream3));
transport->addDataToStream(stream3, StreamBuffer(readData->clone(), 0, true));
StreamId uniStream3 = 0xa;
if (!notifyOnNewStreamsExplicitly) {
EXPECT_CALL(
connCallback,
onNewUnidirectionalStream(uniStream3 - 2 * kStreamIncrement));
EXPECT_CALL(
connCallback, onNewUnidirectionalStream(uniStream3 - kStreamIncrement));
}
EXPECT_CALL(connCallback, onNewUnidirectionalStream(uniStream3));
transport->addDataToStream(
uniStream3, StreamBuffer(readData->clone(), 0, true));
transport.reset();
}
TEST_P(QuicTransportImplTestBase, onNewStreamCallbackDoesNotRemove) {
auto readData = folly::IOBuf::copyBuffer("actual stream data");
StreamId uniStream1 = 2;
StreamId uniStream2 = uniStream1 + kStreamIncrement;
EXPECT_CALL(connCallback, onNewUnidirectionalStream(uniStream1))
.WillOnce(Invoke([&](StreamId id) {
ASSERT_FALSE(transport->read(id, 100).hasError());
}));
EXPECT_CALL(connCallback, onNewUnidirectionalStream(uniStream2))
.WillOnce(Invoke([&](StreamId id) {
ASSERT_FALSE(transport->read(id, 100).hasError());
}));
transport->addDataToStream(
uniStream1, StreamBuffer(readData->clone(), 0, true));
transport->addDataToStream(
uniStream2, StreamBuffer(readData->clone(), 0, true));
transport.reset();
}
TEST_P(QuicTransportImplTestBase, onNewBidirectionalStreamStreamOutOfOrder) {
InSequence dummy;
auto readData = folly::IOBuf::copyBuffer("actual stream data");
StreamId biStream1 = 28;
StreamId uniStream1 = 30;
auto const notifyOnNewStreamsExplicitly =
transport->getTransportSettings().notifyOnNewStreamsExplicitly;
if (notifyOnNewStreamsExplicitly) {
EXPECT_CALL(connCallback, onNewBidirectionalStream(biStream1));
EXPECT_CALL(connCallback, onNewUnidirectionalStream(uniStream1));
} else {
for (StreamId id = 0x00; id <= biStream1; id += kStreamIncrement) {
EXPECT_CALL(connCallback, onNewBidirectionalStream(id));
}
for (StreamId id = 0x02; id <= uniStream1; id += kStreamIncrement) {
EXPECT_CALL(connCallback, onNewUnidirectionalStream(id));
}
}
transport->addDataToStream(
biStream1, StreamBuffer(readData->clone(), 0, true));
transport->addDataToStream(
uniStream1, StreamBuffer(readData->clone(), 0, true));
StreamId biStream2 = 56;
StreamId uniStream2 = 38;
if (notifyOnNewStreamsExplicitly) {
EXPECT_CALL(connCallback, onNewBidirectionalStream(biStream2));
EXPECT_CALL(connCallback, onNewUnidirectionalStream(uniStream2));
} else {
for (StreamId id = biStream1 + kStreamIncrement; id <= biStream2;
id += kStreamIncrement) {
EXPECT_CALL(connCallback, onNewBidirectionalStream(id));
}
for (StreamId id = uniStream1 + kStreamIncrement; id <= uniStream2;
id += kStreamIncrement) {
EXPECT_CALL(connCallback, onNewUnidirectionalStream(id));
}
}
transport->addDataToStream(
biStream2, StreamBuffer(readData->clone(), 0, true));
transport->addDataToStream(
uniStream2, StreamBuffer(readData->clone(), 0, true));
transport.reset();
}
TEST_P(QuicTransportImplTestBase, onNewBidirectionalStreamSetReadCallback) {
auto const notifyOnNewStreamsExplicitly =
transport->getTransportSettings().notifyOnNewStreamsExplicitly;
InSequence dummy;
auto readData = folly::IOBuf::copyBuffer("actual stream data");
transport->addCryptoData(StreamBuffer(readData->clone(), 0, true));
NiceMock<MockReadCallback> stream2Read;
StreamId stream2 = 0x00;
EXPECT_CALL(connCallback, onNewBidirectionalStream(stream2))
.WillOnce(Invoke(
[&](StreamId id) { transport->setReadCallback(id, &stream2Read); }));
transport->addDataToStream(stream2, StreamBuffer(readData->clone(), 0, true));
StreamId stream3 = 0x10;
NiceMock<MockReadCallback> streamRead;
if (notifyOnNewStreamsExplicitly) {
EXPECT_CALL(connCallback, onNewBidirectionalStream(stream3))
.WillOnce(Invoke(
[&](StreamId id) { transport->setReadCallback(id, &streamRead); }));
} else {
for (StreamId start = stream2 + kStreamIncrement; start <= stream3;
start += kStreamIncrement) {
EXPECT_CALL(connCallback, onNewBidirectionalStream(start))
.WillOnce(Invoke([&](StreamId id) {
transport->setReadCallback(id, &streamRead);
}));
}
}
transport->addDataToStream(stream3, StreamBuffer(readData->clone(), 0, true));
evb->loopOnce();
transport.reset();
}
TEST_P(QuicTransportImplTestBase, OnInvalidServerStream) {
EXPECT_CALL(
connSetupCallback,
onConnectionSetupError(IsError(TransportErrorCode::STREAM_STATE_ERROR)));
auto readData = folly::IOBuf::copyBuffer("actual stream data");
StreamId stream1 = 29;
transport->addDataToStream(stream1, StreamBuffer(readData->clone(), 0, true));
EXPECT_TRUE(transport->isClosed());
EXPECT_EQ(
transport->getConnectionError(),
QuicErrorCode(TransportErrorCode::STREAM_STATE_ERROR));
transport.reset();
}
TEST_P(QuicTransportImplTestBase, CreateStream) {
auto streamId = transport->createBidirectionalStream().value();
auto streamId2 = transport->createBidirectionalStream().value();
auto streamId3 = transport->createBidirectionalStream().value();
auto streamId4 = transport->createBidirectionalStream().value();
EXPECT_EQ(streamId2, streamId + kStreamIncrement);
EXPECT_EQ(streamId3, streamId2 + kStreamIncrement);
EXPECT_EQ(streamId4, streamId3 + kStreamIncrement);
transport.reset();
}
TEST_P(QuicTransportImplTestBase, CreateUnidirectionalStream) {
auto streamId = transport->createUnidirectionalStream().value();
auto streamId2 = transport->createUnidirectionalStream().value();
auto streamId3 = transport->createUnidirectionalStream().value();
auto streamId4 = transport->createUnidirectionalStream().value();
EXPECT_EQ(streamId2, streamId + kStreamIncrement);
EXPECT_EQ(streamId3, streamId2 + kStreamIncrement);
EXPECT_EQ(streamId4, streamId3 + kStreamIncrement);
transport.reset();
}
TEST_P(QuicTransportImplTestBase, CreateBothStream) {
auto uniStreamId = transport->createUnidirectionalStream().value();
auto biStreamId = transport->createBidirectionalStream().value();
auto uniStreamId2 = transport->createUnidirectionalStream().value();
auto biStreamId2 = transport->createBidirectionalStream().value();
auto uniStreamId3 = transport->createUnidirectionalStream().value();
auto biStreamId3 = transport->createBidirectionalStream().value();
auto uniStreamId4 = transport->createUnidirectionalStream().value();
auto biStreamId4 = transport->createBidirectionalStream().value();
EXPECT_EQ(uniStreamId2, uniStreamId + kStreamIncrement);
EXPECT_EQ(uniStreamId3, uniStreamId2 + kStreamIncrement);
EXPECT_EQ(uniStreamId4, uniStreamId3 + kStreamIncrement);
EXPECT_EQ(biStreamId2, biStreamId + kStreamIncrement);
EXPECT_EQ(biStreamId3, biStreamId2 + kStreamIncrement);
EXPECT_EQ(biStreamId4, biStreamId3 + kStreamIncrement);
transport.reset();
}
TEST_P(QuicTransportImplTestBase, CreateStreamLimitsBidirectionalZero) {
transport->transportConn->streamManager->setMaxLocalBidirectionalStreams(
0, true);
EXPECT_EQ(transport->getNumOpenableBidirectionalStreams(), 0);
auto result = transport->createBidirectionalStream();
ASSERT_FALSE(result);
EXPECT_EQ(result.error(), LocalErrorCode::STREAM_LIMIT_EXCEEDED);
result = transport->createUnidirectionalStream();
EXPECT_TRUE(result);
transport.reset();
}
TEST_P(QuicTransportImplTestBase, CreateStreamLimitsUnidirectionalZero) {
transport->transportConn->streamManager->setMaxLocalUnidirectionalStreams(
0, true);
EXPECT_EQ(transport->getNumOpenableUnidirectionalStreams(), 0);
auto result = transport->createUnidirectionalStream();
ASSERT_FALSE(result);
EXPECT_EQ(result.error(), LocalErrorCode::STREAM_LIMIT_EXCEEDED);
result = transport->createBidirectionalStream();
EXPECT_TRUE(result);
transport.reset();
}
TEST_P(QuicTransportImplTestBase, CreateStreamLimitsBidirectionalFew) {
transport->transportConn->streamManager->setMaxLocalBidirectionalStreams(
10, true);
EXPECT_EQ(transport->getNumOpenableBidirectionalStreams(), 10);
for (int i = 0; i < 10; i++) {
EXPECT_TRUE(transport->createBidirectionalStream());
EXPECT_EQ(transport->getNumOpenableBidirectionalStreams(), 10 - (i + 1));
}
auto result = transport->createBidirectionalStream();
ASSERT_FALSE(result);
EXPECT_EQ(result.error(), LocalErrorCode::STREAM_LIMIT_EXCEEDED);
EXPECT_TRUE(transport->createUnidirectionalStream());
transport.reset();
}
TEST_P(QuicTransportImplTestBase, CreateStreamLimitsUnidirectionalFew) {
transport->transportConn->streamManager->setMaxLocalUnidirectionalStreams(
10, true);
EXPECT_EQ(transport->getNumOpenableUnidirectionalStreams(), 10);
for (int i = 0; i < 10; i++) {
EXPECT_TRUE(transport->createUnidirectionalStream());
EXPECT_EQ(transport->getNumOpenableUnidirectionalStreams(), 10 - (i + 1));
}
auto result = transport->createUnidirectionalStream();
ASSERT_FALSE(result);
EXPECT_EQ(result.error(), LocalErrorCode::STREAM_LIMIT_EXCEEDED);
EXPECT_TRUE(transport->createBidirectionalStream());
transport.reset();
}
TEST_P(QuicTransportImplTestBase, onBidiStreamsAvailableCallback) {
transport->transportConn->streamManager->setMaxLocalBidirectionalStreams(
0, /*force=*/true);
EXPECT_CALL(connCallback, onBidirectionalStreamsAvailable(_))
.WillOnce(Invoke([](uint64_t numAvailableStreams) {
EXPECT_EQ(numAvailableStreams, 1);
}));
transport->addMaxStreamsFrame(MaxStreamsFrame(1, /*isBidirectionalIn=*/true));
EXPECT_EQ(transport->getNumOpenableBidirectionalStreams(), 1);
// same value max streams frame doesn't trigger callback
transport->addMaxStreamsFrame(MaxStreamsFrame(1, /*isBidirectionalIn=*/true));
}
TEST_P(QuicTransportImplTestBase, onBidiStreamsAvailableCallbackAfterExausted) {
transport->transportConn->streamManager->setMaxLocalBidirectionalStreams(
0, /*force=*/true);
EXPECT_CALL(connCallback, onBidirectionalStreamsAvailable(_)).Times(2);
transport->addMaxStreamsFrame(MaxStreamsFrame(
1,
/*isBidirectionalIn=*/true));
EXPECT_EQ(transport->getNumOpenableBidirectionalStreams(), 1);
auto result = transport->createBidirectionalStream();
EXPECT_TRUE(result);
EXPECT_EQ(transport->getNumOpenableBidirectionalStreams(), 0);
transport->addMaxStreamsFrame(MaxStreamsFrame(
2,
/*isBidirectionalIn=*/true));
}
TEST_P(QuicTransportImplTestBase, oneUniStreamsAvailableCallback) {
transport->transportConn->streamManager->setMaxLocalUnidirectionalStreams(
0, /*force=*/true);
EXPECT_CALL(connCallback, onUnidirectionalStreamsAvailable(_))
.WillOnce(Invoke([](uint64_t numAvailableStreams) {
EXPECT_EQ(numAvailableStreams, 1);
}));
transport->addMaxStreamsFrame(
MaxStreamsFrame(1, /*isBidirectionalIn=*/false));
EXPECT_EQ(transport->getNumOpenableUnidirectionalStreams(), 1);
// same value max streams frame doesn't trigger callback
transport->addMaxStreamsFrame(
MaxStreamsFrame(1, /*isBidirectionalIn=*/false));
}
TEST_P(QuicTransportImplTestBase, onUniStreamsAvailableCallbackAfterExausted) {
transport->transportConn->streamManager->setMaxLocalUnidirectionalStreams(
0, /*force=*/true);
EXPECT_CALL(connCallback, onUnidirectionalStreamsAvailable(_)).Times(2);
transport->addMaxStreamsFrame(
MaxStreamsFrame(1, /*isBidirectionalIn=*/false));
EXPECT_EQ(transport->getNumOpenableUnidirectionalStreams(), 1);
auto result = transport->createUnidirectionalStream();
EXPECT_TRUE(result);
EXPECT_EQ(transport->getNumOpenableUnidirectionalStreams(), 0);
transport->addMaxStreamsFrame(
MaxStreamsFrame(2, /*isBidirectionalIn=*/false));
}
TEST_P(QuicTransportImplTestBase, ReadDataAlsoChecksLossAlarm) {
transport->transportConn->oneRttWriteCipher = test::createNoOpAead();
auto stream = transport->createBidirectionalStream().value();
transport->writeChain(stream, folly::IOBuf::copyBuffer("Hey"), true);
// Artificially stop the write looper so that the read can trigger it.
transport->writeLooper()->stop();
transport->addDataToStream(
stream, StreamBuffer(folly::IOBuf::copyBuffer("Data"), 0));
EXPECT_TRUE(transport->writeLooper()->isRunning());
// Drive the event loop once to allow for the write looper to continue.
evb->loopOnce();
EXPECT_TRUE(transport->isLossTimeoutScheduled());
transport.reset();
}
TEST_P(QuicTransportImplTestBase, ConnectionErrorOnWrite) {
transport->transportConn->oneRttWriteCipher = test::createNoOpAead();
auto stream = transport->createBidirectionalStream().value();
EXPECT_CALL(*socketPtr, write(_, _))
.WillOnce(SetErrnoAndReturn(ENETUNREACH, -1));
transport->writeChain(stream, folly::IOBuf::copyBuffer("Hey"), true, nullptr);
transport->addDataToStream(
stream, StreamBuffer(folly::IOBuf::copyBuffer("Data"), 0));
evb->loopOnce();
EXPECT_TRUE(transport->isClosed());
EXPECT_EQ(
transport->getConnectionError(),
QuicErrorCode(LocalErrorCode::CONNECTION_ABANDONED));
}
TEST_P(QuicTransportImplTestBase, ReadErrorUnsanitizedErrorMsg) {
transport->setServerConnectionId();
transport->transportConn->oneRttWriteCipher = test::createNoOpAead();
auto stream = transport->createBidirectionalStream().value();
MockReadCallback rcb;
transport->setReadCallback(stream, &rcb);
EXPECT_CALL(rcb, readError(stream, _))
.Times(1)
.WillOnce(Invoke([](StreamId, QuicError error) {
EXPECT_EQ("You need to calm down.", error.message);
}));
EXPECT_CALL(*socketPtr, write(_, _)).WillOnce(Invoke([](auto&, auto&) {
throw std::runtime_error("You need to calm down.");
return 0;
}));
transport->writeChain(
stream,
folly::IOBuf::copyBuffer("You are being too loud."),
true,
nullptr);
evb->loopOnce();
EXPECT_TRUE(transport->isClosed());
}
TEST_P(QuicTransportImplTestBase, ConnectionErrorUnhandledException) {
transport->transportConn->oneRttWriteCipher = test::createNoOpAead();
auto stream = transport->createBidirectionalStream().value();
EXPECT_CALL(
connSetupCallback,
onConnectionSetupError(QuicError(
QuicErrorCode(TransportErrorCode::INTERNAL_ERROR),
std::string("Well there's your problem"))));
EXPECT_CALL(*socketPtr, write(_, _)).WillOnce(Invoke([](auto&, auto&) {
throw std::runtime_error("Well there's your problem");
return 0;
}));
transport->writeChain(stream, folly::IOBuf::copyBuffer("Hey"), true, nullptr);
transport->addDataToStream(
stream, StreamBuffer(folly::IOBuf::copyBuffer("Data"), 0));
evb->loopOnce();
EXPECT_TRUE(transport->isClosed());
EXPECT_EQ(
transport->getConnectionError(),
QuicErrorCode(TransportErrorCode::INTERNAL_ERROR));
}
TEST_P(QuicTransportImplTestBase, LossTimeoutNoLessThanTickInterval) {
auto tickInterval = evb->getTimerTickInterval();
transport->scheduleLossTimeout(tickInterval - 1ms);
EXPECT_NEAR(
tickInterval.count(),
transport->getLossTimeoutRemainingTime().count(),
2);
}
TEST_P(QuicTransportImplTestBase, CloseStreamAfterReadError) {
auto qLogger = std::make_shared<FileQLogger>(VantagePoint::Client);
transport->transportConn->qLogger = qLogger;
auto stream1 = transport->createBidirectionalStream().value();
NiceMock<MockReadCallback> readCb1;
transport->setReadCallback(stream1, &readCb1);
transport->addStreamReadError(stream1, LocalErrorCode::NO_ERROR);
transport->closeStream(stream1);
EXPECT_CALL(readCb1, readError(stream1, IsError(LocalErrorCode::NO_ERROR)));
transport->driveReadCallbacks();
EXPECT_FALSE(transport->transportConn->streamManager->streamExists(stream1));
transport.reset();
std::vector<int> indices =
getQLogEventIndices(QLogEventType::TransportStateUpdate, qLogger);
EXPECT_EQ(indices.size(), 1);
auto tmp = std::move(qLogger->logs[indices[0]]);
auto event = dynamic_cast<QLogTransportStateUpdateEvent*>(tmp.get());
EXPECT_EQ(event->update, getClosingStream("1"));
}
TEST_P(QuicTransportImplTestBase, CloseStreamAfterReadFin) {
auto stream2 = transport->createBidirectionalStream().value();
NiceMock<MockReadCallback> readCb2;
transport->setReadCallback(stream2, &readCb2);
transport->addDataToStream(
stream2,
StreamBuffer(folly::IOBuf::copyBuffer("actual stream data"), 0, true));
EXPECT_CALL(readCb2, readAvailable(stream2)).WillOnce(Invoke([&](StreamId) {
auto data = transport->read(stream2, 100);
EXPECT_TRUE(data->second);
transport->closeStream(stream2);
}));
transport->driveReadCallbacks();
EXPECT_FALSE(transport->transportConn->streamManager->streamExists(stream2));
transport.reset();
}
TEST_P(QuicTransportImplTestBase, CloseTransportCleansupOutstandingCounters) {
transport->transportConn->outstandings
.packetCount[PacketNumberSpace::Handshake] = 200;
transport->closeNow(folly::none);
EXPECT_EQ(
0,
transport->transportConn->outstandings
.packetCount[PacketNumberSpace::Handshake]);
}
TEST_P(QuicTransportImplTestBase, DeliveryCallbackUnsetAll) {
auto stream1 = transport->createBidirectionalStream().value();
auto stream2 = transport->createBidirectionalStream().value();
NiceMock<MockDeliveryCallback> dcb1;
NiceMock<MockDeliveryCallback> dcb2;
transport->registerDeliveryCallback(stream1, 10, &dcb1);
transport->registerDeliveryCallback(stream2, 20, &dcb2);
EXPECT_CALL(dcb1, onCanceled(_, _));
EXPECT_CALL(dcb2, onCanceled(_, _));
transport->unsetAllDeliveryCallbacks();
EXPECT_CALL(dcb1, onCanceled(_, _)).Times(0);
EXPECT_CALL(dcb2, onCanceled(_, _)).Times(0);
transport->close(folly::none);
}
TEST_P(QuicTransportImplTestBase, DeliveryCallbackUnsetOne) {
auto stream1 = transport->createBidirectionalStream().value();
auto stream2 = transport->createBidirectionalStream().value();
NiceMock<MockDeliveryCallback> dcb1;
NiceMock<MockDeliveryCallback> dcb2;
transport->registerDeliveryCallback(stream1, 10, &dcb1);
transport->registerDeliveryCallback(stream2, 20, &dcb2);
EXPECT_CALL(dcb1, onCanceled(_, _));
EXPECT_CALL(dcb2, onCanceled(_, _)).Times(0);
transport->cancelDeliveryCallbacksForStream(stream1);
EXPECT_CALL(dcb1, onCanceled(_, _)).Times(0);
EXPECT_CALL(dcb2, onCanceled(_, _));
transport->close(folly::none);
}
TEST_P(QuicTransportImplTestBase, ByteEventCallbacksManagementSingleStream) {
auto stream = transport->createBidirectionalStream().value();
uint64_t offset1 = 10, offset2 = 20;
ByteEvent txEvent1 = ByteEvent{stream, offset1, ByteEvent::Type::TX};
ByteEvent txEvent2 = ByteEvent{stream, offset2, ByteEvent::Type::TX};
ByteEvent ackEvent1 = ByteEvent{stream, offset1, ByteEvent::Type::ACK};
ByteEvent ackEvent2 = ByteEvent{stream, offset2, ByteEvent::Type::ACK};
// Register 2 TX and 2 ACK events for the same stream at 2 different offsets
transport->registerTxCallback(
txEvent1.id, txEvent1.offset, &byteEventCallback);
transport->registerTxCallback(
txEvent2.id, txEvent2.offset, &byteEventCallback);
transport->registerByteEventCallback(
ByteEvent::Type::ACK, ackEvent1.id, ackEvent1.offset, &byteEventCallback);
transport->registerByteEventCallback(
ByteEvent::Type::ACK, ackEvent2.id, ackEvent2.offset, &byteEventCallback);
EXPECT_THAT(
byteEventCallback.getByteEventTracker(),
UnorderedElementsAre(
getByteEventTrackerMatcher(
txEvent1, TestByteEventCallback::Status::REGISTERED),
getByteEventTrackerMatcher(
txEvent2, TestByteEventCallback::Status::REGISTERED),
getByteEventTrackerMatcher(
ackEvent1, TestByteEventCallback::Status::REGISTERED),
getByteEventTrackerMatcher(
ackEvent2, TestByteEventCallback::Status::REGISTERED)));
// Registering the same events a second time will result in an error.
// as double registrations are not allowed.
folly::Expected<folly::Unit, LocalErrorCode> ret;
ret = transport->registerTxCallback(
txEvent1.id, txEvent1.offset, &byteEventCallback);
EXPECT_EQ(LocalErrorCode::INVALID_OPERATION, ret.error());
ret = transport->registerTxCallback(
txEvent2.id, txEvent2.offset, &byteEventCallback);
EXPECT_EQ(LocalErrorCode::INVALID_OPERATION, ret.error());
ret = transport->registerByteEventCallback(
ByteEvent::Type::ACK, ackEvent1.id, ackEvent1.offset, &byteEventCallback);
EXPECT_EQ(LocalErrorCode::INVALID_OPERATION, ret.error());
ret = transport->registerByteEventCallback(
ByteEvent::Type::ACK, ackEvent2.id, ackEvent2.offset, &byteEventCallback);
EXPECT_EQ(LocalErrorCode::INVALID_OPERATION, ret.error());
EXPECT_THAT(
byteEventCallback.getByteEventTracker(),
UnorderedElementsAre(
getByteEventTrackerMatcher(
txEvent1, TestByteEventCallback::Status::REGISTERED),
getByteEventTrackerMatcher(
txEvent2, TestByteEventCallback::Status::REGISTERED),
getByteEventTrackerMatcher(
ackEvent1, TestByteEventCallback::Status::REGISTERED),
getByteEventTrackerMatcher(
ackEvent2, TestByteEventCallback::Status::REGISTERED)));
// On the ACK events, the transport usually sets the srtt value. This value
// should have NO EFFECT on the ByteEvent's hash and we still should be able
// to identify the previously registered byte event correctly.
ackEvent1.srtt = std::chrono::microseconds(1000);
ackEvent2.srtt = std::chrono::microseconds(2000);
// Deliver 1 TX and 1 ACK event. Cancel the other TX anc ACK event
byteEventCallback.onByteEvent(txEvent1);
byteEventCallback.onByteEvent(ackEvent2);
byteEventCallback.onByteEventCanceled(txEvent2);
byteEventCallback.onByteEventCanceled((ByteEventCancellation)ackEvent1);
EXPECT_THAT(
byteEventCallback.getByteEventTracker(),
UnorderedElementsAre(
getByteEventTrackerMatcher(
txEvent1, TestByteEventCallback::Status::RECEIVED),
getByteEventTrackerMatcher(
txEvent2, TestByteEventCallback::Status::CANCELLED),
getByteEventTrackerMatcher(
ackEvent1, TestByteEventCallback::Status::CANCELLED),
getByteEventTrackerMatcher(
ackEvent2, TestByteEventCallback::Status::RECEIVED)));
}
TEST_P(
QuicTransportImplTestBase,
ByteEventCallbacksManagementDifferentStreams) {
auto stream1 = transport->createBidirectionalStream().value();
auto stream2 = transport->createBidirectionalStream().value();
ByteEvent txEvent1 = ByteEvent{stream1, 10, ByteEvent::Type::TX};
ByteEvent txEvent2 = ByteEvent{stream2, 20, ByteEvent::Type::TX};
ByteEvent ackEvent1 = ByteEvent{stream1, 10, ByteEvent::Type::ACK};
ByteEvent ackEvent2 = ByteEvent{stream2, 20, ByteEvent::Type::ACK};
EXPECT_THAT(byteEventCallback.getByteEventTracker(), IsEmpty());
// Register 2 TX and 2 ACK events for 2 separate streams.
transport->registerTxCallback(
txEvent1.id, txEvent1.offset, &byteEventCallback);
transport->registerTxCallback(
txEvent2.id, txEvent2.offset, &byteEventCallback);
transport->registerByteEventCallback(
ByteEvent::Type::ACK, ackEvent1.id, ackEvent1.offset, &byteEventCallback);
transport->registerByteEventCallback(
ByteEvent::Type::ACK, ackEvent2.id, ackEvent2.offset, &byteEventCallback);
EXPECT_THAT(
byteEventCallback.getByteEventTracker(),
UnorderedElementsAre(
getByteEventTrackerMatcher(
txEvent1, TestByteEventCallback::Status::REGISTERED),
getByteEventTrackerMatcher(
txEvent2, TestByteEventCallback::Status::REGISTERED),
getByteEventTrackerMatcher(
ackEvent1, TestByteEventCallback::Status::REGISTERED),
getByteEventTrackerMatcher(
ackEvent2, TestByteEventCallback::Status::REGISTERED)));
// On the ACK events, the transport usually sets the srtt value. This value
// should have NO EFFECT on the ByteEvent's hash and we should still be able
// to identify the previously registered byte event correctly.
ackEvent1.srtt = std::chrono::microseconds(1000);
ackEvent2.srtt = std::chrono::microseconds(2000);
// Deliver the TX event for stream 1 and cancel the ACK event for stream 2
byteEventCallback.onByteEvent(txEvent1);
byteEventCallback.onByteEventCanceled((ByteEventCancellation)ackEvent2);
EXPECT_THAT(
byteEventCallback.getByteEventTracker(),
UnorderedElementsAre(
getByteEventTrackerMatcher(
txEvent1, TestByteEventCallback::Status::RECEIVED),
getByteEventTrackerMatcher(
txEvent2, TestByteEventCallback::Status::REGISTERED),
getByteEventTrackerMatcher(
ackEvent1, TestByteEventCallback::Status::REGISTERED),
getByteEventTrackerMatcher(
ackEvent2, TestByteEventCallback::Status::CANCELLED)));
// Deliver the TX event for stream 2 and cancel the ACK event for stream 1
byteEventCallback.onByteEvent(txEvent2);
byteEventCallback.onByteEventCanceled((ByteEventCancellation)ackEvent1);
EXPECT_THAT(
byteEventCallback.getByteEventTracker(),
UnorderedElementsAre(
getByteEventTrackerMatcher(
txEvent1, TestByteEventCallback::Status::RECEIVED),
getByteEventTrackerMatcher(
txEvent2, TestByteEventCallback::Status::RECEIVED),
getByteEventTrackerMatcher(
ackEvent1, TestByteEventCallback::Status::CANCELLED),
getByteEventTrackerMatcher(
ackEvent2, TestByteEventCallback::Status::CANCELLED)));
}
TEST_P(QuicTransportImplTestBase, RegisterTxDeliveryCallbackLowerThanExpected) {
auto stream = transport->createBidirectionalStream().value();
StrictMock<MockByteEventCallback> txcb1;
StrictMock<MockByteEventCallback> txcb2;
StrictMock<MockByteEventCallback> txcb3;
NiceMock<MockDeliveryCallback> dcb1;
NiceMock<MockDeliveryCallback> dcb2;
NiceMock<MockDeliveryCallback> dcb3;
EXPECT_CALL(txcb1, onByteEventRegistered(getTxMatcher(stream, 10)));
EXPECT_CALL(txcb2, onByteEventRegistered(getTxMatcher(stream, 20)));
transport->registerTxCallback(stream, 10, &txcb1);
transport->registerTxCallback(stream, 20, &txcb2);
transport->registerDeliveryCallback(stream, 10, &dcb1);
transport->registerDeliveryCallback(stream, 20, &dcb2);
Mock::VerifyAndClearExpectations(&txcb1);
Mock::VerifyAndClearExpectations(&txcb2);
auto streamState = transport->transportConn->streamManager->getStream(stream);
streamState->currentWriteOffset = 7;
streamState->ackedIntervals.insert(0, 6);
EXPECT_CALL(txcb3, onByteEventRegistered(getTxMatcher(stream, 2)));
EXPECT_CALL(txcb3, onByteEvent(getTxMatcher(stream, 2)));
EXPECT_CALL(dcb3, onDeliveryAck(stream, 2, _));
transport->registerTxCallback(stream, 2, &txcb3);
transport->registerDeliveryCallback(stream, 2, &dcb3);
evb->loopOnce();
Mock::VerifyAndClearExpectations(&txcb3);
Mock::VerifyAndClearExpectations(&dcb3);
EXPECT_CALL(txcb1, onByteEventCanceled(getTxMatcher(stream, 10)));
EXPECT_CALL(txcb2, onByteEventCanceled(getTxMatcher(stream, 20)));
EXPECT_CALL(dcb1, onCanceled(_, _));
EXPECT_CALL(dcb2, onCanceled(_, _));
transport->close(folly::none);
Mock::VerifyAndClearExpectations(&txcb1);
Mock::VerifyAndClearExpectations(&txcb2);
Mock::VerifyAndClearExpectations(&txcb3);
Mock::VerifyAndClearExpectations(&dcb1);
Mock::VerifyAndClearExpectations(&dcb2);
Mock::VerifyAndClearExpectations(&dcb3);
}
TEST_F(
QuicTransportImplTest,
RegisterTxDeliveryCallbackLowerThanExpectedClose) {
auto stream = transport->createBidirectionalStream().value();
StrictMock<MockByteEventCallback> txcb;
NiceMock<MockDeliveryCallback> dcb;
auto streamState = transport->transportConn->streamManager->getStream(stream);
streamState->currentWriteOffset = 7;
EXPECT_CALL(txcb, onByteEventRegistered(getTxMatcher(stream, 2)));
EXPECT_CALL(txcb, onByteEventCanceled(getTxMatcher(stream, 2)));
EXPECT_CALL(dcb, onCanceled(_, _));
transport->registerTxCallback(stream, 2, &txcb);
transport->registerDeliveryCallback(stream, 2, &dcb);
transport->close(folly::none);
evb->loopOnce();
Mock::VerifyAndClearExpectations(&txcb);
Mock::VerifyAndClearExpectations(&dcb);
}
TEST_P(
QuicTransportImplTestBase,
RegisterDeliveryCallbackMultipleRegistrationsTx) {
auto stream = transport->createBidirectionalStream().value();
StrictMock<MockByteEventCallback> txcb1;
StrictMock<MockByteEventCallback> txcb2;
// Set the current write offset to 7.
auto streamState = transport->transportConn->streamManager->getStream(stream);
streamState->currentWriteOffset = 7;
streamState->ackedIntervals.insert(0, 6);
// Have 2 different recipients register for a callback on the same stream ID
// and offset that is before the current write offset, they will both be
// scheduled for immediate delivery.
EXPECT_CALL(txcb1, onByteEventRegistered(getTxMatcher(stream, 3)));
EXPECT_CALL(txcb2, onByteEventRegistered(getTxMatcher(stream, 3)));
transport->registerTxCallback(stream, 3, &txcb1);
transport->registerTxCallback(stream, 3, &txcb2);
Mock::VerifyAndClearExpectations(&txcb1);
Mock::VerifyAndClearExpectations(&txcb2);
// Now, re-register the same callbacks, it should not go through.
auto ret = transport->registerTxCallback(stream, 3, &txcb1);
EXPECT_EQ(LocalErrorCode::INVALID_OPERATION, ret.error());
ret = transport->registerTxCallback(stream, 3, &txcb2);
EXPECT_EQ(LocalErrorCode::INVALID_OPERATION, ret.error());
// Deliver the first set of registrations.
EXPECT_CALL(txcb1, onByteEvent(getTxMatcher(stream, 3))).Times(1);
EXPECT_CALL(txcb2, onByteEvent(getTxMatcher(stream, 3))).Times(1);
evb->loopOnce();
Mock::VerifyAndClearExpectations(&txcb1);
Mock::VerifyAndClearExpectations(&txcb2);
}
TEST_F(
QuicTransportImplTest,
RegisterDeliveryCallbackMultipleRegistrationsAck) {
auto stream = transport->createBidirectionalStream().value();
StrictMock<MockByteEventCallback> txcb1;
StrictMock<MockByteEventCallback> txcb2;
// Set the current write offset to 7.
auto streamState = transport->transportConn->streamManager->getStream(stream);
streamState->currentWriteOffset = 7;
streamState->ackedIntervals.insert(0, 6);
// Have 2 different recipients register for a callback on the same stream ID
// and offset that is before the current write offset, they will both be
// scheduled for immediate delivery.
EXPECT_CALL(txcb1, onByteEventRegistered(getAckMatcher(stream, 3)));
EXPECT_CALL(txcb2, onByteEventRegistered(getAckMatcher(stream, 3)));
transport->registerByteEventCallback(ByteEvent::Type::ACK, stream, 3, &txcb1);
transport->registerByteEventCallback(ByteEvent::Type::ACK, stream, 3, &txcb2);
Mock::VerifyAndClearExpectations(&txcb1);
Mock::VerifyAndClearExpectations(&txcb2);
// Now, re-register the same callbacks, it should not go through.
auto ret = transport->registerByteEventCallback(
ByteEvent::Type::ACK, stream, 3, &txcb1);
EXPECT_EQ(LocalErrorCode::INVALID_OPERATION, ret.error());
ret = transport->registerByteEventCallback(
ByteEvent::Type::ACK, stream, 3, &txcb2);
EXPECT_EQ(LocalErrorCode::INVALID_OPERATION, ret.error());
// Deliver the first set of registrations.
EXPECT_CALL(txcb1, onByteEvent(getAckMatcher(stream, 3))).Times(1);
EXPECT_CALL(txcb2, onByteEvent(getAckMatcher(stream, 3))).Times(1);
evb->loopOnce();
Mock::VerifyAndClearExpectations(&txcb1);
Mock::VerifyAndClearExpectations(&txcb2);
}
TEST_P(
QuicTransportImplTestBase,
RegisterDeliveryCallbackMultipleRecipientsTx) {
auto stream = transport->createBidirectionalStream().value();
StrictMock<MockByteEventCallback> txcb1;
StrictMock<MockByteEventCallback> txcb2;
// Set the current write offset to 7.
auto streamState = transport->transportConn->streamManager->getStream(stream);
streamState->currentWriteOffset = 7;
streamState->ackedIntervals.insert(0, 6);
// Have 2 different recipients register for a callback on the same stream ID
// and offset.
EXPECT_CALL(txcb1, onByteEventRegistered(getTxMatcher(stream, 3)));
EXPECT_CALL(txcb2, onByteEventRegistered(getTxMatcher(stream, 3)));
transport->registerTxCallback(stream, 3, &txcb1);
transport->registerTxCallback(stream, 3, &txcb2);
Mock::VerifyAndClearExpectations(&txcb1);
Mock::VerifyAndClearExpectations(&txcb2);
// Now, *before* the runOnEvbAsync gets a chance to run, simulate the
// delivery of the callback for txcb1 (offset = 3) by deleting it from the
// outstanding callback queue for this stream ID. This is similar to what
// happens in processCallbacksAfterNetworkData.
bool deleted = transport->deleteRegisteredByteEvent(
stream, 3, &txcb1, ByteEvent::Type::TX);
CHECK_EQ(true, deleted);
// Only the callback for txcb2 should be outstanding now. Run the loop to
// confirm.
EXPECT_CALL(txcb1, onByteEvent(getTxMatcher(stream, 3))).Times(0);
EXPECT_CALL(txcb2, onByteEvent(getTxMatcher(stream, 3))).Times(1);
evb->loopOnce();
Mock::VerifyAndClearExpectations(&txcb1);
Mock::VerifyAndClearExpectations(&txcb2);
}
TEST_P(
QuicTransportImplTestBase,
RegisterDeliveryCallbackMultipleRecipientsAck) {
auto stream = transport->createBidirectionalStream().value();
StrictMock<MockByteEventCallback> txcb1;
StrictMock<MockByteEventCallback> txcb2;
// Set the current write offset to 7.
auto streamState = transport->transportConn->streamManager->getStream(stream);
streamState->currentWriteOffset = 7;
streamState->ackedIntervals.insert(0, 6);
// Have 2 different recipients register for a callback on the same stream ID
// and offset.
EXPECT_CALL(txcb1, onByteEventRegistered(getAckMatcher(stream, 3)));
EXPECT_CALL(txcb2, onByteEventRegistered(getAckMatcher(stream, 3)));
transport->registerByteEventCallback(ByteEvent::Type::ACK, stream, 3, &txcb1);
transport->registerByteEventCallback(ByteEvent::Type::ACK, stream, 3, &txcb2);
Mock::VerifyAndClearExpectations(&txcb1);
Mock::VerifyAndClearExpectations(&txcb2);
// Now, *before* the runOnEvbAsync gets a chance to run, simulate the
// delivery of the callback for txcb1 (offset = 3) by deleting it from the
// outstanding callback queue for this stream ID. This is similar to what
// happens in processCallbacksAfterNetworkData.
bool deleted = transport->deleteRegisteredByteEvent(
stream, 3, &txcb1, ByteEvent::Type::ACK);
CHECK_EQ(true, deleted);
// Only the callback for txcb2 should be outstanding now. Run the loop to
// confirm.
EXPECT_CALL(txcb1, onByteEvent(getAckMatcher(stream, 3))).Times(0);
EXPECT_CALL(txcb2, onByteEvent(getAckMatcher(stream, 3))).Times(1);
evb->loopOnce();
Mock::VerifyAndClearExpectations(&txcb1);
Mock::VerifyAndClearExpectations(&txcb2);
}
TEST_P(QuicTransportImplTestBase, RegisterDeliveryCallbackAsyncDeliveryTx) {
auto stream = transport->createBidirectionalStream().value();
StrictMock<MockByteEventCallback> txcb1;
StrictMock<MockByteEventCallback> txcb2;
// Set the current write offset to 7.
auto streamState = transport->transportConn->streamManager->getStream(stream);
streamState->currentWriteOffset = 7;
streamState->ackedIntervals.insert(0, 6);
// Register tx callbacks for the same stream at offsets 3 (before current
// write offset) and 10 (after current write offset).
// txcb1 (offset = 3) will be scheduled in the lambda (runOnEvbAsync)
// for immediate delivery. txcb2 (offset = 10) will be queued for delivery
// when the actual TX for this offset occurs in the future.
EXPECT_CALL(txcb1, onByteEventRegistered(getTxMatcher(stream, 3)));
EXPECT_CALL(txcb2, onByteEventRegistered(getTxMatcher(stream, 10)));
transport->registerTxCallback(stream, 3, &txcb1);
transport->registerTxCallback(stream, 10, &txcb2);
Mock::VerifyAndClearExpectations(&txcb1);
Mock::VerifyAndClearExpectations(&txcb2);
// Now, *before* the runOnEvbAsync gets a chance to run, simulate the
// delivery of the callback for txcb1 (offset = 3) by deleting it from the
// outstanding callback queue for this stream ID. This is similar to what
// happens in processCallbacksAfterNetworkData.
bool deleted = transport->deleteRegisteredByteEvent(
stream, 3, &txcb1, ByteEvent::Type::TX);
CHECK_EQ(true, deleted);
// Only txcb2 (offset = 10) should be outstanding now. Run the loop.
// txcb1 (offset = 3) should not be delivered now because it is already
// delivered. txcb2 (offset = 10) should not be delivered because the
// current write offset (7) is still less than the offset requested (10)
EXPECT_CALL(txcb1, onByteEvent(getTxMatcher(stream, 3))).Times(0);
EXPECT_CALL(txcb2, onByteEvent(getTxMatcher(stream, 10))).Times(0);
evb->loopOnce();
Mock::VerifyAndClearExpectations(&txcb1);
Mock::VerifyAndClearExpectations(&txcb2);
EXPECT_CALL(txcb2, onByteEventCanceled(getTxMatcher(stream, 10)));
transport->close(folly::none);
Mock::VerifyAndClearExpectations(&txcb2);
}
TEST_P(QuicTransportImplTestBase, RegisterDeliveryCallbackAsyncDeliveryAck) {
auto stream = transport->createBidirectionalStream().value();
StrictMock<MockByteEventCallback> txcb1;
StrictMock<MockByteEventCallback> txcb2;
// Set the current write offset to 7.
auto streamState = transport->transportConn->streamManager->getStream(stream);
streamState->currentWriteOffset = 7;
streamState->ackedIntervals.insert(0, 6);
// Register tx callbacks for the same stream at offsets 3 (before current
// write offset) and 10 (after current write offset).
// txcb1 (offset = 3) will be scheduled in the lambda (runOnEvbAsync)
// for immediate delivery. txcb2 (offset = 10) will be queued for delivery
// when the actual TX for this offset occurs in the future.
EXPECT_CALL(txcb1, onByteEventRegistered(getAckMatcher(stream, 3)));
EXPECT_CALL(txcb2, onByteEventRegistered(getAckMatcher(stream, 10)));
transport->registerByteEventCallback(ByteEvent::Type::ACK, stream, 3, &txcb1);
transport->registerByteEventCallback(
ByteEvent::Type::ACK, stream, 10, &txcb2);
Mock::VerifyAndClearExpectations(&txcb1);
Mock::VerifyAndClearExpectations(&txcb2);
// Now, *before* the runOnEvbAsync gets a chance to run, simulate the
// delivery of the callback for txcb1 (offset = 3) by deleting it from the
// outstanding callback queue for this stream ID. This is similar to what
// happens in processCallbacksAfterNetworkData.
bool deleted = transport->deleteRegisteredByteEvent(
stream, 3, &txcb1, ByteEvent::Type::ACK);
CHECK_EQ(true, deleted);
// Only txcb2 (offset = 10) should be outstanding now. Run the loop.
// txcb1 (offset = 3) should not be delivered now because it is already
// delivered. txcb2 (offset = 10) should not be delivered because the
// current write offset (7) is still less than the offset requested (10)
EXPECT_CALL(txcb1, onByteEvent(getAckMatcher(stream, 3))).Times(0);
EXPECT_CALL(txcb2, onByteEvent(getAckMatcher(stream, 10))).Times(0);
evb->loopOnce();
Mock::VerifyAndClearExpectations(&txcb1);
Mock::VerifyAndClearExpectations(&txcb2);
EXPECT_CALL(txcb2, onByteEventCanceled(getAckMatcher(stream, 10)));
transport->close(folly::none);
Mock::VerifyAndClearExpectations(&txcb2);
}
TEST_P(QuicTransportImplTestBase, CancelAllByteEventCallbacks) {
auto stream1 = transport->createBidirectionalStream().value();
auto stream2 = transport->createBidirectionalStream().value();
NiceMock<MockByteEventCallback> txcb1;
NiceMock<MockByteEventCallback> txcb2;
EXPECT_CALL(txcb1, onByteEventRegistered(getTxMatcher(stream1, 10)));
EXPECT_CALL(txcb2, onByteEventRegistered(getTxMatcher(stream2, 20)));
transport->registerTxCallback(stream1, 10, &txcb1);
transport->registerTxCallback(stream2, 20, &txcb2);
NiceMock<MockDeliveryCallback> dcb1;
NiceMock<MockDeliveryCallback> dcb2;
transport->registerDeliveryCallback(stream1, 10, &dcb1);
transport->registerDeliveryCallback(stream2, 20, &dcb2);
EXPECT_EQ(2, transport->getNumByteEventCallbacksForStream(stream1));
EXPECT_EQ(2, transport->getNumByteEventCallbacksForStream(stream2));
EXPECT_EQ(
1,
transport->getNumByteEventCallbacksForStream(
ByteEvent::Type::TX, stream1));
EXPECT_EQ(
1,
transport->getNumByteEventCallbacksForStream(
ByteEvent::Type::TX, stream2));
EXPECT_EQ(
1,
transport->getNumByteEventCallbacksForStream(
ByteEvent::Type::ACK, stream1));
EXPECT_EQ(
1,
transport->getNumByteEventCallbacksForStream(
ByteEvent::Type::ACK, stream2));
EXPECT_CALL(txcb1, onByteEventCanceled(getTxMatcher(stream1, 10)));
EXPECT_CALL(txcb2, onByteEventCanceled(getTxMatcher(stream2, 20)));
EXPECT_CALL(dcb1, onCanceled(_, _));
EXPECT_CALL(dcb2, onCanceled(_, _));
transport->cancelAllByteEventCallbacks();
Mock::VerifyAndClearExpectations(&txcb1);
Mock::VerifyAndClearExpectations(&txcb2);
Mock::VerifyAndClearExpectations(&dcb1);
Mock::VerifyAndClearExpectations(&dcb2);
EXPECT_EQ(0, transport->getNumByteEventCallbacksForStream(stream1));
EXPECT_EQ(0, transport->getNumByteEventCallbacksForStream(stream2));
EXPECT_EQ(
0,
transport->getNumByteEventCallbacksForStream(
ByteEvent::Type::TX, stream1));
EXPECT_EQ(
0,
transport->getNumByteEventCallbacksForStream(
ByteEvent::Type::TX, stream2));
EXPECT_EQ(
0,
transport->getNumByteEventCallbacksForStream(
ByteEvent::Type::ACK, stream1));
EXPECT_EQ(
0,
transport->getNumByteEventCallbacksForStream(
ByteEvent::Type::ACK, stream2));
EXPECT_CALL(txcb1, onByteEventCanceled(_)).Times(0);
EXPECT_CALL(txcb2, onByteEventCanceled(_)).Times(0);
EXPECT_CALL(dcb1, onCanceled(_, _)).Times(0);
EXPECT_CALL(dcb2, onCanceled(_, _)).Times(0);
transport->close(folly::none);
Mock::VerifyAndClearExpectations(&txcb1);
Mock::VerifyAndClearExpectations(&txcb2);
Mock::VerifyAndClearExpectations(&dcb1);
Mock::VerifyAndClearExpectations(&dcb2);
}
TEST_P(QuicTransportImplTestBase, CancelByteEventCallbacksForStream) {
auto stream1 = transport->createBidirectionalStream().value();
auto stream2 = transport->createBidirectionalStream().value();
StrictMock<MockByteEventCallback> txcb1;
StrictMock<MockByteEventCallback> txcb2;
NiceMock<MockDeliveryCallback> dcb1;
NiceMock<MockDeliveryCallback> dcb2;
EXPECT_CALL(txcb1, onByteEventRegistered(getTxMatcher(stream1, 10)));
EXPECT_CALL(txcb2, onByteEventRegistered(getTxMatcher(stream2, 20)));
transport->registerTxCallback(stream1, 10, &txcb1);
transport->registerTxCallback(stream2, 20, &txcb2);
transport->registerDeliveryCallback(stream1, 10, &dcb1);
transport->registerDeliveryCallback(stream2, 20, &dcb2);
EXPECT_EQ(2, transport->getNumByteEventCallbacksForStream(stream1));
EXPECT_EQ(2, transport->getNumByteEventCallbacksForStream(stream2));
EXPECT_EQ(
1,
transport->getNumByteEventCallbacksForStream(
ByteEvent::Type::TX, stream1));
EXPECT_EQ(
1,
transport->getNumByteEventCallbacksForStream(
ByteEvent::Type::TX, stream2));
EXPECT_EQ(
1,
transport->getNumByteEventCallbacksForStream(
ByteEvent::Type::ACK, stream1));
EXPECT_EQ(
1,
transport->getNumByteEventCallbacksForStream(
ByteEvent::Type::ACK, stream2));
EXPECT_CALL(txcb1, onByteEventCanceled(getTxMatcher(stream1, 10)));
EXPECT_CALL(txcb2, onByteEventCanceled(_)).Times(0);
EXPECT_CALL(dcb1, onCanceled(stream1, 10));
EXPECT_CALL(dcb2, onCanceled(_, _)).Times(0);
transport->cancelByteEventCallbacksForStream(stream1);
Mock::VerifyAndClearExpectations(&txcb1);
Mock::VerifyAndClearExpectations(&txcb2);
Mock::VerifyAndClearExpectations(&dcb1);
Mock::VerifyAndClearExpectations(&dcb2);
EXPECT_EQ(0, transport->getNumByteEventCallbacksForStream(stream1));
EXPECT_EQ(2, transport->getNumByteEventCallbacksForStream(stream2));
EXPECT_EQ(
0,
transport->getNumByteEventCallbacksForStream(
ByteEvent::Type::TX, stream1));
EXPECT_EQ(
1,
transport->getNumByteEventCallbacksForStream(
ByteEvent::Type::TX, stream2));
EXPECT_EQ(
0,
transport->getNumByteEventCallbacksForStream(
ByteEvent::Type::ACK, stream1));
EXPECT_EQ(
1,
transport->getNumByteEventCallbacksForStream(
ByteEvent::Type::ACK, stream2));
EXPECT_CALL(txcb1, onByteEventCanceled(_)).Times(0);
EXPECT_CALL(txcb2, onByteEventCanceled(getTxMatcher(stream2, 20)));
EXPECT_CALL(dcb1, onCanceled(stream1, _)).Times(0);
EXPECT_CALL(dcb2, onCanceled(_, 20));
transport->close(folly::none);
Mock::VerifyAndClearExpectations(&txcb1);
Mock::VerifyAndClearExpectations(&txcb2);
Mock::VerifyAndClearExpectations(&dcb1);
Mock::VerifyAndClearExpectations(&dcb2);
}
TEST_P(QuicTransportImplTestBase, CancelByteEventCallbacksForStreamWithOffset) {
auto stream1 = transport->createBidirectionalStream().value();
auto stream2 = transport->createBidirectionalStream().value();
StrictMock<MockByteEventCallback> txcb1;
StrictMock<MockByteEventCallback> txcb2;
NiceMock<MockDeliveryCallback> dcb1;
NiceMock<MockDeliveryCallback> dcb2;
EXPECT_EQ(0, transport->getNumByteEventCallbacksForStream(stream1));
EXPECT_EQ(0, transport->getNumByteEventCallbacksForStream(stream2));
EXPECT_EQ(
0,
transport->getNumByteEventCallbacksForStream(
ByteEvent::Type::TX, stream1));
EXPECT_EQ(
0,
transport->getNumByteEventCallbacksForStream(
ByteEvent::Type::TX, stream2));
EXPECT_EQ(
0,
transport->getNumByteEventCallbacksForStream(
ByteEvent::Type::ACK, stream1));
EXPECT_EQ(
0,
transport->getNumByteEventCallbacksForStream(
ByteEvent::Type::ACK, stream2));
EXPECT_CALL(txcb1, onByteEventRegistered(getTxMatcher(stream1, 10)));
EXPECT_CALL(txcb1, onByteEventRegistered(getTxMatcher(stream1, 15)));
EXPECT_CALL(txcb1, onByteEventRegistered(getTxMatcher(stream1, 20)));
EXPECT_CALL(txcb2, onByteEventRegistered(getTxMatcher(stream2, 10)));
EXPECT_CALL(txcb2, onByteEventRegistered(getTxMatcher(stream2, 15)));
EXPECT_CALL(txcb2, onByteEventRegistered(getTxMatcher(stream2, 20)));
transport->registerTxCallback(stream1, 10, &txcb1);
transport->registerTxCallback(stream1, 15, &txcb1);
transport->registerTxCallback(stream1, 20, &txcb1);
transport->registerTxCallback(stream2, 10, &txcb2);
transport->registerTxCallback(stream2, 15, &txcb2);
transport->registerTxCallback(stream2, 20, &txcb2);
EXPECT_EQ(3, transport->getNumByteEventCallbacksForStream(stream1));
EXPECT_EQ(3, transport->getNumByteEventCallbacksForStream(stream2));
EXPECT_EQ(
3,
transport->getNumByteEventCallbacksForStream(
ByteEvent::Type::TX, stream1));
EXPECT_EQ(
3,
transport->getNumByteEventCallbacksForStream(
ByteEvent::Type::TX, stream2));
EXPECT_EQ(
0,
transport->getNumByteEventCallbacksForStream(
ByteEvent::Type::ACK, stream1));
EXPECT_EQ(
0,
transport->getNumByteEventCallbacksForStream(
ByteEvent::Type::ACK, stream2));
transport->registerDeliveryCallback(stream1, 10, &dcb1);
transport->registerDeliveryCallback(stream1, 15, &dcb1);
transport->registerDeliveryCallback(stream1, 20, &dcb1);
transport->registerDeliveryCallback(stream2, 10, &dcb2);
transport->registerDeliveryCallback(stream2, 15, &dcb2);
transport->registerDeliveryCallback(stream2, 20, &dcb2);
EXPECT_EQ(6, transport->getNumByteEventCallbacksForStream(stream1));
EXPECT_EQ(6, transport->getNumByteEventCallbacksForStream(stream2));
EXPECT_EQ(
3,
transport->getNumByteEventCallbacksForStream(
ByteEvent::Type::TX, stream1));
EXPECT_EQ(
3,
transport->getNumByteEventCallbacksForStream(
ByteEvent::Type::TX, stream2));
EXPECT_EQ(
3,
transport->getNumByteEventCallbacksForStream(
ByteEvent::Type::ACK, stream1));
EXPECT_EQ(
3,
transport->getNumByteEventCallbacksForStream(
ByteEvent::Type::ACK, stream2));
EXPECT_CALL(txcb1, onByteEventCanceled(getTxMatcher(stream1, 10)));
EXPECT_CALL(dcb1, onCanceled(stream1, 10));
// cancels if offset is < (not <=) offset provided
transport->cancelByteEventCallbacksForStream(stream1, 15);
Mock::VerifyAndClearExpectations(&txcb1);
Mock::VerifyAndClearExpectations(&txcb2);
Mock::VerifyAndClearExpectations(&dcb1);
Mock::VerifyAndClearExpectations(&dcb2);
EXPECT_EQ(4, transport->getNumByteEventCallbacksForStream(stream1));
EXPECT_EQ(6, transport->getNumByteEventCallbacksForStream(stream2));
EXPECT_EQ(
2,
transport->getNumByteEventCallbacksForStream(
ByteEvent::Type::TX, stream1));
EXPECT_EQ(
3,
transport->getNumByteEventCallbacksForStream(
ByteEvent::Type::TX, stream2));
EXPECT_EQ(
2,
transport->getNumByteEventCallbacksForStream(
ByteEvent::Type::ACK, stream1));
EXPECT_EQ(
3,
transport->getNumByteEventCallbacksForStream(
ByteEvent::Type::ACK, stream2));
EXPECT_CALL(txcb1, onByteEventCanceled(getTxMatcher(stream1, 15)));
EXPECT_CALL(txcb1, onByteEventCanceled(getTxMatcher(stream1, 20)));
EXPECT_CALL(dcb1, onCanceled(stream1, 15));
EXPECT_CALL(dcb1, onCanceled(stream1, 20));
// cancels if offset is < (not <=) offset provided
transport->cancelByteEventCallbacksForStream(stream1, 21);
Mock::VerifyAndClearExpectations(&txcb1);
Mock::VerifyAndClearExpectations(&txcb2);
Mock::VerifyAndClearExpectations(&dcb1);
Mock::VerifyAndClearExpectations(&dcb2);
EXPECT_EQ(0, transport->getNumByteEventCallbacksForStream(stream1));
EXPECT_EQ(6, transport->getNumByteEventCallbacksForStream(stream2));
EXPECT_EQ(
0,
transport->getNumByteEventCallbacksForStream(
ByteEvent::Type::TX, stream1));
EXPECT_EQ(
3,
transport->getNumByteEventCallbacksForStream(
ByteEvent::Type::TX, stream2));
EXPECT_EQ(
0,
transport->getNumByteEventCallbacksForStream(
ByteEvent::Type::ACK, stream1));
EXPECT_EQ(
3,
transport->getNumByteEventCallbacksForStream(
ByteEvent::Type::ACK, stream2));
EXPECT_CALL(txcb2, onByteEventCanceled(getTxMatcher(stream2, 10)));
EXPECT_CALL(txcb2, onByteEventCanceled(getTxMatcher(stream2, 15)));
EXPECT_CALL(txcb2, onByteEventCanceled(getTxMatcher(stream2, 20)));
EXPECT_CALL(dcb2, onCanceled(stream2, 10));
EXPECT_CALL(dcb2, onCanceled(stream2, 15));
EXPECT_CALL(dcb2, onCanceled(stream2, 20));
transport->close(folly::none);
Mock::VerifyAndClearExpectations(&txcb1);
Mock::VerifyAndClearExpectations(&txcb2);
Mock::VerifyAndClearExpectations(&dcb1);
Mock::VerifyAndClearExpectations(&dcb2);
EXPECT_EQ(0, transport->getNumByteEventCallbacksForStream(stream1));
EXPECT_EQ(0, transport->getNumByteEventCallbacksForStream(stream2));
EXPECT_EQ(
0,
transport->getNumByteEventCallbacksForStream(
ByteEvent::Type::TX, stream1));
EXPECT_EQ(
0,
transport->getNumByteEventCallbacksForStream(
ByteEvent::Type::TX, stream2));
EXPECT_EQ(
0,
transport->getNumByteEventCallbacksForStream(
ByteEvent::Type::ACK, stream1));
EXPECT_EQ(
0,
transport->getNumByteEventCallbacksForStream(
ByteEvent::Type::ACK, stream2));
}
TEST_P(QuicTransportImplTestBase, CancelByteEventCallbacksTx) {
auto stream1 = transport->createBidirectionalStream().value();
auto stream2 = transport->createBidirectionalStream().value();
StrictMock<MockByteEventCallback> txcb1;
StrictMock<MockByteEventCallback> txcb2;
NiceMock<MockDeliveryCallback> dcb1;
NiceMock<MockDeliveryCallback> dcb2;
EXPECT_CALL(txcb1, onByteEventRegistered(getTxMatcher(stream1, 10)));
EXPECT_CALL(txcb1, onByteEventRegistered(getTxMatcher(stream1, 15)));
EXPECT_CALL(txcb2, onByteEventRegistered(getTxMatcher(stream2, 10)));
EXPECT_CALL(txcb2, onByteEventRegistered(getTxMatcher(stream2, 15)));
transport->registerTxCallback(stream1, 10, &txcb1);
transport->registerTxCallback(stream1, 15, &txcb1);
transport->registerTxCallback(stream2, 10, &txcb2);
transport->registerTxCallback(stream2, 15, &txcb2);
transport->registerDeliveryCallback(stream1, 10, &dcb1);
transport->registerDeliveryCallback(stream1, 15, &dcb1);
transport->registerDeliveryCallback(stream2, 10, &dcb2);
transport->registerDeliveryCallback(stream2, 15, &dcb2);
EXPECT_EQ(4, transport->getNumByteEventCallbacksForStream(stream1));
EXPECT_EQ(4, transport->getNumByteEventCallbacksForStream(stream2));
EXPECT_EQ(
2,
transport->getNumByteEventCallbacksForStream(
ByteEvent::Type::TX, stream1));
EXPECT_EQ(
2,
transport->getNumByteEventCallbacksForStream(
ByteEvent::Type::TX, stream2));
EXPECT_EQ(
2,
transport->getNumByteEventCallbacksForStream(
ByteEvent::Type::ACK, stream1));
EXPECT_EQ(
2,
transport->getNumByteEventCallbacksForStream(
ByteEvent::Type::ACK, stream2));
EXPECT_CALL(txcb1, onByteEventCanceled(getTxMatcher(stream1, 10)));
EXPECT_CALL(txcb1, onByteEventCanceled(getTxMatcher(stream1, 15)));
EXPECT_CALL(txcb2, onByteEventCanceled(getTxMatcher(stream2, 10)));
EXPECT_CALL(txcb2, onByteEventCanceled(getTxMatcher(stream2, 15)));
transport->cancelByteEventCallbacks(ByteEvent::Type::TX);
Mock::VerifyAndClearExpectations(&txcb1);
Mock::VerifyAndClearExpectations(&txcb2);
Mock::VerifyAndClearExpectations(&dcb1);
Mock::VerifyAndClearExpectations(&dcb2);
EXPECT_EQ(2, transport->getNumByteEventCallbacksForStream(stream1));
EXPECT_EQ(2, transport->getNumByteEventCallbacksForStream(stream2));
EXPECT_EQ(
0,
transport->getNumByteEventCallbacksForStream(
ByteEvent::Type::TX, stream1));
EXPECT_EQ(
0,
transport->getNumByteEventCallbacksForStream(
ByteEvent::Type::TX, stream2));
EXPECT_EQ(
2,
transport->getNumByteEventCallbacksForStream(
ByteEvent::Type::ACK, stream1));
EXPECT_EQ(
2,
transport->getNumByteEventCallbacksForStream(
ByteEvent::Type::ACK, stream2));
EXPECT_CALL(dcb1, onCanceled(stream1, 10));
EXPECT_CALL(dcb1, onCanceled(stream1, 15));
EXPECT_CALL(dcb2, onCanceled(stream2, 10));
EXPECT_CALL(dcb2, onCanceled(stream2, 15));
transport->close(folly::none);
Mock::VerifyAndClearExpectations(&txcb1);
Mock::VerifyAndClearExpectations(&txcb2);
Mock::VerifyAndClearExpectations(&dcb1);
Mock::VerifyAndClearExpectations(&dcb2);
}
TEST_P(QuicTransportImplTestBase, CancelByteEventCallbacksDelivery) {
auto stream1 = transport->createBidirectionalStream().value();
auto stream2 = transport->createBidirectionalStream().value();
StrictMock<MockByteEventCallback> txcb1;
StrictMock<MockByteEventCallback> txcb2;
NiceMock<MockDeliveryCallback> dcb1;
NiceMock<MockDeliveryCallback> dcb2;
EXPECT_CALL(txcb1, onByteEventRegistered(getTxMatcher(stream1, 10)));
EXPECT_CALL(txcb1, onByteEventRegistered(getTxMatcher(stream1, 15)));
EXPECT_CALL(txcb2, onByteEventRegistered(getTxMatcher(stream2, 10)));
EXPECT_CALL(txcb2, onByteEventRegistered(getTxMatcher(stream2, 15)));
transport->registerTxCallback(stream1, 10, &txcb1);
transport->registerTxCallback(stream1, 15, &txcb1);
transport->registerTxCallback(stream2, 10, &txcb2);
transport->registerTxCallback(stream2, 15, &txcb2);
transport->registerDeliveryCallback(stream1, 10, &dcb1);
transport->registerDeliveryCallback(stream1, 15, &dcb1);
transport->registerDeliveryCallback(stream2, 10, &dcb2);
transport->registerDeliveryCallback(stream2, 15, &dcb2);
EXPECT_EQ(4, transport->getNumByteEventCallbacksForStream(stream1));
EXPECT_EQ(4, transport->getNumByteEventCallbacksForStream(stream2));
EXPECT_EQ(
2,
transport->getNumByteEventCallbacksForStream(
ByteEvent::Type::TX, stream1));
EXPECT_EQ(
2,
transport->getNumByteEventCallbacksForStream(
ByteEvent::Type::TX, stream2));
EXPECT_EQ(
2,
transport->getNumByteEventCallbacksForStream(
ByteEvent::Type::ACK, stream1));
EXPECT_EQ(
2,
transport->getNumByteEventCallbacksForStream(
ByteEvent::Type::ACK, stream2));
EXPECT_CALL(dcb1, onCanceled(stream1, 10));
EXPECT_CALL(dcb1, onCanceled(stream1, 15));
EXPECT_CALL(dcb2, onCanceled(stream2, 10));
EXPECT_CALL(dcb2, onCanceled(stream2, 15));
transport->cancelByteEventCallbacks(ByteEvent::Type::ACK);
Mock::VerifyAndClearExpectations(&txcb1);
Mock::VerifyAndClearExpectations(&txcb2);
Mock::VerifyAndClearExpectations(&dcb1);
Mock::VerifyAndClearExpectations(&dcb2);
EXPECT_EQ(2, transport->getNumByteEventCallbacksForStream(stream1));
EXPECT_EQ(2, transport->getNumByteEventCallbacksForStream(stream2));
EXPECT_EQ(
2,
transport->getNumByteEventCallbacksForStream(
ByteEvent::Type::TX, stream1));
EXPECT_EQ(
2,
transport->getNumByteEventCallbacksForStream(
ByteEvent::Type::TX, stream2));
EXPECT_EQ(
0,
transport->getNumByteEventCallbacksForStream(
ByteEvent::Type::ACK, stream1));
EXPECT_EQ(
0,
transport->getNumByteEventCallbacksForStream(
ByteEvent::Type::ACK, stream2));
EXPECT_CALL(txcb1, onByteEventCanceled(getTxMatcher(stream1, 10)));
EXPECT_CALL(txcb1, onByteEventCanceled(getTxMatcher(stream1, 15)));
EXPECT_CALL(txcb2, onByteEventCanceled(getTxMatcher(stream2, 10)));
EXPECT_CALL(txcb2, onByteEventCanceled(getTxMatcher(stream2, 15)));
transport->close(folly::none);
Mock::VerifyAndClearExpectations(&txcb1);
Mock::VerifyAndClearExpectations(&txcb2);
Mock::VerifyAndClearExpectations(&dcb1);
Mock::VerifyAndClearExpectations(&dcb2);
}
TEST_P(
QuicTransportImplTestBase,
TestNotifyPendingConnWriteOnCloseWithoutError) {
NiceMock<MockWriteCallback> wcb;
EXPECT_CALL(
wcb,
onConnectionWriteError(IsError(GenericApplicationErrorCode::NO_ERROR)));
transport->notifyPendingWriteOnConnection(&wcb);
transport->close(folly::none);
evb->loopOnce();
}
TEST_P(QuicTransportImplTestClose, TestNotifyPendingConnWriteOnCloseWithError) {
NiceMock<MockWriteCallback> wcb;
transport->notifyPendingWriteOnConnection(&wcb);
if (GetParam()) {
EXPECT_CALL(
wcb,
onConnectionWriteError(
IsAppError(GenericApplicationErrorCode::UNKNOWN)));
transport->close(QuicError(
QuicErrorCode(GenericApplicationErrorCode::UNKNOWN),
std::string("Bye")));
} else {
transport->close(folly::none);
}
evb->loopOnce();
}
TEST_P(QuicTransportImplTestBase, TestNotifyPendingWriteWithActiveCallback) {
auto stream = transport->createBidirectionalStream().value();
NiceMock<MockWriteCallback> wcb;
EXPECT_CALL(wcb, onStreamWriteReady(stream, _));
auto ok1 = transport->notifyPendingWriteOnStream(stream, &wcb);
EXPECT_TRUE(ok1.hasValue());
auto ok2 = transport->notifyPendingWriteOnStream(stream, &wcb);
EXPECT_EQ(ok2.error(), quic::LocalErrorCode::CALLBACK_ALREADY_INSTALLED);
evb->loopOnce();
}
TEST_P(QuicTransportImplTestBase, TestNotifyPendingWriteOnCloseWithoutError) {
auto stream = transport->createBidirectionalStream().value();
NiceMock<MockWriteCallback> wcb;
EXPECT_CALL(
wcb,
onStreamWriteError(
stream, IsError(GenericApplicationErrorCode::NO_ERROR)));
transport->notifyPendingWriteOnStream(stream, &wcb);
transport->close(folly::none);
evb->loopOnce();
}
TEST_P(QuicTransportImplTestClose, TestNotifyPendingWriteOnCloseWithError) {
auto stream = transport->createBidirectionalStream().value();
NiceMock<MockWriteCallback> wcb;
transport->notifyPendingWriteOnStream(stream, &wcb);
if (GetParam()) {
EXPECT_CALL(
wcb,
onStreamWriteError(
stream, IsAppError(GenericApplicationErrorCode::UNKNOWN)));
transport->close(QuicError(
QuicErrorCode(GenericApplicationErrorCode::UNKNOWN),
std::string("Bye")));
} else {
transport->close(folly::none);
}
evb->loopOnce();
}
TEST_P(QuicTransportImplTestBase, TestTransportCloseWithMaxPacketNumber) {
transport->setServerConnectionId();
transport->transportConn->pendingEvents.closeTransport = false;
EXPECT_NO_THROW(transport->invokeWriteSocketData());
transport->transportConn->pendingEvents.closeTransport = true;
EXPECT_THROW(transport->invokeWriteSocketData(), QuicTransportException);
}
TEST_P(QuicTransportImplTestBase, TestGracefulCloseWithActiveStream) {
EXPECT_CALL(connCallback, onConnectionEnd()).Times(0);
EXPECT_CALL(connCallback, onConnectionError(_)).Times(0);
auto stream = transport->createBidirectionalStream().value();
NiceMock<MockWriteCallback> wcb;
NiceMock<MockWriteCallback> wcbConn;
NiceMock<MockReadCallback> rcb;
StrictMock<MockByteEventCallback> txCb;
StrictMock<MockDeliveryCallback> deliveryCb;
EXPECT_CALL(
wcb, onStreamWriteError(stream, IsError(LocalErrorCode::NO_ERROR)));
EXPECT_CALL(
wcbConn, onConnectionWriteError(IsError(LocalErrorCode::NO_ERROR)));
EXPECT_CALL(rcb, readError(stream, IsError(LocalErrorCode::NO_ERROR)));
EXPECT_CALL(deliveryCb, onCanceled(stream, _));
EXPECT_CALL(txCb, onByteEventCanceled(getTxMatcher(stream, 0)));
EXPECT_CALL(txCb, onByteEventCanceled(getTxMatcher(stream, 4)));
transport->notifyPendingWriteOnConnection(&wcbConn);
transport->notifyPendingWriteOnStream(stream, &wcb);
transport->setReadCallback(stream, &rcb);
EXPECT_CALL(*socketPtr, write(_, _))
.WillRepeatedly(SetErrnoAndReturn(EAGAIN, -1));
transport->writeChain(stream, IOBuf::copyBuffer("hello"), true, &deliveryCb);
EXPECT_CALL(txCb, onByteEventRegistered(getTxMatcher(stream, 0)));
EXPECT_CALL(txCb, onByteEventRegistered(getTxMatcher(stream, 4)));
EXPECT_FALSE(transport->registerTxCallback(stream, 0, &txCb).hasError());
EXPECT_FALSE(transport->registerTxCallback(stream, 4, &txCb).hasError());
transport->closeGracefully();
ASSERT_FALSE(transport->transportClosed);
EXPECT_FALSE(transport->createBidirectionalStream());
EXPECT_TRUE(transport->setReadCallback(stream, &rcb).hasError());
EXPECT_TRUE(transport->notifyPendingWriteOnStream(stream, &wcb).hasError());
EXPECT_TRUE(transport->notifyPendingWriteOnConnection(&wcbConn).hasError());
EXPECT_CALL(txCb, onByteEventRegistered(getTxMatcher(stream, 2))).Times(0);
EXPECT_TRUE(transport->registerTxCallback(stream, 2, &txCb).hasError());
EXPECT_TRUE(
transport->registerDeliveryCallback(stream, 2, &deliveryCb).hasError());
EXPECT_TRUE(
transport->resetStream(stream, GenericApplicationErrorCode::UNKNOWN)
.hasError());
transport->addDataToStream(
stream, StreamBuffer(IOBuf::copyBuffer("hello"), 0, false));
EXPECT_FALSE(transport->transportConn->streamManager->getStream(stream)
->readBuffer.empty());
// Close the last stream.
// TODO: replace this when we call conn callbacks.
// EXPECT_CALL(connCallback, onConnectionEnd());
transport->closeStream(stream);
ASSERT_TRUE(transport->transportClosed);
evb->loopOnce();
}
TEST_P(QuicTransportImplTestBase, TestGracefulCloseWithNoActiveStream) {
auto stream = transport->createBidirectionalStream().value();
NiceMock<MockWriteCallback> wcb;
NiceMock<MockWriteCallback> wcbConn;
NiceMock<MockReadCallback> rcb;
NiceMock<MockDeliveryCallback> deliveryCb;
NiceMock<MockByteEventCallback> txCb;
EXPECT_CALL(
rcb, readError(stream, IsError(GenericApplicationErrorCode::NO_ERROR)));
EXPECT_CALL(deliveryCb, onDeliveryAck(stream, _, _));
EXPECT_CALL(txCb, onByteEvent(getTxMatcher(stream, 0)));
EXPECT_CALL(txCb, onByteEvent(getTxMatcher(stream, 4)));
EXPECT_CALL(connCallback, onConnectionEnd()).Times(0);
EXPECT_CALL(connCallback, onConnectionError(_)).Times(0);
transport->setReadCallback(stream, &rcb);
EXPECT_CALL(*socketPtr, write(_, _))
.WillRepeatedly(SetErrnoAndReturn(EAGAIN, -1));
transport->writeChain(stream, IOBuf::copyBuffer("hello"), true, &deliveryCb);
EXPECT_CALL(txCb, onByteEventRegistered(getTxMatcher(stream, 0)));
EXPECT_CALL(txCb, onByteEventRegistered(getTxMatcher(stream, 4)));
EXPECT_FALSE(transport->registerTxCallback(stream, 0, &txCb).hasError());
EXPECT_FALSE(transport->registerTxCallback(stream, 4, &txCb).hasError());
// Close the last stream.
auto streamState = transport->transportConn->streamManager->getStream(stream);
// Fake that the data was TXed and delivered to keep all the state
// consistent.
streamState->currentWriteOffset = 7;
transport->transportConn->streamManager->addTx(stream);
transport->transportConn->streamManager->addDeliverable(stream);
transport->closeStream(stream);
transport->close(folly::none);
ASSERT_TRUE(transport->transportClosed);
EXPECT_FALSE(transport->createBidirectionalStream());
EXPECT_TRUE(transport->setReadCallback(stream, &rcb).hasError());
EXPECT_TRUE(transport->notifyPendingWriteOnStream(stream, &wcb).hasError());
EXPECT_TRUE(transport->notifyPendingWriteOnConnection(&wcbConn).hasError());
EXPECT_CALL(txCb, onByteEventRegistered(getTxMatcher(stream, 2))).Times(0);
EXPECT_TRUE(transport->registerTxCallback(stream, 2, &txCb).hasError());
EXPECT_TRUE(
transport->registerDeliveryCallback(stream, 2, &deliveryCb).hasError());
EXPECT_TRUE(
transport->resetStream(stream, GenericApplicationErrorCode::UNKNOWN)
.hasError());
}
TEST_P(QuicTransportImplTestBase, TestImmediateClose) {
auto stream = transport->createBidirectionalStream().value();
NiceMock<MockWriteCallback> wcb;
NiceMock<MockWriteCallback> wcbConn;
NiceMock<MockReadCallback> rcb;
NiceMock<MockPeekCallback> pcb;
NiceMock<MockDeliveryCallback> deliveryCb;
NiceMock<MockByteEventCallback> txCb;
EXPECT_CALL(
wcb,
onStreamWriteError(
stream, IsAppError(GenericApplicationErrorCode::UNKNOWN)));
EXPECT_CALL(
wcbConn,
onConnectionWriteError(IsAppError(GenericApplicationErrorCode::UNKNOWN)));
EXPECT_CALL(
rcb, readError(stream, IsAppError(GenericApplicationErrorCode::UNKNOWN)));
EXPECT_CALL(
pcb, peekError(stream, IsAppError(GenericApplicationErrorCode::UNKNOWN)));
EXPECT_CALL(deliveryCb, onCanceled(stream, _));
EXPECT_CALL(txCb, onByteEventCanceled(getTxMatcher(stream, 0)));
EXPECT_CALL(txCb, onByteEventCanceled(getTxMatcher(stream, 4)));
EXPECT_CALL(connCallback, onConnectionError(_)).Times(0);
transport->notifyPendingWriteOnConnection(&wcbConn);
transport->notifyPendingWriteOnStream(stream, &wcb);
transport->setReadCallback(stream, &rcb);
transport->setPeekCallback(stream, &pcb);
EXPECT_CALL(*socketPtr, write(_, _))
.WillRepeatedly(SetErrnoAndReturn(EAGAIN, -1));
transport->writeChain(stream, IOBuf::copyBuffer("hello"), true, &deliveryCb);
EXPECT_CALL(txCb, onByteEventRegistered(getTxMatcher(stream, 0)));
EXPECT_CALL(txCb, onByteEventRegistered(getTxMatcher(stream, 4)));
EXPECT_FALSE(transport->registerTxCallback(stream, 0, &txCb).hasError());
EXPECT_FALSE(transport->registerTxCallback(stream, 4, &txCb).hasError());
transport->close(QuicError(
QuicErrorCode(GenericApplicationErrorCode::UNKNOWN),
std::string("Error")));
ASSERT_TRUE(transport->transportClosed);
EXPECT_FALSE(transport->createBidirectionalStream());
EXPECT_TRUE(transport->setReadCallback(stream, &rcb).hasError());
EXPECT_TRUE(transport->notifyPendingWriteOnStream(stream, &wcb).hasError());
EXPECT_TRUE(transport->notifyPendingWriteOnConnection(&wcbConn).hasError());
EXPECT_CALL(txCb, onByteEventRegistered(getTxMatcher(stream, 2))).Times(0);
EXPECT_TRUE(transport->registerTxCallback(stream, 2, &txCb).hasError());
EXPECT_TRUE(
transport->registerDeliveryCallback(stream, 2, &deliveryCb).hasError());
EXPECT_TRUE(
transport->resetStream(stream, GenericApplicationErrorCode::UNKNOWN)
.hasError());
transport->addDataToStream(
stream, StreamBuffer(IOBuf::copyBuffer("hello"), 0, false));
EXPECT_EQ(
transport->transportConn->streamManager->getStream(stream), nullptr);
evb->loopOnce();
}
TEST_P(QuicTransportImplTestBase, ResetStreamUnsetWriteCallback) {
auto stream = transport->createBidirectionalStream().value();
NiceMock<MockWriteCallback> wcb;
EXPECT_CALL(wcb, onStreamWriteError(stream, _)).Times(0);
transport->notifyPendingWriteOnStream(stream, &wcb);
EXPECT_FALSE(
transport->resetStream(stream, GenericApplicationErrorCode::UNKNOWN)
.hasError());
evb->loopOnce();
}
TEST_P(QuicTransportImplTestBase, ResetAllNonControlStreams) {
auto stream1 = transport->createBidirectionalStream().value();
ASSERT_FALSE(transport->setControlStream(stream1));
NiceMock<MockWriteCallback> wcb1;
NiceMock<MockReadCallback> rcb1;
EXPECT_CALL(wcb1, onStreamWriteError(stream1, _)).Times(0);
EXPECT_CALL(rcb1, readError(stream1, _)).Times(0);
transport->notifyPendingWriteOnStream(stream1, &wcb1);
transport->setReadCallback(stream1, &rcb1);
auto stream2 = transport->createBidirectionalStream().value();
NiceMock<MockWriteCallback> wcb2;
NiceMock<MockReadCallback> rcb2;
EXPECT_CALL(wcb2, onStreamWriteError(stream2, _)).Times(1);
EXPECT_CALL(rcb2, readError(stream2, _)).Times(1);
transport->notifyPendingWriteOnStream(stream2, &wcb2);
transport->setReadCallback(stream2, &rcb2);
auto stream3 = transport->createUnidirectionalStream().value();
NiceMock<MockWriteCallback> wcb3;
transport->notifyPendingWriteOnStream(stream3, &wcb3);
EXPECT_CALL(wcb3, onStreamWriteError(stream3, _)).Times(1);
auto stream4 = transport->createBidirectionalStream().value();
NiceMock<MockWriteCallback> wcb4;
NiceMock<MockReadCallback> rcb4;
EXPECT_CALL(wcb4, onStreamWriteError(stream4, _))
.WillOnce(Invoke(
[&](auto, auto) { transport->setReadCallback(stream4, nullptr); }));
EXPECT_CALL(rcb4, readError(_, _)).Times(0);
transport->notifyPendingWriteOnStream(stream4, &wcb4);
transport->setReadCallback(stream4, &rcb4);
transport->resetNonControlStreams(
GenericApplicationErrorCode::UNKNOWN, "bye bye");
evb->loopOnce();
// Have to manually unset the read callbacks so they aren't use-after-freed.
transport->unsetAllReadCallbacks();
}
TEST_P(QuicTransportImplTestBase, DestroyWithoutClosing) {
EXPECT_CALL(connCallback, onConnectionError(_)).Times(0);
EXPECT_CALL(connCallback, onConnectionEnd()).Times(0);
transport.reset();
}
TEST_P(QuicTransportImplTestBase, UncleanShutdownEventBase) {
// if abruptly shutting down the eventbase we should avoid scheduling
// any new timer.
transport->setIdleTimeout();
evb.reset();
}
TEST_P(QuicTransportImplTestBase, GetLocalAddressBoundSocket) {
SocketAddress addr("127.0.0.1", 443);
EXPECT_CALL(*socketPtr, isBound()).WillOnce(Return(true));
EXPECT_CALL(*socketPtr, address()).WillRepeatedly(ReturnRef(addr));
SocketAddress localAddr = transport->getLocalAddress();
EXPECT_TRUE(localAddr == addr);
}
TEST_P(QuicTransportImplTestBase, GetLocalAddressUnboundSocket) {
EXPECT_CALL(*socketPtr, isBound()).WillOnce(Return(false));
SocketAddress localAddr = transport->getLocalAddress();
EXPECT_FALSE(localAddr.isInitialized());
}
TEST_P(QuicTransportImplTestBase, GetLocalAddressBadSocket) {
auto badTransport = std::make_shared<TestQuicTransport>(
evb->getBackingEventBase(), nullptr, &connSetupCallback, &connCallback);
badTransport->closeWithoutWrite();
SocketAddress localAddr = badTransport->getLocalAddress();
EXPECT_FALSE(localAddr.isInitialized());
}
TEST_P(QuicTransportImplTestBase, AsyncStreamFlowControlWrite) {
transport->transportConn->oneRttWriteCipher = test::createNoOpAead();
auto stream = transport->createBidirectionalStream().value();
auto streamState = transport->transportConn->streamManager->getStream(stream);
transport->setServerConnectionId();
transport->writeLooper()->stop();
streamState->flowControlState.advertisedMaxOffset = 0; // Easier to calculate
transport->setStreamFlowControlWindow(stream, 4000);
EXPECT_EQ(0, streamState->flowControlState.advertisedMaxOffset);
// Loop it:
EXPECT_TRUE(transport->writeLooper()->isRunning());
transport->writeLooper()->runLoopCallback();
EXPECT_EQ(4000, streamState->flowControlState.advertisedMaxOffset);
}
TEST_P(QuicTransportImplTestBase, ExceptionInWriteLooperDoesNotCrash) {
auto stream = transport->createBidirectionalStream().value();
transport->setReadCallback(stream, nullptr);
transport->writeChain(stream, IOBuf::copyBuffer("hello"), true, nullptr);
transport->addDataToStream(
stream, StreamBuffer(IOBuf::copyBuffer("hello"), 0, false));
EXPECT_CALL(*socketPtr, write(_, _)).WillOnce(SetErrnoAndReturn(EBADF, -1));
EXPECT_CALL(connSetupCallback, onConnectionSetupError(_))
.WillOnce(Invoke([&](auto) { transport.reset(); }));
transport->writeLooper()->runLoopCallback();
}
class QuicTransportImplTestUniBidi : public QuicTransportImplTest,
public testing::WithParamInterface<bool> {
};
quic::StreamId createStream(
std::shared_ptr<TestQuicTransport> transport,
bool unidirectional) {
if (unidirectional) {
return transport->createUnidirectionalStream().value();
} else {
return transport->createBidirectionalStream().value();
}
}
INSTANTIATE_TEST_SUITE_P(
QuicTransportImplTest,
QuicTransportImplTestUniBidi,
Values(true, false));
TEST_P(QuicTransportImplTestUniBidi, AppIdleTest) {
auto& conn = transport->getConnectionState();
auto mockCongestionController =
std::make_unique<NiceMock<MockCongestionController>>();
auto rawCongestionController = mockCongestionController.get();
conn.congestionController = std::move(mockCongestionController);
EXPECT_CALL(*rawCongestionController, setAppIdle(false, _)).Times(0);
auto stream = createStream(transport, GetParam());
EXPECT_CALL(*rawCongestionController, setAppIdle(true, _));
transport->closeStream(stream);
}
TEST_P(QuicTransportImplTestUniBidi, AppIdleTestControlStreams) {
auto& conn = transport->getConnectionState();
auto mockCongestionController =
std::make_unique<NiceMock<MockCongestionController>>();
auto rawCongestionController = mockCongestionController.get();
conn.congestionController = std::move(mockCongestionController);
EXPECT_CALL(*rawCongestionController, setAppIdle(false, _)).Times(0);
auto stream = createStream(transport, GetParam());
ASSERT_TRUE(stream);
auto ctrlStream1 = createStream(transport, GetParam());
ASSERT_TRUE(ctrlStream1);
transport->setControlStream(ctrlStream1);
auto ctrlStream2 = createStream(transport, GetParam());
ASSERT_TRUE(ctrlStream2);
transport->setControlStream(ctrlStream2);
EXPECT_CALL(*rawCongestionController, setAppIdle(true, _));
transport->closeStream(stream);
}
TEST_P(QuicTransportImplTestUniBidi, AppIdleTestOnlyControlStreams) {
auto& conn = transport->getConnectionState();
auto mockCongestionController =
std::make_unique<NiceMock<MockCongestionController>>();
auto rawCongestionController = mockCongestionController.get();
conn.congestionController = std::move(mockCongestionController);
auto ctrlStream1 = createStream(transport, GetParam());
EXPECT_CALL(*rawCongestionController, setAppIdle(true, _)).Times(1);
transport->setControlStream(ctrlStream1);
EXPECT_CALL(*rawCongestionController, setAppIdle(false, _)).Times(1);
auto ctrlStream2 = createStream(transport, GetParam());
EXPECT_CALL(*rawCongestionController, setAppIdle(true, _)).Times(1);
transport->setControlStream(ctrlStream2);
EXPECT_CALL(*rawCongestionController, setAppIdle(_, _)).Times(0);
transport->closeStream(ctrlStream1);
transport->closeStream(ctrlStream2);
}
TEST_P(QuicTransportImplTestBase, UnidirectionalInvalidReadFuncs) {
auto stream = transport->createUnidirectionalStream().value();
EXPECT_THROW(
transport->read(stream, 100).thenOrThrow([&](auto) {}),
folly::BadExpectedAccess<LocalErrorCode>);
EXPECT_THROW(
transport->setReadCallback(stream, nullptr).thenOrThrow([&](auto) {}),
folly::BadExpectedAccess<LocalErrorCode>);
EXPECT_THROW(
transport->pauseRead(stream).thenOrThrow([&](auto) {}),
folly::BadExpectedAccess<LocalErrorCode>);
EXPECT_THROW(
transport->resumeRead(stream).thenOrThrow([&](auto) {}),
folly::BadExpectedAccess<LocalErrorCode>);
EXPECT_THROW(
transport->stopSending(stream, GenericApplicationErrorCode::UNKNOWN)
.thenOrThrow([&](auto) {}),
folly::BadExpectedAccess<LocalErrorCode>);
}
TEST_P(QuicTransportImplTestBase, UnidirectionalInvalidWriteFuncs) {
auto readData = folly::IOBuf::copyBuffer("actual stream data");
StreamId stream = 0x6;
transport->addDataToStream(stream, StreamBuffer(readData->clone(), 0, true));
EXPECT_THROW(
transport->getStreamWriteOffset(stream).thenOrThrow([&](auto) {}),
folly::BadExpectedAccess<LocalErrorCode>);
EXPECT_THROW(
transport->getStreamWriteBufferedBytes(stream).thenOrThrow([&](auto) {}),
folly::BadExpectedAccess<LocalErrorCode>);
EXPECT_THROW(
transport->notifyPendingWriteOnStream(stream, nullptr)
.thenOrThrow([&](auto) {}),
folly::BadExpectedAccess<LocalErrorCode>);
EXPECT_THROW(
transport->writeChain(stream, folly::IOBuf::copyBuffer("Hey"), false)
.thenOrThrow([&](auto) {}),
folly::BadExpectedAccess<LocalErrorCode>);
EXPECT_THROW(
transport->registerDeliveryCallback(stream, 0, nullptr)
.thenOrThrow([&](auto) {}),
folly::BadExpectedAccess<LocalErrorCode>);
EXPECT_THROW(
transport->registerTxCallback(stream, 0, nullptr).thenOrThrow([&](auto) {
}),
folly::BadExpectedAccess<LocalErrorCode>);
EXPECT_THROW(
transport
->registerByteEventCallback(ByteEvent::Type::ACK, stream, 0, nullptr)
.thenOrThrow([&](auto) {}),
folly::BadExpectedAccess<LocalErrorCode>);
EXPECT_THROW(
transport
->registerByteEventCallback(ByteEvent::Type::TX, stream, 0, nullptr)
.thenOrThrow([&](auto) {}),
folly::BadExpectedAccess<LocalErrorCode>);
EXPECT_THROW(
transport->resetStream(stream, GenericApplicationErrorCode::UNKNOWN)
.thenOrThrow([&](auto) {}),
folly::BadExpectedAccess<LocalErrorCode>);
}
TEST_P(QuicTransportImplTestUniBidi, IsServerStream) {
auto stream = createStream(transport, GetParam());
EXPECT_TRUE(transport->isServerStream(stream));
}
TEST_P(QuicTransportImplTestUniBidi, IsClientStream) {
auto stream = createStream(transport, GetParam());
EXPECT_FALSE(transport->isClientStream(stream));
}
TEST_P(QuicTransportImplTestBase, IsUnidirectionalStream) {
auto stream = transport->createUnidirectionalStream().value();
EXPECT_TRUE(transport->isUnidirectionalStream(stream));
}
TEST_P(QuicTransportImplTestBase, IsBidirectionalStream) {
auto stream = transport->createBidirectionalStream().value();
EXPECT_TRUE(transport->isBidirectionalStream(stream));
}
TEST_P(QuicTransportImplTestBase, GetStreamDirectionalityUnidirectional) {
auto stream = transport->createUnidirectionalStream().value();
EXPECT_EQ(
StreamDirectionality::Unidirectional,
transport->getStreamDirectionality(stream));
}
TEST_P(QuicTransportImplTestBase, GetStreamDirectionalityBidirectional) {
auto stream = transport->createBidirectionalStream().value();
EXPECT_EQ(
StreamDirectionality::Bidirectional,
transport->getStreamDirectionality(stream));
}
TEST_P(QuicTransportImplTestBase, PeekCallbackDataAvailable) {
auto stream1 = transport->createBidirectionalStream().value();
auto stream2 = transport->createBidirectionalStream().value();
NiceMock<MockPeekCallback> peekCb1;
NiceMock<MockPeekCallback> peekCb2;
transport->setPeekCallback(stream1, &peekCb1);
transport->setPeekCallback(stream2, &peekCb2);
transport->addDataToStream(
stream1, StreamBuffer(folly::IOBuf::copyBuffer("actual stream data"), 0));
transport->addDataToStream(
stream2,
StreamBuffer(folly::IOBuf::copyBuffer("actual stream data"), 10));
EXPECT_CALL(peekCb1, onDataAvailable(stream1, _));
transport->driveReadCallbacks();
transport->addDataToStream(
stream2, StreamBuffer(folly::IOBuf::copyBuffer("actual stream data"), 0));
EXPECT_CALL(peekCb2, onDataAvailable(stream2, _));
transport->driveReadCallbacks();
transport->addDataToStream(
stream1, StreamBuffer(folly::IOBuf::copyBuffer("actual stream data"), 0));
transport->addDataToStream(
stream2, StreamBuffer(folly::IOBuf::copyBuffer("actual stream data"), 0));
EXPECT_CALL(peekCb1, onDataAvailable(stream1, _));
EXPECT_CALL(peekCb2, onDataAvailable(stream2, _));
transport->driveReadCallbacks();
transport->setPeekCallback(stream1, nullptr);
transport->setPeekCallback(stream2, nullptr);
transport->driveReadCallbacks();
transport.reset();
}
TEST_P(QuicTransportImplTestBase, PeekError) {
auto stream1 = transport->createBidirectionalStream().value();
NiceMock<MockPeekCallback> peekCb1;
transport->setPeekCallback(stream1, &peekCb1);
transport->addDataToStream(
stream1, StreamBuffer(folly::IOBuf::copyBuffer("actual stream data"), 0));
transport->addStreamReadError(stream1, LocalErrorCode::STREAM_CLOSED);
EXPECT_CALL(
peekCb1, peekError(stream1, IsError(LocalErrorCode::STREAM_CLOSED)));
transport->driveReadCallbacks();
EXPECT_CALL(peekCb1, peekError(stream1, _));
transport.reset();
}
TEST_P(QuicTransportImplTestBase, PeekCallbackUnsetAll) {
auto stream1 = transport->createBidirectionalStream().value();
auto stream2 = transport->createBidirectionalStream().value();
NiceMock<MockPeekCallback> peekCb1;
NiceMock<MockPeekCallback> peekCb2;
// Set the peek callbacks and add data to the streams, and see that the
// callbacks do indeed fire
transport->setPeekCallback(stream1, &peekCb1);
transport->setPeekCallback(stream2, &peekCb2);
transport->addDataToStream(
stream1, StreamBuffer(folly::IOBuf::copyBuffer("actual stream data"), 0));
transport->addDataToStream(
stream2, StreamBuffer(folly::IOBuf::copyBuffer("actual stream data"), 0));
EXPECT_CALL(peekCb1, onDataAvailable(stream1, _));
EXPECT_CALL(peekCb2, onDataAvailable(stream2, _));
transport->driveReadCallbacks();
// unset all of the peek callbacks and see that the callbacks don't fire
// after data is added to the streams
transport->unsetAllPeekCallbacks();
transport->addDataToStream(
stream1, StreamBuffer(folly::IOBuf::copyBuffer("actual stream data"), 0));
transport->addDataToStream(
stream2, StreamBuffer(folly::IOBuf::copyBuffer("actual stream data"), 0));
EXPECT_CALL(peekCb1, onDataAvailable(stream1, _)).Times(0);
EXPECT_CALL(peekCb2, onDataAvailable(stream2, _)).Times(0);
transport->driveReadCallbacks();
}
TEST_P(QuicTransportImplTestBase, PeekCallbackChangePeekCallback) {
InSequence enforceOrder;
auto stream1 = transport->createBidirectionalStream().value();
NiceMock<MockPeekCallback> peekCb1;
NiceMock<MockPeekCallback> peekCb2;
transport->setPeekCallback(stream1, &peekCb1);
transport->addDataToStream(
stream1, StreamBuffer(folly::IOBuf::copyBuffer("actual stream data"), 0));
EXPECT_CALL(peekCb1, onDataAvailable(stream1, _));
transport->driveReadCallbacks();
transport->setPeekCallback(stream1, &peekCb2);
transport->addDataToStream(
stream1, StreamBuffer(folly::IOBuf::copyBuffer("actual stream data"), 0));
EXPECT_CALL(peekCb2, onDataAvailable(stream1, _));
transport->driveReadCallbacks();
transport.reset();
}
TEST_P(QuicTransportImplTestBase, PeekCallbackPauseResume) {
InSequence enforceOrder;
auto stream1 = transport->createBidirectionalStream().value();
NiceMock<MockPeekCallback> peekCb1;
transport->setPeekCallback(stream1, &peekCb1);
transport->addDataToStream(
stream1, StreamBuffer(folly::IOBuf::copyBuffer("actual stream data"), 0));
auto res = transport->pausePeek(stream1);
EXPECT_TRUE(res);
EXPECT_CALL(peekCb1, onDataAvailable(stream1, _)).Times(0);
transport->driveReadCallbacks();
res = transport->resumePeek(stream1);
EXPECT_TRUE(res);
EXPECT_CALL(peekCb1, onDataAvailable(stream1, _));
transport->driveReadCallbacks();
auto stream2 = transport->createBidirectionalStream().value();
res = transport->pausePeek(stream2);
EXPECT_FALSE(res);
EXPECT_EQ(LocalErrorCode::APP_ERROR, res.error());
transport.reset();
}
TEST_P(QuicTransportImplTestBase, PeekCallbackNoCallbackSet) {
auto stream1 = transport->createBidirectionalStream().value();
transport->addDataToStream(
stream1,
StreamBuffer(folly::IOBuf::copyBuffer("actual stream data"), 10));
transport->driveReadCallbacks();
transport->addDataToStream(
stream1, StreamBuffer(folly::IOBuf::copyBuffer("actual stream data"), 0));
transport->driveReadCallbacks();
transport.reset();
}
TEST_P(QuicTransportImplTestBase, PeekCallbackInvalidStream) {
NiceMock<MockPeekCallback> peekCb1;
StreamId invalidStream = 10;
EXPECT_TRUE(transport->setPeekCallback(invalidStream, &peekCb1).hasError());
transport.reset();
}
TEST_P(QuicTransportImplTestBase, PeekData) {
InSequence enforceOrder;
auto stream1 = transport->createBidirectionalStream().value();
NiceMock<MockPeekCallback> peekCb1;
auto peekData = folly::IOBuf::copyBuffer("actual stream data");
transport->setPeekCallback(stream1, &peekCb1);
EXPECT_CALL(peekCb1, onDataAvailable(stream1, _));
transport->addDataToStream(stream1, StreamBuffer(peekData->clone(), 0));
transport->driveReadCallbacks();
bool cbCalled = false;
auto peekCallback = [&](StreamId id,
const folly::Range<PeekIterator>& range) {
cbCalled = true;
EXPECT_EQ(id, stream1);
EXPECT_EQ(range.size(), 1);
auto bufClone = range[0].data.front()->clone();
EXPECT_EQ("actual stream data", bufClone->moveToFbString().toStdString());
};
transport->peek(stream1, peekCallback);
EXPECT_TRUE(cbCalled);
transport.reset();
}
TEST_P(QuicTransportImplTestBase, PeekDataWithError) {
InSequence enforceOrder;
auto streamId = transport->createBidirectionalStream().value();
auto peekData = folly::IOBuf::copyBuffer("actual stream data");
transport->addDataToStream(streamId, StreamBuffer(peekData->clone(), 0));
bool cbCalled = false;
auto peekCallback = [&](StreamId, const folly::Range<PeekIterator>&) {
cbCalled = true;
};
// Same local error code should be returned.
transport->addStreamReadError(streamId, LocalErrorCode::NO_ERROR);
auto result = transport->peek(streamId, peekCallback);
EXPECT_FALSE(cbCalled);
EXPECT_TRUE(result.hasError());
EXPECT_EQ(LocalErrorCode::NO_ERROR, result.error());
// LocalErrorCode::INTERNAL_ERROR should be returned.
transport->addStreamReadError(
streamId, TransportErrorCode::FLOW_CONTROL_ERROR);
result = transport->peek(streamId, peekCallback);
EXPECT_FALSE(cbCalled);
EXPECT_TRUE(result.hasError());
EXPECT_EQ(LocalErrorCode::INTERNAL_ERROR, result.error());
transport.reset();
}
TEST_P(QuicTransportImplTestBase, ConsumeDataWithError) {
InSequence enforceOrder;
auto streamId = transport->createBidirectionalStream().value();
auto peekData = folly::IOBuf::copyBuffer("actual stream data");
transport->addDataToStream(streamId, StreamBuffer(peekData->clone(), 0));
// Same local error code should be returned.
transport->addStreamReadError(streamId, LocalErrorCode::NO_ERROR);
auto result = transport->consume(streamId, 1);
EXPECT_TRUE(result.hasError());
EXPECT_EQ(LocalErrorCode::NO_ERROR, result.error());
// LocalErrorCode::INTERNAL_ERROR should be returned.
transport->addStreamReadError(
streamId, TransportErrorCode::FLOW_CONTROL_ERROR);
result = transport->consume(streamId, 1);
EXPECT_TRUE(result.hasError());
EXPECT_EQ(LocalErrorCode::INTERNAL_ERROR, result.error());
transport.reset();
}
TEST_P(QuicTransportImplTestBase, PeekConsumeReadTest) {
InSequence enforceOrder;
auto stream1 = transport->createBidirectionalStream().value();
auto readData = folly::IOBuf::copyBuffer("actual stream data");
NiceMock<MockPeekCallback> peekCb;
NiceMock<MockReadCallback> readCb;
transport->setPeekCallback(stream1, &peekCb);
transport->setReadCallback(stream1, &readCb);
transport->addDataToStream(
stream1, StreamBuffer(folly::IOBuf::copyBuffer("actual stream data"), 0));
// Both peek and read should be called.
EXPECT_CALL(readCb, readAvailable(stream1));
EXPECT_CALL(peekCb, onDataAvailable(stream1, _));
transport->driveReadCallbacks();
// Only read should be called
EXPECT_CALL(readCb, readAvailable(stream1));
transport->driveReadCallbacks();
// Consume 5 bytes.
transport->consume(stream1, 5);
// Both peek and read should be called.
// Read - because it is called every time
// Peek - because the peekable range has changed
EXPECT_CALL(readCb, readAvailable(stream1));
EXPECT_CALL(peekCb, onDataAvailable(stream1, _));
transport->driveReadCallbacks();
// Read 10 bytes.
transport->read(stream1, 10).thenOrThrow([&](std::pair<Buf, bool> data) {
EXPECT_EQ("l stream d", data.first->moveToFbString().toStdString());
});
// Both peek and read should be called.
// Read - because it is called every time
// Peek - because the peekable range has changed
EXPECT_CALL(readCb, readAvailable(stream1));
EXPECT_CALL(peekCb, onDataAvailable(stream1, _));
transport->driveReadCallbacks();
// Only read should be called.
EXPECT_CALL(readCb, readAvailable(stream1));
transport->driveReadCallbacks();
// Consume the rest of the data.
// Only 3 bytes left, try consuming 42.
transport->consume(stream1, 42);
// Neither read nor peek should be called.
EXPECT_CALL(readCb, readAvailable(stream1)).Times(0);
EXPECT_CALL(peekCb, onDataAvailable(stream1, _)).Times(0);
transport->driveReadCallbacks();
// Add more data, this time with a gap.
auto buf1 = IOBuf::copyBuffer("I just met you and this is crazy.");
auto buf2 = IOBuf::copyBuffer(" Here is my number, so call");
auto buf3 = IOBuf::copyBuffer(" me maybe.");
transport->addDataToStream(stream1, StreamBuffer(buf1->clone(), 0));
transport->addDataToStream(
stream1,
StreamBuffer(
buf3->clone(),
buf1->computeChainDataLength() + buf2->computeChainDataLength()));
// Both peek and read should be called.
EXPECT_CALL(readCb, readAvailable(stream1));
EXPECT_CALL(peekCb, onDataAvailable(stream1, _));
transport->driveReadCallbacks();
// Consume left part.
transport->consume(stream1, buf1->computeChainDataLength());
// Only peek should be called.
EXPECT_CALL(peekCb, onDataAvailable(stream1, _));
transport->driveReadCallbacks();
// Fill in the gap.
transport->addDataToStream(
stream1, StreamBuffer(buf2->clone(), buf1->computeChainDataLength()));
// Both peek and read should be called.
EXPECT_CALL(readCb, readAvailable(stream1));
EXPECT_CALL(peekCb, onDataAvailable(stream1, _));
transport->driveReadCallbacks();
// Read the rest of the buffer.
transport->read(stream1, 0).thenOrThrow([&](std::pair<Buf, bool> data) {
EXPECT_EQ(
" Here is my number, so call me maybe.",
data.first->moveToFbString().toStdString());
});
// Neither read nor peek should be called.
EXPECT_CALL(readCb, readAvailable(stream1)).Times(0);
EXPECT_CALL(peekCb, onDataAvailable(stream1, _)).Times(0);
transport->driveReadCallbacks();
transport.reset();
}
TEST_P(QuicTransportImplTestBase, UpdatePeekableListNoDataTest) {
auto streamId = transport->createBidirectionalStream().value();
const auto& conn = transport->transportConn;
auto stream = transport->getStream(streamId);
// Insert streamId into the list.
conn->streamManager->peekableStreams().insert(streamId);
// After the call the streamId should be removed
// from the list since there is no peekable data in the stream.
conn->streamManager->updatePeekableStreams(*stream);
EXPECT_EQ(0, conn->streamManager->peekableStreams().count(streamId));
}
TEST_P(QuicTransportImplTestBase, UpdatePeekableListWithDataTest) {
auto streamId = transport->createBidirectionalStream().value();
const auto& conn = transport->transportConn;
auto stream = transport->getStream(streamId);
// Add some data to the stream.
transport->addDataToStream(
streamId,
StreamBuffer(folly::IOBuf::copyBuffer("actual stream data"), 0));
// streamId is in the list after the above call.
EXPECT_EQ(1, conn->streamManager->peekableStreams().count(streamId));
// After the call the streamId shall remain
// in the list since there is data in the stream.
conn->streamManager->updatePeekableStreams(*stream);
EXPECT_EQ(1, conn->streamManager->peekableStreams().count(streamId));
}
TEST_P(QuicTransportImplTestBase, UpdatePeekableListEmptyListTest) {
auto streamId = transport->createBidirectionalStream().value();
const auto& conn = transport->transportConn;
auto stream = transport->getStream(streamId);
// Add some data to the stream.
transport->addDataToStream(
streamId,
StreamBuffer(folly::IOBuf::copyBuffer("actual stream data"), 0));
// Erase streamId from the list.
conn->streamManager->peekableStreams().erase(streamId);
EXPECT_EQ(0, conn->streamManager->peekableStreams().count(streamId));
// After the call the streamId should be added to the list
// because there is data in the stream and the streamId is
// not in the list.
conn->streamManager->updatePeekableStreams(*stream);
EXPECT_EQ(1, conn->streamManager->peekableStreams().count(streamId));
}
TEST_P(QuicTransportImplTestBase, UpdatePeekableListWithStreamErrorTest) {
auto streamId = transport->createBidirectionalStream().value();
const auto& conn = transport->transportConn;
// Add some data to the stream.
transport->addDataToStream(
streamId,
StreamBuffer(folly::IOBuf::copyBuffer("actual stream data"), 0));
// streamId is in the list.
EXPECT_EQ(1, conn->streamManager->peekableStreams().count(streamId));
transport->addStreamReadError(streamId, LocalErrorCode::NO_ERROR);
// peekableStreams is updated to allow stream with streamReadError.
// So the streamId shall be in the list
EXPECT_EQ(1, conn->streamManager->peekableStreams().count(streamId));
}
TEST_P(QuicTransportImplTestBase, SuccessfulPing) {
auto conn = transport->transportConn;
std::chrono::milliseconds interval(10);
TestPingCallback pingCallback;
transport->setPingCallback(&pingCallback);
transport->invokeSendPing(interval);
EXPECT_EQ(transport->isPingTimeoutScheduled(), true);
EXPECT_EQ(conn->pendingEvents.cancelPingTimeout, false);
conn->pendingEvents.cancelPingTimeout = true;
transport->invokeHandlePingCallbacks();
evb->loopOnce();
EXPECT_EQ(transport->isPingTimeoutScheduled(), false);
EXPECT_EQ(conn->pendingEvents.cancelPingTimeout, false);
}
TEST_P(QuicTransportImplTestBase, FailedPing) {
auto conn = transport->transportConn;
std::chrono::milliseconds interval(10);
TestPingCallback pingCallback;
transport->setPingCallback(&pingCallback);
transport->invokeSendPing(interval);
EXPECT_EQ(transport->isPingTimeoutScheduled(), true);
EXPECT_EQ(conn->pendingEvents.cancelPingTimeout, false);
conn->pendingEvents.cancelPingTimeout = true;
transport->invokeCancelPingTimeout();
transport->invokeHandlePingCallbacks();
EXPECT_EQ(conn->pendingEvents.cancelPingTimeout, false);
}
TEST_P(QuicTransportImplTestBase, HandleKnobCallbacks) {
auto conn = transport->transportConn;
LegacyObserver::EventSet eventSet;
eventSet.enable(SocketObserverInterface::Events::knobFrameEvents);
auto obs1 = std::make_unique<NiceMock<MockLegacyObserver>>();
auto obs2 = std::make_unique<NiceMock<MockLegacyObserver>>(eventSet);
auto obs3 = std::make_unique<NiceMock<MockLegacyObserver>>(eventSet);
transport->addObserver(obs1.get());
transport->addObserver(obs2.get());
transport->addObserver(obs3.get());
// set test knob frame
uint64_t knobSpace = 0xfaceb00c;
uint64_t knobId = 42;
folly::StringPiece data = "test knob data";
Buf buf(folly::IOBuf::create(data.size()));
memcpy(buf->writableData(), data.data(), data.size());
buf->append(data.size());
conn->pendingEvents.knobs.emplace_back(
KnobFrame(knobSpace, knobId, std::move(buf)));
EXPECT_CALL(connCallback, onKnobMock(knobSpace, knobId, _))
.WillOnce(Invoke([](Unused, Unused, Unused) { /* do nothing */ }));
EXPECT_CALL(*obs1, knobFrameReceived(transport.get(), _)).Times(0);
EXPECT_CALL(*obs2, knobFrameReceived(transport.get(), _)).Times(1);
EXPECT_CALL(*obs3, knobFrameReceived(transport.get(), _)).Times(1);
transport->invokeHandleKnobCallbacks();
evb->loopOnce();
EXPECT_EQ(conn->pendingEvents.knobs.size(), 0);
// detach the observer from the socket
EXPECT_TRUE(transport->removeObserver(obs1.get()));
EXPECT_TRUE(transport->removeObserver(obs2.get()));
EXPECT_TRUE(transport->removeObserver(obs3.get()));
}
TEST_P(QuicTransportImplTestBase, StreamWriteCallbackUnregister) {
auto stream = transport->createBidirectionalStream().value();
// Unset before set
EXPECT_FALSE(transport->unregisterStreamWriteCallback(stream));
// Set
auto wcb = std::make_unique<MockWriteCallback>();
EXPECT_CALL(*wcb, onStreamWriteReady(stream, _)).Times(1);
auto result = transport->notifyPendingWriteOnStream(stream, wcb.get());
EXPECT_TRUE(result);
evb->loopOnce();
// Set then unset
EXPECT_CALL(*wcb, onStreamWriteReady(stream, _)).Times(0);
result = transport->notifyPendingWriteOnStream(stream, wcb.get());
EXPECT_TRUE(result);
EXPECT_TRUE(transport->unregisterStreamWriteCallback(stream));
evb->loopOnce();
// Set, close, unset
result = transport->notifyPendingWriteOnStream(stream, wcb.get());
EXPECT_TRUE(result);
MockReadCallback rcb;
transport->setReadCallback(stream, &rcb);
// ReadCallback kills WriteCallback
EXPECT_CALL(rcb, readError(stream, _))
.WillOnce(Invoke([&](StreamId stream, auto) {
EXPECT_TRUE(transport->unregisterStreamWriteCallback(stream));
wcb.reset();
}));
transport->close(folly::none);
evb->loopOnce();
}
TEST_P(QuicTransportImplTestBase, ObserverRemove) {
auto cb = std::make_unique<StrictMock<MockLegacyObserver>>();
EXPECT_CALL(*cb, observerAttach(transport.get()));
transport->addObserver(cb.get());
EXPECT_THAT(transport->getObservers(), UnorderedElementsAre(cb.get()));
EXPECT_CALL(*cb, observerDetach(transport.get()));
EXPECT_TRUE(transport->removeObserver(cb.get()));
Mock::VerifyAndClearExpectations(cb.get());
EXPECT_THAT(transport->getObservers(), IsEmpty());
}
TEST_P(QuicTransportImplTestBase, ObserverDestroy) {
auto cb = std::make_unique<StrictMock<MockLegacyObserver>>();
EXPECT_CALL(*cb, observerAttach(transport.get()));
transport->addObserver(cb.get());
EXPECT_THAT(transport->getObservers(), UnorderedElementsAre(cb.get()));
InSequence s;
EXPECT_CALL(*cb, closeStarted(transport.get(), _));
EXPECT_CALL(*cb, closing(transport.get(), _));
EXPECT_CALL(*cb, destroy(transport.get()));
transport = nullptr;
Mock::VerifyAndClearExpectations(cb.get());
}
TEST_P(QuicTransportImplTestBase, ObserverRemoveMissing) {
auto cb = std::make_unique<StrictMock<MockLegacyObserver>>();
EXPECT_FALSE(transport->removeObserver(cb.get()));
EXPECT_THAT(transport->getObservers(), IsEmpty());
}
TEST_P(QuicTransportImplTestBase, ObserverSharedPtrRemove) {
auto cb = std::make_shared<StrictMock<MockLegacyObserver>>();
EXPECT_CALL(*cb, observerAttach(transport.get()));
transport->addObserver(cb);
EXPECT_THAT(transport->getObservers(), UnorderedElementsAre(cb.get()));
EXPECT_CALL(*cb, observerDetach(transport.get()));
EXPECT_TRUE(transport->removeObserver(cb));
Mock::VerifyAndClearExpectations(cb.get());
EXPECT_THAT(transport->getObservers(), IsEmpty());
}
TEST_P(QuicTransportImplTestBase, ObserverSharedPtrDestroy) {
auto cb = std::make_shared<StrictMock<MockLegacyObserver>>();
EXPECT_CALL(*cb, observerAttach(transport.get()));
transport->addObserver(cb);
EXPECT_THAT(transport->getObservers(), UnorderedElementsAre(cb.get()));
InSequence s;
EXPECT_CALL(*cb, closeStarted(transport.get(), _));
EXPECT_CALL(*cb, closing(transport.get(), _));
EXPECT_CALL(*cb, destroy(transport.get()));
transport = nullptr;
Mock::VerifyAndClearExpectations(cb.get());
}
TEST_P(QuicTransportImplTestBase, ObserverSharedPtrReleasedDestroy) {
auto cb = std::make_shared<StrictMock<MockLegacyObserver>>();
EXPECT_CALL(*cb, observerAttach(transport.get()));
transport->addObserver(cb);
EXPECT_THAT(transport->getObservers(), UnorderedElementsAre(cb.get()));
// now that observer is attached, we release shared_ptr but keep raw ptr
// since the container holds shared_ptr too, observer should not be destroyed
MockLegacyObserver::Safety dc(*cb.get());
auto cbRaw = cb.get();
cb = nullptr;
EXPECT_FALSE(dc.destroyed()); // should still exist
InSequence s;
EXPECT_CALL(*cbRaw, closeStarted(transport.get(), _));
EXPECT_CALL(*cbRaw, closing(transport.get(), _));
EXPECT_CALL(*cbRaw, destroy(transport.get()));
transport = nullptr;
Mock::VerifyAndClearExpectations(cb.get());
}
TEST_P(QuicTransportImplTestBase, ObserverSharedPtrRemoveMissing) {
auto cb = std::make_shared<StrictMock<MockLegacyObserver>>();
EXPECT_FALSE(transport->removeObserver(cb.get()));
EXPECT_THAT(transport->getObservers(), IsEmpty());
}
TEST_P(QuicTransportImplTestBase, ObserverDetachImmediately) {
auto cb = std::make_unique<StrictMock<MockLegacyObserver>>();
EXPECT_CALL(*cb, observerAttach(transport.get()));
transport->addObserver(cb.get());
EXPECT_THAT(transport->getObservers(), UnorderedElementsAre(cb.get()));
EXPECT_CALL(*cb, observerDetach(transport.get()));
EXPECT_TRUE(transport->removeObserver(cb.get()));
Mock::VerifyAndClearExpectations(cb.get());
EXPECT_THAT(transport->getObservers(), IsEmpty());
}
TEST_P(QuicTransportImplTestBase, ObserverDetachAfterClose) {
// disable draining to ensure closing() event occurs immediately after close()
{
auto transportSettings = transport->getTransportSettings();
transportSettings.shouldDrain = false;
transport->setTransportSettings(transportSettings);
}
auto cb = std::make_unique<StrictMock<MockLegacyObserver>>();
EXPECT_CALL(*cb, observerAttach(transport.get()));
transport->addObserver(cb.get());
EXPECT_THAT(transport->getObservers(), UnorderedElementsAre(cb.get()));
EXPECT_CALL(*cb, closeStarted(transport.get(), _));
EXPECT_CALL(*cb, closing(transport.get(), _));
transport->close(folly::none);
Mock::VerifyAndClearExpectations(cb.get());
EXPECT_CALL(*cb, observerDetach(transport.get()));
EXPECT_TRUE(transport->removeObserver(cb.get()));
Mock::VerifyAndClearExpectations(cb.get());
EXPECT_THAT(transport->getObservers(), IsEmpty());
}
TEST_F(QuicTransportImplTest, ObserverDetachOnCloseStartedDuringDestroy) {
auto cb = std::make_unique<StrictMock<MockLegacyObserver>>();
EXPECT_CALL(*cb, observerAttach(transport.get()));
transport->addObserver(cb.get());
EXPECT_THAT(transport->getObservers(), UnorderedElementsAre(cb.get()));
InSequence s;
EXPECT_CALL(*cb, closeStarted(transport.get(), _))
.WillOnce(Invoke([&cb](auto callbackTransport, auto /* errorOpt */) {
EXPECT_TRUE(callbackTransport->removeObserver(cb.get()));
}));
EXPECT_CALL(*cb, observerDetach(transport.get()));
transport = nullptr;
Mock::VerifyAndClearExpectations(cb.get());
}
TEST_F(QuicTransportImplTest, ObserverDetachOnClosingDuringDestroy) {
auto cb = std::make_unique<StrictMock<MockLegacyObserver>>();
EXPECT_CALL(*cb, observerAttach(transport.get()));
transport->addObserver(cb.get());
EXPECT_THAT(transport->getObservers(), UnorderedElementsAre(cb.get()));
InSequence s;
EXPECT_CALL(*cb, closeStarted(transport.get(), _));
EXPECT_CALL(*cb, closing(transport.get(), _))
.WillOnce(Invoke([&cb](auto callbackTransport, auto /* errorOpt */) {
EXPECT_TRUE(callbackTransport->removeObserver(cb.get()));
}));
EXPECT_CALL(*cb, observerDetach(transport.get()));
transport = nullptr;
Mock::VerifyAndClearExpectations(cb.get());
}
TEST_P(QuicTransportImplTestBase, ObserverMultipleAttachRemove) {
auto cb1 = std::make_unique<StrictMock<MockLegacyObserver>>();
EXPECT_CALL(*cb1, observerAttach(transport.get()));
transport->addObserver(cb1.get());
EXPECT_THAT(transport->getObservers(), UnorderedElementsAre(cb1.get()));
auto cb2 = std::make_unique<StrictMock<MockLegacyObserver>>();
EXPECT_CALL(*cb2, observerAttach(transport.get()));
transport->addObserver(cb2.get());
EXPECT_THAT(
transport->getObservers(), UnorderedElementsAre(cb1.get(), cb2.get()));
EXPECT_CALL(*cb2, observerDetach(transport.get()));
EXPECT_TRUE(transport->removeObserver(cb2.get()));
EXPECT_THAT(transport->getObservers(), UnorderedElementsAre(cb1.get()));
Mock::VerifyAndClearExpectations(cb1.get());
Mock::VerifyAndClearExpectations(cb2.get());
EXPECT_CALL(*cb1, observerDetach(transport.get()));
EXPECT_TRUE(transport->removeObserver(cb1.get()));
EXPECT_THAT(transport->getObservers(), IsEmpty());
Mock::VerifyAndClearExpectations(cb1.get());
Mock::VerifyAndClearExpectations(cb2.get());
transport = nullptr;
}
TEST_P(QuicTransportImplTestBase, ObserverSharedPtrMultipleAttachRemove) {
auto cb1 = std::make_shared<StrictMock<MockLegacyObserver>>();
EXPECT_CALL(*cb1, observerAttach(transport.get()));
transport->addObserver(cb1);
Mock::VerifyAndClearExpectations(cb1.get());
EXPECT_THAT(transport->getObservers(), UnorderedElementsAre(cb1.get()));
auto cb2 = std::make_shared<StrictMock<MockLegacyObserver>>();
EXPECT_CALL(*cb2, observerAttach(transport.get()));
transport->addObserver(cb2);
Mock::VerifyAndClearExpectations(cb2.get());
EXPECT_THAT(
transport->getObservers(), UnorderedElementsAre(cb1.get(), cb2.get()));
EXPECT_CALL(*cb1, observerDetach(transport.get()));
EXPECT_TRUE(transport->removeObserver(cb1));
Mock::VerifyAndClearExpectations(cb1.get());
EXPECT_THAT(transport->getObservers(), UnorderedElementsAre(cb2.get()));
EXPECT_CALL(*cb2, observerDetach(transport.get()));
EXPECT_TRUE(transport->removeObserver(cb2));
Mock::VerifyAndClearExpectations(cb2.get());
EXPECT_THAT(transport->getObservers(), IsEmpty());
}
TEST_P(QuicTransportImplTestBase, ObserverMultipleAttachRemoveReverse) {
auto cb1 = std::make_unique<StrictMock<MockLegacyObserver>>();
EXPECT_CALL(*cb1, observerAttach(transport.get()));
transport->addObserver(cb1.get());
Mock::VerifyAndClearExpectations(cb1.get());
EXPECT_THAT(transport->getObservers(), UnorderedElementsAre(cb1.get()));
auto cb2 = std::make_unique<StrictMock<MockLegacyObserver>>();
EXPECT_CALL(*cb2, observerAttach(transport.get()));
transport->addObserver(cb2.get());
Mock::VerifyAndClearExpectations(cb2.get());
EXPECT_THAT(
transport->getObservers(), UnorderedElementsAre(cb1.get(), cb2.get()));
EXPECT_CALL(*cb2, observerDetach(transport.get()));
EXPECT_TRUE(transport->removeObserver(cb2.get()));
Mock::VerifyAndClearExpectations(cb1.get());
Mock::VerifyAndClearExpectations(cb2.get());
EXPECT_THAT(transport->getObservers(), UnorderedElementsAre(cb1.get()));
EXPECT_CALL(*cb1, observerDetach(transport.get()));
EXPECT_TRUE(transport->removeObserver(cb1.get()));
Mock::VerifyAndClearExpectations(cb1.get());
Mock::VerifyAndClearExpectations(cb2.get());
EXPECT_THAT(transport->getObservers(), IsEmpty());
}
TEST_P(QuicTransportImplTestBase, ObserverMultipleAttachDestroy) {
auto cb1 = std::make_unique<StrictMock<MockLegacyObserver>>();
EXPECT_CALL(*cb1, observerAttach(transport.get()));
transport->addObserver(cb1.get());
EXPECT_THAT(transport->getObservers(), UnorderedElementsAre(cb1.get()));
auto cb2 = std::make_unique<StrictMock<MockLegacyObserver>>();
EXPECT_CALL(*cb2, observerAttach(transport.get()));
transport->addObserver(cb2.get());
EXPECT_THAT(
transport->getObservers(), UnorderedElementsAre(cb1.get(), cb2.get()));
InSequence s;
EXPECT_CALL(*cb1, closeStarted(transport.get(), _));
EXPECT_CALL(*cb2, closeStarted(transport.get(), _));
EXPECT_CALL(*cb1, closing(transport.get(), _));
EXPECT_CALL(*cb2, closing(transport.get(), _));
EXPECT_CALL(*cb1, destroy(transport.get()));
EXPECT_CALL(*cb2, destroy(transport.get()));
transport = nullptr;
Mock::VerifyAndClearExpectations(cb1.get());
Mock::VerifyAndClearExpectations(cb2.get());
}
TEST_P(QuicTransportImplTestBase, ObserverDetachAndAttachEvb) {
LegacyObserver::EventSet eventSet;
eventSet.enable(SocketObserverInterface::Events::evbEvents);
auto obs1 = std::make_unique<NiceMock<MockLegacyObserver>>();
auto obs2 = std::make_unique<NiceMock<MockLegacyObserver>>(eventSet);
auto obs3 = std::make_unique<NiceMock<MockLegacyObserver>>(eventSet);
transport->addObserver(obs1.get());
transport->addObserver(obs2.get());
transport->addObserver(obs3.get());
// check the current event base and create a new one
EXPECT_EQ(evb->getBackingEventBase(), transport->getEventBase());
folly::EventBase backingEvb2;
QuicEventBase evb2(&backingEvb2);
// Detach the event base evb
EXPECT_CALL(*obs1, evbDetach(transport.get(), evb->getBackingEventBase()))
.Times(0);
EXPECT_CALL(*obs2, evbDetach(transport.get(), evb->getBackingEventBase()))
.Times(1);
EXPECT_CALL(*obs3, evbDetach(transport.get(), evb->getBackingEventBase()))
.Times(1);
transport->detachEventBase();
EXPECT_EQ(nullptr, transport->getEventBase());
// Attach a new event base evb2
EXPECT_CALL(*obs1, evbAttach(transport.get(), evb2.getBackingEventBase()))
.Times(0);
EXPECT_CALL(*obs2, evbAttach(transport.get(), evb2.getBackingEventBase()))
.Times(1);
EXPECT_CALL(*obs3, evbAttach(transport.get(), evb2.getBackingEventBase()))
.Times(1);
transport->attachEventBase(evb2.getBackingEventBase());
EXPECT_EQ(evb2.getBackingEventBase(), transport->getEventBase());
// Detach the event base evb2
EXPECT_CALL(*obs1, evbDetach(transport.get(), evb2.getBackingEventBase()))
.Times(0);
EXPECT_CALL(*obs2, evbDetach(transport.get(), evb2.getBackingEventBase()))
.Times(1);
EXPECT_CALL(*obs3, evbDetach(transport.get(), evb2.getBackingEventBase()))
.Times(1);
transport->detachEventBase();
EXPECT_EQ(nullptr, transport->getEventBase());
// Attach the original event base evb
EXPECT_CALL(*obs1, evbAttach(transport.get(), evb->getBackingEventBase()))
.Times(0);
EXPECT_CALL(*obs2, evbAttach(transport.get(), evb->getBackingEventBase()))
.Times(1);
EXPECT_CALL(*obs3, evbAttach(transport.get(), evb->getBackingEventBase()))
.Times(1);
transport->attachEventBase(evb->getBackingEventBase());
EXPECT_EQ(evb->getBackingEventBase(), transport->getEventBase());
EXPECT_TRUE(transport->removeObserver(obs1.get()));
EXPECT_TRUE(transport->removeObserver(obs2.get()));
EXPECT_TRUE(transport->removeObserver(obs3.get()));
}
TEST_P(QuicTransportImplTestBase, GetConnectionStatsSmoke) {
auto stats = transport->getConnectionsStats();
EXPECT_EQ(stats.congestionController, CongestionControlType::Cubic);
EXPECT_EQ(stats.clientConnectionId, "0a090807");
}
TEST_P(QuicTransportImplTestBase, DatagramCallbackDatagramAvailable) {
NiceMock<MockDatagramCallback> datagramCb;
transport->enableDatagram();
transport->setDatagramCallback(&datagramCb);
transport->addDatagram(folly::IOBuf::copyBuffer("datagram payload"));
EXPECT_CALL(datagramCb, onDatagramsAvailable());
transport->driveReadCallbacks();
}
TEST_P(QuicTransportImplTestBase, ZeroLengthDatagram) {
NiceMock<MockDatagramCallback> datagramCb;
transport->enableDatagram();
transport->setDatagramCallback(&datagramCb);
transport->addDatagram(folly::IOBuf::copyBuffer(""));
EXPECT_CALL(datagramCb, onDatagramsAvailable());
transport->driveReadCallbacks();
auto datagrams = transport->readDatagramBufs();
EXPECT_FALSE(datagrams.hasError());
EXPECT_EQ(datagrams->size(), 1);
EXPECT_TRUE(datagrams->front() != nullptr);
EXPECT_EQ(datagrams->front()->computeChainDataLength(), 0);
}
TEST_P(QuicTransportImplTestBase, ZeroLengthDatagramBufs) {
NiceMock<MockDatagramCallback> datagramCb;
transport->enableDatagram();
transport->setDatagramCallback(&datagramCb);
auto recvTime = Clock::now() + 5000ns;
transport->addDatagram(folly::IOBuf::copyBuffer(""), recvTime);
EXPECT_CALL(datagramCb, onDatagramsAvailable());
transport->driveReadCallbacks();
auto datagrams = transport->readDatagrams();
EXPECT_FALSE(datagrams.hasError());
EXPECT_EQ(datagrams->size(), 1);
EXPECT_TRUE(datagrams->front().bufQueue().front() != nullptr);
EXPECT_EQ(datagrams->front().receiveTimePoint(), recvTime);
EXPECT_EQ(datagrams->front().bufQueue().front()->computeChainDataLength(), 0);
}
TEST_P(QuicTransportImplTestBase, Cmsgs) {
transport->setServerConnectionId();
folly::SocketOptionMap cmsgs;
cmsgs[{IPPROTO_IP, IP_TOS}] = 123;
EXPECT_CALL(*socketPtr, setCmsgs(_)).Times(1);
transport->setCmsgs(cmsgs);
EXPECT_CALL(*socketPtr, appendCmsgs(_)).Times(1);
transport->appendCmsgs(cmsgs);
}
TEST_P(QuicTransportImplTestBase, BackgroundModeChangeWithStreamChanges) {
// Verify that background mode is correctly turned on and off
// based upon stream creation, priority changes, stream removal.
// For different steps try local (uni/bi)directional streams and remote
// streams
InSequence s;
auto& conn = transport->getConnectionState();
auto mockCongestionController =
std::make_unique<NiceMock<MockCongestionController>>();
auto rawCongestionController = mockCongestionController.get();
conn.congestionController = std::move(mockCongestionController);
auto& manager = *conn.streamManager;
EXPECT_CALL(*rawCongestionController, setBandwidthUtilizationFactor(_))
.Times(0); // Background params not set
auto stream = manager.createNextUnidirectionalStream().value();
manager.setStreamPriority(stream->id, Priority(1, false));
EXPECT_CALL(*rawCongestionController, setBandwidthUtilizationFactor(0.5))
.Times(1); // On setting the background params
transport->setBackgroundModeParameters(1, 0.5);
EXPECT_CALL(*rawCongestionController, setBandwidthUtilizationFactor(0.5))
.Times(1); // On removing a closed stream
stream->sendState = StreamSendState::Closed;
stream->recvState = StreamRecvState::Closed;
manager.removeClosedStream(stream->id);
EXPECT_CALL(*rawCongestionController, setBandwidthUtilizationFactor(0.5))
.Times(2); // On stream creation - create two streams - one bidirectional
auto stream2Id = manager.createNextUnidirectionalStream().value()->id;
auto stream3id = manager.createNextBidirectionalStream().value()->id;
EXPECT_CALL(*rawCongestionController, setBandwidthUtilizationFactor(1.0))
.Times(1); // On increasing the priority of one of the streams
manager.setStreamPriority(stream3id, Priority(0, false));
EXPECT_CALL(*rawCongestionController, setBandwidthUtilizationFactor(1.0))
.Times(1); // a new lower priority stream does not affect the utlization
// factor
auto streamLower = manager.createNextBidirectionalStream().value();
EXPECT_CALL(*rawCongestionController, setBandwidthUtilizationFactor(1.0))
.Times(1); // On removing a closed stream
streamLower->sendState = StreamSendState::Closed;
streamLower->recvState = StreamRecvState::Closed;
manager.removeClosedStream(streamLower->id);
EXPECT_CALL(*rawCongestionController, setBandwidthUtilizationFactor(0.5))
.Times(1); // On removing a closed stream
CHECK_NOTNULL(manager.getStream(stream3id))->sendState =
StreamSendState::Closed;
CHECK_NOTNULL(manager.getStream(stream3id))->recvState =
StreamRecvState::Closed;
manager.removeClosedStream(stream3id);
EXPECT_CALL(*rawCongestionController, setBandwidthUtilizationFactor(0.5))
.Times(1); // On stream creation - remote stream
auto peerStreamId = 20;
ASSERT_TRUE(isRemoteStream(conn.nodeType, peerStreamId));
auto stream4 = manager.getStream(peerStreamId);
EXPECT_CALL(*rawCongestionController, setBandwidthUtilizationFactor(1.0))
.Times(1); // On clearing the background parameters
transport->clearBackgroundModeParameters();
EXPECT_CALL(*rawCongestionController, setBandwidthUtilizationFactor(_))
.Times(0); // Background params not set
stream4->sendState = StreamSendState::Closed;
stream4->recvState = StreamRecvState::Closed;
manager.removeClosedStream(stream4->id);
CHECK_NOTNULL(manager.getStream(stream2Id))->sendState =
StreamSendState::Closed;
CHECK_NOTNULL(manager.getStream(stream2Id))->recvState =
StreamRecvState::Closed;
manager.removeClosedStream(stream2Id);
}
class QuicTransportImplTestWithGroups : public QuicTransportImplTestBase {};
INSTANTIATE_TEST_SUITE_P(
QuicTransportImplTestWithGroups,
QuicTransportImplTestWithGroups,
::testing::Values(DelayedStreamNotifsTestParam{true}));
TEST_P(QuicTransportImplTestWithGroups, ReadCallbackWithGroupsDataAvailable) {
auto transportSettings = transport->getTransportSettings();
transportSettings.advertisedMaxStreamGroups = 16;
transport->setTransportSettings(transportSettings);
transport->getConnectionState().streamManager->refreshTransportSettings(
transportSettings);
auto groupId = transport->createBidirectionalStreamGroup();
EXPECT_TRUE(groupId.hasValue());
auto stream1 = transport->createBidirectionalStreamInGroup(*groupId).value();
auto stream2 = transport->createBidirectionalStreamInGroup(*groupId).value();
NiceMock<MockReadCallback> readCb1;
NiceMock<MockReadCallback> readCb2;
transport->setReadCallback(stream1, &readCb1);
transport->setReadCallback(stream2, &readCb2);
transport->addDataToStream(
stream1,
StreamBuffer(folly::IOBuf::copyBuffer("actual stream data"), 0),
*groupId);
transport->addDataToStream(
stream2,
StreamBuffer(folly::IOBuf::copyBuffer("actual stream data"), 10),
*groupId);
EXPECT_CALL(readCb1, readAvailableWithGroup(stream1, *groupId));
transport->driveReadCallbacks();
transport->addDataToStream(
stream2,
StreamBuffer(folly::IOBuf::copyBuffer("actual stream data"), 0),
*groupId);
EXPECT_CALL(readCb1, readAvailableWithGroup(stream1, *groupId));
EXPECT_CALL(readCb2, readAvailableWithGroup(stream2, *groupId));
transport->driveReadCallbacks();
EXPECT_CALL(readCb1, readAvailableWithGroup(stream1, *groupId));
EXPECT_CALL(readCb2, readAvailableWithGroup(stream2, *groupId));
transport->driveReadCallbacks();
EXPECT_CALL(readCb2, readAvailableWithGroup(stream2, *groupId));
transport->setReadCallback(stream1, nullptr);
transport->driveReadCallbacks();
transport.reset();
}
TEST_P(QuicTransportImplTestWithGroups, ReadErrorCallbackWithGroups) {
auto transportSettings = transport->getTransportSettings();
transportSettings.advertisedMaxStreamGroups = 16;
transport->setTransportSettings(transportSettings);
transport->getConnectionState().streamManager->refreshTransportSettings(
transportSettings);
auto groupId = transport->createBidirectionalStreamGroup();
EXPECT_TRUE(groupId.hasValue());
auto stream1 = transport->createBidirectionalStreamInGroup(*groupId).value();
NiceMock<MockReadCallback> readCb1;
transport->setReadCallback(stream1, &readCb1);
transport->addStreamReadError(stream1, LocalErrorCode::NO_ERROR);
transport->addDataToStream(
stream1,
StreamBuffer(folly::IOBuf::copyBuffer("actual stream data"), 0),
*groupId);
EXPECT_CALL(readCb1, readErrorWithGroup(stream1, *groupId, _));
transport->driveReadCallbacks();
transport.reset();
}
TEST_P(
QuicTransportImplTestWithGroups,
ReadCallbackWithGroupsCancellCallbacks) {
auto transportSettings = transport->getTransportSettings();
transportSettings.advertisedMaxStreamGroups = 16;
transport->setTransportSettings(transportSettings);
transport->getConnectionState().streamManager->refreshTransportSettings(
transportSettings);
auto groupId = transport->createBidirectionalStreamGroup();
EXPECT_TRUE(groupId.hasValue());
auto stream1 = transport->createBidirectionalStreamInGroup(*groupId).value();
auto stream2 = transport->createBidirectionalStreamInGroup(*groupId).value();
NiceMock<MockReadCallback> readCb1;
NiceMock<MockReadCallback> readCb2;
transport->setReadCallback(stream1, &readCb1);
transport->setReadCallback(stream2, &readCb2);
transport->addDataToStream(
stream1,
StreamBuffer(folly::IOBuf::copyBuffer("actual stream data"), 0),
*groupId);
transport->addDataToStream(
stream2,
StreamBuffer(folly::IOBuf::copyBuffer("actual stream data"), 10),
*groupId);
EXPECT_CALL(readCb1, readErrorWithGroup(stream1, *groupId, _));
EXPECT_CALL(readCb2, readErrorWithGroup(stream2, *groupId, _));
QuicError error =
QuicError(TransportErrorCode::PROTOCOL_VIOLATION, "test error");
transport->cancelAllAppCallbacks(error);
transport.reset();
}
TEST_P(QuicTransportImplTestWithGroups, onNewStreamsAndGroupsCallbacks) {
auto transportSettings = transport->getTransportSettings();
transportSettings.advertisedMaxStreamGroups = 16;
transport->setTransportSettings(transportSettings);
transport->getConnectionState().streamManager->refreshTransportSettings(
transportSettings);
auto readData = folly::IOBuf::copyBuffer("actual stream data");
StreamGroupId groupId = 0x00;
StreamId stream1 = 0x00;
EXPECT_CALL(connCallback, onNewBidirectionalStreamGroup(groupId));
EXPECT_CALL(connCallback, onNewBidirectionalStreamInGroup(stream1, groupId));
transport->addDataToStream(
stream1, StreamBuffer(readData->clone(), 0, true), groupId);
StreamId stream2 = 0x04;
EXPECT_CALL(connCallback, onNewBidirectionalStreamInGroup(stream2, groupId));
transport->addDataToStream(
stream2, StreamBuffer(readData->clone(), 0, true), groupId);
StreamGroupId groupIdUni = 0x02;
StreamId uniStream3 = 0xa;
EXPECT_CALL(connCallback, onNewUnidirectionalStreamGroup(groupIdUni));
EXPECT_CALL(
connCallback, onNewUnidirectionalStreamInGroup(uniStream3, groupIdUni));
transport->addDataToStream(
uniStream3, StreamBuffer(readData->clone(), 0, true), groupIdUni);
transport.reset();
}
TEST_P(
QuicTransportImplTestWithGroups,
TestSetStreamGroupRetransmissionPolicyAllowed) {
auto transportSettings = transport->getTransportSettings();
transportSettings.advertisedMaxStreamGroups = 16;
transport->setTransportSettings(transportSettings);
transport->getConnectionState().streamManager->refreshTransportSettings(
transportSettings);
const StreamGroupId groupId = 0x00;
const QuicStreamGroupRetransmissionPolicy policy;
// Test policy set allowed
auto res = transport->setStreamGroupRetransmissionPolicy(groupId, policy);
EXPECT_TRUE(res.hasValue());
// Test policy set not allowed.
transportSettings.advertisedMaxStreamGroups = 0;
transport->setTransportSettings(transportSettings);
transport->getConnectionState().streamManager->refreshTransportSettings(
transportSettings);
res = transport->setStreamGroupRetransmissionPolicy(groupId, policy);
EXPECT_TRUE(res.hasError());
EXPECT_EQ(res.error(), LocalErrorCode::INVALID_OPERATION);
EXPECT_EQ(1, transport->getStreamGroupRetransmissionPolicies().size());
transport.reset();
}
TEST_P(
QuicTransportImplTestWithGroups,
TestStreamGroupRetransmissionPolicyReset) {
auto transportSettings = transport->getTransportSettings();
transportSettings.advertisedMaxStreamGroups = 16;
transport->setTransportSettings(transportSettings);
transport->getConnectionState().streamManager->refreshTransportSettings(
transportSettings);
const StreamGroupId groupId = 0x00;
QuicStreamGroupRetransmissionPolicy policy;
// Add the policy.
auto res = transport->setStreamGroupRetransmissionPolicy(groupId, policy);
EXPECT_TRUE(res.hasValue());
EXPECT_EQ(transport->getStreamGroupRetransmissionPolicies().size(), 1);
// Reset allowed.
res = transport->setStreamGroupRetransmissionPolicy(groupId, std::nullopt);
EXPECT_TRUE(res.hasValue());
EXPECT_EQ(transport->getStreamGroupRetransmissionPolicies().size(), 0);
// Add the policy back.
res = transport->setStreamGroupRetransmissionPolicy(groupId, policy);
EXPECT_TRUE(res.hasValue());
EXPECT_EQ(transport->getStreamGroupRetransmissionPolicies().size(), 1);
// Reset allowed even if custom policies are disabled.
transportSettings.advertisedMaxStreamGroups = 0;
res = transport->setStreamGroupRetransmissionPolicy(groupId, std::nullopt);
EXPECT_TRUE(res.hasValue());
EXPECT_EQ(transport->getStreamGroupRetransmissionPolicies().size(), 0);
transport.reset();
}
TEST_P(
QuicTransportImplTestWithGroups,
TestStreamGroupRetransmissionPolicyAddRemove) {
auto transportSettings = transport->getTransportSettings();
transportSettings.advertisedMaxStreamGroups = 16;
transport->setTransportSettings(transportSettings);
transport->getConnectionState().streamManager->refreshTransportSettings(
transportSettings);
// Add a policy.
const StreamGroupId groupId = 0x00;
const QuicStreamGroupRetransmissionPolicy policy;
auto res = transport->setStreamGroupRetransmissionPolicy(groupId, policy);
EXPECT_TRUE(res.hasValue());
EXPECT_EQ(transport->getStreamGroupRetransmissionPolicies().size(), 1);
// Add another one.
const StreamGroupId groupId2 = 0x04;
const QuicStreamGroupRetransmissionPolicy policy2;
res = transport->setStreamGroupRetransmissionPolicy(groupId2, policy2);
EXPECT_TRUE(res.hasValue());
EXPECT_EQ(transport->getStreamGroupRetransmissionPolicies().size(), 2);
// Remove second policy.
res = transport->setStreamGroupRetransmissionPolicy(groupId2, std::nullopt);
EXPECT_TRUE(res.hasValue());
EXPECT_EQ(transport->getStreamGroupRetransmissionPolicies().size(), 1);
// Remove first policy.
res = transport->setStreamGroupRetransmissionPolicy(groupId, std::nullopt);
EXPECT_TRUE(res.hasValue());
EXPECT_EQ(transport->getStreamGroupRetransmissionPolicies().size(), 0);
transport.reset();
}
TEST_P(
QuicTransportImplTestWithGroups,
TestStreamGroupRetransmissionPolicyMaxLimit) {
auto transportSettings = transport->getTransportSettings();
transportSettings.advertisedMaxStreamGroups = 1;
transport->setTransportSettings(transportSettings);
transport->getConnectionState().streamManager->refreshTransportSettings(
transportSettings);
// Add a policy.
const StreamGroupId groupId = 0x00;
const QuicStreamGroupRetransmissionPolicy policy;
auto res = transport->setStreamGroupRetransmissionPolicy(groupId, policy);
EXPECT_TRUE(res.hasValue());
EXPECT_EQ(transport->getStreamGroupRetransmissionPolicies().size(), 1);
// Try adding another one; should be over the limit.
const StreamGroupId groupId2 = 0x04;
res = transport->setStreamGroupRetransmissionPolicy(groupId2, policy);
EXPECT_TRUE(res.hasError());
EXPECT_EQ(res.error(), LocalErrorCode::RTX_POLICIES_LIMIT_EXCEEDED);
EXPECT_EQ(transport->getStreamGroupRetransmissionPolicies().size(), 1);
transport.reset();
}
} // namespace test
} // namespace quic
|
/*
Problem: 1006
Author: Kevin Washington (@kevinwsbr)
*/
#include <iostream>
#include <stdio.h>
using namespace std;
int main(){
float a, b, c;
cin >> a;
cin >> b;
cin >> c;
printf("MEDIA = %.1f\n", (a*2 + b*3 + c*5)/(2+3+5));
return 0;
}
|
#pragma once
#include "MovementComponent.h"
#include "PhysicsComponent.h"
#include "Input.h"
#include "Model.h"
class GameObject
{
protected:
bool m_visible;
bool m_collidable;
bool m_isStatic;
bool m_shouldDrawBB;
bool m_useDeceleration;
int m_wvpCBufferIndex;
// Componenets
MovementComponent* m_movementComp;
PhysicsComponent* m_physicsComp;
Model* m_modelPtr;
std::wstring m_texturePath;
public:
GameObject();
GameObject(const GameObject& otherGameObject);
virtual ~GameObject();
GameObject& operator=(const GameObject& otherGameObject);
// Initialization
void initializeStatic(bool collidable, int wvpCBufferIndex, Model* mdl);
void initializeDynamic(bool collidable, bool useDeceleration, int wvpCBufferIndex, float mass, XMFLOAT3 acceleration, XMFLOAT3 deceleration, Model* mdl);
// Update
virtual void update(float dt);
// Getters
bool visible() const;
bool collidable() const;
bool shouldDrawBB() const;
XMVECTOR getScale() const;
XMVECTOR getLocalRotation() const;
XMVECTOR getRotation() const;
XMVECTOR getPosition() const;
XMMATRIX getWorldMatrix() const;
XMMATRIX getTranslationMatrix() const;
int getWvpCBufferIndex() const;
void setWvpCBufferIndex(int index);
MovementComponent* getMoveCompPtr();
PhysicsComponent* getphysicsCompPtr();
BoundingBox getAABB();
BoundingBox* getAABBPtr();
Model* getModelPtr() const;
std::wstring getTexturePath() const;
void setTexturePath(std::wstring texturePath);
// Setters
void setDrawBB(bool drawable);
void setVisibility(bool visible);
void setIfCollidable(bool collidable);
void setRotation(XMVECTOR newRotation);
void setScale(XMVECTOR newScale);
void setPosition(XMVECTOR newPosition);
void setBoundingBox(XMFLOAT3 extends);
void move(Direction dir, float dt);
void move(XMVECTOR dir, float dt);
bool m_removeMe;
};
|
/* -*- Mode: c++; tab-width: 4; indent-tabs-mode: t; c-basic-offset: 4; c-file-style:"stroustrup" -*-
*
* Copyright (C) 1995-2008 Opera Software AS. All rights reserved.
*
* This file is part of the Opera web browser. It may not be distributed
* under any circumstances.
*
*/
#ifndef MDE_OPVIEW_H
#define MDE_OPVIEW_H
#include "modules/pi/OpView.h"
#include "modules/util/simset.h"
#include "modules/libgogi/mde.h"
#include "modules/libgogi/pi_impl/mde_widget.h"
#ifdef UTIL_LISTENERS
#include "modules/util/adt/oplisteners.h"
#endif // UTIL_LISTENERS
#ifndef VEGA_OPPAINTER_SUPPORT
class OpPainter;
#endif
class OpInputMethodString;
class MDE_OpWindow;
class MDE_Widget;
class MDE_OpView : public OpView
{
public:
MDE_OpView();
virtual ~MDE_OpView();
OP_STATUS Init(OpWindow *parentWindow);
OP_STATUS Init(OpView *parentView);
virtual void UseDoublebuffer(BOOL doublebuffer);
virtual void ScrollRect(const OpRect &rect, INT32 dx, INT32 dy);
virtual void Scroll(INT32 dx, INT32 dy, BOOL full_update);
virtual void Sync();
virtual void LockUpdate(BOOL lock);
virtual void SetPos(INT32 x, INT32 y);
virtual void GetPos(INT32* x, INT32* y);
virtual void SetSize(UINT32 w, UINT32 h);
virtual void GetSize(UINT32* w, UINT32* h);
virtual void SetVisibility(BOOL visible);
virtual BOOL GetVisibility();
virtual OP_STATUS SetCustomOverlapRegion(OpRect *rects, INT32 num_rects);
virtual void SetAffectLowerRegions(BOOL affect_lower_regions);
#ifdef WIDGETS_IME_SUPPORT
virtual void SetInputMethodListener(OpInputMethodListener* imlistener);
#endif // WIDGETS_IME_SUPPORT
virtual void SetPaintListener(OpPaintListener* paintlistener);
#ifndef MOUSELESS
virtual void SetMouseListener(OpMouseListener* mouselistener);
#endif // !MOUSELESS
#ifdef TOUCH_EVENTS_SUPPORT
virtual void SetTouchListener(OpTouchListener* touchlistener);
#endif // TOUCH_EVENTS_SUPPORT
#ifdef DRAG_SUPPORT
virtual void SetDragListener(OpDragListener* draglistener);
virtual OpDragListener* GetDragListener() const;
#endif // DRAG_SUPPORT
virtual ShiftKeyState GetShiftKeys();
#ifndef MOUSELESS
virtual BOOL GetMouseButton(MouseButton button);
#ifdef TOUCH_EVENTS_SUPPORT
virtual void SetMouseButton(MouseButton button, bool set);
#endif // TOUCH_EVENTS_SUPPORT
virtual void GetMousePos(INT32* xpos, INT32* ypos);
#endif // !MOUSELESS
virtual OpPoint ConvertToScreen(const OpPoint &point);
virtual OpPoint ConvertFromScreen(const OpPoint &point);
#ifdef WIDGETS_IME_SUPPORT
virtual void AbortInputMethodComposing();
virtual void SetInputMethodMode(IME_MODE mode, IME_CONTEXT context, const uni_char* istyle);
virtual void SetInputMoved();
virtual void SetInputTextChanged();
virtual void CommitIME(const uni_char *text);
virtual void UpdateIME(const uni_char *text, int cursorpos, int highlight_start, int highlight_len);
virtual void UpdateIME(const uni_char *text);
virtual OP_STATUS SubmitIME();
#endif // WIDGETS_IME_SUPPORT
virtual void OnHighlightRectChanged(const OpRect &rect);
virtual OpPainter* GetPainter(const OpRect &rect, BOOL nobackbuffer = FALSE);
virtual void ReleasePainter(const OpRect &rect);
virtual void Invalidate(const OpRect& rect);
#ifdef PLATFORM_FONTSWITCHING
virtual void SetPreferredCodePage(OpFontInfo::CodePage cp);
#endif
virtual MDE_OpWindow* GetParentWindow() { return parentWindow; }
virtual MDE_OpView* GetParentView() { return parentView; }
virtual OpWindow* GetRootWindow() { return GetMDEWidget()->GetRootWindow(); }
#ifdef VEGA_OPPAINTER_SUPPORT
void SetBitmapPainter(OpPainter *painter) { bitmap_painter = painter; }
OpPainter *GetBitmapPainter() { return bitmap_painter; }
#endif // VEGA_OPPAINTER_SUPPORT
// non-interface functions
MDE_Widget* GetMDEWidget() { return mdeWidget; }
#ifdef UTIL_LISTENERS
virtual OP_STATUS AddOpViewListener(OpViewListener* listener) { return m_listeners.Add(listener); }
virtual OP_STATUS RemoveOpViewListener(OpViewListener* listener) { return m_listeners.Remove(listener); }
#endif // UTIL_LISTENERS
private:
MDE_OpView *parentView;
MDE_OpWindow *parentWindow;
Head childViews;
#ifdef UTIL_LISTENERS
OpListeners<OpViewListener> m_listeners;
#endif // UTIL_LISTENERS
MDE_Widget* mdeWidget;
#ifdef VEGA_OPPAINTER_SUPPORT
VEGAOpPainter *painter;
OpPainter *bitmap_painter;
#else
OpPainter* painter;
#endif
INT32 numPainters;
#ifdef MDE_DOUBLEBUF_SUPPORT
BOOL doubleBuffer;
MDE_BUFFER *backbuf;
MDE_BUFFER frontbuf;
#endif
#ifdef WIDGETS_IME_SUPPORT
OpInputMethodListener *imeListener;
OpInputMethodString *imestr;
void *currentIME;
BOOL commiting;
BOOL spawning;
BOOL aborting;
#endif // WIDGETS_IME_SUPPORT
};
#endif // MDE_OPVIEW_H
|
// https://www.youtube.com/watch?v=eeSC43KQdVI&list=PL_dsdStdDXbrzGQUMh2sy6T8GcCCst3Nm
#include <future>
#include <initializer_list>
#include <iostream>
#include <thread>
#include <vector>
#include <windows.h>
using namespace std;
void ThreadFn(int &v1, int v2)
{
cout << "a thread function" << endl;
cout << "Value V1 : " << v1++ << endl;
cout << "Value V2 : " << v2 << endl;
}
void ThreadFn1()
{
cout << "a thread function 1" << endl;
cout << this_thread::get_id() << endl;
}
template <typename T> void ThreadFn2() { cout << "Type is : " << typeid(T).name() << endl; }
void ThreadFn3(initializer_list<int> il) { cout << "size of list : " << il.size() << endl; }
void ThreadFn4(vector<int> il)
{
cout << "size of list : " << il.size() << endl;
for (vector<int>::iterator itr = il.begin(); itr != il.end(); ++itr) {
cout << *itr << endl;
}
}
int AsyncFunc5(int value)
{
cout << "Main Thread5 : " << this_thread::get_id() << endl;
cout << "async..." << endl;
return value + 100;
}
void ThreadFn6(promise<int> &value)
{
this_thread::sleep_for(chrono::seconds(2));
value.set_value(200);
}
/**************************************************************************/
int main()
{
// 콘솔 한글
SetConsoleOutputCP(CP_UTF8);
// 기본 thread
int localvalue = 100;
thread t{ThreadFn, ref(localvalue), 2000};
/*
thread t1{[](int &v1) {
cout << "a thread function" << endl;
cout << "Value V1 : " << v1++ << endl;
},
ref(localvalue)};
*/
t.join();
cout << "Value in Main Thread : " << localvalue << endl;
cout << "----------------" << endl;
// [1] thread stl
thread t1{ThreadFn1};
cout << this_thread::get_id() << endl;
t1.join();
cout << "----------------" << endl;
// [2] thread Template
thread t2{ThreadFn2<int>};
this_thread::sleep_for(chrono::milliseconds(1000));
thread t21{ThreadFn2<float>};
t2.join();
t21.join();
cout << "----------------" << endl;
// [3] thread template and STL
initializer_list<int> il = {1, 2, 3, 4, 5, 6};
thread t3{ThreadFn3, il};
t3.join();
cout << "----------------" << endl;
// [4] thread vector
vector<int> il2 = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10};
thread t4{ThreadFn4, il2};
t4.join();
cout << "----------------" << endl;
// [5] Async
cout << "Main Thread : " << this_thread::get_id() << endl;
future<int> fn = async(launch::async, AsyncFunc5, 200);
// future<void> fn = async(launch::deferred, AsyncFunc5); //동일한 thread id에서 실행
if (fn.valid())
cout << fn.get() << endl;
if (fn.valid())
fn.get();
else
cout << "Invalid" << endl;
cout << "----------------" << endl;
// [6] Promise
promise<int> myPromise;
future<int> fut = myPromise.get_future();
// myPromise.set_value(100);
cout << "Main..." << endl;
thread t6{ThreadFn6, ref(myPromise)};
cout << "Main Thread : " << fut.get() << endl;
t6.join();
cout << "----------------" << endl;
return 0;
}
|
#include<bits/stdc++.h>
using namespace std;
vector<deque<int> > pile;
set<vector<deque<int> > > status;
bool can[8];
int cnt=0;
int ans=0;
bool check(int x) {
if(pile[x].size()<3)
return false;
int f1=pile[x].front();
pile[x].pop_front();
int f2=pile[x].front();
pile[x].pop_front();
int l1=pile[x].back();
pile[x].pop_back();
// cout<<"lll "<<f1<<" "<<f2<<" "<<l1<<"\n";
if(f1+f2+l1==10||f1+f2+l1==20||f1+f2+l1==30) {
// cout<<111111<<"\n";
// printf("%d %d %d\n",f1,f2,l1);
pile[0].push_back(f1);
pile[0].push_back(f2);
pile[0].push_back(l1);
return true;
} else {
pile[x].push_front(f2);
int l2=pile[x].back();
pile[x].pop_back();
if(f1+l2+l1==10||f1+l2+l1==20||f1+l2+l1==30) {
// cout<<2222222<<"\n";
// printf("%d %d %d\n",f1,l1,l2);
pile[0].push_back(f1);
pile[0].push_back(l2);
pile[0].push_back(l1);
return true;
} else {
pile[x].push_front(f1);
int l3=pile[x].back();
pile[x].pop_back();
if(l3+l2+l1==10||l3+l2+l1==20||l3+l2+l1==30) {
// cout<<333333<<"\n";
// printf("%d %d %d\n",l1,l2,l3);
pile[0].push_back(l3);
pile[0].push_back(l2);
pile[0].push_back(l1);
return true;
} else {
pile[x].push_back(l3);
pile[x].push_back(l2);
pile[x].push_back(l1);
}
}
}
return false;
}
int main() {
int a;
while(cin>>a&&a) {
ans=0;
cnt=0;
memset(can,false,sizeof(can));
pile.clear();
status.clear();
for(int i=0; i<=7; i++) {
deque<int> q;
q.clear();
pile.push_back(q);
}
pile[0].push_back(a);
for(int i=0; i<51; i++) {
cin>>a;
// cout<<a<<"\n";
pile[0].push_back(a);
}
// cout<<"111\n";
int flag=0;
while(true) {
for(int i=1; i<8; i++) {
// cout<<"i="<<i<<"\n";
if(cnt==7) {
flag=1;
break;
}
if(pile[0].size()==0) {
flag=2;
break;
}
if(can[i])
continue;
ans++;
int f=pile[0].front();
pile[0].pop_front();
// cout<<"f:"<<f<<"\n";
pile[i].push_back(f);
while(check(i));
// cout<<"sz "<<pile[i].size()<<"\n";
if(pile[i].size()==0) {
// cout<<"hhhhhh"<<" "<<i<<"\n";
can[i]=true;
cnt++;
}
if(status.count(pile)) {
flag=3;
break;
}
status.insert(pile);
}
if(flag!=0)
break;
}
if(flag==1) {
cout<<"Win : "<<ans<<"\n";
} else if(flag==2) {
cout<<"Loss: "<<ans<<"\n";
} else if(flag==3) {
cout<<"Draw: "<<ans<<"\n";
}
}
return 0;
}
|
#ifndef F3LIB_MOTION_H_
#define F3LIB_MOTION_H_
#include "Bone.h"
#include "Skeleton.h"
#include "f3lib/types/Matrix.h"
#include <string>
#include <vector>
namespace f3
{
class MotionAttribute
{
public:
unsigned int m_attributes;
int m_soundId;
float m_frame;
};
class Motion
{
public:
explicit Motion();
~Motion();
void initBones(const Skeleton& skeleton, std::vector<types::Matrix>& boneMatrices) const;
void updateBones(Skeleton& skeleton, int framePrev, int frameNext, float interp,
std::vector<types::Matrix>& boneMatrices) const;
std::vector<MotionAttribute> _attributes; //motion attributes for each frame
int _version;
int _id;
std::string _name;
float _perSlerp;
std::vector<BoneFrame> _boneFrames;
std::vector<Bone> _boneInfos;
std::vector<types::Vector3> _events;
std::vector<types::Vector3> _path;
};
} // namespace f3
#endif // F3LIB_MOTION_H_
|
#include<stdio.h>
int main()
{
int t, a, b, c, max;
scanf("%d",&t);
for (int i = 1; i <=t; ++i)
{
scanf("%d%d%d",&a,&b,&c);
if(a>=b && a>=c) max = a;
else if(b>=a && b>=c) max = b;
else if(c>=a && c>=b) max = c;
if(max == a)
{
if(max<=(b+c)) printf("Yes\n");
else printf("No\n");
}
else if(max == b)
{
if(max<=(a+c)) printf("Yes\n");
else printf("No\n");
}
else if(max == c)
{
if(max<=(b+a)) printf("Yes\n");
else printf("No\n");
}
}
return 0;
}
|
#include <iostream>
#include <vector>
#include <fstream>
#include <sstream>
#include <iomanip>
#include "PendingProcess.h"
#include "Scheduler.cpp"
vector<PendingProcess> readPendingProcessList(istream& in);
using namespace std;
int main() {
int seconds = 0;
int SIZE;
ifstream in;
in.open("pendingProcessList.csv"); // Open file
if (!in) { // Exit with an error massage if the file doesn't exist
cout << "ERROR - File failed to open. make sure that "
<< "the input file and this file are in the "
<< "same directory" << endl;
}
vector <PendingProcess> list = readPendingProcessList(in);
Scheduler obj;
for (PendingProcess& a : list) obj.add(a);
while (obj.empty())
{
cout << "Second " << ":" << obj.next() << endl;
seconds++;
}
in.close();
return 0;
}
vector<PendingProcess>readPendingProcessList(istream & in) {
string name;
int timeRemaining;
string line;
string token;
vector<PendingProcess> ProcessList;
while (getline(in, line)) {
// cout << line << endl;
size_t pos = line.find(",");
name = line.substr(0, pos);
//cout << name;
timeRemaining = stoi(line.substr(pos + 1));
//cout << timeRemaining;
PendingProcess proc(name, timeRemaining);
ProcessList.push_back(proc);
// cout << name << " " << timeRemaining;
}
return ProcessList;
}
|
/* -*- Mode: c++; tab-width: 4; c-basic-offset: 4 -*-
*
* Copyright (C) 1995-2010 Opera Software AS. All rights reserved.
*
* This file is part of the Opera web browser.
* It may not be distributed under any circumstances.
*
* Espen Sand
*/
#include "core/pch.h"
#include "modules/display/color.h"
#include "modules/display/styl_man.h"
#include "modules/hardcore/mem/mem_man.h"
#include "modules/libvega/src/oppainter/vegamdefont.h"
#include "modules/mdefont/mdefont.h"
#include "modules/pi/OpThreadTools.h"
#include "modules/prefsfile/prefsfile.h"
#include "modules/prefs/prefsmanager/collections/pc_files.h"
#include "modules/prefs/prefsmanager/collections/pc_unix.h"
#include "modules/skin/OpSkinManager.h"
#include "modules/url/protocols/commcleaner.h"
#include "adjunct/desktop_util/filelogger/desktopfilelogger.h"
#include "adjunct/desktop_util/boot/DesktopBootstrap.h"
#include "adjunct/desktop_util/resources/ResourceFolders.h"
#include "adjunct/desktop_util/resources/pi/opdesktopproduct.h"
#include "adjunct/quick/Application.h"
#include "adjunct/quick/dialogs/CrashLoggingDialog.h"
#include "adjunct/quick/managers/CommandLineManager.h"
#include "adjunct/widgetruntime/GadgetStartup.h"
#include "platforms/crashlog/crashlog.h" // InstallCrashSignalHandler()
#include "platforms/crashlog/gpu_info.h"
#include "platforms/posix/posix_file_util.h"
#include "platforms/posix/posix_native_util.h"
#include "platforms/posix/posix_logger.h"
#include "platforms/quix/commandline/StartupSettings.h"
#include "platforms/quix/skin/UnixWidgetPainter.h"
#include "platforms/quix/toolkits/ToolkitLoader.h"
#include "platforms/utilix/x11_all.h"
#include "platforms/unix/base/common/lirc.h"
#include "platforms/unix/base/common/sound/oss_audioplayer.h"
#include "platforms/unix/base/common/unixutils.h"
#include "platforms/unix/base/common/unix_gadgetutils.h"
#include "platforms/unix/base/common/unix_opsysteminfo.h"
#include "platforms/unix/base/x11/x11_globals.h"
#include "platforms/unix/base/x11/x11_ipcmanager.h"
#include "platforms/unix/base/x11/x11_nativedialog.h"
#include "platforms/unix/base/x11/x11_opmessageloop.h"
#include "platforms/unix/base/x11/x11_widget.h"
#include "platforms/unix/base/x11/x11prefhandler.h"
#include "platforms/unix/base/x11/x11utils.h"
#include <setjmp.h>
#include <signal.h>
#include <stdio.h>
#include <sys/types.h>
#include <pwd.h>
#ifndef POSSIBLY_UNUSED
// I'm hoping this will be added to core some day (e.g. hardcore/base/deprecate.h)...
#if defined(__GNUC__)
#define POSSIBLY_UNUSED(var) var __attribute__((unused))
#else
#define POSSIBLY_UNUSED(var) var
#endif
#endif
#ifdef CRASHLOG_CRASHLOGGER
extern GpuInfo* g_gpu_info;
GpuInfo the_gpu_info;
#endif
// Some flags set from command line used throughout UNIX code
StartupSettings g_startup_settings;
BOOL g_log_plugin = FALSE;
// Forced DPI value as set by user in opera6.ini
INT32 g_forced_dpi = 0;
// Change to g_plugin_wrapper_path
OpString8 g_motif_wrapper_path;
// Global for the memtools module
const char * g_executable;
/* Jump point for X11 error handling */
jmp_buf g_x11_error_recover;
// Indicate that crash dialog is active
BOOL g_is_crashdialog_active = FALSE;
#if defined(CDK_MODE_SUPPORT)
#include "adjunct/quick/windows/DocumentDesktopWindow.h"
CDKSettings g_cdk_settings;
#endif
#ifdef SELFTEST
# include "modules/selftest/optestsuite.h"
#endif
/**
* Set up signal handlers
*/
static void InitSignalHandling();
/**
* Handle graceful exit
*/
static void ExitSignal(int sig);
/**
* Handle X11 IO error
*/
static int X11IOErrorHandler(X11Types::Display* dpy);
/**
* Makes sure a SUDO user to not overwrite the
* normal ~/.opera directory
*/
static void ReassignSudoHOME();
/**
* Starts or stops POSIX logging
*/
static void StartPosixLogging();
static void StopPosixLogging();
static void DestroyPosixLogging();
/**
* Activates an existing Opera instance. Returns
* TRUE if opera should terminate after this call.
*/
static BOOL ScanForOperaInstance();
/**
* Returns the path and filename of the opera executable
*/
static OP_STATUS GetExecutablePath(const OpStringC8& candidate, OpString8& full_path);
/**
* Sets up wm class name and icon for the active opera mode
*/
static OP_STATUS PrepareWMClassInfo(X11Globals::WMClassInfo& info);
#ifdef CRASHLOG_CRASHLOGGER
class RecoveryParameters
{
public:
RecoveryParameters(): m_count(0), m_data(0), m_restart_index(-1) {}
~RecoveryParameters() { FreeData(); }
void FreeData()
{
if (m_data)
{
for(int i = 0; i < m_count; i++)
op_free(m_data[i]);
OP_DELETEA(m_data);
m_data = 0;
m_count = 0;
m_restart_index = -1;
}
}
void SetRestartFlag(BOOL set)
{
if (m_restart_index != -1)
{
char* text = op_strdup(set ? "continue" : "exit");
if (text)
{
op_free(m_data[m_restart_index]);
m_data[m_restart_index] = text;
}
}
}
void SetData(const char* executable_name, const OpVector<OpString8> & restart_arguments)
{
FreeData();
m_count = restart_arguments.GetCount() + 8;
m_data = OP_NEWA(char*, m_count);
if (!m_data)
return;
int i = 0;
m_data[i++] = op_strdup(executable_name);
m_data[i++] = op_strdup("-crashlog");
char buf[32];
int POSSIBLY_UNUSED(bufused);
bufused = snprintf(buf, sizeof(buf), "%d", getpid());
OP_ASSERT(bufused < sizeof(buf));
m_data[i++] = op_strdup(buf);
m_data[i++] = op_strdup("-crashaction");
m_restart_index = i;
m_data[i++] = op_strdup("continue");
m_data[i++] = op_strdup("-crashlog-gpuinfo");
OP_ASSERT(sizeof(UINTPTR) <= sizeof(unsigned long));
bufused = snprintf(buf, sizeof(buf), "%#lx", static_cast<unsigned long>(reinterpret_cast<UINTPTR>(g_gpu_info)));
OP_ASSERT(bufused < sizeof(buf));
m_data[i++] = op_strdup(buf);
for (UINT32 j = 0; j < restart_arguments.GetCount(); j++)
m_data[i++] = op_strdup(restart_arguments.Get(j)->CStr());
m_data[i++] = 0;
}
char** data() const { return m_data; }
private:
int m_count;
char** m_data;
int m_restart_index;
};
RecoveryParameters recovery_parameters;
#endif // CRASHLOG_CRASHLOGGER
// Global function. Avoid if-defs elsewhere in code
void SetCrashlogRestart(BOOL state)
{
#ifdef CRASHLOG_CRASHLOGGER
recovery_parameters.SetRestartFlag(state);
#endif
}
int main_contentL(int argc, char **argv)
{
#ifdef POSIX_CAP_LOCALE_INIT
PosixModule::InitLocale();
#else
setlocale(LC_CTYPE, "");
#endif
g_executable = argv[0]; // TODO - Get rid of this
GetExecutablePath(argv[0], g_startup_settings.our_binary);
// Prevent a SUDO version use a regular user's ~/.opera directory
ReassignSudoHOME();
// Get startup settings from environment variables (will be overriden by the command line)
OpStatus::Ignore(g_startup_settings.share_dir.Set(op_getenv("OPERA_DIR")));
OpStatus::Ignore(g_startup_settings.binary_dir.Set(op_getenv("OPERA_BINARYDIR")));
OpStatus::Ignore(g_startup_settings.personal_dir.Set(op_getenv("OPERA_PERSONALDIR")));
OpStatus::Ignore(g_startup_settings.temp_dir.Set(op_getenv("TMPDIR")));
// Do argument processing
if (OpStatus::IsError(CommandLineManager::GetInstance()->Init()))
return 1;
if (OpStatus::IsError(CommandLineManager::GetInstance()->ParseArguments(argc, argv)))
return 0;
// Show command line help
if (CommandLineManager::GetInstance()->GetArgument(CommandLineManager::Version))
{
X11Globals::ShowOperaVersion(FALSE, FALSE, 0);
return 0;
}
if (CommandLineManager::GetInstance()->GetArgument(CommandLineManager::WatirTest))
{
CommandLineArgument* cmd_arg = CommandLineManager::GetInstance()->GetArgument(CommandLineManager::PersonalDirectory);
// OPERA_PERSONALDIR is ignored in WatirTest mode, so if personal_dir was not set from -pd, we disregard it
if (!cmd_arg)
g_startup_settings.personal_dir.Empty();
}
OP_PROFILE_INIT(); // Call OP_PROFILE_EXIT() on each return or at end
#ifdef CRASHLOG_CRASHLOGGER
// Must be set before calling recovery_parameters.SetData()
g_gpu_info = &the_gpu_info;
// Set restart arguments for crash recovery
recovery_parameters.SetData(g_startup_settings.our_binary, CommandLineManager::GetInstance()->GetRestartArguments());
g_crash_recovery_parameters = recovery_parameters.data();
// And disable HW acceleration if we are currently doing crash recovery
if (CommandLineManager::GetInstance()->GetArgument(CommandLineManager::CrashLog))
g_desktop_bootstrap->DisableHWAcceleration();
#endif // CRASHLOG_CRASHLOGGER
// Save profile directory (the personal directory) to $OPERA_HOME if set on the command line
// or by $OPERA_PERSONALDIR. The resource code will later read $OPERA_HOME or use a fallback
// (~/.opera) if it has not been set.
OpString opera_home_path;
CommandLineArgument* cmd_arg = CommandLineManager::GetInstance()->GetArgument(CommandLineManager::PersonalDirectory);
if( cmd_arg && cmd_arg->m_string_value.HasContent() )
{
opera_home_path.SetL(cmd_arg->m_string_value);
}
else
{
opera_home_path.SetL(op_getenv("OPERA_PERSONALDIR"));
}
opera_home_path.Strip();
if (opera_home_path.HasContent())
{
char tmp[_MAX_PATH+1];
if (OpStatus::IsError(PosixFileUtil::FullPath(opera_home_path.CStr(), tmp)) ||
OpStatus::IsError(PosixNativeUtil::FromNative(tmp, &opera_home_path)))
{
PosixNativeUtil::NativeString path(opera_home_path.CStr());
printf("opera: Failed to set up profile (personal) directory : %s\n", path.get() ? path.get() : "<NULL>");
OP_PROFILE_EXIT();
return 1;
}
g_env.Set("OPERA_HOME", opera_home_path.CStr());
}
if (OpStatus::IsError(X11Globals::Create()))
{
OP_PROFILE_EXIT();
return -1;
}
// Catch signals
InitSignalHandling();
{
OP_PROFILE_METHOD("Preferences pre-setup");
if (OpStatus::IsError(g_desktop_bootstrap->Init()))
{
OP_PROFILE_EXIT();
return -1;
}
}
// Change permission for personal folder (~/.opera) to 0700 (accessible only for owner
// The directory will be created from g_desktop_bootstrap->Init() above if it does not
// already exists.
if (!access(g_startup_settings.personal_dir.CStr(), F_OK))
chmod(g_startup_settings.personal_dir.CStr(), 0700);
// Directories specified through the environment rather than on the command line need to be stored for correct restarting
if (!CommandLineManager::GetInstance()->GetArgument(CommandLineManager::ShareDirectory) && op_getenv("OPERA_DIR"))
RETURN_VALUE_IF_ERROR(CommandLineManager::GetInstance()->AddRestartArgument(CommandLineManager::ShareDirectory, g_startup_settings.share_dir.CStr()), -1);
if (!CommandLineManager::GetInstance()->GetArgument(CommandLineManager::BinaryDirectory) && op_getenv("OPERA_BINARYDIR"))
RETURN_VALUE_IF_ERROR(CommandLineManager::GetInstance()->AddRestartArgument(CommandLineManager::BinaryDirectory, g_startup_settings.binary_dir.CStr()), -1);
if (!CommandLineManager::GetInstance()->GetArgument(CommandLineManager::PersonalDirectory) && op_getenv("OPERA_PERSONALDIR"))
RETURN_VALUE_IF_ERROR(CommandLineManager::GetInstance()->AddRestartArgument(CommandLineManager::PersonalDirectory, g_startup_settings.personal_dir.CStr()), -1);
// Set environment variables for prefsfile substitutions and child processes
g_env.Set("OPERA_DIR", g_startup_settings.share_dir.CStr());
g_env.Set("OPERA_BINARYDIR", g_startup_settings.binary_dir.CStr());
g_env.Set("OPERA_PERSONALDIR", g_startup_settings.personal_dir.CStr());
g_env.Set("OPERA_HOME", g_startup_settings.personal_dir.CStr()); // For compatibility
// Create and/or clean up temp dir
OpString temp_dir;
RETURN_VALUE_IF_ERROR(PosixNativeUtil::FromNative(g_startup_settings.temp_dir, &temp_dir), -1);
RETURN_VALUE_IF_ERROR(UnixUtils::CleanUpFolder(temp_dir), -1);
#if defined(_DEBUG)
// Make life simpler for developers #1: Set toolkit automatially using the personal dir path
// Examples: -pd <dir>/x11 -pd kde
{
struct
{
const char* name;
int toolkit;
} probe[]=
{
{"gtk/", 2},
{"kde/", 3},
{"x11/", 4},
{0, 0}
};
OpString8 tmp;
tmp.Set(g_startup_settings.personal_dir);
int length = tmp.Length();
for (int i=0; probe[i].name; i++)
{
int l = strlen(probe[i].name);
if (l <= length)
{
int pos = tmp.Find(probe[i].name, length-l);
if (pos != KNotFound)
{
PrefsFile* pf = g_desktop_bootstrap->GetInitInfo()->prefs_reader;
pf->WriteIntL("File Selector", "Dialog Toolkit", probe[i].toolkit);
break;
}
}
}
}
# if defined(__linux__)
if (!g_startup_settings.do_grab)
{
// Make life simpler for developers #2: Automatically set -nograb if gdb is controlling the process
OpString path;
OpFile file;
if (OpStatus::IsSuccess(path.AppendFormat(UNI_L("/proc/%d/cmdline"), getppid())) &&
OpStatus::IsSuccess(file.Construct(path)) &&
OpStatus::IsSuccess(file.Open(OPFILE_READ)))
{
char val;
OpString8 buf;
OpFileLength num_read;
// We are only interested in the first argument. Each argument in the command line is zero-terminated,
// so read until the first 0 byte.
while (OpStatus::IsSuccess(file.Read(&val, 1, &num_read)) && num_read > 0 && val)
{
if (val == '/')
buf.Empty();
else
buf.Append(&val, 1);
}
if (!buf.Compare("gdb") )
{
X11Widget::DisableGrab(true);
printf("opera: '-nograb' automatically applied. Use '-dograb' to override\n");
}
}
}
# endif // linux
#endif
// Test for lock file
OpString lock_file_name;
ResourceFolders::GetFolder(OPFILE_USERPREFS_FOLDER, g_desktop_bootstrap->GetInitInfo(), lock_file_name);
lock_file_name.AppendL(UNI_L("lock"));
BOOL found_locked_file = UnixUtils::LockFile(lock_file_name, 0) == 0;
if (found_locked_file)
{
// Look for a running instance. If found, we will activate it and exit
if (ScanForOperaInstance())
{
OP_PROFILE_EXIT();
return 0;
}
// Ask user what to do. There might be a process that is about to exit at this
// stage, so perhaps we want to test for that and give user some information
OpString8 tmp;
tmp.Set(lock_file_name);
OpString8 message;
message.AppendFormat(
"It appears another Opera instance is using the same configuration directory because its "
"lock file is active:\n\n%s\n\nDo you want "
"to start Opera anyway?", tmp.CStr());
X11NativeDialog::DialogResult res = X11NativeDialog::ShowTwoButtonDialog("Opera", message.CStr(), "Yes", "No");
if (res == X11NativeDialog::REP_NO)
{
OP_PROFILE_EXIT();
return 0;
}
}
PrefsFile* pf = g_desktop_bootstrap->GetInitInfo()->prefs_reader;
/* This value is used in UnixDefaultStyle::GetSystemFont(), which is called
before the UNIX prefs are read. */
g_forced_dpi = pf->ReadIntL("User Prefs", "Force DPI", 0);
// Bug #DSK-249843 [espen 2009-03-26]
// Common resources code will set OPFILE_LANGUAGE_FOLDER to the language
// prefix directory (ie. "en") and parent folder to the locale directory that
// contains all the prefix directories.
// If "Language Files Directory" contains a string, then the prefs code that
// reads it assumes it contains the full path to the correct prefix directory
// (including the prefix directory) and fill OPFILE_LANGUAGE_FOLDER with it
// overriding common resources.
// In OpPrefsFileLanguageManager::LoadL() this path is the fallback if the
// "Language File" string has not been set (only set from Prefs dialog)
//
// Older versions of opera sat "Language Files Directory" to point to
// the locale directory (not including the prefix). That setting combined
// with common resources do not match, and we do not really need it. Opera will
// exit if the fallback is wrong and "Language File" is not set so we
// reset the "Language Files Directory" here and let common resources code decide.
pf->WriteStringL("User Prefs", "Language Files Directory", UNI_L(""));
// Preferences loaded. Now we test if we are in a crash recovery mode and do not want to use it.
if (CommandLineManager::GetInstance()->GetArgument(CommandLineManager::CrashLog))
{
BOOL show_dialog = pf->ReadIntL("User Prefs", "Show Crash Log Upload Dialog", TRUE);
if (!show_dialog)
{
OP_PROFILE_EXIT();
return 0;
}
}
{
OP_PROFILE_METHOD("Font initialization");
if (OpStatus::IsError(MDF_InitFont()))
{
fprintf(stderr, "opera: Failed to set up fonts.\n");
return 0;
}
}
g_desktop_bootstrap->GetInitInfo()->prefs_reader = pf;
{
OP_PROFILE_MSG("Initializing core starting");
OP_PROFILE_METHOD("Init core completed");
TRAPD(core_err, g_opera->InitL(*g_desktop_bootstrap->GetInitInfo()));
if (OpStatus::IsError(core_err))
{
fprintf(stderr, "opera: Failed to set up core.\n");
OP_PROFILE_EXIT();
return -1;
}
}
// Initialize the message loop (must happen after initializing core)
if (OpStatus::IsError(X11OpMessageLoop::Self()->Init()))
{
fprintf(stderr, "opera: Failed to set up the message loop.\n");
OP_PROFILE_EXIT();
return -1;
}
// Let skin manager erase to toolkit base color instead of default color (0xFFC0C0C0)
UINT32 bg = g_op_ui_info->GetSystemColor(OP_SYSTEM_COLOR_UI_BACKGROUND);
UINT32 c = 0xFF000000 | (OP_GET_R_VALUE(bg) << 16) | (OP_GET_G_VALUE(bg) << 8) | OP_GET_B_VALUE(bg);
g_skin_manager->SetTransparentBackgroundColor(c);
// Prepare window class. Should be available for all sort of windows
X11Globals::WMClassInfo info;
if (OpStatus::IsError(PrepareWMClassInfo(info)) || OpStatus::IsError(g_x11->SetWMClassInfo(info)))
{
OP_PROFILE_EXIT();
return -1;
}
if (CommandLineManager::GetInstance()->GetArgument(CommandLineManager::FullVersion))
{
X11Globals::ShowOperaVersion(TRUE, FALSE, 0);
OP_PROFILE_EXIT();
return 0;
}
// Some window managers will provide startup feedback.
g_x11->NotifyStartupBegin(g_x11->GetDefaultScreen());
// Setup widget painter, has to be done after startup because quix starts before skin
// Note: The widget painter manager takes ownership (see QuixModule::Destroy())
if (g_unix_widget_painter)
g_widgetpaintermanager->SetPrimaryWidgetPainter(g_unix_widget_painter);
// Start logging in posix code
StartPosixLogging();
#ifdef SELFTEST
// Note: Might modify argc and argv
SELFTEST_MAIN( &argc, argv );
#endif
UpdateX11FromPrefs();
if (!CommandLineManager::GetInstance()->GetArgument(CommandLineManager::NoLIRC))
Lirc::Create();
g_audio_player = OP_NEW(OssAudioPlayer, ());
if (g_audio_player)
{
g_audio_player->SetAutoCloseDevice(true);
}
// This creates the Application object
if (OpStatus::IsError(g_desktop_bootstrap->Boot()))
{
fprintf(stderr, "opera: Failed to set up the application.\n");
OP_PROFILE_EXIT();
return -1;
}
#ifdef CRASHLOG_CRASHLOGGER
// Show crash dialog we we got a crashlog option on startup
if (CommandLineManager::GetInstance()->GetArgument(CommandLineManager::CrashLog))
{
BOOL restart = FALSE;
BOOL minimal_restart = FALSE;
OpStringC filename(CommandLineManager::GetInstance()->GetArgument(CommandLineManager::CrashLog)->m_string_value);
g_is_crashdialog_active = TRUE;
CrashLoggingDialog* dialog = new CrashLoggingDialog(filename, restart, minimal_restart);
if (dialog)
{
dialog->Init(0);
}
if (!restart)
{
g_desktop_bootstrap->ShutDown();
return 0;
}
if (!minimal_restart)
{
/* This depends on -crashlog causing hardware acceleration
* to be disabled, as well as the crashlog dialog setting
* up the rest of a minimal restart. In that case, we can
* just continue here in order to have our minimal
* restart.
*
* On the other hand, if we don't want a minimal restart,
* we'll just shut down this copy of opera and start a new
* one without the -crashlog arguments. That should give
* us a "normal" startup, which is surely exactly what we
* want.
*/
g_desktop_bootstrap->ShutDown();
// Skip the crashlog arguments for the restart.
OP_ASSERT(op_strcmp(g_crash_recovery_parameters[1], "-crashlog") == 0);
OP_ASSERT(op_strcmp(g_crash_recovery_parameters[3], "-crashaction") == 0);
int drop = 4;
if (op_strcmp(g_crash_recovery_parameters[5], "-crashlog-gpuinfo") == 0)
drop += 2;
g_crash_recovery_parameters[drop] = g_crash_recovery_parameters[0];
execv(g_crash_recovery_parameters[0], g_crash_recovery_parameters + drop);
return 0;
}
/* We have shown the dialog. Now enable crash logging */
InstallCrashSignalHandler();
}
#endif // CRASHLOG_CRASHLOGGER
g_is_crashdialog_active = FALSE;
Application::StartupSetting setting;
CommandLineManager* clm = CommandLineManager::GetInstance();
setting.open_in_background = clm->GetArgument(CommandLineManager::BackgroundTab) != 0;
setting.open_in_new_page = clm->GetArgument(CommandLineManager::NewTab) != 0;
setting.open_in_new_window = clm->GetArgument(CommandLineManager::NewWindow) != 0;
setting.fullscreen = clm->GetArgument(CommandLineManager::Fullscreen) != 0;
setting.iconic = FALSE;
CommandLineArgument* arg = clm->GetArgument(CommandLineManager::Geometry);
if (arg)
{
OpString8 tmp;
tmp.Set(arg->m_string_value);
setting.geometry = X11Utils::ParseGeometry(tmp);
}
g_application->SetStartupSetting(setting);
g_main_message_handler->PostMessage(MSG_QUICK_APPLICATION_START, 0, 0);
CommCleaner *cleaner = OP_NEW(CommCleaner, ());
if( !cleaner )
{
fputs("opera: Could not allocate comm. cleaner.\n", stderr);
OP_PROFILE_EXIT();
return -1;
}
cleaner->ConstructL();
if (setjmp(g_x11_error_recover) == 0)
{
XSetIOErrorHandler(X11IOErrorHandler);
X11OpMessageLoop::Self()->MainLoop();
}
// Stop logging in posix code
StopPosixLogging();
OP_DELETE(cleaner);
cleaner = 0;
g_desktop_bootstrap->ShutDown();
Lirc::Destroy();
{
OP_PROFILE_MSG("Destroying core starting");
OP_PROFILE_METHOD("Destroying core completed");
g_opera->Destroy();
}
MDF_ShutdownFont();
OP_DELETE(g_audio_player);
g_audio_player = 0;
// Destroy loggers
DestroyPosixLogging();
X11Globals::Destroy();
ToolkitLoader::Destroy();
// Remove temp dir
RETURN_VALUE_IF_ERROR(UnixUtils::CleanUpFolder(temp_dir), -1);
OP_PROFILE_EXIT();
return 0;
}
static void ExitSignal(int sig)
{
// Only do this once
static BOOL been_here = FALSE;
if (been_here || (g_application && g_application->IsExiting()) )
return;
been_here = TRUE;
if (!g_thread_tools)
{
exit(0);
return;
}
OpInputAction* action = OP_NEW(OpInputAction, (OpInputAction::ACTION_EXIT));
if (!action) return;
action->SetActionData(1);
g_thread_tools->PostMessageToMainThread(MSG_QUICK_DELAYED_ACTION, reinterpret_cast<MH_PARAM_1>(action), 0);
}
static void HandleSIGCHLD(int sig)
{
X11OpMessageLoop::ReceivedSIGCHLD();
}
static void InitSignalHandling()
{
BOOL failed = FALSE;
/* Setting signal(SIGCHLD, SIG_IGN) is a special operation that makes sure
* child processes get reaped (by the system) when they die, avoiding
* zombie processes and the need for us to clean them up.
*
* Unfortunately, Some libraries install their own SIGCHLD
* handlers. In particular, Qt needs to have its SIGCHLD handler
* triggered or it will hang when spawning subprocesses. Which
* happens when KDE starts up its messaging subsystem (DSK-295272,
* DSK-370690). Qt will chain-call the previously installed
* SIGCHLD handler, but Qt will not reap any zombies except for
* its own.
*
* So we must deal with SIGCHLD ourselves.
*/
/* TODO: We should do all signal handling through the posix
* module. Global state sucks.
*/
if (signal(SIGCHLD, HandleSIGCHLD) == SIG_ERR) failed = TRUE;
if (signal(SIGHUP, SIG_IGN) == SIG_ERR) failed = TRUE; // DSK-344521
if (signal(SIGINT, ExitSignal) == SIG_ERR) failed = TRUE;
if (signal(SIGTERM, ExitSignal) == SIG_ERR) failed = TRUE;
if (failed)
{
printf("opera: Error when enabling signal handling.\n");
}
}
static int X11IOErrorHandler(X11Types::Display* dpy)
{
longjmp(g_x11_error_recover, 1);
return 0;
}
static void ReassignSudoHOME()
{
if( getuid() == 0 )
{
/* Fix for running opera with sudo. The $HOME will not be changed and
* we risk overwriting files in ~/.opera/ with root rw-permissions
* making them unusable later. Note: This will not fix the problem if
* the user is using a custom personaldir */
setpwent();
for( passwd* pw=getpwent(); pw; pw=getpwent() )
{
if( pw->pw_uid == 0 )
{
// Try to prevent to print message if not necessary.
const char* env = op_getenv("HOME");
if( !env || strncmp(env, pw->pw_dir, 5) )
{
printf("opera: $HOME set to %s. Use -personaldir if you do not want to use %s/.opera/\n",
pw->pw_dir, pw->pw_dir);
}
g_env.Set("HOME", pw->pw_dir);
break;
}
}
endpwent();
}
}
static void StartPosixLogging()
{
if (g_startup_settings.posix_dns_logger)
g_posix_log_boss->Set(PosixLogger::DNS, g_startup_settings.posix_dns_logger);
if (g_startup_settings.posix_socket_logger)
g_posix_log_boss->Set(PosixLogger::SOCKET, g_startup_settings.posix_socket_logger);
if (g_startup_settings.posix_file_logger)
g_posix_log_boss->Set(PosixLogger::STREAM, g_startup_settings.posix_file_logger);
if (g_startup_settings.posix_async_logger)
g_posix_log_boss->Set(PosixLogger::ASYNC, g_startup_settings.posix_async_logger);
}
static void StopPosixLogging()
{
g_posix_log_boss->Set(PosixLogger::DNS, 0);
g_posix_log_boss->Set(PosixLogger::SOCKET, 0);
g_posix_log_boss->Set(PosixLogger::STREAM, 0);
g_posix_log_boss->Set(PosixLogger::ASYNC, 0);
}
static void DestroyPosixLogging()
{
OP_DELETE(g_startup_settings.posix_dns_logger);
g_startup_settings.posix_dns_logger = 0;
OP_DELETE(g_startup_settings.posix_socket_logger);
g_startup_settings.posix_socket_logger = 0;
OP_DELETE(g_startup_settings.posix_file_logger);
g_startup_settings.posix_file_logger = 0;
OP_DELETE(g_startup_settings.posix_async_logger);
g_startup_settings.posix_async_logger = 0;
}
static BOOL ScanForOperaInstance()
{
CommandLineManager* clm = CommandLineManager::GetInstance();
CommandLineArgument* arg;
X11Types::Window requested_window = None;
arg = clm->GetArgument(CommandLineManager::WindowId);
if (arg)
{
errno = 0;
uni_char* endptr = 0;
requested_window = uni_strtol(arg->m_string_value.CStr(), &endptr, 0);
if( errno != 0 || (endptr && *endptr ) )
requested_window = None;
}
arg = clm->GetArgument(CommandLineManager::WindowName);
X11IPCManager::ErrorCode error;
OpString name;
name.Set("first");
X11Types::Window win = X11IPCManager::FindOperaWindow(requested_window, arg ? arg->m_string_value.CStr() : name.CStr(), error);
if (win == None)
{
// Terminate if we have requested a special window and could not find it
return requested_window ? TRUE : FALSE;
}
BOOL ok = FALSE;
if (CommandLineManager::GetInstance()->GetArgument(CommandLineManager::FullVersion))
{
OpString cmd;
cmd.Set("version()");
ok = X11IPCManager::Set(win, cmd);
}
else if (clm->GetArgument(CommandLineManager::Remote))
{
arg = clm->GetArgument(CommandLineManager::Remote);
ok = X11IPCManager::Set(win, arg->m_string_value);
}
else if (clm->GetUrls()->GetCount() > 0)
{
for (UINT32 i=0; i<clm->GetUrls()->GetCount(); i++)
{
OpString* url = clm->GetUrls()->Get(i);
if (!url || url->Length() == 0)
{
continue;
}
OpString cmd;
if (clm->GetArgument(CommandLineManager::ActiveTab))
{
cmd.AppendFormat(UNI_L("openURL(%s"), url->CStr());
}
else if (clm->GetArgument(CommandLineManager::NewTab))
{
cmd.AppendFormat(UNI_L("openURL(%s,new-tab"), url->CStr());
}
else if (clm->GetArgument(CommandLineManager::NewPrivateTab))
{
cmd.AppendFormat(UNI_L("openURL(%s,new-private-tab"), url->CStr());
}
else if (clm->GetArgument(CommandLineManager::NewWindow))
{
cmd.AppendFormat(UNI_L("openURL(%s,new-window"), url->CStr());
arg = clm->GetArgument(CommandLineManager::WindowName);
if (arg)
{
cmd.AppendFormat(UNI_L(",N=%s"), arg->m_string_value.CStr());
}
arg = clm->GetArgument(CommandLineManager::Geometry);
if (arg)
{
cmd.AppendFormat(UNI_L(",G=%s"), arg->m_string_value.CStr());
}
}
else if (clm->GetArgument(CommandLineManager::BackgroundTab))
{
cmd.AppendFormat(UNI_L("openURL(%s,background-tab"), url->CStr());
}
else
{
cmd.AppendFormat(UNI_L("openURL(%s,new-tab"), url->CStr());
}
if (clm->GetArgument(CommandLineManager::NoRaise))
{
cmd.AppendFormat(UNI_L(",noraise"));
}
cmd.Append(UNI_L(")"));
ok = X11IPCManager::Set(win, cmd);
}
}
else if (clm->GetArgument(CommandLineManager::NewTab) ||
clm->GetArgument(CommandLineManager::NewPrivateTab) ||
clm->GetArgument(CommandLineManager::NewWindow) ||
clm->GetArgument(CommandLineManager::BackgroundTab))
{
OpString cmd;
if (clm->GetArgument(CommandLineManager::NewTab))
{
cmd.Set(UNI_L("newInstance(new-tab"));
}
else if (clm->GetArgument(CommandLineManager::NewPrivateTab))
{
cmd.Set(UNI_L("newInstance(new-private-tab"));
}
else if (clm->GetArgument(CommandLineManager::NewWindow))
{
cmd.Set(UNI_L("newInstance(new-window"));
arg = clm->GetArgument(CommandLineManager::WindowName);
if (arg)
{
cmd.AppendFormat(UNI_L(",N=%s"), arg->m_string_value.CStr());
}
arg = clm->GetArgument(CommandLineManager::Geometry);
if (arg)
{
cmd.AppendFormat(UNI_L(",G=%s"), arg->m_string_value.CStr());
}
}
else if (clm->GetArgument(CommandLineManager::BackgroundTab))
{
cmd.Set("newInstance(background-tab");
}
if (clm->GetArgument(CommandLineManager::NoRaise))
{
cmd.AppendFormat(UNI_L(",noraise"));
}
cmd.Append(UNI_L(")"));
ok = X11IPCManager::Set(win, cmd);
}
else
{
OpString cmd;
#ifdef GADGET_SUPPORT
if(!GadgetStartup::IsBrowserStartupRequested())
{
cmd.Set(UNI_L("raise()"));
}
else
#endif // GADGET_SUPPORT
{
int sdi;
PrefsFile* pf = g_desktop_bootstrap->GetInitInfo()->prefs_reader;
TRAPD(rc, sdi = pf->ReadIntL("User Prefs", "SDI", 0));
if (OpStatus::IsSuccess(rc) && sdi)
cmd.Set(UNI_L("newInstance(new-window"));
else
cmd.Set(UNI_L("newInstance(new-tab"));
if (clm->GetArgument(CommandLineManager::NoRaise))
{
cmd.AppendFormat(UNI_L(",noraise"));
}
cmd.Append(UNI_L(")"));
}
ok = X11IPCManager::Set(win, cmd);
}
if (ok)
printf("opera: Activated running instance\n");
return ok;
}
static OP_STATUS GetExecutablePath(const OpStringC8& candidate, OpString8& full_path)
{
if (candidate.IsEmpty())
return OpStatus::ERR;
OpString8 buf;
int pos = candidate.Find("/");
if (pos != KNotFound)
{
if (pos == 0)
RETURN_IF_ERROR(buf.Set(candidate));
else
{
if (!buf.Reserve(4096+candidate.Length()+1))
return OpStatus::ERR_NO_MEMORY;
if (!getcwd(buf.CStr(), 4096))
return OpStatus::ERR;
RETURN_IF_ERROR(buf.AppendFormat("/%s",candidate.CStr()));
}
}
else
{
// Single name. Try to match it in the PATH
OpString8 path;
RETURN_IF_ERROR(path.Set(op_getenv("PATH")));
if (path.HasContent())
{
char* p = strtok(path.CStr(), ":");
while (p)
{
OpString8 tmp;
RETURN_IF_ERROR(tmp.AppendFormat("%s/%s", p, candidate.CStr()));
if (tmp.HasContent() && access(tmp.CStr(), X_OK) == 0)
{
RETURN_IF_ERROR(buf.Set(tmp));
break;
}
p = strtok(0, ":");
}
}
}
if (buf.HasContent())
{
// UnixUtils::CanonicalPath() uses 16 bit so we have to convert to and from.
// We will not loose any data, but it takes more time than nesessary
OpString tmp;
RETURN_IF_ERROR(tmp.Set(buf));
UnixUtils::CanonicalPath(tmp);
return full_path.Set(tmp);
}
else
{
return OpStatus::OK; // Use candidate as is
}
}
static OP_STATUS PrepareWMClassInfo(X11Globals::WMClassInfo& info)
{
if (GadgetStartup::IsGadgetStartupRequested())
{
if (g_desktop_product->GetProductType() == PRODUCT_TYPE_OPERA_NEXT)
{
info.id = X11Globals::OperaNextWidget;
RETURN_IF_ERROR(info.name.Set("OperaNextWidget"));
RETURN_IF_ERROR(info.icon.Set("opera-browser"));
}
else
{
info.id = X11Globals::OperaWidget;
RETURN_IF_ERROR(info.name.Set("OperaWidget"));
RETURN_IF_ERROR(info.icon.Set("opera-browser"));
}
// Append widget name
OpString filename;
GadgetStartup::GetRequestedGadgetFilePath(filename);
if (filename.HasContent())
{
OpString name;
if (OpStatus::IsSuccess(UnixGadgetUtils::GetWidgetName(filename, name)))
{
OpString8 buffer;
int length = name.Length();
if (length > 0 && buffer.Reserve(length+1))
{
char* p = buffer.CStr();
for (int i=0; i<length; i++)
{
int ch = name[i];
if(ch >= 'a' && ch <= 'z' || ch >= 'A' && ch <= 'Z' || ch >= '0' && ch <= '9')
*p++ = ch;
}
*p = 0;
}
RETURN_IF_ERROR(info.name.Append(buffer));
}
// Clamp string. 64 is enough
if (info.name.Length() > 64)
info.name.Delete(64);
}
}
else // Browser
{
if (g_desktop_product->GetProductType() == PRODUCT_TYPE_OPERA_NEXT)
{
info.id = X11Globals::OperaNextBrowser;
RETURN_IF_ERROR(info.name.Set("OperaNext"));
RETURN_IF_ERROR(info.icon.Set("opera-next"));
}
else
{
info.id = X11Globals::OperaBrowser;
RETURN_IF_ERROR(info.name.Set("Opera"));
RETURN_IF_ERROR(info.icon.Set("opera-browser"));
}
}
return OpStatus::OK;
}
|
/* -*- Mode: c++; tab-width: 4; indent-tabs-mode: t; c-basic-offset: 4 -*-
*
* Copyright (C) 1995-2009 Opera Software AS. All rights reserved.
*
* This file is part of the Opera web browser. It may not be distributed
* under any circumstances.
*/
#ifndef COCOA_FILECHOOSER_H
#define COCOA_FILECHOOSER_H
#include "adjunct/desktop_pi/desktop_file_chooser.h"
class CocoaFileChooser : public DesktopFileChooser
{
public:
CocoaFileChooser();
~CocoaFileChooser();
virtual OP_STATUS Execute(OpWindow* parent, DesktopFileChooserListener* listener, const DesktopFileChooserRequest& request);
virtual void Cancel();
static bool HandlingCutCopyPaste();
static void Cut();
static void Copy();
static void Paste();
static void SelectAll();
};
#endif
|
#include "pwm_class.h"
#define PWM_CHANNEL 0
#include "pin.h"
#include "bcm2835.h"
// This controls the max range of the PWM signal
#define RANGE 1024
PWM_CLASS::PWM_CLASS(int factor_umplere ,int frecventa)
{
this->frecventa=frecventa;
this->factor_umplere=frecventa * factor_umplere/100;
bcm2835_pwm_set_clock(BCM2835_PWM_CLOCK_DIVIDER_16);
bcm2835_pwm_set_mode(PWM_CHANNEL, 1, 1);
bcm2835_pwm_set_range(PWM_CHANNEL, RANGE);
bcm2835_pwm_set_data(PWM_CHANNEL, this->factor_umplere);
}
void PWM_CLASS::set (int factor_umplere, int frecventa){
this->frecventa=frecventa;
this->factor_umplere=frecventa * factor_umplere/100;
bcm2835_pwm_set_range(PWM_CHANNEL, RANGE);
bcm2835_pwm_set_data(PWM_CHANNEL, this->factor_umplere);
}
int PWM_CLASS::getDutyCycle(){
return this->factor_umplere * 100 / this->frecventa;
}
int PWM_CLASS::getFrequency(){
return this->frecventa;
}
|
#include <iostream>
#include <sstream>
#include <vector>
#include <list>
#include <queue>
#include <algorithm>
#include <iomanip>
#include <map>
#include <unordered_map>
#include <string>
#include <cstdio>
#include <cstring>
#include <climits>
using namespace std;
struct student {
string name, id;
int grade;
student(){}
student(string n, string i, int g):name(n), id(i), grade(g){}
bool operator<(const student& b) const {
return grade < b.grade;
}
};
int main() {
int n;
cin >> n;
vector<student> m, f;
string name, id;
char sex;
int grade;
while (n--) {
cin >> name >> sex >> id >> grade;
if (sex == 'M') m.push_back(student(name, id, grade));
else f.push_back(student(name, id, grade));
}
sort(m.begin(), m.end());
sort(f.begin(), f.end());
if (f.empty()) cout << "Absent" << endl;
else cout << f.rbegin()->name << ' ' << f.rbegin()->id << endl;
if (m.empty()) cout << "Absent" << endl;
else cout << m.begin()->name << ' ' << m.begin()->id << endl;
if (!f.empty() && !m.empty()) {
cout << f.rbegin()->grade - m.begin()->grade << endl;
}
else cout << "NA" << endl;
return 0;
}
|
//
// Created by Tanguy on 28/11/2017.
//
#ifndef MEDIATORPROJECT_AGENT_HPP
#define MEDIATORPROJECT_AGENT_HPP
#include <memory>
#include "IMediator.hpp"
#include "MediatorPacket.hpp"
class Agent {
std::string name;
std::shared_ptr<IMediator> mediator;
public:
Agent(std::string const& _name, std::shared_ptr<IMediator> _mediator):
name(_name), mediator(_mediator) {};
~Agent() = default;
std::shared_ptr<IMediator> &getMediator() {return mediator;};
void sendPacket(std::string const& _mediatorPacket) {
MediatorPacket mediatorPacket(_mediatorPacket);
mediator->addMediatorPacket(mediatorPacket);
};
};
#endif //MEDIATORPROJECT_AGENT_HPP
|
/* -*- Mode: c++; tab-width: 4; indent-tabs-mode: t; c-basic-offset: 4 -*-
*
* Copyright (C) 1995-2007 Opera Software AS. All rights reserved.
*
* This file is part of the Opera web browser.
* It may not be distributed under any circumstances.
*/
#ifndef OP_TREE_VIEW_H
#define OP_TREE_VIEW_H
#include "modules/pi/OpDragManager.h"
#include "modules/util/adt/oplisteners.h"
#include "modules/widgets/OpWidget.h"
#include "modules/widgets/AutoCompletePopup.h"
#include "adjunct/desktop_scope/src/scope_widget_info.h"
#include "adjunct/desktop_util/adt/opsortedvector.h"
#include "adjunct/desktop_util/treemodel/optreemodel.h"
#include "adjunct/quick_toolkit/widgets/OpTreeView/TreeViewModel.h"
#include "adjunct/quick_toolkit/widgets/OpTreeView/LineToItemMap.h"
#include "adjunct/quick_toolkit/widgets/OpTreeView/OpTreeViewListener.h"
class TreeViewModelItem;
class ItemDrawArea;
class ColumnListAccessor;
class Edit;
/***********************************************************************************
**
** OpTreeView
**
***********************************************************************************/
class OpTreeView :
public OpWidget,
public OpTreeModel::Listener,
public OpTreeModel::SortListener,
public OpDelayedTriggerListener
{
public:
class Column;
friend class TreeViewModel;
friend class TreeViewModelItem;
friend class Column;
#ifdef ACCESSIBILITY_EXTENSION_SUPPORT
friend class ColumnListAccessor;
#endif
// -------------------------
// Construction, destruction and initialization:
// -------------------------
static OP_STATUS Construct(OpTreeView** obj);
~OpTreeView() { m_view_model.RemoveListener(this); }
/**
* Sets the TreeModel that the OpTreeView should represent
*
* The sort_by_column and sort_acending choices can be changed
* by a call to Sort with the new values
*
* @param tree_model - The TreeModel
* @param sort_by_column - Which column it should be sorted by
* @param sort_ascending - Items should be sorted ascending
* @param name - Desired name of the OpTreeView
* @param clear_match_text - Whether the match text should be cleared
* @param always_use_sortlistener - If this param is true, a tree view always uses sort listener, even if sort column equals -1.
* @param grouping - Grouping properties to use for this treemodel, or NULL if no grouping is needed
*/
void SetTreeModel(OpTreeModel* tree_model,
INT32 sort_by_column = -1,
BOOL sort_ascending = TRUE,
const char* name = NULL,
BOOL clear_match_text = FALSE,
BOOL always_use_sortlistener = FALSE,
OpTreeModel::TreeModelGrouping* grouping = NULL);
// ----------------------------------------------------------------------
// Listeners:
// ----------------------------------------------------------------------
OP_STATUS AddTreeViewListener(OpTreeViewListener* listener)
{return m_treeview_listeners.Add(listener);}
OP_STATUS RemoveTreeViewListener(OpTreeViewListener* listener)
{return m_treeview_listeners.Remove(listener);}
// ----------------------------------------------------------------------
// Switches:
//
// The switch methods can be used to alter the behaviour of the treeview.
// ----------------------------------------------------------------------
/**
* Switch method: The treeview has column headers
* Default : FALSE
*
* @param show_column_headers
*/
void SetShowColumnHeaders(BOOL show_column_headers);
/**
* Switch method: The treeview is multiselectable
* Default : FALSE
*
* @param is_multiselectable
*/
void SetMultiselectable(BOOL is_multiselectable)
{m_is_multiselectable = is_multiselectable;}
/**
* Switch method: The treeview allows deselection
* Default : TRUE
*
* @param is_deselectable
*/
void SetDeselectable(BOOL is_deselectable)
{m_is_deselectable_by_mouse = m_is_deselectable_by_keyboard = is_deselectable;}
/**
* Switch method: The treeview allows deselection using keyboard
* Default : TRUE
*
* @param is_deselectable
*/
void SetDeselectableByKeyboard(BOOL is_deselectable)
{m_is_deselectable_by_keyboard = is_deselectable;}
/**
* Switch method: The treeview allows deselection using mouse
* Default : TRUE
*
* @param is_deselectable
*/
void SetDeselectableByMouse(BOOL is_deselectable)
{m_is_deselectable_by_mouse = is_deselectable;}
/**
* Switch method: The treeview allows dragging
* Default : FALSE
*
* @param is_drag_enabled
*/
void SetDragEnabled(BOOL is_drag_enabled)
{m_is_drag_enabled = is_drag_enabled;}
/**
* Switch method: Shows the threaded image
* Default : FALSE
*
* @param show_thread_image
*/
void SetShowThreadImage(BOOL show_thread_image)
{m_show_thread_image = show_thread_image;}
/**
* Switch method: Parent folders are bold if they contain bold items
* Default : FALSE
*
* @param bold_folders
*/
void SetBoldFolders(BOOL bold_folders)
{m_bold_folders = bold_folders;}
/**
* Switch method: Opening a folder will open all subfolders aswell
* Default : FALSE
*
* @param root_opens_all
*/
void SetRootOpensAll(BOOL root_opens_all)
{m_root_opens_all = root_opens_all;}
/**
* Switch method: The treeview does the matching itself
* Default : FALSE
*
* @param auto_match
*/
void SetAutoMatch(BOOL auto_match)
{m_auto_match = auto_match;}
/**
* Swith method: The matching is asynchronous - someone else is responsible for calling
* UpdateAfterMatch() when the matching is done
* Default : FALSE
*
* @param async_match
*/
void SetAsyncMatch(BOOL async_match)
{m_async_match = async_match;}
BOOL GetAsyncMatch() {return m_async_match;}
/**
* Switch method: The user can sort - by clicking on the headers
* Default : TRUE
*
* @param user_sortable
*/
void SetUserSortable(BOOL user_sortable)
{ m_user_sortable = user_sortable; }
/**
* Switch method: An empty folder can be opened
* Default : FALSE
*
* @param allow_open_empty_folder
*/
void SetAllowOpenEmptyFolder(BOOL allow_open_empty_folder)
{ m_allow_open_empty_folder = allow_open_empty_folder; }
/**
* Switch method: Select another item if the selected item is removed
* Default : TRUE
*
* @param reselect_when_selected_is_removed
*/
void SetReselectWhenSelectedIsRemoved(BOOL reselect_when_selected_is_removed)
{ m_reselect_when_selected_is_removed = reselect_when_selected_is_removed; }
/**
* Switch method: Expand an item on a single click
* Default : TRUE
*
* @param expand_on_single_click
*/
void SetExpandOnSingleClick(BOOL expand_on_single_click)
{m_expand_on_single_click = expand_on_single_click;}
/**
* Switch method: Make item appear to have focus even when the treeview does not
* Default : FALSE
*
* @param forced_focus
*/
void SetForcedFocus(BOOL forced_focus)
{m_forced_focus = forced_focus;}
/**
* Switch method: Items can be selected on hover
* Default : FALSE
*
* @param select_on_hover
*/
void SetSelectOnHover(BOOL select_on_hover)
{m_select_on_hover = select_on_hover;}
/**
* Switch method: Select an item based on its first letter
* Default : TRUE
*
* @param allow_select_by_letter
*/
void SetAllowSelectByLetter(BOOL allow_select_by_letter)
{ m_allow_select_by_letter = allow_select_by_letter; }
/**
* Switch method: Force the sortorder to be based on the strings
* Default : FALSE
*
* @param force_sort_by_string
*/
void SetForceSortByString(BOOL force_sort_by_string)
{m_force_sort_by_string = force_sort_by_string;}
/**
* Switch method: Send MATCH_QUERY with empty strings aswell
* Default : FALSE
*
* @param force_empty_match_query
*/
void SetForceEmptyMatchQuery(BOOL force_empty_match_query)
{m_force_empty_match_query = force_empty_match_query;}
/**
* Switch method: Allow multi line items in the treeview
* Default : FALSE
*
* @param allow_multi_line_items
*/
void SetAllowMultiLineItems(BOOL allow_multi_line_items)
{m_allow_multi_line_items = allow_multi_line_items;}
/**
* Switch method: Allow multi line icons in the treeview
* Default : FALSE
*
* @param allow_multi_line_icons
*/
void SetAllowMultiLineIcons(BOOL allow_multi_line_icons)
{m_allow_multi_line_icons = allow_multi_line_icons;}
/**
* Switch method: Display associated text using the "weak" color (gray)
* Default : FALSE
*
* @param have_weak_associated_text
*/
void SetHaveWeakAssociatedText(BOOL have_weak_associated_text)
{m_have_weak_associated_text = have_weak_associated_text;}
/**
* Switch method: Force treeview to have background lines even if num cols is less than 2
* Default : FALSE
*
* @param force_background_line
*/
void SetForceBackgroundLine(BOOL force_background_line)
{m_force_background_line = force_background_line;}
#ifdef WIDGET_RUNTIME_SUPPORT
/**
* Should treeview have background lines for items.
*
* @param paint_background_line Set to TRUE if you want have background lines
*/
void SetPaintBackgroundLine(BOOL paint_background_line)
{ m_paint_background_line = paint_background_line; }
#endif // WIDGET_RUNTIME_SUPPORT
/**
* Switch method: Changes the horizonal scrollbar so the full treeview will be shown
* and not resized to fit the control
* Default : FALSE
*
* @param show
*/
void SetShowHorizontalScrollbar(bool show)
{ m_show_horizontal_scrollbar = show; }
/**
* Switch method: Allows scrolling with the keyboard to wrap to the top when reaching the bottom,
* and likewise wrap to the bottom when reaching the top.
* Default : FALSE
*
* @param wrapping TRUE to allow wrapping, FALSE to stop at the ends of the treeview
*/
void SetAllowWrappingOnScrolling(BOOL wrapping)
{ m_allow_wrapping_on_scrolling = wrapping; }
/**
* Switch method: Allows closing all headers during OpenAllItem(FALSE)
* Default : FALSE
*
* @param wrapping TRUE to allow, FALSE to disallow
*/
void SetCloseAllHeaders(BOOL close_all_headers)
{ m_close_all_headers = close_all_headers;}
/**
* Change the indentation in pixels for thread children
* Default : 16
*
* @param indentation
*/
void SetCustomThreadIndentation(INT32 indentation)
{ m_thread_indentation = indentation; }
void SetLinesKeepVisibleOnScroll(INT32 lines_keep_visible)
{ m_keep_visible_on_scroll = lines_keep_visible;}
// ----------------------------------------------------------------------
// Column settings:
// ----------------------------------------------------------------------
void SetThreadColumn(INT32 thread_column)
{m_thread_column = thread_column;}
void SetCheckableColumn(INT32 checkable_column)
{m_checkable_column = checkable_column;}
void SetLinkColumn(INT32 link_column)
{m_link_column = link_column;}
INT32 GetLinkColumn()
{return m_link_column;}
void SetColumnWeight(INT32 column_index, INT32 weight);
void SetColumnFixedWidth(INT32 column_index, INT32 fixed_width);
void SetColumnFixedCharacterWidth(INT32 column_index, INT32 character_count);
void SetColumnImageFixedDrawArea(INT32 column_index, INT32 fixed_width);
void SetColumnHasDropdown(INT32 column_index, BOOL has_dropdown);
BOOL SetColumnVisibility(INT32 column_index, BOOL is_visible);
BOOL SetColumnUserVisibility(INT32 column_index, BOOL is_visible);
INT32 GetColumnCount()
{return m_columns.GetCount();}
BOOL GetColumnName(INT32 column_index, OpString& name);
BOOL GetColumnVisibility(INT32 column_index);
BOOL GetColumnUserVisibility(INT32 column_index);
BOOL GetColumnMatchability(INT32 column_index);
BOOL IsFlat();
// ----------------------------------------------------------------------
// Sorting:
// ----------------------------------------------------------------------
/**
* Change the sort column and sort_acending choices
*
* @param sort_by_column
* @param sort_ascending
*/
void Sort(INT32 sort_by_column, BOOL sort_ascending);
void Regroup();
INT32 GetSortByColumn()
{ return m_sort_by_column; }
BOOL GetSortAscending()
{ return m_sort_ascending; }
// ----------------------------------------------------------------------
// Drawing and Scrolling:
// ----------------------------------------------------------------------
virtual void ScrollToLine(INT32 line, BOOL force_to_center = FALSE);
void ScrollToItem(INT32 item, BOOL force_to_center = FALSE);
void Redraw();
/**
* Set custom color for background line (eg OP_RGB(0xf5, 0xf5, 0xf5))
*
* @param custom_background_line_color
*/
void SetCustomBackgroundLineColor(INT32 custom_background_line_color)
{ m_custom_background_line_color = custom_background_line_color; }
// ----------------------------------------------------------------------
// Matching:
// ----------------------------------------------------------------------
void SetMatch(const uni_char* match_text,
INT32 match_column,
MatchType match_type,
INT32 match_parent_id,
BOOL select,
BOOL force = FALSE);
void SetMatchText(const uni_char* match_text, BOOL select = TRUE)
{ SetMatch(match_text, m_match_column, m_match_type, m_match_parent_id, select); }
void SetMatchColumn(INT32 match_column, BOOL select = FALSE)
{ SetMatch(m_match_text.CStr(), match_column, m_match_type, m_match_parent_id, select); }
void SetMatchType(MatchType match_type, BOOL select = FALSE)
{ SetMatch(m_match_text.CStr(), m_match_column, match_type, m_match_parent_id, select); }
void SetMatchParentID(INT32 match_parent_id, BOOL select = FALSE)
{ SetMatch(m_match_text.CStr(), m_match_column, m_match_type, match_parent_id, select); }
INT32 GetSavedMatchCount()
{return m_saved_matches.GetCount();}
BOOL GetSavedMatch(INT32 match_index, OpString& match_text);
void AddSavedMatch(OpString& match_text);
/**
* Delete all saved quick find searches
*/
void DeleteAllSavedMatches()
{ m_saved_matches.DeleteAll(); WriteSavedMatches(); }
/**
* Update the tree UI after a match has been completed (asks all items if they're matched)
*
* @param select Whether to select an item and scroll to it after updating the UI
*/
void UpdateAfterMatch(BOOL select = TRUE);
const uni_char * GetMatchText()
{return m_match_text.CStr();}
BOOL HasMatch()
{return HasMatchText() || HasMatchType() || HasMatchParentID();}
BOOL HasMatchText()
{return m_match_text.HasContent();}
BOOL HasMatchType()
{return m_match_type != MATCH_ALL;}
BOOL HasMatchParentID()
{return m_match_parent_id != 0;}
// ----------------------------------------------------------------------
// Selection:
// ----------------------------------------------------------------------
virtual void SetSelectedItem(INT32 pos,
BOOL changed_by_mouse = FALSE,
BOOL send_onchange = TRUE,
BOOL allow_parent_fallback = FALSE);
void SetSelectedItemByID(INT32 id,
BOOL changed_by_mouse = FALSE,
BOOL send_onchange = TRUE,
BOOL allow_parent_fallback = FALSE);
INT32 GetSelectedItemPos()
{return m_selected_item;}
INT32 GetSelectedItemModelPos()
{ return m_selected_item == -1 ? m_selected_item : GetModelPos(m_selected_item); }
UINT32 GetSelectedItemCount()
{ return m_selected_item_count; }
OpTreeModelItem * GetSelectedItem()
{return GetItemByPosition(m_selected_item);}
INT32 GetSelectedItems(OpINT32Vector& list, BOOL by_id = TRUE );
BOOL IsLastLineSelected();
BOOL IsFirstLineSelected();
void SelectAllItems(BOOL update = TRUE);
BOOL SelectNext(BOOL forward = TRUE,
BOOL unread_only = FALSE,
BOOL skip_group_headers = TRUE);
BOOL SelectByLetter(INT32 letter, BOOL forward );
// ----------------------------------------------------------------------
// TreeModel and TreeModelItems:
// ----------------------------------------------------------------------
OpTreeModel * GetTreeModel()
{ return m_view_model.GetModel(); };
OpTreeModelItem * GetParentByPosition(INT32 pos);
OpTreeModelItem * GetItemByPosition(INT32 pos);
// ----------------------------------------------------------------------
// The Lines :
// ----------------------------------------------------------------------
/*
* @return TRUE if new items have changed their check state since they where
* populated. Otherwise return FALSE.
*/
BOOL HasChanged();
/**
*
* @return TRUE if item has changed it's check state since it was
* populated. Otherwise return FALSE.
*/
BOOL HasItemChanged(INT32 pos);
INT32 GetChangedItems(INT32*& items);
INT32 GetItemByID(INT32 id);
INT32 GetModelIndexByIndex(INT32 index);
INT32 GetItemByModelItem(OpTreeModelItem* model_item);
INT32 GetItemByModelPos(INT32 pos)
{return m_view_model.GetIndexByModelIndex(pos);}
/**
* Convert a line number to item index.
*
* @param line line number
* @return index of the item "owning" the line number @a line,
* or @c -1 if there's no such item
*/
int GetItemByLine(int line) const;
/**
* Get the index of the item containing a point.
*
* @param point a point relative to widget bounds
* @param truncate_to_visible_items whether the function should only look
* for items that are currently visible (i.e., not scrolled out)
* @return index of the item whose area contains @a point, or @c -1 if
* there's no such item
*/
INT32 GetItemByPoint(OpPoint point, BOOL truncate_to_visible_items = FALSE);
/**
* @return number of items in the tree view
*/
INT32 GetItemCount() const
{ return m_item_count; }
/**
* Get the index of the line containing a point.
*
* @param point a point relative to widget bounds
* @param truncate_to_visible_items whether the function should only look
* for items that are currently visible (i.e., not scrolled out)
* @return index of the line whose area contains @a point, or @c -1 if
* there's no such line
*/
INT32 GetLineByPoint(OpPoint point, BOOL truncate_to_visible_lines = FALSE);
BOOL IsThreadImage(OpPoint point, INT32 pos);
int GetLineByItem(int pos);
INT32 GetLineCount()
{ return m_line_map.GetCount(); };
int GetLineHeight()
{ return m_line_height; }
INT32 GetModelPos(INT32 pos)
{return m_view_model.GetModelIndexByIndex(pos);}
INT32 GetChild(INT32 pos)
{return m_view_model.GetChildIndex(pos);}
INT32 GetSibling(INT32 pos)
{return m_view_model.GetSiblingIndex(pos);}
INT32 GetParent(INT32 pos)
{return m_view_model.GetParentIndex(pos);}
BOOL GetCellRect(INT32 pos,
INT32 column_index,
OpRect& rect,
BOOL text_rect = FALSE);
// ----------------------------------------------------------------------
// The items :
// ----------------------------------------------------------------------
BOOL IsItemOpen(INT32 pos);
BOOL IsItemVisible(INT32 pos);
BOOL IsItemChecked(INT32 pos);
BOOL IsItemDisabled(INT32 pos);
BOOL CanItemOpen(INT32 pos);
void OpenItem(INT32 pos, BOOL open, BOOL scroll_to_fit = TRUE);
/**
* Change the open state of an item an let the listener know about it
*/
virtual void ChangeItemOpenState(TreeViewModelItem* item, BOOL open);
void OpenAllItems(BOOL open);
void ToggleItem(INT32 pos);
void SetCheckboxValue(INT32 pos, BOOL checked);
// ----------------------------------------------------------------------
// The Widgets :
// ----------------------------------------------------------------------
INT32 GetEditColumn()
{return m_edit ? m_edit_column : -1;}
INT32 GetEditPos()
{return m_edit ? m_edit_pos : -1;}
void EditItem(INT32 pos,
INT32 column = 0,
BOOL always_use_full_column_width = FALSE,
AUTOCOMPL_TYPE autocomplete_type = AUTOCOMPLETION_OFF);
/**
* Removes edit field and ignores any changes
*
* @param broadcast Notify listener if such exists if TRUE
*/
void CancelEdit(BOOL broadcast = FALSE);
void FinishEdit()
{if (m_edit) g_input_manager->InvokeAction(OpInputAction::ACTION_EDIT_ITEM, 0, NULL, this);}
OpRect GetEditRect();
BOOL IsScrollable(BOOL vertical);
void StopPendingOnChange()
{ m_send_onchange_later = FALSE; }
// ----------------------------------------------------------------------
// Accessibility:
// ----------------------------------------------------------------------
#ifdef ACCESSIBILITY_EXTENSION_SUPPORT
int GetItemAt(int x, int y);
int GetColumnAt(int x, int y);
Accessibility::State GetUnfilteredState();
void CreateColumnListAccessorIfNeeded();
// == OpAccessibilityExtensionListener ======================
virtual Accessibility::ElementKind AccessibilityGetRole() const
{return Accessibility::kElementKindScrollview;}
virtual Accessibility::State AccessibilityGetState();
virtual void OnKeyboardInputGained(OpInputContext* new_input_context,
OpInputContext* old_input_context,
FOCUS_REASON reason);
virtual void OnKeyboardInputLost(OpInputContext* new_input_context,
OpInputContext* old_input_context,
FOCUS_REASON reason);
virtual int GetAccessibleChildrenCount();
virtual int GetAccessibleChildIndex(OpAccessibleItem* child);
virtual OpAccessibleItem* GetAccessibleChild(int);
virtual OpAccessibleItem* GetAccessibleChildOrSelfAt(int x, int y);
virtual OpAccessibleItem* GetAccessibleFocusedChildOrSelf();
#endif
// == OpTreeModel::Listener ======================
virtual void OnItemAdded(OpTreeModel* tree_model, INT32 item);
virtual void OnItemChanged(OpTreeModel* tree_model, INT32 item, BOOL sort);
virtual void OnItemRemoving(OpTreeModel* tree_model, INT32 index);
virtual void OnSubtreeRemoving(OpTreeModel* tree_model, INT32 parent_index, INT32 index, INT32 subtree_size);
virtual void OnSubtreeRemoved(OpTreeModel* tree_model, INT32 parent_index, INT32 index, INT32 subtree_size);
virtual void OnTreeChanging(OpTreeModel* tree_model);
virtual void OnTreeChanged(OpTreeModel* tree_model);
virtual void OnTreeDeleted(OpTreeModel* tree_model) {}
// == OpTreeModel::SortListener ======================
virtual INT32 OnCompareItems(OpTreeModel* tree_model, OpTreeModelItem* item1, OpTreeModelItem* item2);
// == OpToolTipListener ======================
virtual BOOL HasToolTipText(OpToolTip* tooltip) {return TRUE;}
virtual void GetToolTipText(OpToolTip* tooltip, OpInfoText& text);
virtual void GetToolTipThumbnailText(OpToolTip* tooltip, OpString& title, OpString& url_string, URL& url);
virtual INT32 GetToolTipItem(OpToolTip* tooltip);
virtual INT32 GetToolTipUpdateDelay(OpToolTip* tooltip) {return 100;}
virtual OpToolTipListener::TOOLTIP_TYPE GetToolTipType(OpToolTip* tooltip);
// == WidgetListener ======================
virtual void OnScroll(OpWidget *widget, INT32 old_val, INT32 new_val, BOOL caused_by_input);
virtual void OnRelayout(OpWidget* widget) {}
// == OpWidget ======================
virtual void SetName(const char* name) {OpWidget::SetName(name); ReadColumnSettings(); ReadSavedMatches();}
virtual OP_STATUS SetText(const uni_char* text) {SetMatchText(text); return OpStatus::OK;}
virtual DesktopDragObject* GetDragObject(OpTypedObject::Type type, INT32 x, INT32 y);
virtual void OnDeleted();
virtual void OnLayout();
virtual void OnClick(OpWidget *widget, UINT32 id);
virtual void OnPaint(OpWidgetPainter* widget_painter, const OpRect &paint_rect);
virtual void OnFocus(BOOL focus,FOCUS_REASON reason);
virtual void OnDragStart(const OpPoint& point);
virtual void OnDragLeave(OpDragObject* drag_object);
virtual void OnDragCancel(OpDragObject* drag_object);
virtual void OnDragMove(OpDragObject* drag_object, const OpPoint& point);
virtual void OnDragDrop(OpDragObject* drag_object, const OpPoint& point);
virtual void OnTimer();
virtual void OnShow(BOOL show);
virtual void OnMouseLeave();
virtual void OnMouseMove(const OpPoint &point);
virtual void OnMouseDown(const OpPoint &point, MouseButton button, UINT8 nclicks);
virtual void OnMouseUp(const OpPoint &point, MouseButton button, UINT8 nclicks);
virtual BOOL OnMouseWheel(INT32 delta,BOOL vertical);
virtual void OnSetCursor(const OpPoint &point);
virtual void SetRestrictImageSize(BOOL b) { OpWidget::SetRestrictImageSize(b); m_restrict_image_size = b; }
virtual void GetPreferedSize(INT32* w, INT32* h, INT32 cols, INT32 rows);
virtual void OnScaleChanged();
virtual BOOL OnScrollAction(INT32 delta, BOOL vertical, BOOL smooth);
// == OpWidgetImageListener ======================
virtual void OnImageChanged(OpWidgetImage* widget_image);
// == OpDelayedTriggerListener ======================
virtual void OnTrigger(OpDelayedTrigger*) {UpdateDelayedItems();}
// == OpTreeModelItem ======================
virtual Type GetType() {return WIDGET_TYPE_TREEVIEW;}
virtual BOOL IsOfType(Type type) { return type == WIDGET_TYPE_TREEVIEW || OpWidget::IsOfType(type); }
// == OpInputContext ======================
virtual BOOL OnInputAction(OpInputAction* action);
virtual const char* GetInputContextName() {return "Tree Widget";}
BOOL IsHoveringAssociatedImageItem(INT32 pos) { return pos != -1 && m_hover_associated_image_item == pos; }
#ifdef ANIMATED_SKIN_SUPPORT
virtual void OnAnimatedImageChanged(OpWidgetImage* widget_image);
#endif
void SetExtraLineHeight(UINT32 extra_height) { m_extra_line_height = extra_height; CalculateLineHeight(); }
/** Set to TRUE if associated images should only be showed on the hovered item. Disabled by default. */
void SetOnlyShowAssociatedItemOnHover(BOOL status) { m_only_show_associated_item_on_hover = status; }
// UI Automation (scope)
virtual OpScopeWidgetInfo* CreateScopeWidgetInfo();
OP_STATUS AddQuickWidgetInfoToList(OpScopeDesktopWindowManager_SI::QuickWidgetInfoList &list, TreeViewModelItem* item, INT32 real_col, const OpRect cell_rect, INT32 row, INT32 col);
OP_STATUS AddQuickWidgetInfoInvisibleItems(OpScopeDesktopWindowManager_SI::QuickWidgetInfoList &list, INT32 start_pos, INT32 end_pos);
protected:
OpTreeView();
void SetDropPos(INT32 drop_pos) { m_drop_pos = drop_pos; }
private:
/** Called for every custom widget item that is removed from the model. */
void OnCustomWidgetItemRemoving(TreeViewModelItem *item, OpWidget* widget = NULL);
void SetSelected(INT32 item_index, BOOL selected);
OpTreeView::Column* GetColumnByIndex(INT32 column_index);
/**
* @return the visible rect relative to widget bounds
*/
OpRect GetVisibleRect(bool include_column_headers = false, bool include_scrollbars = false, bool include_group_header = false)
{ return AdjustForDirection(GetVisibleRectLTR(include_column_headers, include_scrollbars, include_group_header)); }
/**
* @return the visible rect relative to widget bounds. The rect is
* computed for LTR even if the widget is RTL.
*/
OpRect GetVisibleRectLTR(bool include_column_headers = false, bool include_scrollbars = false, bool include_group_header = false);
BOOL GetItemRect(INT32 pos, OpRect& rect, BOOL only_visible = TRUE);
/**
* @rect receives the item rect, in LTR coords even if widget is RTL
* @see GetItemRect
*/
BOOL GetItemRectLTR(INT32 pos, OpRect& rect, BOOL only_visible = TRUE);
/**
* @rect receives the cell rect, in LTR coords even if widget is RTL
* @see GetCellRect
*/
BOOL GetCellRectLTR(INT32 pos,
INT32 column_index,
OpRect& rect,
BOOL text_rect = FALSE);
void ComputeTotalSize();
bool UpdateScrollbars();
void SelectItem(INT32 pos,
BOOL force_change = FALSE,
BOOL control = FALSE,
BOOL shift = FALSE,
BOOL changed_by_mouse = FALSE,
BOOL send_onchange = TRUE);
BOOL OpenItemRecursively(INT32 pos,
BOOL open,
BOOL recursively,
BOOL update_lines = TRUE);
void PaintTree(OpWidgetPainter* widget_painter,
const OpRect &paint_rect,
OpScopeDesktopWindowManager_SI::QuickWidgetInfoList *list = NULL,
BOOL include_invisible = TRUE);
int PaintItem(OpWidgetPainter* widget_painter,
INT32 pos,
OpRect paint_rect,
OpRect rect,
BOOL background_line,
OpScopeDesktopWindowManager_SI::QuickWidgetInfoList *list = NULL);
void PaintGroupHeader(OpWidgetPainter* widget_painter,
const OpRect &paint_rect,
BOOL background_line);
void PaintItemBackground(INT32 pos, OpSkinElement* item_skin_element, INT32 skin_state, BOOL background_line, const OpRect& rect);
void PaintSelectedItemBackground(const OpRect &paint_rect, BOOL is_selected_item);
void PaintCell(OpWidgetPainter* widget_painter,
OpSkinElement *item_skin_elm,
INT32 state,
INT32 pos,
OpTreeView::Column* column,
OpRect& cell_rect,
OpScopeDesktopWindowManager_SI::QuickWidgetInfoList *list = NULL);
void PaintText(OpWidgetPainter* widget_painter,
OpSkinElement *item_skin_elm,
INT32 state,
OpRect& cell_rect,
TreeViewModelItem* item,
ItemDrawArea* cache,
BOOL use_weak_style = FALSE,
BOOL use_link_style = FALSE,
BOOL use_bold_style = FALSE,
int right_offset = 0,
int *cell_width = NULL);
/**
* @param get_size_only whether to really paint the image or just get its size
* @param item the item the thread image is for
* @param depth threading depth
* @param parent_rect will draw relative to this rect
* @return the rect of the thread image
*/
OpRect PaintThreadImage(bool get_size_only,
TreeViewModelItem* item,
int depth,
const OpRect& parent_rect);
BOOL HandleGroupHeaderMouseClick(const OpPoint& point, MouseButton button);
bool SetTopGroupHeader();
BOOL MatchItem(INT32 pos, BOOL check = FALSE, BOOL update_line = TRUE);
BOOL UpdateSearch(INT32 pos, BOOL check = FALSE, BOOL update_line = TRUE);
void Rematch(INT32 pos);
void InitItem(INT32 pos);
void UpdateItem(INT32 pos, BOOL clear, BOOL delay = FALSE);
void SetTreeModelInternal(OpTreeModel* tree_model);
void TreeChanged();
void UpdateLines(INT32 pos = -1);
void UpdateSortParameters(OpTreeModel* model, INT32 sort_by_column, BOOL sort_ascending);
void UpdateDelayedItems();
void GetInfoText(INT32 pos, OpInfoText& text);
BOOL StartColumnSizing(OpTreeView::Column* column, const OpPoint& point, BOOL check_only);
void DoColumnSizing(OpTreeView::Column* column, const OpPoint& point);
void EndColumnSizing();
BOOL IsColumnSizing() {return m_is_sizing_column;}
void ReadColumnSettings();
void WriteColumnSettings();
void ReadSavedMatches();
void WriteSavedMatches();
void StartScrollTimer();
void StopScrollTimer();
void UpdateDragSelecting();
void CalculateLineHeight();
// Insert all the lines of this item
OP_STATUS InsertLines(TreeViewModelItem * item);
// Insert all the lines of the item with this index
OP_STATUS InsertLines(int index, int num_lines = -1);
// Remove all the lines of the item with this index
OP_STATUS RemoveLines(int index);
// Get the number of lines this item requires
int GetNumLines(TreeViewModelItem * item);
// Get the visible index to the item that owns the line (beware this is slow)
int GetVisibleItemPos(int line);
// Calculates the total width need if everything is fixed width. It doesn't add the scrollbar width.
// Used in combo with horizonal scroll bars
int GetFixedWidth();
// calculates the rect needed for the associated image
void CalculateAssociatedImageSize(ItemDrawArea* associated_image, const OpRect& item_rect, OpRect& associated_image_rect);
BOOL HasGrouping() const
{ return m_view_model.GetTreeModelGrouping() ? m_view_model.GetTreeModelGrouping()->HasGrouping() : FALSE; }
// -------------------------
// Private member variables:
// -------------------------
// -------------------------
// Switches:
// -------------------------
BOOL m_show_column_headers; // The treeview has column headers
BOOL m_is_multiselectable; // The treeview is multiselectable
BOOL m_is_deselectable_by_keyboard; // The treeview allows deselection from keyboard action
BOOL m_is_deselectable_by_mouse; // The treeview allows deselection from mouse action
BOOL m_is_drag_enabled; // The treeview allows dragging
BOOL m_show_thread_image; // Shows the threaded image
BOOL m_bold_folders; // Parent folder are bold if they contain bold items
BOOL m_root_opens_all; // Opening a folder will open all subfolders aswell
BOOL m_auto_match; // The treeview does the matching itself
BOOL m_async_match; // Matching is done by an asynchronous method
BOOL m_user_sortable; // The user can sort - by clicking on the headers
BOOL m_allow_open_empty_folder; // An empty folder can be opened
BOOL m_reselect_when_selected_is_removed; // Select another item if the selected item is removed
BOOL m_expand_on_single_click; // Expand an item on a single click
BOOL m_forced_focus; // Make item appear to have focus even when the treeview does not
BOOL m_select_on_hover; // Items can be selected on hover
BOOL m_allow_select_by_letter; // Select an item based on its first letter
BOOL m_force_sort_by_string; // Force the sortorder to be based on the strings
BOOL m_force_empty_match_query; // Send MATCH_QUERY with empty strings aswell
BOOL m_allow_multi_line_items; // Allow items to span multiple lines
BOOL m_restrict_image_size; // If TRUE will restrict image size to 16*16
BOOL m_allow_multi_line_icons; // Allow icons to span multiple lines
BOOL m_have_weak_associated_text; // Display the associated text as weak (gray)
BOOL m_force_background_line; // Force treeview to have background lines even if num cols is less than 2
BOOL m_allow_wrapping_on_scrolling; // Allow that scrolling with the keyboard and reaching the bottom will wrap around to the top
BOOL m_paint_background_line; // Should treeview contain background lines
BOOL m_close_all_headers; // OpenAllItems(FALSE) should close also all headers
// -------------------------
// Constants:
// -------------------------
INT32 m_column_headers_height; //(Should maybe not be a member var?)
// -------------------------
// State:
// -------------------------
BOOL m_is_drag_selecting; // State - is currently in a drag
bool m_changed; // State - detect changes while drawing (Should maybe not be a member var?)
// -------------------------
// Widgets:
// -------------------------
// Currently active editable field:
Edit* m_edit;
INT32 m_edit_pos; // Line the edit field is on
INT32 m_edit_column; // Column the edit field is in
// Empty, inactive button - filler in right top corner between scrollbar and column headers
OpButton* m_column_filler;
// Scrollbars :
OpScrollbar* m_horizontal_scrollbar;
OpScrollbar* m_vertical_scrollbar;
OpWidgetListener* m_scrollbar_listener;
bool m_show_horizontal_scrollbar;
// -------------------------
// Drag and drop:
// -------------------------
INT32 m_drop_pos; // The current drop position : where a drop would occur right now
DesktopDragObject::InsertType m_insert_type; // Type of insert : INSERT_INTO, INSERT_BEFORE, INSERT_AFTER
// -------------------------
// Painting:
// -------------------------
OpDelayedTrigger m_redraw_trigger;
OpVector<TreeViewModelItem> m_items_that_need_redraw;
OpINTSet m_item_ids_that_need_string_refresh;
int m_line_height;
BOOL m_is_centering_needed;
INT32 m_custom_background_line_color; // Custom color for background line (eg 0xf5f5f5)
UINT32 m_extra_line_height; // Additional line height
BOOL m_only_show_associated_item_on_hover;
bool m_save_strings_that_need_refresh; // save which strings that need to be refreshed (because the scale changed)
// -------------------------
// Matching:
// -------------------------
OpString m_match_text; // The currently search for text - set by SetMatch
INT32 m_match_column; // - set by SetMatch
MatchType m_match_type; // - set by SetMatch
INT32 m_match_parent_id; // - set by SetMatch
OpAutoVector<OpString> m_saved_matches; // - added to by a call to AddSavedMatch
// -------------------------
// Columns:
// -------------------------
OpWidgetVector<OpTreeView::Column> m_columns; // The columns of the treeview
INT32 m_visible_column_count; // The columns currently visible
INT32 m_thread_column; // Index of the column that is treaded
INT32 m_checkable_column; // Index of the column with the checkboxes
INT32 m_link_column; // Index of the column with the links
BOOL m_column_settings_loaded; // Flag to indicate that the column settings have been loaded
// -------------------------
// Custom widgets:
// -------------------------
OpVector<OpWidget> m_custom_widgets;
OpVector<OpWidget> m_custom_painted_widgets;
// -------------------------
// TreeModel:
// -------------------------
TreeViewModel m_view_model; // The model this OpTreeView represents
// -------------------------
// Selection:
// -------------------------
INT32 m_selected_item; // The index/line of the currently selected item
UINT32 m_selected_item_count; // The number of selected items
INT32 m_shift_item; // The previously selected item when a new one has been selected with shift down
INT32 m_hover_item; // The currently hovered item
INT32 m_hover_associated_image_item; // The currently hovered associated image
INT32 m_reselect_selected_line;// Whether a reselect should occur (Should maybe not be a member var?)
INT32 m_reselect_selected_id; // Id of item that should be selected (Should maybe not be a member var?)
INT32 m_timed_hover_pos; //
INT32 m_timer_counter; //
BOOL m_send_onchange_later; //
BOOL m_selected_on_mousedown; //
// -------------------------
// Sorting:
// -------------------------
INT32 m_sort_by_column; // Which column it should be sorted by
BOOL m_sort_ascending; // Items should be sorted ascending
BOOL m_sort_by_string_first; // Set by the GetColumnData request to the model (default FALSE)
BOOL m_custom_sort; // Set by the GetColumnData request to the model (default FALSE)
BOOL m_always_use_sortlistener;
// -------------------------
// Sizing:
// -------------------------
OpAutoArray<OpRect> m_sizing_columns;
BOOL m_is_sizing_column;
INT32 m_sizing_column_left;
INT32 m_sizing_column_right;
INT32 m_start_x;
INT32 m_thread_indentation; // 16 by default
INT32 m_keep_visible_on_scroll; // 2 by default
// -------------------------
// Items:
// -------------------------
INT32 m_item_count; // The number of items
LineToItemMap m_line_map;
// -------------------------
// Listeners: List of the listeners currently listening to the OpTreeView
// -------------------------
OpListeners<OpTreeViewListener> m_treeview_listeners;
// -------------------------
// Accessibility:
// -------------------------
#ifdef ACCESSIBILITY_EXTENSION_SUPPORT
ColumnListAccessor* m_column_list_accessor;
#endif //ACCESSIBILITY_EXTENSION_SUPPORT
OpPoint m_anchor; // Prevents mouse to interfere with keyboard navigation
struct GroupHeaderInfo
{
INT32 pos;
OpRect rect;
TreeViewModelItem* item;
};
OpAutoVector<GroupHeaderInfo> m_group_headers_to_draw;
class ScopeWidgetInfo;
friend class ScopeWidgetInfo;
};
#endif // OP_TREE_VIEW_H
|
#include <iostream>
#include <vector>
#include <map>
using namespace std;
typedef char EdgeData;
class EdgeNode {
public:
int adjvex;
EdgeData data;
EdgeNode * next;
EdgeNode(int adjvex, EdgeData data, EdgeNode * next) :
adjvex(adjvex), data(data), next(next) {
}
EdgeNode() :next(NULL) {
}
};
typedef vector<EdgeNode*> graph;
map<EdgeData, int> m;
graph g;
int N;
void createnode(EdgeData x) {
if (m[x]) return;
g.push_back(new EdgeNode(++N, x, NULL));
m[x] = N;
}
void input() {//input graph
int n;
EdgeData x, y;
g.push_back(NULL);
cin >> n;
for (int i = 0; i < n; ++i) {
cin >> x >> y;
createnode(x);
createnode(y);
g[m[x]]->next = new EdgeNode(g[m[y]]->adjvex, y, g[m[x]]->next);
g[m[y]]->next = new EdgeNode(g[m[x]]->adjvex, x, g[m[y]]->next);
}
}
template <typename T>
T min(T x, T y) {
if (x > y) return y;
return x;
}
//bioconnected_judge
int counter, apcounter;
void dfs(int u) {
static bool first = true;
static int *dfn = new int[N + 1], *low = new int[N + 1], *parent = new int[N + 1];
if (first) {
first = false;
memset(dfn, 0, (N + 1) * sizeof(int));
memset(parent, 0, (N + 1) * sizeof(int));
parent[u] = 0;
}
int children = 0;
dfn[u] = low[u] = ++counter;
for (auto p = g[u]->next; p; p = p->next) {
int v = p->adjvex;
if (!dfn[v]) {
children++;
parent[v] = u;
dfs(v);
low[u] = min(low[u], low[v]);
if (!parent[u] && children > 1) {//根节点 对根节点u,若其有两棵或两棵以上的子树,则该根结点u为割点;
apcounter++;
cout << g[u]->data << ' ';
}
if (parent[u] && low[v] >= dfn[u]) {//非根节点 若其子树的节点均没有指向u的祖先节点的回边,说明删除u之后,根结点与u的子树的节点不再连通;则节点u为割点。
apcounter++;
cout << g[u]->data << ' ';
}
}
else if (v != parent[u]) {//v已访问,则(u,v)为回边
low[u] = min(low[u], dfn[v]);
}
}
}
void main() {
input();
cout << endl;
dfs(1);//单从1深搜 有几个关节点
if (counter < N)
cout << "\nnot a biconnected graph";
else if(apcounter == 0)
cout << "\nis a biconnected graph";
else if (apcounter)
cout << "\narticulation point num: " << apcounter << "\nnot a biconnected graph";
system("pause");
}
|
// Created on: 1997-02-12
// Created by: Alexander BRIVIN
// Copyright (c) 1997-1999 Matra Datavision
// Copyright (c) 1999-2014 OPEN CASCADE SAS
//
// This file is part of Open CASCADE Technology software library.
//
// This library is free software; you can redistribute it and/or modify it under
// the terms of the GNU Lesser General Public License version 2.1 as published
// by the Free Software Foundation, with special exception defined in the file
// OCCT_LGPL_EXCEPTION.txt. Consult the file LICENSE_LGPL_21.txt included in OCCT
// distribution for complete text of the license and disclaimer of any warranty.
//
// Alternatively, this file may be used under the terms of Open CASCADE
// commercial license or contractual agreement.
#ifndef _Vrml_WWWInline_HeaderFile
#define _Vrml_WWWInline_HeaderFile
#include <Standard.hxx>
#include <Standard_DefineAlloc.hxx>
#include <TCollection_AsciiString.hxx>
#include <gp_Vec.hxx>
#include <Standard_OStream.hxx>
//! defines a WWWInline node of VRML specifying group properties.
//! The WWWInline group node reads its children from anywhere in the
//! World Wide Web.
//! Exactly when its children are read is not defined;
//! reading the children may be delayed until the WWWInline is actually
//! displayed.
//! WWWInline with an empty ("") name does nothing.
//! WWWInline behaves like a Separator, pushing the traversal state
//! before traversing its children and popping it afterwards.
//! By defaults:
//! myName ("")
//! myBboxSize (0,0,0)
//! myBboxCenter (0,0,0)
class Vrml_WWWInline
{
public:
DEFINE_STANDARD_ALLOC
Standard_EXPORT Vrml_WWWInline();
Standard_EXPORT Vrml_WWWInline(const TCollection_AsciiString& aName, const gp_Vec& aBboxSize, const gp_Vec& aBboxCenter);
Standard_EXPORT void SetName (const TCollection_AsciiString& aName);
Standard_EXPORT TCollection_AsciiString Name() const;
Standard_EXPORT void SetBboxSize (const gp_Vec& aBboxSize);
Standard_EXPORT gp_Vec BboxSize() const;
Standard_EXPORT void SetBboxCenter (const gp_Vec& aBboxCenter);
Standard_EXPORT gp_Vec BboxCenter() const;
Standard_EXPORT Standard_OStream& Print (Standard_OStream& anOStream) const;
protected:
private:
TCollection_AsciiString myName;
gp_Vec myBboxSize;
gp_Vec myBboxCenter;
};
#endif // _Vrml_WWWInline_HeaderFile
|
#include "codestatisticswindow.h"
#include <QApplication>
#include <windows.h>
#include "applanguage.h"
#include <QTranslator>
int main(int argc, char *argv[])
{
QApplication app(argc, argv);
CAppLanguage *phLanguage = new CAppLanguage();
QTranslator *pTrans = new QTranslator;
pTrans->load( phLanguage->appLanguageGet() );
app.installTranslator( pTrans );
delete phLanguage;
CodeStatisticsWindow hWin;
hWin.show();
return app.exec();
}
|
/*
* This is a C++ class: CsampleSpace
* 描述样本空间
* 双色球有33个红球,16个蓝球,共49个
* 大乐透有35个红球,12个蓝球,共47个
* data file format:
* xxxx yy yy yy .. yy : zz zz ##
*/
#ifndef CSAMPLESPACE_HPP_INCLUDED
#define CSAMPLESPACE_HPP_INCLUDED
#include "CbaseBall.hpp"
#include "Cgame.hpp"
#include <list>
using namespace std;
class CsamplePace{
public:
CsamplePace();
~CsamplePace();
public:
list <Cgame> sampleSpace;
// FILE *fp; //histoy data file
public:
int get_data_from_txt(const char *path);
int create_data_file(void);
// FILE *get_data_file(char *path);
};
#endif
|
// Created on: 1996-01-09
// Created by: Jacques GOUSSARD
// Copyright (c) 1996-1999 Matra Datavision
// Copyright (c) 1999-2014 OPEN CASCADE SAS
//
// This file is part of Open CASCADE Technology software library.
//
// This library is free software; you can redistribute it and/or modify it under
// the terms of the GNU Lesser General Public License version 2.1 as published
// by the Free Software Foundation, with special exception defined in the file
// OCCT_LGPL_EXCEPTION.txt. Consult the file LICENSE_LGPL_21.txt included in OCCT
// distribution for complete text of the license and disclaimer of any warranty.
//
// Alternatively, this file may be used under the terms of Open CASCADE
// commercial license or contractual agreement.
#ifndef _LocOpe_Generator_HeaderFile
#define _LocOpe_Generator_HeaderFile
#include <Standard.hxx>
#include <Standard_DefineAlloc.hxx>
#include <Standard_Handle.hxx>
#include <TopoDS_Shape.hxx>
#include <TopTools_DataMapOfShapeListOfShape.hxx>
#include <TopTools_ListOfShape.hxx>
class LocOpe_GeneratedShape;
class TopoDS_Face;
class LocOpe_Generator
{
public:
DEFINE_STANDARD_ALLOC
//! Empty constructor.
LocOpe_Generator();
//! Creates the algorithm on the shape <S>.
LocOpe_Generator(const TopoDS_Shape& S);
//! Initializes the algorithm on the shape <S>.
void Init (const TopoDS_Shape& S);
Standard_EXPORT void Perform (const Handle(LocOpe_GeneratedShape)& G);
Standard_Boolean IsDone() const;
//! Returns the new shape
const TopoDS_Shape& ResultingShape() const;
//! Returns the initial shape
const TopoDS_Shape& Shape() const;
//! Returns the descendant face of <F>. <F> may
//! belong to the original shape or to the "generated"
//! shape. The returned face may be a null shape
//! (when <F> disappears).
Standard_EXPORT const TopTools_ListOfShape& DescendantFace (const TopoDS_Face& F);
protected:
private:
TopoDS_Shape myShape;
Handle(LocOpe_GeneratedShape) myGen;
Standard_Boolean myDone;
TopoDS_Shape myRes;
TopTools_DataMapOfShapeListOfShape myModShapes;
};
#include <LocOpe_Generator.lxx>
#endif // _LocOpe_Generator_HeaderFile
|
#include <chuffed/core/sat.h>
#include <chuffed/vars/int-var.h>
#include <iostream>
extern std::map<IntVar*, std::string> intVarString;
// val -> (val-1)/2
IntVarLL::IntVarLL(const IntVar& other) : IntVar(other), ld(2), li(0), hi(1) {
ld[0].var = 0;
ld[0].val = min - 1;
ld[0].prev = -1;
ld[0].next = 1;
ld[1].var = 1;
ld[1].val = max;
ld[1].prev = 0;
ld[1].next = -1;
// This literal becomes true when the integer variable is
// fixed (see updateFixed). It's not learnable, so any
// explanation will use the reason which includes the actual
// bounds literals.
valLit = Lit(sat.nVars(), true);
int v = sat.newVar(1, ChannelInfo(var_id, 1, 0, 0));
sat.flags[v].setDecidable(false);
sat.flags[v].setUIPable(false);
sat.flags[v].setLearnable(false);
if (isFixed()) {
sat.cEnqueue(valLit, nullptr);
}
varLabel = intVarString[(IntVar*)(&other)];
std::stringstream ss;
ss << varLabel << "=fixed";
litString.insert(make_pair(toInt(valLit), ss.str()));
ss.str("");
ss << varLabel << "=notfixed";
litString.insert(make_pair(toInt(~valLit), ss.str()));
}
DecInfo* IntVarLL::branch() {
// Solution-based phase saving
if (sbps_value_selection) {
// Check if we can branch on last solution value
if (indomain(last_solution_value)) { // Lazy variables don't allow to use == decisions
if (setMinNotR(last_solution_value)) {
return new DecInfo(this, last_solution_value - 1, 2);
}
return new DecInfo(this, last_solution_value, 3);
}
}
switch (preferred_val) {
case PV_MIN:
return new DecInfo(this, min, 3);
case PV_MAX:
return new DecInfo(this, max - 1, 2);
case PV_SPLIT_MIN:
return new DecInfo(this, min + (max - min - 1) / 2, 3);
case PV_SPLIT_MAX:
return new DecInfo(this, min + (max - min) / 2, 2);
case PV_MEDIAN:
CHUFFED_ERROR("Median value selection is not supported for variables with lazy literals.\n");
default:
NEVER;
}
}
inline int IntVarLL::getLitNode() {
#if DEBUG_VERBOSE
std::cerr << "IntVarLL::getLitNode\n";
#endif
int i = -1;
if (freelist.size() != 0) {
i = freelist.last();
freelist.pop();
} else {
i = ld.size();
ld.push();
}
return i;
}
void IntVarLL::freeLazyVar(int val) {
int ni;
if (val < min) {
ni = li;
while (ld[ni].val > val) {
ni = ld[ni].prev;
assert(0 <= ni && ni < ld.size());
}
} else if (val >= max) {
ni = hi;
while (ld[ni].val < val) {
ni = ld[ni].next;
assert(0 <= ni && ni < ld.size());
}
} else {
NEVER;
}
assert(ld[ni].val == val);
ld[ld[ni].prev].next = ld[ni].next;
ld[ld[ni].next].prev = ld[ni].prev;
freelist.push(ni);
}
inline Lit IntVarLL::getGELit(int v) {
if (v > max) {
return getMaxLit();
}
assert(v >= min);
int ni = li;
int prev = prevDomVal(v);
if ((vals != nullptr) && (vals[v] == 0)) {
v = nextDomVal(v);
}
while (ld[ni].val < prev) {
ni = ld[ni].next;
assert(0 <= ni && ni < ld.size());
}
if (ld[ni].val == prev) {
return Lit(ld[ni].var, true);
}
// overshot, create new var and insert before ni
int mi = getLitNode();
#if DEBUG_VERBOSE
std::cerr << "created new literal: " << mi << ": " << varLabel << "(" << this << ") >= " << v
<< " || " << varLabel << "(" << this << ") <= " << prev << "\n";
#endif
ld[mi].var = sat.getLazyVar(ChannelInfo(var_id, 1, 1, prev));
ld[mi].val = prev;
ld[mi].next = ni;
ld[mi].prev = ld[ni].prev;
ld[ni].prev = mi;
ld[ld[mi].prev].next = mi;
std::stringstream ss;
ss << varLabel << ">=" << v;
litString.insert(make_pair(ld[mi].var * 2 + 1, ss.str()));
ss.str("");
ss << varLabel << "<=" << prev;
litString.insert(make_pair(ld[mi].var * 2, ss.str()));
return Lit(ld[mi].var, true);
}
inline Lit IntVarLL::getLELit(int v) {
if (v < min) {
return getMinLit();
}
return ~getGELit(v + 1);
}
Lit IntVarLL::getLit(int64_t v, LitRel t) {
// NOTE: Previous assertion that makes little sense. We should further
// investigate if the comparisons with min/max make sense at different
// decision levels.
// So far this assertion only seems to trigger with all_different (bounds)
// assert(engine.decisionLevel() == 0);
if (v < min) {
return toLit(1 ^ (t & 1)); // _, _, 1, 0
}
if (v > max) {
return toLit(t & 1); // _, _, 0, 1
}
switch (t) {
case LR_GE:
return getGELit(v);
case LR_LE:
return getLELit(v);
default:
NEVER;
}
}
// Use when you've just set [x >= v]
inline void IntVarLL::channelMin(int v, Lit p) {
Reason r(~p);
int ni;
int prev = prevDomVal(v);
for (ni = ld[li].next; ld[ni].val < prev; ni = ld[ni].next) {
sat.cEnqueue(Lit(ld[ni].var, true), r);
}
assert(ld[ni].val == prev);
li = ni;
}
// Use when you've just set [x <= v]
inline void IntVarLL::channelMax(int v, Lit p) {
Reason r(~p);
int ni;
assert(!vals || vals[v]);
for (ni = ld[hi].prev; ld[ni].val > v; ni = ld[ni].prev) {
sat.cEnqueue(Lit(ld[ni].var, false), r);
}
assert(ld[ni].val == v);
hi = ni;
}
inline void IntVarLL::updateFixed() {
if (isFixed()) {
Reason r(getMinLit(), getMaxLit());
sat.cEnqueue(valLit, r);
changes |= EVENT_F;
}
}
bool IntVarLL::setMin(int64_t v, Reason r, bool channel) {
assert(setMinNotR(v));
if ((vals != nullptr) && (vals[v] == 0)) {
v = nextDomVal(v);
}
Lit p = getGELit(v);
if (channel) {
sat.cEnqueue(p, r);
}
if (v > max) {
assert(sat.confl);
return false;
}
channelMin(v, p);
min = v;
changes |= EVENT_C | EVENT_L;
updateFixed();
pushInQueue();
return true;
}
bool IntVarLL::setMax(int64_t v, Reason r, bool channel) {
assert(setMaxNotR(v));
if ((vals != nullptr) && (vals[v] == 0)) {
v = prevDomVal(v);
}
Lit p = getLELit(v);
if (channel) {
sat.cEnqueue(p, r);
}
if (v < min) {
assert(sat.confl);
return false;
}
channelMax(v, p);
max = v;
changes |= EVENT_C | EVENT_U;
updateFixed();
pushInQueue();
return true;
}
bool IntVarLL::setVal(int64_t v, Reason r, bool channel) {
assert(setValNotR(v));
assert(channel);
if (setMinNotR(v)) {
if (!setMin(v, r, channel)) {
return false;
}
}
if (setMaxNotR(v)) {
if (!setMax(v, r, channel)) {
return false;
}
}
return true;
}
bool IntVarLL::remVal(int64_t v, Reason r, bool channel) {
assert(channel);
if (!engine.finished_init) {
NEVER;
}
return true;
}
Lit IntVarLL::createLit(int _v) {
int v = _v >> 2;
int s = 1 - _v % 2;
int ni = 1;
while (ld[ni].val > v) {
ni = ld[ni].prev;
assert(0 <= ni && ni < ld.size());
}
if (ld[ni].val == v) {
return Lit(ld[ni].var, s != 0);
}
// overshot, create new var and insert before ni
int mi = getLitNode();
ld[mi].var = sat.getLazyVar(ChannelInfo(var_id, 1, 1, v));
ld[mi].val = v;
ld[mi].prev = ni;
ld[mi].next = ld[ni].next;
ld[ni].next = mi;
ld[ld[mi].next].prev = mi;
Lit p = Lit(ld[ld[mi].next].var, true);
Lit q = Lit(ld[ld[mi].prev].var, false);
// printf("created var %d, ", ld[mi].var);
if (sat.value(p) == l_True) {
auto* r = (Clause*)malloc(sizeof(Clause) + 2 * sizeof(Lit));
r->clearFlags();
r->temp_expl = 1;
r->sz = 2;
(*r)[1] = ~p;
int l = sat.getLevel(var(p));
sat.rtrail[l].push(r);
sat.aEnqueue(Lit(ld[mi].var, true), r, l);
}
if (sat.value(q) == l_True) {
auto* r = (Clause*)malloc(sizeof(Clause) + 2 * sizeof(Lit));
r->clearFlags();
r->temp_expl = 1;
r->sz = 2;
(*r)[1] = ~q;
int l = sat.getLevel(var(q));
sat.rtrail[l].push(r);
sat.aEnqueue(Lit(ld[mi].var, false), r, l);
}
return Lit(ld[mi].var, s != 0);
}
|
#include <simplecpp>
main_program{
int count;
cout << "How many numbers: ";
cin >> count;
float num,maximum;
cout << "Give the next number: ";
cin >> maximum;
repeat(count-1){
cout << "Give the next number: ";
cin >> num;
maximum = max(maximum,num);
}
cout << "Maximum is: " << maximum << endl;
}
|
#pragma once
#include <iostream>
#include <fstream>
#include <sstream>
#include <stdlib.h>
#include "configfile.h"
#include "compute_steering.h"
#include "predict_true.h"
#include "particle.h"
/*!
Calculates the particles and their positions. Mostly calls other functions.
@param[out] particles All particles
@param[in] lm list of landmark data
@param[in] wp list of waypoints, only used to compute steering.
*/
void fastslam1_sim(double* lm, const size_t lm_rows, const size_t lm_cols,
double* wp, const size_t wp_rows, const size_t wp_cols,
Particle **particles_, double **weights_);
void fastslam1_sim_active( double* lm, const size_t lm_rows, const size_t lm_cols,
double* wp, const size_t wp_rows, const size_t wp_cols,
Particle **particles_, double** weights_);
void fastslam1_sim_base( double* lm, const size_t lm_rows, const size_t lm_cols,
double* wp, const size_t wp_rows, const size_t wp_cols,
Particle **particles_, double** weights_);
double fastslam1_sim_base_flops( double* lm, const size_t lm_rows, const size_t lm_cols,
double* wp, const size_t wp_rows, const size_t wp_cols,
Particle **particles_, double** weights_);
double fastslam1_sim_base_memory( double* lm, const size_t lm_rows, const size_t lm_cols,
double* wp, const size_t wp_rows, const size_t wp_cols,
Particle **particles_, double** weights_);
double fastslam1_sim_active_flops( double* lm, const size_t lm_rows, const size_t lm_cols,
double* wp, const size_t wp_rows, const size_t wp_cols,
Particle **particles_, double** weights_);
double fastslam1_sim_active_memory( double* lm, const size_t lm_rows, const size_t lm_cols,
double* wp, const size_t wp_rows, const size_t wp_cols,
Particle **particles_, double** weights_);
//! ------------------------------------- !//
//! --- FastSLAM 1.0 on Victoria Park --- !//
//! ------------------------------------- !//
void fastslam1_sim_base_VP(double* lm, const size_t lm_rows, const size_t lm_cols,
const size_t N_features, Particle **particles_, double** weights_);
void fastslam1_sim_active_VP(double* lm, const size_t lm_rows, const size_t lm_cols,
const size_t N_features, Particle **particles_, double** weights_);
|
#ifndef __LOAM_LASER_ODOMETRY_H__
#define __LOAM_LASER_ODOMETRY_H__
#include <loam_velodyne/common.h>
#include <loam_velodyne/build_transform.h>
#include <loam_velodyne/scanRegistrationLib.h>
#include <opencv/cv.h>
#include <pcl/kdtree/kdtree_flann.h>
class LaserOdometry {
private:
const float scanPeriod;
float imuRollStart, imuPitchStart, imuYawStart;
float imuRollLast, imuPitchLast, imuYawLast;
float imuShiftFromStartX, imuShiftFromStartY, imuShiftFromStartZ;
float imuVeloFromStartX, imuVeloFromStartY, imuVeloFromStartZ;
pcl::KdTreeFLANN<PointType> kdtreeCornerLast;
pcl::KdTreeFLANN<PointType> kdtreeSurfLast;
bool isDegenerate;
pcl::PointCloud<PointType>::Ptr laserCloudCornerLast;
pcl::PointCloud<PointType>::Ptr laserCloudSurfLast;
int laserCloudCornerLastNum;
int laserCloudSurfLastNum;
static const int MAX_POINTS = 40000;
float pointSearchCornerInd1[MAX_POINTS];
float pointSearchCornerInd2[MAX_POINTS];
float pointSearchSurfInd1[MAX_POINTS];
float pointSearchSurfInd2[MAX_POINTS];
float pointSearchSurfInd3[MAX_POINTS];
static const int DOF = 6;
float transformation[DOF];
float transformSum[DOF];
public:
class Inputs : public ScanRegistration::Outputs {};
class Outputs {
public:
pcl::PointCloud<PointType>::Ptr corners, surfels, cloud;
std::vector<float> t;
Outputs() :
corners(new pcl::PointCloud<PointType>),
surfels(new pcl::PointCloud<PointType>),
cloud(new pcl::PointCloud<PointType>),
t(6, 0) {
}
};
LaserOdometry(float scanPeriod_) :
scanPeriod(scanPeriod_),
imuRollStart(0.0), imuPitchStart(0.0), imuYawStart(0.0),
imuRollLast(0.0), imuPitchLast(0.0), imuYawLast(0.0),
imuShiftFromStartX(0.0), imuShiftFromStartY(0.0), imuShiftFromStartZ(0.0),
imuVeloFromStartX(0.0), imuVeloFromStartY(0.0), imuVeloFromStartZ(0.0),
isDegenerate(false),
laserCloudCornerLastNum(0),
laserCloudSurfLastNum(0),
laserCloudCornerLast(new pcl::PointCloud<PointType>),
laserCloudSurfLast(new pcl::PointCloud<PointType>) {
std::fill(transformation, &(transformation[DOF]), 0.0);
std::fill(transformSum, &(transformSum[DOF]), 0.0);
std::fill(pointSearchCornerInd1, &(pointSearchCornerInd1[MAX_POINTS]), 0.0);
std::fill(pointSearchCornerInd2, &(pointSearchCornerInd2[MAX_POINTS]), 0.0);
std::fill(pointSearchSurfInd1, &(pointSearchSurfInd1[MAX_POINTS]), 0.0);
std::fill(pointSearchSurfInd2, &(pointSearchSurfInd2[MAX_POINTS]), 0.0);
std::fill(pointSearchSurfInd3, &(pointSearchSurfInd3[MAX_POINTS]), 0.0);
}
void run(LaserOdometry::Inputs &inputs, LaserOdometry::Outputs &outputs);
void updateImu(const pcl::PointCloud<pcl::PointXYZ> &imuTrans);
protected:
void transformToStart(const PointType &pi, float *curr_transform, PointType &po);
void transformToEnd(pcl::PointCloud<PointType>::Ptr points, float *curr_transform);
void pluginIMURotation(float bcx, float bcy, float bcz,
float blx, float bly, float blz,
float alx, float aly, float alz,
float &acx, float &acy, float &acz);
void accumulateRotation(float cx, float cy, float cz, float lx, float ly, float lz,
float &ox, float &oy, float &oz);
void accumulateTransformation(const float *t_increment, float *t_sum);
bool getCornerFeatureCoefficients(const PointType &A, const PointType &B,
const PointType &X, int iterration, PointType &coeff);
bool getSurfaceFeatureCoefficients(const PointType &A, const PointType &B, const PointType &C,
const PointType &X, int iterration, PointType &coefficients);
};
#endif
|
#include "DataBaseConnector.h"
DataBaseConnector::DataBaseConnector(std::string companyName) :
uri("mongodb://localhost:27017"),
client(uri) {
db = client[companyName];
}
bool DataBaseConnector::userIsRegistered(std::string &login) {
mongocxx::collection coll = db["users"];
if (coll.find_one(document{} << "login" << login << finalize))
return true;
else
return false;
}
void DataBaseConnector::authorizeUser(std::string &login) {
mongocxx::collection coll = db["authorized_users"];
bsoncxx::stdx::optional<mongocxx::result::insert_one> result = coll.insert_one(document{} << "login" << login << finalize);
}
bool DataBaseConnector::userIsAuthorized(std::string &login) {
mongocxx::collection coll = db["authorized_users"];
if (coll.find_one(document{} << "login" << login << finalize))
return true;
else
return false;
}
void DataBaseConnector::logoutUser(std::string &login) {
mongocxx::collection coll = db["authorized_users"];
coll.delete_one(document{} << "login" << login << finalize);
}
void DataBaseConnector::addMessage(boost::property_tree::ptree ¶ms) {
int chatId = params.get<int>("body.chatId");
params.put("body.ownerId", params.get<int>("body.ownerId"));
params.put("body.chatId", params.get<int>("body.chatId"));
mongocxx::collection coll = db[std::to_string(chatId)];
boost::property_tree::ptree messageBody = params.get_child("body");
makeMessagesInChatChecked(chatId, params.get<int>("globalId"));
int messagesCount = getChatMessagesCount(chatId);
messageBody.add("number", messagesCount + 1);
coll.update_one(document{} << "type" << "chat_data" << finalize,
document{} << "$set" << open_document << "messages_count" << messagesCount + 1 << close_document << finalize);
std::stringstream messageStream;
boost::property_tree::json_parser::write_json(messageStream, messageBody);
bsoncxx::document::value messageDoc = bsoncxx::from_json(messageStream.str());
bsoncxx::stdx::optional<mongocxx::result::insert_one> result = coll.insert_one(messageDoc.view());
params.put_child("chat_members", getChatMembers(chatId));
}
void DataBaseConnector::createChat(boost::property_tree::ptree ¶ms) {
params.put_child("body.members_list", boost::property_tree::ptree());
auto &membersList = params.get_child("body.members_list");
mongocxx::collection coll = db["chats_info"];
bsoncxx::stdx::optional<bsoncxx::document::value> chatInfo = coll.find_one(document{} << "type" << "chats_info" << finalize);
boost::property_tree::ptree chatInfoPtree;
std::string chatInfoStr(bsoncxx::to_json(*chatInfo));
std::istringstream chatInfoIStream((chatInfoStr));
boost::property_tree::read_json(chatInfoIStream, chatInfoPtree);
int newChatId = chatInfoPtree.get<int>("chats_count") + 1;
params.put("body.chatId", newChatId);
coll.update_one(document{} << "type" << "chats_info" << finalize,
document{} << "$set" << open_document << "chats_count" << newChatId << close_document << finalize);
coll = db[params.get<std::string>("body.chatId")];
boost::property_tree::ptree body;
body.add("type", "chat_data");
body.add("team_name", params.get<std::string>("body.title"));
std::stringstream chatInfoStream;
boost::property_tree::json_parser::write_json(chatInfoStream, body);
bsoncxx::document::value chatInfoDoc = bsoncxx::from_json(chatInfoStream.str());
bsoncxx::stdx::optional<mongocxx::result::insert_one> result = coll.insert_one(chatInfoDoc.view());
coll.update_one(document{} << "type" << "chat_data" << finalize,
document{} << "$set" << open_document << "messages_count" << 0 << close_document << finalize);
auto membersStr = params.get<std::string>("body.members");
std::stringstream membersStrStream(membersStr);
int memberId;
std::string chatRole;
int i = 0;
std::vector<std::pair<int, std::string>> members;
while (getline(membersStrStream, chatRole, ';')) {
int roleStart = chatRole.find(' ');
memberId = std::stoi(chatRole.substr(0, roleStart));
chatRole = chatRole.substr(roleStart + 1, chatRole.length());
coll.update_one(document{} << "type" << "chat_data" << finalize,
document{} << "$push" << open_document << "members_id"
<< memberId << close_document << finalize);
members.emplace_back(memberId, chatRole);
i++;
boost::property_tree::ptree chat;
chat.put("", memberId);
membersList.push_back(std::make_pair("", chat));
}
coll = db["users"];
for (auto &member : members) {
coll.update_one(document{} << "userId" << member.first << finalize,
document{} << "$push" << open_document << "chatsId" << newChatId << close_document << finalize);
coll.update_one(document{} << "userId" << member.first << finalize,
document{} << "$set" << open_document << "team_roles." + std::to_string(newChatId) << member.second << close_document << finalize);
}
bsoncxx::stdx::optional<bsoncxx::document::value> userDataDoc = coll.find_one(document{} << "type" << "users_data" << finalize);
boost::property_tree::ptree userDataPtree;
std::string userDataStr(bsoncxx::to_json(*userDataDoc));
std::istringstream userDataIStream((userDataStr));
boost::property_tree::read_json(userDataIStream, userDataPtree);
int managersCount = userDataPtree.get<int>("managers_count");
for (int manager = -1; manager >= -managersCount; manager--) {
boost::property_tree::ptree member;
member.put("", manager);
membersList.push_back(std::make_pair("", member));
mongocxx::collection chat = db[std::to_string(newChatId)];
chat.update_one(document{} << "type" << "chat_data" << finalize,
document{} << "$push" << open_document << "members_id" << manager
<< close_document << finalize);
coll.update_one(document{} << "userId" << manager << finalize,
document{} << "$push" << open_document << "chatsId" << newChatId
<< close_document << finalize);
coll.update_one(document{} << "userId" << manager << finalize,
document{} << "$set" << open_document << "team_roles." + std::to_string(newChatId) << "manager"
<< close_document << finalize);
}
mongocxx::collection chat = db[std::to_string(newChatId)];
chat.update_one(document{} << "type" << "chat_data" << finalize,
document{} << "$push" << open_document << "members_id" << 0
<< close_document << finalize);
coll.update_one(document{} << "userId" << 0 << finalize,
document{} << "$set" << open_document << "team_roles." + std::to_string(newChatId) << "company"
<< close_document << finalize);
coll.update_one(document{} << "userId" << 0 << finalize,
document{} << "$push" << open_document << "chatsId" << newChatId
<< close_document << finalize);
boost::property_tree::ptree member;
member.put("", 0);
membersList.push_back(std::make_pair("", member));
params.put("body.chatId", newChatId);
params.put("body.chatName", params.get<std::string>("body.title"));
}
void DataBaseConnector::deleteChat(boost::property_tree::ptree ¶ms) {
mongocxx::collection coll = db[params.get<std::string>("body.chatId")];
coll.drop();
}
void DataBaseConnector::deleteUser(boost::property_tree::ptree ¶ms) {
mongocxx::collection coll = db["users"];
coll.delete_one(document{} << "login" << params.get<std::string>("body.login") << finalize);
}
void DataBaseConnector::createUser(boost::property_tree::ptree ¶ms) {
mongocxx::collection coll = db["users"];
bsoncxx::stdx::optional<bsoncxx::document::value> userDataDoc = coll.find_one(document{} << "type" << "users_data" << finalize);
boost::property_tree::ptree userDataPtree;
std::string userDataStr(bsoncxx::to_json(*userDataDoc));
std::istringstream userDataIStream((userDataStr));
boost::property_tree::read_json(userDataIStream, userDataPtree);
int newUserId;
if (params.get<std::string>("body.role") == "employee") {
newUserId = userDataPtree.get<int>("employees_count") + 1;
coll.update_one(document{} << "type" << "users_data" << finalize,
document{} << "$set" << open_document << "employees_count" << newUserId << close_document << finalize);
} else if (params.get<std::string>("body.role") == "manager") {
newUserId = -(userDataPtree.get<int>("managers_count") + 1);
coll.update_one(document{} << "type" << "users_data" << finalize,
document{} << "$set" << open_document << "managers_count" << -newUserId << close_document << finalize);
}
coll.insert_one(document{} << "userId" << newUserId << finalize);
coll.update_one(document{} << "userId" << newUserId << finalize,
document{} << "$set" << open_document << "login" << params.get<std::string>("body.login")
<< "password" << params.get<std::string>("body.password")
<< "firstName" << params.get<std::string>("body.firstName")
<< "lastName" << params.get<std::string>("body.lastName")
<< "role" << params.get<std::string>("body.role")
<< close_document << finalize);
if (params.get<std::string>("body.role") == "manager") {
mongocxx::collection collChatsInfo = db["chats_info"];
bsoncxx::stdx::optional<bsoncxx::document::value> chatInfoDoc = collChatsInfo.find_one(document{} << "type" << "chats_info" << finalize);
boost::property_tree::ptree chatInfoPtree;
std::string chatInfoStr(bsoncxx::to_json(*chatInfoDoc));
std::istringstream chatInfoIStream((chatInfoStr));
boost::property_tree::read_json(chatInfoIStream, chatInfoPtree);
int chatsCount = chatInfoPtree.get<int>("chats_count");
for (int chatId = 1; chatId <= chatsCount; chatId++) {
mongocxx::collection chat = db[std::to_string(chatId)];
chat.update_one(document{} << "type" << "chat_data" << finalize,
document{} << "$push" << open_document << "members_id" << newUserId
<< close_document << finalize);
coll.update_one(document{} << "userId" << newUserId << finalize,
document{} << "$push" << open_document << "chatsId" << chatId
<< close_document << finalize);
coll.update_one(document{} << "userId" << newUserId << finalize,
document{} << "$set" << open_document << "team_roles." + std::to_string(chatId) << "manager"
<< close_document << finalize);
}
}
}
void DataBaseConnector::getUserInfo(boost::property_tree::ptree ¶ms) {
mongocxx::collection coll = db["users"];
bsoncxx::stdx::optional<bsoncxx::document::value> userInfoDoc = coll.find_one(document{} << "login" << params.get<std::string>("body.login") << finalize);
boost::property_tree::ptree userInfoPtree;
std::string userInfoStr(bsoncxx::to_json(*userInfoDoc));
std::istringstream userInfoIStream((userInfoStr));
boost::property_tree::read_json(userInfoIStream, userInfoPtree);
params.add("body.userId", userInfoPtree.get<int>("userId"));
params.add("body.chatsId", userInfoPtree.get<std::string>("chatsId"));
params.add("body.firstName", userInfoPtree.get<std::string>("firstName"));
params.add("body.lastName", userInfoPtree.get<std::string>("lastName"));
params.add("body.role", userInfoPtree.get<std::string>("role"));
params.add("body.company", userInfoPtree.get<std::string>("company"));
params.add_child("body.chatsId", userInfoPtree.get_child("chatsId"));
}
void DataBaseConnector::getUserChatsPreview(boost::property_tree::ptree ¶ms) {
mongocxx::collection coll = db["users"];
int userId = params.get<int>("globalId");
params.put_child("body.chats", boost::property_tree::ptree());
auto &array = params.get_child("body.chats");
std::vector<int> userChatIds = getUserChats(userId);
for (int userChatId : userChatIds) {
boost::property_tree::ptree chat;
chat.add("chatId", userChatId);
chat.add("chatName", getTeamName(userChatId));
array.push_back(std::make_pair("", chat));
}
}
std::vector<int> DataBaseConnector::getUserChats(int userId) {
mongocxx::collection coll = db["users"];
bsoncxx::stdx::optional<bsoncxx::document::value> doc = coll.find_one(document{} << "userId" << userId << finalize);
boost::property_tree::ptree pt;
std::string docStr(bsoncxx::to_json(*doc));
std::istringstream is((docStr));
boost::property_tree::read_json(is, pt);
std::vector<int> userChats;
for (auto &chatId : pt.get_child("chatsId")) {
userChats.push_back(chatId.second.get<int>(""));
}
return userChats;
}
boost::property_tree::ptree DataBaseConnector::getChatLastMessage(int chatId) {
mongocxx::collection coll = db[std::to_string(chatId)];
bsoncxx::stdx::optional<bsoncxx::document::value> doc = coll.find_one(document{} << "type" << "chat_data" << finalize);
boost::property_tree::ptree pt;
std::string docStr(bsoncxx::to_json(*doc));
std::istringstream is((docStr));
boost::property_tree::read_json(is, pt);
int lastMessageId = pt.get<int>("messages_count");
if (lastMessageId) {
doc = coll.find_one(document{} << "number" << std::to_string(lastMessageId) << finalize);
std::string docStr1(bsoncxx::to_json(*doc));
std::istringstream is1((docStr1));
boost::property_tree::read_json(is1, pt);
return pt;
}
else
return boost::property_tree::ptree();
}
std::string DataBaseConnector::getTeamName(int chatId) {
mongocxx::collection coll = db[std::to_string(chatId)];
bsoncxx::stdx::optional<bsoncxx::document::value> doc = coll.find_one(document{} << "type" << "chat_data" << finalize);
boost::property_tree::ptree pt;
std::string docStr(bsoncxx::to_json(*doc));
std::istringstream is((docStr));
boost::property_tree::read_json(is, pt);
std::string teamName = pt.get<std::string>("team_name");
return teamName;
}
void DataBaseConnector::getChatInfo(boost::property_tree::ptree ¶ms) {
int chatId = params.get<int>("body.chatId");
mongocxx::collection coll = db[std::to_string(chatId)];
bsoncxx::stdx::optional<bsoncxx::document::value> doc = coll.find_one(document{} << "type" << "chat_data" << finalize);
boost::property_tree::ptree pt;
std::string docStr(bsoncxx::to_json(*doc));
std::istringstream is((docStr));
boost::property_tree::read_json(is, pt);
params.add("body.chatName", pt.get<std::string>("team_name"));
params.add_child("body.usersId", pt.get_child("members_id"));
}
int DataBaseConnector::getChatMessagesCount(int chatId) {
mongocxx::collection coll = db[std::to_string(chatId)];
bsoncxx::stdx::optional<bsoncxx::document::value> doc = coll.find_one(document{} << "type" << "chat_data" << finalize);
boost::property_tree::ptree pt;
std::string docStr(bsoncxx::to_json(*doc));
std::istringstream is((docStr));
boost::property_tree::read_json(is, pt);
return pt.get<int>("messages_count");
}
void DataBaseConnector::getChatMessages(boost::property_tree::ptree ¶ms) {
int chatId = params.get<int>("body.chatId");
mongocxx::collection coll = db[std::to_string(chatId)];
bsoncxx::stdx::optional<bsoncxx::document::value> doc = coll.find_one(document{} << "type" << "chat_data" << finalize);
boost::property_tree::ptree pt;
std::string docStr(bsoncxx::to_json(*doc));
std::istringstream is((docStr));
boost::property_tree::read_json(is, pt);
int lastMessageId = pt.get<int>("messages_count");
int userLastMessageId = params.get<int>("body.lastMessageNum");
makeMessagesInChatChecked(chatId, params.get<int>("globalId"));
params.put_child("body.messages", boost::property_tree::ptree());
auto &array = params.get_child("body.messages");
for (int i = userLastMessageId + 1; i <= lastMessageId; i++) {
bsoncxx::stdx::optional<bsoncxx::document::value> doc1 = coll.find_one(document{} << "number" << std::to_string(i) << finalize);
boost::property_tree::ptree pt1;
std::string docStr1(bsoncxx::to_json(*doc1));
std::istringstream is1((docStr1));
boost::property_tree::read_json(is1, pt1);
array.push_back(std::make_pair("", pt1));
}
params.put_child("chat_members", getChatMembers(chatId));
}
void DataBaseConnector::getMessageAuthorInfo(boost::property_tree::ptree ¶ms) {
mongocxx::collection coll = db["users"];
bsoncxx::stdx::optional<bsoncxx::document::value> doc = coll.find_one(document{} << "userId" << params.get<int>("body.userId") << finalize);
boost::property_tree::ptree pt;
std::string docStr(bsoncxx::to_json(*doc));
std::istringstream is((docStr));
boost::property_tree::read_json(is, pt);
params.add("body.firstName", pt.get<std::string>("firstName"));
params.add("body.lastName", pt.get<std::string>("lastName"));
params.add("body.role", pt.get<std::string>("team_roles." + std::to_string(params.get<int>("body.chatId"))));
}
void DataBaseConnector::logRequest(boost::property_tree::ptree ¶ms) {
mongocxx::collection coll = db["0"];
boost::property_tree::ptree body = params;
int messagesCount = getChatMessagesCount(0);
body.add("number", messagesCount + 1);
coll.update_one(document{} << "type" << "chat_data" << finalize,
document{} << "$set" << open_document << "messages_count" << messagesCount + 1 << close_document << finalize);
std::stringstream messageStream;
boost::property_tree::json_parser::write_json(messageStream, body);
bsoncxx::document::value messageDoc = bsoncxx::from_json(messageStream.str());
bsoncxx::stdx::optional<mongocxx::result::insert_one> result = coll.insert_one(messageDoc.view());
}
boost::property_tree::ptree DataBaseConnector::getChatMembers(int chatId) {
mongocxx::collection coll = db[std::to_string(chatId)];
bsoncxx::stdx::optional<bsoncxx::document::value> doc = coll.find_one(document{} << "type" << "chat_data" << finalize);
boost::property_tree::ptree pt;
std::string docStr(bsoncxx::to_json(*doc));
std::istringstream is((docStr));
boost::property_tree::read_json(is, pt);
return pt.get_child("members_id");
}
void DataBaseConnector::makeMessagesInChatChecked(int chatId, int userId) {
mongocxx::collection coll = db[std::to_string(chatId)];
mongocxx::cursor cursor = coll.find(document{} << "isChecked" << "false" << finalize);
coll.update_many(document{} << "isChecked" << "false" << "ownerId" << open_document << "$ne" << std::to_string(userId) << close_document << finalize,
document{} << "$set" << open_document << "isChecked" << "true" << close_document << finalize);
}
void DataBaseConnector::getServerLogs(boost::property_tree::ptree ¶ms) {
mongocxx::collection coll = db["0"];
bsoncxx::stdx::optional<bsoncxx::document::value> doc = coll.find_one(document{} << "type" << "chat_data" << finalize);
boost::property_tree::ptree pt;
std::string docStr(bsoncxx::to_json(*doc));
std::istringstream is((docStr));
boost::property_tree::read_json(is, pt);
int lastMessageId = pt.get<int>("messages_count");
int userLastMessageId = params.get<int>("body.lastMessageNum");
if (userLastMessageId == -1)
userLastMessageId = 0;
params.put_child("body.logs", boost::property_tree::ptree());
auto &array = params.get_child("body.logs");
for (int i = userLastMessageId + 1; i <= lastMessageId; i++) {
bsoncxx::stdx::optional<bsoncxx::document::value> doc1 = coll.find_one(document{} << "number" << std::to_string(i) << finalize);
boost::property_tree::ptree pt1;
std::string docStr1(bsoncxx::to_json(*doc1));
std::istringstream is1((docStr1));
boost::property_tree::read_json(is1, pt1);
array.push_back(std::make_pair("", pt1));
}
}
|
#ifndef DESKTOP_TASK_QUEUE_H
#define DESKTOP_TASK_QUEUE_H
class OpTask
{
public:
virtual ~OpTask() {}
virtual void Execute() = 0;
};
/** DesktopTaskQueue is a pi class that conceptually is an execution queue. Tasks added must be executed one after the
* other, in the order given. UNDER NO CIRCUMSTANCE can tasks on the same queue be executed simultaneously.
* In most cases, that is if you have underutilised porcessor cores, you'd make a new thread.
* In that case you would add the OpTasks to a mutex_lock'ed vector or something have the thread pull them out
* and Execute() them (the mutex lock is there, of course, to prevent adding and removing objects at the same time).
*
* You are not required to do this, however. If all processors are busy or if you are on a single-core
* machine, it is perfectly acceptable to have the Make function return a SynchronousTaskQueue
* (see desktop_util/SychronousTaskQueue.h). The synchronous task queue will simply call
* task->Execute() inline rather than doing anything fancy. There is NOTHING wrong with the synchronous queue, and
* it is probably the most efficient if the machine is strapped for resources. Having heurisics for when to use it
* will probably be more efficient than creating more threads than the machine can handle.
*
* For instance, if the machine has 1 dual-core processor, with no other tasks really doing much, you might want to
* return a threaded task queue at the first call to DesktopTaskQueue::Make and SynchronousTaskQueue after that until
* the threaded queue has finished. Systems vary a lot, though, so profile.
*
* If you ARE implementing a proper threaded queue it might be worthwile to check out the pthread'ed implementation
* in platforms/mac/pi/posix_task_queue.h. Most threading implentations are pretty close, so it might just be a matter of renaming a few
* functions.
*/
class DesktopTaskQueue
{
public:
static OP_STATUS Make(DesktopTaskQueue** new_queue);
/** Destroy the queue. When this function returns, all tasks MUST be completed.
* essentially, the main thread must join with the queue thread.
*/
virtual ~DesktopTaskQueue() {}
/** Add the given task to the queue to be executed. All tasks added this way MUST be executed in the
* order given, although the timing is up to the implentor.
* You are responsible for deleting the task when it has been dealt with.
*/
virtual void AddTask(OpTask* task) = 0;
/** Execute this task as soon as possible (waiting for any currently executing task to finish).
* This is needed for tasks that need to return a status code to the caller.
* DO NOT RETURN UNTIL THE TASK HAS COMPLETED.
* You are responsible for deleting the task when it has been dealt with.
* Only use this call if you have to: It really hurts performance.
*/
virtual void HandleSynchronousTask(OpTask* task) = 0;
/** Wait for the entire queue of tasks to finish, then execute the given task.
* This is needed for tasks that not only need to report completion status to caller, but is also
* dependant on the thread's state matching that of the caller.
* DO NOT RETURN UNTIL EVERYTHING HAS COMPLETED.
* You are responsible for deleting the task when it has been dealt with.
* Only use this call if you have to: It really hurts performance.
*/
virtual void HandleSynchronousTaskWhenDone(OpTask* task) = 0;
};
#endif // DESKTOP_TASK_QUEUE_H
|
#include <stdlib.h>
#include <samplerate.h>
#include <iostream>
#include "pitchContour.h"
using std::cout;
using std::cin;
using std::endl;
JackClient::JackClient() :
JackCpp::AudioIO("pitchContour", 1, 1)
{
start();
sample_rate = getSampleRate();
if (sample_rate != 48000){
cout << "sample rate must be 48000 for even downsampling\n";
close();
exit(0);
}
downsampled_len = (float)desired_sample_rate / sample_rate * input_len;
downsampled_frames = new float[downsampled_len];
// Initialize pitch class
pitch = new Pitch(downsampled_len, desired_sample_rate);
}
JackClient::~JackClient()
{
// delete[] input_frames;
delete[] downsampled_frames;
close();
}
int JackClient::audioCallback(jack_nframes_t nframes, audioBufVector inBufs, audioBufVector outBufs)
{
if (nframes == input_len){
// input_frames = (float*)&inBufs[0];
//processAudio();
// outBufs[0] = downsampled_frames;
memcpy(outBufs[0], inBufs[0], sizeof(float)*input_len);
}
return 0;
}
/* Magic happenens here. */
void JackClient::processAudio()
{
downSample();
// float the_pitch = pitch->getPitch(downsampled_frames, downsampled_len);
// cout << the_pitch << endl;
}
void JackClient::downSample()
{
SRC_DATA src_data;
src_data.data_in = input_frames;
src_data.data_out = downsampled_frames;
src_data.input_frames = input_len;
src_data.output_frames = downsampled_len;
src_data.src_ratio = (float)desired_sample_rate / sample_rate;
int return_val = src_simple( &src_data, SRC_SINC_MEDIUM_QUALITY, 1);
if (return_val != 0){
const char* error_string = src_strerror(return_val);
cout << error_string << endl;
}
}
|
//Q 7
#include"stdio.h"
#include"conio.h"
void main()
{
clrscr();
int largest=0;
int smallest=0;
int A[5][5]={ 5, 2, 3, 6, 10,
7, 9, 8, 4, 15,
17, 29,38,44, 55,
37,119,98,34,215,
87, 90, 1,46,105};
int i, j; //for forLoop
for(i=0; i<5; i++){
for(j=0; j<5; j++)
if(A[i][j]>largest)
largest=A[i][j];
}
smallest=A[0][0];
for(i=0; i<5; i++){
for(j=0; j<5; j++)
if(A[i][j]<smallest){
smallest=A[i][j];
// printf("\nThe Smallest value is : %d",smallest);
}
}
printf("\nThe Largest value is : %d",largest);
printf("\nThe Smallest value is : %d",smallest);
getch();
}
|
/*
* Control_Module_Door_From_UART.cpp
*
* Created: 6/10/2015 1:11:03 PM
* Author: Jimmy
*/
#define F_CPU 16000000L
#include <avr/io.h>
#include "MEGA88A_UART_LIBRARY.h"
#include <util/delay.h>
//Initializes an LED attached to Port B pin 0.
void LED_Init() {
DDRB |= (1<<DDB0);
PORTB |= (1<<DDB0);
}
void LED_blink() {
PORTB ^= (1<<DDB0);
_delay_ms(1000);
PORTB ^= (1<<DDB0);
_delay_ms(1000);
}
void initStrikePin() {
DDRC |= (1<<DDC1);
}
void strikeOn() {
PORTC |= (1<<DDC1);
}
void strikeOff() {
PORTC &= ~(1<<DDC1);
}
int main(void)
{
int i;
LED_Init();
for(i=0;i<3;i++){
LED_blink();
}
initUart();
initStrikePin();
while(1)
{
uint8_t letter;
letter = USART_ReceiveByte();
USART_SendByte(letter);
if(letter == 'O') {
strikeOn();
}
else {
strikeOff();
}
}
}
|
/*
* @Description: front end 任务管理, 放在类里使代码更清晰
* @Author: Ren Qian
* @Date: 2020-02-10 08:38:42
*/
#include "lidar_localization/mapping/front_end/front_end_flow.hpp"
#include "glog/logging.h"
#include "lidar_localization/global_defination/global_defination.h"
namespace lidar_localization {
FrontEndFlow::FrontEndFlow(ros::NodeHandle& nh, std::string cloud_topic, std::string odom_topic) {
cloud_sub_ptr_ = std::make_shared<CloudSubscriber>(nh, cloud_topic, 100000);
laser_odom_pub_ptr_ = std::make_shared<OdometryPublisher>(nh, odom_topic, "/map", "/lidar", 100);
front_end_ptr_ = std::make_shared<FrontEnd>();
}
bool FrontEndFlow::Run() {
if (!ReadData())
return false;
while(HasData()) {
if (!ValidData())
continue;
if (UpdateLaserOdometry()) {
PublishData();
}
}
return true;
}
bool FrontEndFlow::ReadData() {
cloud_sub_ptr_->ParseData(cloud_data_buff_);
return true;
}
bool FrontEndFlow::HasData() {
return cloud_data_buff_.size() > 0;
}
bool FrontEndFlow::ValidData() {
current_cloud_data_ = cloud_data_buff_.front();
cloud_data_buff_.pop_front();
return true;
}
bool FrontEndFlow::UpdateLaserOdometry() {
static bool odometry_inited = false;
if (!odometry_inited) {
odometry_inited = true;
front_end_ptr_->SetInitPose(Eigen::Matrix4f::Identity());
return front_end_ptr_->Update(current_cloud_data_, laser_odometry_);
}
return front_end_ptr_->Update(current_cloud_data_, laser_odometry_);
}
bool FrontEndFlow::PublishData() {
laser_odom_pub_ptr_->Publish(laser_odometry_, current_cloud_data_.time);
return true;
}
}
|
#pragma once
#ifdef QP_SOLVER_SPARSE
#include <Eigen/Sparse>
#endif
#include <Eigen/Dense>
#include <limits>
#include <vector>
#define QP_SOLVER_PRINTING
namespace qp_solver {
/** Quadratic Problem
* minimize 0.5 x' P x + q' x
* subject to l <= A x <= u
*/
template <typename Scalar = double>
struct QuadraticProblem {
using Vector = Eigen::Matrix<Scalar, Eigen::Dynamic, 1>;
#ifdef QP_SOLVER_SPARSE
using Matrix = Eigen::SparseMatrix<Scalar>;
Eigen::Matrix<int, Eigen::Dynamic, 1> P_col_nnz;
Eigen::Matrix<int, Eigen::Dynamic, 1> A_col_nnz;
#else
using Matrix = Eigen::Matrix<Scalar, Eigen::Dynamic, Eigen::Dynamic>;
#endif
const Matrix *P;
const Vector *q;
const Matrix *A;
const Vector *l;
const Vector *u;
};
template <typename Scalar>
struct QPSolverSettings {
Scalar rho = 1e-1; /**< ADMM rho step, 0 < rho */
Scalar sigma = 1e-6; /**< ADMM sigma step, 0 < sigma, (small) */
Scalar alpha = 1.0; /**< ADMM overrelaxation parameter, 0 < alpha < 2,
values in [1.5, 1.8] give good results (empirically) */
Scalar eps_rel = 1e-3; /**< Relative tolerance for termination, 0 < eps_rel */
Scalar eps_abs = 1e-3; /**< Absolute tolerance for termination, 0 < eps_abs */
int max_iter = 1000; /**< Maximal number of iteration, 0 < max_iter */
int check_termination = 25; /**< Check termination after every Nth iteration, 0 (disabled) or 0
< check_termination */
bool warm_start = false; /**< Warm start solver, reuses previous x,z,y */
bool adaptive_rho = false; /**< Adapt rho to optimal estimate */
Scalar adaptive_rho_tolerance =
5; /**< Minimal for rho update factor, 1 < adaptive_rho_tolerance */
int adaptive_rho_interval = 25; /**< change rho every Nth iteration, 0 < adaptive_rho_interval,
set equal to check_termination to save computation */
bool verbose = false;
#ifdef QP_SOLVER_PRINTING
void print() const {
printf("ADMM settings:\n");
printf(" sigma %.2e\n", sigma);
printf(" rho %.2e\n", rho);
printf(" alpha %.2f\n", alpha);
printf(" eps_rel %.1e\n", eps_rel);
printf(" eps_abs %.1e\n", eps_abs);
printf(" max_iter %d\n", max_iter);
printf(" adaptive_rho %d\n", adaptive_rho);
printf(" warm_start %d\n", warm_start);
}
#endif
};
typedef enum { SOLVED, MAX_ITER_EXCEEDED, UNSOLVED, NUMERICAL_ISSUES, UNINITIALIZED } QPSolverStatus;
template <typename Scalar>
struct QPSolverInfo {
QPSolverStatus status = UNINITIALIZED; /**< Solver status */
int iter = 0; /**< Number of iterations */
int rho_updates = 0; /**< Number of rho updates (factorizations) */
Scalar rho_estimate = 0; /**< Last rho estimate */
Scalar res_prim = 0; /**< Primal residual */
Scalar res_dual = 0; /**< Dual residual */
#ifdef QP_SOLVER_PRINTING
void print() const {
printf("ADMM info:\n");
printf(" status ");
switch (status) {
case SOLVED:
printf("SOLVED\n");
break;
case MAX_ITER_EXCEEDED:
printf("MAX_ITER_EXCEEDED\n");
break;
case UNSOLVED:
printf("UNSOLVED\n");
break;
case NUMERICAL_ISSUES:
printf("NUMERICAL_ISSUES\n");
break;
default:
printf("UNINITIALIZED\n");
};
printf(" iter %d\n", iter);
printf(" rho_updates %d\n", rho_updates);
printf(" rho_estimate %f\n", rho_estimate);
printf(" res_prim %f\n", res_prim);
printf(" res_dual %f\n", res_dual);
}
#endif
};
/**
* minimize 0.5 x' P x + q' x
* subject to l <= A x <= u
*
* with:
* x element of R^n
* Ax element of R^m
*/
template <typename SCALAR>
class QPSolver {
public:
using Scalar = SCALAR;
using QP = QuadraticProblem<Scalar>;
using Vector = Eigen::Matrix<Scalar, Eigen::Dynamic, 1>;
#ifdef QP_SOLVER_SPARSE
using Matrix = Eigen::SparseMatrix<Scalar, Eigen::ColMajor>;
using LinearSolver = Eigen::SimplicialLDLT<Matrix, Eigen::Lower>;
#else
using Matrix = Eigen::Matrix<Scalar, Eigen::Dynamic, Eigen::Dynamic>;
using LinearSolver = Eigen::LDLT<Matrix, Eigen::Lower>;
#endif
using Settings = QPSolverSettings<Scalar>;
using Info = QPSolverInfo<Scalar>;
enum { INEQUALITY_CONSTRAINT, EQUALITY_CONSTRAINT, LOOSE_BOUNDS } ConstraintType;
static constexpr Scalar RHO_MIN = 1e-6;
static constexpr Scalar RHO_MAX = 1e+6;
static constexpr Scalar RHO_TOL = 1e-4;
static constexpr Scalar RHO_EQ_FACTOR = 1e+3;
static constexpr Scalar LOOSE_BOUNDS_THRESH = 1e+16;
static constexpr Scalar DIV_BY_ZERO_REGUL = std::numeric_limits<Scalar>::epsilon();
// enforce 16 byte alignment
// https://eigen.tuxfamily.org/dox/group__TopicStructHavingEigenMembers.html
EIGEN_MAKE_ALIGNED_OPERATOR_NEW
/** Constructor */
QPSolver() = default;
/** Setup solver for QP. */
void setup(const QP &qp);
/** Update solver for QP of same size as initial setup. */
void update_qp(const QP &qp);
/** Solve the QP. */
void solve(const QP &qp);
inline const Vector &primal_solution() const { return x; }
inline Vector &primal_solution() { return x; }
inline const Vector &dual_solution() const { return y; }
inline Vector &dual_solution() { return y; }
inline const Settings &settings() const { return settings_; }
inline Settings &settings() { return settings_; }
inline const Info &info() const { return info_; }
inline Info &info() { return info_; }
/* Public funcitions for unit testing */
static void constr_type_init(const Vector& l, const Vector& u, Eigen::VectorXi &constr_type);
private:
/* Construct the KKT matrix of the form
*
* [[ P + sigma*I, A' ],
* [ A, -1/rho.*I ]]
*
* If LinearSolver_UpLo parameter is Eigen::Lower, then only the lower
* triangular part is constructed to optimize memory.
*
* Note: For Eigen::ConjugateGradient it is advised to set Upper|Lower for
* best performance.
*/
void construct_KKT_mat(const QP &qp);
/** KKT matrix value update, assumes same sparsity pattern */
void update_KKT_mat(const QP &qp);
void update_KKT_rho();
bool factorize_KKT();
bool compute_KKT();
#ifdef QP_SOLVER_SPARSE
void sparse_insert_at(Matrix &dst, int row, int col, const Matrix &src) const
#endif
void form_KKT_rhs(const QP &qp, Vector &rhs);
void box_projection(Vector &z, const Vector &l, const Vector &u);
void constr_type_init(const QP &qp);
void rho_vec_update(Scalar rho0);
void update_state(const QP &qp);
Scalar rho_estimate(const Scalar rho0, const QP &qp) const;
Scalar eps_prim(const QP &qp) const;
Scalar eps_dual(const QP &qp) const;
Scalar residual_prim(const QP &qp) const;
Scalar residual_dual(const QP &qp) const;
bool termination_criteria(const QP &qp);
#ifdef QP_SOLVER_PRINTING
void print_status(const QP &qp) const;
#endif
size_t n; //< number of variables
size_t m; //< number of constraints
// Solver state variables
int iter;
Vector x; //< primal variable, size n
Vector z; //< additional variable, size m
Vector y; //< dual variable, size m
Vector x_tilde;
Vector z_tilde;
Vector z_prev;
Vector rho_vec;
Vector rho_inv_vec;
Scalar rho;
Vector rhs;
Vector x_tilde_nu;
// State
Scalar res_prim;
Scalar res_dual;
Scalar max_Ax_z_norm_;
Scalar max_Px_ATy_q_norm_;
Eigen::VectorXi constr_type; /**< constraint type classification */
Settings settings_;
Info info_;
Matrix kkt_mat;
LinearSolver linear_solver;
};
extern template class QPSolver<double>;
extern template class QPSolver<float>;
} // namespace qp_solver
|
#include <iostream>
#include <vector>
#include <fstream>
#include <string>
#include <cassert>
using namespace std;
class AdjMatrix{
private:
int V;
int E;
int** adj;
void isValidVertex(int v) const{
assert(v >= 0 && v < V);
}
public:
AdjMatrix(string file):V(0), E(0), adj(nullptr){
ifstream f;
f.open(file);
int node1, node2;
f >> V >> E;
adj = new int*[V];
for (int i = 0; i < V; ++i){
adj[i] = new int[V];
}
while (f >> node1 >> node2){
adj[node1][node2] = 1;
adj[node2][node1] = 1;
}
f.close();
}
int getV() const{
return V;
}
int getE() const{
return E;
}
bool hasEdge(int i , int j) const{
isValidVertex(i);
isValidVertex(j);
return adj[i][j] == 1;
}
int getEle(int i, int j) const{
isValidVertex(i);
isValidVertex(j);
return adj[i][j];
}
// return the adjacent nodes of node v
vector<int> adjL(int v){
isValidVertex(v);
vector<int> ans;
for (int i = 0; i < V; ++i){
if (adj[v][i] == 1)
ans.push_back(i);
}
return ans;
}
int degree(int v){
isValidVertex(v);
return adjL(v).size();
}
~AdjMatrix(){
for (int i = 0; i < V; ++i){
delete[] adj[i];
}
delete[] adj;
}
};
ostream& operator<< (ostream& os, const AdjMatrix& adj){
int V = adj.getV();
int E = adj.getE();
os << "V = " << V << ", E = " << E << endl;
for (int i = 0; i < V; ++i){
for (int j = 0; j < V; ++j){
os << adj.getEle(i, j) << ' ';
}
os << endl;
}
return os;
}
int main(){
AdjMatrix adj("g.txt");
cout << adj;
return 0;
}
|
#ifndef CLIENT_VEHICLETABLEMODEL_HPP
#define CLIENT_VEHICLETABLEMODEL_HPP
#include "game/vehicle.hpp"
#include "objecttablemodel.hpp"
class VehicleTableModel : public ObjectTableModel<Game::Vehicle>
{
public:
ObjectTableModel<Game::Vehicle>::Field name;
ObjectTableModel<Game::Vehicle>::Field price;
VehicleTableModel(const Game::Container<Game::Vehicle>& dataSource):
ObjectTableModel(dataSource),
name(this, QObject::trUtf8("Nimi"), [](Game::Vehicle* v){return QVariant(v->getName().c_str());}),
price(this, QObject::trUtf8("Hinta"), [](Game::Vehicle* v){return QVariant(QString::number(v->getPrice()));})
{
}
};
#endif
|
// Spline3Dlg.cpp : implementation file
//
#include "stdafx.h"
#include "Interpolater.h"
#include "Spline3Dlg.h"
#ifdef _DEBUG
#define new DEBUG_NEW
#undef THIS_FILE
static char THIS_FILE[] = __FILE__;
#endif
/////////////////////////////////////////////////////////////////////////////
// CSpline3Dlg dialog
CSpline3Dlg::CSpline3Dlg(CWnd* pParent /*=NULL*/)
: CDialog(CSpline3Dlg::IDD, pParent)
{
//{{AFX_DATA_INIT(CSpline3Dlg)
m_strResult = _T("");
//}}AFX_DATA_INIT
}
void CSpline3Dlg::DoDataExchange(CDataExchange* pDX)
{
CDialog::DoDataExchange(pDX);
//{{AFX_DATA_MAP(CSpline3Dlg)
DDX_Text(pDX, IDC_EDIT1, m_strResult);
//}}AFX_DATA_MAP
}
BEGIN_MESSAGE_MAP(CSpline3Dlg, CDialog)
//{{AFX_MSG_MAP(CSpline3Dlg)
//}}AFX_MSG_MAP
END_MESSAGE_MAP()
/////////////////////////////////////////////////////////////////////////////
// CSpline3Dlg message handlers
BOOL CSpline3Dlg::OnInitDialog()
{
CDialog::OnInitDialog();
// TODO: Add extra initialization here
UpdateData(FALSE);
return TRUE; // return TRUE unless you set the focus to a control
// EXCEPTION: OCX Property Pages should return FALSE
}
|
//: C03:Global2.cpp {O}
// Kod zrodlowy pochodzacy z ksiazki
// "Thinking in C++. Edycja polska"
// (c) Bruce Eckel 2000
// Informacje o prawie autorskim znajduja sie w pliku Copyright.txt
// Dostep do zewnetrznych zmiennych globalnych
extern int globe;
// (Odwolanie zostanie okreslone przez program laczacy)
void func() {
globe = 47;
} ///:~
|
/* -*- Mode: c++; tab-width: 4; c-basic-offset: 4 -*-
*
* Copyright (C) 1995-2008 Opera Software AS. All rights reserved.
*
* This file is part of the Opera web browser.
* It may not be distributed under any circumstances.
*/
#include "core/pch.h"
#if !defined(LIBGOGI_PLATFORM_IMPLEMENTS_OPBITMAP) && !defined(VEGA_OPPAINTER_SUPPORT)
#include "modules/libgogi/pi_impl/mde_opbitmap.h"
#include "modules/libgogi/pi_impl/mde_oppainter.h"
#include "modules/libgogi/mde.h"
/*static*/
OP_STATUS
OpBitmap::Create(OpBitmap **bitmap, UINT32 width, UINT32 height,
BOOL transparent,
BOOL alpha,
UINT32 transpcolor, INT32 indexed,
BOOL must_support_painter)
{
OP_ASSERT(bitmap);
if (!width || !height)
return OpStatus::ERR;
OpBitmap* new_bitmap = OP_NEW(MDE_OpBitmap, ());
if (new_bitmap == NULL)
{
return OpStatus::ERR_NO_MEMORY;
}
OP_STATUS ret = ((MDE_OpBitmap*)new_bitmap)->Init(width, height, transparent, alpha,
transpcolor, indexed, must_support_painter);
if (OpStatus::IsSuccess(ret))
{
*bitmap = new_bitmap;
}
else
{
OP_DELETE(new_bitmap);
*bitmap = 0;
}
return ret;
}
/*static*/
OP_STATUS
OpBitmap::CreateFromIcon(OpBitmap **bitmap, const uni_char* icon_path)
{
OP_ASSERT(FALSE);
return OpStatus::ERR;
}
MDE_OpBitmap::MDE_OpBitmap()
: painter(NULL)
, must_support_painter(FALSE)
#ifdef MDE_SUPPORT_SPLIT_BITMAPS
, current_split_bitmap_elm(NULL)
#endif // MDE_SUPPORT_SPLIT_BITMAPS
, buffer(NULL)
#ifdef LIBGOGI_SUPPORT_CREATE_TILE
, current_tile(NULL)
#endif // LIBGOGI_SUPPORT_CREATE_TILE
, m_initStatus(OpStatus::ERR)
{
}
OP_STATUS MDE_OpBitmap::CreateInternalBuffers(MDE_FORMAT format, int extra)
{
#ifdef MDE_SUPPORT_SPLIT_BITMAPS
if (!must_support_painter)
return CreateSplitBuffers(format);
#endif // MDE_SUPPORT_SPLIT_BITMAPS
#ifdef MDE_LIMIT_IMAGE_SIZE
buffer = MDE_CreateBuffer(real_width, real_height, format, extra);
#else
buffer = MDE_CreateBuffer(width, height, format, extra);
#endif
if (!buffer)
{
return OpStatus::ERR_NO_MEMORY;
}
if (hasAlpha)
buffer->method = MDE_METHOD_ALPHA;
if (extra)
{
// make all palete entries white by default
op_memset(buffer->pal, 255, extra*3);
}
return OpStatus::OK;
}
OP_STATUS MDE_OpBitmap::Init(UINT32 w, UINT32 h, BOOL transparent, BOOL alpha,
UINT32 transcol, INT32 indexed, BOOL must_support_painter)
{
width = w;
height = h;
#ifdef MDE_LIMIT_IMAGE_SIZE
scale = 1;
while ((w*h) / (scale*scale) > MDE_MAX_IMAGE_SIZE)
++scale;
// Make sure the real width/height is always big enough
real_width = (w+scale-1)/scale;
real_height = (h+scale-1)/scale;
#endif // MDE_LIMIT_IMAGE_SIZE
hasAlpha = alpha;
isTransparent = transparent;
transparentColor = transcol;
MDE_FORMAT format;
int extra = 0;
#ifdef SUPPORT_INDEXED_OPBITMAP
isIndexed = indexed != 0;
if (indexed)
{
// FIXME: it is probably better to allocate palette dynamicly
format = MDE_FORMAT_INDEX8;
extra = 256;
}
else
#endif // SUPPORT_INDEXED_OPBITMAP
#ifdef USE_16BPP_OPBITMAP
if (!hasAlpha && !isTransparent)
{
format = MDE_FORMAT_RGB16;
}
else
# ifdef USE_16BPP_ALPHA_OPBITMAP
{
format = MDE_FORMAT_RGBA16;
}
# endif // USE_16BPP_ALPHA_OPBITMAP
#endif // USE_16BPP_OPBITMAP
#if !defined(USE_16BPP_ALPHA_OPBITMAP) || !defined(USE_16BPP_OPBITMAP)
{
#ifdef PLATFORM_COLOR_IS_RGBA
format = MDE_FORMAT_RGBA32;
#else
format = MDE_FORMAT_BGRA32;
#endif // PLATFORM_COLOR_IS_RGBA
}
#endif // !USE_16BPP_ALPHA_OPBITMAP || !USE_16BPP_OPBITMAP
this->must_support_painter = must_support_painter;
if (must_support_painter && !Supports(SUPPORTS_PAINTER))
return OpStatus::ERR_NOT_SUPPORTED;
m_initStatus = CreateInternalBuffers(format, extra);
return m_initStatus;
}
/*virtual*/ BOOL
MDE_OpBitmap::Supports(SUPPORTS supports) const
{
switch (supports)
{
case SUPPORTS_INDEXED:
return TRUE;
#ifndef MDE_SUPPORT_HW_PAINTING
case SUPPORTS_PAINTER:
#if defined(MDE_SUPPORT_SPLIT_BITMAPS) || defined(MDE_LIMIT_IMAGE_SIZE)
return must_support_painter;
#endif
return TRUE;
#endif // MDE_SUPPORT_HW_PAINTING
case SUPPORTS_POINTER:
{
# ifdef PLATFORM_COLOR_IS_RGBA
MDE_FORMAT needed_format = MDE_FORMAT_RGBA32;
# else
MDE_FORMAT needed_format = MDE_FORMAT_BGRA32;
# endif // PLATFORM_COLOR_IS_RGBA
#if defined(MDE_SUPPORT_SPLIT_BITMAPS) || defined(MDE_LIMIT_IMAGE_SIZE)
return must_support_painter && buffer->format == needed_format;
#else
return buffer->format == needed_format;
#endif
}
#ifdef LIBGOGI_SUPPORT_CREATE_TILE
# ifdef SUPPORT_INDEXED_OPBITMAP
case SUPPORTS_CREATETILE:
return !isIndexed;
# else
case SUPPORTS_CREATETILE:
return TRUE;
# endif // SUPPORT_INDEXED_OPBITMAP
#endif // LIBGOGI_SUPPORT_CREATE_TILE
// case SUPPORTS_EFFECT:
default:
return FALSE;
}
}
OpPainter*
MDE_OpBitmap::GetPainter()
{
#ifdef MDE_PLATFORM_IMPLEMENTS_OPPAINTER
extern OpPainter* get_op_painter();
painter = get_op_painter();
#else // MDE_PLATFORM_IMPLEMENTS_OPPAINTER
#if defined(MDE_SUPPORT_SPLIT_BITMAPS) || defined(MDE_LIMIT_IMAGE_SIZE)
if (!must_support_painter)
return NULL;
#endif
#if !defined(MDE_SUPPORT_HW_PAINTING)
if (painter == NULL)
painter = OP_NEW(MDE_OpPainter, ());
if (painter != NULL)
((MDE_OpPainter*)painter)->beginPaint(buffer);
#endif
#endif // MDE_PLATFORM_IMPLEMENTS_OPPAINTER
return painter;
}
/*virtual*/
void
MDE_OpBitmap::ReleasePainter()
{
#ifndef MDE_PLATFORM_IMPLEMENTS_OPPAINTER
if (painter)
((MDE_OpPainter*)painter)->endPaint();
#endif // !MDE_PLATFORM_IMPLEMENTS_OPPAINTER
}
/*virtual*/
OP_STATUS
MDE_OpBitmap::InitStatus()
{
return m_initStatus;
}
MDE_OpBitmap::~MDE_OpBitmap()
{
#ifdef MDE_SUPPORT_SPLIT_BITMAPS
split_bitmap_list.Clear();
#endif // MDE_SUPPORT_SPLIT_BITMAPS
if (buffer)
MDE_DeleteBuffer(buffer);
#ifdef LIBGOGI_SUPPORT_CREATE_TILE
OP_DELETE(current_tile);
#endif // LIBGOGI_SUPPORT_CREATE_TILE
OP_DELETE(painter);
}
UINT32 MDE_OpBitmap::GetBytesPerLine() const{
#ifdef MDE_SUPPORT_SPLIT_BITMAPS
SplitBitmapElm *bmp = FindSplitBitmapElm(0);
if (bmp)
{
#ifdef MDE_LIMIT_IMAGE_SIZE
return width*MDE_GetBytesPerPixel(bmp->buffer->format);
#else
return bmp->buffer->stride;
#endif
}
#endif // MDE_SUPPORT_SPLIT_BITMAPS
#ifdef MDE_LIMIT_IMAGE_SIZE
return width*MDE_GetBytesPerPixel(buffer->format);
#else
return buffer->stride;
#endif
}
/*virtual*/
OP_STATUS
MDE_OpBitmap::AddLine(void* data, INT32 line)
{
MDE_BUFFER* buffer = this->buffer;
int stride;
#ifdef MDE_SUPPORT_SPLIT_BITMAPS
OP_ASSERT(must_support_painter ? buffer != NULL : !split_bitmap_list.Empty());
#else
OP_ASSERT(buffer);
#endif // MDE_SUPPORT_SPLIT_BITMAPS
if (line >= (INT32)height)
return OpStatus::ERR;
#ifdef MDE_LIMIT_IMAGE_SIZE
if (line%scale)
return OpStatus::OK;
line /= scale;
#endif // MDE_LIMIT_IMAGE_SIZE
#ifdef MDE_SUPPORT_SPLIT_BITMAPS
if (!must_support_painter)
{
SplitBitmapElm* split_bitmap_elm = FindSplitBitmapElm(line);
OP_ASSERT(split_bitmap_elm != NULL);
buffer = split_bitmap_elm->buffer;
line -= split_bitmap_elm->y_pos;
}
#endif // MDE_SUPPORT_SPLIT_BITMAPS
void *bufferdata = MDE_LockBuffer(buffer, MDE_MakeRect(0, line, buffer->w, 1), stride, false);
OP_ASSERT(bufferdata);
if (!bufferdata)
return OpStatus::ERR;
#ifdef PLATFORM_COLOR_IS_RGBA
if (buffer->format == MDE_FORMAT_RGBA32)
{
#ifdef MDE_LIMIT_IMAGE_SIZE
for (int pix = 0; pix < real_width; ++pix)
{
((UINT32*)bufferdata)[pix] = ((UINT32*)data)[pix*scale];
}
#else
op_memcpy(static_cast<char*>(bufferdata),
data, width*4);
#endif // MDE_LIMIT_IMAGE_SIZE
}
# ifdef USE_16BPP_OPBITMAP
else if (buffer->format == MDE_FORMAT_RGB16)
{
UINT16 *bufdata = (UINT16*)bufferdata;
// copy the line to the buffer
#ifdef MDE_LIMIT_IMAGE_SIZE
for( unsigned int pixel = 0; pixel < real_width; ++pixel )
#else
for( unsigned int pixel = 0; pixel < width; ++pixel )
#endif
{
#ifdef MDE_LIMIT_IMAGE_SIZE
UINT8* pixel_data = (UINT8*)data+4*pixel*scale;
#else
UINT8* pixel_data = (UINT8*)data+4*pixel;
#endif
int r = pixel_data[0];
int g = pixel_data[1];
int b = pixel_data[2];
bufdata[pixel] = (UINT16)MDE_RGB16(r, g, b);
}
}
# endif // USE_16BPP_OPBITMAP
#elif defined(USE_16BPP_OPBITMAP)
if (buffer->format == MDE_FORMAT_BGRA32)
{
#ifdef MDE_LIMIT_IMAGE_SIZE
for (int pix = 0; pix < real_width; ++pix)
{
((UINT32*)bufferdata)[pix] = ((UINT32*)data)[pix*scale];
}
#else
op_memcpy(static_cast<char*>(bufferdata),
data, width*4);
#endif // MDE_LIMIT_IMAGE_SIZE
}
else if (buffer->format == MDE_FORMAT_RGB16)
{
UINT16 *bufdata = (UINT16*)bufferdata;
// copy the line to the buffer
#ifdef MDE_LIMIT_IMAGE_SIZE
for( unsigned int pixel = 0; pixel < real_width; ++pixel )
{
bufdata[pixel] = (UINT16)MDE_RGB16(((((UINT32*)data)[pixel*scale]&0xff0000)>>16),
((((UINT32*)data)[pixel*scale]&0xff00)>>8),
(((UINT32*)data)[pixel*scale]&0xff));
}
#else
for( unsigned int pixel = 0; pixel < width; ++pixel )
{
bufdata[pixel] = (UINT16)MDE_RGB16(((((UINT32*)data)[pixel]&0xff0000)>>16),
((((UINT32*)data)[pixel]&0xff00)>>8),
(((UINT32*)data)[pixel]&0xff));
}
#endif
}
else if (buffer->format == MDE_FORMAT_RGBA16)
{
UINT16 *bufdata = (UINT16*)bufferdata;
// copy the line to the buffer
#ifdef MDE_LIMIT_IMAGE_SIZE
for( unsigned int pixel = 0; pixel < real_width; ++pixel ){
bufdata[pixel] = (UINT16)MDE_RGBA16(((((UINT32*)data)[pixel*scale]&0xff0000)>>16),
((((UINT32*)data)[pixel*scale]&0xff00)>>8),
(((UINT32*)data)[pixel*scale]&0xff),
(((UINT32*)data)[pixel*scale]>>24));
}
#else
for( unsigned int pixel = 0; pixel < width; ++pixel ){
bufdata[pixel] = (UINT16)MDE_RGBA16(((((UINT32*)data)[pixel]&0xff0000)>>16),
((((UINT32*)data)[pixel]&0xff00)>>8),
(((UINT32*)data)[pixel]&0xff),
(((UINT32*)data)[pixel]>>24));
}
#endif
}
#else // BGRA32
// the rowstride _must_ be a multiple of 4
if (buffer->format == MDE_FORMAT_BGRA32)
{
UINT32 *bufdata = (UINT32*)bufferdata;
// copy the line to the buffer
#ifdef MDE_LIMIT_IMAGE_SIZE
for( unsigned int pixel = 0; pixel < real_width; ++pixel ){
bufdata[pixel] = MDE_RGBA(
((((UINT32*)data)[pixel*scale]&0xff0000)>>16),
((((UINT32*)data)[pixel*scale]&0xff00)>>8),
(((UINT32*)data)[pixel*scale]&0xff),
(((UINT32*)data)[pixel*scale]>>24));
}
#else
for( unsigned int pixel = 0; pixel < width; ++pixel ){
bufdata[pixel] = MDE_RGBA(
((((UINT32*)data)[pixel]&0xff0000)>>16),
((((UINT32*)data)[pixel]&0xff00)>>8),
(((UINT32*)data)[pixel]&0xff),
(((UINT32*)data)[pixel]>>24));
}
#endif
}
#endif // USE_16BPP_OPBITMAP
// FIXME: indexed opbitmap will fail if this is called, is that correct behaviour?
else
{
OP_ASSERT(FALSE);
MDE_UnlockBuffer(buffer, false);
return OpStatus::ERR;
}
MDE_UnlockBuffer(buffer, true);
return OpStatus::OK;
}
#ifdef SUPPORT_INDEXED_OPBITMAP
BOOL MDE_OpBitmap::SetPalette(UINT8* pal, UINT32 num_colors)
{
MDE_BUFFER* buffer = this->buffer;
#ifdef MDE_SUPPORT_SPLIT_BITMAPS
OP_ASSERT(must_support_painter ? buffer != NULL : !split_bitmap_list.Empty());
#else
OP_ASSERT(buffer);
#endif // MDE_SUPPORT_SPLIT_BITMAPS
#ifdef MDE_SUPPORT_SPLIT_BITMAPS
if (!must_support_painter)
buffer = ((SplitBitmapElm*)split_bitmap_list.First())->buffer;
#endif // MDE_SUPPORT_SPLIT_BITMAPS
if (!isIndexed ||buffer->format != MDE_FORMAT_INDEX8 || !buffer->pal)
return FALSE;
if (num_colors > 256)
return FALSE;
#ifdef MDE_SUPPORT_SPLIT_BITMAPS
if (!must_support_painter)
{
for (SplitBitmapElm* elm = (SplitBitmapElm*)split_bitmap_list.First();
elm != NULL;
elm = (SplitBitmapElm*)elm->Suc())
{
op_memcpy(elm->buffer->pal, pal, num_colors*3);
}
}
else
#endif // MDE_SUPPORT_SPLIT_BITMAPS
op_memcpy(buffer->pal, pal, num_colors*3);
return TRUE;
}
BOOL MDE_OpBitmap::GetPalette(UINT8* pal) const
{
MDE_BUFFER* buffer = this->buffer;
#ifdef MDE_SUPPORT_SPLIT_BITMAPS
if (!must_support_painter)
buffer = ((SplitBitmapElm*)split_bitmap_list.First())->buffer;
#endif // MDE_SUPPORT_SPLIT_BITMAPS
if (!buffer->pal)
return FALSE;
op_memcpy(pal, buffer->pal, 256 * 3);
return TRUE;
}
/*virtual*/
OP_STATUS
MDE_OpBitmap::AddIndexedLine(void* data, INT32 line)
{
MDE_BUFFER* buffer = this->buffer;
OP_ASSERT(isIndexed);
if (!isIndexed)
return OpStatus::ERR;
if (line >= (INT32)height)
return OpStatus::ERR;
#ifdef MDE_LIMIT_IMAGE_SIZE
if (line%scale)
return OpStatus::OK;
line /= scale;
#endif // MDE_LIMIT_IMAGE_SIZE
#ifdef MDE_SUPPORT_SPLIT_BITMAPS
if (!must_support_painter)
{
SplitBitmapElm* split_bitmap_elm = FindSplitBitmapElm(line);
OP_ASSERT(split_bitmap_elm);
line -= split_bitmap_elm->y_pos;
buffer = split_bitmap_elm->buffer;
}
#endif // MDE_SUPPORT_SPLIT_BITMAPS
OP_ASSERT(buffer);
int stride;
void *bufferdata = MDE_LockBuffer(buffer, MDE_MakeRect(0, line, buffer->w, 1), stride, false);
OP_ASSERT(bufferdata);
if (!bufferdata)
return OpStatus::ERR;
// copy the data
#ifdef MDE_LIMIT_IMAGE_SIZE
for (unsigned int pixel = 0; pixel < real_width; ++pixel)
{
((unsigned char*)bufferdata)[pixel] = ((unsigned char*)data)[pixel*scale];
}
#else
op_memcpy(((unsigned char*)bufferdata), data, stride);
#endif
MDE_UnlockBuffer(buffer, true);
return OpStatus::OK;
}
#endif // SUPPORT_INDEXED_OPBITMAP
BOOL MDE_OpBitmap::SetColorInternal(MDE_BUFFER* buffer, UINT8* color, const OpRect& rect)
{
unsigned int old_col = buffer->col;
if (buffer->format == MDE_FORMAT_INDEX8)
MDE_SetColor(*((UINT32*)color), buffer);
else
MDE_SetColor(MDE_RGBA( (((*(UINT32*)color)&0xff0000)>>16),
(((*(UINT32*)color)&0xff00)>>8),
((*(UINT32*)color)&0xff),
((*(UINT32*)color)>>24)), buffer);
MDE_DrawRectFill(MDE_MakeRect(rect.x, rect.y, rect.width, rect.height), buffer, false);
MDE_SetColor(old_col, buffer);
return TRUE;
}
BOOL
MDE_OpBitmap::SetColor(UINT8* color, BOOL all_transparent, const OpRect *rect)
{
#ifdef MDE_SUPPORT_SPLIT_BITMAPS
OP_ASSERT(!must_support_painter || buffer);
#else
OP_ASSERT(buffer);
#endif // !MDE_SUPPORT_SPLIT_BITMAPS
OpRect fs;
if (color == NULL && all_transparent == FALSE)
return TRUE;
if (rect == NULL)
{
fs.x = 0;
fs.y = 0;
fs.width = width;
fs.height = height;
rect = &fs;
}
#ifdef MDE_LIMIT_IMAGE_SIZE
// FIXME: should this be rounded?
fs.x = rect->x/scale;
fs.y = rect->y/scale;
fs.width = (rect->x+rect->width)/scale - fs.x;
fs.height = (rect->y+rect->height)/scale - fs.y;
rect = &fs;
#endif
if (all_transparent)
{
if (!isTransparent)
transparentColor = 0;
color = (UINT8*)&transparentColor;
}
#ifdef MDE_SUPPORT_SPLIT_BITMAPS
if (!must_support_painter)
{
BOOL ret = FALSE;
for (SplitBitmapElm* elm = (SplitBitmapElm*)split_bitmap_list.First();
elm != NULL;
elm = (SplitBitmapElm*)elm->Suc())
{
MDE_BUFFER* buffer = elm->buffer;
// We need to make sure that the rect is correct.
OpRect r(0, elm->y_pos, buffer->w, buffer->h);
r.IntersectWith(*rect);
r.y -= elm->y_pos;
if (!r.IsEmpty())
{
ret = SetColorInternal(buffer, color, r);
}
}
return ret;
}
#endif // MDE_SUPPORT_SPLIT_BITMAPS
return SetColorInternal(buffer, color, *rect);
}
/*virtual*/
BOOL
MDE_OpBitmap::GetLineData(void* data, UINT32 line) const
{
MDE_BUFFER* buffer = this->buffer;
#ifdef MDE_SUPPORT_SPLIT_BITMAPS
if (must_support_painter)
#endif // MDE_SUPPORT_SPLIT_BITMAPS
{
OP_ASSERT(buffer);
if (!buffer)
{
return FALSE;
}
}
if( line >= height )
return FALSE;
#ifdef MDE_LIMIT_IMAGE_SIZE
line /= scale;
#endif // MDE_LIMIT_IMAGE_SIZE
#ifdef MDE_SUPPORT_SPLIT_BITMAPS
if (!must_support_painter)
{
SplitBitmapElm* split_bitmap_elm = FindSplitBitmapElm((INT32)line);
OP_ASSERT(split_bitmap_elm != NULL);
buffer = split_bitmap_elm->buffer;
line -= split_bitmap_elm->y_pos;
}
#endif // MDE_SUPPORT_SPLIT_BITMAPS
int stride;
void *bufferdata = MDE_LockBuffer(buffer, MDE_MakeRect(0, line, buffer->w, 1), stride, true);
OP_ASSERT(bufferdata);
if (!bufferdata)
return FALSE;
#ifdef PLATFORM_COLOR_IS_RGBA
if (buffer->format == MDE_FORMAT_RGBA32)
{
#ifdef MDE_LIMIT_IMAGE_SIZE
for (int pixel = 0; pixel < width; ++pixel)
{
((UINT32*)data)[pixel] = ((UINT32*)bufferdata)[pixel/scale];
}
#else
op_memcpy(data, static_cast<char*>(bufferdata), width*4);
#endif
MDE_UnlockBuffer(buffer, false);
return TRUE;
}
else if (buffer->format == MDE_FORMAT_RGB16)
{
UINT16 *bufdata = (UINT16*)bufferdata;
for( unsigned int pixel = 0; pixel < width; ++pixel )
{
#ifdef MDE_LIMIT_IMAGE_SIZE
bufdata = ((UINT16*)bufferdata)+pixel/scale;
#endif
UINT8* pixel_data = ((UINT8*)data)+4*pixel;
pixel_data[0]= MDE_COL_R16(*bufdata);
pixel_data[1]= MDE_COL_G16(*bufdata);
pixel_data[2]= MDE_COL_B16(*bufdata);
pixel_data[3]= 255;
#ifndef MDE_LIMIT_IMAGE_SIZE
++bufdata;
#endif
}
}
# ifdef SUPPORT_INDEXED_OPBITMAP
else if (buffer->format == MDE_FORMAT_INDEX8)
{
UINT8 *bufdata = (UINT8*)bufferdata;
for( unsigned int pixel = 0; pixel < width; ++pixel )
{
UINT8* pixel_data = ((UINT8*)data)+4*pixel;
#ifdef MDE_LIMIT_IMAGE_SIZE
UINT32 color = bufdata[pixel/scale];
#else
UINT32 color = bufdata[pixel];
#endif
pixel_data[0]= buffer->pal[color*3];
pixel_data[1]= buffer->pal[color*3+1];
pixel_data[2]= buffer->pal[color*3+2];
pixel_data[3]= (isTransparent && color == transparentColor) ? 0 : 255;
}
}
# endif
#elif defined USE_16BPP_OPBITMAP
if (buffer->format == MDE_FORMAT_RGB16)
{
UINT16 *bufdata = (UINT16*)bufferdata;
for( unsigned int pixel = 0; pixel < width; ++pixel ){
#ifdef MDE_LIMIT_IMAGE_SIZE
bufdata = ((UINT16*)bufferdata)+pixel/scale;
#endif
((UINT32*)data)[pixel] = (255u<<24)|
(MDE_COL_R16(*bufdata)<<16)|
(MDE_COL_G16(*bufdata)<<8)|
MDE_COL_B16(*bufdata);
#ifndef MDE_LIMIT_IMAGE_SIZE
++bufdata;
#endif
}
}
else if (buffer->format == MDE_FORMAT_RGBA16)
{
UINT16 *bufdata = (UINT16*)bufferdata;
for( unsigned int pixel = 0; pixel < width; ++pixel ){
#ifdef MDE_LIMIT_IMAGE_SIZE
bufdata = ((UINT16*)bufferdata)+pixel/scale;
#endif
((UINT32*)data)[pixel] = (MDE_COL_A16A(*bufdata)<<24)|
(MDE_COL_R16A(*bufdata)<<16)|
(MDE_COL_G16A(*bufdata)<<8)|
MDE_COL_B16A(*bufdata);
#ifndef MDE_LIMIT_IMAGE_SIZE
++bufdata;
#endif
}
}
#else
// the rowstride _must_ be a multiple of 4
if (buffer->format == MDE_FORMAT_BGRA32)
{
UINT32 *bufdata = (UINT32*)bufferdata;
for( unsigned int pixel = 0; pixel < width; ++pixel ){
#ifdef MDE_LIMIT_IMAGE_SIZE
((UINT32*)data)[pixel] = (MDE_COL_A(bufdata[pixel/scale])<<24)|
(MDE_COL_R(bufdata[pixel/scale])<<16)|
(MDE_COL_G(bufdata[pixel/scale])<<8)|
MDE_COL_B(bufdata[pixel/scale]);
#else
((UINT32*)data)[pixel] = (MDE_COL_A(bufdata[pixel])<<24)|
(MDE_COL_R(bufdata[pixel])<<16)|
(MDE_COL_G(bufdata[pixel])<<8)|
MDE_COL_B(bufdata[pixel]);
#endif
}
}
#endif // USE_16BPP_OPBITMAP
#ifdef SUPPORT_INDEXED_OPBITMAP
else if (buffer->format == MDE_FORMAT_INDEX8)
{
UINT8 *bufdata = (UINT8*)bufferdata;
for( unsigned int pixel = 0; pixel < width; ++pixel ){
#ifdef MDE_LIMIT_IMAGE_SIZE
if (isTransparent && bufdata[pixel/scale]==transparentColor)
((UINT32*)data)[pixel] = 0;
else
((UINT32*)data)[pixel] = (255u<<24)|
(buffer->pal[bufdata[pixel/scale]*3] << 16) |
(buffer->pal[bufdata[pixel/scale]*3+1] << 8) |
buffer->pal[bufdata[pixel/scale]*3+2];
#else
if (isTransparent && bufdata[pixel]==transparentColor)
((UINT32*)data)[pixel] = 0;
else
((UINT32*)data)[pixel] = (255u<<24)|
(buffer->pal[bufdata[pixel]*3] << 16) |
(buffer->pal[bufdata[pixel]*3+1] << 8) |
buffer->pal[bufdata[pixel]*3+2];
#endif
}
}
#endif
else if (buffer->format == MDE_FORMAT_BGRA32)
{
op_memcpy(data, bufferdata, width * 4);
}
else
{
OP_ASSERT(FALSE);
MDE_UnlockBuffer(buffer, false);
return FALSE;
}
MDE_UnlockBuffer(buffer, false);
return TRUE;
}
#ifdef SUPPORT_INDEXED_OPBITMAP
BOOL MDE_OpBitmap::GetIndexedLineData(void* data, UINT32 line) const
{
MDE_BUFFER* buffer = this->buffer;
#ifdef MDE_SUPPORT_SPLIT_BITMAPS
if (must_support_painter)
#endif // MDE_SUPPORT_SPLIT_BITMAPS
{
OP_ASSERT(buffer);
if (!buffer)
{
return FALSE;
}
}
if( line >= height )
return FALSE;
#ifdef MDE_LIMIT_IMAGE_SIZE
line /= scale;
#endif // MDE_LIMIT_IMAGE_SIZE
#ifdef MDE_SUPPORT_SPLIT_BITMAPS
if (!must_support_painter)
{
SplitBitmapElm* split_bitmap_elm = FindSplitBitmapElm((INT32)line);
OP_ASSERT(split_bitmap_elm != NULL);
buffer = split_bitmap_elm->buffer;
line -= split_bitmap_elm->y_pos;
}
#endif // MDE_SUPPORT_SPLIT_BITMAPS
int stride;
void *bufferdata = MDE_LockBuffer(buffer, MDE_MakeRect(0, line, buffer->w, 1), stride, true);
OP_ASSERT(bufferdata);
if (!bufferdata)
return FALSE;
OP_ASSERT(buffer->format == MDE_FORMAT_INDEX8);
if (buffer->format == MDE_FORMAT_INDEX8)
{
op_memcpy(data, bufferdata, width);
MDE_UnlockBuffer(buffer, false);
return TRUE;
}
MDE_UnlockBuffer(buffer, false);
return FALSE;
}
#endif // SUPPORT_INDEXED_OPBITMAP
UINT32 MDE_OpBitmap::Width() const{
return width;
}
UINT32 MDE_OpBitmap::Height() const{
return height;
}
UINT8 MDE_OpBitmap::GetBpp() const{
#ifdef MDE_SUPPORT_SPLIT_BITMAPS
MDE_BUFFER* buffer = this->buffer;
if (!must_support_painter)
buffer = ((SplitBitmapElm*)split_bitmap_list.First())->buffer;
#endif // MDE_SUPPORT_SPLIT_BITMAPS
return buffer->ps * 8;
}
BOOL MDE_OpBitmap::HasAlpha() const{
return hasAlpha;
}
BOOL MDE_OpBitmap::IsTransparent() const{
return isTransparent;
}
/*virtual*/
UINT32
MDE_OpBitmap::GetTransparentColorIndex() const
{
return transparentColor;
}
MDE_BUFFER *MDE_OpBitmap::GetMDEBuffer()
{
#ifdef MDE_SUPPORT_SPLIT_BITMAPS
OP_ASSERT(must_support_painter);
#endif
return buffer;
}
#ifdef OPBITMAP_POINTER_ACCESS
void* MDE_OpBitmap::GetPointer(AccessType access_type)
#else
void* MDE_OpBitmap::GetPointer() const
#endif // OPBITMAP_POINTER_ACCESS
{
#if defined(MDE_SUPPORT_SPLIT_BITMAPS) || defined(MDE_LIMIT_IMAGE_SIZE)
if (!must_support_painter)
return NULL;
#endif
int stride;
void *bufferdata = MDE_LockBuffer(buffer, MDE_MakeRect(0, 0, buffer->w, buffer->h), stride, true);
if (bufferdata && stride != buffer->stride)
{
MDE_UnlockBuffer(buffer, false);
return NULL;
}
return bufferdata;
}
#ifdef OPBITMAP_POINTER_ACCESS
void MDE_OpBitmap::ReleasePointer(BOOL changed)
#else
void MDE_OpBitmap::ReleasePointer() const
#endif // OPBITMAP_POINTER_ACCESS
{
#if defined(MDE_SUPPORT_SPLIT_BITMAPS) || defined(MDE_LIMIT_IMAGE_SIZE)
if (!must_support_painter)
return;
#endif
MDE_UnlockBuffer(buffer, true);
}
#ifdef MDE_SUPPORT_SPLIT_BITMAPS
SplitBitmapElm::SplitBitmapElm(MDE_BUFFER* buf, int y)
{
buffer = buf;
y_pos = y;
}
SplitBitmapElm::~SplitBitmapElm()
{
MDE_DeleteBuffer(buffer);
}
SplitBitmapElm* MDE_OpBitmap::GetFirstSplitBitmapElm()
{
current_split_bitmap_elm = (SplitBitmapElm*)split_bitmap_list.First();
return current_split_bitmap_elm;
}
SplitBitmapElm* MDE_OpBitmap::GetNextSplitBitmapElm()
{
if (current_split_bitmap_elm == NULL)
{
return NULL;
}
current_split_bitmap_elm = (SplitBitmapElm*)current_split_bitmap_elm->Suc();
return current_split_bitmap_elm;
}
OP_STATUS MDE_OpBitmap::CreateSplitBuffers(MDE_FORMAT format)
{
int bytes_per_pixel = MDE_GetBytesPerPixel(format);
#ifdef MDE_LIMIT_IMAGE_SIZE
int bytes_per_line = real_width * bytes_per_pixel;
#else
int bytes_per_line = width * bytes_per_pixel;
#endif
unsigned int max_lines = MAX(1, bytes_per_line != 0 ? (MDE_SPLIT_BITMAP_SIZE / bytes_per_line) : 0);
unsigned int y_pos = 0;
int colors = (format == MDE_FORMAT_INDEX8) ? 256 : 0;
BOOL failed = FALSE;
#ifdef MDE_LIMIT_IMAGE_SIZE
while (y_pos < real_height)
{
int split_height = MIN(real_height - y_pos, max_lines);
OP_ASSERT(split_height >= 1);
MDE_BUFFER* buffer = MDE_CreateBuffer(real_width, split_height, format, colors);
#else
while (y_pos < height)
{
int split_height = MIN(height - y_pos, max_lines);
OP_ASSERT(split_height >= 1);
MDE_BUFFER* buffer = MDE_CreateBuffer(width, split_height, format, colors);
#endif
if (buffer == NULL)
{
failed = TRUE;
break;
}
if (format == MDE_FORMAT_INDEX8)
{
// make all palete entries white by default
op_memset(buffer->pal, 255, 256*3);
}
SplitBitmapElm* elm = OP_NEW(SplitBitmapElm, (buffer, y_pos));
if (elm == NULL)
{
MDE_DeleteBuffer(buffer);
failed = TRUE;
break;
}
elm->Into(&split_bitmap_list);
y_pos += split_height;
}
if (failed)
{
split_bitmap_list.Clear();
return OpStatus::ERR_NO_MEMORY;
}
return OpStatus::OK;
}
SplitBitmapElm* MDE_OpBitmap::FindSplitBitmapElm(int line) const
{
SplitBitmapElm* last_elm = NULL;
for (SplitBitmapElm* elm = (SplitBitmapElm*)split_bitmap_list.First();
elm != NULL;
elm = (SplitBitmapElm*)elm->Suc())
{
if (elm->y_pos <= line)
{
last_elm = elm;
}
else
{
return last_elm;
}
}
return last_elm;
}
#endif // MDE_SUPPORT_SPLIT_BITMAPS
#ifdef LIBGOGI_SUPPORT_CREATE_TILE
/* virtual */
OpBitmap* MDE_OpBitmap::GetTile(UINT32 horizontal_count,
UINT32 vertical_count)
{
UINT32 tile_width = horizontal_count * width;
UINT32 tile_height = vertical_count * height;
if ( current_tile == NULL ||
current_tile->width < tile_width ||
current_tile->height < tile_height )
{
#ifdef _DEBUG
// fprintf(stderr, "Had to (re)create a tile of size %dx%d\n",
// tile_width, tile_height);
#endif // _DEBUG
OP_DELETE(current_tile);
current_tile = (MDE_OpBitmap*) CreateTile(tile_width, tile_height);
}
else
{
#ifdef _DEBUG
// fprintf(stderr, "Was able to reuse a tile of size %dx%d\n",
// tile_width, tile_height);
#endif // _DEBUG
}
return current_tile;
}
/* virtual */
void MDE_OpBitmap::ReleaseTile(OpBitmap* tile)
{
OP_ASSERT(tile == current_tile);
if (tile == current_tile)
{
OP_DELETE(tile);
current_tile = NULL;
}
}
/* virtual */
OpBitmap* MDE_OpBitmap::CreateTile(UINT32 tile_width, UINT32 tile_height)
{
// The typical tile is made out of a bitmap like (1,2) or (16,1)
// or something like that so it makes sense to use code that's
// tuned for such sizes
// fprintf(stderr, "Creating tile of dimensions (%u, %u) "
// "from bitmap of size (%u, %u (%d))\n",
// tile_width, tile_height, width, height, (int)bits_per_pixel);
MDE_OpBitmap *tile = OP_NEW(MDE_OpBitmap, ());
if ( tile == NULL )
{
return NULL;
}
#ifdef SUPPORT_INDEXED_OPBITMAP
OP_ASSERT(!isIndexed); // Doesn't handle isIndexed
#endif // SUPPORT_INDEXED_OPBITMAP
OP_STATUS status = tile->Init(tile_width, tile_height, isTransparent,
hasAlpha, transparentColor,
FALSE, // Not indexed
FALSE); // must_support_painter
if (OpStatus::IsError(status))
{
OP_DELETE(tile);
return NULL;
}
int stride;
MDE_BUFFER* mde_buf = buffer;
#ifdef MDE_SUPPORT_SPLIT_BITMAPS
if (!must_support_painter)
mde_buf = GetFirstSplitBitmapElm()->buffer;
#endif // MDE_SUPPORT_SPLIT_BITMAPS
UINT8* src = (UINT8*)MDE_LockBuffer(mde_buf, MDE_MakeRect(0,0,mde_buf->w, mde_buf->h), stride, true);
if (!src)
{
OP_DELETE(tile);
return NULL;
}
UINT8 *pixeldata_end = src + stride * mde_buf->h;
int tstride;
MDE_BUFFER* mde_tile_buf = tile->buffer;
#ifdef MDE_SUPPORT_SPLIT_BITMAPS
if (!must_support_painter)
mde_tile_buf = tile->GetFirstSplitBitmapElm()->buffer;
int split_buffer_lines_left = mde_tile_buf->h;
#endif // MDE_SUPPORT_SPLIT_BITMAPS
UINT8 *tiledata = (UINT8*)MDE_LockBuffer(mde_tile_buf, MDE_MakeRect(0,0,tile->Width(), tile->Height()), tstride, false);
UINT8 *linedata_end = src;
if (!tiledata)
{
MDE_UnlockBuffer(mde_buf, false);
OP_DELETE(tile);
return NULL;
}
for ( UINT32 tile_line = 0; tile_line < tile_height; tile_line++ )
{
#ifdef MDE_SUPPORT_SPLIT_BITMAPS
if (0 == split_buffer_lines_left--)
{
MDE_UnlockBuffer(mde_tile_buf, true);
mde_tile_buf = tile->GetNextSplitBitmapElm()->buffer;
tiledata = (UINT8*)MDE_LockBuffer(mde_tile_buf, MDE_MakeRect(0,0,tile->Width(), tile->Height()), tstride, false);
if (!tiledata)
{
MDE_UnlockBuffer(mde_buf, false);
OP_DELETE(tile);
return NULL;
}
split_buffer_lines_left = mde_tile_buf->h - 1; // -1 because we are now in first iteration for this buffer
}
#endif // MDE_SUPPORT_SPLIT_BITMAPS
UINT8 *linedata_start = linedata_end;
linedata_end += stride;
if (stride <= tstride)
{
// The tiled bitmap is wider than the original
int tile_line_left = tstride;
while(tile_line_left >= stride)
{
// Normally a memcpy would be nice here, but rowstride
// is often 3 or 6 bytes and memcpy is too slow for
// that kind of size. It _is_ faster when compiling
// without optimizations, but who cares about that.
#if 0
op_memcpy(tiledata, linedata_start, stride);
tiledata += stride;
#else
// Duff's device. Ugly but fast
int signed_width = stride;
UINT8* linedata = linedata_start;
switch(signed_width & 7)
{
while(signed_width>0)
{
case 0:
*(tiledata++) = *(linedata++);
case 7:
*(tiledata++) = *(linedata++);
case 6:
*(tiledata++) = *(linedata++);
case 5:
*(tiledata++) = *(linedata++);
case 4:
*(tiledata++) = *(linedata++);
case 3:
*(tiledata++) = *(linedata++);
case 2:
*(tiledata++) = *(linedata++);
case 1:
*(tiledata++) = *(linedata++);
signed_width -= 8;
} // end while
} // end switch
#endif // memcpy or Duff's device
tile_line_left -= stride;
}
if (tile_line_left > 0)
{
op_memcpy(tiledata, linedata_start, tile_line_left);
tiledata += tile_line_left; // wrap to next tile line
}
}
else
{
// The original bitmap is wider than the tiled one
op_memcpy(tiledata, linedata_start, tstride);
tiledata += tstride;
}
if ( linedata_end == pixeldata_end )
{
// We're at the end of the original bitmap. Start with line
// 1 again.
linedata_end = src;
}
}
MDE_UnlockBuffer(mde_buf, false);
MDE_UnlockBuffer(mde_tile_buf, true);
return tile;
}
#endif // LIBGOGI_SUPPORT_CREATE_TILE
#endif // !LIBGOGI_PLATFORM_IMPLEMENTS_OPBITMAP && !VEGA_OPPAINTER_SUPPORT
|
#include "Plugin.h"
using namespace studio;
std::vector<PluginPtr> PluginManager::plugins;
PluginPtr PluginManager::makePlugin(const std::string & dllPath)
{
auto p = std::make_shared<Plugin>(dllPath);
plugins.push_back(p);
return p;
}
|
/**
* AUTHOR: I M
*
* Date: 03/09/21
*/
#include "doctest.h"
#include "City.hpp"
#include "Board.hpp"
using namespace pandemic;
#include <string>
#include <algorithm>
using namespace std;
TEST_CASE("GOOD INPUT") { //
CHECK_NOTHROW(bool temp);
CHECK_NOTHROW(bool temp);
CHECK_NOTHROW(bool temp);
CHECK_NOTHROW(bool temp);
CHECK_NOTHROW(bool temp);
CHECK_NOTHROW(bool temp);
CHECK_NOTHROW(bool temp);
CHECK_NOTHROW(bool temp);
CHECK_NOTHROW(bool temp);
CHECK_NOTHROW(bool temp);
CHECK_NOTHROW(bool temp);
CHECK_NOTHROW(bool temp);
CHECK_NOTHROW(bool temp);
CHECK_NOTHROW(bool temp);
CHECK_NOTHROW(bool temp);
CHECK_NOTHROW(bool temp);
CHECK_NOTHROW(bool temp);
CHECK_NOTHROW(bool temp);
CHECK_NOTHROW(bool temp);
CHECK_NOTHROW(bool temp);
CHECK_NOTHROW(bool temp);
CHECK_NOTHROW(bool temp);
CHECK_NOTHROW(bool temp);
CHECK_NOTHROW(bool temp);
CHECK_NOTHROW(bool temp);
CHECK_NOTHROW(bool temp);
CHECK_NOTHROW(bool temp);
CHECK_NOTHROW(bool temp);
CHECK_NOTHROW(bool temp);
CHECK_NOTHROW(bool temp);
CHECK_NOTHROW(bool temp);
CHECK_NOTHROW(bool temp);
CHECK_NOTHROW(bool temp);
CHECK_NOTHROW(bool temp);
}
TEST_CASE("BAD INPUT") {
}
|
/* =============================
* | Name: Abhishek Mantha |
* | Email: amantha@usc.edu |
* | GitHub: abmantha |
* | Date Submitted: 2/13/15 |
* | HW 3 |
* ==============================
*
* Filename: settest.cpp
*
* Test file for the setint.h and setint.cpp file
*/
#include "lib/setint.h"
#include <iostream>
using namespace std;
/* Function prototypes */
void basicTesting(SetInt& s);
void iteratorTesting(SetInt& s);
void copyConstructorTesting(SetInt& s);
void assignmentOverloadTesting(SetInt& s);
void unionIntersectionTesting(SetInt& s);
/* Executes testing for SetInt class*/
int main(int argc, char *argv[]) {
cout << "SETINT -- BEGIN TESTING!" << endl;
cout << endl;
SetInt s;
basicTesting(s);
iteratorTesting(s);
copyConstructorTesting(s);
assignmentOverloadTesting(s);
unionIntersectionTesting(s);
cout << "ALL TESTING IS COMPLETE!" << endl;
return 0;
}
/* Testing basic functions */
void basicTesting(SetInt& s) {
cout << "BASIC TESTING." << endl;
if (s.empty()) {
cout << "SUCCESS: Set is initially empty." << endl;
} else {
cout << "FAIL: Unexpected elements living in set." << endl;
}
if (s.size() == 0) {
cout << "SUCCESS: Set size expected to be 0." << endl;
} else {
cout << "FAIL: Set size is actually " << s.size() << endl;
}
cout << "Checking if element 4 exists in empty set." << endl;
if (!s.exists(4)) {
cout << "SUCCESS: Empty set does not contain any elements." << endl;
} else {
cout << "FAIL: Element 4 does live in set." << endl;
}
cout << "Inserting element 4 into set." << endl;
s.insert(4);
if (s.size() == 1) {
cout << "SUCCESS: Set size expected to be 1." << endl;
} else {
cout << "FAIL: Set size is actually " << s.size() << endl;
}
if (s.exists(4)) {
cout << "SUCCESS: Element 4 does live in set." << endl;
} else {
cout << "FAIL: Element 4 does not live in set." << endl;
}
cout << "Removing element 4 from set." << endl;
s.remove(4);
if (s.empty()) {
cout << "SUCCESS: Set is now empty." << endl;
} else {
cout << "FAIL: Unexpected elements living in set." << endl;
}
if (s.size() == 0) {
cout << "SUCCESS: Set size expected to be 0." << endl;
} else {
cout << "FAIL: Set size is actually " << s.size() << endl;
}
cout << "Checking if element 4 exists in set." << endl;
if (!s.exists(4)) {
cout << "SUCCESS: Element 4 does not live in set." << endl;
} else {
cout << "FAIL: Element 4 does live in set." << endl;
}
cout << "Trying to remove element 4 again." << endl;
s.remove(4);
if (s.size() == 0) {
cout << "SUCCESS: Set size expected to be 0." << endl;
} else {
cout << "FAIL: Set size is actually " << s.size() << endl;
}
if (!s.exists(4)) {
cout << "SUCCESS: Element 4 does not live in set." << endl;
} else {
cout << "FAIL: Element 4 does live in set." << endl;
}
cout << "Inserting element 5 into set." << endl;
s.insert(5);
if (s.size() == 1) {
cout << "SUCCESS: Set size expected to be 1." << endl;
} else {
cout << "FAIL: Set size is actually " << s.size() << endl;
}
if (s.exists(5)) {
cout << "SUCCESS: Element 5 does live in set." << endl;
} else {
cout << "FAIL: Element 5 does not live in set." << endl;
}
cout << "Trying to insert element 5 into set again." << endl;
s.insert(5);
if (s.size() == 1) {
cout << "SUCCESS: Set size expected to be 1. NO REPEATS!" << endl;
} else {
cout << "FAIL: Set size is actually " << s.size() << endl;
}
cout << endl;
}
/* Testing iterator functionality */
void iteratorTesting(SetInt& s) {
cout << "ITERATOR TESTING." << endl;
s.insert(6);
s.insert(1);
s.insert(8);
s.insert(10);
cout << "Current size of set: " << s.size() << endl;
cout << "Printing out all elements in set via iterators." << endl;
const int* item = s.first();
cout << "First item is: " << *item << endl;
while (item != NULL) {
cout << "Item: " << *item << endl;
item = s.next();
}
cout << "Reseting first iterator." << endl;
item = s.first();
if (*item == 5) {
cout << "SUCCESS: First element in set is 6." << endl;
} else {
cout << "FAIL: First element in set is actually " << *item << endl;
}
item = s.next();
if (*item == 6) {
cout << "SUCCESS: Next element in set is 1." << endl;
} else {
cout << "FAIL: First element in set is actually " << *item << endl;
}
cout << "Iterating to last element." << endl;
while(item != NULL) {
item = s.next();
}
cout << "Inserting new element at end." << endl;
s.insert(2);
if (item == NULL) {
cout << "SUCCESS: Element at end is NULL." << endl;
cout << "Expected behavior. List is modified. However, iterator is not tracking insertions or removals. Must reset iterator." << endl;
} else {
cout << "FAIL: Element at end is actually " << *item << endl;
}
cout << "All elements in set with new insertion 2." << endl;
cout << "Current size of set: " << s.size() << endl;
item = s.first();
while (item != NULL) {
cout << "Item: " << *item << endl;
item = s.next();
}
cout << endl;
}
/* Testing copy constructor functionality */
void copyConstructorTesting(SetInt& s) {
cout << "COPY CONSTRUCTOR TESTING." << endl;
s.insert(6);
s.insert(1);
s.insert(8);
s.insert(10);
cout << "Current size of set: " << s.size() << endl;
cout << "Printing out all elements in set via iterators." << endl;
const int* item = s.first();
cout << "First item is: " << *item << endl;
while (item != NULL) {
cout << "Item: " << *item << endl;
item = s.next();
}
cout << "Creating new set s2. Copying all elements from s using copy constructor." << endl;
SetInt s2(s);
if (s.size() == s2.size()) {
cout << "SUCCESS: Both lists have the same number of elements." << endl;
cout << "Current size of s: " << s.size() << endl;
const int* item = s.first();
while (item != NULL) {
cout << "Item in s: " << *item << endl;
item = s.next();
}
cout << "Current size of s2: " << s2.size() << endl;
const int* item2 = s2.first();
while (item2 != NULL) {
cout << "Item in s2: " << *item2 << endl;
item2 = s2.next();
}
} else {
cout << "FAIL: Both lists have different sizes." << endl;
cout << "FAIL: List1 size -- " << s.size() << endl;
cout << "FAIL: List2 size -- " << s2.size() << endl;
}
cout << "Inserting new element in s." << endl;
s.insert(17);
if (s.size() != s2.size()) {
cout << "SUCCESS: Both lists have different number of elements." << endl;
cout << "Current size of s: " << s.size() << endl;
const int* item = s.first();
while (item != NULL) {
cout << "Item in s: " << *item << endl;
item = s.next();
}
cout << "Current size of s2: " << s2.size() << endl;
const int* item2 = s2.first();
while (item2 != NULL) {
cout << "Item in s2: " << *item2 << endl;
item2 = s2.next();
}
} else {
cout << "FAIL: Both lists have same sizes." << endl;
}
cout << "Inserting two new elements to s2." << endl;
s2.insert(20);
s2.insert(33);
if (s.size() != s2.size()) {
cout << "SUCCESS: Both lists have different number of elements." << endl;
cout << "Current size of s: " << s.size() << endl;
const int* item = s.first();
while (item != NULL) {
cout << "Item in s: " << *item << endl;
item = s.next();
}
cout << "Current size of s2: " << s2.size() << endl;
const int* item2 = s2.first();
while (item2 != NULL) {
cout << "Item in s2: " << *item2 << endl;
item2 = s2.next();
}
} else {
cout << "FAIL: Both lists have same sizes." << endl;
}
cout << "Removing three elements from s." << endl;
s.remove(8);
s.remove(10);
s.remove(6);
if (s.size() != s2.size()) {
cout << "SUCCESS: Both lists have different number of elements." << endl;
cout << "Current size of s: " << s.size() << endl;
const int* item = s.first();
while (item != NULL) {
cout << "Item in s: " << *item << endl;
item = s.next();
}
cout << "Current size of s2: " << s2.size() << endl;
const int* item2 = s2.first();
while (item2 != NULL) {
cout << "Item in s2: " << *item2 << endl;
item2 = s2.next();
}
} else {
cout << "FAIL: Both lists have same sizes." << endl;
}
cout << "Removing four elements s2." << endl;
s2.remove(5);
s2.remove(6);
s2.remove(33);
if (s.size() != s2.size()) {
cout << "SUCCESS: Both lists have different number of elements." << endl;
cout << "Current size of s: " << s.size() << endl;
const int* item = s.first();
while (item != NULL) {
cout << "Item in s: " << *item << endl;
item = s.next();
}
cout << "Current size of s2: " << s2.size() << endl;
const int* item2 = s2.first();
while (item2 != NULL) {
cout << "Item in s2: " << *item2 << endl;
item2 = s2.next();
}
} else {
cout << "FAIL: Both lists have same sizes." << endl;
}
cout << endl;
}
/* Testing assignment overloading */
void assignmentOverloadTesting(SetInt& s) {
cout << "ASSIGNMENT OVERLOAD TESTING." << endl;
s.insert(6);
s.insert(1);
s.insert(8);
s.insert(10);
cout << "Current size of set: " << s.size() << endl;
cout << "Printing out all elements in set via iterators." << endl;
const int* item = s.first();
cout << "First item is: " << *item << endl;
while (item != NULL) {
cout << "Item: " << *item << endl;
item = s.next();
}
cout << "Creating new set s2. Copying all elements from s using assignment operator." << endl;
SetInt s2;
s2 = s;
if (s.size() == s2.size()) {
cout << "SUCCESS: Both lists have the same number of elements." << endl;
cout << "Current size of s: " << s.size() << endl;
const int* item = s.first();
while (item != NULL) {
cout << "Item in s: " << *item << endl;
item = s.next();
}
cout << "Current size of s2: " << s2.size() << endl;
const int* item2 = s2.first();
while (item2 != NULL) {
cout << "Item in s2: " << *item2 << endl;
item2 = s2.next();
}
} else {
cout << "FAIL: Both lists have different sizes." << endl;
cout << "FAIL: List1 size -- " << s.size() << endl;
cout << "FAIL: List2 size -- " << s2.size() << endl;
}
cout << "Inserting 2 new element in s." << endl;
s.insert(17);
s.insert(42);
if (s.size() != s2.size()) {
cout << "SUCCESS: Both lists have different number of elements." << endl;
cout << "Current size of s: " << s.size() << endl;
const int* item = s.first();
while (item != NULL) {
cout << "Item in s: " << *item << endl;
item = s.next();
}
cout << "Current size of s2: " << s2.size() << endl;
const int* item2 = s2.first();
while (item2 != NULL) {
cout << "Item in s2: " << *item2 << endl;
item2 = s2.next();
}
} else {
cout << "FAIL: Both lists have same sizes." << endl;
}
cout << "Inserting two new elements to s2." << endl;
s2.insert(20);
s2.insert(33);
if (s.size() != s2.size()) {
cout << "SUCCESS: Both lists have different number of elements." << endl;
cout << "Current size of s: " << s.size() << endl;
const int* item = s.first();
while (item != NULL) {
cout << "Item in s: " << *item << endl;
item = s.next();
}
cout << "Current size of s2: " << s2.size() << endl;
const int* item2 = s2.first();
while (item2 != NULL) {
cout << "Item in s2: " << *item2 << endl;
item2 = s2.next();
}
} else {
cout << "FAIL: Both lists have same sizes." << endl;
}
cout << "Removing three elements from s." << endl;
s.remove(8);
s.remove(10);
s.remove(6);
if (s.size() != s2.size()) {
cout << "SUCCESS: Both lists have different number of elements." << endl;
cout << "Current size of s: " << s.size() << endl;
const int* item = s.first();
while (item != NULL) {
cout << "Item in s: " << *item << endl;
item = s.next();
}
cout << "Current size of s2: " << s2.size() << endl;
const int* item2 = s2.first();
while (item2 != NULL) {
cout << "Item in s2: " << *item2 << endl;
item2 = s2.next();
}
} else {
cout << "FAIL: Both lists have same sizes." << endl;
}
cout << "Removing four elements s2." << endl;
s2.remove(5);
s2.remove(6);
s2.remove(33);
if (s.size() != s2.size()) {
cout << "SUCCESS: Both lists have different number of elements." << endl;
cout << "Current size of s: " << s.size() << endl;
const int* item = s.first();
while (item != NULL) {
cout << "Item in s: " << *item << endl;
item = s.next();
}
cout << "Current size of s2: " << s2.size() << endl;
const int* item2 = s2.first();
while (item2 != NULL) {
cout << "Item in s2: " << *item2 << endl;
item2 = s2.next();
}
} else {
cout << "FAIL: Both lists have same sizes." << endl;
}
cout << endl;
}
/* Testing Union and Intersection testing */
void unionIntersectionTesting(SetInt& s) {
cout << "UNION AND INTERSECTION TESTING." << endl;
SetInt s2;
s2.insert(1);
s2.insert(2);
s2.insert(3);
s2.insert(4);
cout << "Current size of set: " << s.size() << endl;
cout << "Printing out all elements in set via iterators." << endl;
const int* item = s.first();
while (item != NULL) {
cout << "Item in s: " << *item << endl;
item = s.next();
}
cout << "Current size of new set2: " << s2.size() << endl;
cout << "Printing out all elements in set via iterators." << endl;
const int* item2 = s2.first();
while(item2 != NULL) {
cout << "Item in s2: " << *item2 << endl;
item2 = s2.next();
}
cout << "Creating set3 -- the union of s and s2 using setUnion function." << endl;
SetInt s3 = s.setUnion(s2);
if (s3.size() == 7) {
cout << "SUCCESS: Union set s3 contains 7 elements." << endl;
const int* item3 = s3.first();
while (item3 != NULL) {
cout << "Item in s3: " << *item3 << endl;
item3 = s3.next();
}
} else {
cout << "FAIL: Union set s3 actually contains " << s3.size() << endl;
}
cout << "Creating s4 -- the intersection of s and s2 using setIntersection function." << endl;
SetInt s4 = s.setIntersection(s2);
if (s4.size() == 2) {
cout << "SUCCESS: Intersection set s4 contains 2 elements." << endl;
const int* item4 = s4.first();
while (item4 != NULL) {
cout << "Item in s4: " << *item4 << endl;
item4 = s4.next();
}
} else {
cout << "FAIL: Intersection set s4 actually contains " << s4.size() << endl;
}
cout << "Inserting new element 10 in s3 and s4." << endl;
s3.insert(10);
s4.insert(10);
if (s3.size() == 8) {
cout << "SUCCESS: s3 contains 8 elements." << endl;
} else {
cout << "FAIL: s3 actually contains " << s3.size() << endl;
}
if (s4.size() == 3) {
cout << "SUCCESS: s4 contains 3 elements." << endl;
} else {
cout << "FAIL: s4 actually contains " << s4.size() << endl;
}
cout << "Creating s5 -- the union of s3 and s4 using the | operator." << endl;
cout << "Creating s6 -- the intersection of s3 and s4 using the & operator." << endl;
SetInt s5 = s3 | s4;
SetInt s6 = s3 & s4;
if (s5.size() == 8) {
cout << "SUCCESS: Union set s5 contains 8 elements." << endl;
const int* item5 = s5.first();
while (item5 != NULL) {
cout << "Item in s5: " << *item5 << endl;
item5 = s5.next();
}
} else {
cout << "FAIL: Union set s5 actually contains " << s5.size() << endl;
}
if (s6.size() == 3) {
cout << "SUCCESS: Union set s6 contains 3 elements." << endl;
const int* item6 = s6.first();
while (item6 != NULL) {
cout << "Item in s6: " << *item6 << endl;
item6 = s6.next();
}
} else {
cout << "FAIL: Union set s6 actually contains " << s6.size() << endl;
}
cout << endl;
}
|
#include<iostream>
#include<cstdio>
#include<map>
#include<set>
#include<vector>
#include<stack>
#include<queue>
#include<string>
#include<cstring>
#include<algorithm>
#include<cmath>
using namespace std;
struct point{
long long x,y;
const point operator -(const point& rhs)
{
point ans;
ans.x = x - rhs.x;
ans.y = y - rhs.y;
return ans;
}
const bool operator <(const point& rhs)
{
return x*rhs.y - y*rhs.x < 0;
}
const bool operator == (const point& rhs)
{
return x*rhs.y - y*rhs.x == 0;
}
};
point a[1010],s[1010];
bool cmp(point a,point b)
{
return a.x*b.y - b.x*a.y < 0;
}
int main()
{
int t,n;
scanf("%d",&t);
while (t--)
{
int ans = 0;
scanf("%d",&n);
for (int i = 1;i <= n; i++)
scanf("%d%d",&a[i].x,&a[i].y);
for (int i = 1;i < n; i++)
{
for (int j = i+1;j <= n; j++)
{
s[j-i] = a[j]-a[i];
//cout << s[j-i].x << " " << s[j-i].y << endl;
}
sort(s+1,s+n-i+1,cmp);
int sum = 1;
for (int j = 2;j <= n-i; j++)
if (s[j] == s[j-1])
sum++;
else
{
ans += sum*(sum-1) >> 1;
sum = 1;
}
ans += sum*(sum-1) >> 1;
}
printf("%d\n",ans);
}
return 0;
}
|
/* leetcode 66
*
*
*
*/
#include <vector>
#include <deque>
#include <algorithm>
using namespace std;
class Solution {
public:
vector<int> plusOne(vector<int>& digits) {
for (int i = digits.size() - 1; i >= 0; i--) {
digits[i]++;
digits[i] = digits[i] % 10;
if (digits[i] != 0) {
return digits;
}
}
vector<int> ans(digits.size() + 1);
ans.at(0) = 1;
return ans;
}
};
/************************** run solution **************************/
vector<int> _solution_run(vector<int>& matrix)
{
Solution leetcode_66;
return leetcode_66.plusOne(matrix);
}
#ifdef USE_SOLUTION_CUSTOM
vector<vector<int>> _solution_custom(TestCases &tc)
{
return {};
}
#endif
/************************** get testcase **************************/
#ifdef USE_GET_TEST_CASES_IN_CPP
vector<string> _get_test_cases_string()
{
return {};
}
#endif
|
/*
* Player - One Hell of a Robot Server
* Copyright (C) 2000 Brian Gerkey & Kasper Stoy
* gerkey@usc.edu kaspers@robotics.usc.edu
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*
*/
#include "semantic_localization/sensors/sensor.h"
// Default constructor
Sensor::Sensor()
{
return;
}
Sensor::~Sensor()
{
}
// Apply the action model
bool Sensor::UpdateAction(pf_t *pf, SensorData *data)
{
return false;
}
// Initialize the filter
bool Sensor::InitSensor(pf_t *pf, SensorData *data)
{
return false;
}
// Apply the sensor model
bool Sensor::UpdateSensor(pf_t *pf, SensorData *data)
{
return false;
}
|
#include"Winsock.h"
#include"windows.h"
#include"stdio.h"
#pragma comment(lib,"wsock32.lib")
#define RECV_PORT 5012
#define MaxNum 10 //最大连接数
#define MaxLength 1024 //最大消息长度
DWORD ClientTread(void * PD); //
SOCKET ServerSock;
sockaddr_in ServerAddr;
int Addrlen;
HANDLE HdTread[MaxNum];
struct {
char name[10];
char ToName[10];
bool Priv;
int num;
DWORD ThreadId;
SOCKET Socket;
sockaddr_in Addr;
}Client[MaxNum];
DWORD StartSock();
DWORD CreateTCPSocket();
DWORD BindSocket();
DWORD ConnectProcess();
DWORD ClientTread(void * PD);
DWORD TCPSend(SOCKET s, char data[]);
DWORD TCPRecv(SOCKET s, char data[]);
void DeleteOne(int i);
int main()
{
if(StartSock()==-1) //初始化socket
return -1;
if(CreateTCPSocket()==-1) //创建tcp socket
return -1;
if(BindSocket() == -1) //绑定socket
return -1;
if(ConnectProcess()==-1) //连接处理
return -1;
return 1;
}
DWORD StartSock() //初始化socket
{
WSADATA WSAData;
if(WSAStartup(MAKEWORD(2,2),&WSAData)!=0)
{
printf("socket init Failed:%d\n",WSAGetLastError());
getchar();
return -1;
}
return 1;
}
DWORD CreateTCPSocket() //创建tcp socket
{
ServerSock = socket(AF_INET,SOCK_STREAM,0); //create a tcp socket
if(ServerSock == SOCKET_ERROR)
{
printf("sock create Failed:%d\n",WSAGetLastError());
WSACleanup();
getchar();
return -1;
}
ServerAddr.sin_family = AF_INET;
ServerAddr.sin_addr.s_addr = inet_addr("172.20.10.5");
ServerAddr.sin_port = htons(RECV_PORT);
return 1;
}
DWORD BindSocket() //绑定socket
{
if(bind(ServerSock,(struct sockaddr FAR*)&ServerAddr,sizeof(ServerAddr))==SOCKET_ERROR)
{
printf("bind Failed:%d\n",WSAGetLastError());
getchar();
return -1;
}
return 1;
}
DWORD ConnectProcess() //连接处理
{
int i=0,k;
Addrlen = sizeof(sockaddr_in);
if(listen(ServerSock,MaxNum)<0)
{
printf("listen Failed:%d\n",WSAGetLastError());
getchar();
return -1;
}
for(i=0;i<MaxNum;i++)
{
Client[i].num = -1; //初始化编号(-1表示尚未使用)
}
printf("Server listening....\n");
for(;;)
{
for(i=0;i<MaxNum;i++){
if(Client[i].num==-1 || Client[i].Socket==INVALID_SOCKET){
Client[i].Socket=accept(ServerSock,(struct sockaddr FAR*)&Client[i].Addr,&Addrlen);
if(Client[i].Socket!=INVALID_SOCKET){ //have got a socket Id
printf("远程主机:%s 通过端口: %d 进入聊天室...\n", inet_ntoa(Client[i].Addr.sin_addr),ntohs(Client[i].Addr.sin_port));
Client[i].num=i;
break;
}
}
}
if(i >= MaxNum) { //reach the max numbers!
Sleep(1000);
continue;
}
k = i; //get a index
HdTread[i] = CreateThread(NULL,0,(LPTHREAD_START_ROUTINE)ClientTread,(void *)&k,0,&Client[i].ThreadId);
}
}
//线程处理函数(参数PD为客户索引)
DWORD ClientTread(void * PD){
char buff[1024], temp[1024]; // buff[]:Recieve Message
int client_id = *(int *)PD;
int len;
DWORD ExitCode = 0;
//处理登录
while(1){
memset(buff,'\0',sizeof(buff));
while (TCPRecv(Client[client_id].Socket, buff) <= 0); //接收客户client_id的消息
char temp_save[] = {"talker:"};
if(!strncmp(buff,temp_save,7)){ // the user quit talk
char name[10];
for(int j =7;j<12;++j){
name[j-7] = buff[j];
}
name[5] = '\0';
for(int k =0;k<MaxNum;++k){
if(!strncmp(name,Client[k].name,6)){
TCPSend(Client[client_id].Socket, "The name has been used. Please input again.");
continue;
}
}
Client[client_id].Priv = false;
Client[client_id].num = client_id;
memset(Client[client_id].name,'\0',sizeof(Client[client_id].name));
strcpy(Client[client_id].name ,name);
memset(Client[client_id].ToName,'\0',sizeof(Client[client_id].ToName));
strcpy(Client[client_id].ToName,"all");
TCPSend(Client[client_id].Socket, "欢迎来到椰岛绿洲聊天室\n________________________________\nThe method that you send a message:\nyour_words\n//(all)your_words\n//(name)your_words\n//{name}your_words--means private talk\n________________________________\n");
//发送在线用户
char online_user[1024];
memset(online_user,'\0',sizeof(online_user));
strncat(online_user,"当前在线用户:",strlen("当前在线用户:"));
for(j=0; j<MaxNum; ++j){
if(Client[j].num!=-1){
strcat(online_user,Client[j].name);
strcat(online_user," ");
}
strcat(online_user,"\0");
}
TCPSend(Client[client_id].Socket,online_user);
//向所有用户发送该用户上线
char send_join[100];
memset(send_join,'\0',sizeof(send_join));
strncat(send_join,name,strlen(name)+1);
strncat(send_join," join us",8);
printf("%s\n",send_join);
for (int i = 0; i<MaxNum; ++i) {
if (Client[i].num != -1 && Client[i].Socket != INVALID_SOCKET){
TCPSend(Client[i].Socket,send_join);
}
}//end of 转发
break;
}
}
//*********** deal with the talking words *******************
while(1){
memset(buff,'\0',sizeof(buff));
while (TCPRecv(Client[client_id].Socket, buff) <= 0); //接收客户client_id的消息
//------- 解析消息 ---------------------
//...
//处理正常离开
if (!strncmp(buff, "Down", 4)){ // the user quit talk
printf("%s go down\n", inet_ntoa(Client[client_id].Addr.sin_addr));
DeleteOne(client_id); //删除当前用户
ExitThread(client_id); //退出线程
}
//处理转发
char change_ToName[10];
memset(change_ToName,'\0',sizeof(change_ToName));
if(!strncmp(buff, "//(all)",7)){
printf("(all)");
memset(Client[client_id].ToName,'\0',sizeof(Client[client_id].ToName));
strcpy(Client[client_id].ToName,"all");
for (int i = 0; i<MaxNum; ++i) {
if (Client[i].num != -1 && Client[i].Socket != INVALID_SOCKET){
int len = TCPSend(Client[i].Socket, buff);
if (len <= 0){// 该用户意外退出了
printf("%s exceptionally go down...\n", Client[i].name);
DeleteOne(i); ////删除该用户
TerminateThread(HdTread[i], ExitCode);//终止该用户的线程
}
}
}
}else if(!strncmp(buff, "//(",3)){
printf("(name)");
memset(Client[client_id].ToName,'\0',sizeof(Client[client_id].ToName));
for(int j =3;buff[j]!=')';++j){
change_ToName[j-3] = buff[j];
}
strcpy(Client[client_id].ToName,change_ToName);
for (int i = 0; i<MaxNum; ++i) {
if (Client[i].num != -1 && Client[i].Socket != INVALID_SOCKET){
int len = TCPSend(Client[i].Socket, buff);
if (len <= 0){// 该用户意外退出了
printf("%s exceptionally go down...\n", Client[i].name);
DeleteOne(i); ////删除该用户
TerminateThread(HdTread[i], ExitCode);//终止该用户的线程
}
}
}
}else if(!strncmp(buff, "//{",3)){
printf("{name}");
memset(Client[client_id].ToName,'\0',sizeof(Client[client_id].ToName));
for(int j =3;buff[j]!='}';++j){
change_ToName[j-3] = buff[j];
}
strcpy(Client[client_id].ToName,change_ToName);
for (int i = 0; i<MaxNum; ++i) {
if (Client[i].num != -1 && Client[i].Socket != INVALID_SOCKET && strncmp(Client[i].name, Client[client_id].ToName,5)==0){
int len = TCPSend(Client[i].Socket, buff);
if (len <= 0){// 该用户意外退出了
printf("%s exceptionally go down...\n", Client[i].name);
DeleteOne(i); ////删除该用户
TerminateThread(HdTread[i], ExitCode);//终止该用户的线程
}
}
}
}else{
printf("无前缀");
//发送给所有用户
if(!strncmp(Client[client_id].ToName,"all" ,3)){
for (int i = 0; i<MaxNum; ++i) {
if (Client[i].num != -1 && Client[i].Socket != INVALID_SOCKET){
int len = TCPSend(Client[i].Socket, buff);
if (len <= 0){// 该用户意外退出了
printf("%s exceptionally go down...\n", Client[i].name);
DeleteOne(i); ////删除该用户
TerminateThread(HdTread[i], ExitCode);//终止该用户的线程
}
}
}
}
//发送给特定用户
for (int i = 0; i<MaxNum; ++i) {
if (Client[i].num != -1 && Client[i].Socket != INVALID_SOCKET && strncmp(Client[i].name, Client[client_id].ToName,5) == 0){
int len = TCPSend(Client[i].Socket, buff);
if (len <= 0){// 该用户意外退出了
printf("%s exceptionally go down...\n", Client[i].name);
DeleteOne(i); ////删除该用户
TerminateThread(HdTread[i], ExitCode);//终止该用户的线程
}
break;
}
}
}
/*
// -------------------------------------
//---------------------- 服务器转发至所有在线客户 ------------------------------
for (int i = 0; i<MaxNum; i++) {
if (Client[i].num != -1 && Client[i].Socket != INVALID_SOCKET)
{
len = TCPSend(Client[i].Socket, buff);
if (len <= 0) // 该用户意外退出了
{
printf("%s exceptionally go down...\n", Client[i].name);
DeleteOne(i); ////删除该用户
TerminateThread(HdTread[i], ExitCode);//终止该用户的线程
}
}
}//end of 转发
*/
}
}
DWORD TCPSend(SOCKET s, char data[]){
int length;
length = send(s, data, strlen(data)+1, 0);
if (length <= 0)
return -1;
return 1;
}
DWORD TCPRecv(SOCKET s, char data[]){
int length;
length = recv(s, data, MaxLength, 0); //此处第3个参数不能用 sizeof(data)
if (length <= 0)
return -1;
return 1;
}
void DeleteOne(int i){ //删除一个客户,将其占用的socket还回去
Client[i].num = -1;
memset(Client[i].name,'\0',sizeof(Client[i].name));
memset(Client[i].ToName,'\0',sizeof(Client[i].ToName));
if (Client[i].Socket != INVALID_SOCKET)
{
Client[i].Socket = INVALID_SOCKET;
}
//其它处理工作
//...
}
|
#include "selectWidget.h"
#include "ui_selectWidget.h"
selectWidget::selectWidget(QWidget *parent) :
QWidget(parent),
ui(new Ui::selectWidget)
{
ui->setupUi(this);
connect(ui->allCBox, &QCheckBox::clicked, [this](bool checked){
checked ? selectAllChecked() : clearAllChecked();
});
connect(ui->reverseCBox, &QCheckBox::toggled, [this]{
reverseAllChecked();
});
connect(ui->cancelSelectBtn, &QPushButton::clicked, [this]{
clearAllChecked();
});
}
selectWidget::~selectWidget()
{
delete ui;
}
void selectWidget::setTableWidget(QTableWidget *tableWidget)
{
m_tableWidget = tableWidget;
}
/**
* @brief MainWindow::clearAllChecked 取消所有选中
*/
void selectWidget::clearAllChecked()
{
if(!m_tableWidget)
return;
for(int i = 0; i < m_tableWidget->rowCount(); i++)
m_tableWidget->item(i, 0)->setCheckState(Qt::Unchecked);
emit checkedNumber(0);
}
/**
* @brief MainWindow::selectAllChecked 全选
*/
void selectWidget::selectAllChecked()
{
if(!m_tableWidget)
return;
for(int i = 0; i < m_tableWidget->rowCount(); i++)
m_tableWidget->item(i, 0)->setCheckState(Qt::Checked);
emit checkedNumber(m_tableWidget->rowCount());
}
/**
* @brief MainWindow::reverseAllChecked 反选
*/
void selectWidget::reverseAllChecked()
{
if(!m_tableWidget)
return;
int k = 0;
for(int i = 0; i < m_tableWidget->rowCount(); i++) {
Qt::CheckState state = m_tableWidget->item(i, 0)->checkState();
state == Qt::Checked ? m_tableWidget->item(i, 0)->setCheckState(Qt::Unchecked)
: m_tableWidget->item(i, 0)->setCheckState(Qt::Checked);
if(state == Qt::Unchecked)
k++;
}
emit checkedNumber(k);
}
void selectWidget::setUnCheck()
{
ui->allCBox->setChecked(false);
ui->reverseCBox->setChecked(false);
}
|
#include "core/pch.h"
#if defined(USE_FREETYPE) && defined(FT_INTERNAL_FREETYPE) && defined(FT_USE_LZW_MODULE)
extern "C" {
#include "ftlzw.c"
}
#endif // USE_FREEYYPE && FT_INTERNAL_FREETYPE && FT_USE_LZW_MODULE
|
#include<bits/stdc++.h>
using namespace std;
int countMoves(int array[], int n);
int main(){
int array[] = { 7, 8, 9 };
int len = 3;
cout<<countMoves(array, len);
return 0;
}
int countMoves(int array[], int n){
int letsmovee = 0;
while (1){
int zeroes = 0;
for (int i = 0; i < n; i++){
if (array[i] % 2 == 1){
--array[i];
++letsmovee;
}
if (array[i] == 0){
zeroes = zeroes + 1;
}
}
if (zeroes == n){
break;
}
for (int j = 0; j < n; j++){
array[j] = array[j] / 2;
}
letsmovee = letsmovee + 1;
}
return letsmovee;
}
|
#ifndef CHAT_PANEL_H
#define CHAT_PANEL_H
#if defined(M2_SUPPORT) && defined(IRC_SUPPORT)
#include "adjunct/quick/panels/HotlistPanel.h"
#include "modules/widgets/OpWidgetFactory.h"
/***********************************************************************************
**
** ChatPanel
**
***********************************************************************************/
class ChatPanel : public HotlistPanel
{
public:
ChatPanel();
virtual ~ChatPanel() {};
void JoinChatRoom(UINT32 account_id, OpString& room);
virtual OP_STATUS Init();
virtual void GetPanelText(OpString& text, Hotlist::PanelTextType text_type);
virtual const char* GetPanelImage() {return "Panel Chat";}
virtual void OnLayoutPanel(OpRect& rect);
virtual void OnFullModeChanged(BOOL full_mode);
virtual void OnFocus(BOOL focus,FOCUS_REASON reason);
virtual Type GetType() {return PANEL_TYPE_CHAT;}
BOOL IsSingleClick() {return !IsFullMode() && g_pcui->GetIntegerPref(PrefsCollectionUI::HotlistSingleClick);}
// OpWidgetListener
virtual void OnMouseEvent(OpWidget *widget, INT32 pos, INT32 x, INT32 y, MouseButton button, BOOL down, UINT8 nclicks);
// == OpInputContext ======================
virtual BOOL OnInputAction(OpInputAction* action);
virtual const char* GetInputContextName() {return "Chat Panel";}
private:
BOOL ShowContextMenu(const OpPoint &point, BOOL center, BOOL use_keyboard_context);
OpTreeView* m_rooms_view;
};
#endif //M2_SUPPORT && IRC_SUPPORT
#endif // CHAT_PANEL_H
|
#include <iostream>
#include <cstdlib>
using namespace std;
int ile;
float mediana;
void quicksort(float *tablica, int lewy, int prawy)
{
int v=tablica[(lewy+prawy)/2];
int i,j,x;
i=lewy;
j=prawy;
do
{
while(tablica[i]<v) i++;
while(tablica[j]>v) j--;
if(i<=j)
{
x=tablica[i];
tablica[i]=tablica[j];
tablica[j]=x;
i++;
j--;
}
}
while(i<=j);
if(j>lewy) quicksort(tablica,lewy, j);
if(i<prawy) quicksort(tablica, i, prawy);
}
float srednia(float *tab, int ile) //dynamiczne rezerwowanie pamięci (tyle ile poda użytkownik)
{
float suma=0;
for (int i=0; i<ile; i++)
{
suma+=*tab;
tab++;
}
return suma/ile;
}
int main()
{
cout << "Ile liczb w tablicy: ";
if (!(cin >> ile)) //zabezpieczenie przed wpisaniem tekstu
{
cerr <<"To nie jest liczba!";
exit (0);
}
float *tablica;
tablica = new float [ile];
cout <<"Podaj liczby: ";
for (int i=0; i<ile; i++)
{
cout <<endl<<"Podaj " <<i+1 <<" liczbe : ";
if (!(cin >>tablica [i])) //zabezpieczenie przed wpisaniem tekstu
{
cerr <<"To nie jest liczba, sproboj jeszcze raz!";
exit (0);
}
}
cout<<"Srednia wynosi: "<<srednia(tablica, ile)<<endl;
quicksort(tablica, 0, ile-1);
if (ile%2 == 0)
{
mediana = tablica[(ile-1)/2]+tablica[ile/2];
mediana = mediana/2;
}
else
{
mediana = tablica [ile/2];
}
cout << "Mediana wynosi: " << mediana << endl;
delete [] tablica;
return 0;
}
|
#pragma once
#include "server.h"
#include <string.h>
#include <vector>
#include <stdio.h>
#include <stdlib.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <unistd.h>
#include <arpa/inet.h>
#include <iostream>
using namespace std;
class Worker {
public:
Worker(int in_client);
~Worker();
vector<string> split(const char *str, char c);
vector<string> get_subjects(string name);
void handle_client();
string parse_message(string message);
string read_message(); //reading message until new line
string read_put(int length); //reading message of given length
void store_message(string name, string subject, string data);
void handle_message(string message);
void send_response(string response);
protected:
int client;
//allocated buffer
char* buf;
int buflen;
string cache;
};
|
/*
* Stopping Times
* Copyright (C) Leonardo Marchetti 2011 <leonardomarchetti@gmail.com>
*/
#include "wrappedFunction1D.h"
/* Class WrappedFunction1D has template methods. To see their implementation look at wrappedFunction1D.inl file. */
namespace StoppingTimes{
}
|
#include <iostream>
void drawM(char** &arr, char simbol, int chap) {
for(int i = 0; i < chap; ++i) {
arr[i][0] = simbol;
}
for(int i = 0;i < chap; ++i) {
arr[i][chap -1] = simbol;
}
if(0 != chap % 2) {
for(int i = 1;i <= chap / 2; ++i) {
arr[i][i] = simbol;
}
for(int i = 1;i <= chap / 2; ++i) {
arr[i][chap - 1 - i] = simbol;
}
} else {
for(int i = 1;i < chap / 2; ++i) {
arr[i][i] = simbol;
}
for(int i = 1;i < chap / 2; ++i) {
arr[i][chap - 1 - i] = simbol;
}
}
}
int draw(char** &arr, char simbol) {
int chap = 0;
int m = 0;
std::cout<<"Mutqagrel zangvaci chap@ (nax@ntreli e kent tiv)-> ";
std::cin>>chap;
if(3 > chap) {
return 1;
} else {
arr = new char*[chap];
for(int i = 0;i < chap; ++i) {
arr[i] = new char[chap];
}
for(int i = 0;i < chap; ++i) {
for(int j = 0;j < chap; ++j) {
arr[i][j] = ' ';
}
}
drawM(arr, simbol, chap);
return chap;
}
}
int count(char** &arr, int chap, char simbol) {
int count = 0;
for(int i = 0;i < chap; ++i) {
for(int j = 0;j < chap; ++j) {
if(simbol == arr[i][j]) {
count++;
}
}
}
return count;
}
int main() {
char** arr;
char simb;
std::cout<<"@ntrel simvol -> ";
std::cin>>simb;
int size = draw(arr, simb);
if( 1 != size) {
for(int i = 0; i < size; ++i) {
for(int j = 0; j < size; ++j) {
std::cout<<arr[i][j]<<" ";
}
std::cout<<'\n';
}
std::cout<<"Sivolneri qanakn e -> "<<count(arr, size, simb)<<'\n';
} else {
std::cout<<"Sxal mutqagrum \n";
}
for(int i = 0; i < size; ++i) {
delete arr[i];
}
delete [] arr;
return 0;
}
|
/*
There are many homeless cats in PKU campus.
They are all happy because the students in the cat club of PKU take good care of them.
Li lei is one of the members of the cat club. He loves those cats very much. Last week,
he won a scholarship and he wanted to share his pleasure with cats.
So he bought some really tasty fish to feed them, and watched them eating with great pleasure.
At the same time, he found an interesting question:
There are m fish and n cats, and it takes ci minutes for the ith cat to eat out one fish.
A cat starts to eat another fish (if it can get one) immediately after it has finished one fish.
A cat never shares its fish with other cats. When there are not enough fish left,
the cat which eats quicker has higher priority to get a fish than the cat which eats slower.
All cats start eating at the same time. Li Lei wanted to know, after x minutes, how many fish would be left.
*/
#include<cstdio>
#include<algorithm>
using namespace std;
const int maxn=1e2+4;
int a[maxn];
int main(){
int m,n,x;
while (~scanf("%d%d%d",&m,&n,&x))
{
for(int i=0;i<n;++i)scanf("%d",&a[i]);
sort(a,a+n);
int b[maxn]={0};
int j=m>n?n:m;
for(int i=0;i<j;++i)b[i]=1;
m-=j;
int t=0,sum=0;
while(t<x)
{
t++;
for(int i=0;i<j;++i)
{
if(t%a[i]==0)
{
b[i]=0;
if(m&&t<x)b[i]=1,m--;
}
}
while(!b[j-1]&&!m)j--;
}
for(int i=0;i<j;++i)sum+=b[i];
printf("%d %d\n",m,sum);
}
}
|
#include"Character.h"
#include"TextPanel.h"
#include"Potion.h"
#include<cmath>
#include<iostream>
Character::Character(int x, int y, char display, std::string type, int hp, int atk, int def):Entity(x,y,display,type)
{
this->initHp = hp;
this->hp = hp;
this->atk = atk;
this->def = def;
this->curFloorAtkBoost = 0;
this->curFloorDefBoost = 0;
this->isDead = false;
}
void Character::changeHP(int hp)
{
//If the hp after is greater than the initial hp, then
//the hp is the initial hp
if (this->hp + hp > this->initHp)
{
this->hp = this->initHp;
}
//else treat it the normal way
else
{
this->hp += hp;
}
}
void Character::changeCurFloorATKBoost(int atkBoost)
{
this->curFloorAtkBoost += atkBoost;
}
void Character::changeCurFloorDEFBoost(int defBoost)
{
this->curFloorDefBoost += defBoost;
}
void Character::restoreCurFloorBoost()
{
this->curFloorAtkBoost = 0;
this->curFloorDefBoost = 0;
}
void Character::combat(Character *enemy)
{
//检测对象
//如果攻击对象(this)是Player,则主语为you
//否则,被攻击对象为Player,主语为攻击对象(enemy)的类型
int damage = -ceil(this->getATK()*(100.0 - enemy->getDEF()) / 100.0);
enemy->changeHP(damage);
if (enemy->getHP() <= 0)
{
enemy->setIsDead(true);
}
//若攻击对象的display:char 为‘@’,则代表攻击对象为Player
if (this->getDisplay() == '@')
{
TextPanel::appendMessage("You attack the " + enemy->getType() + " for " + std::to_string(-damage) + "damage!\n");
}
//否则,更换主语为Enemy的类型,宾语为You(player)
else
{
TextPanel::appendMessage(this->getType() + " attacks you for " + std::to_string(-damage) + " damage!\n");
}
}
int Character::getHP()
{
return this->hp;
}
int Character::getInitHp()
{
return this->initHp;
}
int Character::getATK()
{
return this->atk+this->curFloorAtkBoost;
}
int Character::getDEF()
{
int defTotal = this->def + this->curFloorDefBoost;
if (defTotal > 100) {
return 100;
}
else if(defTotal<0)
{
return 0;
}
else
{
return defTotal;
}
}
void Character::setIsDead(bool isDead)
{
this->isDead = isDead;
}
bool Character::getIsDead()
{
return this->isDead;
}
void Character::usePotion(Potion *p)
{
p->setIsUsed(true);
this->changeCurFloorATKBoost(p->getAtkEffect());
this->changeCurFloorDEFBoost(p->getDefEffect());
this->changeHP(p->getHpEffect());
}
void Character::update()
{
}
|
#pragma once
// Здесь представленно описание класса "Социальная сеть" и прототипы всех необходимых методов.
#include "Group.h"
#include "Member.h"
class SocNetwork
{
public:
SocNetwork();
~SocNetwork();
void AddGroup(const Group &); // Метод "Добавление группы".
void DeleteGroup(const Group &); // Метод "Удаление группы"
};
|
/**
* \copyright
* (c) 2012 - 2015 E.S.R. Labs GmbH (http://www.esrlabs.com)
* All rights reserved.
*/
#ifndef SLINKEDLIST_H_
#define SLINKEDLIST_H_
#include "util/SBaseTypes.h"
#include "util/SIteratorBaseTypes.h"
#include "util/CompileTimeConstraints.h"
#include <cassert>
template<typename T>
class SLinkedListSetNode
{
public:
typedef T value_type;
SLinkedListSetNode() :
fpNext(0L),
fAddedToList(false)
{}
T* getNext() const
{
return fpNext;
}
void setNext(T* pNext)
{
fpNext = pNext;
}
void addToList()
{
assert(!fAddedToList);
fAddedToList = true;
}
void removeFromList()
{
fAddedToList = false;
}
private:
SLinkedListSetNode(const SLinkedListSetNode&);
SLinkedListSetNode& operator=(const SLinkedListSetNode&);
T* fpNext;
bool fAddedToList;
};
template<typename T>
class SLinkedListSetIterator;
template<typename T>
class SLinkedListSet
: common::Derived_from<T, SLinkedListSetNode<T> >
{
private:
/** type of list itsself */
typedef SLinkedListSet<T> self_type;
public:
/** type of values stored in vector */
typedef typename STypeTraits<T>::value_type value_type;
/** pointer to value */
typedef typename STypeTraits<T>::pointer pointer;
/** reference to value */
typedef typename STypeTraits<T>::reference reference;
/** const reference to value */
typedef typename STypeTraits<T>::const_reference const_reference;
/** unsigned integral type */
typedef typename STypeTraits<T>::size_type size_type;
/** signed integral type */
typedef typename STypeTraits<T>::difference_type difference_type;
/** iterator type */
typedef SLinkedListSetIterator<T> iterator;
/** const iterator type */
typedef SLinkedListSetIterator<const T> const_iterator;
SLinkedListSet() :
fpFirst(0L),
fpLast(0L)
{
clear();
}
/**
* @note
* O(n)!
* @todo
* Maybe a field would be better
*/
size_type size() const
{
size_type size = (fpFirst) ? 1 : 0;
for (const T* pNode = fpFirst; pNode != fpLast; pNode = pNode->getNext())
{
++size;
}
return size;
}
bool empty() const
{
return (fpFirst == 0L);
}
void clear()
{
while (!empty())
{
pop_front();
}
fpFirst = 0L;
fpLast = 0L;
}
const_reference front() const
{
assert(fpFirst);
return *fpFirst;
}
reference front()
{
return const_cast<reference>(
static_cast<const self_type&>(
*this).front());
}
const_reference back() const
{
assert(fpLast);
return *fpLast;
}
reference back()
{
return const_cast<reference>(
static_cast<const self_type&>(
*this).back());
}
void push_front(T& node)
{
if (contains_node(&node))
{
return;
}
node.addToList();
node.setNext(fpFirst);
fpFirst = &node;
if (!fpLast)
{//inserted first node
fpLast = fpFirst;
fpFirst->setNext(0L);
}
}
void push_back(T& node)
{
if (empty())
{//inserted first node
fpFirst = &node;
}
else
{
if (contains_node(&node))
{
return;
}
fpLast->setNext(&node);
}
node.addToList();
fpLast = &node;
fpLast->setNext(0L);
}
void pop_front()
{
if (!fpFirst)
{
return;
}
fpFirst->removeFromList();
fpFirst = fpFirst->getNext();
if (!fpFirst)
{//removed last element
fpLast = 0L;
}
}
void pop_back();
iterator begin()
{
return iterator(fpFirst);
}
const_iterator begin() const
{
return const_iterator(fpFirst);
}
iterator end()
{
return iterator(0L);
}
const_iterator end() const
{
return const_iterator(0L);
}
iterator erase(iterator pos);
iterator insert(iterator pos, T& value);
void remove(const T& value);
bool contains(const T& value) const
{
return contains_node(&value);
}
private:
SLinkedListSet(const SLinkedListSet&);
SLinkedListSet& operator=(const SLinkedListSet&);
T* findPredecessor(const T* pNode) const
{
T* pResult = fpFirst;
while ((pResult != 0L) && (pResult->getNext() != pNode))
{
pResult = pResult->getNext();
}
return pResult;
}
bool contains_node(const T* pNodeToFind) const;
T* fpFirst;
T* fpLast;
};
template<typename T>
bool SLinkedListSet<T>::contains_node(const T* pNodeToFind) const
{
T* pNode = fpFirst;
while (pNode != 0L)
{
if (pNodeToFind == pNode)
{
return true;
}
pNode = pNode->getNext();
}
return false;
}
template<typename T>
void SLinkedListSet<T>::pop_back()
{
if (!fpLast)
{
return;
}
fpLast->removeFromList();
if (fpFirst == fpLast)
{
clear();
}
else
{
fpLast = findPredecessor(fpLast);
assert(fpLast);
fpLast->setNext(0L);
}
}
template<typename T>
typename SLinkedListSet<T>::iterator SLinkedListSet<T>::erase(
SLinkedListSet<T>::iterator pos)
{
if (!fpFirst)
{
return end();
}
iterator next = pos;
++next;
if (pos == begin())
{//remove first element
pop_front();
}
else
{
pos->removeFromList();
T* pNode = findPredecessor(pos.operator->());
assert(pNode);
if (pNode->getNext() == fpLast)
{//removing last element
fpLast = pNode;
}
pNode->setNext(pos->getNext());
}
return next;
}
template<typename T>
typename SLinkedListSet<T>::iterator SLinkedListSet<T>::insert(
SLinkedListSet<T>::iterator pos,
T& value)
{
if (contains_node(&value))
{
return pos;
}
if (empty() || (pos == begin()))
{
push_front(value);
}
else if (pos == end())
{
push_back(value);
}
else
{
value.addToList();
T* pNode = findPredecessor(pos.operator->());
assert(pNode);
value.setNext(pNode->getNext());
pNode->setNext(&value);
}
return iterator(&value);
}
template<typename T>
void SLinkedListSet<T>::remove(const T& value)
{
if (&value == fpFirst)
{
pop_front();
}
else if (&value == fpLast)
{
pop_back();
}
else
{
const_cast<T&>(value).removeFromList();
T* pNode = findPredecessor(&value);
if (pNode)
{
pNode->setNext(value.getNext());
}
}
}
template <typename T>
bool operator==(
const SLinkedListSetIterator<T>& x,
const SLinkedListSetIterator<T>& y);
template <typename T>
bool operator!=(
const SLinkedListSetIterator<T>& x,
const SLinkedListSetIterator<T>& y);
template<typename T>
class SLinkedListSetIterator
{
public:
/** the iterators category */
typedef SForwardIteratorTag iterator_category;
/** value type of iterator */
typedef typename STypeTraits<T>::value_type value_type;
/** reference to value */
typedef typename STypeTraits<T>::reference reference;
/** pointer to value */
typedef typename STypeTraits<T>::pointer pointer;
/** signed integral type */
typedef typename STypeTraits<T>::difference_type difference_type;
SLinkedListSetIterator(T* pValue) :
fpValue(pValue)
{}
SLinkedListSetIterator(const SLinkedListSetIterator& rhs) :
fpValue(rhs.fpValue)
{}
SLinkedListSetIterator& operator=(const SLinkedListSetIterator& rhs)
{
fpValue = rhs.fpValue;
return *this;
}
SLinkedListSetIterator& operator++()
{
fpValue = fpValue->getNext();
return *this;
}
reference operator*()
{
return *fpValue;
}
pointer operator->()
{
return fpValue;
}
private:
friend bool operator==<T>(
const SLinkedListSetIterator<T>&,
const SLinkedListSetIterator<T>&);
friend bool operator!=<T>(
const SLinkedListSetIterator<T>&,
const SLinkedListSetIterator<T>&);
T* fpValue;
};
template<typename T>
inline bool operator==(
const SLinkedListSetIterator<T>& x,
const SLinkedListSetIterator<T>& y)
{
return (x.fpValue == y.fpValue);
}
template<typename T>
inline bool operator!=(
const SLinkedListSetIterator<T>& x,
const SLinkedListSetIterator<T>& y)
{
return !(x == y);
}
#endif /*SLINKEDLIST_H_*/
|
// GuessTheNumberGUI.cpp : Defines the entry point for the application.
//
#include "framework.h"
#include "GuessTheNumberGUI.h"
#include <string>
#include <random>
#define MAX_LOADSTRING 100
// Global Variables:
HINSTANCE hInst; // current instance
HWND hGTN; // "Guess The Number" heading
HWND hRange; // "Range: "
HWND hFN; // First number
HWND hTo; // hFN "to" hSN
HWND hSN; // Second number
HWND hGuesses; // "Number of Guesses: "
HWND hNGuesses; // Number of guesses
HWND hStart; // Start
HWND hGuess; // "Guess:"
HWND hEnterGuess; // Enter guess
HWND hGuessButton; // Guess button
HWND hGuessesLeft; // "Guesses Left:"
HWND hNGuessesLeft; // Number of Guesses left
WCHAR szTitle[MAX_LOADSTRING]; // The title bar text
WCHAR szWindowClass[MAX_LOADSTRING]; // the main window class name
unsigned long long lowerNumber; // Lower number of range
unsigned long long higherNumber; // Higher number of range
unsigned long long guesses; // Number of guesses
unsigned long long guessesleft; // Number of guesses remaining
unsigned long long number; // Guess
unsigned long long lowerHelp; // Used by Help
unsigned long long higherHelp; // Used by Help
bool gameStarted = false; // Tells WM_PAINT whether the game has started or not
// Forward declarations of functions included in this code module:
ATOM MyRegisterClass(HINSTANCE hInstance);
BOOL InitInstance(HINSTANCE, int);
LRESULT CALLBACK WndProc(HWND, UINT, WPARAM, LPARAM);
INT_PTR CALLBACK About(HWND, UINT, WPARAM, LPARAM);
int APIENTRY wWinMain(_In_ HINSTANCE hInstance,
_In_opt_ HINSTANCE hPrevInstance,
_In_ LPWSTR lpCmdLine,
_In_ int nCmdShow)
{
UNREFERENCED_PARAMETER(hPrevInstance);
UNREFERENCED_PARAMETER(lpCmdLine);
// TODO: Place code here.
// Initialize global strings
LoadStringW(hInstance, IDS_APP_TITLE, szTitle, MAX_LOADSTRING);
LoadStringW(hInstance, IDC_GUESSTHENUMBERGUI, szWindowClass, MAX_LOADSTRING);
MyRegisterClass(hInstance);
// Perform application initialization:
if (!InitInstance (hInstance, nCmdShow))
{
return FALSE;
}
HACCEL hAccelTable = LoadAccelerators(hInstance, MAKEINTRESOURCE(IDC_GUESSTHENUMBERGUI));
MSG msg;
// Main message loop:
while (GetMessage(&msg, nullptr, 0, 0))
{
if (!TranslateAccelerator(msg.hwnd, hAccelTable, &msg))
{
TranslateMessage(&msg);
DispatchMessage(&msg);
}
}
return (int) msg.wParam;
}
//
// FUNCTION: MyRegisterClass()
//
// PURPOSE: Registers the window class.
//
ATOM MyRegisterClass(HINSTANCE hInstance)
{
WNDCLASSEXW wcex;
wcex.cbSize = sizeof(WNDCLASSEX);
wcex.style = CS_HREDRAW | CS_VREDRAW;
wcex.lpfnWndProc = WndProc;
wcex.cbClsExtra = 0;
wcex.cbWndExtra = 0;
wcex.hInstance = hInstance;
wcex.hIcon = LoadIcon(hInstance, MAKEINTRESOURCE(IDI_ADEETHYIA));
wcex.hCursor = LoadCursor(nullptr, IDC_ARROW);
wcex.hbrBackground = (HBRUSH)(COLOR_WINDOW+1);
wcex.lpszMenuName = MAKEINTRESOURCEW(IDC_GUESSTHENUMBERGUI);
wcex.lpszClassName = szWindowClass;
wcex.hIconSm = LoadIcon(wcex.hInstance, MAKEINTRESOURCE(IDI_ADEETHYIA));
return RegisterClassExW(&wcex);
}
//
// FUNCTION: InitInstance(HINSTANCE, int)
//
// PURPOSE: Saves instance handle and creates main window
//
// COMMENTS:
//
// In this function, we save the instance handle in a global variable and
// create and display the main program window.
//
BOOL InitInstance(HINSTANCE hInstance, int nCmdShow)
{
hInst = hInstance; // Store instance handle in our global variable
HWND hWnd = CreateWindowW(szWindowClass, szTitle, WS_OVERLAPPEDWINDOW,
CW_USEDEFAULT, 0, CW_USEDEFAULT, 0, nullptr, nullptr, hInstance, nullptr);
if (!hWnd)
{
return FALSE;
}
ShowWindow(hWnd, nCmdShow);
UpdateWindow(hWnd);
return TRUE;
}
//
// FUNCTION: WndProc(HWND, UINT, WPARAM, LPARAM)
//
// PURPOSE: Processes messages for the main window.
//
// WM_COMMAND - process the application menu
// WM_PAINT - Paint the main window
// WM_DESTROY - post a quit message and return
//
//
LRESULT CALLBACK WndProc(HWND hWnd, UINT message, WPARAM wParam, LPARAM lParam)
{
RECT window;
GetClientRect(hWnd, &window);
wchar_t fn[10], sn[10], ng[10], g[10];
switch (message)
{
case WM_COMMAND:
{
int wmId = LOWORD(wParam);
// Parse the menu selections:
switch (wmId)
{
break;
case IDM_EXIT:
DestroyWindow(hWnd);
break;
case IDM_START:
if (!gameStarted)
{
GetWindowTextW(hFN, fn, 10);
GetWindowTextW(hSN, sn, 10);
GetWindowTextW(hNGuesses, ng, 10);
if (std::wstring(fn) == L"" || std::wstring(sn) == L"" || std::wstring(ng) == L"")
{
int i = (std::wstring(fn) == L"") + (std::wstring(sn) == L"") + (std::wstring(ng) == L"");
MessageBoxW(hWnd, L"Enter a whole number in each box", (L"Boxes left empty: " + std::to_wstring(i)).c_str(), MB_OK);
break;
}
if (std::stoull(ng) == 0)
{
MessageBoxW(hWnd, L"Number of guesses cannot be 0", L"No guesses?", MB_OK);
break;
}
lowerNumber = min(std::stoull(fn), std::stoull(sn));
higherNumber = max(std::stoull(fn), std::stoull(sn));
lowerHelp = lowerNumber;
higherHelp = higherNumber;
guesses = std::stoull(ng);
guessesleft = guesses;
std::wstring msg = std::wstring(L"Range: " + std::to_wstring(lowerNumber) + L" to " + std::to_wstring(higherNumber) + L"\n" + L"Guesses: " + std::to_wstring(guesses));
gameStarted = true;
DeleteObject(fn);
DeleteObject(sn);
DeleteObject(ng);
DestroyWindow(hRange);
DestroyWindow(hFN);
DestroyWindow(hTo);
DestroyWindow(hSN);
DestroyWindow(hGuesses);
DestroyWindow(hNGuesses);
DestroyWindow(hStart);
std::random_device rd; // only used once to initialise (seed) engine
std::mt19937 rng(rd()); // random-number engine used (Mersenne-Twister in this case)
std::uniform_int_distribution<unsigned long long> uni(lowerNumber, higherNumber);
number = uni(rng);
SendMessageW(hWnd, (UINT)WM_CREATE, (WPARAM)0, (LPARAM)0);
}
else if (gameStarted)
{
std::wstring msg = std::wstring(L"Range: " + std::to_wstring(lowerNumber) + L" to " + std::to_wstring(higherNumber) + L"\n" + L"Guesses left: " + std::to_wstring(guessesleft));
MessageBoxW(hWnd, msg.c_str(), L"Range and Guesses Left", MB_OK);
}
break;
case IDM_GUESS:
if (gameStarted)
{
GetWindowTextW(hEnterGuess, g, 10);
if (std::wstring(g) == L"")
{
break;
}
guessesleft--;
std::wstring hol = L"";
std::wstring title = L"";
SetWindowTextW(hNGuessesLeft, std::to_wstring(guessesleft).c_str());
if (std::stoull(g) == number)
{
double Scor = 100000 * log(higherNumber - lowerNumber + 1) / log(2) / (guesses - guessesleft);
double score = ceil(Scor) / 100;
title = L"You succeeded!";
hol = L"You succeeded!\nTries used: " + std::to_wstring(guesses - guessesleft) + L"\nScore: " + std::to_wstring(score);
MessageBoxW(hWnd, hol.c_str(), title.c_str(), MB_ICONINFORMATION);
gameStarted = false;
DestroyWindow(hGuess);
DestroyWindow(hEnterGuess);
DestroyWindow(hGuessButton);
SendMessage(hWnd, (UINT)WM_CREATE, (WPARAM)0, (LPARAM)0);
}
else if (guessesleft == 0)
{
title = L"You failed!";
hol = L"You failed!\nThe number was " + std::to_wstring(number) + L"\nTries used: " + std::to_wstring(guesses - guessesleft) + L"\nScore: 0";
MessageBoxW(hWnd, hol.c_str(), title.c_str(), MB_ICONERROR);
gameStarted = false;
DestroyWindow(hGuess);
DestroyWindow(hEnterGuess);
DestroyWindow(hGuessButton);
SendMessage(hWnd, (UINT)WM_CREATE, (WPARAM)0, (LPARAM)0);
}
else if (std::stoull(g) > number)
{
title = L"Lower";
hol = L"The number is less than " + std::wstring(g) + L"\nTries left: " + std::to_wstring(guessesleft);
MessageBoxW(hWnd, hol.c_str(), title.c_str(), MB_OK);
higherHelp = std::stoull(g);
}
else if (std::stoull(g) < number)
{
title = L"Higher";
hol = L"The number is more than " + std::wstring(g) + L"\nTries left: " + std::to_wstring(guessesleft);
MessageBoxW(hWnd, hol.c_str(), title.c_str(), MB_OK);
lowerHelp = std::stoull(g);
}
}
else
{
MessageBoxW(hWnd, L"A game has not been started yet", L"Game not started", MB_OK);
}
break;
case IDM_HELP:
if (!gameStarted)
{
SetWindowTextW(hFN, L"1");
SetWindowTextW(hSN, L"100");
SetWindowTextW(hNGuesses, L"10");
int choice = MessageBoxW(hWnd, L"Guess a random number in a specified range with a specified amount of guesses\n\nPress OK to start", L"Start Game", MB_OKCANCEL);
if (choice == IDOK)
{
SendMessage(hWnd, (UINT)WM_COMMAND, (WPARAM)IDM_START, (LPARAM)0);
}
}
else if (gameStarted)
{
unsigned long long goodguess = (lowerHelp + higherHelp) / 2;
SetWindowTextW(hEnterGuess, std::to_wstring(goodguess).c_str());
int choice = MessageBoxW(hWnd, (L"Guess the random number between " + std::to_wstring(lowerNumber) + L" and " + std::to_wstring(higherNumber) + L" in " + std::to_wstring(guessesleft) + L" guesses\n\nPress OK to guess").c_str(), L"Enter Guess", MB_OKCANCEL);
if (choice == IDOK)
{
SendMessage(hWnd, (UINT)WM_COMMAND, (WPARAM)IDM_GUESS, (LPARAM)0);
}
}
break;
default:
return DefWindowProc(hWnd, message, wParam, lParam);
}
}
break;
case WM_CREATE:
if (!gameStarted)
{
hGTN = CreateWindowExW(0L, L"static", L"Guess The Number", WS_VISIBLE | WS_CHILD | ES_CENTER, 0, 0, window.right, window.bottom / 4, hWnd, NULL, NULL, NULL);
hRange = CreateWindowExW(0L, L"static", L"Range:", WS_VISIBLE | WS_CHILD | ES_CENTER, 0, 5 * window.bottom / 16, window.right / 4, window.bottom / 4, hWnd, NULL, NULL, NULL);
hFN = CreateWindowExW(0L, L"Edit", L"", WS_VISIBLE | WS_CHILD | WS_BORDER | ES_NUMBER | ES_CENTER, window.right / 4, 5 * window.bottom / 16, window.right / 4, window.bottom / 4, hWnd, NULL, NULL, NULL);
hTo = CreateWindowExW(0L, L"static", L" to ", WS_VISIBLE | WS_CHILD | ES_CENTER, 2 * window.right / 4, 5 * window.bottom / 16, window.right / 4, window.bottom / 4, hWnd, NULL, NULL, NULL);
hSN = CreateWindowExW(0L, L"Edit", L"", WS_VISIBLE | WS_CHILD | WS_BORDER | ES_NUMBER | ES_CENTER, 3 * window.right / 4, 5 * window.bottom / 16, window.right / 4, window.bottom / 4, hWnd, NULL, NULL, NULL);
hGuesses = CreateWindowExW(0L, L"static", L"Number of Guesses:", WS_VISIBLE | WS_CHILD | ES_CENTER, 0, 5 * window.bottom / 8, 2 * window.right / 4, window.bottom / 4, hWnd, NULL, NULL, NULL);
hNGuesses = CreateWindowExW(0L, L"Edit", L"", WS_VISIBLE | WS_CHILD | WS_BORDER | ES_NUMBER | ES_CENTER, 2 * window.right / 4, 5 * window.bottom / 8, 2 * window.right / 4, window.bottom / 4, hWnd, NULL, NULL, NULL);
hStart = CreateWindowExW(0L, L"Button", L"Start", WS_VISIBLE | WS_CHILD | WS_BORDER, 0, 7 * window.bottom / 8, window.right, window.bottom / 8, hWnd, (HMENU)IDM_START, NULL, NULL);
SendMessageW(hFN, (UINT)EM_SETLIMITTEXT, (WPARAM)10, (LPARAM)0);
SendMessageW(hSN, (UINT)EM_SETLIMITTEXT, (WPARAM)10, (LPARAM)0);
SendMessageW(hNGuesses, (UINT)EM_SETLIMITTEXT, (WPARAM)10, (LPARAM)0);
}
else if (gameStarted)
{
hGuess = CreateWindowExW(0L, L"static", L"Enter Guess:", WS_VISIBLE | WS_CHILD | ES_CENTER, 0, 5 * window.bottom / 16, window.right / 2, window.bottom / 4, hWnd, NULL, NULL, NULL);
hEnterGuess = CreateWindowExW(0L, L"Edit", L"", WS_VISIBLE | WS_CHILD | WS_BORDER | ES_NUMBER | ES_CENTER, window.right / 2, 5 * window.bottom / 16, window.right / 2, window.bottom / 4, hWnd, NULL, NULL, NULL);
hGuessesLeft = CreateWindowExW(0L, L"static", L"Guesses Left:", WS_VISIBLE | WS_CHILD | ES_CENTER, 0, 10 * window.bottom / 16, window.right / 2, window.bottom / 4, hWnd, NULL, NULL, NULL);
hNGuessesLeft = CreateWindowExW(0L, L"static", std::to_wstring(guessesleft).c_str(), WS_VISIBLE | WS_CHILD | ES_CENTER, 0, 10 * window.bottom / 16, window.right / 2, window.bottom / 4, hWnd, NULL, NULL, NULL);
hGuessButton = hStart = CreateWindowExW(0L, L"Button", L"Guess", WS_VISIBLE | WS_CHILD | WS_BORDER | ES_CENTER, 0, 7 * window.bottom / 8, window.right, window.bottom / 8, hWnd, (HMENU)IDM_GUESS, NULL, NULL);
SendMessageW(hEnterGuess, (UINT)EM_SETLIMITTEXT, (WPARAM)10, (LPARAM)0);
}
case WM_PAINT:
{
int length = window.right > window.bottom ? window.bottom : window.right;
int font = (int)120 * length / 534;
if (font > 200)
font = 200;
else if (font > 150)
font = 150;
else if (font > 100)
font = 100;
else if (font > 50)
font = 50;
else
font = 30;
HFONT hFont = CreateFont(font, 0, 0, 0, FW_REGULAR, FALSE, FALSE, FALSE, UNICODE, OUT_DEFAULT_PRECIS, CLIP_DEFAULT_PRECIS, DEFAULT_QUALITY, DEFAULT_PITCH | FF_SWISS, L"Calibri");
HFONT hFont1 = CreateFont(font / 2, 0, 0, 0, FW_REGULAR, FALSE, FALSE, FALSE, UNICODE, OUT_DEFAULT_PRECIS, CLIP_DEFAULT_PRECIS, DEFAULT_QUALITY, DEFAULT_PITCH | FF_SWISS, L"Calibri");
SendMessage(hGTN, (UINT)WM_SETFONT, (WPARAM)hFont, (LPARAM)0);
if (!gameStarted)
{
MoveWindow(hGTN, 0, 0, window.right, window.bottom / 4, true);
MoveWindow(hRange, 0, 5 * window.bottom / 16, window.right / 4, window.bottom / 4, true);
SendMessage(hRange, (UINT)WM_SETFONT, (WPARAM)hFont1, (LPARAM)0);
MoveWindow(hFN, window.right / 4, 5 * window.bottom / 16, window.right / 4, window.bottom / 4, true);
SendMessage(hFN, (UINT)WM_SETFONT, (WPARAM)hFont1, (LPARAM)0);
MoveWindow(hTo, 2 * window.right / 4, 5 * window.bottom / 16, window.right / 4, window.bottom / 4, true);
SendMessage(hTo, (UINT)WM_SETFONT, (WPARAM)hFont1, (LPARAM)0);
MoveWindow(hSN, 3 * window.right / 4, 5 * window.bottom / 16, window.right / 4, window.bottom / 4, true);
SendMessage(hSN, (UINT)WM_SETFONT, (WPARAM)hFont1, (LPARAM)0);
MoveWindow(hGuesses, 0, 5 * window.bottom / 8, 2 * window.right / 4, window.bottom / 4, true);
SendMessage(hGuesses, (UINT)WM_SETFONT, (WPARAM)hFont1, (LPARAM)0);
MoveWindow(hNGuesses, 2 * window.right / 4, 5 * window.bottom / 8, 2 * window.right / 4, window.bottom / 4, true);
SendMessage(hNGuesses, (UINT)WM_SETFONT, (WPARAM)hFont1, (LPARAM)0);
MoveWindow(hStart, 0, 7 * window.bottom / 8, window.right, window.bottom / 8, true);
SendMessage(hStart, (UINT)WM_SETFONT, (WPARAM)hFont1, (LPARAM)0);
}
else
{
MoveWindow(hGTN, 0, 0, window.right, window.bottom / 4, true);
MoveWindow(hGuess, 0, 5 * window.bottom / 16, window.right / 2, window.bottom / 4, true);
SendMessage(hGuess, (UINT)WM_SETFONT, (WPARAM)hFont1, (LPARAM)0);
MoveWindow(hEnterGuess, window.right / 2, 5 * window.bottom / 16, window.right / 2, window.bottom / 4, true);
SendMessage(hEnterGuess, (UINT)WM_SETFONT, (WPARAM)hFont1, (LPARAM)0);
MoveWindow(hGuessesLeft, 0, 10 * window.bottom / 16, window.right / 2, window.bottom / 4, true);
SendMessage(hGuessesLeft, (UINT)WM_SETFONT, (WPARAM)hFont1, (LPARAM)0);
MoveWindow(hNGuessesLeft, window.right / 2, 10 * window.bottom / 16, window.right / 2, window.bottom / 4, true);
SendMessage(hNGuessesLeft, (UINT)WM_SETFONT, (WPARAM)hFont1, (LPARAM)0);
MoveWindow(hGuessButton, 0, 7 * window.bottom / 8, window.right, window.bottom / 8, true);
SendMessage(hGuessButton, (UINT)WM_SETFONT, (WPARAM)hFont1, (LPARAM)0);
}
PAINTSTRUCT ps;
HDC hdc = BeginPaint(hWnd, &ps);
// TODO: Add any drawing code that uses hdc here...
EndPaint(hWnd, &ps);
}
break;
case WM_CTLCOLORSTATIC:
if (true)
{
HBRUSH hBrush = CreateSolidBrush(RGB(255, 255, 255));
HDC hdcStatic = (HDC)wParam;
SetTextColor(hdcStatic, RGB(0, 0, 0));
SetBkColor(hdcStatic, RGB(255, 255, 255));
return (INT_PTR)hBrush;
}
case WM_DESTROY:
PostQuitMessage(0);
break;
default:
return DefWindowProc(hWnd, message, wParam, lParam);
}
return 0;
}
|
#include<iostream>
#include<cstdio>
#include<map>
#include<set>
#include<vector>
#include<stack>
#include<queue>
#include<string>
#include<cstring>
#include<algorithm>
#include<cmath>
using namespace std;
const double win[9][9] = { 0.50, 0.58, 0.59, 0.45, 0.56, 0.58,0.57,0.39,0.38,
0.42, 0.50, 0.65, 0.75, 0.68, 0.52, 0.40, 0.55, 0.60,
0.41, 0.35, 0.50 ,0.46, 0.48 , 0.47 , 0.44 , 0.57 , 0.54,
0.55, 0.25, 0.54 , 0.50, 0.53 , 0.51 , 0.63 , 0.52 , 0.42,
0.44, 0.32, 0.52 , 0.47, 0.50 , 0.47 , 0.46, 0.55 , 0.46,
0.42, 0.48, 0.53 , 0.49, 0.53 , 0.50 , 0.44 , 0.40 , 0.59,
0.43, 0.60 , 0.56 , 0.37 , 0.54 , 0.56 , 0.50 , 0.68 , 0.39,
0.61, 0.45 , 0.43 , 0.48 , 0.45 , 0.60 , 0.32 , 0.50 , 0.48,
0.62, 0.40 , 0.46 , 0.58 , 0.54 , 0.41 , 0.61 , 0.52 , 0.50};
map<string,int> dic;
int a[5],b[5];
int main()
{
dic["Druid"] = 0;dic["Hunter"] = 1;dic["Mage"] = 2;
dic["Shaman"] = 3;dic["Paladin"] = 4;dic["Warlock"] = 5;
dic["Warrior"] = 6;dic["Rogue"] = 7;dic["Priest"] = 8;
int t;
string st;
scanf("%d",&t);
while (t--) {
for (int i = 1;i <= 3; i++) {
cin >> st;
a[i] = dic[st];
}
for (int i = 1;i <= 3; i++) {
cin >> st;
b[i] = dic[st];
}
double ans = 0;
for (int i = 1;i <= 3; i++)
ans += win[a[i]][b[i]];
printf("%.2lf\n",ans);
}
return 0;
}
|
#include "ManagerUtils/PlotUtils/interface/Common.hpp"
#include "TriggerEfficiency/EfficiencyPlot/interface/EfficiencyPlot.h"
#include "TEfficiency.h"
#include <iostream>
using namespace std;
extern double
ErrorProp(const double& x1, const double& m1, const double& x2,const double& m2)
{
double result = sqrt( (m1*m1)/(x2*x2) + (m2*m2)*(x1*x1)/(x2*x2*x2*x2));
return result;
}
extern TH1*
MakeScale(TEfficiency* data, TEfficiency* mc)
{
TH1* scale =data->GetCopyTotalHisto();
int xbins = scale->GetXaxis()->GetNbins();
int ybins = scale->GetYaxis()->GetNbins();
int databin, mcbin;
double deff, derr, meff, merr, seff, serr;
for(int i=0; i < xbins+2; ++i){
for(int j=0; j < ybins+2; ++j){
databin = data->GetGlobalBin(i, j);
deff = data->GetEfficiency( databin );
derr = data->GetEfficiencyErrorLow( databin );
mcbin = mc->GetGlobalBin( i,j ) ;
meff = mc->GetEfficiency( mcbin );
merr = mc->GetEfficiencyErrorLow( mcbin );
if( meff!=0 ){
seff = deff/meff;
serr = ErrorProp(deff, derr, meff, merr);
}
else{
seff = 0;
serr = 0;
}
scale->SetBinContent(i, j, seff);
scale->SetBinError(i, j, serr);
}
}
return scale;
}
extern void
PlotSF()
{
for( const auto& trg : PlotMgr().GetListData<string>( "trglst" ) ){
TH1* scale = MakeScale( HistTEff( "data" + trg, "eff_pt_eta"), HistTEff( "mc" + trg, "eff_pt_eta") );
mgr::SaveToROOT( scale, PlotMgr().GetResultsName( "root", "SF_HLT_Ele40" ), "SF_pt_eta" );
TCanvas* c = mgr::NewCanvas();
scale->Draw("COLZ text");
scale->SetStats( false );
scale->SetTitle("");
scale->GetYaxis()->SetTitle( "P_{T} [GeV]" );
scale->GetXaxis()->SetTitle( "SuperCluster #eta" );
mgr::SetAxis( scale );
mgr::SetSinglePad(c);
c->SetRightMargin( 1 );
mgr::DrawCMSLabelOuter( PRELIMINARY );
mgr::DrawLuminosity(41290);
mgr::SaveToPDF( c, PlotMgr().GetResultsName( "pdf", "SF_" + trg ) );
}
}
|
/*********************************************************\
* Copyright (c) 2012-2018 The Unrimp Team
*
* 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.
\*********************************************************/
//[-------------------------------------------------------]
//[ Header guard ]
//[-------------------------------------------------------]
#pragma once
//[-------------------------------------------------------]
//[ Includes ]
//[-------------------------------------------------------]
#include "Renderer/SmartRefCount.h"
#include "Renderer/Texture/TextureTypes.h"
//[-------------------------------------------------------]
//[ Forward declarations ]
//[-------------------------------------------------------]
namespace Renderer
{
class IRenderer;
class ITexture1D;
class ITexture2D;
class ITexture3D;
class ITextureCube;
class ITexture2DArray;
}
//[-------------------------------------------------------]
//[ Namespace ]
//[-------------------------------------------------------]
namespace Renderer
{
//[-------------------------------------------------------]
//[ Classes ]
//[-------------------------------------------------------]
/**
* @brief
* Abstract texture manager interface
*
* @remarks
* The texture manager is responsible for managing fine granular instances of
* - 1D texture ("Renderer::ITexture1D")
* - 2D texture ("Renderer::ITexture2D")
* - 2D texture array ("Renderer::ITexture2DArray")
* - 3D texture ("Renderer::ITexture3D")
* - Cube texture ("Renderer::ITextureCube")
*/
class ITextureManager : public RefCount<ITextureManager>
{
//[-------------------------------------------------------]
//[ Public methods ]
//[-------------------------------------------------------]
public:
/**
* @brief
* Destructor
*/
inline virtual ~ITextureManager() override;
/**
* @brief
* Return the owner renderer instance
*
* @return
* The owner renderer instance, do not release the returned instance unless you added an own reference to it
*/
inline IRenderer& getRenderer() const;
//[-------------------------------------------------------]
//[ Public virtual Renderer::ITextureManager methods ]
//[-------------------------------------------------------]
public:
//[-------------------------------------------------------]
//[ Resource creation ]
//[-------------------------------------------------------]
/**
* @brief
* Create a 1D texture instance
*
* @param[in] width
* Texture width, must be >0 else a null pointer is returned
* @param[in] textureFormat
* Texture format
* @param[in] data
* Texture data, can be a null pointer, the data is internally copied and you have to free your memory if you no longer need it
* @param[in] flags
* Texture flags, see "Renderer::TextureFlag::Enum"
* @param[in] textureUsage
* Indication of the texture usage
*
* @return
* The created 1D texture instance, null pointer on error. Release the returned instance if you no longer need it.
*
* @note
* - The following texture data layout is expected: Mip0, Mip1, Mip2, Mip3 ...
*/
virtual ITexture1D* createTexture1D(uint32_t width, TextureFormat::Enum textureFormat, const void* data = nullptr, uint32_t flags = 0, TextureUsage textureUsage = TextureUsage::DEFAULT) = 0;
/**
* @brief
* Create a 2D texture instance
*
* @param[in] width
* Texture width, must be >0 else a null pointer is returned
* @param[in] height
* Texture height, must be >0 else a null pointer is returned
* @param[in] textureFormat
* Texture data format
* @param[in] data
* Texture data, can be a null pointer, the data is internally copied and you have to free your memory if you no longer need it
* @param[in] flags
* Texture flags, see "Renderer::TextureFlag::Enum"
* @param[in] textureUsage
* Indication of the texture usage
* @param[in] numberOfMultisamples
* The number of multisamples per pixel (valid values: 1, 2, 4, 8)
* @param[in] optimizedTextureClearValue
* Optional optimized texture clear value
*
* @return
* The created 2D texture instance, null pointer on error. Release the returned instance if you no longer need it.
*
* @note
* - The following texture data layout is expected: Mip0, Mip1, Mip2, Mip3 ...
*/
virtual ITexture2D* createTexture2D(uint32_t width, uint32_t height, TextureFormat::Enum textureFormat, const void* data = nullptr, uint32_t flags = 0, TextureUsage textureUsage = TextureUsage::DEFAULT, uint8_t numberOfMultisamples = 1, const OptimizedTextureClearValue* optimizedTextureClearValue = nullptr) = 0;
/**
* @brief
* Create a 2D array texture instance
*
* @param[in] width
* Texture width, must be >0 else a null pointer is returned
* @param[in] height
* Texture height, must be >0 else a null pointer is returned
* @param[in] numberOfSlices
* Number of slices, must be >0 else a null pointer is returned
* @param[in] textureFormat
* Texture format
* @param[in] data
* Texture data, can be a null pointer, the data is internally copied and you have to free your memory if you no longer need it
* @param[in] flags
* Texture flags, see "Renderer::TextureFlag::Enum"
* @param[in] textureUsage
* Indication of the texture usage
*
* @return
* The created 2D array texture instance, null pointer on error. Release the returned instance if you no longer need it.
*
* @remarks
* The texture array data consists of a sequence of texture slices. Each the texture slice data of a single texture slice has to
* be in CRN-texture layout, which means organized in mip-major order, like this:
* - Mip0: Slice0, Slice1, Slice2, Slice3, Slice4, Slice5
* - Mip1: Slice0, Slice1, Slice2, Slice3, Slice4, Slice5
* (DDS-texture layout is using face-major order)
*
* @note
* - Only supported if "Renderer::Capabilities::maximumNumberOf2DTextureArraySlices" is not 0
*/
virtual ITexture2DArray* createTexture2DArray(uint32_t width, uint32_t height, uint32_t numberOfSlices, TextureFormat::Enum textureFormat, const void* data = nullptr, uint32_t flags = 0, TextureUsage textureUsage = TextureUsage::DEFAULT) = 0;
/**
* @brief
* Create a 3D texture instance
*
* @param[in] width
* Texture width, must be >0 else a null pointer is returned
* @param[in] height
* Texture height, must be >0 else a null pointer is returned
* @param[in] depth
* Texture depth, must be >0 else a null pointer is returned
* @param[in] textureFormat
* Texture format
* @param[in] data
* Texture data, can be a null pointer, the data is internally copied and you have to free your memory if you no longer need it
* @param[in] flags
* Texture flags, see "Renderer::TextureFlag::Enum"
* @param[in] textureUsage
* Indication of the texture usage
*
* @return
* The created 3D texture instance, null pointer on error. Release the returned instance if you no longer need it.
*
* @remarks
* The texture data has to be in CRN-texture layout, which means organized in mip-major order, like this:
* - Mip0: Slice0, Slice1, Slice2, Slice3, Slice4, Slice5
* - Mip1: Slice0, Slice1, Slice2, Slice3, Slice4, Slice5
* (DDS-texture layout is using face-major order)
*/
virtual ITexture3D* createTexture3D(uint32_t width, uint32_t height, uint32_t depth, TextureFormat::Enum textureFormat, const void* data = nullptr, uint32_t flags = 0, TextureUsage textureUsage = TextureUsage::DEFAULT) = 0;
/**
* @brief
* Create a cube texture instance
*
* @param[in] width
* Texture width, must be >0 else a null pointer is returned
* @param[in] height
* Texture height, must be >0 else a null pointer is returned
* @param[in] textureFormat
* Texture format
* @param[in] data
* Texture data, can be a null pointer, the data is internally copied and you have to free your memory if you no longer need it
* @param[in] flags
* Texture flags, see "Renderer::TextureFlag::Enum"
* @param[in] textureUsage
* Indication of the texture usage
*
* @return
* The created cube texture instance, null pointer on error. Release the returned instance if you no longer need it.
*
* @remarks
* The texture data has to be in CRN-texture layout, which means organized in mip-major order, like this:
* - Mip0: Face0, Face1, Face2, Face3, Face4, Face5
* - Mip1: Face0, Face1, Face2, Face3, Face4, Face5
* (DDS-texture layout is using face-major order)
*/
virtual ITextureCube* createTextureCube(uint32_t width, uint32_t height, TextureFormat::Enum textureFormat, const void* data = nullptr, uint32_t flags = 0, TextureUsage textureUsage = TextureUsage::DEFAULT) = 0;
//[-------------------------------------------------------]
//[ Protected methods ]
//[-------------------------------------------------------]
protected:
/**
* @brief
* Constructor
*
* @param[in] renderer
* Owner renderer instance
*/
inline explicit ITextureManager(IRenderer& renderer);
explicit ITextureManager(const ITextureManager& source) = delete;
ITextureManager& operator =(const ITextureManager& source) = delete;
//[-------------------------------------------------------]
//[ Private data ]
//[-------------------------------------------------------]
private:
IRenderer& mRenderer; ///< The owner renderer instance
};
//[-------------------------------------------------------]
//[ Type definitions ]
//[-------------------------------------------------------]
typedef SmartRefCount<ITextureManager> ITextureManagerPtr;
//[-------------------------------------------------------]
//[ Namespace ]
//[-------------------------------------------------------]
} // Renderer
//[-------------------------------------------------------]
//[ Implementation ]
//[-------------------------------------------------------]
#include "Renderer/Texture/ITextureManager.inl"
|
int sensor = 4;
int ler;
void setup() {
Serial.begin(9600);
pinMode(sensor, INPUT);
}
void loop() {
ler = digitalRead(sensor);
if (ler==1)
Serial.println("Livre");
else
Serial.println("Detectado");
delay(1000);
}
|
/*
nicole cranon <nicole.cranon@ucdenver.edu>
csci 4640, fall 2015
assignment 6 - predicate generator
*/
#include "predictGenerator.h"
#include "grammerAnalyzer.h"
#include <iostream>
#include <algorithm>
int main (int argc, char *argv[]) {
if (argc < 2) {
std::cerr << "\nNot enough arguments provided!\n";
return 0;
}
std::vector<std::string> ingrammer,
outgrammer,
RHSList,
LHSList;
std::set<std::string> nonterminals,
terminals,
symbols;
ga::read_productions (argv[1], ingrammer);
ga::analyze (ingrammer, outgrammer, nonterminals, terminals, symbols,
LHSList, RHSList);
for (unsigned i = 0; i < RHSList.size(); ++i) {
RHSList[i] = predict::normalize (RHSList[i]);
//std::cout << "\nRHS->" << RHSList[i] << "<-\n";
}
for (unsigned i = 0; i < LHSList.size(); ++i) {
LHSList[i] = predict::normalize (LHSList[i]);
//std::cout << "\nLHS->" << l << "<-\n";
}
auto tmpnonterminals = nonterminals;
for (std::set<std::string>::iterator itr = tmpnonterminals.begin(); itr != tmpnonterminals.end(); ++itr) {
auto temp = predict::normalize (*itr);
nonterminals.insert(temp);
nonterminals.erase(*itr);
}
auto tmpterminals = terminals;
for (std::set<std::string>::iterator itr = tmpterminals.begin(); itr != tmpterminals.end(); ++itr) {
auto temp = predict::normalize (*itr);
terminals.insert(temp);
terminals.erase(*itr);
}
auto tmpsymbols = symbols;
for (std::set<std::string>::iterator itr = tmpsymbols.begin(); itr != tmpsymbols.end(); ++itr) {
auto temp = predict::normalize (*itr);
symbols.insert(temp);
symbols.erase(*itr);
}
auto RHSStringList = predict::getRHS_stringList (RHSList);
predict::markLambda (LHSList, RHSStringList);
for (auto d : predict::derivesLambda) {
// std::cout << "\nDerives Lambda-> " << std::boolalpha << d.first << ' ' << d.second << " <-\n";
}
predict::fillFirstSet (nonterminals, terminals, LHSList, RHSList, RHSStringList);
std::cout << "\nFirst Sets";
for (auto nt: nonterminals) {
std::cout << '\n' << nt << " = {";
for (auto elem: predict::firstSet[nt]) {
if (elem.compare("") == 0) {
std::cout << "lambda";
} else {
std::cout << elem;
}
std::cout << ',';
}
std::cout << "}";
}
predict::fillFollowSet (nonterminals, terminals, LHSList, RHSList, RHSStringList);
std::cout << "\n\nFollow Sets";
for (auto nt: nonterminals) {
std::cout << '\n' << nt << " = {";
for (auto elem: predict::followSet[nt]) {
if (elem.compare("") == 0) {
std::cout << "lambda";
} else {
std::cout << elem;
}
std::cout << ',';
}
std::cout << "}";
}
predict::predict (LHSList, RHSList, RHSStringList);
std::cout << "\n\nPredict Sets";
for (unsigned i = 0; i < predict::predictSet.size(); ++i) {
std::cout << "\n " << i+1 << ". " << LHSList[i] << " = {";
for (auto elem: predict::predictSet[i]) {
std::cout << elem << ',';
}
std::cout << "}";
}
std::cout << "\n\n";
}
|
/*
* arrayStack.hpp
*
* Created on: 2017年3月21日
* Author: lcy
*/
#ifndef ARRAYSTACK_HPP_
#define ARRAYSTACK_HPP_
#include "Stack.hpp"
template<typename T>
class arrayStack : public stack<T>
{
public:
arrayStack(int initialCapacity = 10);
~arrayStack() {delete [] stack;}
bool empty() const {return stackTop == -1;}
int size() const {return stackTop + 1;}
T& top()
{
if(stackTop == -1)
throw illegalParameterValue("stack is empty");
return stack[stackTop];
}
void pop()
{
if(stackTop == -1)
throw illegalParameterValue("stack is empty");
stack[stackTop--].~T();
}
void push(const T& theElement);
void output(const std::ostream& out);
private:
int stackTop;
int arrayLength;
T* stack;
};
template<typename T>
arrayStack<T>::arrayStack(int initialCapacity)
{
if(initialCapacity < 1)
{
std::ostringstream s;
s << "Initial capacity = " << initialCapacity << " must be > 0";
throw illegalParameterValue(s.str());
}
arrayLength = initialCapacity;
stack = new T[arrayLength];
stackTop = -1;
}
template<typename T>
void arrayStack<T>::push(const T& theElement)
{
if(stackTop == arrayLength - 1)
{
T* temp = new T[arrayLength * 2];
std::copy(stack,stack + arrayLength,temp);
delete [] stack;
stack = temp;
}
stack[++stackTop] = theElement;
}
template<typename T>
void arrayStack<T>::output(const std::ostream& out)
{
if(stackTop == -1)
throw illegalParameterValue("stack is empty");
for(int i = 0;i <= stackTop;i++)
std::cout << stack[i] << std::endl;
}
template<typename T>
const std::ostream& operator<<(const std::ostream& out, arrayStack<T>& stack)
{
stack.output(out);
return out;
}
#endif /* ARRAYSTACK_HPP_ */
|
( English:'French';
Native:'Français';
LangFile:'french.lang';
DicFile:'francais.dic';
FlagID:'fr';
Letters:'A,B,C,D,E,F,G,H,I,J,K,L,M,N,O,P,Q,R,S,T,U,V,W,X,Y,Z';
LetterCount:'9,2,2,3,15,2,2,2,8,1,1,5,3,6,6,2,1,6,6,6,6,2,1,1,1,1';
LetterValue:'1,3,3,2,1,4,2,4,1,8,10,1,2,1,1,3,8,1,1,1,1,4,10,10,10,10';
NumberOfJokers:2;
ReadingDirection:rdLeftToRight;
ExcludedCat:'';
RulesValid:true;
NumberOfLetters:7;
NumberOfRandoms:0;
TimeControl:2;
TimeControlEnd:true; //point 7
TimeControlBuy:false; //point 7
TimePerGame:'0:50:00'; //http://www.ffsc.fr/classique.php?page=organisation (point 8) -> "Le temps alloué recommandé par joueur et par partie est de 25 minutes."
PenaltyValue:1; //this value ought to be zero, but zero is prohibited in the program
PenaltyCount:1; //this value ought to be zero, but zero is prohibited in the program
GameLostByTime:false; //point 7
WordCheckMode:2;
ChallengePenalty:5; //point 5.3 - a penalty of n points per word not being a feature in Scrabble3D, a setting of 5 points per move has been chosen arbitrarily
ChallengeTime:20; //chosen arbitrarily
JokerExchange:false;
ChangeIsPass:false; //not explicitly mentioned, therefore derived indirectly from point 4.2 and 4.3; JE CHANGE ≠ JE PASSE
CambioSecco:false;
SubstractLetters:true; //point 7
AddLetters:true; //point 7
JokerPenalty:0;
NumberOfPasses:3; //point 7
LimitExchange:7; //point 4.3
EndBonus:0;
ScrabbleBonus:50)
{References:
http://www.fisf.net
http://www.fisf.net/documents/reglements-et-guides.html
http://www.fisf.net/index.php?option=com_content&task=view&id=29&Itemid=52
http://www.fisf.net/index.php?option=com_docman&task=cat_view&gid=15&Itemid=45
- (RÈGLEMENT DU SCRABBLE CLASSIQUE DE COMPÉTITION, v7.5a (1er septembre 2010)
http://www.ffsc.fr
http://www.ffsc.fr/classique.php?page=reglement
http://www.ffsc.fr/classique.php?page=organisation
-
Current state of implementation in this *.inc file: 2012-08-10}
|
#include "scoreboard.h"
#include "game.h"
extern Game* game;
ScoreBoard::ScoreBoard(QObject* parent, int f, int s, int u, int t, int sc, int lv)
{
Q_UNUSED(parent)
setRect(QRectF(0,0,400,400));
setBrush(Qt::darkBlue);
QPen pen(Qt::green, 2);
setPen(pen);
finished_processes = new QGraphicsTextItem(this);
finished_processes->setPlainText(QString("finished processes: %1").arg(f));
finished_processes->setFont(QFont("times",15));
finished_processes->setDefaultTextColor(Qt::green);
finished_processes->setPos(x()+100,y()+60);
starved_processes = new QGraphicsTextItem(this);
starved_processes->setPlainText(QString("starved processes: %1").arg(s));
starved_processes->setFont(QFont("times",15));
starved_processes->setPos(x()+100,y()+90);
starved_processes->setDefaultTextColor(Qt::green);
user_satisfaction = new QGraphicsTextItem(this);
user_satisfaction->setPlainText(QString("user satisfaction: %1").arg(u));
user_satisfaction->setFont(QFont("times",15));
user_satisfaction->setPos(x()+100,y()+120);
user_satisfaction->setDefaultTextColor(Qt::green);
total_time = new QGraphicsTextItem(this);
float timeInMinutes = t/60;
float timeInsSeconds = t - timeInMinutes*60;
total_time->setPlainText(QString("total time: %1:%2 ").arg(timeInMinutes).arg(timeInsSeconds));
total_time->setFont(QFont("times",15));
total_time->setPos(x()+100,y()+150);
total_time->setDefaultTextColor(Qt::green);
score = new QGraphicsTextItem(this);
score->setPlainText(QString("score: %1").arg(sc));
score->setFont(QFont("times",15));
score->setPos(x()+100, y()+180);
score->setDefaultTextColor(Qt::green);
back_to_menu = new QPushButton();
back_to_menu->setText("back to menu");
connect(back_to_menu, &QPushButton::clicked, this, &ScoreBoard::emit_game_finished);
if(lv!=0)
tsc = (f + s + u + t + sc)/5*lv;
else
tsc = (f + s + u + t + sc)/5;
TotalScore = new QGraphicsTextItem(this);
TotalScore->setPlainText(QString("total score: %1").arg(tsc));
TotalScore->setFont(QFont("times",15));
TotalScore->setDefaultTextColor(Qt::green);
TotalScore->setPos(x()+100,y()+210);
}
int ScoreBoard::getScore()
{
return tsc;
}
void ScoreBoard::emit_game_finished()
{
game->emit closeGame();
game->close();
}
|
#include "PointersManager.h"
bool PointersManager::checkMouseInPointer(std::shared_ptr<Pointer> ptr, Position pos)
{
float x = ptr->getPosition().x - ptr->getSize().width/2;
float y = ptr->getPosition().y - ptr->getSize().height / 2;
if (x < pos.x && pos.x < x + ptr->getSize().width && y < pos.y && pos.y < y + ptr->getSize().height)
return true;
return false;
}
void PointersManager::recalcDelta()//изменение скорости движения фишки
{
float summ = 0;
for (int i = 0; i < moved_vect.size()-1; i++)
{
float y1 = moved_vect[i].y;
float y2 = moved_vect[i + 1].y;
float x1 = moved_vect[i].x;
float x2 = moved_vect[i + 1].x;
summ += sqrt((x1 - x2)*(x1 - x2) + (y1 - y2)*(y1 - y2));
}
if (!const_speed)
delta_cur += speedup;
if (delta_cur > delta && speedup > 0)
{
lenght_speedup = lenght_path;
const_speed = true;
}
if (abs(lenght_path - summ)<0.5)
{
delta_cur = 0;
lenght_path = 0;
const_speed = false;
lenght_speedup = 0;
}
}
int PointersManager::setMarkMovedPointer(Position mousepos)
{
for (int i = 0; i < movedpointers.size(); i++)
{
if(checkMouseInPointer(movedpointers[i], mousepos))
{
movedpointers[i]->setMarked(true);
return i;
}
}
return -1;
}
void PointersManager::drawPointers()
{
for (int i = 0; i < crosspointers.size(); i++)
crosspointers[i]->draw();
for (int i = 0; i < movedpointers.size(); i++)
movedpointers[i]->draw();
}
void PointersManager::updatePointers(Position mouse, bool isdown, bool &isclick)
{
if (!isdown)
isclick = false;
if (ismoved)
{
int indx = -1;
if (cur_line<moved_vect.size()-1)
{
float y1 = moved_vect[cur_line].y;
float y2 = moved_vect[cur_line + 1].y;
float x1 = moved_vect[cur_line].x;
float x2 = moved_vect[cur_line + 1].x;
float dy = y2 - y1;
float dx = x2 - x1;
float a = sqrt(dy*dy + dx*dx);
lenght_path+=delta_cur;
movedpointers[moved_elem_index]->addToPosition(delta_cur*dx/a, delta_cur*dy/a);
recalcDelta();
ismoved = true;
Position pos = movedpointers[moved_elem_index]->getPosition();
if (abs(y2 - pos.y) < 0.2 && abs(x2 - pos.x) < 0.2)
{
movedpointers[moved_elem_index]->setPosition(Position(x2, y2));
cur_line++;
}
}
else
{
cur_line = 0;
lenght_path = 0;
ismoved = false; //остановка движения
moved_vect.erase(moved_vect.begin(), moved_vect.end()); //очистка вектора движения
}
}
else
{
for (int i = 0; i < movedpointers.size(); i++)
if (checkMouseInPointer(movedpointers[i], mouse) && isdown && !isclick) //клик на фишке
{
movedpointers[i]->setMarked(true);//делаем ее выделенной
movedpointers[i]->update();
isclick = true;
for (int j = 0; j < movedpointers.size(); j++)
{
if (i != j && movedpointers[j]->isMarked()) // убираем выделение выделенным другим
{
movedpointers[j]->setMarked(false);
movedpointers[j]->update();
}
}
for (int j = 0; j < crosspointers.size(); j++) // убираем выделения пересечений
{
crosspointers[j]->setMarked(false);
}
for (int j = 0; j < crosspointers.size(); j++) //выставляем путь для прохождения фишки
{
if (crosspointers[j]->getNumb() == movedpointers[i]->getCurNumb())
{
crosspointers[j]->setMarkedPath();
break;
}
}
break;
}
for (int i = 0; i < crosspointers.size(); i++)
if (checkMouseInPointer(crosspointers[i], mouse) && isdown && !isclick && crosspointers[i]->isMarked())//поинтер на который идем
{
for (int j = 0; j < movedpointers.size(); j++)//просматриваем все маркеры
if (movedpointers[j]->isMarked()) //если маркер сейчас активен
{
for (int k = 0; k < crosspointers.size(); k++)//смотрим все поинтеры с которых маркер может идти
if (crosspointers[k]->getNumb() == movedpointers[j]->getCurNumb())//тот что сейчас маркер на поинтере
{
std::vector<Position> moved_vect_t = crosspointers[k]->findPath(crosspointers[i]->getNumb());//ищем путь от поинтера где сейчас маркер до того поинтера куда кликнули
if (!moved_vect_t.empty())
{
moved_vect.push_back(movedpointers[j]->getPosition());//добавили начальную координату для движения
moved_vect.insert(moved_vect.end(), moved_vect_t.begin(), moved_vect_t.end()); // вставили все остальные координаты и получили полный путь
crosspointers[k]->setMarked(true);//поставили выделение поинтера начального
crosspointers[i]->setMarked(false);//убрали выделение текущего поинтера
crosspointers[k]->setBusy(false); //убрал значение занятости у поинтера старого
crosspointers[i]->setBusy(true); // установил текущую занятость
movedpointers[j]->setCurNumb(crosspointers[i]->getNumb()); //установил у маркера ид поинтера
for (int i = 0; i < crosspointers.size(); i++)//очистить пути
crosspointers[i]->resetRoute();
}
break;
}
if (!moved_vect.empty())
{
moved_elem_index = j;
ismoved = true;
}
break;
}
isclick = true;
}
}
}
//индексы для чтения данных выгруженных из файла
#define CNT_MOVED 0 // запись количества фишек
#define CNT_ALL_CROSS 1 // кол-во пересечений
#define START_POSITIONS 2 // начало позиций пересечений
#define LIST_MOVED_POINT 0 // началальное расположение фишек
#define LIST_MOVED_GOAL 1 // нужное расположение
#define CNT_ROUTES 2 // количество связей
#define START_ROUTES 3 //начало перечисления связей
void PointersManager::getPointersFromFile(std::string file)
{
char buf[100];
std::vector<std::string> data;
FILE* f = NULL;
f = fopen(file.c_str(), "r");
if (f == nullptr)
return;
while (1)
{
char * result = fgets(buf, 100, f);
if (!result) break;
int strln = strlen(result);
if (result[strln -1] == '\n') result[strln-1] = 0;
data.push_back(result);
}
fclose(f);
int cntmoved = atoi(data[CNT_MOVED].c_str());
int cntcross = atoi(data[CNT_ALL_CROSS].c_str());
int i = 0;
if (!crosspointers.empty())
{
crosspointers.erase(crosspointers.begin(), crosspointers.end());
movedpointers.erase(movedpointers.begin(), movedpointers.end());
init();
}
//создание точек пересечения
while (i < cntcross)
{
crosspointers.push_back(std::make_shared<Pointer>());
crosspointers[i]->setNumb(i + 1);
crosspointers[i]->setColor(0xff0066ff);
crosspointers[i]->setSpriteColor(0xff0066ff);
crosspointers[i]->setMrkColor(0x800066ff);//цвет при выделении
crosspointers[i]->setSize(Size(20, 20));
crosspointers[i]->setSizeForGoal(Size(20/delim, 20/delim));
i++;
}
//создание маркеров
i = 0;
while (i < cntmoved)
{
movedpointers.push_back(std::make_shared<Pointer>());
int color = RGB(rand() % 255, rand() % 255, rand() % 255);
movedpointers[i]->setColor(color + 0xff000000);
movedpointers[i]->setSpriteColor(color + 0xff000000);
movedpointers[i]->setMrkColor(color + 0x8f000000);
movedpointers[i]->setSize(Size(30, 30));
movedpointers[i]->setSizeForGoal(Size(30/delim, 30/delim));
i++;
}
i = 0;
//позиции для пересечений
while (i < cntcross)
{
int ch = 0;
std::string posX;
std::string posY;
while (data[START_POSITIONS + i][ch] != ',')
{
posX += data[START_POSITIONS + i][ch];
ch++;
}
while (ch < data[START_POSITIONS + i].length())
posY += data[START_POSITIONS + i][++ch];
crosspointers[i]->setPosition(Position(atof(posX.c_str()), atof(posY.c_str())));
crosspointers[i]->setPosGoal(Position(atof(posX.c_str())/delim+pospreview.x, atof(posY.c_str())/delim + pospreview.y));
i++;
}
i = 0;
int ch1 = 0;
int ch2 = 0;
while (i < cntmoved)
{
std::string id;
std::string idgoal;
// начальная нумерация маркера
while (data[START_POSITIONS + cntcross + LIST_MOVED_POINT][ch1] != ','&& ch1 < data[START_POSITIONS + cntcross + LIST_MOVED_POINT].length())
{
id += data[START_POSITIONS + cntcross + LIST_MOVED_POINT][ch1];
ch1++;
}
// нужный номер
while (data[START_POSITIONS + cntcross+ LIST_MOVED_GOAL][ch2] != ','&& ch2 < data[START_POSITIONS + cntcross+ LIST_MOVED_GOAL].length())
{
idgoal += data[START_POSITIONS + cntcross + LIST_MOVED_GOAL][ch2];
ch2++;
}
int numb = atoi(id.c_str());
int goaln = atoi(idgoal.c_str());
movedpointers[i]->setNumb(numb);
movedpointers[i]->setCurNumb(numb);
movedpointers[i]->setGoal(goaln);
movedpointers[i]->setPosition(crosspointers[numb - 1]->getPosition());
movedpointers[i]->setPosGoal(crosspointers[numb - 1]->getPosGoal());
crosspointers[numb-1]->setBusy(true);
i++; ch1++;
ch2++;
}
for (int i = 0; i < cntmoved; i++)
for (int j = 0; j < cntmoved; j++)
if (movedpointers[i]->getGoal()== movedpointers[j]->getNumb())
{
movedpointers[i]->setGoalColor(movedpointers[j]->getColor());
break;
}
//получение и заполнение возможных путей для движения фишки
int cnt_cross = atoi(data[START_POSITIONS + cntcross + CNT_ROUTES].c_str());
i = 0;
while (i < cnt_cross)
{
int ch = 0;
std::string idfrom;
std::string idto;
while (data[START_POSITIONS + cntcross + START_ROUTES + i][ch] != ',')
{
idfrom += data[START_POSITIONS + cntcross + START_ROUTES + i][ch];
ch++;
}
while (ch < data[START_POSITIONS + cntcross + START_ROUTES + i].length())
idto += data[START_POSITIONS + cntcross + START_ROUTES + i][++ch];
int idfromi = atoi(idfrom.c_str());
int idtoi = atoi(idto.c_str());
if (idfromi > 0 && idtoi > 0 && idfromi <= crosspointers.size() && idtoi <= crosspointers.size())
{
crosspointers[idfromi - 1]->addPtr(crosspointers[idtoi - 1]);
crosspointers[idtoi - 1]->addPtr(crosspointers[idfromi - 1]);
}
i++;
}
}
bool PointersManager::checkGoal()
{
if (!ismoved)
{
for (int i = 0; i < movedpointers.size(); i++)
{
if (movedpointers[i]->getCurNumb() != movedpointers[i]->getGoal())
return false;
}
return true;
}
return false;
}
|
// Created on: 1993-11-09
// Created by: Laurent BOURESCHE
// Copyright (c) 1993-1999 Matra Datavision
// Copyright (c) 1999-2014 OPEN CASCADE SAS
//
// This file is part of Open CASCADE Technology software library.
//
// This library is free software; you can redistribute it and/or modify it under
// the terms of the GNU Lesser General Public License version 2.1 as published
// by the Free Software Foundation, with special exception defined in the file
// OCCT_LGPL_EXCEPTION.txt. Consult the file LICENSE_LGPL_21.txt included in OCCT
// distribution for complete text of the license and disclaimer of any warranty.
//
// Alternatively, this file may be used under the terms of Open CASCADE
// commercial license or contractual agreement.
#ifndef _ChFi3d_Builder_HeaderFile
#define _ChFi3d_Builder_HeaderFile
#include <BRepAdaptor_Curve2d.hxx>
#include <BRepAdaptor_Surface.hxx>
#include <GeomAbs_Shape.hxx>
#include <ChFiDS_ErrorStatus.hxx>
#include <ChFiDS_Map.hxx>
#include <ChFiDS_Regularities.hxx>
#include <ChFiDS_SequenceOfSurfData.hxx>
#include <ChFiDS_StripeMap.hxx>
#include <ChFiDS_ElSpine.hxx>
#include <math_Vector.hxx>
#include <TopoDS_Shape.hxx>
#include <TopTools_ListOfShape.hxx>
#include <TopTools_DataMapOfShapeListOfInteger.hxx>
#include <TopTools_DataMapOfShapeShape.hxx>
#include <TopAbs_Orientation.hxx>
#include <TopAbs_State.hxx>
class TopOpeBRepDS_HDataStructure;
class TopOpeBRepBuild_HBuilder;
class TopoDS_Edge;
class ChFiDS_Spine;
class TopoDS_Vertex;
class Geom_Surface;
class ChFiDS_SurfData;
class Adaptor3d_TopolTool;
class BRepBlend_Line;
class Blend_Function;
class Blend_FuncInv;
class Blend_SurfRstFunction;
class Blend_SurfPointFuncInv;
class Blend_SurfCurvFuncInv;
class Blend_RstRstFunction;
class Blend_CurvPointFuncInv;
class ChFiDS_Stripe;
class BRepTopAdaptor_TopolTool;
class gp_Pnt2d;
class ChFiDS_CommonPoint;
class TopoDS_Face;
class AppBlend_Approx;
class Geom2d_Curve;
//! Root class for calculation of surfaces (fillets,
//! chamfers) destined to smooth edges of
//! a gap on a Shape and the reconstruction of the Shape.
class ChFi3d_Builder
{
public:
DEFINE_STANDARD_ALLOC
Standard_EXPORT virtual ~ChFi3d_Builder();
Standard_EXPORT void SetParams (const Standard_Real Tang,
const Standard_Real Tesp,
const Standard_Real T2d,
const Standard_Real TApp3d,
const Standard_Real TolApp2d,
const Standard_Real Fleche);
Standard_EXPORT void SetContinuity (const GeomAbs_Shape InternalContinuity,
const Standard_Real AngularTolerance);
//! extracts from the list the contour containing edge E.
Standard_EXPORT void Remove (const TopoDS_Edge& E);
//! gives the number of the contour containing E or 0
//! if E does not belong to any contour.
Standard_EXPORT Standard_Integer Contains (const TopoDS_Edge& E) const;
//! gives the number of the contour containing E or 0
//! if E does not belong to any contour.
//! Sets in IndexInSpine the index of E in the contour if it's found
Standard_EXPORT Standard_Integer Contains (const TopoDS_Edge& E,
Standard_Integer& IndexInSpine) const;
//! gives the number of disjoint contours on which
//! the fillets are calculated
Standard_EXPORT Standard_Integer NbElements() const;
//! gives the n'th set of edges (contour)
//! if I >NbElements()
Standard_EXPORT Handle(ChFiDS_Spine) Value (const Standard_Integer I) const;
//! returns the length of the contour of index IC.
Standard_EXPORT Standard_Real Length (const Standard_Integer IC) const;
//! returns the First vertex V of
//! the contour of index IC.
Standard_EXPORT TopoDS_Vertex FirstVertex (const Standard_Integer IC) const;
//! returns the Last vertex V of
//! the contour of index IC.
Standard_EXPORT TopoDS_Vertex LastVertex (const Standard_Integer IC) const;
//! returns the abscissa of the vertex V on
//! the contour of index IC.
Standard_EXPORT Standard_Real Abscissa (const Standard_Integer IC,
const TopoDS_Vertex& V) const;
//! returns the relative abscissa([0.,1.]) of the
//! vertex V on the contour of index IC.
Standard_EXPORT Standard_Real RelativeAbscissa (const Standard_Integer IC,
const TopoDS_Vertex& V) const;
//! returns true if the contour of index IC is closed
//! an tangent.
Standard_EXPORT Standard_Boolean ClosedAndTangent (const Standard_Integer IC) const;
//! returns true if the contour of index IC is closed
Standard_EXPORT Standard_Boolean Closed (const Standard_Integer IC) const;
//! general calculation of geometry on all edges,
//! topologic reconstruction.
Standard_EXPORT void Compute();
//! returns True if the computation is success
Standard_EXPORT Standard_Boolean IsDone() const;
//! if (Isdone()) makes the result.
//! if (!Isdone())
Standard_EXPORT TopoDS_Shape Shape() const;
//! Advanced function for the history
Standard_EXPORT const TopTools_ListOfShape& Generated (const TopoDS_Shape& EouV);
//! Returns the number of contours on which the calculation
//! has failed.
Standard_EXPORT Standard_Integer NbFaultyContours() const;
//! Returns the number of I'th contour on which the calculation
//! has failed.
Standard_EXPORT Standard_Integer FaultyContour (const Standard_Integer I) const;
//! Returns the number of surfaces calculated on the contour IC.
Standard_EXPORT Standard_Integer NbComputedSurfaces (const Standard_Integer IC) const;
//! Returns the IS'th surface calculated on the contour IC.
Standard_EXPORT Handle(Geom_Surface) ComputedSurface (const Standard_Integer IC,
const Standard_Integer IS) const;
//! Returns the number of vertices on which the calculation
//! has failed.
Standard_EXPORT Standard_Integer NbFaultyVertices() const;
//! Returns the IV'th vertex on which the calculation has failed.
Standard_EXPORT TopoDS_Vertex FaultyVertex (const Standard_Integer IV) const;
//! returns True if a partial result has been calculated
Standard_EXPORT Standard_Boolean HasResult() const;
//! if (HasResult()) returns partial result
//! if (!HasResult())
Standard_EXPORT TopoDS_Shape BadShape() const;
//! for the stripe IC ,indication on the cause
//! of failure WalkingFailure,TwistedSurface,Error, Ok
Standard_EXPORT ChFiDS_ErrorStatus StripeStatus (const Standard_Integer IC) const;
//! Reset all results of compute and returns the algorithm
//! in the state of the last acquisition to enable modification of contours or areas.
Standard_EXPORT void Reset();
//! Returns the Builder of topologic operations.
Standard_EXPORT Handle(TopOpeBRepBuild_HBuilder) Builder() const;
//! Method, implemented in the inheritants, calculates
//! the elements of construction of the surface (fillet or
//! chamfer).
Standard_EXPORT Standard_Boolean SplitKPart (const Handle(ChFiDS_SurfData)& Data,
ChFiDS_SequenceOfSurfData& SetData,
const Handle(ChFiDS_Spine)& Spine,
const Standard_Integer Iedge,
const Handle(Adaptor3d_Surface)& S1,
const Handle(Adaptor3d_TopolTool)& I1,
const Handle(Adaptor3d_Surface)& S2,
const Handle(Adaptor3d_TopolTool)& I2,
Standard_Boolean& Intf,
Standard_Boolean& Intl);
Standard_EXPORT Standard_Boolean PerformTwoCornerbyInter (const Standard_Integer Index);
protected:
Standard_EXPORT ChFi3d_Builder(const TopoDS_Shape& S, const Standard_Real Ta);
Standard_EXPORT virtual void SimulKPart (const Handle(ChFiDS_SurfData)& SD) const = 0;
Standard_EXPORT virtual Standard_Boolean SimulSurf (Handle(ChFiDS_SurfData)& Data,
const Handle(ChFiDS_ElSpine)& Guide,
const Handle(ChFiDS_Spine)& Spine,
const Standard_Integer Choix,
const Handle(BRepAdaptor_Surface)& S1,
const Handle(Adaptor3d_TopolTool)& I1,
const Handle(BRepAdaptor_Surface)& S2,
const Handle(Adaptor3d_TopolTool)& I2,
const Standard_Real TolGuide,
Standard_Real& First,
Standard_Real& Last,
const Standard_Boolean Inside,
const Standard_Boolean Appro,
const Standard_Boolean Forward,
const Standard_Boolean RecOnS1,
const Standard_Boolean RecOnS2,
const math_Vector& Soldep,
Standard_Integer& Intf,
Standard_Integer& Intl) = 0;
Standard_EXPORT virtual void SimulSurf (Handle(ChFiDS_SurfData)& Data,
const Handle(ChFiDS_ElSpine)& Guide,
const Handle(ChFiDS_Spine)& Spine,
const Standard_Integer Choix,
const Handle(BRepAdaptor_Surface)& S1,
const Handle(Adaptor3d_TopolTool)& I1,
const Handle(BRepAdaptor_Curve2d)& PC1,
const Handle(BRepAdaptor_Surface)& Sref1,
const Handle(BRepAdaptor_Curve2d)& PCref1,
Standard_Boolean& Decroch1,
const Handle(BRepAdaptor_Surface)& S2,
const Handle(Adaptor3d_TopolTool)& I2,
const TopAbs_Orientation Or2,
const Standard_Real Fleche,
const Standard_Real TolGuide,
Standard_Real& First,
Standard_Real& Last,
const Standard_Boolean Inside,
const Standard_Boolean Appro,
const Standard_Boolean Forward,
const Standard_Boolean RecP,
const Standard_Boolean RecS,
const Standard_Boolean RecRst,
const math_Vector& Soldep);
Standard_EXPORT virtual void SimulSurf (Handle(ChFiDS_SurfData)& Data,
const Handle(ChFiDS_ElSpine)& Guide,
const Handle(ChFiDS_Spine)& Spine,
const Standard_Integer Choix,
const Handle(BRepAdaptor_Surface)& S1,
const Handle(Adaptor3d_TopolTool)& I1,
const TopAbs_Orientation Or1,
const Handle(BRepAdaptor_Surface)& S2,
const Handle(Adaptor3d_TopolTool)& I2,
const Handle(BRepAdaptor_Curve2d)& PC2,
const Handle(BRepAdaptor_Surface)& Sref2,
const Handle(BRepAdaptor_Curve2d)& PCref2,
Standard_Boolean& Decroch2,
const Standard_Real Fleche,
const Standard_Real TolGuide,
Standard_Real& First,
Standard_Real& Last,
const Standard_Boolean Inside,
const Standard_Boolean Appro,
const Standard_Boolean Forward,
const Standard_Boolean RecP,
const Standard_Boolean RecS,
const Standard_Boolean RecRst,
const math_Vector& Soldep);
Standard_EXPORT virtual void SimulSurf (Handle(ChFiDS_SurfData)& Data,
const Handle(ChFiDS_ElSpine)& Guide,
const Handle(ChFiDS_Spine)& Spine,
const Standard_Integer Choix,
const Handle(BRepAdaptor_Surface)& S1,
const Handle(Adaptor3d_TopolTool)& I1,
const Handle(BRepAdaptor_Curve2d)& PC1,
const Handle(BRepAdaptor_Surface)& Sref1,
const Handle(BRepAdaptor_Curve2d)& PCref1,
Standard_Boolean& Decroch1,
const TopAbs_Orientation Or1,
const Handle(BRepAdaptor_Surface)& S2,
const Handle(Adaptor3d_TopolTool)& I2,
const Handle(BRepAdaptor_Curve2d)& PC2,
const Handle(BRepAdaptor_Surface)& Sref2,
const Handle(BRepAdaptor_Curve2d)& PCref2,
Standard_Boolean& Decroch2,
const TopAbs_Orientation Or2,
const Standard_Real Fleche,
const Standard_Real TolGuide,
Standard_Real& First,
Standard_Real& Last,
const Standard_Boolean Inside,
const Standard_Boolean Appro,
const Standard_Boolean Forward,
const Standard_Boolean RecP1,
const Standard_Boolean RecRst1,
const Standard_Boolean RecP2,
const Standard_Boolean RecRst2,
const math_Vector& Soldep);
Standard_EXPORT Standard_Boolean SimulData (Handle(ChFiDS_SurfData)& Data,
const Handle(ChFiDS_ElSpine)& Guide,
const Handle(ChFiDS_ElSpine)& AdditionalGuide,
Handle(BRepBlend_Line)& Lin,
const Handle(Adaptor3d_Surface)& S1,
const Handle(Adaptor3d_TopolTool)& I1,
const Handle(Adaptor3d_Surface)& S2,
const Handle(Adaptor3d_TopolTool)& I2,
Blend_Function& Func,
Blend_FuncInv& FInv,
const Standard_Real PFirst,
const Standard_Real MaxStep,
const Standard_Real Fleche,
const Standard_Real TolGuide,
Standard_Real& First,
Standard_Real& Last,
const Standard_Boolean Inside,
const Standard_Boolean Appro,
const Standard_Boolean Forward,
const math_Vector& Soldep,
const Standard_Integer NbSecMin,
const Standard_Boolean RecOnS1 = Standard_False,
const Standard_Boolean RecOnS2 = Standard_False);
Standard_EXPORT Standard_Boolean SimulData (Handle(ChFiDS_SurfData)& Data,
const Handle(ChFiDS_ElSpine)& HGuide,
Handle(BRepBlend_Line)& Lin,
const Handle(Adaptor3d_Surface)& S1,
const Handle(Adaptor3d_TopolTool)& I1,
const Handle(Adaptor3d_Surface)& S2,
const Handle(Adaptor2d_Curve2d)& PC2,
const Handle(Adaptor3d_TopolTool)& I2,
Standard_Boolean& Decroch,
Blend_SurfRstFunction& Func,
Blend_FuncInv& FInv,
Blend_SurfPointFuncInv& FInvP,
Blend_SurfCurvFuncInv& FInvC,
const Standard_Real PFirst,
const Standard_Real MaxStep,
const Standard_Real Fleche,
const Standard_Real TolGuide,
Standard_Real& First,
Standard_Real& Last,
const math_Vector& Soldep,
const Standard_Integer NbSecMin,
const Standard_Boolean Inside,
const Standard_Boolean Appro,
const Standard_Boolean Forward,
const Standard_Boolean RecP,
const Standard_Boolean RecS,
const Standard_Boolean RecRst);
Standard_EXPORT Standard_Boolean SimulData (Handle(ChFiDS_SurfData)& Data,
const Handle(ChFiDS_ElSpine)& HGuide,
Handle(BRepBlend_Line)& Lin,
const Handle(Adaptor3d_Surface)& S1,
const Handle(Adaptor2d_Curve2d)& PC1,
const Handle(Adaptor3d_TopolTool)& I1,
Standard_Boolean& Decroch1,
const Handle(Adaptor3d_Surface)& S2,
const Handle(Adaptor2d_Curve2d)& PC2,
const Handle(Adaptor3d_TopolTool)& I2,
Standard_Boolean& Decroch2,
Blend_RstRstFunction& Func,
Blend_SurfCurvFuncInv& FInv1,
Blend_CurvPointFuncInv& FInvP1,
Blend_SurfCurvFuncInv& FInv2,
Blend_CurvPointFuncInv& FInvP2,
const Standard_Real PFirst,
const Standard_Real MaxStep,
const Standard_Real Fleche,
const Standard_Real TolGuide,
Standard_Real& First,
Standard_Real& Last,
const math_Vector& Soldep,
const Standard_Integer NbSecMin,
const Standard_Boolean Inside,
const Standard_Boolean Appro,
const Standard_Boolean Forward,
const Standard_Boolean RecP1,
const Standard_Boolean RecRst1,
const Standard_Boolean RecP2,
const Standard_Boolean RecRst2);
Standard_EXPORT virtual void SetRegul() = 0;
Standard_EXPORT Standard_Boolean PerformElement (const Handle(ChFiDS_Spine)& CElement,
const Standard_Real Offset,
const TopoDS_Face& theFirstFace);
Standard_EXPORT void PerformExtremity (const Handle(ChFiDS_Spine)& CElement);
Standard_EXPORT void PerformSetOfSurf (Handle(ChFiDS_Stripe)& S,
const Standard_Boolean Simul = Standard_False);
Standard_EXPORT void PerformSetOfKPart (Handle(ChFiDS_Stripe)& S,
const Standard_Boolean Simul = Standard_False);
Standard_EXPORT void PerformSetOfKGen (Handle(ChFiDS_Stripe)& S,
const Standard_Boolean Simul = Standard_False);
Standard_EXPORT void Trunc (const Handle(ChFiDS_SurfData)& SD,
const Handle(ChFiDS_Spine)& Spine,
const Handle(Adaptor3d_Surface)& S1,
const Handle(Adaptor3d_Surface)& S2,
const Standard_Integer iedge,
const Standard_Boolean isfirst,
const Standard_Integer cntlFiOnS);
Standard_EXPORT void CallPerformSurf (Handle(ChFiDS_Stripe)& Stripe,
const Standard_Boolean Simul,
ChFiDS_SequenceOfSurfData& SeqSD,
Handle(ChFiDS_SurfData)& SD,
const Handle(ChFiDS_ElSpine)& Guide,
const Handle(ChFiDS_Spine)& Spine,
const Handle(BRepAdaptor_Surface)& HS1,
const Handle(BRepAdaptor_Surface)& HS3,
const gp_Pnt2d& P1,
const gp_Pnt2d& P3,
const Handle(Adaptor3d_TopolTool)& I1,
const Handle(BRepAdaptor_Surface)& HS2,
const Handle(BRepAdaptor_Surface)& HS4,
const gp_Pnt2d& P2, const gp_Pnt2d& P4,
const Handle(Adaptor3d_TopolTool)& I2,
const Standard_Real MaxStep,
const Standard_Real Fleche,
const Standard_Real TolGuide,
Standard_Real& First,
Standard_Real& Last,
const Standard_Boolean Inside,
const Standard_Boolean Appro,
const Standard_Boolean Forward,
const Standard_Boolean RecOnS1,
const Standard_Boolean RecOnS2,
math_Vector& Soldep,
Standard_Integer& Intf,
Standard_Integer& Intl,
Handle(BRepAdaptor_Surface)& Surf1,
Handle(BRepAdaptor_Surface)& Surf2);
//! Method, implemented in the inheritants, calculating
//! elements of construction of the surface (fillet or
//! chamfer).
Standard_EXPORT virtual Standard_Boolean PerformSurf (ChFiDS_SequenceOfSurfData& Data,
const Handle(ChFiDS_ElSpine)& Guide,
const Handle(ChFiDS_Spine)& Spine,
const Standard_Integer Choix,
const Handle(BRepAdaptor_Surface)& S1,
const Handle(Adaptor3d_TopolTool)& I1,
const Handle(BRepAdaptor_Surface)& S2,
const Handle(Adaptor3d_TopolTool)& I2,
const Standard_Real MaxStep,
const Standard_Real Fleche,
const Standard_Real TolGuide,
Standard_Real& First,
Standard_Real& Last,
const Standard_Boolean Inside,
const Standard_Boolean Appro,
const Standard_Boolean Forward,
const Standard_Boolean RecOnS1,
const Standard_Boolean RecOnS2,
const math_Vector& Soldep,
Standard_Integer& Intf,
Standard_Integer& Intl) = 0;
//! Method, implemented in inheritants, calculates
//! the elements of construction of the surface (fillet
//! or chamfer) contact edge/face.
Standard_EXPORT virtual void PerformSurf (ChFiDS_SequenceOfSurfData& Data,
const Handle(ChFiDS_ElSpine)& Guide,
const Handle(ChFiDS_Spine)& Spine,
const Standard_Integer Choix,
const Handle(BRepAdaptor_Surface)& S1,
const Handle(Adaptor3d_TopolTool)& I1,
const Handle(BRepAdaptor_Curve2d)& PC1,
const Handle(BRepAdaptor_Surface)& Sref1,
const Handle(BRepAdaptor_Curve2d)& PCref1,
Standard_Boolean& Decroch1,
const Handle(BRepAdaptor_Surface)& S2,
const Handle(Adaptor3d_TopolTool)& I2,
const TopAbs_Orientation Or2,
const Standard_Real MaxStep,
const Standard_Real Fleche,
const Standard_Real TolGuide,
Standard_Real& First,
Standard_Real& Last,
const Standard_Boolean Inside,
const Standard_Boolean Appro,
const Standard_Boolean Forward,
const Standard_Boolean RecP,
const Standard_Boolean RecS,
const Standard_Boolean RecRst,
const math_Vector& Soldep);
//! Method, implemented in inheritants, calculates
//! the elements of construction of the surface (fillet
//! or chamfer) contact edge/face.
Standard_EXPORT virtual void PerformSurf (ChFiDS_SequenceOfSurfData& Data,
const Handle(ChFiDS_ElSpine)& Guide,
const Handle(ChFiDS_Spine)& Spine,
const Standard_Integer Choix,
const Handle(BRepAdaptor_Surface)& S1,
const Handle(Adaptor3d_TopolTool)& I1,
const TopAbs_Orientation Or1,
const Handle(BRepAdaptor_Surface)& S2,
const Handle(Adaptor3d_TopolTool)& I2,
const Handle(BRepAdaptor_Curve2d)& PC2,
const Handle(BRepAdaptor_Surface)& Sref2,
const Handle(BRepAdaptor_Curve2d)& PCref2,
Standard_Boolean& Decroch2,
const Standard_Real MaxStep,
const Standard_Real Fleche,
const Standard_Real TolGuide,
Standard_Real& First,
Standard_Real& Last,
const Standard_Boolean Inside,
const Standard_Boolean Appro,
const Standard_Boolean Forward,
const Standard_Boolean RecP,
const Standard_Boolean RecS,
const Standard_Boolean RecRst,
const math_Vector& Soldep);
//! Method, implemented in inheritants, calculates
//! the elements of construction of the surface (fillet
//! or chamfer) contact edge/edge.
Standard_EXPORT virtual void PerformSurf (ChFiDS_SequenceOfSurfData& Data,
const Handle(ChFiDS_ElSpine)& Guide,
const Handle(ChFiDS_Spine)& Spine,
const Standard_Integer Choix,
const Handle(BRepAdaptor_Surface)& S1,
const Handle(Adaptor3d_TopolTool)& I1,
const Handle(BRepAdaptor_Curve2d)& PC1,
const Handle(BRepAdaptor_Surface)& Sref1,
const Handle(BRepAdaptor_Curve2d)& PCref1,
Standard_Boolean& Decroch1,
const TopAbs_Orientation Or1,
const Handle(BRepAdaptor_Surface)& S2,
const Handle(Adaptor3d_TopolTool)& I2,
const Handle(BRepAdaptor_Curve2d)& PC2,
const Handle(BRepAdaptor_Surface)& Sref2,
const Handle(BRepAdaptor_Curve2d)& PCref2,
Standard_Boolean& Decroch2,
const TopAbs_Orientation Or2,
const Standard_Real MaxStep,
const Standard_Real Fleche,
const Standard_Real TolGuide,
Standard_Real& First,
Standard_Real& Last,
const Standard_Boolean Inside,
const Standard_Boolean Appro,
const Standard_Boolean Forward,
const Standard_Boolean RecP1,
const Standard_Boolean RecRst1,
const Standard_Boolean RecP2,
const Standard_Boolean RecRst2,
const math_Vector& Soldep);
Standard_EXPORT virtual void PerformTwoCorner (const Standard_Integer Index) = 0;
Standard_EXPORT virtual void PerformThreeCorner (const Standard_Integer Index) = 0;
Standard_EXPORT void PerformMoreThreeCorner (const Standard_Integer Index,
const Standard_Integer nbcourb);
Standard_EXPORT virtual void ExtentOneCorner (const TopoDS_Vertex& V,
const Handle(ChFiDS_Stripe)& S) = 0;
Standard_EXPORT virtual void ExtentTwoCorner (const TopoDS_Vertex& V,
const ChFiDS_ListOfStripe& LS) = 0;
Standard_EXPORT virtual void ExtentThreeCorner (const TopoDS_Vertex& V,
const ChFiDS_ListOfStripe& LS) = 0;
Standard_EXPORT virtual Standard_Boolean PerformFirstSection (const Handle(ChFiDS_Spine)& S,
const Handle(ChFiDS_ElSpine)& HGuide,
const Standard_Integer Choix,
Handle(BRepAdaptor_Surface)& S1,
Handle(BRepAdaptor_Surface)& S2,
const Handle(Adaptor3d_TopolTool)& I1,
const Handle(Adaptor3d_TopolTool)& I2,
const Standard_Real Par,
math_Vector& SolDep,
TopAbs_State& Pos1,
TopAbs_State& Pos2) const = 0;
Standard_EXPORT Standard_Boolean SearchFace (const Handle(ChFiDS_Spine)& Sp,
const ChFiDS_CommonPoint& Pc,
const TopoDS_Face& FRef,
TopoDS_Face& FVoi) const;
Standard_EXPORT Standard_Boolean StripeOrientations (const Handle(ChFiDS_Spine)& Sp,
TopAbs_Orientation& Or1,
TopAbs_Orientation& Or2,
Standard_Integer& ChoixConge) const;
//! Calculates a Line of contact face/face.
Standard_EXPORT Standard_Boolean ComputeData (Handle(ChFiDS_SurfData)& Data,
const Handle(ChFiDS_ElSpine)& Guide,
const Handle(ChFiDS_Spine)& Spine,
Handle(BRepBlend_Line)& Lin,
const Handle(Adaptor3d_Surface)& S1,
const Handle(Adaptor3d_TopolTool)& I1,
const Handle(Adaptor3d_Surface)& S2,
const Handle(Adaptor3d_TopolTool)& I2,
Blend_Function& Func,
Blend_FuncInv& FInv,
const Standard_Real PFirst,
const Standard_Real MaxStep,
const Standard_Real Fleche,
const Standard_Real TolGuide,
Standard_Real& First,
Standard_Real& Last,
const Standard_Boolean Inside,
const Standard_Boolean Appro,
const Standard_Boolean Forward,
const math_Vector& Soldep,
Standard_Integer& Intf,
Standard_Integer& Intl,
Standard_Boolean& Gd1,
Standard_Boolean& Gd2,
Standard_Boolean& Gf1,
Standard_Boolean& Gf2,
const Standard_Boolean RecOnS1 = Standard_False,
const Standard_Boolean RecOnS2 = Standard_False);
//! Calculates a Line of contact edge/face.
Standard_EXPORT Standard_Boolean ComputeData (Handle(ChFiDS_SurfData)& Data,
const Handle(ChFiDS_ElSpine)& HGuide,
Handle(BRepBlend_Line)& Lin,
const Handle(Adaptor3d_Surface)& S1,
const Handle(Adaptor3d_TopolTool)& I1,
const Handle(Adaptor3d_Surface)& S2,
const Handle(Adaptor2d_Curve2d)& PC2,
const Handle(Adaptor3d_TopolTool)& I2,
Standard_Boolean& Decroch,
Blend_SurfRstFunction& Func,
Blend_FuncInv& FInv,
Blend_SurfPointFuncInv& FInvP,
Blend_SurfCurvFuncInv& FInvC,
const Standard_Real PFirst,
const Standard_Real MaxStep,
const Standard_Real Fleche,
const Standard_Real TolGuide,
Standard_Real& First,
Standard_Real& Last,
const math_Vector& Soldep,
const Standard_Boolean Inside,
const Standard_Boolean Appro,
const Standard_Boolean Forward,
const Standard_Boolean RecP,
const Standard_Boolean RecS,
const Standard_Boolean RecRst);
//! Calculates a Line of contact edge/edge.
Standard_EXPORT Standard_Boolean ComputeData (Handle(ChFiDS_SurfData)& Data,
const Handle(ChFiDS_ElSpine)& HGuide,
Handle(BRepBlend_Line)& Lin,
const Handle(Adaptor3d_Surface)& S1,
const Handle(Adaptor2d_Curve2d)& PC1,
const Handle(Adaptor3d_TopolTool)& I1,
Standard_Boolean& Decroch1,
const Handle(Adaptor3d_Surface)& S2,
const Handle(Adaptor2d_Curve2d)& PC2,
const Handle(Adaptor3d_TopolTool)& I2,
Standard_Boolean& Decroch2,
Blend_RstRstFunction& Func,
Blend_SurfCurvFuncInv& FInv1,
Blend_CurvPointFuncInv& FInvP1,
Blend_SurfCurvFuncInv& FInv2,
Blend_CurvPointFuncInv& FInvP2,
const Standard_Real PFirst,
const Standard_Real MaxStep,
const Standard_Real Fleche,
const Standard_Real TolGuide,
Standard_Real& First,
Standard_Real& Last,
const math_Vector& Soldep,
const Standard_Boolean Inside,
const Standard_Boolean Appro,
const Standard_Boolean Forward,
const Standard_Boolean RecP1,
const Standard_Boolean RecRst1,
const Standard_Boolean RecP2,
const Standard_Boolean RecRst2);
Standard_EXPORT Standard_Boolean CompleteData (Handle(ChFiDS_SurfData)& Data,
Blend_Function& Func,
Handle(BRepBlend_Line)& Lin,
const Handle(Adaptor3d_Surface)& S1,
const Handle(Adaptor3d_Surface)& S2,
const TopAbs_Orientation Or1,
const Standard_Boolean Gd1,
const Standard_Boolean Gd2,
const Standard_Boolean Gf1,
const Standard_Boolean Gf2,
const Standard_Boolean Reversed = Standard_False);
Standard_EXPORT Standard_Boolean CompleteData (Handle(ChFiDS_SurfData)& Data,
Blend_SurfRstFunction& Func,
Handle(BRepBlend_Line)& Lin,
const Handle(Adaptor3d_Surface)& S1,
const Handle(Adaptor3d_Surface)& S2,
const TopAbs_Orientation Or,
const Standard_Boolean Reversed);
Standard_EXPORT Standard_Boolean CompleteData (Handle(ChFiDS_SurfData)& Data,
Blend_RstRstFunction& Func,
Handle(BRepBlend_Line)& Lin,
const Handle(Adaptor3d_Surface)& S1,
const Handle(Adaptor3d_Surface)& S2,
const TopAbs_Orientation Or);
Standard_EXPORT Standard_Boolean StoreData (Handle(ChFiDS_SurfData)& Data,
const AppBlend_Approx& Approx,
const Handle(BRepBlend_Line)& Lin,
const Handle(Adaptor3d_Surface)& S1,
const Handle(Adaptor3d_Surface)& S2,
const TopAbs_Orientation Or1,
const Standard_Boolean Gd1,
const Standard_Boolean Gd2,
const Standard_Boolean Gf1,
const Standard_Boolean Gf2,
const Standard_Boolean Reversed = Standard_False);
Standard_EXPORT Standard_Boolean CompleteData (Handle(ChFiDS_SurfData)& Data,
const Handle(Geom_Surface)& Surfcoin,
const Handle(Adaptor3d_Surface)& S1,
const Handle(Geom2d_Curve)& PC1,
const Handle(Adaptor3d_Surface)& S2,
const Handle(Geom2d_Curve)& PC2,
const TopAbs_Orientation Or,
const Standard_Boolean On1,
const Standard_Boolean Gd1,
const Standard_Boolean Gd2,
const Standard_Boolean Gf1,
const Standard_Boolean Gf2);
Standard_Real tolappangle;
Standard_Real tolesp;
Standard_Real tol2d;
Standard_Real tolapp3d;
Standard_Real tolapp2d;
Standard_Real fleche;
GeomAbs_Shape myConti;
ChFiDS_Map myEFMap;
ChFiDS_Map myESoMap;
ChFiDS_Map myEShMap;
ChFiDS_Map myVFMap;
ChFiDS_Map myVEMap;
Handle(TopOpeBRepDS_HDataStructure) myDS;
Handle(TopOpeBRepBuild_HBuilder) myCoup;
ChFiDS_ListOfStripe myListStripe;
ChFiDS_StripeMap myVDataMap;
ChFiDS_Regularities myRegul;
ChFiDS_ListOfStripe badstripes;
TopTools_ListOfShape badvertices;
TopTools_DataMapOfShapeListOfInteger myEVIMap;
TopTools_DataMapOfShapeShape myEdgeFirstFace;
Standard_Boolean done;
Standard_Boolean hasresult;
private:
Standard_EXPORT Standard_Boolean FaceTangency (const TopoDS_Edge& E0,
const TopoDS_Edge& E1,
const TopoDS_Vertex& V) const;
Standard_EXPORT void PerformSetOfSurfOnElSpine (const Handle(ChFiDS_ElSpine)& ES,
Handle(ChFiDS_Stripe)& St,
Handle(BRepTopAdaptor_TopolTool)& It1,
Handle(BRepTopAdaptor_TopolTool)& It2,
const Standard_Boolean Simul = Standard_False);
Standard_EXPORT void PerformFilletOnVertex (const Standard_Integer Index);
Standard_EXPORT void PerformSingularCorner (const Standard_Integer Index);
Standard_EXPORT void PerformOneCorner (const Standard_Integer Index,
const Standard_Boolean PrepareOnSame = Standard_False);
Standard_EXPORT void IntersectMoreCorner (const Standard_Integer Index);
Standard_EXPORT void PerformMoreSurfdata (const Standard_Integer Index);
Standard_EXPORT void PerformIntersectionAtEnd (const Standard_Integer Index);
Standard_EXPORT void ExtentAnalyse();
Standard_EXPORT Standard_Boolean FindFace (const TopoDS_Vertex& V,
const ChFiDS_CommonPoint& P1,
const ChFiDS_CommonPoint& P2,
TopoDS_Face& Fv) const;
Standard_EXPORT Standard_Boolean FindFace (const TopoDS_Vertex& V,
const ChFiDS_CommonPoint& P1,
const ChFiDS_CommonPoint& P2,
TopoDS_Face& Fv,
const TopoDS_Face& Favoid) const;
Standard_EXPORT Standard_Boolean MoreSurfdata (const Standard_Integer Index) const;
Standard_EXPORT Standard_Boolean StartSol (const Handle(ChFiDS_Spine)& Spine,
Handle(BRepAdaptor_Surface)& HS,
gp_Pnt2d& P,
Handle(BRepAdaptor_Curve2d)& HC,
Standard_Real& W,
const Handle(ChFiDS_SurfData)& SD,
const Standard_Boolean isFirst,
const Standard_Integer OnS,
Handle(BRepAdaptor_Surface)& HSref,
Handle(BRepAdaptor_Curve2d)& HCref,
Standard_Boolean& RecP,
Standard_Boolean& RecS,
Standard_Boolean& RecRst,
Standard_Boolean& C1Obst,
Handle(BRepAdaptor_Surface)& HSbis,
gp_Pnt2d& Pbis,
const Standard_Boolean Decroch,
const TopoDS_Vertex& Vref) const;
Standard_EXPORT void StartSol (const Handle(ChFiDS_Stripe)& S,
const Handle(ChFiDS_ElSpine)& HGuide,
Handle(BRepAdaptor_Surface)& HS1,
Handle(BRepAdaptor_Surface)& HS2,
Handle(BRepTopAdaptor_TopolTool)& I1,
Handle(BRepTopAdaptor_TopolTool)& I2,
gp_Pnt2d& P1,
gp_Pnt2d& P2,
Standard_Real& First) const;
Standard_EXPORT void ConexFaces (const Handle(ChFiDS_Spine)& Sp,
const Standard_Integer IEdge,
Handle(BRepAdaptor_Surface)& HS1,
Handle(BRepAdaptor_Surface)& HS2) const;
//! Assign to tolesp parameter minimal value of spine's tolesp if it is less
//! than default initial value.
Standard_EXPORT void UpdateTolesp();
TopoDS_Shape myShape;
Standard_Real angular;
TopTools_ListOfShape myGenerated;
TopoDS_Shape myShapeResult;
TopoDS_Shape badShape;
};
#endif // _ChFi3d_Builder_HeaderFile
|
#pragma once
#include "Vectors.h"
#include <windows.h>
#include <gl\gl.h>
#include <gl\glu.h>
#include "Texgen.h"
#include "includelist.h"
#include "Splines.h"
#include "ParticleEngine.h"
#define aDDict_DEFAULTSHADE 0
#define aDDict_FLATSHADE 1
#define aDDict_GOURAUDSHADE 2
#define aDDict_SCALE 0
#define aDDict_ROTATE 1
#define aDDict_MOVE 2
#define aDDict_DUMMY 0
#define aDDict_SCENE 1
#define aDDict_SUBSCENE 2
#define aDDict_SPHEREEMITTER 3
#define aDDict_CUBEEMITTER 4
#define aDDict_CYLINDEREMITTER 5
#define aDDict_PLANEDEFLECTOR 6
#define aDDict_SPHEREDEFLECTOR 7
#define aDDict_GRAVITY 8
#define radtheta 3.1415f/180.0f
struct SUPERSHAPEARC
{
unsigned char mint,mfloat;
float n1,n2,n3,a,b;
};
struct SUPERSHAPE
{
SUPERSHAPEARC SuperShape1,SuperShape2;
unsigned char Sphere; //sphere or toroid?
float Trad0,TradPhi; //toroid data
unsigned char RadFunc; //radial function
float Rada,Radb; //radial function variables
unsigned char VertFunc; //vertical function
float Verta; //vertical function variable
int Rangex1,Rangex2,Rangey1,Rangey2; //range variables
unsigned char Xres,Yres; //resolution
};
struct CAMERA
{
VECTOR3 Eye,Target,Up;
float Roll,Fov;
VECTOR3 i,j,Normal;
float d;
};
struct EDGE
{
int v1,v2; //vertices on the ends of edge
int p1,p2; //polygons on the side of edge
bool selected; //needed variable for calculations
bool InWireframe;
};
struct VERTEX
{
VECTOR3 Position,MapTransformedPosition;
VECTOR3 Normal,CurrentNormal;
VECTOR2 TextureCoordinate,CurrentTextureCoordinate;
int *EdgeList; //connected edges
int EdgeNum,EdgeCapacity;
float Weight[4];
bool Selected;
int SelectCount;
int PolyCount;
};
struct POLYGON
{
int v[3]; //vertices
int e[3]; //edges
VECTOR2 t[3],ct[3];
GLuint Material;
VECTOR3 Normal,CurrentNormal;
unsigned char Shading,CurrentShading;
bool Selected,Highlighted;
};
class OBJECT
{
public:
int ID;
unsigned char Primitive;
int Param1,Param2,Param3,Param4,Param5;
VERTEX *VertexList;
int VertexNum,VertexCapacity;
POLYGON *PolygonList;
int PolygonNum,PolygonCapacity;
EDGE *EdgeList;
int EdgeNum,EdgeCapacity;
GLuint DisplayList;
GLuint WireDisplayList;
GLuint SRCBlend,DSTBlend;
bool Wireframe;
int Shading;
MATRIX ModelView,TransformBuffer,Inverted,IT;
int NewVertexNum;
VECTOR3 *NewVertices;
VECTOR3 *NewNormals;
VECTOR2 *NewTexCoords;
int *NewIndices;
void OptimizeForVBO();
void AddVertex(float x, float y, float z, float u, float v);
void AddPolygon(int x, int y, int z, bool e1, bool e2, bool e3);
void AddPolygon(int x, int y, int z, char Shading, bool e1, bool e2, bool e3);
void AddPolygon(int x, int y, int z, float t1x, float t1y, float t2x, float t2y, float t3x, float t3y, bool e1, bool e2, bool e3);
void AddPolygon(int x, int y, int z, char Shading, float t1x, float t1y, float t2x, float t2y, float t3x, float t3y, bool e1, bool e2, bool e3);
int AddEdge(int a, int b, int p, bool InWireframe);
void CalculateTextureCoordinates();
void CalculateNormals();
#ifdef INCLUDE_MESHSMOOTH
void MeshSmooth(bool Linear);
void SortVertexEdges();
void TessellateEdges(int *, bool);
void BuildNewFaces(int *, bool);
#endif
#ifdef INCLUDE_OBJ_MESHBLUR
void MeshBlur();
#endif
bool Textured;
MATERIAL *Material;
bool EnvMapped;
MATERIAL *EnvMap;
bool NormalsInverted;
unsigned char Xtile,Ytile;
bool XSwap,YSwap,Swap;
float OffsetX,OffsetY;
RGBA Color;
bool ZMask,Backface,Backfront;
unsigned char AEpsilon;
char MapXformType;
char MapXformColor;
int TargetObjectID;
};
struct LIGHT
{
GLint Identifier;
bool Lit;
GLfloat Ambient[4];
GLfloat Color[4];
GLfloat Position[4];
GLfloat Spot_Direction[4];
GLfloat Spot_Exponent;
GLfloat Spot_Cutoff;
GLfloat Constant_Attenuation,Linear_Attenuation,Quadratic_Attenuation;
bool CastShadow;
};
struct WORLDOBJECT;
struct OBJDUMMY
{
OBJECT *OriginalObj; //material datanak stb
WORLDOBJECT *OriginalWorldObj; //world-be hogy beazonositsa a hozza tartozo matrixot a rendernel
GLuint List; //display list
bool Envmap;
MATRIX ModelView;
};
class SCENE
{
public:
int ID;
bool ColorDiscard;
OBJECT *ObjectList;
int ObjectNum,ObjectCapacity;
GLuint ZmaskList,NoZmaskList;
//void AddObject();
OBJECT *FindObjectByID(int ID);
int FindObjectIndex(int ID);
int CountObjects();
void SetupDummies();
void CalculateDummy(OBJECT *Object, int &DummyNum, MATRIX *Position);
int ObjDummyCount;
OBJDUMMY *ObjDummies;
};
class DEFAULTOBJECTSPLINES
{
public:
SPLINE *Posx,*Posy,*Posz;
SPLINE *Rotx,*Roty,*Rotz,*Rotw;
SPLINE *Sclx,*Scly,*Sclz;
SPLINE *AnimID; //Sub-World animacio ID
SPLINE *AnimTime; //Sub-Worldokhoz
SPLINE *Red,*Green,*Blue,*Alpha,*Size,*Prtfrme;
};
struct LIGHTSPLINES
{
SPLINE *Lit;
SPLINE *Red,*Green,*Blue;
SPLINE *ARed,*AGreen,*ABlue;
};
struct CAMSPLINES
{
int CamID;
SPLINE *Eyex,*Eyey,*Eyez;
SPLINE *Trgx,*Trgy,*Trgz;
SPLINE *Fov,*Roll;
};
struct ANIMDATA
{
int AnimID;
LIGHTSPLINES *Lights;
};
struct ANIMPOS
{
int AnimID;
float AnimPos;
};
struct EMITTERDATA;
struct WORLDOBJECT
{
int ID;
int ParentID;
void *Data;
int Primitive;
MATRIX ModelView,TransformBuffer,Inverted,IT;
//RST Position;
EMITTERDATA *EmitterData;
GLuint SRCBlend,DSTBlend;
bool Textured,ZMask;
MATERIAL *Material;
DEFAULTOBJECTSPLINES *Animations;
int AnimNum;
int AnimCapacity;
RST PosData;
ANIMPOS APosData;
RGBA Color;
WORLDOBJECT *Parent;
unsigned char AEpsilon;
int TargetID;
};
class WORLD
{
public:
int ID;
WORLDOBJECT *ObjectList;
int ObjectNum,ObjectCapacity;
int ObjectCount,ParticleCount,SubWorldCount;
bool Lighting;
LIGHT Lights[8];
CAMERA Camera;
bool Fog;
unsigned char FogCol[4];
float FogStart,FogEnd;
int AnimNum;
int AnimCapacity;
ANIMDATA *Animations;
CAMSPLINES *CamAnims;
int CamNum;
int CamCapacity;
//void AddObject();
void SetupLighting();
//void RenderWireFrame(VECTOR3 v);
void Render(bool SubWorld, bool ZMask);
#ifdef INCLUDE_PARTICLE_ENGINE
void RenderParticles(CAMERA *Cam, int ActualAnim, MATRIX *WorldData);
void RenderParticleTree(CAMERA *Cam, int ActualAnim, MATRIX *WorldData);
void CalculateParticles(int CurrentFrame);
//void AddAnimation();
//void AddCamera();
void CalculateParticleObjectMatrices();
#endif
void CalculateObjectMatrices();
void SetToAnimPos(ANIMPOS *a);
WORLDOBJECT *FindObjectByID(int ID);
/*int ObjDummyCount;
OBJDUMMY *ObjDummies;
int CountObjects();
void SetupDummies();*/
};
struct PVSelect
{
int ID;
int Brush;
int Operator;
int Param1;
int Param2;
int Param3;
};
struct PSelect
{
int BrushNum;
PVSelect *Brushes;
};
void Obj_DoPolySelection(OBJECT *o,PVSelect *SelectData, bool HighLight);
void SelectObjPolys(OBJECT *o, PVSelect *i, int num);
//void SelectObjVertices(OBJECT *o,PVSelect *i, int num, bool Border);
void SelectObjVertices(OBJECT *o,PVSelect *i,int BrushNum, int num, bool Border);
#ifdef INCLUDE_OBJ_MAPXFORM
void CalculateObjectVertexWeights(OBJECT *o, MATERIAL *m, int XTile, int YTile, bool XSwap, bool YSwap, bool Swap, float XOffset, float YOffset);
#endif
void Spline_Slerp(SPLINE *s,SPLINE *x,SPLINE *y,SPLINE *z, float *a, float *b, float *c, float *d, float Time);
void Spline_QuaternionGetVectors(SPLINE *s,SPLINE *x,SPLINE *y,SPLINE *z);
void MultModelViewMatrix(MATRIX m);
void SetCameraView(CAMERA *Cam, float AspectRatio);
void SetModelViewMatrix(MATRIX m);
#ifdef INCLUDE_PARTICLE_ENGINE
extern int MaxParticleNum;
void InitParticleIndexBuffer();
#endif
#ifdef INCLUDE_OBJ_BUTTERFLYSMOOTH
void initVertexBlend();
#endif
|
#pragma once
#include <iostream>
#include <vector>
#include <functional>
namespace fsm {
/**
* @brief Class for state machine.
*
* @tparam Enum A enum class of states
*/
template <typename Enum>
class state_machine
{
public: template<class F, class...Args>
static auto guard(F&& f, Args&&... args) -> std::function<bool()>
{
return std::bind(f, args...);
}
public: template<class F, class...Args>
static auto event(F&& f, Args&&... args) -> std::function<void()>
{
return std::bind(f, args...);
}
public: struct state
{
using event_type = std::function<void()>;
using guard_type = std::function<bool()>;
Enum current_state;
Enum next_state;
// This function is called when the state is entered
event_type event;
// conditional guard requirement which must be satisfied to visit state
guard_type guard;
state(Enum current_state, Enum next_state)
: current_state(current_state)
, next_state(next_state) {}
state(Enum current_state, Enum next_state, event_type event)
: current_state(current_state)
, next_state(next_state)
, event(event) {}
state(Enum current_state, Enum next_state, guard_type guard)
: current_state(current_state)
, next_state(next_state)
, guard(guard) {}
state(Enum current_state, Enum next_state,
guard_type guard,
event_type event)
: current_state(current_state)
, next_state(next_state)
, guard(guard)
, event(event) {}
state(Enum current_state, Enum next_state,
event_type event,
guard_type guard)
: current_state(current_state)
, next_state(next_state)
, event(event)
, guard(guard) {}
};
private: std::vector<state> transition_matrix_;
private: Enum current_state_;
public: state_machine
( Enum initial_state,
std::vector<state> transition_matrix
)
: transition_matrix_(transition_matrix)
, current_state_(initial_state)
{};
/**
* Attempts to move state machine onto next state if applicable
*/
public: void next()
{
std::cout << "next()\n";
std::vector<state> valid_next_states;
std::copy_if(
transition_matrix_.begin(),
transition_matrix_.end(),
std::back_inserter(valid_next_states),
std::bind(
&state_machine::guard_satisfied,
this,
std::placeholders::_1));
if (valid_next_states.size() == 1)
{
transition(valid_next_states[0]);
}
else if (valid_next_states.size() > 1)
{
// uh oh, non-determinism found.
std::cout << "Non-deterministic state machine.\n";
}
}
/**
* Checks to see if state can be entered
* @param state a given state in the transition matrix
* @return true if state can be entered
*/
private: bool guard_satisfied(const state state)
{
return (state.current_state == current_state_ &&
state.guard() == true);
}
private: void transition(const state state)
{
std::cout << "transition()\n";
state.event();
current_state_ = state.next_state;
std::cout
<< static_cast<std::uint32_t>(state.current_state)
<< " -> "
<< static_cast<std::uint32_t>(state.next_state)
<< "\n";
}
};
}
|
/*
cheali-charger - open source firmware for a variety of LiPo chargers
Copyright (C) 2013 Paweł Stawicki. All right reserved.
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#include "Options.h"
#include "LcdPrint.h"
#include "StaticMenu.h"
#include "SMPS.h"
#include "Utils.h"
#include "Calibrate.h"
#include "Screen.h"
#include "Version.h"
#include "Settings.h"
#include "ProgramData.h"
#include "eeprom.h"
using namespace options;
const char * const optionsStaticMenu[] PROGMEM = {
string_settings,
string_calibrate,
#ifdef ENABLE_EEPROM_RESTORE_DEFAULT
string_resetDefault,
#endif
NULL
};
void Options::resetDefault()
{
eeprom::restoreDefault();
}
void Options::run()
{
StaticMenu optionsMenu(optionsStaticMenu);
int8_t i;
do {
i = optionsMenu.runSimple();
START_CASE_COUNTER;
switch(i) {
case NEXT_CASE: settings.edit(); break;
#ifdef ENABLE_CALIBRATION
case NEXT_CASE: Calibrate::run(); break;
#endif
#ifdef ENABLE_EEPROM_RESTORE_DEFAULT
case NEXT_CASE: resetDefault(); break;
#endif
}
} while(i>=0);
}
|
// Copyright (c) 2012-2017 The Cryptonote developers
// Copyright (c) 2018-2023 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.
#pragma once
#include "INode.h"
#include <mutex>
#include <condition_variable>
namespace cn {
template <typename T>
class ObservableValue {
public:
ObservableValue(const T defaultValue = 0) :
m_prev(defaultValue), m_value(defaultValue) {
}
void init(T value) {
std::lock_guard<std::mutex> lk(m_mutex);
m_value = m_prev = value;
}
void set(T value) {
std::lock_guard<std::mutex> lk(m_mutex);
m_value = value;
m_cv.notify_all();
}
T get() {
std::lock_guard<std::mutex> lk(m_mutex);
return m_value;
}
bool waitFor(std::chrono::milliseconds ms, T& value) {
std::unique_lock<std::mutex> lk(m_mutex);
if (m_cv.wait_for(lk, ms, [this] { return m_prev != m_value; })) {
value = m_prev = m_value;
return true;
}
return false;
}
T wait() {
std::unique_lock<std::mutex> lk(m_mutex);
m_cv.wait(lk, [this] { return m_prev != m_value; });
m_prev = m_value;
return m_value;
}
private:
std::mutex m_mutex;
std::condition_variable m_cv;
T m_prev;
T m_value;
};
class NodeObserver: public INodeObserver {
public:
NodeObserver(INode& node) : m_node(node) {
m_knownHeight.init(node.getLastKnownBlockHeight());
node.addObserver(this);
}
~NodeObserver() {
m_node.removeObserver(this);
}
virtual void lastKnownBlockHeightUpdated(uint32_t height) override {
m_knownHeight.set(height);
}
virtual void localBlockchainUpdated(uint32_t height) override {
m_localHeight.set(height);
}
virtual void peerCountUpdated(size_t count) override {
m_peerCount.set(count);
}
bool waitLastKnownBlockHeightUpdated(std::chrono::milliseconds ms, uint32_t& value) {
return m_knownHeight.waitFor(ms, value);
}
bool waitLocalBlockchainUpdated(std::chrono::milliseconds ms, uint32_t& value) {
return m_localHeight.waitFor(ms, value);
}
uint32_t waitLastKnownBlockHeightUpdated() {
return m_knownHeight.wait();
}
ObservableValue<uint32_t> m_knownHeight;
ObservableValue<uint32_t> m_localHeight;
ObservableValue<size_t> m_peerCount;
private:
INode& m_node;
};
}
|
#include "../logger.h"
using std::cout;
using std::endl;
int main() {
logger *l = new logger();
cout << "log threshold: " << l->threshold() << endl;
l->debug("hello");
l->error("hello");
l->print("hello");
l->threshold(logger::dbg);
cout << "log threshold: " << l->threshold() << endl;
l->debug("hello");
l->error("hello");
l->print("hello");
}//end main()
|
#include<bits/stdc++.h>
using namespace std;
int main()
{
string name1, name2;
string choice1, choice2;
int num1, num2, t, sum;
cin>>t;
while(t--)
{
cin>>name1>>choice1>>name2>>choice2>>num1>>num2;
sum=num1+num2;
if(sum%2==0)
{
if(choice1=="PAR")
{
cout<<name1<<"\n";
}
else
{
cout<<name2<<"\n";
}
}
else
{
if(choice1=="IMPAR")
{
cout<<name1<<"\n";
}
else
{
cout<<name2<<"\n";
}
}
}
return 0;
}
|
#include "IMAGELoad.h"
#include "Model.h"
#include "PNGLoad.h"
#include "BMPLoad.h"
#include "DDSLoad.h"
GLuint loadTex(const char* path)
{
int pathLen = strlen(path);
char* imgExt = path + pathLen - 3;
char bmp[3] = {'b', 'm', 'p'};
char png[3] = {'p', 'n', 'g'};
char dds[3] = {'d', 'd', 's'};
if (memcmp(imgExt, bmp, 3) == 0)
{
return loadBMP(path);
}
else if (memcmp(imgExt, png, 3) == 0)
{
return texturePNG(makePNG_IS(path));
}
else if (memcmp(imgExt, dds, 3) == 0)
{
return loadDDS(path);
};
return 0;
};
GLuint texturePNG(PNGImageStruct* is)
{
GLuint textureID;
glGenTextures(1, &textureID);
glBindTexture(GL_TEXTURE_2D, textureID);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST);
glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA, is->width, is->height, 0, GL_RGBA, GL_UNSIGNED_BYTE, is->pixelData);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST);
return textureID;
};
|
//
// CHttpClient.h
// client
//
// Created by Sergey Proforov on 09.05.16.
// Copyright (c) 2016 Proforov Inc. All rights reserved.
//
#ifndef __client__CHttpClient__
#define __client__CHttpClient__
#include <memory>
#include "IConnection.h"
#include "IService.h"
//Класс для работы с HTTP севером
class CHttpClient : public IService{
private:
std::shared_ptr<IConnection> _conn;
std::string _address;
int16_t _port;
private:
CHttpClient(const CHttpClient & copy);
public:
CHttpClient(const char * address, uint16_t port);
virtual ~CHttpClient();
virtual void get(unsigned int naturalNubmer,
std::function<void(unsigned int n, std::string)> callBack );
};
#endif /* defined(__client__CHttpClient__) */
|
/*
Copyright (c) 2013 Randy Gaul http://RandyGaul.net
This software is provided 'as-is', without any express or implied
warranty. In no event will the authors be held liable for any damages
arising from the use of this software.
Permission is granted to anyone to use this software for any purpose,
including commercial applications, and to alter it and redistribute it
freely, subject to the following restrictions:
1. The origin of this software must not be misrepresented; you must not
claim that you wrote the original software. If you use this software
in a product, an acknowledgment in the product documentation would be
appreciated but is not required.
2. Altered source versions must be plainly marked as such, and must not be
misrepresented as being the original software.
3. This notice may not be removed or altered from any source distribution.
*/
#include "KPhysicsEngine.h"
KClock::KClock()
{
// Assign to a single processor
SetThreadAffinityMask(GetCurrentThread(), 1);
// Grab frequency of this processor
QueryPerformanceFrequency(&m_freq);
// Setup initial times
Start();
Stop();
}
KClock::~KClock()
{
}
// Records current time in start variable
void KClock::Start(void)
{
QueryPerformanceCounter(&m_start);
}
// Records current time in stop variable
void KClock::Stop(void)
{
QueryPerformanceCounter(&m_stop);
}
// Get current time from previous Start call
float KClock::Elapsed(void)
{
QueryPerformanceCounter(&m_current);
return (m_current.QuadPart - m_start.QuadPart) / (float)m_freq.QuadPart;
}
// Time between last Start and Stop calls
float KClock::Difference(void)
{
return (m_stop.QuadPart - m_start.QuadPart) / (float)m_freq.QuadPart;
}
// Get the current clock count
LONGLONG KClock::Current(void)
{
QueryPerformanceCounter(&m_current);
return m_current.QuadPart;
}
|
#ifndef GAMEOBJECT_H
#define GAMEOBJECT_H
#include <iostream>
#include <SDL.h>
class LoaderParams;
class GameObject
{
public:
virtual void draw() =0;
virtual void update() =0;
virtual void clean() =0;
virtual void load(const LoaderParams* pParams) =0;
protected:
GameObject () {}
virtual ~GameObject() {}
};
#endif
|
//
// main.cpp
// word-ladder-ii
//
// Created by xiedeping01 on 15/11/12.
// Copyright (c) 2015年 xiedeping01. All rights reserved.
//
#include <iostream>
#include <vector>
#include <string>
#include <unordered_map>
#include <unordered_set>
#include <queue>
using namespace std;
class Solution {
public:
vector<vector<string>> findLadders(string beginWord, string endWord, unordered_set<string> &wordList) {
// 最直观的思路:
// 1. 先BFS,找到最短的长度
// 2. 再DFS,以最短长度为界限,寻找所有Path
// 这个方法会超时,因为BFS和DFS分别遍历了整个图,存在重复工作
// 优化的方式是:
// 1. 先BFS,找到最短的长度,并遍历完endWrod所在的层次,保存所有被遍历节点的父节点列表
// 2. 对父节点列表进行DFS,重建所有路径
// 由于DFS只对父节点列表进行遍历,没有任何额外开销。
// edge case
vector<vector<string> > result;
if (beginWord == endWord) return result;
// BFS
unordered_map<string, vector<string> > parentList;
buildParentList(beginWord, endWord, wordList, parentList);
// DFS
vector<string> ladder;
ladder.push_back(endWord);
buildLadder(endWord, beginWord, parentList, ladder, result);
return result;
}
void buildParentList(const string &beginWord, const string &endWord,
const unordered_set<string> &wordList,
unordered_map<string, vector<string>> &parentList) {
// BFS使用的队列
queue<string> Q;
// 保存每个节点到beginWord的距离,并起到visited的作用
unordered_map<string, int> distance;
// 如果遇到endWord, 此变量表示遍历完本层之后,结束遍历
bool found = false;
Q.push(beginWord);
distance[beginWord] = 0;
while (!Q.empty() && !found) {
// 由于需要统计distance,必须按层遍历
for (int i = (int)Q.size(); i >= 1; i--) {
string curWord = Q.front(); Q.pop();
for (int j = 0; j < curWord.length(); j++) {
string newWord = curWord;
for (char ch = 'a'; ch <= 'z'; ch++) {
if (ch == curWord[j]) continue;
newWord[j] = ch;
if (newWord == endWord) {
parentList[endWord].push_back(curWord);
found = true;
break;
}
if (wordList.find(newWord) == wordList.end()) continue;
// 发现新单词,并入队,待下一层遍历
if (distance.find(newWord) == distance.end()) {
distance[newWord] = distance[curWord] + 1;
Q.push(newWord);
}
// 无论是新单词,还是下一层待遍历的单词,都保存父子关系
if (distance[newWord] == distance[curWord] + 1) {
parentList[newWord].push_back(curWord);
}
}
}
}
}
}
void buildLadder(const string &beginWord, const string &endWord,
unordered_map<string, vector<string>> &parentList,
vector<string> &ladder, vector<vector<string> > &result) {
if (beginWord == endWord) {
result.push_back(ladder);
reverse(result.back().begin(), result.back().end());
return;
}
for (vector<string>::const_iterator it = parentList[beginWord].begin();
it != parentList[beginWord].end(); ++it) {
ladder.push_back(*it);
buildLadder(*it, endWord, parentList, ladder, result);
ladder.pop_back();
}
}
};
int main(int argc, const char * argv[]) {
string beginWord = "hit", endWord = "cog";
unordered_set<string> wordList = {"hot","dot","dog","lot","log"};
vector<vector<string>> result = Solution().findLadders(beginWord, endWord, wordList);
for (const auto &ladder : result) {
for (const auto & str : ladder) {
cout << str << " ";
}
cout << endl;
}
return 0;
}
|
#include"pch.h"
#include"Timer.h"
using namespace std::chrono;
Timer::Timer(const bool remember)
{
m_startTime = high_resolution_clock::now();
m_stopTime = high_resolution_clock::now();
m_isRunning = false;
m_timeAdd = 0;
m_remeber = remember;
m_resumeValue = 0;
}
double Timer::timeElapsed() const
{
if (m_isRunning)
{
auto elapsed = std::chrono::duration<double>(high_resolution_clock::now() - m_startTime);
return elapsed.count() + m_timeAdd;
}
else
{
auto elapsed = std::chrono::duration<double>(m_stopTime - m_startTime);
return elapsed.count() + m_timeAdd;
}
}
bool Timer::start()
{
bool canStart = true;
if (m_isRunning)
canStart = false;
else
{
if (m_remeber)
{
addTime((int)m_resumeValue);
}
m_startTime = high_resolution_clock::now();
m_isRunning = true;
}
return canStart;
}
bool Timer::stop()
{
bool canStop = true;
if (m_isRunning)
{
if (m_remeber)
{
auto time = std::chrono::duration_cast<std::chrono::seconds>(high_resolution_clock::now() - m_startTime);
m_resumeValue = (double)time.count();
}
m_stopTime = high_resolution_clock::now();
m_isRunning = false;
}
else
canStop = false;
return canStop;
}
void Timer::restart()
{
m_isRunning = true;
m_startTime = std::chrono::high_resolution_clock::now();
}
void Timer::addTime(const int timeAdd)
{
m_timeAdd += timeAdd;
}
bool Timer::isActive() const
{
return m_isRunning;
}
|
#include <vector>
#include <string>
#include <iostream>
#include <fstream>
#include <sstream>
#include <list>
#include <algorithm>
#include <sstream>
#include <set>
#include <cmath>
#include <map>
#include <stack>
#include <queue>
#include <cstdio>
#include <cstdlib>
#include <cstring>
#include <numeric>
#include <bitset>
#include <deque>
#include <memory>
const long long LINF = (5e18);
const int INF = (1<<30);
#define EPS 1e-6
const int MOD = 1000000007;
using namespace std;
class BigFatInteger {
public:
int clog(long long c) {
int res = 0;
long long t = 1;
while (c > t) {
t <<= 1;
++res;
}
return res;
}
map<int, int> decomp(int n) {
map<int, int> res;
for (int i=2; i<=n; ++i) {
while (n%i==0) {
res[i]++;
n /= i;
}
}
return res;
}
int minOperations(int A, int B) {
map<int, int> d(decomp(A));
int mx = 0;
for (auto p: d)
mx = max(mx, p.second);
return (int)d.size() + clog((long long)mx*B);
}
// 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(); if ((Case == -1) || (Case == 4)) test_case_4(); }
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 int &Expected, const int &Received) { cerr << "Test Case #" << Case << "..."; if (Expected == Received) cerr << "PASSED" << endl; else { cerr << "FAILED" << endl; cerr << "\tExpected: \"" << Expected << '\"' << endl; cerr << "\tReceived: \"" << Received << '\"' << endl; } }
void test_case_0() { int Arg0 = 6; int Arg1 = 1; int Arg2 = 2; verify_case(0, Arg2, minOperations(Arg0, Arg1)); }
void test_case_1() { int Arg0 = 162; int Arg1 = 1; int Arg2 = 4; verify_case(1, Arg2, minOperations(Arg0, Arg1)); }
void test_case_2() { int Arg0 = 999983; int Arg1 = 9; int Arg2 = 5; verify_case(2, Arg2, minOperations(Arg0, Arg1)); }
void test_case_3() { int Arg0 = 360; int Arg1 = 8; int Arg2 = 8; verify_case(3, Arg2, minOperations(Arg0, Arg1)); }
void test_case_4() { int Arg0 = 16384; int Arg1 = 599186; int Arg2 = 24; verify_case(4, Arg2, minOperations(Arg0, Arg1)); }
// END CUT HERE
};
// BEGIN CUT HERE
int main() {
BigFatInteger ___test;
___test.run_test(-1);
}
// END CUT HERE
|
#ifndef FSS_H_
#define FSS_H_
#include "libdpf/libdpf.h"
#include "typedef.h"
class fss1bit {
private:
AES_KEY aes_key;
public:
fss1bit();
uint gen(unsigned long alpha, uint m, uchar *keys[2]);
void eval_all(const uchar *key, uint m, uchar *out);
void eval_all_with_perm(const uchar *key, uint m, unsigned long perm, uchar *out);
};
#endif /* FSS_H_ */
|
#pragma once
#include "Tool.h"
#include "AppColors.h"
#include <vector>
#include <SFML/Graphics.hpp>
#include <imgui-SFML.h>
#include <opencv2/imgproc/types_c.h>
#include <opencv2/imgproc/imgproc_c.h>
#include <opencv2/imgproc.hpp>
#include <opencv2/core/core.hpp>
#include <opencv2/highgui/highgui_c.h>
#include <opencv2/highgui/highgui.hpp>
#include <nlohmann/json.hpp>
#include <algorithm>
#include <SFML/Graphics/Shader.hpp>
#include <SFML/OpenGL.hpp>
#include <SFML/Graphics/Texture.hpp>
#include "Application.h"
namespace CAE
{
class MagicTool : public Tool
{
private:
std::vector<cv::Rect> outputRect;
sf::Image workImage;
static cv::Mat sfml2opencv(const sf::Texture& tex, bool toBGRA = false, bool fixZeroTransp = false);
//bool gray; //you should always use grayscale btw
//bool makeAllBlack;
// bool useMorph;
bool ButtonPressed;
//int thresh;
//int add;
//int morph_iteration;
//int mode;
sf::IntRect offset;
//sf::Vector2i kernel_rect;
History_data* his;
sf::IntRect cr;
cv::Mat source_image;
cv::Mat use_image;
cv::Mat transform_image;
cv::Vec4b transp_color;
cv::Vec4b transp_color2;
sf::RectangleShape shape;
std::shared_ptr<Group> group;
sf::IntRect rect;
bool once = false;
bool AnyHovered;
void assetUpdated() override
{
setImage(*asset->getTexture());
makeTransformImage();
}
public:
MagicTool(EMHolder& m, const sf::Texture& t, sf::RenderWindow& window, bool useFloatMove = false) : Tool(m, t, window),
ButtonPressed(false),
AnyHovered{false},
transp_color()
{
shape.setFillColor(sf::Color::Transparent);
shape.setOutlineColor(CAE::Colors::OutLine_r);
shape.setOutlineThickness(1);
}
void Enable() override
{
EventsHolder["MagicTool"].setEnable(true);
}
void Disable() override
{
EventsHolder["MagicTool"].setEnable(false);
ButtonPressed = false;
}
void setSelectedGroup(std::shared_ptr<Group> g)
{ group = g; }
void Init() override
{
auto& eManager = EventsHolder.addEM("MagicTool", false);
eManager.addEvent(MouseEvent::ButtonPressed(sf::Mouse::Left), [this](sf::Event&)
{
ButtonPressed = true;
});
eManager.addEvent(MouseEvent::ButtonReleased(sf::Mouse::Left), [this](sf::Event&)
{
if(once && group != nullptr && !AnyHovered)
{
ButtonPressed = false;
once = false;
cropSrc(rect, true);
for(auto& r : makeBounds())
group->addPart(r);
//group->getParts().emplace_back(std::make_shared<Part>(r,*his, 0));
rect = {};
shape.setPosition(sf::Vector2f(0, 0));
shape.setSize(sf::Vector2f(0, 0));
}
});
eManager.addEvent(MouseEvent(sf::Event::MouseMoved), [this](sf::Event&)
{
if(ButtonPressed && !AnyHovered)
{
if(!once)
{
once = true;
rect.left = EventsHolder.currMousePos().x;
rect.top = EventsHolder.currMousePos().y;
} else
{
auto delta = sf::Vector2f(rect.left, rect.top) - EventsHolder.currMousePos();
rect.width = -delta.x;
rect.height = -delta.y;
}
shape.setPosition(sf::Vector2f(rect.left, rect.top));
shape.setSize(sf::Vector2f(rect.width, rect.height));
}
});
}
void update() override
{
AnyHovered = ImGui::IsAnyWindowHovered() || ImGui::IsAnyItemHovered();
if(AnyHovered)
{
rect = {};
shape.setPosition(sf::Vector2f(0, 0));
shape.setSize(sf::Vector2f(0, 0));
once = ButtonPressed = false;
}
}
void draw(sf::RenderWindow& w) override
{ if(!AnyHovered) w.draw(shape); }
void makeTransformImage();
std::vector<sf::FloatRect> makeBounds();
//void makeBounds(std::vector<sf::FloatRect>& b);
auto getTransformPreview()
{ return workImage; }
auto getTransformImage()
{ return transform_image; }
auto getSource()
{ return source_image; }
void settingWindow();
nlohmann::json save2Json();
void load4Json(const nlohmann::json& j);
void cropSrc(sf::IntRect crop, bool rebuildSrc = false);
void setImage(const sf::Texture& t, sf::IntRect crop = {});
};
}
|
#include <iostream>
#include "term.h"
#include "triangleTerm.h"
#include "strings.h"
bool Term::enableTypes[TermTypeCount] = { };
bool Term::fuzzificationTypes[TermTypeCount] = { };
bool Term::defuzzificationTypes[TermTypeCount] = { };
Term::Term(std::string name, TermType type, bool isIn)
{
this->name = name;
enableTypes[type] = true;
if (isIn == true)
{
fuzzificationTypes[type] = true;
}
else
{
defuzzificationTypes[type] = true;
}
}
void Term::setVariableName(std::string variableName)
{
this->variableName = variableName;
}
std::string Term::getMaxJName() const
{
return variableName + name;
}
std::string Term::getName() const
{
return name;
}
std::string Term::getDegreeOfMembershipName() const
{
return getMaxJName() + std::string("DegreeOfMembership");
}
void Term::createFuzzyfication(std::ofstream& file)
{
file << " DFEVar " << getDegreeOfMembershipName() << " = ";
}
void Term::debugPrint()
{
std::cout << "Variable Name: " << variableName << " Name: " << name;
}
void Term::writeTypeDefsToFile(std::ofstream& file)
{
if (enableTypes[TRIANGLE] == true)
{
TriangleTerm::writeTypeDefsToFile(file);
}
file << Strings::getDefuzzificationStructString() << std::endl;
}
void Term::writeHelperFunctionsToFile(std::ofstream& file)
{
if (enableTypes[TRIANGLE] == true)
{
TriangleTerm::writeDataStructureCreationMethodeToFile(file);
}
if (fuzzificationTypes[TRIANGLE] == true)
{
TriangleTerm::writeFuzzificationMethodeToFile(file);
}
if (defuzzificationTypes[TRIANGLE] == true)
{
TriangleTerm::writeDefuzzificationMethodeToFile(file);
}
}
|
#include "Headers.h"
bool compareRect(const Rect& r1, const Rect& r2)
{
if (r1.y < r2.y - r2.height) {
return true;
}
return r1.x < r2.x;
}
bool compareRectX(const Rect& r1, const Rect& r2)
{
return r1.x < r2.x;
}
|
/* Implementation and tests for normalize path.*/
#include "cc/shared/common.h"
void normalize_path(char* buffer) {
RT_ASSERT(buffer);
// Process: overwrite in place using a read-head and write-head.
char* write = buffer;
for (char* read = buffer; read[0]; ++read) {
// If the next 3 characters are not "/..", just copy the character from
// read-head to write-head and move on.
if (read[0] != '/' || read[1] != '.' || read[2] != '.') {
write[0] = read[0];
++write;
continue;
}
// Move write-head back to ignore previous word. Do not commit a read
// under-flow.
while (write > buffer && write[-1] != '/') {
--write;
}
// Move read-head ahead by 2 extra characters that were read (the ".."
// after the '/').
read += 2;
// If there is more text then move write-head back or read-head forward to
// eliminate duplicate separators (treating word beginning as a separator).
if (read[1]) {
if (write > buffer) {
--write;
} else {
++read;
}
}
}
// Finally, close out the string.
write[0] = 0;
}
void test_case(const char* expected, const char* input) {
static const int kMaxChars = 1000;
char actual[kMaxChars];
ZERO_ARRAY(actual);
strncpy(actual, input, kMaxChars - 1);
normalize_path(actual);
if (0 == strcmp(expected, actual)) {
return;
}
printf("Input: \"%s\"\n", input);
printf("Expected: \"%s\"\n", expected);
printf("Actual: \"%s\"\n\n", actual);
RT_ASSERT(false);
}
void do_verification() {
test_case("", "");
test_case("/Root/Folder", "/Root/Folder");
test_case("Root", "Root");
test_case("Root/Folder", "Root/Folder");
test_case("/", "/Root/..");
test_case("./Folder", "./Root/../Folder");
test_case("Folder", "Root/../Folder");
test_case("", "Root/../");
test_case("NewRoot/", "Root/../NewRoot/");
test_case("Root/", "Root/Folder1/..");
test_case("Root/Folder3", "Root/Folder1/../Folder2/../Folder3");
test_case("Root/Folder1/Folder3/",
"Root/Folder1/Folder2/../Folder3/");
test_case("Root/Folder3/",
"Root/Folder1/Folder2/../../Folder3/");
test_case("Root/Folder3/",
"Root/Folder1/Folder2/Folder3/../../../Folder3/");
test_case("Root/Folder4/x",
"Root/Folder1/Folder2/Folder3/../../../Folder4/x");
test_case("/", "/");
printf("Normalize path testing done.\n");
}
void do_measurement() {
// No Op.
}
|
class Solution {
void Util(vector<string> &ans, string op, int o, int c, int n) {
if(op.size() == 2*n) {
ans.push_back(op);
return;
}
if(o > 0) {
op.push_back('(');
Util(ans, op, o-1, c, n);
op.pop_back();
}
if(c > o) {
op.push_back(')');
Util(ans, op, o, c-1, n);
}
return;
}
public:
vector<string> generateParenthesis(int n) {
vector<string> ans;
string op;
Util(ans, op, n, n, n);
return ans;
}
};
|
#include "Sound.h"
#include "stb_vorbis.h"
#include <vector>
//!The ALSound class. This controlls the API individual sounds
struct ALSound
{
ALSound()
{
alGenBuffers(1, &bufferId);
}
~ALSound()
{
alDeleteBuffers(1, &bufferId);
}
//!The function loads the sound interacts with the API
void Load(std::string _path)
{
int channels = 0;
int sampleRate = 0;
short* output = NULL;
size_t samples = stb_vorbis_decode_filename(_path.c_str(), &channels, &sampleRate, &output);
if (samples == -1)
{
throw std::exception();
}
// Record the sample rate required by OpenAL
freq = sampleRate;
// Record the format required by OpenAL
if (channels == 1)
{
format = AL_FORMAT_MONO16;
}
else
{
format = AL_FORMAT_STEREO16;
// Force format to be mono (Useful for positional audio)
// format = AL_FORMAT_MONO16;
// freq *= 2;
}
// Allocate enough space based on short (two chars) multipled by the number of
// channels and length of clip
bufferData.resize(sizeof(*output) * channels * samples);
memcpy(&bufferData.at(0), output, bufferData.size());
// Clean up the read data
free(output);
alBufferData(bufferId, format, &bufferData.at(0), static_cast<ALsizei>(bufferData.size()), freq);
}
//!The function returns the sound ID for playing the sound
ALuint GetId()
{
return bufferId;
}
private:
ALuint bufferId = 0;
ALenum format = 0;
ALsizei freq = 0;
std::vector<char> bufferData;
};
void Sound::Load(std::string _path)
{
sound = std::make_shared<ALSound>();
sound->Load(_path);
}
ALuint Sound::GetSoundID()
{
return sound->GetId();
}
|
// RekeningGiro.h
#ifndef REKENINGGIRO_H
#define REKENINGGIRO_H
#include "Rekening.h" // include the Account header file
class RekeningGiro : public Rekening {
public:
// Konstruktor menginisialisi saldo (parameter 1) dan suku bunga (parameter 2)
// Set suku bunga 0.0 apabila suku bunga bernilai negatif
RekeningGiro(double, double);
// Getter, Setter
void setSukuBunga(double);
double getSukuBunga() const;
// Member Function
// Bunga dihitung dari saldo dikali suku bunga
double hitungBunga();
private:
double sukuBunga;
};
#endif
|
#ifndef CAR_H
#define CAR_H
#include <iostream>
#define MAX_AC 4
#define MIN_AC 0
#define MAX_GEAR 6
#define MIN_GEAR 1
using namespace std;
enum Fuel {premium, pertamax, solar};
class Car {
private:
Fuel fuel;
int gear;
int ac_power;
bool on;
public:
// Ctor
// Menginisiasi jenis fuel dengan t_fuel, gear = 0, ac_power = 0 dan on = false.
Car(Fuel t_fuel);
// Getter
Fuel getFuel();
int getGear();
int getAcPower();
bool getOn();
/*
Melakukan isi bensin terhadap mobil
Melakukan pengecekan jenis bensin masukan apakah sesuai dengan jenis bensin mobil.
Bila tidak sesuai lakukan throw jenis bensin masukan (t_fuel)
Bila sesuai, akan menghasilkan keluaran "Berhasil isi bensin sebanyak (nilai amount_in_liter) liter" diakhiri newline dan abaikan tanda '()'
*/
void fillingFuel(Fuel t_fuel, int amount_in_liter);
/*
Melakukan pergantian gigi mobil
Melakukan pengecekan t_gear sebagai masukan gigi apakah berada pada range MIN_GEAR<=X<=MAX_GEAR.
Bila tidak sesuai range lakukan throw gigi masukan (t_gear).
Bila sesuai, akan merubah nilai gear si mobil dan
menghasilkan keluaran "Berhasil mengubah gigi menjadi gigi (nilai t_gear)" diakhiri newline dan abaikan tanda '()'.
*/
void changeGear(int t_gear);
/*
Melakukan pergantian power ac pada mobil
Melakukan pengecekan t_ac_power sebagai masukan power ac apakah berada pada range MIN_AC<=X<=MAX_AC.
Bila tidak sesuai range lakukan throw power ac masukan (t_ac_power).
Bila sesuai, akan merubah nilai ac_power si mobil dan
menghasilkan keluaran "Berhasil mengubah power ac menjadi (nilai t_ac_power)" diakhiri newline dan abaikan tanda '()'.
*/
void changeAcPower(int t_ac_power);
/*
Melakukan starter/ menyalakan mobil
Melakukan pengecekan apakah mobil sudah dalam kondisi menyala atau belum ketika fungsi start dipanggil.
Bila mobil sudah menyala lakukan throw nilai on mobil.
Bila mobil belum menyala akan merubah nilai on mobil menjadi true dan
menghasilkan keluaran "Berhasil melakukan starter mobil" diakhiri newline.
*/
void start();
/*
Melakukan pergantian pengecekan seluruh fitur pada mobil
Pengecekan fitur dilakukan dengan cara pemanggilan fungsi dengan urutan
start -> fillingFuel dengan menggunakan parameter masukan pertama dan kedua
-> changeGear dengan menggunakan parameter masukan ketiga
-> changeAcPower dengan menggunakan parameter masukan keempat.
Implementasikan prosedur ini menggunakan try catch, dengan multiple catch, total tiga jenis catch.
Catch tipe boolean, akan menghasilkan keluaran "Mobil sudah menyala" diakhiri newline
Catch tipe integer, akan menghasilkan keluaran "Input angka diluar range" diakhiri newline
Catch tipe Fuel, akan menghasilkan keluaran "Bensin tidak sesuai" diakhiri newline
*/
void service(Fuel t_fuel, int amount_in_liter, int t_gear, int t_ac_power);
};
#endif
|
#ifndef MRJR_CHECKER
#include <iostream>
#include <string>
#include <fstream>
using namespace std;
class checker
{
public:
// Takes in a filestream, checks for errors, and returns a bool for the error/lack thereof
static bool cycle(ifstream& currentStream);
private:
// Takes in a character and tells if it's a forward delimiter, returns a bool
static bool forward(char currentChar);
// Takes in a character and tells if it's a reverse delimiter, returns a bool
static bool reverse(char currentChar);
// Takes in a character and returns the compliment of that character if it's a delimiter
static char compliment(char currentChar);
// Takes in an expected character, a received character, and the line number and prints the error message
static void message(char charE, char charR, int lineNum);
// Takes in a character and an array of characters and checks to see if the character is in the array
static bool boolCheck(char currentChar, char *cA);
};
#endif
|
#include <Drawables/Drawable.h>
CDrawable::CDrawable(GLenum drawMode, GLsizei elementsCount)
: _drawMode(drawMode)
, _elementsCount(elementsCount)
{
}
void CDrawable::updateVertices(GLsizeiptr size, const void *data, GLenum drawType)
{
_vao.bind();
_vbo.bind();
_vbo.updateData(size, data, drawType);
}
void CDrawable::updateAttrib(GLuint index, GLint size, GLsizei stride, GLuint offset)
{
_vbo.updateAttrib(index, size, stride, offset);
}
void CDrawable::render() const
{
_vao.bind();
glDrawArrays(_drawMode, 0, _elementsCount);
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.