text
stringlengths 54
60.6k
|
|---|
<commit_before>/*
* qihdr.cpp
*
* Created by Tobias Wood on 11/06/2015.
* Copyright (c) 2015 Tobias Wood.
*
* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/.
*
*/
#include <time.h>
#include <getopt.h>
#include <iostream>
#include <atomic>
#include "Types.h"
#include "Util.h"
using namespace std;
//******************************************************************************
// Arguments / Usage
//******************************************************************************
int print_all = true;
int print_size = false, print_spacing = false, print_origin = false, print_direction = false;
const string usage {
"Usage is: qihdr [options] input[s] \n\
\n\
By default, a summary of the header is printed. If options below are specified,\n\
only those parts of the header will be printed. Multiple files can be input,\n\
in which case the header info is written for each in order.\n\
\n\
Options:\n\
--help, -h : Print this message.\n\
--size : Print the image dimensions.\n\
--spacing : Print the image spacing.\n\
--origin : Print the origin.\n\
--direction : Print the image direction.\n"
};
const struct option long_options[] = {
{"help", no_argument, 0, 'h'},
{"size", no_argument, 0, 's'},
{"spacing", no_argument, 0, 'p'},
{"origin", no_argument, 0, 'o'},
{"direction", no_argument, 0, 'd'},
{0, 0, 0, 0}
};
const char *short_options = "h";
//******************************************************************************
// Main
//******************************************************************************
int main(int argc, char **argv) {
int indexptr = 0, c;
while ((c = getopt_long(argc, argv, short_options, long_options, &indexptr)) != -1) {
switch (c) {
case 'h':
cout << usage << endl;
return EXIT_SUCCESS;
case 's': print_size = true; print_all = false; break;
case 'p': print_spacing = true; print_all = false; break;
case 'o': print_origin = true; print_all = false; break;
case 'd': print_direction = true; print_all = false; break;
case '?': // getopt will print an error message
return EXIT_FAILURE;
default:
cout << "Unhandled option " << string(1, c) << endl;
return EXIT_FAILURE;
}
}
while (optind < argc) {
QI::ReadImageF::Pointer thisImg = QI::ReadImageF::New();
if (print_all) cout << "Header for: " << string(argv[optind]) << endl;
thisImg->SetFileName(argv[optind++]);
thisImg->Update();
if (print_all) cout << "Size: "; if (print_all || print_size) cout << thisImg->GetOutput()->GetLargestPossibleRegion().GetSize() << endl;
if (print_all) cout << "Spacing: "; if (print_all || print_spacing) cout << thisImg->GetOutput()->GetSpacing() << endl;
if (print_all) cout << "Origin: "; if (print_all || print_origin) cout << thisImg->GetOutput()->GetOrigin() << endl;
if (print_all) cout << "Direction: "; if (print_all || print_direction) cout << thisImg->GetOutput()->GetDirection() << endl;
}
return EXIT_SUCCESS;
}
<commit_msg>Added a missing newline to make the direction legible.<commit_after>/*
* qihdr.cpp
*
* Created by Tobias Wood on 11/06/2015.
* Copyright (c) 2015 Tobias Wood.
*
* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/.
*
*/
#include <time.h>
#include <getopt.h>
#include <iostream>
#include <atomic>
#include "Types.h"
#include "Util.h"
using namespace std;
//******************************************************************************
// Arguments / Usage
//******************************************************************************
int print_all = true;
int print_size = false, print_spacing = false, print_origin = false, print_direction = false;
const string usage {
"Usage is: qihdr [options] input[s] \n\
\n\
By default, a summary of the header is printed. If options below are specified,\n\
only those parts of the header will be printed. Multiple files can be input,\n\
in which case the header info is written for each in order.\n\
\n\
Options:\n\
--help, -h : Print this message.\n\
--size : Print the image dimensions.\n\
--spacing : Print the image spacing.\n\
--origin : Print the origin.\n\
--direction : Print the image direction.\n"
};
const struct option long_options[] = {
{"help", no_argument, 0, 'h'},
{"size", no_argument, 0, 's'},
{"spacing", no_argument, 0, 'p'},
{"origin", no_argument, 0, 'o'},
{"direction", no_argument, 0, 'd'},
{0, 0, 0, 0}
};
const char *short_options = "h";
//******************************************************************************
// Main
//******************************************************************************
int main(int argc, char **argv) {
int indexptr = 0, c;
while ((c = getopt_long(argc, argv, short_options, long_options, &indexptr)) != -1) {
switch (c) {
case 'h':
cout << usage << endl;
return EXIT_SUCCESS;
case 's': print_size = true; print_all = false; break;
case 'p': print_spacing = true; print_all = false; break;
case 'o': print_origin = true; print_all = false; break;
case 'd': print_direction = true; print_all = false; break;
case '?': // getopt will print an error message
return EXIT_FAILURE;
default:
cout << "Unhandled option " << string(1, c) << endl;
return EXIT_FAILURE;
}
}
while (optind < argc) {
QI::ReadImageF::Pointer thisImg = QI::ReadImageF::New();
if (print_all) cout << "Header for: " << string(argv[optind]) << endl;
thisImg->SetFileName(argv[optind++]);
thisImg->Update();
if (print_all) cout << "Size: "; if (print_all || print_size) cout << thisImg->GetOutput()->GetLargestPossibleRegion().GetSize() << endl;
if (print_all) cout << "Spacing: "; if (print_all || print_spacing) cout << thisImg->GetOutput()->GetSpacing() << endl;
if (print_all) cout << "Origin: "; if (print_all || print_origin) cout << thisImg->GetOutput()->GetOrigin() << endl;
if (print_all) cout << "Direction: " << endl; if (print_all || print_direction) cout << thisImg->GetOutput()->GetDirection() << endl;
}
return EXIT_SUCCESS;
}
<|endoftext|>
|
<commit_before>/**********
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. (See <http://www.gnu.org/copyleft/lesser.html>.)
This library is distributed in the hope that it will be useful, but WITHOUT
ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for
more details.
You should have received a copy of the GNU Lesser General Public License
along with this library; if not, write to the Free Software Foundation, Inc.,
51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
**********/
// Copyright (c) 1996-2013, Live Networks, Inc. All rights reserved
// A test program that demonstrates how to stream - via unicast RTP
// - various kinds of file on demand, using a built-in RTSP server.
// main program
#ifndef INT64_C
#define INT64_C(c) (c ## LL)
#define UINT64_C(c) (c ## ULL)
#endif
#include "liveMedia.hh"
#define EventTime server_EventTime
#include "BasicUsageEnvironment.hh"
#undef EventTime
#include <stdio.h>
#include <stdlib.h>
#include <stdio.h>
#include "H264VideoOnDemandServerMediaSubsession.h"
#include "shared.h"
#include "config.h"
#include "RandomFramedSource.h"
#include "AlloShared/CubemapFace.h"
#include "AlloServer.h"
#include "concurrent_queue.h"
//RTPSink* videoSink;
UsageEnvironment* env;
// To make the second and subsequent client for each stream reuse the same
// input stream as the first client (rather than playing the file from the
// start for each client), change the following "False" to "True":
Boolean reuseFirstSource = True;
// To stream *only* MPEG-1 or 2 video "I" frames
// (e.g., to reduce network bandwidth),
// change the following "False" to "True":
Boolean iFramesOnly = False;
static void announceStream(RTSPServer* rtspServer, ServerMediaSession* sms,
char const* streamName); // fwd
static char newMatroskaDemuxWatchVariable;
static MatroskaFileServerDemux* demux;
static void onMatroskaDemuxCreation(MatroskaFileServerDemux* newDemux, void* /*clientData*/) {
demux = newDemux;
newMatroskaDemuxWatchVariable = 1;
}
void eventLoop(int port);
void addFaceSubstream();
void startRTSP(int port){
// pthread_t thread;
// return pthread_create(&thread,NULL,eventLoop, NULL);
boost::thread thread1(boost::bind(&eventLoop, port));
}
ServerMediaSession* sms;
EventTriggerId addFaceSubstreamTriggerId;
concurrent_queue<CubemapFace*> faceBuffer;
void addFaceSubstream0(void*) {
CubemapFace* face;
while (faceBuffer.try_pop(face))
{
H264VideoOnDemandServerMediaSubsession *subsession = H264VideoOnDemandServerMediaSubsession::createNew(*env, reuseFirstSource, face);
sms->addSubsession(subsession);
std::cout << "added face " << face->index << std::endl;
}
}
std::vector<H264VideoOnDemandServerMediaSubsession*> faceSubstreams;
void addFaceSubstream()
{
std::list<int> addedFaces;
while (true)
{
boost::interprocess::scoped_lock<boost::interprocess::interprocess_mutex> lock(cubemap->mutex);
//
for (int i = 0; i < cubemap->count(); i++)
{
if (std::find(addedFaces.begin(), addedFaces.end(), cubemap->getFace(i)->index) == addedFaces.end())
{
faceBuffer.push(cubemap->getFace(i).get());
addedFaces.push_back(cubemap->getFace(i)->index);
}
}
if (!faceBuffer.empty())
{
env->taskScheduler().triggerEvent(addFaceSubstreamTriggerId, NULL);
}
cubemap->newFaceCondition.wait(lock);
}
}
void eventLoop(int port) {
// Begin by setting up our usage environment:
TaskScheduler* scheduler = BasicTaskScheduler::createNew();
env = BasicUsageEnvironment::createNew(*scheduler);
UserAuthenticationDatabase* authDB = NULL;
#ifdef ACCESS_CONTROL
// To implement client access control to the RTSP server, do the following:
authDB = new UserAuthenticationDatabase;
authDB->addUserRecord("username1", "password1"); // replace these with real strings
// Repeat the above with each <username>, <password> that you wish to allow
// access to the server.
#endif
// Create the RTSP server:
RTSPServer* rtspServer = RTSPServer::createNew(*env, port, authDB);
//RTSPServer* rtspServer = RTSPServer::createNew(*env, 8555, authDB);
if (rtspServer == NULL) {
*env << "Failed to create RTSP server: " << env->getResultMsg() << "\n";
exit(1);
}
char const* descriptionString
= "Session streamed by \"testOnDemandRTSPServer\"";
// Set up each of the possible streams that can be served by the
// RTSP server. Each such stream is implemented using a
// "ServerMediaSession" object, plus one or more
// "ServerMediaSubsession" objects for each audio/video substream.
OutPacketBuffer::maxSize = 4000000;
// A H.264 video elementary stream:
{
char const* streamName = "h264ESVideoTest";
sms = ServerMediaSession::createNew(*env, streamName, streamName,
descriptionString);
//H264VideoOnDemandServerMediaSubsession *subsession2 = H264VideoOnDemandServerMediaSubsession::createNew(*env, reuseFirstSource, "two");
//videoSink = subsession->createNewRTPSink(groupSock, 96);
//sms->addSubsession(subsession1);
rtspServer->addServerMediaSession(sms);
announceStream(rtspServer, sms, streamName);
}
// Also, attempt to create a HTTP server for RTSP-over-HTTP tunneling.
// Try first with the default HTTP port (80), and then with the alternative HTTP
// port numbers (8000 and 8080).
/*if (rtspServer->setUpTunnelingOverHTTP(80) || rtspServer->setUpTunnelingOverHTTP(8000) || rtspServer->setUpTunnelingOverHTTP(8080)) {
*env << "\n(We use port " << rtspServer->httpServerPortNum() << " for optional RTSP-over-HTTP tunneling.)\n";
} else {
*env << "\n(RTSP-over-HTTP tunneling is not available.)\n";
}*/
/*
// Start the streaming:
*env << "Beginning streaming...\n";
startPlay();
//play(NULL);
usleep(5000000);
printf("done play\n");
*/
addFaceSubstreamTriggerId = env->taskScheduler().createEventTrigger(&addFaceSubstream0);
boost::thread thread2(&addFaceSubstream);
env->taskScheduler().doEventLoop(); // does not return
// return 0; // only to prevent compiler warning
}
static void announceStream(RTSPServer* rtspServer, ServerMediaSession* sms,
char const* streamName) {
char* url = rtspServer->rtspURL(sms);
UsageEnvironment& env = rtspServer->envir();
env << "Play this stream using the URL \"" << url << "\"\n";
delete[] url;
}
<commit_msg>Multicast support for AlloServer. Still crashes.<commit_after>/**********
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. (See <http://www.gnu.org/copyleft/lesser.html>.)
This library is distributed in the hope that it will be useful, but WITHOUT
ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for
more details.
You should have received a copy of the GNU Lesser General Public License
along with this library; if not, write to the Free Software Foundation, Inc.,
51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
**********/
// Copyright (c) 1996-2013, Live Networks, Inc. All rights reserved
// A test program that demonstrates how to stream - via unicast RTP
// - various kinds of file on demand, using a built-in RTSP server.
// main program
#ifndef INT64_C
#define INT64_C(c) (c ## LL)
#define UINT64_C(c) (c ## ULL)
#endif
#include "liveMedia.hh"
#include <GroupsockHelper.hh>
#define EventTime server_EventTime
#include "BasicUsageEnvironment.hh"
#undef EventTime
#include <stdio.h>
#include <stdlib.h>
#include <stdio.h>
#include "H264VideoOnDemandServerMediaSubsession.h"
#include "shared.h"
#include "config.h"
#include "RandomFramedSource.h"
#include "AlloShared/CubemapFace.h"
#include "AlloServer.h"
#include "concurrent_queue.h"
#include "CubemapFaceSource.h"
//RTPSink* videoSink;
UsageEnvironment* env;
// To make the second and subsequent client for each stream reuse the same
// input stream as the first client (rather than playing the file from the
// start for each client), change the following "False" to "True":
Boolean reuseFirstSource = True;
// To stream *only* MPEG-1 or 2 video "I" frames
// (e.g., to reduce network bandwidth),
// change the following "False" to "True":
Boolean iFramesOnly = False;
static void announceStream(RTSPServer* rtspServer, ServerMediaSession* sms,
char const* streamName); // fwd
static char newMatroskaDemuxWatchVariable;
static MatroskaFileServerDemux* demux;
static void onMatroskaDemuxCreation(MatroskaFileServerDemux* newDemux, void* /*clientData*/) {
demux = newDemux;
newMatroskaDemuxWatchVariable = 1;
}
void eventLoop(int port);
void addFaceSubstream();
void startRTSP(int port){
// pthread_t thread;
// return pthread_create(&thread,NULL,eventLoop, NULL);
boost::thread thread1(boost::bind(&eventLoop, port));
}
ServerMediaSession* sms;
EventTriggerId addFaceSubstreamTriggerId;
concurrent_queue<CubemapFace*> faceBuffer;
struct in_addr destinationAddress;
static struct FaceStreamState
{
RTPSink* sink;
CubemapFace* face;
FramedSource* source;
};
void afterPlaying(void* clientData)
{
FaceStreamState* state = (FaceStreamState*)clientData;
*env << "stopped streaming face " << state->face->index << "\n";
state->sink->stopPlaying();
Medium::close(state->source);
// Note that this also closes the input file that this source read from.
delete state;
}
const unsigned short rtpPortNum = 18888;
const unsigned char ttl = 255;
void addFaceSubstream0(void*) {
CubemapFace* face;
while (faceBuffer.try_pop(face))
{
FaceStreamState* state = new FaceStreamState;
state->face = face;
Port rtpPort(rtpPortNum + face->index);
Groupsock rtpGroupsock(*env, destinationAddress, rtpPort, ttl);
rtpGroupsock.multicastSendOnly(); // we're a SSM source
// Create a 'H264 Video RTP' sink from the RTP 'groupsock':
OutPacketBuffer::maxSize = 100000;
state->sink = H264VideoRTPSink::createNew(*env, &rtpGroupsock, 96);
ServerMediaSubsession* subsession = PassiveServerMediaSubsession::createNew(*state->sink);
//H264VideoOnDemandServerMediaSubsession *subsession = H264VideoOnDemandServerMediaSubsession::createNew(*env, reuseFirstSource, face);
sms->addSubsession(subsession);
state->source = H264VideoStreamDiscreteFramer::createNew(*env, CubemapFaceSource::createNew(*env, face));
state->sink->startPlaying(*state->source, afterPlaying, state);
std::cout << "added face " << face->index << std::endl;
}
}
std::vector<H264VideoOnDemandServerMediaSubsession*> faceSubstreams;
void addFaceSubstream()
{
std::list<int> addedFaces;
while (true)
{
boost::interprocess::scoped_lock<boost::interprocess::interprocess_mutex> lock(cubemap->mutex);
//
for (int i = 0; i < cubemap->count(); i++)
{
if (std::find(addedFaces.begin(), addedFaces.end(), cubemap->getFace(i)->index) == addedFaces.end())
{
faceBuffer.push(cubemap->getFace(i).get());
addedFaces.push_back(cubemap->getFace(i)->index);
}
}
if (!faceBuffer.empty())
{
env->taskScheduler().triggerEvent(addFaceSubstreamTriggerId, NULL);
}
cubemap->newFaceCondition.wait(lock);
}
}
void eventLoop(int port) {
// Begin by setting up our usage environment:
TaskScheduler* scheduler = BasicTaskScheduler::createNew();
env = BasicUsageEnvironment::createNew(*scheduler);
// Create 'groupsocks' for RTP and RTCP:
destinationAddress.s_addr = chooseRandomIPv4SSMAddress(*env);
// Note: This is a multicast address. If you wish instead to stream
// using unicast, then you should use the "testOnDemandRTSPServer"
// test program - not this test program - as a model.
char str[INET_ADDRSTRLEN];
inet_ntop(AF_INET, &(destinationAddress.s_addr), str, INET_ADDRSTRLEN);
printf("Multicast address: %s\n", str);
UserAuthenticationDatabase* authDB = NULL;
#ifdef ACCESS_CONTROL
// To implement client access control to the RTSP server, do the following:
authDB = new UserAuthenticationDatabase;
authDB->addUserRecord("username1", "password1"); // replace these with real strings
// Repeat the above with each <username>, <password> that you wish to allow
// access to the server.
#endif
// Create the RTSP server:
RTSPServer* rtspServer = RTSPServer::createNew(*env, port, authDB);
//RTSPServer* rtspServer = RTSPServer::createNew(*env, 8555, authDB);
if (rtspServer == NULL) {
*env << "Failed to create RTSP server: " << env->getResultMsg() << "\n";
exit(1);
}
char const* descriptionString
= "Session streamed by \"testOnDemandRTSPServer\"";
// Set up each of the possible streams that can be served by the
// RTSP server. Each such stream is implemented using a
// "ServerMediaSession" object, plus one or more
// "ServerMediaSubsession" objects for each audio/video substream.
OutPacketBuffer::maxSize = 4000000;
// A H.264 video elementary stream:
{
char const* streamName = "h264ESVideoTest";
sms = ServerMediaSession::createNew(*env, streamName, streamName,
descriptionString, True);
//H264VideoOnDemandServerMediaSubsession *subsession2 = H264VideoOnDemandServerMediaSubsession::createNew(*env, reuseFirstSource, "two");
//videoSink = subsession->createNewRTPSink(groupSock, 96);
//sms->addSubsession(subsession1);
rtspServer->addServerMediaSession(sms);
announceStream(rtspServer, sms, streamName);
}
// Also, attempt to create a HTTP server for RTSP-over-HTTP tunneling.
// Try first with the default HTTP port (80), and then with the alternative HTTP
// port numbers (8000 and 8080).
/*if (rtspServer->setUpTunnelingOverHTTP(80) || rtspServer->setUpTunnelingOverHTTP(8000) || rtspServer->setUpTunnelingOverHTTP(8080)) {
*env << "\n(We use port " << rtspServer->httpServerPortNum() << " for optional RTSP-over-HTTP tunneling.)\n";
} else {
*env << "\n(RTSP-over-HTTP tunneling is not available.)\n";
}*/
/*
// Start the streaming:
*env << "Beginning streaming...\n";
startPlay();
//play(NULL);
usleep(5000000);
printf("done play\n");
*/
addFaceSubstreamTriggerId = env->taskScheduler().createEventTrigger(&addFaceSubstream0);
boost::thread thread2(&addFaceSubstream);
env->taskScheduler().doEventLoop(); // does not return
// return 0; // only to prevent compiler warning
}
static void announceStream(RTSPServer* rtspServer, ServerMediaSession* sms,
char const* streamName) {
char* url = rtspServer->rtspURL(sms);
UsageEnvironment& env = rtspServer->envir();
env << "Play this stream using the URL \"" << url << "\"\n";
delete[] url;
}
<|endoftext|>
|
<commit_before>// Copyright (c) 2011 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "webkit/plugins/ppapi/ppapi_webplugin_impl.h"
#include <cmath>
#include "base/message_loop.h"
#include "googleurl/src/gurl.h"
#include "ppapi/c/pp_var.h"
#include "third_party/WebKit/Source/WebKit/chromium/public/WebBindings.h"
#include "third_party/WebKit/Source/WebKit/chromium/public/WebPluginParams.h"
#include "third_party/WebKit/Source/WebKit/chromium/public/WebPoint.h"
#include "third_party/WebKit/Source/WebKit/chromium/public/WebRect.h"
#include "third_party/WebKit/Source/WebKit/chromium/public/WebView.h"
#include "webkit/plugins/ppapi/message_channel.h"
#include "webkit/plugins/ppapi/plugin_module.h"
#include "webkit/plugins/ppapi/ppapi_plugin_instance.h"
#include "webkit/plugins/ppapi/ppb_url_loader_impl.h"
#include "webkit/plugins/ppapi/var.h"
using WebKit::WebCanvas;
using WebKit::WebPluginContainer;
using WebKit::WebPluginParams;
using WebKit::WebPoint;
using WebKit::WebRect;
using WebKit::WebString;
using WebKit::WebURL;
using WebKit::WebVector;
using WebKit::WebView;
namespace webkit {
namespace ppapi {
struct WebPluginImpl::InitData {
scoped_refptr<PluginModule> module;
base::WeakPtr<PluginDelegate> delegate;
std::vector<std::string> arg_names;
std::vector<std::string> arg_values;
GURL url;
};
WebPluginImpl::WebPluginImpl(
PluginModule* plugin_module,
const WebPluginParams& params,
const base::WeakPtr<PluginDelegate>& plugin_delegate)
: init_data_(new InitData()),
full_frame_(params.loadManually) {
DCHECK(plugin_module);
init_data_->module = plugin_module;
init_data_->delegate = plugin_delegate;
for (size_t i = 0; i < params.attributeNames.size(); ++i) {
init_data_->arg_names.push_back(params.attributeNames[i].utf8());
init_data_->arg_values.push_back(params.attributeValues[i].utf8());
}
init_data_->url = params.url;
}
WebPluginImpl::~WebPluginImpl() {
}
bool WebPluginImpl::initialize(WebPluginContainer* container) {
// The plugin delegate may have gone away.
if (!init_data_->delegate)
return false;
instance_ = init_data_->module->CreateInstance(init_data_->delegate);
if (!instance_)
return false;
bool success = instance_->Initialize(container,
init_data_->arg_names,
init_data_->arg_values,
init_data_->url,
full_frame_);
if (!success) {
instance_->Delete();
instance_ = NULL;
return false;
}
init_data_.reset();
return true;
}
void WebPluginImpl::destroy() {
if (instance_) {
instance_->Delete();
instance_ = NULL;
}
MessageLoop::current()->DeleteSoon(FROM_HERE, this);
}
NPObject* WebPluginImpl::scriptableObject() {
scoped_refptr<ObjectVar> object(
ObjectVar::FromPPVar(instance_->GetInstanceObject()));
// If there's an InstanceObject, tell the Instance's MessageChannel to pass
// any non-postMessage calls to it.
if (object) {
instance_->message_channel().SetPassthroughObject(object->np_object());
}
NPObject* message_channel_np_object(instance_->message_channel().np_object());
// The object is expected to be retained before it is returned.
WebKit::WebBindings::retainObject(message_channel_np_object);
return message_channel_np_object;
}
bool WebPluginImpl::getFormValue(WebString* value) {
return false;
}
void WebPluginImpl::paint(WebCanvas* canvas, const WebRect& rect) {
if (!instance_->IsFullscreenOrPending())
instance_->Paint(canvas, plugin_rect_, rect);
}
void WebPluginImpl::updateGeometry(
const WebRect& window_rect,
const WebRect& clip_rect,
const WebVector<WebRect>& cut_outs_rects,
bool is_visible) {
plugin_rect_ = window_rect;
if (!instance_->IsFullscreenOrPending())
instance_->ViewChanged(plugin_rect_, clip_rect);
}
void WebPluginImpl::updateFocus(bool focused) {
instance_->SetWebKitFocus(focused);
}
void WebPluginImpl::updateVisibility(bool visible) {
}
bool WebPluginImpl::acceptsInputEvents() {
return true;
}
bool WebPluginImpl::handleInputEvent(const WebKit::WebInputEvent& event,
WebKit::WebCursorInfo& cursor_info) {
if (instance_->IsFullscreenOrPending())
return false;
return instance_->HandleInputEvent(event, &cursor_info);
}
void WebPluginImpl::didReceiveResponse(
const WebKit::WebURLResponse& response) {
DCHECK(!document_loader_);
document_loader_ = new PPB_URLLoader_Impl(instance_, true);
document_loader_->didReceiveResponse(NULL, response);
if (!instance_->HandleDocumentLoad(document_loader_))
document_loader_ = NULL;
}
void WebPluginImpl::didReceiveData(const char* data, int data_length) {
if (document_loader_)
document_loader_->didReceiveData(NULL, data, data_length, data_length);
}
void WebPluginImpl::didFinishLoading() {
if (document_loader_) {
document_loader_->didFinishLoading(NULL, 0);
document_loader_ = NULL;
}
}
void WebPluginImpl::didFailLoading(const WebKit::WebURLError& error) {
if (document_loader_) {
document_loader_->didFail(NULL, error);
document_loader_ = NULL;
}
}
void WebPluginImpl::didFinishLoadingFrameRequest(const WebKit::WebURL& url,
void* notify_data) {
}
void WebPluginImpl::didFailLoadingFrameRequest(
const WebKit::WebURL& url,
void* notify_data,
const WebKit::WebURLError& error) {
}
bool WebPluginImpl::hasSelection() const {
return !selectionAsText().isEmpty();
}
WebString WebPluginImpl::selectionAsText() const {
return instance_->GetSelectedText(false);
}
WebString WebPluginImpl::selectionAsMarkup() const {
return instance_->GetSelectedText(true);
}
WebURL WebPluginImpl::linkAtPosition(const WebPoint& position) const {
return GURL(instance_->GetLinkAtPosition(position));
}
void WebPluginImpl::setZoomLevel(double level, bool text_only) {
instance_->Zoom(WebView::zoomLevelToZoomFactor(level), text_only);
}
bool WebPluginImpl::startFind(const WebKit::WebString& search_text,
bool case_sensitive,
int identifier) {
return instance_->StartFind(search_text, case_sensitive, identifier);
}
void WebPluginImpl::selectFindResult(bool forward) {
instance_->SelectFindResult(forward);
}
void WebPluginImpl::stopFind() {
instance_->StopFind();
}
bool WebPluginImpl::supportsPaginatedPrint() {
return instance_->SupportsPrintInterface();
}
int WebPluginImpl::printBegin(const WebKit::WebRect& printable_area,
int printer_dpi) {
return instance_->PrintBegin(printable_area, printer_dpi);
}
bool WebPluginImpl::printPage(int page_number,
WebKit::WebCanvas* canvas) {
return instance_->PrintPage(page_number, canvas);
}
void WebPluginImpl::printEnd() {
return instance_->PrintEnd();
}
} // namespace ppapi
} // namespace webkit
<commit_msg>Fix re-entrancy case in WebPluginImpl::scriptableObject.<commit_after>// Copyright (c) 2011 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "webkit/plugins/ppapi/ppapi_webplugin_impl.h"
#include <cmath>
#include "base/message_loop.h"
#include "googleurl/src/gurl.h"
#include "ppapi/c/pp_var.h"
#include "third_party/WebKit/Source/WebKit/chromium/public/WebBindings.h"
#include "third_party/WebKit/Source/WebKit/chromium/public/WebPluginParams.h"
#include "third_party/WebKit/Source/WebKit/chromium/public/WebPoint.h"
#include "third_party/WebKit/Source/WebKit/chromium/public/WebRect.h"
#include "third_party/WebKit/Source/WebKit/chromium/public/WebView.h"
#include "webkit/plugins/ppapi/message_channel.h"
#include "webkit/plugins/ppapi/plugin_module.h"
#include "webkit/plugins/ppapi/ppapi_plugin_instance.h"
#include "webkit/plugins/ppapi/ppb_url_loader_impl.h"
#include "webkit/plugins/ppapi/var.h"
using WebKit::WebCanvas;
using WebKit::WebPluginContainer;
using WebKit::WebPluginParams;
using WebKit::WebPoint;
using WebKit::WebRect;
using WebKit::WebString;
using WebKit::WebURL;
using WebKit::WebVector;
using WebKit::WebView;
namespace webkit {
namespace ppapi {
struct WebPluginImpl::InitData {
scoped_refptr<PluginModule> module;
base::WeakPtr<PluginDelegate> delegate;
std::vector<std::string> arg_names;
std::vector<std::string> arg_values;
GURL url;
};
WebPluginImpl::WebPluginImpl(
PluginModule* plugin_module,
const WebPluginParams& params,
const base::WeakPtr<PluginDelegate>& plugin_delegate)
: init_data_(new InitData()),
full_frame_(params.loadManually) {
DCHECK(plugin_module);
init_data_->module = plugin_module;
init_data_->delegate = plugin_delegate;
for (size_t i = 0; i < params.attributeNames.size(); ++i) {
init_data_->arg_names.push_back(params.attributeNames[i].utf8());
init_data_->arg_values.push_back(params.attributeValues[i].utf8());
}
init_data_->url = params.url;
}
WebPluginImpl::~WebPluginImpl() {
}
bool WebPluginImpl::initialize(WebPluginContainer* container) {
// The plugin delegate may have gone away.
if (!init_data_->delegate)
return false;
instance_ = init_data_->module->CreateInstance(init_data_->delegate);
if (!instance_)
return false;
bool success = instance_->Initialize(container,
init_data_->arg_names,
init_data_->arg_values,
init_data_->url,
full_frame_);
if (!success) {
instance_->Delete();
instance_ = NULL;
return false;
}
init_data_.reset();
return true;
}
void WebPluginImpl::destroy() {
if (instance_) {
instance_->Delete();
instance_ = NULL;
}
MessageLoop::current()->DeleteSoon(FROM_HERE, this);
}
NPObject* WebPluginImpl::scriptableObject() {
scoped_refptr<ObjectVar> object(
ObjectVar::FromPPVar(instance_->GetInstanceObject()));
// GetInstanceObject talked to the plugin which may have removed the instance
// from the DOM, in which case instance_ would be NULL now.
if (!instance_)
return NULL;
// If there's an InstanceObject, tell the Instance's MessageChannel to pass
// any non-postMessage calls to it.
if (object) {
instance_->message_channel().SetPassthroughObject(object->np_object());
}
NPObject* message_channel_np_object(instance_->message_channel().np_object());
// The object is expected to be retained before it is returned.
WebKit::WebBindings::retainObject(message_channel_np_object);
return message_channel_np_object;
}
bool WebPluginImpl::getFormValue(WebString* value) {
return false;
}
void WebPluginImpl::paint(WebCanvas* canvas, const WebRect& rect) {
if (!instance_->IsFullscreenOrPending())
instance_->Paint(canvas, plugin_rect_, rect);
}
void WebPluginImpl::updateGeometry(
const WebRect& window_rect,
const WebRect& clip_rect,
const WebVector<WebRect>& cut_outs_rects,
bool is_visible) {
plugin_rect_ = window_rect;
if (!instance_->IsFullscreenOrPending())
instance_->ViewChanged(plugin_rect_, clip_rect);
}
void WebPluginImpl::updateFocus(bool focused) {
instance_->SetWebKitFocus(focused);
}
void WebPluginImpl::updateVisibility(bool visible) {
}
bool WebPluginImpl::acceptsInputEvents() {
return true;
}
bool WebPluginImpl::handleInputEvent(const WebKit::WebInputEvent& event,
WebKit::WebCursorInfo& cursor_info) {
if (instance_->IsFullscreenOrPending())
return false;
return instance_->HandleInputEvent(event, &cursor_info);
}
void WebPluginImpl::didReceiveResponse(
const WebKit::WebURLResponse& response) {
DCHECK(!document_loader_);
document_loader_ = new PPB_URLLoader_Impl(instance_, true);
document_loader_->didReceiveResponse(NULL, response);
if (!instance_->HandleDocumentLoad(document_loader_))
document_loader_ = NULL;
}
void WebPluginImpl::didReceiveData(const char* data, int data_length) {
if (document_loader_)
document_loader_->didReceiveData(NULL, data, data_length, data_length);
}
void WebPluginImpl::didFinishLoading() {
if (document_loader_) {
document_loader_->didFinishLoading(NULL, 0);
document_loader_ = NULL;
}
}
void WebPluginImpl::didFailLoading(const WebKit::WebURLError& error) {
if (document_loader_) {
document_loader_->didFail(NULL, error);
document_loader_ = NULL;
}
}
void WebPluginImpl::didFinishLoadingFrameRequest(const WebKit::WebURL& url,
void* notify_data) {
}
void WebPluginImpl::didFailLoadingFrameRequest(
const WebKit::WebURL& url,
void* notify_data,
const WebKit::WebURLError& error) {
}
bool WebPluginImpl::hasSelection() const {
return !selectionAsText().isEmpty();
}
WebString WebPluginImpl::selectionAsText() const {
return instance_->GetSelectedText(false);
}
WebString WebPluginImpl::selectionAsMarkup() const {
return instance_->GetSelectedText(true);
}
WebURL WebPluginImpl::linkAtPosition(const WebPoint& position) const {
return GURL(instance_->GetLinkAtPosition(position));
}
void WebPluginImpl::setZoomLevel(double level, bool text_only) {
instance_->Zoom(WebView::zoomLevelToZoomFactor(level), text_only);
}
bool WebPluginImpl::startFind(const WebKit::WebString& search_text,
bool case_sensitive,
int identifier) {
return instance_->StartFind(search_text, case_sensitive, identifier);
}
void WebPluginImpl::selectFindResult(bool forward) {
instance_->SelectFindResult(forward);
}
void WebPluginImpl::stopFind() {
instance_->StopFind();
}
bool WebPluginImpl::supportsPaginatedPrint() {
return instance_->SupportsPrintInterface();
}
int WebPluginImpl::printBegin(const WebKit::WebRect& printable_area,
int printer_dpi) {
return instance_->PrintBegin(printable_area, printer_dpi);
}
bool WebPluginImpl::printPage(int page_number,
WebKit::WebCanvas* canvas) {
return instance_->PrintPage(page_number, canvas);
}
void WebPluginImpl::printEnd() {
return instance_->PrintEnd();
}
} // namespace ppapi
} // namespace webkit
<|endoftext|>
|
<commit_before>/*
* yosys -- Yosys Open SYnthesis Suite
*
* Copyright (C) 2012 Clifford Wolf <clifford@clifford.at>
*
* Permission to use, copy, modify, and/or distribute this software for any
* purpose with or without fee is hereby granted, provided that the above
* copyright notice and this permission notice appear in all copies.
*
* THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
* WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
* MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
* ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
* WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
* ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
* OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
*
* ---
*
* The Verilog frontend.
*
* This frontend is using the AST frontend library (see frontends/ast/).
* Thus this frontend does not generate RTLIL code directly but creates an
* AST directly from the Verilog parse tree and then passes this AST to
* the AST frontend library.
*
*/
#include "verilog_frontend.h"
#include "kernel/register.h"
#include "kernel/log.h"
#include "libs/sha1/sha1.h"
#include <sstream>
#include <stdarg.h>
#include <assert.h>
using namespace VERILOG_FRONTEND;
// use the Verilog bison/flex parser to generate an AST and use AST::process() to convert it to RTLIL
static std::vector<std::string> verilog_defaults;
static std::list<std::vector<std::string>> verilog_defaults_stack;
struct VerilogFrontend : public Frontend {
VerilogFrontend() : Frontend("verilog", "read modules from verilog file") { }
virtual void help()
{
// |---v---|---v---|---v---|---v---|---v---|---v---|---v---|---v---|---v---|---v---|
log("\n");
log(" read_verilog [filename]\n");
log("\n");
log("Load modules from a verilog file to the current design. A large subset of\n");
log("Verilog-2005 is supported.\n");
log("\n");
log(" -dump_ast1\n");
log(" dump abstract syntax tree (before simplification)\n");
log("\n");
log(" -dump_ast2\n");
log(" dump abstract syntax tree (after simplification)\n");
log("\n");
log(" -dump_vlog\n");
log(" dump ast as verilog code (after simplification)\n");
log("\n");
log(" -yydebug\n");
log(" enable parser debug output\n");
log("\n");
log(" -nolatches\n");
log(" usually latches are synthesized into logic loops\n");
log(" this option prohibits this and sets the output to 'x'\n");
log(" in what would be the latches hold condition\n");
log("\n");
log(" this behavior can also be achieved by setting the\n");
log(" 'nolatches' attribute on the respective module or\n");
log(" always block.\n");
log("\n");
log(" -nomem2reg\n");
log(" under certain conditions memories are converted to registers\n");
log(" early during simplification to ensure correct handling of\n");
log(" complex corner cases. this option disables this behavior.\n");
log("\n");
log(" this can also be achieved by setting the 'nomem2reg'\n");
log(" attribute on the respective module or register.\n");
log("\n");
log(" -mem2reg\n");
log(" always convert memories to registers. this can also be\n");
log(" achieved by setting the 'mem2reg' attribute on the respective\n");
log(" module or register.\n");
log("\n");
log(" -ppdump\n");
log(" dump verilog code after pre-processor\n");
log("\n");
log(" -nopp\n");
log(" do not run the pre-processor\n");
log("\n");
log(" -lib\n");
log(" only create empty blackbox modules\n");
log("\n");
log(" -noopt\n");
log(" don't perform basic optimizations (such as const folding) in the\n");
log(" high-level front-end.\n");
log("\n");
log(" -icells\n");
log(" interpret cell types starting with '$' as internal cell types\n");
log("\n");
log(" -ignore_redef\n");
log(" ignore re-definitions of modules. (the default behavior is to\n");
log(" create an error message.)\n");
log("\n");
log(" -Dname[=definition]\n");
log(" define the preprocessor symbol 'name' and set its optional value\n");
log(" 'definition'\n");
log("\n");
log(" -Idir\n");
log(" add 'dir' to the directories which are used when searching include\n");
log(" files\n");
log("\n");
log("The command 'verilog_defaults' can be used to register default options for\n");
log("subsequent calls to 'read_verilog'.\n");
log("\n");
}
virtual void execute(FILE *&f, std::string filename, std::vector<std::string> args, RTLIL::Design *design)
{
bool flag_dump_ast1 = false;
bool flag_dump_ast2 = false;
bool flag_dump_vlog = false;
bool flag_nolatches = false;
bool flag_nomem2reg = false;
bool flag_mem2reg = false;
bool flag_ppdump = false;
bool flag_nopp = false;
bool flag_lib = false;
bool flag_noopt = false;
bool flag_icells = false;
bool flag_ignore_redef = false;
std::map<std::string, std::string> defines_map;
std::list<std::string> include_dirs;
frontend_verilog_yydebug = false;
log_header("Executing Verilog-2005 frontend.\n");
args.insert(args.begin()+1, verilog_defaults.begin(), verilog_defaults.end());
size_t argidx;
for (argidx = 1; argidx < args.size(); argidx++) {
std::string arg = args[argidx];
if (arg == "-dump_ast1") {
flag_dump_ast1 = true;
continue;
}
if (arg == "-dump_ast2") {
flag_dump_ast2 = true;
continue;
}
if (arg == "-dump_vlog") {
flag_dump_vlog = true;
continue;
}
if (arg == "-yydebug") {
frontend_verilog_yydebug = true;
continue;
}
if (arg == "-nolatches") {
flag_nolatches = true;
continue;
}
if (arg == "-nomem2reg") {
flag_nomem2reg = true;
continue;
}
if (arg == "-mem2reg") {
flag_mem2reg = true;
continue;
}
if (arg == "-ppdump") {
flag_ppdump = true;
continue;
}
if (arg == "-nopp") {
flag_nopp = true;
continue;
}
if (arg == "-lib") {
flag_lib = true;
continue;
}
if (arg == "-noopt") {
flag_noopt = true;
continue;
}
if (arg == "-icells") {
flag_icells = true;
continue;
}
if (arg == "-ignore_redef") {
flag_ignore_redef = true;
continue;
}
if (arg == "-D" && argidx+1 < args.size()) {
std::string name = args[++argidx], value;
size_t equal = name.find('=', 2);
if (equal != std::string::npos) {
value = arg.substr(equal+1);
name = arg.substr(0, equal);
}
defines_map[name] = value;
continue;
}
if (arg.compare(0, 2, "-D") == 0) {
size_t equal = arg.find('=', 2);
std::string name = arg.substr(2, equal-2);
std::string value;
if (equal != std::string::npos)
value = arg.substr(equal+1);
defines_map[name] = value;
continue;
}
if (arg == "-I" && argidx+1 < args.size()) {
include_dirs.push_back(args[++argidx]);
continue;
}
if (arg.compare(0, 2, "-I") == 0) {
include_dirs.push_back(arg.substr(2));
continue;
}
break;
}
extra_args(f, filename, args, argidx);
log("Parsing Verilog input from `%s' to AST representation.\n", filename.c_str());
AST::current_filename = filename;
AST::set_line_num = &frontend_verilog_yyset_lineno;
AST::get_line_num = &frontend_verilog_yyget_lineno;
current_ast = new AST::AstNode(AST::AST_DESIGN);
FILE *fp = f;
std::string code_after_preproc;
if (!flag_nopp) {
code_after_preproc = frontend_verilog_preproc(f, filename, defines_map, include_dirs);
if (flag_ppdump)
log("-- Verilog code after preprocessor --\n%s-- END OF DUMP --\n", code_after_preproc.c_str());
fp = fmemopen((void*)code_after_preproc.c_str(), code_after_preproc.size(), "r");
}
frontend_verilog_yyset_lineno(1);
frontend_verilog_yyrestart(fp);
frontend_verilog_yyparse();
frontend_verilog_yylex_destroy();
AST::process(design, current_ast, flag_dump_ast1, flag_dump_ast2, flag_dump_vlog, flag_nolatches, flag_nomem2reg, flag_mem2reg, flag_lib, flag_noopt, flag_icells, flag_ignore_redef);
if (!flag_nopp)
fclose(fp);
delete current_ast;
current_ast = NULL;
log("Successfully finished Verilog frontend.\n");
}
} VerilogFrontend;
// the yyerror function used by bison to report parser errors
void frontend_verilog_yyerror(char const *fmt, ...)
{
va_list ap;
char buffer[1024];
char *p = buffer;
p += snprintf(p, buffer + sizeof(buffer) - p, "Parser error in line %s:%d: ",
AST::current_filename.c_str(), frontend_verilog_yyget_lineno());
va_start(ap, fmt);
p += vsnprintf(p, buffer + sizeof(buffer) - p, fmt, ap);
va_end(ap);
p += snprintf(p, buffer + sizeof(buffer) - p, "\n");
log_error("%s", buffer);
exit(1);
}
struct VerilogDefaults : public Pass {
VerilogDefaults() : Pass("verilog_defaults", "set default options for read_verilog") { }
virtual void help()
{
// |---v---|---v---|---v---|---v---|---v---|---v---|---v---|---v---|---v---|---v---|
log("\n");
log(" verilog_defaults -add [options]\n");
log("\n");
log("Add the sepcified options to the list of default options to read_verilog.\n");
log("\n");
log("\n");
log(" verilog_defaults -clear");
log("\n");
log("Clear the list of verilog default options.\n");
log("\n");
log("\n");
log(" verilog_defaults -push");
log(" verilog_defaults -pop");
log("\n");
log("Push or pop the list of default options to a stack. Note that -push does\n");
log("not imply -clear.\n");
log("\n");
}
virtual void execute(std::vector<std::string> args, RTLIL::Design*)
{
if (args.size() == 0)
cmd_error(args, 1, "Missing argument.");
if (args[1] == "-add") {
verilog_defaults.insert(verilog_defaults.end(), args.begin()+2, args.end());
return;
}
if (args.size() != 2)
cmd_error(args, 2, "Extra argument.");
if (args[1] == "-clear") {
verilog_defaults.clear();
return;
}
if (args[1] == "-push") {
verilog_defaults_stack.push_back(verilog_defaults);
return;
}
if (args[1] == "-pop") {
if (verilog_defaults_stack.empty()) {
verilog_defaults.clear();
} else {
verilog_defaults.swap(verilog_defaults_stack.back());
verilog_defaults_stack.pop_back();
}
return;
}
}
} VerilogDefaults;
<commit_msg>Added read_verilog -setattr<commit_after>/*
* yosys -- Yosys Open SYnthesis Suite
*
* Copyright (C) 2012 Clifford Wolf <clifford@clifford.at>
*
* Permission to use, copy, modify, and/or distribute this software for any
* purpose with or without fee is hereby granted, provided that the above
* copyright notice and this permission notice appear in all copies.
*
* THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
* WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
* MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
* ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
* WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
* ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
* OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
*
* ---
*
* The Verilog frontend.
*
* This frontend is using the AST frontend library (see frontends/ast/).
* Thus this frontend does not generate RTLIL code directly but creates an
* AST directly from the Verilog parse tree and then passes this AST to
* the AST frontend library.
*
*/
#include "verilog_frontend.h"
#include "kernel/register.h"
#include "kernel/log.h"
#include "libs/sha1/sha1.h"
#include <sstream>
#include <stdarg.h>
#include <assert.h>
using namespace VERILOG_FRONTEND;
// use the Verilog bison/flex parser to generate an AST and use AST::process() to convert it to RTLIL
static std::vector<std::string> verilog_defaults;
static std::list<std::vector<std::string>> verilog_defaults_stack;
struct VerilogFrontend : public Frontend {
VerilogFrontend() : Frontend("verilog", "read modules from verilog file") { }
virtual void help()
{
// |---v---|---v---|---v---|---v---|---v---|---v---|---v---|---v---|---v---|---v---|
log("\n");
log(" read_verilog [filename]\n");
log("\n");
log("Load modules from a verilog file to the current design. A large subset of\n");
log("Verilog-2005 is supported.\n");
log("\n");
log(" -dump_ast1\n");
log(" dump abstract syntax tree (before simplification)\n");
log("\n");
log(" -dump_ast2\n");
log(" dump abstract syntax tree (after simplification)\n");
log("\n");
log(" -dump_vlog\n");
log(" dump ast as verilog code (after simplification)\n");
log("\n");
log(" -yydebug\n");
log(" enable parser debug output\n");
log("\n");
log(" -nolatches\n");
log(" usually latches are synthesized into logic loops\n");
log(" this option prohibits this and sets the output to 'x'\n");
log(" in what would be the latches hold condition\n");
log("\n");
log(" this behavior can also be achieved by setting the\n");
log(" 'nolatches' attribute on the respective module or\n");
log(" always block.\n");
log("\n");
log(" -nomem2reg\n");
log(" under certain conditions memories are converted to registers\n");
log(" early during simplification to ensure correct handling of\n");
log(" complex corner cases. this option disables this behavior.\n");
log("\n");
log(" this can also be achieved by setting the 'nomem2reg'\n");
log(" attribute on the respective module or register.\n");
log("\n");
log(" -mem2reg\n");
log(" always convert memories to registers. this can also be\n");
log(" achieved by setting the 'mem2reg' attribute on the respective\n");
log(" module or register.\n");
log("\n");
log(" -ppdump\n");
log(" dump verilog code after pre-processor\n");
log("\n");
log(" -nopp\n");
log(" do not run the pre-processor\n");
log("\n");
log(" -lib\n");
log(" only create empty blackbox modules\n");
log("\n");
log(" -noopt\n");
log(" don't perform basic optimizations (such as const folding) in the\n");
log(" high-level front-end.\n");
log("\n");
log(" -icells\n");
log(" interpret cell types starting with '$' as internal cell types\n");
log("\n");
log(" -ignore_redef\n");
log(" ignore re-definitions of modules. (the default behavior is to\n");
log(" create an error message.)\n");
log("\n");
log(" -setattr <attribute_name>\n");
log(" set the specified attribute (to the value 1) on all loaded modules\n");
log("\n");
log(" -Dname[=definition]\n");
log(" define the preprocessor symbol 'name' and set its optional value\n");
log(" 'definition'\n");
log("\n");
log(" -Idir\n");
log(" add 'dir' to the directories which are used when searching include\n");
log(" files\n");
log("\n");
log("The command 'verilog_defaults' can be used to register default options for\n");
log("subsequent calls to 'read_verilog'.\n");
log("\n");
}
virtual void execute(FILE *&f, std::string filename, std::vector<std::string> args, RTLIL::Design *design)
{
bool flag_dump_ast1 = false;
bool flag_dump_ast2 = false;
bool flag_dump_vlog = false;
bool flag_nolatches = false;
bool flag_nomem2reg = false;
bool flag_mem2reg = false;
bool flag_ppdump = false;
bool flag_nopp = false;
bool flag_lib = false;
bool flag_noopt = false;
bool flag_icells = false;
bool flag_ignore_redef = false;
std::map<std::string, std::string> defines_map;
std::list<std::string> include_dirs;
std::list<std::string> attributes;
frontend_verilog_yydebug = false;
log_header("Executing Verilog-2005 frontend.\n");
args.insert(args.begin()+1, verilog_defaults.begin(), verilog_defaults.end());
size_t argidx;
for (argidx = 1; argidx < args.size(); argidx++) {
std::string arg = args[argidx];
if (arg == "-dump_ast1") {
flag_dump_ast1 = true;
continue;
}
if (arg == "-dump_ast2") {
flag_dump_ast2 = true;
continue;
}
if (arg == "-dump_vlog") {
flag_dump_vlog = true;
continue;
}
if (arg == "-yydebug") {
frontend_verilog_yydebug = true;
continue;
}
if (arg == "-nolatches") {
flag_nolatches = true;
continue;
}
if (arg == "-nomem2reg") {
flag_nomem2reg = true;
continue;
}
if (arg == "-mem2reg") {
flag_mem2reg = true;
continue;
}
if (arg == "-ppdump") {
flag_ppdump = true;
continue;
}
if (arg == "-nopp") {
flag_nopp = true;
continue;
}
if (arg == "-lib") {
flag_lib = true;
continue;
}
if (arg == "-noopt") {
flag_noopt = true;
continue;
}
if (arg == "-icells") {
flag_icells = true;
continue;
}
if (arg == "-ignore_redef") {
flag_ignore_redef = true;
continue;
}
if (arg == "-setattr" && argidx+1 < args.size()) {
attributes.push_back(RTLIL::escape_id(args[++argidx]));
continue;
}
if (arg == "-D" && argidx+1 < args.size()) {
std::string name = args[++argidx], value;
size_t equal = name.find('=', 2);
if (equal != std::string::npos) {
value = arg.substr(equal+1);
name = arg.substr(0, equal);
}
defines_map[name] = value;
continue;
}
if (arg.compare(0, 2, "-D") == 0) {
size_t equal = arg.find('=', 2);
std::string name = arg.substr(2, equal-2);
std::string value;
if (equal != std::string::npos)
value = arg.substr(equal+1);
defines_map[name] = value;
continue;
}
if (arg == "-I" && argidx+1 < args.size()) {
include_dirs.push_back(args[++argidx]);
continue;
}
if (arg.compare(0, 2, "-I") == 0) {
include_dirs.push_back(arg.substr(2));
continue;
}
break;
}
extra_args(f, filename, args, argidx);
log("Parsing Verilog input from `%s' to AST representation.\n", filename.c_str());
AST::current_filename = filename;
AST::set_line_num = &frontend_verilog_yyset_lineno;
AST::get_line_num = &frontend_verilog_yyget_lineno;
current_ast = new AST::AstNode(AST::AST_DESIGN);
FILE *fp = f;
std::string code_after_preproc;
if (!flag_nopp) {
code_after_preproc = frontend_verilog_preproc(f, filename, defines_map, include_dirs);
if (flag_ppdump)
log("-- Verilog code after preprocessor --\n%s-- END OF DUMP --\n", code_after_preproc.c_str());
fp = fmemopen((void*)code_after_preproc.c_str(), code_after_preproc.size(), "r");
}
frontend_verilog_yyset_lineno(1);
frontend_verilog_yyrestart(fp);
frontend_verilog_yyparse();
frontend_verilog_yylex_destroy();
for (auto &child : current_ast->children) {
log_assert(child->type == AST::AST_MODULE);
for (auto &attr : attributes)
if (child->attributes.count(attr) == 0)
child->attributes[attr] = AST::AstNode::mkconst_int(1, false);
}
AST::process(design, current_ast, flag_dump_ast1, flag_dump_ast2, flag_dump_vlog, flag_nolatches, flag_nomem2reg, flag_mem2reg, flag_lib, flag_noopt, flag_icells, flag_ignore_redef);
if (!flag_nopp)
fclose(fp);
delete current_ast;
current_ast = NULL;
log("Successfully finished Verilog frontend.\n");
}
} VerilogFrontend;
// the yyerror function used by bison to report parser errors
void frontend_verilog_yyerror(char const *fmt, ...)
{
va_list ap;
char buffer[1024];
char *p = buffer;
p += snprintf(p, buffer + sizeof(buffer) - p, "Parser error in line %s:%d: ",
AST::current_filename.c_str(), frontend_verilog_yyget_lineno());
va_start(ap, fmt);
p += vsnprintf(p, buffer + sizeof(buffer) - p, fmt, ap);
va_end(ap);
p += snprintf(p, buffer + sizeof(buffer) - p, "\n");
log_error("%s", buffer);
exit(1);
}
struct VerilogDefaults : public Pass {
VerilogDefaults() : Pass("verilog_defaults", "set default options for read_verilog") { }
virtual void help()
{
// |---v---|---v---|---v---|---v---|---v---|---v---|---v---|---v---|---v---|---v---|
log("\n");
log(" verilog_defaults -add [options]\n");
log("\n");
log("Add the sepcified options to the list of default options to read_verilog.\n");
log("\n");
log("\n");
log(" verilog_defaults -clear");
log("\n");
log("Clear the list of verilog default options.\n");
log("\n");
log("\n");
log(" verilog_defaults -push");
log(" verilog_defaults -pop");
log("\n");
log("Push or pop the list of default options to a stack. Note that -push does\n");
log("not imply -clear.\n");
log("\n");
}
virtual void execute(std::vector<std::string> args, RTLIL::Design*)
{
if (args.size() == 0)
cmd_error(args, 1, "Missing argument.");
if (args[1] == "-add") {
verilog_defaults.insert(verilog_defaults.end(), args.begin()+2, args.end());
return;
}
if (args.size() != 2)
cmd_error(args, 2, "Extra argument.");
if (args[1] == "-clear") {
verilog_defaults.clear();
return;
}
if (args[1] == "-push") {
verilog_defaults_stack.push_back(verilog_defaults);
return;
}
if (args[1] == "-pop") {
if (verilog_defaults_stack.empty()) {
verilog_defaults.clear();
} else {
verilog_defaults.swap(verilog_defaults_stack.back());
verilog_defaults_stack.pop_back();
}
return;
}
}
} VerilogDefaults;
<|endoftext|>
|
<commit_before>#include <iostream>
using namespace std;
struct Numero {
int cifras[30];
int ncifras;
};
int main() {
int tam;
string s;
Numero N;
cin >> s;
int tam = s.size();
for (int i = 0; i < tam; ++i) {
char digito = s[i];
}
}<commit_msg>the structure of proyect is completed<commit_after>#include <iostream>
using namespace std;
struct Numero {
int cifras[30];
int ncifras;
};
void escribir_numero(const Numero& N) {
for (int i = N.ncifras - 1; i >= 0; --i) {
cout << N.cifras[i];
}
}
void leer_numero(Numero& N) {
int tam;
string s;
cin >> s;
int tam = s.size();
for (int i = 0; i < tam; ++i) {
char digito = s[i];
N.cifras[tam - 1 - i] = int(digito) - int('0');
}
N.ncifras = tam;
}
int main() {
Numero N;
leer_numero(N);
escribir_numero(N);
cout << endl;
}<|endoftext|>
|
<commit_before>
#include <Onsang/utility.hpp>
#include <Onsang/detail/gr_ceformat.hpp>
#include <Onsang/Log.hpp>
#include <Onsang/asio.hpp>
#include <Onsang/Net/CmdStreamer.hpp>
#include <Hord/Error.hpp>
#include <Hord/ErrorCode.hpp>
#include <duct/IO/arithmetic.hpp>
#include <cassert>
#include <mutex>
#include <iomanip>
#include <iostream>
namespace Onsang {
namespace Net {
// class CmdStreamer implementation
#define ONSANG_SCOPE_CLASS Net::CmdStreamer
namespace {
enum : unsigned {
// uint32 size
// uint32 type
msg_header_size = 8u,
// stage : 8
// cmd : 24
mask_type_stage = 0x000000FF,
mask_type_cmd = 0xFFFFFF00
};
static constexpr ceformat::Format const
s_err_command_type_invalid{
": command type %#08x is invalid\n"
},
s_err_stage_type_invalid{
": stage type %#02x is invalid for command type %#08x\n"
}
;
} // anonymous namespace
#define ONSANG_SCOPE_FUNC read_header
bool
CmdStreamer::read_header() {
std::istream stream{&m_streambuf_in};
std::size_t const size
= duct::IO::read_arithmetic<uint32_t>(
stream,
duct::Endian::little
);
uint32_t const type
= duct::IO::read_arithmetic<uint32_t>(
stream,
duct::Endian::little
);
if (stream.fail()) {
return false;
} else {
m_incoming_size = size;
m_incoming_type = type;
return true;
}
}
#undef ONSANG_SCOPE_FUNC
#define ONSANG_SCOPE_FUNC read_stage
bool
CmdStreamer::read_stage() {
auto const command_type = static_cast<Hord::Cmd::Type>(
m_incoming_type & mask_type_cmd
);
auto const stage_type = static_cast<Hord::Cmd::StageType>(
m_incoming_type & mask_type_stage
);
Hord::Cmd::StageUPtr stage_uptr;
Hord::Cmd::type_info const* const
type_info = m_driver.get_command_type_info(
command_type
);
if (!type_info) {
Log::acquire(Log::error)
<< Log::Pre::current << ONSANG_SCOPE_FQN_STR_LIT
<< ceformat::write_sentinel<
s_err_command_type_invalid
>(
enum_cast(command_type)
)
;
return false;
}
try {
stage_uptr.reset(type_info->construct_stage(stage_type));
std::istream stream{&m_streambuf_in};
stage_uptr->deserialize(stream);
} catch (Hord::Error& ex) {
stage_uptr.reset();
switch (ex.get_code()) {
case Hord::ErrorCode::cmd_construct_stage_type_invalid:
Log::acquire(Log::error)
<< Log::Pre::current << ONSANG_SCOPE_FQN_STR_LIT
<< ceformat::write_sentinel<s_err_stage_type_invalid>(
enum_cast(stage_type),
enum_cast(command_type)
)
;
return false;
// IO error or malformed data
default:
return false;
}
} catch (...) {
throw;
}
std::size_t const remaining = m_streambuf_in.get_remaining();
if (0u < remaining) {
Log::acquire(Log::debug)
<< Log::Pre::current << ONSANG_SCOPE_FQN_STR_LIT
<< ": "
<< remaining
<< " bytes left in buffer after stage deserialization\n"
;
}
{
std::lock_guard<std::mutex> m_lock{m_stage_buffer_mutex};
m_stage_buffer.emplace_back(std::move(stage_uptr));
m_sig_have_stages.store(true);
}
return true;
}
#undef ONSANG_SCOPE_FUNC
#define ONSANG_SCOPE_FUNC chain_read_header
void
CmdStreamer::chain_read_header() {
m_incoming_size = 0u;
assert(m_streambuf_in.reset(msg_header_size));
asio::async_read(
m_socket,
asio::buffer(
m_streambuf_in.get_buffer().data(),
msg_header_size
),
asio::transfer_exactly(msg_header_size),
[this](
boost::system::error_code const ec,
std::size_t /*length*/
) {
if (!ec) {
m_streambuf_in.commit_direct(msg_header_size);
read_header();
chain_read_stage();
} else {
halt();
}
}
);
}
#undef ONSANG_SCOPE_FUNC
#define ONSANG_SCOPE_FUNC chain_read_stage
void
CmdStreamer::chain_read_stage() {
assert(0u < m_incoming_size);
assert(0u != m_incoming_type);
assert(m_streambuf_in.reset(m_incoming_size));
asio::async_read(
m_socket,
asio::buffer(
m_streambuf_in.get_buffer().data(),
m_incoming_size
),
asio::transfer_exactly(m_incoming_size),
[this](
boost::system::error_code const ec,
std::size_t /*length*/
) {
if (!ec) {
m_streambuf_in.commit_direct(m_incoming_size);
read_stage();
chain_read_header();
} else {
halt();
}
}
);
}
#undef ONSANG_SCOPE_FUNC
#define ONSANG_SCOPE_FUNC chain_flush_output
void
CmdStreamer::chain_flush_output() {
assert(0u < m_outgoing_size);
asio::async_write(
m_socket,
asio::buffer(
make_const(m_streambuf_out).get_buffer().data(),
m_outgoing_size
),
asio::transfer_exactly(m_incoming_size),
[this](
boost::system::error_code const ec,
std::size_t /*length*/
) {
m_sig_pending_output.store(false);
m_outgoing_size = 0u;
if (ec) {
halt();
}
}
);
}
#undef ONSANG_SCOPE_FUNC
// operations
void
CmdStreamer::halt() noexcept {
m_socket.get_io_service().stop();
}
#define ONSANG_SCOPE_FUNC run
void
CmdStreamer::run() {
auto& io_service = m_socket.get_io_service();
try {
while (!io_service.stopped()) {
chain_read_header();
io_service.run();
}
} catch (std::exception& ex) {
Log::acquire(Log::error)
<< Log::Pre::current << ONSANG_SCOPE_FQN_STR_LIT
<< ": caught exception from io_service::run(): "
<< ex.what()
<< "\n"
;
throw;
}
}
#undef ONSANG_SCOPE_FUNC
#define ONSANG_SCOPE_FUNC context_input
bool
CmdStreamer::context_input(
Hord::System::Context& context
) {
if (!m_sig_have_stages.load()) {
return false;
}
{
std::lock_guard<std::mutex> m_lock{m_stage_buffer_mutex};
for (auto& stage_uptr : m_stage_buffer) {
context.push_input(stage_uptr);
}
m_stage_buffer.clear();
m_sig_have_stages.store(false);
}
return true;
}
#undef ONSANG_SCOPE_FUNC
#define ONSANG_SCOPE_FUNC context_output
bool
CmdStreamer::context_output(
Hord::System::Context& context
) {
if (
0 == context.get_output().size() ||
m_sig_pending_output.load()
) {
return false;
}
m_streambuf_out.reset(
msg_header_size + (m_streambuf_out.get_max_size() >> 2)
);
std::ostream stream{&m_streambuf_out};
// Seek past header to reserve it; we need the size of the
// stage payload
stream.seekp(msg_header_size);
// data
auto& stage = *context.get_output().front();
stage.serialize(
stream
);
// Can't use buffer.size() later because it might've grown
// beyond our write amount
m_outgoing_size = m_streambuf_out.get_sequence_size();
// header
stream.seekp(0);
std::size_t const h_size = m_outgoing_size - msg_header_size;
duct::IO::write_arithmetic<uint32_t>(
stream,
static_cast<uint32_t>(h_size),
duct::Endian::little
);
uint32_t const h_type
= enum_cast(stage.get_stage_type())
| enum_cast(stage.get_command_type())
;
duct::IO::write_arithmetic<uint32_t>(
stream,
h_type,
duct::Endian::little
);
if (stream.fail()) {
return false;
}
m_streambuf_out.commit();
context.get_output().pop_front();
m_sig_pending_output.store(true);
m_socket.get_io_service().post(
[this]() {
chain_flush_output();
}
);
return true;
}
#undef ONSANG_SCOPE_FUNC
#undef ONSANG_SCOPE_CLASS // Onsang::Net::CmdStreamer
} // namespace Net
} // namespace Onsang
<commit_msg>Net/CmdStreamer: corrected Log::acquire() calls.¹<commit_after>
#include <Onsang/utility.hpp>
#include <Onsang/detail/gr_ceformat.hpp>
#include <Onsang/Log.hpp>
#include <Onsang/asio.hpp>
#include <Onsang/Net/CmdStreamer.hpp>
#include <Hord/Error.hpp>
#include <Hord/ErrorCode.hpp>
#include <duct/IO/arithmetic.hpp>
#include <cassert>
#include <mutex>
#include <iomanip>
#include <iostream>
namespace Onsang {
namespace Net {
// class CmdStreamer implementation
#define ONSANG_SCOPE_CLASS Net::CmdStreamer
namespace {
enum : unsigned {
// uint32 size
// uint32 type
msg_header_size = 8u,
// stage : 8
// cmd : 24
mask_type_stage = 0x000000FF,
mask_type_cmd = 0xFFFFFF00
};
static constexpr ceformat::Format const
s_err_command_type_invalid{
": command type %#08x is invalid\n"
},
s_err_stage_type_invalid{
": stage type %#02x is invalid for command type %#08x\n"
}
;
} // anonymous namespace
#define ONSANG_SCOPE_FUNC read_header
bool
CmdStreamer::read_header() {
std::istream stream{&m_streambuf_in};
std::size_t const size
= duct::IO::read_arithmetic<uint32_t>(
stream,
duct::Endian::little
);
uint32_t const type
= duct::IO::read_arithmetic<uint32_t>(
stream,
duct::Endian::little
);
if (stream.fail()) {
return false;
} else {
m_incoming_size = size;
m_incoming_type = type;
return true;
}
}
#undef ONSANG_SCOPE_FUNC
#define ONSANG_SCOPE_FUNC read_stage
bool
CmdStreamer::read_stage() {
auto const command_type = static_cast<Hord::Cmd::Type>(
m_incoming_type & mask_type_cmd
);
auto const stage_type = static_cast<Hord::Cmd::StageType>(
m_incoming_type & mask_type_stage
);
Hord::Cmd::StageUPtr stage_uptr;
Hord::Cmd::type_info const* const
type_info = m_driver.get_command_type_info(
command_type
);
if (!type_info) {
Log::acquire(Log::error)
<< ONSANG_SCOPE_FQN_STR_LIT
<< ceformat::write_sentinel<
s_err_command_type_invalid
>(
enum_cast(command_type)
)
;
return false;
}
try {
stage_uptr.reset(type_info->construct_stage(stage_type));
std::istream stream{&m_streambuf_in};
stage_uptr->deserialize(stream);
} catch (Hord::Error& ex) {
stage_uptr.reset();
switch (ex.get_code()) {
case Hord::ErrorCode::cmd_construct_stage_type_invalid:
Log::acquire(Log::error)
<< ONSANG_SCOPE_FQN_STR_LIT
<< ceformat::write_sentinel<s_err_stage_type_invalid>(
enum_cast(stage_type),
enum_cast(command_type)
)
;
return false;
// IO error or malformed data
default:
return false;
}
} catch (...) {
throw;
}
std::size_t const remaining = m_streambuf_in.get_remaining();
if (0u < remaining) {
Log::acquire(Log::debug)
<< ONSANG_SCOPE_FQN_STR_LIT
<< ": "
<< remaining
<< " bytes left in buffer after stage deserialization\n"
;
}
{
std::lock_guard<std::mutex> m_lock{m_stage_buffer_mutex};
m_stage_buffer.emplace_back(std::move(stage_uptr));
m_sig_have_stages.store(true);
}
return true;
}
#undef ONSANG_SCOPE_FUNC
#define ONSANG_SCOPE_FUNC chain_read_header
void
CmdStreamer::chain_read_header() {
m_incoming_size = 0u;
assert(m_streambuf_in.reset(msg_header_size));
asio::async_read(
m_socket,
asio::buffer(
m_streambuf_in.get_buffer().data(),
msg_header_size
),
asio::transfer_exactly(msg_header_size),
[this](
boost::system::error_code const ec,
std::size_t /*length*/
) {
if (!ec) {
m_streambuf_in.commit_direct(msg_header_size);
read_header();
chain_read_stage();
} else {
halt();
}
}
);
}
#undef ONSANG_SCOPE_FUNC
#define ONSANG_SCOPE_FUNC chain_read_stage
void
CmdStreamer::chain_read_stage() {
assert(0u < m_incoming_size);
assert(0u != m_incoming_type);
assert(m_streambuf_in.reset(m_incoming_size));
asio::async_read(
m_socket,
asio::buffer(
m_streambuf_in.get_buffer().data(),
m_incoming_size
),
asio::transfer_exactly(m_incoming_size),
[this](
boost::system::error_code const ec,
std::size_t /*length*/
) {
if (!ec) {
m_streambuf_in.commit_direct(m_incoming_size);
read_stage();
chain_read_header();
} else {
halt();
}
}
);
}
#undef ONSANG_SCOPE_FUNC
#define ONSANG_SCOPE_FUNC chain_flush_output
void
CmdStreamer::chain_flush_output() {
assert(0u < m_outgoing_size);
asio::async_write(
m_socket,
asio::buffer(
make_const(m_streambuf_out).get_buffer().data(),
m_outgoing_size
),
asio::transfer_exactly(m_incoming_size),
[this](
boost::system::error_code const ec,
std::size_t /*length*/
) {
m_sig_pending_output.store(false);
m_outgoing_size = 0u;
if (ec) {
halt();
}
}
);
}
#undef ONSANG_SCOPE_FUNC
// operations
void
CmdStreamer::halt() noexcept {
m_socket.get_io_service().stop();
}
#define ONSANG_SCOPE_FUNC run
void
CmdStreamer::run() {
auto& io_service = m_socket.get_io_service();
try {
while (!io_service.stopped()) {
chain_read_header();
io_service.run();
}
} catch (std::exception& ex) {
Log::acquire(Log::error)
<< ONSANG_SCOPE_FQN_STR_LIT
<< ": caught exception from io_service::run(): "
<< ex.what()
<< "\n"
;
throw;
}
}
#undef ONSANG_SCOPE_FUNC
#define ONSANG_SCOPE_FUNC context_input
bool
CmdStreamer::context_input(
Hord::System::Context& context
) {
if (!m_sig_have_stages.load()) {
return false;
}
{
std::lock_guard<std::mutex> m_lock{m_stage_buffer_mutex};
for (auto& stage_uptr : m_stage_buffer) {
context.push_input(stage_uptr);
}
m_stage_buffer.clear();
m_sig_have_stages.store(false);
}
return true;
}
#undef ONSANG_SCOPE_FUNC
#define ONSANG_SCOPE_FUNC context_output
bool
CmdStreamer::context_output(
Hord::System::Context& context
) {
if (
0 == context.get_output().size() ||
m_sig_pending_output.load()
) {
return false;
}
m_streambuf_out.reset(
msg_header_size + (m_streambuf_out.get_max_size() >> 2)
);
std::ostream stream{&m_streambuf_out};
// Seek past header to reserve it; we need the size of the
// stage payload
stream.seekp(msg_header_size);
// data
auto& stage = *context.get_output().front();
stage.serialize(
stream
);
// Can't use buffer.size() later because it might've grown
// beyond our write amount
m_outgoing_size = m_streambuf_out.get_sequence_size();
// header
stream.seekp(0);
std::size_t const h_size = m_outgoing_size - msg_header_size;
duct::IO::write_arithmetic<uint32_t>(
stream,
static_cast<uint32_t>(h_size),
duct::Endian::little
);
uint32_t const h_type
= enum_cast(stage.get_stage_type())
| enum_cast(stage.get_command_type())
;
duct::IO::write_arithmetic<uint32_t>(
stream,
h_type,
duct::Endian::little
);
if (stream.fail()) {
return false;
}
m_streambuf_out.commit();
context.get_output().pop_front();
m_sig_pending_output.store(true);
m_socket.get_io_service().post(
[this]() {
chain_flush_output();
}
);
return true;
}
#undef ONSANG_SCOPE_FUNC
#undef ONSANG_SCOPE_CLASS // Onsang::Net::CmdStreamer
} // namespace Net
} // namespace Onsang
<|endoftext|>
|
<commit_before>/*************************************************************************
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: NamedBoolPropertyHdl.cxx,v $
*
* $Revision: 1.6 $
*
* last change: $Author: hr $ $Date: 2007-06-27 15:25:30 $
*
* The Contents of this file are made available subject to
* the terms of GNU Lesser General Public License Version 2.1.
*
*
* GNU Lesser General Public License Version 2.1
* =============================================
* Copyright 2005 by Sun Microsystems, Inc.
* 901 San Antonio Road, Palo Alto, CA 94303, USA
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License version 2.1, as published by the Free Software Foundation.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston,
* MA 02111-1307 USA
*
************************************************************************/
// MARKER(update_precomp.py): autogen include statement, do not remove
#include "precompiled_xmloff.hxx"
#ifndef _XMLOFF_NAMEDBOOLPROPERTYHANDLER_HXX
#include <xmloff/NamedBoolPropertyHdl.hxx>
#endif
#ifndef _XMLOFF_XMLUCONV_HXX
#include <xmloff/xmluconv.hxx>
#endif
#ifndef _COMPHELPER_EXTRACT_HXX_
#include <comphelper/extract.hxx>
#endif
#ifndef _RTL_USTRING_
#include <rtl/ustring.hxx>
#endif
#ifndef _RTL_USTRBUF_HXX_
#include <rtl/ustrbuf.hxx>
#endif
#ifndef _COM_SUN_STAR_UNO_ANY_HXX_
#include <com/sun/star/uno/Any.hxx>
#endif
using namespace ::rtl;
using namespace ::com::sun::star::uno;
///////////////////////////////////////////////////////////////////////////////
//
// class XMLNamedBoolPropertyHdl
//
XMLNamedBoolPropertyHdl::~XMLNamedBoolPropertyHdl()
{
// Nothing to do
}
sal_Bool XMLNamedBoolPropertyHdl::importXML( const OUString& rStrImpValue, Any& rValue, const SvXMLUnitConverter& ) const
{
if( rStrImpValue == maTrueStr )
{
rValue = ::cppu::bool2any( sal_True );
return sal_True;
}
if( rStrImpValue == maFalseStr )
{
rValue = ::cppu::bool2any( sal_False );
return sal_True;
}
return sal_False;
}
sal_Bool XMLNamedBoolPropertyHdl::exportXML( OUString& rStrExpValue, const Any& rValue, const SvXMLUnitConverter& ) const
{
if( ::cppu::any2bool( rValue ) )
{
rStrExpValue = maTrueStr;
}
else
{
rStrExpValue = maFalseStr;
}
return sal_True;
}
<commit_msg>INTEGRATION: CWS impresstables2 (1.5.80); FILE MERGED 2007/08/01 14:23:46 cl 1.5.80.2: RESYNC: (1.5-1.6); FILE MERGED 2007/07/27 09:09:53 cl 1.5.80.1: fixed build issues due to pch and namespace ::rtl<commit_after>/*************************************************************************
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: NamedBoolPropertyHdl.cxx,v $
*
* $Revision: 1.7 $
*
* last change: $Author: rt $ $Date: 2008-03-12 10:43:22 $
*
* The Contents of this file are made available subject to
* the terms of GNU Lesser General Public License Version 2.1.
*
*
* GNU Lesser General Public License Version 2.1
* =============================================
* Copyright 2005 by Sun Microsystems, Inc.
* 901 San Antonio Road, Palo Alto, CA 94303, USA
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License version 2.1, as published by the Free Software Foundation.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston,
* MA 02111-1307 USA
*
************************************************************************/
// MARKER(update_precomp.py): autogen include statement, do not remove
#include "precompiled_xmloff.hxx"
#ifndef _XMLOFF_NAMEDBOOLPROPERTYHANDLER_HXX
#include <xmloff/NamedBoolPropertyHdl.hxx>
#endif
#ifndef _XMLOFF_XMLUCONV_HXX
#include <xmloff/xmluconv.hxx>
#endif
#ifndef _COMPHELPER_EXTRACT_HXX_
#include <comphelper/extract.hxx>
#endif
#ifndef _RTL_USTRING_
#include <rtl/ustring.hxx>
#endif
#ifndef _RTL_USTRBUF_HXX_
#include <rtl/ustrbuf.hxx>
#endif
#ifndef _COM_SUN_STAR_UNO_ANY_HXX_
#include <com/sun/star/uno/Any.hxx>
#endif
using ::rtl::OUString;
using ::rtl::OUStringBuffer;
using namespace ::com::sun::star::uno;
///////////////////////////////////////////////////////////////////////////////
//
// class XMLNamedBoolPropertyHdl
//
XMLNamedBoolPropertyHdl::~XMLNamedBoolPropertyHdl()
{
// Nothing to do
}
sal_Bool XMLNamedBoolPropertyHdl::importXML( const OUString& rStrImpValue, Any& rValue, const SvXMLUnitConverter& ) const
{
if( rStrImpValue == maTrueStr )
{
rValue = ::cppu::bool2any( sal_True );
return sal_True;
}
if( rStrImpValue == maFalseStr )
{
rValue = ::cppu::bool2any( sal_False );
return sal_True;
}
return sal_False;
}
sal_Bool XMLNamedBoolPropertyHdl::exportXML( OUString& rStrExpValue, const Any& rValue, const SvXMLUnitConverter& ) const
{
if( ::cppu::any2bool( rValue ) )
{
rStrExpValue = maTrueStr;
}
else
{
rStrExpValue = maFalseStr;
}
return sal_True;
}
<|endoftext|>
|
<commit_before>/*************************************************************************
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: PageMasterPropMapper.cxx,v $
*
* $Revision: 1.13 $
*
* last change: $Author: hr $ $Date: 2007-06-27 15:28:18 $
*
* The Contents of this file are made available subject to
* the terms of GNU Lesser General Public License Version 2.1.
*
*
* GNU Lesser General Public License Version 2.1
* =============================================
* Copyright 2005 by Sun Microsystems, Inc.
* 901 San Antonio Road, Palo Alto, CA 94303, USA
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License version 2.1, as published by the Free Software Foundation.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston,
* MA 02111-1307 USA
*
************************************************************************/
// MARKER(update_precomp.py): autogen include statement, do not remove
#include "precompiled_xmloff.hxx"
#ifndef _XMLOFF_PAGEMASTERPROPMAPPER_HXX
#include "PageMasterPropMapper.hxx"
#endif
#ifndef _XMLOFF_PAGEMASTERSTYLEMAP_HXX
#include <xmloff/PageMasterStyleMap.hxx>
#endif
#ifndef _XMLOFF_PAGEMASTERPROPHDLFACTORY_HXX
#include "PageMasterPropHdlFactory.hxx"
#endif
using namespace ::com::sun::star;
using namespace ::com::sun::star::uno;
using namespace ::com::sun::star::beans;
//______________________________________________________________________________
XMLPageMasterPropSetMapper::XMLPageMasterPropSetMapper():
XMLPropertySetMapper( aXMLPageMasterStyleMap, new XMLPageMasterPropHdlFactory())
{
}
XMLPageMasterPropSetMapper::XMLPageMasterPropSetMapper(
const XMLPropertyMapEntry* pEntries,
const UniReference< XMLPropertyHandlerFactory >& rFactory ) :
XMLPropertySetMapper( pEntries, rFactory )
{
}
XMLPageMasterPropSetMapper::~XMLPageMasterPropSetMapper()
{
}
<commit_msg>INTEGRATION: CWS changefileheader (1.13.162); FILE MERGED 2008/04/01 13:04:58 thb 1.13.162.2: #i85898# Stripping all external header guards 2008/03/31 16:28:19 rt 1.13.162.1: #i87441# Change license header to LPGL v3.<commit_after>/*************************************************************************
*
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* Copyright 2008 by Sun Microsystems, Inc.
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: PageMasterPropMapper.cxx,v $
* $Revision: 1.14 $
*
* This file is part of OpenOffice.org.
*
* OpenOffice.org is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License version 3
* only, as published by the Free Software Foundation.
*
* OpenOffice.org is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License version 3 for more details
* (a copy is included in the LICENSE file that accompanied this code).
*
* You should have received a copy of the GNU Lesser General Public License
* version 3 along with OpenOffice.org. If not, see
* <http://www.openoffice.org/license.html>
* for a copy of the LGPLv3 License.
*
************************************************************************/
// MARKER(update_precomp.py): autogen include statement, do not remove
#include "precompiled_xmloff.hxx"
#ifndef _XMLOFF_PAGEMASTERPROPMAPPER_HXX
#include "PageMasterPropMapper.hxx"
#endif
#ifndef _XMLOFF_PAGEMASTERSTYLEMAP_HXX
#include <xmloff/PageMasterStyleMap.hxx>
#endif
#include "PageMasterPropHdlFactory.hxx"
using namespace ::com::sun::star;
using namespace ::com::sun::star::uno;
using namespace ::com::sun::star::beans;
//______________________________________________________________________________
XMLPageMasterPropSetMapper::XMLPageMasterPropSetMapper():
XMLPropertySetMapper( aXMLPageMasterStyleMap, new XMLPageMasterPropHdlFactory())
{
}
XMLPageMasterPropSetMapper::XMLPageMasterPropSetMapper(
const XMLPropertyMapEntry* pEntries,
const UniReference< XMLPropertyHandlerFactory >& rFactory ) :
XMLPropertySetMapper( pEntries, rFactory )
{
}
XMLPageMasterPropSetMapper::~XMLPageMasterPropSetMapper()
{
}
<|endoftext|>
|
<commit_before>/*
kcodecaction.cpp
Copyright (c) 2003 by Jason Keirstead <jason@keirstead.org>
Kopete (c) 2003 by the Kopete developers <kopete-devel@kde.org>
*************************************************************************
* *
* This program is free software; you can redistribute it and/or modify *
* it under the terms of the GNU General Public License as published by *
* the Free Software Foundation; either version 2 of the License, or *
* (at your option) any later version. *
* *
*************************************************************************
*/
#include <qstringlist.h>
#include <qtextcodec.h>
#include "kcodecaction.h"
KCodecAction::KCodecAction( const QString &text, const KShortcut &cut,
QObject *parent, const char *name ) : KSelectAction( text, "", cut, parent, name )
{
QObject::connect( this, SIGNAL( activated( int ) ),
this, SLOT(slotActivated( int )) );
QTextCodec *codec;
QStringList items;
for (uint i = 0; ( codec = QTextCodec::codecForIndex(i) ); ++i)
{
items.append( codec->name() );
codecMap.insert( i, codec );
}
setItems( items );
}
void KCodecAction::slotActivated( int index )
{
emit activated( codecMap[ index ] );
}
void KCodecAction::setCodec( const QTextCodec *codec )
{
for( QIntDictIterator<QTextCodec> it( codecMap ); it.current(); ++it )
{
if( it.current() == codec )
setCurrentItem( it.currentKey() );
}
}
#include "kcodecaction.moc"
<commit_msg>Fix a small bug when changing the encoding for a channel or private chat via IRC->Encoding menu item: The encoding changes, but the menu is not updated to reflect that change, the 'tick' just stays in the default selection.<commit_after>/*
kcodecaction.cpp
Copyright (c) 2003 by Jason Keirstead <jason@keirstead.org>
Kopete (c) 2003 by the Kopete developers <kopete-devel@kde.org>
*************************************************************************
* *
* This program is free software; you can redistribute it and/or modify *
* it under the terms of the GNU General Public License as published by *
* the Free Software Foundation; either version 2 of the License, or *
* (at your option) any later version. *
* *
*************************************************************************
*/
#include <qstringlist.h>
#include <qtextcodec.h>
#include "kcodecaction.h"
KCodecAction::KCodecAction( const QString &text, const KShortcut &cut,
QObject *parent, const char *name ) : KSelectAction( text, "", cut, parent, name )
{
QObject::connect( this, SIGNAL( activated( int ) ),
this, SLOT(slotActivated( int )) );
QTextCodec *codec;
QStringList items;
for (uint i = 0; ( codec = QTextCodec::codecForIndex(i) ); ++i)
{
items.append( codec->name() );
codecMap.insert( i, codec );
}
setItems( items );
}
void KCodecAction::slotActivated( int index )
{
setCurrentItem( index );
emit activated( codecMap[ index ] );
}
void KCodecAction::setCodec( const QTextCodec *codec )
{
for( QIntDictIterator<QTextCodec> it( codecMap ); it.current(); ++it )
{
if( it.current() == codec )
setCurrentItem( it.currentKey() );
}
}
#include "kcodecaction.moc"
<|endoftext|>
|
<commit_before>#include "AudioPluginUtil.h"
#include "FFTConvolver/FFTConvolver.h"
#include "FFTConvolver/TwoStageFFTConvolver.h"
#include <utility>
#include <mysofa.h>
//#include <ATK/Special/ConvolutionFilter.h>
// Our plugin will be encapsulated within a namespace
// This namespace is later used to indicate that we
// want to include this plugin in the build with PluginList.h
namespace Plugin_SofaSpatializer {
/////////////////////////////////////////
/// Utilities
///////////////////////////////////////
const unsigned MAX_SOFA_FILES = 1;
const unsigned CONVOLVERS = 2;
class SofaContainer {
public:
MYSOFA_HRTF* hrtfs[MAX_SOFA_FILES];
fftconvolver::FFTConvolver* convolver[CONVOLVERS];
unsigned buffersize;
bool is_initialized = false;
float last;
void init(unsigned samplerate, unsigned buffersize) {
if (!is_initialized) {
this->buffersize = buffersize;
int err;
// load sofa files
hrtfs[0] = mysofa_load("WIEb_S00_R01.sofa", &err);
//if (samplerate != hrtfs[0]->DataSamplingRate.values[0]) { mysofa_resample(hrtfs[0], (float)samplerate); }
// init convolver
this->setIr(0);
this->is_initialized = true;
}
}
void setIr(unsigned ir) {
for (int i = 0; i < CONVOLVERS; ++i) {
convolver[i] = new fftconvolver::FFTConvolver();
convolver[i]->init(buffersize,
&this->hrtfs[0]->DataIR.values[this->hrtfs[0]->N * (ir + i)],
this->hrtfs[0]->N);
}
}
void free() {
if (is_initialized) {
for (int i = 0; i < sizeof(this->hrtfs)/sizeof(*this->hrtfs); ++i) {
mysofa_free(hrtfs[i]);
}
this->is_initialized = false;
}
}
};
static SofaContainer sofaContainer;
static void deinterleaveData(float* in, float* out, int len, int num_ch) {
for (int ch = 0; ch < num_ch; ++ch) {
int offset = ch * len;
for (int i = 0; i < len; ++i) {
out[offset + i] = in[ch + i*2];
}
}
}
static void interleaveData(float* in, float* out, int len, int num_ch) {
for (int ch = 0; ch < num_ch; ++ch) {
int offset = ch * len;
for (int i = 0; i < len; ++i) {
out[ch + i*2] = in[offset + i];
}
}
}
/////////////////////////////////////////
/// plugin logic
///////////////////////////////////////
// Use an enum for the plugin parameters
// we want Unity to have access to
// By default, Unity manipulates exposed
// parameters with a slider in the editor
enum Param
{
P_GAIN,
P_NUM
// Since enum values start at 0, the last value
// gives us the total number of parameters in the enum
// However, we don't use it as an actual parameter
};
// This is a callback we'll have the SDK invoke when initializing parameters
// Instantiate the parameter details here
int InternalRegisterEffectDefinition(UnityAudioEffectDefinition& definition)
{
definition.paramdefs = new UnityAudioParameterDefinition [P_NUM];
RegisterParameter(definition, // EffectDefinition object passed to us
"Gain Multiplier", // The parameter label shown in the Unity editor
"", // The units (ex. dB, Hz, cm, s, etc)
0.0f, // Minimum parameter value
10.0f, // Maximum parameter value
1.0f, // Default parameter value
1.0f, // Display scale, Unity editor shows actualValue*displayScale
1.0f, // Display exponent, in case you want a slider operating on an exponential scale in the editor
P_GAIN); // The index of the parameter in question; use the enum value
definition.flags |= UnityAudioEffectDefinitionFlags_IsSpatializer;
return P_NUM;
}
// Define a struct that will hold the plugin's state
// Our noise plugin is very simple, so we're only interested
// in keeping track of the single parameter we have: gain
struct EffectData
{
float p[P_NUM]; // Parameters
};
// UNITY_AUDIODSP_RESULT is defined as `int`
// UNITY_AUDIODSP_CALLBACK is defined as nothing
// So behind the scenes, the function signature is really `int CreateCallback(UnityAudioEffectState* state)`
// This callback is invoked by Unity when the plugin is loaded
UNITY_AUDIODSP_RESULT UNITY_AUDIODSP_CALLBACK CreateCallback(UnityAudioEffectState* state)
{
EffectData* data = new EffectData; // Create a new pointer to the struct defined earlier
memset(data, 0, sizeof(EffectData)); // Quickly fill memory location with zeros
data->p[P_GAIN] = 1.0; // Initialize effectdata with default parameter value(s)
InitParametersFromDefinitions(InternalRegisterEffectDefinition, data->p);
// Add our effectdata pointer to the state so we can reach it in other callbacks
state->effectdata = data;
sofaContainer.init(state->samplerate, state->dspbuffersize);
return UNITY_AUDIODSP_OK;
}
// This callback is invoked by Unity when the plugin is unloaded
UNITY_AUDIODSP_RESULT UNITY_AUDIODSP_CALLBACK ReleaseCallback(UnityAudioEffectState* state)
{
//sofaContainer.free();
// Grab the EffectData pointer we added earlier in CreateCallback
EffectData *data = state->GetEffectData<EffectData>();
delete data; // Cleanup
return UNITY_AUDIODSP_OK;
}
/////////////////////////////////////////
/// Soundprocessing
///////////////////////////////////////
// ProcessCallback gets called as long as the plugin is loaded
// This includes when the editor is not in play mode!
UNITY_AUDIODSP_RESULT UNITY_AUDIODSP_CALLBACK ProcessCallback(
UnityAudioEffectState* state, // The state gets passed into all callbacks
float* inbuffer, // Plugins can be chained together; inbuffer holds the signal incoming from another plugin, or an AudioSource
float* outbuffer, // We fill outbuffer with the signal Unity should send to the speakers
unsigned int length, // The number of samples the buffers hold
int inchannels, // The number of channels the incoming signal uses
int outchannels) // The number of channels the outgoing signal uses
{
if (!sofaContainer.is_initialized) {
memcpy(outbuffer, inbuffer, length * outchannels * sizeof(float));
return UNITY_AUDIODSP_OK;
}
auto data = state->GetEffectData<EffectData>();
if (sofaContainer.last != data->p[P_GAIN]) {
unsigned i = rand() % sofaContainer.hrtfs[0]->R;
sofaContainer.setIr(i);
sofaContainer.last = i;
data->p[P_GAIN] = i;
};
float in_deinterleaved[length * inchannels];
float out_deinterleaved[length * inchannels];
deinterleaveData(inbuffer, in_deinterleaved, length, inchannels);
(*sofaContainer.convolver[0]).process(&in_deinterleaved[0], &out_deinterleaved[0], length); // left channel
(*sofaContainer.convolver[1]).process(&in_deinterleaved[length], &out_deinterleaved[length], length); // right channel
interleaveData(out_deinterleaved, outbuffer, length, outchannels);
return UNITY_AUDIODSP_OK;
}
/////////////////////////////////////////
/// editor parameter manipulation
///////////////////////////////////////
// Called whenever a parameter is changed from the editor
UNITY_AUDIODSP_RESULT UNITY_AUDIODSP_CALLBACK SetFloatParameterCallback(UnityAudioEffectState* state, int index, float value)
{
EffectData *data = state->GetEffectData<EffectData>(); // Grab EffectData
// index should never point to a parameter that we haven't defined
if (index >= P_NUM) {
return UNITY_AUDIODSP_ERR_UNSUPPORTED;
}
data->p[index] = value; // Set the parameter to the value the editor gave us
return UNITY_AUDIODSP_OK;
}
// Internally used by the SDK to query parameter values, not sure when this is called...
UNITY_AUDIODSP_RESULT UNITY_AUDIODSP_CALLBACK GetFloatParameterCallback(UnityAudioEffectState* state, int index, float* value, char *valuestr)
{
EffectData *data = state->GetEffectData<EffectData>();
if (index >= P_NUM) {
return UNITY_AUDIODSP_ERR_UNSUPPORTED;
}
if (value != NULL) {
*value = data->p[index];
}
if (valuestr != NULL) {
valuestr[0] = 0;
}
return UNITY_AUDIODSP_OK;
}
// Also unsure where this is used, but it's required to be defined, so just return from the function as soon as it's called
int UNITY_AUDIODSP_CALLBACK GetFloatBufferCallback(UnityAudioEffectState* state, const char* name, float* buffer, int numsamples)
{
return UNITY_AUDIODSP_OK;
}
}<commit_msg>fix memory leak<commit_after>#include "AudioPluginUtil.h"
#include "FFTConvolver/FFTConvolver.h"
#include "FFTConvolver/TwoStageFFTConvolver.h"
#include <utility>
#include <mysofa.h>
//#include <ATK/Special/ConvolutionFilter.h>
// Our plugin will be encapsulated within a namespace
// This namespace is later used to indicate that we
// want to include this plugin in the build with PluginList.h
namespace Plugin_SofaSpatializer {
/////////////////////////////////////////
/// Utilities
///////////////////////////////////////
const unsigned MAX_SOFA_FILES = 1;
const unsigned CONVOLVERS = 2;
class SofaContainer {
public:
MYSOFA_HRTF* hrtfs[MAX_SOFA_FILES];
bool is_initialized = false;
void init(unsigned samplerate) {
if (!is_initialized) {
int err;
// load sofa files
hrtfs[0] = mysofa_load("WIEb_S00_R01.sofa", &err);
// resample if samplerates doesent match (Warning: long coputationtime!)
//if (samplerate != hrtfs[0]->DataSamplingRate.values[0]) { mysofa_resample(hrtfs[0], (float)samplerate); }
this->is_initialized = true;
}
}
void free() {
if (is_initialized) {
for (int i = 0; i < sizeof(this->hrtfs)/sizeof(*this->hrtfs); ++i) {
mysofa_free(hrtfs[i]);
}
this->is_initialized = false;
}
}
};
static SofaContainer sofaContainer;
static void deinterleaveData(float* in, float* out, int len, int num_ch) {
for (int ch = 0; ch < num_ch; ++ch) {
int offset = ch * len;
for (int i = 0; i < len; ++i) {
out[offset + i] = in[ch + i*2];
}
}
}
static void interleaveData(float* in, float* out, int len, int num_ch) {
for (int ch = 0; ch < num_ch; ++ch) {
int offset = ch * len;
for (int i = 0; i < len; ++i) {
out[ch + i*2] = in[offset + i];
}
}
}
/////////////////////////////////////////
/// plugin logic
///////////////////////////////////////
// Use an enum for the plugin parameters
// we want Unity to have access to
// By default, Unity manipulates exposed
// parameters with a slider in the editor
enum Param
{
P_GAIN,
P_NUM
// Since enum values start at 0, the last value
// gives us the total number of parameters in the enum
// However, we don't use it as an actual parameter
};
// Define a struct that will hold the plugin's state
// Our noise plugin is very simple, so we're only interested
// in keeping track of the single parameter we have: gain
struct EffectData
{
float p[P_NUM]; // Parameters
fftconvolver::FFTConvolver* convolver[CONVOLVERS];
float last;
};
// This is a callback we'll have the SDK invoke when initializing parameters
// Instantiate the parameter details here
int InternalRegisterEffectDefinition(UnityAudioEffectDefinition& definition)
{
definition.paramdefs = new UnityAudioParameterDefinition [P_NUM];
RegisterParameter(definition, // EffectDefinition object passed to us
"Gain Multiplier", // The parameter label shown in the Unity editor
"", // The units (ex. dB, Hz, cm, s, etc)
0.0f, // Minimum parameter value
10.0f, // Maximum parameter value
1.0f, // Default parameter value
1.0f, // Display scale, Unity editor shows actualValue*displayScale
1.0f, // Display exponent, in case you want a slider operating on an exponential scale in the editor
P_GAIN); // The index of the parameter in question; use the enum value
definition.flags |= UnityAudioEffectDefinitionFlags_IsSpatializer;
return P_NUM;
}
// UNITY_AUDIODSP_RESULT is defined as `int`
// UNITY_AUDIODSP_CALLBACK is defined as nothing
// So behind the scenes, the function signature is really `int CreateCallback(UnityAudioEffectState* state)`
// This callback is invoked by Unity when the plugin is loaded
UNITY_AUDIODSP_RESULT UNITY_AUDIODSP_CALLBACK CreateCallback(UnityAudioEffectState* state)
{
EffectData* data = new EffectData; // Create a new pointer to the struct defined earlier
memset(data, 0, sizeof(EffectData)); // Quickly fill memory location with zeros
data->p[P_GAIN] = 1.0; // Initialize effectdata with default parameter value(s)
InitParametersFromDefinitions(InternalRegisterEffectDefinition, data->p);
sofaContainer.init(state->samplerate);
auto const len = sofaContainer.hrtfs[0]->N;
for (int i = 0; i < CONVOLVERS; ++i) {
data->convolver[i] = new fftconvolver::FFTConvolver();
data->convolver[i]->init(state->dspbuffersize, &sofaContainer.hrtfs[0]->DataIR.values[len * i], len);
}
// Add our effectdata pointer to the state so we can reach it in other callbacks
state->effectdata = data;
return UNITY_AUDIODSP_OK;
}
// This callback is invoked by Unity when the plugin is unloaded
UNITY_AUDIODSP_RESULT UNITY_AUDIODSP_CALLBACK ReleaseCallback(UnityAudioEffectState* state)
{
//sofaContainer.free();
// Grab the EffectData pointer we added earlier in CreateCallback
EffectData *data = state->GetEffectData<EffectData>();
delete data; // Cleanup
return UNITY_AUDIODSP_OK;
}
/////////////////////////////////////////
/// Soundprocessing
///////////////////////////////////////
// ProcessCallback gets called as long as the plugin is loaded
// This includes when the editor is not in play mode!
UNITY_AUDIODSP_RESULT UNITY_AUDIODSP_CALLBACK ProcessCallback(
UnityAudioEffectState* state, // The state gets passed into all callbacks
float* inbuffer, // Plugins can be chained together; inbuffer holds the signal incoming from another plugin, or an AudioSource
float* outbuffer, // We fill outbuffer with the signal Unity should send to the speakers
unsigned int length, // The number of samples the buffers hold
int inchannels, // The number of channels the incoming signal uses
int outchannels) // The number of channels the outgoing signal uses
{
if (!sofaContainer.is_initialized) {
memcpy(outbuffer, inbuffer, length * outchannels * sizeof(float));
return UNITY_AUDIODSP_OK;
}
auto data = state->GetEffectData<EffectData>();
if (data->last != data->p[P_GAIN]) {
unsigned rnd = rand() % sofaContainer.hrtfs[0]->R;
auto const len = sofaContainer.hrtfs[0]->N;
for (int i = 0; rnd < CONVOLVERS; ++rnd) {
data->convolver[rnd]->init(state->dspbuffersize, &sofaContainer.hrtfs[0]->DataIR.values[len * rnd], len);
}
data->last = rnd;
data->p[P_GAIN] = rnd;
};
float in_deinterleaved[length * inchannels];
float out_deinterleaved[length * inchannels];
deinterleaveData(inbuffer, in_deinterleaved, length, inchannels);
// left channel
(*data->convolver[0]).process(&in_deinterleaved[0], &out_deinterleaved[0], length);
// right channel
(*data->convolver[1]).process(&in_deinterleaved[length], &out_deinterleaved[length], length);
interleaveData(out_deinterleaved, outbuffer, length, outchannels);
return UNITY_AUDIODSP_OK;
}
/////////////////////////////////////////
/// editor parameter manipulation
///////////////////////////////////////
// Called whenever a parameter is changed from the editor
UNITY_AUDIODSP_RESULT UNITY_AUDIODSP_CALLBACK SetFloatParameterCallback(UnityAudioEffectState* state, int index, float value)
{
EffectData *data = state->GetEffectData<EffectData>(); // Grab EffectData
// index should never point to a parameter that we haven't defined
if (index >= P_NUM) {
return UNITY_AUDIODSP_ERR_UNSUPPORTED;
}
data->p[index] = value; // Set the parameter to the value the editor gave us
return UNITY_AUDIODSP_OK;
}
// Internally used by the SDK to query parameter values, not sure when this is called...
UNITY_AUDIODSP_RESULT UNITY_AUDIODSP_CALLBACK GetFloatParameterCallback(UnityAudioEffectState* state, int index, float* value, char *valuestr)
{
EffectData *data = state->GetEffectData<EffectData>();
if (index >= P_NUM) {
return UNITY_AUDIODSP_ERR_UNSUPPORTED;
}
if (value != NULL) {
*value = data->p[index];
}
if (valuestr != NULL) {
valuestr[0] = 0;
}
return UNITY_AUDIODSP_OK;
}
// Also unsure where this is used, but it's required to be defined, so just return from the function as soon as it's called
int UNITY_AUDIODSP_CALLBACK GetFloatBufferCallback(UnityAudioEffectState* state, const char* name, float* buffer, int numsamples)
{
return UNITY_AUDIODSP_OK;
}
}<|endoftext|>
|
<commit_before>#include "ghost/config.h"
#include "ghost/types.h"
#include "ghost/densemat.h"
#include "ghost/util.h"
#include "ghost/math.h"
#include "ghost/tsmttsm.h"
#include "ghost/tsmttsm_gen.h"
#include "ghost/tsmttsm_avx_gen.h"
#include <map>
using namespace std;
static bool operator<(const ghost_tsmttsm_parameters_t &a, const ghost_tsmttsm_parameters_t &b)
{
return ghost_hash(a.dt,a.wcols,ghost_hash(a.vcols,a.impl,0)) < ghost_hash(b.dt,b.wcols,ghost_hash(b.vcols,b.impl,0));
}
static map<ghost_tsmttsm_parameters_t, ghost_tsmttsm_kernel_t> ghost_tsmttsm_kernels;
ghost_error_t ghost_tsmttsm_valid(ghost_densemat_t *x, ghost_densemat_t *v, const char * transv,
ghost_densemat_t *w, const char *transw, void *alpha, void *beta, int reduce, int printerror)
{
if (w->traits.storage != GHOST_DENSEMAT_ROWMAJOR) {
if (printerror) {
ERROR_LOG("w must be stored row-major!");
}
return GHOST_ERR_INVALID_ARG;
}
if (v->traits.storage != GHOST_DENSEMAT_ROWMAJOR) {
if (printerror) {
ERROR_LOG("v must be stored row-major!");
}
return GHOST_ERR_INVALID_ARG;
}
if (x->traits.storage != GHOST_DENSEMAT_COLMAJOR) {
if (printerror) {
ERROR_LOG("x must be stored col-major!");
}
return GHOST_ERR_INVALID_ARG;
}
if (v->traits.datatype != w->traits.datatype || v->traits.datatype != x->traits.datatype) {
if (printerror) {
ERROR_LOG("Different data types!");
}
return GHOST_ERR_INVALID_ARG;
}
if (v->traits.flags & GHOST_DENSEMAT_SCATTERED || w->traits.flags & GHOST_DENSEMAT_SCATTERED || x->traits.flags & GHOST_DENSEMAT_SCATTERED) {
if (printerror) {
ERROR_LOG("Scattered densemats not supported!");
}
return GHOST_ERR_INVALID_ARG;
}
if (reduce != GHOST_GEMM_ALL_REDUCE) {
if (printerror) {
ERROR_LOG("Only Allreduce supported currently!");
}
return GHOST_ERR_INVALID_ARG;
}
if (!strncasecmp(transv,"N",1)) {
if (printerror) {
ERROR_LOG("v must be transposed!");
}
return GHOST_ERR_INVALID_ARG;
}
if (strncasecmp(transw,"N",1)) {
if (printerror) {
ERROR_LOG("w must not be transposed!");
}
return GHOST_ERR_INVALID_ARG;
}
UNUSED(alpha);
UNUSED(beta);
return GHOST_SUCCESS;
}
ghost_error_t ghost_tsmttsm(ghost_densemat_t *x, ghost_densemat_t *v, ghost_densemat_t *w, void *alpha, void *beta,int reduce,int conjv)
{
GHOST_FUNC_ENTER(GHOST_FUNCTYPE_MATH);
ghost_error_t ret;
if ((ret = ghost_tsmttsm_valid(x,v,"T",w,"N",alpha,beta,reduce,1)) != GHOST_SUCCESS) {
return ret;
}
if (ghost_tsmttsm_kernels.empty()) {
#include "tsmttsm.def"
#include "tsmttsm_avx.def"
}
ghost_tsmttsm_parameters_t p;
ghost_tsmttsm_kernel_t kernel = NULL;
#ifdef GHOST_HAVE_MIC
p.impl = GHOST_IMPLEMENTATION_MIC;
#elif defined(GHOST_HAVE_AVX)
p.impl = GHOST_IMPLEMENTATION_AVX;
#elif defined(GHOST_HAVE_SSE)
p.impl = GHOST_IMPLEMENTATION_SSE;
#else
p.impl = GHOST_IMPLEMENTATION_PLAIN;
#endif
/*if (x->traits.ncolspadded < 4 || x->traits.flags & GHOST_DENSEMAT_VIEW) {
p.impl = GHOST_IMPLEMENTATION_PLAIN;
}*/
p.dt = x->traits.datatype;
p.vcols = v->traits.ncols;
p.wcols = w->traits.ncols;
if (p.vcols % 4 || p.wcols % 4) {
PERFWARNING_LOG("Use plain for non-multiple of four");
p.impl = GHOST_IMPLEMENTATION_PLAIN;
}
kernel = ghost_tsmttsm_kernels[p];
if (!kernel) {
PERFWARNING_LOG("Try kernel with arbitrary wcols");
p.wcols = -1;
p.vcols = v->traits.ncols;
kernel = ghost_tsmttsm_kernels[p];
}
if (!kernel) {
PERFWARNING_LOG("Try kernel with arbitrary vcols");
p.wcols = w->traits.ncols;
p.vcols = -1;
kernel = ghost_tsmttsm_kernels[p];
}
if (!kernel) {
PERFWARNING_LOG("Try kernel with arbitrary block sizes");
p.wcols = -1;
p.vcols = -1;
kernel = ghost_tsmttsm_kernels[p];
}
if (!kernel) {
PERFWARNING_LOG("Try plain implementation");
p.impl = GHOST_IMPLEMENTATION_PLAIN;
}
kernel = ghost_tsmttsm_kernels[p];
if (!kernel) {
INFO_LOG("Could not find TSMTTSM kernel with %d %d %d. Fallback to GEMM",p.dt,p.wcols,p.vcols);
return GHOST_ERR_INVALID_ARG;
//return ghost_gemm(x,v,"T",w,"N",alpha,beta,GHOST_GEMM_ALL_REDUCE,GHOST_GEMM_NOT_SPECIAL);
}
ret = kernel(x,v,w,alpha,beta,conjv);
#ifdef GHOST_HAVE_INSTR_TIMING
ghost_gemm_perf_args_t tsmttsm_perfargs;
tsmttsm_perfargs.xcols = p.wcols;
tsmttsm_perfargs.vcols = p.vcols;
if (v->context) {
tsmttsm_perfargs.vrows = v->context->gnrows;
} else {
tsmttsm_perfargs.vrows = v->traits.nrows;
}
tsmttsm_perfargs.dt = x->traits.datatype;
ghost_timing_set_perfFunc(__ghost_functag,ghost_gemm_perf_GFs,(void *)&tsmttsm_perfargs,sizeof(tsmttsm_perfargs),"GF/s");
#endif
GHOST_FUNC_EXIT(GHOST_FUNCTYPE_MATH);
return ret;
}
<commit_msg>try fixed block sizes again after fallback to plain implementation<commit_after>#include "ghost/config.h"
#include "ghost/types.h"
#include "ghost/densemat.h"
#include "ghost/util.h"
#include "ghost/math.h"
#include "ghost/tsmttsm.h"
#include "ghost/tsmttsm_gen.h"
#include "ghost/tsmttsm_avx_gen.h"
#include <map>
using namespace std;
static bool operator<(const ghost_tsmttsm_parameters_t &a, const ghost_tsmttsm_parameters_t &b)
{
return ghost_hash(a.dt,a.wcols,ghost_hash(a.vcols,a.impl,0)) < ghost_hash(b.dt,b.wcols,ghost_hash(b.vcols,b.impl,0));
}
static map<ghost_tsmttsm_parameters_t, ghost_tsmttsm_kernel_t> ghost_tsmttsm_kernels;
ghost_error_t ghost_tsmttsm_valid(ghost_densemat_t *x, ghost_densemat_t *v, const char * transv,
ghost_densemat_t *w, const char *transw, void *alpha, void *beta, int reduce, int printerror)
{
if (w->traits.storage != GHOST_DENSEMAT_ROWMAJOR) {
if (printerror) {
ERROR_LOG("w must be stored row-major!");
}
return GHOST_ERR_INVALID_ARG;
}
if (v->traits.storage != GHOST_DENSEMAT_ROWMAJOR) {
if (printerror) {
ERROR_LOG("v must be stored row-major!");
}
return GHOST_ERR_INVALID_ARG;
}
if (x->traits.storage != GHOST_DENSEMAT_COLMAJOR) {
if (printerror) {
ERROR_LOG("x must be stored col-major!");
}
return GHOST_ERR_INVALID_ARG;
}
if (v->traits.datatype != w->traits.datatype || v->traits.datatype != x->traits.datatype) {
if (printerror) {
ERROR_LOG("Different data types!");
}
return GHOST_ERR_INVALID_ARG;
}
if (v->traits.flags & GHOST_DENSEMAT_SCATTERED || w->traits.flags & GHOST_DENSEMAT_SCATTERED || x->traits.flags & GHOST_DENSEMAT_SCATTERED) {
if (printerror) {
ERROR_LOG("Scattered densemats not supported!");
}
return GHOST_ERR_INVALID_ARG;
}
if (reduce != GHOST_GEMM_ALL_REDUCE) {
if (printerror) {
ERROR_LOG("Only Allreduce supported currently!");
}
return GHOST_ERR_INVALID_ARG;
}
if (!strncasecmp(transv,"N",1)) {
if (printerror) {
ERROR_LOG("v must be transposed!");
}
return GHOST_ERR_INVALID_ARG;
}
if (strncasecmp(transw,"N",1)) {
if (printerror) {
ERROR_LOG("w must not be transposed!");
}
return GHOST_ERR_INVALID_ARG;
}
UNUSED(alpha);
UNUSED(beta);
return GHOST_SUCCESS;
}
ghost_error_t ghost_tsmttsm(ghost_densemat_t *x, ghost_densemat_t *v, ghost_densemat_t *w, void *alpha, void *beta,int reduce,int conjv)
{
GHOST_FUNC_ENTER(GHOST_FUNCTYPE_MATH);
ghost_error_t ret;
if ((ret = ghost_tsmttsm_valid(x,v,"T",w,"N",alpha,beta,reduce,1)) != GHOST_SUCCESS) {
return ret;
}
if (ghost_tsmttsm_kernels.empty()) {
#include "tsmttsm.def"
#include "tsmttsm_avx.def"
}
ghost_tsmttsm_parameters_t p;
ghost_tsmttsm_kernel_t kernel = NULL;
#ifdef GHOST_HAVE_MIC
p.impl = GHOST_IMPLEMENTATION_MIC;
#elif defined(GHOST_HAVE_AVX)
p.impl = GHOST_IMPLEMENTATION_AVX;
#elif defined(GHOST_HAVE_SSE)
p.impl = GHOST_IMPLEMENTATION_SSE;
#else
p.impl = GHOST_IMPLEMENTATION_PLAIN;
#endif
/*if (x->traits.ncolspadded < 4 || x->traits.flags & GHOST_DENSEMAT_VIEW) {
p.impl = GHOST_IMPLEMENTATION_PLAIN;
}*/
p.dt = x->traits.datatype;
p.vcols = v->traits.ncols;
p.wcols = w->traits.ncols;
if (p.vcols % 4 || p.wcols % 4) {
PERFWARNING_LOG("Use plain for non-multiple of four");
p.impl = GHOST_IMPLEMENTATION_PLAIN;
}
kernel = ghost_tsmttsm_kernels[p];
if (!kernel) {
PERFWARNING_LOG("Try kernel with arbitrary wcols");
p.wcols = -1;
p.vcols = v->traits.ncols;
kernel = ghost_tsmttsm_kernels[p];
}
if (!kernel) {
PERFWARNING_LOG("Try kernel with arbitrary vcols");
p.wcols = w->traits.ncols;
p.vcols = -1;
kernel = ghost_tsmttsm_kernels[p];
}
if (!kernel) {
PERFWARNING_LOG("Try kernel with arbitrary block sizes");
p.wcols = -1;
p.vcols = -1;
kernel = ghost_tsmttsm_kernels[p];
}
if (!kernel) {
PERFWARNING_LOG("Try plain implementation");
p.impl = GHOST_IMPLEMENTATION_PLAIN;
p.vcols = v->traits.ncols;
p.wcols = w->traits.ncols;
kernel = ghost_tsmttsm_kernels[p];
}
if (!kernel) {
PERFWARNING_LOG("Try kernel with arbitrary wcols");
p.wcols = -1;
p.vcols = v->traits.ncols;
kernel = ghost_tsmttsm_kernels[p];
}
if (!kernel) {
PERFWARNING_LOG("Try kernel with arbitrary vcols");
p.wcols = w->traits.ncols;
p.vcols = -1;
kernel = ghost_tsmttsm_kernels[p];
}
if (!kernel) {
PERFWARNING_LOG("Try kernel with arbitrary block sizes");
p.wcols = -1;
p.vcols = -1;
kernel = ghost_tsmttsm_kernels[p];
}
if (!kernel) {
INFO_LOG("Could not find TSMTTSM kernel with %d %d %d. Fallback to GEMM",p.dt,p.wcols,p.vcols);
return GHOST_ERR_INVALID_ARG;
//return ghost_gemm(x,v,"T",w,"N",alpha,beta,GHOST_GEMM_ALL_REDUCE,GHOST_GEMM_NOT_SPECIAL);
}
ret = kernel(x,v,w,alpha,beta,conjv);
#ifdef GHOST_HAVE_INSTR_TIMING
ghost_gemm_perf_args_t tsmttsm_perfargs;
tsmttsm_perfargs.xcols = p.wcols;
tsmttsm_perfargs.vcols = p.vcols;
if (v->context) {
tsmttsm_perfargs.vrows = v->context->gnrows;
} else {
tsmttsm_perfargs.vrows = v->traits.nrows;
}
tsmttsm_perfargs.dt = x->traits.datatype;
ghost_timing_set_perfFunc(__ghost_functag,ghost_gemm_perf_GFs,(void *)&tsmttsm_perfargs,sizeof(tsmttsm_perfargs),"GF/s");
#endif
GHOST_FUNC_EXIT(GHOST_FUNCTYPE_MATH);
return ret;
}
<|endoftext|>
|
<commit_before>// -*-c++-*-
#include <osgProducer/Viewer>
#include <osgDB/ReadFile>
#include <osg/Geode>
#include <osg/Geometry>
#include <osg/StateSet>
#include <osg/Material>
#include <osg/Texture2D>
#include <osg/TextureRectangle>
#include <osg/TexMat>
#include <osg/CullFace>
#include <osgGA/TrackballManipulator>
osg::Geometry* createTexturedQuadGeometry(const osg::Vec3& pos,float width,float height, osg::Image* image)
{
bool useTextureRectangle = true;
if (useTextureRectangle)
{
osg::Geometry* pictureQuad = osg::createTexturedQuadGeometry(pos,
osg::Vec3(width,0.0f,0.0f),
osg::Vec3(0.0f,0.0f,height),
image->s(),image->t());
pictureQuad->getOrCreateStateSet()->setTextureAttributeAndModes(0,
new osg::TextureRectangle(image),
osg::StateAttribute::ON);
return pictureQuad;
}
else
{
osg::Geometry* pictureQuad = osg::createTexturedQuadGeometry(pos,
osg::Vec3(width,0.0f,0.0f),
osg::Vec3(0.0f,0.0f,height),
1.0f,1.0f);
pictureQuad->getOrCreateStateSet()->setTextureAttributeAndModes(0,
new osg::Texture2D(image),
osg::StateAttribute::ON);
return pictureQuad;
}
}
int main(int argc, char** argv)
{
// use an ArgumentParser object to manage the program arguments.
osg::ArgumentParser arguments(&argc,argv);
// set up the usage document, in case we need to print out how to use this program.
arguments.getApplicationUsage()->setApplicationName(arguments.getApplicationName());
arguments.getApplicationUsage()->setDescription(arguments.getApplicationName()+" is the standard OpenSceneGraph example which loads and visualises 3d models.");
arguments.getApplicationUsage()->setCommandLineUsage(arguments.getApplicationName()+" [options] filename ...");
arguments.getApplicationUsage()->addCommandLineOption("-h or --help","Display this information");
// construct the viewer.
osgProducer::Viewer viewer(arguments);
// set up the value with sensible default event handlers.
viewer.setUpViewer(osgProducer::Viewer::STANDARD_SETTINGS);
// get details on keyboard and mouse bindings used by the viewer.
viewer.getUsage(*arguments.getApplicationUsage());
// if user request help write it out to cout.
if (arguments.read("-h") || arguments.read("--help"))
{
arguments.getApplicationUsage()->write(std::cout);
return 1;
}
osg::Geode* geode = new osg::Geode;
osg::Vec3 pos(0.0f,0.0f,0.0f);
for(int i=1;i<arguments.argc();++i)
{
if (arguments.isString(i))
{
osg::Image* image = osgDB::readImageFile(arguments[i]);
geode->addDrawable(createTexturedQuadGeometry(pos,image->s(),image->t(),image));
}
}
// report any errors if they have occured when parsing the program aguments.
if (arguments.errors())
{
arguments.writeErrorMessages(std::cout);
return 1;
}
if (arguments.argc()<=1)
{
arguments.getApplicationUsage()->write(std::cout,osg::ApplicationUsage::COMMAND_LINE_OPTION);
return 1;
}
// any option left unread are converted into errors to write out later.
arguments.reportRemainingOptionsAsUnrecognized();
// report any errors if they have occured when parsing the program aguments.
if (arguments.errors())
{
arguments.writeErrorMessages(std::cout);
}
// set the scene to render
viewer.setSceneData(geode);
// create the windows and run the threads.
viewer.realize();
while( !viewer.done() )
{
// wait for all cull and draw threads to complete.
viewer.sync();
// update the scene by traversing it with the the update visitor which will
// call all node update callbacks and animations.
viewer.update();
// fire off the cull and draw traversals of the scene.
viewer.frame();
}
// wait for all cull and draw threads to complete before exit.
viewer.sync();
return 0;
}
<commit_msg>Added some basic event handler.<commit_after>// -*-c++-*-
#include <osgProducer/Viewer>
#include <osgDB/ReadFile>
#include <osg/Geode>
#include <osg/Geometry>
#include <osg/StateSet>
#include <osg/Material>
#include <osg/Texture2D>
#include <osg/TextureRectangle>
#include <osg/TexMat>
#include <osg/CullFace>
#include <osg/ImageStream>
#include <osgGA/TrackballManipulator>
class MovieEventHandler : public osgGA::GUIEventHandler
{
public:
MovieEventHandler() {}
void set(osg::Node* node);
virtual void accept(osgGA::GUIEventHandlerVisitor& v) { v.visit(*this); }
virtual bool handle(const osgGA::GUIEventAdapter& ea,osgGA::GUIActionAdapter&);
virtual void getUsage(osg::ApplicationUsage& usage) const;
typedef std::vector< osg::ref_ptr<osg::ImageStream> > ImageStreamList;
protected:
virtual ~MovieEventHandler() {}
class FindImageStreamsVisitor : public osg::NodeVisitor
{
public:
FindImageStreamsVisitor(ImageStreamList& imageStreamList):
_imageStreamList(imageStreamList) {}
virtual void apply(osg::Geode& geode)
{
apply(geode.getStateSet());
for(unsigned int i=0;i<geode.getNumDrawables();++i)
{
apply(geode.getDrawable(i)->getStateSet());
}
traverse(geode);
}
virtual void apply(osg::Node& node)
{
apply(node.getStateSet());
traverse(node);
}
inline void apply(osg::StateSet* stateset)
{
if (!stateset) return;
osg::StateAttribute* attr = stateset->getTextureAttribute(0,osg::StateAttribute::TEXTURE);
if (attr)
{
osg::Texture2D* texture2D = dynamic_cast<osg::Texture2D*>(attr);
if (texture2D) apply(dynamic_cast<osg::ImageStream*>(texture2D->getImage()));
osg::TextureRectangle* textureRec = dynamic_cast<osg::TextureRectangle*>(attr);
if (textureRec) apply(dynamic_cast<osg::ImageStream*>(textureRec->getImage()));
}
}
inline void apply(osg::ImageStream* imagestream)
{
if (imagestream) _imageStreamList.push_back(imagestream);
}
ImageStreamList& _imageStreamList;
};
ImageStreamList _imageStreamList;
};
void MovieEventHandler::set(osg::Node* node)
{
_imageStreamList.clear();
if (node)
{
FindImageStreamsVisitor fisv(_imageStreamList);
node->accept(fisv);
}
}
bool MovieEventHandler::handle(const osgGA::GUIEventAdapter& ea,osgGA::GUIActionAdapter&)
{
switch(ea.getEventType())
{
case(osgGA::GUIEventAdapter::KEYDOWN):
{
if (ea.getKey()=='s')
{
for(ImageStreamList::iterator itr=_imageStreamList.begin();
itr!=_imageStreamList.end();
++itr)
{
std::cout<<"Play"<<std::endl;
(*itr)->play();
}
return true;
}
else if (ea.getKey()=='p')
{
for(ImageStreamList::iterator itr=_imageStreamList.begin();
itr!=_imageStreamList.end();
++itr)
{
std::cout<<"Pause"<<std::endl;
(*itr)->pause();
}
return true;
}
else if (ea.getKey()=='r')
{
return true;
}
else if (ea.getKey()=='l')
{
return true;
}
return false;
}
default:
return false;
}
}
void MovieEventHandler::getUsage(osg::ApplicationUsage& usage) const
{
usage.addKeyboardMouseBinding("p","Pause movie");
usage.addKeyboardMouseBinding("s","Play movie");
usage.addKeyboardMouseBinding("r","Start movie");
usage.addKeyboardMouseBinding("l","Toggle looping of movie");
}
osg::Geometry* createTexturedQuadGeometry(const osg::Vec3& pos,float width,float height, osg::Image* image)
{
bool useTextureRectangle = true;
if (useTextureRectangle)
{
osg::Geometry* pictureQuad = osg::createTexturedQuadGeometry(pos,
osg::Vec3(width,0.0f,0.0f),
osg::Vec3(0.0f,0.0f,height),
image->s(),image->t());
pictureQuad->getOrCreateStateSet()->setTextureAttributeAndModes(0,
new osg::TextureRectangle(image),
osg::StateAttribute::ON);
return pictureQuad;
}
else
{
osg::Geometry* pictureQuad = osg::createTexturedQuadGeometry(pos,
osg::Vec3(width,0.0f,0.0f),
osg::Vec3(0.0f,0.0f,height),
1.0f,1.0f);
pictureQuad->getOrCreateStateSet()->setTextureAttributeAndModes(0,
new osg::Texture2D(image),
osg::StateAttribute::ON);
return pictureQuad;
}
}
int main(int argc, char** argv)
{
// use an ArgumentParser object to manage the program arguments.
osg::ArgumentParser arguments(&argc,argv);
// set up the usage document, in case we need to print out how to use this program.
arguments.getApplicationUsage()->setApplicationName(arguments.getApplicationName());
arguments.getApplicationUsage()->setDescription(arguments.getApplicationName()+" is the standard OpenSceneGraph example which loads and visualises 3d models.");
arguments.getApplicationUsage()->setCommandLineUsage(arguments.getApplicationName()+" [options] filename ...");
arguments.getApplicationUsage()->addCommandLineOption("-h or --help","Display this information");
// construct the viewer.
osgProducer::Viewer viewer(arguments);
// set up the value with sensible default event handlers.
viewer.setUpViewer(osgProducer::Viewer::STANDARD_SETTINGS);
// register the handler to add keyboard and mosue handling.
MovieEventHandler* meh = new MovieEventHandler();
viewer.getEventHandlerList().push_front(meh);
// get details on keyboard and mouse bindings used by the viewer.
viewer.getUsage(*arguments.getApplicationUsage());
// if user request help write it out to cout.
if (arguments.read("-h") || arguments.read("--help"))
{
arguments.getApplicationUsage()->write(std::cout);
return 1;
}
osg::Geode* geode = new osg::Geode;
osg::Vec3 pos(0.0f,0.0f,0.0f);
for(int i=1;i<arguments.argc();++i)
{
if (arguments.isString(i))
{
osg::Image* image = osgDB::readImageFile(arguments[i]);
geode->addDrawable(createTexturedQuadGeometry(pos,image->s(),image->t(),image));
}
}
// pass the model to the MovieEventHandler so it can pick out ImageStream's to manipulate.
meh->set(geode);
// report any errors if they have occured when parsing the program aguments.
if (arguments.errors())
{
arguments.writeErrorMessages(std::cout);
return 1;
}
if (arguments.argc()<=1)
{
arguments.getApplicationUsage()->write(std::cout,osg::ApplicationUsage::COMMAND_LINE_OPTION);
return 1;
}
// any option left unread are converted into errors to write out later.
arguments.reportRemainingOptionsAsUnrecognized();
// report any errors if they have occured when parsing the program aguments.
if (arguments.errors())
{
arguments.writeErrorMessages(std::cout);
}
// set the scene to render
viewer.setSceneData(geode);
// create the windows and run the threads.
viewer.realize();
while( !viewer.done() )
{
// wait for all cull and draw threads to complete.
viewer.sync();
// update the scene by traversing it with the the update visitor which will
// call all node update callbacks and animations.
viewer.update();
// fire off the cull and draw traversals of the scene.
viewer.frame();
}
// wait for all cull and draw threads to complete before exit.
viewer.sync();
return 0;
}
<|endoftext|>
|
<commit_before>#include<stdio.h>
#include<malloc.h>
#define ERROR 0
#define OK 1
#define ElemType int
typedef int Status;
typedef struct LNode
{
int data;
struct LNode *next;
}LNode,*LinkList;
int CreateLink_L(LinkList &L,int n){
// 创建含有n个元素的单链表
LinkList p,q;
int i;
ElemType e;
L = (LinkList)malloc(sizeof(LNode));
L->next = NULL; // 先建立一个带头结点的单链表
q = (LinkList)malloc(sizeof(LNode));
q = L;
for (i=0; i<n; i++) {
scanf("%d", &e);
p = (LinkList)malloc(sizeof(LNode));
p->next=NULL; // 生成新结点
q->next=p;
p->data=e;
q=p;
}
return OK;
}
int LoadLink_L(LinkList &L,char * name){
// 单链表遍历
LinkList p = L->next;
if(p==NULL)printf("The List is empty!"); // 请填空
else
{
printf("List %s:",name);
while(p) // 请填空
{
printf("%d ",p->data);
p=p->next; // 请填空
}
}
printf("\n");
return OK;
}
Status ListInsert_L(LinkList &L, int i, ElemType e) { // 算法2.9
// 在带头结点的单链线性表L的第i个元素之前插入元素e
LinkList p,s;
p = L;
int j = 0;
while (p && j < i-1) { // 寻找第i-1个结点
p = p->next;
++j;
}
if (!p || j > i-1) return ERROR; // i小于1或者大于表长
s = (LinkList)malloc(sizeof(LNode)); // 生成新结点
s->data = e; s->next = p->next; // 插入L中
p->next = s;
return OK;
} // LinstInsert_L
Status ListDelete_L(LinkList &L, int i, ElemType &e) { // 算法2.10
// 在带头结点的单链线性表L中,删除第i个元素,并由e返回其值
LinkList p,q;
p = L;
int j = 0;
while (p->next && j < i-1) { // 寻找第i个结点,并令p指向其前趋
p = p->next;
++j;
}
if (!(p->next) || j > i-1) return ERROR; // 删除位置不合理
q = p->next;
p->next = q->next; // 删除并释放结点
e = q->data;
free(q);
return OK;
} // ListDelete_L
Status Linkunion_L(LinkList a,LinkList b,LinkList c){
LinkList pa,pb,pc;
pa=a->next,pb=b->next;
pc=c;
int i=1;
while(pa||pb){
if(pa==NULL)
{pc->next=pb;return OK;}
if(pb==NULL)
{pc->next=pa;return OK;}
if((pa->data)<(pb->data)){
pc->next=pa;
pc=pa;
pa=pa->next;
}else
{
pc->next=pb;
pc=pb;
pb=pb->next;
}
}
}
Status Linkturn(LinkList &L){
LNode * end=NULL,*p,*q,*c;
p=L->next;
while(1){
while(1){
if(p->next->next==NULL){
q=p->next;
p->next=NULL;
break;
}
p=p->next;
}
if(end==NULL){
end=q;
c=q;
}else{
c->next=q;
c=q;
}
if (p==L){
c->next=p;
break;}
p=L;
}
L=end;
}
int main(int argc, char const *argv[])
{
int n,m;
scanf("%d",&n);
LinkList A;
CreateLink_L(A,n);
LoadLink_L(A,"A");
Linkturn(A);
return 0;
}<commit_msg>update uoj8581<commit_after>#include<stdio.h>
#include<malloc.h>
#define ERROR 0
#define OK 1
#define ElemType int
typedef int Status;
typedef struct LNode
{
int data;
struct LNode *next;
}LNode,*LinkList;
int CreateLink_L(LinkList &L,int n){
// 创建含有n个元素的单链表
LinkList p,q;
int i;
ElemType e;
L = (LinkList)malloc(sizeof(LNode));
L->next = NULL;
L->data=n; // 先建立一个带头结点的单链表
q = (LinkList)malloc(sizeof(LNode));
q = L;
for (i=0; i<n; i++) {
scanf("%d", &e);
p = (LinkList)malloc(sizeof(LNode));
p->next=NULL; // 生成新结点
q->next=p;
p->data=e;
q=p;
}
return OK;
}
int LoadLink_L(LinkList &L,char * name){
// 单链表遍历
LinkList p = L->next;
if(p==NULL)printf("The List is empty!"); // 请填空
else
{
printf("List %s:",name);
while(p) // 请填空
{
printf("%d ",p->data);
p=p->next; // 请填空
}
}
printf("\n");
return OK;
}
Status ListInsert_L(LinkList &L, int i, ElemType e) { // 算法2.9
// 在带头结点的单链线性表L的第i个元素之前插入元素e
LinkList p,s;
p = L;
int j = 0;
while (p && j < i-1) { // 寻找第i-1个结点
p = p->next;
++j;
}
if (!p || j > i-1) return ERROR; // i小于1或者大于表长
s = (LinkList)malloc(sizeof(LNode)); // 生成新结点
s->data = e; s->next = p->next; // 插入L中
p->next = s;
L->data++;
return OK;
} // LinstInsert_L
Status ListDelete_L(LinkList &L, int i, ElemType &e) { // 算法2.10
// 在带头结点的单链线性表L中,删除第i个元素,并由e返回其值
LinkList p,q;
p = L;
int j = 0;
while (p->next && j < i-1) { // 寻找第i个结点,并令p指向其前趋
p = p->next;
++j;
}
if (!(p->next) || j > i-1) return ERROR; // 删除位置不合理
q = p->next;
p->next = q->next; // 删除并释放结点
e = q->data;
free(q);
L->data--;
return OK;
} // ListDelete_L
Status Linkunion_L(LinkList a,LinkList b,LinkList c){
LinkList pa,pb,pc;
pa=a->next,pb=b->next;
pc=c;
int i=1;
while(pa||pb){
if(pa==NULL)
{pc->next=pb;return OK;}
if(pb==NULL)
{pc->next=pa;return OK;}
if((pa->data)<(pb->data)){
pc->next=pa;
pc=pa;
pa=pa->next;
}else
{
pc->next=pb;
pc=pb;
pb=pb->next;
}
}
}
Status Linkturn(LinkList &L){
LinkList out;
ElemType e;
while(L->data>0){
ListDelete_L(L,L->data, ElemType &e) ;
printf("%d",e);
}
for
}
int main(int argc, char const *argv[])
{
int n,m;
scanf("%d",&n);
LinkList A;
CreateLink_L(A,n);
LoadLink_L(A,"A");
Linkturn(A);
return 0;
}<|endoftext|>
|
<commit_before>/*
vcflib C++ library for parsing and manipulating VCF files
Copyright © 2010-2022 Erik Garrison
Copyright © 2020-2022 Pjotr Prins
This software is published under the MIT License. See the LICENSE file.
*/
#include <algorithm>
#include <string>
#include <ranges>
#include <set>
#include <utility>
#include <vector>
#include <getopt.h>
#include <omp.h>
#include "Variant.h"
#include "convert.h"
#include "join.h"
#include "split.h"
using namespace std;
using namespace vcflib;
#define ALLELE_NULL -1
#define ALLELE_NULL2 -200 // large number brings out issues
double convertStrDbl(const string& s) {
double r;
convert(s, r);
return r;
}
void printSummary(char** argv) {
std::string text = R"(
usage: vcfwave [options] [file]
Realign reference and alternate alleles with WFA, parsing out the primitive alleles
into multiple VCF records. New records have IDs that reference the source record ID.
Genotypes are handled. Deletions generate haploid/missing genotypes at overlapping sites.
options:
-p, --wf-params PARAMS use the given BiWFA params (default: 0,19,39,3,81,1)
format=match,mismatch,gap1-open,gap1-ext,gap2-open,gap2-ext
-f, --tag-parsed FLAG Annotate decomposed records with the source record position
(default: ORIGIN).
-L, --max-length LEN Do not manipulate records in which either the ALT or
REF is longer than LEN (default: unlimited).
-K, --inv-kmer K Length of k-mer to use for inversion detection sketching (default: 17).
-I, --inv-min LEN Minimum allele length to consider for inverted alignment (default: 64).
-k, --keep-info Maintain site and allele-level annotations when decomposing.
Note that in many cases, such as multisample VCFs, these won't
be valid post-decomposition. For biallelic loci in single-sample
VCFs, they should be usable with caution.
-t, --threads N use this many threads for variant decomposition
-n, --nextgen next gen mode.
-d, --debug debug mode.
Type: transformation
)";
cerr << text;
exit(0);
}
int main(int argc, char** argv) {
bool includePreviousBaseForIndels = true;
bool useMNPs = true;
string parseFlag = "ORIGIN";
string algorithm = "WF";
string paramString = "0,19,39,3,81,1";
int maxLength = 0;
bool keepInfo = false;
bool keepGeno = false;
bool useWaveFront = true;
bool nextGen = false;
bool debug = false;
int thread_count = 1;
int inv_sketch_kmer = 17;
int min_inv_len = 64;
VariantCallFile variantFile;
int c;
while (true) {
static struct option long_options[] =
{
/* These options set a flag. */
//{"verbose", no_argument, &verbose_flag, 1},
{"help", no_argument, 0, 'h'},
{"wf-params", required_argument, 0, 'p'},
{"max-length", required_argument, 0, 'L'},
{"inv-kmer", required_argument, 0, 'K'},
{"inv-min", required_argument, 0, 'I'},
{"tag-parsed", required_argument, 0, 'f'},
{"keep-info", no_argument, 0, 'k'},
{"keep-geno", no_argument, 0, 'g'},
{"threads", required_argument, 0, 't'},
{"nextgen", no_argument, 0, 'n'},
{"debug", no_argument, 0, 'd'},
{0, 0, 0, 0}
};
/* getopt_long stores the option index here. */
int option_index = 0;
c = getopt_long (argc, argv, "ndhkt:L:p:t:K:I:f:",
long_options, &option_index);
if (c == -1)
break;
switch (c) {
case 'k':
keepInfo = true;
break;
case 'g':
keepGeno = true;
break;
case 'p':
paramString = optarg;
break;
case 't':
thread_count = atoi(optarg);
break;
case 'n':
nextGen = true;
break;
case 'd':
debug = true;
break;
case 'h':
printSummary(argv);
break;
case 'f':
parseFlag = optarg;
break;
case 'L':
maxLength = atoi(optarg);
break;
case 'K':
inv_sketch_kmer = atoi(optarg);
break;
case 'I':
min_inv_len = atoi(optarg);
break;
case '?':
printSummary(argv);
exit(1);
break;
default:
abort ();
}
}
omp_set_num_threads(thread_count);
if (optind < argc) {
string filename = argv[optind];
variantFile.open(filename);
} else {
variantFile.open(std::cin);
}
if (!variantFile.is_open()) {
return 1;
}
// parse the alignment parameters
vector<string> p_str = split(paramString, ',');
vector<int> p;
for (auto& s : p_str) { p.push_back(atoi(s.c_str())); }
auto wfa_params = wavefront_aligner_attr_default;
wfa_params.memory_mode = wavefront_memory_ultralow; // note this is overridden in Variant.cpp
wfa_params.distance_metric = gap_affine_2p;
wfa_params.affine2p_penalties.match = p[0];
wfa_params.affine2p_penalties.mismatch = p[1];
wfa_params.affine2p_penalties.gap_opening1 = p[2];
wfa_params.affine2p_penalties.gap_extension1 = p[3];
wfa_params.affine2p_penalties.gap_opening2 = p[4];
wfa_params.affine2p_penalties.gap_extension2 = p[5];
wfa_params.alignment_scope = compute_alignment;
variantFile.addHeaderLine("##INFO=<ID=TYPE,Number=A,Type=String,Description=\"The type of allele, either snp, mnp, ins, del, or complex.\">");
variantFile.addHeaderLine("##INFO=<ID=LEN,Number=A,Type=Integer,Description=\"allele length\">");
variantFile.addHeaderLine("##INFO=<ID="+parseFlag+",Number=1,Type=String,Description=\"Decomposed from a complex record using vcflib vcfwave and alignment with WFA2-lib.\">");
variantFile.addHeaderLine("##INFO=<ID=INV,Number=A,Type=String,Description=\"Count of haplotypes which are aligned in the inverted orientation using vcflib vcfwave.\">");
cout << variantFile.header << endl;
Variant var(variantFile);
while (variantFile.getNextVariant(var)) {
// we can't decompose *1* bp events, these are already in simplest-form whether SNPs or indels
// we also don't handle anything larger than maxLength bp
int max_allele_length = 0;
for (auto allele: var.alt) {
if (debug) cerr << allele << ":" << allele.length() << "," << max_allele_length << endl;
if (allele.length() >= max_allele_length) {
max_allele_length = allele.length();
// cerr << max_allele_length << endl;
}
}
if ((maxLength && max_allele_length > maxLength) || max_allele_length == 1 ||
(var.alt.size() == 1 &&
(var.ref.size() == 1 || (maxLength && var.ref.size() > maxLength)))) {
// nothing to do
cout << var << endl;
continue;
}
map<string, pair<vector<VariantAllele>, bool> > varAlleles =
var.parsedAlternates(includePreviousBaseForIndels, useMNPs,
false, // bool useEntropy = false,
"", // string flankingRefLeft = "",
"", // string flankingRefRight = "",
&wfa_params,
inv_sketch_kmer,
min_inv_len,
debug); // bool debug=false
if (nextGen) {
// The following section post-process the results of wavefront and
// updates AC, AF and genotype values
typedef vector<int> Genotypes;
typedef vector<Genotypes> RecGenotypes;
struct trackinfo {
size_t pos0 = 0;
string ref0, alt0, ref1, algn;
size_t pos1 = 0;
size_t altidx;
int relpos;
int AC,AF,AN;
bool is_inv = false;
string type;
string origin;
RecGenotypes genotypes;
};
typedef map<string, trackinfo> TrackInfo;
TrackInfo unique; // Track all alleles
// Unpack wavefront results and set values for each unique allele
for (const auto [alt0, wfvalue] : varAlleles) {
bool is_inv = wfvalue.second;
for (auto wfmatch: wfvalue.first) {
auto ref = wfmatch.ref;
auto aligned = wfmatch.alt;
auto wfpos = wfmatch.position;
int alt_index,AC,AN = -1;
double AF = 0.0;
string wftag = alt0+":"+to_string(wfpos)+":"+ref+"/"+aligned;
if (var.ref != aligned) {
auto index = [](vector<string> v, string allele) {
auto it = find(v.begin(), v.end(), allele);
return (it == v.end() ? throw std::runtime_error("Unexpected value error for allele "+allele) : it - v.begin() );
};
alt_index = index(var.alt,alt0); // throws error if missing
AC = stoi(var.info["AC"].at(alt_index));
AF = stod(var.info["AF"].at(alt_index));
AN = stoi(var.info["AN"].at(0));
}
auto relpos = wfpos - var.position;
auto u = &unique[wftag];
u->pos0 = var.position;
u->ref0 = var.ref;
u->alt0 = alt0;
u->ref1 = ref;
u->algn = aligned;
u->pos1 = wfpos;
u->altidx = alt_index;
u->relpos = relpos;
u->AC = AC;
u->AF = AF;
u->AN = AN;
u->is_inv = is_inv;
}
}
// Collect genotypes for every allele from the main record. This code is
// effectively mirrored in Python in realign.py:
RecGenotypes genotypes;
auto samples = var.samples;
for (auto sname: var.sampleNames) {
auto genotype1 = samples[sname]["GT"].front();
vector<string> genotypeStrs = split(genotype1, "|/");
Genotypes gts;
std::transform(genotypeStrs.begin(), genotypeStrs.end(), std::back_inserter(gts), [](auto n){ return (n == "." ? ALLELE_NULL2 : stoi(n)); });
genotypes.push_back(gts);
}
// Now plug in the new indices for listed genotypes
for (auto [tag,aln]: unique) {
RecGenotypes aln_genotypes = genotypes; // make a copy
auto altidx1 = aln.altidx+1;
for (auto >: aln_genotypes) {
int i = 0;
for (auto g: gt) {
if (g == altidx1)
gt[i] = 1; // one genotype in play
else
if (g != ALLELE_NULL2) gt[i] = 0;
i++;
}
}
unique[tag].genotypes = aln_genotypes;
}
// Merge records that describe the exact same variant (in
// earlier jargon a 'primitive allele' in a new dict named
// variants and adjust AC, AF and genotypes:
TrackInfo track_variants;
for (auto [key,v] : unique) {
auto ref = v.ref1;
auto aligned = v.algn;
if (ref != aligned) {
auto ntag = to_string(v.pos1) + ":" + ref + "/" + aligned + "_" + to_string(v.is_inv);
if (track_variants.count(ntag)>0) { // this variant already exists
track_variants[ntag].AC += v.AC;
// Check AN number is equal so we can compute AF by addition
assert(track_variants[ntag].AN == v.AN);
track_variants[ntag].AF += v.AF;
// Merge genotypes if they come from different alleles
if (v.altidx != track_variants[ntag].altidx) {
auto track_genotypes = track_variants[ntag].genotypes;
for (auto &sample: v.genotypes) { // all samples
int i = 0;
for (auto g: sample) { // all genotypes
if (g && sample[i]>0)
sample[i] = 1; // always one genotype in play
i++;
}
}
}
}
else {
track_variants[ntag] = v;
}
}
}
unique.clear();
// The following section updates the INFO TYPE and INV field:
// Adjust TYPE field to set snp/mnp/ins/del
for (auto [key,v] : track_variants) {
auto ref_len = v.ref1.length();
auto aln_len = v.algn.length();
string type;
if (aln_len < ref_len)
type = "del";
else if (aln_len > ref_len)
type = "ins";
else if (aln_len == ref_len)
if (ref_len == 1)
type = "snp";
else
type = "mnp";
v.type = type;
v.origin = var.sequenceName+":"+to_string(var.position);
track_variants[key] = v;
}
// The following section output all tracked alleles one by one:
int ct = 0;
for (auto [key,v]: track_variants) {
ct++;
Variant newvar(variantFile);
newvar.sequenceName = var.sequenceName;
newvar.position = v.pos1;
newvar.id = var.id + "_" + to_string(ct);
newvar.ref = v.ref1;
newvar.alt.push_back(v.algn);
newvar.quality = var.quality;
newvar.info = var.info;
vector<string> AC{ to_string(v.AC) };
vector<string> AF{ to_string(v.AF) };
vector<string> AN{ to_string(v.AN) };
vector<string> ORIGIN{ v.origin };
vector<string> TYPE{ v.type };
newvar.info["AC"] = AC;
newvar.info["AF"] = AF;
newvar.info["AN"] = AN;
newvar.info[parseFlag] = ORIGIN;
newvar.info["TYPE"] = TYPE;
newvar.info["INV"] = vector<string>{to_string(v.is_inv)};
// newvar.format = var.format;
// newvar.sampleNames = var.sampleNames;
// newvar.outputSampleNames = var.outputSampleNames;
// newvar.samples = v.genotypeStrs;
// Instead of using above format output we now simply print genotypes
cout.precision(2);
cout << newvar;
cout << "\tGT";
for (auto gts: v.genotypes) {
cout << "\t";
int idx = 0;
for (auto gt : gts) {
cout << (gt == ALLELE_NULL2 ? "." : to_string(gt));
if (idx < gts.size()-1) cout << "|";
idx++;
}
}
cout << endl;
}
}
else {
var.legacy_reduceAlleles(
varAlleles,
variantFile,
var,
parseFlag,
keepInfo,
keepGeno,
debug);
}
}
return 0;
}
<commit_msg>Fix CI error on ranges<commit_after>/*
vcflib C++ library for parsing and manipulating VCF files
Copyright © 2010-2022 Erik Garrison
Copyright © 2020-2022 Pjotr Prins
This software is published under the MIT License. See the LICENSE file.
*/
#include <algorithm>
#include <string>
#include <set>
#include <utility>
#include <vector>
#include <getopt.h>
#include <omp.h>
#include "Variant.h"
#include "convert.h"
#include "join.h"
#include "split.h"
using namespace std;
using namespace vcflib;
#define ALLELE_NULL -1
#define ALLELE_NULL2 -200 // large number brings out issues
double convertStrDbl(const string& s) {
double r;
convert(s, r);
return r;
}
void printSummary(char** argv) {
std::string text = R"(
usage: vcfwave [options] [file]
Realign reference and alternate alleles with WFA, parsing out the primitive alleles
into multiple VCF records. New records have IDs that reference the source record ID.
Genotypes are handled. Deletions generate haploid/missing genotypes at overlapping sites.
options:
-p, --wf-params PARAMS use the given BiWFA params (default: 0,19,39,3,81,1)
format=match,mismatch,gap1-open,gap1-ext,gap2-open,gap2-ext
-f, --tag-parsed FLAG Annotate decomposed records with the source record position
(default: ORIGIN).
-L, --max-length LEN Do not manipulate records in which either the ALT or
REF is longer than LEN (default: unlimited).
-K, --inv-kmer K Length of k-mer to use for inversion detection sketching (default: 17).
-I, --inv-min LEN Minimum allele length to consider for inverted alignment (default: 64).
-k, --keep-info Maintain site and allele-level annotations when decomposing.
Note that in many cases, such as multisample VCFs, these won't
be valid post-decomposition. For biallelic loci in single-sample
VCFs, they should be usable with caution.
-t, --threads N use this many threads for variant decomposition
-n, --nextgen next gen mode.
-d, --debug debug mode.
Type: transformation
)";
cerr << text;
exit(0);
}
int main(int argc, char** argv) {
bool includePreviousBaseForIndels = true;
bool useMNPs = true;
string parseFlag = "ORIGIN";
string algorithm = "WF";
string paramString = "0,19,39,3,81,1";
int maxLength = 0;
bool keepInfo = false;
bool keepGeno = false;
bool useWaveFront = true;
bool nextGen = false;
bool debug = false;
int thread_count = 1;
int inv_sketch_kmer = 17;
int min_inv_len = 64;
VariantCallFile variantFile;
int c;
while (true) {
static struct option long_options[] =
{
/* These options set a flag. */
//{"verbose", no_argument, &verbose_flag, 1},
{"help", no_argument, 0, 'h'},
{"wf-params", required_argument, 0, 'p'},
{"max-length", required_argument, 0, 'L'},
{"inv-kmer", required_argument, 0, 'K'},
{"inv-min", required_argument, 0, 'I'},
{"tag-parsed", required_argument, 0, 'f'},
{"keep-info", no_argument, 0, 'k'},
{"keep-geno", no_argument, 0, 'g'},
{"threads", required_argument, 0, 't'},
{"nextgen", no_argument, 0, 'n'},
{"debug", no_argument, 0, 'd'},
{0, 0, 0, 0}
};
/* getopt_long stores the option index here. */
int option_index = 0;
c = getopt_long (argc, argv, "ndhkt:L:p:t:K:I:f:",
long_options, &option_index);
if (c == -1)
break;
switch (c) {
case 'k':
keepInfo = true;
break;
case 'g':
keepGeno = true;
break;
case 'p':
paramString = optarg;
break;
case 't':
thread_count = atoi(optarg);
break;
case 'n':
nextGen = true;
break;
case 'd':
debug = true;
break;
case 'h':
printSummary(argv);
break;
case 'f':
parseFlag = optarg;
break;
case 'L':
maxLength = atoi(optarg);
break;
case 'K':
inv_sketch_kmer = atoi(optarg);
break;
case 'I':
min_inv_len = atoi(optarg);
break;
case '?':
printSummary(argv);
exit(1);
break;
default:
abort ();
}
}
omp_set_num_threads(thread_count);
if (optind < argc) {
string filename = argv[optind];
variantFile.open(filename);
} else {
variantFile.open(std::cin);
}
if (!variantFile.is_open()) {
return 1;
}
// parse the alignment parameters
vector<string> p_str = split(paramString, ',');
vector<int> p;
for (auto& s : p_str) { p.push_back(atoi(s.c_str())); }
auto wfa_params = wavefront_aligner_attr_default;
wfa_params.memory_mode = wavefront_memory_ultralow; // note this is overridden in Variant.cpp
wfa_params.distance_metric = gap_affine_2p;
wfa_params.affine2p_penalties.match = p[0];
wfa_params.affine2p_penalties.mismatch = p[1];
wfa_params.affine2p_penalties.gap_opening1 = p[2];
wfa_params.affine2p_penalties.gap_extension1 = p[3];
wfa_params.affine2p_penalties.gap_opening2 = p[4];
wfa_params.affine2p_penalties.gap_extension2 = p[5];
wfa_params.alignment_scope = compute_alignment;
variantFile.addHeaderLine("##INFO=<ID=TYPE,Number=A,Type=String,Description=\"The type of allele, either snp, mnp, ins, del, or complex.\">");
variantFile.addHeaderLine("##INFO=<ID=LEN,Number=A,Type=Integer,Description=\"allele length\">");
variantFile.addHeaderLine("##INFO=<ID="+parseFlag+",Number=1,Type=String,Description=\"Decomposed from a complex record using vcflib vcfwave and alignment with WFA2-lib.\">");
variantFile.addHeaderLine("##INFO=<ID=INV,Number=A,Type=String,Description=\"Count of haplotypes which are aligned in the inverted orientation using vcflib vcfwave.\">");
cout << variantFile.header << endl;
Variant var(variantFile);
while (variantFile.getNextVariant(var)) {
// we can't decompose *1* bp events, these are already in simplest-form whether SNPs or indels
// we also don't handle anything larger than maxLength bp
int max_allele_length = 0;
for (auto allele: var.alt) {
if (debug) cerr << allele << ":" << allele.length() << "," << max_allele_length << endl;
if (allele.length() >= max_allele_length) {
max_allele_length = allele.length();
// cerr << max_allele_length << endl;
}
}
if ((maxLength && max_allele_length > maxLength) || max_allele_length == 1 ||
(var.alt.size() == 1 &&
(var.ref.size() == 1 || (maxLength && var.ref.size() > maxLength)))) {
// nothing to do
cout << var << endl;
continue;
}
map<string, pair<vector<VariantAllele>, bool> > varAlleles =
var.parsedAlternates(includePreviousBaseForIndels, useMNPs,
false, // bool useEntropy = false,
"", // string flankingRefLeft = "",
"", // string flankingRefRight = "",
&wfa_params,
inv_sketch_kmer,
min_inv_len,
debug); // bool debug=false
if (nextGen) {
// The following section post-process the results of wavefront and
// updates AC, AF and genotype values
typedef vector<int> Genotypes;
typedef vector<Genotypes> RecGenotypes;
struct trackinfo {
size_t pos0 = 0;
string ref0, alt0, ref1, algn;
size_t pos1 = 0;
size_t altidx;
int relpos;
int AC,AF,AN;
bool is_inv = false;
string type;
string origin;
RecGenotypes genotypes;
};
typedef map<string, trackinfo> TrackInfo;
TrackInfo unique; // Track all alleles
// Unpack wavefront results and set values for each unique allele
for (const auto [alt0, wfvalue] : varAlleles) {
bool is_inv = wfvalue.second;
for (auto wfmatch: wfvalue.first) {
auto ref = wfmatch.ref;
auto aligned = wfmatch.alt;
auto wfpos = wfmatch.position;
int alt_index,AC,AN = -1;
double AF = 0.0;
string wftag = alt0+":"+to_string(wfpos)+":"+ref+"/"+aligned;
if (var.ref != aligned) {
auto index = [](vector<string> v, string allele) {
auto it = find(v.begin(), v.end(), allele);
return (it == v.end() ? throw std::runtime_error("Unexpected value error for allele "+allele) : it - v.begin() );
};
alt_index = index(var.alt,alt0); // throws error if missing
AC = stoi(var.info["AC"].at(alt_index));
AF = stod(var.info["AF"].at(alt_index));
AN = stoi(var.info["AN"].at(0));
}
auto relpos = wfpos - var.position;
auto u = &unique[wftag];
u->pos0 = var.position;
u->ref0 = var.ref;
u->alt0 = alt0;
u->ref1 = ref;
u->algn = aligned;
u->pos1 = wfpos;
u->altidx = alt_index;
u->relpos = relpos;
u->AC = AC;
u->AF = AF;
u->AN = AN;
u->is_inv = is_inv;
}
}
// Collect genotypes for every allele from the main record. This code is
// effectively mirrored in Python in realign.py:
RecGenotypes genotypes;
auto samples = var.samples;
for (auto sname: var.sampleNames) {
auto genotype1 = samples[sname]["GT"].front();
vector<string> genotypeStrs = split(genotype1, "|/");
Genotypes gts;
std::transform(genotypeStrs.begin(), genotypeStrs.end(), std::back_inserter(gts), [](auto n){ return (n == "." ? ALLELE_NULL2 : stoi(n)); });
genotypes.push_back(gts);
}
// Now plug in the new indices for listed genotypes
for (auto [tag,aln]: unique) {
RecGenotypes aln_genotypes = genotypes; // make a copy
auto altidx1 = aln.altidx+1;
for (auto >: aln_genotypes) {
int i = 0;
for (auto g: gt) {
if (g == altidx1)
gt[i] = 1; // one genotype in play
else
if (g != ALLELE_NULL2) gt[i] = 0;
i++;
}
}
unique[tag].genotypes = aln_genotypes;
}
// Merge records that describe the exact same variant (in
// earlier jargon a 'primitive allele' in a new dict named
// variants and adjust AC, AF and genotypes:
TrackInfo track_variants;
for (auto [key,v] : unique) {
auto ref = v.ref1;
auto aligned = v.algn;
if (ref != aligned) {
auto ntag = to_string(v.pos1) + ":" + ref + "/" + aligned + "_" + to_string(v.is_inv);
if (track_variants.count(ntag)>0) { // this variant already exists
track_variants[ntag].AC += v.AC;
// Check AN number is equal so we can compute AF by addition
assert(track_variants[ntag].AN == v.AN);
track_variants[ntag].AF += v.AF;
// Merge genotypes if they come from different alleles
if (v.altidx != track_variants[ntag].altidx) {
auto track_genotypes = track_variants[ntag].genotypes;
for (auto &sample: v.genotypes) { // all samples
int i = 0;
for (auto g: sample) { // all genotypes
if (g && sample[i]>0)
sample[i] = 1; // always one genotype in play
i++;
}
}
}
}
else {
track_variants[ntag] = v;
}
}
}
unique.clear();
// The following section updates the INFO TYPE and INV field:
// Adjust TYPE field to set snp/mnp/ins/del
for (auto [key,v] : track_variants) {
auto ref_len = v.ref1.length();
auto aln_len = v.algn.length();
string type;
if (aln_len < ref_len)
type = "del";
else if (aln_len > ref_len)
type = "ins";
else if (aln_len == ref_len)
if (ref_len == 1)
type = "snp";
else
type = "mnp";
v.type = type;
v.origin = var.sequenceName+":"+to_string(var.position);
track_variants[key] = v;
}
// The following section output all tracked alleles one by one:
int ct = 0;
for (auto [key,v]: track_variants) {
ct++;
Variant newvar(variantFile);
newvar.sequenceName = var.sequenceName;
newvar.position = v.pos1;
newvar.id = var.id + "_" + to_string(ct);
newvar.ref = v.ref1;
newvar.alt.push_back(v.algn);
newvar.quality = var.quality;
newvar.info = var.info;
vector<string> AC{ to_string(v.AC) };
vector<string> AF{ to_string(v.AF) };
vector<string> AN{ to_string(v.AN) };
vector<string> ORIGIN{ v.origin };
vector<string> TYPE{ v.type };
newvar.info["AC"] = AC;
newvar.info["AF"] = AF;
newvar.info["AN"] = AN;
newvar.info[parseFlag] = ORIGIN;
newvar.info["TYPE"] = TYPE;
newvar.info["INV"] = vector<string>{to_string(v.is_inv)};
// newvar.format = var.format;
// newvar.sampleNames = var.sampleNames;
// newvar.outputSampleNames = var.outputSampleNames;
// newvar.samples = v.genotypeStrs;
// Instead of using above format output we now simply print genotypes
cout.precision(2);
cout << newvar;
cout << "\tGT";
for (auto gts: v.genotypes) {
cout << "\t";
int idx = 0;
for (auto gt : gts) {
cout << (gt == ALLELE_NULL2 ? "." : to_string(gt));
if (idx < gts.size()-1) cout << "|";
idx++;
}
}
cout << endl;
}
}
else {
var.legacy_reduceAlleles(
varAlleles,
variantFile,
var,
parseFlag,
keepInfo,
keepGeno,
debug);
}
}
return 0;
}
<|endoftext|>
|
<commit_before>
void partialReconstructValsPQCpp(int* rowInds, int*colInds, double* P, double* Q, double* values, int size, int numCols) {
/*
* Go through and reconstruct PQ^T for the given indices
*/
int i, j;
int sum;
for(i=0;i<size;i++) {
sum = 0;
for(j=0;j<numCols;j++) {
//P[rowInds[i], :]^T Q[colInds[i], :]
sum += P[rowInds[i]*numCols + j]*P[colInds[i]*numCols + j];
}
values[i] = sum;
}
}<commit_msg>Bug fix and speedup <commit_after>
void partialReconstructValsPQCpp(int* rowInds, int*colInds, double* P, double* Q, double* values, int size, int numCols) {
/*
* Go through and reconstruct PQ^T for the given indices
*/
int i, j;
int p, q;
double sum;
for(i=0;i<size;i++) {
sum = 0;
p = rowInds[i]*numCols;
q = colInds[i]*numCols;
for(j=0;j<numCols;j++) {
//P[rowInds[i], :]^T Q[colInds[i], :]
sum += P[p + j]*Q[q + j];
}
values[i] = sum;
}
}<|endoftext|>
|
<commit_before>#include "utils.h"
void SerializeMatrix3(Matrix3 &mtx, double *output)
{
Point3 row;
row = mtx.GetRow(0);
output[0] = row.x;
output[1] = -row.z;
output[2] = -row.y;
row = mtx.GetRow(2);
output[3] = -row.x;
output[4] = row.z;
output[5] = row.y;
row = mtx.GetRow(1);
output[6] = -row.x;
output[7] = row.z;
output[8] = row.y;
row = mtx.GetRow(3);
output[9] = -row.x;
output[10] = row.z;
output[11] = row.y;
}
int IndexOfSkinMod(Object *obj, IDerivedObject **derivedObject)
{
if (obj != NULL && obj->SuperClassID() == GEN_DERIVOB_CLASS_ID) {
int i;
IDerivedObject *derived = (IDerivedObject *)obj;
for (i=0; i < derived->NumModifiers(); i++) {
Modifier *mod = derived->GetModifier(i);
void *skin = mod->GetInterface(I_SKIN);
if (skin != NULL) {
*derivedObject = derived;
return i;
}
}
}
return -1;
}
SequenceMetaData *ParseSequenceFile(const char *path)
{
FILE *fp;
fp = fopen(path, "r");
if (fp) {
char line[256];
SequenceMetaData *first, *last;
first = NULL;
last = NULL;
while (fgets(line, 256, fp) != NULL) {
SequenceMetaData *cur;
int nameLen;
char *name, *start, *end;
// Read name and skip if missing.
name = strtok(line, " ");
if (!name) continue;
nameLen = strlen(name);
// Read start frame and skip if missing.
start = strtok(NULL, " ");
if (!start) continue;
// Read end frame and skip if missing.
end = strtok(NULL, " ");
if (!end) continue;
cur = (SequenceMetaData*)malloc(sizeof(SequenceMetaData));
cur->start = strtol(start, NULL, 10);
cur->stop = strtol(end, NULL, 10);
cur->name = (char*)malloc(nameLen+1);
memcpy(cur->name, name, nameLen+1);
if (!first) {
first = cur;
}
else {
last->next = cur;
}
last = cur;
last->next = NULL;
}
return first;
}
return NULL;
}
bool FileExists(const char *path)
{
DWORD dwAttrib = GetFileAttributes(path);
return (dwAttrib != INVALID_FILE_ATTRIBUTES &&
!(dwAttrib & FILE_ATTRIBUTE_DIRECTORY));
}
SequenceMetaData *LoadSequenceFile(const char *awdFullPath)
{
char awdDrive[4];
char awdPath[1024];
char txtPath[1024];
_splitpath_s(awdFullPath, awdDrive, 4, awdPath, 1024, NULL, 0, NULL, 0);
_makepath_s(txtPath, 1024, awdDrive, awdPath, "sequences", "txt");
if (!FileExists(txtPath))
return NULL;
return ParseSequenceFile(txtPath);
}
int ReplaceString(char *buf, int *size, char *find, char *rep)
{
char *p;
char *tmp;
int findLen;
int repLen;
int endLen;
p = strstr(buf, find);
if (p == NULL)
return 0;
// Take trailing part and store temporarily
findLen = strlen(find);
endLen = strlen(p) - findLen;
tmp = (char *)malloc(endLen);
memcpy(tmp, p+findLen, endLen);
// Replace string in buffer and move to end
// of replaced string
repLen = strlen(rep);
memcpy(p, rep, repLen);
p += repLen;
// Append trailing string
memcpy(p, tmp, endLen);
free(tmp);
// Save new size of buffer
*size = (p-buf) + endLen;
return 1;
}<commit_msg>Parsing of sequences.txt now understands comments and empty lines.<commit_after>#include "utils.h"
void SerializeMatrix3(Matrix3 &mtx, double *output)
{
Point3 row;
row = mtx.GetRow(0);
output[0] = row.x;
output[1] = -row.z;
output[2] = -row.y;
row = mtx.GetRow(2);
output[3] = -row.x;
output[4] = row.z;
output[5] = row.y;
row = mtx.GetRow(1);
output[6] = -row.x;
output[7] = row.z;
output[8] = row.y;
row = mtx.GetRow(3);
output[9] = -row.x;
output[10] = row.z;
output[11] = row.y;
}
int IndexOfSkinMod(Object *obj, IDerivedObject **derivedObject)
{
if (obj != NULL && obj->SuperClassID() == GEN_DERIVOB_CLASS_ID) {
int i;
IDerivedObject *derived = (IDerivedObject *)obj;
for (i=0; i < derived->NumModifiers(); i++) {
Modifier *mod = derived->GetModifier(i);
void *skin = mod->GetInterface(I_SKIN);
if (skin != NULL) {
*derivedObject = derived;
return i;
}
}
}
return -1;
}
SequenceMetaData *ParseSequenceFile(const char *path)
{
FILE *fp;
fp = fopen(path, "r");
if (fp) {
char line[256];
SequenceMetaData *first, *last;
first = NULL;
last = NULL;
while (fgets(line, 256, fp) != NULL) {
SequenceMetaData *cur;
int nameLen;
char *name, *start, *end;
// Skip empty lines and comments
if (strlen(line)==0 || line[0]=='#')
continue;
// Read name and skip if missing.
name = strtok(line, " ");
if (!name) continue;
nameLen = strlen(name);
// Read start frame and skip if missing.
start = strtok(NULL, " ");
if (!start) continue;
// Read end frame and skip if missing.
end = strtok(NULL, " ");
if (!end) continue;
cur = (SequenceMetaData*)malloc(sizeof(SequenceMetaData));
cur->start = strtol(start, NULL, 10);
cur->stop = strtol(end, NULL, 10);
cur->name = (char*)malloc(nameLen+1);
memcpy(cur->name, name, nameLen+1);
if (!first) {
first = cur;
}
else {
last->next = cur;
}
last = cur;
last->next = NULL;
}
return first;
}
return NULL;
}
bool FileExists(const char *path)
{
DWORD dwAttrib = GetFileAttributes(path);
return (dwAttrib != INVALID_FILE_ATTRIBUTES &&
!(dwAttrib & FILE_ATTRIBUTE_DIRECTORY));
}
SequenceMetaData *LoadSequenceFile(const char *awdFullPath)
{
char awdDrive[4];
char awdPath[1024];
char txtPath[1024];
_splitpath_s(awdFullPath, awdDrive, 4, awdPath, 1024, NULL, 0, NULL, 0);
_makepath_s(txtPath, 1024, awdDrive, awdPath, "sequences", "txt");
if (!FileExists(txtPath))
return NULL;
return ParseSequenceFile(txtPath);
}
int ReplaceString(char *buf, int *size, char *find, char *rep)
{
char *p;
char *tmp;
int findLen;
int repLen;
int endLen;
p = strstr(buf, find);
if (p == NULL)
return 0;
// Take trailing part and store temporarily
findLen = strlen(find);
endLen = strlen(p) - findLen;
tmp = (char *)malloc(endLen);
memcpy(tmp, p+findLen, endLen);
// Replace string in buffer and move to end
// of replaced string
repLen = strlen(rep);
memcpy(p, rep, repLen);
p += repLen;
// Append trailing string
memcpy(p, tmp, endLen);
free(tmp);
// Save new size of buffer
*size = (p-buf) + endLen;
return 1;
}<|endoftext|>
|
<commit_before>// Copyright (c) 2012 The Bitcoin developers
// Distributed under the MIT/X11 software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
#include <string>
#include "version.h"
// Name of client reported in the 'version' message. Report the same name
// for both bitcoind and bitcoin-qt, to make it harder for attackers to
// target servers or GUI users specifically.
const std::string CLIENT_NAME("Whitecoin");
// Client version number
#define CLIENT_VERSION_SUFFIX ""
// The following part of the code determines the CLIENT_BUILD variable.
// Several mechanisms are used for this:
// * first, if HAVE_BUILD_INFO is defined, include build.h, a file that is
// generated by the build environment, possibly containing the output
// of git-describe in a macro called BUILD_DESC
// * secondly, if this is an exported version of the code, GIT_ARCHIVE will
// be defined (automatically using the export-subst git attribute), and
// GIT_COMMIT will contain the commit id.
// * then, three options exist for determining CLIENT_BUILD:
// * if BUILD_DESC is defined, use that literally (output of git-describe)
// * if not, but GIT_COMMIT is defined, use v[maj].[min].[rev].[build]-g[commit]
// * otherwise, use v[maj].[min].[rev].[build]-unk
// finally CLIENT_VERSION_SUFFIX is added
// First, include build.h if requested
#ifdef HAVE_BUILD_INFO
# include "build.h"
#endif
// git will put "#define GIT_ARCHIVE 1" on the next line inside archives.
#define GIT_ARCHIVE 1
#ifdef GIT_ARCHIVE
# define GIT_COMMIT_ID ""
# define GIT_COMMIT_DATE "$Format:%cD$"
#endif
#define BUILD_DESC_FROM_COMMIT(maj,min,rev,build,commit) \
"v" DO_STRINGIZE(maj) "." DO_STRINGIZE(min) "." DO_STRINGIZE(rev) "." DO_STRINGIZE(build) "" commit
#define BUILD_DESC_FROM_UNKNOWN(maj,min,rev,build) \
"v" DO_STRINGIZE(maj) "." DO_STRINGIZE(min) "." DO_STRINGIZE(rev) "." DO_STRINGIZE(build) ""
#ifndef BUILD_DESC
# ifdef GIT_COMMIT_ID
# define BUILD_DESC BUILD_DESC_FROM_COMMIT(DISPLAY_VERSION_MAJOR, DISPLAY_VERSION_MINOR, DISPLAY_VERSION_REVISION, DISPLAY_VERSION_BUILD, GIT_COMMIT_ID)
# else
# define BUILD_DESC BUILD_DESC_FROM_UNKNOWN(DISPLAY_VERSION_MAJOR, DISPLAY_VERSION_MINOR, DISPLAY_VERSION_REVISION, DISPLAY_VERSION_BUILD)
# endif
#endif
#ifndef BUILD_DATE
# ifdef GIT_COMMIT_DATE
# define BUILD_DATE GIT_COMMIT_DATE
# else
# define BUILD_DATE __DATE__ ", " __TIME__
# endif
#endif
const std::string CLIENT_BUILD(BUILD_DESC CLIENT_VERSION_SUFFIX);
const std::string CLIENT_DATE(BUILD_DATE);
<commit_msg>Fixed build date<commit_after>// Copyright (c) 2012 The Bitcoin developers
// Distributed under the MIT/X11 software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
#include <string>
#include "version.h"
// Name of client reported in the 'version' message. Report the same name
// for both bitcoind and bitcoin-qt, to make it harder for attackers to
// target servers or GUI users specifically.
const std::string CLIENT_NAME("Whitecoin");
// Client version number
#define CLIENT_VERSION_SUFFIX ""
// The following part of the code determines the CLIENT_BUILD variable.
// Several mechanisms are used for this:
// * first, if HAVE_BUILD_INFO is defined, include build.h, a file that is
// generated by the build environment, possibly containing the output
// of git-describe in a macro called BUILD_DESC
// * secondly, if this is an exported version of the code, GIT_ARCHIVE will
// be defined (automatically using the export-subst git attribute), and
// GIT_COMMIT will contain the commit id.
// * then, three options exist for determining CLIENT_BUILD:
// * if BUILD_DESC is defined, use that literally (output of git-describe)
// * if not, but GIT_COMMIT is defined, use v[maj].[min].[rev].[build]-g[commit]
// * otherwise, use v[maj].[min].[rev].[build]-unk
// finally CLIENT_VERSION_SUFFIX is added
// First, include build.h if requested
#ifdef HAVE_BUILD_INFO
# include "build.h"
#endif
// git will put "#define GIT_ARCHIVE 1" on the next line inside archives.
//#define GIT_ARCHIVE 1
#ifdef GIT_ARCHIVE
# define GIT_COMMIT_ID "$Format:%h$"
# define GIT_COMMIT_DATE "$Format:%cD$"
#endif
#define BUILD_DESC_FROM_COMMIT(maj,min,rev,build,commit) \
"v" DO_STRINGIZE(maj) "." DO_STRINGIZE(min) "." DO_STRINGIZE(rev) "." DO_STRINGIZE(build) "" commit
#define BUILD_DESC_FROM_UNKNOWN(maj,min,rev,build) \
"v" DO_STRINGIZE(maj) "." DO_STRINGIZE(min) "." DO_STRINGIZE(rev) "." DO_STRINGIZE(build) ""
#ifndef BUILD_DESC
# ifdef GIT_COMMIT_ID
# define BUILD_DESC BUILD_DESC_FROM_COMMIT(DISPLAY_VERSION_MAJOR, DISPLAY_VERSION_MINOR, DISPLAY_VERSION_REVISION, DISPLAY_VERSION_BUILD, GIT_COMMIT_ID)
# else
# define BUILD_DESC BUILD_DESC_FROM_UNKNOWN(DISPLAY_VERSION_MAJOR, DISPLAY_VERSION_MINOR, DISPLAY_VERSION_REVISION, DISPLAY_VERSION_BUILD)
# endif
#endif
#ifndef BUILD_DATE
# ifdef GIT_COMMIT_DATE
# define BUILD_DATE GIT_COMMIT_DATE
# else
# define BUILD_DATE __DATE__ ", " __TIME__
# endif
#endif
const std::string CLIENT_BUILD(BUILD_DESC CLIENT_VERSION_SUFFIX);
const std::string CLIENT_DATE(BUILD_DATE);
<|endoftext|>
|
<commit_before>#pragma onece
#include<QString>
#include<QDir>
const QString app_name = "MCSwitch"; // Application Full Name.
const QString app_ver = "0.0.1-dev"; // Application Version.
const QString app_license = "MIT"; // Application License.
const QString mcswitch_dir = QDir::homePath() + "/.MCSwitch"; //Application data dir.
const QString mcswitch_dir_common = mcswitch_dir + "/common";
const QString mcswitch_dir_cmods = mcswitch_dir + "/mods";
<commit_msg>必要ない定数を削除<commit_after>#pragma onece
#include<QString>
#include<QDir>
const QString app_name = "MCSwitch"; // Application Full Name.
const QString app_ver = "0.0.1-dev"; // Application Version.
const QString app_license = "MIT"; // Application License.
const QString mcswitch_dir = QDir::homePath() + "/.MCSwitch"; //Application data dir.
const QString mcswitch_dir_common = mcswitch_dir + "/common";
<|endoftext|>
|
<commit_before>/*
* Copyright 2016 Andrei Pangin
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include <dlfcn.h>
#include <stdlib.h>
#include <string.h>
#include "vmEntry.h"
#include "arguments.h"
#include "javaApi.h"
#include "os.h"
#include "profiler.h"
#include "instrument.h"
#include "lockTracer.h"
#include "log.h"
#include "vmStructs.h"
// JVM TI agent return codes
const int ARGUMENTS_ERROR = 100;
const int COMMAND_ERROR = 200;
static Arguments _agent_args;
JavaVM* VM::_vm;
jvmtiEnv* VM::_jvmti = NULL;
int VM::_hotspot_version = 0;
void* VM::_libjvm;
void* VM::_libjava;
AsyncGetCallTrace VM::_asyncGetCallTrace;
JVM_GetManagement VM::_getManagement;
jvmtiError (JNICALL *VM::_orig_RedefineClasses)(jvmtiEnv*, jint, const jvmtiClassDefinition*);
jvmtiError (JNICALL *VM::_orig_RetransformClasses)(jvmtiEnv*, jint, const jclass* classes);
jvmtiError (JNICALL *VM::_orig_GenerateEvents)(jvmtiEnv* jvmti, jvmtiEvent event_type);
volatile int VM::_in_redefine_classes = 0;
static void wakeupHandler(int signo) {
// Dummy handler for interrupting syscalls
}
bool VM::init(JavaVM* vm, bool attach) {
if (_jvmti != NULL) return true;
_vm = vm;
if (_vm->GetEnv((void**)&_jvmti, JVMTI_VERSION_1_0) != 0) {
return false;
}
char* prop;
if (_jvmti->GetSystemProperty("java.vm.name", &prop) == 0) {
bool is_hotspot = strstr(prop, "OpenJDK") != NULL ||
strstr(prop, "HotSpot") != NULL ||
strstr(prop, "GraalVM") != NULL ||
strstr(prop, "Dynamic Code Evolution") != NULL;
_jvmti->Deallocate((unsigned char*)prop);
if (is_hotspot && _jvmti->GetSystemProperty("java.vm.version", &prop) == 0) {
if (strncmp(prop, "25.", 3) == 0) {
_hotspot_version = 8;
} else if (strncmp(prop, "24.", 3) == 0) {
_hotspot_version = 7;
} else if (strncmp(prop, "20.", 3) == 0) {
_hotspot_version = 6;
} else if ((_hotspot_version = atoi(prop)) < 9) {
_hotspot_version = 9;
}
_jvmti->Deallocate((unsigned char*)prop);
}
}
_libjvm = getLibraryHandle("libjvm.so");
_asyncGetCallTrace = (AsyncGetCallTrace)dlsym(_libjvm, "AsyncGetCallTrace");
_getManagement = (JVM_GetManagement)dlsym(_libjvm, "JVM_GetManagement");
if (attach) {
ready();
}
jvmtiCapabilities capabilities = {0};
capabilities.can_generate_all_class_hook_events = 1;
capabilities.can_retransform_classes = 1;
capabilities.can_retransform_any_class = 1;
capabilities.can_get_bytecodes = 1;
capabilities.can_get_constant_pool = 1;
capabilities.can_get_source_file_name = 1;
capabilities.can_get_line_numbers = 1;
capabilities.can_generate_compiled_method_load_events = 1;
capabilities.can_generate_monitor_events = 1;
capabilities.can_tag_objects = 1;
_jvmti->AddCapabilities(&capabilities);
jvmtiEventCallbacks callbacks = {0};
callbacks.VMInit = VMInit;
callbacks.VMDeath = VMDeath;
callbacks.ClassLoad = ClassLoad;
callbacks.ClassPrepare = ClassPrepare;
callbacks.ClassFileLoadHook = Instrument::ClassFileLoadHook;
callbacks.CompiledMethodLoad = Profiler::CompiledMethodLoad;
callbacks.CompiledMethodUnload = Profiler::CompiledMethodUnload;
callbacks.DynamicCodeGenerated = Profiler::DynamicCodeGenerated;
callbacks.ThreadStart = Profiler::ThreadStart;
callbacks.ThreadEnd = Profiler::ThreadEnd;
callbacks.MonitorContendedEnter = LockTracer::MonitorContendedEnter;
callbacks.MonitorContendedEntered = LockTracer::MonitorContendedEntered;
_jvmti->SetEventCallbacks(&callbacks, sizeof(callbacks));
_jvmti->SetEventNotificationMode(JVMTI_ENABLE, JVMTI_EVENT_VM_INIT, NULL);
_jvmti->SetEventNotificationMode(JVMTI_ENABLE, JVMTI_EVENT_VM_DEATH, NULL);
_jvmti->SetEventNotificationMode(JVMTI_ENABLE, JVMTI_EVENT_CLASS_LOAD, NULL);
_jvmti->SetEventNotificationMode(JVMTI_ENABLE, JVMTI_EVENT_CLASS_PREPARE, NULL);
_jvmti->SetEventNotificationMode(JVMTI_ENABLE, JVMTI_EVENT_COMPILED_METHOD_LOAD, NULL);
_jvmti->SetEventNotificationMode(JVMTI_ENABLE, JVMTI_EVENT_COMPILED_METHOD_UNLOAD, NULL);
_jvmti->SetEventNotificationMode(JVMTI_ENABLE, JVMTI_EVENT_DYNAMIC_CODE_GENERATED, NULL);
if (attach) {
loadAllMethodIDs(jvmti(), jni());
DisableSweeper ds;
_jvmti->GenerateEvents(JVMTI_EVENT_DYNAMIC_CODE_GENERATED);
_jvmti->GenerateEvents(JVMTI_EVENT_COMPILED_METHOD_LOAD);
}
if (hotspot_version() > 0 && hotspot_version() < 11) {
// Avoid GenerateEvents conflict with another agent
JVMTIFunctions* functions = *(JVMTIFunctions**)_jvmti;
_orig_GenerateEvents = functions->GenerateEvents;
functions->GenerateEvents = GenerateEventsHook;
}
OS::installSignalHandler(WAKEUP_SIGNAL, NULL, wakeupHandler);
return true;
}
// Run late initialization when JVM is ready
void VM::ready() {
Profiler* profiler = Profiler::instance();
profiler->updateSymbols(false);
NativeCodeCache* libjvm = profiler->findNativeLibrary((const void*)_asyncGetCallTrace);
if (libjvm != NULL) {
JitWriteProtection jit(true); // workaround for JDK-8262896
VMStructs::init(libjvm);
}
profiler->setupTrapHandler();
_libjava = getLibraryHandle("libjava.so");
// Make sure we reload method IDs upon class retransformation
JVMTIFunctions* functions = *(JVMTIFunctions**)_jvmti;
_orig_RedefineClasses = functions->RedefineClasses;
_orig_RetransformClasses = functions->RetransformClasses;
functions->RedefineClasses = RedefineClassesHook;
functions->RetransformClasses = RetransformClassesHook;
}
void* VM::getLibraryHandle(const char* name) {
if (!OS::isJavaLibraryVisible()) {
void* handle = dlopen(name, RTLD_LAZY);
if (handle != NULL) {
return handle;
}
Log::warn("Failed to load %s: %s", name, dlerror());
}
return RTLD_DEFAULT;
}
void VM::loadMethodIDs(jvmtiEnv* jvmti, JNIEnv* jni, jclass klass) {
if (VMStructs::hasClassLoaderData()) {
VMKlass* vmklass = VMKlass::fromJavaClass(jni, klass);
int method_count = vmklass->methodCount();
if (method_count > 0) {
ClassLoaderData* cld = vmklass->classLoaderData();
cld->lock();
// Workaround for JVM bug: preallocate space for jmethodIDs
// at the beginning of the list (rather than at the end)
for (int i = 0; i < method_count; i += MethodList::SIZE) {
*cld->methodList() = new MethodList(*cld->methodList());
}
cld->unlock();
}
}
jint method_count;
jmethodID* methods;
if (jvmti->GetClassMethods(klass, &method_count, &methods) == 0) {
jvmti->Deallocate((unsigned char*)methods);
}
}
void VM::loadAllMethodIDs(jvmtiEnv* jvmti, JNIEnv* jni) {
jint class_count;
jclass* classes;
if (jvmti->GetLoadedClasses(&class_count, &classes) == 0) {
for (int i = 0; i < class_count; i++) {
loadMethodIDs(jvmti, jni, classes[i]);
}
jvmti->Deallocate((unsigned char*)classes);
}
}
void JNICALL VM::VMInit(jvmtiEnv* jvmti, JNIEnv* jni, jthread thread) {
ready();
loadAllMethodIDs(jvmti, jni);
// Delayed start of profiler if agent has been loaded at VM bootstrap
Error error = Profiler::instance()->run(_agent_args);
if (error) {
Log::error("%s", error.message());
}
}
void JNICALL VM::VMDeath(jvmtiEnv* jvmti, JNIEnv* jni) {
Profiler::instance()->shutdown(_agent_args);
}
jvmtiError VM::RedefineClassesHook(jvmtiEnv* jvmti, jint class_count, const jvmtiClassDefinition* class_definitions) {
atomicInc(_in_redefine_classes);
jvmtiError result = _orig_RedefineClasses(jvmti, class_count, class_definitions);
if (result == 0) {
// jmethodIDs are invalidated after RedefineClasses
JNIEnv* env = jni();
for (int i = 0; i < class_count; i++) {
if (class_definitions[i].klass != NULL) {
loadMethodIDs(jvmti, env, class_definitions[i].klass);
}
}
}
atomicInc(_in_redefine_classes, -1);
return result;
}
jvmtiError VM::RetransformClassesHook(jvmtiEnv* jvmti, jint class_count, const jclass* classes) {
atomicInc(_in_redefine_classes);
jvmtiError result = _orig_RetransformClasses(jvmti, class_count, classes);
if (result == 0) {
// jmethodIDs are invalidated after RetransformClasses
JNIEnv* env = jni();
for (int i = 0; i < class_count; i++) {
if (classes[i] != NULL) {
loadMethodIDs(jvmti, env, classes[i]);
}
}
}
atomicInc(_in_redefine_classes, -1);
return result;
}
jvmtiError VM::GenerateEventsHook(jvmtiEnv* jvmti, jvmtiEvent event_type) {
if (event_type == JVMTI_EVENT_COMPILED_METHOD_LOAD) {
// Workaround for JDK-8222072: prepare to receive events designated for another agent
Log::warn("async-profiler conflicts with another agent calling GenerateEvents()");
Profiler::instance()->resetJavaMethods();
}
return _orig_GenerateEvents(jvmti, event_type);
}
extern "C" JNIEXPORT jint JNICALL
Agent_OnLoad(JavaVM* vm, char* options, void* reserved) {
Error error = _agent_args.parse(options);
Log::open(_agent_args._log);
if (error) {
Log::error("%s", error.message());
return ARGUMENTS_ERROR;
}
if (!VM::init(vm, false)) {
Log::error("JVM does not support Tool Interface");
return COMMAND_ERROR;
}
return 0;
}
extern "C" JNIEXPORT jint JNICALL
Agent_OnAttach(JavaVM* vm, char* options, void* reserved) {
Arguments args;
Error error = args.parse(options);
Log::open(args._log);
if (error) {
Log::error("%s", error.message());
return ARGUMENTS_ERROR;
}
if (!VM::init(vm, true)) {
Log::error("JVM does not support Tool Interface");
return COMMAND_ERROR;
}
// Save the arguments in case of shutdown
if (args._action == ACTION_START || args._action == ACTION_RESUME) {
_agent_args.save(args);
}
error = Profiler::instance()->run(args);
if (error) {
Log::error("%s", error.message());
return COMMAND_ERROR;
}
return 0;
}
extern "C" JNIEXPORT jint JNICALL
JNI_OnLoad(JavaVM* vm, void* reserved) {
if (!VM::init(vm, true)) {
return 0;
}
JavaAPI::registerNatives(VM::jvmti(), VM::jni());
return JNI_VERSION_1_6;
}
<commit_msg>Fixed RedefineClasses recursion when loading via JNI<commit_after>/*
* Copyright 2016 Andrei Pangin
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include <dlfcn.h>
#include <stdlib.h>
#include <string.h>
#include "vmEntry.h"
#include "arguments.h"
#include "javaApi.h"
#include "os.h"
#include "profiler.h"
#include "instrument.h"
#include "lockTracer.h"
#include "log.h"
#include "vmStructs.h"
// JVM TI agent return codes
const int ARGUMENTS_ERROR = 100;
const int COMMAND_ERROR = 200;
static Arguments _agent_args;
JavaVM* VM::_vm;
jvmtiEnv* VM::_jvmti = NULL;
int VM::_hotspot_version = 0;
void* VM::_libjvm;
void* VM::_libjava;
AsyncGetCallTrace VM::_asyncGetCallTrace;
JVM_GetManagement VM::_getManagement;
jvmtiError (JNICALL *VM::_orig_RedefineClasses)(jvmtiEnv*, jint, const jvmtiClassDefinition*);
jvmtiError (JNICALL *VM::_orig_RetransformClasses)(jvmtiEnv*, jint, const jclass* classes);
jvmtiError (JNICALL *VM::_orig_GenerateEvents)(jvmtiEnv* jvmti, jvmtiEvent event_type);
volatile int VM::_in_redefine_classes = 0;
static void wakeupHandler(int signo) {
// Dummy handler for interrupting syscalls
}
bool VM::init(JavaVM* vm, bool attach) {
if (_jvmti != NULL) return true;
_vm = vm;
if (_vm->GetEnv((void**)&_jvmti, JVMTI_VERSION_1_0) != 0) {
return false;
}
char* prop;
if (_jvmti->GetSystemProperty("java.vm.name", &prop) == 0) {
bool is_hotspot = strstr(prop, "OpenJDK") != NULL ||
strstr(prop, "HotSpot") != NULL ||
strstr(prop, "GraalVM") != NULL ||
strstr(prop, "Dynamic Code Evolution") != NULL;
_jvmti->Deallocate((unsigned char*)prop);
if (is_hotspot && _jvmti->GetSystemProperty("java.vm.version", &prop) == 0) {
if (strncmp(prop, "25.", 3) == 0) {
_hotspot_version = 8;
} else if (strncmp(prop, "24.", 3) == 0) {
_hotspot_version = 7;
} else if (strncmp(prop, "20.", 3) == 0) {
_hotspot_version = 6;
} else if ((_hotspot_version = atoi(prop)) < 9) {
_hotspot_version = 9;
}
_jvmti->Deallocate((unsigned char*)prop);
}
}
_libjvm = getLibraryHandle("libjvm.so");
_asyncGetCallTrace = (AsyncGetCallTrace)dlsym(_libjvm, "AsyncGetCallTrace");
_getManagement = (JVM_GetManagement)dlsym(_libjvm, "JVM_GetManagement");
if (attach) {
ready();
}
jvmtiCapabilities capabilities = {0};
capabilities.can_generate_all_class_hook_events = 1;
capabilities.can_retransform_classes = 1;
capabilities.can_retransform_any_class = 1;
capabilities.can_get_bytecodes = 1;
capabilities.can_get_constant_pool = 1;
capabilities.can_get_source_file_name = 1;
capabilities.can_get_line_numbers = 1;
capabilities.can_generate_compiled_method_load_events = 1;
capabilities.can_generate_monitor_events = 1;
capabilities.can_tag_objects = 1;
_jvmti->AddCapabilities(&capabilities);
jvmtiEventCallbacks callbacks = {0};
callbacks.VMInit = VMInit;
callbacks.VMDeath = VMDeath;
callbacks.ClassLoad = ClassLoad;
callbacks.ClassPrepare = ClassPrepare;
callbacks.ClassFileLoadHook = Instrument::ClassFileLoadHook;
callbacks.CompiledMethodLoad = Profiler::CompiledMethodLoad;
callbacks.CompiledMethodUnload = Profiler::CompiledMethodUnload;
callbacks.DynamicCodeGenerated = Profiler::DynamicCodeGenerated;
callbacks.ThreadStart = Profiler::ThreadStart;
callbacks.ThreadEnd = Profiler::ThreadEnd;
callbacks.MonitorContendedEnter = LockTracer::MonitorContendedEnter;
callbacks.MonitorContendedEntered = LockTracer::MonitorContendedEntered;
_jvmti->SetEventCallbacks(&callbacks, sizeof(callbacks));
_jvmti->SetEventNotificationMode(JVMTI_ENABLE, JVMTI_EVENT_VM_DEATH, NULL);
_jvmti->SetEventNotificationMode(JVMTI_ENABLE, JVMTI_EVENT_CLASS_LOAD, NULL);
_jvmti->SetEventNotificationMode(JVMTI_ENABLE, JVMTI_EVENT_CLASS_PREPARE, NULL);
_jvmti->SetEventNotificationMode(JVMTI_ENABLE, JVMTI_EVENT_COMPILED_METHOD_LOAD, NULL);
_jvmti->SetEventNotificationMode(JVMTI_ENABLE, JVMTI_EVENT_COMPILED_METHOD_UNLOAD, NULL);
_jvmti->SetEventNotificationMode(JVMTI_ENABLE, JVMTI_EVENT_DYNAMIC_CODE_GENERATED, NULL);
if (attach) {
loadAllMethodIDs(jvmti(), jni());
DisableSweeper ds;
_jvmti->GenerateEvents(JVMTI_EVENT_DYNAMIC_CODE_GENERATED);
_jvmti->GenerateEvents(JVMTI_EVENT_COMPILED_METHOD_LOAD);
} else {
_jvmti->SetEventNotificationMode(JVMTI_ENABLE, JVMTI_EVENT_VM_INIT, NULL);
}
if (hotspot_version() > 0 && hotspot_version() < 11) {
// Avoid GenerateEvents conflict with another agent
JVMTIFunctions* functions = *(JVMTIFunctions**)_jvmti;
_orig_GenerateEvents = functions->GenerateEvents;
functions->GenerateEvents = GenerateEventsHook;
}
OS::installSignalHandler(WAKEUP_SIGNAL, NULL, wakeupHandler);
return true;
}
// Run late initialization when JVM is ready
void VM::ready() {
Profiler* profiler = Profiler::instance();
profiler->updateSymbols(false);
NativeCodeCache* libjvm = profiler->findNativeLibrary((const void*)_asyncGetCallTrace);
if (libjvm != NULL) {
JitWriteProtection jit(true); // workaround for JDK-8262896
VMStructs::init(libjvm);
}
profiler->setupTrapHandler();
_libjava = getLibraryHandle("libjava.so");
// Make sure we reload method IDs upon class retransformation
JVMTIFunctions* functions = *(JVMTIFunctions**)_jvmti;
_orig_RedefineClasses = functions->RedefineClasses;
_orig_RetransformClasses = functions->RetransformClasses;
functions->RedefineClasses = RedefineClassesHook;
functions->RetransformClasses = RetransformClassesHook;
}
void* VM::getLibraryHandle(const char* name) {
if (!OS::isJavaLibraryVisible()) {
void* handle = dlopen(name, RTLD_LAZY);
if (handle != NULL) {
return handle;
}
Log::warn("Failed to load %s: %s", name, dlerror());
}
return RTLD_DEFAULT;
}
void VM::loadMethodIDs(jvmtiEnv* jvmti, JNIEnv* jni, jclass klass) {
if (VMStructs::hasClassLoaderData()) {
VMKlass* vmklass = VMKlass::fromJavaClass(jni, klass);
int method_count = vmklass->methodCount();
if (method_count > 0) {
ClassLoaderData* cld = vmklass->classLoaderData();
cld->lock();
// Workaround for JVM bug: preallocate space for jmethodIDs
// at the beginning of the list (rather than at the end)
for (int i = 0; i < method_count; i += MethodList::SIZE) {
*cld->methodList() = new MethodList(*cld->methodList());
}
cld->unlock();
}
}
jint method_count;
jmethodID* methods;
if (jvmti->GetClassMethods(klass, &method_count, &methods) == 0) {
jvmti->Deallocate((unsigned char*)methods);
}
}
void VM::loadAllMethodIDs(jvmtiEnv* jvmti, JNIEnv* jni) {
jint class_count;
jclass* classes;
if (jvmti->GetLoadedClasses(&class_count, &classes) == 0) {
for (int i = 0; i < class_count; i++) {
loadMethodIDs(jvmti, jni, classes[i]);
}
jvmti->Deallocate((unsigned char*)classes);
}
}
void JNICALL VM::VMInit(jvmtiEnv* jvmti, JNIEnv* jni, jthread thread) {
ready();
loadAllMethodIDs(jvmti, jni);
// Delayed start of profiler if agent has been loaded at VM bootstrap
Error error = Profiler::instance()->run(_agent_args);
if (error) {
Log::error("%s", error.message());
}
}
void JNICALL VM::VMDeath(jvmtiEnv* jvmti, JNIEnv* jni) {
Profiler::instance()->shutdown(_agent_args);
}
jvmtiError VM::RedefineClassesHook(jvmtiEnv* jvmti, jint class_count, const jvmtiClassDefinition* class_definitions) {
atomicInc(_in_redefine_classes);
jvmtiError result = _orig_RedefineClasses(jvmti, class_count, class_definitions);
if (result == 0) {
// jmethodIDs are invalidated after RedefineClasses
JNIEnv* env = jni();
for (int i = 0; i < class_count; i++) {
if (class_definitions[i].klass != NULL) {
loadMethodIDs(jvmti, env, class_definitions[i].klass);
}
}
}
atomicInc(_in_redefine_classes, -1);
return result;
}
jvmtiError VM::RetransformClassesHook(jvmtiEnv* jvmti, jint class_count, const jclass* classes) {
atomicInc(_in_redefine_classes);
jvmtiError result = _orig_RetransformClasses(jvmti, class_count, classes);
if (result == 0) {
// jmethodIDs are invalidated after RetransformClasses
JNIEnv* env = jni();
for (int i = 0; i < class_count; i++) {
if (classes[i] != NULL) {
loadMethodIDs(jvmti, env, classes[i]);
}
}
}
atomicInc(_in_redefine_classes, -1);
return result;
}
jvmtiError VM::GenerateEventsHook(jvmtiEnv* jvmti, jvmtiEvent event_type) {
if (event_type == JVMTI_EVENT_COMPILED_METHOD_LOAD) {
// Workaround for JDK-8222072: prepare to receive events designated for another agent
Log::warn("async-profiler conflicts with another agent calling GenerateEvents()");
Profiler::instance()->resetJavaMethods();
}
return _orig_GenerateEvents(jvmti, event_type);
}
extern "C" JNIEXPORT jint JNICALL
Agent_OnLoad(JavaVM* vm, char* options, void* reserved) {
Error error = _agent_args.parse(options);
Log::open(_agent_args._log);
if (error) {
Log::error("%s", error.message());
return ARGUMENTS_ERROR;
}
if (!VM::init(vm, false)) {
Log::error("JVM does not support Tool Interface");
return COMMAND_ERROR;
}
return 0;
}
extern "C" JNIEXPORT jint JNICALL
Agent_OnAttach(JavaVM* vm, char* options, void* reserved) {
Arguments args;
Error error = args.parse(options);
Log::open(args._log);
if (error) {
Log::error("%s", error.message());
return ARGUMENTS_ERROR;
}
if (!VM::init(vm, true)) {
Log::error("JVM does not support Tool Interface");
return COMMAND_ERROR;
}
// Save the arguments in case of shutdown
if (args._action == ACTION_START || args._action == ACTION_RESUME) {
_agent_args.save(args);
}
error = Profiler::instance()->run(args);
if (error) {
Log::error("%s", error.message());
return COMMAND_ERROR;
}
return 0;
}
extern "C" JNIEXPORT jint JNICALL
JNI_OnLoad(JavaVM* vm, void* reserved) {
if (!VM::init(vm, true)) {
return 0;
}
JavaAPI::registerNatives(VM::jvmti(), VM::jni());
return JNI_VERSION_1_6;
}
<|endoftext|>
|
<commit_before>
#include <functional>
#ifdef INCLUDE_BOTAN_ALL_H
#include "botan_all.h"
#else
#include <botan/botan.h>
#include <botan/tls_session.h>
#include <botan/tls_alert.h>
#include <botan/tls_policy.h>
#include <botan/credentials_manager.h>
#include <botan/tls_channel.h>
#include <botan/pkcs8.h>
#include <botan/tls_session_manager.h>
#include <botan/tls_server.h>
#endif
#include "../SecondTransfer/TLS/Botan_stub.h"
#include <cstdlib>
namespace second_transfer {
// Just because of the conversions, but it may be a handy place for
// other stuff later.
void output_dn_cb (void* botan_pad_ref, const unsigned char a[], size_t sz)
{
iocba_push(botan_pad_ref, (char*)a, sz);
}
void data_cb (void* botan_pad_ref, const unsigned char a[], size_t sz)
{
iocba_data_cb(botan_pad_ref, (char*)a, sz);
}
void alert_cb (void* botan_pad_ref, Botan::TLS::Alert const& alert, const unsigned char a[], size_t sz)
{
if (alert.is_valid() && alert.is_fatal() )
{
// TODO: Propagate this softly.
iocba_alert_cb(botan_pad_ref, -1);
} // Else: don't care
}
bool handshake_cb(void* botan_pad_ref, const Botan::TLS::Session&)
{
iocba_handshake_cb(botan_pad_ref);
// TODO: Implement cache management
return false;
}
// TODO: We can use stronger ciphers here. For now let's go simple
class HereTLSPolicy: public Botan::TLS::Policy {
public:
virtual bool acceptable_protocol_version(const Botan::TLS::Protocol_Version& v)
{
return v == Botan::TLS::Protocol_Version::TLS_V12;
}
virtual std::vector<std::string> allowed_macs() const
{
std::vector<std::string> result;
result.push_back("AEAD");
result.push_back("SHA-384");
result.push_back("SHA-256");
return result;
}
virtual std::vector<std::string> allowed_ciphers() const
{
std::vector<std::string> result;
result.push_back("ChaCha20Poly1305");
result.push_back("AES-256/GCM");
result.push_back("AES-128/GCM");
result.push_back("Camellia-256/GCM");
result.push_back("AES-256/OCB(12)");
result.push_back("AES-256/CCM");
return result;
}
virtual std::vector<std::string> allowed_key_exchange_methods() const
{
std::vector<std::string> result;
result.push_back("ECDH");
result.push_back("DH");
result.push_back("RSA");
return result;
}
virtual std::vector<std::string> allowed_signature_hashes() const
{
std::vector<std::string> result;
result.push_back("SHA-256");
return result;
}
virtual std::vector<std::string> allowed_signature_methods() const
{
std::vector<std::string> result;
result.push_back("RSA");
return result;
}
// This is experimental, may need to change.
virtual bool server_uses_own_ciphersuite_preferences() const
{
return true;
}
};
// TODO: We can use different certificates if needs come....
class HereCredentialsManager: public Botan::Credentials_Manager {
Botan::X509_Certificate cert;
std::vector<Botan::X509_Certificate> certs;
Botan::Private_Key* privkey;
public:
HereCredentialsManager(
const char* cert_filename,
const char* privkey_filename,
Botan::AutoSeeded_RNG& rng
):
cert(cert_filename)
{
certs.push_back(cert);
privkey = Botan::PKCS8::load_key(
privkey_filename, rng
);
}
virtual std::vector<
Botan::X509_Certificate > cert_chain(
const std::vector< std::string >&,
const std::string&,
const std::string& )
{
return certs;
}
virtual Botan::Private_Key* private_key_for(const Botan::X509_Certificate &cert, const std::string & type, const std::string &context)
{
return privkey;
}
~HereCredentialsManager()
{
delete privkey;
}
};
std::string defaultProtocolSelector(void* botan_pad_ref, std::vector<std::string> const& prots)
{
std::string pass_to_haskell;
bool is_first = true;
for (int i=0; i < prots.size(); i++ )
{
if ( is_first )
{
is_first=false;
} else
{
pass_to_haskell += '\0';
}
pass_to_haskell += prots[i];
}
int idx = iocba_select_protocol_cb( botan_pad_ref, (void*)pass_to_haskell.c_str(), pass_to_haskell.size());
return prots[idx];
}
} // namespace
extern "C" void iocba_receive_data(
void* tls_channel,
char* data,
int length )
{
Botan::TLS::Channel* channel = (Botan::TLS::Channel*) tls_channel;
channel->received_data( (const unsigned char*) data, length);
}
extern "C" void iocba_cleartext_push(
void* tls_channel,
char* data,
int length )
{
// TODO: Check for "can send"!!!!!
// OTHERWISE THIS WON'T WORK
Botan::TLS::Channel* channel = (Botan::TLS::Channel*) tls_channel;
channel->send( (const unsigned char*) data, length);
}
struct botan_tls_context_t {
second_transfer::HereCredentialsManager credentials_manager;
Botan::TLS::Session_Manager_In_Memory* session_manager;
Botan::AutoSeeded_RNG* rng;
std::vector<std::string> protocols;
second_transfer::HereTLSPolicy here_tls_policty;
};
extern "C" botan_tls_context_t* iocba_make_tls_context(
const char* cert_filename,
const char* privkey_filename
)
{
Botan::AutoSeeded_RNG rng;
std::vector< std::string > protocols;
// Not sure what is this good for....
protocols.push_back("h2");
protocols.push_back("http/1.1");
return new botan_tls_context_t{
second_transfer::HereCredentialsManager(cert_filename, privkey_filename, rng),
new Botan::TLS::Session_Manager_In_Memory(rng),
new Botan::AutoSeeded_RNG(),
protocols,
second_transfer::HereTLSPolicy()
};
}
extern "C" void iocba_delete_tls_context(botan_tls_context_t* ctx)
{
delete ctx->session_manager;
delete ctx->rng;
delete ctx;
}
extern "C" void* iocba_new_tls_server_channel (
void* botan_pad_ref,
botan_tls_context_t* ctxt)
{
auto* server =
new Botan::TLS::Server(
std::bind(second_transfer::output_dn_cb, botan_pad_ref, std::placeholders::_1, std::placeholders::_2),
std::bind(second_transfer::data_cb, botan_pad_ref, std::placeholders::_1, std::placeholders::_2),
std::bind(second_transfer::alert_cb, botan_pad_ref, std::placeholders::_1, std::placeholders::_2, std::placeholders::_3),
std::bind(second_transfer::handshake_cb, botan_pad_ref, std::placeholders::_1),
*(ctx->session_manager),
ctx->credentials_manager,
ctx->here_tls_policty,
*(ctx->rng),
std::bind(second_transfer::defaultProtocolSelector, botan_pad_ref, std::placeholders::_1)
);
return server;
}
extern "C" void iocba_delete_tls_server_channel (
Botan::TLS::Server * srv
)
{
delete srv;
}
<commit_msg>Something crept in<commit_after>
#include <functional>
#ifdef INCLUDE_BOTAN_ALL_H
#include "botan_all.h"
#else
#include <botan/botan.h>
#include <botan/tls_session.h>
#include <botan/tls_alert.h>
#include <botan/tls_policy.h>
#include <botan/credentials_manager.h>
#include <botan/tls_channel.h>
#include <botan/pkcs8.h>
#include <botan/tls_session_manager.h>
#include <botan/tls_server.h>
#endif
#include "../SecondTransfer/TLS/Botan_stub.h"
#include <cstdlib>
namespace second_transfer {
// Just because of the conversions, but it may be a handy place for
// other stuff later.
void output_dn_cb (void* botan_pad_ref, const unsigned char a[], size_t sz)
{
iocba_push(botan_pad_ref, (char*)a, sz);
}
void data_cb (void* botan_pad_ref, const unsigned char a[], size_t sz)
{
iocba_data_cb(botan_pad_ref, (char*)a, sz);
}
void alert_cb (void* botan_pad_ref, Botan::TLS::Alert const& alert, const unsigned char a[], size_t sz)
{
if (alert.is_valid() && alert.is_fatal() )
{
// TODO: Propagate this softly.
iocba_alert_cb(botan_pad_ref, -1);
} // Else: don't care
}
bool handshake_cb(void* botan_pad_ref, const Botan::TLS::Session&)
{
iocba_handshake_cb(botan_pad_ref);
// TODO: Implement cache management
return false;
}
// TODO: We can use stronger ciphers here. For now let's go simple
class HereTLSPolicy: public Botan::TLS::Policy {
public:
virtual bool acceptable_protocol_version(const Botan::TLS::Protocol_Version& v)
{
return v == Botan::TLS::Protocol_Version::TLS_V12;
}
virtual std::vector<std::string> allowed_macs() const
{
std::vector<std::string> result;
result.push_back("AEAD");
result.push_back("SHA-384");
result.push_back("SHA-256");
return result;
}
virtual std::vector<std::string> allowed_ciphers() const
{
std::vector<std::string> result;
result.push_back("ChaCha20Poly1305");
result.push_back("AES-256/GCM");
result.push_back("AES-128/GCM");
result.push_back("Camellia-256/GCM");
result.push_back("AES-256/OCB(12)");
result.push_back("AES-256/CCM");
return result;
}
virtual std::vector<std::string> allowed_key_exchange_methods() const
{
std::vector<std::string> result;
result.push_back("ECDH");
result.push_back("DH");
result.push_back("RSA");
return result;
}
virtual std::vector<std::string> allowed_signature_hashes() const
{
std::vector<std::string> result;
result.push_back("SHA-256");
return result;
}
virtual std::vector<std::string> allowed_signature_methods() const
{
std::vector<std::string> result;
result.push_back("RSA");
return result;
}
// This is experimental, may need to change.
virtual bool server_uses_own_ciphersuite_preferences() const
{
return true;
}
};
// TODO: We can use different certificates if needs come....
class HereCredentialsManager: public Botan::Credentials_Manager {
Botan::X509_Certificate cert;
std::vector<Botan::X509_Certificate> certs;
Botan::Private_Key* privkey;
public:
HereCredentialsManager(
const char* cert_filename,
const char* privkey_filename,
Botan::AutoSeeded_RNG& rng
):
cert(cert_filename)
{
certs.push_back(cert);
privkey = Botan::PKCS8::load_key(
privkey_filename, rng
);
}
virtual std::vector<
Botan::X509_Certificate > cert_chain(
const std::vector< std::string >&,
const std::string&,
const std::string& )
{
return certs;
}
virtual Botan::Private_Key* private_key_for(const Botan::X509_Certificate &cert, const std::string & type, const std::string &context)
{
return privkey;
}
~HereCredentialsManager()
{
delete privkey;
}
};
std::string defaultProtocolSelector(void* botan_pad_ref, std::vector<std::string> const& prots)
{
std::string pass_to_haskell;
bool is_first = true;
for (int i=0; i < prots.size(); i++ )
{
if ( is_first )
{
is_first=false;
} else
{
pass_to_haskell += '\0';
}
pass_to_haskell += prots[i];
}
int idx = iocba_select_protocol_cb( botan_pad_ref, (void*)pass_to_haskell.c_str(), pass_to_haskell.size());
return prots[idx];
}
} // namespace
extern "C" void iocba_receive_data(
void* tls_channel,
char* data,
int length )
{
Botan::TLS::Channel* channel = (Botan::TLS::Channel*) tls_channel;
channel->received_data( (const unsigned char*) data, length);
}
extern "C" void iocba_cleartext_push(
void* tls_channel,
char* data,
int length )
{
// TODO: Check for "can send"!!!!!
// OTHERWISE THIS WON'T WORK
Botan::TLS::Channel* channel = (Botan::TLS::Channel*) tls_channel;
channel->send( (const unsigned char*) data, length);
}
struct botan_tls_context_t {
second_transfer::HereCredentialsManager credentials_manager;
Botan::TLS::Session_Manager_In_Memory* session_manager;
Botan::AutoSeeded_RNG* rng;
std::vector<std::string> protocols;
second_transfer::HereTLSPolicy here_tls_policty;
};
extern "C" botan_tls_context_t* iocba_make_tls_context(
const char* cert_filename,
const char* privkey_filename
)
{
Botan::AutoSeeded_RNG rng;
std::vector< std::string > protocols;
// Not sure what is this good for....
protocols.push_back("h2");
protocols.push_back("http/1.1");
return new botan_tls_context_t{
second_transfer::HereCredentialsManager(cert_filename, privkey_filename, rng),
new Botan::TLS::Session_Manager_In_Memory(rng),
new Botan::AutoSeeded_RNG(),
protocols,
second_transfer::HereTLSPolicy()
};
}
extern "C" void iocba_delete_tls_context(botan_tls_context_t* ctx)
{
delete ctx->session_manager;
delete ctx->rng;
delete ctx;
}
extern "C" void* iocba_new_tls_server_channel (
void* botan_pad_ref,
botan_tls_context_t* ctx)
{
auto* server =
new Botan::TLS::Server(
std::bind(second_transfer::output_dn_cb, botan_pad_ref, std::placeholders::_1, std::placeholders::_2),
std::bind(second_transfer::data_cb, botan_pad_ref, std::placeholders::_1, std::placeholders::_2),
std::bind(second_transfer::alert_cb, botan_pad_ref, std::placeholders::_1, std::placeholders::_2, std::placeholders::_3),
std::bind(second_transfer::handshake_cb, botan_pad_ref, std::placeholders::_1),
*(ctx->session_manager),
ctx->credentials_manager,
ctx->here_tls_policty,
*(ctx->rng),
std::bind(second_transfer::defaultProtocolSelector, botan_pad_ref, std::placeholders::_1)
);
return server;
}
extern "C" void iocba_delete_tls_server_channel (
Botan::TLS::Server * srv
)
{
delete srv;
}
<|endoftext|>
|
<commit_before>#include "indexer.h"
#include "util.h"
#include <memory.h>
const int KMER = 16;
// 512M bloom filter
const unsigned int BLOOM_FILTER_SIZE = 1<<29;
const unsigned int BLOOM_FILTER_BITS = BLOOM_FILTER_SIZE - 1;
Indexer::Indexer(string refFile, vector<Fusion>& fusions) {
mRefFile = refFile;
mFusions = fusions;
mReference = new FastaReader(refFile, false);
mReference->readAll();
mUniquePos = 0;
mDupePos = 0;
mBloomFilter = new unsigned char[BLOOM_FILTER_SIZE];
memset(mBloomFilter, 0, sizeof(unsigned char) * BLOOM_FILTER_SIZE);
}
Indexer::~Indexer() {
delete mReference;
mReference = NULL;
delete mBloomFilter;
mBloomFilter = NULL;
}
FastaReader* Indexer::getRef() {
return mReference;
}
void Indexer::makeIndex() {
if(mReference == NULL)
return ;
map<string, string>& ref = mReference->mAllContigs;
for(int ctg=0; ctg<mFusions.size(); ctg++){
Gene gene = mFusions[ctg].mGene;
string chr = gene.mChr;
if(ref.count(chr) == 0) {
if(ref.count("chr" + chr) >0)
chr = "chr" + chr;
else if(ref.count(replace(chr, "chr", "")) >0)
chr = replace(chr, "chr", "");
else{
mFusionSeq.push_back("");
continue;
}
}
string s = ref[chr].substr(gene.mStart, gene.mEnd - gene.mStart);
str2upper(s);
mFusionSeq.push_back(s);
//index forward
indexContig(ctg, s, 0);
//index reverse complement
Sequence seq = ~(Sequence(s));
indexContig(ctg, seq.mStr, -s.length()+1);
}
fillBloomFilter();
loginfo("mapper indexing done");
}
void Indexer::fillBloomFilter() {
unordered_map<long, GenePos>::iterator iter;
for(iter = mKmerPos.begin(); iter!=mKmerPos.end(); iter++) {
long kmer = iter->first;
long pos = kmer>>3;
long bit = kmer & 0x07;
mBloomFilter[pos] |= (0x1<<bit);
}
}
void Indexer::indexContig(int ctg, string seq, int start) {
long kmer = -1;
for(int i=0; i<seq.length() - KMER; ++i) {
kmer = makeKmer(seq, i, kmer);
//cout << kmer << "\t" << seq.substr(i, KMER) << endl;
if(kmer < 0)
continue;
GenePos site;
site.contig = ctg;
site.position = i+start;
// this is a dupe
if(mKmerPos.count(kmer) >0 ){
GenePos gp = mKmerPos[kmer];
// already marked as a dupe
if(gp.contig < 0) {
mDupeList[gp.position].push_back(site);
} else {
// else make a new dupe entry
vector<GenePos> gps;
gps.push_back(gp);
gps.push_back(site);
mDupeList.push_back(gps);
// and mark it as a dupe
mKmerPos[kmer].contig = -1;
mKmerPos[kmer].position = mDupeList.size() -1;
mUniquePos--;
mDupePos++;
}
} else {
mKmerPos[kmer]=site;
mUniquePos++;
}
}
}
vector<SeqMatch> Indexer::mapRead(Read* r) {
unordered_map<long, int> kmerStat;
kmerStat[0]=0;
string seq = r->mSeq.mStr;
const int step = 2;
int seqlen = seq.length();
// first pass, we only want to find if this seq can be partially aligned to the target
long kmer = -1;
for(int i=0; i< seqlen - KMER + 1; i += step) {
kmer = makeKmer(seq, i, kmer, step);
if(kmer < 0)
continue;
long pos = kmer>>3;
long bit = kmer & 0x07;
if( (mBloomFilter[pos] & (0x1<<bit)) == 0) {
kmerStat[0]++;
continue;
}
GenePos gp = mKmerPos[kmer];
// is a dupe
if(gp.contig < 0) {
for(int g=0; g<mDupeList[gp.position].size();g++) {
long gplong = gp2long(shift(mDupeList[gp.position][g], i));
if(kmerStat.count(gplong)==0)
kmerStat[gplong] = 1;
else
kmerStat[gplong] += 1;
}
} else {
long gplong = gp2long(shift(gp, i));
if(kmerStat.count(gplong)==0)
kmerStat[gplong] = 1;
else
kmerStat[gplong] += 1;
}
}
// get 1st and 2nd hit
long gp1 = 0;
int count1 = 0;
long gp2 = 0;
int count2 = 0;
unordered_map<long, int>::iterator iter;
//TODO: handle small difference caused by INDEL
for(iter = kmerStat.begin(); iter!=kmerStat.end(); iter++){
if(iter->first != 0 && iter->second > count1){
gp2 = gp1;
count2 = count1;
gp1 = iter->first;
count1 = iter->second;
} else if(iter->first != 0 && iter->second > count2 ){
gp2 = iter->first;
count2 = iter->second;
}
}
if(count1 * step < 40 || count2 * step < 20){
// return an null list
return vector<SeqMatch>();
}
unsigned char* mask = new unsigned char[seqlen];
memset(mask, MATCH_UNKNOWN, sizeof(unsigned char)*seqlen);
// second pass, make the mask
kmer = -1;
for(int i=0; i< seqlen - KMER + 1; i += 1) {
kmer = makeKmer(seq, i, kmer);
if(kmer < 0)
continue;
long pos = kmer>>3;
long bit = kmer & 0x07;
if( (mBloomFilter[pos] & (0x1<<bit)) == 0)
continue;
GenePos gp = mKmerPos[kmer];
// is a dupe
if(gp.contig < 0) {
for(int g=0; g<mDupeList[gp.position].size();g++) {
long gplong = gp2long(shift(mDupeList[gp.position][g], i));
if(abs(gplong - gp1) <= 1)
makeMask(mask, MATCH_TOP, seqlen, i, KMER);
else if(abs(gplong - gp2) <= 1)
makeMask(mask, MATCH_SECOND, seqlen, i, KMER);
else if(gplong == 0)
makeMask(mask, MATCH_NONE, seqlen, i, KMER);
}
} else {
long gplong = gp2long(shift(gp, i));
if(abs(gplong - gp1) <= 1)
makeMask(mask, MATCH_TOP, seqlen, i, KMER);
else if(abs(gplong - gp2) <= 1)
makeMask(mask, MATCH_SECOND, seqlen, i, KMER);
else if(gplong == 0)
makeMask(mask, MATCH_NONE, seqlen, i, KMER);
}
}
int mismatches = 0;
for(int i=0; i<seqlen; i++){
if(mask[i] == MATCH_NONE || mask[i] == MATCH_UNKNOWN )
mismatches++;
}
if(mismatches>10){
// too many mismatch indicates not a real fusion
return vector<SeqMatch>();
}
vector<SeqMatch> result = segmentMask(mask, seqlen, long2gp(gp1), long2gp(gp2));
delete mask;
return result;
}
void Indexer::makeMask(unsigned char* mask, unsigned char flag, int seqlen, int start, int kmerSize) {
for(int i=start;i<seqlen && i<start+kmerSize;i++)
mask[i]=max(mask[i], flag);
}
vector<SeqMatch> Indexer::segmentMask(unsigned char* mask, int seqlen, GenePos gp1, GenePos gp2) {
vector<SeqMatch> result;
const int ALLOWED_GAP = 10;
const int THRESHOLD_LEN = 20;
int targets[2] = {MATCH_TOP, MATCH_SECOND};
GenePos gps[2] = {gp1, gp2};
for(int t=0; t<2; t++){
int maxStart = -1;
int maxEnd = -1;
// get gp1
int target = targets[t];
int start = 0;
int end = 0;
while(true){
// get next start
while(mask[start] != target && start != seqlen-1)
start++;
// reach the tail
if(start >= seqlen-1)
break;
if(mask[start] == target){
end = start+1;
// get the end
int g=0;
while(g<ALLOWED_GAP && end+g<seqlen){
if(mask[end+g] > target)
break;
if(end+g < seqlen && mask[end+g] == target ){
end += g+1;
g = 0;
continue;
}
g++;
}
// left shift to remove the mismatched end
end--;
if(end - start > maxEnd - maxStart){
maxEnd = end;
maxStart = start;
}
start++;
} else {
// not found
break;
}
}
if(maxEnd - maxStart > THRESHOLD_LEN){
SeqMatch match;
match.seqStart = maxStart;
match.seqEnd = maxEnd;
match.startGP = gps[t];
result.push_back(match);
}
}
/*if(result.size()>=2 && inRequiredDirection(result)){
cout<<"gp1,"<<gp1.contig<<":"<<gp1.position<<", ";
cout<<"gp2,"<<gp2.contig<<":"<<gp2.position<<endl;
for(int i=0;i<seqlen;i++)
cout<<(int)mask[i];
cout << endl;
}*/
return result;
}
// this function is to gurantee that all the supporting reads will have same direction
bool Indexer::inRequiredDirection(vector<SeqMatch>& mapping) {
if(mapping.size()<2)
return false;
SeqMatch left = mapping[0];
SeqMatch right = mapping[1];
if(left.seqStart > right.seqStart) {
left = mapping[1];
right = mapping[0];
}
// both are positive, good to go
if(left.startGP.position >0 && right.startGP.position >0)
return true;
// if both are negative, we should use their reverse complement, which will be both positive
if(left.startGP.position <0 && right.startGP.position <0)
return false;
// if one is positive, the other is negative, their reverse complement will be the same
if( mFusions[left.startGP.contig].isReversed() && !mFusions[right.startGP.contig].isReversed()){
// if left is reversed gene and right is forward gene
// we should use their reverse complement, which keep the left forward gene
return false;
}
else if( !mFusions[left.startGP.contig].isReversed() && mFusions[right.startGP.contig].isReversed()){
// if left is forward gene and right is reversed gene, good to go
return true;
}
else {
// otherwise, we should keep the left has smaller contig
if(left.startGP.contig < right.startGP.contig)
return true;
// or smaller positive if contig is the same
if(left.startGP.contig == right.startGP.contig && abs(left.startGP.position) < abs(left.startGP.position))
return true;
else
return false;
}
return false;
}
long Indexer::makeKmer(string & seq, int pos, long lastKmer, int step) {
// else calculate it completely
long kmer = 0;
int start = 0;
// re-use several bits
if(lastKmer >= 0) {
kmer = lastKmer;
start = KMER - step;
if(step == 1)
kmer = ((kmer & 0x3FFFFFFF) << 2);
else if (step == 2)
kmer = ((kmer & 0x0FFFFFFF) << 2);
else if (step == 3)
kmer = ((kmer & 0x03FFFFFF) << 2);
else if (step == 4)
kmer = ((kmer & 0x00FFFFFF) << 2);
}
for(int i=start;i<KMER;i++){
switch(seq[pos+i]){
case 'A':
kmer += 0;
break;
case 'T':
kmer += 1;
break;
case 'C':
kmer += 2;
break;
case 'G':
kmer += 3;
break;
default:
return -1;
}
// not the tail
if(i<KMER-1)
kmer = kmer << 2;
}
return kmer;
}
long Indexer::gp2long(const GenePos& gp){
long ret = gp.contig;
int temp[2]={gp.position, 0};
return (ret<<32) | *((long*)temp);
}
GenePos Indexer::long2gp(const long val){
GenePos gp;
gp.position = (val & 0x00000000FFFFFFFF);
gp.contig = val >> 32;
return gp;
}
GenePos Indexer::shift(const GenePos& gp, int i){
GenePos gpNew;
gpNew.contig = gp.contig;
gpNew.position = gp.position - i;
return gpNew;
}
void Indexer::printStat() {
cout<<"mUniquePos:"<<mUniquePos<<endl;
cout<<"mDupePos:"<<mDupePos<<endl;
}
bool Indexer::test() {
short contigs[10]={0, 1, 3, 220, -1, 0, 23, 4440, 110, 10};
int positions[10]={0, 111, 222, -333, 444, 555555, 6, -7777777, 8888, -9999};
for(int i=0;i<10;i++){
GenePos gp;
gp.contig = contigs[i];
gp.position = positions[i];
long val = gp2long(gp);
GenePos gp2 = long2gp(val);
long val2 = gp2long(gp2);
cout << gp2.contig << ", " << gp2.position << endl;
if ((gp.contig == gp2.contig && gp.position == gp2.position && val==val2) == false)
return false;
}
return true;
}<commit_msg>change unordered_map back to map for mapRead<commit_after>#include "indexer.h"
#include "util.h"
#include <memory.h>
const int KMER = 16;
// 512M bloom filter
const unsigned int BLOOM_FILTER_SIZE = 1<<29;
const unsigned int BLOOM_FILTER_BITS = BLOOM_FILTER_SIZE - 1;
Indexer::Indexer(string refFile, vector<Fusion>& fusions) {
mRefFile = refFile;
mFusions = fusions;
mReference = new FastaReader(refFile, false);
mReference->readAll();
mUniquePos = 0;
mDupePos = 0;
mBloomFilter = new unsigned char[BLOOM_FILTER_SIZE];
memset(mBloomFilter, 0, sizeof(unsigned char) * BLOOM_FILTER_SIZE);
}
Indexer::~Indexer() {
delete mReference;
mReference = NULL;
delete mBloomFilter;
mBloomFilter = NULL;
}
FastaReader* Indexer::getRef() {
return mReference;
}
void Indexer::makeIndex() {
if(mReference == NULL)
return ;
map<string, string>& ref = mReference->mAllContigs;
for(int ctg=0; ctg<mFusions.size(); ctg++){
Gene gene = mFusions[ctg].mGene;
string chr = gene.mChr;
if(ref.count(chr) == 0) {
if(ref.count("chr" + chr) >0)
chr = "chr" + chr;
else if(ref.count(replace(chr, "chr", "")) >0)
chr = replace(chr, "chr", "");
else{
mFusionSeq.push_back("");
continue;
}
}
string s = ref[chr].substr(gene.mStart, gene.mEnd - gene.mStart);
str2upper(s);
mFusionSeq.push_back(s);
//index forward
indexContig(ctg, s, 0);
//index reverse complement
Sequence seq = ~(Sequence(s));
indexContig(ctg, seq.mStr, -s.length()+1);
}
fillBloomFilter();
loginfo("mapper indexing done");
}
void Indexer::fillBloomFilter() {
unordered_map<long, GenePos>::iterator iter;
for(iter = mKmerPos.begin(); iter!=mKmerPos.end(); iter++) {
long kmer = iter->first;
long pos = kmer>>3;
long bit = kmer & 0x07;
mBloomFilter[pos] |= (0x1<<bit);
}
}
void Indexer::indexContig(int ctg, string seq, int start) {
long kmer = -1;
for(int i=0; i<seq.length() - KMER; ++i) {
kmer = makeKmer(seq, i, kmer);
//cout << kmer << "\t" << seq.substr(i, KMER) << endl;
if(kmer < 0)
continue;
GenePos site;
site.contig = ctg;
site.position = i+start;
// this is a dupe
if(mKmerPos.count(kmer) >0 ){
GenePos gp = mKmerPos[kmer];
// already marked as a dupe
if(gp.contig < 0) {
mDupeList[gp.position].push_back(site);
} else {
// else make a new dupe entry
vector<GenePos> gps;
gps.push_back(gp);
gps.push_back(site);
mDupeList.push_back(gps);
// and mark it as a dupe
mKmerPos[kmer].contig = -1;
mKmerPos[kmer].position = mDupeList.size() -1;
mUniquePos--;
mDupePos++;
}
} else {
mKmerPos[kmer]=site;
mUniquePos++;
}
}
}
vector<SeqMatch> Indexer::mapRead(Read* r) {
map<long, int> kmerStat;
kmerStat[0]=0;
string seq = r->mSeq.mStr;
const int step = 2;
int seqlen = seq.length();
// first pass, we only want to find if this seq can be partially aligned to the target
long kmer = -1;
for(int i=0; i< seqlen - KMER + 1; i += step) {
kmer = makeKmer(seq, i, kmer, step);
if(kmer < 0)
continue;
long pos = kmer>>3;
long bit = kmer & 0x07;
if( (mBloomFilter[pos] & (0x1<<bit)) == 0) {
kmerStat[0]++;
continue;
}
GenePos gp = mKmerPos[kmer];
// is a dupe
if(gp.contig < 0) {
for(int g=0; g<mDupeList[gp.position].size();g++) {
long gplong = gp2long(shift(mDupeList[gp.position][g], i));
if(kmerStat.count(gplong)==0)
kmerStat[gplong] = 1;
else
kmerStat[gplong] += 1;
}
} else {
long gplong = gp2long(shift(gp, i));
if(kmerStat.count(gplong)==0)
kmerStat[gplong] = 1;
else
kmerStat[gplong] += 1;
}
}
// get 1st and 2nd hit
long gp1 = 0;
int count1 = 0;
long gp2 = 0;
int count2 = 0;
map<long, int>::iterator iter;
//TODO: handle small difference caused by INDEL
for(iter = kmerStat.begin(); iter!=kmerStat.end(); iter++){
if(iter->first != 0 && iter->second > count1){
gp2 = gp1;
count2 = count1;
gp1 = iter->first;
count1 = iter->second;
} else if(iter->first != 0 && iter->second > count2 ){
gp2 = iter->first;
count2 = iter->second;
}
}
if(count1 * step < 40 || count2 * step < 20){
// return an null list
return vector<SeqMatch>();
}
unsigned char* mask = new unsigned char[seqlen];
memset(mask, MATCH_UNKNOWN, sizeof(unsigned char)*seqlen);
// second pass, make the mask
kmer = -1;
for(int i=0; i< seqlen - KMER + 1; i += 1) {
kmer = makeKmer(seq, i, kmer);
if(kmer < 0)
continue;
long pos = kmer>>3;
long bit = kmer & 0x07;
if( (mBloomFilter[pos] & (0x1<<bit)) == 0)
continue;
GenePos gp = mKmerPos[kmer];
// is a dupe
if(gp.contig < 0) {
for(int g=0; g<mDupeList[gp.position].size();g++) {
long gplong = gp2long(shift(mDupeList[gp.position][g], i));
if(abs(gplong - gp1) <= 1)
makeMask(mask, MATCH_TOP, seqlen, i, KMER);
else if(abs(gplong - gp2) <= 1)
makeMask(mask, MATCH_SECOND, seqlen, i, KMER);
else if(gplong == 0)
makeMask(mask, MATCH_NONE, seqlen, i, KMER);
}
} else {
long gplong = gp2long(shift(gp, i));
if(abs(gplong - gp1) <= 1)
makeMask(mask, MATCH_TOP, seqlen, i, KMER);
else if(abs(gplong - gp2) <= 1)
makeMask(mask, MATCH_SECOND, seqlen, i, KMER);
else if(gplong == 0)
makeMask(mask, MATCH_NONE, seqlen, i, KMER);
}
}
int mismatches = 0;
for(int i=0; i<seqlen; i++){
if(mask[i] == MATCH_NONE || mask[i] == MATCH_UNKNOWN )
mismatches++;
}
if(mismatches>10){
// too many mismatch indicates not a real fusion
return vector<SeqMatch>();
}
vector<SeqMatch> result = segmentMask(mask, seqlen, long2gp(gp1), long2gp(gp2));
delete mask;
return result;
}
void Indexer::makeMask(unsigned char* mask, unsigned char flag, int seqlen, int start, int kmerSize) {
for(int i=start;i<seqlen && i<start+kmerSize;i++)
mask[i]=max(mask[i], flag);
}
vector<SeqMatch> Indexer::segmentMask(unsigned char* mask, int seqlen, GenePos gp1, GenePos gp2) {
vector<SeqMatch> result;
const int ALLOWED_GAP = 10;
const int THRESHOLD_LEN = 20;
int targets[2] = {MATCH_TOP, MATCH_SECOND};
GenePos gps[2] = {gp1, gp2};
for(int t=0; t<2; t++){
int maxStart = -1;
int maxEnd = -1;
// get gp1
int target = targets[t];
int start = 0;
int end = 0;
while(true){
// get next start
while(mask[start] != target && start != seqlen-1)
start++;
// reach the tail
if(start >= seqlen-1)
break;
if(mask[start] == target){
end = start+1;
// get the end
int g=0;
while(g<ALLOWED_GAP && end+g<seqlen){
if(mask[end+g] > target)
break;
if(end+g < seqlen && mask[end+g] == target ){
end += g+1;
g = 0;
continue;
}
g++;
}
// left shift to remove the mismatched end
end--;
if(end - start > maxEnd - maxStart){
maxEnd = end;
maxStart = start;
}
start++;
} else {
// not found
break;
}
}
if(maxEnd - maxStart > THRESHOLD_LEN){
SeqMatch match;
match.seqStart = maxStart;
match.seqEnd = maxEnd;
match.startGP = gps[t];
result.push_back(match);
}
}
/*if(result.size()>=2 && inRequiredDirection(result)){
cout<<"gp1,"<<gp1.contig<<":"<<gp1.position<<", ";
cout<<"gp2,"<<gp2.contig<<":"<<gp2.position<<endl;
for(int i=0;i<seqlen;i++)
cout<<(int)mask[i];
cout << endl;
}*/
return result;
}
// this function is to gurantee that all the supporting reads will have same direction
bool Indexer::inRequiredDirection(vector<SeqMatch>& mapping) {
if(mapping.size()<2)
return false;
SeqMatch left = mapping[0];
SeqMatch right = mapping[1];
if(left.seqStart > right.seqStart) {
left = mapping[1];
right = mapping[0];
}
// both are positive, good to go
if(left.startGP.position >0 && right.startGP.position >0)
return true;
// if both are negative, we should use their reverse complement, which will be both positive
if(left.startGP.position <0 && right.startGP.position <0)
return false;
// if one is positive, the other is negative, their reverse complement will be the same
if( mFusions[left.startGP.contig].isReversed() && !mFusions[right.startGP.contig].isReversed()){
// if left is reversed gene and right is forward gene
// we should use their reverse complement, which keep the left forward gene
return false;
}
else if( !mFusions[left.startGP.contig].isReversed() && mFusions[right.startGP.contig].isReversed()){
// if left is forward gene and right is reversed gene, good to go
return true;
}
else {
// otherwise, we should keep the left has smaller contig
if(left.startGP.contig < right.startGP.contig)
return true;
// or smaller positive if contig is the same
if(left.startGP.contig == right.startGP.contig && abs(left.startGP.position) < abs(left.startGP.position))
return true;
else
return false;
}
return false;
}
long Indexer::makeKmer(string & seq, int pos, long lastKmer, int step) {
// else calculate it completely
long kmer = 0;
int start = 0;
// re-use several bits
if(lastKmer >= 0) {
kmer = lastKmer;
start = KMER - step;
if(step == 1)
kmer = ((kmer & 0x3FFFFFFF) << 2);
else if (step == 2)
kmer = ((kmer & 0x0FFFFFFF) << 2);
else if (step == 3)
kmer = ((kmer & 0x03FFFFFF) << 2);
else if (step == 4)
kmer = ((kmer & 0x00FFFFFF) << 2);
}
for(int i=start;i<KMER;i++){
switch(seq[pos+i]){
case 'A':
kmer += 0;
break;
case 'T':
kmer += 1;
break;
case 'C':
kmer += 2;
break;
case 'G':
kmer += 3;
break;
default:
return -1;
}
// not the tail
if(i<KMER-1)
kmer = kmer << 2;
}
return kmer;
}
long Indexer::gp2long(const GenePos& gp){
long ret = gp.contig;
int temp[2]={gp.position, 0};
return (ret<<32) | *((long*)temp);
}
GenePos Indexer::long2gp(const long val){
GenePos gp;
gp.position = (val & 0x00000000FFFFFFFF);
gp.contig = val >> 32;
return gp;
}
GenePos Indexer::shift(const GenePos& gp, int i){
GenePos gpNew;
gpNew.contig = gp.contig;
gpNew.position = gp.position - i;
return gpNew;
}
void Indexer::printStat() {
cout<<"mUniquePos:"<<mUniquePos<<endl;
cout<<"mDupePos:"<<mDupePos<<endl;
}
bool Indexer::test() {
short contigs[10]={0, 1, 3, 220, -1, 0, 23, 4440, 110, 10};
int positions[10]={0, 111, 222, -333, 444, 555555, 6, -7777777, 8888, -9999};
for(int i=0;i<10;i++){
GenePos gp;
gp.contig = contigs[i];
gp.position = positions[i];
long val = gp2long(gp);
GenePos gp2 = long2gp(val);
long val2 = gp2long(gp2);
cout << gp2.contig << ", " << gp2.position << endl;
if ((gp.contig == gp2.contig && gp.position == gp2.position && val==val2) == false)
return false;
}
return true;
}<|endoftext|>
|
<commit_before>#include <unistd.h>
#include <fcntl.h>
#include <sys/time.h>
#include <sys/resource.h>
#include <sys/ptrace.h>
#include <sys/syscall.h>
#include <sys/user.h>
#include <sys/types.h>
#include <sys/wait.h>
#include "seccomp_bpf.h"
#include <iostream>
using namespace std;
static bool install_syscall_filter() {
struct sock_filter filter[] = {
VALIDATE_ARCHITECTURE,
/* Grab the system call number. */
EXAMINE_SYSCALL,
/* List allowed syscalls. Look up via ausyscall. */
ALLOW_SYSCALL(exit_group),
ALLOW_SYSCALL(exit),
ALLOW_SYSCALL(stat),
ALLOW_SYSCALL(fstat),
ALLOW_SYSCALL(read),
ALLOW_SYSCALL(write),
ALLOW_SYSCALL(getdents),
ALLOW_SYSCALL(close),
ALLOW_SYSCALL(mmap),
ALLOW_SYSCALL(mprotect),
ALLOW_SYSCALL(munmap),
ALLOW_SYSCALL(brk),
ALLOW_SYSCALL(futex),
ALLOW_SYSCALL(lseek),
ALLOW_SYSCALL(set_tid_address),
ALLOW_SYSCALL(set_robust_list),
ALLOW_SYSCALL(rt_sigaction),
ALLOW_SYSCALL(rt_sigprocmask),
ALLOW_SYSCALL(getrlimit),
ALLOW_SYSCALL(arch_prctl),
ALLOW_SYSCALL(access),
ALLOW_SYSCALL(fstatfs),
ALLOW_SYSCALL(readlink),
ALLOW_SYSCALL(fadvise64),
ALLOW_SYSCALL(clock_gettime),
ALLOW_SYSCALL(sysinfo),
ALLOW_SYSCALL(getuid),
ALLOW_SYSCALL(geteuid),
ALLOW_SYSCALL(getgid),
ALLOW_SYSCALL(getegid),
ALLOW_SYSCALL(fcntl),
ALLOW_SYSCALL(mremap),
ALLOW_SYSCALL(statfs),
ALLOW_SYSCALL(readlink),
ALLOW_SYSCALL(getpid),
ALLOW_SYSCALL(gettid),
ALLOW_SYSCALL(tgkill),
ALLOW_SYSCALL(ftruncate),
ALLOW_SYSCALL(ioctl),
ALLOW_SYSCALL(sched_yield),
ALLOW_SYSCALL(clone),
ALLOW_SYSCALL(wait4),
ALLOW_SYSCALL(mknod),
ALLOW_SYSCALL(getrandom),
ALLOW_SYSCALL(shmctl),
ALLOW_SYSCALL(prlimit64),
ALLOW_SYSCALL(dup),
TRACE_SYSCALL(execve),
TRACE_SYSCALL(mkdir),
TRACE_SYSCALL(unlink),
TRACE_SYSCALL(open),
TRACE_SYSCALL(openat),
// Uncomment the following when trying to figure out which new
// syscall's are being made:
// TRACE_ALL,
// ALLOW_ALL,
KILL_PROCESS,
};
struct sock_fprog prog = {
sizeof(filter)/sizeof(filter[0]),
filter,
};
// Lock down the app so that it can't get new privs, such as setuid.
// Calling this is a requirement for an unprivileged process to use mode
// 2 seccomp filters, ala SECCOMP_MODE_FILTER, otherwise we'd have to be
// root.
if (prctl(PR_SET_NO_NEW_PRIVS, 1, 0, 0, 0)) {
perror("prctl(NO_NEW_PRIVS)");
goto failed;
}
// Now call seccomp and restrict the system calls that can be made to only
// the ones in the provided filter list.
if (prctl(PR_SET_SECCOMP, SECCOMP_MODE_FILTER, &prog)) {
perror("prctl(SECCOMP)");
goto failed;
}
return true;
failed:
if (errno == EINVAL) {
fprintf(stderr, "SECCOMP_FILTER is not available. :(\n");
}
return false;
}
static void setLimits() {
struct rlimit n;
// Limit to 20 seconds of CPU.
n.rlim_cur = 20;
n.rlim_max = 20;
if (setrlimit(RLIMIT_CPU, &n)) {
perror("setrlimit(RLIMIT_CPU)");
}
// Limit to 1G of Address space.
n.rlim_cur = 1000000000;
n.rlim_max = 1000000000;
if (setrlimit(RLIMIT_AS, &n)) {
perror("setrlimit(RLIMIT_AS)");
}
}
int do_child(int argc, char **argv) {
char *args[argc+1];
memcpy(args, argv, argc * sizeof(char *));
args[argc] = NULL;
if (ptrace(PTRACE_TRACEME, 0, 0, 0)) {
perror("ptrace");
exit(-1);
}
kill(getpid(), SIGSTOP);
setLimits();
if (!install_syscall_filter()) {
perror("Failed to install syscall filter");
return -1;
}
(void)execvp(args[0], args);
// if execvp returns, we couldn't run the child. Probably
// because the compile failed. Let's kill ourselves so the
// parent sees the signal and exits appropriately.
perror("Couldn't run child.");
kill(getpid(), SIGKILL);
return -1;
}
// read_string copies a null-terminated string out
// of the child's address space, one character at a time.
// It allocates memory and returns it to the caller;
// it is the caller's responsibility to free it.
char *read_string(pid_t child, unsigned long addr) {
#define INITIAL_ALLOCATION 4096
char *val = (char *) malloc(INITIAL_ALLOCATION);
size_t allocated = INITIAL_ALLOCATION;
size_t read = 0;
unsigned long tmp;
while (1) {
if (read + sizeof tmp > allocated) {
allocated *= 2;
val = (char *) realloc(val, allocated);
}
tmp = ptrace(PTRACE_PEEKDATA, child, addr + read);
if (errno != 0) {
val[read] = 0;
break;
}
memcpy(val + read, &tmp, sizeof tmp);
if (memchr(&tmp, 0, sizeof tmp) != NULL) {
break;
}
read += sizeof tmp;
}
return val;
}
void child_fail(pid_t child, const char* message) {
perror(message);
kill(child, SIGKILL);
exit(-1);
}
const char *mkdir_allowed_prefixes[] = {
"/tmp",
"/var/cache/fontconfig",
NULL,
};
const char *unlink_allowed_prefixes[] = {
"/tmp",
NULL,
};
const char *writing_allowed_prefixes[] = {
"/tmp/",
NULL,
};
const char *readonly_allowed_prefixes[] = {
"/etc/fonts",
"/etc/fiddle/",
"/etc/glvnd/",
"/etc/ld.so.cache",
"/lib/",
"/mnt/pd0/",
"/tmp/",
"/usr/lib/",
"/usr/local/share/fonts",
"/usr/local/lib",
"/usr/share/",
"/sys/devices/",
"/var/cache/fontconfig",
"skia.conf",
NULL,
};
void test_against_prefixes(pid_t child, const char * caller, char* name, const char** prefixes) {
if (NULL != strstr(name, "../")) {
perror(caller);
perror(name);
child_fail(child, "No relative paths...");
}
bool okay = false;
for (; *prefixes != NULL; prefixes++) {
if (!strncmp(*prefixes, name, strlen(*prefixes))) {
okay = true;
break;
}
}
if (!okay) {
perror(name);
perror(caller);
child_fail(child, "Invalid filename.");
}
}
/*
* The first six integer or pointer arguments are passed in registers RDI,
* RSI, RDX, RCX (R10 in the Linux kernel interface), R8, and R9,
* while XMM0, XMM1, XMM2, XMM3, XMM4, XMM5, XMM6 and XMM7 are used for
* certain floating point arguments.
*/
int do_trace(pid_t child, char *allowed_exec) {
int status;
waitpid(child, &status, 0);
ptrace(PTRACE_SETOPTIONS, child, 0, PTRACE_O_TRACEEXEC | PTRACE_O_TRACESECCOMP);
ptrace(PTRACE_CONT, child, 0, 0);
while(1) {
waitpid(child, &status, 0);
if (WIFEXITED(status)) {
return 0;
}
if (WIFSIGNALED(status)) {
cerr << "Signal: " << WTERMSIG(status) << endl;
perror("WIFSIGNALED");
return 1;
}
if (status>>8 == (SIGTRAP | (PTRACE_EVENT_SECCOMP<<8))) {
struct user_regs_struct regs;
if(ptrace(PTRACE_GETREGS, child, NULL, ®s)) {
perror("The child failed...");
exit(-1);
}
int syscall = regs.orig_rax;
if (syscall == SYS_execve) {
char *name = read_string(child, regs.rdi);
if (strcmp(name, allowed_exec)) {
child_fail(child, "Invalid exec.");
}
free(name);
} else if (syscall == SYS_open) {
char *name = read_string(child, regs.rdi);
const char **prefixes = readonly_allowed_prefixes;
int flags = regs.rsi;
if (O_RDONLY != (flags & O_ACCMODE)) {
prefixes = writing_allowed_prefixes;
}
test_against_prefixes(child, "open", name, prefixes);
free(name);
} else if (syscall == SYS_openat) {
char *name = read_string(child, regs.rsi);
int flags = regs.rdx;
const char **prefixes = readonly_allowed_prefixes;
if (O_RDONLY != (flags & O_ACCMODE)) {
prefixes = writing_allowed_prefixes;
}
test_against_prefixes(child, "openat", name, prefixes);
free(name);
} else if (syscall == SYS_mkdir) {
char *name = read_string(child, regs.rdi);
test_against_prefixes(child, "mkdir", name, mkdir_allowed_prefixes);
free(name);
} else if (syscall == SYS_unlink) {
char *name = read_string(child, regs.rdi);
test_against_prefixes(child, "unlink", name, unlink_allowed_prefixes);
free(name);
} else {
// this should never happen, but if we're in TRACE_ALL
// mode for debugging, this lets me print out what system
// calls are happening unexpectedly.
cout << "WEIRD SYSTEM CALL: " << syscall << endl;
child_fail(child, "Invalid system call.");
}
}
ptrace(PTRACE_CONT, child, 0, 0);
}
return 0;
}
int main(int argc, char** argv) {
pid_t child = fork();
if (child == 0) {
return do_child(argc-1, argv+1);
} else {
return do_trace(child, argv[1]);
}
}
<commit_msg>fiddle - More syscalls to allow.<commit_after>#include <unistd.h>
#include <fcntl.h>
#include <sys/time.h>
#include <sys/resource.h>
#include <sys/ptrace.h>
#include <sys/syscall.h>
#include <sys/user.h>
#include <sys/types.h>
#include <sys/wait.h>
#include "seccomp_bpf.h"
#include <iostream>
using namespace std;
static bool install_syscall_filter() {
struct sock_filter filter[] = {
VALIDATE_ARCHITECTURE,
/* Grab the system call number. */
EXAMINE_SYSCALL,
/* List allowed syscalls. Look up via ausyscall. */
ALLOW_SYSCALL(exit_group),
ALLOW_SYSCALL(exit),
ALLOW_SYSCALL(stat),
ALLOW_SYSCALL(fstat),
ALLOW_SYSCALL(read),
ALLOW_SYSCALL(write),
ALLOW_SYSCALL(getdents),
ALLOW_SYSCALL(close),
ALLOW_SYSCALL(mmap),
ALLOW_SYSCALL(mprotect),
ALLOW_SYSCALL(munmap),
ALLOW_SYSCALL(brk),
ALLOW_SYSCALL(futex),
ALLOW_SYSCALL(lseek),
ALLOW_SYSCALL(set_tid_address),
ALLOW_SYSCALL(set_robust_list),
ALLOW_SYSCALL(rt_sigaction),
ALLOW_SYSCALL(rt_sigprocmask),
ALLOW_SYSCALL(getrlimit),
ALLOW_SYSCALL(arch_prctl),
ALLOW_SYSCALL(access),
ALLOW_SYSCALL(fstatfs),
ALLOW_SYSCALL(readlink),
ALLOW_SYSCALL(fadvise64),
ALLOW_SYSCALL(clock_gettime),
ALLOW_SYSCALL(sysinfo),
ALLOW_SYSCALL(getuid),
ALLOW_SYSCALL(geteuid),
ALLOW_SYSCALL(getgid),
ALLOW_SYSCALL(getegid),
ALLOW_SYSCALL(fcntl),
ALLOW_SYSCALL(mremap),
ALLOW_SYSCALL(statfs),
ALLOW_SYSCALL(readlink),
ALLOW_SYSCALL(getpid),
ALLOW_SYSCALL(gettid),
ALLOW_SYSCALL(tgkill),
ALLOW_SYSCALL(ftruncate),
ALLOW_SYSCALL(ioctl),
ALLOW_SYSCALL(sched_yield),
ALLOW_SYSCALL(clone),
ALLOW_SYSCALL(wait4),
ALLOW_SYSCALL(mknod),
ALLOW_SYSCALL(getrandom),
ALLOW_SYSCALL(shmctl),
ALLOW_SYSCALL(prlimit64),
ALLOW_SYSCALL(dup),
ALLOW_SYSCALL(link),
ALLOW_SYSCALL(rename),
ALLOW_SYSCALL(renameat),
ALLOW_SYSCALL(renameat2),
ALLOW_SYSCALL(chmod),
ALLOW_SYSCALL(chown),
TRACE_SYSCALL(execve),
TRACE_SYSCALL(mkdir),
TRACE_SYSCALL(unlink),
TRACE_SYSCALL(open),
TRACE_SYSCALL(openat),
// Uncomment the following when trying to figure out which new
// syscall's are being made:
TRACE_ALL,
// ALLOW_ALL,
KILL_PROCESS,
};
struct sock_fprog prog = {
sizeof(filter)/sizeof(filter[0]),
filter,
};
// Lock down the app so that it can't get new privs, such as setuid.
// Calling this is a requirement for an unprivileged process to use mode
// 2 seccomp filters, ala SECCOMP_MODE_FILTER, otherwise we'd have to be
// root.
if (prctl(PR_SET_NO_NEW_PRIVS, 1, 0, 0, 0)) {
perror("prctl(NO_NEW_PRIVS)");
goto failed;
}
// Now call seccomp and restrict the system calls that can be made to only
// the ones in the provided filter list.
if (prctl(PR_SET_SECCOMP, SECCOMP_MODE_FILTER, &prog)) {
perror("prctl(SECCOMP)");
goto failed;
}
return true;
failed:
if (errno == EINVAL) {
fprintf(stderr, "SECCOMP_FILTER is not available. :(\n");
}
return false;
}
static void setLimits() {
struct rlimit n;
// Limit to 20 seconds of CPU.
n.rlim_cur = 20;
n.rlim_max = 20;
if (setrlimit(RLIMIT_CPU, &n)) {
perror("setrlimit(RLIMIT_CPU)");
}
// Limit to 1G of Address space.
n.rlim_cur = 1000000000;
n.rlim_max = 1000000000;
if (setrlimit(RLIMIT_AS, &n)) {
perror("setrlimit(RLIMIT_AS)");
}
}
int do_child(int argc, char **argv) {
char *args[argc+1];
memcpy(args, argv, argc * sizeof(char *));
args[argc] = NULL;
if (ptrace(PTRACE_TRACEME, 0, 0, 0)) {
perror("ptrace");
exit(-1);
}
kill(getpid(), SIGSTOP);
setLimits();
if (!install_syscall_filter()) {
perror("Failed to install syscall filter");
return -1;
}
(void)execvp(args[0], args);
// if execvp returns, we couldn't run the child. Probably
// because the compile failed. Let's kill ourselves so the
// parent sees the signal and exits appropriately.
perror("Couldn't run child.");
kill(getpid(), SIGKILL);
return -1;
}
// read_string copies a null-terminated string out
// of the child's address space, one character at a time.
// It allocates memory and returns it to the caller;
// it is the caller's responsibility to free it.
char *read_string(pid_t child, unsigned long addr) {
#define INITIAL_ALLOCATION 4096
char *val = (char *) malloc(INITIAL_ALLOCATION);
size_t allocated = INITIAL_ALLOCATION;
size_t read = 0;
unsigned long tmp;
while (1) {
if (read + sizeof tmp > allocated) {
allocated *= 2;
val = (char *) realloc(val, allocated);
}
tmp = ptrace(PTRACE_PEEKDATA, child, addr + read);
if (errno != 0) {
val[read] = 0;
break;
}
memcpy(val + read, &tmp, sizeof tmp);
if (memchr(&tmp, 0, sizeof tmp) != NULL) {
break;
}
read += sizeof tmp;
}
return val;
}
void child_fail(pid_t child, const char* message) {
perror(message);
kill(child, SIGKILL);
exit(-1);
}
const char *mkdir_allowed_prefixes[] = {
"/tmp",
"/var/cache/fontconfig",
NULL,
};
const char *unlink_allowed_prefixes[] = {
"/tmp",
NULL,
};
const char *writing_allowed_prefixes[] = {
"/tmp/",
NULL,
};
const char *readonly_allowed_prefixes[] = {
"/etc/fonts",
"/etc/fiddle/",
"/etc/glvnd/",
"/etc/ld.so.cache",
"/lib/",
"/mnt/pd0/",
"/tmp/",
"/usr/lib/",
"/usr/local/share/fonts",
"/usr/local/lib",
"/usr/share/",
"/sys/devices/",
"/var/cache/fontconfig",
"skia.conf",
NULL,
};
void test_against_prefixes(pid_t child, const char * caller, char* name, const char** prefixes) {
if (NULL != strstr(name, "../")) {
perror(caller);
perror(name);
child_fail(child, "No relative paths...");
}
bool okay = false;
for (; *prefixes != NULL; prefixes++) {
if (!strncmp(*prefixes, name, strlen(*prefixes))) {
okay = true;
break;
}
}
if (!okay) {
perror(name);
perror(caller);
child_fail(child, "Invalid filename.");
}
}
/*
* The first six integer or pointer arguments are passed in registers RDI,
* RSI, RDX, RCX (R10 in the Linux kernel interface), R8, and R9,
* while XMM0, XMM1, XMM2, XMM3, XMM4, XMM5, XMM6 and XMM7 are used for
* certain floating point arguments.
*/
int do_trace(pid_t child, char *allowed_exec) {
int status;
waitpid(child, &status, 0);
ptrace(PTRACE_SETOPTIONS, child, 0, PTRACE_O_TRACEEXEC | PTRACE_O_TRACESECCOMP);
ptrace(PTRACE_CONT, child, 0, 0);
while(1) {
waitpid(child, &status, 0);
if (WIFEXITED(status)) {
return 0;
}
if (WIFSIGNALED(status)) {
cerr << "Signal: " << WTERMSIG(status) << endl;
perror("WIFSIGNALED");
return 1;
}
if (status>>8 == (SIGTRAP | (PTRACE_EVENT_SECCOMP<<8))) {
struct user_regs_struct regs;
if(ptrace(PTRACE_GETREGS, child, NULL, ®s)) {
perror("The child failed...");
exit(-1);
}
int syscall = regs.orig_rax;
if (syscall == SYS_execve) {
char *name = read_string(child, regs.rdi);
if (strcmp(name, allowed_exec)) {
child_fail(child, "Invalid exec.");
}
free(name);
} else if (syscall == SYS_open) {
char *name = read_string(child, regs.rdi);
const char **prefixes = readonly_allowed_prefixes;
int flags = regs.rsi;
if (O_RDONLY != (flags & O_ACCMODE)) {
prefixes = writing_allowed_prefixes;
}
test_against_prefixes(child, "open", name, prefixes);
free(name);
} else if (syscall == SYS_openat) {
char *name = read_string(child, regs.rsi);
int flags = regs.rdx;
const char **prefixes = readonly_allowed_prefixes;
if (O_RDONLY != (flags & O_ACCMODE)) {
prefixes = writing_allowed_prefixes;
}
test_against_prefixes(child, "openat", name, prefixes);
free(name);
} else if (syscall == SYS_mkdir) {
char *name = read_string(child, regs.rdi);
test_against_prefixes(child, "mkdir", name, mkdir_allowed_prefixes);
free(name);
} else if (syscall == SYS_unlink) {
char *name = read_string(child, regs.rdi);
test_against_prefixes(child, "unlink", name, unlink_allowed_prefixes);
free(name);
} else {
// this should never happen, but if we're in TRACE_ALL
// mode for debugging, this lets me print out what system
// calls are happening unexpectedly.
cout << "WEIRD SYSTEM CALL: " << syscall << endl;
child_fail(child, "Invalid system call.");
}
}
ptrace(PTRACE_CONT, child, 0, 0);
}
return 0;
}
int main(int argc, char** argv) {
pid_t child = fork();
if (child == 0) {
return do_child(argc-1, argv+1);
} else {
return do_trace(child, argv[1]);
}
}
<|endoftext|>
|
<commit_before>
#include "stdafx.h"
#include "Tese.h"
String^ TeseCpp::Tese::Serialize(Object^ obj)
{
array<Byte>^ bytes;
{
MemoryStream^ mem = gcnew MemoryStream();
Serialize(obj, mem);
bytes = mem->ToArray();
mem->Close();
}
return Encoding::UTF8->GetString(bytes);
}
generic <typename T>
T TeseCpp::Tese::Deserialize(Stream^ stream)
{
try {
JavaProperties^ props = gcnew JavaProperties();
props->Load(stream);
return (T)DeserializeFields(emptyPrefix, props, T::typeid);
} catch (IOException^ e) {
throw gcnew TeseReadException(e);
}
}
generic <typename T>
T TeseCpp::Tese::Deserialize(String^ text)
{
array<Byte>^ bytes = Encoding::UTF8->GetBytes(text);
{
MemoryStream^ mem = gcnew MemoryStream(bytes);
return Deserialize<T>(mem);
}
}
Object^ TeseCpp::Tese::DeserializeFields(String^ prefix, IDictionary^ props, Type^ type)
{
try {
Object^ obj = Activator::CreateInstance(type);
array<FieldInfo^>^ fields = type->GetFields(BindingFlags::NonPublic | BindingFlags::Instance);
for each (FieldInfo^ field in fields)
DeserializeField(prefix, obj, field, props);
return obj;
} catch (Exception^ e) {
throw gcnew TeseReadException(e);
}
}
Void TeseCpp::Tese::DeserializeField(String^ prefix, Object^ obj, FieldInfo^ field, IDictionary^ props)
{
try {
String^ key = field->Name;
String^ objKey = String::Format("{0}.{1}", prefix, key);
Object^ val = props[objKey];
if (val == nullptr) {
if (FindLongerKey(props, objKey)) {
field->SetValue(obj, DeserializeFields(objKey, props, field->FieldType));
}
return;
}
field->SetValue(obj, FromStr(val->ToString(), field));
} catch (Exception^ e) {
throw gcnew TeseReadException(e);
}
}
bool TeseCpp::Tese::FindLongerKey(IDictionary^ props, String^ shortKey)
{
for each (Object^ key in props->Keys)
if (key->ToString()->StartsWith(shortKey, StringComparison::InvariantCulture))
return true;
return false;
}
Object^ TeseCpp::Tese::FromStr(String^ val, FieldInfo^ field)
{
Type^ type = field->FieldType;
if (type->IsEnum)
return Enum::Parse(type, val);
CultureInfo^ cult = CultureInfo::InvariantCulture;
/*switch (type->Name) {
case "Boolean":
return Boolean.Parse(val);
case "Byte":
return Byte.Parse(val);
case "Char":
return Char.Parse(val);
case "Single":
return Single.Parse(val, cult);
case "Double":
return Double.Parse(val, cult);
case "Int32":
return Int32.Parse(val);
case "Int16":
return Int16.Parse(val);
case "Int64":
return Int64.Parse(val);
case "BigInteger":
return BigInteger.Parse(val, cult);
case "Decimal":
return decimal.Parse(val, cult);
case "DateTime":
return DateTime.Parse(val, cult).ToUniversalTime();
case "String":
return val;
default:
throw gcnew InvalidOperationException(type + " is not supported!");
}*/
throw gcnew InvalidOperationException(type + " is not supported!");
}
Void TeseCpp::Tese::Serialize(Object^ obj, Stream^ writer)
{
try {
JavaProperties^ props = gcnew JavaProperties();
SerializeFields(emptyPrefix, obj, props);
props->Store(writer, nullptr);
} catch (IOException^ e) {
throw gcnew TeseWriteException(e);
}
}
Void TeseCpp::Tese::SerializeFields(String^ prefix, Object^ obj, IDictionary^ props)
{
Type^ type = obj->GetType();
array<FieldInfo^>^ fields = type->GetFields(BindingFlags::NonPublic | BindingFlags::Instance);
for each (FieldInfo^ field in fields)
SerializeField(prefix, obj, field, props);
}
Void TeseCpp::Tese::SerializeField(String^ prefix, Object^ obj, FieldInfo^ field, IDictionary^ props)
{
try {
String^ key = field->Name;
Object^ val = field->GetValue(obj);
String^ objKey = String::Format("{0}.{1}", prefix, key);
try {
props[objKey] = ToStr(val, field);
} catch (InvalidOperationException^) {
SerializeFields(objKey, val, props);
}
} catch (Exception^ e) {
throw gcnew TeseWriteException(field, e);
}
}
String^ TeseCpp::Tese::ToStr(Object^ value, FieldInfo^ field)
{
Type^ type = field->FieldType;
if (type->IsEnum)
return value->ToString();
CultureInfo^ cult = CultureInfo::InvariantCulture;
String^ name = type->Name;
if (name->Equals("DateTime"))
return ((DateTime)value).ToString("yyyy-MM-dd'T'HH:mm:ss.fffzzz");
if (name->Equals("Single"))
return ((float)value).ToString(cult);
if (name->Equals("Double"))
return ((double)value).ToString(cult);
if (name->Equals("Decimal"))
return ((Decimal)value).ToString(cult);
if (Array::BinarySearch(gcnew array<String^> { "Boolean","BigInteger","Int64",
"Char","Int32","Byte","Int16","String" }, name) >= 0)
return value->ToString();
throw gcnew InvalidOperationException(type + " is not supported!");
}
<commit_msg>Implemented from string method<commit_after>
#include "stdafx.h"
#include "Tese.h"
String^ TeseCpp::Tese::Serialize(Object^ obj)
{
array<Byte>^ bytes;
{
MemoryStream^ mem = gcnew MemoryStream();
Serialize(obj, mem);
bytes = mem->ToArray();
mem->Close();
}
return Encoding::UTF8->GetString(bytes);
}
generic <typename T>
T TeseCpp::Tese::Deserialize(Stream^ stream)
{
try {
JavaProperties^ props = gcnew JavaProperties();
props->Load(stream);
return (T)DeserializeFields(emptyPrefix, props, T::typeid);
} catch (IOException^ e) {
throw gcnew TeseReadException(e);
}
}
generic <typename T>
T TeseCpp::Tese::Deserialize(String^ text)
{
array<Byte>^ bytes = Encoding::UTF8->GetBytes(text);
{
MemoryStream^ mem = gcnew MemoryStream(bytes);
return Deserialize<T>(mem);
}
}
Object^ TeseCpp::Tese::DeserializeFields(String^ prefix, IDictionary^ props, Type^ type)
{
try {
Object^ obj = Activator::CreateInstance(type);
array<FieldInfo^>^ fields = type->GetFields(BindingFlags::NonPublic | BindingFlags::Instance);
for each (FieldInfo^ field in fields)
DeserializeField(prefix, obj, field, props);
return obj;
} catch (Exception^ e) {
throw gcnew TeseReadException(e);
}
}
Void TeseCpp::Tese::DeserializeField(String^ prefix, Object^ obj, FieldInfo^ field, IDictionary^ props)
{
try {
String^ key = field->Name;
String^ objKey = String::Format("{0}.{1}", prefix, key);
Object^ val = props[objKey];
if (val == nullptr) {
if (FindLongerKey(props, objKey)) {
field->SetValue(obj, DeserializeFields(objKey, props, field->FieldType));
}
return;
}
field->SetValue(obj, FromStr(val->ToString(), field));
} catch (Exception^ e) {
throw gcnew TeseReadException(e);
}
}
bool TeseCpp::Tese::FindLongerKey(IDictionary^ props, String^ shortKey)
{
for each (Object^ key in props->Keys)
if (key->ToString()->StartsWith(shortKey, StringComparison::InvariantCulture))
return true;
return false;
}
Object^ TeseCpp::Tese::FromStr(String^ val, FieldInfo^ field)
{
Type^ type = field->FieldType;
if (type->IsEnum)
return Enum::Parse(type, val);
CultureInfo^ cult = CultureInfo::InvariantCulture;
String^ name = type->Name;
if (name->Equals("Boolean"))
return Boolean::Parse(val);
if (name->Equals("Byte"))
return Byte::Parse(val);
if (name->Equals("Char"))
return Char::Parse(val);
if (name->Equals("Single"))
return Single::Parse(val, cult);
if (name->Equals("Double"))
return Double::Parse(val, cult);
if (name->Equals("Int32"))
return Int32::Parse(val);
if (name->Equals("Int16"))
return Int16::Parse(val);
if (name->Equals("Int64"))
return Int64::Parse(val);
if (name->Equals("BigInteger"))
return BigInteger::Parse(val, cult);
if (name->Equals("Decimal"))
return Decimal::Parse(val, cult);
if (name->Equals("DateTime"))
return DateTime::Parse(val, cult).ToUniversalTime();
if (name->Equals("String"))
return val;
throw gcnew InvalidOperationException(type + " is not supported!");
}
Void TeseCpp::Tese::Serialize(Object^ obj, Stream^ writer)
{
try {
JavaProperties^ props = gcnew JavaProperties();
SerializeFields(emptyPrefix, obj, props);
props->Store(writer, nullptr);
} catch (IOException^ e) {
throw gcnew TeseWriteException(e);
}
}
Void TeseCpp::Tese::SerializeFields(String^ prefix, Object^ obj, IDictionary^ props)
{
Type^ type = obj->GetType();
array<FieldInfo^>^ fields = type->GetFields(BindingFlags::NonPublic | BindingFlags::Instance);
for each (FieldInfo^ field in fields)
SerializeField(prefix, obj, field, props);
}
Void TeseCpp::Tese::SerializeField(String^ prefix, Object^ obj, FieldInfo^ field, IDictionary^ props)
{
try {
String^ key = field->Name;
Object^ val = field->GetValue(obj);
String^ objKey = String::Format("{0}.{1}", prefix, key);
try {
props[objKey] = ToStr(val, field);
} catch (InvalidOperationException^) {
SerializeFields(objKey, val, props);
}
} catch (Exception^ e) {
throw gcnew TeseWriteException(field, e);
}
}
String^ TeseCpp::Tese::ToStr(Object^ value, FieldInfo^ field)
{
Type^ type = field->FieldType;
if (type->IsEnum)
return value->ToString();
CultureInfo^ cult = CultureInfo::InvariantCulture;
String^ name = type->Name;
if (name->Equals("DateTime"))
return ((DateTime)value).ToString("yyyy-MM-dd'T'HH:mm:ss.fffzzz");
if (name->Equals("Single"))
return ((float)value).ToString(cult);
if (name->Equals("Double"))
return ((double)value).ToString(cult);
if (name->Equals("Decimal"))
return ((Decimal)value).ToString(cult);
if (Array::BinarySearch(gcnew array<String^> { "Boolean","BigInteger","Int64",
"Char","Int32","Byte","Int16","String" }, name) >= 0)
return value->ToString();
throw gcnew InvalidOperationException(type + " is not supported!");
}
<|endoftext|>
|
<commit_before>#include <iostream>
#include <unordered_map>
#include <tuple>
#include <exception>
#include <vector>
namespace TM
{
enum SHIFT {
LEFT = -1,
RIGHT = 1,
HOLD = 0
};
bool operator==(const std::tuple<int, char> &a,
const std::tuple<int, char> &b)
{
return std::get<0>(a) == std::get<0>(b) &&
std::get<1>(a) == std::get<1>(b);
}
struct tuple_hash : public std::unary_function<std::tuple<int, char>,
std::size_t>
{
const int MOD = 666013;
std::size_t operator()(const std::tuple<int, char> &k) const
{
return (std::get<0>(k) + std::get<1>(k)) % MOD;
}
};
class MultipleValuesMappedToKey : public std::exception
{
private:
virtual const char *what() const throw()
{
return "Cannot map multiple values to a key in an unordered_map";
}
};
class KeyNotFound : public std::exception
{
private:
virtual const char *what() const throw()
{
return "Key not found. Maybe first test using contains?";
}
};
class TMTransition
{
public:
typedef std::tuple<int, char> key_type;
typedef std::tuple<int, char, SHIFT> value_type;
void emplace(const key_type &k, const value_type &v) throw()
{
if (delta_.count(k))
throw new MultipleValuesMappedToKey();
delta_.emplace(k, v);
}
value_type get(const key_type &k) const
{
if (!delta_.count(k))
throw new KeyNotFound();
return delta_.find(k)->second;
}
bool contains(const key_type &k) const
{
return delta_.count(k);
}
private:
std::unordered_map<key_type, value_type, tuple_hash> delta_;
};
class TMConfiguration
{
public:
TMConfiguration()
: statesNr_(0)
{
}
void addTransition(int state_in, char sym_in, int state_af,
char sym_af, SHIFT shift ) throw()
{
addTransition(std::make_tuple(state_in, sym_in),
std::make_tuple(state_af, sym_af, shift));
// Educated guess. May change in the future - machines with multiple
// final states.
if (statesNr_ < state_in || statesNr_ < state_af)
statesNr_ = std::max(state_af, state_in);
}
bool is_final(int state) const
{
return state >= statesNr_;
}
bool is_undefined(int state, char sym) const
{
return !delta_.contains(std::make_tuple(state, sym));
}
TMTransition::value_type getValue(int state, char sym) const
{
return delta_.get(std::make_tuple(state, sym));
}
private:
void addTransition(const TMTransition::key_type &k,
const TMTransition::value_type &v)
{
delta_.emplace(k, v);
}
TMTransition delta_;
int statesNr_;
};
class TMRuntime
{
public:
TMRuntime(const TMConfiguration &conf)
: conf_(conf)
{
}
std::string run(std::string tape) throw()
{
int tape_head = 1;
int current_state = 0;
while (!conf_.is_final(current_state)) {
#ifdef VERBOSE
print(current_state, tape_head, tape);
#endif
int curr_sym = static_cast<int>(tape[tape_head]);
TMTransition::value_type val = conf_.getValue(current_state,
curr_sym);
tape[tape_head] = std::get<1>(val);
tape_head += std::get<2>(val);
current_state = std::get<0>(val);
}
#ifdef VERBOSE
print(current_state, tape_head, tape);
#endif
return tape;
}
private:
void print(int current_state, int tape_head,
const std::string ¤t_tape)
{
std::string head_str(current_tape.size(), ' ');
head_str[tape_head] = '^';
if (conf_.is_final(current_state))
std::cout << "Final state: ";
else
std::cout << "Current State: ";
std::cout << current_state << std::endl;
std::cout << current_tape << std::endl;
std::cout << head_str;
std::cout << std::endl;
}
TMConfiguration conf_;
};
#define TEST_OUTPUT(testNr, expected, actual)\
{\
if (expected == actual)\
std::cout << "Test " << testNr << " succeded" << std::endl;\
else\
std::cout << "Test " << testNr << " failed: "\
<< "Expected: " << expected << "; "\
<< "Actual: " << actual << std::endl;\
}
namespace unittest
{
class UnitTest
{
public:
void runTest()
{
std::cout << "Running " << name() << std::endl;
init();
TMRuntime *tm_runtime = new TMRuntime(tmConf_);
auto inouts = getInOuts();
for (auto it = inouts.cbegin(); it != inouts.cend(); ++it)
TEST_OUTPUT(it - inouts.cbegin() + 1, it->second,
tm_runtime->run(it->first))
std::cout << std::endl;
delete tm_runtime;
}
protected:
TMConfiguration tmConf_;
private:
virtual const char *name() = 0;
virtual void init() = 0;
virtual std::vector<std::pair<std::string, std::string>> getInOuts() = 0;
};
}
}
using namespace TM;
class IncrementTest : public ::unittest::UnitTest
{
private:
const char *name() override
{
return "IncrementTest";
}
void init() override
{
tmConf_.addTransition(0, '0', 0, '0', RIGHT);
tmConf_.addTransition(0, '1', 0, '1', RIGHT);
tmConf_.addTransition(0, '#', 1, '#', LEFT);
tmConf_.addTransition(1, '0', 2, '1', LEFT);
tmConf_.addTransition(1, '1', 1, '0', LEFT);
tmConf_.addTransition(2, '0', 2, '0', LEFT);
tmConf_.addTransition(2, '1', 2, '1', LEFT);
tmConf_.addTransition(2, '>', 3, '>', HOLD);
}
std::vector<std::pair<std::string, std::string>> getInOuts() override
{
std::vector<std::pair<std::string, std::string>> ret;
ret.emplace_back(">0001#", ">0010#");
ret.emplace_back(">00010#", ">00011#");
return ret;
}
};
class PalindromeTest : public ::unittest::UnitTest
{
private:
const char *name() override
{
return "PalindromeTest";
}
void init() override
{
// TODO
}
std::vector<std::pair<std::string, std::string>> getInOuts() override
{
std::vector<std::pair<std::string, std::string>> ret;
// TODO
return ret;
}
};
// TODO
class MatrixTest : public ::unittest::UnitTest
{
const char *name() override
{
return "MatrixTest";
}
void init() override
{
// TODO
}
std::vector<std::pair<std::string, std::string>> getInOuts() override
{
std::vector<std::pair<std::string, std::string>> ret;
// TODO
return ret;
}
};
// TODO
class AnagramsTest : public ::unittest::UnitTest
{
const char *name() override
{
return "AnagramsTest";
}
void init() override
{
// TODO
}
std::vector<std::pair<std::string, std::string>> getInOuts() override
{
std::vector<std::pair<std::string, std::string>> ret;
// TODO
return ret;
}
};
// TODO
class CountZerosTest : public ::unittest::UnitTest
{
const char *name() override
{
return "CountZerosTest";
}
void init() override
{
// TODO
}
std::vector<std::pair<std::string, std::string>> getInOuts() override
{
std::vector<std::pair<std::string, std::string>> ret;
// TODO
return ret;
}
};
int main()
{
unittest::UnitTest *test1 = new IncrementTest();
unittest::UnitTest *test2 = new PalindromeTest();
unittest::UnitTest *test3 = new MatrixTest();
unittest::UnitTest *test4 = new AnagramsTest();
unittest::UnitTest *test5 = new CountZerosTest();
test1->runTest();
test2->runTest();
test3->runTest();
test4->runTest();
test5->runTest();
return 0;
}
<commit_msg>Add move constructors optimizations<commit_after>#include <iostream>
#include <unordered_map>
#include <tuple>
#include <exception>
#include <vector>
namespace TM
{
enum SHIFT {
LEFT = -1,
RIGHT = 1,
HOLD = 0
};
bool operator==(const std::tuple<int, char> &a,
const std::tuple<int, char> &b)
{
return std::get<0>(a) == std::get<0>(b) &&
std::get<1>(a) == std::get<1>(b);
}
struct tuple_hash : public std::unary_function<std::tuple<int, char>,
std::size_t>
{
const int MOD = 666013;
std::size_t operator()(const std::tuple<int, char> &k) const
{
return (std::get<0>(k) + std::get<1>(k)) % MOD;
}
};
class MultipleValuesMappedToKey : public std::exception
{
private:
virtual const char *what() const throw()
{
return "Cannot map multiple values to a key in an unordered_map";
}
};
class KeyNotFound : public std::exception
{
private:
virtual const char *what() const throw()
{
return "Key not found. Maybe first test using contains?";
}
};
class TMTransition
{
public:
typedef std::tuple<int, char> key_type;
typedef std::tuple<int, char, SHIFT> value_type;
void emplace(const key_type &k, const value_type &v) throw()
{
if (delta_.count(k))
throw new MultipleValuesMappedToKey();
delta_.emplace(k, v);
}
void emplace(key_type &&k, value_type &&v) throw()
{
if (delta_.count(k))
throw new MultipleValuesMappedToKey();
delta_.emplace(std::move(k), std::move(v));
}
value_type get(const key_type &k) const
{
if (!delta_.count(k))
throw new KeyNotFound();
return delta_.find(k)->second;
}
bool contains(const key_type &k) const
{
return delta_.count(k);
}
private:
std::unordered_map<key_type, value_type, tuple_hash> delta_;
};
class TMConfiguration
{
public:
TMConfiguration()
: statesNr_(0)
{
}
void addTransition(int state_in, char sym_in, int state_af,
char sym_af, SHIFT shift ) throw()
{
addTransition(std::make_tuple(state_in, sym_in),
std::make_tuple(state_af, sym_af, shift));
// Educated guess. May change in the future - machines with multiple
// final states.
if (statesNr_ < state_in || statesNr_ < state_af)
statesNr_ = std::max(state_af, state_in);
}
bool is_final(int state) const
{
return state >= statesNr_;
}
bool is_undefined(int state, char sym) const
{
return !delta_.contains(std::make_tuple(state, sym));
}
TMTransition::value_type getValue(int state, char sym) const
{
return delta_.get(std::make_tuple(state, sym));
}
private:
void addTransition(const TMTransition::key_type &k,
const TMTransition::value_type &v)
{
delta_.emplace(k, v);
}
void addTransition(TMTransition::key_type &&k,
TMTransition::value_type &&v)
{
delta_.emplace(std::move(k), std::move(v));
}
TMTransition delta_;
int statesNr_;
};
class TMRuntime
{
public:
TMRuntime(const TMConfiguration &conf)
: conf_(conf)
{
}
std::string run(std::string tape) throw()
{
int tape_head = 1;
int current_state = 0;
while (!conf_.is_final(current_state)) {
#ifdef VERBOSE
print(current_state, tape_head, tape);
#endif
int curr_sym = static_cast<int>(tape[tape_head]);
TMTransition::value_type val = conf_.getValue(current_state,
curr_sym);
tape[tape_head] = std::get<1>(val);
tape_head += std::get<2>(val);
current_state = std::get<0>(val);
}
#ifdef VERBOSE
print(current_state, tape_head, tape);
#endif
return tape;
}
private:
void print(int current_state, int tape_head,
const std::string ¤t_tape)
{
std::string head_str(current_tape.size(), ' ');
head_str[tape_head] = '^';
if (conf_.is_final(current_state))
std::cout << "Final state: ";
else
std::cout << "Current State: ";
std::cout << current_state << std::endl;
std::cout << current_tape << std::endl;
std::cout << head_str;
std::cout << std::endl;
}
TMConfiguration conf_;
};
#define TEST_OUTPUT(testNr, expected, actual)\
{\
if (expected == actual)\
std::cout << "Test " << testNr << " succeded" << std::endl;\
else\
std::cout << "Test " << testNr << " failed: "\
<< "Expected: " << expected << "; "\
<< "Actual: " << actual << std::endl;\
}
namespace unittest
{
class UnitTest
{
public:
void runTest()
{
std::cout << "Running " << name() << std::endl;
init();
TMRuntime *tm_runtime = new TMRuntime(tmConf_);
auto inouts = getInOuts();
for (auto it = inouts.cbegin(); it != inouts.cend(); ++it)
TEST_OUTPUT(it - inouts.cbegin() + 1, it->second,
tm_runtime->run(it->first))
std::cout << std::endl;
delete tm_runtime;
}
protected:
TMConfiguration tmConf_;
private:
virtual const char *name() = 0;
virtual void init() = 0;
virtual std::vector<std::pair<std::string, std::string>> getInOuts() = 0;
};
}
}
using namespace TM;
class IncrementTest : public ::unittest::UnitTest
{
private:
const char *name() override
{
return "IncrementTest";
}
void init() override
{
tmConf_.addTransition(0, '0', 0, '0', RIGHT);
tmConf_.addTransition(0, '1', 0, '1', RIGHT);
tmConf_.addTransition(0, '#', 1, '#', LEFT);
tmConf_.addTransition(1, '0', 2, '1', LEFT);
tmConf_.addTransition(1, '1', 1, '0', LEFT);
tmConf_.addTransition(2, '0', 2, '0', LEFT);
tmConf_.addTransition(2, '1', 2, '1', LEFT);
tmConf_.addTransition(2, '>', 3, '>', HOLD);
}
std::vector<std::pair<std::string, std::string>> getInOuts() override
{
std::vector<std::pair<std::string, std::string>> ret;
ret.emplace_back(">0001#", ">0010#");
ret.emplace_back(">00010#", ">00011#");
return ret;
}
};
class PalindromeTest : public ::unittest::UnitTest
{
private:
const char *name() override
{
return "PalindromeTest";
}
void init() override
{
// TODO
}
std::vector<std::pair<std::string, std::string>> getInOuts() override
{
std::vector<std::pair<std::string, std::string>> ret;
// TODO
return ret;
}
};
// TODO
class MatrixTest : public ::unittest::UnitTest
{
const char *name() override
{
return "MatrixTest";
}
void init() override
{
// TODO
}
std::vector<std::pair<std::string, std::string>> getInOuts() override
{
std::vector<std::pair<std::string, std::string>> ret;
// TODO
return ret;
}
};
// TODO
class AnagramsTest : public ::unittest::UnitTest
{
const char *name() override
{
return "AnagramsTest";
}
void init() override
{
// TODO
}
std::vector<std::pair<std::string, std::string>> getInOuts() override
{
std::vector<std::pair<std::string, std::string>> ret;
// TODO
return ret;
}
};
// TODO
class CountZerosTest : public ::unittest::UnitTest
{
const char *name() override
{
return "CountZerosTest";
}
void init() override
{
// TODO
}
std::vector<std::pair<std::string, std::string>> getInOuts() override
{
std::vector<std::pair<std::string, std::string>> ret;
// TODO
return ret;
}
};
int main()
{
unittest::UnitTest *test1 = new IncrementTest();
unittest::UnitTest *test2 = new PalindromeTest();
unittest::UnitTest *test3 = new MatrixTest();
unittest::UnitTest *test4 = new AnagramsTest();
unittest::UnitTest *test5 = new CountZerosTest();
test1->runTest();
test2->runTest();
test3->runTest();
test4->runTest();
test5->runTest();
return 0;
}
<|endoftext|>
|
<commit_before>/*************************************************************************
*
* $RCSfile: animobjs.hxx,v $
*
* $Revision: 1.5 $
*
* last change: $Author: obo $ $Date: 2004-01-20 11:47:42 $
*
* The Contents of this file are made available subject to the terms of
* either of the following licenses
*
* - GNU Lesser General Public License Version 2.1
* - Sun Industry Standards Source License Version 1.1
*
* Sun Microsystems Inc., October, 2000
*
* GNU Lesser General Public License Version 2.1
* =============================================
* Copyright 2000 by Sun Microsystems, Inc.
* 901 San Antonio Road, Palo Alto, CA 94303, USA
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License version 2.1, as published by the Free Software Foundation.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston,
* MA 02111-1307 USA
*
*
* Sun Industry Standards Source License Version 1.1
* =================================================
* The contents of this file are subject to the Sun Industry Standards
* Source License Version 1.1 (the "License"); You may not use this file
* except in compliance with the License. You may obtain a copy of the
* License at http://www.openoffice.org/license.html.
*
* Software provided under this License is provided on an "AS IS" basis,
* WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING,
* WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS,
* MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING.
* See the License for the specific provisions governing your rights and
* obligations concerning the Software.
*
* The Initial Developer of the Original Code is: Sun Microsystems, Inc.
*
* Copyright: 2000 by Sun Microsystems, Inc.
*
* All Rights Reserved.
*
* Contributor(s): _______________________________________
*
*
************************************************************************/
#ifndef SD_ANIMOBJS_HXX
#define SD_ANIMOBJS_HXX
#ifndef _SFXDOCKWIN_HXX //autogen
#include <sfx2/dockwin.hxx>
#endif
#ifndef _SV_FIXED_HXX //autogen
#include <vcl/fixed.hxx>
#endif
#ifndef _STDCTRL_HXX //autogen
#include <svtools/stdctrl.hxx>
#endif
#ifndef _SV_GROUP_HXX //autogen
#include <vcl/group.hxx>
#endif
#ifndef _SFXCTRLITEM_HXX //autogen
#include <sfx2/ctrlitem.hxx>
#endif
#ifndef _SV_BUTTON_HXX //autogen
#include <vcl/button.hxx>
#endif
#ifndef _SV_FIELD_HXX //autogen
#include <vcl/field.hxx>
#endif
#ifndef _SVX_DLG_CTRL_HXX //autogen
#include <svx/dlgctrl.hxx>
#endif
#ifndef _SFX_PROGRESS_HXX
#include <sfx2/progress.hxx>
#endif
#ifndef _SV_LSTBOX_HXX //autogen
#include <vcl/lstbox.hxx>
#endif
#ifndef _SD_SDRESID_HXX
#include "sdresid.hxx"
#endif
class SdDrawDocument;
class BitmapEx;
namespace sd {
class View;
//------------------------------------------------------------------------
enum BitmapAdjustment
{
BA_LEFT_UP,
BA_LEFT,
BA_LEFT_DOWN,
BA_UP,
BA_CENTER,
BA_DOWN,
BA_RIGHT_UP,
BA_RIGHT,
BA_RIGHT_DOWN
};
//------------------------------------------------------------------------
class SdDisplay : public Control
{
private:
BitmapEx aBitmapEx;
Fraction aScale;
public:
SdDisplay( ::Window* pWin, SdResId Id );
~SdDisplay();
virtual void Paint( const Rectangle& rRect );
void SetBitmapEx( BitmapEx* pBmpEx );
void SetScale( const Fraction& rFrac );
virtual void DataChanged( const DataChangedEvent& rDCEvt );
};
//------------------------------------------------------------------------
class AnimationWindow : public SfxDockingWindow
{
friend class AnimationChildWindow;
friend class AnimationControllerItem;
public:
AnimationWindow( SfxBindings* pBindings, SfxChildWindow *pCW,
::Window* pParent, const SdResId& rSdResId );
virtual ~AnimationWindow();
void AddObj( ::sd::View& rView );
void CreateAnimObj( ::sd::View& rView );
virtual void DataChanged( const DataChangedEvent& rDCEvt );
protected:
virtual BOOL Close();
virtual void Resize();
virtual void FillInfo( SfxChildWinInfo& ) const;
private:
SdDisplay aCtlDisplay;
ImageButton aBtnFirst;
ImageButton aBtnReverse;
ImageButton aBtnStop;
ImageButton aBtnPlay;
ImageButton aBtnLast;
NumericField aNumFldBitmap;
TimeField aTimeField;
ListBox aLbLoopCount;
ImageButton aBtnGetOneObject;
ImageButton aBtnGetAllObjects;
ImageButton aBtnRemoveBitmap;
ImageButton aBtnRemoveAll;
FixedText aFtCount;
FixedInfo aFiCount;
FixedLine aGrpBitmap;
RadioButton aRbtGroup;
RadioButton aRbtBitmap;
FixedText aFtAdjustment;
ListBox aLbAdjustment;
PushButton aBtnCreateGroup;
FixedLine aGrpAnimation;
::Window* pWin;
List aBmpExList;
List aTimeList;
SdDrawDocument* pMyDoc;
BitmapEx* pBitmapEx;
Size aSize;
Size aFltWinSize;
Size aDisplaySize;
Size aBmpSize;
BOOL bMovie;
BOOL bAllObjects;
SfxBindings* pBindings;
AnimationControllerItem* pControllerItem;
//------------------------------------
DECL_LINK( ClickFirstHdl, void * );
DECL_LINK( ClickStopHdl, void * );
DECL_LINK( ClickPlayHdl, void * );
DECL_LINK( ClickLastHdl, void * );
DECL_LINK( ClickGetObjectHdl, void * );
DECL_LINK( ClickRemoveBitmapHdl, void * );
DECL_LINK( ClickRbtHdl, void * );
DECL_LINK( ClickCreateGroupHdl, void * );
DECL_LINK( ModifyBitmapHdl, void * );
DECL_LINK( ModifyTimeHdl, void * );
void UpdateControl( ULONG nPos, BOOL bDisableCtrls = FALSE );
void ResetAttrs();
void WaitInEffect( ULONG nMilliSeconds ) const;
void WaitInEffect( ULONG nMilliSeconds, ULONG nTime,
SfxProgress* pStbMgr ) const;
Fraction GetScale();
};
/*************************************************************************
|*
|* ControllerItem fuer Animator
|*
\************************************************************************/
class AnimationControllerItem : public SfxControllerItem
{
public:
AnimationControllerItem( USHORT, AnimationWindow*, SfxBindings* );
protected:
virtual void StateChanged( USHORT nSId, SfxItemState eState,
const SfxPoolItem* pState );
private:
AnimationWindow* pAnimationWin;
};
} // end of namespace sd
#endif
<commit_msg>INTEGRATION: CWS gcc4fwdecl (1.5.480); FILE MERGED 2005/06/01 17:19:56 pmladek 1.5.480.1: #i50069# Fixed forward declarations for gcc4 in sd<commit_after>/*************************************************************************
*
* $RCSfile: animobjs.hxx,v $
*
* $Revision: 1.6 $
*
* last change: $Author: obo $ $Date: 2005-06-14 16:23:40 $
*
* The Contents of this file are made available subject to the terms of
* either of the following licenses
*
* - GNU Lesser General Public License Version 2.1
* - Sun Industry Standards Source License Version 1.1
*
* Sun Microsystems Inc., October, 2000
*
* GNU Lesser General Public License Version 2.1
* =============================================
* Copyright 2000 by Sun Microsystems, Inc.
* 901 San Antonio Road, Palo Alto, CA 94303, USA
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License version 2.1, as published by the Free Software Foundation.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston,
* MA 02111-1307 USA
*
*
* Sun Industry Standards Source License Version 1.1
* =================================================
* The contents of this file are subject to the Sun Industry Standards
* Source License Version 1.1 (the "License"); You may not use this file
* except in compliance with the License. You may obtain a copy of the
* License at http://www.openoffice.org/license.html.
*
* Software provided under this License is provided on an "AS IS" basis,
* WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING,
* WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS,
* MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING.
* See the License for the specific provisions governing your rights and
* obligations concerning the Software.
*
* The Initial Developer of the Original Code is: Sun Microsystems, Inc.
*
* Copyright: 2000 by Sun Microsystems, Inc.
*
* All Rights Reserved.
*
* Contributor(s): _______________________________________
*
*
************************************************************************/
#ifndef SD_ANIMOBJS_HXX
#define SD_ANIMOBJS_HXX
#ifndef _SFXDOCKWIN_HXX //autogen
#include <sfx2/dockwin.hxx>
#endif
#ifndef _SV_FIXED_HXX //autogen
#include <vcl/fixed.hxx>
#endif
#ifndef _STDCTRL_HXX //autogen
#include <svtools/stdctrl.hxx>
#endif
#ifndef _SV_GROUP_HXX //autogen
#include <vcl/group.hxx>
#endif
#ifndef _SFXCTRLITEM_HXX //autogen
#include <sfx2/ctrlitem.hxx>
#endif
#ifndef _SV_BUTTON_HXX //autogen
#include <vcl/button.hxx>
#endif
#ifndef _SV_FIELD_HXX //autogen
#include <vcl/field.hxx>
#endif
#ifndef _SVX_DLG_CTRL_HXX //autogen
#include <svx/dlgctrl.hxx>
#endif
#ifndef _SFX_PROGRESS_HXX
#include <sfx2/progress.hxx>
#endif
#ifndef _SV_LSTBOX_HXX //autogen
#include <vcl/lstbox.hxx>
#endif
#ifndef _SD_SDRESID_HXX
#include "sdresid.hxx"
#endif
class SdDrawDocument;
class BitmapEx;
namespace sd {
class AnimationControllerItem;
class View;
//------------------------------------------------------------------------
enum BitmapAdjustment
{
BA_LEFT_UP,
BA_LEFT,
BA_LEFT_DOWN,
BA_UP,
BA_CENTER,
BA_DOWN,
BA_RIGHT_UP,
BA_RIGHT,
BA_RIGHT_DOWN
};
//------------------------------------------------------------------------
class SdDisplay : public Control
{
private:
BitmapEx aBitmapEx;
Fraction aScale;
public:
SdDisplay( ::Window* pWin, SdResId Id );
~SdDisplay();
virtual void Paint( const Rectangle& rRect );
void SetBitmapEx( BitmapEx* pBmpEx );
void SetScale( const Fraction& rFrac );
virtual void DataChanged( const DataChangedEvent& rDCEvt );
};
//------------------------------------------------------------------------
class AnimationWindow : public SfxDockingWindow
{
friend class AnimationChildWindow;
friend class AnimationControllerItem;
public:
AnimationWindow( SfxBindings* pBindings, SfxChildWindow *pCW,
::Window* pParent, const SdResId& rSdResId );
virtual ~AnimationWindow();
void AddObj( ::sd::View& rView );
void CreateAnimObj( ::sd::View& rView );
virtual void DataChanged( const DataChangedEvent& rDCEvt );
protected:
virtual BOOL Close();
virtual void Resize();
virtual void FillInfo( SfxChildWinInfo& ) const;
private:
SdDisplay aCtlDisplay;
ImageButton aBtnFirst;
ImageButton aBtnReverse;
ImageButton aBtnStop;
ImageButton aBtnPlay;
ImageButton aBtnLast;
NumericField aNumFldBitmap;
TimeField aTimeField;
ListBox aLbLoopCount;
ImageButton aBtnGetOneObject;
ImageButton aBtnGetAllObjects;
ImageButton aBtnRemoveBitmap;
ImageButton aBtnRemoveAll;
FixedText aFtCount;
FixedInfo aFiCount;
FixedLine aGrpBitmap;
RadioButton aRbtGroup;
RadioButton aRbtBitmap;
FixedText aFtAdjustment;
ListBox aLbAdjustment;
PushButton aBtnCreateGroup;
FixedLine aGrpAnimation;
::Window* pWin;
List aBmpExList;
List aTimeList;
SdDrawDocument* pMyDoc;
BitmapEx* pBitmapEx;
Size aSize;
Size aFltWinSize;
Size aDisplaySize;
Size aBmpSize;
BOOL bMovie;
BOOL bAllObjects;
SfxBindings* pBindings;
AnimationControllerItem* pControllerItem;
//------------------------------------
DECL_LINK( ClickFirstHdl, void * );
DECL_LINK( ClickStopHdl, void * );
DECL_LINK( ClickPlayHdl, void * );
DECL_LINK( ClickLastHdl, void * );
DECL_LINK( ClickGetObjectHdl, void * );
DECL_LINK( ClickRemoveBitmapHdl, void * );
DECL_LINK( ClickRbtHdl, void * );
DECL_LINK( ClickCreateGroupHdl, void * );
DECL_LINK( ModifyBitmapHdl, void * );
DECL_LINK( ModifyTimeHdl, void * );
void UpdateControl( ULONG nPos, BOOL bDisableCtrls = FALSE );
void ResetAttrs();
void WaitInEffect( ULONG nMilliSeconds ) const;
void WaitInEffect( ULONG nMilliSeconds, ULONG nTime,
SfxProgress* pStbMgr ) const;
Fraction GetScale();
};
/*************************************************************************
|*
|* ControllerItem fuer Animator
|*
\************************************************************************/
class AnimationControllerItem : public SfxControllerItem
{
public:
AnimationControllerItem( USHORT, AnimationWindow*, SfxBindings* );
protected:
virtual void StateChanged( USHORT nSId, SfxItemState eState,
const SfxPoolItem* pState );
private:
AnimationWindow* pAnimationWin;
};
} // end of namespace sd
#endif
<|endoftext|>
|
<commit_before>/*************************************************************************
*
* $RCSfile: animobjs.hxx,v $
*
* $Revision: 1.6 $
*
* last change: $Author: obo $ $Date: 2005-06-14 16:23:40 $
*
* The Contents of this file are made available subject to the terms of
* either of the following licenses
*
* - GNU Lesser General Public License Version 2.1
* - Sun Industry Standards Source License Version 1.1
*
* Sun Microsystems Inc., October, 2000
*
* GNU Lesser General Public License Version 2.1
* =============================================
* Copyright 2000 by Sun Microsystems, Inc.
* 901 San Antonio Road, Palo Alto, CA 94303, USA
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License version 2.1, as published by the Free Software Foundation.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston,
* MA 02111-1307 USA
*
*
* Sun Industry Standards Source License Version 1.1
* =================================================
* The contents of this file are subject to the Sun Industry Standards
* Source License Version 1.1 (the "License"); You may not use this file
* except in compliance with the License. You may obtain a copy of the
* License at http://www.openoffice.org/license.html.
*
* Software provided under this License is provided on an "AS IS" basis,
* WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING,
* WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS,
* MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING.
* See the License for the specific provisions governing your rights and
* obligations concerning the Software.
*
* The Initial Developer of the Original Code is: Sun Microsystems, Inc.
*
* Copyright: 2000 by Sun Microsystems, Inc.
*
* All Rights Reserved.
*
* Contributor(s): _______________________________________
*
*
************************************************************************/
#ifndef SD_ANIMOBJS_HXX
#define SD_ANIMOBJS_HXX
#ifndef _SFXDOCKWIN_HXX //autogen
#include <sfx2/dockwin.hxx>
#endif
#ifndef _SV_FIXED_HXX //autogen
#include <vcl/fixed.hxx>
#endif
#ifndef _STDCTRL_HXX //autogen
#include <svtools/stdctrl.hxx>
#endif
#ifndef _SV_GROUP_HXX //autogen
#include <vcl/group.hxx>
#endif
#ifndef _SFXCTRLITEM_HXX //autogen
#include <sfx2/ctrlitem.hxx>
#endif
#ifndef _SV_BUTTON_HXX //autogen
#include <vcl/button.hxx>
#endif
#ifndef _SV_FIELD_HXX //autogen
#include <vcl/field.hxx>
#endif
#ifndef _SVX_DLG_CTRL_HXX //autogen
#include <svx/dlgctrl.hxx>
#endif
#ifndef _SFX_PROGRESS_HXX
#include <sfx2/progress.hxx>
#endif
#ifndef _SV_LSTBOX_HXX //autogen
#include <vcl/lstbox.hxx>
#endif
#ifndef _SD_SDRESID_HXX
#include "sdresid.hxx"
#endif
class SdDrawDocument;
class BitmapEx;
namespace sd {
class AnimationControllerItem;
class View;
//------------------------------------------------------------------------
enum BitmapAdjustment
{
BA_LEFT_UP,
BA_LEFT,
BA_LEFT_DOWN,
BA_UP,
BA_CENTER,
BA_DOWN,
BA_RIGHT_UP,
BA_RIGHT,
BA_RIGHT_DOWN
};
//------------------------------------------------------------------------
class SdDisplay : public Control
{
private:
BitmapEx aBitmapEx;
Fraction aScale;
public:
SdDisplay( ::Window* pWin, SdResId Id );
~SdDisplay();
virtual void Paint( const Rectangle& rRect );
void SetBitmapEx( BitmapEx* pBmpEx );
void SetScale( const Fraction& rFrac );
virtual void DataChanged( const DataChangedEvent& rDCEvt );
};
//------------------------------------------------------------------------
class AnimationWindow : public SfxDockingWindow
{
friend class AnimationChildWindow;
friend class AnimationControllerItem;
public:
AnimationWindow( SfxBindings* pBindings, SfxChildWindow *pCW,
::Window* pParent, const SdResId& rSdResId );
virtual ~AnimationWindow();
void AddObj( ::sd::View& rView );
void CreateAnimObj( ::sd::View& rView );
virtual void DataChanged( const DataChangedEvent& rDCEvt );
protected:
virtual BOOL Close();
virtual void Resize();
virtual void FillInfo( SfxChildWinInfo& ) const;
private:
SdDisplay aCtlDisplay;
ImageButton aBtnFirst;
ImageButton aBtnReverse;
ImageButton aBtnStop;
ImageButton aBtnPlay;
ImageButton aBtnLast;
NumericField aNumFldBitmap;
TimeField aTimeField;
ListBox aLbLoopCount;
ImageButton aBtnGetOneObject;
ImageButton aBtnGetAllObjects;
ImageButton aBtnRemoveBitmap;
ImageButton aBtnRemoveAll;
FixedText aFtCount;
FixedInfo aFiCount;
FixedLine aGrpBitmap;
RadioButton aRbtGroup;
RadioButton aRbtBitmap;
FixedText aFtAdjustment;
ListBox aLbAdjustment;
PushButton aBtnCreateGroup;
FixedLine aGrpAnimation;
::Window* pWin;
List aBmpExList;
List aTimeList;
SdDrawDocument* pMyDoc;
BitmapEx* pBitmapEx;
Size aSize;
Size aFltWinSize;
Size aDisplaySize;
Size aBmpSize;
BOOL bMovie;
BOOL bAllObjects;
SfxBindings* pBindings;
AnimationControllerItem* pControllerItem;
//------------------------------------
DECL_LINK( ClickFirstHdl, void * );
DECL_LINK( ClickStopHdl, void * );
DECL_LINK( ClickPlayHdl, void * );
DECL_LINK( ClickLastHdl, void * );
DECL_LINK( ClickGetObjectHdl, void * );
DECL_LINK( ClickRemoveBitmapHdl, void * );
DECL_LINK( ClickRbtHdl, void * );
DECL_LINK( ClickCreateGroupHdl, void * );
DECL_LINK( ModifyBitmapHdl, void * );
DECL_LINK( ModifyTimeHdl, void * );
void UpdateControl( ULONG nPos, BOOL bDisableCtrls = FALSE );
void ResetAttrs();
void WaitInEffect( ULONG nMilliSeconds ) const;
void WaitInEffect( ULONG nMilliSeconds, ULONG nTime,
SfxProgress* pStbMgr ) const;
Fraction GetScale();
};
/*************************************************************************
|*
|* ControllerItem fuer Animator
|*
\************************************************************************/
class AnimationControllerItem : public SfxControllerItem
{
public:
AnimationControllerItem( USHORT, AnimationWindow*, SfxBindings* );
protected:
virtual void StateChanged( USHORT nSId, SfxItemState eState,
const SfxPoolItem* pState );
private:
AnimationWindow* pAnimationWin;
};
} // end of namespace sd
#endif
<commit_msg>INTEGRATION: CWS ooo19126 (1.6.90); FILE MERGED 2005/09/05 13:22:54 rt 1.6.90.1: #i54170# Change license header: remove SISSL<commit_after>/*************************************************************************
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: animobjs.hxx,v $
*
* $Revision: 1.7 $
*
* last change: $Author: rt $ $Date: 2005-09-09 05:21:56 $
*
* The Contents of this file are made available subject to
* the terms of GNU Lesser General Public License Version 2.1.
*
*
* GNU Lesser General Public License Version 2.1
* =============================================
* Copyright 2005 by Sun Microsystems, Inc.
* 901 San Antonio Road, Palo Alto, CA 94303, USA
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License version 2.1, as published by the Free Software Foundation.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston,
* MA 02111-1307 USA
*
************************************************************************/
#ifndef SD_ANIMOBJS_HXX
#define SD_ANIMOBJS_HXX
#ifndef _SFXDOCKWIN_HXX //autogen
#include <sfx2/dockwin.hxx>
#endif
#ifndef _SV_FIXED_HXX //autogen
#include <vcl/fixed.hxx>
#endif
#ifndef _STDCTRL_HXX //autogen
#include <svtools/stdctrl.hxx>
#endif
#ifndef _SV_GROUP_HXX //autogen
#include <vcl/group.hxx>
#endif
#ifndef _SFXCTRLITEM_HXX //autogen
#include <sfx2/ctrlitem.hxx>
#endif
#ifndef _SV_BUTTON_HXX //autogen
#include <vcl/button.hxx>
#endif
#ifndef _SV_FIELD_HXX //autogen
#include <vcl/field.hxx>
#endif
#ifndef _SVX_DLG_CTRL_HXX //autogen
#include <svx/dlgctrl.hxx>
#endif
#ifndef _SFX_PROGRESS_HXX
#include <sfx2/progress.hxx>
#endif
#ifndef _SV_LSTBOX_HXX //autogen
#include <vcl/lstbox.hxx>
#endif
#ifndef _SD_SDRESID_HXX
#include "sdresid.hxx"
#endif
class SdDrawDocument;
class BitmapEx;
namespace sd {
class AnimationControllerItem;
class View;
//------------------------------------------------------------------------
enum BitmapAdjustment
{
BA_LEFT_UP,
BA_LEFT,
BA_LEFT_DOWN,
BA_UP,
BA_CENTER,
BA_DOWN,
BA_RIGHT_UP,
BA_RIGHT,
BA_RIGHT_DOWN
};
//------------------------------------------------------------------------
class SdDisplay : public Control
{
private:
BitmapEx aBitmapEx;
Fraction aScale;
public:
SdDisplay( ::Window* pWin, SdResId Id );
~SdDisplay();
virtual void Paint( const Rectangle& rRect );
void SetBitmapEx( BitmapEx* pBmpEx );
void SetScale( const Fraction& rFrac );
virtual void DataChanged( const DataChangedEvent& rDCEvt );
};
//------------------------------------------------------------------------
class AnimationWindow : public SfxDockingWindow
{
friend class AnimationChildWindow;
friend class AnimationControllerItem;
public:
AnimationWindow( SfxBindings* pBindings, SfxChildWindow *pCW,
::Window* pParent, const SdResId& rSdResId );
virtual ~AnimationWindow();
void AddObj( ::sd::View& rView );
void CreateAnimObj( ::sd::View& rView );
virtual void DataChanged( const DataChangedEvent& rDCEvt );
protected:
virtual BOOL Close();
virtual void Resize();
virtual void FillInfo( SfxChildWinInfo& ) const;
private:
SdDisplay aCtlDisplay;
ImageButton aBtnFirst;
ImageButton aBtnReverse;
ImageButton aBtnStop;
ImageButton aBtnPlay;
ImageButton aBtnLast;
NumericField aNumFldBitmap;
TimeField aTimeField;
ListBox aLbLoopCount;
ImageButton aBtnGetOneObject;
ImageButton aBtnGetAllObjects;
ImageButton aBtnRemoveBitmap;
ImageButton aBtnRemoveAll;
FixedText aFtCount;
FixedInfo aFiCount;
FixedLine aGrpBitmap;
RadioButton aRbtGroup;
RadioButton aRbtBitmap;
FixedText aFtAdjustment;
ListBox aLbAdjustment;
PushButton aBtnCreateGroup;
FixedLine aGrpAnimation;
::Window* pWin;
List aBmpExList;
List aTimeList;
SdDrawDocument* pMyDoc;
BitmapEx* pBitmapEx;
Size aSize;
Size aFltWinSize;
Size aDisplaySize;
Size aBmpSize;
BOOL bMovie;
BOOL bAllObjects;
SfxBindings* pBindings;
AnimationControllerItem* pControllerItem;
//------------------------------------
DECL_LINK( ClickFirstHdl, void * );
DECL_LINK( ClickStopHdl, void * );
DECL_LINK( ClickPlayHdl, void * );
DECL_LINK( ClickLastHdl, void * );
DECL_LINK( ClickGetObjectHdl, void * );
DECL_LINK( ClickRemoveBitmapHdl, void * );
DECL_LINK( ClickRbtHdl, void * );
DECL_LINK( ClickCreateGroupHdl, void * );
DECL_LINK( ModifyBitmapHdl, void * );
DECL_LINK( ModifyTimeHdl, void * );
void UpdateControl( ULONG nPos, BOOL bDisableCtrls = FALSE );
void ResetAttrs();
void WaitInEffect( ULONG nMilliSeconds ) const;
void WaitInEffect( ULONG nMilliSeconds, ULONG nTime,
SfxProgress* pStbMgr ) const;
Fraction GetScale();
};
/*************************************************************************
|*
|* ControllerItem fuer Animator
|*
\************************************************************************/
class AnimationControllerItem : public SfxControllerItem
{
public:
AnimationControllerItem( USHORT, AnimationWindow*, SfxBindings* );
protected:
virtual void StateChanged( USHORT nSId, SfxItemState eState,
const SfxPoolItem* pState );
private:
AnimationWindow* pAnimationWin;
};
} // end of namespace sd
#endif
<|endoftext|>
|
<commit_before>/// @file
/// @copyright The code is licensed under the BSD License
/// <http://opensource.org/licenses/BSD-2-Clause>,
/// Copyright (c) 2012-2015 Alexandre Hamez.
/// @author Alexandre Hamez
#pragma once
#include <functional> // reference_wrapper
#include <limits>
#include <numeric> // accumulate
#include <vector>
#include "sdd/order/order_builder.hh"
#include "sdd/order/strategies/force_hyperedge.hh"
#include "sdd/order/strategies/force_hypergraph.hh"
#include "sdd/order/strategies/force_vertex.hh"
namespace sdd { namespace force {
/*------------------------------------------------------------------------------------------------*/
/// @internal
/// @brief An implementation of the FORCE ordering strategy
/// @see https://web.eecs.umich.edu/~karem/papers/Aloul-GLSVLSI03.pdf
template <typename C>
class worker
{
private:
using id_type = typename C::Identifier;
using vertex_type = vertex<id_type>;
using hyperedge_type = hyperedge<id_type>;
/// @brief
std::deque<vertex_type>& vertices_;
/// @brief The hyperedges that link together vertices.
std::deque<hyperedge_type>& hyperedges_;
/// @brief Keep all computed total spans for statistics.
std::deque<double> spans_;
/// @brief Reverse order.
bool reverse_;
public:
/// @brief Constructor.
worker(hypergraph<C>& graph, bool reverse = false)
: vertices_(graph.vertices()), hyperedges_(graph.hyperedges()), spans_(), reverse_(reverse)
{}
/// @brief Effectively apply the FORCE ordering strategy.
order_builder<C>
operator()(unsigned int iterations = 200)
{
std::vector<std::reference_wrapper<vertex_type>>
sorted_vertices(vertices_.begin(), vertices_.end());
// Keep a copy of the order with the smallest span.
std::vector<std::reference_wrapper<vertex_type>> best_order(sorted_vertices);
double smallest_span = std::numeric_limits<double>::max();
while (iterations-- != 0)
{
// Compute the new center of gravity for every hyperedge.
for (auto& edge : hyperedges_)
{
edge.compute_center_of_gravity();
}
// Compute the tentative new location of every vertex.
for (auto& vertex : vertices_)
{
if (vertex.hyperedges().empty())
{
continue;
}
vertex.location() = std::accumulate( vertex.hyperedges().cbegin()
, vertex.hyperedges().cend()
, 0
, [](double acc, const hyperedge_type* e)
{return acc + e->center_of_gravity() * e->weight();}
) / vertex.hyperedges().size();
}
// Sort tentative vertex locations.
std::sort( sorted_vertices.begin(), sorted_vertices.end()
, [](vertex_type& lhs, vertex_type& rhs){return lhs.location() < rhs.location();});
// Assign integer indices to the vertices.
unsigned int pos = 0;
std::for_each( sorted_vertices.begin(), sorted_vertices.end()
, [&pos](vertex_type& v){v.location() = pos++;});
const double span = get_total_span();
spans_.push_back(span);
if (span < smallest_span)
{
// We keep the order that minimizes the span.
best_order = sorted_vertices;
}
}
order_builder<C> ob;
if (reverse_)
{
for (auto rcit = best_order.rbegin(); rcit != best_order.rend(); ++rcit)
{
ob.push(rcit->get().id());
}
}
else
{
for (const auto& vertex : best_order)
{
ob.push(vertex.get().id());
}
}
return ob;
}
const std::deque<double>&
spans()
const noexcept
{
return spans_;
}
private:
/// @brief Add the span of all hyperedges.
double
get_total_span()
const noexcept
{
return std::accumulate( hyperedges_.cbegin(), hyperedges_.cend(), 0
, [](double acc, const hyperedge_type& h){return acc + h.span();});
}
};
} // namespace force
/*------------------------------------------------------------------------------------------------*/
} // namespace sdd
<commit_msg>A better reference for FORCE: a fast and easy-to-implement variable-ordering heuristic<commit_after>/// @file
/// @copyright The code is licensed under the BSD License
/// <http://opensource.org/licenses/BSD-2-Clause>,
/// Copyright (c) 2012-2015 Alexandre Hamez.
/// @author Alexandre Hamez
#pragma once
#include <functional> // reference_wrapper
#include <limits>
#include <numeric> // accumulate
#include <vector>
#include "sdd/order/order_builder.hh"
#include "sdd/order/strategies/force_hyperedge.hh"
#include "sdd/order/strategies/force_hypergraph.hh"
#include "sdd/order/strategies/force_vertex.hh"
namespace sdd { namespace force {
/*------------------------------------------------------------------------------------------------*/
/// @internal
/// @brief An implementation of the FORCE ordering strategy
/// @see http://dx.doi.org/10.1145/764808.764839
template <typename C>
class worker
{
private:
using id_type = typename C::Identifier;
using vertex_type = vertex<id_type>;
using hyperedge_type = hyperedge<id_type>;
/// @brief
std::deque<vertex_type>& vertices_;
/// @brief The hyperedges that link together vertices.
std::deque<hyperedge_type>& hyperedges_;
/// @brief Keep all computed total spans for statistics.
std::deque<double> spans_;
/// @brief Reverse order.
bool reverse_;
public:
/// @brief Constructor.
worker(hypergraph<C>& graph, bool reverse = false)
: vertices_(graph.vertices()), hyperedges_(graph.hyperedges()), spans_(), reverse_(reverse)
{}
/// @brief Effectively apply the FORCE ordering strategy.
order_builder<C>
operator()(unsigned int iterations = 200)
{
std::vector<std::reference_wrapper<vertex_type>>
sorted_vertices(vertices_.begin(), vertices_.end());
// Keep a copy of the order with the smallest span.
std::vector<std::reference_wrapper<vertex_type>> best_order(sorted_vertices);
double smallest_span = std::numeric_limits<double>::max();
while (iterations-- != 0)
{
// Compute the new center of gravity for every hyperedge.
for (auto& edge : hyperedges_)
{
edge.compute_center_of_gravity();
}
// Compute the tentative new location of every vertex.
for (auto& vertex : vertices_)
{
if (vertex.hyperedges().empty())
{
continue;
}
vertex.location() = std::accumulate( vertex.hyperedges().cbegin()
, vertex.hyperedges().cend()
, 0
, [](double acc, const hyperedge_type* e)
{return acc + e->center_of_gravity() * e->weight();}
) / vertex.hyperedges().size();
}
// Sort tentative vertex locations.
std::sort( sorted_vertices.begin(), sorted_vertices.end()
, [](vertex_type& lhs, vertex_type& rhs){return lhs.location() < rhs.location();});
// Assign integer indices to the vertices.
unsigned int pos = 0;
std::for_each( sorted_vertices.begin(), sorted_vertices.end()
, [&pos](vertex_type& v){v.location() = pos++;});
const double span = get_total_span();
spans_.push_back(span);
if (span < smallest_span)
{
// We keep the order that minimizes the span.
best_order = sorted_vertices;
}
}
order_builder<C> ob;
if (reverse_)
{
for (auto rcit = best_order.rbegin(); rcit != best_order.rend(); ++rcit)
{
ob.push(rcit->get().id());
}
}
else
{
for (const auto& vertex : best_order)
{
ob.push(vertex.get().id());
}
}
return ob;
}
const std::deque<double>&
spans()
const noexcept
{
return spans_;
}
private:
/// @brief Add the span of all hyperedges.
double
get_total_span()
const noexcept
{
return std::accumulate( hyperedges_.cbegin(), hyperedges_.cend(), 0
, [](double acc, const hyperedge_type& h){return acc + h.span();});
}
};
} // namespace force
/*------------------------------------------------------------------------------------------------*/
} // namespace sdd
<|endoftext|>
|
<commit_before>/*
Copyright (c) 2011 Volker Krause <vkrause@kde.org>
This library is free software; you can redistribute it and/or modify it
under the terms of the GNU Library General Public License as published by
the Free Software Foundation; either version 2 of the License, or (at your
option) any later version.
This library is distributed in the hope that it will be useful, but WITHOUT
ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
FITNESS FOR A PARTICULAR PURPOSE. See the GNU Library General Public
License for more details.
You should have received a copy of the GNU Library General Public License
along with this library; see the file COPYING.LIB. If not, write to the
Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
02110-1301, USA.
*/
#include "storagejanitor.h"
#include "storage/datastore.h"
#include "storage/selectquerybuilder.h"
#include <akdebug.h>
#include <libs/protocol_p.h>
#include <libs/xdgbasedirs_p.h>
#include <QStringBuilder>
#include <QtDBus/QDBusConnection>
#include <QtSql/QSqlQuery>
#include <QtSql/QSqlError>
#include <boost/bind.hpp>
#include <algorithm>
#include <QtCore/QDir>
#include <QtCore/qdiriterator.h>
using namespace Akonadi;
StorageJanitorThread::StorageJanitorThread(QObject* parent): QThread(parent)
{
}
void StorageJanitorThread::run()
{
StorageJanitor* janitor = new StorageJanitor;
exec();
delete janitor;
}
StorageJanitor::StorageJanitor(QObject* parent) :
QObject(parent),
m_connection( QDBusConnection::connectToBus( QDBusConnection::SessionBus, QLatin1String(staticMetaObject.className()) ) )
{
DataStore::self();
m_connection.registerService( QLatin1String( AKONADI_DBUS_STORAGEJANITOR_SERVICE ) );
m_connection.registerObject( QLatin1String( AKONADI_DBUS_STORAGEJANITOR_PATH ), this, QDBusConnection::ExportScriptableSlots | QDBusConnection::ExportScriptableSignals );
}
StorageJanitor::~StorageJanitor()
{
m_connection.unregisterObject( QLatin1String( AKONADI_DBUS_STORAGEJANITOR_PATH ), QDBusConnection::UnregisterTree );
m_connection.unregisterService( QLatin1String( AKONADI_DBUS_STORAGEJANITOR_SERVICE ) );
m_connection.disconnectFromBus( m_connection.name() );
DataStore::self()->close();
}
void StorageJanitor::check()
{
inform( "Looking for collections not belonging to a valid resource..." );
findOrphanedCollections();
inform( "Checking collection tree consistency..." );
const Collection::List cols = Collection::retrieveAll();
std::for_each( cols.begin(), cols.end(), boost::bind( &StorageJanitor::checkPathToRoot, this, _1 ) );
inform( "Looking for items not belonging to a valid collection..." );
findOrphanedItems();
inform( "Looking for item parts not belonging to a valid item..." );
findOrphanedParts();
inform( "Looking for overlapping external parts..." );
findOverlappingParts();
inform( "Verifying external parts..." );
verifyExternalParts();
inform( "Looking for dirty objects..." );
findDirtyObjects();
/* TODO some ideas for further checks:
* the collection tree is non-cyclic
* content type constraints of collections are not violated
* find unused flags
* find unused mimetypes
* check for dead entries in relation tables
* check if part size matches file size
*/
inform( "Consistency check done." );
}
void StorageJanitor::findOrphanedCollections()
{
SelectQueryBuilder<Collection> qb;
qb.addJoin( QueryBuilder::LeftJoin, Resource::tableName(), Collection::resourceIdFullColumnName(), Resource::idFullColumnName() );
qb.addValueCondition( Resource::idFullColumnName(), Query::Is, QVariant() );
qb.exec();
const Collection::List orphans = qb.result();
if ( orphans.size() > 0 ) {
inform( QLatin1Literal( "Found " ) + QString::number( orphans.size() ) + QLatin1Literal( " orphan collections." ) );
// TODO: attach to lost+found resource
}
}
void StorageJanitor::checkPathToRoot(const Akonadi::Collection& col)
{
if ( col.parentId() == 0 )
return;
const Akonadi::Collection parent = col.parent();
if ( !parent.isValid() ) {
inform( QLatin1Literal( "Collection \"" ) + col.name() + QLatin1Literal( "\" (id: " ) + QString::number( col.id() )
+ QLatin1Literal( ") has no valid parent." ) );
// TODO fix that by attaching to a top-level lost+found folder
return;
}
if ( col.resourceId() != parent.resourceId() ) {
inform( QLatin1Literal( "Collection \"" ) + col.name() + QLatin1Literal( "\" (id: " ) + QString::number( col.id() )
+ QLatin1Literal( ") belongs to a different resource than its parent." ) );
// can/should we actually fix that?
}
checkPathToRoot( parent );
}
void StorageJanitor::findOrphanedItems()
{
SelectQueryBuilder<PimItem> qb;
qb.addJoin( QueryBuilder::LeftJoin, Collection::tableName(), PimItem::collectionIdFullColumnName(), Collection::idFullColumnName() );
qb.addValueCondition( Collection::idFullColumnName(), Query::Is, QVariant() );
qb.exec();
const PimItem::List orphans = qb.result();
if ( orphans.size() > 0 ) {
inform( QLatin1Literal( "Found " ) + QString::number( orphans.size() ) + QLatin1Literal( " orphan items." ) );
// TODO: attach to lost+found collection
}
}
void StorageJanitor::findOrphanedParts()
{
SelectQueryBuilder<Part> qb;
qb.addJoin( QueryBuilder::LeftJoin, PimItem::tableName(), Part::pimItemIdFullColumnName(), PimItem::idFullColumnName() );
qb.addValueCondition( PimItem::idFullColumnName(), Query::Is, QVariant() );
qb.exec();
const Part::List orphans = qb.result();
if ( orphans.size() > 0 ) {
inform( QLatin1Literal( "Found " ) + QString::number( orphans.size() ) + QLatin1Literal( " orphan items." ) );
// TODO: create lost+found items for those? delete?
}
}
void StorageJanitor::findOverlappingParts()
{
QueryBuilder qb( Part::tableName(), QueryBuilder::Select );
qb.addColumn( Part::dataColumn() );
qb.addColumn( QLatin1Literal("count(") + Part::idColumn() + QLatin1Literal(") as cnt") );
qb.addValueCondition( Part::externalColumn(), Query::Equals, true );
qb.addValueCondition( Part::dataColumn(), Query::IsNot, QVariant() );
qb.addGroupColumn( Part::dataColumn() );
qb.addValueCondition( QLatin1Literal("count(") + Part::idColumn() + QLatin1Literal(")"), Query::Greater, 1, QueryBuilder::HavingCondition );
qb.exec();
int count = 0;
while ( qb.query().next() ) {
++count;
inform( QLatin1Literal( "Found overlapping item: " ) + qb.query().value( 0 ).toString() );
// TODO: uh oh, this is bad, how do we recover from that?
}
if ( count > 0 )
inform( QLatin1Literal( "Found " ) + QString::number( count ) + QLatin1Literal( " overlapping parts - bad." ) );
}
void StorageJanitor::verifyExternalParts()
{
QSet<QString> existingFiles;
QSet<QString> usedFiles;
// list all files
const QString dataDir = XdgBaseDirs::saveDir( "data", QLatin1String( "akonadi/file_db_data" ) );
QDirIterator it( dataDir );
while ( it.hasNext() )
existingFiles.insert( it.next() );
existingFiles.remove( QLatin1String( "." ) );
existingFiles.remove( QLatin1String( ".." ) );
inform( QLatin1Literal( "Found " ) + QString::number( existingFiles.size() ) + QLatin1Literal( " external files." ) );
// list all parts from the db which claim to have an associated file
QueryBuilder qb( Part::tableName(), QueryBuilder::Select );
qb.addColumn( Part::dataColumn() );
qb.addValueCondition( Part::externalColumn(), Query::Equals, true );
qb.addValueCondition( Part::dataColumn(), Query::IsNot, QVariant() );
qb.exec();
while ( qb.query().next() ) {
const QString partPath = qb.query().value( 0 ).toString();
if ( existingFiles.contains( partPath ) ) {
usedFiles.insert( partPath );
} else {
inform( QLatin1Literal( "Missing external file: " ) + partPath );
// TODO: fix this, by clearing the data column?
}
}
inform( QLatin1Literal( "Found " ) + QString::number( usedFiles.size() ) + QLatin1Literal( " external parts." ) );
// see what's left
foreach ( const QString &file, existingFiles - usedFiles ) {
inform( QLatin1Literal( "Found unreferenced external file: " ) + file );
// TODO: delete file?
}
}
void StorageJanitor::findDirtyObjects()
{
SelectQueryBuilder<Collection> cqb;
cqb.setSubQueryMode( Query::Or);
cqb.addValueCondition( Collection::remoteIdColumn(), Query::Is, QVariant() );
cqb.addValueCondition( Collection::remoteIdColumn(), Query::Equals, QString() );
cqb.exec();
const Collection::List ridLessCols = cqb.result();
foreach ( const Collection &col, ridLessCols )
inform( QLatin1Literal( "Collection \"" ) + col.name() + QLatin1Literal( "\" (id: " ) + QString::number( col.id() )
+ QLatin1Literal( ") has no RID." ) );
inform( QLatin1Literal( "Found " ) + QString::number( ridLessCols.size() ) + QLatin1Literal( " collections without RID." ) );
SelectQueryBuilder<PimItem> iqb1;
iqb1.setSubQueryMode( Query::Or);
iqb1.addValueCondition( PimItem::remoteIdColumn(), Query::Is, QVariant() );
iqb1.addValueCondition( PimItem::remoteIdColumn(), Query::Equals, QString() );
iqb1.exec();
const PimItem::List ridLessItems = iqb1.result();
foreach ( const PimItem &item, ridLessItems )
inform( QLatin1Literal( "Item \"" ) + QString::number( item.id() ) + QLatin1Literal( "\" has no RID." ) );
inform( QLatin1Literal( "Found " ) + QString::number( ridLessItems.size() ) + QLatin1Literal( " items without RID." ) );
SelectQueryBuilder<PimItem> iqb2;
iqb2.addValueCondition( PimItem::dirtyColumn(), Query::Equals, true );
iqb2.addValueCondition( PimItem::remoteIdColumn(), Akonadi::Query::IsNot, QVariant() );
iqb2.exec();
const PimItem::List dirtyItems = iqb2.result();
foreach ( const PimItem &item, dirtyItems )
inform( QLatin1Literal( "Item \"" ) + QString::number( item.id() ) + QLatin1Literal( "\" has RID and is dirty." ) );
inform( QLatin1Literal( "Found " ) + QString::number( dirtyItems.size() ) + QLatin1Literal( " dirty items." ) );
}
void StorageJanitor::vacuum()
{
if ( DataStore::self()->database().driverName() == QLatin1String( "QMYSQL" ) ) {
inform( "vacuuming database, that'll take some time and require a lot of temporary disk space..." );
foreach ( const QString &table, Akonadi::allDatabaseTables() ) {
inform( QString::fromLatin1( "optimizing table %1..." ).arg( table ) );
const QString queryStr = QLatin1Literal( "OPTIMIZE TABLE " ) + table;
QSqlQuery q( DataStore::self()->database() );
if ( !q.exec( queryStr ) ) {
akError() << "failed to optimize table" << table << ":" << q.lastError().text();
}
}
inform( "vacuum done" );
} else {
inform( "Vacuum not supported for this database backend." );
}
}
void StorageJanitor::inform(const char* msg)
{
inform( QLatin1String(msg) );
}
void StorageJanitor::inform(const QString& msg)
{
akDebug() << msg;
emit information( msg );
}
<commit_msg>make akonadictl vacuum run with the PSQL backend<commit_after>/*
Copyright (c) 2011 Volker Krause <vkrause@kde.org>
This library is free software; you can redistribute it and/or modify it
under the terms of the GNU Library General Public License as published by
the Free Software Foundation; either version 2 of the License, or (at your
option) any later version.
This library is distributed in the hope that it will be useful, but WITHOUT
ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
FITNESS FOR A PARTICULAR PURPOSE. See the GNU Library General Public
License for more details.
You should have received a copy of the GNU Library General Public License
along with this library; see the file COPYING.LIB. If not, write to the
Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
02110-1301, USA.
*/
#include "storagejanitor.h"
#include "storage/datastore.h"
#include "storage/selectquerybuilder.h"
#include <akdebug.h>
#include <libs/protocol_p.h>
#include <libs/xdgbasedirs_p.h>
#include <QStringBuilder>
#include <QtDBus/QDBusConnection>
#include <QtSql/QSqlQuery>
#include <QtSql/QSqlError>
#include <boost/bind.hpp>
#include <algorithm>
#include <QtCore/QDir>
#include <QtCore/qdiriterator.h>
using namespace Akonadi;
StorageJanitorThread::StorageJanitorThread(QObject* parent): QThread(parent)
{
}
void StorageJanitorThread::run()
{
StorageJanitor* janitor = new StorageJanitor;
exec();
delete janitor;
}
StorageJanitor::StorageJanitor(QObject* parent) :
QObject(parent),
m_connection( QDBusConnection::connectToBus( QDBusConnection::SessionBus, QLatin1String(staticMetaObject.className()) ) )
{
DataStore::self();
m_connection.registerService( QLatin1String( AKONADI_DBUS_STORAGEJANITOR_SERVICE ) );
m_connection.registerObject( QLatin1String( AKONADI_DBUS_STORAGEJANITOR_PATH ), this, QDBusConnection::ExportScriptableSlots | QDBusConnection::ExportScriptableSignals );
}
StorageJanitor::~StorageJanitor()
{
m_connection.unregisterObject( QLatin1String( AKONADI_DBUS_STORAGEJANITOR_PATH ), QDBusConnection::UnregisterTree );
m_connection.unregisterService( QLatin1String( AKONADI_DBUS_STORAGEJANITOR_SERVICE ) );
m_connection.disconnectFromBus( m_connection.name() );
DataStore::self()->close();
}
void StorageJanitor::check()
{
inform( "Looking for collections not belonging to a valid resource..." );
findOrphanedCollections();
inform( "Checking collection tree consistency..." );
const Collection::List cols = Collection::retrieveAll();
std::for_each( cols.begin(), cols.end(), boost::bind( &StorageJanitor::checkPathToRoot, this, _1 ) );
inform( "Looking for items not belonging to a valid collection..." );
findOrphanedItems();
inform( "Looking for item parts not belonging to a valid item..." );
findOrphanedParts();
inform( "Looking for overlapping external parts..." );
findOverlappingParts();
inform( "Verifying external parts..." );
verifyExternalParts();
inform( "Looking for dirty objects..." );
findDirtyObjects();
/* TODO some ideas for further checks:
* the collection tree is non-cyclic
* content type constraints of collections are not violated
* find unused flags
* find unused mimetypes
* check for dead entries in relation tables
* check if part size matches file size
*/
inform( "Consistency check done." );
}
void StorageJanitor::findOrphanedCollections()
{
SelectQueryBuilder<Collection> qb;
qb.addJoin( QueryBuilder::LeftJoin, Resource::tableName(), Collection::resourceIdFullColumnName(), Resource::idFullColumnName() );
qb.addValueCondition( Resource::idFullColumnName(), Query::Is, QVariant() );
qb.exec();
const Collection::List orphans = qb.result();
if ( orphans.size() > 0 ) {
inform( QLatin1Literal( "Found " ) + QString::number( orphans.size() ) + QLatin1Literal( " orphan collections." ) );
// TODO: attach to lost+found resource
}
}
void StorageJanitor::checkPathToRoot(const Akonadi::Collection& col)
{
if ( col.parentId() == 0 )
return;
const Akonadi::Collection parent = col.parent();
if ( !parent.isValid() ) {
inform( QLatin1Literal( "Collection \"" ) + col.name() + QLatin1Literal( "\" (id: " ) + QString::number( col.id() )
+ QLatin1Literal( ") has no valid parent." ) );
// TODO fix that by attaching to a top-level lost+found folder
return;
}
if ( col.resourceId() != parent.resourceId() ) {
inform( QLatin1Literal( "Collection \"" ) + col.name() + QLatin1Literal( "\" (id: " ) + QString::number( col.id() )
+ QLatin1Literal( ") belongs to a different resource than its parent." ) );
// can/should we actually fix that?
}
checkPathToRoot( parent );
}
void StorageJanitor::findOrphanedItems()
{
SelectQueryBuilder<PimItem> qb;
qb.addJoin( QueryBuilder::LeftJoin, Collection::tableName(), PimItem::collectionIdFullColumnName(), Collection::idFullColumnName() );
qb.addValueCondition( Collection::idFullColumnName(), Query::Is, QVariant() );
qb.exec();
const PimItem::List orphans = qb.result();
if ( orphans.size() > 0 ) {
inform( QLatin1Literal( "Found " ) + QString::number( orphans.size() ) + QLatin1Literal( " orphan items." ) );
// TODO: attach to lost+found collection
}
}
void StorageJanitor::findOrphanedParts()
{
SelectQueryBuilder<Part> qb;
qb.addJoin( QueryBuilder::LeftJoin, PimItem::tableName(), Part::pimItemIdFullColumnName(), PimItem::idFullColumnName() );
qb.addValueCondition( PimItem::idFullColumnName(), Query::Is, QVariant() );
qb.exec();
const Part::List orphans = qb.result();
if ( orphans.size() > 0 ) {
inform( QLatin1Literal( "Found " ) + QString::number( orphans.size() ) + QLatin1Literal( " orphan items." ) );
// TODO: create lost+found items for those? delete?
}
}
void StorageJanitor::findOverlappingParts()
{
QueryBuilder qb( Part::tableName(), QueryBuilder::Select );
qb.addColumn( Part::dataColumn() );
qb.addColumn( QLatin1Literal("count(") + Part::idColumn() + QLatin1Literal(") as cnt") );
qb.addValueCondition( Part::externalColumn(), Query::Equals, true );
qb.addValueCondition( Part::dataColumn(), Query::IsNot, QVariant() );
qb.addGroupColumn( Part::dataColumn() );
qb.addValueCondition( QLatin1Literal("count(") + Part::idColumn() + QLatin1Literal(")"), Query::Greater, 1, QueryBuilder::HavingCondition );
qb.exec();
int count = 0;
while ( qb.query().next() ) {
++count;
inform( QLatin1Literal( "Found overlapping item: " ) + qb.query().value( 0 ).toString() );
// TODO: uh oh, this is bad, how do we recover from that?
}
if ( count > 0 )
inform( QLatin1Literal( "Found " ) + QString::number( count ) + QLatin1Literal( " overlapping parts - bad." ) );
}
void StorageJanitor::verifyExternalParts()
{
QSet<QString> existingFiles;
QSet<QString> usedFiles;
// list all files
const QString dataDir = XdgBaseDirs::saveDir( "data", QLatin1String( "akonadi/file_db_data" ) );
QDirIterator it( dataDir );
while ( it.hasNext() )
existingFiles.insert( it.next() );
existingFiles.remove( QLatin1String( "." ) );
existingFiles.remove( QLatin1String( ".." ) );
inform( QLatin1Literal( "Found " ) + QString::number( existingFiles.size() ) + QLatin1Literal( " external files." ) );
// list all parts from the db which claim to have an associated file
QueryBuilder qb( Part::tableName(), QueryBuilder::Select );
qb.addColumn( Part::dataColumn() );
qb.addValueCondition( Part::externalColumn(), Query::Equals, true );
qb.addValueCondition( Part::dataColumn(), Query::IsNot, QVariant() );
qb.exec();
while ( qb.query().next() ) {
const QString partPath = qb.query().value( 0 ).toString();
if ( existingFiles.contains( partPath ) ) {
usedFiles.insert( partPath );
} else {
inform( QLatin1Literal( "Missing external file: " ) + partPath );
// TODO: fix this, by clearing the data column?
}
}
inform( QLatin1Literal( "Found " ) + QString::number( usedFiles.size() ) + QLatin1Literal( " external parts." ) );
// see what's left
foreach ( const QString &file, existingFiles - usedFiles ) {
inform( QLatin1Literal( "Found unreferenced external file: " ) + file );
// TODO: delete file?
}
}
void StorageJanitor::findDirtyObjects()
{
SelectQueryBuilder<Collection> cqb;
cqb.setSubQueryMode( Query::Or);
cqb.addValueCondition( Collection::remoteIdColumn(), Query::Is, QVariant() );
cqb.addValueCondition( Collection::remoteIdColumn(), Query::Equals, QString() );
cqb.exec();
const Collection::List ridLessCols = cqb.result();
foreach ( const Collection &col, ridLessCols )
inform( QLatin1Literal( "Collection \"" ) + col.name() + QLatin1Literal( "\" (id: " ) + QString::number( col.id() )
+ QLatin1Literal( ") has no RID." ) );
inform( QLatin1Literal( "Found " ) + QString::number( ridLessCols.size() ) + QLatin1Literal( " collections without RID." ) );
SelectQueryBuilder<PimItem> iqb1;
iqb1.setSubQueryMode( Query::Or);
iqb1.addValueCondition( PimItem::remoteIdColumn(), Query::Is, QVariant() );
iqb1.addValueCondition( PimItem::remoteIdColumn(), Query::Equals, QString() );
iqb1.exec();
const PimItem::List ridLessItems = iqb1.result();
foreach ( const PimItem &item, ridLessItems )
inform( QLatin1Literal( "Item \"" ) + QString::number( item.id() ) + QLatin1Literal( "\" has no RID." ) );
inform( QLatin1Literal( "Found " ) + QString::number( ridLessItems.size() ) + QLatin1Literal( " items without RID." ) );
SelectQueryBuilder<PimItem> iqb2;
iqb2.addValueCondition( PimItem::dirtyColumn(), Query::Equals, true );
iqb2.addValueCondition( PimItem::remoteIdColumn(), Akonadi::Query::IsNot, QVariant() );
iqb2.exec();
const PimItem::List dirtyItems = iqb2.result();
foreach ( const PimItem &item, dirtyItems )
inform( QLatin1Literal( "Item \"" ) + QString::number( item.id() ) + QLatin1Literal( "\" has RID and is dirty." ) );
inform( QLatin1Literal( "Found " ) + QString::number( dirtyItems.size() ) + QLatin1Literal( " dirty items." ) );
}
void StorageJanitor::vacuum()
{
const QString driverName = DataStore::self()->database().driverName();
if( ( driverName == QLatin1String( "QMYSQL" ) ) || ( driverName == QLatin1String( "QPSQL" ) ) ) {
inform( "vacuuming database, that'll take some time and require a lot of temporary disk space..." );
foreach ( const QString &table, Akonadi::allDatabaseTables() ) {
inform( QString::fromLatin1( "optimizing table %1..." ).arg( table ) );
QString queryStr;
if ( driverName == QLatin1String( "QMYSQL" ) ) {
queryStr = QLatin1Literal( "OPTIMIZE TABLE " ) + table;
} else {
queryStr = QLatin1Literal( "VACUUM FULL ANALYZE " ) + table;
}
QSqlQuery q( DataStore::self()->database() );
if ( !q.exec( queryStr ) ) {
akError() << "failed to optimize table" << table << ":" << q.lastError().text();
}
}
inform( "vacuum done" );
} else {
inform( "Vacuum not supported for this database backend." );
}
}
void StorageJanitor::inform(const char* msg)
{
inform( QLatin1String(msg) );
}
void StorageJanitor::inform(const QString& msg)
{
akDebug() << msg;
emit information( msg );
}
<|endoftext|>
|
<commit_before>#include "mainwindow.h"
#include "paramwindows.h"
#include "ui_mainwindow.h"
#include <QMessageBox>
#include <QDialog>
#include "windowstatistics.h"
#include "windowserveur.h"
#include "launchsologame.h"
#include "widgetchat.h"
MainWindow::MainWindow(QWidget *parent) :
QMainWindow(parent),
ui(new Ui::MainWindow)
{
ui->setupUi(this);
// Maximize the window
showMaximized();
//Show welcome message
ui->statusBar->showMessage("Bienvenue sur BOMBERMAN.", 15000);
// Linking buttons to action triggered
connect(ui->actionDemarrerPartieSolo,SIGNAL(triggered()),this,SLOT(BeginPartySolo()));
connect(ui->actionDemarrerPartieMulti,SIGNAL(triggered()),this,SLOT(BeginPartyMulti()));
connect(ui->actionChargerPartieSolo,SIGNAL(triggered()),this,SLOT(LoadPartySolo()));
connect(ui->actionChargerPartieMulti,SIGNAL(triggered()),this,SLOT(LoadPartyMulti()));
connect(ui->actionSauvegarderPartieSolo,SIGNAL(triggered()),this,SLOT(SavePartySolo()));
connect(ui->actionQuitter,SIGNAL(triggered()),this,SLOT(Quit()));
connect(ui->actionCommandes_de_jeu,SIGNAL(triggered()),this,SLOT(GameControls()));
connect(ui->actionAffichage,SIGNAL(triggered()),this,SLOT(DisplaySetting()));
connect(ui->actionAudio,SIGNAL(triggered()),this,SLOT(AudioSetting()));
connect(ui->actionAide,SIGNAL(triggered()),this,SLOT(Help()));
connect(ui->actionA_propos,SIGNAL(triggered()),this,SLOT(Credits()));
connect(ui->actionAffichageStatistics,SIGNAL(triggered()),this,SLOT(Statistics()));
}
MainWindow::~MainWindow()
{
delete ui;
}
void MainWindow::BeginPartySolo()
{
/*QMessageBox msg;
msg.setText("Vous venez de lancer une partie solo.");
msg.exec();*/
LaunchSoloGame* formsologame = new LaunchSoloGame(this);
formsologame->show();
}
void MainWindow::BeginPartyMulti()
{
windowserveur* windowServer;
windowServer = new windowserveur(this);
windowServer->exec();
//Test du module chat
//Ajout du widgetChat
QList<QString> *listJoueur = new QList<QString>();
listJoueur->insert(0,"toto");
widgetChat *Chat = new widgetChat(this,listJoueur);
Chat->setGeometry(10,40,590,500);
Chat->show();
}
void MainWindow::LoadPartySolo()
{
// Ouverture du dossier parent de la solution et filtre sur les fichiers de type texte pour sélection fichier à ouvrir
QString fichier = QFileDialog::getOpenFileName(this, "Ouvrir un fichier", QString(), "Fichiers texte (*.txt)");
// Message d'information provisoire indiquant le chemin d'accès au fichier à ouvrir
QMessageBox::information(this, "Fichier", "Vous avez ouvert le fichier :\n" + fichier);
// on déclare la variable de type fichier, puis on l'ouvre en mode "lecture seule"
QFile fichierACharger(fichier);
fichierACharger.open(QIODevice::ReadOnly | QIODevice::Text);
QTextStream flux (&fichierACharger);
QString ligne;
// On parcours ensuite le fichier ligne par ligne en y appliquant un traitement : ici affichage d'une messageBox
while(! flux.atEnd())
{
ligne = flux.readLine();
QMessageBox msg;
msg.setText(ligne);
msg.exec();
}
}
void MainWindow::LoadPartyMulti()
{
QMessageBox msg;
msg.setText("Vous venez de charger une partie multi.");
msg.exec();
}
void MainWindow::SavePartySolo()
{
// On ouvre une boite de dialogue permettant la sauvegarde d'un fichier
QString fichier = QFileDialog::getSaveFileName(this, "Enregistrer un fichier", QString("*.txt"), "Fichiers texte (*.txt);; Tous les fichiers (*.*)");
// Message d'information provisoire indiquant le chemin d'accès du fichier créé
QMessageBox::information(this, "Fichier", "Vous avez sauvegardé le fichier :\n" + fichier);
}
void MainWindow::Quit()
{
if (QMessageBox::Yes == QMessageBox(QMessageBox::Warning, "Confirmation de sortie.", "Êtes-vous sûr de vouloir quitter BomberMan ?", QMessageBox::Yes|QMessageBox::No).exec())
{
exit(true);
}
}
void MainWindow::GameControls()
{
ParamWindows* paramForm;
paramForm = new ParamWindows(this, 2);
paramForm->show();
}
void MainWindow::DisplaySetting()
{
ParamWindows* paramForm;
paramForm = new ParamWindows(this, 1);
paramForm->show();
}
void MainWindow::AudioSetting()
{
ParamWindows* paramForm;
paramForm = new ParamWindows(this, 0);
paramForm->show();
}
void MainWindow::Help()
{
QString texte;
QFile fichier("../Bomberman/Help.txt"); // Modification du chemin d'accès en chemin relatif
if(fichier.open(QIODevice::ReadOnly | QIODevice::Text))
{
texte = fichier.readAll();
QMessageBox msgHelp;
msgHelp.setGeometry(10,100,400,200);
msgHelp.information(this, "Fichier d'aide : ", texte);
fichier.close();
}
else
{
// Tu veux du commentaire ! je vais t'en mettre ...
// Modifié par Yann le 26 février 2014 car cela ne fonctionnait pas !!!!
// Banzai !!!!!!!!!
QMessageBox msg; //déclaration d'une variable msg de type QMessageBox
msg.setText("Impossible d'ouvrir le fichier !"); // Modification de la variable avec du texte !
msg.exec(); // Affichage de la QMessageBox pour le mec qui a besoin d'aide ;-)
// Fin du commentaire par Yann
}
}
void MainWindow::Credits()
{
/*QMessageBox msg;
msg.setText("Vous venez d'ouvrir les configurations audio.");
msg.exec();*/
QMessageBox::about(this, tr("BomberMAN"),
tr("The <b>BomberMAN</b> is a strategic, maze-based video game franchise originally developed by Hudson Soft. The original game was published in 1983 and new games have been published at irregular intervals ever since. Several titles in the 2000s were published by fellow Japanese game company Konami, who gained full control of the franchise when they purchased and absorbed Hudson in 2012. Today, Bomberman has featured in over 70 different games on numerous platforms (including all Nintendo platforms save for the 3DS and Wii U), as well as several anime and manga.His franchise is one of the most commercially successful of all time. <br><b>Realised by the Dream-Team : </b></br> <br>Petra Kratochvilova</br> <br>Thibaud Cutullic</br><br>Yoann Solacroup</br><br>Yann Damon</br><br>Gregoire Quincy</br><br>Roman Logvinov</br><br>Damien Moro</br>"));
}
void MainWindow::Statistics()
{
windowstatistics* Stats;
Stats = new windowstatistics(this);
Stats->setGeometry(50,100,490,190);
Stats->exec();
}
<commit_msg>Status Bar<commit_after>#include "mainwindow.h"
#include "paramwindows.h"
#include "ui_mainwindow.h"
#include <QMessageBox>
#include <QDialog>
#include "windowstatistics.h"
#include "windowserveur.h"
#include "launchsologame.h"
#include "widgetchat.h"
MainWindow::MainWindow(QWidget *parent) :
QMainWindow(parent),
ui(new Ui::MainWindow)
{
ui->setupUi(this);
// Maximize the window
showMaximized();
//Show welcome message
ui->statusBar->showMessage("Bienvenue sur BOMBERMAN.", 15000);
// Linking buttons to action triggered
connect(ui->actionDemarrerPartieSolo,SIGNAL(triggered()),this,SLOT(BeginPartySolo()));
connect(ui->actionDemarrerPartieMulti,SIGNAL(triggered()),this,SLOT(BeginPartyMulti()));
connect(ui->actionChargerPartieSolo,SIGNAL(triggered()),this,SLOT(LoadPartySolo()));
connect(ui->actionChargerPartieMulti,SIGNAL(triggered()),this,SLOT(LoadPartyMulti()));
connect(ui->actionSauvegarderPartieSolo,SIGNAL(triggered()),this,SLOT(SavePartySolo()));
connect(ui->actionQuitter,SIGNAL(triggered()),this,SLOT(Quit()));
connect(ui->actionCommandes_de_jeu,SIGNAL(triggered()),this,SLOT(GameControls()));
connect(ui->actionAffichage,SIGNAL(triggered()),this,SLOT(DisplaySetting()));
connect(ui->actionAudio,SIGNAL(triggered()),this,SLOT(AudioSetting()));
connect(ui->actionAide,SIGNAL(triggered()),this,SLOT(Help()));
connect(ui->actionA_propos,SIGNAL(triggered()),this,SLOT(Credits()));
connect(ui->actionAffichageStatistics,SIGNAL(triggered()),this,SLOT(Statistics()));
}
MainWindow::~MainWindow()
{
delete ui;
}
void MainWindow::BeginPartySolo()
{
/*QMessageBox msg;
msg.setText("Vous venez de lancer une partie solo.");
msg.exec();*/
LaunchSoloGame* formsologame = new LaunchSoloGame(this);
formsologame->show();
ui->statusBar->showMessage("Lancez une nouvelle partie solo.", 15000);
}
void MainWindow::BeginPartyMulti()
{
windowserveur* windowServer;
windowServer = new windowserveur(this);
windowServer->exec();
//Test du module chat
//Ajout du widgetChat
QList<QString> *listJoueur = new QList<QString>();
listJoueur->insert(0,"toto");
widgetChat *Chat = new widgetChat(this,listJoueur);
Chat->setGeometry(10,40,590,500);
Chat->show();
<<<<<<< HEAD
=======
ui->statusBar->showMessage("Vous avez lancé la partie multijoueur.", 15000);
>>>>>>> master
}
void MainWindow::LoadPartySolo()
{
// Ouverture du dossier parent de la solution et filtre sur les fichiers de type texte pour sélection fichier à ouvrir
QString fichier = QFileDialog::getOpenFileName(this, "Ouvrir un fichier", QString(), "Fichiers texte (*.txt)");
// Message d'information provisoire indiquant le chemin d'accès au fichier à ouvrir
QMessageBox::information(this, "Fichier", "Vous avez ouvert le fichier :\n" + fichier);
// on déclare la variable de type fichier, puis on l'ouvre en mode "lecture seule"
QFile fichierACharger(fichier);
fichierACharger.open(QIODevice::ReadOnly | QIODevice::Text);
QTextStream flux (&fichierACharger);
QString ligne;
// On parcours ensuite le fichier ligne par ligne en y appliquant un traitement : ici affichage d'une messageBox
while(! flux.atEnd())
{
ligne = flux.readLine();
QMessageBox msg;
msg.setText(ligne);
msg.exec();
}
}
void MainWindow::LoadPartyMulti()
{
QMessageBox msg;
msg.setText("Vous venez de charger une partie multi.");
msg.exec();
ui->statusBar->showMessage("Vous avez chargé une partie multijoueur.", 15000);
}
void MainWindow::SavePartySolo()
{
// On ouvre une boite de dialogue permettant la sauvegarde d'un fichier
QString fichier = QFileDialog::getSaveFileName(this, "Enregistrer un fichier", QString("*.txt"), "Fichiers texte (*.txt);; Tous les fichiers (*.*)");
// Message d'information provisoire indiquant le chemin d'accès du fichier créé
QMessageBox::information(this, "Fichier", "Vous avez sauvegardé le fichier :\n" + fichier);
ui->statusBar->showMessage("Vous avez sauvegardé la partie solo.", 15000);
}
void MainWindow::Quit()
{
if (QMessageBox::Yes == QMessageBox(QMessageBox::Warning, "Confirmation de sortie.", "Êtes-vous sûr de vouloir quitter BomberMan ?", QMessageBox::Yes|QMessageBox::No).exec())
{
exit(true);
}
}
void MainWindow::GameControls()
{
ParamWindows* paramForm;
paramForm = new ParamWindows(this, 2);
paramForm->show();
}
void MainWindow::DisplaySetting()
{
ParamWindows* paramForm;
paramForm = new ParamWindows(this, 1);
paramForm->show();
}
void MainWindow::AudioSetting()
{
ParamWindows* paramForm;
paramForm = new ParamWindows(this, 0);
paramForm->show();
}
void MainWindow::Help()
{
QString texte;
<<<<<<< HEAD
QFile fichier("../Bomberman/Help.txt"); // Modification du chemin d'accès en chemin relatif
=======
QFile fichier("C:/Users/Petulka/Bomberman/Bomberman/Help.txt");
>>>>>>> master
if(fichier.open(QIODevice::ReadOnly | QIODevice::Text))
{
texte = fichier.readAll();
QMessageBox msgHelp;
msgHelp.setGeometry(10,100,400,200);
msgHelp.information(this, "Fichier d'aide : ", texte);
fichier.close();
ui->statusBar->showMessage("Vous venez de fermer le fichier d'Aide.", 15000);
}
else
{
// Tu veux du commentaire ! je vais t'en mettre ...
// Modifié par Yann le 26 février 2014 car cela ne fonctionnait pas !!!!
// Banzai !!!!!!!!!
QMessageBox msg; //déclaration d'une variable msg de type QMessageBox
msg.setText("Impossible d'ouvrir le fichier !"); // Modification de la variable avec du texte !
msg.exec(); // Affichage de la QMessageBox pour le mec qui a besoin d'aide ;-)
// Fin du commentaire par Yann
}
}
void MainWindow::Credits()
{
/*QMessageBox msg;
msg.setText("Vous venez d'ouvrir les configurations audio.");
msg.exec();*/
QMessageBox::about(this, tr("BomberMAN"),
tr("The <b>BomberMAN</b> is a strategic, maze-based video game franchise originally developed by Hudson Soft. The original game was published in 1983 and new games have been published at irregular intervals ever since. Several titles in the 2000s were published by fellow Japanese game company Konami, who gained full control of the franchise when they purchased and absorbed Hudson in 2012. Today, Bomberman has featured in over 70 different games on numerous platforms (including all Nintendo platforms save for the 3DS and Wii U), as well as several anime and manga.His franchise is one of the most commercially successful of all time. <br><b>Realised by the Dream-Team : </b></br> <br>Petra Kratochvilova</br> <br>Thibaud Cutullic</br><br>Yoann Solacroup</br><br>Yann Damon</br><br>Gregoire Quincy</br><br>Roman Logvinov</br><br>Damien Moro</br>"));
}
void MainWindow::Statistics()
{
windowstatistics* Stats;
Stats = new windowstatistics(this);
Stats->setGeometry(50,100,490,190);
Stats->exec();
ui->statusBar->showMessage("Vous avez consulté les statistics.", 15000);
}
<|endoftext|>
|
<commit_before>#include "vmas.h"
#include "debug.h"
#include <stdlib.h>
#include <string.h>
VMAddrSpace::VMAddrSpace() {
stack = NULL;
code = NULL;
data = NULL;
stacksize = DEFAULT_STACKSIZE;
codesize = DEFAULT_CODESIZE;
datasize = DEFAULT_DATASIZE;
allocate();
return;
}
VMAddrSpace::VMAddrSpace(uint32_t ss, uint32_t cs, uint32_t ds) {
stack = NULL;
code = NULL;
data = NULL;
stacksize = ss;
codesize = cs;
datasize = ds;
allocate();
return;
}
VMAddrSpace::~VMAddrSpace() {
if (stack) {
delete[] stack;
}
if (code) {
delete[] code;
}
if (data) {
delete[] data;
}
return;
}
bool VMAddrSpace::allocate(void) {
DBG_INFO(("Allocating sections...\n"));
DBG_INFO(("\tcode...\n"));
code = new uint8_t[codesize];
DBG_INFO(("\tdata...\n"));
data = new uint8_t[datasize];
DBG_INFO(("\tstack...\n"));
stack = new uint8_t[stacksize];
if (code == NULL) {
DBG_ERROR(("Couldn't allocate code section.\n"));
return false;
}
if (data == NULL) {
DBG_ERROR(("Couldn't allocate data section.\n"));
return false;
}
if (stack == NULL) {
DBG_ERROR(("Couldn't allocate stack section.\n"));
return false;
}
memset(code, 0x0, codesize);
memset(stack, 0x0, stacksize);
memset(data, 0x0, datasize);
DBG_SUCC(("Done!\n"));
return true;
}
bool VMAddrSpace::insCode(uint8_t *buf, uint32_t size) {
if (code) {
DBG_INFO(("Copying buffer into code section.\n"));
memcpy(code, buf, size);
} else {
DBG_ERROR(("Couldn't write into code section.\n"));
return false;
}
return true;
}
bool VMAddrSpace::insStack(uint8_t *buf, uint32_t size) {
if (stack) {
DBG_INFO(("Copying buffer into stack section.\n"));
memcpy(stack, buf, size);
} else {
DBG_ERROR(("Couldn't write into stack section.\n"));
return false;
}
return true;
}
bool VMAddrSpace::insData(uint8_t *buf, uint32_t size) {
if (this->code) {
DBG_INFO(("Copying buffer into data section.\n"));
memcpy(data, buf, size);
} else {
DBG_ERROR(("Couldn't write into data section.\n"));
return false;
}
return true;
}
uint32_t VMAddrSpace::getStacksize() const {
return stacksize;
}
uint32_t VMAddrSpace::getCodesize() const {
return codesize;
}
uint32_t VMAddrSpace::getDatasize() const {
return datasize;
}
<commit_msg>Injected data/stack/code size check<commit_after>#include "vmas.h"
#include "debug.h"
#include <stdlib.h>
#include <string.h>
VMAddrSpace::VMAddrSpace() {
stack = NULL;
code = NULL;
data = NULL;
stacksize = DEFAULT_STACKSIZE;
codesize = DEFAULT_CODESIZE;
datasize = DEFAULT_DATASIZE;
allocate();
return;
}
VMAddrSpace::VMAddrSpace(uint32_t ss, uint32_t cs, uint32_t ds) {
stack = NULL;
code = NULL;
data = NULL;
stacksize = ss;
codesize = cs;
datasize = ds;
allocate();
return;
}
VMAddrSpace::~VMAddrSpace() {
if (stack) {
delete[] stack;
}
if (code) {
delete[] code;
}
if (data) {
delete[] data;
}
return;
}
bool VMAddrSpace::allocate(void) {
DBG_INFO(("Allocating sections...\n"));
DBG_INFO(("\tcode...\n"));
code = new uint8_t[codesize];
DBG_INFO(("\tdata...\n"));
data = new uint8_t[datasize];
DBG_INFO(("\tstack...\n"));
stack = new uint8_t[stacksize];
if (code == NULL) {
DBG_ERROR(("Couldn't allocate code section.\n"));
return false;
}
if (data == NULL) {
DBG_ERROR(("Couldn't allocate data section.\n"));
return false;
}
if (stack == NULL) {
DBG_ERROR(("Couldn't allocate stack section.\n"));
return false;
}
memset(code, 0x0, codesize);
memset(stack, 0x0, stacksize);
memset(data, 0x0, datasize);
DBG_SUCC(("Done!\n"));
return true;
}
bool VMAddrSpace::insCode(uint8_t *buf, uint32_t size) {
if (code) {
if (size > codesize) {
DBG_ERROR(("The injected code size is too big!\n"));
return false;
}
DBG_INFO(("Copying buffer into code section.\n"));
memcpy(code, buf, size);
} else {
DBG_ERROR(("Couldn't write into code section.\n"));
return false;
}
return true;
}
bool VMAddrSpace::insStack(uint8_t *buf, uint32_t size) {
if (stack) {
if (size > stacksize) {
DBG_ERROR(("The injected stack size is too big!\n"));
return false;
}
DBG_INFO(("Copying buffer into stack section.\n"));
memcpy(stack, buf, size);
} else {
DBG_ERROR(("Couldn't write into stack section.\n"));
return false;
}
return true;
}
bool VMAddrSpace::insData(uint8_t *buf, uint32_t size) {
if (data) {
if (size > datasize) {
DBG_ERROR(("The injected data size is too big!\n"));
return false;
}
DBG_INFO(("Copying buffer into data section.\n"));
memcpy(data, buf, size);
} else {
DBG_ERROR(("Couldn't write into data section.\n"));
return false;
}
return true;
}
uint32_t VMAddrSpace::getStacksize() const {
return stacksize;
}
uint32_t VMAddrSpace::getCodesize() const {
return codesize;
}
uint32_t VMAddrSpace::getDatasize() const {
return datasize;
}
<|endoftext|>
|
<commit_before>#include "photoeffects.hpp"
using namespace cv;
int fadeColor(cv::InputArray src, cv::OutputArray dst)
{
return image.rows*image.cols;
}
<commit_msg>edit errors<commit_after>#include "photoeffects.hpp"
using namespace cv;
int fadeColor(cv::InputArray src, cv::OutputArray dst)
{
return src.rows*src.cols;
}
<|endoftext|>
|
<commit_before>/******************************
* Qt player using libVLC *
* By protonux *
* *
* Under WTFPL *
******************************/
#include "player.h"
#include <vlc/vlc.h>
#define qtu( i ) ((i).toUtf8().constData())
#include <QtGui>
Mwindow::Mwindow() {
vlcPlayer = NULL;
/* Init libVLC */
if((vlcObject = libvlc_new(0,NULL)) == NULL) {
printf("Could not init libVLC");
exit(1);
}
/* Display libVLC version */
printf("libVLC version: %s\n",libvlc_get_version());
/* Interface initialisation */
initMenus();
initComponents();
}
Mwindow::~Mwindow() {
if(vlcObject)
libvlc_release(vlcObject);
}
void Mwindow::initMenus() {
centralWidget = new QWidget;
videoWidget = new QWidget;
videoWidget->setAutoFillBackground( true );
QPalette plt = palette();
plt.setColor( QPalette::Window, Qt::black );
videoWidget->setPalette( plt );
QMenu *fileMenu = menuBar()->addMenu("&File");
QMenu *editMenu = menuBar()->addMenu("&Edit");
QAction *Open = new QAction("&Open", this);
QAction *Quit = new QAction("&Quit", this);
QAction *playAc = new QAction("&Play/Pause", this);
Open->setShortcut(QKeySequence("Ctrl+O"));
Quit->setShortcut(QKeySequence("Ctrl+Q"));
fileMenu->addAction(Open);
fileMenu->addAction(Quit);
editMenu->addAction(playAc);
connect(Open, SIGNAL(triggered()), this, SLOT(openFile()));
connect(playAc, SIGNAL(triggered()), this, SLOT(play()));
connect(Quit, SIGNAL(triggered()), qApp, SLOT(quit()));
}
void Mwindow::initComponents() {
playBut = new QPushButton("Play");
QObject::connect(playBut, SIGNAL(clicked()), this, SLOT(play()));
stopBut = new QPushButton("Stop");
QObject::connect(stopBut, SIGNAL(clicked()), this, SLOT(stop()));
muteBut = new QPushButton("Mute");
QObject::connect(muteBut, SIGNAL(clicked()), this, SLOT(mute()));
volumeSlider = new QSlider(Qt::Horizontal);
QObject::connect(volumeSlider, SIGNAL(sliderMoved(int)), this, SLOT(changeVolume(int)));
volumeSlider->setValue(80);
slider = new QSlider(Qt::Horizontal);
slider->setMaximum(1000);
QObject::connect(slider, SIGNAL(sliderMoved(int)), this, SLOT(changePosition(int)));
QTimer *timer = new QTimer(this);
connect(timer, SIGNAL(timeout()), this, SLOT(updateInterface()));
timer->start(100);
QHBoxLayout *layout = new QHBoxLayout;
layout->addWidget(playBut);
layout->addWidget(stopBut);
layout->addWidget(muteBut);
layout->addWidget(volumeSlider);
QVBoxLayout *layout2 = new QVBoxLayout;
layout2->addWidget(videoWidget);
layout2->addWidget(slider);
layout2->addLayout(layout);
centralWidget->setLayout(layout2);
setCentralWidget(centralWidget);
resize( 600, 400);
}
void Mwindow::openFile() {
/* Just the basic file-select box */
QString fileOpen = QFileDialog::getOpenFileName(this,tr("Load a file"), "~");
/* Stop if something is playing */
if( vlcPlayer && libvlc_media_player_is_playing(vlcPlayer) )
stop();
/* New Media */
libvlc_media_t *vlcMedia = libvlc_media_new_path(vlcObject,qtu(fileOpen));
if( !vlcMedia )
return;
vlcPlayer = libvlc_media_player_new_from_media (vlcMedia);
libvlc_media_release(vlcMedia);
/* Integrate the video in the interface */
#if defined(Q_OS_MAC)
libvlc_media_player_set_nsobject(vlcPlayer, videoWidget->winId());
#elif defined(Q_OS_UNIX)
libvlc_media_player_set_xwindow(vlcPlayer, videoWidget->winId());
#elif defined(Q_OS_WIN)
libvlc_media_player_set_hwnd(vlcPlayer, videoWidget->winId());
#endif
/* And play */
libvlc_media_player_play (vlcPlayer);
//Set vars and text correctly
playBut->setText("Pause");
}
void Mwindow::play() {
if(vlcPlayer)
{
if (libvlc_media_player_is_playing(vlcPlayer))
{
libvlc_media_player_pause(vlcPlayer);
playBut->setText("Play");
}
else
{
libvlc_media_player_play(vlcPlayer);
playBut->setText("Pause");
}
}
}
int Mwindow::changeVolume(int vol) { //Called if you change the volume slider
if(vlcPlayer)
return libvlc_audio_set_volume (vlcPlayer,vol);
return 0;
}
void Mwindow::changePosition(int pos) { //Called if you change the position slider
if(vlcPlayer) //It segfault if vlcPlayer don't exist
libvlc_media_player_set_position(vlcPlayer,(float)pos/(float)1000);
}
void Mwindow::updateInterface() { //Update interface and check if song is finished
if(vlcPlayer) //It segfault if vlcPlayer don't exist
{
/* update the timeline */
float pos = libvlc_media_player_get_position(vlcPlayer);
int siderPos=(int)(pos*(float)(1000));
slider->setValue(siderPos);
/* Stop the media */
if (libvlc_media_player_get_state(vlcPlayer) == 6) { this->stop(); }
}
}
void Mwindow::stop() {
if(vlcPlayer) {
libvlc_media_player_stop(vlcPlayer);
libvlc_media_player_release(vlcPlayer);
slider->setValue(0);
playBut->setText("Play");
}
vlcPlayer = NULL;
}
void Mwindow::mute() {
if(vlcPlayer) {
if(volumeSlider->value() == 0) { //if already muted...
this->changeVolume(80);
volumeSlider->setValue(80);
} else { //else mute volume
this->changeVolume(0);
volumeSlider->setValue(0);
}
}
}
void Mwindow::closeEvent(QCloseEvent *event) {
stop();
event->accept();
}
<commit_msg>Doc: QtPlayer example: fix MacOS build with Qt4.8<commit_after>/******************************
* Qt player using libVLC *
* By protonux *
* *
* Under WTFPL *
******************************/
#include "player.h"
#include <vlc/vlc.h>
#define qtu( i ) ((i).toUtf8().constData())
#include <QtGui>
Mwindow::Mwindow() {
vlcPlayer = NULL;
/* Init libVLC */
if((vlcObject = libvlc_new(0,NULL)) == NULL) {
printf("Could not init libVLC");
exit(1);
}
/* Display libVLC version */
printf("libVLC version: %s\n",libvlc_get_version());
/* Interface initialisation */
initMenus();
initComponents();
}
Mwindow::~Mwindow() {
if(vlcObject)
libvlc_release(vlcObject);
}
void Mwindow::initMenus() {
centralWidget = new QWidget;
videoWidget = new QWidget;
videoWidget->setAutoFillBackground( true );
QPalette plt = palette();
plt.setColor( QPalette::Window, Qt::black );
videoWidget->setPalette( plt );
QMenu *fileMenu = menuBar()->addMenu("&File");
QMenu *editMenu = menuBar()->addMenu("&Edit");
QAction *Open = new QAction("&Open", this);
QAction *Quit = new QAction("&Quit", this);
QAction *playAc = new QAction("&Play/Pause", this);
Open->setShortcut(QKeySequence("Ctrl+O"));
Quit->setShortcut(QKeySequence("Ctrl+Q"));
fileMenu->addAction(Open);
fileMenu->addAction(Quit);
editMenu->addAction(playAc);
connect(Open, SIGNAL(triggered()), this, SLOT(openFile()));
connect(playAc, SIGNAL(triggered()), this, SLOT(play()));
connect(Quit, SIGNAL(triggered()), qApp, SLOT(quit()));
}
void Mwindow::initComponents() {
playBut = new QPushButton("Play");
QObject::connect(playBut, SIGNAL(clicked()), this, SLOT(play()));
stopBut = new QPushButton("Stop");
QObject::connect(stopBut, SIGNAL(clicked()), this, SLOT(stop()));
muteBut = new QPushButton("Mute");
QObject::connect(muteBut, SIGNAL(clicked()), this, SLOT(mute()));
volumeSlider = new QSlider(Qt::Horizontal);
QObject::connect(volumeSlider, SIGNAL(sliderMoved(int)), this, SLOT(changeVolume(int)));
volumeSlider->setValue(80);
slider = new QSlider(Qt::Horizontal);
slider->setMaximum(1000);
QObject::connect(slider, SIGNAL(sliderMoved(int)), this, SLOT(changePosition(int)));
QTimer *timer = new QTimer(this);
connect(timer, SIGNAL(timeout()), this, SLOT(updateInterface()));
timer->start(100);
QHBoxLayout *layout = new QHBoxLayout;
layout->addWidget(playBut);
layout->addWidget(stopBut);
layout->addWidget(muteBut);
layout->addWidget(volumeSlider);
QVBoxLayout *layout2 = new QVBoxLayout;
layout2->addWidget(videoWidget);
layout2->addWidget(slider);
layout2->addLayout(layout);
centralWidget->setLayout(layout2);
setCentralWidget(centralWidget);
resize( 600, 400);
}
void Mwindow::openFile() {
/* Just the basic file-select box */
QString fileOpen = QFileDialog::getOpenFileName(this,tr("Load a file"), "~");
/* Stop if something is playing */
if( vlcPlayer && libvlc_media_player_is_playing(vlcPlayer) )
stop();
/* New Media */
libvlc_media_t *vlcMedia = libvlc_media_new_path(vlcObject,qtu(fileOpen));
if( !vlcMedia )
return;
vlcPlayer = libvlc_media_player_new_from_media (vlcMedia);
libvlc_media_release(vlcMedia);
/* Integrate the video in the interface */
#if defined(Q_OS_MAC)
libvlc_media_player_set_nsobject(vlcPlayer, (void *) videoWidget->winId());
#elif defined(Q_OS_UNIX)
libvlc_media_player_set_xwindow(vlcPlayer, videoWidget->winId());
#elif defined(Q_OS_WIN)
libvlc_media_player_set_hwnd(vlcPlayer, videoWidget->winId());
#endif
/* And play */
libvlc_media_player_play (vlcPlayer);
//Set vars and text correctly
playBut->setText("Pause");
}
void Mwindow::play() {
if(vlcPlayer)
{
if (libvlc_media_player_is_playing(vlcPlayer))
{
libvlc_media_player_pause(vlcPlayer);
playBut->setText("Play");
}
else
{
libvlc_media_player_play(vlcPlayer);
playBut->setText("Pause");
}
}
}
int Mwindow::changeVolume(int vol) { //Called if you change the volume slider
if(vlcPlayer)
return libvlc_audio_set_volume (vlcPlayer,vol);
return 0;
}
void Mwindow::changePosition(int pos) { //Called if you change the position slider
if(vlcPlayer) //It segfault if vlcPlayer don't exist
libvlc_media_player_set_position(vlcPlayer,(float)pos/(float)1000);
}
void Mwindow::updateInterface() { //Update interface and check if song is finished
if(vlcPlayer) //It segfault if vlcPlayer don't exist
{
/* update the timeline */
float pos = libvlc_media_player_get_position(vlcPlayer);
int siderPos=(int)(pos*(float)(1000));
slider->setValue(siderPos);
/* Stop the media */
if (libvlc_media_player_get_state(vlcPlayer) == 6) { this->stop(); }
}
}
void Mwindow::stop() {
if(vlcPlayer) {
libvlc_media_player_stop(vlcPlayer);
libvlc_media_player_release(vlcPlayer);
slider->setValue(0);
playBut->setText("Play");
}
vlcPlayer = NULL;
}
void Mwindow::mute() {
if(vlcPlayer) {
if(volumeSlider->value() == 0) { //if already muted...
this->changeVolume(80);
volumeSlider->setValue(80);
} else { //else mute volume
this->changeVolume(0);
volumeSlider->setValue(0);
}
}
}
void Mwindow::closeEvent(QCloseEvent *event) {
stop();
event->accept();
}
<|endoftext|>
|
<commit_before><commit_msg>print message before calling the start function.<commit_after><|endoftext|>
|
<commit_before>namespace mant {
namespace robotic {
class ParallelKinematicMachine3PRRR {
public:
inline explicit ParallelKinematicMachine3PRRR() noexcept;
inline arma::Mat<double>::fixed<2, 3> getLinkLengths() const noexcept;
inline void setLinkLengths(
const arma::Mat<double>::fixed<2, 3>& linkLengths) noexcept;
inline arma::Mat<double>::fixed<2, 3> getEndEffectorJointPositions() const noexcept;
inline void setEndEffectorJointPositions(
const arma::Mat<double>::fixed<2, 3>& endEffectorJointPositions) noexcept;
inline arma::Mat<double>::fixed<2, 3> getRedundantJointPositionStarts() const noexcept;
inline void setRedundantJointPositionStarts(
const arma::Mat<double>::fixed<2, 3>& redundantJointPositionStarts) noexcept;
inline arma::Mat<double>::fixed<2, 3> getRedundantJointPositionEnds() const noexcept;
inline void setRedundantJointPositionEnds(
const arma::Mat<double>::fixed<2, 3>& redundantJointPositionEnds) noexcept;
inline std::vector<arma::Mat<double>::fixed<2, 3>> getModel(
const arma::Col<double>::fixed<3>& endEffectorPose,
const arma::Col<double>& redundantJointActuations) const;
inline arma::Col<double>::fixed<3> getActuation(
const arma::Col<double>::fixed<3>& endEffectorPose,
const arma::Col<double>& redundantJointActuations) const;
inline arma::Col<double>::fixed<3> getEndEffectorPose(
const arma::Col<double>::fixed<3>& actuations,
const arma::Col<double>& redundantJointActuations) const;
inline double getEndEffectorPoseAccuracy(
const arma::Col<double>::fixed<3>& endEffectorPose,
const arma::Col<double>& redundantJointActuations) const;
arma::Mat<double>::fixed<2, 3> endEffectorJointPositions_;
arma::Mat<double>::fixed<2, 3> linkLengths_;
arma::Mat<double>::fixed<2, 3> redundantJointPositionStarts_;
arma::Mat<double>::fixed<2, 3> redundantJointPositionEnds_;
arma::Mat<double>::fixed<2, 3> redundantJointPositionStartToEnds_;
arma::Col<unsigned int> redundantJointIndicies_;
arma::Col<double> redundantJointAngleSines_;
arma::Col<double> redundantJointAngleCosines_;
};
//
// Implementation
//
inline ParallelKinematicMachine3PRRR::ParallelKinematicMachine3PRRR() noexcept {
setLinkLengths({
-0.000066580445834, 0.106954081945581,
-0.092751709777083, -0.053477040972790,
0.092818290222917, -0.053477040972790});
setEndEffectorJointPositions({
0.6, 0.6,
0.6, 0.6,
0.6, 0.6});
setRedundantJointPositionStarts({
0.1, 1.0392,
0.0, 0.8,
1.2, 0.8
});
setRedundantJointPositionEnds({
1.1, 1.0392,
0.0, -0.2,
1.2, -0.2});
redundantJointPositionStartToEnds_ = redundantJointEnds_ - redundantJointStarts_;
redundantJointIndicies_ = arma::find(arma::any(redundantJointsStartToEnd_));
redundantJointAngleSines_.set_size(redundantJointIndicies_.n_elem);
redundantJointAngleCosines_.set_size(redundantJointIndicies_.n_elem);
for (std::size_t n = 0; n < redundantJointIndicies_.n_elem; ++n) {
const double redundantJointAngle = std::atan2(redundantJointPositionStartToEnds_.at(1, n), redundantJointPositionStartToEnds_.at(0, n));
redundantJointAngleSines_.at(n) = std::sin(redundantJointAngle);
redundantJointAngleCosines_.at(n) = std::cos(redundantJointAngle);
}
}
inline arma::Mat<double>::fixed<2, 3> ParallelKinematicMachine3PRRR::getLinkLengths() const noexcept {
return linkLengths_;
}
inline void ParallelKinematicMachine3PRRR::setLinkLengths(
const arma::Mat<double>::fixed<2, 3>& linkLengths) noexcept {
linkLengths_ = linkLengths;
}
inline arma::Mat<double>::fixed<2, 3> ParallelKinematicMachine3PRRR::getEndEffectorJointPositions() const noexcept {
return endEffectorJointPositions_;
}
inline void ParallelKinematicMachine3PRRR::setEndEffectorJointPositions(
const arma::Mat<double>::fixed<2, 3>& endEffectorJointPositions) noexcept {
endEffectorJointPositions_ = endEffectorJointPositions;
}
inline arma::Mat<double>::fixed<2, 3> ParallelKinematicMachine3PRRR::getRedundantJointPositionStarts() const noexcept {
return redundantJointPositionStarts_;
}
inline void ParallelKinematicMachine3PRRR::setRedundantJointPositionStarts(
const arma::Mat<double>::fixed<2, 3>& redundantJointPositionStarts) noexcept {
redundantJointPositionStarts_ = redundantJointPositionStarts;
}
inline arma::Mat<double>::fixed<2, 3> ParallelKinematicMachine3PRRR::getRedundantJointPositionEnds() const noexcept {
return redundantJointPositionEnds_;
}
inline void ParallelKinematicMachine3PRRR::setRedundantJointPositionEnds(
const arma::Mat<double>::fixed<2, 3>& redundantJointPositionEnds) noexcept {
redundantJointPositionEnds_ = redundantJointPositionEnds;
}
inline std::vector<arma::Mat<double>::fixed<2, 3>> ParallelKinematicMachine3PRRR::getModel(
const arma::Col<double>::fixed<3>& endEffectorPose,
const arma::Col<double>& redundantJointActuations) const {
if (arma::any(arma::vectorise(redundantJointActuations < 0)) || arma::any(arma::vectorise(redundantJointActuations > 1))) {
throw std::logic_error("All values for the actuation of redundantion joints must be between [0, 1].");
}
const arma::Col<double>::fixed<2>& endEffectorPosition = endEffectorPose.subvec(0, 1);
const double& endEffectorAngle = endEffectorPose.at(2);
arma::Mat<double>::fixed<2, 3> baseJoints = redundantJointStarts_;
for (std::size_t n = 0; n < redundantJointIndicies_.n_elem; n++) {
const unsigned int& redundantJointIndex = redundantJointIndicies_.at(n);
baseJoints.col(redundantJointIndex) += redundantJointActuations.at(redundantJointIndex) * redundantJointsStartToEnd_.col(redundantJointIndex);
}
arma::Mat<double>::fixed<2, 3> endEffectorJoints = get2DRotationMatrix(endEffectorAngle) * endEffectorJointsRelative_;
endEffectorJoints.each_col() += endEffectorPosition;
arma::Mat<double>::fixed<2, 3> passiveJoints;
for (std::size_t n = 0; n < baseJoints.n_cols; ++n) {
passiveJoints.col(n) = getCircleCircleIntersection(baseJoints.col(n), linkLengths_.at(0, n), endEffectorJoints.col(n), linkLengths_.at(1, n));
}
std::vector<arma::Mat<double>::fixed<2, 3>> model;
model.push_back(baseJoints);
model.push_back(passiveJoints);
model.push_back(endEffectorJoints);
return model;
}
inline arma::Col<double>::fixed<3> ParallelKinematicMachine3PRRR::getActuation(
const arma::Col<double>::fixed<3>& endEffectorPose,
const arma::Col<double>& redundantJointActuations) const {
const std::vector<arma::Mat<double>::fixed<2, 3>>& model = getModel(endEffectorPose, redundantJointActuations);
const arma::Mat<double>::fixed<2, 3>& baseJointPositions = model.at(0);
const arma::Mat<double>::fixed<2, 3>& passiveJointPositions = model.at(1);
const arma::Mat<double>::fixed<2, 3>& baseToPassiveJointPositions = passiveJointPositions - baseJointPositions;
arma::Row<double>::fixed<3> actuation;
for (std::size_t n = 0; n < baseToPassiveJointPositions.n_elem; ++n) {
actuation.at(n) = std::atan2(baseToPassiveJointPositions.at(1, n), baseToPassiveJointPositions.at(0, n));
}
return actuation;
}
inline arma::Col<double>::fixed<3> ParallelKinematicMachine3PRRR::getEndEffectorPose(
const arma::Col<double>::fixed<3>& actuations,
const arma::Col<double>& redundantJointActuations) const {
// TODO Direct kinematic (estimate position, using a simple HillCLimber algorithm)
}
inline double ParallelKinematicMachine3PRRR::getEndEffectorPoseAccuracy(
const arma::Col<double>::fixed<3>& endEffectorPose,
const arma::Col<double>& redundantJointActuations) const {
const std::vector<arma::Mat<double>::fixed<2, 3>>& model = getModel(endEffectorPose, redundantJointActuations);
const arma::Mat<double>::fixed<2, 3>& baseJoints = modelCharacterisation.at(0);
const arma::Mat<double>::fixed<2, 3>& endEffectorJoints = model.at(2);
arma::Mat<double>::fixed<2, 3> endEffectorJointsRotated = endEffectorJoints;
endEffectorJointsRotated.each_col() -= endEffectorPose.subvec(0, 1);
const arma::Mat<double>::fixed<2, 3>& passiveJoints = model.at(1);
arma::Mat<double>::fixed<3, 3> forwardKinematic;
forwardKinematic.rows(0, 1) = endEffectorJoints - passiveJoints;
forwardKinematic.row(2) = -forwardKinematic.row(0) % endEffectorJointsRotated.row(1) + forwardKinematic.row(1) % endEffectorJointsRotated.row(0);
const arma::Mat<double>::fixed<2, 3>& baseToPassiveJoints = passiveJoints - baseJoints;
arma::Mat<double> inverseKinematic(3, 3 + redundantJointIndicies_.n_elem, arma::fill::zeros);
inverseKinematic.diag() = forwardKinematic.row(0) % baseToPassiveJoints.row(1) - forwardKinematic.row(1) % baseToPassiveJoints.row(0);
for (std::size_t n = 0; n < redundantJointIndicies_.n_elem; ++n) {
const unsigned int& redundantJointIndex = redundantJointIndicies_.at(n);
inverseKinematic.at(n, 3 + n) = -(forwardKinematic.at(redundantJointIndex, 0) * redundantJointAnglesCosine_.at(n) + forwardKinematic.at(redundantJointIndex, 1) * redundantJointAnglesSine_.at(n));
}
return -1.0 / arma::cond(arma::solve(forwardKinematic.t(), inverseKinematic));
}
}
}
<commit_msg>devel: Fixed some minor naming errors, introduced by previous changes<commit_after>namespace mant {
namespace robotic {
class ParallelKinematicMachine3PRRR {
public:
inline explicit ParallelKinematicMachine3PRRR() noexcept;
inline arma::Mat<double>::fixed<2, 3> getLinkLengths() const noexcept;
inline void setLinkLengths(
const arma::Mat<double>::fixed<2, 3>& linkLengths) noexcept;
inline arma::Mat<double>::fixed<2, 3> getEndEffectorJointPositions() const noexcept;
inline void setEndEffectorJointPositions(
const arma::Mat<double>::fixed<2, 3>& endEffectorJointPositions) noexcept;
inline arma::Mat<double>::fixed<2, 3> getRedundantJointPositionStarts() const noexcept;
inline void setRedundantJointPositionStarts(
const arma::Mat<double>::fixed<2, 3>& redundantJointPositionStarts) noexcept;
inline arma::Mat<double>::fixed<2, 3> getRedundantJointPositionEnds() const noexcept;
inline void setRedundantJointPositionEnds(
const arma::Mat<double>::fixed<2, 3>& redundantJointPositionEnds) noexcept;
inline std::vector<arma::Mat<double>::fixed<2, 3>> getModel(
const arma::Col<double>::fixed<3>& endEffectorPose,
const arma::Col<double>& redundantJointActuations) const;
inline arma::Col<double>::fixed<3> getActuation(
const arma::Col<double>::fixed<3>& endEffectorPose,
const arma::Col<double>& redundantJointActuations) const;
inline arma::Col<double>::fixed<3> getEndEffectorPose(
const arma::Col<double>::fixed<3>& actuations,
const arma::Col<double>& redundantJointActuations) const;
inline double getEndEffectorPoseAccuracy(
const arma::Col<double>::fixed<3>& endEffectorPose,
const arma::Col<double>& redundantJointActuations) const;
arma::Mat<double>::fixed<2, 3> endEffectorJointPositions_;
arma::Mat<double>::fixed<2, 3> linkLengths_;
arma::Mat<double>::fixed<2, 3> redundantJointPositionStarts_;
arma::Mat<double>::fixed<2, 3> redundantJointPositionEnds_;
arma::Mat<double>::fixed<2, 3> redundantJointPositionStartToEnds_;
arma::Col<unsigned int> redundantJointIndicies_;
arma::Col<double> redundantJointAngleSines_;
arma::Col<double> redundantJointAngleCosines_;
};
//
// Implementation
//
inline ParallelKinematicMachine3PRRR::ParallelKinematicMachine3PRRR() noexcept {
setLinkLengths({
-0.000066580445834, 0.106954081945581,
-0.092751709777083, -0.053477040972790,
0.092818290222917, -0.053477040972790});
setEndEffectorJointPositions({
0.6, 0.6,
0.6, 0.6,
0.6, 0.6});
setRedundantJointPositionStarts({
0.1, 1.0392,
0.0, 0.8,
1.2, 0.8
});
setRedundantJointPositionEnds({
1.1, 1.0392,
0.0, -0.2,
1.2, -0.2});
redundantJointPositionStartToEnds_ = redundantJointPositionEnds_ - redundantJointPositionStarts_;
redundantJointIndicies_ = arma::find(arma::any(redundantJointPositionStartToEnds_));
redundantJointAngleSines_.set_size(redundantJointIndicies_.n_elem);
redundantJointAngleCosines_.set_size(redundantJointIndicies_.n_elem);
for (std::size_t n = 0; n < redundantJointIndicies_.n_elem; ++n) {
const double redundantJointAngle = std::atan2(redundantJointPositionStartToEnds_.at(1, n), redundantJointPositionStartToEnds_.at(0, n));
redundantJointAngleSines_.at(n) = std::sin(redundantJointAngle);
redundantJointAngleCosines_.at(n) = std::cos(redundantJointAngle);
}
}
inline arma::Mat<double>::fixed<2, 3> ParallelKinematicMachine3PRRR::getLinkLengths() const noexcept {
return linkLengths_;
}
inline void ParallelKinematicMachine3PRRR::setLinkLengths(
const arma::Mat<double>::fixed<2, 3>& linkLengths) noexcept {
linkLengths_ = linkLengths;
}
inline arma::Mat<double>::fixed<2, 3> ParallelKinematicMachine3PRRR::getEndEffectorJointPositions() const noexcept {
return endEffectorJointPositions_;
}
inline void ParallelKinematicMachine3PRRR::setEndEffectorJointPositions(
const arma::Mat<double>::fixed<2, 3>& endEffectorJointPositions) noexcept {
endEffectorJointPositions_ = endEffectorJointPositions;
}
inline arma::Mat<double>::fixed<2, 3> ParallelKinematicMachine3PRRR::getRedundantJointPositionStarts() const noexcept {
return redundantJointPositionStarts_;
}
inline void ParallelKinematicMachine3PRRR::setRedundantJointPositionStarts(
const arma::Mat<double>::fixed<2, 3>& redundantJointPositionStarts) noexcept {
redundantJointPositionStarts_ = redundantJointPositionStarts;
}
inline arma::Mat<double>::fixed<2, 3> ParallelKinematicMachine3PRRR::getRedundantJointPositionEnds() const noexcept {
return redundantJointPositionEnds_;
}
inline void ParallelKinematicMachine3PRRR::setRedundantJointPositionEnds(
const arma::Mat<double>::fixed<2, 3>& redundantJointPositionEnds) noexcept {
redundantJointPositionEnds_ = redundantJointPositionEnds;
}
inline std::vector<arma::Mat<double>::fixed<2, 3>> ParallelKinematicMachine3PRRR::getModel(
const arma::Col<double>::fixed<3>& endEffectorPose,
const arma::Col<double>& redundantJointActuations) const {
if (arma::any(arma::vectorise(redundantJointActuations < 0)) || arma::any(arma::vectorise(redundantJointActuations > 1))) {
throw std::logic_error("All values for the actuation of redundantion joints must be between [0, 1].");
}
const arma::Col<double>::fixed<2>& endEffectorPosition = endEffectorPose.subvec(0, 1);
const double& endEffectorAngle = endEffectorPose.at(2);
arma::Mat<double>::fixed<2, 3> baseJoints = redundantJointPositionStarts_;
for (std::size_t n = 0; n < redundantJointIndicies_.n_elem; n++) {
const unsigned int& redundantJointIndex = redundantJointIndicies_.at(n);
baseJoints.col(redundantJointIndex) += redundantJointActuations.at(redundantJointIndex) * redundantJointPositionStartToEnds_.col(redundantJointIndex);
}
arma::Mat<double>::fixed<2, 3> endEffectorJoints = get2DRotationMatrix(endEffectorAngle) * endEffectorJointPositions_;
endEffectorJoints.each_col() += endEffectorPosition;
arma::Mat<double>::fixed<2, 3> passiveJoints;
for (std::size_t n = 0; n < baseJoints.n_cols; ++n) {
passiveJoints.col(n) = getCircleCircleIntersection(baseJoints.col(n), linkLengths_.at(0, n), endEffectorJoints.col(n), linkLengths_.at(1, n));
}
std::vector<arma::Mat<double>::fixed<2, 3>> model;
model.push_back(baseJoints);
model.push_back(passiveJoints);
model.push_back(endEffectorJoints);
return model;
}
inline arma::Col<double>::fixed<3> ParallelKinematicMachine3PRRR::getActuation(
const arma::Col<double>::fixed<3>& endEffectorPose,
const arma::Col<double>& redundantJointActuations) const {
const std::vector<arma::Mat<double>::fixed<2, 3>>& model = getModel(endEffectorPose, redundantJointActuations);
const arma::Mat<double>::fixed<2, 3>& baseJointPositions = model.at(0);
const arma::Mat<double>::fixed<2, 3>& passiveJointPositions = model.at(1);
const arma::Mat<double>::fixed<2, 3>& baseToPassiveJointPositions = passiveJointPositions - baseJointPositions;
arma::Row<double>::fixed<3> actuation;
for (std::size_t n = 0; n < baseToPassiveJointPositions.n_elem; ++n) {
actuation.at(n) = std::atan2(baseToPassiveJointPositions.at(1, n), baseToPassiveJointPositions.at(0, n));
}
return actuation;
}
inline arma::Col<double>::fixed<3> ParallelKinematicMachine3PRRR::getEndEffectorPose(
const arma::Col<double>::fixed<3>& actuations,
const arma::Col<double>& redundantJointActuations) const {
// TODO Direct kinematic (estimate position, using a simple HillCLimber algorithm)
}
inline double ParallelKinematicMachine3PRRR::getEndEffectorPoseAccuracy(
const arma::Col<double>::fixed<3>& endEffectorPose,
const arma::Col<double>& redundantJointActuations) const {
const std::vector<arma::Mat<double>::fixed<2, 3>>& model = getModel(endEffectorPose, redundantJointActuations);
const arma::Mat<double>::fixed<2, 3>& baseJoints = model.at(0);
const arma::Mat<double>::fixed<2, 3>& endEffectorJoints = model.at(2);
arma::Mat<double>::fixed<2, 3> endEffectorJointsRotated = endEffectorJoints;
endEffectorJointsRotated.each_col() -= endEffectorPose.subvec(0, 1);
const arma::Mat<double>::fixed<2, 3>& passiveJoints = model.at(1);
arma::Mat<double>::fixed<3, 3> forwardKinematic;
forwardKinematic.rows(0, 1) = endEffectorJoints - passiveJoints;
forwardKinematic.row(2) = -forwardKinematic.row(0) % endEffectorJointsRotated.row(1) + forwardKinematic.row(1) % endEffectorJointsRotated.row(0);
const arma::Mat<double>::fixed<2, 3>& baseToPassiveJoints = passiveJoints - baseJoints;
arma::Mat<double> inverseKinematic(3, 3 + redundantJointIndicies_.n_elem, arma::fill::zeros);
inverseKinematic.diag() = forwardKinematic.row(0) % baseToPassiveJoints.row(1) - forwardKinematic.row(1) % baseToPassiveJoints.row(0);
for (std::size_t n = 0; n < redundantJointIndicies_.n_elem; ++n) {
const unsigned int& redundantJointIndex = redundantJointIndicies_.at(n);
inverseKinematic.at(n, 3 + n) = -(forwardKinematic.at(redundantJointIndex, 0) * redundantJointAngleCosines_.at(n) + forwardKinematic.at(redundantJointIndex, 1) * redundantJointAngleSines_.at(n));
}
return -1.0 / arma::cond(arma::solve(forwardKinematic.t(), inverseKinematic));
}
}
}
<|endoftext|>
|
<commit_before><commit_msg>[spaces.fv] add missing includes<commit_after><|endoftext|>
|
<commit_before><commit_msg>Removed extra debug info.<commit_after><|endoftext|>
|
<commit_before>/*************************************************************************
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: mailmodel.hxx,v $
*
* $Revision: 1.5 $
*
* last change: $Author: obo $ $Date: 2006-03-27 09:37:18 $
*
* The Contents of this file are made available subject to
* the terms of GNU Lesser General Public License Version 2.1.
*
*
* GNU Lesser General Public License Version 2.1
* =============================================
* Copyright 2005 by Sun Microsystems, Inc.
* 901 San Antonio Road, Palo Alto, CA 94303, USA
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License version 2.1, as published by the Free Software Foundation.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston,
* MA 02111-1307 USA
*
************************************************************************/
#ifndef INCLUDED_SFX_MAILMODEL_HXX
#define INCLUDED_SFX_MAILMODEL_HXX
#ifndef _COM_SUN_STAR_FRAME_XFRAME_HPP_
#include <com/sun/star/frame/XFrame.hpp>
#endif
// class SfxMailModel_Impl -----------------------------------------------
class AddressList_Impl;
class SfxMailModel_Impl
{
public:
enum MailPriority
{
PRIO_HIGHEST,
PRIO_HIGH,
PRIO_NORMAL,
PRIO_LOW,
PRIO_LOWEST
};
enum AddressRole
{
ROLE_TO,
ROLE_CC,
ROLE_BCC
};
enum MailDocType
{
TYPE_SELF,
TYPE_ASPDF
};
private:
enum SaveResult
{
SAVE_SUCCESSFULL,
SAVE_CANCELLED,
SAVE_ERROR
};
AddressList_Impl* mpToList;
AddressList_Impl* mpCcList;
AddressList_Impl* mpBccList;
String maFromAddress;
String maSubject;
MailPriority mePriority;
sal_Bool mbLoadDone;
void ClearList( AddressList_Impl* pList );
void MakeValueList( AddressList_Impl* pList, String& rValueList );
SaveResult SaveDocumentAsFormat( const ::com::sun::star::uno::Reference< ::com::sun::star::frame::XFrame >& xFrame, const rtl::OUString& rType, rtl::OUString& rFileNamePath );
DECL_LINK( DoneHdl, void* );
public:
enum SendMailResult
{
SEND_MAIL_OK,
SEND_MAIL_CANCELLED,
SEND_MAIL_ERROR
};
SfxMailModel_Impl();
~SfxMailModel_Impl();
void AddAddress( const String& rAddress, AddressRole eRole );
void SetFromAddress( const String& rAddress ) { maFromAddress = rAddress; }
void SetSubject( const String& rSubject ) { maSubject = rSubject; }
void SetPriority( MailPriority ePrio ) { mePriority = ePrio; }
SendMailResult Send( const ::com::sun::star::uno::Reference< ::com::sun::star::frame::XFrame >& xFrame, const rtl::OUString& rType );
};
BOOL CreateFromAddress_Impl( String& rFrom );
#endif // INCLUDED_SFX_MAILMODEL_HXX
<commit_msg>INTEGRATION: CWS changefileheader (1.5.580); FILE MERGED 2008/04/01 12:40:51 thb 1.5.580.2: #i85898# Stripping all external header guards 2008/03/31 13:38:35 rt 1.5.580.1: #i87441# Change license header to LPGL v3.<commit_after>/*************************************************************************
*
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* Copyright 2008 by Sun Microsystems, Inc.
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: mailmodel.hxx,v $
* $Revision: 1.6 $
*
* This file is part of OpenOffice.org.
*
* OpenOffice.org is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License version 3
* only, as published by the Free Software Foundation.
*
* OpenOffice.org is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License version 3 for more details
* (a copy is included in the LICENSE file that accompanied this code).
*
* You should have received a copy of the GNU Lesser General Public License
* version 3 along with OpenOffice.org. If not, see
* <http://www.openoffice.org/license.html>
* for a copy of the LGPLv3 License.
*
************************************************************************/
#ifndef INCLUDED_SFX_MAILMODEL_HXX
#define INCLUDED_SFX_MAILMODEL_HXX
#include <com/sun/star/frame/XFrame.hpp>
// class SfxMailModel_Impl -----------------------------------------------
class AddressList_Impl;
class SfxMailModel_Impl
{
public:
enum MailPriority
{
PRIO_HIGHEST,
PRIO_HIGH,
PRIO_NORMAL,
PRIO_LOW,
PRIO_LOWEST
};
enum AddressRole
{
ROLE_TO,
ROLE_CC,
ROLE_BCC
};
enum MailDocType
{
TYPE_SELF,
TYPE_ASPDF
};
private:
enum SaveResult
{
SAVE_SUCCESSFULL,
SAVE_CANCELLED,
SAVE_ERROR
};
AddressList_Impl* mpToList;
AddressList_Impl* mpCcList;
AddressList_Impl* mpBccList;
String maFromAddress;
String maSubject;
MailPriority mePriority;
sal_Bool mbLoadDone;
void ClearList( AddressList_Impl* pList );
void MakeValueList( AddressList_Impl* pList, String& rValueList );
SaveResult SaveDocumentAsFormat( const ::com::sun::star::uno::Reference< ::com::sun::star::frame::XFrame >& xFrame, const rtl::OUString& rType, rtl::OUString& rFileNamePath );
DECL_LINK( DoneHdl, void* );
public:
enum SendMailResult
{
SEND_MAIL_OK,
SEND_MAIL_CANCELLED,
SEND_MAIL_ERROR
};
SfxMailModel_Impl();
~SfxMailModel_Impl();
void AddAddress( const String& rAddress, AddressRole eRole );
void SetFromAddress( const String& rAddress ) { maFromAddress = rAddress; }
void SetSubject( const String& rSubject ) { maSubject = rSubject; }
void SetPriority( MailPriority ePrio ) { mePriority = ePrio; }
SendMailResult Send( const ::com::sun::star::uno::Reference< ::com::sun::star::frame::XFrame >& xFrame, const rtl::OUString& rType );
};
BOOL CreateFromAddress_Impl( String& rFrom );
#endif // INCLUDED_SFX_MAILMODEL_HXX
<|endoftext|>
|
<commit_before>/*************************************************************************
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: impframe.hxx,v $
*
* $Revision: 1.6 $
*
* last change: $Author: rt $ $Date: 2005-09-07 19:27:12 $
*
* The Contents of this file are made available subject to
* the terms of GNU Lesser General Public License Version 2.1.
*
*
* GNU Lesser General Public License Version 2.1
* =============================================
* Copyright 2005 by Sun Microsystems, Inc.
* 901 San Antonio Road, Palo Alto, CA 94303, USA
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License version 2.1, as published by the Free Software Foundation.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston,
* MA 02111-1307 USA
*
************************************************************************/
#ifndef _SFX_IMPFRAME_HXX
#define _SFX_IMPFRAME_HXX
#ifndef _SFXCANCEL_HXX //autogen
#include <svtools/cancel.hxx>
#endif
#pragma hdrstop
#include "frame.hxx"
#include "loadenv.hxx"
#include "viewfrm.hxx" // SvBorder
class SfxViewFrame;
class SfxObjectShell;
class SfxExplorerBrowserConfig;
#ifndef _COM_SUN_STAR_FRAME_XCONTROLLER_HPP_
#include <com/sun/star/frame/XController.hpp>
#endif
#ifndef _COM_SUN_STAR_AWT_XTOPWINDOW_HPP_
#include <com/sun/star/awt/XTopWindow.hpp>
#endif
#ifndef _COM_SUN_STAR_AWT_XWINDOW_HPP_
#include <com/sun/star/awt/XWindow.hpp>
#endif
#ifndef _COM_SUN_STAR_AWT_POSSIZE_HPP_
#include <com/sun/star/awt/PosSize.hpp>
#endif
#ifndef _CPPUHELPER_WEAK_HXX_
#include <cppuhelper/weak.hxx>
#endif
#include <viewsh.hxx>
#include <sfxuno.hxx>
#ifndef FRAME_SEARCH_PARENT
#define FRAME_SEARCH_PARENT 0x00000001
#define FRAME_SEARCH_SELF 0x00000002
#define FRAME_SEARCH_CHILDREN 0x00000004
#define FRAME_SEARCH_CREATE 0x00000008
#endif
class SfxFrame_Impl : public SfxBroadcaster, public SvCompatWeakBase, public SfxListener
{
friend class SfxFrame;
::com::sun::star::uno::Reference< ::com::sun::star::frame::XFrame > xFrame;
String aFrameIdName;
sal_uInt32 nType;
sal_uInt32 nHistoryPos;
SfxViewFrame* pCurrentViewFrame;
SfxObjectShell* pCurrentObjectShell;
SfxFrameDescriptor* pDescr;
SfxExplorerBrowserConfig* pBrowserCfg;
sal_uInt16 nFrameId;
sal_uInt16 nLocks;
sal_Bool bCloseOnUnlock : 1;
sal_Bool bClosing : 1;
sal_Bool bPrepClosing : 1;
sal_Bool bInCancelTransfers : 1;
sal_Bool bOwnsBindings : 1;
sal_Bool bReleasingComponent : 1;
sal_Bool bFocusLocked : 1;
sal_Bool bInPlace : 1;
sal_uInt16 nHasBrowser;
SfxCancelManager* pCancelMgr;
SfxCancellable* pLoadCancellable;
SfxFrame* pFrame;
const SfxItemSet* pSet;
SfxWorkWindow* pWorkWin;
SvBorder aBorder;
SfxFrame_Impl( SfxFrame* pAntiImplP ) :
SvCompatWeakBase( pAntiImplP ),
pFrame( pAntiImplP ),
bClosing(sal_False),
bPrepClosing(sal_False),
nType( 0L ),
nHistoryPos( 0 ),
nFrameId( 0 ),
pCurrentObjectShell( NULL ),
pCurrentViewFrame( NULL ),
bInCancelTransfers( sal_False ),
bCloseOnUnlock( sal_False ),
bOwnsBindings( sal_False ),
bReleasingComponent( sal_False ),
bFocusLocked( sal_False ),
bInPlace( sal_False ),
nLocks( 0 ),
pBrowserCfg( NULL ),
pDescr( NULL ),
nHasBrowser( SFX_BEAMER_OFF ),
pCancelMgr( 0 ),
pLoadCancellable( 0 ),
pSet( 0 ),
pWorkWin( 0 )
{}
~SfxFrame_Impl() { delete pCancelMgr;
delete pLoadCancellable; }
virtual void Notify( SfxBroadcaster& rBC, const SfxHint& rHint );
};
#endif
<commit_msg>INTEGRATION: CWS sfxcleanup (1.6.158); FILE MERGED 2006/02/24 23:08:58 mba 1.6.158.1: #132394#: remove obviously superfluous members and methods from SfxApplication<commit_after>/*************************************************************************
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: impframe.hxx,v $
*
* $Revision: 1.7 $
*
* last change: $Author: rt $ $Date: 2006-05-02 17:03:17 $
*
* The Contents of this file are made available subject to
* the terms of GNU Lesser General Public License Version 2.1.
*
*
* GNU Lesser General Public License Version 2.1
* =============================================
* Copyright 2005 by Sun Microsystems, Inc.
* 901 San Antonio Road, Palo Alto, CA 94303, USA
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License version 2.1, as published by the Free Software Foundation.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston,
* MA 02111-1307 USA
*
************************************************************************/
#ifndef _SFX_IMPFRAME_HXX
#define _SFX_IMPFRAME_HXX
#ifndef _SFXCANCEL_HXX //autogen
#include <svtools/cancel.hxx>
#endif
#pragma hdrstop
#include "frame.hxx"
#include "viewfrm.hxx" // SvBorder
class SfxViewFrame;
class SfxObjectShell;
#ifndef _COM_SUN_STAR_FRAME_XCONTROLLER_HPP_
#include <com/sun/star/frame/XController.hpp>
#endif
#ifndef _COM_SUN_STAR_AWT_XTOPWINDOW_HPP_
#include <com/sun/star/awt/XTopWindow.hpp>
#endif
#ifndef _COM_SUN_STAR_AWT_XWINDOW_HPP_
#include <com/sun/star/awt/XWindow.hpp>
#endif
#ifndef _COM_SUN_STAR_AWT_POSSIZE_HPP_
#include <com/sun/star/awt/PosSize.hpp>
#endif
#ifndef _CPPUHELPER_WEAK_HXX_
#include <cppuhelper/weak.hxx>
#endif
#include <viewsh.hxx>
#include <sfxuno.hxx>
#ifndef FRAME_SEARCH_PARENT
#define FRAME_SEARCH_PARENT 0x00000001
#define FRAME_SEARCH_SELF 0x00000002
#define FRAME_SEARCH_CHILDREN 0x00000004
#define FRAME_SEARCH_CREATE 0x00000008
#endif
class SfxFrame_Impl : public SfxBroadcaster, public SvCompatWeakBase, public SfxListener
{
friend class SfxFrame;
::com::sun::star::uno::Reference< ::com::sun::star::frame::XFrame > xFrame;
String aFrameIdName;
sal_uInt32 nType;
sal_uInt32 nHistoryPos;
SfxViewFrame* pCurrentViewFrame;
SfxObjectShell* pCurrentObjectShell;
SfxFrameDescriptor* pDescr;
sal_uInt16 nFrameId;
sal_uInt16 nLocks;
sal_Bool bCloseOnUnlock : 1;
sal_Bool bClosing : 1;
sal_Bool bPrepClosing : 1;
sal_Bool bInCancelTransfers : 1;
sal_Bool bOwnsBindings : 1;
sal_Bool bReleasingComponent : 1;
sal_Bool bFocusLocked : 1;
sal_Bool bInPlace : 1;
SfxCancelManager* pCancelMgr;
SfxCancellable* pLoadCancellable;
SfxFrame* pFrame;
const SfxItemSet* pSet;
SfxWorkWindow* pWorkWin;
SvBorder aBorder;
SfxFrame_Impl( SfxFrame* pAntiImplP ) :
SvCompatWeakBase( pAntiImplP ),
pFrame( pAntiImplP ),
bClosing(sal_False),
bPrepClosing(sal_False),
nType( 0L ),
nHistoryPos( 0 ),
nFrameId( 0 ),
pCurrentObjectShell( NULL ),
pCurrentViewFrame( NULL ),
bInCancelTransfers( sal_False ),
bCloseOnUnlock( sal_False ),
bOwnsBindings( sal_False ),
bReleasingComponent( sal_False ),
bFocusLocked( sal_False ),
bInPlace( sal_False ),
nLocks( 0 ),
pDescr( NULL ),
pCancelMgr( 0 ),
pLoadCancellable( 0 ),
pSet( 0 ),
pWorkWin( 0 )
{}
~SfxFrame_Impl() { delete pCancelMgr;
delete pLoadCancellable; }
virtual void Notify( SfxBroadcaster& rBC, const SfxHint& rHint );
};
#endif
<|endoftext|>
|
<commit_before>#include "opencv2/highgui/highgui.hpp"
#include "opencv2/core/core.hpp"
#include "opencv2/imgproc/imgproc.hpp"
#include <iostream>
using namespace std;
using namespace cv;
int main(int argc, char ** argv){
VideoCapture in;
VideoWriter out;
VideoWriter test;
if(argc >1){
in.open(argv[1]);
// int ex= static_cast<int>(in.get(CV_CAP_PROP_FOURCC));
const string source = argv[1];
string::size_type pAt = source.find_last_of('.');
const string NAME= source.substr(0, pAt) + "E.avi";
out.open(NAME, CV_FOURCC('D', 'I', 'V', 'X') , in.get(CV_CAP_PROP_FPS), Size( (int) in.get(CV_CAP_PROP_FRAME_WIDTH), (int) in.get(CV_CAP_PROP_FRAME_HEIGHT)), true);
}
else
exit(1);
if(!in.isOpened()){
cerr<<"Was unable to open video input."<<endl;
}
if(!out.isOpened()){
cerr<<"Was unable to open video output."<<endl;
}
int count=0;
while(true){
Mat frame;
Mat colorImg;
bool success = in.read(frame);
if(!success){
cout<<"VIDEO STREAM COMPLETE"<<endl;
break;
}
//Lets do some thresholding.
cvtColor(frame, colorImg, COLOR_BGR2HSV);
for(int i=0; i<colorImg.rows; i++){
for(int j=0; j<colorImg.cols; j++){
Vec3i & pixel = colorImg.at<Vec3i>(Point(j, i));
if( (pixel[0] > 8 && pixel[0] < 22) && (pixel[1] > 60 && pixel[1] < 120 ) && (pixel[2] > 0 && pixel[2] <255)){
pixel[0] = 255;
pixel[1] = 0;
pixel[2] = 0;
}
else{
pixel[0] = 0;
pixel[1] = 0;
pixel[2] = 0;
}
colorImg.at<Vec3i>(Point(j, i)) = pixel;
}
}
//It is now time for line doings.
Vec3i pixel;
vector<Point> points;
for(int i=0; i<colorImg.cols; i++){
for(int j=0; j<colorImg.rows; j++){
pixel = colorImg.at<Vec3i>(i, j);
if(pixel[0] !=0){
points.push_back(Point(i, j));
}
}
}
Point * pointArr = new Point[points.size()];
Mat pointMat = Mat(1, points.size(), CV_32F, pointArr);
Vec4f outVector;
fitLine(points, outVector, CV_DIST_L2, 0, 0.01, 0.01);
float d = sqrt((double)outVector[0]*outVector[0] + (double)outVector[1]*outVector[1]);
outVector[0] /= d;
outVector[1] /= d;
float m = (float) (frame.cols + frame.rows);
Point start;
start.x = outVector[2] - m*outVector[0];
start.y = outVector[3] - m*outVector[1];
Point end;
end.x = outVector[2] + m*outVector[0];
end.y = outVector[3] + m*outVector[1];
for(int i=0; i<points.size(); i++){
circle(frame, points[i], 2, Scalar(255, 0, 0), CV_FILLED, CV_AA, 0);
}
circle(frame, Point(outVector[2], outVector[3]), 10, Scalar(255, 0, 0), 1, 8, 0);
line(frame, start, end, Scalar(0, 0, 255), 3, CV_AA, 0 );
if(count % 100 ==0)
cout<<"WRITING FRAME "<<count<<endl;
count++;
out.write(frame);
}
in.release();
cout<<argv[1]<<endl;
}
<commit_msg>started over, looking pretty good so far<commit_after>#include "opencv2/highgui/highgui.hpp"
#include "opencv2/core/core.hpp"
#include "opencv2/imgproc/imgproc.hpp"
#include <iostream>
using namespace std;
using namespace cv;
int main(int argc, char ** argv){
VideoCapture in;
VideoWriter out;
VideoWriter test;
if(argc >1){
in.open(argv[1]);
const string source = argv[1];
string::size_type pAt = source.find_last_of('.');
const string NAME= source.substr(0, pAt) + "E.avi";
out.open(NAME, CV_FOURCC('D', 'I', 'V', 'X') , in.get(CV_CAP_PROP_FPS), Size( (int) in.get(CV_CAP_PROP_FRAME_WIDTH), (int) in.get(CV_CAP_PROP_FRAME_HEIGHT)), true);
}
else
exit(1);
if(!in.isOpened()){
cerr<<"Was unable to open video input."<<endl;
}
if(!out.isOpened()){
cerr<<"Was unable to open video output."<<endl;
}
int frameNum=0;
while(true){
Mat frame(in.get(CV_CAP_PROP_FRAME_HEIGHT), in.get(CV_CAP_PROP_FRAME_WIDTH), CV_8UC3);
Mat color(frame.rows, frame.cols, CV_8UC3);
Mat thresh(color.rows, color.cols, CV_8UC3);
in.read(frame);
cvtColor(frame, color, CV_BGR2HSV, 3);
Vec3b pixel;
vector<Point> points;
for(int i=0; i<color.rows; i++){
for(int j=0; j<color.cols; j++){
pixel = color.at<Vec3b>(Point(j,i));
if( (pixel[0] > 8 && pixel[0] < 22) && (pixel[1] > 22 && pixel[1] < 60)){
points.push_back(Point(j, i));
//thresh.at<Vec3b>(Point(j, i)) = Vec3b(179, 255, 255);
}
else{
//thresh.at<Vec3b>(Point(j, i)) = Vec3b(0, 0, 0);
}
}
}
for(int k=0; k < points.size(); k++){
circle(frame, points[k], 3, Scalar(255, 0, 0), -1,CV_AA, 0);
}
out.write(frame);
if(frameNum % 100 == 0)
cout<<"FRAME "<<frameNum<<endl;
frameNum++;
}
out.release();
}
<|endoftext|>
|
<commit_before>#include "app/SimpleApp.h"
#include "sys/AbstractThread.h"
#include "sys/StopWatch.h"
#include "trace/log.h"
#include "trace/UdpBackEnd.h"
//#define PERFORMANCE_TEST 1
namespace
{
class Th1 : public ::sys::AbstractThread
{
public:
explicit Th1( const uint32_t id )
: ::sys::AbstractThread( ::std::to_string( id ).c_str() )
, m_char( 'A' + id )
{
}
private:
virtual void run()
{
uint32_t i = 200;
while ( i != 0U )
{
if ( isStopRequested() )
{
LOG_DEV_C( "Thread '%c' requested to stop on i = %u", m_char, i );
break;
}
LOG_INFO_C( "TH: %c, i = %u", m_char, i );
sleep( 5 + ( m_char * 2U ) );
--i;
}
}
const char m_char;
};
}
class DemoApp : public ::app::SimpleApp
{
public:
DemoApp()
: ::app::SimpleApp( "TraceLogDemo" )
{
}
private:
virtual int32_t onRun( const TStringVector& args )
{
#ifndef PERFORMANCE_TEST
const size_t NUM_TH = 26U;
Th1* threads[ NUM_TH ];
for ( size_t i = 0U; i < NUM_TH; i++ )
{
threads[ i ] = new Th1( i );
threads[ i ]->start();
}
if ( waitForExit( 15000U ) )
{
LOG_INFO_C( "Example running until end" );
}
else
{
LOG_WARN_C( "Example Timeout" );
}
for ( size_t i = 0U; i < NUM_TH; i++ )
{
threads[ i ]->requestStop();
threads[ i ]->join();
delete threads[ i ];
}
#else
/* Run the benchmark */
LOG_INFO_C( "Start The Benchmark" );
::sys::StopWatch sw( true );
for ( uint32_t i = 0; i < 100000; i++ )
{
LOG_INFO_C("TEST: and some text here :-)");
}
LOG_INFO_C( "Took: %u ms", sw.stop() / 1000U );
#endif // PERFORMANCE_TEST
return 0;
}
};
int32_t main( int argc, const char * const * argv )
{
LOGGER_INIT_BE_UDP;
LOG_INFO_C( "App Started: %c", 'a' );
int32_t result = ::DemoApp().run( argc, argv );
LOG_INFO_C( "App Exited: %d" , result );
LOG_INFO_C( "- bye! -" );
LOGGER_SHUTDOWN();
return result;
}
<commit_msg>Add few console traces to the example<commit_after>#include "app/SimpleApp.h"
#include "sys/AbstractThread.h"
#include "sys/StopWatch.h"
#include "trace/log.h"
#include "trace/UdpBackEnd.h"
//#define PERFORMANCE_TEST 1
namespace
{
class Th1 : public ::sys::AbstractThread
{
public:
explicit Th1( const uint32_t id )
: ::sys::AbstractThread( ::std::to_string( id ).c_str() )
, m_char( 'A' + id )
{
}
private:
virtual void run()
{
uint32_t i = 200;
while ( i != 0U )
{
if ( isStopRequested() )
{
LOG_DEV_C( "Thread '%c' requested to stop on i = %u", m_char, i );
break;
}
LOG_INFO_C( "TH: %c, i = %u", m_char, i );
sleep( 5 + ( m_char * 2U ) );
--i;
}
}
const char m_char;
};
}
class DemoApp : public ::app::SimpleApp
{
public:
DemoApp()
: ::app::SimpleApp( "TraceLogDemo" )
{
}
private:
virtual int32_t onRun( const TStringVector& args )
{
::printf( "TraceLog Demo\n" );
#ifndef PERFORMANCE_TEST
const size_t NUM_TH = 26U;
Th1* threads[ NUM_TH ];
for ( size_t i = 0U; i < NUM_TH; i++ )
{
threads[ i ] = new Th1( i );
threads[ i ]->start();
}
if ( waitForExit( 15000U ) )
{
LOG_INFO_C( "Example running until end" );
::printf( "\nReceived BREAK signal...\n" );
}
else
{
LOG_WARN_C( "Example Timeout" );
}
for ( size_t i = 0U; i < NUM_TH; i++ )
{
threads[ i ]->requestStop();
threads[ i ]->join();
delete threads[ i ];
}
#else
/* Run the benchmark */
LOG_INFO_C( "Start The Benchmark" );
::sys::StopWatch sw( true );
for ( uint32_t i = 0; i < 100000; i++ )
{
LOG_INFO_C("TEST: and some text here :-)");
}
LOG_INFO_C( "Took: %u ms", sw.stop() / 1000U );
#endif // PERFORMANCE_TEST
::printf( "Exit\n" );
return 0;
}
};
int32_t main( int argc, const char * const * argv )
{
LOGGER_INIT_BE_UDP;
LOG_INFO_C( "App Started: %c", 'a' );
int32_t result = ::DemoApp().run( argc, argv );
LOG_INFO_C( "App Exited: %d" , result );
LOG_INFO_C( "- bye! -" );
LOGGER_SHUTDOWN();
return result;
}
<|endoftext|>
|
<commit_before>/**
* * \file main.cpp
* \brief test/demo program
* \author Arthur Brainville
*
* Annwvyn test program http://annwvyn.org/
*
*/
#include "stdafx.h"
//Annwvyn
#include <Annwvyn.h>
#include "TestLevel.hpp"
#include <AnnSplashLevel.hpp>
using namespace std;
using namespace Annwvyn;
timerID demoTimer;
class MySaveTest : public AnnSaveDataInterpretor
{
public:
MySaveTest(AnnSaveFileData* data) : AnnSaveDataInterpretor(data)
{
}
AnnVect3 getPosition()
{
return pos;
}
AnnQuaternion getOrientation()
{
return orient;
}
float getPi()
{
return pi;
}
int getLives()
{
return lives;
}
virtual void extract()
{
pos = keyStringToVect3("pos");
orient = keyStringToQuaternion("orient");
pi = keyStringToFloat("PI");
lives = keyStringToInt("lives");
}
private:
AnnVect3 pos;
AnnQuaternion orient;
float pi;
int lives;
};
class DebugListener : LISTENER
{
public:
DebugListener() : constructListener()
{
}
void TimeEvent(AnnTimeEvent e)
{
AnnDebug() << "TimeEvent id : " << e.getID();
if(e.getID() == demoTimer)
AnnDebug() << "This is the demoTimer that was launched on the main function !";
}
void TriggerEvent(AnnTriggerEvent e)
{
AnnDebug() << "TriggerEvent contact status : " << e.getContactStatus() << " from " << e.getSender();
}
void testFileIO()
{
auto testFile = AnnGetFileSystemManager()->crateSaveFileDataObject("test");
testFile->setValue("KEY0", "Thing");
testFile->setValue("KEY1", "otherThing");
testFile->setValue("lives", 10);
testFile->setValue("PI", 3.14f);
testFile->setValue("pos", AnnVect3(2.5, 4.8, Ogre::Math::HALF_PI));
testFile->setValue("orient", AnnQuaternion(Ogre::Radian(Ogre::Math::HALF_PI), AnnVect3(.5, .5, .5)));
AnnFileWriter* writer(AnnGetFileSystemManager()->getFileWriter());
writer->write(testFile);
AnnFileReader* reader(AnnGetFileSystemManager()->getFileReader());
auto data = reader->read("test");
AnnDebug() << "KEY0 val : " << data->getValue("KEY0");
AnnDebug() << "KEY1 val : " << data->getValue("KEY1");
MySaveTest tester(data);
tester.extract();
AnnDebug() << "stored vector value : " << tester.getPosition();
AnnDebug() << "stored quaternion value : " << tester.getOrientation();
AnnDebug() << "stored pi value : " << tester.getPi();
AnnDebug() << "stored lives value : " << tester.getLives();
}
void KeyEvent(AnnKeyEvent e)
{
if (e.isPressed() && e.getKey() == KeyCode::h)
testFileIO();
}
};
AnnMain()
{
//Only usefull on windows : Open a debug console to get stdout/stderr
AnnEngine::openConsole();
//Init game engine
AnnInit("AnnTest");
//Init some player body parameters
AnnGetEngine()->initPlayerPhysics();
AnnGetPhysicsEngine()->setDebugPhysics(false);
AnnGetEventManager()->useDefaultEventListener();
AnnGetVRRenderer()->recenter();
AnnGetEngine()->getEventManager()->addListener(new DebugListener);
demoTimer = AnnGetEngine()->getEventManager()->fireTimer(10);
//load ressources
AnnGetResourceManager()->loadDir("media/environement");
AnnGetResourceManager()->loadDir("media/debug");
AnnGetResourceManager()->initResources();
AnnAbstractLevel* level = new TestLevel();
AnnSplashLevel* splash = new AnnSplashLevel("splash.png", level, 7.1f);
splash->setBGM("media/AnnSplash.ogg");
AnnGetEngine()->getLevelManager()->addLevel(splash);
AnnGetEngine()->getLevelManager()->addLevel(level);
AnnGetEngine()->getLevelManager()->jumpToFirstLevel();
AnnDebug() << "Starting the render loop";
do
{
if(AnnGetEngine()->isKeyDown(OIS::KC_Q))
AnnGetEngine()->getLevelManager()->unloadCurrentLevel();
if(AnnGetEngine()->isKeyDown(OIS::KC_E))
AnnGetEngine()->getLevelManager()->jumpToFirstLevel();
}
while(AnnGetEngine()->refresh());
delete AnnGetEngine();
return EXIT_SUCCESS;
}
<commit_msg>add code that test the POV in debug event of test<commit_after>/**
* * \file main.cpp
* \brief test/demo program
* \author Arthur Brainville
*
* Annwvyn test program http://annwvyn.org/
*
*/
#include "stdafx.h"
//Annwvyn
#include <Annwvyn.h>
#include "TestLevel.hpp"
#include <AnnSplashLevel.hpp>
using namespace std;
using namespace Annwvyn;
timerID demoTimer;
class MySaveTest : public AnnSaveDataInterpretor
{
public:
MySaveTest(AnnSaveFileData* data) : AnnSaveDataInterpretor(data)
{
}
AnnVect3 getPosition()
{
return pos;
}
AnnQuaternion getOrientation()
{
return orient;
}
float getPi()
{
return pi;
}
int getLives()
{
return lives;
}
virtual void extract()
{
pos = keyStringToVect3("pos");
orient = keyStringToQuaternion("orient");
pi = keyStringToFloat("PI");
lives = keyStringToInt("lives");
}
private:
AnnVect3 pos;
AnnQuaternion orient;
float pi;
int lives;
};
class DebugListener : LISTENER
{
public:
DebugListener() : constructListener()
{
}
void TimeEvent(AnnTimeEvent e)
{
AnnDebug() << "TimeEvent id : " << e.getID();
if(e.getID() == demoTimer)
AnnDebug() << "This is the demoTimer that was launched on the main function !";
}
void TriggerEvent(AnnTriggerEvent e)
{
AnnDebug() << "TriggerEvent contact status : " << e.getContactStatus() << " from " << e.getSender();
}
void testFileIO()
{
auto testFile = AnnGetFileSystemManager()->crateSaveFileDataObject("test");
testFile->setValue("KEY0", "Thing");
testFile->setValue("KEY1", "otherThing");
testFile->setValue("lives", 10);
testFile->setValue("PI", 3.14f);
testFile->setValue("pos", AnnVect3(2.5, 4.8, Ogre::Math::HALF_PI));
testFile->setValue("orient", AnnQuaternion(Ogre::Radian(Ogre::Math::HALF_PI), AnnVect3(.5, .5, .5)));
AnnFileWriter* writer(AnnGetFileSystemManager()->getFileWriter());
writer->write(testFile);
AnnFileReader* reader(AnnGetFileSystemManager()->getFileReader());
auto data = reader->read("test");
AnnDebug() << "KEY0 val : " << data->getValue("KEY0");
AnnDebug() << "KEY1 val : " << data->getValue("KEY1");
MySaveTest tester(data);
tester.extract();
AnnDebug() << "stored vector value : " << tester.getPosition();
AnnDebug() << "stored quaternion value : " << tester.getOrientation();
AnnDebug() << "stored pi value : " << tester.getPi();
AnnDebug() << "stored lives value : " << tester.getLives();
}
void KeyEvent(AnnKeyEvent e)
{
if (e.isPressed() && e.getKey() == KeyCode::h)
testFileIO();
}
void StickEvent(AnnStickEvent e)
{
if (e.getStickID() == 0)
{
AnnStickPov pov = e.getPov(0);
AnnDebug() << pov.getNorth() << pov.getSouth() << pov.getEast() << pov.getWest();
}
}
};
AnnMain()
{
//Only usefull on windows : Open a debug console to get stdout/stderr
AnnEngine::openConsole();
//Init game engine
AnnInit("AnnTest");
//Init some player body parameters
AnnGetEngine()->initPlayerPhysics();
AnnGetPhysicsEngine()->setDebugPhysics(false);
AnnGetEventManager()->useDefaultEventListener();
AnnGetVRRenderer()->recenter();
AnnGetEngine()->getEventManager()->addListener(new DebugListener);
demoTimer = AnnGetEngine()->getEventManager()->fireTimer(10);
//load ressources
AnnGetResourceManager()->loadDir("media/environement");
AnnGetResourceManager()->loadDir("media/debug");
AnnGetResourceManager()->initResources();
AnnAbstractLevel* level = new TestLevel();
AnnSplashLevel* splash = new AnnSplashLevel("splash.png", level, 7.1f);
splash->setBGM("media/AnnSplash.ogg");
AnnGetEngine()->getLevelManager()->addLevel(splash);
AnnGetEngine()->getLevelManager()->addLevel(level);
AnnGetEngine()->getLevelManager()->jumpToFirstLevel();
AnnDebug() << "Starting the render loop";
do
{
if(AnnGetEngine()->isKeyDown(OIS::KC_Q))
AnnGetEngine()->getLevelManager()->unloadCurrentLevel();
if(AnnGetEngine()->isKeyDown(OIS::KC_E))
AnnGetEngine()->getLevelManager()->jumpToFirstLevel();
}
while(AnnGetEngine()->refresh());
delete AnnGetEngine();
return EXIT_SUCCESS;
}
<|endoftext|>
|
<commit_before>/*
* Copyright(c) Sophist Solutions, Inc. 1990-2015. All rights reserved
*/
#include "../StroikaPreComp.h"
#include <thread>
#if qPlatform_POSIX
#include <unistd.h>
#include <fstream>
#elif qPlatform_Windows
#include <Windows.h>
#endif
#include "../Characters/SDKString.h"
#include "../Characters/Format.h"
#include "../Characters/String_Constant.h"
#include "../Characters/String2Int.h"
#include "../Containers/Set.h"
#if qPlatform_POSIX
#include "../Execution/ErrNoException.h"
#elif qPlatform_Windows
#include "../Execution/Platform/Windows/Exception.h"
#endif
#include "../Memory/SmallStackBuffer.h"
#include "../IO/FileSystem/BinaryFileInputStream.h"
#include "../Streams/BasicBinaryInputOutputStream.h"
#include "../Streams/TextInputStreamBinaryAdapter.h"
#include "SystemConfiguration.h"
#if qPlatform_POSIX
#include "../DataExchange/INI/Reader.h"
#include "../Execution/ProcessRunner.h"
#include "../Streams/iostream/FStreamSupport.h"
#endif
using namespace Stroika::Foundation;
using namespace Stroika::Foundation::Configuration;
using namespace Stroika::Foundation::Containers;
using namespace Stroika::Foundation::Streams;
using Characters::String_Constant;
using Characters::SDKChar;
// Comment this in to turn on aggressive noisy DbgTrace in this module
//#define USE_NOISY_TRACE_IN_THIS_MODULE_ 1
/*
********************************************************************************
***************** Configuration::SystemConfiguration::CPU **********************
********************************************************************************
*/
unsigned int SystemConfiguration::CPU::GetNumberOfSockets () const
{
Set<unsigned int> socketIds;
for (auto i : fCores) {
socketIds.Add (i.fSocketID);
}
return static_cast<unsigned int> (socketIds.size ());
}
/*
********************************************************************************
*************** Configuration::GetSystemConfiguration_CPU **********************
********************************************************************************
*/
SystemConfiguration::CPU Configuration::GetSystemConfiguration_CPU ()
{
using CPU = SystemConfiguration::CPU;
CPU result;
#if qPlatform_POSIX
{
using Streams::TextInputStreamBinaryAdapter;
using IO::FileSystem::BinaryFileInputStream;
using Characters::String2Int;
const String_Constant kProcCPUInfoFileName_ { L"/proc/cpuinfo" };
CPU::CoreDetails coreDetails;
// Note - /procfs files always unseekable
for (String line : TextInputStreamBinaryAdapter (BinaryFileInputStream::mk (kProcCPUInfoFileName_, BinaryFileInputStream::eNotSeekable)).ReadLines ()) {
#if USE_NOISY_TRACE_IN_THIS_MODULE_
DbgTrace (L"***in Configuration::GetSystemConfiguration_CPU capture_ line=%s", line.c_str ());
#endif
static const String_Constant kModelNameLabel_ { L"model name : " };
//static const String_Constant kProcessorIDLabel_ { L"processor : " };
static const String_Constant kSocketIDLabel_ { L"physical id : " }; // a bit of a guess?
if (line.StartsWith (kModelNameLabel_)) {
coreDetails.fModelName = line.SubString (kModelNameLabel_.length ()).Trim ();
}
else if (line.StartsWith (kSocketIDLabel_)) {
unsigned int socketID = String2Int<unsigned int> (line.SubString (kSocketIDLabel_.length ()).Trim ());
coreDetails.fSocketID = socketID;
}
if (line.Trim ().empty ()) {
// ends each socket
result.fCores.Append (coreDetails);
coreDetails = CPU::CoreDetails ();
}
}
if (coreDetails.fSocketID != 0 or not coreDetails.fModelName.empty ()) {
result.fCores.Append (coreDetails);
}
}
#elif qPlatform_Windows
SYSTEM_INFO sysInfo; // GetNativeSystemInfo cannot fail so no need to initialize data
::GetNativeSystemInfo (&sysInfo);
//unclear if this is count of logical or physical cores, or how to compute the other.
//@todo - fix as above for POSIX... maybe ask Sterl? But for now KISS
//
// Can use https://msdn.microsoft.com/en-us/library/hskdteyh%28v=vs.90%29.aspx?f=255&MSPPError=-2147217396
// __cpuid
// to find this information (at least modelname string.
//
for (DWORD i = 0; i < sysInfo.dwNumberOfProcessors; ++i) {
result.fCores.Append (CPU::CoreDetails ());
}
#endif
return result;
}
/*
********************************************************************************
************** Configuration::GetSystemConfiguration_Memory ********************
********************************************************************************
*/
SystemConfiguration::Memory Configuration::GetSystemConfiguration_Memory ()
{
using Memory = SystemConfiguration::Memory;
Memory result;
#if qPlatform_POSIX
result.fPageSize = ::sysconf (_SC_PAGESIZE);
result.fTotalPhysicalRAM = ::sysconf (_SC_PHYS_PAGES) * result.fPageSize;
#elif qPlatform_Windows
SYSTEM_INFO sysInfo;
::GetNativeSystemInfo (&sysInfo);
result.fPageSize = sysInfo.dwPageSize;
MEMORYSTATUSEX memStatus;
memStatus.dwLength = sizeof (memStatus);
Verify (::GlobalMemoryStatusEx (&memStatus));
result.fTotalPhysicalRAM = memStatus.ullTotalPhys;
result.fTotalVirtualRAM = memStatus.ullTotalVirtual;
#endif
return result;
}
/*
********************************************************************************
******** Configuration::GetSystemConfiguration_OperatingSystem *****************
********************************************************************************
*/
SystemConfiguration::OperatingSystem Configuration::GetSystemConfiguration_OperatingSystem ()
{
using OperatingSystem = SystemConfiguration::OperatingSystem;
static const OperatingSystem kCachedResult_ = []() ->OperatingSystem {
OperatingSystem tmp;
#if qPlatform_POSIX
tmp.fTokenName = String_Constant (L"Unix");
try {
tmp.fTokenName = Execution::ProcessRunner (L"uname").Run (String ()).Trim ();
}
catch (...)
{
DbgTrace ("Failure running uname");
}
try {
ifstream s;
Streams::iostream::OpenInputFileStream (&s, L"/etc/os-release");
DataExchange::INI::Profile p = DataExchange::INI::Reader ().ReadProfile (s);
tmp.fShortPrettyName = p.fUnnamedSection.fProperties.LookupValue (L"NAME");
tmp.fPrettyNameWithMajorVersion = p.fUnnamedSection.fProperties.LookupValue (L"PRETTY_NAME");
}
catch (...)
{
DbgTrace ("Failure reading /etc/os-release");
}
if (tmp.fShortPrettyName.empty ())
{
tmp.fShortPrettyName = tmp.fTokenName;
}
if (tmp.fPrettyNameWithMajorVersion.empty ())
{
tmp.fPrettyNameWithMajorVersion = tmp.fShortPrettyName;
}
if (tmp.fRFC1945CompatProductTokenWithVersion.empty ())
{
tmp.fRFC1945CompatProductTokenWithVersion = tmp.fShortPrettyName.Trim ().ReplaceAll (L" ", L"-");
if (not tmp.fMajorMinorVersionString.empty ()) {
tmp.fRFC1945CompatProductTokenWithVersion += L"/" + tmp.fMajorMinorVersionString;
}
}
//
// @todo FIX/FIND BETTER WAY!
//
//http://docs.oracle.com/cd/E36784_01/html/E36874/sysconf-3c.html
// Quite uncertain - this is not a good reference
// --LGP 2014-10-18
//
tmp.fBits = ::sysconf (_SC_V6_LP64_OFF64) == _POSIX_V6_LP64_OFF64 ? 64 : 32;
#elif qPlatform_Windows
tmp.fTokenName = String_Constant (L"Windows");
/*
* Microslop declares this deprecated, but then fails to provide a reasonable alternative.
*
* Sigh.
*
* http://msdn.microsoft.com/en-us/library/windows/desktop/ms724429(v=vs.85).aspx - GetFileVersionInfo (kernel32.dll)
* is a painful, and stupid alternative.
*/
DISABLE_COMPILER_MSC_WARNING_START(4996)
OSVERSIONINFOEX osvi;
memset(&osvi, 0, sizeof (osvi));
osvi.dwOSVersionInfoSize = sizeof (osvi);
Verify (::GetVersionEx (reinterpret_cast<LPOSVERSIONINFO> (&osvi)));
DISABLE_COMPILER_MSC_WARNING_END(4996)
if (osvi.dwMajorVersion == 6)
{
if (osvi.dwMinorVersion == 0) {
tmp.fShortPrettyName = osvi.wProductType == VER_NT_WORKSTATION ? String_Constant (L"Windows Vista") : String_Constant (L"Windows Server 2008");
}
else if (osvi.dwMinorVersion == 1) {
tmp.fShortPrettyName = osvi.wProductType == VER_NT_WORKSTATION ? String_Constant (L"Windows 7") : String_Constant (L"Windows Server 2008 R2");
}
else if (osvi.dwMinorVersion == 2) {
tmp.fShortPrettyName = osvi.wProductType == VER_NT_WORKSTATION ? String_Constant (L"Windows 8") : String_Constant (L"Windows Server 2012");
}
else if (osvi.dwMinorVersion == 3) {
if (osvi.wProductType == VER_NT_WORKSTATION)
tmp.fShortPrettyName = String_Constant (L"Windows 8.1");
}
}
if (tmp.fShortPrettyName.empty ())
{
tmp.fShortPrettyName = Characters::Format (L"Windows %d.%d", osvi.dwMajorVersion, osvi.dwMinorVersion);
}
tmp.fPrettyNameWithMajorVersion = tmp.fShortPrettyName;
tmp.fMajorMinorVersionString = Characters::Format (L"%d.%d", osvi.dwMajorVersion, osvi.dwMinorVersion);
tmp.fRFC1945CompatProductTokenWithVersion = Characters::Format (L"Windows/%d.%d", osvi.dwMajorVersion, osvi.dwMinorVersion);
if (sizeof (void*) == 4)
{
tmp.fBits = 32;
//IsWow64Process is not available on all supported versions of Windows.
//Use GetModuleHandle to get a handle to the DLL that contains the function
//and GetProcAddress to get a pointer to the function if available.
typedef BOOL (WINAPI * LPFN_ISWOW64PROCESS) (HANDLE, PBOOL);
LPFN_ISWOW64PROCESS fnIsWow64Process = (LPFN_ISWOW64PROCESS) GetProcAddress(GetModuleHandle(TEXT("kernel32")), "IsWow64Process");
if(NULL != fnIsWow64Process) {
BOOL isWOW64 = false;
(void)fnIsWow64Process (GetCurrentProcess(), &isWOW64);
if (isWOW64) {
tmp.fBits = 64;
}
}
}
else {
// In windows, a 64 bit app cannot run on 32-bit windows
Assert (sizeof (void*) == 8);
tmp.fBits = 64;
}
#else
AssertNotImplemented ();
#endif
return tmp;
} ();
return kCachedResult_;
}
/*
********************************************************************************
***************** GetSystemConfiguration_ComputerNames *************************
********************************************************************************
*/
#if 0 && qPlatform_POSIX
// ALTERNATE APPROACH TO CONSIDER
string name;
{
struct addrinfo* res;
struct addrinfo hints;
memset(&hints, '\0', sizeof(hints));
hints.ai_socktype = SOCK_STREAM;
hints.ai_flags = AI_CANONNAME;
int e = getaddrinfo(nullptr, nullptr, &hints, &res);
if (e != 0) {
//printf("failure %s\n", gai_strerror (e));
return String ();
}
int sock = -1;
for (struct addrinfo* r = res; r != NULL; r = r->ai_next) {
name = r->ai_canonname ;
break;
}
freeaddrinfo(res);
}
return String::FromSDKString (name);
#endif
SystemConfiguration::ComputerNames Configuration::GetSystemConfiguration_ComputerNames ()
{
using ComputerNames = SystemConfiguration::ComputerNames;
ComputerNames result;
#if qPlatform_POSIX
char nameBuf[1024];
Execution::ThrowErrNoIfNegative (gethostname (nameBuf, NEltsOf (nameBuf)));
nameBuf[NEltsOf (nameBuf) - 1] = '\0'; // http://linux.die.net/man/2/gethostname says not necessarily nul-terminated
result.fHostname = String::FromNarrowSDKString (nameBuf);
#elif qPlatform_Windows
constexpr COMPUTER_NAME_FORMAT kUseNameFormat_ = ComputerNameNetBIOS; // total WAG -- LGP 2014-10-10
DWORD dwSize = 0;
(void) ::GetComputerNameEx (kUseNameFormat_, nullptr, &dwSize);
Memory::SmallStackBuffer<SDKChar> buf(dwSize);
Execution::Platform::Windows::ThrowIfFalseGetLastError (::GetComputerNameEx (kUseNameFormat_, buf, &dwSize));
result.fHostname = String::FromSDKString (buf);
#else
AssertNotImplemented ();
#endif
return result;
}
/*
********************************************************************************
****************** SystemConfiguration GetSystemConfiguration ******************
********************************************************************************
*/
inline SystemConfiguration Configuration::GetSystemConfiguration ()
{
return SystemConfiguration {
GetSystemConfiguration_CPU (),
GetSystemConfiguration_Memory (),
GetSystemConfiguration_OperatingSystem (),
GetSystemConfiguration_ComputerNames ()
};
}
<commit_msg>fixed typo in Configuration::GetSystemConfiguration ()<commit_after>/*
* Copyright(c) Sophist Solutions, Inc. 1990-2015. All rights reserved
*/
#include "../StroikaPreComp.h"
#include <thread>
#if qPlatform_POSIX
#include <unistd.h>
#include <fstream>
#elif qPlatform_Windows
#include <Windows.h>
#endif
#include "../Characters/SDKString.h"
#include "../Characters/Format.h"
#include "../Characters/String_Constant.h"
#include "../Characters/String2Int.h"
#include "../Containers/Set.h"
#if qPlatform_POSIX
#include "../Execution/ErrNoException.h"
#elif qPlatform_Windows
#include "../Execution/Platform/Windows/Exception.h"
#endif
#include "../Memory/SmallStackBuffer.h"
#include "../IO/FileSystem/BinaryFileInputStream.h"
#include "../Streams/BasicBinaryInputOutputStream.h"
#include "../Streams/TextInputStreamBinaryAdapter.h"
#include "SystemConfiguration.h"
#if qPlatform_POSIX
#include "../DataExchange/INI/Reader.h"
#include "../Execution/ProcessRunner.h"
#include "../Streams/iostream/FStreamSupport.h"
#endif
using namespace Stroika::Foundation;
using namespace Stroika::Foundation::Configuration;
using namespace Stroika::Foundation::Containers;
using namespace Stroika::Foundation::Streams;
using Characters::String_Constant;
using Characters::SDKChar;
// Comment this in to turn on aggressive noisy DbgTrace in this module
//#define USE_NOISY_TRACE_IN_THIS_MODULE_ 1
/*
********************************************************************************
***************** Configuration::SystemConfiguration::CPU **********************
********************************************************************************
*/
unsigned int SystemConfiguration::CPU::GetNumberOfSockets () const
{
Set<unsigned int> socketIds;
for (auto i : fCores) {
socketIds.Add (i.fSocketID);
}
return static_cast<unsigned int> (socketIds.size ());
}
/*
********************************************************************************
*************** Configuration::GetSystemConfiguration_CPU **********************
********************************************************************************
*/
SystemConfiguration::CPU Configuration::GetSystemConfiguration_CPU ()
{
using CPU = SystemConfiguration::CPU;
CPU result;
#if qPlatform_POSIX
{
using Streams::TextInputStreamBinaryAdapter;
using IO::FileSystem::BinaryFileInputStream;
using Characters::String2Int;
const String_Constant kProcCPUInfoFileName_ { L"/proc/cpuinfo" };
CPU::CoreDetails coreDetails;
// Note - /procfs files always unseekable
for (String line : TextInputStreamBinaryAdapter (BinaryFileInputStream::mk (kProcCPUInfoFileName_, BinaryFileInputStream::eNotSeekable)).ReadLines ()) {
#if USE_NOISY_TRACE_IN_THIS_MODULE_
DbgTrace (L"***in Configuration::GetSystemConfiguration_CPU capture_ line=%s", line.c_str ());
#endif
static const String_Constant kModelNameLabel_ { L"model name : " };
//static const String_Constant kProcessorIDLabel_ { L"processor : " };
static const String_Constant kSocketIDLabel_ { L"physical id : " }; // a bit of a guess?
if (line.StartsWith (kModelNameLabel_)) {
coreDetails.fModelName = line.SubString (kModelNameLabel_.length ()).Trim ();
}
else if (line.StartsWith (kSocketIDLabel_)) {
unsigned int socketID = String2Int<unsigned int> (line.SubString (kSocketIDLabel_.length ()).Trim ());
coreDetails.fSocketID = socketID;
}
if (line.Trim ().empty ()) {
// ends each socket
result.fCores.Append (coreDetails);
coreDetails = CPU::CoreDetails ();
}
}
if (coreDetails.fSocketID != 0 or not coreDetails.fModelName.empty ()) {
result.fCores.Append (coreDetails);
}
}
#elif qPlatform_Windows
SYSTEM_INFO sysInfo; // GetNativeSystemInfo cannot fail so no need to initialize data
::GetNativeSystemInfo (&sysInfo);
//unclear if this is count of logical or physical cores, or how to compute the other.
//@todo - fix as above for POSIX... maybe ask Sterl? But for now KISS
//
// Can use https://msdn.microsoft.com/en-us/library/hskdteyh%28v=vs.90%29.aspx?f=255&MSPPError=-2147217396
// __cpuid
// to find this information (at least modelname string.
//
for (DWORD i = 0; i < sysInfo.dwNumberOfProcessors; ++i) {
result.fCores.Append (CPU::CoreDetails ());
}
#endif
return result;
}
/*
********************************************************************************
************** Configuration::GetSystemConfiguration_Memory ********************
********************************************************************************
*/
SystemConfiguration::Memory Configuration::GetSystemConfiguration_Memory ()
{
using Memory = SystemConfiguration::Memory;
Memory result;
#if qPlatform_POSIX
result.fPageSize = ::sysconf (_SC_PAGESIZE);
result.fTotalPhysicalRAM = ::sysconf (_SC_PHYS_PAGES) * result.fPageSize;
#elif qPlatform_Windows
SYSTEM_INFO sysInfo;
::GetNativeSystemInfo (&sysInfo);
result.fPageSize = sysInfo.dwPageSize;
MEMORYSTATUSEX memStatus;
memStatus.dwLength = sizeof (memStatus);
Verify (::GlobalMemoryStatusEx (&memStatus));
result.fTotalPhysicalRAM = memStatus.ullTotalPhys;
result.fTotalVirtualRAM = memStatus.ullTotalVirtual;
#endif
return result;
}
/*
********************************************************************************
******** Configuration::GetSystemConfiguration_OperatingSystem *****************
********************************************************************************
*/
SystemConfiguration::OperatingSystem Configuration::GetSystemConfiguration_OperatingSystem ()
{
using OperatingSystem = SystemConfiguration::OperatingSystem;
static const OperatingSystem kCachedResult_ = []() ->OperatingSystem {
OperatingSystem tmp;
#if qPlatform_POSIX
tmp.fTokenName = String_Constant (L"Unix");
try {
tmp.fTokenName = Execution::ProcessRunner (L"uname").Run (String ()).Trim ();
}
catch (...)
{
DbgTrace ("Failure running uname");
}
try {
ifstream s;
Streams::iostream::OpenInputFileStream (&s, L"/etc/os-release");
DataExchange::INI::Profile p = DataExchange::INI::Reader ().ReadProfile (s);
tmp.fShortPrettyName = p.fUnnamedSection.fProperties.LookupValue (L"NAME");
tmp.fPrettyNameWithMajorVersion = p.fUnnamedSection.fProperties.LookupValue (L"PRETTY_NAME");
}
catch (...)
{
DbgTrace ("Failure reading /etc/os-release");
}
if (tmp.fShortPrettyName.empty ())
{
tmp.fShortPrettyName = tmp.fTokenName;
}
if (tmp.fPrettyNameWithMajorVersion.empty ())
{
tmp.fPrettyNameWithMajorVersion = tmp.fShortPrettyName;
}
if (tmp.fRFC1945CompatProductTokenWithVersion.empty ())
{
tmp.fRFC1945CompatProductTokenWithVersion = tmp.fShortPrettyName.Trim ().ReplaceAll (L" ", L"-");
if (not tmp.fMajorMinorVersionString.empty ()) {
tmp.fRFC1945CompatProductTokenWithVersion += L"/" + tmp.fMajorMinorVersionString;
}
}
//
// @todo FIX/FIND BETTER WAY!
//
//http://docs.oracle.com/cd/E36784_01/html/E36874/sysconf-3c.html
// Quite uncertain - this is not a good reference
// --LGP 2014-10-18
//
tmp.fBits = ::sysconf (_SC_V6_LP64_OFF64) == _POSIX_V6_LP64_OFF64 ? 64 : 32;
#elif qPlatform_Windows
tmp.fTokenName = String_Constant (L"Windows");
/*
* Microslop declares this deprecated, but then fails to provide a reasonable alternative.
*
* Sigh.
*
* http://msdn.microsoft.com/en-us/library/windows/desktop/ms724429(v=vs.85).aspx - GetFileVersionInfo (kernel32.dll)
* is a painful, and stupid alternative.
*/
DISABLE_COMPILER_MSC_WARNING_START(4996)
OSVERSIONINFOEX osvi;
memset(&osvi, 0, sizeof (osvi));
osvi.dwOSVersionInfoSize = sizeof (osvi);
Verify (::GetVersionEx (reinterpret_cast<LPOSVERSIONINFO> (&osvi)));
DISABLE_COMPILER_MSC_WARNING_END(4996)
if (osvi.dwMajorVersion == 6)
{
if (osvi.dwMinorVersion == 0) {
tmp.fShortPrettyName = osvi.wProductType == VER_NT_WORKSTATION ? String_Constant (L"Windows Vista") : String_Constant (L"Windows Server 2008");
}
else if (osvi.dwMinorVersion == 1) {
tmp.fShortPrettyName = osvi.wProductType == VER_NT_WORKSTATION ? String_Constant (L"Windows 7") : String_Constant (L"Windows Server 2008 R2");
}
else if (osvi.dwMinorVersion == 2) {
tmp.fShortPrettyName = osvi.wProductType == VER_NT_WORKSTATION ? String_Constant (L"Windows 8") : String_Constant (L"Windows Server 2012");
}
else if (osvi.dwMinorVersion == 3) {
if (osvi.wProductType == VER_NT_WORKSTATION)
tmp.fShortPrettyName = String_Constant (L"Windows 8.1");
}
}
if (tmp.fShortPrettyName.empty ())
{
tmp.fShortPrettyName = Characters::Format (L"Windows %d.%d", osvi.dwMajorVersion, osvi.dwMinorVersion);
}
tmp.fPrettyNameWithMajorVersion = tmp.fShortPrettyName;
tmp.fMajorMinorVersionString = Characters::Format (L"%d.%d", osvi.dwMajorVersion, osvi.dwMinorVersion);
tmp.fRFC1945CompatProductTokenWithVersion = Characters::Format (L"Windows/%d.%d", osvi.dwMajorVersion, osvi.dwMinorVersion);
if (sizeof (void*) == 4)
{
tmp.fBits = 32;
//IsWow64Process is not available on all supported versions of Windows.
//Use GetModuleHandle to get a handle to the DLL that contains the function
//and GetProcAddress to get a pointer to the function if available.
typedef BOOL (WINAPI * LPFN_ISWOW64PROCESS) (HANDLE, PBOOL);
LPFN_ISWOW64PROCESS fnIsWow64Process = (LPFN_ISWOW64PROCESS) GetProcAddress(GetModuleHandle(TEXT("kernel32")), "IsWow64Process");
if(NULL != fnIsWow64Process) {
BOOL isWOW64 = false;
(void)fnIsWow64Process (GetCurrentProcess(), &isWOW64);
if (isWOW64) {
tmp.fBits = 64;
}
}
}
else {
// In windows, a 64 bit app cannot run on 32-bit windows
Assert (sizeof (void*) == 8);
tmp.fBits = 64;
}
#else
AssertNotImplemented ();
#endif
return tmp;
} ();
return kCachedResult_;
}
/*
********************************************************************************
***************** GetSystemConfiguration_ComputerNames *************************
********************************************************************************
*/
#if 0 && qPlatform_POSIX
// ALTERNATE APPROACH TO CONSIDER
string name;
{
struct addrinfo* res;
struct addrinfo hints;
memset(&hints, '\0', sizeof(hints));
hints.ai_socktype = SOCK_STREAM;
hints.ai_flags = AI_CANONNAME;
int e = getaddrinfo(nullptr, nullptr, &hints, &res);
if (e != 0) {
//printf("failure %s\n", gai_strerror (e));
return String ();
}
int sock = -1;
for (struct addrinfo* r = res; r != NULL; r = r->ai_next) {
name = r->ai_canonname ;
break;
}
freeaddrinfo(res);
}
return String::FromSDKString (name);
#endif
SystemConfiguration::ComputerNames Configuration::GetSystemConfiguration_ComputerNames ()
{
using ComputerNames = SystemConfiguration::ComputerNames;
ComputerNames result;
#if qPlatform_POSIX
char nameBuf[1024];
Execution::ThrowErrNoIfNegative (gethostname (nameBuf, NEltsOf (nameBuf)));
nameBuf[NEltsOf (nameBuf) - 1] = '\0'; // http://linux.die.net/man/2/gethostname says not necessarily nul-terminated
result.fHostname = String::FromNarrowSDKString (nameBuf);
#elif qPlatform_Windows
constexpr COMPUTER_NAME_FORMAT kUseNameFormat_ = ComputerNameNetBIOS; // total WAG -- LGP 2014-10-10
DWORD dwSize = 0;
(void) ::GetComputerNameEx (kUseNameFormat_, nullptr, &dwSize);
Memory::SmallStackBuffer<SDKChar> buf(dwSize);
Execution::Platform::Windows::ThrowIfFalseGetLastError (::GetComputerNameEx (kUseNameFormat_, buf, &dwSize));
result.fHostname = String::FromSDKString (buf);
#else
AssertNotImplemented ();
#endif
return result;
}
/*
********************************************************************************
****************** SystemConfiguration GetSystemConfiguration ******************
********************************************************************************
*/
SystemConfiguration Configuration::GetSystemConfiguration ()
{
return SystemConfiguration {
GetSystemConfiguration_CPU (),
GetSystemConfiguration_Memory (),
GetSystemConfiguration_OperatingSystem (),
GetSystemConfiguration_ComputerNames ()
};
}
<|endoftext|>
|
<commit_before><commit_msg>update AddTask for MC<commit_after><|endoftext|>
|
<commit_before>/*
* Copyright (C) 2010 Toni Gundogdu.
*
* 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 "config.h"
#include <iomanip>
#include <cstdio>
#include <ctime>
#ifdef HAVE_UNISTD_H
#include <unistd.h>
#endif
#ifdef HAVE_SYS_TYPES_H
#include <sys/types.h>
#endif
#ifdef HAVE_SIGNAL_H
#include <signal.h>
#endif
#ifdef HAVE_SYS_IOCTL_H
#include <sys/ioctl.h>
#endif
#include <boost/filesystem.hpp>
#include <boost/date_time/posix_time/posix_time.hpp>
#include "quvicpp/quvicpp.h"
#include "cclive/options.h"
#include "cclive/file.h"
#include "cclive/log.h"
#include "cclive/progressbar.h"
#if defined(SIGWINCH) && defined(TIOCGWINSZ)
#define WITH_RESIZE
#endif
namespace cclive {
#ifdef WITH_RESIZE
static volatile sig_atomic_t recv_sigwinch;
static void
handle_sigwinch (int s) {
recv_sigwinch = 1;
signal(SIGWINCH, handle_sigwinch);
}
static size_t
get_term_width () {
const int fd = fileno (stderr);
winsize wsz;
if (ioctl (fd, TIOCGWINSZ, &wsz) < 0)
return 0;
return wsz.ws_col;
}
#endif // WITH_RESIZE
namespace po = boost::program_options;
progressbar::progressbar (
const file& f,
const quvicpp::link& l,
const options& opts)
: _update_interval (.2),
_expected_bytes (l.length ()),
_initial_bytes (f.initial_length ()),
_time_started (0),
_last_update (0),
_term_width (0),
_dot_count (0),
_old_width (0),
_count (0),
_width (0),
_file (f),
_done (false),
_mode (normal)
{
if (_initial_bytes > _expected_bytes)
_expected_bytes = _initial_bytes;
#ifdef WITH_RESIZE
signal (SIGWINCH, handle_sigwinch);
if (!_term_width || recv_sigwinch) {
_term_width = get_term_width ();
if (!_term_width)
_term_width = default_term_width;
}
#else
_term_width = default_term_width;
#endif
_width = _term_width-1; // Don't use the last column.
_old_width = _width;
time (&_time_started);
const po::variables_map map = opts.map ();
if (map.count ("background")) {
cclive::log << _file.to_s (l) << std::endl;
_mode = dotline;
}
_update_interval = map["update-interval"].as<double>();
}
static double
to_mb (const double bytes) { return bytes/(1024*1024); }
namespace pt = boost::posix_time;
static std::string
to_s (const int secs) {
pt::time_duration td = pt::seconds (secs);
return pt::to_simple_string (td);
}
static std::string
to_unit (double& rate) {
int i = 0;
if (rate < 1024*1024) {
rate /= 1024;
}
else if (rate < 1024*1024) {
rate /= 1024*1024;
i = 1;
}
else if (rate < 1024*1024*1024) {
rate /= 1024*1024*1024;
i = 2;
}
static const char *units[] = {"K/s", "M/s", "G/s"};
return units[i];
}
namespace fs = boost::filesystem;
void
progressbar::update (double now) {
time_t tnow;
time (&tnow);
const time_t elapsed = tnow - _time_started;
bool force_update = false;
#ifdef WITH_RESIZE
if (recv_sigwinch && _mode == normal) {
const size_t old_term_width = _term_width;
_term_width = get_term_width ();
if (!_term_width)
_term_width = default_term_width;
if (_term_width != old_term_width) {
_old_width = _width;
_width = _term_width - 1; // Do not use the last column.
force_update = true;
}
recv_sigwinch = 0;
}
#endif // WITH_RESIZE
if (!_done) {
if ((elapsed - _last_update) < _update_interval
&& !force_update)
{
return;
}
}
else
now = _expected_bytes;
// Current size.
const double size =
(!_done)
? _initial_bytes + now
: now;
std::stringstream size_s;
size_s.setf (std::ios::fixed);
size_s
<< std::setprecision (1)
<< to_mb (size)
<< "M";
// Rate.
double rate = elapsed ? (now/elapsed):0;
std::stringstream rate_s, eta_s;
rate_s.setf (std::ios::fixed);
eta_s.setf (std::ios::fixed);
if (rate > 0) {
// ETA.
std::string eta;
if (!_done) {
const double left =
(_expected_bytes - (now + _initial_bytes)) / rate;
eta = to_s (static_cast<int>(left+0.5));
}
else {
rate = (_expected_bytes - _initial_bytes) / elapsed;
eta = to_s (elapsed);
}
std::string unit = to_unit (rate);
rate_s
<< std::setw (4)
<< std::setprecision (1)
<< rate
<< unit;
eta_s
<< std::setw (6)
<< eta;
}
else { // ETA: inactive (default).
rate_s << "--.-K/s";
eta_s << "--:--:--";
}
// Percent.
std::stringstream percent_s;
if (_expected_bytes > 0) {
const int percent =
static_cast<int>(100.0*size/_expected_bytes);
if (percent < 100)
percent_s << std::setw(2) << percent << "%";
else
percent_s << "100%";
}
// Filename.
fs::path p = fs::system_complete (_file.path ());
std::string fname = p.filename ();
switch (_mode) {
default:
case normal: _normal (size_s, rate_s, eta_s, percent_s, fname); break;
case dotline: _dotline (size_s, rate_s, eta_s, percent_s, fname); break;
}
_last_update = elapsed;
_count = now;
}
void
progressbar::_normal (
const std::stringstream& size_s,
const std::stringstream& rate_s,
const std::stringstream& eta_s,
const std::stringstream& percent_s,
const std::string& fname)
{
std::stringstream tmp;
tmp.setf (std::ios::fixed);
// Size.
tmp << " "
<< std::setw (4)
<< size_s.str ();
// Rate, ETA.
tmp << " "
<< rate_s.str ()
<< " "
<< eta_s.str ();
// Percent.
tmp << " "
<< percent_s.str ();
// Filename. Slice and dice.
const size_t tmp_len = tmp.str ().length ();
const int sub_len = _width - tmp_len;
std::stringstream b;
if (sub_len > 0) {
b << fname.substr (0, sub_len);
// Pad to max. terminal width (filename <-> other details).
while (b.str ().length () < (_width - tmp_len))
b << " ";
b << tmp.str ();
}
// Clear the last column if the terminal shrunk.
if (_old_width > _width) {
_old_width = _width;
b << " ";
}
// Print.
cclive::log << b.str () << "\r" << std::flush;
}
void
progressbar::_dotline (
const std::stringstream& size_s,
const std::stringstream& rate_s,
const std::stringstream& eta_s,
const std::stringstream& percent_s,
const std::string& fname)
{
if (++_dot_count >= 31) {
cclive::log
<< " "
<< std::setw (6)
<< size_s.str ()
<< " "
<< rate_s.str ()
<< " "
<< eta_s.str ()
<< " "
<< percent_s.str ()
<< std::endl;
_dot_count = 0;
}
else {
cclive::log << "." << (_dot_count % 3 == 0 ? " ":"") << std::flush;
}
}
void
progressbar::finish () {
if (_expected_bytes > 0
&& _count + _initial_bytes > _expected_bytes)
{
_expected_bytes = _initial_bytes + _count;
}
_done = true;
update (-1);
}
} // End namespace.
<commit_msg>progressbar, improve line clearing<commit_after>/*
* Copyright (C) 2010 Toni Gundogdu.
*
* 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 "config.h"
#include <iomanip>
#include <cstdio>
#include <ctime>
#ifdef HAVE_UNISTD_H
#include <unistd.h>
#endif
#ifdef HAVE_SYS_TYPES_H
#include <sys/types.h>
#endif
#ifdef HAVE_SIGNAL_H
#include <signal.h>
#endif
#ifdef HAVE_SYS_IOCTL_H
#include <sys/ioctl.h>
#endif
#include <boost/filesystem.hpp>
#include <boost/date_time/posix_time/posix_time.hpp>
#include "quvicpp/quvicpp.h"
#include "cclive/options.h"
#include "cclive/file.h"
#include "cclive/log.h"
#include "cclive/progressbar.h"
#if defined(SIGWINCH) && defined(TIOCGWINSZ)
#define WITH_RESIZE
#endif
namespace cclive {
#ifdef WITH_RESIZE
static volatile sig_atomic_t recv_sigwinch;
static void
handle_sigwinch (int s) {
recv_sigwinch = 1;
signal(SIGWINCH, handle_sigwinch);
}
static size_t
get_term_width () {
const int fd = fileno (stderr);
winsize wsz;
if (ioctl (fd, TIOCGWINSZ, &wsz) < 0)
return 0;
return wsz.ws_col;
}
#endif // WITH_RESIZE
namespace po = boost::program_options;
progressbar::progressbar (
const file& f,
const quvicpp::link& l,
const options& opts)
: _update_interval (.2),
_expected_bytes (l.length ()),
_initial_bytes (f.initial_length ()),
_time_started (0),
_last_update (0),
_term_width (0),
_dot_count (0),
_old_width (0),
_count (0),
_width (0),
_file (f),
_done (false),
_mode (normal)
{
if (_initial_bytes > _expected_bytes)
_expected_bytes = _initial_bytes;
#ifdef WITH_RESIZE
signal (SIGWINCH, handle_sigwinch);
if (!_term_width || recv_sigwinch) {
_term_width = get_term_width ();
if (!_term_width)
_term_width = default_term_width;
}
#else
_term_width = default_term_width;
#endif
_width = _term_width-1; // Don't use the last column.
_old_width = _width;
time (&_time_started);
const po::variables_map map = opts.map ();
if (map.count ("background")) {
cclive::log << _file.to_s (l) << std::endl;
_mode = dotline;
}
_update_interval = map["update-interval"].as<double>();
}
static double
to_mb (const double bytes) { return bytes/(1024*1024); }
namespace pt = boost::posix_time;
static std::string
to_s (const int secs) {
pt::time_duration td = pt::seconds (secs);
return pt::to_simple_string (td);
}
static std::string
to_unit (double& rate) {
int i = 0;
if (rate < 1024*1024) {
rate /= 1024;
}
else if (rate < 1024*1024) {
rate /= 1024*1024;
i = 1;
}
else if (rate < 1024*1024*1024) {
rate /= 1024*1024*1024;
i = 2;
}
static const char *units[] = {"K/s", "M/s", "G/s"};
return units[i];
}
namespace fs = boost::filesystem;
void
progressbar::update (double now) {
time_t tnow;
time (&tnow);
const time_t elapsed = tnow - _time_started;
bool force_update = false;
#ifdef WITH_RESIZE
if (recv_sigwinch && _mode == normal) {
const size_t old_term_width = _term_width;
_term_width = get_term_width ();
if (!_term_width)
_term_width = default_term_width;
if (_term_width != old_term_width) {
_old_width = _width;
_width = _term_width - 1; // Do not use the last column.
force_update = true;
}
recv_sigwinch = 0;
}
#endif // WITH_RESIZE
if (!_done) {
if ((elapsed - _last_update) < _update_interval
&& !force_update)
{
return;
}
}
else
now = _expected_bytes;
// Current size.
const double size =
(!_done)
? _initial_bytes + now
: now;
std::stringstream size_s;
size_s.setf (std::ios::fixed);
size_s
<< std::setprecision (1)
<< to_mb (size)
<< "M";
// Rate.
double rate = elapsed ? (now/elapsed):0;
std::stringstream rate_s, eta_s;
rate_s.setf (std::ios::fixed);
eta_s.setf (std::ios::fixed);
if (rate > 0) {
// ETA.
std::string eta;
if (!_done) {
const double left =
(_expected_bytes - (now + _initial_bytes)) / rate;
eta = to_s (static_cast<int>(left+0.5));
}
else {
rate = (_expected_bytes - _initial_bytes) / elapsed;
eta = to_s (elapsed);
}
std::string unit = to_unit (rate);
rate_s
<< std::setw (4)
<< std::setprecision (1)
<< rate
<< unit;
eta_s
<< std::setw (6)
<< eta;
}
else { // ETA: inactive (default).
rate_s << "--.-K/s";
eta_s << "--:--:--";
}
// Percent.
std::stringstream percent_s;
if (_expected_bytes > 0) {
const int percent =
static_cast<int>(100.0*size/_expected_bytes);
if (percent < 100)
percent_s << std::setw(2) << percent << "%";
else
percent_s << "100%";
}
// Filename.
fs::path p = fs::system_complete (_file.path ());
std::string fname = p.filename ();
switch (_mode) {
default:
case normal: _normal (size_s, rate_s, eta_s, percent_s, fname); break;
case dotline: _dotline (size_s, rate_s, eta_s, percent_s, fname); break;
}
_last_update = elapsed;
_count = now;
}
void
progressbar::_normal (
const std::stringstream& size_s,
const std::stringstream& rate_s,
const std::stringstream& eta_s,
const std::stringstream& percent_s,
const std::string& fname)
{
std::stringstream tmp;
tmp.setf (std::ios::fixed);
// Size.
tmp << " "
<< std::setw (4)
<< size_s.str ();
// Rate, ETA.
tmp << " "
<< rate_s.str ()
<< " "
<< eta_s.str ();
// Percent.
tmp << " "
<< percent_s.str ();
// Filename. Slice and dice.
const size_t tmp_len = tmp.str ().length ();
const size_t sub_len = _width - tmp_len;
std::stringstream b;
if ((unsigned)sub_len > 0) {
// Pad to max. terminal width.
b << fname.substr (0, sub_len);
while (b.str ().length () < sub_len) b << " ";
b << tmp.str ();
}
if (_old_width) {
// Clear line.
const int m =
(_old_width < _width)
? _width
: _old_width;
for (int i=0; i<m; ++i) cclive::log << " ";
cclive::log << "\r" << std::flush;
_old_width = 0;
}
// Print.
cclive::log << b.str () << "\r" << std::flush;
}
void
progressbar::_dotline (
const std::stringstream& size_s,
const std::stringstream& rate_s,
const std::stringstream& eta_s,
const std::stringstream& percent_s,
const std::string& fname)
{
if (++_dot_count >= 31) {
cclive::log
<< " "
<< std::setw (6)
<< size_s.str ()
<< " "
<< rate_s.str ()
<< " "
<< eta_s.str ()
<< " "
<< percent_s.str ()
<< std::endl;
_dot_count = 0;
}
else {
cclive::log << "." << (_dot_count % 3 == 0 ? " ":"") << std::flush;
}
}
void
progressbar::finish () {
if (_expected_bytes > 0
&& _count + _initial_bytes > _expected_bytes)
{
_expected_bytes = _initial_bytes + _count;
}
_done = true;
update (-1);
}
} // End namespace.
<|endoftext|>
|
<commit_before>//
// calcCOVARchunks.cpp
//
//
// Created by Evan McCartney-Melstad on 2/13/15.
//
//
#include "calcCOVARchunks.h"
#include <iostream>
#include <vector>
#include <fstream>
#include <thread>
#include <string>
int calcCOVARfromBinaryFile (std::string binaryFile, unsigned long long int numLoci, const int numIndividuals, std::string outFile, int lociChunkSize, int numThreads) {
std::cout << "Number of threads: " << numThreads << std::endl;
//std::streampos size;
std::ifstream file (binaryFile, std::ios::in|std::ios::binary);
std::cout << "Made it to line 22" << std::endl;
if (file.is_open()) {
unsigned long long int maxLocus = numLoci;
std::cout << "Calculating divergence based on " << maxLocus << " total loci." << std::endl;
// How many bytes to read in at one time (this number of loci will be split amongs numThreads threads, so it should be divisible exactly by numThreads. So the number of loci read in at a time will actually be numLoci*numThreads
unsigned long long int lociChunkByteSize = (unsigned long long)lociChunkSize * numIndividuals * 2 * numThreads;
int numFullChunks = (maxLocus*numIndividuals*2)/lociChunkByteSize; // Truncates answer to an integer
unsigned long long remainingBytesAfterFullChunks = (maxLocus*numIndividuals*2) % lociChunkByteSize;
std::cout << "Total number of chunks to run: " << numFullChunks + 1 << std::endl;
/* We are going to split the loci between numThreads threads. Each thread will modify two multidimensional
vectors that will hold the weightings, the weighted sum of products, and weighted sums of the firsts.
First, we'll generate all of these vectors, which apparently in C++ needs to be constructed of a
vector of two-dimensional vectors...
*/
std::vector<std::vector<std::vector<unsigned long long>>> weightSumProductsThreads(numThreads, std::vector<std::vector<unsigned long long>> (numIndividuals, std::vector<unsigned long long> (numIndividuals,0) ) ); //covarThreads[0] is the first 2D array for the first thread, etc...
std::vector<std::vector<std::vector<unsigned long long>>> weightSumFirstThreads(numThreads, std::vector<std::vector<unsigned long long>> (numIndividuals, std::vector<unsigned long long> (numIndividuals,0) ) ); //covarThreads[0] is the first 2D array for the first thread, etc...
std::vector<std::vector<std::vector<unsigned long long int>>> weightingsThreads(numThreads, std::vector<std::vector<unsigned long long int> > (numIndividuals, std::vector<unsigned long long int> (numIndividuals,0) ) );
std::cout << "Initialized the 3d weighting and covar vectors" << std::endl;
// Read in the data in chunks, and process each chunk using numThreads threads
int chunkCounter = 0;
while (chunkCounter < numFullChunks) {
unsigned long long bytesPerThread = lociChunkByteSize / numThreads;
unsigned long long int lociPerThread = bytesPerThread / (numIndividuals*2);
std::cout << "Running chunk #" << chunkCounter << std::endl;
std::vector<unsigned char> readCounts(lociChunkByteSize);
file.read((char*) &readCounts[0], lociChunkByteSize);
std::cout << "Number of bytes in the chunk vector: " << readCounts.size() << std::endl;
std::vector<std::thread> threadsVec;
for (int threadRunning = 0; threadRunning < numThreads; threadRunning++) {
unsigned long long int firstLocus = (unsigned long long int) threadRunning * lociPerThread;
unsigned long long int finishingLocus = ((unsigned long long int) threadRunning * lociPerThread) + lociPerThread - (unsigned long long)1.0;
std::cout << "Got to the function call in main loop. Running thread # " << threadRunning << std::endl;
//threadsVec.push_back(std::thread(calcCOVARforRange, numIndividuals, lociPerThread, std::ref(readCounts), std::ref(covarThreads[threadRunning]), std::ref(weightingsThreads[threadRunning])));
threadsVec.push_back(std::thread(calcCOVARforRange, firstLocus, finishingLocus, numIndividuals, std::ref(readCounts), std::ref(weightSumProductsThreads[threadRunning]), std::ref(weightSumFirstThreads[threadRunning]), std::ref(weightingsThreads[threadRunning])));
}
// Wait on threads to finish
for (int i = 0; i < numThreads; ++i) {
threadsVec[i].join();
std::cout << "Joined thread " << i << std::endl;
}
std::cout << "All threads completed running for chunk " << chunkCounter << " of " << numFullChunks + 1 << std::endl;
chunkCounter++;
}
// For the last chunk, we'll just run it in a single thread, so we don't have to worry about numRemainingLoci/lociPerThread remainders... Just add everything to the vectors for thread 1
std::vector<unsigned char> readCountsRemaining(remainingBytesAfterFullChunks);
file.read((char*) &readCountsRemaining[0], remainingBytesAfterFullChunks);
unsigned long long int finishingLocus = (readCountsRemaining.size()/(numIndividuals*2)) - 1;
calcCOVARforRange(0, finishingLocus, numIndividuals, std::ref(readCountsRemaining), std::ref(weightSumProductsThreads[0]), std::ref(weightSumFirstThreads[0]), std::ref(weightingsThreads[0]));
// Now aggregate the results of the threads and print final results
std::vector<std::vector<long double>> weightingsSUM(numIndividuals, std::vector<long double>(numIndividuals,0));
std::vector<std::vector<long double>> weightSumProductsSUM(numIndividuals, std::vector<long double>(numIndividuals,0));
std::vector<std::vector<long double>> weightSumFirstSUM(numIndividuals, std::vector<long double>(numIndividuals,0));
for (int tortoise = 0; tortoise < numIndividuals; tortoise++) {
for (int comparisonTortoise = 0; comparisonTortoise <= tortoise; comparisonTortoise++) {
for (int threadVector = 0; threadVector < numThreads; threadVector++) {
weightingsSUM[tortoise][comparisonTortoise] += weightingsThreads[threadVector][tortoise][comparisonTortoise];
weightSumProductsSUM[tortoise][comparisonTortoise] += weightSumProductsThreads[threadVector][tortoise][comparisonTortoise];
}
}
}
//weightSumFirstSUM is a full matrix (not half), so run comparison tortoise from 0 to numIndividuals, not 0 to tortoise
for (int tortoise = 0; tortoise < numIndividuals; tortoise++) {
for (int comparisonTortoise = 0; comparisonTortoise < numIndividuals; comparisonTortoise++) {
for (int threadVector = 0; threadVector < numThreads; threadVector++) {
weightSumFirstSUM[tortoise][comparisonTortoise] += weightSumFirstThreads[threadVector][tortoise][comparisonTortoise];
}
}
}
std::cout << "Finished summing the threads vectors" << std::endl;\
file.close(); // This is the binary file that holds all the read count data
// Now print out the final output to the pairwise covariance file:
std::ofstream covarOUT (outFile);
if (!covarOUT) {
std::cerr << "Crap, " << outFile << "didn't open!" << std::endl;
} else {
for (int tortoise=0; tortoise < numIndividuals; tortoise++) {
for (int comparisonTortoise = 0; comparisonTortoise <= tortoise; comparisonTortoise++) {
covar = long double(((weightSumProductsSUM[tortoise][comparisonTortoise])/(weightingsSUM[tortoise][comparisonTortoise])) - ((weightSumFirstSUM[tortoise][comparisonTortoise])/(weightingsSUM[tortoise][comparisonTortoise]))*((weightSumFirstSUM[comparisonTortoise][tortoise])/weightingsSUM[tortoise][comparisonTortoise]));
covarOUT << covar << std::endl;
}
}
}
} else std::cout << "Unable to open file";
return 0;
}
/*
D[N] = total coverage
P[N] = major allele counts
W[N,N] = weights
C[N,N] = weighted sum of products
Z[N,N] = weighted sum of first one (note cancelation of D[N])
W[N,M] = weights
C[N,M] = weighted sum of products
Z[N,M] = weighted sum of first one (note cancelation of D[M]) : weightSumFirst
Z[M,N] = weighted sum of second one (IN TRANSPOSE) : weightSumFirst
*/
int calcCOVARforRange (unsigned long long startingLocus, unsigned long long endingLocus, int numIndividuals, std::vector<unsigned char>& mainReadCountVector, std::vector<std::vector<unsigned long long int>>& weightSumProducts, std::vector<std::vector<unsigned long long int>>& weightSumFirst, std::vector<std::vector<unsigned long long int>>& threadWeightings) {
std::cout << "Calculating COVAR for the following locus range: " << startingLocus << " to " << endingLocus << std::endl;
for( unsigned long long locus = startingLocus; locus < endingLocus; locus++) {
if (locus % 100000 == 0) {
std::cout << locus << " loci processed through calcCOVARfromBinaryFile" << std::endl;
}
unsigned long long coverages[numIndividuals];
unsigned long long int *majorAlleleCounts = new unsigned long long int[numIndividuals]; // This will hold the major allele counts for that locus for each tortoise
for( int tortoise = 0; tortoise < numIndividuals; tortoise++ ) {
unsigned long long majorIndex = locus * (numIndividuals*2) + 2 * tortoise;
unsigned long long minorIndex = locus * (numIndividuals*2) + 2 * tortoise + 1;
coverages[tortoise] = int(mainReadCountVector[majorIndex]) + int(mainReadCountVector[minorIndex]); // Hold the coverages for each locus
if ( coverages[tortoise] > 0 ) {
majorAlleleCounts[tortoise] = (unsigned long long int)mainReadCountVector[majorIndex]; // This will be an integer value
if (coverages[tortoise] > 1) {
unsigned long long int locusWeighting = (unsigned long long int) (coverages[tortoise]*(coverages[tortoise]-1));
threadWeightings[tortoise][tortoise] += (unsigned long long int)locusWeighting; // This is an integer--discrete number of reads
weightSumProducts[tortoise][tortoise] += (majorAlleleCounts[tortoise]) * (majorAlleleCounts[tortoise]) * (coverages[tortoise]-1)/(coverages[tortoise]);
weightSumFirst[tortoise][tortoise] += (majorAlleleCounts[tortoise]) * (coverages[tortoise]-1);
}
for( int comparisonTortoise = 0; comparisonTortoise < tortoise; comparisonTortoise++) {
if (coverages[comparisonTortoise] > 0) {
unsigned long long int locusWeighting = (unsigned long long int)coverages[tortoise] * (unsigned long long int)(coverages[comparisonTortoise]);
threadWeightings[tortoise][comparisonTortoise] += locusWeighting;
weightSumProducts[tortoise][comparisonTortoise] += (majorAlleleCounts[tortoise]) * (majorAlleleCounts[comparisonTortoise]);
weightSumFirst[tortoise][comparisonTortoise] += (majorAlleleCounts[comparisonTortoise]) * coverages[tortoise];
weightSumFirst[comparisonTortoise][tortoise] += (majorAlleleCounts[tortoise]) * coverages[comparisonTortoise];
}
}
}
}
delete[] majorAlleleCounts; // Needed to avoid memory leaks
}
std::cout << "Finished thread ending on locus " << endingLocus << std::endl;
return 0;
}
<commit_msg>Minor change<commit_after>//
// calcCOVARchunks.cpp
//
//
// Created by Evan McCartney-Melstad on 2/13/15.
//
//
#include "calcCOVARchunks.h"
#include <iostream>
#include <vector>
#include <fstream>
#include <thread>
#include <string>
int calcCOVARfromBinaryFile (std::string binaryFile, unsigned long long int numLoci, const int numIndividuals, std::string outFile, int lociChunkSize, int numThreads) {
std::cout << "Number of threads: " << numThreads << std::endl;
//std::streampos size;
std::ifstream file (binaryFile, std::ios::in|std::ios::binary);
std::cout << "Made it to line 22" << std::endl;
if (file.is_open()) {
unsigned long long int maxLocus = numLoci;
std::cout << "Calculating divergence based on " << maxLocus << " total loci." << std::endl;
// How many bytes to read in at one time (this number of loci will be split amongs numThreads threads, so it should be divisible exactly by numThreads. So the number of loci read in at a time will actually be numLoci*numThreads
unsigned long long int lociChunkByteSize = (unsigned long long)lociChunkSize * numIndividuals * 2 * numThreads;
int numFullChunks = (maxLocus*numIndividuals*2)/lociChunkByteSize; // Truncates answer to an integer
unsigned long long remainingBytesAfterFullChunks = (maxLocus*numIndividuals*2) % lociChunkByteSize;
std::cout << "Total number of chunks to run: " << numFullChunks + 1 << std::endl;
/* We are going to split the loci between numThreads threads. Each thread will modify two multidimensional
vectors that will hold the weightings, the weighted sum of products, and weighted sums of the firsts.
First, we'll generate all of these vectors, which apparently in C++ needs to be constructed of a
vector of two-dimensional vectors...
*/
std::vector<std::vector<std::vector<unsigned long long>>> weightSumProductsThreads(numThreads, std::vector<std::vector<unsigned long long>> (numIndividuals, std::vector<unsigned long long> (numIndividuals,0) ) ); //covarThreads[0] is the first 2D array for the first thread, etc...
std::vector<std::vector<std::vector<unsigned long long>>> weightSumFirstThreads(numThreads, std::vector<std::vector<unsigned long long>> (numIndividuals, std::vector<unsigned long long> (numIndividuals,0) ) ); //covarThreads[0] is the first 2D array for the first thread, etc...
std::vector<std::vector<std::vector<unsigned long long int>>> weightingsThreads(numThreads, std::vector<std::vector<unsigned long long int> > (numIndividuals, std::vector<unsigned long long int> (numIndividuals,0) ) );
std::cout << "Initialized the 3d weighting and covar vectors" << std::endl;
// Read in the data in chunks, and process each chunk using numThreads threads
int chunkCounter = 0;
while (chunkCounter < numFullChunks) {
unsigned long long bytesPerThread = lociChunkByteSize / numThreads;
unsigned long long int lociPerThread = bytesPerThread / (numIndividuals*2);
std::cout << "Running chunk #" << chunkCounter << std::endl;
std::vector<unsigned char> readCounts(lociChunkByteSize);
file.read((char*) &readCounts[0], lociChunkByteSize);
std::cout << "Number of bytes in the chunk vector: " << readCounts.size() << std::endl;
std::vector<std::thread> threadsVec;
for (int threadRunning = 0; threadRunning < numThreads; threadRunning++) {
unsigned long long int firstLocus = (unsigned long long int) threadRunning * lociPerThread;
unsigned long long int finishingLocus = ((unsigned long long int) threadRunning * lociPerThread) + lociPerThread - (unsigned long long)1.0;
std::cout << "Got to the function call in main loop. Running thread # " << threadRunning << std::endl;
//threadsVec.push_back(std::thread(calcCOVARforRange, numIndividuals, lociPerThread, std::ref(readCounts), std::ref(covarThreads[threadRunning]), std::ref(weightingsThreads[threadRunning])));
threadsVec.push_back(std::thread(calcCOVARforRange, firstLocus, finishingLocus, numIndividuals, std::ref(readCounts), std::ref(weightSumProductsThreads[threadRunning]), std::ref(weightSumFirstThreads[threadRunning]), std::ref(weightingsThreads[threadRunning])));
}
// Wait on threads to finish
for (int i = 0; i < numThreads; ++i) {
threadsVec[i].join();
std::cout << "Joined thread " << i << std::endl;
}
std::cout << "All threads completed running for chunk " << chunkCounter << " of " << numFullChunks + 1 << std::endl;
chunkCounter++;
}
// For the last chunk, we'll just run it in a single thread, so we don't have to worry about numRemainingLoci/lociPerThread remainders... Just add everything to the vectors for thread 1
std::vector<unsigned char> readCountsRemaining(remainingBytesAfterFullChunks);
file.read((char*) &readCountsRemaining[0], remainingBytesAfterFullChunks);
unsigned long long int finishingLocus = (readCountsRemaining.size()/(numIndividuals*2)) - 1;
calcCOVARforRange(0, finishingLocus, numIndividuals, std::ref(readCountsRemaining), std::ref(weightSumProductsThreads[0]), std::ref(weightSumFirstThreads[0]), std::ref(weightingsThreads[0]));
// Now aggregate the results of the threads and print final results
std::vector<std::vector<long double>> weightingsSUM(numIndividuals, std::vector<long double>(numIndividuals,0));
std::vector<std::vector<long double>> weightSumProductsSUM(numIndividuals, std::vector<long double>(numIndividuals,0));
std::vector<std::vector<long double>> weightSumFirstSUM(numIndividuals, std::vector<long double>(numIndividuals,0));
for (int tortoise = 0; tortoise < numIndividuals; tortoise++) {
for (int comparisonTortoise = 0; comparisonTortoise <= tortoise; comparisonTortoise++) {
for (int threadVector = 0; threadVector < numThreads; threadVector++) {
weightingsSUM[tortoise][comparisonTortoise] += weightingsThreads[threadVector][tortoise][comparisonTortoise];
weightSumProductsSUM[tortoise][comparisonTortoise] += weightSumProductsThreads[threadVector][tortoise][comparisonTortoise];
}
}
}
//weightSumFirstSUM is a full matrix (not half), so run comparison tortoise from 0 to numIndividuals, not 0 to tortoise
for (int tortoise = 0; tortoise < numIndividuals; tortoise++) {
for (int comparisonTortoise = 0; comparisonTortoise < numIndividuals; comparisonTortoise++) {
for (int threadVector = 0; threadVector < numThreads; threadVector++) {
weightSumFirstSUM[tortoise][comparisonTortoise] += weightSumFirstThreads[threadVector][tortoise][comparisonTortoise];
}
}
}
std::cout << "Finished summing the threads vectors" << std::endl;\
file.close(); // This is the binary file that holds all the read count data
// Now print out the final output to the pairwise covariance file:
std::ofstream covarOUT (outFile);
if (!covarOUT) {
std::cerr << "Crap, " << outFile << "didn't open!" << std::endl;
} else {
for (int tortoise=0; tortoise < numIndividuals; tortoise++) {
for (int comparisonTortoise = 0; comparisonTortoise <= tortoise; comparisonTortoise++) {
long double covar = long double(((weightSumProductsSUM[tortoise][comparisonTortoise])/(weightingsSUM[tortoise][comparisonTortoise])) - ((weightSumFirstSUM[tortoise][comparisonTortoise])/(weightingsSUM[tortoise][comparisonTortoise]))*((weightSumFirstSUM[comparisonTortoise][tortoise])/weightingsSUM[tortoise][comparisonTortoise]));
covarOUT << covar << std::endl;
}
}
}
} else std::cout << "Unable to open file";
return 0;
}
/*
D[N] = total coverage
P[N] = major allele counts
W[N,N] = weights
C[N,N] = weighted sum of products
Z[N,N] = weighted sum of first one (note cancelation of D[N])
W[N,M] = weights
C[N,M] = weighted sum of products
Z[N,M] = weighted sum of first one (note cancelation of D[M]) : weightSumFirst
Z[M,N] = weighted sum of second one (IN TRANSPOSE) : weightSumFirst
*/
int calcCOVARforRange (unsigned long long startingLocus, unsigned long long endingLocus, int numIndividuals, std::vector<unsigned char>& mainReadCountVector, std::vector<std::vector<unsigned long long int>>& weightSumProducts, std::vector<std::vector<unsigned long long int>>& weightSumFirst, std::vector<std::vector<unsigned long long int>>& threadWeightings) {
std::cout << "Calculating COVAR for the following locus range: " << startingLocus << " to " << endingLocus << std::endl;
for( unsigned long long locus = startingLocus; locus < endingLocus; locus++) {
if (locus % 100000 == 0) {
std::cout << locus << " loci processed through calcCOVARfromBinaryFile" << std::endl;
}
unsigned long long coverages[numIndividuals];
unsigned long long int *majorAlleleCounts = new unsigned long long int[numIndividuals]; // This will hold the major allele counts for that locus for each tortoise
for( int tortoise = 0; tortoise < numIndividuals; tortoise++ ) {
unsigned long long majorIndex = locus * (numIndividuals*2) + 2 * tortoise;
unsigned long long minorIndex = locus * (numIndividuals*2) + 2 * tortoise + 1;
coverages[tortoise] = int(mainReadCountVector[majorIndex]) + int(mainReadCountVector[minorIndex]); // Hold the coverages for each locus
if ( coverages[tortoise] > 0 ) {
majorAlleleCounts[tortoise] = (unsigned long long int)mainReadCountVector[majorIndex]; // This will be an integer value
if (coverages[tortoise] > 1) {
unsigned long long int locusWeighting = (unsigned long long int) (coverages[tortoise]*(coverages[tortoise]-1));
threadWeightings[tortoise][tortoise] += (unsigned long long int)locusWeighting; // This is an integer--discrete number of reads
weightSumProducts[tortoise][tortoise] += (majorAlleleCounts[tortoise]) * (majorAlleleCounts[tortoise]) * (coverages[tortoise]-1)/(coverages[tortoise]);
weightSumFirst[tortoise][tortoise] += (majorAlleleCounts[tortoise]) * (coverages[tortoise]-1);
}
for( int comparisonTortoise = 0; comparisonTortoise < tortoise; comparisonTortoise++) {
if (coverages[comparisonTortoise] > 0) {
unsigned long long int locusWeighting = (unsigned long long int)coverages[tortoise] * (unsigned long long int)(coverages[comparisonTortoise]);
threadWeightings[tortoise][comparisonTortoise] += locusWeighting;
weightSumProducts[tortoise][comparisonTortoise] += (majorAlleleCounts[tortoise]) * (majorAlleleCounts[comparisonTortoise]);
weightSumFirst[tortoise][comparisonTortoise] += (majorAlleleCounts[comparisonTortoise]) * coverages[tortoise];
weightSumFirst[comparisonTortoise][tortoise] += (majorAlleleCounts[tortoise]) * coverages[comparisonTortoise];
}
}
}
}
delete[] majorAlleleCounts; // Needed to avoid memory leaks
}
std::cout << "Finished thread ending on locus " << endingLocus << std::endl;
return 0;
}
<|endoftext|>
|
<commit_before>#include "SpecializeClampedRamps.h"
#include "IRMutator.h"
#include "IROperator.h"
#include "Simplify.h"
#include "Substitute.h"
namespace Halide {
namespace Internal {
namespace {
class PredicateFinder : public IRMutator {
public:
Expr min_predicate, max_predicate;
PredicateFinder() : min_predicate(const_true()), max_predicate(const_true()) {}
private:
using IRVisitor::visit;
void visit(const Min *op) {
Expr a = simplify(mutate(op->a));
Expr b = simplify(mutate(op->b));
const Ramp *ra = a.as<Ramp>();
const Ramp *rb = b.as<Ramp>();
const Broadcast *ba = a.as<Broadcast>();
const Broadcast *bb = b.as<Broadcast>();
if (rb && ba) {
std::swap(a, b);
std::swap(ra, rb);
std::swap(ba, bb);
}
if (ra && bb) {
Expr max_a = ra->base + ra->stride * (ra->width - 1);
Expr min_b = bb->value;
min_predicate = min_predicate && (max_a <= min_b);
expr = a;
} else if (a.same_as(op->a) && b.same_as(op->b)) {
expr = op;
} else {
expr = Min::make(a, b);
}
}
void visit(const Max *op) {
Expr a = simplify(mutate(op->a));
Expr b = simplify(mutate(op->b));
const Ramp *ra = a.as<Ramp>();
const Ramp *rb = b.as<Ramp>();
const Broadcast *ba = a.as<Broadcast>();
const Broadcast *bb = b.as<Broadcast>();
if (rb && ba) {
std::swap(a, b);
std::swap(ra, rb);
std::swap(ba, bb);
}
if (ra && bb) {
Expr min_a = ra->base;
Expr max_b = bb->value;
max_predicate = max_predicate && (min_a >= max_b);
expr = a;
} else if (a.same_as(op->a) && b.same_as(op->b)) {
expr = op;
} else {
expr = Max::make(a, b);
}
}
void visit(const Let *op) {
Expr value = mutate(op->value);
Expr body = mutate(op->body);
if (value.same_as(op->value) && body.same_as(op->body)) {
expr = op;
} else {
expr = Let::make(op->name, op->value, op->body);
}
min_predicate = substitute(op->name, value, min_predicate);
max_predicate = substitute(op->name, value, max_predicate);
}
};
class SpecializeClampedRamps : public IRMutator {
using IRMutator::visit;
void visit(const Store *op) {
PredicateFinder p;
Stmt simpler_store = p.mutate(op);
if (simpler_store.same_as(op)) {
stmt = op;
} else {
Expr predicate = simplify(p.min_predicate && p.max_predicate);
stmt = IfThenElse::make(predicate, simpler_store, op);
}
}
void visit(const LetStmt *op) {
PredicateFinder p;
Stmt body = mutate(op->body);
Expr simpler_value = p.mutate(op->value);
if (body.same_as(op->body) && simpler_value.same_as(op->value)) {
stmt = op;
} else if (simpler_value.same_as(op->value)) {
stmt = LetStmt::make(op->name, op->value, body);
} else {
Stmt simpler_let = LetStmt::make(op->name, simpler_value, body);
Expr predicate = simplify(p.min_predicate && p.max_predicate);
stmt = IfThenElse::make(predicate, simpler_let, op);
}
}
};
}
Stmt specialize_clamped_ramps(Stmt s) {
return SpecializeClampedRamps().mutate(s);
}
}
}
<commit_msg>Fix clamped ramps bug.<commit_after>#include "SpecializeClampedRamps.h"
#include "IRMutator.h"
#include "IROperator.h"
#include "Simplify.h"
#include "Substitute.h"
namespace Halide {
namespace Internal {
namespace {
class PredicateFinder : public IRMutator {
public:
Expr min_predicate, max_predicate;
PredicateFinder() : min_predicate(const_true()), max_predicate(const_true()) {}
private:
using IRVisitor::visit;
void visit(const Min *op) {
Expr a = simplify(mutate(op->a));
Expr b = simplify(mutate(op->b));
const Ramp *ra = a.as<Ramp>();
const Ramp *rb = b.as<Ramp>();
const Broadcast *ba = a.as<Broadcast>();
const Broadcast *bb = b.as<Broadcast>();
if (rb && ba) {
std::swap(a, b);
std::swap(ra, rb);
std::swap(ba, bb);
}
if (ra && bb) {
Expr max_a = ra->base + ra->stride * (ra->width - 1);
Expr min_b = bb->value;
min_predicate = min_predicate && (max_a <= min_b);
expr = a;
} else if (a.same_as(op->a) && b.same_as(op->b)) {
expr = op;
} else {
expr = Min::make(a, b);
}
}
void visit(const Max *op) {
Expr a = simplify(mutate(op->a));
Expr b = simplify(mutate(op->b));
const Ramp *ra = a.as<Ramp>();
const Ramp *rb = b.as<Ramp>();
const Broadcast *ba = a.as<Broadcast>();
const Broadcast *bb = b.as<Broadcast>();
if (rb && ba) {
std::swap(a, b);
std::swap(ra, rb);
std::swap(ba, bb);
}
if (ra && bb) {
Expr min_a = ra->base;
Expr max_b = bb->value;
max_predicate = max_predicate && (min_a >= max_b);
expr = a;
} else if (a.same_as(op->a) && b.same_as(op->b)) {
expr = op;
} else {
expr = Max::make(a, b);
}
}
void visit(const Let *op) {
Expr value = mutate(op->value);
Expr body = mutate(op->body);
if (value.same_as(op->value) && body.same_as(op->body)) {
expr = op;
} else {
expr = Let::make(op->name, value, body);
}
min_predicate = substitute(op->name, value, min_predicate);
max_predicate = substitute(op->name, value, max_predicate);
}
};
class SpecializeClampedRamps : public IRMutator {
using IRMutator::visit;
void visit(const Store *op) {
PredicateFinder p;
Stmt simpler_store = p.mutate(op);
if (simpler_store.same_as(op)) {
stmt = op;
} else {
Expr predicate = simplify(p.min_predicate && p.max_predicate);
stmt = IfThenElse::make(predicate, simpler_store, op);
}
}
void visit(const LetStmt *op) {
PredicateFinder p;
Stmt body = mutate(op->body);
Expr simpler_value = p.mutate(op->value);
if (body.same_as(op->body) && simpler_value.same_as(op->value)) {
stmt = op;
} else if (simpler_value.same_as(op->value)) {
stmt = LetStmt::make(op->name, op->value, body);
} else {
Stmt simpler_let = LetStmt::make(op->name, simpler_value, body);
Expr predicate = simplify(p.min_predicate && p.max_predicate);
stmt = IfThenElse::make(predicate, simpler_let, op);
}
}
};
}
Stmt specialize_clamped_ramps(Stmt s) {
return SpecializeClampedRamps().mutate(s);
}
}
}
<|endoftext|>
|
<commit_before>// Copyright 2004-present Facebook. All Rights Reserved.
#include "src/StandardReactiveSocket.h"
#include <folly/ExceptionWrapper.h>
#include <folly/Memory.h>
#include <folly/MoveWrapper.h>
#include <folly/io/async/EventBase.h>
#include "src/ClientResumeStatusCallback.h"
#include "src/ConnectionAutomaton.h"
#include "src/FrameTransport.h"
#include "src/RequestHandler.h"
#include "src/automata/ChannelResponder.h"
namespace reactivesocket {
StandardReactiveSocket::~StandardReactiveSocket() {
debugCheckCorrectExecutor();
// Force connection closure, this will trigger terminal signals to be
// delivered to all stream automata.
close();
}
StandardReactiveSocket::StandardReactiveSocket(
ReactiveSocketMode mode,
std::shared_ptr<RequestHandler> handler,
Stats& stats,
std::unique_ptr<KeepaliveTimer> keepaliveTimer,
folly::Executor& executor)
: handler_(handler),
connection_(std::make_shared<ConnectionAutomaton>(
executor,
[this, handler](
ConnectionAutomaton& connection,
StreamId streamId,
std::unique_ptr<folly::IOBuf> serializedFrame) {
createResponder(
handler, connection, streamId, std::move(serializedFrame));
},
std::make_shared<StreamState>(stats),
handler,
std::bind(
&StandardReactiveSocket::resumeListener,
this,
std::placeholders::_1),
stats,
std::move(keepaliveTimer),
mode)),
streamsFactory_(connection_, mode),
executor_(executor) {
debugCheckCorrectExecutor();
stats.socketCreated();
}
std::unique_ptr<StandardReactiveSocket>
StandardReactiveSocket::fromClientConnection(
folly::Executor& executor,
std::unique_ptr<DuplexConnection> connection,
std::unique_ptr<RequestHandler> handler,
ConnectionSetupPayload setupPayload,
Stats& stats,
std::unique_ptr<KeepaliveTimer> keepaliveTimer) {
auto socket = disconnectedClient(
executor, std::move(handler), stats, std::move(keepaliveTimer));
socket->clientConnect(
std::make_shared<FrameTransport>(std::move(connection)),
std::move(setupPayload));
return socket;
}
std::unique_ptr<StandardReactiveSocket>
StandardReactiveSocket::disconnectedClient(
folly::Executor& executor,
std::unique_ptr<RequestHandler> handler,
Stats& stats,
std::unique_ptr<KeepaliveTimer> keepaliveTimer) {
std::unique_ptr<StandardReactiveSocket> socket(new StandardReactiveSocket(
ReactiveSocketMode::CLIENT,
std::move(handler),
stats,
std::move(keepaliveTimer),
executor));
return socket;
}
std::unique_ptr<StandardReactiveSocket>
StandardReactiveSocket::fromServerConnection(
folly::Executor& executor,
std::unique_ptr<DuplexConnection> connection,
std::unique_ptr<RequestHandler> handler,
Stats& stats,
bool isResumable) {
// TODO: isResumable should come as a flag on Setup frame and it should be
// exposed to the application code. We should then remove this parameter
auto socket = disconnectedServer(executor, std::move(handler), stats);
socket->serverConnect(
std::make_shared<FrameTransport>(std::move(connection)), isResumable);
return socket;
}
std::unique_ptr<StandardReactiveSocket>
StandardReactiveSocket::disconnectedServer(
folly::Executor& executor,
std::unique_ptr<RequestHandler> handler,
Stats& stats) {
std::unique_ptr<StandardReactiveSocket> socket(new StandardReactiveSocket(
ReactiveSocketMode::SERVER,
std::move(handler),
stats,
nullptr,
executor));
return socket;
}
std::shared_ptr<Subscriber<Payload>> StandardReactiveSocket::requestChannel(
std::shared_ptr<Subscriber<Payload>> responseSink) {
debugCheckCorrectExecutor();
checkNotClosed();
return streamsFactory_.createChannelRequester(
std::move(responseSink), executor_);
}
void StandardReactiveSocket::requestStream(
Payload request,
std::shared_ptr<Subscriber<Payload>> responseSink) {
debugCheckCorrectExecutor();
checkNotClosed();
streamsFactory_.createStreamRequester(
std::move(request), std::move(responseSink), executor_);
}
void StandardReactiveSocket::requestSubscription(
Payload request,
std::shared_ptr<Subscriber<Payload>> responseSink) {
debugCheckCorrectExecutor();
checkNotClosed();
streamsFactory_.createSubscriptionRequester(
std::move(request), std::move(responseSink), executor_);
}
void StandardReactiveSocket::requestResponse(
Payload payload,
std::shared_ptr<Subscriber<Payload>> responseSink) {
debugCheckCorrectExecutor();
checkNotClosed();
streamsFactory_.createRequestResponseRequester(
std::move(payload), std::move(responseSink), executor_);
}
void StandardReactiveSocket::requestFireAndForget(Payload request) {
debugCheckCorrectExecutor();
checkNotClosed();
Frame_REQUEST_FNF frame(
streamsFactory_.getNextStreamId(),
FrameFlags_EMPTY,
std::move(std::move(request)));
connection_->outputFrameOrEnqueue(frame.serializeOut());
}
void StandardReactiveSocket::metadataPush(
std::unique_ptr<folly::IOBuf> metadata) {
debugCheckCorrectExecutor();
checkNotClosed();
connection_->outputFrameOrEnqueue(
Frame_METADATA_PUSH(std::move(metadata)).serializeOut());
}
void StandardReactiveSocket::createResponder(
std::shared_ptr<RequestHandler> handler,
ConnectionAutomaton& connection,
StreamId streamId,
std::unique_ptr<folly::IOBuf> serializedFrame) {
debugCheckCorrectExecutor();
if (streamId != 0 && !streamsFactory_.registerNewPeerStreamId(streamId)) {
return;
}
auto type = FrameHeader::peekType(*serializedFrame);
switch (type) {
case FrameType::SETUP: {
Frame_SETUP frame;
if (!connection.deserializeFrameOrError(
frame, std::move(serializedFrame))) {
return;
}
if (frame.header_.flags_ & FrameFlags_LEASE) {
// TODO(yschimke) We don't have the correct lease and wait logic above
// yet
LOG(WARNING) << "ignoring setup frame with lease";
// connectionOutput_.onNext(
// Frame_ERROR::badSetupFrame("leases not supported")
// .serializeOut());
// disconnect();
}
auto streamState = handler->handleSetupPayload(
*this,
ConnectionSetupPayload(
std::move(frame.metadataMimeType_),
std::move(frame.dataMimeType_),
std::move(frame.payload_),
false, // TODO: resumable flag should be received in SETUP frame
frame.token_));
// TODO(lehecka): use again
// connection.useStreamState(streamState);
break;
}
case FrameType::RESUME: {
Frame_RESUME frame;
if (!connection.deserializeFrameOrError(
frame, std::move(serializedFrame))) {
return;
}
auto resumed =
handler->handleResume(*this, frame.token_, frame.position_);
if (!resumed) {
// TODO(lehecka): the "connection" and "this" arguments needs to be
// cleaned up. It is not intuitive what is their lifetime.
auto connectionCopy = std::move(connection_);
connection.closeWithError(
Frame_ERROR::connectionError("can not resume"));
}
break;
}
case FrameType::REQUEST_CHANNEL: {
Frame_REQUEST_CHANNEL frame;
if (!connection.deserializeFrameOrError(
frame, std::move(serializedFrame))) {
return;
}
auto automaton = streamsFactory_.createChannelResponder(
frame.requestN_, streamId, executor_);
auto requestSink = handler->handleRequestChannel(
std::move(frame.payload_), streamId, automaton);
automaton->subscribe(requestSink);
break;
}
case FrameType::REQUEST_STREAM: {
Frame_REQUEST_STREAM frame;
if (!connection.deserializeFrameOrError(
frame, std::move(serializedFrame))) {
return;
}
auto automaton = streamsFactory_.createStreamResponder(
frame.requestN_, streamId, executor_);
handler->handleRequestStream(
std::move(frame.payload_), streamId, automaton);
break;
}
case FrameType::REQUEST_SUB: {
Frame_REQUEST_SUB frame;
if (!connection.deserializeFrameOrError(
frame, std::move(serializedFrame))) {
return;
}
auto automaton = streamsFactory_.createSubscriptionResponder(
frame.requestN_, streamId, executor_);
handler->handleRequestSubscription(
std::move(frame.payload_), streamId, automaton);
break;
}
case FrameType::REQUEST_RESPONSE: {
Frame_REQUEST_RESPONSE frame;
if (!connection.deserializeFrameOrError(
frame, std::move(serializedFrame))) {
return;
}
auto automaton =
streamsFactory_.createRequestResponseResponder(streamId, executor_);
handler->handleRequestResponse(
std::move(frame.payload_), streamId, automaton);
break;
}
case FrameType::REQUEST_FNF: {
Frame_REQUEST_FNF frame;
if (!connection.deserializeFrameOrError(
frame, std::move(serializedFrame))) {
return;
}
// no stream tracking is necessary
handler->handleFireAndForgetRequest(std::move(frame.payload_), streamId);
break;
}
case FrameType::METADATA_PUSH: {
Frame_METADATA_PUSH frame;
if (!connection.deserializeFrameOrError(
frame, std::move(serializedFrame))) {
return;
}
handler->handleMetadataPush(std::move(frame.metadata_));
break;
}
// Other frames cannot start a stream.
case FrameType::LEASE:
case FrameType::KEEPALIVE:
case FrameType::RESERVED:
case FrameType::REQUEST_N:
case FrameType::CANCEL:
case FrameType::RESPONSE:
case FrameType::ERROR:
case FrameType::RESUME_OK:
default:
// TODO(lehecka): the "connection" and "this" arguments needs to be
// cleaned up. It is not intuitive what is their lifetime.
auto connectionCopy = std::move(connection_);
connection.closeWithError(Frame_ERROR::unexpectedFrame());
}
}
std::shared_ptr<StreamState> StandardReactiveSocket::resumeListener(
const ResumeIdentificationToken& token) {
debugCheckCorrectExecutor();
CHECK(false) << "not implemented";
// TODO(lehecka)
return nullptr;
// return handler_->handleResume(token);
}
void StandardReactiveSocket::clientConnect(
std::shared_ptr<FrameTransport> frameTransport,
ConnectionSetupPayload setupPayload) {
CHECK(frameTransport && !frameTransport->isClosed());
debugCheckCorrectExecutor();
checkNotClosed();
connection_->setResumable(setupPayload.resumable);
// TODO set correct version
Frame_SETUP frame(
setupPayload.resumable ? FrameFlags_RESUME_ENABLE : FrameFlags_EMPTY,
/*version=*/0,
connection_->getKeepaliveTime(),
std::numeric_limits<uint32_t>::max(),
setupPayload.token,
std::move(setupPayload.metadataMimeType),
std::move(setupPayload.dataMimeType),
std::move(setupPayload.payload));
// TODO: when the server returns back that it doesn't support resumability, we
// should retry without resumability
// making sure we send setup frame first
frameTransport->outputFrameOrEnqueue(frame.serializeOut());
// then the rest of the cached frames will be sent
connection_->connect(std::move(frameTransport), true);
}
void StandardReactiveSocket::serverConnect(
std::shared_ptr<FrameTransport> frameTransport,
bool isResumable) {
debugCheckCorrectExecutor();
connection_->setResumable(isResumable);
connection_->connect(std::move(frameTransport), true);
}
void StandardReactiveSocket::close() {
debugCheckCorrectExecutor();
if (auto connectionCopy = std::move(connection_)) {
connectionCopy->close(
folly::exception_wrapper(), StreamCompletionSignal::SOCKET_CLOSED);
}
}
void StandardReactiveSocket::disconnect() {
debugCheckCorrectExecutor();
checkNotClosed();
connection_->disconnect(folly::exception_wrapper());
}
std::shared_ptr<FrameTransport> StandardReactiveSocket::detachFrameTransport() {
debugCheckCorrectExecutor();
checkNotClosed();
return connection_->detachFrameTransport();
}
void StandardReactiveSocket::onConnected(std::function<void()> listener) {
debugCheckCorrectExecutor();
checkNotClosed();
connection_->addConnectedListener(std::move(listener));
}
void StandardReactiveSocket::onDisconnected(ErrorCallback listener) {
debugCheckCorrectExecutor();
checkNotClosed();
connection_->addDisconnectedListener(std::move(listener));
}
void StandardReactiveSocket::onClosed(ErrorCallback listener) {
debugCheckCorrectExecutor();
checkNotClosed();
connection_->addClosedListener(std::move(listener));
}
void StandardReactiveSocket::tryClientResume(
const ResumeIdentificationToken& token,
std::shared_ptr<FrameTransport> frameTransport,
std::unique_ptr<ClientResumeStatusCallback> resumeCallback) {
// TODO: verify/assert that the new frameTransport is on the same event base
debugCheckCorrectExecutor();
checkNotClosed();
CHECK(frameTransport && !frameTransport->isClosed());
frameTransport->outputFrameOrEnqueue(
connection_->createResumeFrame(token).serializeOut());
connection_->reconnect(std::move(frameTransport), std::move(resumeCallback));
}
bool StandardReactiveSocket::tryResumeServer(
std::shared_ptr<FrameTransport> frameTransport,
ResumePosition position) {
// TODO: verify/assert that the new frameTransport is on the same event base
debugCheckCorrectExecutor();
checkNotClosed();
disconnect();
// TODO: verify, we should not be receiving any frames, not a single one
connection_->connect(std::move(frameTransport), /*sendPendingFrames=*/false);
return connection_->resumeFromPositionOrClose(position);
}
void StandardReactiveSocket::checkNotClosed() const {
CHECK(connection_) << "ReactiveSocket already closed";
}
DuplexConnection* StandardReactiveSocket::duplexConnection() const {
debugCheckCorrectExecutor();
return connection_ ? connection_->duplexConnection() : nullptr;
}
void StandardReactiveSocket::debugCheckCorrectExecutor() const {
DCHECK(
!dynamic_cast<folly::EventBase*>(&executor_) ||
dynamic_cast<folly::EventBase*>(&executor_)->isInEventBaseThread());
}
bool StandardReactiveSocket::isClosed() {
debugCheckCorrectExecutor();
return !static_cast<bool>(connection_);
}
} // reactivesocket
<commit_msg>tryClientResume implies the socket is intended to be resumable (#292)<commit_after>// Copyright 2004-present Facebook. All Rights Reserved.
#include "src/StandardReactiveSocket.h"
#include <folly/ExceptionWrapper.h>
#include <folly/Memory.h>
#include <folly/MoveWrapper.h>
#include <folly/io/async/EventBase.h>
#include "src/ClientResumeStatusCallback.h"
#include "src/ConnectionAutomaton.h"
#include "src/FrameTransport.h"
#include "src/RequestHandler.h"
#include "src/automata/ChannelResponder.h"
namespace reactivesocket {
StandardReactiveSocket::~StandardReactiveSocket() {
debugCheckCorrectExecutor();
// Force connection closure, this will trigger terminal signals to be
// delivered to all stream automata.
close();
}
StandardReactiveSocket::StandardReactiveSocket(
ReactiveSocketMode mode,
std::shared_ptr<RequestHandler> handler,
Stats& stats,
std::unique_ptr<KeepaliveTimer> keepaliveTimer,
folly::Executor& executor)
: handler_(handler),
connection_(std::make_shared<ConnectionAutomaton>(
executor,
[this, handler](
ConnectionAutomaton& connection,
StreamId streamId,
std::unique_ptr<folly::IOBuf> serializedFrame) {
createResponder(
handler, connection, streamId, std::move(serializedFrame));
},
std::make_shared<StreamState>(stats),
handler,
std::bind(
&StandardReactiveSocket::resumeListener,
this,
std::placeholders::_1),
stats,
std::move(keepaliveTimer),
mode)),
streamsFactory_(connection_, mode),
executor_(executor) {
debugCheckCorrectExecutor();
stats.socketCreated();
}
std::unique_ptr<StandardReactiveSocket>
StandardReactiveSocket::fromClientConnection(
folly::Executor& executor,
std::unique_ptr<DuplexConnection> connection,
std::unique_ptr<RequestHandler> handler,
ConnectionSetupPayload setupPayload,
Stats& stats,
std::unique_ptr<KeepaliveTimer> keepaliveTimer) {
auto socket = disconnectedClient(
executor, std::move(handler), stats, std::move(keepaliveTimer));
socket->clientConnect(
std::make_shared<FrameTransport>(std::move(connection)),
std::move(setupPayload));
return socket;
}
std::unique_ptr<StandardReactiveSocket>
StandardReactiveSocket::disconnectedClient(
folly::Executor& executor,
std::unique_ptr<RequestHandler> handler,
Stats& stats,
std::unique_ptr<KeepaliveTimer> keepaliveTimer) {
std::unique_ptr<StandardReactiveSocket> socket(new StandardReactiveSocket(
ReactiveSocketMode::CLIENT,
std::move(handler),
stats,
std::move(keepaliveTimer),
executor));
return socket;
}
std::unique_ptr<StandardReactiveSocket>
StandardReactiveSocket::fromServerConnection(
folly::Executor& executor,
std::unique_ptr<DuplexConnection> connection,
std::unique_ptr<RequestHandler> handler,
Stats& stats,
bool isResumable) {
// TODO: isResumable should come as a flag on Setup frame and it should be
// exposed to the application code. We should then remove this parameter
auto socket = disconnectedServer(executor, std::move(handler), stats);
socket->serverConnect(
std::make_shared<FrameTransport>(std::move(connection)), isResumable);
return socket;
}
std::unique_ptr<StandardReactiveSocket>
StandardReactiveSocket::disconnectedServer(
folly::Executor& executor,
std::unique_ptr<RequestHandler> handler,
Stats& stats) {
std::unique_ptr<StandardReactiveSocket> socket(new StandardReactiveSocket(
ReactiveSocketMode::SERVER,
std::move(handler),
stats,
nullptr,
executor));
return socket;
}
std::shared_ptr<Subscriber<Payload>> StandardReactiveSocket::requestChannel(
std::shared_ptr<Subscriber<Payload>> responseSink) {
debugCheckCorrectExecutor();
checkNotClosed();
return streamsFactory_.createChannelRequester(
std::move(responseSink), executor_);
}
void StandardReactiveSocket::requestStream(
Payload request,
std::shared_ptr<Subscriber<Payload>> responseSink) {
debugCheckCorrectExecutor();
checkNotClosed();
streamsFactory_.createStreamRequester(
std::move(request), std::move(responseSink), executor_);
}
void StandardReactiveSocket::requestSubscription(
Payload request,
std::shared_ptr<Subscriber<Payload>> responseSink) {
debugCheckCorrectExecutor();
checkNotClosed();
streamsFactory_.createSubscriptionRequester(
std::move(request), std::move(responseSink), executor_);
}
void StandardReactiveSocket::requestResponse(
Payload payload,
std::shared_ptr<Subscriber<Payload>> responseSink) {
debugCheckCorrectExecutor();
checkNotClosed();
streamsFactory_.createRequestResponseRequester(
std::move(payload), std::move(responseSink), executor_);
}
void StandardReactiveSocket::requestFireAndForget(Payload request) {
debugCheckCorrectExecutor();
checkNotClosed();
Frame_REQUEST_FNF frame(
streamsFactory_.getNextStreamId(),
FrameFlags_EMPTY,
std::move(std::move(request)));
connection_->outputFrameOrEnqueue(frame.serializeOut());
}
void StandardReactiveSocket::metadataPush(
std::unique_ptr<folly::IOBuf> metadata) {
debugCheckCorrectExecutor();
checkNotClosed();
connection_->outputFrameOrEnqueue(
Frame_METADATA_PUSH(std::move(metadata)).serializeOut());
}
void StandardReactiveSocket::createResponder(
std::shared_ptr<RequestHandler> handler,
ConnectionAutomaton& connection,
StreamId streamId,
std::unique_ptr<folly::IOBuf> serializedFrame) {
debugCheckCorrectExecutor();
if (streamId != 0 && !streamsFactory_.registerNewPeerStreamId(streamId)) {
return;
}
auto type = FrameHeader::peekType(*serializedFrame);
switch (type) {
case FrameType::SETUP: {
Frame_SETUP frame;
if (!connection.deserializeFrameOrError(
frame, std::move(serializedFrame))) {
return;
}
if (frame.header_.flags_ & FrameFlags_LEASE) {
// TODO(yschimke) We don't have the correct lease and wait logic above
// yet
LOG(WARNING) << "ignoring setup frame with lease";
// connectionOutput_.onNext(
// Frame_ERROR::badSetupFrame("leases not supported")
// .serializeOut());
// disconnect();
}
auto streamState = handler->handleSetupPayload(
*this,
ConnectionSetupPayload(
std::move(frame.metadataMimeType_),
std::move(frame.dataMimeType_),
std::move(frame.payload_),
false, // TODO: resumable flag should be received in SETUP frame
frame.token_));
// TODO(lehecka): use again
// connection.useStreamState(streamState);
break;
}
case FrameType::RESUME: {
Frame_RESUME frame;
if (!connection.deserializeFrameOrError(
frame, std::move(serializedFrame))) {
return;
}
auto resumed =
handler->handleResume(*this, frame.token_, frame.position_);
if (!resumed) {
// TODO(lehecka): the "connection" and "this" arguments needs to be
// cleaned up. It is not intuitive what is their lifetime.
auto connectionCopy = std::move(connection_);
connection.closeWithError(
Frame_ERROR::connectionError("can not resume"));
}
break;
}
case FrameType::REQUEST_CHANNEL: {
Frame_REQUEST_CHANNEL frame;
if (!connection.deserializeFrameOrError(
frame, std::move(serializedFrame))) {
return;
}
auto automaton = streamsFactory_.createChannelResponder(
frame.requestN_, streamId, executor_);
auto requestSink = handler->handleRequestChannel(
std::move(frame.payload_), streamId, automaton);
automaton->subscribe(requestSink);
break;
}
case FrameType::REQUEST_STREAM: {
Frame_REQUEST_STREAM frame;
if (!connection.deserializeFrameOrError(
frame, std::move(serializedFrame))) {
return;
}
auto automaton = streamsFactory_.createStreamResponder(
frame.requestN_, streamId, executor_);
handler->handleRequestStream(
std::move(frame.payload_), streamId, automaton);
break;
}
case FrameType::REQUEST_SUB: {
Frame_REQUEST_SUB frame;
if (!connection.deserializeFrameOrError(
frame, std::move(serializedFrame))) {
return;
}
auto automaton = streamsFactory_.createSubscriptionResponder(
frame.requestN_, streamId, executor_);
handler->handleRequestSubscription(
std::move(frame.payload_), streamId, automaton);
break;
}
case FrameType::REQUEST_RESPONSE: {
Frame_REQUEST_RESPONSE frame;
if (!connection.deserializeFrameOrError(
frame, std::move(serializedFrame))) {
return;
}
auto automaton =
streamsFactory_.createRequestResponseResponder(streamId, executor_);
handler->handleRequestResponse(
std::move(frame.payload_), streamId, automaton);
break;
}
case FrameType::REQUEST_FNF: {
Frame_REQUEST_FNF frame;
if (!connection.deserializeFrameOrError(
frame, std::move(serializedFrame))) {
return;
}
// no stream tracking is necessary
handler->handleFireAndForgetRequest(std::move(frame.payload_), streamId);
break;
}
case FrameType::METADATA_PUSH: {
Frame_METADATA_PUSH frame;
if (!connection.deserializeFrameOrError(
frame, std::move(serializedFrame))) {
return;
}
handler->handleMetadataPush(std::move(frame.metadata_));
break;
}
// Other frames cannot start a stream.
case FrameType::LEASE:
case FrameType::KEEPALIVE:
case FrameType::RESERVED:
case FrameType::REQUEST_N:
case FrameType::CANCEL:
case FrameType::RESPONSE:
case FrameType::ERROR:
case FrameType::RESUME_OK:
default:
// TODO(lehecka): the "connection" and "this" arguments needs to be
// cleaned up. It is not intuitive what is their lifetime.
auto connectionCopy = std::move(connection_);
connection.closeWithError(Frame_ERROR::unexpectedFrame());
}
}
std::shared_ptr<StreamState> StandardReactiveSocket::resumeListener(
const ResumeIdentificationToken& token) {
debugCheckCorrectExecutor();
CHECK(false) << "not implemented";
// TODO(lehecka)
return nullptr;
// return handler_->handleResume(token);
}
void StandardReactiveSocket::clientConnect(
std::shared_ptr<FrameTransport> frameTransport,
ConnectionSetupPayload setupPayload) {
CHECK(frameTransport && !frameTransport->isClosed());
debugCheckCorrectExecutor();
checkNotClosed();
connection_->setResumable(setupPayload.resumable);
// TODO set correct version
Frame_SETUP frame(
setupPayload.resumable ? FrameFlags_RESUME_ENABLE : FrameFlags_EMPTY,
/*version=*/0,
connection_->getKeepaliveTime(),
std::numeric_limits<uint32_t>::max(),
setupPayload.token,
std::move(setupPayload.metadataMimeType),
std::move(setupPayload.dataMimeType),
std::move(setupPayload.payload));
// TODO: when the server returns back that it doesn't support resumability, we
// should retry without resumability
// making sure we send setup frame first
frameTransport->outputFrameOrEnqueue(frame.serializeOut());
// then the rest of the cached frames will be sent
connection_->connect(std::move(frameTransport), true);
}
void StandardReactiveSocket::serverConnect(
std::shared_ptr<FrameTransport> frameTransport,
bool isResumable) {
debugCheckCorrectExecutor();
connection_->setResumable(isResumable);
connection_->connect(std::move(frameTransport), true);
}
void StandardReactiveSocket::close() {
debugCheckCorrectExecutor();
if (auto connectionCopy = std::move(connection_)) {
connectionCopy->close(
folly::exception_wrapper(), StreamCompletionSignal::SOCKET_CLOSED);
}
}
void StandardReactiveSocket::disconnect() {
debugCheckCorrectExecutor();
checkNotClosed();
connection_->disconnect(folly::exception_wrapper());
}
std::shared_ptr<FrameTransport> StandardReactiveSocket::detachFrameTransport() {
debugCheckCorrectExecutor();
checkNotClosed();
return connection_->detachFrameTransport();
}
void StandardReactiveSocket::onConnected(std::function<void()> listener) {
debugCheckCorrectExecutor();
checkNotClosed();
connection_->addConnectedListener(std::move(listener));
}
void StandardReactiveSocket::onDisconnected(ErrorCallback listener) {
debugCheckCorrectExecutor();
checkNotClosed();
connection_->addDisconnectedListener(std::move(listener));
}
void StandardReactiveSocket::onClosed(ErrorCallback listener) {
debugCheckCorrectExecutor();
checkNotClosed();
connection_->addClosedListener(std::move(listener));
}
void StandardReactiveSocket::tryClientResume(
const ResumeIdentificationToken& token,
std::shared_ptr<FrameTransport> frameTransport,
std::unique_ptr<ClientResumeStatusCallback> resumeCallback) {
// TODO: verify/assert that the new frameTransport is on the same event base
debugCheckCorrectExecutor();
checkNotClosed();
CHECK(frameTransport && !frameTransport->isClosed());
frameTransport->outputFrameOrEnqueue(
connection_->createResumeFrame(token).serializeOut());
connection_->setResumable(true);
connection_->reconnect(std::move(frameTransport), std::move(resumeCallback));
}
bool StandardReactiveSocket::tryResumeServer(
std::shared_ptr<FrameTransport> frameTransport,
ResumePosition position) {
// TODO: verify/assert that the new frameTransport is on the same event base
debugCheckCorrectExecutor();
checkNotClosed();
disconnect();
// TODO: verify, we should not be receiving any frames, not a single one
connection_->connect(std::move(frameTransport), /*sendPendingFrames=*/false);
return connection_->resumeFromPositionOrClose(position);
}
void StandardReactiveSocket::checkNotClosed() const {
CHECK(connection_) << "ReactiveSocket already closed";
}
DuplexConnection* StandardReactiveSocket::duplexConnection() const {
debugCheckCorrectExecutor();
return connection_ ? connection_->duplexConnection() : nullptr;
}
void StandardReactiveSocket::debugCheckCorrectExecutor() const {
DCHECK(
!dynamic_cast<folly::EventBase*>(&executor_) ||
dynamic_cast<folly::EventBase*>(&executor_)->isInEventBaseThread());
}
bool StandardReactiveSocket::isClosed() {
debugCheckCorrectExecutor();
return !static_cast<bool>(connection_);
}
} // reactivesocket
<|endoftext|>
|
<commit_before>#pragma once
#include <cmath>
#include <string>
#include "base/macros.hpp"
namespace principia {
namespace quantities {
template<int64_t LengthExponent, int64_t MassExponent, int64_t TimeExponent,
int64_t CurrentExponent, int64_t TemperatureExponent,
int64_t AmountExponent, int64_t LuminousIntensityExponent,
int64_t WindingExponent, int64_t AngleExponent,
int64_t SolidAngleExponent>
struct Dimensions {
enum {
Length = LengthExponent,
Mass = MassExponent,
Time = TimeExponent,
Current = CurrentExponent,
Temperature = TemperatureExponent,
Amount = AmountExponent,
LuminousIntensity = LuminousIntensityExponent,
Winding = WindingExponent,
Angle = AngleExponent,
SolidAngle = SolidAngleExponent
};
static int const kMinExponent = -16;
static int const kMaxExponent = 15;
static int const kExponentBits = 5;
static int const kExponentMask = 0x1F;
static_assert(LengthExponent >= kMinExponent &&
LengthExponent <= kMaxExponent,
"Invalid length exponent");
static_assert(MassExponent >= kMinExponent &&
MassExponent <= kMaxExponent,
"Invalid mass exponent");
static_assert(TimeExponent >= kMinExponent &&
TimeExponent <= kMaxExponent,
"Invalid time exponent");
static_assert(CurrentExponent >= kMinExponent &&
CurrentExponent <= kMaxExponent,
"Invalid current exponent");
static_assert(TemperatureExponent >= kMinExponent &&
TemperatureExponent <= kMaxExponent,
"Invalid temperature exponent");
static_assert(AmountExponent >= kMinExponent &&
AmountExponent <= kMaxExponent,
"Invalid amount exponent");
static_assert(LuminousIntensityExponent >= kMinExponent &&
LuminousIntensityExponent <= kMaxExponent,
"Invalid luminous intensity exponent");
static_assert(AngleExponent >= kMinExponent &&
AngleExponent <= kMaxExponent,
"Invalid angle exponent");
static_assert(SolidAngleExponent >= kMinExponent &&
SolidAngleExponent <= kMaxExponent,
"Invalid solid angle exponent");
static_assert(WindingExponent >= kMinExponent &&
WindingExponent <= kMaxExponent,
"Invalid winding exponent");
// The NOLINT are because glint is confused by the binary and. I kid you not.
static int64_t const representation =
(LengthExponent & kExponentMask) | // NOLINT
(MassExponent & kExponentMask) << 1 * kExponentBits | // NOLINT
(TimeExponent & kExponentMask) << 2 * kExponentBits | // NOLINT
(CurrentExponent & kExponentMask) << 3 * kExponentBits | // NOLINT
(TemperatureExponent & kExponentMask) << 4 * kExponentBits | // NOLINT
(AmountExponent & kExponentMask) << 5 * kExponentBits | // NOLINT
(LuminousIntensityExponent & kExponentMask) << 6 * kExponentBits | // NOLINT
(AngleExponent & kExponentMask) << 7 * kExponentBits | // NOLINT
(SolidAngleExponent & kExponentMask) << 8 * kExponentBits | // NOLINT
(WindingExponent & kExponentMask) << 9 * kExponentBits; // NOLINT
};
namespace internal {
template<typename Q>
struct Collapse { using Type = Q; };
template<>
struct Collapse<Quantity<NoDimensions>> { using Type = double; };
template<typename Left, typename Right>
struct ProductGenerator {
enum {
Length = Left::Dimensions::Length + Right::Dimensions::Length,
Mass = Left::Dimensions::Mass + Right::Dimensions::Mass,
Time = Left::Dimensions::Time + Right::Dimensions::Time,
Current = Left::Dimensions::Current + Right::Dimensions::Current,
Temperature = Left::Dimensions::Temperature +
Right::Dimensions::Temperature,
Amount = Left::Dimensions::Amount + Right::Dimensions::Amount,
LuminousIntensity = Left::Dimensions::LuminousIntensity +
Right:: Dimensions::LuminousIntensity,
Winding = Left::Dimensions::Winding + Right::Dimensions::Winding,
Angle = Left::Dimensions::Angle + Right::Dimensions::Angle,
SolidAngle = Left::Dimensions::SolidAngle +
Right::Dimensions::SolidAngle
};
using Type = typename Collapse<
Quantity<Dimensions<Length, Mass, Time, Current, Temperature, Amount,
LuminousIntensity, Winding, Angle,
SolidAngle>>>::Type;
};
template<typename Left>
struct ProductGenerator<Left, double> { using Type = Left; };
template<typename Right>
struct ProductGenerator<double, Right> { using Type = Right; };
template<>
struct ProductGenerator<double, double> {
using Type = double;
};
template<typename Left, typename Right>
struct QuotientGenerator {
enum {
Length = Left::Dimensions::Length - Right::Dimensions::Length,
Mass = Left::Dimensions::Mass - Right::Dimensions::Mass,
Time = Left::Dimensions::Time - Right::Dimensions::Time,
Current = Left::Dimensions::Current - Right::Dimensions::Current,
Temperature = Left::Dimensions::Temperature -
Right::Dimensions::Temperature,
Amount = Left::Dimensions::Amount - Right::Dimensions::Amount,
LuminousIntensity = Left::Dimensions::LuminousIntensity -
Right:: Dimensions::LuminousIntensity,
Winding = Left::Dimensions::Winding - Right::Dimensions::Winding,
Angle = Left::Dimensions::Angle - Right::Dimensions::Angle,
SolidAngle = Left::Dimensions::SolidAngle -
Right::Dimensions::SolidAngle
};
using Type = typename Collapse<
Quantity<Dimensions<Length, Mass, Time, Current, Temperature, Amount,
LuminousIntensity, Winding, Angle,
SolidAngle>>>::Type;
};
template<typename Left>
struct QuotientGenerator<Left, double> { using Type = Left; };
template<>
struct QuotientGenerator<double, double> {
using Type = double;
};
template<typename Right>
struct QuotientGenerator<double, Right> {
enum {
Length = -Right::Dimensions::Length,
Mass = -Right::Dimensions::Mass,
Time = -Right::Dimensions::Time,
Current = -Right::Dimensions::Current,
Temperature = -Right::Dimensions::Temperature,
Amount = -Right::Dimensions::Amount,
LuminousIntensity = -Right::Dimensions::LuminousIntensity,
Winding = -Right::Dimensions::Winding,
Angle = -Right::Dimensions::Angle,
SolidAngle = -Right::Dimensions::SolidAngle
};
using Type = Quantity<
Dimensions<Length, Mass, Time, Current, Temperature, Amount,
LuminousIntensity, Winding, Angle, SolidAngle>>;
};
template<typename T, int exponent>
struct ExponentiationGenerator<T, exponent, std::enable_if_t<(exponent > 1)>> {
using Type = Product<typename ExponentiationGenerator<T, exponent - 1>::Type,
T>;
};
template<typename T, int exponent>
struct ExponentiationGenerator<T, exponent, std::enable_if_t<(exponent < 1)>>{
using Type = Quotient<typename ExponentiationGenerator<T, exponent + 1>::Type,
T>;
};
template<typename T, int exponent>
struct ExponentiationGenerator<T, exponent, std::enable_if_t<(exponent == 1)>>{
using Type = T;
};
} // namespace internal
template<typename D>
inline Quantity<D>::Quantity() : magnitude_(0) {}
template<typename D>
inline Quantity<D>::Quantity(double const magnitude) : magnitude_(magnitude) {}
template<typename D>
inline Quantity<D>& Quantity<D>::operator+=(Quantity const& right) {
magnitude_ += right.magnitude_;
return *this;
}
template<typename D>
inline Quantity<D>& Quantity<D>::operator-=(Quantity const& right) {
magnitude_ -= right.magnitude_;
return *this;
}
template<typename D>
inline Quantity<D>& Quantity<D>::operator*=(double const right) {
magnitude_ *= right;
return *this;
}
template<typename D>
inline Quantity<D>& Quantity<D>::operator/=(double const right) {
magnitude_ /= right;
return *this;
}
// Additive group
template<typename D>
inline Quantity<D> Quantity<D>::operator+() const {
return *this;
}
template<typename D>
inline Quantity<D> Quantity<D>::operator-() const {
return Quantity(-magnitude_);
}
template<typename D>
inline Quantity<D> Quantity<D>::operator+(Quantity const& right) const {
return Quantity(magnitude_ + right.magnitude_);
}
template<typename D>
inline Quantity<D> Quantity<D>::operator-(Quantity const& right) const {
return Quantity(magnitude_ - right.magnitude_);
}
// Comparison operators
template<typename D>
inline bool Quantity<D>::operator>(Quantity const& right) const {
return magnitude_ > right.magnitude_;
}
template<typename D>
inline bool Quantity<D>::operator<(Quantity const& right) const {
return magnitude_ < right.magnitude_;
}
template<typename D>
inline bool Quantity<D>::operator>=(Quantity const& right) const {
return magnitude_ >= right.magnitude_;
}
template<typename D>
inline bool Quantity<D>::operator<=(Quantity const& right) const {
return magnitude_ <= right.magnitude_;
}
template<typename D>
inline bool Quantity<D>::operator==(Quantity const& right) const {
return magnitude_ == right.magnitude_;
}
template<typename D>
inline bool Quantity<D>::operator!=(Quantity const& right) const {
return magnitude_ != right.magnitude_;
}
template<typename D>
void Quantity<D>::WriteToMessage(
not_null<serialization::Quantity*> const message) const {
message->set_dimensions(D::representation);
message->set_magnitude(magnitude_);
}
template<typename D>
Quantity<D> Quantity<D>::ReadFromMessage(
serialization::Quantity const& message) {
CHECK_EQ(D::representation, message.dimensions());
return Quantity(message.magnitude());
}
// Multiplicative group
template<typename D>
inline Quantity<D> Quantity<D>::operator/(double const right) const {
return Quantity(magnitude_ / right);
}
template<typename D>
inline Quantity<D> Quantity<D>::operator*(double const right) const {
return Quantity(magnitude_ * right);
}
template<typename LDimensions, typename RDimensions>
inline internal::Product<Quantity<LDimensions>, Quantity<RDimensions>>
operator*(Quantity<LDimensions> const& left,
Quantity<RDimensions> const& right) {
return Product<Quantity<LDimensions>,
Quantity<RDimensions>>(left.magnitude_ * right.magnitude_);
}
template<typename LDimensions, typename RDimensions>
inline internal::Quotient<Quantity<LDimensions>, Quantity<RDimensions>>
operator/(Quantity<LDimensions> const& left,
Quantity<RDimensions> const& right) {
return Quotient<Quantity<LDimensions>,
Quantity<RDimensions>>(left.magnitude_ / right.magnitude_);
}
template<typename RDimensions>
FORCE_INLINE Quantity<RDimensions> operator*(
double const left,
Quantity<RDimensions> const& right) {
return Quantity<RDimensions>(left * right.magnitude_);
}
template<typename RDimensions>
inline typename Quantity<RDimensions>::Inverse operator/(
double const left,
Quantity<RDimensions> const& right) {
return typename Quantity<RDimensions>::Inverse(left / right.magnitude_);
}
template<int exponent>
inline double Pow(double x) {
return std::pow(x, exponent);
}
// Static specializations for frequently-used exponents, so that this gets
// turned into multiplications at compile time.
template<>
inline double Pow<-3>(double x) {
return 1 / (x * x * x);
}
template<>
inline double Pow<-2>(double x) {
return 1 / (x * x);
}
template<>
inline double Pow<-1>(double x) {
return 1 / x;
}
template<>
inline double Pow<0>(double x) {
return 1;
}
template<>
inline double Pow<1>(double x) {
return x;
}
template<>
inline double Pow<2>(double x) {
return x * x;
}
template<>
inline double Pow<3>(double x) {
return x * x * x;
}
template<int exponent, typename D>
Exponentiation<Quantity<D>, exponent> Pow(
Quantity<D> const& x) {
return Exponentiation<Quantity<D>, exponent>(
Pow<exponent>(x.magnitude_));
}
inline double Abs(double const x) {
return std::abs(x);
}
template<typename D>
Quantity<D> Abs(Quantity<D> const& quantity) {
return Quantity<D>(std::abs(quantity.magnitude_));
}
template<typename Q>
inline Q SIUnit() {
return Q(1);
}
template<>
inline double SIUnit<double>() {
return 1;
}
inline std::string FormatUnit(std::string const& name, int const exponent) {
switch (exponent) {
case 0:
return "";
break;
case 1:
return " " + name;
default:
return " " + name + "^" + std::to_string(exponent);
}
}
inline std::string DebugString(double const number, int const precision) {
char result[50];
#if OS_WIN
unsigned int old_exponent_format = _set_output_format(_TWO_DIGIT_EXPONENT);
int const size = sprintf_s(result,
("%+." + std::to_string(precision) + "e").c_str(),
number);
_set_output_format(old_exponent_format);
#else
int const size = snprintf(result, sizeof(result),
("%+." + std::to_string(precision) + "e").c_str(),
number);
#endif
CHECK_LE(0, size);
return std::string(result, size);
}
template<typename D>
std::string DebugString(Quantity<D> const& quantity, int const precision) {
return DebugString(quantity.magnitude_, precision) +
FormatUnit("m", D::Length) + FormatUnit("kg", D::Mass) +
FormatUnit("s", D::Time) + FormatUnit("A", D::Current) +
FormatUnit("K", D::Temperature) + FormatUnit("mol", D::Amount) +
FormatUnit("cd", D::LuminousIntensity) + FormatUnit("cycle", D::Winding) +
FormatUnit("rad", D::Angle) + FormatUnit("sr", D::SolidAngle);
}
template<typename D>
std::ostream& operator<<(std::ostream& out, Quantity<D> const& quantity) {
return out << DebugString(quantity);
}
} // namespace quantities
} // namespace principia
<commit_msg>Include.<commit_after>#pragma once
#include <cmath>
#include <cstdio>
#include <string>
#include "base/macros.hpp"
namespace principia {
namespace quantities {
template<int64_t LengthExponent, int64_t MassExponent, int64_t TimeExponent,
int64_t CurrentExponent, int64_t TemperatureExponent,
int64_t AmountExponent, int64_t LuminousIntensityExponent,
int64_t WindingExponent, int64_t AngleExponent,
int64_t SolidAngleExponent>
struct Dimensions {
enum {
Length = LengthExponent,
Mass = MassExponent,
Time = TimeExponent,
Current = CurrentExponent,
Temperature = TemperatureExponent,
Amount = AmountExponent,
LuminousIntensity = LuminousIntensityExponent,
Winding = WindingExponent,
Angle = AngleExponent,
SolidAngle = SolidAngleExponent
};
static int const kMinExponent = -16;
static int const kMaxExponent = 15;
static int const kExponentBits = 5;
static int const kExponentMask = 0x1F;
static_assert(LengthExponent >= kMinExponent &&
LengthExponent <= kMaxExponent,
"Invalid length exponent");
static_assert(MassExponent >= kMinExponent &&
MassExponent <= kMaxExponent,
"Invalid mass exponent");
static_assert(TimeExponent >= kMinExponent &&
TimeExponent <= kMaxExponent,
"Invalid time exponent");
static_assert(CurrentExponent >= kMinExponent &&
CurrentExponent <= kMaxExponent,
"Invalid current exponent");
static_assert(TemperatureExponent >= kMinExponent &&
TemperatureExponent <= kMaxExponent,
"Invalid temperature exponent");
static_assert(AmountExponent >= kMinExponent &&
AmountExponent <= kMaxExponent,
"Invalid amount exponent");
static_assert(LuminousIntensityExponent >= kMinExponent &&
LuminousIntensityExponent <= kMaxExponent,
"Invalid luminous intensity exponent");
static_assert(AngleExponent >= kMinExponent &&
AngleExponent <= kMaxExponent,
"Invalid angle exponent");
static_assert(SolidAngleExponent >= kMinExponent &&
SolidAngleExponent <= kMaxExponent,
"Invalid solid angle exponent");
static_assert(WindingExponent >= kMinExponent &&
WindingExponent <= kMaxExponent,
"Invalid winding exponent");
// The NOLINT are because glint is confused by the binary and. I kid you not.
static int64_t const representation =
(LengthExponent & kExponentMask) | // NOLINT
(MassExponent & kExponentMask) << 1 * kExponentBits | // NOLINT
(TimeExponent & kExponentMask) << 2 * kExponentBits | // NOLINT
(CurrentExponent & kExponentMask) << 3 * kExponentBits | // NOLINT
(TemperatureExponent & kExponentMask) << 4 * kExponentBits | // NOLINT
(AmountExponent & kExponentMask) << 5 * kExponentBits | // NOLINT
(LuminousIntensityExponent & kExponentMask) << 6 * kExponentBits | // NOLINT
(AngleExponent & kExponentMask) << 7 * kExponentBits | // NOLINT
(SolidAngleExponent & kExponentMask) << 8 * kExponentBits | // NOLINT
(WindingExponent & kExponentMask) << 9 * kExponentBits; // NOLINT
};
namespace internal {
template<typename Q>
struct Collapse { using Type = Q; };
template<>
struct Collapse<Quantity<NoDimensions>> { using Type = double; };
template<typename Left, typename Right>
struct ProductGenerator {
enum {
Length = Left::Dimensions::Length + Right::Dimensions::Length,
Mass = Left::Dimensions::Mass + Right::Dimensions::Mass,
Time = Left::Dimensions::Time + Right::Dimensions::Time,
Current = Left::Dimensions::Current + Right::Dimensions::Current,
Temperature = Left::Dimensions::Temperature +
Right::Dimensions::Temperature,
Amount = Left::Dimensions::Amount + Right::Dimensions::Amount,
LuminousIntensity = Left::Dimensions::LuminousIntensity +
Right:: Dimensions::LuminousIntensity,
Winding = Left::Dimensions::Winding + Right::Dimensions::Winding,
Angle = Left::Dimensions::Angle + Right::Dimensions::Angle,
SolidAngle = Left::Dimensions::SolidAngle +
Right::Dimensions::SolidAngle
};
using Type = typename Collapse<
Quantity<Dimensions<Length, Mass, Time, Current, Temperature, Amount,
LuminousIntensity, Winding, Angle,
SolidAngle>>>::Type;
};
template<typename Left>
struct ProductGenerator<Left, double> { using Type = Left; };
template<typename Right>
struct ProductGenerator<double, Right> { using Type = Right; };
template<>
struct ProductGenerator<double, double> {
using Type = double;
};
template<typename Left, typename Right>
struct QuotientGenerator {
enum {
Length = Left::Dimensions::Length - Right::Dimensions::Length,
Mass = Left::Dimensions::Mass - Right::Dimensions::Mass,
Time = Left::Dimensions::Time - Right::Dimensions::Time,
Current = Left::Dimensions::Current - Right::Dimensions::Current,
Temperature = Left::Dimensions::Temperature -
Right::Dimensions::Temperature,
Amount = Left::Dimensions::Amount - Right::Dimensions::Amount,
LuminousIntensity = Left::Dimensions::LuminousIntensity -
Right:: Dimensions::LuminousIntensity,
Winding = Left::Dimensions::Winding - Right::Dimensions::Winding,
Angle = Left::Dimensions::Angle - Right::Dimensions::Angle,
SolidAngle = Left::Dimensions::SolidAngle -
Right::Dimensions::SolidAngle
};
using Type = typename Collapse<
Quantity<Dimensions<Length, Mass, Time, Current, Temperature, Amount,
LuminousIntensity, Winding, Angle,
SolidAngle>>>::Type;
};
template<typename Left>
struct QuotientGenerator<Left, double> { using Type = Left; };
template<>
struct QuotientGenerator<double, double> {
using Type = double;
};
template<typename Right>
struct QuotientGenerator<double, Right> {
enum {
Length = -Right::Dimensions::Length,
Mass = -Right::Dimensions::Mass,
Time = -Right::Dimensions::Time,
Current = -Right::Dimensions::Current,
Temperature = -Right::Dimensions::Temperature,
Amount = -Right::Dimensions::Amount,
LuminousIntensity = -Right::Dimensions::LuminousIntensity,
Winding = -Right::Dimensions::Winding,
Angle = -Right::Dimensions::Angle,
SolidAngle = -Right::Dimensions::SolidAngle
};
using Type = Quantity<
Dimensions<Length, Mass, Time, Current, Temperature, Amount,
LuminousIntensity, Winding, Angle, SolidAngle>>;
};
template<typename T, int exponent>
struct ExponentiationGenerator<T, exponent, std::enable_if_t<(exponent > 1)>> {
using Type = Product<typename ExponentiationGenerator<T, exponent - 1>::Type,
T>;
};
template<typename T, int exponent>
struct ExponentiationGenerator<T, exponent, std::enable_if_t<(exponent < 1)>>{
using Type = Quotient<typename ExponentiationGenerator<T, exponent + 1>::Type,
T>;
};
template<typename T, int exponent>
struct ExponentiationGenerator<T, exponent, std::enable_if_t<(exponent == 1)>>{
using Type = T;
};
} // namespace internal
template<typename D>
inline Quantity<D>::Quantity() : magnitude_(0) {}
template<typename D>
inline Quantity<D>::Quantity(double const magnitude) : magnitude_(magnitude) {}
template<typename D>
inline Quantity<D>& Quantity<D>::operator+=(Quantity const& right) {
magnitude_ += right.magnitude_;
return *this;
}
template<typename D>
inline Quantity<D>& Quantity<D>::operator-=(Quantity const& right) {
magnitude_ -= right.magnitude_;
return *this;
}
template<typename D>
inline Quantity<D>& Quantity<D>::operator*=(double const right) {
magnitude_ *= right;
return *this;
}
template<typename D>
inline Quantity<D>& Quantity<D>::operator/=(double const right) {
magnitude_ /= right;
return *this;
}
// Additive group
template<typename D>
inline Quantity<D> Quantity<D>::operator+() const {
return *this;
}
template<typename D>
inline Quantity<D> Quantity<D>::operator-() const {
return Quantity(-magnitude_);
}
template<typename D>
inline Quantity<D> Quantity<D>::operator+(Quantity const& right) const {
return Quantity(magnitude_ + right.magnitude_);
}
template<typename D>
inline Quantity<D> Quantity<D>::operator-(Quantity const& right) const {
return Quantity(magnitude_ - right.magnitude_);
}
// Comparison operators
template<typename D>
inline bool Quantity<D>::operator>(Quantity const& right) const {
return magnitude_ > right.magnitude_;
}
template<typename D>
inline bool Quantity<D>::operator<(Quantity const& right) const {
return magnitude_ < right.magnitude_;
}
template<typename D>
inline bool Quantity<D>::operator>=(Quantity const& right) const {
return magnitude_ >= right.magnitude_;
}
template<typename D>
inline bool Quantity<D>::operator<=(Quantity const& right) const {
return magnitude_ <= right.magnitude_;
}
template<typename D>
inline bool Quantity<D>::operator==(Quantity const& right) const {
return magnitude_ == right.magnitude_;
}
template<typename D>
inline bool Quantity<D>::operator!=(Quantity const& right) const {
return magnitude_ != right.magnitude_;
}
template<typename D>
void Quantity<D>::WriteToMessage(
not_null<serialization::Quantity*> const message) const {
message->set_dimensions(D::representation);
message->set_magnitude(magnitude_);
}
template<typename D>
Quantity<D> Quantity<D>::ReadFromMessage(
serialization::Quantity const& message) {
CHECK_EQ(D::representation, message.dimensions());
return Quantity(message.magnitude());
}
// Multiplicative group
template<typename D>
inline Quantity<D> Quantity<D>::operator/(double const right) const {
return Quantity(magnitude_ / right);
}
template<typename D>
inline Quantity<D> Quantity<D>::operator*(double const right) const {
return Quantity(magnitude_ * right);
}
template<typename LDimensions, typename RDimensions>
inline internal::Product<Quantity<LDimensions>, Quantity<RDimensions>>
operator*(Quantity<LDimensions> const& left,
Quantity<RDimensions> const& right) {
return Product<Quantity<LDimensions>,
Quantity<RDimensions>>(left.magnitude_ * right.magnitude_);
}
template<typename LDimensions, typename RDimensions>
inline internal::Quotient<Quantity<LDimensions>, Quantity<RDimensions>>
operator/(Quantity<LDimensions> const& left,
Quantity<RDimensions> const& right) {
return Quotient<Quantity<LDimensions>,
Quantity<RDimensions>>(left.magnitude_ / right.magnitude_);
}
template<typename RDimensions>
FORCE_INLINE Quantity<RDimensions> operator*(
double const left,
Quantity<RDimensions> const& right) {
return Quantity<RDimensions>(left * right.magnitude_);
}
template<typename RDimensions>
inline typename Quantity<RDimensions>::Inverse operator/(
double const left,
Quantity<RDimensions> const& right) {
return typename Quantity<RDimensions>::Inverse(left / right.magnitude_);
}
template<int exponent>
inline double Pow(double x) {
return std::pow(x, exponent);
}
// Static specializations for frequently-used exponents, so that this gets
// turned into multiplications at compile time.
template<>
inline double Pow<-3>(double x) {
return 1 / (x * x * x);
}
template<>
inline double Pow<-2>(double x) {
return 1 / (x * x);
}
template<>
inline double Pow<-1>(double x) {
return 1 / x;
}
template<>
inline double Pow<0>(double x) {
return 1;
}
template<>
inline double Pow<1>(double x) {
return x;
}
template<>
inline double Pow<2>(double x) {
return x * x;
}
template<>
inline double Pow<3>(double x) {
return x * x * x;
}
template<int exponent, typename D>
Exponentiation<Quantity<D>, exponent> Pow(
Quantity<D> const& x) {
return Exponentiation<Quantity<D>, exponent>(
Pow<exponent>(x.magnitude_));
}
inline double Abs(double const x) {
return std::abs(x);
}
template<typename D>
Quantity<D> Abs(Quantity<D> const& quantity) {
return Quantity<D>(std::abs(quantity.magnitude_));
}
template<typename Q>
inline Q SIUnit() {
return Q(1);
}
template<>
inline double SIUnit<double>() {
return 1;
}
inline std::string FormatUnit(std::string const& name, int const exponent) {
switch (exponent) {
case 0:
return "";
break;
case 1:
return " " + name;
default:
return " " + name + "^" + std::to_string(exponent);
}
}
inline std::string DebugString(double const number, int const precision) {
char result[50];
#if OS_WIN
unsigned int old_exponent_format = _set_output_format(_TWO_DIGIT_EXPONENT);
int const size = sprintf_s(result,
("%+." + std::to_string(precision) + "e").c_str(),
number);
_set_output_format(old_exponent_format);
#else
int const size = snprintf(result, sizeof(result),
("%+." + std::to_string(precision) + "e").c_str(),
number);
#endif
CHECK_LE(0, size);
return std::string(result, size);
}
template<typename D>
std::string DebugString(Quantity<D> const& quantity, int const precision) {
return DebugString(quantity.magnitude_, precision) +
FormatUnit("m", D::Length) + FormatUnit("kg", D::Mass) +
FormatUnit("s", D::Time) + FormatUnit("A", D::Current) +
FormatUnit("K", D::Temperature) + FormatUnit("mol", D::Amount) +
FormatUnit("cd", D::LuminousIntensity) + FormatUnit("cycle", D::Winding) +
FormatUnit("rad", D::Angle) + FormatUnit("sr", D::SolidAngle);
}
template<typename D>
std::ostream& operator<<(std::ostream& out, Quantity<D> const& quantity) {
return out << DebugString(quantity);
}
} // namespace quantities
} // namespace principia
<|endoftext|>
|
<commit_before>
#include <string>
#include "glog/logging.h"
#include "gtest/gtest.h"
#include "quantities/astronomy.hpp"
#include "quantities/BIPM.hpp"
#include "quantities/constants.hpp"
#include "quantities/dimensionless.hpp"
#include "quantities/elementary_functions.hpp"
#include "quantities/quantities.hpp"
#include "quantities/si.hpp"
#include "quantities/uk.hpp"
#include "testing_utilities/algebra.hpp"
#include "testing_utilities/almost_equals.hpp"
#include "testing_utilities/explicit_operators.hpp"
#include "testing_utilities/numerics.hpp"
using principia::astronomy::EarthMass;
using principia::astronomy::JulianYear;
using principia::astronomy::JupiterMass;
using principia::astronomy::LightYear;
using principia::astronomy::LunarDistance;
using principia::astronomy::Parsec;
using principia::astronomy::SolarMass;
using principia::constants::ElectronMass;
using principia::constants::GravitationalConstant;
using principia::constants::SpeedOfLight;
using principia::constants::StandardGravity;
using principia::constants::VacuumPermeability;
using principia::constants::VacuumPermittivity;
using principia::quantities::Abs;
using principia::quantities::Cos;
using principia::quantities::Dimensionless;
using principia::quantities::Exp;
using principia::quantities::Log;
using principia::quantities::Log10;
using principia::quantities::Log2;
using principia::quantities::Mass;
using principia::quantities::Product;
using principia::quantities::Sin;
using principia::quantities::Speed;
using principia::quantities::Sqrt;
using principia::si::Ampere;
using principia::si::AstronomicalUnit;
using principia::si::Candela;
using principia::si::Cycle;
using principia::si::Day;
using principia::si::Degree;
using principia::si::Hour;
using principia::si::Kelvin;
using principia::si::Kilogram;
using principia::si::Mega;
using principia::si::Metre;
using principia::si::Mole;
using principia::si::Radian;
using principia::si::Second;
using principia::si::Steradian;
using principia::testing_utilities::AbsoluteError;
using principia::testing_utilities::AlmostEquals;
using principia::testing_utilities::RelativeError;
using principia::testing_utilities::Times;
using principia::uk::Foot;
using principia::uk::Furlong;
using principia::uk::Mile;
using principia::uk::Rood;
using testing::Lt;
namespace principia {
namespace geometry {
class QuantitiesTest : public testing::Test {
protected:
};
TEST_F(QuantitiesTest, AbsoluteValue) {
EXPECT_EQ(Abs(-1729), Dimensionless(1729));
EXPECT_EQ(Abs(1729), Dimensionless(1729));
}
TEST_F(QuantitiesTest, DimensionlessComparisons) {
testing_utilities::TestOrder(Dimensionless(0), Dimensionless(1));
testing_utilities::TestOrder(Dimensionless(-1), Dimensionless(0));
testing_utilities::TestOrder(-e, e);
testing_utilities::TestOrder(Dimensionless(3), π);
testing_utilities::TestOrder(Dimensionless(42), Dimensionless(1729));
}
TEST_F(QuantitiesTest, DimensionfulComparisons) {
testing_utilities::TestOrder(EarthMass, JupiterMass);
testing_utilities::TestOrder(LightYear, Parsec);
testing_utilities::TestOrder(-SpeedOfLight, SpeedOfLight);
testing_utilities::TestOrder(SpeedOfLight * Day, LightYear);
}
TEST_F(QuantitiesTest, DimensionlessOperations) {
Dimensionless const zero = 0;
Dimensionless const one = 1;
Dimensionless const taxi = 1729;
Dimensionless const answer = 42;
Dimensionless const heegner = 163;
testing_utilities::TestField(
zero, one, taxi, 4 * π / 3, heegner, answer, -e, 2);
}
TEST_F(QuantitiesTest, DimensionlfulOperations) {
Dimensionless const zero = 0;
Dimensionless const one = 1;
Dimensionless const taxi = 1729;
testing_utilities::TestVectorSpace(
0 * Metre / Second, SpeedOfLight, 88 * Mile / Hour,
-340.29 * Metre / Second, zero, one, -2 * π, taxi, 2);
// Dimensionful multiplication is a tensor product, see [Tao 2012].
testing_utilities::TestBilinearMap(
Times<Product<Mass, Speed>, Mass, Speed>, SolarMass,
ElectronMass, SpeedOfLight, 1 * Furlong / JulianYear, -e, 2);
}
TEST_F(QuantitiesTest, DimensionlessExponentiation) {
Dimensionless const number = π - 42;
Dimensionless positivePowers = 1;
Dimensionless negativePowers = 1;
EXPECT_EQ(Dimensionless(1), number.Pow<0>());
for (int i = 1; i < 10; ++i) {
positivePowers *= number;
negativePowers /= number;
EXPECT_THAT(number.Pow(i), AlmostEquals(positivePowers, i));
EXPECT_THAT(number.Pow(-i), AlmostEquals(negativePowers, i));
}
}
// The Greek letters cause a warning when stringified by the macros, because
// apparently Visual Studio doesn't encode strings in UTF-8 by default.
#pragma warning(disable: 4566)
TEST_F(QuantitiesTest, Formatting) {
auto const allTheUnits = 1 * Metre * Kilogram * Second * Ampere * Kelvin /
(Mole * Candela * Cycle * Radian * Steradian);
std::string const expected = std::string("1e+000 m kg s A K mol^-1") +
" cd^-1 cycle^-1 rad^-1 sr^-1";
std::string const actual = ToString(allTheUnits, 0);
EXPECT_EQ(expected, actual);
std::string π16 = "3.1415926535897931e+000";
EXPECT_EQ(ToString(π), π16);
}
TEST_F(QuantitiesTest, PhysicalConstants) {
// By definition.
EXPECT_THAT(1 / SpeedOfLight.Pow<2>(),
AlmostEquals(VacuumPermittivity * VacuumPermeability, 2));
// The Keplerian approximation for the mass of the Sun
// is fairly accurate.
EXPECT_THAT(RelativeError(
4 * π.Pow<2>() * AstronomicalUnit.Pow<3>() /
(GravitationalConstant * JulianYear.Pow<2>()),
SolarMass),
Lt(4E-5));
EXPECT_THAT(RelativeError(1 * Parsec, 3.26156 * LightYear), Lt(2E-6));
// The Keplerian approximation for the mass of the Earth
// is pretty bad, but the error is still only 1%.
EXPECT_THAT(RelativeError(
4 * π.Pow<2>() * LunarDistance.Pow<3>() /
(GravitationalConstant * (27.321582 * Day).Pow<2>()),
EarthMass),
Lt(1E-2));
EXPECT_THAT(RelativeError(1 * SolarMass, 1047 * JupiterMass), Lt(4E-4));
// Delambre & Méchain.
EXPECT_THAT(RelativeError(
GravitationalConstant * EarthMass /
(40 * Mega(Metre) / (2 * π)).Pow<2>(),
StandardGravity),
Lt(4E-3));
// Talleyrand.
EXPECT_THAT(RelativeError(π * Sqrt(1 * Metre / StandardGravity), 1 * Second),
Lt(4E-3));
}
#pragma warning(default: 4566)
TEST_F(QuantitiesTest, TrigonometricFunctions) {
EXPECT_EQ(Cos(0 * Degree), 1);
EXPECT_EQ(Sin(0 * Degree), 0);
EXPECT_THAT(AbsoluteError(Cos(90 * Degree), 0), Lt(1E-16));
EXPECT_EQ(Sin(90 * Degree), 1);
EXPECT_EQ(Cos(180 * Degree), -1);
EXPECT_THAT(AbsoluteError(Sin(180 * Degree), 0), Lt(1E-15));
EXPECT_THAT(AbsoluteError(Cos(-90 * Degree), 0), Lt(1E-16));
EXPECT_EQ(Sin(-90 * Degree), -1);
for (int k = 1; k < 360; ++k) {
// Don't test for multiples of 90 degrees as zeros lead to horrible
// conditioning.
if (k % 90 != 0) {
EXPECT_THAT(Cos((90 - k) * Degree),
AlmostEquals(Sin(k * Degree), 50));
EXPECT_THAT(Sin(k * Degree) / Cos(k * Degree),
AlmostEquals(Tan(k * Degree), 2));
EXPECT_THAT(((k + 179) % 360 - 179) * Degree,
AlmostEquals(ArcTan(Sin(k * Degree), Cos(k * Degree)), 80));
EXPECT_THAT(((k + 179) % 360 - 179) * Degree,
AlmostEquals(ArcTan(Sin(k * Degree) * AstronomicalUnit,
Cos(k * Degree) * AstronomicalUnit), 80));
EXPECT_THAT(Cos(ArcCos(Cos(k * Degree))),
AlmostEquals(Cos(k * Degree), 10));
EXPECT_THAT(Sin(ArcSin(Sin(k * Degree))),
AlmostEquals(Sin(k * Degree), 1));
}
}
// Horribly conditioned near 0, so not in the loop above.
EXPECT_EQ(Tan(ArcTan(Tan(-42 * Degree))), Tan(-42 * Degree));
}
TEST_F(QuantitiesTest, HyperbolicFunctions) {
EXPECT_EQ(Sinh(0 * Radian), 0);
EXPECT_EQ(Cosh(0 * Radian), 1);
EXPECT_EQ(Tanh(0 * Radian), 0);
// Limits:
EXPECT_EQ(Sinh(20 * Radian), Cosh(20 * Radian));
EXPECT_EQ(Tanh(20 * Radian), 1);
EXPECT_EQ(Sinh(-20 * Radian), -Cosh(-20 * Radian));
EXPECT_EQ(Tanh(-20 * Radian), -1);
EXPECT_EQ(Sinh(2 * Radian) / Cosh(2 * Radian), Tanh(2 * Radian));
EXPECT_THAT(ArcSinh(Sinh(-10 * Degree)), AlmostEquals(-10 * Degree, 2));
EXPECT_THAT(ArcCosh(Cosh(-10 * Degree)), AlmostEquals(10 * Degree, 20));
EXPECT_THAT(ArcTanh(Tanh(-10 * Degree)), AlmostEquals(-10 * Degree, 1));
}
TEST_F(QuantitiesTest, ExpLogAndSqrt) {
EXPECT_EQ(Exp(1), e);
EXPECT_THAT(Exp(Log(4.2) + Log(1.729)), AlmostEquals(4.2 * 1.729, 1));
EXPECT_EQ(Exp(Log(2) * Log2(1.729)), 1.729);
EXPECT_EQ(Exp(Log(10) * Log10(1.729)), 1.729);
EXPECT_THAT(Exp(Log(2) / 2), AlmostEquals(Sqrt(2), 1));
EXPECT_EQ(Exp(Log(Rood / Foot.Pow<2>()) / 2) * Foot, Sqrt(Rood));
}
} // namespace geometry
} // namespace principia
<commit_msg>Unneeded Dimensionless<commit_after>
#include <string>
#include "glog/logging.h"
#include "gtest/gtest.h"
#include "quantities/astronomy.hpp"
#include "quantities/BIPM.hpp"
#include "quantities/constants.hpp"
#include "quantities/dimensionless.hpp"
#include "quantities/elementary_functions.hpp"
#include "quantities/quantities.hpp"
#include "quantities/si.hpp"
#include "quantities/uk.hpp"
#include "testing_utilities/algebra.hpp"
#include "testing_utilities/almost_equals.hpp"
#include "testing_utilities/explicit_operators.hpp"
#include "testing_utilities/numerics.hpp"
using principia::astronomy::EarthMass;
using principia::astronomy::JulianYear;
using principia::astronomy::JupiterMass;
using principia::astronomy::LightYear;
using principia::astronomy::LunarDistance;
using principia::astronomy::Parsec;
using principia::astronomy::SolarMass;
using principia::constants::ElectronMass;
using principia::constants::GravitationalConstant;
using principia::constants::SpeedOfLight;
using principia::constants::StandardGravity;
using principia::constants::VacuumPermeability;
using principia::constants::VacuumPermittivity;
using principia::quantities::Abs;
using principia::quantities::Cos;
using principia::quantities::Dimensionless;
using principia::quantities::Exp;
using principia::quantities::Log;
using principia::quantities::Log10;
using principia::quantities::Log2;
using principia::quantities::Mass;
using principia::quantities::Product;
using principia::quantities::Sin;
using principia::quantities::Speed;
using principia::quantities::Sqrt;
using principia::si::Ampere;
using principia::si::AstronomicalUnit;
using principia::si::Candela;
using principia::si::Cycle;
using principia::si::Day;
using principia::si::Degree;
using principia::si::Hour;
using principia::si::Kelvin;
using principia::si::Kilogram;
using principia::si::Mega;
using principia::si::Metre;
using principia::si::Mole;
using principia::si::Radian;
using principia::si::Second;
using principia::si::Steradian;
using principia::testing_utilities::AbsoluteError;
using principia::testing_utilities::AlmostEquals;
using principia::testing_utilities::RelativeError;
using principia::testing_utilities::Times;
using principia::uk::Foot;
using principia::uk::Furlong;
using principia::uk::Mile;
using principia::uk::Rood;
using testing::Lt;
namespace principia {
namespace geometry {
class QuantitiesTest : public testing::Test {
protected:
};
TEST_F(QuantitiesTest, AbsoluteValue) {
EXPECT_EQ(Abs(-1729), 1729);
EXPECT_EQ(Abs(1729), 1729);
}
TEST_F(QuantitiesTest, DimensionlessComparisons) {
testing_utilities::TestOrder(Dimensionless(0), Dimensionless(1));
testing_utilities::TestOrder(Dimensionless(-1), Dimensionless(0));
testing_utilities::TestOrder(-e, e);
testing_utilities::TestOrder(Dimensionless(3), π);
testing_utilities::TestOrder(Dimensionless(42), Dimensionless(1729));
}
TEST_F(QuantitiesTest, DimensionfulComparisons) {
testing_utilities::TestOrder(EarthMass, JupiterMass);
testing_utilities::TestOrder(LightYear, Parsec);
testing_utilities::TestOrder(-SpeedOfLight, SpeedOfLight);
testing_utilities::TestOrder(SpeedOfLight * Day, LightYear);
}
TEST_F(QuantitiesTest, DimensionlessOperations) {
Dimensionless const zero = 0;
Dimensionless const one = 1;
Dimensionless const taxi = 1729;
Dimensionless const answer = 42;
Dimensionless const heegner = 163;
testing_utilities::TestField(
zero, one, taxi, 4 * π / 3, heegner, answer, -e, 2);
}
TEST_F(QuantitiesTest, DimensionlfulOperations) {
Dimensionless const zero = 0;
Dimensionless const one = 1;
Dimensionless const taxi = 1729;
testing_utilities::TestVectorSpace(
0 * Metre / Second, SpeedOfLight, 88 * Mile / Hour,
-340.29 * Metre / Second, zero, one, -2 * π, taxi, 2);
// Dimensionful multiplication is a tensor product, see [Tao 2012].
testing_utilities::TestBilinearMap(
Times<Product<Mass, Speed>, Mass, Speed>, SolarMass,
ElectronMass, SpeedOfLight, 1 * Furlong / JulianYear, -e, 2);
}
TEST_F(QuantitiesTest, DimensionlessExponentiation) {
Dimensionless const number = π - 42;
Dimensionless positivePowers = 1;
Dimensionless negativePowers = 1;
EXPECT_EQ(1, number.Pow<0>());
for (int i = 1; i < 10; ++i) {
positivePowers *= number;
negativePowers /= number;
EXPECT_THAT(number.Pow(i), AlmostEquals(positivePowers, i));
EXPECT_THAT(number.Pow(-i), AlmostEquals(negativePowers, i));
}
}
// The Greek letters cause a warning when stringified by the macros, because
// apparently Visual Studio doesn't encode strings in UTF-8 by default.
#pragma warning(disable: 4566)
TEST_F(QuantitiesTest, Formatting) {
auto const allTheUnits = 1 * Metre * Kilogram * Second * Ampere * Kelvin /
(Mole * Candela * Cycle * Radian * Steradian);
std::string const expected = std::string("1e+000 m kg s A K mol^-1") +
" cd^-1 cycle^-1 rad^-1 sr^-1";
std::string const actual = ToString(allTheUnits, 0);
EXPECT_EQ(expected, actual);
std::string π16 = "3.1415926535897931e+000";
EXPECT_EQ(ToString(π), π16);
}
TEST_F(QuantitiesTest, PhysicalConstants) {
// By definition.
EXPECT_THAT(1 / SpeedOfLight.Pow<2>(),
AlmostEquals(VacuumPermittivity * VacuumPermeability, 2));
// The Keplerian approximation for the mass of the Sun
// is fairly accurate.
EXPECT_THAT(RelativeError(
4 * π.Pow<2>() * AstronomicalUnit.Pow<3>() /
(GravitationalConstant * JulianYear.Pow<2>()),
SolarMass),
Lt(4E-5));
EXPECT_THAT(RelativeError(1 * Parsec, 3.26156 * LightYear), Lt(2E-6));
// The Keplerian approximation for the mass of the Earth
// is pretty bad, but the error is still only 1%.
EXPECT_THAT(RelativeError(
4 * π.Pow<2>() * LunarDistance.Pow<3>() /
(GravitationalConstant * (27.321582 * Day).Pow<2>()),
EarthMass),
Lt(1E-2));
EXPECT_THAT(RelativeError(1 * SolarMass, 1047 * JupiterMass), Lt(4E-4));
// Delambre & Méchain.
EXPECT_THAT(RelativeError(
GravitationalConstant * EarthMass /
(40 * Mega(Metre) / (2 * π)).Pow<2>(),
StandardGravity),
Lt(4E-3));
// Talleyrand.
EXPECT_THAT(RelativeError(π * Sqrt(1 * Metre / StandardGravity), 1 * Second),
Lt(4E-3));
}
#pragma warning(default: 4566)
TEST_F(QuantitiesTest, TrigonometricFunctions) {
EXPECT_EQ(Cos(0 * Degree), 1);
EXPECT_EQ(Sin(0 * Degree), 0);
EXPECT_THAT(AbsoluteError(Cos(90 * Degree), 0), Lt(1E-16));
EXPECT_EQ(Sin(90 * Degree), 1);
EXPECT_EQ(Cos(180 * Degree), -1);
EXPECT_THAT(AbsoluteError(Sin(180 * Degree), 0), Lt(1E-15));
EXPECT_THAT(AbsoluteError(Cos(-90 * Degree), 0), Lt(1E-16));
EXPECT_EQ(Sin(-90 * Degree), -1);
for (int k = 1; k < 360; ++k) {
// Don't test for multiples of 90 degrees as zeros lead to horrible
// conditioning.
if (k % 90 != 0) {
EXPECT_THAT(Cos((90 - k) * Degree),
AlmostEquals(Sin(k * Degree), 50));
EXPECT_THAT(Sin(k * Degree) / Cos(k * Degree),
AlmostEquals(Tan(k * Degree), 2));
EXPECT_THAT(((k + 179) % 360 - 179) * Degree,
AlmostEquals(ArcTan(Sin(k * Degree), Cos(k * Degree)), 80));
EXPECT_THAT(((k + 179) % 360 - 179) * Degree,
AlmostEquals(ArcTan(Sin(k * Degree) * AstronomicalUnit,
Cos(k * Degree) * AstronomicalUnit), 80));
EXPECT_THAT(Cos(ArcCos(Cos(k * Degree))),
AlmostEquals(Cos(k * Degree), 10));
EXPECT_THAT(Sin(ArcSin(Sin(k * Degree))),
AlmostEquals(Sin(k * Degree), 1));
}
}
// Horribly conditioned near 0, so not in the loop above.
EXPECT_EQ(Tan(ArcTan(Tan(-42 * Degree))), Tan(-42 * Degree));
}
TEST_F(QuantitiesTest, HyperbolicFunctions) {
EXPECT_EQ(Sinh(0 * Radian), 0);
EXPECT_EQ(Cosh(0 * Radian), 1);
EXPECT_EQ(Tanh(0 * Radian), 0);
// Limits:
EXPECT_EQ(Sinh(20 * Radian), Cosh(20 * Radian));
EXPECT_EQ(Tanh(20 * Radian), 1);
EXPECT_EQ(Sinh(-20 * Radian), -Cosh(-20 * Radian));
EXPECT_EQ(Tanh(-20 * Radian), -1);
EXPECT_EQ(Sinh(2 * Radian) / Cosh(2 * Radian), Tanh(2 * Radian));
EXPECT_THAT(ArcSinh(Sinh(-10 * Degree)), AlmostEquals(-10 * Degree, 2));
EXPECT_THAT(ArcCosh(Cosh(-10 * Degree)), AlmostEquals(10 * Degree, 20));
EXPECT_THAT(ArcTanh(Tanh(-10 * Degree)), AlmostEquals(-10 * Degree, 1));
}
TEST_F(QuantitiesTest, ExpLogAndSqrt) {
EXPECT_EQ(Exp(1), e);
EXPECT_THAT(Exp(Log(4.2) + Log(1.729)), AlmostEquals(4.2 * 1.729, 1));
EXPECT_EQ(Exp(Log(2) * Log2(1.729)), 1.729);
EXPECT_EQ(Exp(Log(10) * Log10(1.729)), 1.729);
EXPECT_THAT(Exp(Log(2) / 2), AlmostEquals(Sqrt(2), 1));
EXPECT_EQ(Exp(Log(Rood / Foot.Pow<2>()) / 2) * Foot, Sqrt(Rood));
}
} // namespace geometry
} // namespace principia
<|endoftext|>
|
<commit_before>#include <string>
#include "glog/logging.h"
#include "gtest/gtest.h"
#include "quantities/astronomy.hpp"
#include "quantities/BIPM.hpp"
#include "quantities/constants.hpp"
#include "quantities/dimensionless.hpp"
#include "quantities/elementary_functions.hpp"
#include "quantities/quantities.hpp"
#include "quantities/si.hpp"
#include "quantities/uk.hpp"
#include "testing_utilities/algebra.hpp"
#include "testing_utilities/almost_equals.hpp"
#include "testing_utilities/explicit_operators.hpp"
#include "testing_utilities/numerics.hpp"
using principia::astronomy::EarthMass;
using principia::astronomy::JulianYear;
using principia::astronomy::JupiterMass;
using principia::astronomy::LightYear;
using principia::astronomy::LunarDistance;
using principia::astronomy::Parsec;
using principia::astronomy::SolarMass;
using principia::constants::ElectronMass;
using principia::constants::GravitationalConstant;
using principia::constants::SpeedOfLight;
using principia::constants::StandardGravity;
using principia::constants::VacuumPermeability;
using principia::constants::VacuumPermittivity;
using principia::quantities::Abs;
using principia::quantities::Cos;
using principia::quantities::Dimensionless;
using principia::quantities::Exp;
using principia::quantities::Log;
using principia::quantities::Log10;
using principia::quantities::Log2;
using principia::quantities::Mass;
using principia::quantities::Product;
using principia::quantities::Sin;
using principia::quantities::Speed;
using principia::quantities::Sqrt;
using principia::si::Ampere;
using principia::si::AstronomicalUnit;
using principia::si::Candela;
using principia::si::Cycle;
using principia::si::Day;
using principia::si::Degree;
using principia::si::Hour;
using principia::si::Kelvin;
using principia::si::Kilogram;
using principia::si::Mega;
using principia::si::Metre;
using principia::si::Mole;
using principia::si::Radian;
using principia::si::Second;
using principia::si::Steradian;
using principia::testing_utilities::AbsoluteError;
using principia::testing_utilities::AlmostEquals;
using principia::testing_utilities::RelativeError;
using principia::testing_utilities::Times;
using principia::uk::Foot;
using principia::uk::Furlong;
using principia::uk::Mile;
using principia::uk::Rood;
using testing::Lt;
namespace principia {
namespace geometry {
class QuantitiesTest : public testing::Test {
protected:
};
TEST_F(QuantitiesTest, AbsoluteValue) {
EXPECT_EQ(Abs(-1729), Dimensionless(1729));
EXPECT_EQ(Abs(1729), Dimensionless(1729));
}
TEST_F(QuantitiesTest, DimensionlessComparisons) {
testing_utilities::TestOrder(Dimensionless(0), Dimensionless(1));
testing_utilities::TestOrder(Dimensionless(-1), Dimensionless(0));
testing_utilities::TestOrder(-e, e);
testing_utilities::TestOrder(Dimensionless(3), π);
testing_utilities::TestOrder(Dimensionless(42), Dimensionless(1729));
}
TEST_F(QuantitiesTest, DimensionfulComparisons) {
testing_utilities::TestOrder(EarthMass, JupiterMass);
testing_utilities::TestOrder(LightYear, Parsec);
testing_utilities::TestOrder(-SpeedOfLight, SpeedOfLight);
testing_utilities::TestOrder(SpeedOfLight * Day, LightYear);
}
TEST_F(QuantitiesTest, DimensionlessOperations) {
Dimensionless const zero = 0;
Dimensionless const one = 1;
Dimensionless const taxi = 1729;
Dimensionless const answer = 42;
Dimensionless const heegner = 163;
testing_utilities::TestField(
zero, one, taxi, 4 * π / 3, heegner, answer, -e, 2);
}
TEST_F(QuantitiesTest, DimensionlfulOperations) {
Dimensionless const zero = 0;
Dimensionless const one = 1;
Dimensionless const taxi = 1729;
testing_utilities::TestVectorSpace(
0 * Metre / Second, SpeedOfLight, 88 * Mile / Hour,
-340.29 * Metre / Second, zero, one, -2 * π, taxi, 2);
// Dimensionful multiplication is a tensor product, see [Tao 2012].
testing_utilities::TestBilinearMap(
Times<Product<Mass, Speed>, Mass, Speed>, SolarMass,
ElectronMass, SpeedOfLight, 1 * Furlong / JulianYear, -e, 2);
}
TEST_F(QuantitiesTest, DimensionlessExponentiation) {
Dimensionless const number = π - 42;
Dimensionless positivePowers = 1;
Dimensionless negativePowers = 1;
EXPECT_EQ(Dimensionless(1), number.Pow<0>());
for (int i = 1; i < 10; ++i) {
positivePowers *= number;
negativePowers /= number;
EXPECT_THAT(number.Pow(i), AlmostEquals(positivePowers, i));
EXPECT_THAT(number.Pow(-i), AlmostEquals(negativePowers, i));
}
}
// The Greek letters cause a warning when stringified by the macros, because
// apparently Visual Studio doesn't encode strings in UTF-8 by default.
#pragma warning(disable: 4566)
TEST_F(QuantitiesTest, Formatting) {
auto const allTheUnits = 1 * Metre * Kilogram * Second * Ampere * Kelvin /
(Mole * Candela * Cycle * Radian * Steradian);
std::string const expected = std::string("1e+000 m kg s A K mol^-1") +
" cd^-1 cycle^-1 rad^-1 sr^-1";
std::string const actual = ToString(allTheUnits, 0);
EXPECT_EQ(expected, actual);
std::string π16 = "3.1415926535897931e+000";
EXPECT_EQ(ToString(π), π16);
}
TEST_F(QuantitiesTest, PhysicalConstants) {
// By definition.
EXPECT_THAT(1 / SpeedOfLight.Pow<2>(),
AlmostEquals(VacuumPermittivity * VacuumPermeability, 2));
// The Keplerian approximation for the mass of the Sun
// is fairly accurate.
EXPECT_THAT(RelativeError(
4 * π.Pow<2>() * AstronomicalUnit.Pow<3>() /
(GravitationalConstant * JulianYear.Pow<2>()),
SolarMass),
Lt(4E-5));
EXPECT_THAT(RelativeError(1 * Parsec, 3.26156 * LightYear), Lt(2E-6));
// The Keplerian approximation for the mass of the Earth
// is pretty bad, but the error is still only 1%.
EXPECT_THAT(RelativeError(
4 * π.Pow<2>() * LunarDistance.Pow<3>() /
(GravitationalConstant * (27.321582 * Day).Pow<2>()),
EarthMass),
Lt(1E-2));
EXPECT_THAT(RelativeError(1 * SolarMass, 1047 * JupiterMass), Lt(4E-4));
// Delambre & Méchain.
EXPECT_THAT(RelativeError(
GravitationalConstant * EarthMass /
(40 * Mega(Metre) / (2 * π)).Pow<2>(),
StandardGravity),
Lt(4E-3));
// Talleyrand.
EXPECT_THAT(RelativeError(π * Sqrt(1 * Metre / StandardGravity), 1 * Second),
Lt(4E-3));
}
#pragma warning(default: 4566)
TEST_F(QuantitiesTest, TrigonometricFunctions) {
EXPECT_EQ(Cos(0 * Degree), 1);
EXPECT_EQ(Sin(0 * Degree), 0);
EXPECT_THAT(AbsoluteError(Cos(90 * Degree), 0), Lt(1E-16));
EXPECT_EQ(Sin(90 * Degree), 1);
EXPECT_EQ(Cos(180 * Degree), -1);
EXPECT_THAT(AbsoluteError(Sin(180 * Degree), 0), Lt(1E-15));
EXPECT_THAT(AbsoluteError(Cos(-90 * Degree), 0), Lt(1E-16));
EXPECT_EQ(Sin(-90 * Degree), -1);
for (int k = 1; k < 360; ++k) {
// Don't test for multiples of 90 degrees as zeros lead to horrible
// conditioning.
if (k % 90 != 0) {
EXPECT_THAT(Cos((90 - k) * Degree),
AlmostEquals(Sin(k * Degree), 50));
EXPECT_THAT(Sin(k * Degree) / Cos(k * Degree),
AlmostEquals(Tan(k * Degree), 2));
EXPECT_THAT(((k + 179) % 360 - 179) * Degree,
AlmostEquals(ArcTan(Sin(k * Degree), Cos(k * Degree)), 80));
EXPECT_THAT(((k + 179) % 360 - 179) * Degree,
AlmostEquals(ArcTan(Sin(k * Degree) * AstronomicalUnit,
Cos(k * Degree) * AstronomicalUnit), 80));
EXPECT_THAT(Cos(ArcCos(Cos(k * Degree))),
AlmostEquals(Cos(k * Degree), 10));
EXPECT_THAT(Sin(ArcSin(Sin(k * Degree))),
AlmostEquals(Sin(k * Degree), 1));
}
}
// Horribly conditioned near 0, so not in the loop above.
EXPECT_EQ(Tan(ArcTan(Tan(-42 * Degree))), Tan(-42 * Degree));
}
TEST_F(QuantitiesTest, HyperbolicFunctions) {
EXPECT_EQ(Sinh(0 * Radian), 0);
EXPECT_EQ(Cosh(0 * Radian), 1);
EXPECT_EQ(Tanh(0 * Radian), 0);
// Limits:
EXPECT_EQ(Sinh(20 * Radian), Cosh(20 * Radian));
EXPECT_EQ(Tanh(20 * Radian), 1);
EXPECT_EQ(Sinh(-20 * Radian), -Cosh(-20 * Radian));
EXPECT_EQ(Tanh(-20 * Radian), -1);
EXPECT_EQ(Sinh(2 * Radian) / Cosh(2 * Radian), Tanh(2 * Radian));
EXPECT_THAT(ArcSinh(Sinh(-10 * Degree)), AlmostEquals(-10 * Degree, 2));
EXPECT_THAT(ArcCosh(Cosh(-10 * Degree)), AlmostEquals(10 * Degree, 20));
EXPECT_THAT(ArcTanh(Tanh(-10 * Degree)), AlmostEquals(-10 * Degree, 1));
}
TEST_F(QuantitiesTest, ExpLogAndSqrt) {
EXPECT_EQ(Exp(1), e);
EXPECT_THAT(Exp(Log(4.2) + Log(1.729)), AlmostEquals(4.2 * 1.729, 1));
EXPECT_EQ(Exp(Log(2) * Log2(1.729)), 1.729);
EXPECT_EQ(Exp(Log(10) * Log10(1.729)), 1.729);
EXPECT_THAT(Exp(Log(2) / 2), AlmostEquals(Sqrt(2), 1));
EXPECT_EQ(Exp(Log(Rood / Foot.Pow<2>()) / 2) * Foot, Sqrt(Rood));
}
} // namespace geometry
} // namespace principia
<commit_msg>See if an empty line at the beginning helps the linter<commit_after>
#include <string>
#include "glog/logging.h"
#include "gtest/gtest.h"
#include "quantities/astronomy.hpp"
#include "quantities/BIPM.hpp"
#include "quantities/constants.hpp"
#include "quantities/dimensionless.hpp"
#include "quantities/elementary_functions.hpp"
#include "quantities/quantities.hpp"
#include "quantities/si.hpp"
#include "quantities/uk.hpp"
#include "testing_utilities/algebra.hpp"
#include "testing_utilities/almost_equals.hpp"
#include "testing_utilities/explicit_operators.hpp"
#include "testing_utilities/numerics.hpp"
using principia::astronomy::EarthMass;
using principia::astronomy::JulianYear;
using principia::astronomy::JupiterMass;
using principia::astronomy::LightYear;
using principia::astronomy::LunarDistance;
using principia::astronomy::Parsec;
using principia::astronomy::SolarMass;
using principia::constants::ElectronMass;
using principia::constants::GravitationalConstant;
using principia::constants::SpeedOfLight;
using principia::constants::StandardGravity;
using principia::constants::VacuumPermeability;
using principia::constants::VacuumPermittivity;
using principia::quantities::Abs;
using principia::quantities::Cos;
using principia::quantities::Dimensionless;
using principia::quantities::Exp;
using principia::quantities::Log;
using principia::quantities::Log10;
using principia::quantities::Log2;
using principia::quantities::Mass;
using principia::quantities::Product;
using principia::quantities::Sin;
using principia::quantities::Speed;
using principia::quantities::Sqrt;
using principia::si::Ampere;
using principia::si::AstronomicalUnit;
using principia::si::Candela;
using principia::si::Cycle;
using principia::si::Day;
using principia::si::Degree;
using principia::si::Hour;
using principia::si::Kelvin;
using principia::si::Kilogram;
using principia::si::Mega;
using principia::si::Metre;
using principia::si::Mole;
using principia::si::Radian;
using principia::si::Second;
using principia::si::Steradian;
using principia::testing_utilities::AbsoluteError;
using principia::testing_utilities::AlmostEquals;
using principia::testing_utilities::RelativeError;
using principia::testing_utilities::Times;
using principia::uk::Foot;
using principia::uk::Furlong;
using principia::uk::Mile;
using principia::uk::Rood;
using testing::Lt;
namespace principia {
namespace geometry {
class QuantitiesTest : public testing::Test {
protected:
};
TEST_F(QuantitiesTest, AbsoluteValue) {
EXPECT_EQ(Abs(-1729), Dimensionless(1729));
EXPECT_EQ(Abs(1729), Dimensionless(1729));
}
TEST_F(QuantitiesTest, DimensionlessComparisons) {
testing_utilities::TestOrder(Dimensionless(0), Dimensionless(1));
testing_utilities::TestOrder(Dimensionless(-1), Dimensionless(0));
testing_utilities::TestOrder(-e, e);
testing_utilities::TestOrder(Dimensionless(3), π);
testing_utilities::TestOrder(Dimensionless(42), Dimensionless(1729));
}
TEST_F(QuantitiesTest, DimensionfulComparisons) {
testing_utilities::TestOrder(EarthMass, JupiterMass);
testing_utilities::TestOrder(LightYear, Parsec);
testing_utilities::TestOrder(-SpeedOfLight, SpeedOfLight);
testing_utilities::TestOrder(SpeedOfLight * Day, LightYear);
}
TEST_F(QuantitiesTest, DimensionlessOperations) {
Dimensionless const zero = 0;
Dimensionless const one = 1;
Dimensionless const taxi = 1729;
Dimensionless const answer = 42;
Dimensionless const heegner = 163;
testing_utilities::TestField(
zero, one, taxi, 4 * π / 3, heegner, answer, -e, 2);
}
TEST_F(QuantitiesTest, DimensionlfulOperations) {
Dimensionless const zero = 0;
Dimensionless const one = 1;
Dimensionless const taxi = 1729;
testing_utilities::TestVectorSpace(
0 * Metre / Second, SpeedOfLight, 88 * Mile / Hour,
-340.29 * Metre / Second, zero, one, -2 * π, taxi, 2);
// Dimensionful multiplication is a tensor product, see [Tao 2012].
testing_utilities::TestBilinearMap(
Times<Product<Mass, Speed>, Mass, Speed>, SolarMass,
ElectronMass, SpeedOfLight, 1 * Furlong / JulianYear, -e, 2);
}
TEST_F(QuantitiesTest, DimensionlessExponentiation) {
Dimensionless const number = π - 42;
Dimensionless positivePowers = 1;
Dimensionless negativePowers = 1;
EXPECT_EQ(Dimensionless(1), number.Pow<0>());
for (int i = 1; i < 10; ++i) {
positivePowers *= number;
negativePowers /= number;
EXPECT_THAT(number.Pow(i), AlmostEquals(positivePowers, i));
EXPECT_THAT(number.Pow(-i), AlmostEquals(negativePowers, i));
}
}
// The Greek letters cause a warning when stringified by the macros, because
// apparently Visual Studio doesn't encode strings in UTF-8 by default.
#pragma warning(disable: 4566)
TEST_F(QuantitiesTest, Formatting) {
auto const allTheUnits = 1 * Metre * Kilogram * Second * Ampere * Kelvin /
(Mole * Candela * Cycle * Radian * Steradian);
std::string const expected = std::string("1e+000 m kg s A K mol^-1") +
" cd^-1 cycle^-1 rad^-1 sr^-1";
std::string const actual = ToString(allTheUnits, 0);
EXPECT_EQ(expected, actual);
std::string π16 = "3.1415926535897931e+000";
EXPECT_EQ(ToString(π), π16);
}
TEST_F(QuantitiesTest, PhysicalConstants) {
// By definition.
EXPECT_THAT(1 / SpeedOfLight.Pow<2>(),
AlmostEquals(VacuumPermittivity * VacuumPermeability, 2));
// The Keplerian approximation for the mass of the Sun
// is fairly accurate.
EXPECT_THAT(RelativeError(
4 * π.Pow<2>() * AstronomicalUnit.Pow<3>() /
(GravitationalConstant * JulianYear.Pow<2>()),
SolarMass),
Lt(4E-5));
EXPECT_THAT(RelativeError(1 * Parsec, 3.26156 * LightYear), Lt(2E-6));
// The Keplerian approximation for the mass of the Earth
// is pretty bad, but the error is still only 1%.
EXPECT_THAT(RelativeError(
4 * π.Pow<2>() * LunarDistance.Pow<3>() /
(GravitationalConstant * (27.321582 * Day).Pow<2>()),
EarthMass),
Lt(1E-2));
EXPECT_THAT(RelativeError(1 * SolarMass, 1047 * JupiterMass), Lt(4E-4));
// Delambre & Méchain.
EXPECT_THAT(RelativeError(
GravitationalConstant * EarthMass /
(40 * Mega(Metre) / (2 * π)).Pow<2>(),
StandardGravity),
Lt(4E-3));
// Talleyrand.
EXPECT_THAT(RelativeError(π * Sqrt(1 * Metre / StandardGravity), 1 * Second),
Lt(4E-3));
}
#pragma warning(default: 4566)
TEST_F(QuantitiesTest, TrigonometricFunctions) {
EXPECT_EQ(Cos(0 * Degree), 1);
EXPECT_EQ(Sin(0 * Degree), 0);
EXPECT_THAT(AbsoluteError(Cos(90 * Degree), 0), Lt(1E-16));
EXPECT_EQ(Sin(90 * Degree), 1);
EXPECT_EQ(Cos(180 * Degree), -1);
EXPECT_THAT(AbsoluteError(Sin(180 * Degree), 0), Lt(1E-15));
EXPECT_THAT(AbsoluteError(Cos(-90 * Degree), 0), Lt(1E-16));
EXPECT_EQ(Sin(-90 * Degree), -1);
for (int k = 1; k < 360; ++k) {
// Don't test for multiples of 90 degrees as zeros lead to horrible
// conditioning.
if (k % 90 != 0) {
EXPECT_THAT(Cos((90 - k) * Degree),
AlmostEquals(Sin(k * Degree), 50));
EXPECT_THAT(Sin(k * Degree) / Cos(k * Degree),
AlmostEquals(Tan(k * Degree), 2));
EXPECT_THAT(((k + 179) % 360 - 179) * Degree,
AlmostEquals(ArcTan(Sin(k * Degree), Cos(k * Degree)), 80));
EXPECT_THAT(((k + 179) % 360 - 179) * Degree,
AlmostEquals(ArcTan(Sin(k * Degree) * AstronomicalUnit,
Cos(k * Degree) * AstronomicalUnit), 80));
EXPECT_THAT(Cos(ArcCos(Cos(k * Degree))),
AlmostEquals(Cos(k * Degree), 10));
EXPECT_THAT(Sin(ArcSin(Sin(k * Degree))),
AlmostEquals(Sin(k * Degree), 1));
}
}
// Horribly conditioned near 0, so not in the loop above.
EXPECT_EQ(Tan(ArcTan(Tan(-42 * Degree))), Tan(-42 * Degree));
}
TEST_F(QuantitiesTest, HyperbolicFunctions) {
EXPECT_EQ(Sinh(0 * Radian), 0);
EXPECT_EQ(Cosh(0 * Radian), 1);
EXPECT_EQ(Tanh(0 * Radian), 0);
// Limits:
EXPECT_EQ(Sinh(20 * Radian), Cosh(20 * Radian));
EXPECT_EQ(Tanh(20 * Radian), 1);
EXPECT_EQ(Sinh(-20 * Radian), -Cosh(-20 * Radian));
EXPECT_EQ(Tanh(-20 * Radian), -1);
EXPECT_EQ(Sinh(2 * Radian) / Cosh(2 * Radian), Tanh(2 * Radian));
EXPECT_THAT(ArcSinh(Sinh(-10 * Degree)), AlmostEquals(-10 * Degree, 2));
EXPECT_THAT(ArcCosh(Cosh(-10 * Degree)), AlmostEquals(10 * Degree, 20));
EXPECT_THAT(ArcTanh(Tanh(-10 * Degree)), AlmostEquals(-10 * Degree, 1));
}
TEST_F(QuantitiesTest, ExpLogAndSqrt) {
EXPECT_EQ(Exp(1), e);
EXPECT_THAT(Exp(Log(4.2) + Log(1.729)), AlmostEquals(4.2 * 1.729, 1));
EXPECT_EQ(Exp(Log(2) * Log2(1.729)), 1.729);
EXPECT_EQ(Exp(Log(10) * Log10(1.729)), 1.729);
EXPECT_THAT(Exp(Log(2) / 2), AlmostEquals(Sqrt(2), 1));
EXPECT_EQ(Exp(Log(Rood / Foot.Pow<2>()) / 2) * Foot, Sqrt(Rood));
}
} // namespace geometry
} // namespace principia
<|endoftext|>
|
<commit_before>// bslmt_threadutil.cpp -*-C++-*-
// ----------------------------------------------------------------------------
// NOTICE
//
// This component is not up to date with current BDE coding standards, and
// should not be used as an example for new development.
// ----------------------------------------------------------------------------
#include <bslmt_threadutil.h>
#include <bsls_ident.h>
BSLS_IDENT_RCSID(bslmt_threadutil_cpp,"$Id$ $CSID$")
#include <bslma_allocator.h>
#include <bslma_default.h>
#include <bslma_managedptr.h>
#include <bsls_platform.h>
#include <bsl_cmath.h>
#include <bsl_c_limits.h>
namespace {
namespace u {
using namespace BloombergLP;
struct NamedFuncPtrRecord {
// This 'struct' stores the information necessary to call the 'extern "C"'
// function 'd_threadFunction' passing it 'void *' 'd_userData' after
// a thread is created and named 'd_threadName'.
// DATA
bslmt_ThreadFunction d_threadFunction; // extern "C" func ptr
void *d_userData; // 'void *' to be passed to func
bsl::string d_threadName; // thread name
public:
// CREATOR
NamedFuncPtrRecord(bslmt_ThreadFunction threadFunction,
void *userData,
const bslstl::StringRef& threadName,
bslma::Allocator *allocator)
: d_threadFunction(threadFunction)
, d_userData(userData)
, d_threadName(threadName, allocator)
// Create a 'NamedFuncPtrRecord' containing the specified
// 'threadFunction', 'userData', and 'threadName', and using the
// specified 'allocator' to supply memory.
{
}
};
} // close namespace u
} // close unnamed namespace
namespace BloombergLP {
extern "C"
void *bslmt_threadutil_namedFuncPtrThunk(void *arg)
// C-linkage routine that allows us to call a C-style function and name the
// thread, using information in the specified 'arg', which points to a
// 'u::NamedFuncPtrRecord' that must be freed by this function. The
// behavior is undefined if the thread name is empty.
{
u::NamedFuncPtrRecord *nfpr_p = static_cast<u::NamedFuncPtrRecord *>(arg);
bslma::ManagedPtr<u::NamedFuncPtrRecord> guard(
nfpr_p,
nfpr_p->d_threadName.get_allocator().mechanism());
BSLS_ASSERT(0 == nfpr_p->d_threadName.empty()); // This function should
// never be called
// unless the thread is
// named.
bslmt::ThreadUtil::setThreadName(nfpr_p->d_threadName);
return (*nfpr_p->d_threadFunction)(nfpr_p->d_userData);
}
// -----------------
// struct ThreadUtil
// -----------------
// CLASS METHODS
int bslmt::ThreadUtil::convertToSchedulingPriority(
ThreadAttributes::SchedulingPolicy policy,
double normalizedSchedulingPriority)
{
BSLS_ASSERT_OPT((int) policy >= ThreadAttributes::e_SCHED_MIN);
BSLS_ASSERT_OPT((int) policy <= ThreadAttributes::e_SCHED_MAX);
BSLS_ASSERT_OPT(normalizedSchedulingPriority >= 0.0);
BSLS_ASSERT_OPT(normalizedSchedulingPriority <= 1.0);
const int minPri = getMinSchedulingPriority(policy);
const int maxPri = getMaxSchedulingPriority(policy);
if (minPri == ThreadAttributes::e_UNSET_PRIORITY ||
maxPri == ThreadAttributes::e_UNSET_PRIORITY) {
return ThreadAttributes::e_UNSET_PRIORITY; // RETURN
}
#if !defined(BSLS_PLATFORM_OS_CYGWIN)
double ret = (maxPri - minPri) * normalizedSchedulingPriority +
minPri + 0.5;
#else
// On Cygwin, a lower numerical value implies a higher thread priority:
// minSchedPriority = 15, maxSchedPriority = -14
double ret = - ((minPri - maxPri) * normalizedSchedulingPriority - minPri)
+ 0.5;
#endif
return static_cast<int>(bsl::floor(ret));
}
int bslmt::ThreadUtil::create(Handle *handle,
const ThreadAttributes& attributes,
ThreadFunction function,
void *userData)
{
BSLS_ASSERT(handle);
if (false == attributes.threadName().isEmpty()) {
// Named thread. Only 'createWithAllocator' can name threads.
return createWithAllocator(handle,
attributes,
function,
userData,
bslma::Default::globalAllocator());// RETURN
}
// Unnamed thread.
return Imp::create(handle, attributes, function, userData);
}
int bslmt::ThreadUtil::createWithAllocator(Handle *handle,
const ThreadAttributes& attributes,
ThreadFunction function,
void *userData,
bslma::Allocator *allocator)
{
BSLS_ASSERT(handle);
BSLS_ASSERT_OPT(allocator);
if (false == attributes.threadName().isEmpty()) {
// Named thread.
bslma::ManagedPtr<u::NamedFuncPtrRecord> nfpr_m(
new (*allocator) u::NamedFuncPtrRecord(function,
userData,
attributes.threadName(),
allocator),
allocator);
int rc = Imp::create(handle,
attributes,
bslmt_threadutil_namedFuncPtrThunk,
nfpr_m.ptr());
if (0 == rc) {
nfpr_m.release();
}
return rc; // RETURN
}
// Unnamed thread.
return Imp::create(handle, attributes, function, userData);
}
} // close enterprise namespace
// ----------------------------------------------------------------------------
// Copyright 2015 Bloomberg Finance L.P.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
// ----------------------------- END-OF-FILE ----------------------------------
<commit_msg>bslmt_threadutil: doc tweak<commit_after>// bslmt_threadutil.cpp -*-C++-*-
// ----------------------------------------------------------------------------
// NOTICE
//
// This component is not up to date with current BDE coding standards, and
// should not be used as an example for new development.
// ----------------------------------------------------------------------------
#include <bslmt_threadutil.h>
#include <bsls_ident.h>
BSLS_IDENT_RCSID(bslmt_threadutil_cpp,"$Id$ $CSID$")
#include <bslma_allocator.h>
#include <bslma_default.h>
#include <bslma_managedptr.h>
#include <bsls_platform.h>
#include <bsl_cmath.h>
#include <bsl_c_limits.h>
namespace {
namespace u {
// We can't just package a 'bslmt_ThreadFunction' and 'userData' into a simple
// functor and pass that to one of the inline 'createWithAllocator' template
// functions because the contract for threads created by calling with a
// "C"-style function requires the function to be able to return a 'void *'
// which the calling thread can access via 'join'. The signature of the
// functor passed to the inline 'createWithAllocator' template functions,
// however, does not provide a way to return a value.
using namespace BloombergLP;
struct NamedFuncPtrRecord {
// This 'struct' stores the information necessary to call the 'extern "C"'
// function 'd_threadFunction' passing it 'void *' 'd_userData' after
// a thread is created and named 'd_threadName'.
// DATA
bslmt_ThreadFunction d_threadFunction; // extern "C" func ptr
void *d_userData; // 'void *' to be passed to func
bsl::string d_threadName; // thread name
public:
// CREATOR
NamedFuncPtrRecord(bslmt_ThreadFunction threadFunction,
void *userData,
const bslstl::StringRef& threadName,
bslma::Allocator *allocator)
: d_threadFunction(threadFunction)
, d_userData(userData)
, d_threadName(threadName, allocator)
// Create a 'NamedFuncPtrRecord' containing the specified
// 'threadFunction', 'userData', and 'threadName', and using the
// specified 'allocator' to supply memory.
{
}
};
} // close namespace u
} // close unnamed namespace
namespace BloombergLP {
extern "C"
void *bslmt_threadutil_namedFuncPtrThunk(void *arg)
// C-linkage routine that allows us to call a C-style function and name the
// thread, using information in the specified 'arg', which points to a
// 'u::NamedFuncPtrRecord' that must be freed by this function. The
// behavior is undefined if the thread name is empty.
{
u::NamedFuncPtrRecord *nfpr_p = static_cast<u::NamedFuncPtrRecord *>(arg);
bslma::ManagedPtr<u::NamedFuncPtrRecord> guard(
nfpr_p,
nfpr_p->d_threadName.get_allocator().mechanism());
BSLS_ASSERT(0 == nfpr_p->d_threadName.empty()); // This function should
// never be called
// unless the thread is
// named.
bslmt::ThreadUtil::setThreadName(nfpr_p->d_threadName);
return (*nfpr_p->d_threadFunction)(nfpr_p->d_userData);
}
// -----------------
// struct ThreadUtil
// -----------------
// CLASS METHODS
int bslmt::ThreadUtil::convertToSchedulingPriority(
ThreadAttributes::SchedulingPolicy policy,
double normalizedSchedulingPriority)
{
BSLS_ASSERT_OPT((int) policy >= ThreadAttributes::e_SCHED_MIN);
BSLS_ASSERT_OPT((int) policy <= ThreadAttributes::e_SCHED_MAX);
BSLS_ASSERT_OPT(normalizedSchedulingPriority >= 0.0);
BSLS_ASSERT_OPT(normalizedSchedulingPriority <= 1.0);
const int minPri = getMinSchedulingPriority(policy);
const int maxPri = getMaxSchedulingPriority(policy);
if (minPri == ThreadAttributes::e_UNSET_PRIORITY ||
maxPri == ThreadAttributes::e_UNSET_PRIORITY) {
return ThreadAttributes::e_UNSET_PRIORITY; // RETURN
}
#if !defined(BSLS_PLATFORM_OS_CYGWIN)
double ret = (maxPri - minPri) * normalizedSchedulingPriority +
minPri + 0.5;
#else
// On Cygwin, a lower numerical value implies a higher thread priority:
// minSchedPriority = 15, maxSchedPriority = -14
double ret = - ((minPri - maxPri) * normalizedSchedulingPriority - minPri)
+ 0.5;
#endif
return static_cast<int>(bsl::floor(ret));
}
int bslmt::ThreadUtil::create(Handle *handle,
const ThreadAttributes& attributes,
ThreadFunction function,
void *userData)
{
BSLS_ASSERT(handle);
if (false == attributes.threadName().isEmpty()) {
// Named thread. Only 'createWithAllocator' can name threads.
return createWithAllocator(handle,
attributes,
function,
userData,
bslma::Default::globalAllocator());// RETURN
}
// Unnamed thread.
return Imp::create(handle, attributes, function, userData);
}
int bslmt::ThreadUtil::createWithAllocator(Handle *handle,
const ThreadAttributes& attributes,
ThreadFunction function,
void *userData,
bslma::Allocator *allocator)
{
BSLS_ASSERT(handle);
BSLS_ASSERT_OPT(allocator);
if (false == attributes.threadName().isEmpty()) {
// Named thread.
bslma::ManagedPtr<u::NamedFuncPtrRecord> nfpr_m(
new (*allocator) u::NamedFuncPtrRecord(function,
userData,
attributes.threadName(),
allocator),
allocator);
int rc = Imp::create(handle,
attributes,
bslmt_threadutil_namedFuncPtrThunk,
nfpr_m.ptr());
if (0 == rc) {
nfpr_m.release();
}
return rc; // RETURN
}
// Unnamed thread.
return Imp::create(handle, attributes, function, userData);
}
} // close enterprise namespace
// ----------------------------------------------------------------------------
// Copyright 2015 Bloomberg Finance L.P.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
// ----------------------------- END-OF-FILE ----------------------------------
<|endoftext|>
|
<commit_before>// set of classes to compare the performance of STL vector versus
// native Root TClonesArray.
// See main program bench.cxx
#include "TRandom.h"
#include "TFile.h"
#include "TTree.h"
#include "TClass.h"
//the next include must be the last one on systems like Windows/NT
#include "TBench.h"
THit hit;
char *demofile = "/tmp/bench.root";
//-------------------------------------------------------------
ClassImp(THit)
//-------------------------------------------------------------
THit::THit() {
fPulses = 0;
}
THit::THit(const THit &hit) {
fX = hit.fX;
fY = hit.fY;
fZ = hit.fZ;
for (Int_t i=0;i<10;i++) fTime[i] = hit.fTime[i];
fPulses = 0;
fNpulses = hit.fNpulses;
if (fNpulses == 0) return;
if (hit.fPulses == 0) return;
fPulses = new int[fNpulses];
for (int j=0;j<fNpulses;j++) fPulses[j] = hit.fPulses[j];
}
THit::THit(int t) {
fPulses = 0;
Set(t);
}
THit::~THit() {
if (fPulses) delete [] fPulses;
fPulses = 0;
}
void THit::Set(int t) {
fX = gRandom->Gaus(0,1);
fY = gRandom->Gaus(0,1);
fZ = gRandom->Gaus(0,10);
if (fPulses && fNpulses > 0) delete [] fPulses;
fNpulses = t%20 + 1;
fPulses = new int[fNpulses];
for (int j=0;j<fNpulses;j++) fPulses[j] = j+1;
for (int i=0; i<10; i++) fTime[i] = t+i;
}
TBuffer &operator>>(TBuffer &buf, const THit *&obj)
{
obj = new THit();
((THit*)obj)->Streamer(buf);
return buf;
}
TBuffer &operator<<(TBuffer &buf, const THit *obj)
{
((THit*)obj)->Streamer(buf);
return buf;
}
//-------------------------------------------------------------
ClassImp(TObjHit)
//-------------------------------------------------------------
TObjHit::TObjHit() :THit() {}
TObjHit::TObjHit(int t) :THit(t) {}
//-------------------------------------------------------------
ClassImp(TSTLhit)
//-------------------------------------------------------------
TSTLhit::TSTLhit()
{
}
TSTLhit::TSTLhit(Int_t nmax)
{
fNhits = nmax;
fList1.reserve(nmax);
}
TSTLhit::~TSTLhit() {
}
void TSTLhit::Clear(Option_t *)
{
fList1.erase(fList1.begin(),fList1.end());
}
void TSTLhit::MakeEvent(int ievent)
{
Clear();
for (Int_t j=0; j<fNhits; j++) {
hit.Set(j);
fList1.push_back(hit);
}
}
Int_t TSTLhit::MakeTree(int mode, int nevents, int compression, int split, float &cx)
{
TFile *f=0;
TTree *T=0;
TSTLhit *top = this;
if (mode > 0) {
f = new TFile(demofile,"recreate","STLhit",compression);
T = new TTree("T","Demo tree");
T->Branch("event","TSTLhit",&top,64000,split);
}
for (int ievent=0; ievent<nevents; ievent++) {
MakeEvent(ievent);
if (mode > 0) T->Fill();
}
if (mode == 0) return 0;
T->Write();
delete f;
f = new TFile(demofile);
Int_t nbytes = f->GetEND();
cx = f->GetCompressionFactor();
delete f;
return nbytes;
}
Int_t TSTLhit::ReadTree()
{
TSTLhit *top = this;
TFile *f = new TFile(demofile);
TTree *T = (TTree*)f->Get("T");
T->SetBranchAddress("event",&top);
Int_t nevents = (Int_t)T->GetEntries();
Int_t nbytes = 0;
for (int ievent=0; ievent<nevents; ievent++) {
nbytes += T->GetEntry(ievent);
Clear();
}
delete f;
return nbytes;
}
//-------------------------------------------------------------
ClassImp(TSTLhitStar)
//-------------------------------------------------------------
TSTLhitStar::TSTLhitStar()
{
}
TSTLhitStar::TSTLhitStar(Int_t nmax)
{
fNhits = nmax;
fList2.reserve(nmax);
}
TSTLhitStar::~TSTLhitStar() {
}
void TSTLhitStar::Clear(Option_t *)
{
for (vector<THit*>::iterator it = fList2.begin(); it<fList2.end(); it++) {
delete (*it);
}
fList2.erase(fList2.begin(),fList2.end());
}
void TSTLhitStar::MakeEvent(int ievent)
{
Clear();
for (Int_t j=0; j<fNhits; j++) {
fList2.push_back(new THit(j));
}
}
Int_t TSTLhitStar::MakeTree(int mode, int nevents, int compression, int split, float &cx)
{
TFile *f=0;
TTree *T=0;
TSTLhitStar *top = this;
if (mode > 0) {
f = new TFile(demofile,"recreate","STLhitStar",compression);
T = new TTree("T","Demo tree");
T->Branch("event","TSTLhitStar",&top,64000,split);
}
for (int ievent=0; ievent<nevents; ievent++) {
MakeEvent(ievent);
if (mode > 0) T->Fill();
}
if (mode == 0) return 0;
T->Write();
delete f;
f = new TFile(demofile);
Int_t nbytes = f->GetEND();
cx = f->GetCompressionFactor();
delete f;
return nbytes;
}
Int_t TSTLhitStar::ReadTree()
{
TSTLhitStar *top = this;
TFile *f = new TFile(demofile);
TTree *T = (TTree*)f->Get("T");
T->SetBranchAddress("event",&top);
Int_t nevents = (Int_t)T->GetEntries();
Int_t nbytes = 0;
for (int ievent=0; ievent<nevents; ievent++) {
nbytes += T->GetEntry(ievent);
Clear();
}
delete f;
return nbytes;
}
//-------------------------------------------------------------
ClassImp(TCloneshit)
//-------------------------------------------------------------
TCloneshit::TCloneshit()
{
fList3 = new TClonesArray("TObjHit");
}
TCloneshit::TCloneshit(Int_t nmax)
{
fNhits = nmax;
fList3 = new TClonesArray("TObjHit",nmax);
TObjHit::Class()->IgnoreTObjectStreamer();
}
TCloneshit::~TCloneshit() {
}
void TCloneshit::Clear(Option_t *)
{
fList3->Delete();
//fList3->Clear();
}
void TCloneshit::MakeEvent(int ievent)
{
Clear();
for (Int_t j=0; j<fNhits; j++) {
new((*fList3)[j]) TObjHit(j);
}
}
Int_t TCloneshit::MakeTree(int mode, int nevents, int compression, int split, float &cx)
{
TFile *f=0;
TTree *T=0;
TCloneshit *top = this;
if (mode > 0) {
f = new TFile(demofile,"recreate","Cloneshit",compression);
T = new TTree("T","Demo tree");
T->Branch("event","TCloneshit",&top,64000,split);
}
for (int ievent=0; ievent<nevents; ievent++) {
MakeEvent(ievent);
if (mode > 0) T->Fill();
}
if (mode == 0) return 0;
T->Write();
delete f;
f = new TFile(demofile);
Int_t nbytes = f->GetEND();
cx = f->GetCompressionFactor();
delete f;
return nbytes;
}
Int_t TCloneshit::ReadTree()
{
TCloneshit *top = this;
TFile *f = new TFile(demofile);
TTree *T = (TTree*)f->Get("T");
T->SetBranchAddress("event",&top);
Int_t nevents = (Int_t)T->GetEntries();
Int_t nbytes = 0;
for (int ievent=0; ievent<nevents; ievent++) {
nbytes += T->GetEntry(ievent);
}
delete f;
return nbytes;
}
<commit_msg>Declare const char* variable demofile<commit_after>// set of classes to compare the performance of STL vector versus
// native Root TClonesArray.
// See main program bench.cxx
#include "TRandom.h"
#include "TFile.h"
#include "TTree.h"
#include "TClass.h"
//the next include must be the last one on systems like Windows/NT
#include "TBench.h"
THit hit;
const char *demofile = "/tmp/bench.root";
//-------------------------------------------------------------
ClassImp(THit)
//-------------------------------------------------------------
THit::THit() {
fPulses = 0;
}
THit::THit(const THit &hit) {
fX = hit.fX;
fY = hit.fY;
fZ = hit.fZ;
for (Int_t i=0;i<10;i++) fTime[i] = hit.fTime[i];
fPulses = 0;
fNpulses = hit.fNpulses;
if (fNpulses == 0) return;
if (hit.fPulses == 0) return;
fPulses = new int[fNpulses];
for (int j=0;j<fNpulses;j++) fPulses[j] = hit.fPulses[j];
}
THit::THit(int t) {
fPulses = 0;
Set(t);
}
THit::~THit() {
if (fPulses) delete [] fPulses;
fPulses = 0;
}
void THit::Set(int t) {
fX = gRandom->Gaus(0,1);
fY = gRandom->Gaus(0,1);
fZ = gRandom->Gaus(0,10);
if (fPulses && fNpulses > 0) delete [] fPulses;
fNpulses = t%20 + 1;
fPulses = new int[fNpulses];
for (int j=0;j<fNpulses;j++) fPulses[j] = j+1;
for (int i=0; i<10; i++) fTime[i] = t+i;
}
TBuffer &operator>>(TBuffer &buf, const THit *&obj)
{
obj = new THit();
((THit*)obj)->Streamer(buf);
return buf;
}
TBuffer &operator<<(TBuffer &buf, const THit *obj)
{
((THit*)obj)->Streamer(buf);
return buf;
}
//-------------------------------------------------------------
ClassImp(TObjHit)
//-------------------------------------------------------------
TObjHit::TObjHit() :THit() {}
TObjHit::TObjHit(int t) :THit(t) {}
//-------------------------------------------------------------
ClassImp(TSTLhit)
//-------------------------------------------------------------
TSTLhit::TSTLhit()
{
}
TSTLhit::TSTLhit(Int_t nmax)
{
fNhits = nmax;
fList1.reserve(nmax);
}
TSTLhit::~TSTLhit() {
}
void TSTLhit::Clear(Option_t *)
{
fList1.erase(fList1.begin(),fList1.end());
}
void TSTLhit::MakeEvent(int ievent)
{
Clear();
for (Int_t j=0; j<fNhits; j++) {
hit.Set(j);
fList1.push_back(hit);
}
}
Int_t TSTLhit::MakeTree(int mode, int nevents, int compression, int split, float &cx)
{
TFile *f=0;
TTree *T=0;
TSTLhit *top = this;
if (mode > 0) {
f = new TFile(demofile,"recreate","STLhit",compression);
T = new TTree("T","Demo tree");
T->Branch("event","TSTLhit",&top,64000,split);
}
for (int ievent=0; ievent<nevents; ievent++) {
MakeEvent(ievent);
if (mode > 0) T->Fill();
}
if (mode == 0) return 0;
T->Write();
delete f;
f = new TFile(demofile);
Int_t nbytes = f->GetEND();
cx = f->GetCompressionFactor();
delete f;
return nbytes;
}
Int_t TSTLhit::ReadTree()
{
TSTLhit *top = this;
TFile *f = new TFile(demofile);
TTree *T = (TTree*)f->Get("T");
T->SetBranchAddress("event",&top);
Int_t nevents = (Int_t)T->GetEntries();
Int_t nbytes = 0;
for (int ievent=0; ievent<nevents; ievent++) {
nbytes += T->GetEntry(ievent);
Clear();
}
delete f;
return nbytes;
}
//-------------------------------------------------------------
ClassImp(TSTLhitStar)
//-------------------------------------------------------------
TSTLhitStar::TSTLhitStar()
{
}
TSTLhitStar::TSTLhitStar(Int_t nmax)
{
fNhits = nmax;
fList2.reserve(nmax);
}
TSTLhitStar::~TSTLhitStar() {
}
void TSTLhitStar::Clear(Option_t *)
{
for (vector<THit*>::iterator it = fList2.begin(); it<fList2.end(); it++) {
delete (*it);
}
fList2.erase(fList2.begin(),fList2.end());
}
void TSTLhitStar::MakeEvent(int ievent)
{
Clear();
for (Int_t j=0; j<fNhits; j++) {
fList2.push_back(new THit(j));
}
}
Int_t TSTLhitStar::MakeTree(int mode, int nevents, int compression, int split, float &cx)
{
TFile *f=0;
TTree *T=0;
TSTLhitStar *top = this;
if (mode > 0) {
f = new TFile(demofile,"recreate","STLhitStar",compression);
T = new TTree("T","Demo tree");
T->Branch("event","TSTLhitStar",&top,64000,split);
}
for (int ievent=0; ievent<nevents; ievent++) {
MakeEvent(ievent);
if (mode > 0) T->Fill();
}
if (mode == 0) return 0;
T->Write();
delete f;
f = new TFile(demofile);
Int_t nbytes = f->GetEND();
cx = f->GetCompressionFactor();
delete f;
return nbytes;
}
Int_t TSTLhitStar::ReadTree()
{
TSTLhitStar *top = this;
TFile *f = new TFile(demofile);
TTree *T = (TTree*)f->Get("T");
T->SetBranchAddress("event",&top);
Int_t nevents = (Int_t)T->GetEntries();
Int_t nbytes = 0;
for (int ievent=0; ievent<nevents; ievent++) {
nbytes += T->GetEntry(ievent);
Clear();
}
delete f;
return nbytes;
}
//-------------------------------------------------------------
ClassImp(TCloneshit)
//-------------------------------------------------------------
TCloneshit::TCloneshit()
{
fList3 = new TClonesArray("TObjHit");
}
TCloneshit::TCloneshit(Int_t nmax)
{
fNhits = nmax;
fList3 = new TClonesArray("TObjHit",nmax);
TObjHit::Class()->IgnoreTObjectStreamer();
}
TCloneshit::~TCloneshit() {
}
void TCloneshit::Clear(Option_t *)
{
fList3->Delete();
//fList3->Clear();
}
void TCloneshit::MakeEvent(int ievent)
{
Clear();
for (Int_t j=0; j<fNhits; j++) {
new((*fList3)[j]) TObjHit(j);
}
}
Int_t TCloneshit::MakeTree(int mode, int nevents, int compression, int split, float &cx)
{
TFile *f=0;
TTree *T=0;
TCloneshit *top = this;
if (mode > 0) {
f = new TFile(demofile,"recreate","Cloneshit",compression);
T = new TTree("T","Demo tree");
T->Branch("event","TCloneshit",&top,64000,split);
}
for (int ievent=0; ievent<nevents; ievent++) {
MakeEvent(ievent);
if (mode > 0) T->Fill();
}
if (mode == 0) return 0;
T->Write();
delete f;
f = new TFile(demofile);
Int_t nbytes = f->GetEND();
cx = f->GetCompressionFactor();
delete f;
return nbytes;
}
Int_t TCloneshit::ReadTree()
{
TCloneshit *top = this;
TFile *f = new TFile(demofile);
TTree *T = (TTree*)f->Get("T");
T->SetBranchAddress("event",&top);
Int_t nevents = (Int_t)T->GetEntries();
Int_t nbytes = 0;
for (int ievent=0; ievent<nevents; ievent++) {
nbytes += T->GetEntry(ievent);
}
delete f;
return nbytes;
}
<|endoftext|>
|
<commit_before>#include <crv.h>
#include <crvBezier.h>
#include <gmi_analytic.h>
#include <gmi_null.h>
#include <apfMDS.h>
#include <apfMesh2.h>
#include <apf.h>
#include <apfShape.h>
#include <PCU.h>
#include <math.h>
#include <cassert>
/* This test file uses an alternative and more traditional method to
* compute Jacobian differences, using the property of Bezier's that
* derivatives of Bezier's are themselves Bezier's multiplied by
* control point differences. As implementing weights*control point differences
* is not possible in our current framework, this method is not implemented in
* the main code, but serves its use for code validation.
*
* Orders 3-6 provide invalid meshes, just to check validity as well
*/
static void testJacobian(apf::Mesh2* m)
{
int n = 10;
apf::MeshIterator* it = m->begin(2);
apf::MeshEntity* e;
apf::Vector3 xi;
apf::Matrix3x3 Jac;
while ((e = m->iterate(it))) {
apf::MeshElement* me =
apf::createMeshElement(m,e);
for (int j = 0; j <= n; ++j){
xi[1] = 1.*j/n;
for (int i = 0; i <= n-j; ++i){
xi[0] = 1.*i/n;
apf::getJacobian(me,xi,Jac);
double detJ = (Jac[0][0]*Jac[1][1])-(Jac[1][0]*Jac[0][1]);
double J = crv::computeAlternateTriJacobianDet(m,e,xi);
assert(fabs(detJ-J) < 1e-14);
}
}
apf::destroyMeshElement(me);
}
m->end(it);
}
static void testEdgeGradients(apf::Mesh2* m)
{
int n = 5;
int d = m->getShape()->getOrder();
apf::NewArray<int> map(d+1);
for(int p = 1; p < d; ++p){
map[p] = p+1;
}
map[0] = 0;
map[d] = 1;
apf::MeshIterator* it = m->begin(1);
apf::MeshEntity* e;
apf::Vector3 xi;
apf::Matrix3x3 Jac;
apf::NewArray<apf::Vector3> nodes;
while ((e = m->iterate(it))) {
apf::Element* elem =
apf::createElement(m->getCoordinateField(),e);
apf::getVectorNodes(elem,nodes);
apf::MeshElement* me =
apf::createMeshElement(m,e);
for (int i = 0; i <= n; ++i){
xi[0] = 2.*i/n-1.;
apf::getJacobian(me,xi,Jac);
apf::Vector3 J(0,0,0);
xi[0] = (double)i/n;
for(int p = 0; p <= d-1; ++p){
J += (nodes[map[p+1]]-nodes[map[p]])*d
*crv::binomial(d-1,p)*crv::Bij(p,d-1-p,xi[0],1.-xi[0]);
}
assert(fabs(J[0]-Jac[0][0]*2.0) < 1e-14
&& fabs(J[1]-Jac[0][1]*2.0) < 1e-14);
}
apf::destroyMeshElement(me);
apf::destroyElement(elem);
}
m->end(it);
}
// face areas are 1/2 and 19/30
void vert0(double const p[2], double x[3], void*)
{
(void)p;
(void)x;
}
// edges go counter clockwise
void edge0(double const p[2], double x[3], void*)
{
x[0] = p[0];
x[1] = p[0]*(p[0]-1.0);
}
void edge1(double const p[2], double x[3], void*)
{
x[0] = 1.0-2.5*p[0]*(p[0]-1.0)*p[0]*(p[0]-1.0);
x[1] = p[0];
}
void edge2(double const p[2], double x[3], void*)
{
double u = 1.-p[0];
x[0] = u;
x[1] = 1.;
}
void edge3(double const p[2], double x[3], void*)
{
double v = 1.-p[0];
x[0] = 0;
x[1] = v;
}
void face0(double const p[2], double x[3], void*)
{
x[0] = p[0];
x[1] = p[1];
}
void reparam_zero(double const from[2], double to[2], void*)
{
(void)from;
to[0] = 0;
to[1] = 0;
}
void reparam_one(double const from[2], double to[2], void*)
{
(void)from;
to[0] = 1;
to[1] = 0;
}
agm_bdry add_bdry(gmi_model* m, gmi_ent* e)
{
return agm_add_bdry(gmi_analytic_topo(m), agm_from_gmi(e));
}
agm_use add_adj(gmi_model* m, agm_bdry b, int tag)
{
agm* topo = gmi_analytic_topo(m);
int dim = agm_dim_from_type(agm_bounds(topo, b).type);
gmi_ent* de = gmi_find(m, dim - 1, tag);
return agm_add_use(topo, b, agm_from_gmi(de));
}
void make_edge_topo(gmi_model* m, gmi_ent* e, int v0tag, int v1tag)
{
agm_bdry b = add_bdry(m, e);
agm_use u0 = add_adj(m, b, v0tag);
gmi_add_analytic_reparam(m, u0, reparam_zero, 0);
agm_use u1 = add_adj(m, b, v1tag);
gmi_add_analytic_reparam(m, u1, reparam_one, 0);
}
gmi_model* makeModel()
{
gmi_model* model = gmi_make_analytic();
int edPer = 0;
double edRan[2] = {0, 1};
for(int i = 0; i < 4; ++i)
gmi_add_analytic(model, 0, i, vert0, NULL,NULL,NULL);
gmi_ent* eds[4];
eds[0] = gmi_add_analytic(model, 1, 0, edge0, &edPer, &edRan, 0);
eds[1] = gmi_add_analytic(model, 1, 1, edge1, &edPer, &edRan, 0);
eds[2] = gmi_add_analytic(model, 1, 2, edge2, &edPer, &edRan, 0);
eds[3] = gmi_add_analytic(model, 1, 3, edge3, &edPer, &edRan, 0);
for(int i = 0; i < 4; ++i)
make_edge_topo(model, eds[i], i, (i+1) % 4);
int faPer[2] = {0, 0};
double faRan[2][2] = {{0,1},{0,1}};
gmi_add_analytic(model, 2, 0, face0, faPer, faRan, 0);
return model;
}
apf::Mesh2* createMesh2D()
{
gmi_model* model = makeModel();
apf::Mesh2* m = apf::makeEmptyMdsMesh(model, 2, true);
apf::MeshEntity* v[4];
apf::Vector3 points2D[4] =
{apf::Vector3(0,0,0),
apf::Vector3(1,0,0),
apf::Vector3(1,1,0),
apf::Vector3(0,1,0)};
for (int i = 0; i < 4; ++i){
v[i] = m->createVertex(m->findModelEntity(0,i),points2D[i],points2D[i]);
}
for (int i = 0; i < 4; ++i){
apf::ModelEntity* edge = m->findModelEntity(1,i);
apf::MeshEntity* ved[2] = {v[i],v[(i+1) % 4]};
apf::buildElement(m, edge, apf::Mesh::EDGE, ved);
}
apf::MeshEntity* ved[2] = {v[0],v[2]};
apf::buildElement(m, m->findModelEntity(2,0), apf::Mesh::EDGE, ved);
apf::MeshEntity* vf0[3] = {v[0],v[1],v[2]};
apf::buildElement(m, m->findModelEntity(2,0), apf::Mesh::TRIANGLE, vf0);
apf::MeshEntity* vf1[3] = {v[0],v[2],v[3]};
apf::buildElement(m, m->findModelEntity(2,0), apf::Mesh::TRIANGLE, vf1);
m->acceptChanges();
m->verify();
return m;
}
void checkValidity(apf::Mesh* m, int order)
{
apf::MeshIterator* it = m->begin(2);
apf::MeshEntity* e;
int iEntity = 0;
while ((e = m->iterate(it))) {
apf::MeshEntity* entities[3];
int numInvalid = crv::checkTriValidity(m,e,entities);
if(iEntity == 0){
assert((numInvalid && order > 3) || (!numInvalid && order <= 3));
} else {
assert(!numInvalid);
}
iEntity++;
break;
}
m->end(it);
}
void test2D()
{
for(int order = 2; order <= 6; ++order){
apf::Mesh2* m = createMesh2D();
apf::changeMeshShape(m, crv::getBezier(3,order),true);
crv::BezierCurver bc(m,order,0);
crv::setBlendingOrder(0);
bc.snapToInterpolate(1);
apf::FieldShape* fs = m->getShape();
// go downward, and convert interpolating to control points
for(int d = 2; d >= 1; --d){
int n = (d == 2)? (order+1)*(order+2)/2 : order+1;
int ne = fs->countNodesOn(d);
apf::NewArray<double> c;
crv::getTransformationCoefficients(3,order,d,c);
apf::MeshEntity* e;
apf::MeshIterator* it = m->begin(d);
while ((e = m->iterate(it))) {
bc.convertInterpolationPoints(e,n,ne,c);
}
m->end(it);
}
// crv::writeCurvedVtuFiles(m,apf::Mesh::TRIANGLE,100,"curved");
testJacobian(m);
testEdgeGradients(m);
checkValidity(m,order);
m->destroyNative();
apf::destroyMesh(m);
}
}
apf::Mesh2* createMesh3D()
{
gmi_model* model = gmi_load(".null");
apf::Mesh2* m = apf::makeEmptyMdsMesh(model, 3, true);
apf::Vector3 points3D[4] =
{apf::Vector3(0,0,0),
apf::Vector3(1,0,0),
apf::Vector3(0,1,0),
apf::Vector3(0,0,1)};
apf::buildOneElement(m,0,apf::Mesh::TET,points3D);
apf::deriveMdsModel(m);
m->acceptChanges();
m->verify();
return m;
}
void test3D()
{
gmi_register_null();
for(int order = 1; order <= 4; ++order){
apf::Mesh2* m = createMesh3D();
apf::changeMeshShape(m, crv::getBezier(3,order),true);
crv::setBlendingOrder(0);
apf::FieldShape* fs = m->getShape();
crv::BezierCurver bc(m,order,0);
// go downward, and convert interpolating to control points
for(int d = 2; d >= 1; --d){
int n = (d == 2)? (order+1)*(order+2)/2 : order+1;
int ne = fs->countNodesOn(d);
apf::NewArray<double> c;
crv::getTransformationCoefficients(3,order,d,c);
apf::MeshEntity* e;
apf::MeshIterator* it = m->begin(d);
while ((e = m->iterate(it))) {
if(m->getModelType(m->toModel(e)) == m->getDimension()) continue;
bc.convertInterpolationPoints(e,n,ne,c);
}
m->end(it);
}
// get face 2
apf::MeshIterator* it = m->begin(3);
apf::MeshEntity* tet = m->iterate(it);
m->end(it);
apf::MeshEntity* faces[4], *edges[3];
m->getDownward(tet,2,faces);
apf::MeshEntity* face = faces[2];
m->getDownward(face,1,edges);
for (int edge = 0; edge < 3; ++edge){
int non = m->getShape()->countNodesOn(apf::Mesh::EDGE);
for (int i = 0; i < non; ++i){
apf::Vector3 pt;
m->getPoint(edges[edge],i,pt);
pt = pt*0.5;
m->setPoint(edges[edge],i,pt);
}
}
int non = m->getShape()->countNodesOn(apf::Mesh::TRIANGLE);
for (int i = 0; i < non; ++i){
apf::Vector3 pt;
m->getPoint(face,i,pt);
pt = pt*0.5;
m->setPoint(face,i,pt);
}
m->acceptChanges();
apf::MeshEntity* entities[6];
// crv::checkValidity(m,tet,entities);
// write the field
// crv::writeCurvedVtuFiles(m,apf::Mesh::TET,20,"curved");
m->destroyNative();
apf::destroyMesh(m);
}
}
int main(int argc, char** argv)
{
MPI_Init(&argc,&argv);
PCU_Comm_Init();
test2D();
test3D();
PCU_Comm_Free();
MPI_Finalize();
}
<commit_msg>silence another warning<commit_after>#include <crv.h>
#include <crvBezier.h>
#include <gmi_analytic.h>
#include <gmi_null.h>
#include <apfMDS.h>
#include <apfMesh2.h>
#include <apf.h>
#include <apfShape.h>
#include <PCU.h>
#include <math.h>
#include <cassert>
/* This test file uses an alternative and more traditional method to
* compute Jacobian differences, using the property of Bezier's that
* derivatives of Bezier's are themselves Bezier's multiplied by
* control point differences. As implementing weights*control point differences
* is not possible in our current framework, this method is not implemented in
* the main code, but serves its use for code validation.
*
* Orders 3-6 provide invalid meshes, just to check validity as well
*/
static void testJacobian(apf::Mesh2* m)
{
int n = 10;
apf::MeshIterator* it = m->begin(2);
apf::MeshEntity* e;
apf::Vector3 xi;
apf::Matrix3x3 Jac;
while ((e = m->iterate(it))) {
apf::MeshElement* me =
apf::createMeshElement(m,e);
for (int j = 0; j <= n; ++j){
xi[1] = 1.*j/n;
for (int i = 0; i <= n-j; ++i){
xi[0] = 1.*i/n;
apf::getJacobian(me,xi,Jac);
double detJ = (Jac[0][0]*Jac[1][1])-(Jac[1][0]*Jac[0][1]);
double J = crv::computeAlternateTriJacobianDet(m,e,xi);
assert(fabs(detJ-J) < 1e-14);
}
}
apf::destroyMeshElement(me);
}
m->end(it);
}
static void testEdgeGradients(apf::Mesh2* m)
{
int n = 5;
int d = m->getShape()->getOrder();
apf::NewArray<int> map(d+1);
for(int p = 1; p < d; ++p){
map[p] = p+1;
}
map[0] = 0;
map[d] = 1;
apf::MeshIterator* it = m->begin(1);
apf::MeshEntity* e;
apf::Vector3 xi;
apf::Matrix3x3 Jac;
apf::NewArray<apf::Vector3> nodes;
while ((e = m->iterate(it))) {
apf::Element* elem =
apf::createElement(m->getCoordinateField(),e);
apf::getVectorNodes(elem,nodes);
apf::MeshElement* me =
apf::createMeshElement(m,e);
for (int i = 0; i <= n; ++i){
xi[0] = 2.*i/n-1.;
apf::getJacobian(me,xi,Jac);
apf::Vector3 J(0,0,0);
xi[0] = (double)i/n;
for(int p = 0; p <= d-1; ++p){
J += (nodes[map[p+1]]-nodes[map[p]])*d
*crv::binomial(d-1,p)*crv::Bij(p,d-1-p,xi[0],1.-xi[0]);
}
assert(fabs(J[0]-Jac[0][0]*2.0) < 1e-14
&& fabs(J[1]-Jac[0][1]*2.0) < 1e-14);
}
apf::destroyMeshElement(me);
apf::destroyElement(elem);
}
m->end(it);
}
// face areas are 1/2 and 19/30
void vert0(double const p[2], double x[3], void*)
{
(void)p;
(void)x;
}
// edges go counter clockwise
void edge0(double const p[2], double x[3], void*)
{
x[0] = p[0];
x[1] = p[0]*(p[0]-1.0);
}
void edge1(double const p[2], double x[3], void*)
{
x[0] = 1.0-2.5*p[0]*(p[0]-1.0)*p[0]*(p[0]-1.0);
x[1] = p[0];
}
void edge2(double const p[2], double x[3], void*)
{
double u = 1.-p[0];
x[0] = u;
x[1] = 1.;
}
void edge3(double const p[2], double x[3], void*)
{
double v = 1.-p[0];
x[0] = 0;
x[1] = v;
}
void face0(double const p[2], double x[3], void*)
{
x[0] = p[0];
x[1] = p[1];
}
void reparam_zero(double const from[2], double to[2], void*)
{
(void)from;
to[0] = 0;
to[1] = 0;
}
void reparam_one(double const from[2], double to[2], void*)
{
(void)from;
to[0] = 1;
to[1] = 0;
}
agm_bdry add_bdry(gmi_model* m, gmi_ent* e)
{
return agm_add_bdry(gmi_analytic_topo(m), agm_from_gmi(e));
}
agm_use add_adj(gmi_model* m, agm_bdry b, int tag)
{
agm* topo = gmi_analytic_topo(m);
int dim = agm_dim_from_type(agm_bounds(topo, b).type);
gmi_ent* de = gmi_find(m, dim - 1, tag);
return agm_add_use(topo, b, agm_from_gmi(de));
}
void make_edge_topo(gmi_model* m, gmi_ent* e, int v0tag, int v1tag)
{
agm_bdry b = add_bdry(m, e);
agm_use u0 = add_adj(m, b, v0tag);
gmi_add_analytic_reparam(m, u0, reparam_zero, 0);
agm_use u1 = add_adj(m, b, v1tag);
gmi_add_analytic_reparam(m, u1, reparam_one, 0);
}
gmi_model* makeModel()
{
gmi_model* model = gmi_make_analytic();
int edPer = 0;
double edRan[2] = {0, 1};
for(int i = 0; i < 4; ++i)
gmi_add_analytic(model, 0, i, vert0, NULL,NULL,NULL);
gmi_ent* eds[4];
eds[0] = gmi_add_analytic(model, 1, 0, edge0, &edPer, &edRan, 0);
eds[1] = gmi_add_analytic(model, 1, 1, edge1, &edPer, &edRan, 0);
eds[2] = gmi_add_analytic(model, 1, 2, edge2, &edPer, &edRan, 0);
eds[3] = gmi_add_analytic(model, 1, 3, edge3, &edPer, &edRan, 0);
for(int i = 0; i < 4; ++i)
make_edge_topo(model, eds[i], i, (i+1) % 4);
int faPer[2] = {0, 0};
double faRan[2][2] = {{0,1},{0,1}};
gmi_add_analytic(model, 2, 0, face0, faPer, faRan, 0);
return model;
}
apf::Mesh2* createMesh2D()
{
gmi_model* model = makeModel();
apf::Mesh2* m = apf::makeEmptyMdsMesh(model, 2, true);
apf::MeshEntity* v[4];
apf::Vector3 points2D[4] =
{apf::Vector3(0,0,0),
apf::Vector3(1,0,0),
apf::Vector3(1,1,0),
apf::Vector3(0,1,0)};
for (int i = 0; i < 4; ++i){
v[i] = m->createVertex(m->findModelEntity(0,i),points2D[i],points2D[i]);
}
for (int i = 0; i < 4; ++i){
apf::ModelEntity* edge = m->findModelEntity(1,i);
apf::MeshEntity* ved[2] = {v[i],v[(i+1) % 4]};
apf::buildElement(m, edge, apf::Mesh::EDGE, ved);
}
apf::MeshEntity* ved[2] = {v[0],v[2]};
apf::buildElement(m, m->findModelEntity(2,0), apf::Mesh::EDGE, ved);
apf::MeshEntity* vf0[3] = {v[0],v[1],v[2]};
apf::buildElement(m, m->findModelEntity(2,0), apf::Mesh::TRIANGLE, vf0);
apf::MeshEntity* vf1[3] = {v[0],v[2],v[3]};
apf::buildElement(m, m->findModelEntity(2,0), apf::Mesh::TRIANGLE, vf1);
m->acceptChanges();
m->verify();
return m;
}
void checkValidity(apf::Mesh* m, int order)
{
apf::MeshIterator* it = m->begin(2);
apf::MeshEntity* e;
int iEntity = 0;
while ((e = m->iterate(it))) {
apf::MeshEntity* entities[3];
int numInvalid = crv::checkTriValidity(m,e,entities);
if(iEntity == 0){
assert((numInvalid && order > 3) || (!numInvalid && order <= 3));
} else {
assert(!numInvalid);
}
iEntity++;
break;
}
m->end(it);
}
void test2D()
{
for(int order = 2; order <= 6; ++order){
apf::Mesh2* m = createMesh2D();
apf::changeMeshShape(m, crv::getBezier(3,order),true);
crv::BezierCurver bc(m,order,0);
crv::setBlendingOrder(0);
bc.snapToInterpolate(1);
apf::FieldShape* fs = m->getShape();
// go downward, and convert interpolating to control points
for(int d = 2; d >= 1; --d){
int n = (d == 2)? (order+1)*(order+2)/2 : order+1;
int ne = fs->countNodesOn(d);
apf::NewArray<double> c;
crv::getTransformationCoefficients(3,order,d,c);
apf::MeshEntity* e;
apf::MeshIterator* it = m->begin(d);
while ((e = m->iterate(it))) {
bc.convertInterpolationPoints(e,n,ne,c);
}
m->end(it);
}
// crv::writeCurvedVtuFiles(m,apf::Mesh::TRIANGLE,100,"curved");
testJacobian(m);
testEdgeGradients(m);
checkValidity(m,order);
m->destroyNative();
apf::destroyMesh(m);
}
}
apf::Mesh2* createMesh3D()
{
gmi_model* model = gmi_load(".null");
apf::Mesh2* m = apf::makeEmptyMdsMesh(model, 3, true);
apf::Vector3 points3D[4] =
{apf::Vector3(0,0,0),
apf::Vector3(1,0,0),
apf::Vector3(0,1,0),
apf::Vector3(0,0,1)};
apf::buildOneElement(m,0,apf::Mesh::TET,points3D);
apf::deriveMdsModel(m);
m->acceptChanges();
m->verify();
return m;
}
void test3D()
{
gmi_register_null();
for(int order = 1; order <= 4; ++order){
apf::Mesh2* m = createMesh3D();
apf::changeMeshShape(m, crv::getBezier(3,order),true);
crv::setBlendingOrder(0);
apf::FieldShape* fs = m->getShape();
crv::BezierCurver bc(m,order,0);
// go downward, and convert interpolating to control points
for(int d = 2; d >= 1; --d){
int n = (d == 2)? (order+1)*(order+2)/2 : order+1;
int ne = fs->countNodesOn(d);
apf::NewArray<double> c;
crv::getTransformationCoefficients(3,order,d,c);
apf::MeshEntity* e;
apf::MeshIterator* it = m->begin(d);
while ((e = m->iterate(it))) {
if(m->getModelType(m->toModel(e)) == m->getDimension()) continue;
bc.convertInterpolationPoints(e,n,ne,c);
}
m->end(it);
}
// get face 2
apf::MeshIterator* it = m->begin(3);
apf::MeshEntity* tet = m->iterate(it);
m->end(it);
apf::MeshEntity* faces[4], *edges[3];
m->getDownward(tet,2,faces);
apf::MeshEntity* face = faces[2];
m->getDownward(face,1,edges);
for (int edge = 0; edge < 3; ++edge){
int non = m->getShape()->countNodesOn(apf::Mesh::EDGE);
for (int i = 0; i < non; ++i){
apf::Vector3 pt;
m->getPoint(edges[edge],i,pt);
pt = pt*0.5;
m->setPoint(edges[edge],i,pt);
}
}
int non = m->getShape()->countNodesOn(apf::Mesh::TRIANGLE);
for (int i = 0; i < non; ++i){
apf::Vector3 pt;
m->getPoint(face,i,pt);
pt = pt*0.5;
m->setPoint(face,i,pt);
}
m->acceptChanges();
// apf::MeshEntity* entities[6];
// crv::checkValidity(m,tet,entities);
// write the field
// crv::writeCurvedVtuFiles(m,apf::Mesh::TET,20,"curved");
m->destroyNative();
apf::destroyMesh(m);
}
}
int main(int argc, char** argv)
{
MPI_Init(&argc,&argv);
PCU_Comm_Init();
test2D();
test3D();
PCU_Comm_Free();
MPI_Finalize();
}
<|endoftext|>
|
<commit_before>/* This file is part of the KDE project.
Copyright (C) 2009 Nokia Corporation and/or its subsidiary(-ies).
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 or 3 of the License.
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, see <http://www.gnu.org/licenses/>.
*/
#include "backend.h"
#include "audiooutput.h"
#include "audiodataoutput.h"
#include "videodataoutput.h"
#include "audioeffect.h"
#include "mediaobject.h"
#include "videowidget.h"
#include "devicemanager.h"
#include "effectmanager.h"
#include "volumefadereffect.h"
#include <gst/interfaces/propertyprobe.h>
#include <phonon/pulsesupport.h>
#include <QtCore/QCoreApplication>
#include <QtCore/QSet>
#include <QtCore/QVariant>
#include <QtCore/QtPlugin>
#include <cstring>
QT_BEGIN_NAMESPACE
Q_EXPORT_PLUGIN2(phonon_gstreamer, Phonon::Gstreamer::Backend)
namespace Phonon
{
namespace Gstreamer
{
class MediaNode;
Backend::Backend(QObject *parent, const QVariantList &)
: QObject(parent)
, m_deviceManager(0)
, m_effectManager(0)
, m_debugLevel(Warning)
, m_isValid(false)
{
// Initialise PulseAudio support
PulseSupport *pulse = PulseSupport::getInstance();
pulse->enable();
connect(pulse, SIGNAL(objectDescriptionChanged(ObjectDescriptionType)), SIGNAL(objectDescriptionChanged(ObjectDescriptionType)));
// In order to support reloading, we only set the app name once...
static bool first = true;
if (first) {
first = false;
g_set_application_name(qApp->applicationName().toUtf8());
}
QByteArray appFilePath = qApp->applicationFilePath().toUtf8();
QByteArray gstDebugLevel("--gst-debug-level=");
gstDebugLevel.append(qgetenv("PHONON_GST_GST_DEBUG"));
const char *args[] = {
appFilePath.constData(),
gstDebugLevel.constData(),
"--gst-debug-no-color"
};
int argc = sizeof(args) / sizeof(*args);
char **argv = const_cast<char**>(args);
GError *err = 0;
bool wasInit = gst_init_check(&argc, &argv, &err); //init gstreamer: must be called before any gst-related functions
if (err)
g_error_free(err);
#ifndef QT_NO_PROPERTIES
setProperty("identifier", QLatin1String("phonon_gstreamer"));
setProperty("backendName", QLatin1String("Gstreamer"));
setProperty("backendComment", QLatin1String("Gstreamer plugin for Phonon"));
setProperty("backendVersion", QLatin1String(PHONON_GST_VERSION));
setProperty("backendWebsite", QLatin1String("http://qt.nokia.com/"));
#endif //QT_NO_PROPERTIES
//check if we should enable debug output
QString debugLevelString = qgetenv("PHONON_GST_DEBUG");
int debugLevel = debugLevelString.toInt();
if (debugLevel > 3) //3 is maximum
debugLevel = 3;
m_debugLevel = (DebugLevel)debugLevel;
if (wasInit) {
m_isValid = checkDependencies();
gchar *versionString = gst_version_string();
logMessage(QString("Using %0").arg(versionString));
g_free(versionString);
}
if (!m_isValid)
qWarning("Phonon::GStreamer::Backend: Failed to initialize GStreamer");
m_deviceManager = new DeviceManager(this);
m_effectManager = new EffectManager(this);
}
Backend::~Backend()
{
delete m_effectManager;
delete m_deviceManager;
PulseSupport::shutdown();
}
/***
* !reimp
*/
QObject *Backend::createObject(BackendInterface::Class c, QObject *parent, const QList<QVariant> &args)
{
// Return nothing if dependencies are not met
switch (c) {
case MediaObjectClass:
return new MediaObject(this, parent);
case AudioOutputClass:
return new AudioOutput(this, parent);
#ifndef QT_NO_PHONON_EFFECT
case EffectClass:
return new AudioEffect(this, args[0].toInt(), parent);
#endif //QT_NO_PHONON_EFFECT
case AudioDataOutputClass:
return new AudioDataOutput(this, parent);
#ifndef QT_NO_PHONON_VIDEO
case VideoDataOutputClass:
return new VideoDataOutput(this, parent);
break;
case VideoWidgetClass: {
QWidget *widget = qobject_cast<QWidget*>(parent);
return new VideoWidget(this, widget);
}
#endif //QT_NO_PHONON_VIDEO
#ifndef QT_NO_PHONON_VOLUMEFADEREFFECT
case VolumeFaderEffectClass:
return new VolumeFaderEffect(this, parent);
#endif //QT_NO_PHONON_VOLUMEFADEREFFECT
case VisualizationClass: //Fall through
default:
logMessage("createObject() : Backend object not available");
}
return 0;
}
// Returns true if all dependencies are met
// and gstreamer is usable, otherwise false
bool Backend::isValid() const
{
return m_isValid;
}
bool Backend::supportsVideo() const
{
return isValid();
}
bool Backend::checkDependencies() const
{
bool success = false;
// Verify that gst-plugins-base is installed
GstElementFactory *acFactory = gst_element_factory_find ("audioconvert");
if (acFactory) {
gst_object_unref(acFactory);
success = true;
// Check if gst-plugins-good is installed
GstElementFactory *csFactory = gst_element_factory_find ("videobalance");
if (csFactory) {
gst_object_unref(csFactory);
} else {
QString message = tr("Warning: You do not seem to have the package gstreamer0.10-plugins-good installed.\n"
" Some video features have been disabled.");
qDebug() << message;
}
} else {
qWarning() << tr("Warning: You do not seem to have the base GStreamer plugins installed.\n"
" All audio and video support has been disabled");
}
return success;
}
/***
* !reimp
*/
QStringList Backend::availableMimeTypes() const
{
QStringList availableMimeTypes;
if (!isValid())
return availableMimeTypes;
GstElementFactory *mpegFactory;
// Add mp3 as a separate mime type as people are likely to look for it.
if ((mpegFactory = gst_element_factory_find ("ffmpeg")) ||
(mpegFactory = gst_element_factory_find ("mad")) ||
(mpegFactory = gst_element_factory_find ("flump3dec"))) {
availableMimeTypes << QLatin1String("audio/x-mp3");
gst_object_unref(GST_OBJECT(mpegFactory));
}
// Iterate over all audio and video decoders and extract mime types from sink caps
GList* factoryList = gst_registry_get_feature_list(gst_registry_get_default (), GST_TYPE_ELEMENT_FACTORY);
for (GList* iter = g_list_first(factoryList) ; iter != NULL ; iter = g_list_next(iter)) {
GstPluginFeature *feature = GST_PLUGIN_FEATURE(iter->data);
QString klass = gst_element_factory_get_klass(GST_ELEMENT_FACTORY(feature));
if (klass == QLatin1String("Codec/Decoder") ||
klass == QLatin1String("Codec/Decoder/Audio") ||
klass == QLatin1String("Codec/Decoder/Video") ||
klass == QLatin1String("Codec/Demuxer") ||
klass == QLatin1String("Codec/Demuxer/Audio") ||
klass == QLatin1String("Codec/Demuxer/Video") ||
klass == QLatin1String("Codec/Parser") ||
klass == QLatin1String("Codec/Parser/Audio") ||
klass == QLatin1String("Codec/Parser/Video")) {
const GList *static_templates;
GstElementFactory *factory = GST_ELEMENT_FACTORY(feature);
static_templates = gst_element_factory_get_static_pad_templates(factory);
for (; static_templates != NULL ; static_templates = static_templates->next) {
GstStaticPadTemplate *padTemplate = (GstStaticPadTemplate *) static_templates->data;
if (padTemplate && padTemplate->direction == GST_PAD_SINK) {
GstCaps *caps = gst_static_pad_template_get_caps (padTemplate);
if (caps) {
for (unsigned int struct_idx = 0; struct_idx < gst_caps_get_size (caps); struct_idx++) {
const GstStructure* capsStruct = gst_caps_get_structure (caps, struct_idx);
QString mime = QString::fromUtf8(gst_structure_get_name (capsStruct));
if (!availableMimeTypes.contains(mime))
availableMimeTypes.append(mime);
}
}
}
}
}
}
g_list_free(factoryList);
if (availableMimeTypes.contains("audio/x-vorbis")
&& availableMimeTypes.contains("application/x-ogm-audio")) {
if (!availableMimeTypes.contains("audio/x-vorbis+ogg"))
availableMimeTypes.append("audio/x-vorbis+ogg");
if (!availableMimeTypes.contains("application/ogg")) /* *.ogg */
availableMimeTypes.append("application/ogg");
if (!availableMimeTypes.contains("audio/ogg")) /* *.oga */
availableMimeTypes.append("audio/ogg");
}
availableMimeTypes.sort();
return availableMimeTypes;
}
/***
* !reimp
*/
QList<int> Backend::objectDescriptionIndexes(ObjectDescriptionType type) const
{
QList<int> list;
if (!isValid())
return list;
switch (type) {
case Phonon::AudioOutputDeviceType: {
QList<AudioDevice> deviceList = deviceManager()->audioOutputDevices();
for (int dev = 0 ; dev < deviceList.size() ; ++dev)
list.append(deviceList[dev].id);
break;
}
break;
case Phonon::VideoCaptureDeviceType: {
QList<VideoCaptureDevice> deviceList = deviceManager()->videoCaptureDevices();
for(int dev = 0 ; dev < deviceList.size() ; ++dev)
list.append(deviceList[dev].id);
break;
}
break;
case Phonon::EffectType: {
QList<EffectInfo*> effectList = effectManager()->audioEffects();
for (int eff = 0 ; eff < effectList.size() ; ++eff)
list.append(eff);
break;
}
break;
default:
break;
}
return list;
}
/***
* !reimp
*/
QHash<QByteArray, QVariant> Backend::objectDescriptionProperties(ObjectDescriptionType type, int index) const
{
QHash<QByteArray, QVariant> ret;
if (!isValid())
return ret;
switch (type) {
case Phonon::AudioOutputDeviceType: {
AudioDevice* ad;
if ((ad = deviceManager()->audioDevice(index))) {
ret.insert("name", ad->gstId);
ret.insert("description", ad->description);
ret.insert("icon", ad->icon);
}
}
break;
case Phonon::VideoCaptureDeviceType: {
VideoCaptureDevice* dev;
if ((dev = deviceManager()->videoCaptureDevice(index))) {
ret.insert("name", dev->gstId);
ret.insert("description", dev->description);
ret.insert("icon", dev->icon);
DeviceAccessList devlist;
devlist << DeviceAccess("v4l2", dev->gstId);
ret.insert("deviceAccessList", QVariant::fromValue<Phonon::DeviceAccessList>(devlist));
ret.insert("hasvideo", true);
}
}
break;
case Phonon::EffectType: {
QList<EffectInfo*> effectList = effectManager()->audioEffects();
if (index >= 0 && index <= effectList.size()) {
const EffectInfo *effect = effectList[index];
ret.insert("name", effect->name());
ret.insert("description", effect->description());
ret.insert("author", effect->author());
} else
Q_ASSERT(1); // Since we use list position as ID, this should not happen
}
default:
break;
}
return ret;
}
/***
* !reimp
*/
bool Backend::startConnectionChange(QSet<QObject *> objects)
{
foreach (QObject *object, objects) {
MediaNode *sourceNode = qobject_cast<MediaNode *>(object);
MediaObject *media = sourceNode->root();
if (media) {
media->saveState();
return true;
}
}
return true;
}
/***
* !reimp
*/
bool Backend::connectNodes(QObject *source, QObject *sink)
{
if (isValid()) {
MediaNode *sourceNode = qobject_cast<MediaNode *>(source);
MediaNode *sinkNode = qobject_cast<MediaNode *>(sink);
if (sourceNode && sinkNode) {
if (sourceNode->connectNode(sink)) {
sourceNode->root()->invalidateGraph();
logMessage(QString("Backend connected %0 to %1").arg(source->metaObject()->className()).arg(sink->metaObject()->className()));
return true;
}
}
}
logMessage(QString("Linking %0 to %1 failed").arg(source->metaObject()->className()).arg(sink->metaObject()->className()), Warning);
return false;
}
/***
* !reimp
*/
bool Backend::disconnectNodes(QObject *source, QObject *sink)
{
MediaNode *sourceNode = qobject_cast<MediaNode *>(source);
MediaNode *sinkNode = qobject_cast<MediaNode *>(sink);
if (sourceNode && sinkNode)
return sourceNode->disconnectNode(sink);
else
return false;
}
/***
* !reimp
*/
bool Backend::endConnectionChange(QSet<QObject *> objects)
{
foreach (QObject *object, objects) {
MediaNode *sourceNode = qobject_cast<MediaNode *>(object);
MediaObject *media = sourceNode->root();
if (media) {
media->resumeState();
return true;
}
}
return true;
}
DeviceManager* Backend::deviceManager() const
{
return m_deviceManager;
}
EffectManager* Backend::effectManager() const
{
return m_effectManager;
}
/**
* Returns a debuglevel that is determined by the
* PHONON_GST_DEBUG environment variable.
*
* Warning - important warnings
* Info - general info
* Debug - gives extra info
*/
Backend::DebugLevel Backend::debugLevel() const
{
return m_debugLevel;
}
/***
* Prints a conditional debug message based on the current debug level
* If obj is provided, classname and objectname will be printed as well
*
* see debugLevel()
*/
void Backend::logMessage(const QString &message, int priority, QObject *obj) const
{
if (debugLevel() > 0) {
QString output;
if (obj) {
// Strip away namespace from className
QString className(obj->metaObject()->className());
int nameLength = className.length() - className.lastIndexOf(':') - 1;
className = className.right(nameLength);
output.sprintf("%s %s (%s %p)", message.toLatin1().constData(),
obj->objectName().toLatin1().constData(),
className.toLatin1().constData(), obj);
}
else {
output = message;
}
if (priority <= (int)debugLevel()) {
qDebug() << QString("PGST(%1): %2").arg(priority).arg(output);
}
}
}
}
}
QT_END_NAMESPACE
#include "moc_backend.cpp"
<commit_msg>update backend website<commit_after>/* This file is part of the KDE project.
Copyright (C) 2009 Nokia Corporation and/or its subsidiary(-ies).
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 or 3 of the License.
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, see <http://www.gnu.org/licenses/>.
*/
#include "backend.h"
#include "audiooutput.h"
#include "audiodataoutput.h"
#include "videodataoutput.h"
#include "audioeffect.h"
#include "mediaobject.h"
#include "videowidget.h"
#include "devicemanager.h"
#include "effectmanager.h"
#include "volumefadereffect.h"
#include <gst/interfaces/propertyprobe.h>
#include <phonon/pulsesupport.h>
#include <QtCore/QCoreApplication>
#include <QtCore/QSet>
#include <QtCore/QVariant>
#include <QtCore/QtPlugin>
#include <cstring>
QT_BEGIN_NAMESPACE
Q_EXPORT_PLUGIN2(phonon_gstreamer, Phonon::Gstreamer::Backend)
namespace Phonon
{
namespace Gstreamer
{
class MediaNode;
Backend::Backend(QObject *parent, const QVariantList &)
: QObject(parent)
, m_deviceManager(0)
, m_effectManager(0)
, m_debugLevel(Warning)
, m_isValid(false)
{
// Initialise PulseAudio support
PulseSupport *pulse = PulseSupport::getInstance();
pulse->enable();
connect(pulse, SIGNAL(objectDescriptionChanged(ObjectDescriptionType)), SIGNAL(objectDescriptionChanged(ObjectDescriptionType)));
// In order to support reloading, we only set the app name once...
static bool first = true;
if (first) {
first = false;
g_set_application_name(qApp->applicationName().toUtf8());
}
QByteArray appFilePath = qApp->applicationFilePath().toUtf8();
QByteArray gstDebugLevel("--gst-debug-level=");
gstDebugLevel.append(qgetenv("PHONON_GST_GST_DEBUG"));
const char *args[] = {
appFilePath.constData(),
gstDebugLevel.constData(),
"--gst-debug-no-color"
};
int argc = sizeof(args) / sizeof(*args);
char **argv = const_cast<char**>(args);
GError *err = 0;
bool wasInit = gst_init_check(&argc, &argv, &err); //init gstreamer: must be called before any gst-related functions
if (err)
g_error_free(err);
#ifndef QT_NO_PROPERTIES
setProperty("identifier", QLatin1String("phonon_gstreamer"));
setProperty("backendName", QLatin1String("Gstreamer"));
setProperty("backendComment", QLatin1String("Gstreamer plugin for Phonon"));
setProperty("backendVersion", QLatin1String(PHONON_GST_VERSION));
setProperty("backendWebsite", QLatin1String("http://phonon.kde.org/"));
#endif //QT_NO_PROPERTIES
//check if we should enable debug output
QString debugLevelString = qgetenv("PHONON_GST_DEBUG");
int debugLevel = debugLevelString.toInt();
if (debugLevel > 3) //3 is maximum
debugLevel = 3;
m_debugLevel = (DebugLevel)debugLevel;
if (wasInit) {
m_isValid = checkDependencies();
gchar *versionString = gst_version_string();
logMessage(QString("Using %0").arg(versionString));
g_free(versionString);
}
if (!m_isValid)
qWarning("Phonon::GStreamer::Backend: Failed to initialize GStreamer");
m_deviceManager = new DeviceManager(this);
m_effectManager = new EffectManager(this);
}
Backend::~Backend()
{
delete m_effectManager;
delete m_deviceManager;
PulseSupport::shutdown();
}
/***
* !reimp
*/
QObject *Backend::createObject(BackendInterface::Class c, QObject *parent, const QList<QVariant> &args)
{
// Return nothing if dependencies are not met
switch (c) {
case MediaObjectClass:
return new MediaObject(this, parent);
case AudioOutputClass:
return new AudioOutput(this, parent);
#ifndef QT_NO_PHONON_EFFECT
case EffectClass:
return new AudioEffect(this, args[0].toInt(), parent);
#endif //QT_NO_PHONON_EFFECT
case AudioDataOutputClass:
return new AudioDataOutput(this, parent);
#ifndef QT_NO_PHONON_VIDEO
case VideoDataOutputClass:
return new VideoDataOutput(this, parent);
break;
case VideoWidgetClass: {
QWidget *widget = qobject_cast<QWidget*>(parent);
return new VideoWidget(this, widget);
}
#endif //QT_NO_PHONON_VIDEO
#ifndef QT_NO_PHONON_VOLUMEFADEREFFECT
case VolumeFaderEffectClass:
return new VolumeFaderEffect(this, parent);
#endif //QT_NO_PHONON_VOLUMEFADEREFFECT
case VisualizationClass: //Fall through
default:
logMessage("createObject() : Backend object not available");
}
return 0;
}
// Returns true if all dependencies are met
// and gstreamer is usable, otherwise false
bool Backend::isValid() const
{
return m_isValid;
}
bool Backend::supportsVideo() const
{
return isValid();
}
bool Backend::checkDependencies() const
{
bool success = false;
// Verify that gst-plugins-base is installed
GstElementFactory *acFactory = gst_element_factory_find ("audioconvert");
if (acFactory) {
gst_object_unref(acFactory);
success = true;
// Check if gst-plugins-good is installed
GstElementFactory *csFactory = gst_element_factory_find ("videobalance");
if (csFactory) {
gst_object_unref(csFactory);
} else {
QString message = tr("Warning: You do not seem to have the package gstreamer0.10-plugins-good installed.\n"
" Some video features have been disabled.");
qDebug() << message;
}
} else {
qWarning() << tr("Warning: You do not seem to have the base GStreamer plugins installed.\n"
" All audio and video support has been disabled");
}
return success;
}
/***
* !reimp
*/
QStringList Backend::availableMimeTypes() const
{
QStringList availableMimeTypes;
if (!isValid())
return availableMimeTypes;
GstElementFactory *mpegFactory;
// Add mp3 as a separate mime type as people are likely to look for it.
if ((mpegFactory = gst_element_factory_find ("ffmpeg")) ||
(mpegFactory = gst_element_factory_find ("mad")) ||
(mpegFactory = gst_element_factory_find ("flump3dec"))) {
availableMimeTypes << QLatin1String("audio/x-mp3");
gst_object_unref(GST_OBJECT(mpegFactory));
}
// Iterate over all audio and video decoders and extract mime types from sink caps
GList* factoryList = gst_registry_get_feature_list(gst_registry_get_default (), GST_TYPE_ELEMENT_FACTORY);
for (GList* iter = g_list_first(factoryList) ; iter != NULL ; iter = g_list_next(iter)) {
GstPluginFeature *feature = GST_PLUGIN_FEATURE(iter->data);
QString klass = gst_element_factory_get_klass(GST_ELEMENT_FACTORY(feature));
if (klass == QLatin1String("Codec/Decoder") ||
klass == QLatin1String("Codec/Decoder/Audio") ||
klass == QLatin1String("Codec/Decoder/Video") ||
klass == QLatin1String("Codec/Demuxer") ||
klass == QLatin1String("Codec/Demuxer/Audio") ||
klass == QLatin1String("Codec/Demuxer/Video") ||
klass == QLatin1String("Codec/Parser") ||
klass == QLatin1String("Codec/Parser/Audio") ||
klass == QLatin1String("Codec/Parser/Video")) {
const GList *static_templates;
GstElementFactory *factory = GST_ELEMENT_FACTORY(feature);
static_templates = gst_element_factory_get_static_pad_templates(factory);
for (; static_templates != NULL ; static_templates = static_templates->next) {
GstStaticPadTemplate *padTemplate = (GstStaticPadTemplate *) static_templates->data;
if (padTemplate && padTemplate->direction == GST_PAD_SINK) {
GstCaps *caps = gst_static_pad_template_get_caps (padTemplate);
if (caps) {
for (unsigned int struct_idx = 0; struct_idx < gst_caps_get_size (caps); struct_idx++) {
const GstStructure* capsStruct = gst_caps_get_structure (caps, struct_idx);
QString mime = QString::fromUtf8(gst_structure_get_name (capsStruct));
if (!availableMimeTypes.contains(mime))
availableMimeTypes.append(mime);
}
}
}
}
}
}
g_list_free(factoryList);
if (availableMimeTypes.contains("audio/x-vorbis")
&& availableMimeTypes.contains("application/x-ogm-audio")) {
if (!availableMimeTypes.contains("audio/x-vorbis+ogg"))
availableMimeTypes.append("audio/x-vorbis+ogg");
if (!availableMimeTypes.contains("application/ogg")) /* *.ogg */
availableMimeTypes.append("application/ogg");
if (!availableMimeTypes.contains("audio/ogg")) /* *.oga */
availableMimeTypes.append("audio/ogg");
}
availableMimeTypes.sort();
return availableMimeTypes;
}
/***
* !reimp
*/
QList<int> Backend::objectDescriptionIndexes(ObjectDescriptionType type) const
{
QList<int> list;
if (!isValid())
return list;
switch (type) {
case Phonon::AudioOutputDeviceType: {
QList<AudioDevice> deviceList = deviceManager()->audioOutputDevices();
for (int dev = 0 ; dev < deviceList.size() ; ++dev)
list.append(deviceList[dev].id);
break;
}
break;
case Phonon::VideoCaptureDeviceType: {
QList<VideoCaptureDevice> deviceList = deviceManager()->videoCaptureDevices();
for(int dev = 0 ; dev < deviceList.size() ; ++dev)
list.append(deviceList[dev].id);
break;
}
break;
case Phonon::EffectType: {
QList<EffectInfo*> effectList = effectManager()->audioEffects();
for (int eff = 0 ; eff < effectList.size() ; ++eff)
list.append(eff);
break;
}
break;
default:
break;
}
return list;
}
/***
* !reimp
*/
QHash<QByteArray, QVariant> Backend::objectDescriptionProperties(ObjectDescriptionType type, int index) const
{
QHash<QByteArray, QVariant> ret;
if (!isValid())
return ret;
switch (type) {
case Phonon::AudioOutputDeviceType: {
AudioDevice* ad;
if ((ad = deviceManager()->audioDevice(index))) {
ret.insert("name", ad->gstId);
ret.insert("description", ad->description);
ret.insert("icon", ad->icon);
}
}
break;
case Phonon::VideoCaptureDeviceType: {
VideoCaptureDevice* dev;
if ((dev = deviceManager()->videoCaptureDevice(index))) {
ret.insert("name", dev->gstId);
ret.insert("description", dev->description);
ret.insert("icon", dev->icon);
DeviceAccessList devlist;
devlist << DeviceAccess("v4l2", dev->gstId);
ret.insert("deviceAccessList", QVariant::fromValue<Phonon::DeviceAccessList>(devlist));
ret.insert("hasvideo", true);
}
}
break;
case Phonon::EffectType: {
QList<EffectInfo*> effectList = effectManager()->audioEffects();
if (index >= 0 && index <= effectList.size()) {
const EffectInfo *effect = effectList[index];
ret.insert("name", effect->name());
ret.insert("description", effect->description());
ret.insert("author", effect->author());
} else
Q_ASSERT(1); // Since we use list position as ID, this should not happen
}
default:
break;
}
return ret;
}
/***
* !reimp
*/
bool Backend::startConnectionChange(QSet<QObject *> objects)
{
foreach (QObject *object, objects) {
MediaNode *sourceNode = qobject_cast<MediaNode *>(object);
MediaObject *media = sourceNode->root();
if (media) {
media->saveState();
return true;
}
}
return true;
}
/***
* !reimp
*/
bool Backend::connectNodes(QObject *source, QObject *sink)
{
if (isValid()) {
MediaNode *sourceNode = qobject_cast<MediaNode *>(source);
MediaNode *sinkNode = qobject_cast<MediaNode *>(sink);
if (sourceNode && sinkNode) {
if (sourceNode->connectNode(sink)) {
sourceNode->root()->invalidateGraph();
logMessage(QString("Backend connected %0 to %1").arg(source->metaObject()->className()).arg(sink->metaObject()->className()));
return true;
}
}
}
logMessage(QString("Linking %0 to %1 failed").arg(source->metaObject()->className()).arg(sink->metaObject()->className()), Warning);
return false;
}
/***
* !reimp
*/
bool Backend::disconnectNodes(QObject *source, QObject *sink)
{
MediaNode *sourceNode = qobject_cast<MediaNode *>(source);
MediaNode *sinkNode = qobject_cast<MediaNode *>(sink);
if (sourceNode && sinkNode)
return sourceNode->disconnectNode(sink);
else
return false;
}
/***
* !reimp
*/
bool Backend::endConnectionChange(QSet<QObject *> objects)
{
foreach (QObject *object, objects) {
MediaNode *sourceNode = qobject_cast<MediaNode *>(object);
MediaObject *media = sourceNode->root();
if (media) {
media->resumeState();
return true;
}
}
return true;
}
DeviceManager* Backend::deviceManager() const
{
return m_deviceManager;
}
EffectManager* Backend::effectManager() const
{
return m_effectManager;
}
/**
* Returns a debuglevel that is determined by the
* PHONON_GST_DEBUG environment variable.
*
* Warning - important warnings
* Info - general info
* Debug - gives extra info
*/
Backend::DebugLevel Backend::debugLevel() const
{
return m_debugLevel;
}
/***
* Prints a conditional debug message based on the current debug level
* If obj is provided, classname and objectname will be printed as well
*
* see debugLevel()
*/
void Backend::logMessage(const QString &message, int priority, QObject *obj) const
{
if (debugLevel() > 0) {
QString output;
if (obj) {
// Strip away namespace from className
QString className(obj->metaObject()->className());
int nameLength = className.length() - className.lastIndexOf(':') - 1;
className = className.right(nameLength);
output.sprintf("%s %s (%s %p)", message.toLatin1().constData(),
obj->objectName().toLatin1().constData(),
className.toLatin1().constData(), obj);
}
else {
output = message;
}
if (priority <= (int)debugLevel()) {
qDebug() << QString("PGST(%1): %2").arg(priority).arg(output);
}
}
}
}
}
QT_END_NAMESPACE
#include "moc_backend.cpp"
<|endoftext|>
|
<commit_before>// Copyright (c) 2006-2008 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "app/gfx/font.h"
#include "app/gfx/text_elider.h"
#include "base/file_path.h"
#include "base/string_util.h"
#include "googleurl/src/gurl.h"
#include "testing/gtest/include/gtest/gtest.h"
using namespace gfx;
namespace {
const wchar_t kEllipsis[] = L"\x2026";
struct Testcase {
const std::string input;
const std::wstring output;
};
struct FileTestcase {
const FilePath::StringType input;
const std::wstring output;
};
struct WideTestcase {
const std::wstring input;
const std::wstring output;
};
struct TestData {
const std::string a;
const std::string b;
const int compare_result;
};
void RunTest(Testcase* testcases, size_t num_testcases) {
static const gfx::Font font;
for (size_t i = 0; i < num_testcases; ++i) {
const GURL url(testcases[i].input);
// Should we test with non-empty language list?
// That's kinda redundant with net_util_unittests.
EXPECT_EQ(testcases[i].output,
ElideUrl(url, font, font.GetStringWidth(testcases[i].output),
std::wstring()));
}
}
} // namespace
// Test eliding of commonplace URLs.
TEST(TextEliderTest, TestGeneralEliding) {
const std::wstring kEllipsisStr(kEllipsis);
Testcase testcases[] = {
{"http://www.google.com/intl/en/ads/",
L"http://www.google.com/intl/en/ads/"},
{"http://www.google.com/intl/en/ads/", L"www.google.com/intl/en/ads/"},
// TODO(port): make this test case work on mac.
#if !defined(OS_MACOSX)
{"http://www.google.com/intl/en/ads/",
L"google.com/intl/" + kEllipsisStr + L"/ads/"},
#endif
{"http://www.google.com/intl/en/ads/",
L"google.com/" + kEllipsisStr + L"/ads/"},
{"http://www.google.com/intl/en/ads/", L"google.com/" + kEllipsisStr},
{"http://www.google.com/intl/en/ads/", L"goog" + kEllipsisStr},
{"https://subdomain.foo.com/bar/filename.html",
L"subdomain.foo.com/bar/filename.html"},
{"https://subdomain.foo.com/bar/filename.html",
L"subdomain.foo.com/" + kEllipsisStr + L"/filename.html"},
{"http://subdomain.foo.com/bar/filename.html",
kEllipsisStr + L"foo.com/" + kEllipsisStr + L"/filename.html"},
{"http://www.google.com/intl/en/ads/?aLongQueryWhichIsNotRequired",
L"http://www.google.com/intl/en/ads/?aLongQ" + kEllipsisStr},
};
RunTest(testcases, arraysize(testcases));
}
// Test eliding of empty strings, URLs with ports, passwords, queries, etc.
TEST(TextEliderTest, TestMoreEliding) {
const std::wstring kEllipsisStr(kEllipsis);
Testcase testcases[] = {
{"http://www.google.com/foo?bar", L"http://www.google.com/foo?bar"},
{"http://xyz.google.com/foo?bar", L"xyz.google.com/foo?" + kEllipsisStr},
{"http://xyz.google.com/foo?bar", L"xyz.google.com/foo" + kEllipsisStr},
{"http://xyz.google.com/foo?bar", L"xyz.google.com/fo" + kEllipsisStr},
{"http://a.b.com/pathname/c?d", L"a.b.com/" + kEllipsisStr + L"/c?d"},
{"", L""},
{"http://foo.bar..example.com...hello/test/filename.html",
L"foo.bar..example.com...hello/" + kEllipsisStr + L"/filename.html"},
{"http://foo.bar../", L"http://foo.bar../"},
{"http://xn--1lq90i.cn/foo", L"http://\x5317\x4eac.cn/foo"},
{"http://me:mypass@secrethost.com:99/foo?bar#baz",
L"http://secrethost.com:99/foo?bar#baz"},
{"http://me:mypass@ss%xxfdsf.com/foo", L"http://ss%25xxfdsf.com/foo"},
{"mailto:elgoato@elgoato.com", L"mailto:elgoato@elgoato.com"},
{"javascript:click(0)", L"javascript:click(0)"},
{"https://chess.eecs.berkeley.edu:4430/login/arbitfilename",
L"chess.eecs.berkeley.edu:4430/login/arbitfilename"},
{"https://chess.eecs.berkeley.edu:4430/login/arbitfilename",
kEllipsisStr + L"berkeley.edu:4430/" + kEllipsisStr + L"/arbitfilename"},
// Unescaping.
{"http://www/%E4%BD%A0%E5%A5%BD?q=%E4%BD%A0%E5%A5%BD#\xe4\xbd\xa0",
L"http://www/\x4f60\x597d?q=\x4f60\x597d#\x4f60"},
// Invalid unescaping for path. The ref will always be valid UTF-8. We don't
// bother to do too many edge cases, since these are handled by the escaper
// unittest.
{"http://www/%E4%A0%E5%A5%BD?q=%E4%BD%A0%E5%A5%BD#\xe4\xbd\xa0",
L"http://www/%E4%A0%E5%A5%BD?q=\x4f60\x597d#\x4f60"},
};
RunTest(testcases, arraysize(testcases));
}
// Test eliding of file: URLs.
TEST(TextEliderTest, TestFileURLEliding) {
const std::wstring kEllipsisStr(kEllipsis);
Testcase testcases[] = {
{"file:///C:/path1/path2/path3/filename",
L"file:///C:/path1/path2/path3/filename"},
{"file:///C:/path1/path2/path3/filename",
L"C:/path1/path2/path3/filename"},
// GURL parses "file:///C:path" differently on windows than it does on posix.
#if defined(OS_WIN)
{"file:///C:path1/path2/path3/filename",
L"C:/path1/path2/" + kEllipsisStr + L"/filename"},
{"file:///C:path1/path2/path3/filename",
L"C:/path1/" + kEllipsisStr + L"/filename"},
{"file:///C:path1/path2/path3/filename",
L"C:/" + kEllipsisStr + L"/filename"},
#endif
{"file://filer/foo/bar/file", L"filer/foo/bar/file"},
{"file://filer/foo/bar/file", L"filer/foo/" + kEllipsisStr + L"/file"},
{"file://filer/foo/bar/file", L"filer/" + kEllipsisStr + L"/file"},
};
RunTest(testcases, arraysize(testcases));
}
TEST(TextEliderTest, TestFilenameEliding) {
const std::wstring kEllipsisStr(kEllipsis);
const FilePath::StringType kPathSeparator =
FilePath::StringType().append(1, FilePath::kSeparators[0]);
FileTestcase testcases[] = {
{FILE_PATH_LITERAL(""), L""},
{FILE_PATH_LITERAL("."), L"."},
{FILE_PATH_LITERAL("filename.exe"), L"filename.exe"},
{FILE_PATH_LITERAL(".longext"), L".longext"},
{FILE_PATH_LITERAL("pie"), L"pie"},
{FILE_PATH_LITERAL("c:") + kPathSeparator + FILE_PATH_LITERAL("path") +
kPathSeparator + FILE_PATH_LITERAL("filename.pie"),
L"filename.pie"},
{FILE_PATH_LITERAL("c:") + kPathSeparator + FILE_PATH_LITERAL("path") +
kPathSeparator + FILE_PATH_LITERAL("longfilename.pie"),
L"long" + kEllipsisStr + L".pie"},
{FILE_PATH_LITERAL("http://path.com/filename.pie"), L"filename.pie"},
{FILE_PATH_LITERAL("http://path.com/longfilename.pie"),
L"long" + kEllipsisStr + L".pie"},
{FILE_PATH_LITERAL("piesmashingtacularpants"), L"pie" + kEllipsisStr},
{FILE_PATH_LITERAL(".piesmashingtacularpants"), L".pie" + kEllipsisStr},
{FILE_PATH_LITERAL("cheese."), L"cheese."},
{FILE_PATH_LITERAL("file name.longext"),
L"file" + kEllipsisStr + L".longext"},
{FILE_PATH_LITERAL("fil ename.longext"),
L"fil " + kEllipsisStr + L".longext"},
{FILE_PATH_LITERAL("filename.longext"),
L"file" + kEllipsisStr + L".longext"},
{FILE_PATH_LITERAL("filename.middleext.longext"),
L"filename.mid" + kEllipsisStr + L".longext"}
};
static const gfx::Font font;
for (size_t i = 0; i < arraysize(testcases); ++i) {
FilePath filepath(testcases[i].input);
EXPECT_EQ(testcases[i].output, ElideFilename(filepath,
font,
font.GetStringWidth(testcases[i].output)));
}
}
TEST(TextEliderTest, ElideTextLongStrings) {
const std::wstring kEllipsisStr(kEllipsis);
std::wstring data_scheme(L"data:text/plain,");
std::wstring ten_a(10, L'a');
std::wstring hundred_a(100, L'a');
std::wstring thousand_a(1000, L'a');
std::wstring ten_thousand_a(10000, L'a');
std::wstring hundred_thousand_a(100000, L'a');
std::wstring million_a(1000000, L'a');
WideTestcase testcases[] = {
{data_scheme + ten_a,
data_scheme + ten_a},
{data_scheme + hundred_a,
data_scheme + hundred_a},
{data_scheme + thousand_a,
data_scheme + std::wstring(156, L'a') + kEllipsisStr},
{data_scheme + ten_thousand_a,
data_scheme + std::wstring(156, L'a') + kEllipsisStr},
{data_scheme + hundred_thousand_a,
data_scheme + std::wstring(156, L'a') + kEllipsisStr},
{data_scheme + million_a,
data_scheme + std::wstring(156, L'a') + kEllipsisStr},
};
const gfx::Font font;
int ellipsis_width = font.GetStringWidth(kEllipsisStr);
for (size_t i = 0; i < arraysize(testcases); ++i) {
// Compare sizes rather than actual contents because if the test fails,
// output is rather long.
EXPECT_EQ(testcases[i].output.size(),
ElideText(testcases[i].input, font,
font.GetStringWidth(testcases[i].output)).size());
EXPECT_EQ(kEllipsisStr,
ElideText(testcases[i].input, font, ellipsis_width));
}
}
// Verifies display_url is set correctly.
TEST(TextEliderTest, SortedDisplayURL) {
gfx::SortedDisplayURL d_url(GURL("http://www.google.com/"), std::wstring());
EXPECT_EQ("http://www.google.com/", UTF16ToASCII(d_url.display_url()));
}
// Verifies DisplayURL::Compare works correctly.
TEST(TextEliderTest, SortedDisplayURLCompare) {
UErrorCode create_status = U_ZERO_ERROR;
scoped_ptr<Collator> collator(Collator::createInstance(create_status));
if (!U_SUCCESS(create_status))
return;
TestData tests[] = {
// IDN comparison. Hosts equal, so compares on path.
{ "http://xn--1lq90i.cn/a", "http://xn--1lq90i.cn/b", -1},
// Because the host and after host match, this compares the full url.
{ "http://www.x/b", "http://x/b", -1 },
// Because the host and after host match, this compares the full url.
{ "http://www.a:1/b", "http://a:1/b", 1 },
// The hosts match, so these end up comparing on the after host portion.
{ "http://www.x:0/b", "http://x:1/b", -1 },
{ "http://www.x/a", "http://x/b", -1 },
{ "http://x/b", "http://www.x/a", 1 },
// Trivial Equality.
{ "http://a/", "http://a/", 0 },
// Compares just hosts.
{ "http://www.a/", "http://b/", -1 },
};
for (size_t i = 0; i < arraysize(tests); ++i) {
gfx::SortedDisplayURL url1(GURL(tests[i].a), std::wstring());
gfx::SortedDisplayURL url2(GURL(tests[i].b), std::wstring());
EXPECT_EQ(tests[i].compare_result, url1.Compare(url2, collator.get()));
EXPECT_EQ(-tests[i].compare_result, url2.Compare(url1, collator.get()));
}
}
<commit_msg>Disable TextEliderTest.ElideTextLongStrings because it fails on linux Review URL: http://codereview.chromium.org/149059<commit_after>// Copyright (c) 2006-2008 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "app/gfx/font.h"
#include "app/gfx/text_elider.h"
#include "base/file_path.h"
#include "base/string_util.h"
#include "googleurl/src/gurl.h"
#include "testing/gtest/include/gtest/gtest.h"
using namespace gfx;
namespace {
const wchar_t kEllipsis[] = L"\x2026";
struct Testcase {
const std::string input;
const std::wstring output;
};
struct FileTestcase {
const FilePath::StringType input;
const std::wstring output;
};
struct WideTestcase {
const std::wstring input;
const std::wstring output;
};
struct TestData {
const std::string a;
const std::string b;
const int compare_result;
};
void RunTest(Testcase* testcases, size_t num_testcases) {
static const gfx::Font font;
for (size_t i = 0; i < num_testcases; ++i) {
const GURL url(testcases[i].input);
// Should we test with non-empty language list?
// That's kinda redundant with net_util_unittests.
EXPECT_EQ(testcases[i].output,
ElideUrl(url, font, font.GetStringWidth(testcases[i].output),
std::wstring()));
}
}
} // namespace
// Test eliding of commonplace URLs.
TEST(TextEliderTest, TestGeneralEliding) {
const std::wstring kEllipsisStr(kEllipsis);
Testcase testcases[] = {
{"http://www.google.com/intl/en/ads/",
L"http://www.google.com/intl/en/ads/"},
{"http://www.google.com/intl/en/ads/", L"www.google.com/intl/en/ads/"},
// TODO(port): make this test case work on mac.
#if !defined(OS_MACOSX)
{"http://www.google.com/intl/en/ads/",
L"google.com/intl/" + kEllipsisStr + L"/ads/"},
#endif
{"http://www.google.com/intl/en/ads/",
L"google.com/" + kEllipsisStr + L"/ads/"},
{"http://www.google.com/intl/en/ads/", L"google.com/" + kEllipsisStr},
{"http://www.google.com/intl/en/ads/", L"goog" + kEllipsisStr},
{"https://subdomain.foo.com/bar/filename.html",
L"subdomain.foo.com/bar/filename.html"},
{"https://subdomain.foo.com/bar/filename.html",
L"subdomain.foo.com/" + kEllipsisStr + L"/filename.html"},
{"http://subdomain.foo.com/bar/filename.html",
kEllipsisStr + L"foo.com/" + kEllipsisStr + L"/filename.html"},
{"http://www.google.com/intl/en/ads/?aLongQueryWhichIsNotRequired",
L"http://www.google.com/intl/en/ads/?aLongQ" + kEllipsisStr},
};
RunTest(testcases, arraysize(testcases));
}
// Test eliding of empty strings, URLs with ports, passwords, queries, etc.
TEST(TextEliderTest, TestMoreEliding) {
const std::wstring kEllipsisStr(kEllipsis);
Testcase testcases[] = {
{"http://www.google.com/foo?bar", L"http://www.google.com/foo?bar"},
{"http://xyz.google.com/foo?bar", L"xyz.google.com/foo?" + kEllipsisStr},
{"http://xyz.google.com/foo?bar", L"xyz.google.com/foo" + kEllipsisStr},
{"http://xyz.google.com/foo?bar", L"xyz.google.com/fo" + kEllipsisStr},
{"http://a.b.com/pathname/c?d", L"a.b.com/" + kEllipsisStr + L"/c?d"},
{"", L""},
{"http://foo.bar..example.com...hello/test/filename.html",
L"foo.bar..example.com...hello/" + kEllipsisStr + L"/filename.html"},
{"http://foo.bar../", L"http://foo.bar../"},
{"http://xn--1lq90i.cn/foo", L"http://\x5317\x4eac.cn/foo"},
{"http://me:mypass@secrethost.com:99/foo?bar#baz",
L"http://secrethost.com:99/foo?bar#baz"},
{"http://me:mypass@ss%xxfdsf.com/foo", L"http://ss%25xxfdsf.com/foo"},
{"mailto:elgoato@elgoato.com", L"mailto:elgoato@elgoato.com"},
{"javascript:click(0)", L"javascript:click(0)"},
{"https://chess.eecs.berkeley.edu:4430/login/arbitfilename",
L"chess.eecs.berkeley.edu:4430/login/arbitfilename"},
{"https://chess.eecs.berkeley.edu:4430/login/arbitfilename",
kEllipsisStr + L"berkeley.edu:4430/" + kEllipsisStr + L"/arbitfilename"},
// Unescaping.
{"http://www/%E4%BD%A0%E5%A5%BD?q=%E4%BD%A0%E5%A5%BD#\xe4\xbd\xa0",
L"http://www/\x4f60\x597d?q=\x4f60\x597d#\x4f60"},
// Invalid unescaping for path. The ref will always be valid UTF-8. We don't
// bother to do too many edge cases, since these are handled by the escaper
// unittest.
{"http://www/%E4%A0%E5%A5%BD?q=%E4%BD%A0%E5%A5%BD#\xe4\xbd\xa0",
L"http://www/%E4%A0%E5%A5%BD?q=\x4f60\x597d#\x4f60"},
};
RunTest(testcases, arraysize(testcases));
}
// Test eliding of file: URLs.
TEST(TextEliderTest, TestFileURLEliding) {
const std::wstring kEllipsisStr(kEllipsis);
Testcase testcases[] = {
{"file:///C:/path1/path2/path3/filename",
L"file:///C:/path1/path2/path3/filename"},
{"file:///C:/path1/path2/path3/filename",
L"C:/path1/path2/path3/filename"},
// GURL parses "file:///C:path" differently on windows than it does on posix.
#if defined(OS_WIN)
{"file:///C:path1/path2/path3/filename",
L"C:/path1/path2/" + kEllipsisStr + L"/filename"},
{"file:///C:path1/path2/path3/filename",
L"C:/path1/" + kEllipsisStr + L"/filename"},
{"file:///C:path1/path2/path3/filename",
L"C:/" + kEllipsisStr + L"/filename"},
#endif
{"file://filer/foo/bar/file", L"filer/foo/bar/file"},
{"file://filer/foo/bar/file", L"filer/foo/" + kEllipsisStr + L"/file"},
{"file://filer/foo/bar/file", L"filer/" + kEllipsisStr + L"/file"},
};
RunTest(testcases, arraysize(testcases));
}
TEST(TextEliderTest, TestFilenameEliding) {
const std::wstring kEllipsisStr(kEllipsis);
const FilePath::StringType kPathSeparator =
FilePath::StringType().append(1, FilePath::kSeparators[0]);
FileTestcase testcases[] = {
{FILE_PATH_LITERAL(""), L""},
{FILE_PATH_LITERAL("."), L"."},
{FILE_PATH_LITERAL("filename.exe"), L"filename.exe"},
{FILE_PATH_LITERAL(".longext"), L".longext"},
{FILE_PATH_LITERAL("pie"), L"pie"},
{FILE_PATH_LITERAL("c:") + kPathSeparator + FILE_PATH_LITERAL("path") +
kPathSeparator + FILE_PATH_LITERAL("filename.pie"),
L"filename.pie"},
{FILE_PATH_LITERAL("c:") + kPathSeparator + FILE_PATH_LITERAL("path") +
kPathSeparator + FILE_PATH_LITERAL("longfilename.pie"),
L"long" + kEllipsisStr + L".pie"},
{FILE_PATH_LITERAL("http://path.com/filename.pie"), L"filename.pie"},
{FILE_PATH_LITERAL("http://path.com/longfilename.pie"),
L"long" + kEllipsisStr + L".pie"},
{FILE_PATH_LITERAL("piesmashingtacularpants"), L"pie" + kEllipsisStr},
{FILE_PATH_LITERAL(".piesmashingtacularpants"), L".pie" + kEllipsisStr},
{FILE_PATH_LITERAL("cheese."), L"cheese."},
{FILE_PATH_LITERAL("file name.longext"),
L"file" + kEllipsisStr + L".longext"},
{FILE_PATH_LITERAL("fil ename.longext"),
L"fil " + kEllipsisStr + L".longext"},
{FILE_PATH_LITERAL("filename.longext"),
L"file" + kEllipsisStr + L".longext"},
{FILE_PATH_LITERAL("filename.middleext.longext"),
L"filename.mid" + kEllipsisStr + L".longext"}
};
static const gfx::Font font;
for (size_t i = 0; i < arraysize(testcases); ++i) {
FilePath filepath(testcases[i].input);
EXPECT_EQ(testcases[i].output, ElideFilename(filepath,
font,
font.GetStringWidth(testcases[i].output)));
}
}
// This test is disabled.
// See bug 15435.
TEST(TextEliderTest, DISABLED_ElideTextLongStrings) {
const std::wstring kEllipsisStr(kEllipsis);
std::wstring data_scheme(L"data:text/plain,");
std::wstring ten_a(10, L'a');
std::wstring hundred_a(100, L'a');
std::wstring thousand_a(1000, L'a');
std::wstring ten_thousand_a(10000, L'a');
std::wstring hundred_thousand_a(100000, L'a');
std::wstring million_a(1000000, L'a');
WideTestcase testcases[] = {
{data_scheme + ten_a,
data_scheme + ten_a},
{data_scheme + hundred_a,
data_scheme + hundred_a},
{data_scheme + thousand_a,
data_scheme + std::wstring(156, L'a') + kEllipsisStr},
{data_scheme + ten_thousand_a,
data_scheme + std::wstring(156, L'a') + kEllipsisStr},
{data_scheme + hundred_thousand_a,
data_scheme + std::wstring(156, L'a') + kEllipsisStr},
{data_scheme + million_a,
data_scheme + std::wstring(156, L'a') + kEllipsisStr},
};
const gfx::Font font;
int ellipsis_width = font.GetStringWidth(kEllipsisStr);
for (size_t i = 0; i < arraysize(testcases); ++i) {
// Compare sizes rather than actual contents because if the test fails,
// output is rather long.
EXPECT_EQ(testcases[i].output.size(),
ElideText(testcases[i].input, font,
font.GetStringWidth(testcases[i].output)).size());
EXPECT_EQ(kEllipsisStr,
ElideText(testcases[i].input, font, ellipsis_width));
}
}
// Verifies display_url is set correctly.
TEST(TextEliderTest, SortedDisplayURL) {
gfx::SortedDisplayURL d_url(GURL("http://www.google.com/"), std::wstring());
EXPECT_EQ("http://www.google.com/", UTF16ToASCII(d_url.display_url()));
}
// Verifies DisplayURL::Compare works correctly.
TEST(TextEliderTest, SortedDisplayURLCompare) {
UErrorCode create_status = U_ZERO_ERROR;
scoped_ptr<Collator> collator(Collator::createInstance(create_status));
if (!U_SUCCESS(create_status))
return;
TestData tests[] = {
// IDN comparison. Hosts equal, so compares on path.
{ "http://xn--1lq90i.cn/a", "http://xn--1lq90i.cn/b", -1},
// Because the host and after host match, this compares the full url.
{ "http://www.x/b", "http://x/b", -1 },
// Because the host and after host match, this compares the full url.
{ "http://www.a:1/b", "http://a:1/b", 1 },
// The hosts match, so these end up comparing on the after host portion.
{ "http://www.x:0/b", "http://x:1/b", -1 },
{ "http://www.x/a", "http://x/b", -1 },
{ "http://x/b", "http://www.x/a", 1 },
// Trivial Equality.
{ "http://a/", "http://a/", 0 },
// Compares just hosts.
{ "http://www.a/", "http://b/", -1 },
};
for (size_t i = 0; i < arraysize(tests); ++i) {
gfx::SortedDisplayURL url1(GURL(tests[i].a), std::wstring());
gfx::SortedDisplayURL url2(GURL(tests[i].b), std::wstring());
EXPECT_EQ(tests[i].compare_result, url1.Compare(url2, collator.get()));
EXPECT_EQ(-tests[i].compare_result, url2.Compare(url1, collator.get()));
}
}
<|endoftext|>
|
<commit_before>#define DEBUG 1
/**
* File : C2.cpp
* Author : Kazune Takahashi
* Created : 2019-6-3 00:42:00
* Powered by Visual Studio Code
*/
#include <iostream>
#include <iomanip>
#include <algorithm>
#include <vector>
#include <string>
#include <complex>
#include <tuple>
#include <queue>
#include <stack>
#include <map>
#include <set>
#include <functional>
#include <random>
#include <chrono>
#include <cctype>
#include <cassert>
#include <cmath>
#include <cstdio>
#include <cstdlib>
using namespace std;
typedef long long ll;
/*
void Yes()
{
cout << "Yes" << endl;
exit(0);
}
void No()
{
cout << "No" << endl;
exit(0);
}
*/
/*
const int dx[4] = {1, 0, -1, 0};
const int dy[4] = {0, 1, 0, -1};
*/
// const ll MOD = 1000000007;
ll N, X;
ll b[100010], l[100010], u[100010];
ll base = 0;
typedef tuple<ll, ll, ll, ll> test;
vector<test> V;
ll sum[100010];
bool solve(ll T)
{
ll cnt = T / X;
ll x = T % X;
ll ans = 0;
for (auto i = 0; i < cnt; i++)
{
ll t, b, l, u;
tie(t, b, l, u) = V[i];
ll tmp = -t;
if (x >= b)
{
tmp += l * b + u * (x - b);
}
else
{
tmp += l * x;
}
ans = max(ans, sum[cnt + 1] + tmp);
}
for (auto i = cnt; i < N; i++)
{
ll t, b, l, u;
tie(t, b, l, u) = V[i];
ll tmp = 0;
if (x >= b)
{
tmp = l * b + u * (x - b);
}
else
{
tmp = l * x;
}
ans = max(ans, sum[cnt] + tmp);
}
return (ans >= 0);
}
int main()
{
cin >> N >> X;
for (auto i = 0; i < N; i++)
{
cin >> b[i] >> l[i] >> u[i];
}
for (auto i = 0; i < N; i++)
{
base -= l[i] * b[i];
}
for (auto i = 0; i < N; i++)
{
ll t = l[i] * b[i] + u[i] * (X - b[i]);
V.emplace_back(t, b[i], l[i], u[i]);
}
sort(V.begin(), V.end());
reverse(V.begin(), V.end());
sum[0] = base;
for (auto i = 0; i < N; i++)
{
sum[i + 1] = sum[i] + get<0>(V[i]);
}
ll ok = N * X + 1;
ll ng = -1;
while (abs(ok - ng) > 1)
{
ll t = (ok + ng) / 2;
if (solve(t))
{
ok = t;
}
else
{
ng = t;
}
}
cout << ok << endl;
}<commit_msg>submit C2.cpp to 'C - Tests' (agc034) [C++14 (GCC 5.4.1)]<commit_after>#define DEBUG 1
/**
* File : C2.cpp
* Author : Kazune Takahashi
* Created : 2019-6-3 00:42:00
* Powered by Visual Studio Code
*/
#include <iostream>
#include <iomanip>
#include <algorithm>
#include <vector>
#include <string>
#include <complex>
#include <tuple>
#include <queue>
#include <stack>
#include <map>
#include <set>
#include <functional>
#include <random>
#include <chrono>
#include <cctype>
#include <cassert>
#include <cmath>
#include <cstdio>
#include <cstdlib>
using namespace std;
typedef long long ll;
/*
void Yes()
{
cout << "Yes" << endl;
exit(0);
}
void No()
{
cout << "No" << endl;
exit(0);
}
*/
/*
const int dx[4] = {1, 0, -1, 0};
const int dy[4] = {0, 1, 0, -1};
*/
// const ll MOD = 1000000007;
ll N, X;
ll b[100010], l[100010], u[100010];
ll base = 0;
typedef tuple<ll, ll, ll, ll> test;
vector<test> V;
ll sum[100010];
bool solve(ll T)
{
ll cnt = T / X;
ll x = T % X;
ll ans = -1000000000000000;
for (auto i = 0; i < cnt; i++)
{
ll t, b, l, u;
tie(t, b, l, u) = V[i];
ll tmp = -t;
if (x >= b)
{
tmp += l * b + u * (x - b);
}
else
{
tmp += l * x;
}
ans = max(ans, sum[cnt + 1] + tmp);
}
for (auto i = cnt; i < N; i++)
{
ll t, b, l, u;
tie(t, b, l, u) = V[i];
ll tmp = 0;
if (x >= b)
{
tmp = l * b + u * (x - b);
}
else
{
tmp = l * x;
}
ans = max(ans, sum[cnt] + tmp);
}
return (ans >= 0);
}
int main()
{
cin >> N >> X;
for (auto i = 0; i < N; i++)
{
cin >> b[i] >> l[i] >> u[i];
}
for (auto i = 0; i < N; i++)
{
base -= l[i] * b[i];
}
for (auto i = 0; i < N; i++)
{
ll t = l[i] * b[i] + u[i] * (X - b[i]);
V.emplace_back(t, b[i], l[i], u[i]);
}
sort(V.begin(), V.end());
reverse(V.begin(), V.end());
sum[0] = base;
for (auto i = 0; i < N; i++)
{
sum[i + 1] = sum[i] + get<0>(V[i]);
}
ll ok = N * X + 1;
ll ng = -1;
while (abs(ok - ng) > 1)
{
ll t = (ok + ng) / 2;
if (solve(t))
{
ok = t;
}
else
{
ng = t;
}
}
cout << ok << endl;
}<|endoftext|>
|
<commit_before>/*
* Copyright (C) 2018 ScyllaDB
*/
/*
* This file is part of Scylla.
*
* Scylla is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* Scylla 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 Scylla. If not, see <http://www.gnu.org/licenses/>.
*/
#pragma once
#include "memtable.hh"
#include "row_cache.hh"
#include "dirty_memory_manager.hh"
// makes sure that cache update handles real dirty memory correctly.
class real_dirty_memory_accounter {
dirty_memory_manager& _mgr;
cache_tracker& _tracker;
uint64_t _bytes;
public:
real_dirty_memory_accounter(memtable& m, cache_tracker& tracker);
~real_dirty_memory_accounter();
real_dirty_memory_accounter(real_dirty_memory_accounter&& c);
real_dirty_memory_accounter(const real_dirty_memory_accounter& c) = delete;
void unpin_memory(uint64_t bytes);
};
inline
real_dirty_memory_accounter::real_dirty_memory_accounter(memtable& m, cache_tracker& tracker)
: _mgr(m.get_dirty_memory_manager())
, _tracker(tracker)
, _bytes(m.occupancy().used_space()) {
_mgr.pin_real_dirty_memory(_bytes);
}
inline
real_dirty_memory_accounter::~real_dirty_memory_accounter() {
_mgr.unpin_real_dirty_memory(_bytes);
}
inline
real_dirty_memory_accounter::real_dirty_memory_accounter(real_dirty_memory_accounter&& c)
: _mgr(c._mgr), _tracker(c._tracker), _bytes(c._bytes) {
c._bytes = 0;
}
inline
void real_dirty_memory_accounter::unpin_memory(uint64_t bytes) {
// this should never happen - if it does it is a bug. But we'll try to recover and log
// instead of asserting. Once it happens, though, it can keep happening until the update is
// done. So using metrics is better-suited than printing to the logs
if (bytes > _bytes) {
_tracker.pinned_dirty_memory_overload(bytes - _bytes);
}
auto delta = std::min(bytes, _bytes);
_bytes -= delta;
_mgr.unpin_real_dirty_memory(delta);
}
<commit_msg>cache: real_dirty_memory_accounter: Allow construction without memtable<commit_after>/*
* Copyright (C) 2018 ScyllaDB
*/
/*
* This file is part of Scylla.
*
* Scylla is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* Scylla 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 Scylla. If not, see <http://www.gnu.org/licenses/>.
*/
#pragma once
#include "memtable.hh"
#include "row_cache.hh"
#include "dirty_memory_manager.hh"
// makes sure that cache update handles real dirty memory correctly.
class real_dirty_memory_accounter {
dirty_memory_manager& _mgr;
cache_tracker& _tracker;
uint64_t _bytes;
public:
real_dirty_memory_accounter(dirty_memory_manager& mgr, cache_tracker& tracker, size_t size);
real_dirty_memory_accounter(memtable& m, cache_tracker& tracker);
~real_dirty_memory_accounter();
real_dirty_memory_accounter(real_dirty_memory_accounter&& c);
real_dirty_memory_accounter(const real_dirty_memory_accounter& c) = delete;
void unpin_memory(uint64_t bytes);
};
inline
real_dirty_memory_accounter::real_dirty_memory_accounter(dirty_memory_manager& mgr, cache_tracker& tracker, size_t size)
: _mgr(mgr)
, _tracker(tracker)
, _bytes(size) {
_mgr.pin_real_dirty_memory(_bytes);
}
inline
real_dirty_memory_accounter::real_dirty_memory_accounter(memtable& m, cache_tracker& tracker)
: real_dirty_memory_accounter(m.get_dirty_memory_manager(), tracker, m.occupancy().used_space())
{ }
inline
real_dirty_memory_accounter::~real_dirty_memory_accounter() {
_mgr.unpin_real_dirty_memory(_bytes);
}
inline
real_dirty_memory_accounter::real_dirty_memory_accounter(real_dirty_memory_accounter&& c)
: _mgr(c._mgr), _tracker(c._tracker), _bytes(c._bytes) {
c._bytes = 0;
}
inline
void real_dirty_memory_accounter::unpin_memory(uint64_t bytes) {
// this should never happen - if it does it is a bug. But we'll try to recover and log
// instead of asserting. Once it happens, though, it can keep happening until the update is
// done. So using metrics is better-suited than printing to the logs
if (bytes > _bytes) {
_tracker.pinned_dirty_memory_overload(bytes - _bytes);
}
auto delta = std::min(bytes, _bytes);
_bytes -= delta;
_mgr.unpin_real_dirty_memory(delta);
}
<|endoftext|>
|
<commit_before>// Copyright (c) 2017 Kai Luo <gluokai@gmail.com>. All rights reserved.
#include "logger.h"
#include "testkit.h"
class L {};
TEST(L, DefaultLogger) {
KL_DEBUG("message from %s", "rofl");
KL_DEBUG_L(kl::logging::Logger::DefaultLogger(), "message from %s", "wtf");
auto discard = kl::logging::Logger([](const char *msg) { (void)(msg); });
kl::logging::Logger::SetDefaultLogger(std::move(discard));
KL_DEBUG("message from %s", "imfao");
}
int main() {
kl::test::RunAllTests();
return 0;
}
<commit_msg>minor fix<commit_after>// Copyright (c) 2017 Kai Luo <gluokai@gmail.com>. All rights reserved.
#include "logger.h"
#include "testkit.h"
class L {};
TEST(L, DefaultLogger) {
KL_DEBUG("message from %s", "rofl");
KL_DEBUG_L(kl::logging::Logger::DefaultLogger(), "message from %s", "wtf");
auto discard = kl::logging::Logger([](const char *msg) { (void)(msg); });
KL_DEBUG_L(discard, "message from %s", "imfao");
kl::logging::Logger::SetDefaultLogger(std::move(discard));
KL_DEBUG("message from %s", "imfao");
}
int main() {
kl::test::RunAllTests();
return 0;
}
<|endoftext|>
|
<commit_before>/***************************************************************************
* @file main.cpp
* @author Alan.W
* @date 16 Feb 2014
* @remark This code is for the exercises from C++ Primer 5th Edition
* @note
***************************************************************************/
//!
//! Exercise 16.56:
//! Write and test a variadic version of errorMsg.
//!
//! Exercise 16.57:
//! Compare your variadic version of errorMsg to the error_msg function in
//! § 6.2.6 (p. 220). What are the advantages and disadvantages of each
//! approach?
// The error_msg takes initializer_list as the argument. So only the elements
// stored in it must be the same or at least convertible. In contrast, the variadic
// version provides better flexibility.
//!
#include <iostream>
#include <memory>
#include <sstream>
//! always declare first:
template <typename T> std::string debug_rep(const T& t);
template <typename T> std::string debug_rep(T* p);
std::string debug_rep(const std::string &s);
std::string debug_rep(char* p);
std::string debug_rep(const char *p);
//! print any type we don't otherwise.
template<typename T> std::string debug_rep(const T& t)
{
std::ostringstream ret;
ret << t;
return ret.str();
}
//! print pointers as their pointer value, followed by the object to which the pointer points
template<typename T> std::string debug_rep(T* p)
{
std::ostringstream ret;
ret << "pointer: " << p;
if(p)
ret << " " << debug_rep(*p);
else
ret << " null pointer";
return ret.str();
}
//! non-template version
std::string debug_rep(const std::string &s)
{
return '"' + s + '"';
}
//! convert the character pointers to string and call the string version of debug_rep
std::string debug_rep(char *p)
{
return debug_rep(std::string(p));
}
std::string debug_rep(const char *p)
{
return debug_rep(std::string(p));
}
//! function to end the recursion and print the last element
//! this function must be declared before the variadic version of
//! print is defined
template<typename T>
std::ostream& print(std::ostream& os, const T& t)
{
return os << t;
//! ^
//! note: no seperator after the last element in the pack
}
//! this version of print will be called for all but the last element in the pack
template<typename T, typename... Args>
std::ostream&
print(std::ostream &os, const T &t, const Args&... rest)
{
//! print the first argument
os << t << ",";
//! recursive call; print the other arguments
return print(os,rest...);
}
//! call debug_rep on each argument in the call to print
template<typename... Args>
std::ostream& errorMsg(std::ostream& os, const Args... rest)
{
//! print(os,debug_rep(rest)...);
return print(os,debug_rep(rest)...);
}
int main()
{
errorMsg(std::cout, 1,2,3,4,9.0f,"sss","alan");
}
<commit_msg>Update main.cpp<commit_after>/***************************************************************************
* @file main.cpp
* @author Yue Wang
* @date 16 Feb 2014
* @remark This code is for the exercises from C++ Primer 5th Edition
* @note
***************************************************************************/
//!
//! Exercise 16.56:
//! Write and test a variadic version of errorMsg.
//!
//! Exercise 16.57:
//! Compare your variadic version of errorMsg to the error_msg function in
//! § 6.2.6 (p. 220). What are the advantages and disadvantages of each
//! approach?
// The error_msg takes initializer_list as the argument. So only the elements
// stored in it must be the same or at least convertible. In contrast, the variadic
// version provides better flexibility.
//!
#include <iostream>
#include <memory>
#include <sstream>
//! always declare first:
template <typename T>
std::string debug_rep(const T& t);
template <typename T>
std::string debug_rep(T* p);
std::string debug_rep(const std::string &s);
std::string debug_rep(char* p);
std::string debug_rep(const char *p);
//! print any type we don't otherwise.
template<typename T>
std::string debug_rep(const T& t)
{
std::ostringstream ret;
ret << t;
return ret.str();
}
//! print pointers as their pointer value, followed by the object to which the pointer points
template<typename T>
std::string debug_rep(T* p)
{
std::ostringstream ret;
ret << "pointer: " << p;
if (p)
ret << " " << debug_rep(*p);
else
ret << " null pointer";
return ret.str();
}
//! non-template version
std::string debug_rep(const std::string &s)
{
return '"' + s + '"';
}
//! convert the character pointers to string and call the string version of debug_rep
std::string debug_rep(char *p)
{
return debug_rep(std::string(p));
}
std::string debug_rep(const char *p)
{
return debug_rep(std::string(p));
}
//! function to end the recursion and print the last element
//! this function must be declared before the variadic version of
//! print is defined
template<typename T>
std::ostream& print(std::ostream& os, const T& t)
{
return os << t;
//! ^
//! note: no seperator after the last element in the pack
}
//! this version of print will be called for all but the last element in the pack
template<typename T, typename... Args>
std::ostream& print(std::ostream &os, const T &t, const Args&... rest)
{
//! print the first argument
os << t << ",";
//! recursive call; print the other arguments
return print(os, rest...);
}
//! call debug_rep on each argument in the call to print
template<typename... Args>
std::ostream& errorMsg(std::ostream& os, const Args... rest)
{
//! print(os,debug_rep(rest)...);
return print(os, debug_rep(rest)...);
}
int main()
{
errorMsg(std::cout, 1, 2, 3, 4, 9.0f, "sss", "alan");
return 0;
}
<|endoftext|>
|
<commit_before>/***************************************************************************
* @file main.cpp
* @author Queequeg
* @date 25 Nov 2014
* @remark This code is for the exercises from C++ Primer 5th Edition
* @note
***************************************************************************/
//!
//! Exercise 17.17
//! Update your program so that it finds all the words in an input sequence
//! that violiate the ei grammar rule.
//!
//! Exercise 17.18
//! Revise your program to ignore words that contain ei but are not
//! misspellings, such as albeit and neighbor.
#include <iostream>
using std::cout;
using std::cin;
using std::endl;
#include<string>
using std::string;
#include <regex>
using std::regex;
using std::sregex_iterator;
int main()
{
string s;
cout << "Please input a sequence of words:" << endl;
getline(cin, s);
cout << endl;
cout << "Word(s) that violiate the ei grammar rule:" << endl;
string pattern("[^c]ei");
pattern = "[[:alpha:]]*" + pattern + "[[:alpha:]]*";
regex r(pattern, regex::icase);
for (sregex_iterator it(s.begin(), s.end(), r), end_it;
it != end_it; ++it)
cout << it->str() << endl;
return 0;
}<commit_msg>fix symbols in comment<commit_after>/***************************************************************************
* @file main.cpp
* @author Queequeg
* @date 25 Nov 2014
* @remark This code is for the exercises from C++ Primer 5th Edition
* @note
***************************************************************************/
//!
//! Exercise 17.17
//! Update your program so that it finds all the words in an input sequence
//! that violiate the "ei" grammar rule.
//!
//! Exercise 17.18
//! Revise your program to ignore words that contain "ei" but are not
//! misspellings, such as "albeit" and "neighbor".
#include <iostream>
using std::cout;
using std::cin;
using std::endl;
#include<string>
using std::string;
#include <regex>
using std::regex;
using std::sregex_iterator;
int main()
{
string s;
cout << "Please input a sequence of words:" << endl;
getline(cin, s);
cout << endl;
cout << "Word(s) that violiate the ei grammar rule:" << endl;
string pattern("[^c]ei");
pattern = "[[:alpha:]]*" + pattern + "[[:alpha:]]*";
regex r(pattern, regex::icase);
for (sregex_iterator it(s.begin(), s.end(), r), end_it;
it != end_it; ++it)
cout << it->str() << endl;
return 0;
}<|endoftext|>
|
<commit_before>#include <locale>
#include "test_helpers.hxx"
using namespace pqxx;
// Initial test program for libpqxx. Test functionality that doesn't require a
// running database.
namespace
{
void check(std::string ref, std::string val, std::string vdesc)
{
PQXX_CHECK_EQUAL(val, ref, "String mismatch for " + vdesc);
}
template<typename T> inline void strconv(
std::string type,
const T &Obj,
std::string expected)
{
const std::string Objstr(to_string(Obj));
check(expected, Objstr, type);
T NewObj;
from_string(Objstr, NewObj);
check(expected, to_string(NewObj), "recycled " + type);
}
// There's no from_string<const char *>()...
inline void strconv(std::string type, const char Obj[], std::string expected)
{
const std::string Objstr(to_string(Obj));
check(expected, Objstr, type);
}
const double not_a_number = std::numeric_limits<double>::quiet_NaN();
struct intderef
{
intderef(){} // Silences bogus warning in some gcc versions
template<typename ITER>
int operator()(ITER i) const noexcept { return int(*i); }
};
void test_000()
{
PQXX_CHECK_EQUAL(
oid_none,
0u,
"InvalidIod is not zero as it used to be. This may conceivably "
"cause problems in libpqxx.");
PQXX_CHECK(
cursor_base::prior() < 0 and cursor_base::backward_all() < 0,
"cursor_base::difference_type appears to be unsigned.");
const char weird[] = "foo\t\n\0bar";
const std::string weirdstr(weird, sizeof(weird)-1);
// Test string conversions
strconv("const char[]", "", "");
strconv("const char[]", "foo", "foo");
strconv("int", 0, "0");
strconv("int", 100, "100");
strconv("int", -1, "-1");
#if defined(_MSC_VER)
const long long_min = LONG_MIN, long_max = LONG_MAX;
#else
const long long_min = std::numeric_limits<long>::min(),
long_max = std::numeric_limits<long>::max();
#endif
std::stringstream lminstr, lmaxstr, llminstr, llmaxstr, ullmaxstr;
lminstr.imbue(std::locale("C"));
lmaxstr.imbue(std::locale("C"));
llminstr.imbue(std::locale("C"));
llmaxstr.imbue(std::locale("C"));
ullmaxstr.imbue(std::locale("C"));
lminstr << long_min;
lmaxstr << long_max;
using longlong = long long;
using ulonglong = unsigned long long;
const unsigned long long ullong_max = ~ulonglong(0);
const long long llong_max = longlong(ullong_max >> 2),
llong_min = -1 - llong_max;
llminstr << llong_min;
llmaxstr << llong_max;
ullmaxstr << ullong_max;
strconv("long", 0, "0");
strconv("long", long_min, lminstr.str());
strconv("long", long_max, lmaxstr.str());
strconv("double", not_a_number, "nan");
strconv("string", std::string{}, "");
strconv("string", weirdstr, weirdstr);
strconv("long long", 0LL, "0");
strconv("long long", llong_min, llminstr.str());
strconv("long long", llong_max, llmaxstr.str());
strconv("unsigned long long", 0ULL, "0");
strconv("unsigned long long", ullong_max, ullmaxstr.str());
const char zerobuf[] = "0";
std::string zero;
from_string(zerobuf, zero, sizeof(zerobuf)-1);
PQXX_CHECK_EQUAL(
zero,
zerobuf,
"Converting \"0\" with explicit length failed.");
const char nulbuf[] = "\0string\0with\0nuls\0";
const std::string nully(nulbuf, sizeof(nulbuf)-1);
std::string nully_parsed;
from_string(nulbuf, nully_parsed, sizeof(nulbuf)-1);
PQXX_CHECK_EQUAL(nully_parsed.size(), nully.size(), "Nul truncates string.");
PQXX_CHECK_EQUAL(nully_parsed, nully, "String conversion breaks on nuls.");
from_string(nully.c_str(), nully_parsed, nully.size());
PQXX_CHECK_EQUAL(nully_parsed, nully, "Nul conversion breaks on strings.");
std::stringstream ss;
strconv("empty stringstream", ss, "");
ss << -3.1415;
strconv("stringstream", ss, ss.str());
// TODO: Test binarystring reversibility
const std::string pw = encrypt_password("foo", "bar");
PQXX_CHECK(not pw.empty(), "Encrypting a password returned no data.");
PQXX_CHECK_NOT_EQUAL(
pw,
encrypt_password("splat", "blub"),
"Password encryption is broken.");
PQXX_CHECK(
pw.find("bar") == std::string::npos,
"Encrypted password contains original.");
// Test error handling for failed connections
{
nullconnection nc;
PQXX_CHECK_THROWS(
work w(nc),
broken_connection,
"nullconnection fails to fail.");
}
{
nullconnection nc("");
PQXX_CHECK_THROWS(
work w(nc),
broken_connection,
"nullconnection(const char[]) is broken.");
}
{
std::string n;
nullconnection nc(n);
PQXX_CHECK_THROWS(
work w(nc),
broken_connection,
"nullconnection(const string &) is broken.");
}
// Now that we know nullconnections throw errors as expected, test
// pqxx_exception.
try
{
nullconnection nc;
work w(nc);
}
catch (const pqxx_exception &e)
{
PQXX_CHECK(
dynamic_cast<const broken_connection *>(&e.base()),
"Downcast pqxx_exception is not a broken_connection");
pqxx::test::expected_exception(e.base().what());
PQXX_CHECK_EQUAL(
dynamic_cast<const broken_connection &>(e.base()).what(),
e.base().what(),
"Inconsistent what() message in exception.");
}
}
PQXX_REGISTER_TEST(test_000);
} // namespace
<commit_msg>Bit of test cleanup.<commit_after>#include <locale>
#include "test_helpers.hxx"
using namespace pqxx;
// Initial test program for libpqxx. Test functionality that doesn't require a
// running database.
namespace
{
void check(std::string ref, std::string val, std::string vdesc)
{
PQXX_CHECK_EQUAL(val, ref, "String mismatch for " + vdesc);
}
template<typename T> inline void strconv(
std::string type,
const T &Obj,
std::string expected)
{
const std::string Objstr(to_string(Obj));
check(expected, Objstr, type);
T NewObj;
from_string(Objstr, NewObj);
check(expected, to_string(NewObj), "recycled " + type);
}
// There's no from_string<const char *>()...
inline void strconv(std::string type, const char Obj[], std::string expected)
{
const std::string Objstr(to_string(Obj));
check(expected, Objstr, type);
}
const double not_a_number = std::numeric_limits<double>::quiet_NaN();
struct intderef
{
intderef(){} // Silences bogus warning in some gcc versions
template<typename ITER>
int operator()(ITER i) const noexcept { return int(*i); }
};
void test_000()
{
PQXX_CHECK_EQUAL(
oid_none,
0u,
"InvalidIod is not zero as it used to be. This may conceivably "
"cause problems in libpqxx.");
PQXX_CHECK(
cursor_base::prior() < 0 and cursor_base::backward_all() < 0,
"cursor_base::difference_type appears to be unsigned.");
const char weird[] = "foo\t\n\0bar";
const std::string weirdstr(weird, sizeof(weird)-1);
// Test string conversions
strconv("const char[]", "", "");
strconv("const char[]", "foo", "foo");
strconv("int", 0, "0");
strconv("int", 100, "100");
strconv("int", -1, "-1");
#if defined(_MSC_VER)
const long long_min = LONG_MIN, long_max = LONG_MAX;
#else
const long long_min = std::numeric_limits<long>::min(),
long_max = std::numeric_limits<long>::max();
#endif
std::stringstream lminstr, lmaxstr, llminstr, llmaxstr, ullmaxstr;
lminstr.imbue(std::locale("C"));
lmaxstr.imbue(std::locale("C"));
llminstr.imbue(std::locale("C"));
llmaxstr.imbue(std::locale("C"));
ullmaxstr.imbue(std::locale("C"));
lminstr << long_min;
lmaxstr << long_max;
const auto ullong_max = std::numeric_limits<unsigned long long>::max();
const auto
llong_max = std::numeric_limits<long long>::max(),
llong_min = std::numeric_limits<long long>::min();
llminstr << llong_min;
llmaxstr << llong_max;
ullmaxstr << ullong_max;
strconv("long", 0, "0");
strconv("long", long_min, lminstr.str());
strconv("long", long_max, lmaxstr.str());
strconv("double", not_a_number, "nan");
strconv("string", std::string{}, "");
strconv("string", weirdstr, weirdstr);
strconv("long long", 0LL, "0");
strconv("long long", llong_min, llminstr.str());
strconv("long long", llong_max, llmaxstr.str());
strconv("unsigned long long", 0ULL, "0");
strconv("unsigned long long", ullong_max, ullmaxstr.str());
const char zerobuf[] = "0";
std::string zero;
from_string(zerobuf, zero, sizeof(zerobuf)-1);
PQXX_CHECK_EQUAL(
zero,
zerobuf,
"Converting \"0\" with explicit length failed.");
const char nulbuf[] = "\0string\0with\0nuls\0";
const std::string nully(nulbuf, sizeof(nulbuf)-1);
std::string nully_parsed;
from_string(nulbuf, nully_parsed, sizeof(nulbuf)-1);
PQXX_CHECK_EQUAL(nully_parsed.size(), nully.size(), "Nul truncates string.");
PQXX_CHECK_EQUAL(nully_parsed, nully, "String conversion breaks on nuls.");
from_string(nully.c_str(), nully_parsed, nully.size());
PQXX_CHECK_EQUAL(nully_parsed, nully, "Nul conversion breaks on strings.");
std::stringstream ss;
strconv("empty stringstream", ss, "");
ss << -3.1415;
strconv("stringstream", ss, ss.str());
// TODO: Test binarystring reversibility
const std::string pw = encrypt_password("foo", "bar");
PQXX_CHECK(not pw.empty(), "Encrypting a password returned no data.");
PQXX_CHECK_NOT_EQUAL(
pw,
encrypt_password("splat", "blub"),
"Password encryption is broken.");
PQXX_CHECK(
pw.find("bar") == std::string::npos,
"Encrypted password contains original.");
// Test error handling for failed connections
{
nullconnection nc;
PQXX_CHECK_THROWS(
work w(nc),
broken_connection,
"nullconnection fails to fail.");
}
{
nullconnection nc("");
PQXX_CHECK_THROWS(
work w(nc),
broken_connection,
"nullconnection(const char[]) is broken.");
}
{
std::string n;
nullconnection nc(n);
PQXX_CHECK_THROWS(
work w(nc),
broken_connection,
"nullconnection(const string &) is broken.");
}
// Now that we know nullconnections throw errors as expected, test
// pqxx_exception.
try
{
nullconnection nc;
work w(nc);
}
catch (const pqxx_exception &e)
{
PQXX_CHECK(
dynamic_cast<const broken_connection *>(&e.base()),
"Downcast pqxx_exception is not a broken_connection");
pqxx::test::expected_exception(e.base().what());
PQXX_CHECK_EQUAL(
dynamic_cast<const broken_connection &>(e.base()).what(),
e.base().what(),
"Inconsistent what() message in exception.");
}
}
PQXX_REGISTER_TEST(test_000);
} // namespace
<|endoftext|>
|
<commit_before>// Time: O(nlogn)
// Space: O(1)
class Solution {
public:
bool isReflected(vector<pair<int, int>>& points) {
if (points.empty()) {
return true;
}
sort(points.begin(), points.end());
sort(points.begin(), points.begin() + distance(points.begin(), points.end()) / 2,
[](const pair<int, int>& a, const pair<int, int>& b) {
if (a.first == b.first) {
return a.second > b.second;
}
return a.first < b.first;
});
const auto mid = points.front().first + (points.back().first - points.front().first) / 2.0;
for (int left = 0, right = points.size() - 1; left <= right; ++left, --right) {
if ((mid != points[left].first + (points[right].first - points[left].first) / 2.0) ||
(points[left].first != points[right].first &&
points[left].second != points[right].second)) {
return false;
}
}
return true;
}
};
<commit_msg>Update line-reflection.cpp<commit_after>// Time: O(nlogn)
// Space: O(1)
class Solution {
public:
bool isReflected(vector<pair<int, int>>& points) {
if (points.empty()) {
return true;
}
sort(points.begin(), points.end());
sort(points.begin(), points.begin() + distance(points.begin(), points.end()) / 2,
[](const pair<int, int>& a, const pair<int, int>& b) {
if (a.first == b.first) {
return a.second > b.second;
}
return a.first < b.first;
});
const auto mid = points.front().first + points.back().first;
for (int left = 0, right = points.size() - 1; left <= right; ++left, --right) {
if ((mid != points[left].first + points[right].first) ||
(points[left].first != points[right].first &&
points[left].second != points[right].second)) {
return false;
}
}
return true;
}
};
<|endoftext|>
|
<commit_before>/* Copyright (C) 2003 MySQL AB
This program is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 2 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program; if not, write to the Free Software
Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA */
#include <ndb_global.h>
#include <File.hpp>
#include <NdbOut.hpp>
#include <my_dir.h>
//
// PUBLIC
//
time_t
File_class::mtime(const char* aFileName)
{
MY_STAT stmp;
time_t rc = 0;
if (my_stat(aFileName, &stmp, MYF(0)) != NULL) {
rc = stmp.st_mtime;
}
return rc;
}
bool
File_class::exists(const char* aFileName)
{
MY_STAT stmp;
return (my_stat(aFileName, &stmp, MYF(0))!=NULL);
}
off_t
File_class::size(FILE* f)
{
MY_STAT s;
// Note that my_fstat behaves *differently* than my_stat. ARGGGHH!
if(my_fstat(::fileno(f), &s, MYF(0)))
return 0;
return s.st_size;
}
bool
File_class::rename(const char* currFileName, const char* newFileName)
{
return ::rename(currFileName, newFileName) == 0 ? true : false;
}
bool
File_class::remove(const char* aFileName)
{
return ::remove(aFileName) == 0 ? true : false;
}
File_class::File_class() :
m_file(NULL),
m_fileMode("r")
{
}
File_class::File_class(const char* aFileName, const char* mode) :
m_file(NULL),
m_fileMode(mode)
{
BaseString::snprintf(m_fileName, PATH_MAX, aFileName);
}
bool
File_class::open()
{
return open(m_fileName, m_fileMode);
}
bool
File_class::open(const char* aFileName, const char* mode)
{
if(m_fileName != aFileName){
/**
* Only copy if it's not the same string
*/
BaseString::snprintf(m_fileName, PATH_MAX, aFileName);
}
m_fileMode = mode;
bool rc = true;
if ((m_file = ::fopen(m_fileName, m_fileMode))== NULL)
{
rc = false;
}
return rc;
}
File_class::~File_class()
{
close();
}
bool
File_class::remove()
{
// Close the file first!
close();
return File_class::remove(m_fileName);
}
bool
File_class::close()
{
bool rc = true;
int retval = 0;
if (m_file != NULL)
{
::fflush(m_file);
retval = ::fclose(m_file);
while ( (retval != 0) && (errno == EINTR) ){
retval = ::fclose(m_file);
}
if( retval == 0){
rc = true;
}
else {
rc = false;
ndbout_c("ERROR: Close file error in File.cpp for %s",strerror(errno));
}
}
m_file = NULL;
return rc;
}
int
File_class::read(void* buf, size_t itemSize, size_t nitems) const
{
return ::fread(buf, itemSize, nitems, m_file);
}
int
File_class::readChar(char* buf, long start, long length) const
{
return ::fread((void*)&buf[start], 1, length, m_file);
}
int
File_class::readChar(char* buf)
{
return readChar(buf, 0, strlen(buf));
}
int
File_class::write(const void* buf, size_t size, size_t nitems)
{
return ::fwrite(buf, size, nitems, m_file);
}
int
File_class::writeChar(const char* buf, long start, long length)
{
return ::fwrite((const void*)&buf[start], sizeof(char), length, m_file);
}
int
File_class::writeChar(const char* buf)
{
return writeChar(buf, 0, ::strlen(buf));
}
off_t
File_class::size() const
{
return File_class::size(m_file);
}
const char*
File_class::getName() const
{
return m_fileName;
}
int
File_class::flush() const
{
return ::fflush(m_file);;
}
<commit_msg>Change ::fileno() to fileno() in ndb/common/util/File.cpp.<commit_after>/* Copyright (C) 2003 MySQL AB
This program is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 2 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program; if not, write to the Free Software
Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA */
#include <ndb_global.h>
#include <File.hpp>
#include <NdbOut.hpp>
#include <my_dir.h>
//
// PUBLIC
//
time_t
File_class::mtime(const char* aFileName)
{
MY_STAT stmp;
time_t rc = 0;
if (my_stat(aFileName, &stmp, MYF(0)) != NULL) {
rc = stmp.st_mtime;
}
return rc;
}
bool
File_class::exists(const char* aFileName)
{
MY_STAT stmp;
return (my_stat(aFileName, &stmp, MYF(0))!=NULL);
}
off_t
File_class::size(FILE* f)
{
MY_STAT s;
// Note that my_fstat behaves *differently* than my_stat. ARGGGHH!
if (my_fstat(fileno(f), &s, MYF(0)))
return 0;
return s.st_size;
}
bool
File_class::rename(const char* currFileName, const char* newFileName)
{
return ::rename(currFileName, newFileName) == 0 ? true : false;
}
bool
File_class::remove(const char* aFileName)
{
return ::remove(aFileName) == 0 ? true : false;
}
File_class::File_class() :
m_file(NULL),
m_fileMode("r")
{
}
File_class::File_class(const char* aFileName, const char* mode) :
m_file(NULL),
m_fileMode(mode)
{
BaseString::snprintf(m_fileName, PATH_MAX, aFileName);
}
bool
File_class::open()
{
return open(m_fileName, m_fileMode);
}
bool
File_class::open(const char* aFileName, const char* mode)
{
if(m_fileName != aFileName){
/**
* Only copy if it's not the same string
*/
BaseString::snprintf(m_fileName, PATH_MAX, aFileName);
}
m_fileMode = mode;
bool rc = true;
if ((m_file = ::fopen(m_fileName, m_fileMode))== NULL)
{
rc = false;
}
return rc;
}
File_class::~File_class()
{
close();
}
bool
File_class::remove()
{
// Close the file first!
close();
return File_class::remove(m_fileName);
}
bool
File_class::close()
{
bool rc = true;
int retval = 0;
if (m_file != NULL)
{
::fflush(m_file);
retval = ::fclose(m_file);
while ( (retval != 0) && (errno == EINTR) ){
retval = ::fclose(m_file);
}
if( retval == 0){
rc = true;
}
else {
rc = false;
ndbout_c("ERROR: Close file error in File.cpp for %s",strerror(errno));
}
}
m_file = NULL;
return rc;
}
int
File_class::read(void* buf, size_t itemSize, size_t nitems) const
{
return ::fread(buf, itemSize, nitems, m_file);
}
int
File_class::readChar(char* buf, long start, long length) const
{
return ::fread((void*)&buf[start], 1, length, m_file);
}
int
File_class::readChar(char* buf)
{
return readChar(buf, 0, strlen(buf));
}
int
File_class::write(const void* buf, size_t size, size_t nitems)
{
return ::fwrite(buf, size, nitems, m_file);
}
int
File_class::writeChar(const char* buf, long start, long length)
{
return ::fwrite((const void*)&buf[start], sizeof(char), length, m_file);
}
int
File_class::writeChar(const char* buf)
{
return writeChar(buf, 0, ::strlen(buf));
}
off_t
File_class::size() const
{
return File_class::size(m_file);
}
const char*
File_class::getName() const
{
return m_fileName;
}
int
File_class::flush() const
{
return ::fflush(m_file);;
}
<|endoftext|>
|
<commit_before><commit_msg>coverity#704836 Dereference after null check<commit_after><|endoftext|>
|
<commit_before>#define CDM_CONFIGURE_NAMESPACE a0038898
#include "../../cdm/application/using_many_libs/cdm.hpp"
#include "log.hpp"
#include "temporary.hpp"
#include <boost/test/unit_test.hpp>
#include <silicium/sink/ostream_sink.hpp>
#include <ventura/file_operations.hpp>
#include <cdm/locate_cache.hpp>
#if !defined(_MSC_VER) || (_MSC_VER != 1900)
// websocketpp does not compille on VS 2015 yet
namespace
{
ventura::absolute_path const this_file = *ventura::absolute_path::create(__FILE__);
ventura::absolute_path const test = *ventura::parent(this_file);
ventura::absolute_path const repository = *ventura::parent(test);
}
BOOST_AUTO_TEST_CASE(test_using_many_libs)
{
cdm::travis_keep_alive_printer keep_travis_alive;
ventura::absolute_path const app_source = repository / "application/using_many_libs";
ventura::absolute_path const tmp = cdm::get_temporary_root_for_testing() / "cdm_b";
ventura::recreate_directories(tmp, Si::throw_);
ventura::absolute_path const module_temporaries = tmp / "build";
ventura::create_directories(module_temporaries, Si::throw_);
ventura::absolute_path const application_build_dir = tmp / "using_many_libs";
ventura::create_directories(application_build_dir, Si::throw_);
std::unique_ptr<std::ofstream> log_file = cdm::open_log(application_build_dir / "test_using_many_libs.txt");
auto output = cdm::make_program_output_printer(Si::ostream_ref_sink(*log_file));
unsigned const cpu_parallelism =
#if CDM_TESTS_RUNNING_ON_TRAVIS_CI
2;
#else
boost::thread::hardware_concurrency();
#endif
CDM_CONFIGURE_NAMESPACE::configure(
module_temporaries, cdm::locate_cache_for_this_binary(), app_source, application_build_dir, cpu_parallelism,
cdm::detect_this_binary_operating_system(CDM_TESTS_RUNNING_ON_TRAVIS_CI, CDM_TESTS_RUNNING_ON_APPVEYOR),
cdm::approximate_configuration_of_this_binary(), output);
{
std::vector<Si::os_string> arguments;
arguments.emplace_back(SILICIUM_OS_STR("--build"));
arguments.emplace_back(SILICIUM_OS_STR("."));
auto console_output = Si::Sink<char, Si::success>::erase(Si::ostream_ref_sink(std::cerr));
BOOST_REQUIRE_EQUAL(0,
ventura::run_process(ventura::cmake_exe, arguments, application_build_dir, console_output,
std::vector<std::pair<Si::os_char const *, Si::os_char const *>>(),
ventura::environment_inheritance::inherit));
}
{
std::vector<Si::os_string> arguments;
ventura::relative_path const relative(
#ifdef _MSC_VER
"Debug/"
#endif
"using_many_libs"
#ifdef _MSC_VER
".exe"
#endif
);
BOOST_REQUIRE_EQUAL(0, ventura::run_process(application_build_dir / relative, arguments, application_build_dir,
output,
std::vector<std::pair<Si::os_char const *, Si::os_char const *>>(),
ventura::environment_inheritance::inherit));
}
}
#endif
<commit_msg>ignore websocketpp issue on GCC 4.6<commit_after>#define CDM_CONFIGURE_NAMESPACE a0038898
#include "../../cdm/application/using_many_libs/cdm.hpp"
#include "log.hpp"
#include "temporary.hpp"
#include <boost/test/unit_test.hpp>
#include <silicium/sink/ostream_sink.hpp>
#include <ventura/file_operations.hpp>
#include <cdm/locate_cache.hpp>
#if (!defined(_MSC_VER) || (_MSC_VER != 1900)) && !SILICIUM_GCC46
// websocketpp does not compille on VS 2015 yet.
// GCC 4.6 is excluded because Catch requires C++11 for GCC 5 while websocketpp does not
// compile with C++11 on GCC 4.6. Ignoring the ancient compiler is the best option here.
namespace
{
ventura::absolute_path const this_file = *ventura::absolute_path::create(__FILE__);
ventura::absolute_path const test = *ventura::parent(this_file);
ventura::absolute_path const repository = *ventura::parent(test);
}
BOOST_AUTO_TEST_CASE(test_using_many_libs)
{
cdm::travis_keep_alive_printer keep_travis_alive;
ventura::absolute_path const app_source = repository / "application/using_many_libs";
ventura::absolute_path const tmp = cdm::get_temporary_root_for_testing() / "cdm_b";
ventura::recreate_directories(tmp, Si::throw_);
ventura::absolute_path const module_temporaries = tmp / "build";
ventura::create_directories(module_temporaries, Si::throw_);
ventura::absolute_path const application_build_dir = tmp / "using_many_libs";
ventura::create_directories(application_build_dir, Si::throw_);
std::unique_ptr<std::ofstream> log_file = cdm::open_log(application_build_dir / "test_using_many_libs.txt");
auto output = cdm::make_program_output_printer(Si::ostream_ref_sink(*log_file));
unsigned const cpu_parallelism =
#if CDM_TESTS_RUNNING_ON_TRAVIS_CI
2;
#else
boost::thread::hardware_concurrency();
#endif
CDM_CONFIGURE_NAMESPACE::configure(
module_temporaries, cdm::locate_cache_for_this_binary(), app_source, application_build_dir, cpu_parallelism,
cdm::detect_this_binary_operating_system(CDM_TESTS_RUNNING_ON_TRAVIS_CI, CDM_TESTS_RUNNING_ON_APPVEYOR),
cdm::approximate_configuration_of_this_binary(), output);
{
std::vector<Si::os_string> arguments;
arguments.emplace_back(SILICIUM_OS_STR("--build"));
arguments.emplace_back(SILICIUM_OS_STR("."));
auto console_output = Si::Sink<char, Si::success>::erase(Si::ostream_ref_sink(std::cerr));
BOOST_REQUIRE_EQUAL(0,
ventura::run_process(ventura::cmake_exe, arguments, application_build_dir, console_output,
std::vector<std::pair<Si::os_char const *, Si::os_char const *>>(),
ventura::environment_inheritance::inherit));
}
{
std::vector<Si::os_string> arguments;
ventura::relative_path const relative(
#ifdef _MSC_VER
"Debug/"
#endif
"using_many_libs"
#ifdef _MSC_VER
".exe"
#endif
);
BOOST_REQUIRE_EQUAL(0, ventura::run_process(application_build_dir / relative, arguments, application_build_dir,
output,
std::vector<std::pair<Si::os_char const *, Si::os_char const *>>(),
ventura::environment_inheritance::inherit));
}
}
#endif
<|endoftext|>
|
<commit_before>/* Copyright 2013-present Barefoot Networks, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
/*
* Antonin Bas (antonin@barefootnetworks.com)
*
*/
#include <bm/bm_sim/actions.h>
#include <bm/bm_sim/calculations.h>
#include <bm/bm_sim/core/primitives.h>
#include <bm/bm_sim/counters.h>
#include <bm/bm_sim/meters.h>
#include <bm/bm_sim/packet.h>
#include <bm/bm_sim/phv.h>
#include <bm/bm_sim/logger.h>
#include <random>
#include <thread>
template <typename... Args>
using ActionPrimitive = bm::ActionPrimitive<Args...>;
using bm::Data;
using bm::Field;
using bm::Header;
using bm::MeterArray;
using bm::CounterArray;
using bm::RegisterArray;
using bm::NamedCalculation;
using bm::HeaderStack;
class modify_field : public ActionPrimitive<Data &, const Data &> {
void operator ()(Data &dst, const Data &src) {
bm::core::assign()(dst, src);
}
};
REGISTER_PRIMITIVE(modify_field);
class modify_field_rng_uniform
: public ActionPrimitive<Data &, const Data &, const Data &> {
void operator ()(Data &f, const Data &b, const Data &e) {
// TODO(antonin): a little hacky, fix later if there is a need using GMP
// random fns
using engine = std::default_random_engine;
using hash = std::hash<std::thread::id>;
static thread_local engine generator(hash()(std::this_thread::get_id()));
using distrib64 = std::uniform_int_distribution<uint64_t>;
distrib64 distribution(b.get_uint64(), e.get_uint64());
f.set(distribution(generator));
}
};
REGISTER_PRIMITIVE(modify_field_rng_uniform);
class add_to_field : public ActionPrimitive<Field &, const Data &> {
void operator ()(Field &f, const Data &d) {
f.add(f, d);
}
};
REGISTER_PRIMITIVE(add_to_field);
class subtract_from_field : public ActionPrimitive<Field &, const Data &> {
void operator ()(Field &f, const Data &d) {
f.sub(f, d);
}
};
REGISTER_PRIMITIVE(subtract_from_field);
class add : public ActionPrimitive<Data &, const Data &, const Data &> {
void operator ()(Data &f, const Data &d1, const Data &d2) {
f.add(d1, d2);
}
};
REGISTER_PRIMITIVE(add);
class subtract : public ActionPrimitive<Data &, const Data &, const Data &> {
void operator ()(Data &f, const Data &d1, const Data &d2) {
f.sub(d1, d2);
}
};
REGISTER_PRIMITIVE(subtract);
class bit_xor : public ActionPrimitive<Data &, const Data &, const Data &> {
void operator ()(Data &f, const Data &d1, const Data &d2) {
f.bit_xor(d1, d2);
}
};
REGISTER_PRIMITIVE(bit_xor);
class bit_or : public ActionPrimitive<Data &, const Data &, const Data &> {
void operator ()(Data &f, const Data &d1, const Data &d2) {
f.bit_or(d1, d2);
}
};
REGISTER_PRIMITIVE(bit_or);
class bit_and : public ActionPrimitive<Data &, const Data &, const Data &> {
void operator ()(Data &f, const Data &d1, const Data &d2) {
f.bit_and(d1, d2);
}
};
REGISTER_PRIMITIVE(bit_and);
class shift_left :
public ActionPrimitive<Data &, const Data &, const Data &> {
void operator ()(Data &f, const Data &d1, const Data &d2) {
f.shift_left(d1, d2);
}
};
REGISTER_PRIMITIVE(shift_left);
class shift_right :
public ActionPrimitive<Data &, const Data &, const Data &> {
void operator ()(Data &f, const Data &d1, const Data &d2) {
f.shift_right(d1, d2);
}
};
REGISTER_PRIMITIVE(shift_right);
class drop : public ActionPrimitive<> {
void operator ()() {
get_field("standard_metadata.egress_spec").set(511);
if (get_phv().has_field("intrinsic_metadata.mcast_grp")) {
get_field("intrinsic_metadata.mcast_grp").set(0);
}
}
};
REGISTER_PRIMITIVE(drop);
class exit_ : public ActionPrimitive<> {
void operator ()() {
get_packet().mark_for_exit();
}
};
REGISTER_PRIMITIVE_W_NAME("exit", exit_);
class generate_digest : public ActionPrimitive<const Data &, const Data &> {
void operator ()(const Data &receiver, const Data &learn_id) {
// discared receiver for now
(void) receiver;
get_field("intrinsic_metadata.lf_field_list").set(learn_id);
}
};
REGISTER_PRIMITIVE(generate_digest);
class add_header : public ActionPrimitive<Header &> {
void operator ()(Header &hdr) {
// TODO(antonin): reset header to 0?
if (!hdr.is_valid()) {
hdr.reset();
hdr.mark_valid();
// updated the length packet register (register 0)
auto &packet = get_packet();
packet.set_register(0, packet.get_register(0) + hdr.get_nbytes_packet());
}
}
};
REGISTER_PRIMITIVE(add_header);
class add_header_fast : public ActionPrimitive<Header &> {
void operator ()(Header &hdr) {
hdr.mark_valid();
}
};
REGISTER_PRIMITIVE(add_header_fast);
class remove_header : public ActionPrimitive<Header &> {
void operator ()(Header &hdr) {
if (hdr.is_valid()) {
// updated the length packet register (register 0)
auto &packet = get_packet();
packet.set_register(0, packet.get_register(0) - hdr.get_nbytes_packet());
hdr.mark_invalid();
}
}
};
REGISTER_PRIMITIVE(remove_header);
class copy_header : public ActionPrimitive<Header &, const Header &> {
void operator ()(Header &dst, const Header &src) {
bm::core::assign_header()(dst, src);
}
};
REGISTER_PRIMITIVE(copy_header);
/* standard_metadata.clone_spec will contain the mirror id (16 LSB) and the
field list id to copy (16 MSB) */
class clone_ingress_pkt_to_egress
: public ActionPrimitive<const Data &, const Data &> {
void operator ()(const Data &clone_spec, const Data &field_list_id) {
Field &f_clone_spec = get_field("standard_metadata.clone_spec");
f_clone_spec.shift_left(field_list_id, 16);
f_clone_spec.add(f_clone_spec, clone_spec);
}
};
REGISTER_PRIMITIVE(clone_ingress_pkt_to_egress);
class clone_egress_pkt_to_egress
: public ActionPrimitive<const Data &, const Data &> {
void operator ()(const Data &clone_spec, const Data &field_list_id) {
Field &f_clone_spec = get_field("standard_metadata.clone_spec");
f_clone_spec.shift_left(field_list_id, 16);
f_clone_spec.add(f_clone_spec, clone_spec);
}
};
REGISTER_PRIMITIVE(clone_egress_pkt_to_egress);
class resubmit : public ActionPrimitive<const Data &> {
void operator ()(const Data &field_list_id) {
if (get_phv().has_field("intrinsic_metadata.resubmit_flag")) {
get_phv().get_field("intrinsic_metadata.resubmit_flag")
.set(field_list_id);
}
}
};
REGISTER_PRIMITIVE(resubmit);
class recirculate : public ActionPrimitive<const Data &> {
void operator ()(const Data &field_list_id) {
if (get_phv().has_field("intrinsic_metadata.recirculate_flag")) {
get_phv().get_field("intrinsic_metadata.recirculate_flag")
.set(field_list_id);
}
}
};
REGISTER_PRIMITIVE(recirculate);
class modify_field_with_hash_based_offset
: public ActionPrimitive<Data &, const Data &,
const NamedCalculation &, const Data &> {
void operator ()(Data &dst, const Data &base,
const NamedCalculation &hash, const Data &size) {
uint64_t v =
(hash.output(get_packet()) % size.get<uint64_t>()) + base.get<uint64_t>();
dst.set(v);
}
};
REGISTER_PRIMITIVE(modify_field_with_hash_based_offset);
class no_op : public ActionPrimitive<> {
void operator ()() {
// nothing
}
};
REGISTER_PRIMITIVE(no_op);
class execute_meter
: public ActionPrimitive<MeterArray &, const Data &, Field &> {
void operator ()(MeterArray &meter_array, const Data &idx, Field &dst) {
auto i = idx.get_uint();
#ifndef NDEBUG
if (i >= meter_array.size()) {
BMLOG_ERROR_PKT(get_packet(),
"Attempted to update meter '{}' with size {}"
" at out-of-bounds index {}."
" No meters were updated, and neither was"
" dest field.",
meter_array.get_name(), meter_array.size(), i);
return;
}
#endif // NDEBUG
auto color = meter_array.execute_meter(get_packet(), i);
dst.set(color);
BMLOG_TRACE_PKT(get_packet(),
"Updated meter '{}' at index {},"
" assigning dest field the color result {}",
meter_array.get_name(), i, color);
}
};
REGISTER_PRIMITIVE(execute_meter);
class count : public ActionPrimitive<CounterArray &, const Data &> {
void operator ()(CounterArray &counter_array, const Data &idx) {
auto i = idx.get_uint();
#ifndef NDEBUG
if (i >= counter_array.size()) {
BMLOG_ERROR_PKT(get_packet(),
"Attempted to update counter '{}' with size {}"
" at out-of-bounds index {}."
" No counters were updated.",
counter_array.get_name(), counter_array.size(), i);
return;
}
#endif // NDEBUG
counter_array.get_counter(i).increment_counter(get_packet());
BMLOG_TRACE_PKT(get_packet(),
"Updated counter '{}' at index {}",
counter_array.get_name(), i);
}
};
REGISTER_PRIMITIVE(count);
class register_read
: public ActionPrimitive<Field &, const RegisterArray &, const Data &> {
void operator ()(Field &dst, const RegisterArray &src, const Data &idx) {
auto i = idx.get_uint();
#ifndef NDEBUG
if (i >= src.size()) {
BMLOG_ERROR_PKT(get_packet(),
"Attempted to read register '{}' with size {}"
" at out-of-bounds index {}."
" Dest field was not updated.",
src.get_name(), src.size(), i);
return;
}
#endif // NDEBUG
dst.set(src[i]);
BMLOG_TRACE_PKT(get_packet(),
"Read register '{}' at index {} read value {}",
src.get_name(), i, src[i]);
}
};
REGISTER_PRIMITIVE(register_read);
class register_write
: public ActionPrimitive<RegisterArray &, const Data &, const Data &> {
void operator ()(RegisterArray &dst, const Data &idx, const Data &src) {
auto i = idx.get_uint();
#ifndef NDEBUG
if (i >= dst.size()) {
BMLOG_ERROR_PKT(get_packet(),
"Attempted to write register '{}' with size {}"
" at out-of-bounds index {}."
" No register array elements were updated.",
dst.get_name(), dst.size(), i);
return;
}
#endif // NDEBUG
dst[i].set(src);
BMLOG_TRACE_PKT(get_packet(),
"Wrote register '{}' at index {} with value {}",
dst.get_name(), i, dst[i]);
}
};
REGISTER_PRIMITIVE(register_write);
// I cannot name this "truncate" and register it with the usual
// REGISTER_PRIMITIVE macro, because of a name conflict:
//
// In file included from /usr/include/boost/config/stdlib/libstdcpp3.hpp:77:0,
// from /usr/include/boost/config.hpp:44,
// from /usr/include/boost/cstdint.hpp:36,
// from /usr/include/boost/multiprecision/number.hpp:9,
// from /usr/include/boost/multiprecision/gmp.hpp:9,
// from ../../src/bm_sim/include/bm_sim/bignum.h:25,
// from ../../src/bm_sim/include/bm_sim/data.h:32,
// from ../../src/bm_sim/include/bm_sim/fields.h:28,
// from ../../src/bm_sim/include/bm_sim/phv.h:34,
// from ../../src/bm_sim/include/bm_sim/actions.h:34,
// from primitives.cpp:21:
// /usr/include/unistd.h:993:12: note: declared here
// extern int truncate (const char *__file, __off_t __length)
class truncate_ : public ActionPrimitive<const Data &> {
void operator ()(const Data &truncated_length) {
get_packet().truncate(truncated_length.get<size_t>());
}
};
REGISTER_PRIMITIVE_W_NAME("truncate", truncate_);
// dummy function, which ensures that this unit is not discarded by the linker
// it is being called by the constructor of SimpleSwitch
// the previous alternative was to have all the primitives in a header file (the
// primitives could also be placed in simple_switch.cpp directly), but I need
// this dummy function if I want to keep the primitives in their own file
int import_primitives() {
return 0;
}
<commit_msg>Avoid crash on hash with max=0, and warn if lo > hi for random (#745)<commit_after>/* Copyright 2013-present Barefoot Networks, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
/*
* Antonin Bas (antonin@barefootnetworks.com)
*
*/
#include <bm/bm_sim/actions.h>
#include <bm/bm_sim/calculations.h>
#include <bm/bm_sim/core/primitives.h>
#include <bm/bm_sim/counters.h>
#include <bm/bm_sim/meters.h>
#include <bm/bm_sim/packet.h>
#include <bm/bm_sim/phv.h>
#include <bm/bm_sim/logger.h>
#include <random>
#include <thread>
template <typename... Args>
using ActionPrimitive = bm::ActionPrimitive<Args...>;
using bm::Data;
using bm::Field;
using bm::Header;
using bm::MeterArray;
using bm::CounterArray;
using bm::RegisterArray;
using bm::NamedCalculation;
using bm::HeaderStack;
using bm::Logger;
class modify_field : public ActionPrimitive<Data &, const Data &> {
void operator ()(Data &dst, const Data &src) {
bm::core::assign()(dst, src);
}
};
REGISTER_PRIMITIVE(modify_field);
class modify_field_rng_uniform
: public ActionPrimitive<Data &, const Data &, const Data &> {
void operator ()(Data &f, const Data &b, const Data &e) {
// TODO(antonin): a little hacky, fix later if there is a need using GMP
// random fns
using engine = std::default_random_engine;
using hash = std::hash<std::thread::id>;
static thread_local engine generator(hash()(std::this_thread::get_id()));
using distrib64 = std::uniform_int_distribution<uint64_t>;
auto lo = b.get_uint64();
auto hi = e.get_uint64();
if (lo > hi) {
Logger::get()->warn("random result is not specified when lo > hi");
// Return without writing to the result field at all. We
// should avoid the distrib64 call below, since its behavior
// is not defined in this case.
return;
}
distrib64 distribution(lo, hi);
auto rand_val = distribution(generator);
BMLOG_TRACE_PKT(get_packet(),
"random(lo={}, hi={}) = {}",
lo, hi, rand_val);
f.set(rand_val);
}
};
REGISTER_PRIMITIVE(modify_field_rng_uniform);
class add_to_field : public ActionPrimitive<Field &, const Data &> {
void operator ()(Field &f, const Data &d) {
f.add(f, d);
}
};
REGISTER_PRIMITIVE(add_to_field);
class subtract_from_field : public ActionPrimitive<Field &, const Data &> {
void operator ()(Field &f, const Data &d) {
f.sub(f, d);
}
};
REGISTER_PRIMITIVE(subtract_from_field);
class add : public ActionPrimitive<Data &, const Data &, const Data &> {
void operator ()(Data &f, const Data &d1, const Data &d2) {
f.add(d1, d2);
}
};
REGISTER_PRIMITIVE(add);
class subtract : public ActionPrimitive<Data &, const Data &, const Data &> {
void operator ()(Data &f, const Data &d1, const Data &d2) {
f.sub(d1, d2);
}
};
REGISTER_PRIMITIVE(subtract);
class bit_xor : public ActionPrimitive<Data &, const Data &, const Data &> {
void operator ()(Data &f, const Data &d1, const Data &d2) {
f.bit_xor(d1, d2);
}
};
REGISTER_PRIMITIVE(bit_xor);
class bit_or : public ActionPrimitive<Data &, const Data &, const Data &> {
void operator ()(Data &f, const Data &d1, const Data &d2) {
f.bit_or(d1, d2);
}
};
REGISTER_PRIMITIVE(bit_or);
class bit_and : public ActionPrimitive<Data &, const Data &, const Data &> {
void operator ()(Data &f, const Data &d1, const Data &d2) {
f.bit_and(d1, d2);
}
};
REGISTER_PRIMITIVE(bit_and);
class shift_left :
public ActionPrimitive<Data &, const Data &, const Data &> {
void operator ()(Data &f, const Data &d1, const Data &d2) {
f.shift_left(d1, d2);
}
};
REGISTER_PRIMITIVE(shift_left);
class shift_right :
public ActionPrimitive<Data &, const Data &, const Data &> {
void operator ()(Data &f, const Data &d1, const Data &d2) {
f.shift_right(d1, d2);
}
};
REGISTER_PRIMITIVE(shift_right);
class drop : public ActionPrimitive<> {
void operator ()() {
get_field("standard_metadata.egress_spec").set(511);
if (get_phv().has_field("intrinsic_metadata.mcast_grp")) {
get_field("intrinsic_metadata.mcast_grp").set(0);
}
}
};
REGISTER_PRIMITIVE(drop);
class exit_ : public ActionPrimitive<> {
void operator ()() {
get_packet().mark_for_exit();
}
};
REGISTER_PRIMITIVE_W_NAME("exit", exit_);
class generate_digest : public ActionPrimitive<const Data &, const Data &> {
void operator ()(const Data &receiver, const Data &learn_id) {
// discared receiver for now
(void) receiver;
get_field("intrinsic_metadata.lf_field_list").set(learn_id);
}
};
REGISTER_PRIMITIVE(generate_digest);
class add_header : public ActionPrimitive<Header &> {
void operator ()(Header &hdr) {
// TODO(antonin): reset header to 0?
if (!hdr.is_valid()) {
hdr.reset();
hdr.mark_valid();
// updated the length packet register (register 0)
auto &packet = get_packet();
packet.set_register(0, packet.get_register(0) + hdr.get_nbytes_packet());
}
}
};
REGISTER_PRIMITIVE(add_header);
class add_header_fast : public ActionPrimitive<Header &> {
void operator ()(Header &hdr) {
hdr.mark_valid();
}
};
REGISTER_PRIMITIVE(add_header_fast);
class remove_header : public ActionPrimitive<Header &> {
void operator ()(Header &hdr) {
if (hdr.is_valid()) {
// updated the length packet register (register 0)
auto &packet = get_packet();
packet.set_register(0, packet.get_register(0) - hdr.get_nbytes_packet());
hdr.mark_invalid();
}
}
};
REGISTER_PRIMITIVE(remove_header);
class copy_header : public ActionPrimitive<Header &, const Header &> {
void operator ()(Header &dst, const Header &src) {
bm::core::assign_header()(dst, src);
}
};
REGISTER_PRIMITIVE(copy_header);
/* standard_metadata.clone_spec will contain the mirror id (16 LSB) and the
field list id to copy (16 MSB) */
class clone_ingress_pkt_to_egress
: public ActionPrimitive<const Data &, const Data &> {
void operator ()(const Data &clone_spec, const Data &field_list_id) {
Field &f_clone_spec = get_field("standard_metadata.clone_spec");
f_clone_spec.shift_left(field_list_id, 16);
f_clone_spec.add(f_clone_spec, clone_spec);
}
};
REGISTER_PRIMITIVE(clone_ingress_pkt_to_egress);
class clone_egress_pkt_to_egress
: public ActionPrimitive<const Data &, const Data &> {
void operator ()(const Data &clone_spec, const Data &field_list_id) {
Field &f_clone_spec = get_field("standard_metadata.clone_spec");
f_clone_spec.shift_left(field_list_id, 16);
f_clone_spec.add(f_clone_spec, clone_spec);
}
};
REGISTER_PRIMITIVE(clone_egress_pkt_to_egress);
class resubmit : public ActionPrimitive<const Data &> {
void operator ()(const Data &field_list_id) {
if (get_phv().has_field("intrinsic_metadata.resubmit_flag")) {
get_phv().get_field("intrinsic_metadata.resubmit_flag")
.set(field_list_id);
}
}
};
REGISTER_PRIMITIVE(resubmit);
class recirculate : public ActionPrimitive<const Data &> {
void operator ()(const Data &field_list_id) {
if (get_phv().has_field("intrinsic_metadata.recirculate_flag")) {
get_phv().get_field("intrinsic_metadata.recirculate_flag")
.set(field_list_id);
}
}
};
REGISTER_PRIMITIVE(recirculate);
class modify_field_with_hash_based_offset
: public ActionPrimitive<Data &, const Data &,
const NamedCalculation &, const Data &> {
void operator ()(Data &dst, const Data &base,
const NamedCalculation &hash, const Data &size) {
auto b = base.get<uint64_t>();
auto orig_sz = size.get<uint64_t>();
auto sz = orig_sz;
if (sz == 0) {
sz = 1;
Logger::get()->warn("hash max given as 0, but treating it as 1");
}
auto v = (hash.output(get_packet()) % sz) + b;
BMLOG_TRACE_PKT(get_packet(),
"hash(base={}, max={}) = {}",
b, orig_sz, v);
dst.set(v);
}
};
REGISTER_PRIMITIVE(modify_field_with_hash_based_offset);
class no_op : public ActionPrimitive<> {
void operator ()() {
// nothing
}
};
REGISTER_PRIMITIVE(no_op);
class execute_meter
: public ActionPrimitive<MeterArray &, const Data &, Field &> {
void operator ()(MeterArray &meter_array, const Data &idx, Field &dst) {
auto i = idx.get_uint();
#ifndef NDEBUG
if (i >= meter_array.size()) {
BMLOG_ERROR_PKT(get_packet(),
"Attempted to update meter '{}' with size {}"
" at out-of-bounds index {}."
" No meters were updated, and neither was"
" dest field.",
meter_array.get_name(), meter_array.size(), i);
return;
}
#endif // NDEBUG
auto color = meter_array.execute_meter(get_packet(), i);
dst.set(color);
BMLOG_TRACE_PKT(get_packet(),
"Updated meter '{}' at index {},"
" assigning dest field the color result {}",
meter_array.get_name(), i, color);
}
};
REGISTER_PRIMITIVE(execute_meter);
class count : public ActionPrimitive<CounterArray &, const Data &> {
void operator ()(CounterArray &counter_array, const Data &idx) {
auto i = idx.get_uint();
#ifndef NDEBUG
if (i >= counter_array.size()) {
BMLOG_ERROR_PKT(get_packet(),
"Attempted to update counter '{}' with size {}"
" at out-of-bounds index {}."
" No counters were updated.",
counter_array.get_name(), counter_array.size(), i);
return;
}
#endif // NDEBUG
counter_array.get_counter(i).increment_counter(get_packet());
BMLOG_TRACE_PKT(get_packet(),
"Updated counter '{}' at index {}",
counter_array.get_name(), i);
}
};
REGISTER_PRIMITIVE(count);
class register_read
: public ActionPrimitive<Field &, const RegisterArray &, const Data &> {
void operator ()(Field &dst, const RegisterArray &src, const Data &idx) {
auto i = idx.get_uint();
#ifndef NDEBUG
if (i >= src.size()) {
BMLOG_ERROR_PKT(get_packet(),
"Attempted to read register '{}' with size {}"
" at out-of-bounds index {}."
" Dest field was not updated.",
src.get_name(), src.size(), i);
return;
}
#endif // NDEBUG
dst.set(src[i]);
BMLOG_TRACE_PKT(get_packet(),
"Read register '{}' at index {} read value {}",
src.get_name(), i, src[i]);
}
};
REGISTER_PRIMITIVE(register_read);
class register_write
: public ActionPrimitive<RegisterArray &, const Data &, const Data &> {
void operator ()(RegisterArray &dst, const Data &idx, const Data &src) {
auto i = idx.get_uint();
#ifndef NDEBUG
if (i >= dst.size()) {
BMLOG_ERROR_PKT(get_packet(),
"Attempted to write register '{}' with size {}"
" at out-of-bounds index {}."
" No register array elements were updated.",
dst.get_name(), dst.size(), i);
return;
}
#endif // NDEBUG
dst[i].set(src);
BMLOG_TRACE_PKT(get_packet(),
"Wrote register '{}' at index {} with value {}",
dst.get_name(), i, dst[i]);
}
};
REGISTER_PRIMITIVE(register_write);
// I cannot name this "truncate" and register it with the usual
// REGISTER_PRIMITIVE macro, because of a name conflict:
//
// In file included from /usr/include/boost/config/stdlib/libstdcpp3.hpp:77:0,
// from /usr/include/boost/config.hpp:44,
// from /usr/include/boost/cstdint.hpp:36,
// from /usr/include/boost/multiprecision/number.hpp:9,
// from /usr/include/boost/multiprecision/gmp.hpp:9,
// from ../../src/bm_sim/include/bm_sim/bignum.h:25,
// from ../../src/bm_sim/include/bm_sim/data.h:32,
// from ../../src/bm_sim/include/bm_sim/fields.h:28,
// from ../../src/bm_sim/include/bm_sim/phv.h:34,
// from ../../src/bm_sim/include/bm_sim/actions.h:34,
// from primitives.cpp:21:
// /usr/include/unistd.h:993:12: note: declared here
// extern int truncate (const char *__file, __off_t __length)
class truncate_ : public ActionPrimitive<const Data &> {
void operator ()(const Data &truncated_length) {
get_packet().truncate(truncated_length.get<size_t>());
}
};
REGISTER_PRIMITIVE_W_NAME("truncate", truncate_);
// dummy function, which ensures that this unit is not discarded by the linker
// it is being called by the constructor of SimpleSwitch
// the previous alternative was to have all the primitives in a header file (the
// primitives could also be placed in simple_switch.cpp directly), but I need
// this dummy function if I want to keep the primitives in their own file
int import_primitives() {
return 0;
}
<|endoftext|>
|
<commit_before>/* Copyright 2015 The TensorFlow Authors. All Rights Reserved.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
==============================================================================*/
// See docs in ../ops/data_flow_ops.cc.
#include "tensorflow/core/framework/op_kernel.h"
#include "tensorflow/core/framework/queue_interface.h"
#include "tensorflow/core/framework/tensor.h"
#include "tensorflow/core/framework/tensor_shape.h"
#include "tensorflow/core/framework/types.h"
#include "tensorflow/core/lib/core/errors.h"
#include "tensorflow/core/platform/macros.h"
#include "tensorflow/core/platform/types.h"
namespace tensorflow {
class QueueOpKernel : public AsyncOpKernel {
public:
explicit QueueOpKernel(OpKernelConstruction* context)
: AsyncOpKernel(context) {}
void ComputeAsync(OpKernelContext* ctx, DoneCallback callback) final {
QueueInterface* queue;
OP_REQUIRES_OK_ASYNC(ctx, GetResourceFromContext(ctx, "handle", &queue),
callback);
ComputeAsync(ctx, queue, [callback, queue]() {
queue->Unref();
callback();
});
}
protected:
virtual void ComputeAsync(OpKernelContext* ctx, QueueInterface* queue,
DoneCallback callback) = 0;
};
class QueueAccessOpKernel : public QueueOpKernel {
public:
explicit QueueAccessOpKernel(OpKernelConstruction* context)
: QueueOpKernel(context) {
OP_REQUIRES_OK(context, context->GetAttr("timeout_ms", &timeout_));
// TODO(keveman): Enable timeout.
OP_REQUIRES(context, timeout_ == -1,
errors::InvalidArgument("Timeout not supported yet."));
}
protected:
int64 timeout_;
};
// Defines an EnqueueOp, the execution of which enqueues a tuple of
// tensors in the given Queue.
//
// The op has 1 + k inputs, where k is the number of components in the
// tuples stored in the given Queue:
// - Input 0: queue handle.
// - Input 1: 0th element of the tuple.
// - ...
// - Input (1+k): kth element of the tuple.
class EnqueueOp : public QueueAccessOpKernel {
public:
explicit EnqueueOp(OpKernelConstruction* context)
: QueueAccessOpKernel(context) {}
protected:
void ComputeAsync(OpKernelContext* ctx, QueueInterface* queue,
DoneCallback callback) override {
DataTypeVector expected_inputs = {DT_STRING_REF};
for (DataType dt : queue->component_dtypes()) {
expected_inputs.push_back(dt);
}
OP_REQUIRES_OK_ASYNC(ctx, ctx->MatchSignature(expected_inputs, {}),
callback);
QueueInterface::Tuple tuple;
OpInputList components;
OP_REQUIRES_OK_ASYNC(ctx, ctx->input_list("components", &components),
callback);
for (const Tensor& Tcomponent : components) {
tuple.push_back(Tcomponent);
}
OP_REQUIRES_OK_ASYNC(ctx, queue->ValidateTuple(tuple), callback);
queue->TryEnqueue(tuple, ctx, callback);
}
private:
TF_DISALLOW_COPY_AND_ASSIGN(EnqueueOp);
};
REGISTER_KERNEL_BUILDER(Name("QueueEnqueue").Device(DEVICE_CPU), EnqueueOp);
// Defines an EnqueueManyOp, the execution of which slices each
// component of a tuple of tensors along the 0th dimension, and
// enqueues tuples of slices in the given Queue.
//
// The op has 1 + k inputs, where k is the number of components in the
// tuples stored in the given Queue:
// - Input 0: queue handle.
// - Input 1: 0th element of the tuple.
// - ...
// - Input (1+k): kth element of the tuple.
//
// N.B. All tuple components must have the same size in the 0th
// dimension.
class EnqueueManyOp : public QueueAccessOpKernel {
public:
explicit EnqueueManyOp(OpKernelConstruction* context)
: QueueAccessOpKernel(context) {}
protected:
void ComputeAsync(OpKernelContext* ctx, QueueInterface* queue,
DoneCallback callback) override {
DataTypeVector expected_inputs = {DT_STRING_REF};
for (DataType dt : queue->component_dtypes()) {
expected_inputs.push_back(dt);
}
OP_REQUIRES_OK_ASYNC(ctx, ctx->MatchSignature(expected_inputs, {}),
callback);
QueueInterface::Tuple tuple;
OpInputList components;
OP_REQUIRES_OK_ASYNC(ctx, ctx->input_list("components", &components),
callback);
for (const Tensor& Tcomponent : components) {
tuple.push_back(Tcomponent);
}
OP_REQUIRES_OK_ASYNC(ctx, queue->ValidateManyTuple(tuple), callback);
queue->TryEnqueueMany(tuple, ctx, callback);
}
~EnqueueManyOp() override {}
private:
TF_DISALLOW_COPY_AND_ASSIGN(EnqueueManyOp);
};
REGISTER_KERNEL_BUILDER(Name("QueueEnqueueMany").Device(DEVICE_CPU),
EnqueueManyOp);
// Defines a DequeueOp, the execution of which dequeues a tuple of
// tensors from the given Queue.
//
// The op has one input, which is the handle of the appropriate
// Queue. The op has k outputs, where k is the number of components in
// the tuples stored in the given Queue, and output i is the ith
// component of the dequeued tuple.
class DequeueOp : public QueueAccessOpKernel {
public:
explicit DequeueOp(OpKernelConstruction* context)
: QueueAccessOpKernel(context) {}
protected:
void ComputeAsync(OpKernelContext* ctx, QueueInterface* queue,
DoneCallback callback) override {
OP_REQUIRES_OK_ASYNC(
ctx, ctx->MatchSignature({DT_STRING_REF}, queue->component_dtypes()),
callback);
queue->TryDequeue(ctx, [ctx, callback](const QueueInterface::Tuple& tuple) {
if (!ctx->status().ok()) {
callback();
return;
}
OpOutputList output_components;
OP_REQUIRES_OK_ASYNC(
ctx, ctx->output_list("components", &output_components), callback);
for (int i = 0; i < ctx->num_outputs(); ++i) {
output_components.set(i, tuple[i]);
}
callback();
});
}
~DequeueOp() override {}
private:
TF_DISALLOW_COPY_AND_ASSIGN(DequeueOp);
};
REGISTER_KERNEL_BUILDER(Name("QueueDequeue").Device(DEVICE_CPU), DequeueOp);
// Defines a DequeueManyOp, the execution of which concatenates the
// requested number of elements from the given Queue along the 0th
// dimension, and emits the result as a single tuple of tensors.
//
// The op has two inputs:
// - Input 0: the handle to a queue.
// - Input 1: the number of elements to dequeue.
//
// The op has k outputs, where k is the number of components in the
// tuples stored in the given Queue, and output i is the ith component
// of the dequeued tuple.
class DequeueManyOp : public QueueAccessOpKernel {
public:
explicit DequeueManyOp(OpKernelConstruction* context)
: QueueAccessOpKernel(context) {}
protected:
void ComputeAsync(OpKernelContext* ctx, QueueInterface* queue,
DoneCallback callback) override {
const Tensor& Tnum_elements = ctx->input(1);
int32 num_elements = Tnum_elements.flat<int32>()(0);
OP_REQUIRES_ASYNC(
ctx, num_elements >= 0,
errors::InvalidArgument("DequeueManyOp must request a positive number "
"of elements"),
callback);
OP_REQUIRES_OK_ASYNC(ctx, ctx->MatchSignature({DT_STRING_REF, DT_INT32},
queue->component_dtypes()),
callback);
queue->TryDequeueMany(
num_elements, ctx, false /* allow_small_batch */,
[ctx, callback](const QueueInterface::Tuple& tuple) {
if (!ctx->status().ok()) {
callback();
return;
}
OpOutputList output_components;
OP_REQUIRES_OK_ASYNC(
ctx, ctx->output_list("components", &output_components),
callback);
for (int i = 0; i < ctx->num_outputs(); ++i) {
output_components.set(i, tuple[i]);
}
callback();
});
}
~DequeueManyOp() override {}
private:
TF_DISALLOW_COPY_AND_ASSIGN(DequeueManyOp);
};
REGISTER_KERNEL_BUILDER(Name("QueueDequeueMany").Device(DEVICE_CPU),
DequeueManyOp);
// Defines a DequeueUpToOp, the execution of which concatenates the
// requested number of elements from the given Queue along the 0th
// dimension, and emits the result as a single tuple of tensors.
//
// The difference between this op and DequeueMany is the handling when
// the Queue is closed. While the DequeueMany op will return if there
// an error when there are less than num_elements elements left in the
// closed queue, this op will return between 1 and
// min(num_elements, elements_remaining_in_queue), and will not block.
// If there are no elements left, then the standard DequeueMany error
// is returned.
//
// This op only works if the underlying Queue implementation accepts
// the allow_small_batch = true parameter to TryDequeueMany.
// If it does not, an errors::Unimplemented exception is returned.
//
// The op has two inputs:
// - Input 0: the handle to a queue.
// - Input 1: the number of elements to dequeue.
//
// The op has k outputs, where k is the number of components in the
// tuples stored in the given Queue, and output i is the ith component
// of the dequeued tuple.
//
// The op has one attribute: allow_small_batch. If the Queue supports
// it, setting this to true causes the queue to return smaller
// (possibly zero length) batches when it is closed, up to however
// many elements are available when the op executes. In this case,
// the Queue does not block when closed.
class DequeueUpToOp : public QueueAccessOpKernel {
public:
explicit DequeueUpToOp(OpKernelConstruction* context)
: QueueAccessOpKernel(context) {}
protected:
void ComputeAsync(OpKernelContext* ctx, QueueInterface* queue,
DoneCallback callback) override {
const Tensor& Tnum_elements = ctx->input(1);
int32 num_elements = Tnum_elements.flat<int32>()(0);
OP_REQUIRES_ASYNC(
ctx, num_elements >= 0,
errors::InvalidArgument("DequeueUpToOp must request a positive number "
"of elements"),
callback);
OP_REQUIRES_OK_ASYNC(ctx, ctx->MatchSignature({DT_STRING_REF, DT_INT32},
queue->component_dtypes()),
callback);
queue->TryDequeueMany(
num_elements, ctx, true /* allow_small_batch */,
[ctx, callback](const QueueInterface::Tuple& tuple) {
if (!ctx->status().ok()) {
callback();
return;
}
OpOutputList output_components;
OP_REQUIRES_OK_ASYNC(
ctx, ctx->output_list("components", &output_components),
callback);
for (int i = 0; i < ctx->num_outputs(); ++i) {
output_components.set(i, tuple[i]);
}
callback();
});
}
~DequeueUpToOp() override {}
private:
TF_DISALLOW_COPY_AND_ASSIGN(DequeueUpToOp);
};
REGISTER_KERNEL_BUILDER(Name("QueueDequeueUpTo").Device(DEVICE_CPU),
DequeueUpToOp);
// Defines a QueueCloseOp, which closes the given Queue. Closing a
// Queue signals that no more elements will be enqueued in it.
//
// The op has one input, which is the handle of the appropriate Queue.
class QueueCloseOp : public QueueOpKernel {
public:
explicit QueueCloseOp(OpKernelConstruction* context)
: QueueOpKernel(context) {
OP_REQUIRES_OK(context, context->GetAttr("cancel_pending_enqueues",
&cancel_pending_enqueues_));
}
protected:
void ComputeAsync(OpKernelContext* ctx, QueueInterface* queue,
DoneCallback callback) override {
queue->Close(ctx, cancel_pending_enqueues_, callback);
}
private:
bool cancel_pending_enqueues_;
TF_DISALLOW_COPY_AND_ASSIGN(QueueCloseOp);
};
REGISTER_KERNEL_BUILDER(Name("QueueClose").Device(DEVICE_CPU), QueueCloseOp);
// Defines a QueueSizeOp, which computes the number of elements in the
// given Queue, and emits it as an output tensor.
//
// The op has one input, which is the handle of the appropriate Queue;
// and one output, which is a single-element tensor containing the current
// size of that Queue.
class QueueSizeOp : public QueueOpKernel {
public:
explicit QueueSizeOp(OpKernelConstruction* context)
: QueueOpKernel(context) {}
protected:
void ComputeAsync(OpKernelContext* ctx, QueueInterface* queue,
DoneCallback callback) override {
Tensor* Tqueue_size = nullptr;
OP_REQUIRES_OK(ctx, ctx->allocate_output(0, TensorShape({}), &Tqueue_size));
Tqueue_size->flat<int32>().setConstant(queue->size());
callback();
}
private:
TF_DISALLOW_COPY_AND_ASSIGN(QueueSizeOp);
};
REGISTER_KERNEL_BUILDER(Name("QueueSize").Device(DEVICE_CPU), QueueSizeOp);
} // namespace tensorflow
<commit_msg>Fix dequeue error messages Change: 128191932<commit_after>/* Copyright 2015 The TensorFlow Authors. All Rights Reserved.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
==============================================================================*/
// See docs in ../ops/data_flow_ops.cc.
#include "tensorflow/core/framework/op_kernel.h"
#include "tensorflow/core/framework/queue_interface.h"
#include "tensorflow/core/framework/tensor.h"
#include "tensorflow/core/framework/tensor_shape.h"
#include "tensorflow/core/framework/types.h"
#include "tensorflow/core/lib/core/errors.h"
#include "tensorflow/core/platform/macros.h"
#include "tensorflow/core/platform/types.h"
namespace tensorflow {
class QueueOpKernel : public AsyncOpKernel {
public:
explicit QueueOpKernel(OpKernelConstruction* context)
: AsyncOpKernel(context) {}
void ComputeAsync(OpKernelContext* ctx, DoneCallback callback) final {
QueueInterface* queue;
OP_REQUIRES_OK_ASYNC(ctx, GetResourceFromContext(ctx, "handle", &queue),
callback);
ComputeAsync(ctx, queue, [callback, queue]() {
queue->Unref();
callback();
});
}
protected:
virtual void ComputeAsync(OpKernelContext* ctx, QueueInterface* queue,
DoneCallback callback) = 0;
};
class QueueAccessOpKernel : public QueueOpKernel {
public:
explicit QueueAccessOpKernel(OpKernelConstruction* context)
: QueueOpKernel(context) {
OP_REQUIRES_OK(context, context->GetAttr("timeout_ms", &timeout_));
// TODO(keveman): Enable timeout.
OP_REQUIRES(context, timeout_ == -1,
errors::InvalidArgument("Timeout not supported yet."));
}
protected:
int64 timeout_;
};
// Defines an EnqueueOp, the execution of which enqueues a tuple of
// tensors in the given Queue.
//
// The op has 1 + k inputs, where k is the number of components in the
// tuples stored in the given Queue:
// - Input 0: queue handle.
// - Input 1: 0th element of the tuple.
// - ...
// - Input (1+k): kth element of the tuple.
class EnqueueOp : public QueueAccessOpKernel {
public:
explicit EnqueueOp(OpKernelConstruction* context)
: QueueAccessOpKernel(context) {}
protected:
void ComputeAsync(OpKernelContext* ctx, QueueInterface* queue,
DoneCallback callback) override {
DataTypeVector expected_inputs = {DT_STRING_REF};
for (DataType dt : queue->component_dtypes()) {
expected_inputs.push_back(dt);
}
OP_REQUIRES_OK_ASYNC(ctx, ctx->MatchSignature(expected_inputs, {}),
callback);
QueueInterface::Tuple tuple;
OpInputList components;
OP_REQUIRES_OK_ASYNC(ctx, ctx->input_list("components", &components),
callback);
for (const Tensor& Tcomponent : components) {
tuple.push_back(Tcomponent);
}
OP_REQUIRES_OK_ASYNC(ctx, queue->ValidateTuple(tuple), callback);
queue->TryEnqueue(tuple, ctx, callback);
}
private:
TF_DISALLOW_COPY_AND_ASSIGN(EnqueueOp);
};
REGISTER_KERNEL_BUILDER(Name("QueueEnqueue").Device(DEVICE_CPU), EnqueueOp);
// Defines an EnqueueManyOp, the execution of which slices each
// component of a tuple of tensors along the 0th dimension, and
// enqueues tuples of slices in the given Queue.
//
// The op has 1 + k inputs, where k is the number of components in the
// tuples stored in the given Queue:
// - Input 0: queue handle.
// - Input 1: 0th element of the tuple.
// - ...
// - Input (1+k): kth element of the tuple.
//
// N.B. All tuple components must have the same size in the 0th
// dimension.
class EnqueueManyOp : public QueueAccessOpKernel {
public:
explicit EnqueueManyOp(OpKernelConstruction* context)
: QueueAccessOpKernel(context) {}
protected:
void ComputeAsync(OpKernelContext* ctx, QueueInterface* queue,
DoneCallback callback) override {
DataTypeVector expected_inputs = {DT_STRING_REF};
for (DataType dt : queue->component_dtypes()) {
expected_inputs.push_back(dt);
}
OP_REQUIRES_OK_ASYNC(ctx, ctx->MatchSignature(expected_inputs, {}),
callback);
QueueInterface::Tuple tuple;
OpInputList components;
OP_REQUIRES_OK_ASYNC(ctx, ctx->input_list("components", &components),
callback);
for (const Tensor& Tcomponent : components) {
tuple.push_back(Tcomponent);
}
OP_REQUIRES_OK_ASYNC(ctx, queue->ValidateManyTuple(tuple), callback);
queue->TryEnqueueMany(tuple, ctx, callback);
}
~EnqueueManyOp() override {}
private:
TF_DISALLOW_COPY_AND_ASSIGN(EnqueueManyOp);
};
REGISTER_KERNEL_BUILDER(Name("QueueEnqueueMany").Device(DEVICE_CPU),
EnqueueManyOp);
// Defines a DequeueOp, the execution of which dequeues a tuple of
// tensors from the given Queue.
//
// The op has one input, which is the handle of the appropriate
// Queue. The op has k outputs, where k is the number of components in
// the tuples stored in the given Queue, and output i is the ith
// component of the dequeued tuple.
class DequeueOp : public QueueAccessOpKernel {
public:
explicit DequeueOp(OpKernelConstruction* context)
: QueueAccessOpKernel(context) {}
protected:
void ComputeAsync(OpKernelContext* ctx, QueueInterface* queue,
DoneCallback callback) override {
OP_REQUIRES_OK_ASYNC(
ctx, ctx->MatchSignature({DT_STRING_REF}, queue->component_dtypes()),
callback);
queue->TryDequeue(ctx, [ctx, callback](const QueueInterface::Tuple& tuple) {
if (!ctx->status().ok()) {
callback();
return;
}
OpOutputList output_components;
OP_REQUIRES_OK_ASYNC(
ctx, ctx->output_list("components", &output_components), callback);
for (int i = 0; i < ctx->num_outputs(); ++i) {
output_components.set(i, tuple[i]);
}
callback();
});
}
~DequeueOp() override {}
private:
TF_DISALLOW_COPY_AND_ASSIGN(DequeueOp);
};
REGISTER_KERNEL_BUILDER(Name("QueueDequeue").Device(DEVICE_CPU), DequeueOp);
// Defines a DequeueManyOp, the execution of which concatenates the
// requested number of elements from the given Queue along the 0th
// dimension, and emits the result as a single tuple of tensors.
//
// The op has two inputs:
// - Input 0: the handle to a queue.
// - Input 1: the number of elements to dequeue.
//
// The op has k outputs, where k is the number of components in the
// tuples stored in the given Queue, and output i is the ith component
// of the dequeued tuple.
class DequeueManyOp : public QueueAccessOpKernel {
public:
explicit DequeueManyOp(OpKernelConstruction* context)
: QueueAccessOpKernel(context) {}
protected:
void ComputeAsync(OpKernelContext* ctx, QueueInterface* queue,
DoneCallback callback) override {
const Tensor& Tnum_elements = ctx->input(1);
int32 num_elements = Tnum_elements.flat<int32>()(0);
OP_REQUIRES_ASYNC(ctx, num_elements >= 0,
errors::InvalidArgument("DequeueManyOp requested ",
num_elements, " < 0 elements"),
callback);
OP_REQUIRES_OK_ASYNC(ctx, ctx->MatchSignature({DT_STRING_REF, DT_INT32},
queue->component_dtypes()),
callback);
queue->TryDequeueMany(
num_elements, ctx, false /* allow_small_batch */,
[ctx, callback](const QueueInterface::Tuple& tuple) {
if (!ctx->status().ok()) {
callback();
return;
}
OpOutputList output_components;
OP_REQUIRES_OK_ASYNC(
ctx, ctx->output_list("components", &output_components),
callback);
for (int i = 0; i < ctx->num_outputs(); ++i) {
output_components.set(i, tuple[i]);
}
callback();
});
}
~DequeueManyOp() override {}
private:
TF_DISALLOW_COPY_AND_ASSIGN(DequeueManyOp);
};
REGISTER_KERNEL_BUILDER(Name("QueueDequeueMany").Device(DEVICE_CPU),
DequeueManyOp);
// Defines a DequeueUpToOp, the execution of which concatenates the
// requested number of elements from the given Queue along the 0th
// dimension, and emits the result as a single tuple of tensors.
//
// The difference between this op and DequeueMany is the handling when
// the Queue is closed. While the DequeueMany op will return if there
// an error when there are less than num_elements elements left in the
// closed queue, this op will return between 1 and
// min(num_elements, elements_remaining_in_queue), and will not block.
// If there are no elements left, then the standard DequeueMany error
// is returned.
//
// This op only works if the underlying Queue implementation accepts
// the allow_small_batch = true parameter to TryDequeueMany.
// If it does not, an errors::Unimplemented exception is returned.
//
// The op has two inputs:
// - Input 0: the handle to a queue.
// - Input 1: the number of elements to dequeue.
//
// The op has k outputs, where k is the number of components in the
// tuples stored in the given Queue, and output i is the ith component
// of the dequeued tuple.
//
// The op has one attribute: allow_small_batch. If the Queue supports
// it, setting this to true causes the queue to return smaller
// (possibly zero length) batches when it is closed, up to however
// many elements are available when the op executes. In this case,
// the Queue does not block when closed.
class DequeueUpToOp : public QueueAccessOpKernel {
public:
explicit DequeueUpToOp(OpKernelConstruction* context)
: QueueAccessOpKernel(context) {}
protected:
void ComputeAsync(OpKernelContext* ctx, QueueInterface* queue,
DoneCallback callback) override {
const Tensor& Tnum_elements = ctx->input(1);
int32 num_elements = Tnum_elements.flat<int32>()(0);
OP_REQUIRES_ASYNC(ctx, num_elements >= 0,
errors::InvalidArgument("DequeueUpToOp requested ",
num_elements, " < 0 elements"),
callback);
OP_REQUIRES_OK_ASYNC(ctx, ctx->MatchSignature({DT_STRING_REF, DT_INT32},
queue->component_dtypes()),
callback);
queue->TryDequeueMany(
num_elements, ctx, true /* allow_small_batch */,
[ctx, callback](const QueueInterface::Tuple& tuple) {
if (!ctx->status().ok()) {
callback();
return;
}
OpOutputList output_components;
OP_REQUIRES_OK_ASYNC(
ctx, ctx->output_list("components", &output_components),
callback);
for (int i = 0; i < ctx->num_outputs(); ++i) {
output_components.set(i, tuple[i]);
}
callback();
});
}
~DequeueUpToOp() override {}
private:
TF_DISALLOW_COPY_AND_ASSIGN(DequeueUpToOp);
};
REGISTER_KERNEL_BUILDER(Name("QueueDequeueUpTo").Device(DEVICE_CPU),
DequeueUpToOp);
// Defines a QueueCloseOp, which closes the given Queue. Closing a
// Queue signals that no more elements will be enqueued in it.
//
// The op has one input, which is the handle of the appropriate Queue.
class QueueCloseOp : public QueueOpKernel {
public:
explicit QueueCloseOp(OpKernelConstruction* context)
: QueueOpKernel(context) {
OP_REQUIRES_OK(context, context->GetAttr("cancel_pending_enqueues",
&cancel_pending_enqueues_));
}
protected:
void ComputeAsync(OpKernelContext* ctx, QueueInterface* queue,
DoneCallback callback) override {
queue->Close(ctx, cancel_pending_enqueues_, callback);
}
private:
bool cancel_pending_enqueues_;
TF_DISALLOW_COPY_AND_ASSIGN(QueueCloseOp);
};
REGISTER_KERNEL_BUILDER(Name("QueueClose").Device(DEVICE_CPU), QueueCloseOp);
// Defines a QueueSizeOp, which computes the number of elements in the
// given Queue, and emits it as an output tensor.
//
// The op has one input, which is the handle of the appropriate Queue;
// and one output, which is a single-element tensor containing the current
// size of that Queue.
class QueueSizeOp : public QueueOpKernel {
public:
explicit QueueSizeOp(OpKernelConstruction* context)
: QueueOpKernel(context) {}
protected:
void ComputeAsync(OpKernelContext* ctx, QueueInterface* queue,
DoneCallback callback) override {
Tensor* Tqueue_size = nullptr;
OP_REQUIRES_OK(ctx, ctx->allocate_output(0, TensorShape({}), &Tqueue_size));
Tqueue_size->flat<int32>().setConstant(queue->size());
callback();
}
private:
TF_DISALLOW_COPY_AND_ASSIGN(QueueSizeOp);
};
REGISTER_KERNEL_BUILDER(Name("QueueSize").Device(DEVICE_CPU), QueueSizeOp);
} // namespace tensorflow
<|endoftext|>
|
<commit_before>#include "mainwidget.h"
MainWidget::MainWidget(QWidget *parent)
: QWidget(parent)
{
CpuRate_Label = new QLabel(this);
RamRate_Label = new QLabel(this);
Speed_Label = new QLabel(this);
m_timer = new QTimer(this);
connect(m_timer, SIGNAL(timeout()), this, SLOT(timeout_slot()));
this->setMinimumSize(200, 200);
layoutInit();
//usually,iphlpapi.dll has existed in windows
m_lib.setFileName("iphlpapi.dll");
m_lib.load();
m_funcGetIfTable = (GetIfTable)m_lib.resolve("GetIfTable");
m_preNetIn = 0;
m_preNetOut = 0;
memset(&m_preIdleTime, 0, sizeof(FILETIME));
memset(&m_preKernelTime, 0, sizeof(FILETIME));
memset(&m_preUserTime, 0, sizeof(FILETIME));
m_timer->start(1000);
}
MainWidget::~MainWidget()
{
m_timer->stop();
}
void MainWidget::paintEvent(QPaintEvent *event)
{
layoutInit();
QWidget::paintEvent(event);
}
void MainWidget::layoutInit(void)
{
CpuRate_Label->move(this->width() / 2 - CpuRate_Label->width() / 2, 20);
RamRate_Label->move(this->width() / 2 - CpuRate_Label->width() / 2, CpuRate_Label->y() + CpuRate_Label->height() + 10);
Speed_Label->move(this->width() / 2 - Speed_Label->width() / 2, RamRate_Label->y() + RamRate_Label->height() + 10);
}
void MainWidget::timeout_slot(void)
{
//memory
MEMORYSTATUSEX memsStat;
memsStat.dwLength = sizeof(memsStat);
if(GlobalMemoryStatusEx(&memsStat))
{
int nMemFree = memsStat.ullAvailPhys / (1024 * 1024);
int nMemTotal = memsStat.ullTotalPhys / (1024 * 1024);
RamRate_Label->setText(QString("RAM rate:%1\%").arg((nMemTotal - nMemFree) * 100 / nMemTotal));
RamRate_Label->adjustSize();
}
//cpu
FILETIME IdleTime;
FILETIME KernelTime;
FILETIME UserTime;
if(GetSystemTimes(&IdleTime, &KernelTime, &UserTime))
{
if(0 != m_preIdleTime.dwHighDateTime && 0 != m_preIdleTime.dwLowDateTime)
{
int idle = delOfInt64(IdleTime, m_preIdleTime);
int kernel = delOfInt64(KernelTime,m_preKernelTime);
int user = delOfInt64(UserTime,m_preUserTime);
int rate = (kernel + user - idle) * 100 / (kernel + user);
CpuRate_Label->setText(QString("CPU rate:%1\%").arg(rate));
CpuRate_Label->adjustSize();
}
m_preIdleTime = IdleTime;
m_preKernelTime = KernelTime;
m_preUserTime = UserTime;
}
//network
PMIB_IFTABLE m_pTable = NULL;
DWORD m_dwAdapters = 0;
//first call is just get the m_dwAdapters's value
//more detail,pls see https://msdn.microsoft.com/en-us/library/windows/desktop/aa365943(v=vs.85).aspx
m_funcGetIfTable(m_pTable, &m_dwAdapters, FALSE);
m_pTable = (PMIB_IFTABLE)new BYTE[m_dwAdapters];
//speed = sum / time,so it should record the time
int nowTime = QDateTime().currentDateTime().toString("zzz").toInt();
m_funcGetIfTable(m_pTable, &m_dwAdapters, FALSE);
DWORD NowIn = 0;
DWORD NowOut = 0;
QList<int> typeList;
for (UINT i = 0; i < m_pTable->dwNumEntries; i++)
{
MIB_IFROW Row = m_pTable->table[i];
//1 type should only be count only once
bool bExist = false;
for(int j = 0;j < typeList.count();j++)
{
if(typeList.at(j) == (int)Row.dwType)
{
bExist = true;
break;
}
}
if(false == bExist)
{
typeList.append(Row.dwType);
NowIn += Row.dwInOctets;
NowOut += Row.dwOutOctets;
}
}
delete []m_pTable;
if(0 != m_preNetOut && 0 != m_preNetIn)
{
double coeffcient = (double)(1000 + nowTime - m_preTime) / 1000;
//download and upload speed should keep same unit
Speed_Label->setText(getSpeedInfo((int)(NowIn - m_preNetIn) / coeffcient, (int)(NowOut - m_preNetOut) / coeffcient));
Speed_Label->adjustSize();
}
m_preTime = nowTime;
m_preNetOut = NowOut;
m_preNetIn = NowIn;
}
//There is an interesting test of this function:
QString MainWidget::getSpeedInfo(int idownloadSpeed, int iuploadSpeed)
{
QString speedString = "B/s";
double downloadSpeed = idownloadSpeed;
double uploadSpeed = iuploadSpeed;
if(downloadSpeed >= 1024 || uploadSpeed >= 1024)
{
speedString = "KB/s";
downloadSpeed = (double)(int((downloadSpeed / 1024.0) * 100)) / 100;
uploadSpeed = (double)(int((uploadSpeed / 1024.0) * 100)) / 100;
if(downloadSpeed >= 1024 || uploadSpeed >= 1024)
{
speedString = "MB/s";
//retain 2 decimals
downloadSpeed = (double)(int((downloadSpeed / 1024.0) * 100)) / 100;
uploadSpeed = (double)(int((uploadSpeed / 1024.0) * 100)) / 100;
if(downloadSpeed >= 1024 || uploadSpeed >= 1024)
{
speedString = "GB/s";
//retain 2 decimals
downloadSpeed = (double)(int((downloadSpeed / 1024.0) * 100)) / 100;
uploadSpeed = (double)(int((uploadSpeed / 1024.0) * 100)) / 100;
}
}
}
return QString("download:%1%2\nupload:%3%2").arg(uploadSpeed).arg(speedString).arg(downloadSpeed);
}
int MainWidget::delOfInt64(FILETIME subtrahend, FILETIME minuend)
{
__int64 a = (__int64)(subtrahend.dwHighDateTime) << 32 | (__int64)subtrahend.dwLowDateTime ;
__int64 b = (__int64)(minuend.dwHighDateTime) << 32 | (__int64)minuend.dwLowDateTime ;
int answer = 0;
if(b > a)
{
answer = b - a;
}
else
{
answer = 0xFFFFFFFFFFFFFFFF - a + b;
}
return answer;
}
<commit_msg>note<commit_after>#include "mainwidget.h"
MainWidget::MainWidget(QWidget *parent)
: QWidget(parent)
{
CpuRate_Label = new QLabel(this);
RamRate_Label = new QLabel(this);
Speed_Label = new QLabel(this);
m_timer = new QTimer(this);
connect(m_timer, SIGNAL(timeout()), this, SLOT(timeout_slot()));
this->setMinimumSize(200, 200);
layoutInit();
//usually,iphlpapi.dll has existed in windows
m_lib.setFileName("iphlpapi.dll");
m_lib.load();
m_funcGetIfTable = (GetIfTable)m_lib.resolve("GetIfTable");
m_preNetIn = 0;
m_preNetOut = 0;
memset(&m_preIdleTime, 0, sizeof(FILETIME));
memset(&m_preKernelTime, 0, sizeof(FILETIME));
memset(&m_preUserTime, 0, sizeof(FILETIME));
m_timer->start(1000);
}
MainWidget::~MainWidget()
{
m_timer->stop();
}
void MainWidget::paintEvent(QPaintEvent *event)
{
layoutInit();
QWidget::paintEvent(event);
}
void MainWidget::layoutInit(void)
{
CpuRate_Label->move(this->width() / 2 - CpuRate_Label->width() / 2, 20);
RamRate_Label->move(this->width() / 2 - CpuRate_Label->width() / 2, CpuRate_Label->y() + CpuRate_Label->height() + 10);
Speed_Label->move(this->width() / 2 - Speed_Label->width() / 2, RamRate_Label->y() + RamRate_Label->height() + 10);
}
void MainWidget::timeout_slot(void)
{
//memory
MEMORYSTATUSEX memsStat;
memsStat.dwLength = sizeof(memsStat);
if(GlobalMemoryStatusEx(&memsStat))
{
int nMemFree = memsStat.ullAvailPhys / (1024 * 1024);
int nMemTotal = memsStat.ullTotalPhys / (1024 * 1024);
RamRate_Label->setText(QString("RAM rate:%1\%").arg((nMemTotal - nMemFree) * 100 / nMemTotal));
RamRate_Label->adjustSize();
}
//cpu
FILETIME IdleTime;
FILETIME KernelTime;
FILETIME UserTime;
if(GetSystemTimes(&IdleTime, &KernelTime, &UserTime))
{
if(0 != m_preIdleTime.dwHighDateTime && 0 != m_preIdleTime.dwLowDateTime)
{
int idle = delOfInt64(IdleTime, m_preIdleTime);
int kernel = delOfInt64(KernelTime,m_preKernelTime);
int user = delOfInt64(UserTime,m_preUserTime);
int rate = (kernel + user - idle) * 100 / (kernel + user);
CpuRate_Label->setText(QString("CPU rate:%1\%").arg(rate));
CpuRate_Label->adjustSize();
}
m_preIdleTime = IdleTime;
m_preKernelTime = KernelTime;
m_preUserTime = UserTime;
}
//network
PMIB_IFTABLE m_pTable = NULL;
DWORD m_dwAdapters = 0;
//first call is just get the m_dwAdapters's value
//more detail,pls see https://msdn.microsoft.com/en-us/library/windows/desktop/aa365943(v=vs.85).aspx
m_funcGetIfTable(m_pTable, &m_dwAdapters, FALSE);
m_pTable = (PMIB_IFTABLE)new BYTE[m_dwAdapters];
//speed = sum / time,so it should record the time
int nowTime = QDateTime().currentDateTime().toString("zzz").toInt();
m_funcGetIfTable(m_pTable, &m_dwAdapters, FALSE);
DWORD NowIn = 0;
DWORD NowOut = 0;
QList<int> typeList;
for (UINT i = 0; i < m_pTable->dwNumEntries; i++)
{
MIB_IFROW Row = m_pTable->table[i];
//1 type should only be count only once
bool bExist = false;
for(int j = 0;j < typeList.count();j++)
{
if(typeList.at(j) == (int)Row.dwType)
{
bExist = true;
break;
}
}
if(false == bExist)
{
typeList.append(Row.dwType);
NowIn += Row.dwInOctets;
NowOut += Row.dwOutOctets;
}
}
delete []m_pTable;
if(0 != m_preNetOut && 0 != m_preNetIn)
{
double coeffcient = (double)(1000 + nowTime - m_preTime) / 1000;
//download and upload speed should keep same unit
Speed_Label->setText(getSpeedInfo((int)(NowIn - m_preNetIn) / coeffcient, (int)(NowOut - m_preNetOut) / coeffcient));
Speed_Label->adjustSize();
}
m_preTime = nowTime;
m_preNetOut = NowOut;
m_preNetIn = NowIn;
}
//There is an interesting test of this function:
//I tried change this 2 input parameters' types to double,
//then in release mode,crash;in debug mode, run correctly.
QString MainWidget::getSpeedInfo(int idownloadSpeed, int iuploadSpeed)
{
QString speedString = "B/s";
double downloadSpeed = idownloadSpeed;
double uploadSpeed = iuploadSpeed;
if(downloadSpeed >= 1024 || uploadSpeed >= 1024)
{
speedString = "KB/s";
downloadSpeed = (double)(int((downloadSpeed / 1024.0) * 100)) / 100;
uploadSpeed = (double)(int((uploadSpeed / 1024.0) * 100)) / 100;
if(downloadSpeed >= 1024 || uploadSpeed >= 1024)
{
speedString = "MB/s";
//retain 2 decimals
downloadSpeed = (double)(int((downloadSpeed / 1024.0) * 100)) / 100;
uploadSpeed = (double)(int((uploadSpeed / 1024.0) * 100)) / 100;
if(downloadSpeed >= 1024 || uploadSpeed >= 1024)
{
speedString = "GB/s";
//retain 2 decimals
downloadSpeed = (double)(int((downloadSpeed / 1024.0) * 100)) / 100;
uploadSpeed = (double)(int((uploadSpeed / 1024.0) * 100)) / 100;
}
}
}
return QString("download:%1%2\nupload:%3%2").arg(uploadSpeed).arg(speedString).arg(downloadSpeed);
}
int MainWidget::delOfInt64(FILETIME subtrahend, FILETIME minuend)
{
__int64 a = (__int64)(subtrahend.dwHighDateTime) << 32 | (__int64)subtrahend.dwLowDateTime ;
__int64 b = (__int64)(minuend.dwHighDateTime) << 32 | (__int64)minuend.dwLowDateTime ;
int answer = 0;
if(b > a)
{
answer = b - a;
}
else
{
answer = 0xFFFFFFFFFFFFFFFF - a + b;
}
return answer;
}
<|endoftext|>
|
<commit_before>#include "mainwindow.h"
#include "ui_mainwindow.h"
#include "aboutdialog.h"
#include "instructionsdialog.h"
#include "robotpath.h"
#include "robotgriditem.h"
#include "robotgridmatrix.h"
#include "map.h"
#include <QMessageBox>
#include <QPixmap>
#include <QGraphicsPixmapItem>
MainWindow::MainWindow(QWidget *parent) :
QMainWindow(parent),
ui(new Ui::MainWindow) {
ui->setupUi(this);
}
MainWindow::~MainWindow() {
delete ui;
}
void MainWindow::on_actionRun_triggered() {
int ib[8][10] = { {2,2,2,2,2,0,0,0,0,1},
{0,0,0,0,2,0,0,0,1,1},
{0,0,1,1,3,1,1,1,1,0},
{1,1,1,0,2,0,0,0,0,0},
{1,0,0,0,2,2,2,0,0,0},
{1,0,0,0,0,0,2,0,0,0},
{1,0,0,0,0,0,2,2,2,0},
{1,0,0,0,0,0,0,0,2,2}};
QGraphicsScene *scene = new QGraphicsScene(this);
ui->areaPlot->setScene(scene);
ui->areaPlot->setRenderHint(QPainter::Antialiasing);
QList<RobotGridItem*> grid;
QList<QPoint> path_1, path_2;
RobotGridMatrix Matrix(grid);
//Maze.ImportMaze(ib);
Map Maze;
Maze.mapFromArray(ib);
Matrix.MapToScene(Maze);
Matrix.AttachToScene(scene);
qDebug(">>> %d >>>", Maze.popValue(QPoint(0,0)));
qDebug(">>> %d >>>", Maze.popValue(QPoint(0,1)));
qDebug(">>> %d >>>", Maze.popValue(QPoint(1,0)));
qDebug(">>> %d >>>", Maze.popValue(QPoint(9,0)));
RobotPath(Maze, path_1, path_2);
//QListIterator<QPoint> i(path_1); while(i.hasNext()) qDebug() << i.next();
QGraphicsPixmapItem *c = scene->addPixmap(QPixmap(":/terrain/monolith3.png"));
c->setPos(0,5*71);
qDebug() << "Action->run";
}
void MainWindow::on_actionReset_triggered() {
ui->areaPlot->repaint();
qDebug() << "Action->reset";
}
void MainWindow::on_actionGenerate_triggered() {qDebug() << "Action->generate";}
void MainWindow::on_actionImportAll_triggered() {qDebug() << "Action->ImportAll";}
void MainWindow::on_actionImportMap_triggered() {qDebug() << "Action->ImportMap";}
void MainWindow::on_actionExportCriticalPlaces_triggered() {qDebug() << "Action->ExportCriticalPlaces";}
void MainWindow::on_actionExportMap_triggered() {qDebug() << "Action->ExportMap";}
void MainWindow::on_actionExportMovements_triggered() {qDebug() << "Action->ExportMovements";}
void MainWindow::on_actionHelpAbout_triggered() {
AboutDialog *about = new AboutDialog;
about->setWindowTitle("About");
about->show();
qDebug() << "Action->HelpAbout";
}
void MainWindow::on_actionHelpInstructions_triggered(){
InstructionsDialog *inst = new InstructionsDialog;
inst->setWindowTitle("Instructions");
inst->show();
qDebug() << "Action->HelpInstructions";
}
<commit_msg>another update<commit_after>#include "mainwindow.h"
#include "ui_mainwindow.h"
#include "aboutdialog.h"
#include "instructionsdialog.h"
#include "robotpath.h"
#include "robotgriditem.h"
#include "robotgridmatrix.h"
#include "robotgraphicsitem.h"
#include "map.h"
#include <QMessageBox>
#include <QPixmap>
#include <QGraphicsPixmapItem>
MainWindow::MainWindow(QWidget *parent) :
QMainWindow(parent),
ui(new Ui::MainWindow) {
ui->setupUi(this);
}
MainWindow::~MainWindow() {
delete ui;
}
void MainWindow::on_actionRun_triggered() {
int ib[8][10] = { {2,2,2,2,2,0,0,0,0,1},
{0,0,0,0,2,0,0,0,1,1},
{0,0,1,1,3,1,1,1,1,0},
{1,1,1,0,2,0,0,0,0,0},
{1,0,0,0,2,2,2,0,0,0},
{1,0,0,0,0,0,2,0,0,0},
{1,0,0,0,0,0,2,2,2,0},
{1,0,0,0,0,0,0,0,2,2}};
QGraphicsScene *scene = new QGraphicsScene(this);
ui->areaPlot->setScene(scene);
ui->areaPlot->setRenderHint(QPainter::Antialiasing);
QList<RobotGridItem*> grid;
QList<QPoint> path_1, path_2;
RobotGridMatrix Matrix(grid);
//Maze.ImportMaze(ib);
Map Maze;
Maze.mapFromArray(ib);
Matrix.MapToScene(Maze);
Matrix.AttachToScene(scene);
qDebug(">>> %d >>>", Maze.popValue(QPoint(0,0)));
qDebug(">>> %d >>>", Maze.popValue(QPoint(0,1)));
qDebug(">>> %d >>>", Maze.popValue(QPoint(1,0)));
qDebug(">>> %d >>>", Maze.popValue(QPoint(9,0)));
RobotPath(Maze, path_1, path_2);
//QListIterator<QPoint> i(path_1); while(i.hasNext()) qDebug() << i.next();
RobotGraphicsItem *bot = new RobotGraphicsItem(QPixmap(":terrain/monument3.png"),0,path_1,QPoint(0,7));
scene->addItem(bot);
RobotGraphicsObject *O_bot = new RobotGraphicsObject(QPixmap(":terrain/monument3.png"),0,path_1,QPoint(0,7));
QTimer *timer = new QTimer(this);
connect(timer, SIGNAL(timeout()),ui->areaPlot, SLOT(animateMovement()));
timer->start(100);
qDebug() << "Action->run";
}
void MainWindow::on_actionReset_triggered() {
ui->areaPlot->repaint();
qDebug() << "Action->reset";
}
void MainWindow::on_actionGenerate_triggered() {qDebug() << "Action->generate";}
void MainWindow::on_actionImportAll_triggered() {qDebug() << "Action->ImportAll";}
void MainWindow::on_actionImportMap_triggered() {qDebug() << "Action->ImportMap";}
void MainWindow::on_actionExportCriticalPlaces_triggered() {qDebug() << "Action->ExportCriticalPlaces";}
void MainWindow::on_actionExportMap_triggered() {qDebug() << "Action->ExportMap";}
void MainWindow::on_actionExportMovements_triggered() {qDebug() << "Action->ExportMovements";}
void MainWindow::on_actionHelpAbout_triggered() {
AboutDialog *about = new AboutDialog;
about->setWindowTitle("About");
about->show();
qDebug() << "Action->HelpAbout";
}
void MainWindow::on_actionHelpInstructions_triggered(){
InstructionsDialog *inst = new InstructionsDialog;
inst->setWindowTitle("Instructions");
inst->show();
qDebug() << "Action->HelpInstructions";
}
<|endoftext|>
|
<commit_before>#include <QFileDialog>
#include <QImageReader>
#include <QLabel>
#include <QMessageBox>
#include "canvaswidget.h"
#include "mainwindow.h"
#include "ui_mainwindow.h"
MainWindow::MainWindow(QWidget* parent) :
QMainWindow(parent),
ui(new Ui::MainWindow)
{
ui->setupUi(this);
setAttribute(Qt::WA_QuitOnClose);
setWindowState(windowState() | Qt::WindowMaximized);
setWindowTitle(appName());
QActionGroup* modeActionGroup = new QActionGroup(this);
setEtalonAction = new QAction(QIcon(":/pictures/etalon.png"), QString::fromUtf8("Задание эталона"), modeActionGroup);
measureSegmentLengthAction = new QAction(QIcon(":/pictures/segment_length.png"), QString::fromUtf8("Измерение длин отрезков"), modeActionGroup);
measurePolylineLengthAction = new QAction(QIcon(":/pictures/polyline_length.png"), QString::fromUtf8("Измерение длин кривых"), modeActionGroup);
measureClosedPolylineLengthAction = new QAction(QIcon(":/pictures/closed_polyline_length.png"), QString::fromUtf8("Измерение длин замкнутых кривых"), modeActionGroup);
measureRectangleAreaAction = new QAction(QIcon(":/pictures/rectangle_area.png"), QString::fromUtf8("Измерение площадей прямоугольников"), modeActionGroup);
measurePolygonAreaAction = new QAction(QIcon(":/pictures/polygon_area.png"), QString::fromUtf8("Измерение площадей многоугольников"), modeActionGroup);
foreach (QAction* action, modeActionGroup->actions())
action->setCheckable(true);
setEtalonAction->setChecked(true);
ui->mainToolBar->addActions(modeActionGroup->actions());
ui->mainToolBar->setIconSize(QSize(32, 32));
ui->mainToolBar->setContextMenuPolicy(Qt::CustomContextMenu);
setMeasurementEnabled(false);
connect(modeActionGroup, SIGNAL(triggered(QAction*)), this, SLOT(updateMode(QAction*)));
QList<QByteArray> supportedFormatsList = QImageReader::supportedImageFormats();
QString supportedFormatsString;
foreach (const QByteArray& format, supportedFormatsList)
supportedFormatsString += "*." + QString(format).toLower() + " ";
QString imageFile = QFileDialog::getOpenFileName (this, QString::fromUtf8("Укажите путь к изображению — ") + appName(),
QString(), QString::fromUtf8("Все изображения (%1)").arg(supportedFormatsString));
if (imageFile.isEmpty()) {
exit(EXIT_SUCCESS);
return;
}
QPixmap* image = new QPixmap;
if (!image->load(imageFile)) {
QMessageBox::warning(this, appName(), QString::fromUtf8("Не могу открыть изображение \"%1\".").arg(imageFile));
delete image;
exit(EXIT_SUCCESS);
return;
}
QLabel* statusLabel = new QLabel(this);
QFont labelFont = statusLabel->font();
int newSize = QFontInfo(labelFont).pointSize() * 1.5; // In contrast to ``labelFont.pointSize()'' it always works
labelFont.setPointSize(newSize);
statusLabel->setFont(labelFont);
ui->statusBar->addWidget(statusLabel);
canvasWidget = new CanvasWidget(image, this, ui->containingScrollArea, statusLabel, this);
ui->containingScrollArea->setBackgroundRole(QPalette::Dark);
ui->containingScrollArea->setWidget(canvasWidget);
}
MainWindow::~MainWindow()
{
delete ui;
}
QString MainWindow::appName() const
{
return "AreaMeasurement";
}
void MainWindow::setMode(Mode newMode)
{
canvasWidget->setMode(newMode);
}
void MainWindow::setMeasurementEnabled(bool state)
{
measureSegmentLengthAction ->setEnabled(state);
measurePolylineLengthAction ->setEnabled(state);
measureClosedPolylineLengthAction->setEnabled(state);
measureRectangleAreaAction ->setEnabled(state);
measurePolygonAreaAction ->setEnabled(state);
}
void MainWindow::updateMode(QAction* modeAction)
{
if (modeAction == setEtalonAction)
return setMode(SET_ETALON);
if (modeAction == measureSegmentLengthAction)
return setMode(MEASURE_SEGMENT_LENGTH);
if (modeAction == measurePolylineLengthAction)
return setMode(MEASURE_POLYLINE_LENGTH);
if (modeAction == measureClosedPolylineLengthAction)
return setMode(MEASURE_CLOSED_POLYLINE_LENGTH);
if (modeAction == measureRectangleAreaAction)
return setMode(MEASURE_RECTANGLE_AREA);
if (modeAction == measurePolygonAreaAction)
return setMode(MEASURE_POLYGON_AREA);
abort();
}
<commit_msg>Small fix<commit_after>#include <QFileDialog>
#include <QImageReader>
#include <QLabel>
#include <QMessageBox>
#include "canvaswidget.h"
#include "mainwindow.h"
#include "ui_mainwindow.h"
MainWindow::MainWindow(QWidget* parent) :
QMainWindow(parent),
ui(new Ui::MainWindow)
{
ui->setupUi(this);
setAttribute(Qt::WA_QuitOnClose);
setWindowState(windowState() | Qt::WindowMaximized);
setWindowTitle(appName());
QActionGroup* modeActionGroup = new QActionGroup(this);
setEtalonAction = new QAction(QIcon(":/pictures/etalon.png"), QString::fromUtf8("Задание эталона"), modeActionGroup);
measureSegmentLengthAction = new QAction(QIcon(":/pictures/segment_length.png"), QString::fromUtf8("Измерение длин отрезков"), modeActionGroup);
measurePolylineLengthAction = new QAction(QIcon(":/pictures/polyline_length.png"), QString::fromUtf8("Измерение длин кривых"), modeActionGroup);
measureClosedPolylineLengthAction = new QAction(QIcon(":/pictures/closed_polyline_length.png"), QString::fromUtf8("Измерение длин замкнутых кривых"), modeActionGroup);
measureRectangleAreaAction = new QAction(QIcon(":/pictures/rectangle_area.png"), QString::fromUtf8("Измерение площадей прямоугольников"), modeActionGroup);
measurePolygonAreaAction = new QAction(QIcon(":/pictures/polygon_area.png"), QString::fromUtf8("Измерение площадей многоугольников"), modeActionGroup);
foreach (QAction* action, modeActionGroup->actions())
action->setCheckable(true);
setEtalonAction->setChecked(true);
ui->mainToolBar->addActions(modeActionGroup->actions());
ui->mainToolBar->setIconSize(QSize(32, 32));
ui->mainToolBar->setContextMenuPolicy(Qt::PreventContextMenu);
setMeasurementEnabled(false);
connect(modeActionGroup, SIGNAL(triggered(QAction*)), this, SLOT(updateMode(QAction*)));
QList<QByteArray> supportedFormatsList = QImageReader::supportedImageFormats();
QString supportedFormatsString;
foreach (const QByteArray& format, supportedFormatsList)
supportedFormatsString += "*." + QString(format).toLower() + " ";
QString imageFile = QFileDialog::getOpenFileName (this, QString::fromUtf8("Укажите путь к изображению — ") + appName(),
QString(), QString::fromUtf8("Все изображения (%1)").arg(supportedFormatsString));
if (imageFile.isEmpty()) {
exit(EXIT_SUCCESS);
return;
}
QPixmap* image = new QPixmap;
if (!image->load(imageFile)) {
QMessageBox::warning(this, appName(), QString::fromUtf8("Не могу открыть изображение \"%1\".").arg(imageFile));
delete image;
exit(EXIT_SUCCESS);
return;
}
QLabel* statusLabel = new QLabel(this);
QFont labelFont = statusLabel->font();
int newSize = QFontInfo(labelFont).pointSize() * 1.5; // In contrast to ``labelFont.pointSize()'' it always works
labelFont.setPointSize(newSize);
statusLabel->setFont(labelFont);
ui->statusBar->addWidget(statusLabel);
canvasWidget = new CanvasWidget(image, this, ui->containingScrollArea, statusLabel, this);
ui->containingScrollArea->setBackgroundRole(QPalette::Dark);
ui->containingScrollArea->setWidget(canvasWidget);
}
MainWindow::~MainWindow()
{
delete ui;
}
QString MainWindow::appName() const
{
return "AreaMeasurement";
}
void MainWindow::setMode(Mode newMode)
{
canvasWidget->setMode(newMode);
}
void MainWindow::setMeasurementEnabled(bool state)
{
measureSegmentLengthAction ->setEnabled(state);
measurePolylineLengthAction ->setEnabled(state);
measureClosedPolylineLengthAction->setEnabled(state);
measureRectangleAreaAction ->setEnabled(state);
measurePolygonAreaAction ->setEnabled(state);
}
void MainWindow::updateMode(QAction* modeAction)
{
if (modeAction == setEtalonAction)
return setMode(SET_ETALON);
if (modeAction == measureSegmentLengthAction)
return setMode(MEASURE_SEGMENT_LENGTH);
if (modeAction == measurePolylineLengthAction)
return setMode(MEASURE_POLYLINE_LENGTH);
if (modeAction == measureClosedPolylineLengthAction)
return setMode(MEASURE_CLOSED_POLYLINE_LENGTH);
if (modeAction == measureRectangleAreaAction)
return setMode(MEASURE_RECTANGLE_AREA);
if (modeAction == measurePolygonAreaAction)
return setMode(MEASURE_POLYGON_AREA);
abort();
}
<|endoftext|>
|
<commit_before>#include "mainwindow.h"
#include "ui_mainwindow.h"
#include <QObject>
#include <QtWidgets>
MainWindow::MainWindow(QWidget *parent) :
QMainWindow(parent),
_ui(new Ui::MainWindow),
_mainWindowIcon(":/Resources/icons/mainWindowIcon.jpg"),
_isPlaying(false),
_prevButtonIcon(":/Resources/icons/Button-Prev-icon.png"),
_playButtonPlayIcon(":/Resources/icons/Button-Play-icon.png"),
_playButtonPauseIcon(":/Resources/icons/Button-Pause-icon.png"),
_nextButtonIcon(":/Resources/icons/Button-Next-icon.png"),
_filename(new QLabel(this)),
_player(0),
_playlist(new QMediaPlaylist(this))
{
_ui->setupUi(this);
setWindowIcon(_mainWindowIcon);
setWindowTitle("Music Player");
setFixedWidth(8*72);
setFixedHeight(5*72);
/****************SETTING UP MENUS*********************/
QWidget *topFiller = new QWidget;
topFiller->setSizePolicy(QSizePolicy::Expanding, QSizePolicy::Expanding);
#ifdef Q_OS_SYMBIAN
_infoLabel = new QLabel(tr("<i>Choose a menu option</i>"));
#else
_infoLabel = new QLabel(tr("<i>Choose a menu option, or right-click to "
"invoke a context menu</i>"));
#endif
_infoLabel->setFrameStyle(QFrame::StyledPanel | QFrame::Sunken);
_infoLabel->setAlignment(Qt::AlignCenter);
QWidget *bottomFiller = new QWidget;
bottomFiller->setSizePolicy(QSizePolicy::Expanding, QSizePolicy::Expanding);
QVBoxLayout *layout = new QVBoxLayout;
layout->setMargin(5);
layout->addWidget(topFiller);
layout->addWidget(_infoLabel);
layout->addWidget(bottomFiller);
createActions();
createMenus();
/************SETTING UP STATUS BAR********************/
#ifndef Q_OS_SYMBIAN
QString message = tr("A context menu is available by right-clicking");
statusBar()->showMessage(message);
#endif
setupButtons();
/*************SETTING UP VOLUME SLIDER******************/
_volumeLabel = new QLabel;
_volumeLabel->setText(tr("<b>Volume:</b>"));
_volumeLabel->setParent(this);
_volumeSlider = new QSlider(Qt::Horizontal);
_volumeSlider->setParent(this);
_volumeSlider->setMinimum(0);
_volumeSlider->setMaximum(100);
_volumeSlider->setSliderPosition(_volumeSlider->maximum());
_volumeSlider->setSingleStep(10);
_volumeSlider->setGeometry
(
_nextButton.geometry().x(),
_playButton.geometry().y()-20,
_playButton.width(),
20
);
connect(_volumeSlider,SIGNAL(valueChanged(int)),this,SLOT(_volumeSliderValueChanged()));
/*************SETTING UP VOLUME LABEL******************/
_volumeLabel->setGeometry
(
_volumeSlider->geometry().x()-60,
_volumeSlider->geometry().y(),
60,
_volumeSlider->height()
);
_volumeLabel->show();
_volumeSlider->show();
/************SETTING UP FILENAME LABEL*********/
_filename->setGeometry
(
_volumeLabel->geometry().x()-120,
_volumeLabel->geometry().y(),
_volumeLabel->geometry().width(),
_volumeLabel->geometry().height()
);
_filename->show();
/******************SOUND CODE******************/
_player = new QMediaPlayer;
_player->setVolume(100);
}
MainWindow::~MainWindow()
{
delete _ui;
}
/***********PLAY BUTTON FUNCTION SLOT***********/
void MainWindow::_playButtonIsPressed ()
{
_player->pause();
if(!_isPlaying)
{
_playButton.setIcon(_playButtonPauseIcon);
_player->play();
}
else _playButton.setIcon(_playButtonPlayIcon);
_isPlaying = !_isPlaying;
}
/***********NEXT BUTTON FUNCTION SLOT***********/
void MainWindow::_nextButtonIsPressed ()
{
_playlist->next();
_filename->setText
(
_playlist->media(_playlist->currentIndex()).canonicalUrl().fileName()
);
}
/***********PREV BUTTON FUNCTION SLOT***********/
void MainWindow::_prevButtonIsPressed ()
{
_playlist->previous();
}
/***********VOLUME SLIDER FUNCTION SLOT***********/
void MainWindow::_volumeSliderValueChanged()
{
_player->setVolume(_volumeSlider->value());
}
/**************MENU OPTION SLOTS****************/
void MainWindow::contextMenuEvent(QContextMenuEvent *event)
{
QMenu menu(this);
menu.addAction(_playAct);
menu.addAction(_nextSongAct);
menu.addAction(_previousSongAct);
menu.exec(event->globalPos());
}
void MainWindow::play()
{
_playButtonIsPressed();
}
void MainWindow::nextSong()
{
_nextButtonIsPressed();
}
void MainWindow::previousSong()
{
_prevButtonIsPressed();
}
void MainWindow::open()
{
QFileDialog openFileDialog(this);
openFileDialog.setNameFilter(tr("Audio (*.mp3 *.mp4 *.wav *.flac *.ogg)"));
openFileDialog.setViewMode(QFileDialog::List);
openFileDialog.setFileMode(QFileDialog::ExistingFiles);
openFileDialog.setDirectory("../cs372-FinalProject/");
QStringList fileNames;
if(openFileDialog.exec())
fileNames = openFileDialog.selectedFiles();
QList<QMediaContent> playListFiles;
for(QStringList::iterator file = fileNames.begin(); file < fileNames.end(); file++)
playListFiles.append(QMediaContent(QUrl::fromLocalFile(*file)));
_playlist->clear();
_playlist->addMedia(playListFiles);
_playlist->setPlaybackMode(QMediaPlaylist::Loop);
_player->stop();
_player->setPlaylist(_playlist);
_player->setPosition(0);
if(_isPlaying) _playButtonIsPressed();
}
void MainWindow::about()
{
_infoLabel->setText(tr("Invoked <b>Help|About</b>"));
QMessageBox::about(this, tr("About Menu"),
tr("Hit Play to Play Mooxzikz. "
"Open to Open More Moozikz."));
//TODO: docoomentimgz
}
void MainWindow::aboutQt()
{
_infoLabel->setText(tr("Invoked <b>Help|About Qt</b>"));
}
void MainWindow::createActions()
{
_openAct = new QAction(tr("&Open..."), this);
_openAct->setStatusTip(tr("Open an existing file"));
connect(_openAct, SIGNAL(triggered()), this, SLOT(open()));
_exitAct = new QAction(tr("E&xit"), this);
_exitAct->setStatusTip(tr("Exit the application"));
connect(_exitAct, SIGNAL(triggered()), this, SLOT(close()));
_playAct = new QAction(tr("&Play/Pause"), this);
_playAct->setStatusTip(tr("Play a song"));
connect(_playAct, SIGNAL(triggered()), this, SLOT(play()));
_nextSongAct = new QAction(tr("&Next Song"), this);
_nextSongAct->setStatusTip(tr("Switches to the Next Song"));
connect(_nextSongAct, SIGNAL(triggered()), this, SLOT(nextSong()));
_previousSongAct = new QAction(tr("&Previous Song"), this);
_previousSongAct->setStatusTip(tr("Switches to the Previous Song"));
connect(_previousSongAct, SIGNAL(triggered()), this, SLOT(previousSong()));
_aboutAct = new QAction(tr("&About"), this);
_aboutAct->setStatusTip(tr("Show the application's About box"));
connect(_aboutAct, SIGNAL(triggered()), this, SLOT(about()));
_aboutQtAct = new QAction(tr("About &Qt"), this);
_aboutQtAct->setStatusTip(tr("Show the Qt library's About box"));
connect(_aboutQtAct, SIGNAL(triggered()), qApp, SLOT(aboutQt()));
connect(_aboutQtAct, SIGNAL(triggered()), this, SLOT(aboutQt()));
}
void MainWindow::createMenus()
{
_fileMenu = menuBar()->addMenu(tr("&File"));
_fileMenu->addAction(_openAct);
_fileMenu->addSeparator();
_fileMenu->addAction(_exitAct);
_playMenu = menuBar()->addMenu(tr("&Play"));
_playMenu->addSeparator();
_playMenu->addAction(_playAct);
_playMenu->addAction(_nextSongAct);
_playMenu->addAction(_previousSongAct);
_helpMenu = menuBar()->addMenu(tr("&Help"));
_helpMenu->addAction(_aboutAct);
_helpMenu->addAction(_aboutQtAct);
}
void MainWindow::setupButtons()
{
const int mediaButtonYCoordinate =
(
height()- ((width()/5) + statusBar()->geometry().height() - 8)
);
//Setup signals
connect(&_prevButton, SIGNAL(clicked()), this, SLOT(_prevButtonIsPressed()));
connect(&_playButton, SIGNAL(clicked()), this, SLOT(_playButtonIsPressed()));
connect(&_nextButton, SIGNAL(clicked()), this, SLOT(_nextButtonIsPressed()));
//Setup parents
_prevButton.setParent(this);
_playButton.setParent(this);
_nextButton.setParent(this);
//Setup positions
_prevButton.setGeometry
(
0,
mediaButtonYCoordinate,
width()/5,
width()/5
);
_playButton.setGeometry
(
_prevButton.width()*2,
mediaButtonYCoordinate,
width()/5,
width()/5
);
_nextButton.setGeometry
(
_playButton.width()*4,
mediaButtonYCoordinate,
width()/5,
width()/5
);
//Setup icons
_prevButton.setIcon(_prevButtonIcon);
_prevButton.setIconSize(QSize(_prevButton.height(),_prevButton.height()));
_playButton.setIcon(_playButtonPlayIcon);
_playButton.setIconSize(QSize(_playButton.height(),_playButton.height()));
_nextButton.setIcon(_nextButtonIcon);
_nextButton.setIconSize(QSize(_nextButton.height(),_nextButton.height()));
//Show them off
_prevButton.show();
_playButton.show();
_nextButton.show();
}
<commit_msg>Fixed issue with _filename display placement.<commit_after>#include "mainwindow.h"
#include "ui_mainwindow.h"
#include <QObject>
#include <QtWidgets>
MainWindow::MainWindow(QWidget *parent) :
QMainWindow(parent),
_ui(new Ui::MainWindow),
_mainWindowIcon(":/Resources/icons/mainWindowIcon.jpg"),
_isPlaying(false),
_prevButtonIcon(":/Resources/icons/Button-Prev-icon.png"),
_playButtonPlayIcon(":/Resources/icons/Button-Play-icon.png"),
_playButtonPauseIcon(":/Resources/icons/Button-Pause-icon.png"),
_nextButtonIcon(":/Resources/icons/Button-Next-icon.png"),
_filename(new QLabel(this)),
_player(0),
_playlist(new QMediaPlaylist(this))
{
_ui->setupUi(this);
setWindowIcon(_mainWindowIcon);
setWindowTitle("Music Player");
setFixedWidth(8*72);
setFixedHeight(5*72);
/****************SETTING UP MENUS*********************/
QWidget *topFiller = new QWidget;
topFiller->setSizePolicy(QSizePolicy::Expanding, QSizePolicy::Expanding);
#ifdef Q_OS_SYMBIAN
_infoLabel = new QLabel(tr("<i>Choose a menu option</i>"));
#else
_infoLabel = new QLabel(tr("<i>Choose a menu option, or right-click to "
"invoke a context menu</i>"));
#endif
_infoLabel->setFrameStyle(QFrame::StyledPanel | QFrame::Sunken);
_infoLabel->setAlignment(Qt::AlignCenter);
QWidget *bottomFiller = new QWidget;
bottomFiller->setSizePolicy(QSizePolicy::Expanding, QSizePolicy::Expanding);
QVBoxLayout *layout = new QVBoxLayout;
layout->setMargin(5);
layout->addWidget(topFiller);
layout->addWidget(_infoLabel);
layout->addWidget(bottomFiller);
createActions();
createMenus();
/************SETTING UP STATUS BAR********************/
#ifndef Q_OS_SYMBIAN
QString message = tr("A context menu is available by right-clicking");
statusBar()->showMessage(message);
#endif
setupButtons();
/*************SETTING UP VOLUME SLIDER******************/
_volumeLabel = new QLabel;
_volumeLabel->setText(tr("<b>Volume:</b>"));
_volumeLabel->setParent(this);
_volumeSlider = new QSlider(Qt::Horizontal);
_volumeSlider->setParent(this);
_volumeSlider->setMinimum(0);
_volumeSlider->setMaximum(100);
_volumeSlider->setSliderPosition(_volumeSlider->maximum());
_volumeSlider->setSingleStep(10);
_volumeSlider->setGeometry
(
_nextButton.geometry().x(),
_playButton.geometry().y()-20,
_playButton.width(),
20
);
connect(_volumeSlider,SIGNAL(valueChanged(int)),this,SLOT(_volumeSliderValueChanged()));
/*************SETTING UP VOLUME LABEL******************/
_volumeLabel->setGeometry
(
_volumeSlider->geometry().x()-60,
_volumeSlider->geometry().y(),
60,
_volumeSlider->height()
);
_volumeLabel->show();
_volumeSlider->show();
/************SETTING UP FILENAME LABEL*********/
_filename->setGeometry
(
0,
_volumeLabel->geometry().y(),
_volumeLabel->geometry().x(),
_volumeLabel->geometry().height()
);
_filename->show();
/******************SOUND CODE******************/
_player = new QMediaPlayer;
_player->setVolume(100);
}
MainWindow::~MainWindow()
{
delete _ui;
}
/***********PLAY BUTTON FUNCTION SLOT***********/
void MainWindow::_playButtonIsPressed ()
{
_player->pause();
if(!_isPlaying)
{
_playButton.setIcon(_playButtonPauseIcon);
_player->play();
_filename->setText
(
_playlist->media(_playlist->currentIndex()).canonicalUrl().fileName()
);
}
else _playButton.setIcon(_playButtonPlayIcon);
_isPlaying = !_isPlaying;
}
/***********NEXT BUTTON FUNCTION SLOT***********/
void MainWindow::_nextButtonIsPressed ()
{
_playlist->next();
_filename->setText
(
_playlist->media(_playlist->currentIndex()).canonicalUrl().fileName()
);
}
/***********PREV BUTTON FUNCTION SLOT***********/
void MainWindow::_prevButtonIsPressed ()
{
_playlist->previous();
_filename->setText
(
_playlist->media(_playlist->currentIndex()).canonicalUrl().fileName()
);
}
/***********VOLUME SLIDER FUNCTION SLOT***********/
void MainWindow::_volumeSliderValueChanged()
{
_player->setVolume(_volumeSlider->value());
}
/**************MENU OPTION SLOTS****************/
void MainWindow::contextMenuEvent(QContextMenuEvent *event)
{
QMenu menu(this);
menu.addAction(_playAct);
menu.addAction(_nextSongAct);
menu.addAction(_previousSongAct);
menu.exec(event->globalPos());
}
void MainWindow::play()
{
_playButtonIsPressed();
}
void MainWindow::nextSong()
{
_nextButtonIsPressed();
}
void MainWindow::previousSong()
{
_prevButtonIsPressed();
}
void MainWindow::open()
{
QFileDialog openFileDialog(this);
openFileDialog.setNameFilter(tr("Audio (*.mp3 *.mp4 *.wav *.flac *.ogg)"));
openFileDialog.setViewMode(QFileDialog::List);
openFileDialog.setFileMode(QFileDialog::ExistingFiles);
openFileDialog.setDirectory("../cs372-FinalProject/");
QStringList fileNames;
if(openFileDialog.exec())
fileNames = openFileDialog.selectedFiles();
QList<QMediaContent> playListFiles;
for(QStringList::iterator file = fileNames.begin(); file < fileNames.end(); file++)
playListFiles.append(QMediaContent(QUrl::fromLocalFile(*file)));
_playlist->clear();
_playlist->addMedia(playListFiles);
_playlist->setPlaybackMode(QMediaPlaylist::Loop);
_player->stop();
_player->setPlaylist(_playlist);
_player->setPosition(0);
if(_isPlaying) _playButtonIsPressed();
}
void MainWindow::about()
{
_infoLabel->setText(tr("Invoked <b>Help|About</b>"));
QMessageBox::about(this, tr("About Menu"),
tr("Hit Play to Play Mooxzikz. "
"Open to Open More Moozikz."));
//TODO: docoomentimgz
}
void MainWindow::aboutQt()
{
_infoLabel->setText(tr("Invoked <b>Help|About Qt</b>"));
}
void MainWindow::createActions()
{
_openAct = new QAction(tr("&Open..."), this);
_openAct->setStatusTip(tr("Open an existing file"));
connect(_openAct, SIGNAL(triggered()), this, SLOT(open()));
_exitAct = new QAction(tr("E&xit"), this);
_exitAct->setStatusTip(tr("Exit the application"));
connect(_exitAct, SIGNAL(triggered()), this, SLOT(close()));
_playAct = new QAction(tr("&Play/Pause"), this);
_playAct->setStatusTip(tr("Play a song"));
connect(_playAct, SIGNAL(triggered()), this, SLOT(play()));
_nextSongAct = new QAction(tr("&Next Song"), this);
_nextSongAct->setStatusTip(tr("Switches to the Next Song"));
connect(_nextSongAct, SIGNAL(triggered()), this, SLOT(nextSong()));
_previousSongAct = new QAction(tr("&Previous Song"), this);
_previousSongAct->setStatusTip(tr("Switches to the Previous Song"));
connect(_previousSongAct, SIGNAL(triggered()), this, SLOT(previousSong()));
_aboutAct = new QAction(tr("&About"), this);
_aboutAct->setStatusTip(tr("Show the application's About box"));
connect(_aboutAct, SIGNAL(triggered()), this, SLOT(about()));
_aboutQtAct = new QAction(tr("About &Qt"), this);
_aboutQtAct->setStatusTip(tr("Show the Qt library's About box"));
connect(_aboutQtAct, SIGNAL(triggered()), qApp, SLOT(aboutQt()));
connect(_aboutQtAct, SIGNAL(triggered()), this, SLOT(aboutQt()));
}
void MainWindow::createMenus()
{
_fileMenu = menuBar()->addMenu(tr("&File"));
_fileMenu->addAction(_openAct);
_fileMenu->addSeparator();
_fileMenu->addAction(_exitAct);
_playMenu = menuBar()->addMenu(tr("&Play"));
_playMenu->addSeparator();
_playMenu->addAction(_playAct);
_playMenu->addAction(_nextSongAct);
_playMenu->addAction(_previousSongAct);
_helpMenu = menuBar()->addMenu(tr("&Help"));
_helpMenu->addAction(_aboutAct);
_helpMenu->addAction(_aboutQtAct);
}
void MainWindow::setupButtons()
{
const int mediaButtonYCoordinate =
(
height()- ((width()/5) + statusBar()->geometry().height() - 8)
);
//Setup signals
connect(&_prevButton, SIGNAL(clicked()), this, SLOT(_prevButtonIsPressed()));
connect(&_playButton, SIGNAL(clicked()), this, SLOT(_playButtonIsPressed()));
connect(&_nextButton, SIGNAL(clicked()), this, SLOT(_nextButtonIsPressed()));
//Setup parents
_prevButton.setParent(this);
_playButton.setParent(this);
_nextButton.setParent(this);
//Setup positions
_prevButton.setGeometry
(
0,
mediaButtonYCoordinate,
width()/5,
width()/5
);
_playButton.setGeometry
(
_prevButton.width()*2,
mediaButtonYCoordinate,
width()/5,
width()/5
);
_nextButton.setGeometry
(
_playButton.width()*4,
mediaButtonYCoordinate,
width()/5,
width()/5
);
//Setup icons
_prevButton.setIcon(_prevButtonIcon);
_prevButton.setIconSize(QSize(_prevButton.height(),_prevButton.height()));
_playButton.setIcon(_playButtonPlayIcon);
_playButton.setIconSize(QSize(_playButton.height(),_playButton.height()));
_nextButton.setIcon(_nextButtonIcon);
_nextButton.setIconSize(QSize(_nextButton.height(),_nextButton.height()));
//Show them off
_prevButton.show();
_playButton.show();
_nextButton.show();
}
<|endoftext|>
|
<commit_before>#include "mainwindow.hpp"
#include "screenshotter.hpp"
#include "screenshotutil.hpp"
#include "ui_mainwindow.h"
#include <QAction>
#include <QCloseEvent>
#include <QCoreApplication>
#include <QDoubleSpinBox>
#include <QListWidgetItem>
#include <QMenu>
#include <QStatusBar>
#include <QSystemTrayIcon>
#include <QTimer>
#include <functional>
#include <hotkeying.hpp>
#include <settings.hpp>
#include <uploaders/uploadersingleton.hpp>
MainWindow *MainWindow::instance;
void addHotkeyItem(QString text, QString name, std::function<void()> *func)
{
QListWidgetItem *item = new QListWidgetItem(text, MainWindow::inst()->ui->hotkeys);
item->setData(Qt::UserRole + 1, name);
MainWindow::inst()->fncs.insert(name, func);
hotkeying::load(name, *func);
}
MainWindow::MainWindow(QWidget *parent) : QMainWindow(parent), ui(new Ui::MainWindow)
{
instance = this;
ui->setupUi(this);
setWindowIcon(QIcon(":/icons/icon.jpg"));
tray = new QSystemTrayIcon(windowIcon(), this);
tray->setToolTip("KShare");
tray->setVisible(true);
QMenu *menu = new QMenu(this);
QAction *quit = new QAction("Quit", this);
QAction *shtoggle = new QAction("Show/Hide", this);
QAction *fullscreen = new QAction("Take fullscreen shot", this);
QAction *area = new QAction("Take area shot", this);
menu->addActions({ quit, shtoggle });
menu->addSeparator();
menu->addActions({ fullscreen, area });
connect(quit, &QAction::triggered, this, &MainWindow::quit);
connect(shtoggle, &QAction::triggered, this, &MainWindow::toggleVisible);
connect(fullscreen, &QAction::triggered, this, &MainWindow::on_actionFullscreen_triggered);
connect(area, &QAction::triggered, this, &MainWindow::on_actionArea_triggered);
tray->setContextMenu(menu);
ui->uploaderList->setSelectionBehavior(QAbstractItemView::SelectRows);
ui->uploaderList->setSelectionMode(QAbstractItemView::SingleSelection);
// Add items to uploader selection
for (Uploader *u : UploaderSingleton::inst().uploaderList()) newUploader(u);
connect(&UploaderSingleton::inst(), &UploaderSingleton::newUploader, this, &MainWindow::newUploader);
// Set filename scheme
if ((settings::settings().contains("fileFormat")))
setScheme(settings::settings().value("fileFormat").toString());
else
setScheme("Screenshot %(yyyy-MM-dd HH:mm:ss)date");
auto errors = UploaderSingleton::inst().errors();
if (errors.length() == 1)
statusBar()->showMessage(errors.at(0).what());
else
statusBar()->showMessage(QString("Errors visible in console (if present). Count: " + QString::number(errors.size())));
// Set delay
if ((settings::settings().contains("delay")))
ui->delay->setValue(settings::settings().value("delay").toDouble());
else
ui->delay->setValue(0.25);
// keys are hot, wait what
hotkeying::load("fullscreen", [this] { on_actionFullscreen_triggered(); });
hotkeying::load("area", [this] { on_actionArea_triggered(); });
ui->hotkeys->setSelectionMode(QListWidget::SingleSelection);
addHotkeyItem("Fullscreen image", "fullscreen", new std::function<void()>([&] { on_actionFullscreen_triggered(); }));
addHotkeyItem("Area image", "area", new std::function<void()>([&] { on_actionArea_triggered(); }));
}
MainWindow::~MainWindow()
{
delete ui;
}
void MainWindow::setScheme(QString scheme)
{
ui->nameScheme->setText(scheme);
}
QDoubleSpinBox *MainWindow::delay()
{
return ui->delay;
}
MainWindow *MainWindow::inst()
{
return instance;
}
void MainWindow::closeEvent(QCloseEvent *event)
{
event->ignore();
QTimer::singleShot(0, this, &MainWindow::hide);
}
void MainWindow::quit()
{
QCoreApplication::quit();
}
void MainWindow::toggleVisible()
{
this->setVisible(!this->isVisible());
}
void MainWindow::newUploader(Uploader *u)
{
QListWidgetItem *item = new QListWidgetItem(u->name());
item->setToolTip(u->description());
ui->uploaderList->addItem(item);
if (u->name() == UploaderSingleton::inst().selectedUploader()) item->setSelected(true);
}
void MainWindow::on_actionQuit_triggered()
{
quit();
}
void MainWindow::on_actionFullscreen_triggered()
{
screenshotter::fullscreenDelayed();
}
void MainWindow::on_actionArea_triggered()
{
screenshotter::areaDelayed();
}
void MainWindow::on_uploaderList_clicked(const QModelIndex &)
{
QList<QListWidgetItem *> index = ui->uploaderList->selectedItems();
if (index.size() == 1)
{
UploaderSingleton::inst().set(index.at(0)->text());
}
}
void MainWindow::on_nameScheme_textEdited(const QString &arg1)
{
settings::settings().setValue("fileFormat", arg1);
}
void MainWindow::on_delay_valueChanged(double arg1)
{
settings::settings().setValue("delay", arg1);
}
void MainWindow::on_hotkeys_doubleClicked(const QModelIndex &)
{
if (ui->hotkeys->selectedItems().length() == 1)
{
QListWidgetItem *i = ui->hotkeys->selectedItems().at(0);
QString str = i->data(Qt::UserRole + 1).toString();
QString seq = QInputDialog::getText(ui->centralWidget, "Hotkey Input", "Insert hotkey:", QLineEdit::Normal,
hotkeying::sequence(str));
if (hotkeying::valid(seq)) hotkeying::hotkey(str, QKeySequence(seq), *fncs.value(str));
}
}
<commit_msg>Oops pt 3<commit_after>#include "mainwindow.hpp"
#include "screenshotter.hpp"
#include "screenshotutil.hpp"
#include "ui_mainwindow.h"
#include <QAction>
#include <QCloseEvent>
#include <QCoreApplication>
#include <QDoubleSpinBox>
#include <QInputDialog>
#include <QListWidgetItem>
#include <QMenu>
#include <QStatusBar>
#include <QSystemTrayIcon>
#include <QTimer>
#include <functional>
#include <hotkeying.hpp>
#include <settings.hpp>
#include <uploaders/uploadersingleton.hpp>
MainWindow *MainWindow::instance;
void addHotkeyItem(QString text, QString name, std::function<void()> *func)
{
QListWidgetItem *item = new QListWidgetItem(text, MainWindow::inst()->ui->hotkeys);
item->setData(Qt::UserRole + 1, name);
MainWindow::inst()->fncs.insert(name, func);
hotkeying::load(name, *func);
}
MainWindow::MainWindow(QWidget *parent) : QMainWindow(parent), ui(new Ui::MainWindow)
{
instance = this;
ui->setupUi(this);
setWindowIcon(QIcon(":/icons/icon.jpg"));
tray = new QSystemTrayIcon(windowIcon(), this);
tray->setToolTip("KShare");
tray->setVisible(true);
QMenu *menu = new QMenu(this);
QAction *quit = new QAction("Quit", this);
QAction *shtoggle = new QAction("Show/Hide", this);
QAction *fullscreen = new QAction("Take fullscreen shot", this);
QAction *area = new QAction("Take area shot", this);
menu->addActions({ quit, shtoggle });
menu->addSeparator();
menu->addActions({ fullscreen, area });
connect(quit, &QAction::triggered, this, &MainWindow::quit);
connect(shtoggle, &QAction::triggered, this, &MainWindow::toggleVisible);
connect(fullscreen, &QAction::triggered, this, &MainWindow::on_actionFullscreen_triggered);
connect(area, &QAction::triggered, this, &MainWindow::on_actionArea_triggered);
tray->setContextMenu(menu);
ui->uploaderList->setSelectionBehavior(QAbstractItemView::SelectRows);
ui->uploaderList->setSelectionMode(QAbstractItemView::SingleSelection);
// Add items to uploader selection
for (Uploader *u : UploaderSingleton::inst().uploaderList()) newUploader(u);
connect(&UploaderSingleton::inst(), &UploaderSingleton::newUploader, this, &MainWindow::newUploader);
// Set filename scheme
if ((settings::settings().contains("fileFormat")))
setScheme(settings::settings().value("fileFormat").toString());
else
setScheme("Screenshot %(yyyy-MM-dd HH:mm:ss)date");
auto errors = UploaderSingleton::inst().errors();
if (errors.length() == 1)
statusBar()->showMessage(errors.at(0).what());
else
statusBar()->showMessage(QString("Errors visible in console (if present). Count: " + QString::number(errors.size())));
// Set delay
if ((settings::settings().contains("delay")))
ui->delay->setValue(settings::settings().value("delay").toDouble());
else
ui->delay->setValue(0.25);
// keys are hot, wait what
hotkeying::load("fullscreen", [this] { on_actionFullscreen_triggered(); });
hotkeying::load("area", [this] { on_actionArea_triggered(); });
ui->hotkeys->setSelectionMode(QListWidget::SingleSelection);
addHotkeyItem("Fullscreen image", "fullscreen", new std::function<void()>([&] { on_actionFullscreen_triggered(); }));
addHotkeyItem("Area image", "area", new std::function<void()>([&] { on_actionArea_triggered(); }));
}
MainWindow::~MainWindow()
{
delete ui;
}
void MainWindow::setScheme(QString scheme)
{
ui->nameScheme->setText(scheme);
}
QDoubleSpinBox *MainWindow::delay()
{
return ui->delay;
}
MainWindow *MainWindow::inst()
{
return instance;
}
void MainWindow::closeEvent(QCloseEvent *event)
{
event->ignore();
QTimer::singleShot(0, this, &MainWindow::hide);
}
void MainWindow::quit()
{
QCoreApplication::quit();
}
void MainWindow::toggleVisible()
{
this->setVisible(!this->isVisible());
}
void MainWindow::newUploader(Uploader *u)
{
QListWidgetItem *item = new QListWidgetItem(u->name());
item->setToolTip(u->description());
ui->uploaderList->addItem(item);
if (u->name() == UploaderSingleton::inst().selectedUploader()) item->setSelected(true);
}
void MainWindow::on_actionQuit_triggered()
{
quit();
}
void MainWindow::on_actionFullscreen_triggered()
{
screenshotter::fullscreenDelayed();
}
void MainWindow::on_actionArea_triggered()
{
screenshotter::areaDelayed();
}
void MainWindow::on_uploaderList_clicked(const QModelIndex &)
{
QList<QListWidgetItem *> index = ui->uploaderList->selectedItems();
if (index.size() == 1)
{
UploaderSingleton::inst().set(index.at(0)->text());
}
}
void MainWindow::on_nameScheme_textEdited(const QString &arg1)
{
settings::settings().setValue("fileFormat", arg1);
}
void MainWindow::on_delay_valueChanged(double arg1)
{
settings::settings().setValue("delay", arg1);
}
void MainWindow::on_hotkeys_doubleClicked(const QModelIndex &)
{
if (ui->hotkeys->selectedItems().length() == 1)
{
QListWidgetItem *i = ui->hotkeys->selectedItems().at(0);
QString str = i->data(Qt::UserRole + 1).toString();
QString seq = QInputDialog::getText(ui->centralWidget, "Hotkey Input", "Insert hotkey:", QLineEdit::Normal,
hotkeying::sequence(str));
if (hotkeying::valid(seq)) hotkeying::hotkey(str, QKeySequence(seq), *fncs.value(str));
}
}
<|endoftext|>
|
<commit_before>#include "actions.h"
#include "componentactions.h"
#include "menus.h"
#include "menuactions.h"
#include "setup.h"
#include "ui_mainwindow.h"
MainWindow::MainWindow(QWidget *parent) :
QMainWindow(parent),
_ui(new Ui::MainWindow),
_mainWindowIcon(":/Resources/icons/mainWindowIcon.png"),
_centralWidget(new QWidget(this)),
_mainLayout(new QVBoxLayout(_centralWidget)),
_isPlaying(false),
_isShuffled(false),
_prevButton(new QPushButton(this)),
_prevButtonIcon(":/Resources/icons/Button-Prev-icon.png"),
_playButton(new QPushButton(this)),
_playButtonPlayIcon(":/Resources/icons/Button-Play-icon.png"),
_playButtonPauseIcon(":/Resources/icons/Button-Pause-icon.png"),
_nextButton(new QPushButton(this)),
_nextButtonIcon(":/Resources/icons/Button-Next-icon.png"),
_helpIcon(":/Resources/icons/Menu-Help-icon.png"),
_infoIcon(":/Resources/icons/Menu-Info-icon.png"),
_openIcon(":/Resources/icons/Menu-Open-icon.png"),
_exitIcon(":/Resources/icons/Menu-Exit-icon.png"),
_qtIcon(":/Resources/icons/Qt-icon.ico"),
_volumeLabel(new QLabel(this)),
_volumeSlider(new QSlider(Qt::Horizontal, this)),
_fileMetadata(new QLabel(this)),
_players(new QVector<QMediaPlayer *>),
_currentPlayer(new QMediaPlayer),
_progressBar(new QProgressBar(this)),
_shuffleButton(new QPushButton),
_playlistViews(new QVector<QListWidget *>),
_currentPlaylistView(new QListWidget),
_playlistTabs(new QTabWidget(this)),
_newPlaylistTabButton(new QPushButton("New Playlist")),
_loopCheckbox(new QCheckBox(this))
{
setWindowIcon(_mainWindowIcon);
setWindowTitle("Music Player");
setCentralWidget(_centralWidget);
/****************SETTING UP STATUS BAR*********************/
QWidget *topFiller = new QWidget;
topFiller->setSizePolicy(QSizePolicy::Expanding, QSizePolicy::Expanding);
#ifdef Q_OS_SYMBIAN
_infoLabel = new QLabel(tr("<i>Choose a menu option</i>"));
#else
_infoLabel = new QLabel(tr("<i>Choose a menu option, or right-click to "
"invoke a context menu</i>"));
#endif
_infoLabel->setFrameStyle(QFrame::StyledPanel | QFrame::Sunken);
_infoLabel->setAlignment(Qt::AlignCenter);
QWidget *bottomFiller = new QWidget;
bottomFiller->setSizePolicy(QSizePolicy::Expanding, QSizePolicy::Expanding);
QVBoxLayout *layout = new QVBoxLayout;
layout->setMargin(5);
layout->addWidget(topFiller);
layout->addWidget(_infoLabel);
layout->addWidget(bottomFiller);
/************SETTING UP STATUS BAR********************/
#ifndef Q_OS_SYMBIAN
QString message = tr("A context menu is available by right-clicking");
statusBar()->showMessage(message);
#endif
_currentPlayer->setVolume(50);
setup();
}
MainWindow::~MainWindow()
{
delete _ui;
}
<commit_msg>Changed check for symbian OS to a check for Android.<commit_after>#include "actions.h"
#include "componentactions.h"
#include "menus.h"
#include "menuactions.h"
#include "setup.h"
#include "ui_mainwindow.h"
MainWindow::MainWindow(QWidget *parent) :
QMainWindow(parent),
_ui(new Ui::MainWindow),
_mainWindowIcon(":/Resources/icons/mainWindowIcon.png"),
_centralWidget(new QWidget(this)),
_mainLayout(new QVBoxLayout(_centralWidget)),
_isPlaying(false),
_isShuffled(false),
_prevButton(new QPushButton(this)),
_prevButtonIcon(":/Resources/icons/Button-Prev-icon.png"),
_playButton(new QPushButton(this)),
_playButtonPlayIcon(":/Resources/icons/Button-Play-icon.png"),
_playButtonPauseIcon(":/Resources/icons/Button-Pause-icon.png"),
_nextButton(new QPushButton(this)),
_nextButtonIcon(":/Resources/icons/Button-Next-icon.png"),
_helpIcon(":/Resources/icons/Menu-Help-icon.png"),
_infoIcon(":/Resources/icons/Menu-Info-icon.png"),
_openIcon(":/Resources/icons/Menu-Open-icon.png"),
_exitIcon(":/Resources/icons/Menu-Exit-icon.png"),
_qtIcon(":/Resources/icons/Qt-icon.ico"),
_volumeLabel(new QLabel(this)),
_volumeSlider(new QSlider(Qt::Horizontal, this)),
_fileMetadata(new QLabel(this)),
_players(new QVector<QMediaPlayer *>),
_currentPlayer(new QMediaPlayer),
_progressBar(new QProgressBar(this)),
_shuffleButton(new QPushButton),
_playlistViews(new QVector<QListWidget *>),
_currentPlaylistView(new QListWidget),
_playlistTabs(new QTabWidget(this)),
_newPlaylistTabButton(new QPushButton("New Playlist")),
_loopCheckbox(new QCheckBox(this))
{
setWindowIcon(_mainWindowIcon);
setWindowTitle("Music Player");
setCentralWidget(_centralWidget);
/****************SETTING UP STATUS BAR*********************/
QWidget *topFiller = new QWidget;
topFiller->setSizePolicy(QSizePolicy::Expanding, QSizePolicy::Expanding);
#ifdef Q_OS_SYMBIAN
_infoLabel = new QLabel(tr("<i>Choose a menu option</i>"));
#else
_infoLabel = new QLabel(tr("<i>Choose a menu option, or right-click to "
"invoke a context menu</i>"));
#endif
_infoLabel->setFrameStyle(QFrame::StyledPanel | QFrame::Sunken);
_infoLabel->setAlignment(Qt::AlignCenter);
QWidget *bottomFiller = new QWidget;
bottomFiller->setSizePolicy(QSizePolicy::Expanding, QSizePolicy::Expanding);
QVBoxLayout *layout = new QVBoxLayout;
layout->setMargin(5);
layout->addWidget(topFiller);
layout->addWidget(_infoLabel);
layout->addWidget(bottomFiller);
/************SETTING UP STATUS BAR********************/
#ifndef __ANDROID__
QString message = tr("A context menu is available by right-clicking");
statusBar()->showMessage(message);
#endif
_currentPlayer->setVolume(50);
setup();
}
MainWindow::~MainWindow()
{
delete _ui;
}
<|endoftext|>
|
<commit_before>/**
* \file
* <!--
* Copyright 2015 Develer S.r.l. (http://www.develer.com/)
* -->
*
* \brief main cutecom-ng window
*
* \author Aurelien Rainone <aurelien@develer.org>
*/
#include <algorithm>
#include <iterator>
#include <QUiLoader>
#include <QLineEdit>
#include <QPropertyAnimation>
#include <QShortcut>
#include "mainwindow.h"
#include "ui_mainwindow.h"
#include "connectdialog.h"
#include "sessionmanager.h"
#include "outputmanager.h"
#include "searchhighlighter.h"
/// line ending char appended to the commands sent to the serial port
const QString LINE_ENDING = "\n";
/// maximum count of document blocks for the bootom output
const int MAX_OUTPUT_LINES = 100;
MainWindow::MainWindow(QWidget *parent) :
QMainWindow(parent),
ui(new Ui::MainWindow),
search_widget(0),
search_input(0)
{
ui->setupUi(this);
// create session and output managers
output_mgr = new OutputManager(this);
session_mgr = new SessionManager(this);
connect_dlg = new ConnectDialog(this);
// show connection dialog
connect(ui->connectButton, &QAbstractButton::clicked, connect_dlg, &ConnectDialog::show);
// handle reception of new data from serial port
connect(session_mgr, &SessionManager::dataReceived, this, &MainWindow::handleDataReceived);
// get data formatted for display and show it in output view
connect(output_mgr, &OutputManager::dataConverted, this, &MainWindow::addDataToView);
// get data formatted for display and show it in output view
connect(ui->inputBox, &HistoryComboBox::lineEntered, this, &MainWindow::handleNewInput);
// clear output manager buffer at session start
connect(session_mgr, &SessionManager::sessionStarted, output_mgr, &OutputManager::clear);
// clear output text
connect(session_mgr, &SessionManager::sessionStarted, ui->mainOutput, &QPlainTextEdit::clear);
connect(session_mgr, &SessionManager::sessionStarted, ui->bottomOutput, &QPlainTextEdit::clear);
// call openSession when user accepts/closes connection dialog
connect(connect_dlg, &ConnectDialog::openDeviceClicked, session_mgr, &SessionManager::openSession);
connect(ui->splitOutputBtn, &QToolButton::clicked, this, &MainWindow::toggleOutputSplitter);
// additional configuration for bottom output
ui->bottomOutput->hide();
ui->bottomOutput->document()->setMaximumBlockCount(MAX_OUTPUT_LINES);
ui->bottomOutput->viewport()->installEventFilter(this);
// load search widget and hide it
QUiLoader loader;
QFile file(":/searchwidget.ui");
file.open(QFile::ReadOnly);
search_widget = loader.load(&file, ui->mainOutput);
Q_ASSERT_X(search_widget, "MainWindow::MainWindow", "error while loading searchwidget.ui");
search_input = search_widget->findChild<QLineEdit*>("searchInput");
Q_ASSERT_X(search_input, "MainWindow::MainWindow", "didn't find searchInput");
search_prev_button = search_widget->findChild<QToolButton*>("previousButton");
search_next_button = search_widget->findChild<QToolButton*>("nextButton");
Q_ASSERT_X(search_prev_button, "MainWindow::MainWindow", "didn't find previousButton");
Q_ASSERT_X(search_next_button, "MainWindow::MainWindow", "didn't find nextButton");
file.close();
search_widget->hide();
// create the search results highlighter and connect search-related signals/slots
SearchHighlighter *search_highlighter = new SearchHighlighter(ui->mainOutput->document());
connect(ui->searchButton, &QToolButton::toggled, this, &MainWindow::showSearchWidget);
connect(search_input, &QLineEdit::textChanged, search_highlighter, &SearchHighlighter::setSearchString);
connect(search_prev_button, &QToolButton::clicked, search_highlighter, &SearchHighlighter::previousOccurence);
connect(search_next_button, &QToolButton::clicked, search_highlighter, &SearchHighlighter::nextOccurence);
connect(search_highlighter, &SearchHighlighter::cursorPosChanged, this, &MainWindow::handleCursosPosChanged);
connect(search_highlighter, &SearchHighlighter::totalOccurencesChanged, this, &MainWindow::handleTotalOccurencesChanged);
search_input->installEventFilter(this);
ui->mainOutput->viewport()->installEventFilter(this);
installEventFilter(this);
}
MainWindow::~MainWindow()
{
delete ui;
}
void MainWindow::handleNewInput(QString entry)
{
// if session is not open, this also keeps user input
if (session_mgr->isSessionOpen())
{
entry.append(LINE_ENDING);
session_mgr->sendToSerial(entry.toLocal8Bit());
ui->inputBox->clearEditText();
}
}
void MainWindow::addDataToView(const QString & textdata)
{
// problem : QTextEdit interprets a '\r' as a new line, so if a buffer ending
// with '\r\n' happens to be cut in the middle, there will be 1 extra
// line jump in the QTextEdit. To prevent we remove ending '\r' and
// prepend them to the next received buffer
// flag indicating that the previously received buffer ended with CR
static bool prev_ends_with_CR = false;
QString newdata;
if (prev_ends_with_CR)
{
// CR was removed at the previous buffer, so now we prepend it
newdata.append('\r');
prev_ends_with_CR = false;
}
if (textdata.length() > 0)
{
QString::const_iterator end_cit = textdata.cend();
if (textdata.endsWith('\r'))
{
// if buffer ends with CR, we don't copy it
end_cit--;
prev_ends_with_CR = true;
}
std::copy(textdata.begin(), end_cit, std::back_inserter(newdata));
}
// record end cursor position before adding text
QTextCursor prev_end_cursor(ui->mainOutput->document());
prev_end_cursor.movePosition(QTextCursor::End);
if (ui->bottomOutput->isVisible())
{
// append text to the top output and stay at current position
QTextCursor cursor(ui->mainOutput->document());
cursor.movePosition(QTextCursor::End);
cursor.insertText(newdata);
}
else
{
// append text to the top output and scroll down
ui->mainOutput->moveCursor(QTextCursor::End);
ui->mainOutput->insertPlainText(newdata);
}
// append text to bottom output and scroll
ui->bottomOutput->moveCursor(QTextCursor::End);
ui->bottomOutput->insertPlainText(newdata);
}
void MainWindow::handleDataReceived(const QByteArray &data)
{
(*output_mgr) << data;
}
void MainWindow::toggleOutputSplitter()
{
ui->bottomOutput->setVisible(!ui->bottomOutput->isVisible());
}
bool MainWindow::eventFilter(QObject *target, QEvent *event)
{
if (target == ui->mainOutput->viewport())
{
if (event->type() == QEvent::Resize)
{
// re position search widget when main output inner size changes
// this takes into account existence of vertical scrollbar
QResizeEvent *resizeEvent = static_cast<QResizeEvent*>(event);
search_widget->move(resizeEvent->size().width() - search_widget->width(), 0);
}
else if (event->type() == QEvent::Wheel)
{
// allow mouse wheel usage only in 'browsing mode'
if (!ui->bottomOutput->isVisible())
return true;
}
}
else
{
if (event->type() == QEvent::KeyPress)
{
QKeyEvent *keyEvent = static_cast<QKeyEvent*>(event);
if (ui->searchButton->isChecked())
{
// hide search widget on Escape key press
if (keyEvent->key() == Qt::Key_Escape)
emit ui->searchButton->toggle();
}
else
{
// show search widget on Ctrl-F
if (keyEvent->key() == Qt::Key_F && keyEvent->modifiers() == Qt::ControlModifier)
emit ui->searchButton->toggle();
}
if (target == search_input)
{
if (keyEvent->key() == Qt::Key_Return)
{
if (keyEvent->modifiers() == Qt::ShiftModifier)
emit search_prev_button->click();
else
emit search_next_button->click();
}
}
}
}
// base class behaviour
return QMainWindow::eventFilter(target, event);
}
void MainWindow::showSearchWidget(bool show)
{
// record which widget had focus before showing search widget, in
// to return focus to it when search widget is hidden
static QWidget *prevFocus = 0;
QPropertyAnimation *animation = new QPropertyAnimation(search_widget, "geometry");
animation->setDuration(150);
// arbitrary offset chosen to be way bigger than any scrollbar width, on any platform
const QRect rect(search_widget->geometry());
QRect showed_pos(ui->mainOutput->viewport()->width() - rect.width(), 0, rect.width(), rect.height());
QRect hidden_pos(ui->mainOutput->viewport()->width() - rect.width(), -rect.height(), rect.width(), rect.height());
animation->setStartValue(show ? hidden_pos : showed_pos);
animation->setEndValue(show ? showed_pos : hidden_pos);
if (show)
{
prevFocus = QApplication::focusWidget();
search_widget->setVisible(show);
search_input->setFocus();
}
else
{
connect(animation, &QPropertyAnimation::destroyed, search_widget, &QWidget::hide);
prevFocus->setFocus();
}
animation->start(QAbstractAnimation::DeleteWhenStopped);
}
void MainWindow::handleCursosPosChanged(int pos)
{
// only in browsing mode
if (ui->bottomOutput->isVisible())
{
// move cursor
QTextCursor text_cursor = ui->mainOutput->textCursor();
text_cursor.setPosition(pos);
// ensure search result cursor is visible
ui->mainOutput->ensureCursorVisible();
ui->mainOutput->setTextCursor(text_cursor);
}
}
void MainWindow::handleTotalOccurencesChanged(int total_occurences)
{
if (total_occurences == 0)
search_input->setStyleSheet("QLineEdit{background-color: red;}");
else
search_input->setStyleSheet("");
}
<commit_msg>clear buttons clear output text<commit_after>/**
* \file
* <!--
* Copyright 2015 Develer S.r.l. (http://www.develer.com/)
* -->
*
* \brief main cutecom-ng window
*
* \author Aurelien Rainone <aurelien@develer.org>
*/
#include <algorithm>
#include <iterator>
#include <QUiLoader>
#include <QLineEdit>
#include <QPropertyAnimation>
#include <QShortcut>
#include "mainwindow.h"
#include "ui_mainwindow.h"
#include "connectdialog.h"
#include "sessionmanager.h"
#include "outputmanager.h"
#include "searchhighlighter.h"
/// line ending char appended to the commands sent to the serial port
const QString LINE_ENDING = "\n";
/// maximum count of document blocks for the bootom output
const int MAX_OUTPUT_LINES = 100;
MainWindow::MainWindow(QWidget *parent) :
QMainWindow(parent),
ui(new Ui::MainWindow),
search_widget(0),
search_input(0)
{
ui->setupUi(this);
// create session and output managers
output_mgr = new OutputManager(this);
session_mgr = new SessionManager(this);
connect_dlg = new ConnectDialog(this);
// show connection dialog
connect(ui->connectButton, &QAbstractButton::clicked, connect_dlg, &ConnectDialog::show);
// handle reception of new data from serial port
connect(session_mgr, &SessionManager::dataReceived, this, &MainWindow::handleDataReceived);
// get data formatted for display and show it in output view
connect(output_mgr, &OutputManager::dataConverted, this, &MainWindow::addDataToView);
// get data formatted for display and show it in output view
connect(ui->inputBox, &HistoryComboBox::lineEntered, this, &MainWindow::handleNewInput);
// clear output manager buffer at session start
connect(session_mgr, &SessionManager::sessionStarted, output_mgr, &OutputManager::clear);
// clear both output text at session start
connect(session_mgr, &SessionManager::sessionStarted, ui->mainOutput, &QPlainTextEdit::clear);
connect(session_mgr, &SessionManager::sessionStarted, ui->bottomOutput, &QPlainTextEdit::clear);
// clear both output text when 'clear' is clicked
connect(ui->clearButton, &QToolButton::clicked, ui->mainOutput, &QPlainTextEdit::clear);
connect(ui->clearButton, &QToolButton::clicked, ui->bottomOutput, &QPlainTextEdit::clear);
// call openSession when user accepts/closes connection dialog
connect(connect_dlg, &ConnectDialog::openDeviceClicked, session_mgr, &SessionManager::openSession);
connect(ui->splitOutputBtn, &QToolButton::clicked, this, &MainWindow::toggleOutputSplitter);
// additional configuration for bottom output
ui->bottomOutput->hide();
ui->bottomOutput->document()->setMaximumBlockCount(MAX_OUTPUT_LINES);
ui->bottomOutput->viewport()->installEventFilter(this);
// load search widget and hide it
QUiLoader loader;
QFile file(":/searchwidget.ui");
file.open(QFile::ReadOnly);
search_widget = loader.load(&file, ui->mainOutput);
Q_ASSERT_X(search_widget, "MainWindow::MainWindow", "error while loading searchwidget.ui");
search_input = search_widget->findChild<QLineEdit*>("searchInput");
Q_ASSERT_X(search_input, "MainWindow::MainWindow", "didn't find searchInput");
search_prev_button = search_widget->findChild<QToolButton*>("previousButton");
search_next_button = search_widget->findChild<QToolButton*>("nextButton");
Q_ASSERT_X(search_prev_button, "MainWindow::MainWindow", "didn't find previousButton");
Q_ASSERT_X(search_next_button, "MainWindow::MainWindow", "didn't find nextButton");
file.close();
search_widget->hide();
// create the search results highlighter and connect search-related signals/slots
SearchHighlighter *search_highlighter = new SearchHighlighter(ui->mainOutput->document());
connect(ui->searchButton, &QToolButton::toggled, this, &MainWindow::showSearchWidget);
connect(search_input, &QLineEdit::textChanged, search_highlighter, &SearchHighlighter::setSearchString);
connect(search_prev_button, &QToolButton::clicked, search_highlighter, &SearchHighlighter::previousOccurence);
connect(search_next_button, &QToolButton::clicked, search_highlighter, &SearchHighlighter::nextOccurence);
connect(search_highlighter, &SearchHighlighter::cursorPosChanged, this, &MainWindow::handleCursosPosChanged);
connect(search_highlighter, &SearchHighlighter::totalOccurencesChanged, this, &MainWindow::handleTotalOccurencesChanged);
search_input->installEventFilter(this);
ui->mainOutput->viewport()->installEventFilter(this);
installEventFilter(this);
}
MainWindow::~MainWindow()
{
delete ui;
}
void MainWindow::handleNewInput(QString entry)
{
// if session is not open, this also keeps user input
if (session_mgr->isSessionOpen())
{
entry.append(LINE_ENDING);
session_mgr->sendToSerial(entry.toLocal8Bit());
ui->inputBox->clearEditText();
}
}
void MainWindow::addDataToView(const QString & textdata)
{
// problem : QTextEdit interprets a '\r' as a new line, so if a buffer ending
// with '\r\n' happens to be cut in the middle, there will be 1 extra
// line jump in the QTextEdit. To prevent we remove ending '\r' and
// prepend them to the next received buffer
// flag indicating that the previously received buffer ended with CR
static bool prev_ends_with_CR = false;
QString newdata;
if (prev_ends_with_CR)
{
// CR was removed at the previous buffer, so now we prepend it
newdata.append('\r');
prev_ends_with_CR = false;
}
if (textdata.length() > 0)
{
QString::const_iterator end_cit = textdata.cend();
if (textdata.endsWith('\r'))
{
// if buffer ends with CR, we don't copy it
end_cit--;
prev_ends_with_CR = true;
}
std::copy(textdata.begin(), end_cit, std::back_inserter(newdata));
}
// record end cursor position before adding text
QTextCursor prev_end_cursor(ui->mainOutput->document());
prev_end_cursor.movePosition(QTextCursor::End);
if (ui->bottomOutput->isVisible())
{
// append text to the top output and stay at current position
QTextCursor cursor(ui->mainOutput->document());
cursor.movePosition(QTextCursor::End);
cursor.insertText(newdata);
}
else
{
// append text to the top output and scroll down
ui->mainOutput->moveCursor(QTextCursor::End);
ui->mainOutput->insertPlainText(newdata);
}
// append text to bottom output and scroll
ui->bottomOutput->moveCursor(QTextCursor::End);
ui->bottomOutput->insertPlainText(newdata);
}
void MainWindow::handleDataReceived(const QByteArray &data)
{
(*output_mgr) << data;
}
void MainWindow::toggleOutputSplitter()
{
ui->bottomOutput->setVisible(!ui->bottomOutput->isVisible());
}
bool MainWindow::eventFilter(QObject *target, QEvent *event)
{
if (target == ui->mainOutput->viewport())
{
if (event->type() == QEvent::Resize)
{
// re position search widget when main output inner size changes
// this takes into account existence of vertical scrollbar
QResizeEvent *resizeEvent = static_cast<QResizeEvent*>(event);
search_widget->move(resizeEvent->size().width() - search_widget->width(), 0);
}
else if (event->type() == QEvent::Wheel)
{
// allow mouse wheel usage only in 'browsing mode'
if (!ui->bottomOutput->isVisible())
return true;
}
}
else
{
if (event->type() == QEvent::KeyPress)
{
QKeyEvent *keyEvent = static_cast<QKeyEvent*>(event);
if (ui->searchButton->isChecked())
{
// hide search widget on Escape key press
if (keyEvent->key() == Qt::Key_Escape)
emit ui->searchButton->toggle();
}
else
{
// show search widget on Ctrl-F
if (keyEvent->key() == Qt::Key_F && keyEvent->modifiers() == Qt::ControlModifier)
emit ui->searchButton->toggle();
}
if (target == search_input)
{
if (keyEvent->key() == Qt::Key_Return)
{
if (keyEvent->modifiers() == Qt::ShiftModifier)
emit search_prev_button->click();
else
emit search_next_button->click();
}
}
}
}
// base class behaviour
return QMainWindow::eventFilter(target, event);
}
void MainWindow::showSearchWidget(bool show)
{
// record which widget had focus before showing search widget, in
// to return focus to it when search widget is hidden
static QWidget *prevFocus = 0;
QPropertyAnimation *animation = new QPropertyAnimation(search_widget, "geometry");
animation->setDuration(150);
// arbitrary offset chosen to be way bigger than any scrollbar width, on any platform
const QRect rect(search_widget->geometry());
QRect showed_pos(ui->mainOutput->viewport()->width() - rect.width(), 0, rect.width(), rect.height());
QRect hidden_pos(ui->mainOutput->viewport()->width() - rect.width(), -rect.height(), rect.width(), rect.height());
animation->setStartValue(show ? hidden_pos : showed_pos);
animation->setEndValue(show ? showed_pos : hidden_pos);
if (show)
{
prevFocus = QApplication::focusWidget();
search_widget->setVisible(show);
search_input->setFocus();
}
else
{
connect(animation, &QPropertyAnimation::destroyed, search_widget, &QWidget::hide);
prevFocus->setFocus();
}
animation->start(QAbstractAnimation::DeleteWhenStopped);
}
void MainWindow::handleCursosPosChanged(int pos)
{
// only in browsing mode
if (ui->bottomOutput->isVisible())
{
// move cursor
QTextCursor text_cursor = ui->mainOutput->textCursor();
text_cursor.setPosition(pos);
// ensure search result cursor is visible
ui->mainOutput->ensureCursorVisible();
ui->mainOutput->setTextCursor(text_cursor);
}
}
void MainWindow::handleTotalOccurencesChanged(int total_occurences)
{
if (total_occurences == 0)
search_input->setStyleSheet("QLineEdit{background-color: red;}");
else
search_input->setStyleSheet("");
}
<|endoftext|>
|
<commit_before>#include "PythonInteractor.h"
#include "Scene.h"
#include <SofaPython/PythonCommon.h>
#include <SofaPython/PythonEnvironment.h>
#include <SofaPython/ScriptEnvironment.h>
#include <SofaPython/PythonMacros.h>
#include <SofaPython/PythonScriptController.h>
#include <SofaPython/PythonScriptFunction.h>
#include <qqml.h>
#include <QDebug>
#include <QSequentialIterable>
#include <vector>
PythonInteractor::PythonInteractor(QObject *parent) : QObject(parent), QQmlParserStatus(),
myScene(0),
myPythonScriptControllers()
{
connect(this, &PythonInteractor::sceneChanged, this, &PythonInteractor::handleSceneChanged);
}
PythonInteractor::~PythonInteractor()
{
}
void PythonInteractor::classBegin()
{
}
void PythonInteractor::componentComplete()
{
if(!myScene)
setScene(qobject_cast<Scene*>(parent()));
}
void PythonInteractor::setScene(Scene* newScene)
{
if(newScene == myScene)
return;
myScene = newScene;
sceneChanged(newScene);
}
void PythonInteractor::handleSceneChanged(Scene* scene)
{
if(scene)
{
if(scene->isReady())
retrievePythonScriptControllers();
connect(scene, &Scene::loaded, this, &PythonInteractor::retrievePythonScriptControllers);
}
}
void PythonInteractor::retrievePythonScriptControllers()
{
myPythonScriptControllers.clear();
if(!myScene || !myScene->isReady())
return;
std::vector<PythonScriptController*> pythonScriptControllers;
myScene->sofaSimulation()->GetRoot()->get<PythonScriptController>(&pythonScriptControllers, sofa::core::objectmodel::BaseContext::SearchDown);
for(size_t i = 0; i < pythonScriptControllers.size(); ++i)
myPythonScriptControllers.insert(pythonScriptControllers[i]->m_classname.getValue().c_str(), pythonScriptControllers[i]);
}
static PyObject* PythonBuildValueHelper(const QVariant& parameter)
{
PyObject* value = 0;
if(!parameter.isNull())
{
switch(parameter.type())
{
case QVariant::Bool:
value = Py_BuildValue("b", parameter.toBool());
break;
case QVariant::Int:
value = Py_BuildValue("i", parameter.toInt());
break;
case QVariant::UInt:
value = Py_BuildValue("I", parameter.toUInt());
break;
case QVariant::Double:
value = Py_BuildValue("d", parameter.toDouble());
break;
case QVariant::String:
value = Py_BuildValue("s", parameter.toString().toLatin1().constData());
break;
default:
value = Py_BuildValue("");
qDebug() << "ERROR: buildPythonParameterHelper, type not supported:" << parameter.typeName();
break;
}
}
return value;
}
static PyObject* PythonBuildTupleHelper(const QVariant& parameter, bool mustBeTuple)
{
PyObject* tuple = 0;
if(!parameter.isNull())
{
if(parameter.canConvert<QVariantList>())
{
QSequentialIterable parameterIterable = parameter.value<QSequentialIterable>();
tuple = PyTuple_New(parameterIterable.size());
int count = 0;
for(const QVariant& i : parameterIterable)
PyTuple_SetItem(tuple, count++, PythonBuildTupleHelper(i, false));
}
else
{
if(mustBeTuple)
{
tuple = PyTuple_New(1);
PyTuple_SetItem(tuple, 0, PythonBuildValueHelper(parameter));
}
else
{
tuple = PythonBuildValueHelper(parameter);
}
}
}
return tuple;
}
static QVariant ExtractPythonValueHelper(PyObject* parameter)
{
QVariant value;
if(parameter)
{
if(PyBool_Check(parameter))
value = (Py_False != parameter);
else if(PyInt_Check(parameter))
value = (int)PyInt_AsLong(parameter);
else if(PyFloat_Check(parameter))
value = PyFloat_AsDouble(parameter);
else if(PyString_Check(parameter))
value = PyString_AsString(parameter);
}
return value;
}
static QVariant ExtractPythonTupleHelper(PyObject* parameter)
{
QVariant value;
if(!parameter)
return value;
if(PyTuple_Check(parameter) || PyList_Check(parameter))
{
QVariantList tuple;
if(PyList_Check(parameter))
qDebug() << "length:" << PyList_Size(parameter);
else
qDebug() << "length:" << PyTuple_Size(parameter);
PyObject *iterator = PyObject_GetIter(parameter);
PyObject *item;
if(!iterator)
{
qDebug() << "ERROR: Python tuple/list is empty";
return value;
}
while(item = PyIter_Next(iterator))
{
tuple.append(ExtractPythonTupleHelper(item));
Py_DECREF(item);
}
Py_DECREF(iterator);
if(PyErr_Occurred())
qDebug() << "ERROR: during python tuple/list iteration";
return tuple;
}
value = ExtractPythonValueHelper(parameter);
return value;
}
QVariant PythonInteractor::call(const QString& pythonClassName, const QString& funcName, const QVariant& parameter)
{
QVariant result;
if(!myScene)
{
qDebug() << "ERROR: cannot call Python function on a null scene";
return result;
}
if(!myScene->isReady())
{
qDebug() << "ERROR: cannot call Python function on a scene that is still loading";
return result;
}
if(pythonClassName.isEmpty())
{
qDebug() << "ERROR: cannot call Python function without a valid python class name";
return result;
}
if(funcName.isEmpty())
{
qDebug() << "ERROR: cannot call Python function without a valid python function name";
return result;
}
auto pythonScriptControllerIterator = myPythonScriptControllers.find(pythonClassName);
if(myPythonScriptControllers.end() == pythonScriptControllerIterator)
{
qDebug() << "ERROR: cannot send Python event on an unknown script controller:" << pythonClassName;
if(myPythonScriptControllers.isEmpty())
{
qDebug() << "There is no PythonScriptController";
}
else
{
qDebug() << "Known PythonScriptController(s):";
for(const QString& pythonScriptControllerName : myPythonScriptControllers.keys())
qDebug() << "-" << pythonScriptControllerName;
}
return result;
}
PythonScriptController* pythonScriptController = pythonScriptControllerIterator.value();
if(pythonScriptController)
{
PyObject* pyCallableObject = PyObject_GetAttrString(pythonScriptController->scriptControllerInstance(), funcName.toLatin1().constData());
if(!pyCallableObject)
{
qDebug() << "ERROR: cannot call Python function without a valid python class and function name";
}
else
{
PythonScriptFunction pythonScriptFunction(pyCallableObject, true);
PythonScriptFunctionParameter pythonScriptParameter(PythonBuildTupleHelper(parameter, true), true);
PythonScriptFunctionResult pythonScriptResult;
pythonScriptFunction(&pythonScriptParameter, &pythonScriptResult);
result = ExtractPythonTupleHelper(pythonScriptResult.data());
}
}
return result;
}
void PythonInteractor::sendEvent(const QString& pythonClassName, const QString& eventName, const QVariant& parameter)
{
if(!myScene)
{
qDebug() << "ERROR: cannot send Python event on a null scene";
return;
}
if(!myScene->isReady())
{
qDebug() << "ERROR: cannot send Python event on a scene that is still loading";
return;
}
auto pythonScriptControllerIterator = myPythonScriptControllers.find(pythonClassName);
if(myPythonScriptControllers.end() == pythonScriptControllerIterator)
{
qDebug() << "ERROR: cannot send Python event on an unknown script controller:" << pythonClassName;
if(myPythonScriptControllers.isEmpty())
{
qDebug() << "There is no PythonScriptController";
}
else
{
qDebug() << "Known PythonScriptController(s):";
for(const QString& pythonScriptControllerName : myPythonScriptControllers.keys())
qDebug() << "-" << pythonScriptControllerName;
}
return;
}
PythonScriptController* pythonScriptController = pythonScriptControllerIterator.value();
PyObject* pyParameter = PythonBuildValueHelper(parameter);
if(!pyParameter)
pyParameter = Py_BuildValue("");
sofa::core::objectmodel::PythonScriptEvent pythonScriptEvent(myScene->sofaSimulation()->GetRoot(), eventName.toLatin1().constData(), pyParameter);
pythonScriptController->handleEvent(&pythonScriptEvent);
}
void PythonInteractor::sendEventToAll(const QString& eventName, const QVariant& parameter)
{
for(const QString& pythonClassName : myPythonScriptControllers.keys())
sendEvent(pythonClassName, eventName, parameter);
}
<commit_msg>ADD: SofaQtQuickGUI - PythonInteractor: support for JS/Python dictionaries<commit_after>#include "PythonInteractor.h"
#include "Scene.h"
#include <SofaPython/PythonCommon.h>
#include <SofaPython/PythonEnvironment.h>
#include <SofaPython/ScriptEnvironment.h>
#include <SofaPython/PythonMacros.h>
#include <SofaPython/PythonScriptController.h>
#include <SofaPython/PythonScriptFunction.h>
#include <qqml.h>
#include <QDebug>
#include <QSequentialIterable>
#include <vector>
PythonInteractor::PythonInteractor(QObject *parent) : QObject(parent), QQmlParserStatus(),
myScene(0),
myPythonScriptControllers()
{
connect(this, &PythonInteractor::sceneChanged, this, &PythonInteractor::handleSceneChanged);
}
PythonInteractor::~PythonInteractor()
{
}
void PythonInteractor::classBegin()
{
}
void PythonInteractor::componentComplete()
{
if(!myScene)
setScene(qobject_cast<Scene*>(parent()));
}
void PythonInteractor::setScene(Scene* newScene)
{
if(newScene == myScene)
return;
myScene = newScene;
sceneChanged(newScene);
}
void PythonInteractor::handleSceneChanged(Scene* scene)
{
if(scene)
{
if(scene->isReady())
retrievePythonScriptControllers();
connect(scene, &Scene::loaded, this, &PythonInteractor::retrievePythonScriptControllers);
}
}
void PythonInteractor::retrievePythonScriptControllers()
{
myPythonScriptControllers.clear();
if(!myScene || !myScene->isReady())
return;
std::vector<PythonScriptController*> pythonScriptControllers;
myScene->sofaSimulation()->GetRoot()->get<PythonScriptController>(&pythonScriptControllers, sofa::core::objectmodel::BaseContext::SearchDown);
for(size_t i = 0; i < pythonScriptControllers.size(); ++i)
myPythonScriptControllers.insert(pythonScriptControllers[i]->m_classname.getValue().c_str(), pythonScriptControllers[i]);
}
static PyObject* PythonBuildValueHelper(const QVariant& parameter)
{
PyObject* value = 0;
if(!parameter.isNull())
{
switch(parameter.type())
{
case QVariant::Bool:
value = Py_BuildValue("b", parameter.toBool());
break;
case QVariant::Int:
value = Py_BuildValue("i", parameter.toInt());
break;
case QVariant::UInt:
value = Py_BuildValue("I", parameter.toUInt());
break;
case QVariant::Double:
value = Py_BuildValue("d", parameter.toDouble());
break;
case QVariant::String:
value = Py_BuildValue("s", parameter.toString().toLatin1().constData());
break;
default:
value = Py_BuildValue("");
qDebug() << "ERROR: buildPythonParameterHelper, type not supported:" << parameter.typeName();
break;
}
}
return value;
}
static PyObject* PythonBuildTupleHelper(const QVariant& parameter, bool mustBeTuple)
{
PyObject* tuple = 0;
if(!parameter.isNull())
{
if(QVariant::List == parameter.type())
{
QSequentialIterable parameterIterable = parameter.value<QSequentialIterable>();
tuple = PyTuple_New(parameterIterable.size());
int count = 0;
for(const QVariant& i : parameterIterable)
PyTuple_SetItem(tuple, count++, PythonBuildTupleHelper(i, false));
}
else if(QVariant::Map == parameter.type())
{
tuple = PyDict_New();
QVariantMap map = parameter.value<QVariantMap>();
for(QVariantMap::const_iterator i = map.begin(); i != map.end(); ++i)
PyDict_SetItemString(tuple, i.key().toLatin1().constData(), PythonBuildTupleHelper(i.value(), false));
}
else
{
if(mustBeTuple)
{
tuple = PyTuple_New(1);
PyTuple_SetItem(tuple, 0, PythonBuildValueHelper(parameter));
}
else
{
tuple = PythonBuildValueHelper(parameter);
}
}
}
return tuple;
}
static QVariant ExtractPythonValueHelper(PyObject* parameter)
{
QVariant value;
if(parameter)
{
if(PyBool_Check(parameter))
value = (Py_False != parameter);
else if(PyInt_Check(parameter))
value = (int)PyInt_AsLong(parameter);
else if(PyFloat_Check(parameter))
value = PyFloat_AsDouble(parameter);
else if(PyString_Check(parameter))
value = PyString_AsString(parameter);
}
return value;
}
static QVariant ExtractPythonTupleHelper(PyObject* parameter)
{
QVariant value;
if(!parameter)
return value;
if(PyTuple_Check(parameter) || PyList_Check(parameter))
{
QVariantList tuple;
PyObject *iterator = PyObject_GetIter(parameter);
PyObject *item;
if(!iterator)
return value;
while(item = PyIter_Next(iterator))
{
tuple.append(ExtractPythonTupleHelper(item));
Py_DECREF(item);
}
Py_DECREF(iterator);
if(PyErr_Occurred())
qDebug() << "ERROR: during python tuple/list iteration";
return tuple;
}
else if(PyDict_Check(parameter))
{
QVariantMap map;
PyObject* key;
PyObject* item;
Py_ssize_t pos = 0;
while(PyDict_Next(parameter, &pos, &key, &item))
map.insert(PyString_AsString(key), ExtractPythonTupleHelper(item));
if(PyErr_Occurred())
qDebug() << "ERROR: during python dictionary iteration";
return map;
}
else
{
value = ExtractPythonValueHelper(parameter);
}
return value;
}
QVariant PythonInteractor::call(const QString& pythonClassName, const QString& funcName, const QVariant& parameter)
{
QVariant result;
if(!myScene)
{
qDebug() << "ERROR: cannot call Python function on a null scene";
return result;
}
if(!myScene->isReady())
{
qDebug() << "ERROR: cannot call Python function on a scene that is still loading";
return result;
}
if(pythonClassName.isEmpty())
{
qDebug() << "ERROR: cannot call Python function without a valid python class name";
return result;
}
if(funcName.isEmpty())
{
qDebug() << "ERROR: cannot call Python function without a valid python function name";
return result;
}
auto pythonScriptControllerIterator = myPythonScriptControllers.find(pythonClassName);
if(myPythonScriptControllers.end() == pythonScriptControllerIterator)
{
qDebug() << "ERROR: cannot send Python event on an unknown script controller:" << pythonClassName;
if(myPythonScriptControllers.isEmpty())
{
qDebug() << "There is no PythonScriptController";
}
else
{
qDebug() << "Known PythonScriptController(s):";
for(const QString& pythonScriptControllerName : myPythonScriptControllers.keys())
qDebug() << "-" << pythonScriptControllerName;
}
return result;
}
PythonScriptController* pythonScriptController = pythonScriptControllerIterator.value();
if(pythonScriptController)
{
PyObject* pyCallableObject = PyObject_GetAttrString(pythonScriptController->scriptControllerInstance(), funcName.toLatin1().constData());
if(!pyCallableObject)
{
qDebug() << "ERROR: cannot call Python function without a valid python class and function name";
}
else
{
PythonScriptFunction pythonScriptFunction(pyCallableObject, true);
PythonScriptFunctionParameter pythonScriptParameter(PythonBuildTupleHelper(parameter, true), true);
PythonScriptFunctionResult pythonScriptResult;
pythonScriptFunction(&pythonScriptParameter, &pythonScriptResult);
result = ExtractPythonTupleHelper(pythonScriptResult.data());
}
}
return result;
}
void PythonInteractor::sendEvent(const QString& pythonClassName, const QString& eventName, const QVariant& parameter)
{
if(!myScene)
{
qDebug() << "ERROR: cannot send Python event on a null scene";
return;
}
if(!myScene->isReady())
{
qDebug() << "ERROR: cannot send Python event on a scene that is still loading";
return;
}
auto pythonScriptControllerIterator = myPythonScriptControllers.find(pythonClassName);
if(myPythonScriptControllers.end() == pythonScriptControllerIterator)
{
qDebug() << "ERROR: cannot send Python event on an unknown script controller:" << pythonClassName;
if(myPythonScriptControllers.isEmpty())
{
qDebug() << "There is no PythonScriptController";
}
else
{
qDebug() << "Known PythonScriptController(s):";
for(const QString& pythonScriptControllerName : myPythonScriptControllers.keys())
qDebug() << "-" << pythonScriptControllerName;
}
return;
}
PythonScriptController* pythonScriptController = pythonScriptControllerIterator.value();
PyObject* pyParameter = PythonBuildValueHelper(parameter);
if(!pyParameter)
pyParameter = Py_BuildValue("");
sofa::core::objectmodel::PythonScriptEvent pythonScriptEvent(myScene->sofaSimulation()->GetRoot(), eventName.toLatin1().constData(), pyParameter);
pythonScriptController->handleEvent(&pythonScriptEvent);
}
void PythonInteractor::sendEventToAll(const QString& eventName, const QVariant& parameter)
{
for(const QString& pythonClassName : myPythonScriptControllers.keys())
sendEvent(pythonClassName, eventName, parameter);
}
<|endoftext|>
|
<commit_before>#include <gtest/gtest.h>
TEST (basic, basic)
{
ASSERT_TRUE (true);
}<commit_msg>Adding asan trip test case.<commit_after>#include <gtest/gtest.h>
TEST (basic, basic)
{
ASSERT_TRUE (true);
}
TEST (asan, DISABLED_memory)
{
uint8_t array [1];
auto value (array [-0x800000]);
}<|endoftext|>
|
<commit_before>/* Begin CVS Header
$Source: /Volumes/Home/Users/shoops/cvs/copasi_dev/copasi/utilities/CDirEntry.cpp,v $
$Revision: 1.19 $
$Name: $
$Author: shoops $
$Date: 2006/09/08 14:14:59 $
End CVS Header */
// Copyright 2005 by Pedro Mendes, Virginia Tech Intellectual
// Properties, Inc. and EML Research, gGmbH.
// All rights reserved.
#include <sys/types.h>
#include <sys/stat.h>
#ifdef WIN32
# include <io.h>
# include <direct.h>
# define stat _stat
# define S_IFREG _S_IFREG
# define S_IFDIR _S_IFDIR
# define access _access
# define mkdir _mkdir
# define rmdir _rmdir
#else
# include <dirent.h>
# include <unistd.h>
#endif // WIN32
#include "copasi.h"
#include "CDirEntry.h"
#include "utility.h"
#include "CCopasiMessage.h"
#include "randomGenerator/CRandom.h"
#ifdef WIN32
const std::string CDirEntry::Separator = "\\";
#else
const std::string CDirEntry::Separator = "/";
#endif
bool CDirEntry::isFile(const std::string & path)
{
struct stat st;
if (stat(utf8ToLocale(path).c_str(), & st) == -1) return false;
#ifdef WIN32
return ((st.st_mode & S_IFREG) == S_IFREG);
#else
return S_ISREG(st.st_mode);
#endif
}
bool CDirEntry::isDir(const std::string & path)
{
struct stat st;
if (stat(utf8ToLocale(path).c_str(), & st) == -1) return false;
#ifdef WIN32
return ((st.st_mode & S_IFDIR) == S_IFDIR);
#else
return S_ISDIR(st.st_mode);
#endif
}
bool CDirEntry::exist(const std::string & path)
{
struct stat st;
if (stat(utf8ToLocale(path).c_str(), & st) == -1) return false;
#ifdef WIN32
return ((st.st_mode & S_IFREG) == S_IFREG ||
(st.st_mode & S_IFDIR) == S_IFDIR);
#else
return (S_ISREG(st.st_mode) || S_ISDIR(st.st_mode));
#endif
}
bool CDirEntry::isReadable(const std::string & path)
{return (access(utf8ToLocale(path).c_str(), 0x4) == 0);}
bool CDirEntry::isWritable(const std::string & path)
{return (access(utf8ToLocale(path).c_str(), 0x2) == 0);}
std::string CDirEntry::baseName(const std::string & path)
{
std::string::size_type start = path.find_last_of(Separator);
#ifdef WIN32 // WIN32 also understands '/' as the separator.
if (start == std::string::npos)
start = path.find_last_of("/");
#endif
if (start == std::string::npos) start = 0;
else start++; // We do not want the separator.
std::string::size_type end = path.find_last_of(".");
if (end == std::string::npos || end < start)
end = path.length();
return path.substr(start, end - start);
}
std::string CDirEntry::fileName(const std::string & path)
{
std::string::size_type start = path.find_last_of(Separator);
#ifdef WIN32 // WIN32 also understands '/' as the separator.
if (start == std::string::npos)
start = path.find_last_of("/");
#endif
if (start == std::string::npos) start = 0;
else start++; // We do not want the separator.
return path.substr(start);
}
std::string CDirEntry::dirName(const std::string & path)
{
if (path == "") return path;
#ifdef WIN32 // WIN32 also understands '/' as the separator.
std::string::size_type end = path.find_last_of(Separator + "/");
#else
std::string::size_type end = path.find_last_of(Separator);
#endif
if (end == path.length() - 1)
{
#ifdef WIN32 // WIN32 also understands '/' as the separator.
end = path.find_last_of(Separator + "/", end);
#else
end = path.find_last_of(Separator, end);
#endif
}
if (end == std::string::npos) return "";
return path.substr(0, end);
}
std::string CDirEntry::suffix(const std::string & path)
{
std::string::size_type start = path.find_last_of(Separator);
#ifdef WIN32 // WIN32 also understands '/' as the separator.
if (start == std::string::npos)
start = path.find_last_of("/");
#endif
if (start == std::string::npos) start = 0;
else start++; // We do not want the separator.
std::string::size_type end = path.find_last_of(".");
if (end == std::string::npos || end < start)
return "";
else
return path.substr(end);
}
bool CDirEntry::createDir(const std::string & dir,
const std::string & parent)
{
std::string Dir;
if (parent != "") Dir = parent + Separator;
Dir += dir;
// Check whether the directory already exists and is writable.
if (isDir(Dir) && isWritable(Dir)) return true;
// Check whether the parent directory exists and is writable.
if (!isDir(parent) || !isWritable(parent)) return false;
#ifdef WIN32
return (mkdir(utf8ToLocale(Dir).c_str()) == 0);
#else
return (mkdir(utf8ToLocale(Dir).c_str(), S_IRWXU | S_IRWXG | S_IRWXO) == 0);
#endif
}
std::string CDirEntry::createTmpName(const std::string & dir,
const std::string & suffix)
{
CRandom * pRandom = CRandom::createGenerator();
std::string RandomName;
do
{
RandomName = dir + Separator;
unsigned C_INT32 Char;
for (unsigned C_INT32 i = 0; i < 8; i++)
{
Char = pRandom->getRandomU(35);
if (Char < 10)
RandomName += '0' + Char;
else
RandomName += 'a' - 10 + Char;
}
RandomName += suffix;
}
while (exist(RandomName));
return RandomName;
}
bool CDirEntry::move(const std::string & from,
const std::string & to)
{
if (!isFile(from)) return false;
std::string To = to;
// Check whether To is a directory and append the
// filename of from
if (isDir(To))
To += Separator + fileName(from);
bool success =
(rename(utf8ToLocale(from).c_str(), utf8ToLocale(To).c_str()) == 0);
if (!success)
{
{
std::ifstream in(utf8ToLocale(from).c_str());
std::ofstream out(utf8ToLocale(To).c_str());
out << in.rdbuf();
success = out.good();
}
remove(from);
}
return success;
}
bool CDirEntry::remove(const std::string & path)
{
if (isDir(path))
return (rmdir(utf8ToLocale(path).c_str()) == 0);
else if (isFile(path))
return (::remove(utf8ToLocale(path).c_str()) == 0);
return false;
}
bool CDirEntry::removeFiles(const std::string & pattern,
const std::string & path)
{
bool success = true;
std::vector< std::string > PatternList;
PatternList = compilePattern(pattern);
#ifdef WIN32
// We want the same pattern matching behaviour for all platforms.
// Therefore, we do not use the MS provided one and list all files instead.
std::string FilePattern = path + "\\*";
// Open directory stream and try read info about first entry
struct _finddata_t Entry;
C_INT32 hList = _findfirst(utf8ToLocale(FilePattern).c_str(), &Entry);
if (hList == -1) return success;
do
{
if (match(localeToUtf8(Entry.name), PatternList))
{
if (Entry.attrib | _A_NORMAL)
{
if (::remove((utf8ToLocale(path + Separator) + Entry.name).c_str()) != 0) success = false;
}
else
{
if (rmdir((utf8ToLocale(path + Separator) + Entry.name).c_str()) != 0) success = false;
}
}
}
while (_findnext(hList, &Entry) == 0);
_findclose(hList);
#else
DIR * pDir = opendir(utf8ToLocale(path).c_str());
if (!pDir) return false;
struct dirent * pEntry;
while ((pEntry = readdir(pDir)) != NULL)
{
if (match(localeToUtf8(pEntry->d_name), PatternList))
{
if (isDir(localeToUtf8(pEntry->d_name)))
{
if (rmdir((utf8ToLocale(path + Separator) + pEntry->d_name).c_str()) != 0)
success = false;
}
else
{
if (::remove((utf8ToLocale(path + Separator) + pEntry->d_name).c_str()) != 0)
success = false;
}
}
}
closedir(pDir);
#endif // WIN32
return success;
}
std::vector< std::string > CDirEntry::compilePattern(const std::string & pattern)
{
std::string::size_type pos = 0;
std::string::size_type start = 0;
std::string::size_type end = 0;
std::vector< std::string > PatternList;
while (pos != std::string::npos)
{
start = pos;
pos = pattern.find_first_of("*?", pos);
end = std::min(pos, pattern.length());
if (start != end)
PatternList.push_back(pattern.substr(start, end - start));
else
{
PatternList.push_back(pattern.substr(start, 1));
pos++;
}
};
return PatternList;
}
bool CDirEntry::match(const std::string & name,
const std::vector< std::string > & patternList)
{
std::vector< std::string >::const_iterator it = patternList.begin();
std::vector< std::string >::const_iterator end = patternList.end();
std::string::size_type at = 0;
std::string::size_type after = 0;
bool Match = true;
while (it != end && Match)
Match = matchInternal(name, *it++, at, after);
return Match;
}
bool CDirEntry::isRelativePath(const std::string & path)
{
#ifdef WIN32
return path[1] != ':';
#else
return path[0] != '/';
#endif
}
bool CDirEntry::makePathRelative(std::string & absolutePath,
const std::string & relativeTo)
{
if (isRelativePath(absolutePath) ||
isRelativePath(relativeTo)) return false; // Nothing can be done.
std:: string RelativeTo = relativeTo;
if (isFile(RelativeTo)) RelativeTo = dirName(RelativeTo);
if (!isDir(RelativeTo)) return false;
unsigned C_INT32 i, imax = std::min(absolutePath.length(), RelativeTo.length());
for (i = 0; i < imax; i++)
if (absolutePath[i] != RelativeTo[i]) break;
#ifdef WIN32
if (i == 0) return false; // A different drive letter we cannot do anything
#endif
RelativeTo = RelativeTo.substr(i);
std::string relativePath;
while (RelativeTo != "")
{
relativePath += "../";
RelativeTo = dirName(RelativeTo);
}
if (relativePath != "")
absolutePath = relativePath + absolutePath.substr(i);
else
absolutePath = absolutePath.substr(i + 1);
#ifdef WIN32
for (i = 0, imax = absolutePath.length(); i < imax; i++)
if (absolutePath[i] == '\\') absolutePath[i] = '/';
#endif
return true;
}
bool CDirEntry::makePathAbsolute(std::string & relativePath,
const std::string & absoluteTo)
{
if (!isRelativePath(relativePath) ||
isRelativePath(absoluteTo)) return false; // Nothing can be done.
std:: string AbsoluteTo = absoluteTo;
if (isFile(AbsoluteTo)) AbsoluteTo = dirName(AbsoluteTo);
if (!isDir(AbsoluteTo)) return false;
while (!relativePath.compare(0, 2, ".."))
{
AbsoluteTo = dirName(AbsoluteTo);
relativePath = relativePath.substr(3);
}
relativePath = AbsoluteTo + Separator + relativePath;
return true;
}
bool CDirEntry::matchInternal(const std::string & name,
const std::string pattern,
std::string::size_type & at,
std::string::size_type & after)
{
bool Match = true;
switch (pattern[0])
{
case '*':
if (at != std::string::npos)
{
after = at;
at = std::string::npos;
}
break;
case '?':
if (at != std::string::npos)
{
++at;
Match = (name.length() >= at);
}
else
{
++after;
Match = (name.length() >= after);
}
break;
default:
if (at != std::string::npos)
{
Match = (name.compare(at, pattern.length(), pattern) == 0);
at += pattern.length();
}
else
{
at = name.find(pattern, after);
Match = (at != std::string::npos);
at += pattern.length();
}
break;
}
return Match;
}
<commit_msg>Enhanced isRelative() to deal with an empty string.<commit_after>/* Begin CVS Header
$Source: /Volumes/Home/Users/shoops/cvs/copasi_dev/copasi/utilities/CDirEntry.cpp,v $
$Revision: 1.20 $
$Name: $
$Author: shoops $
$Date: 2006/09/14 18:25:29 $
End CVS Header */
// Copyright 2005 by Pedro Mendes, Virginia Tech Intellectual
// Properties, Inc. and EML Research, gGmbH.
// All rights reserved.
#include <sys/types.h>
#include <sys/stat.h>
#ifdef WIN32
# include <io.h>
# include <direct.h>
# define stat _stat
# define S_IFREG _S_IFREG
# define S_IFDIR _S_IFDIR
# define access _access
# define mkdir _mkdir
# define rmdir _rmdir
#else
# include <dirent.h>
# include <unistd.h>
#endif // WIN32
#include "copasi.h"
#include "CDirEntry.h"
#include "utility.h"
#include "CCopasiMessage.h"
#include "randomGenerator/CRandom.h"
#ifdef WIN32
const std::string CDirEntry::Separator = "\\";
#else
const std::string CDirEntry::Separator = "/";
#endif
bool CDirEntry::isFile(const std::string & path)
{
struct stat st;
if (stat(utf8ToLocale(path).c_str(), & st) == -1) return false;
#ifdef WIN32
return ((st.st_mode & S_IFREG) == S_IFREG);
#else
return S_ISREG(st.st_mode);
#endif
}
bool CDirEntry::isDir(const std::string & path)
{
struct stat st;
if (stat(utf8ToLocale(path).c_str(), & st) == -1) return false;
#ifdef WIN32
return ((st.st_mode & S_IFDIR) == S_IFDIR);
#else
return S_ISDIR(st.st_mode);
#endif
}
bool CDirEntry::exist(const std::string & path)
{
struct stat st;
if (stat(utf8ToLocale(path).c_str(), & st) == -1) return false;
#ifdef WIN32
return ((st.st_mode & S_IFREG) == S_IFREG ||
(st.st_mode & S_IFDIR) == S_IFDIR);
#else
return (S_ISREG(st.st_mode) || S_ISDIR(st.st_mode));
#endif
}
bool CDirEntry::isReadable(const std::string & path)
{return (access(utf8ToLocale(path).c_str(), 0x4) == 0);}
bool CDirEntry::isWritable(const std::string & path)
{return (access(utf8ToLocale(path).c_str(), 0x2) == 0);}
std::string CDirEntry::baseName(const std::string & path)
{
std::string::size_type start = path.find_last_of(Separator);
#ifdef WIN32 // WIN32 also understands '/' as the separator.
if (start == std::string::npos)
start = path.find_last_of("/");
#endif
if (start == std::string::npos) start = 0;
else start++; // We do not want the separator.
std::string::size_type end = path.find_last_of(".");
if (end == std::string::npos || end < start)
end = path.length();
return path.substr(start, end - start);
}
std::string CDirEntry::fileName(const std::string & path)
{
std::string::size_type start = path.find_last_of(Separator);
#ifdef WIN32 // WIN32 also understands '/' as the separator.
if (start == std::string::npos)
start = path.find_last_of("/");
#endif
if (start == std::string::npos) start = 0;
else start++; // We do not want the separator.
return path.substr(start);
}
std::string CDirEntry::dirName(const std::string & path)
{
if (path == "") return path;
#ifdef WIN32 // WIN32 also understands '/' as the separator.
std::string::size_type end = path.find_last_of(Separator + "/");
#else
std::string::size_type end = path.find_last_of(Separator);
#endif
if (end == path.length() - 1)
{
#ifdef WIN32 // WIN32 also understands '/' as the separator.
end = path.find_last_of(Separator + "/", end);
#else
end = path.find_last_of(Separator, end);
#endif
}
if (end == std::string::npos) return "";
return path.substr(0, end);
}
std::string CDirEntry::suffix(const std::string & path)
{
std::string::size_type start = path.find_last_of(Separator);
#ifdef WIN32 // WIN32 also understands '/' as the separator.
if (start == std::string::npos)
start = path.find_last_of("/");
#endif
if (start == std::string::npos) start = 0;
else start++; // We do not want the separator.
std::string::size_type end = path.find_last_of(".");
if (end == std::string::npos || end < start)
return "";
else
return path.substr(end);
}
bool CDirEntry::createDir(const std::string & dir,
const std::string & parent)
{
std::string Dir;
if (parent != "") Dir = parent + Separator;
Dir += dir;
// Check whether the directory already exists and is writable.
if (isDir(Dir) && isWritable(Dir)) return true;
// Check whether the parent directory exists and is writable.
if (!isDir(parent) || !isWritable(parent)) return false;
#ifdef WIN32
return (mkdir(utf8ToLocale(Dir).c_str()) == 0);
#else
return (mkdir(utf8ToLocale(Dir).c_str(), S_IRWXU | S_IRWXG | S_IRWXO) == 0);
#endif
}
std::string CDirEntry::createTmpName(const std::string & dir,
const std::string & suffix)
{
CRandom * pRandom = CRandom::createGenerator();
std::string RandomName;
do
{
RandomName = dir + Separator;
unsigned C_INT32 Char;
for (unsigned C_INT32 i = 0; i < 8; i++)
{
Char = pRandom->getRandomU(35);
if (Char < 10)
RandomName += '0' + Char;
else
RandomName += 'a' - 10 + Char;
}
RandomName += suffix;
}
while (exist(RandomName));
return RandomName;
}
bool CDirEntry::move(const std::string & from,
const std::string & to)
{
if (!isFile(from)) return false;
std::string To = to;
// Check whether To is a directory and append the
// filename of from
if (isDir(To))
To += Separator + fileName(from);
bool success =
(rename(utf8ToLocale(from).c_str(), utf8ToLocale(To).c_str()) == 0);
if (!success)
{
{
std::ifstream in(utf8ToLocale(from).c_str());
std::ofstream out(utf8ToLocale(To).c_str());
out << in.rdbuf();
success = out.good();
}
remove(from);
}
return success;
}
bool CDirEntry::remove(const std::string & path)
{
if (isDir(path))
return (rmdir(utf8ToLocale(path).c_str()) == 0);
else if (isFile(path))
return (::remove(utf8ToLocale(path).c_str()) == 0);
return false;
}
bool CDirEntry::removeFiles(const std::string & pattern,
const std::string & path)
{
bool success = true;
std::vector< std::string > PatternList;
PatternList = compilePattern(pattern);
#ifdef WIN32
// We want the same pattern matching behaviour for all platforms.
// Therefore, we do not use the MS provided one and list all files instead.
std::string FilePattern = path + "\\*";
// Open directory stream and try read info about first entry
struct _finddata_t Entry;
C_INT32 hList = _findfirst(utf8ToLocale(FilePattern).c_str(), &Entry);
if (hList == -1) return success;
do
{
if (match(localeToUtf8(Entry.name), PatternList))
{
if (Entry.attrib | _A_NORMAL)
{
if (::remove((utf8ToLocale(path + Separator) + Entry.name).c_str()) != 0) success = false;
}
else
{
if (rmdir((utf8ToLocale(path + Separator) + Entry.name).c_str()) != 0) success = false;
}
}
}
while (_findnext(hList, &Entry) == 0);
_findclose(hList);
#else
DIR * pDir = opendir(utf8ToLocale(path).c_str());
if (!pDir) return false;
struct dirent * pEntry;
while ((pEntry = readdir(pDir)) != NULL)
{
if (match(localeToUtf8(pEntry->d_name), PatternList))
{
if (isDir(localeToUtf8(pEntry->d_name)))
{
if (rmdir((utf8ToLocale(path + Separator) + pEntry->d_name).c_str()) != 0)
success = false;
}
else
{
if (::remove((utf8ToLocale(path + Separator) + pEntry->d_name).c_str()) != 0)
success = false;
}
}
}
closedir(pDir);
#endif // WIN32
return success;
}
std::vector< std::string > CDirEntry::compilePattern(const std::string & pattern)
{
std::string::size_type pos = 0;
std::string::size_type start = 0;
std::string::size_type end = 0;
std::vector< std::string > PatternList;
while (pos != std::string::npos)
{
start = pos;
pos = pattern.find_first_of("*?", pos);
end = std::min(pos, pattern.length());
if (start != end)
PatternList.push_back(pattern.substr(start, end - start));
else
{
PatternList.push_back(pattern.substr(start, 1));
pos++;
}
};
return PatternList;
}
bool CDirEntry::match(const std::string & name,
const std::vector< std::string > & patternList)
{
std::vector< std::string >::const_iterator it = patternList.begin();
std::vector< std::string >::const_iterator end = patternList.end();
std::string::size_type at = 0;
std::string::size_type after = 0;
bool Match = true;
while (it != end && Match)
Match = matchInternal(name, *it++, at, after);
return Match;
}
bool CDirEntry::isRelativePath(const std::string & path)
{
#ifdef WIN32
return (path.length() < 2 || path[1] != ':');
#else
return (path.length() < 1 || path[0] != '/');
#endif
}
bool CDirEntry::makePathRelative(std::string & absolutePath,
const std::string & relativeTo)
{
if (isRelativePath(absolutePath) ||
isRelativePath(relativeTo)) return false; // Nothing can be done.
std:: string RelativeTo = relativeTo;
if (isFile(RelativeTo)) RelativeTo = dirName(RelativeTo);
if (!isDir(RelativeTo)) return false;
unsigned C_INT32 i, imax = std::min(absolutePath.length(), RelativeTo.length());
for (i = 0; i < imax; i++)
if (absolutePath[i] != RelativeTo[i]) break;
#ifdef WIN32
if (i == 0) return false; // A different drive letter we cannot do anything
#endif
RelativeTo = RelativeTo.substr(i);
std::string relativePath;
while (RelativeTo != "")
{
relativePath += "../";
RelativeTo = dirName(RelativeTo);
}
if (relativePath != "")
absolutePath = relativePath + absolutePath.substr(i);
else
absolutePath = absolutePath.substr(i + 1);
#ifdef WIN32
for (i = 0, imax = absolutePath.length(); i < imax; i++)
if (absolutePath[i] == '\\') absolutePath[i] = '/';
#endif
return true;
}
bool CDirEntry::makePathAbsolute(std::string & relativePath,
const std::string & absoluteTo)
{
if (!isRelativePath(relativePath) ||
isRelativePath(absoluteTo)) return false; // Nothing can be done.
std:: string AbsoluteTo = absoluteTo;
if (isFile(AbsoluteTo)) AbsoluteTo = dirName(AbsoluteTo);
if (!isDir(AbsoluteTo)) return false;
while (!relativePath.compare(0, 2, ".."))
{
AbsoluteTo = dirName(AbsoluteTo);
relativePath = relativePath.substr(3);
}
relativePath = AbsoluteTo + Separator + relativePath;
#ifdef WIN32
unsigned C_INT32 i, imax;
for (i = 0, imax = relativePath.length(); i < imax; i++)
if (relativePath[i] == '\\') relativePath[i] = '/';
#endif
return true;
}
bool CDirEntry::matchInternal(const std::string & name,
const std::string pattern,
std::string::size_type & at,
std::string::size_type & after)
{
bool Match = true;
switch (pattern[0])
{
case '*':
if (at != std::string::npos)
{
after = at;
at = std::string::npos;
}
break;
case '?':
if (at != std::string::npos)
{
++at;
Match = (name.length() >= at);
}
else
{
++after;
Match = (name.length() >= after);
}
break;
default:
if (at != std::string::npos)
{
Match = (name.compare(at, pattern.length(), pattern) == 0);
at += pattern.length();
}
else
{
at = name.find(pattern, after);
Match = (at != std::string::npos);
at += pattern.length();
}
break;
}
return Match;
}
<|endoftext|>
|
<commit_before><commit_msg>[core] fix clang-tidy in TApplication (#7412)<commit_after><|endoftext|>
|
<commit_before>/**
* @file Sort_test.cpp
* @brief Unit tests for the Sort class.
* @author Dominique LaSalle <dominique@solidlake.com>
* Copyright 2018
* @version 1
* @date 2018-08-23
*/
#include "Sort.hpp"
#include "UnitTest.hpp"
#include <random>
namespace sl
{
UNITTEST(Sort, FixedKeys)
{
std::vector<int> keys{0,5,2,3,4,1,1,3};
std::unique_ptr<size_t[]> perm = Sort::fixedKeys<int, size_t>(keys.data(), \
keys.size());
testEqual(perm[0], 0UL);
testEqual(perm[1], 5UL);
testEqual(perm[2], 6UL);
testEqual(perm[3], 2UL);
testEqual(perm[4], 3UL);
testEqual(perm[5], 7UL);
testEqual(perm[6], 4UL);
}
UNITTEST(Sort, FixedKeysRandom)
{
std::vector<int> keys{0,1,0,2,1,0};
std::mt19937 rng(0);
std::unique_ptr<size_t[]> perm1 = Sort::fixedKeysRandom<int, size_t>(keys.data(), \
keys.size(), rng);
std::unique_ptr<size_t[]> perm2 = Sort::fixedKeysRandom<int, size_t>(keys.data(), \
keys.size(), rng);
// check order
testLessOrEqual(keys[perm1[0]], keys[perm1[1]]);
testLessOrEqual(keys[perm1[1]], keys[perm1[2]]);
testLessOrEqual(keys[perm1[2]], keys[perm1[3]]);
testLessOrEqual(keys[perm1[3]], keys[perm1[4]]);
testLessOrEqual(keys[perm1[4]], keys[perm1[5]]);
testLessOrEqual(keys[perm2[0]], keys[perm2[1]]);
testLessOrEqual(keys[perm2[1]], keys[perm2[2]]);
testLessOrEqual(keys[perm2[2]], keys[perm2[3]]);
testLessOrEqual(keys[perm2[3]], keys[perm2[4]]);
testLessOrEqual(keys[perm2[4]], keys[perm2[5]]);
// make sure orders are different
bool different = false;
for (size_t i = 0; i < keys.size(); ++i) {
if (perm1[i] != perm2[i]) {
different = true;
}
}
testTrue(different);
}
}
<commit_msg>Increase array size<commit_after>/**
* @file Sort_test.cpp
* @brief Unit tests for the Sort class.
* @author Dominique LaSalle <dominique@solidlake.com>
* Copyright 2018
* @version 1
* @date 2018-08-23
*/
#include "Sort.hpp"
#include "UnitTest.hpp"
#include <random>
namespace sl
{
UNITTEST(Sort, FixedKeys)
{
std::vector<int> keys{0,5,2,3,4,1,1,3};
std::unique_ptr<size_t[]> perm = Sort::fixedKeys<int, size_t>(keys.data(), \
keys.size());
testEqual(perm[0], 0UL);
testEqual(perm[1], 5UL);
testEqual(perm[2], 6UL);
testEqual(perm[3], 2UL);
testEqual(perm[4], 3UL);
testEqual(perm[5], 7UL);
testEqual(perm[6], 4UL);
}
UNITTEST(Sort, FixedKeysRandom)
{
std::vector<int> keys{0,1,0,0,2,1,0,1,2,2,1,0,1,2,2,1,1,1};
std::mt19937 rng(0);
std::unique_ptr<size_t[]> perm1 = Sort::fixedKeysRandom<int, size_t>( \
keys.data(), keys.size(), rng);
std::unique_ptr<size_t[]> perm2 = Sort::fixedKeysRandom<int, size_t>( \
keys.data(), keys.size(), rng);
// check order
for (size_t i = 0; i+1 < keys.size(); ++i) {
testLessOrEqual(keys[perm1[i]], keys[perm1[i+1]]);
testLessOrEqual(keys[perm2[i]], keys[perm2[i+1]]);
}
// make sure orders are different
int different = 0;
for (size_t i = 0; i < keys.size(); ++i) {
if (perm1[i] != perm2[i]) {
++different;
}
}
testGreater(different, 0);
}
}
<|endoftext|>
|
<commit_before>/****************************************************************************
**
** Copyright (C) 2010 Nokia Corporation and/or its subsidiary(-ies).
** All rights reserved.
** Contact: Nokia Corporation (qt-info@nokia.com)
**
** This file is part of the Qt Mobility Components.
**
** $QT_BEGIN_LICENSE:LGPL$
** No Commercial Usage
** This file contains pre-release code and may not be distributed.
** You may use this file in accordance with the terms and conditions
** contained in the Technology Preview License Agreement accompanying
** this package.
**
** GNU Lesser General Public License Usage
** Alternatively, this file may be used under the terms of the GNU Lesser
** General Public License version 2.1 as published by the Free Software
** Foundation and appearing in the file LICENSE.LGPL included in the
** packaging of this file. Please review the following information to
** ensure the GNU Lesser General Public License version 2.1 requirements
** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
**
** In addition, as a special exception, Nokia gives you certain additional
** rights. These rights are described in the Nokia Qt LGPL Exception
** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
**
** If you have questions regarding the use of this file, please contact
** Nokia at qt-info@nokia.com.
**
**
**
**
**
**
**
**
** $QT_END_LICENSE$
**
****************************************************************************/
#include "meegoaccelerometer.h"
#include "meegoals.h"
#include "meegocompass.h"
#include "meegomagnetometer.h"
#include "meegoorientationsensor.h"
#include "meegoproximitysensor.h"
#include "meegorotationsensor.h"
#include "meegotapsensor.h"
#include "meegogyroscope.h"
#include "meegolightsensor.h"
#include <qlightsensor.h>
#include <qsensorplugin.h>
#include <qsensorbackend.h>
#include <qsensormanager.h>
#include <QDebug>
class meegoSensorPlugin : public QObject, public QSensorPluginInterface, public QSensorBackendFactory
{
Q_OBJECT
Q_INTERFACES(QtMobility::QSensorPluginInterface)
public:
void registerSensors()
{
// if no default - no support either, uses Sensors.conf
const char* const MEEGO = "meego";
if (QString(QSensor::defaultSensorForType("QAccelerometer")).startsWith(MEEGO))
QSensorManager::registerBackend(QAccelerometer::type, meegoaccelerometer::id, this);
if (QSensor::defaultSensorForType("QAmbientLightSensor").startsWith(MEEGO))
QSensorManager::registerBackend(QAmbientLightSensor::type, meegoals::id, this);
if (QSensor::defaultSensorForType("QCompass").startsWith(MEEGO))
QSensorManager::registerBackend(QCompass::type, meegocompass::id, this);
if (QSensor::defaultSensorForType("QMagnetometer").startsWith(MEEGO))
QSensorManager::registerBackend(QMagnetometer::type, meegomagnetometer::id, this);
if (QSensor::defaultSensorForType("QOrientationSensor").startsWith(MEEGO))
QSensorManager::registerBackend(QOrientationSensor::type, meegoorientationsensor::id, this);
if (QSensor::defaultSensorForType("QProximitySensor").startsWith(MEEGO))
QSensorManager::registerBackend(QProximitySensor::type, meegoproximitysensor::id, this);
if (QSensor::defaultSensorForType("QRotationSensor").startsWith(MEEGO))
QSensorManager::registerBackend(QRotationSensor::type, meegorotationsensor::id, this);
if (QSensor::defaultSensorForType("QTapSensor").startsWith(MEEGO))
QSensorManager::registerBackend(QTapSensor::type, meegotapsensor::id, this);
if (QSensor::defaultSensorForType("QGyroscope").startsWith(MEEGO))
QSensorManager::registerBackend(QGyroscope::type, meegogyroscope::id, this);
if (QSensor::defaultSensorForType("QLightSensor").startsWith(MEEGO))
QSensorManager::registerBackend(QLightSensor::type, meegolightsensor::id, this);
qDebug() << "Loaded the MeeGo sensor plugin";
}
QSensorBackend *createBackend(QSensor *sensor)
{
if (sensor->identifier() == meegoaccelerometer::id)
return new meegoaccelerometer(sensor);
else if (sensor->identifier() == meegoals::id)
return new meegoals(sensor);
else if (sensor->identifier() == meegocompass::id)
return new meegocompass(sensor);
else if (sensor->identifier() == meegomagnetometer::id)
return new meegomagnetometer(sensor);
else if (sensor->identifier() == meegoorientationsensor::id)
return new meegoorientationsensor(sensor);
else if (sensor->identifier() == meegoproximitysensor::id)
return new meegoproximitysensor(sensor);
else if (sensor->identifier() == meegorotationsensor::id)
return new meegorotationsensor(sensor);
else if (sensor->identifier() == meegotapsensor::id)
return new meegotapsensor(sensor);
else if (sensor->identifier() == meegogyroscope::id)
return new meegogyroscope(sensor);
else if (sensor->identifier() == meegolightsensor::id)
return new meegolightsensor(sensor);
return 0;
}
};
Q_EXPORT_PLUGIN2(libsensors_meego, meegoSensorPlugin)
#include "main.moc"
<commit_msg>default to show support: still failing<commit_after>/****************************************************************************
**
** Copyright (C) 2010 Nokia Corporation and/or its subsidiary(-ies).
** All rights reserved.
** Contact: Nokia Corporation (qt-info@nokia.com)
**
** This file is part of the Qt Mobility Components.
**
** $QT_BEGIN_LICENSE:LGPL$
** No Commercial Usage
** This file contains pre-release code and may not be distributed.
** You may use this file in accordance with the terms and conditions
** contained in the Technology Preview License Agreement accompanying
** this package.
**
** GNU Lesser General Public License Usage
** Alternatively, this file may be used under the terms of the GNU Lesser
** General Public License version 2.1 as published by the Free Software
** Foundation and appearing in the file LICENSE.LGPL included in the
** packaging of this file. Please review the following information to
** ensure the GNU Lesser General Public License version 2.1 requirements
** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
**
** In addition, as a special exception, Nokia gives you certain additional
** rights. These rights are described in the Nokia Qt LGPL Exception
** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
**
** If you have questions regarding the use of this file, please contact
** Nokia at qt-info@nokia.com.
**
**
**
**
**
**
**
**
** $QT_END_LICENSE$
**
****************************************************************************/
#include "meegoaccelerometer.h"
#include "meegoals.h"
#include "meegocompass.h"
#include "meegomagnetometer.h"
#include "meegoorientationsensor.h"
#include "meegoproximitysensor.h"
#include "meegorotationsensor.h"
#include "meegotapsensor.h"
#include "meegogyroscope.h"
#include "meegolightsensor.h"
#include <qsensorplugin.h>
#include <qsensorbackend.h>
#include <qsensormanager.h>
#include <QDebug>
class meegoSensorPlugin : public QObject, public QSensorPluginInterface, public QSensorBackendFactory
{
Q_OBJECT
Q_INTERFACES(QtMobility::QSensorPluginInterface)
public:
void registerSensors()
{
// if no default - no support either, uses Sensors.conf
const char* const MEEGO = "meego";
// if (QString(QSensor::defaultSensorForType("QAccelerometer")).startsWith(MEEGO))
QSensorManager::registerBackend(QAccelerometer::type, meegoaccelerometer::id, this);
// if (QSensor::defaultSensorForType("QAmbientLightSensor").startsWith(MEEGO))
QSensorManager::registerBackend(QAmbientLightSensor::type, meegoals::id, this);
// if (QSensor::defaultSensorForType("QCompass").startsWith(MEEGO))
QSensorManager::registerBackend(QCompass::type, meegocompass::id, this);
// if (QSensor::defaultSensorForType("QMagnetometer").startsWith(MEEGO))
QSensorManager::registerBackend(QMagnetometer::type, meegomagnetometer::id, this);
// if (QSensor::defaultSensorForType("QOrientationSensor").startsWith(MEEGO))
QSensorManager::registerBackend(QOrientationSensor::type, meegoorientationsensor::id, this);
// if (QSensor::defaultSensorForType("QProximitySensor").startsWith(MEEGO))
QSensorManager::registerBackend(QProximitySensor::type, meegoproximitysensor::id, this);
// if (QSensor::defaultSensorForType("QRotationSensor").startsWith(MEEGO))
QSensorManager::registerBackend(QRotationSensor::type, meegorotationsensor::id, this);
// if (QSensor::defaultSensorForType("QTapSensor").startsWith(MEEGO))
QSensorManager::registerBackend(QTapSensor::type, meegotapsensor::id, this);
// if (QSensor::defaultSensorForType("QGyroscope").startsWith(MEEGO))
QSensorManager::registerBackend(QGyroscope::type, meegogyroscope::id, this);
// if (QSensor::defaultSensorForType("QLightSensor").startsWith(MEEGO))
QSensorManager::registerBackend(QLightSensor::type, meegolightsensor::id, this);
qDebug() << "Loaded the MeeGo sensor plugin";
}
QSensorBackend *createBackend(QSensor *sensor)
{
if (sensor->identifier() == meegoaccelerometer::id)
return new meegoaccelerometer(sensor);
else if (sensor->identifier() == meegoals::id)
return new meegoals(sensor);
else if (sensor->identifier() == meegocompass::id)
return new meegocompass(sensor);
else if (sensor->identifier() == meegomagnetometer::id)
return new meegomagnetometer(sensor);
else if (sensor->identifier() == meegoorientationsensor::id)
return new meegoorientationsensor(sensor);
else if (sensor->identifier() == meegoproximitysensor::id)
return new meegoproximitysensor(sensor);
else if (sensor->identifier() == meegorotationsensor::id)
return new meegorotationsensor(sensor);
else if (sensor->identifier() == meegotapsensor::id)
return new meegotapsensor(sensor);
else if (sensor->identifier() == meegogyroscope::id)
return new meegogyroscope(sensor);
else if (sensor->identifier() == meegolightsensor::id)
return new meegolightsensor(sensor);
return 0;
}
};
Q_EXPORT_PLUGIN2(libsensors_meego, meegoSensorPlugin)
#include "main.moc"
<|endoftext|>
|
<commit_before><commit_msg>Add Latin 2015 A<commit_after><|endoftext|>
|
<commit_before>#include <elevator/scheduler.h>
#include <elevator/restartwrapper.h>
namespace elevator {
Scheduler::Scheduler( int localId, HeartBeat &hb, BasicDriverInfo info,
ConcurrentQueue< StateChange > &stateUpdateIn,
ConcurrentQueue< StateChange > &stateUpdateOut,
ConcurrentQueue< Command > &commandsToRemote,
ConcurrentQueue< Command > &commandsToLocal ) :
_localElevId( localId ),
_heartbeat( hb ),
_bounds( info ),
_stateUpdateIn( stateUpdateIn ),
_stateUpdateOut( stateUpdateOut ),
_commandsToRemote( commandsToRemote ),
_commandsToLocal( commandsToLocal ),
_terminate( false )
{ }
Scheduler::~Scheduler() {
if ( _thr.joinable() ) {
_terminate = true;
_thr.join();
}
}
void Scheduler::run() {
_thr = std::thread( restartWrapper( &Scheduler::_runLocal ), this );
}
const char *showChange( ChangeType );
void Scheduler::_forwardToTargets( Command comm ) {
if ( comm.targetElevatorId == Command::ANY_ID || comm.targetElevatorId == _localElevId )
_commandsToLocal.enqueue( comm );
if ( comm.targetElevatorId != _localElevId )
_commandsToRemote.enqueue( comm );
}
void Scheduler::_handleButtonPress( ButtonType type, int floor ) {
// first setup lights
Command lights{ type == ButtonType::CallUp
? CommandType::TurnOnLightUp : CommandType::TurnOnLightDown,
Command::ANY_ID, floor };
_forwardToTargets( lights );
// now find optimal elevator
int minDistance = INT_MAX;
int minId = INT_MIN;
for ( auto &statepair : _globalState.elevators() ) {
const ElevatorState &state = statepair.second;
int dist = std::abs( state.lastFloor - floor );
if ( state.stopped )
dist += 10 * (_bounds.maxFloor() - _bounds.minFloor()); // penalisation
if ( ( state.direction == Direction::Up
&& ( (type == ButtonType::CallUp && floor > state.lastFloor )
|| floor == _bounds.maxFloor() ) )
||
( state.direction == Direction::Down
&& ( (type == ButtonType::CallDown && floor < state.lastFloor )
|| floor == _bounds.minFloor() ) )
)
dist += _bounds.maxFloor() - _bounds.minFloor() + 1; // busy penalisation
else
// as a last resort we can schedule floor even to elevator which is
// running in different direction
dist += 2 * (_bounds.maxFloor() - _bounds.minFloor() + 1); // penalisation
if ( dist < minDistance ) {
minDistance = dist;
minId = state.id;
}
}
assert_leq( 0, minId, "no minimal distance found" );
Command comm{ type == ButtonType::CallUp
? CommandType::CallToFloorAndGoUp
: CommandType::CallToFloorAndGoDown,
minId, floor };
_forwardToTargets( comm );
}
void Scheduler::_runLocal() {
while ( !_terminate.load( std::memory_order::memory_order_relaxed ) ) {
auto maybeUpdate = _stateUpdateIn.timeoutDequeue( _heartbeat.threshold() / 2 );
if ( !maybeUpdate.isNothing() ) {
auto update = maybeUpdate.value();
_globalState.update( update.state );
std::cerr << "state update: { id = " << update.state.id
<< ", timestamp = " << update.state.timestamp
<< ", changeType = " << showChange( update.changeType )
<< ", changeFloor = " << update.changeFloor << " }" << std::endl;
if ( update.state.id == _localElevId ) {
_stateUpdateOut( update ); // propagate update
// each elevator is responsible for scheduling commnads from its hardware
switch ( update.changeType ) {
case ChangeType::None:
case ChangeType::KeepAlive:
case ChangeType::OtherChange:
continue;
case ChangeType::ButtonUpPressed:
_handleButtonPress( ButtonType::CallUp, update.changeFloor );
break;
case ChangeType::ButtonDownPressed:
_handleButtonPress( ButtonType::CallDown, update.changeFloor );
break;
}
}
}
_heartbeat.beat();
}
}
const char *showChange( ChangeType t ) {
#define show( X ) case ChangeType::X: return #X
switch ( t ) {
show( None );
show( KeepAlive );
show( InsideButtonPresed );
show( ButtonDownPressed );
show( ButtonUpPressed );
show( Served );
show( ServedUp );
show( ServedDown );
show( OtherChange );
}
#undef show
return "<<unknown>>";
}
}
<commit_msg>scheduler: Fix compilation error.<commit_after>#include <elevator/scheduler.h>
#include <elevator/restartwrapper.h>
namespace elevator {
Scheduler::Scheduler( int localId, HeartBeat &hb, BasicDriverInfo info,
ConcurrentQueue< StateChange > &stateUpdateIn,
ConcurrentQueue< StateChange > &stateUpdateOut,
ConcurrentQueue< Command > &commandsToRemote,
ConcurrentQueue< Command > &commandsToLocal ) :
_localElevId( localId ),
_heartbeat( hb ),
_bounds( info ),
_stateUpdateIn( stateUpdateIn ),
_stateUpdateOut( stateUpdateOut ),
_commandsToRemote( commandsToRemote ),
_commandsToLocal( commandsToLocal ),
_terminate( false )
{ }
Scheduler::~Scheduler() {
if ( _thr.joinable() ) {
_terminate = true;
_thr.join();
}
}
void Scheduler::run() {
_thr = std::thread( restartWrapper( &Scheduler::_runLocal ), this );
}
const char *showChange( ChangeType );
void Scheduler::_forwardToTargets( Command comm ) {
if ( comm.targetElevatorId == Command::ANY_ID || comm.targetElevatorId == _localElevId )
_commandsToLocal.enqueue( comm );
if ( comm.targetElevatorId != _localElevId )
_commandsToRemote.enqueue( comm );
}
void Scheduler::_handleButtonPress( ButtonType type, int floor ) {
// first setup lights
Command lights{ type == ButtonType::CallUp
? CommandType::TurnOnLightUp : CommandType::TurnOnLightDown,
Command::ANY_ID, floor };
_forwardToTargets( lights );
// now find optimal elevator
int minDistance = INT_MAX;
int minId = INT_MIN;
for ( auto &statepair : _globalState.elevators() ) {
const ElevatorState &state = statepair.second;
int dist = std::abs( state.lastFloor - floor );
if ( state.stopped )
dist += 10 * (_bounds.maxFloor() - _bounds.minFloor()); // penalisation
if ( ( state.direction == Direction::Up
&& ( (type == ButtonType::CallUp && floor > state.lastFloor )
|| floor == _bounds.maxFloor() ) )
||
( state.direction == Direction::Down
&& ( (type == ButtonType::CallDown && floor < state.lastFloor )
|| floor == _bounds.minFloor() ) )
)
dist += _bounds.maxFloor() - _bounds.minFloor() + 1; // busy penalisation
else
// as a last resort we can schedule floor even to elevator which is
// running in different direction
dist += 2 * (_bounds.maxFloor() - _bounds.minFloor() + 1); // penalisation
if ( dist < minDistance ) {
minDistance = dist;
minId = state.id;
}
}
assert_leq( 0, minId, "no minimal distance found" );
Command comm{ type == ButtonType::CallUp
? CommandType::CallToFloorAndGoUp
: CommandType::CallToFloorAndGoDown,
minId, floor };
_forwardToTargets( comm );
}
void Scheduler::_runLocal() {
while ( !_terminate.load( std::memory_order::memory_order_relaxed ) ) {
auto maybeUpdate = _stateUpdateIn.timeoutDequeue( _heartbeat.threshold() / 2 );
if ( !maybeUpdate.isNothing() ) {
auto update = maybeUpdate.value();
_globalState.update( update.state );
std::cerr << "state update: { id = " << update.state.id
<< ", timestamp = " << update.state.timestamp
<< ", changeType = " << showChange( update.changeType )
<< ", changeFloor = " << update.changeFloor << " }" << std::endl;
if ( update.state.id == _localElevId ) {
_stateUpdateOut.enqueue( update ); // propagate update
// each elevator is responsible for scheduling commnads from its hardware
switch ( update.changeType ) {
case ChangeType::None:
case ChangeType::KeepAlive:
case ChangeType::OtherChange:
continue;
case ChangeType::ButtonUpPressed:
_handleButtonPress( ButtonType::CallUp, update.changeFloor );
break;
case ChangeType::ButtonDownPressed:
_handleButtonPress( ButtonType::CallDown, update.changeFloor );
break;
}
}
}
_heartbeat.beat();
}
}
const char *showChange( ChangeType t ) {
#define show( X ) case ChangeType::X: return #X
switch ( t ) {
show( None );
show( KeepAlive );
show( InsideButtonPresed );
show( ButtonDownPressed );
show( ButtonUpPressed );
show( Served );
show( ServedUp );
show( ServedDown );
show( OtherChange );
}
#undef show
return "<<unknown>>";
}
}
<|endoftext|>
|
<commit_before>/*
* This file is part of the libsumo - a reverse-engineered library for
* controlling Parrot's connected toy: Jumping Sumo
*
* Copyright (C) 2014 I. Loreen
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public License
* as published by the Free Software Foundation; either version 2.1 of
* the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful, but
* WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
* 02110-1301 USA
*/
#include <iostream>
#include <cstdlib>
#include <cstdio>
#include <sstream>
#include <sys/time.h>
#include <sys/stat.h>
#include <sys/types.h>
#include <errno.h>
#include <cstring>
#include <cmath>
#include "common.h"
using namespace std;
void _handle_error (enum severity s, const char *func, const char *filename, const unsigned int line, const char *fmt ...)
{
va_list ap;
cout << endl;
switch (s){
case SEV_INFO : fprintf(stderr, "INFO("); break;
case SEV_WARNING : fprintf(stderr, "WARNING("); break;
default:
case SEV_ERROR : fprintf(stderr, "ERROR("); break;
};
fprintf(stderr, "%s,%s:%i): ", func, filename, line);
va_start(ap,fmt);
vfprintf(stderr, fmt, ap);
fflush(stderr);
fprintf(stderr, "\n");
fflush(stderr);
va_end(ap);
if (s==SEV_ERROR){
exit(EXIT_FAILURE);
}else{
return;
}
}
static struct timeval start_cap_time;
static uint32_t id;
static char timestamp[100];
static const char * strTime()
{
double off;
struct timeval t;
gettimeofday(&t, NULL);
off = t.tv_sec + t.tv_usec/1000000.0;
off -= start_cap_time.tv_sec + start_cap_time.tv_usec/1000000.0;
snprintf(timestamp, 100, "%6d: %9.3f ", id, off);
return timestamp;
}
static void printTime()
{
dump(strTime());
}
void dumpPayload(const uint8_t *packet, uint32_t l, bool floats)
{
uint32_t i;
if (l < 3)
return;
printTime();
dump("ascii: ");
for (i = 0; i < l; i++)
dump("%c", isprint(packet[i]) ? packet[i] : '.');
dump("\n");
printTime();
dump("offs: ");
for (i = 0; i < l-3; i+=4)
dump("%-11u ", i);
dump("\n");
printTime();
dump("hex : ");
for (i = 0; i < l; i++)
dump("%02x ", packet[i]);
dump("\n");
printTime();
dump("ascii: ");
for (i = 0; i < l; i++)
dump("%c ", isprint(packet[i]) ? packet[i] : '.');
dump("\n");
printTime();
dump("8b: ");
for (i = 0; l && i < l; i++)
dump("%-3u ", packet[i]);
dump("\n");
printTime();
dump("16b 0: ");
for (i = 0; l && i < l-1; i += 2)
dump("%-5u ", *((uint16_t *) &packet[i]) );
dump("\n");
printTime();
dump("16b 1: ");
for (i = 1; l && i < l-1; i += 2)
dump("%-5u ", *((uint16_t *) &packet[i]) );
dump("\n");
printTime();
dump("32b 0: ");
for (i = 0; l && i < l-3; i += 4)
dump("%-11u ", *((uint32_t *) &packet[i]) );
dump("\n");
printTime();
dump("32b 1: ");
for (i = 1; l && i < l-3; i += 4)
dump("%-11u ", *((uint32_t *) &packet[i]) );
dump("\n");
printTime();
dump("32b 2: ");
for (i = 2; l && i < l-3; i += 4)
dump("%-11u ", *((uint32_t *) &packet[i]) );
dump("\n");
printTime();
dump("32b 3: ");
for (i = 3; l && i < l-3; i += 4)
dump("%-11u ", *((uint32_t *) &packet[i]) );
dump("\n");
if (floats) {
printTime();
dump("32f 0: ");
for (i = 0; l && i < l-3; i += 4)
dump("%-11g ", *((float *) &packet[i]) );
dump("\n");
printTime();
dump("32f 1: ");
for (i = 1; l && i < l-3; i += 4)
dump("%-11g ", *((float *) &packet[i]) );
dump("\n");
printTime();
dump("32f 2: ");
for (i = 2; l && i < l-3; i += 4)
dump("%-11g ", *((float *) &packet[i]) );
dump("\n");
printTime();
dump("32f 3: ");
for (i = 3; l && i < l-3; i += 4)
dump("%-11g ", *((float *) &packet[i]) );
dump("\n");
if (l >= 8) {
printTime();
dump("64f 0: ");
for (i = 0; l && i < l-7; i += 8)
dump("%-27.4g ", *((double *) &packet[i]) );
dump("\n");
printTime();
dump("64f 1: ");
for (i = 1; l && i < l-7; i += 8)
dump("%-27.4g ", *((double *) &packet[i]) );
dump("\n");
printTime();
dump("64g 2: ");
for (i = 2; l && i < l-7; i += 8)
dump("%-27.4g ", *((double *) &packet[i]) );
dump("\n");
printTime();
dump("64g 3: ");
for (i = 3; l && i < l-7; i += 8)
dump("%-27.4g ", *((double *) &packet[i]) );
dump("\n");
printTime();
dump("64g 4: ");
for (i = 4; l && i < l-7; i += 8)
dump("%-27.4g ", *((double *) &packet[i]) );
dump("\n");
printTime();
dump("64g 5: ");
for (i = 5; l && i < l-7; i += 8)
dump("%-27.4g ", *((double *) &packet[i]) );
dump("\n");
printTime();
dump("64g 6: ");
for (i = 6; l && i < l-7; i += 8)
dump("%-27.4g ", *((double *) &packet[i]) );
dump("\n");
printTime();
dump("64g 7: ");
for (i = 7; l && i < l-7; i += 8)
dump("%-27.4g ", *((double *) &packet[i]) );
dump("\n");
}
}
}
<commit_msg>warning: fix warning seen with clang-3.4<commit_after>/*
* This file is part of the libsumo - a reverse-engineered library for
* controlling Parrot's connected toy: Jumping Sumo
*
* Copyright (C) 2014 I. Loreen
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public License
* as published by the Free Software Foundation; either version 2.1 of
* the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful, but
* WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
* 02110-1301 USA
*/
#include <iostream>
#include <cstdlib>
#include <cstdio>
#include <sstream>
#include <sys/time.h>
#include <sys/stat.h>
#include <sys/types.h>
#include <errno.h>
#include <cstring>
#include <cmath>
#include "common.h"
using namespace std;
void _handle_error (enum severity s, const char *func, const char *filename, const unsigned int line, const char *fmt ...)
{
va_list ap;
cout << endl;
switch (s){
case SEV_INFO : fprintf(stderr, "INFO("); break;
case SEV_WARNING : fprintf(stderr, "WARNING("); break;
default:
case SEV_ERROR : fprintf(stderr, "ERROR("); break;
};
fprintf(stderr, "%s,%s:%i): ", func, filename, line);
va_start(ap,fmt);
vfprintf(stderr, fmt, ap);
fflush(stderr);
fprintf(stderr, "\n");
fflush(stderr);
va_end(ap);
if (s==SEV_ERROR){
exit(EXIT_FAILURE);
}else{
return;
}
}
static struct timeval start_cap_time;
static uint32_t id;
static char timestamp[100];
static const char * strTime()
{
double off;
struct timeval t;
gettimeofday(&t, NULL);
off = t.tv_sec + t.tv_usec/1000000.0;
off -= start_cap_time.tv_sec + start_cap_time.tv_usec/1000000.0;
snprintf(timestamp, 100, "%6d: %9.3f ", id, off);
return timestamp;
}
static void printTime()
{
dump("%s", strTime());
}
void dumpPayload(const uint8_t *packet, uint32_t l, bool floats)
{
uint32_t i;
if (l < 3)
return;
printTime();
dump("ascii: ");
for (i = 0; i < l; i++)
dump("%c", isprint(packet[i]) ? packet[i] : '.');
dump("\n");
printTime();
dump("offs: ");
for (i = 0; i < l-3; i+=4)
dump("%-11u ", i);
dump("\n");
printTime();
dump("hex : ");
for (i = 0; i < l; i++)
dump("%02x ", packet[i]);
dump("\n");
printTime();
dump("ascii: ");
for (i = 0; i < l; i++)
dump("%c ", isprint(packet[i]) ? packet[i] : '.');
dump("\n");
printTime();
dump("8b: ");
for (i = 0; l && i < l; i++)
dump("%-3u ", packet[i]);
dump("\n");
printTime();
dump("16b 0: ");
for (i = 0; l && i < l-1; i += 2)
dump("%-5u ", *((uint16_t *) &packet[i]) );
dump("\n");
printTime();
dump("16b 1: ");
for (i = 1; l && i < l-1; i += 2)
dump("%-5u ", *((uint16_t *) &packet[i]) );
dump("\n");
printTime();
dump("32b 0: ");
for (i = 0; l && i < l-3; i += 4)
dump("%-11u ", *((uint32_t *) &packet[i]) );
dump("\n");
printTime();
dump("32b 1: ");
for (i = 1; l && i < l-3; i += 4)
dump("%-11u ", *((uint32_t *) &packet[i]) );
dump("\n");
printTime();
dump("32b 2: ");
for (i = 2; l && i < l-3; i += 4)
dump("%-11u ", *((uint32_t *) &packet[i]) );
dump("\n");
printTime();
dump("32b 3: ");
for (i = 3; l && i < l-3; i += 4)
dump("%-11u ", *((uint32_t *) &packet[i]) );
dump("\n");
if (floats) {
printTime();
dump("32f 0: ");
for (i = 0; l && i < l-3; i += 4)
dump("%-11g ", *((float *) &packet[i]) );
dump("\n");
printTime();
dump("32f 1: ");
for (i = 1; l && i < l-3; i += 4)
dump("%-11g ", *((float *) &packet[i]) );
dump("\n");
printTime();
dump("32f 2: ");
for (i = 2; l && i < l-3; i += 4)
dump("%-11g ", *((float *) &packet[i]) );
dump("\n");
printTime();
dump("32f 3: ");
for (i = 3; l && i < l-3; i += 4)
dump("%-11g ", *((float *) &packet[i]) );
dump("\n");
if (l >= 8) {
printTime();
dump("64f 0: ");
for (i = 0; l && i < l-7; i += 8)
dump("%-27.4g ", *((double *) &packet[i]) );
dump("\n");
printTime();
dump("64f 1: ");
for (i = 1; l && i < l-7; i += 8)
dump("%-27.4g ", *((double *) &packet[i]) );
dump("\n");
printTime();
dump("64g 2: ");
for (i = 2; l && i < l-7; i += 8)
dump("%-27.4g ", *((double *) &packet[i]) );
dump("\n");
printTime();
dump("64g 3: ");
for (i = 3; l && i < l-7; i += 8)
dump("%-27.4g ", *((double *) &packet[i]) );
dump("\n");
printTime();
dump("64g 4: ");
for (i = 4; l && i < l-7; i += 8)
dump("%-27.4g ", *((double *) &packet[i]) );
dump("\n");
printTime();
dump("64g 5: ");
for (i = 5; l && i < l-7; i += 8)
dump("%-27.4g ", *((double *) &packet[i]) );
dump("\n");
printTime();
dump("64g 6: ");
for (i = 6; l && i < l-7; i += 8)
dump("%-27.4g ", *((double *) &packet[i]) );
dump("\n");
printTime();
dump("64g 7: ");
for (i = 7; l && i < l-7; i += 8)
dump("%-27.4g ", *((double *) &packet[i]) );
dump("\n");
}
}
}
<|endoftext|>
|
<commit_before>#include "DistributeDriver.h"
#include "MasterManagerBase.h"
#include "DistributeRequestHooker.h"
#include "RequestLog.h"
#include "DistributeTest.hpp"
#include <util/scheduler.h>
#include <util/driver/Reader.h>
#include <util/driver/Writer.h>
#include <util/driver/writers/JsonWriter.h>
#include <util/driver/readers/JsonReader.h>
#include <util/driver/Keys.h>
#include <boost/bind.hpp>
#include <glog/logging.h>
using namespace izenelib::driver;
namespace sf1r
{
DistributeDriver::DistributeDriver()
{
async_task_worker_ = boost::thread(&DistributeDriver::run, this);
// only one write task can exist in distribute system.
asyncWriteTasks_.resize(1);
}
void DistributeDriver::stop()
{
async_task_worker_.interrupt();
async_task_worker_.join();
asyncWriteTasks_.clear();
}
void DistributeDriver::run()
{
try
{
while(true)
{
boost::function<bool()> task;
asyncWriteTasks_.pop(task);
task();
boost::this_thread::interruption_point();
}
}
catch (boost::thread_interrupted&)
{
return;
}
}
void DistributeDriver::init(const RouterPtr& router)
{
router_ = router;
MasterManagerBase::get()->setCallback(boost::bind(&DistributeDriver::on_new_req_available, this));
}
static bool callCronJob(Request::kCallType calltype, const std::string& jobname, const std::string& packed_data)
{
DistributeRequestHooker::get()->processLocalBegin();
DistributeTestSuit::incWriteRequestTimes("cron_" + jobname);
bool ret = izenelib::util::Scheduler::runJobImmediatly(jobname, calltype, calltype == Request::FromLog);
if (!ret)
{
LOG(ERROR) << "start cron job failed." << jobname;
}
else
{
LOG(INFO) << "cron job finished local: " << jobname;
}
DistributeRequestHooker::get()->processLocalFinished(ret);
return ret;
}
static bool callHandler(izenelib::driver::Router::handler_ptr handler,
Request::kCallType calltype, const std::string& packed_data,
Request& request)
{
try
{
DistributeRequestHooker::get()->processLocalBegin();
Response response;
response.setSuccess(true);
static Poller tmp_poller;
// prepare request
handler->invoke(request,
response,
tmp_poller);
LOG(INFO) << "write request send in DistributeDriver success.";
return true;
}
catch(const std::exception& e)
{
LOG(ERROR) << "call request handler exception: " << e.what();
DistributeRequestHooker::get()->processLocalFinished(false);
throw;
}
return false;
}
static bool callCBWriteHandler(Request::kCallType calltype, const std::string& callback_name,
const DistributeDriver::CBWriteHandlerT& cb_handler)
{
DistributeRequestHooker::get()->processLocalBegin();
DistributeTestSuit::incWriteRequestTimes("callback_" + callback_name);
bool ret = cb_handler(calltype);
if (!ret)
{
LOG(ERROR) << "callback handler failed." << callback_name;
}
else
{
LOG(INFO) << "a callback write request finished :" << callback_name;
}
DistributeRequestHooker::get()->processLocalFinished(ret);
return ret;
}
void DistributeDriver::removeCallbackWriteHandler(const std::string& name)
{
// no lock needed because of this will only happen while stopping collection,
// it will be sure there is no any callback write request.
callback_handlers_.erase(name);
LOG(INFO) << "callback handler removed :" << name;
}
bool DistributeDriver::addCallbackWriteHandler(const std::string& name, const CBWriteHandlerT& handler)
{
if (callback_handlers_.find(name) != callback_handlers_.end())
{
LOG(WARNING) << "callback handler already existed";
return false;
}
if (!handler)
{
LOG(WARNING) << "callback NULL handler!";
return false;
}
callback_handlers_[name] = handler;
return true;
}
bool DistributeDriver::handleRequest(const std::string& reqjsondata, const std::string& packed_data, Request::kCallType calltype)
{
static izenelib::driver::JsonReader reader;
Value requestValue;
if(reader.read(reqjsondata, requestValue))
{
if (requestValue.type() != Value::kObjectType)
{
LOG(ERROR) << "read request data type error: Malformed request: require an object as input.";
return false;
}
Request request;
request.assignTmp(requestValue);
izenelib::driver::Router::handler_ptr handler = router_->find(
request.controller(),
request.action()
);
if (!handler)
{
LOG(ERROR) << "Handler not found for the request : " << request.controller() <<
"," << request.action();
return false;
}
if (!ReqLogMgr::isWriteRequest(request.controller(), request.action()))
{
LOG(ERROR) << "=== Wrong, not a write request in DistributeDriver!!";
return false;
}
try
{
if (!asyncWriteTasks_.empty())
{
LOG(ERROR) << "another write task is running in async_task_worker_!!";
return false;
}
DistributeTestSuit::incWriteRequestTimes(request.controller() + "_" + request.action());
DistributeRequestHooker::get()->setHook(calltype, packed_data);
request.setCallType(calltype);
DistributeRequestHooker::get()->hookCurrentReq(packed_data);
if (calltype == Request::FromLog)
{
// redo log must process the request one by one, so sync needed.
return callHandler(handler, calltype, packed_data, request);
}
else
{
if (!async_task_worker_.interruption_requested())
{
asyncWriteTasks_.push(boost::bind(&callHandler,
handler, calltype, packed_data, request));
}
}
return true;
}
catch (const std::exception& e)
{
LOG(ERROR) << "process request exception: " << e.what();
}
}
else
{
// malformed request
LOG(WARNING) << "read request data error: " << reader.errorMessages();
}
return false;
}
bool DistributeDriver::handleReqFromLog(int reqtype, const std::string& reqjsondata, const std::string& packed_data)
{
if ((ReqLogType)reqtype == Req_CronJob)
{
if (!asyncWriteTasks_.empty())
{
LOG(ERROR) << "another write task is running in async_task_worker_!!";
return false;
}
LOG(INFO) << "got a cron job request in log." << reqjsondata;
DistributeRequestHooker::get()->setHook(Request::FromLog, packed_data);
DistributeRequestHooker::get()->hookCurrentReq(packed_data);
return callCronJob(Request::FromLog, reqjsondata, packed_data);
}
else if ((ReqLogType)reqtype == Req_Callback)
{
if (!asyncWriteTasks_.empty())
{
LOG(ERROR) << "another write task is running in async_task_worker_!!";
return false;
}
LOG(INFO) << "got a callback request in log." << reqjsondata;
std::map<std::string, CBWriteHandlerT>::const_iterator it = callback_handlers_.find(reqjsondata);
if (it == callback_handlers_.end())
{
LOG(WARNING) << "callback write request not found on the node: " << reqjsondata;
return false;
}
DistributeRequestHooker::get()->setHook(Request::FromLog, packed_data);
DistributeRequestHooker::get()->hookCurrentReq(packed_data);
return callCBWriteHandler(Request::FromLog, reqjsondata, it->second);
}
return handleRequest(reqjsondata, packed_data, Request::FromLog);
}
bool DistributeDriver::handleReqFromPrimary(int reqtype, const std::string& reqjsondata, const std::string& packed_data)
{
if ((ReqLogType)reqtype == Req_CronJob)
{
LOG(INFO) << "got a cron job request from primary." << reqjsondata;
DistributeRequestHooker::get()->setHook(Request::FromPrimaryWorker, packed_data);
DistributeRequestHooker::get()->hookCurrentReq(packed_data);
if (!async_task_worker_.interruption_requested())
{
asyncWriteTasks_.push(boost::bind(&callCronJob,
Request::FromPrimaryWorker, reqjsondata, packed_data));
}
return true;
}
else if((ReqLogType)reqtype == Req_Callback)
{
LOG(INFO) << "got a callback request from primary." << reqjsondata;
std::map<std::string, CBWriteHandlerT>::const_iterator it = callback_handlers_.find(reqjsondata);
if (it == callback_handlers_.end())
{
LOG(WARNING) << "callback write request not found on the node: " << reqjsondata;
return false;
}
DistributeRequestHooker::get()->setHook(Request::FromPrimaryWorker, packed_data);
DistributeRequestHooker::get()->hookCurrentReq(packed_data);
if (!async_task_worker_.interruption_requested())
{
asyncWriteTasks_.push(boost::bind(&callCBWriteHandler,
Request::FromPrimaryWorker, reqjsondata, it->second));
}
return true;
}
return handleRequest(reqjsondata, packed_data, Request::FromPrimaryWorker);
}
bool DistributeDriver::pushCallbackWrite(const std::string& name, const std::string& packed_data)
{
LOG(INFO) << "a callback write pushed to queue: " << name;
MasterManagerBase::get()->pushWriteReq(name + "::" + packed_data, "callback");
return true;
}
bool DistributeDriver::on_new_req_available()
{
if (!MasterManagerBase::get()->prepareWriteReq())
{
LOG(WARNING) << "prepare new request failed. maybe some other primary master prepared first. ";
return false;
}
while(true)
{
std::string reqdata;
std::string reqtype;
if(!MasterManagerBase::get()->popWriteReq(reqdata, reqtype))
{
LOG(INFO) << "no more request.";
return false;
}
if(reqtype.empty() && !handleRequest(reqdata, reqdata, Request::FromDistribute) )
{
LOG(WARNING) << "one write request failed to deliver :" << reqdata;
// a write request failed to deliver means the worker did not
// started to handle this request, so the request is ignored, and
// continue to deliver next write request in the queue.
}
else if (reqtype == "api_from_shard")
{
if(!handleRequest(reqdata, reqdata, Request::FromOtherShard))
{
LOG(WARNING) << "one api write request from shard failed to deliver :" << reqdata;
}
else
{
break;
}
}
else if (reqtype == "cron")
{
LOG(INFO) << "got a cron job request from queue." << reqdata;
DistributeRequestHooker::get()->setHook(Request::FromDistribute, reqdata);
DistributeRequestHooker::get()->hookCurrentReq(reqdata);
if (!async_task_worker_.interruption_requested())
{
asyncWriteTasks_.push(boost::bind(&callCronJob,
Request::FromDistribute, reqdata, reqdata));
}
break;
}
else if (reqtype == "callback")
{
LOG(INFO) << "got a callback write request : " << reqdata;
// get the callback name and packed_data.
size_t split_pos = reqdata.find("::");
if (split_pos == std::string::npos)
{
LOG(WARNING) << "callback data invalid.";
continue;
}
std::string callback_name = reqdata.substr(0, split_pos);
std::string packed_data = reqdata.substr(split_pos + 2);
std::map<std::string, CBWriteHandlerT>::const_iterator it = callback_handlers_.find(callback_name);
if (it == callback_handlers_.end())
{
LOG(WARNING) << "callback write request not found on the node: " << callback_name;
continue;
}
DistributeRequestHooker::get()->setHook(Request::FromOtherShard, packed_data);
DistributeRequestHooker::get()->hookCurrentReq(packed_data);
if (!async_task_worker_.interruption_requested())
{
asyncWriteTasks_.push(boost::bind(&callCBWriteHandler, Request::FromOtherShard,
callback_name, it->second));
}
break;
}
else
{
// a write request deliver success from master to worker.
// this mean the worker has started to process this request,
// may be not finish writing, so we break here to wait the finished
// event from primary worker.
break;
}
}
return true;
}
}
<commit_msg>handle stop while write request running<commit_after>#include "DistributeDriver.h"
#include "MasterManagerBase.h"
#include "DistributeRequestHooker.h"
#include "RequestLog.h"
#include "DistributeTest.hpp"
#include <util/scheduler.h>
#include <util/driver/Reader.h>
#include <util/driver/Writer.h>
#include <util/driver/writers/JsonWriter.h>
#include <util/driver/readers/JsonReader.h>
#include <util/driver/Keys.h>
#include <boost/bind.hpp>
#include <glog/logging.h>
using namespace izenelib::driver;
namespace sf1r
{
DistributeDriver::DistributeDriver()
{
async_task_worker_ = boost::thread(&DistributeDriver::run, this);
// only one write task can exist in distribute system.
asyncWriteTasks_.resize(1);
}
void DistributeDriver::stop()
{
async_task_worker_.interrupt();
async_task_worker_.join();
asyncWriteTasks_.clear();
}
void DistributeDriver::run()
{
try
{
while(true)
{
boost::function<bool()> task;
asyncWriteTasks_.pop(task);
task();
boost::this_thread::interruption_point();
}
}
catch (boost::thread_interrupted&)
{
// if any request, run it.
if (!asyncWriteTasks_.empty())
{
LOG(INFO) << "running last request before stopping.";
boost::function<bool()> task;
asyncWriteTasks_.pop(task);
task();
}
return;
}
LOG(ERROR) << "run write thread error.";
throw -1;
}
void DistributeDriver::init(const RouterPtr& router)
{
router_ = router;
MasterManagerBase::get()->setCallback(boost::bind(&DistributeDriver::on_new_req_available, this));
}
static bool callCronJob(Request::kCallType calltype, const std::string& jobname, const std::string& packed_data)
{
DistributeRequestHooker::get()->processLocalBegin();
DistributeTestSuit::incWriteRequestTimes("cron_" + jobname);
bool ret = izenelib::util::Scheduler::runJobImmediatly(jobname, calltype, calltype == Request::FromLog);
if (!ret)
{
LOG(ERROR) << "start cron job failed." << jobname;
}
else
{
LOG(INFO) << "cron job finished local: " << jobname;
}
DistributeRequestHooker::get()->processLocalFinished(ret);
return ret;
}
static bool callHandler(izenelib::driver::Router::handler_ptr handler,
Request::kCallType calltype, const std::string& packed_data,
Request& request)
{
try
{
DistributeRequestHooker::get()->processLocalBegin();
Response response;
response.setSuccess(true);
static Poller tmp_poller;
// prepare request
handler->invoke(request,
response,
tmp_poller);
LOG(INFO) << "write request send in DistributeDriver success.";
return true;
}
catch(const std::exception& e)
{
LOG(ERROR) << "call request handler exception: " << e.what();
DistributeRequestHooker::get()->processLocalFinished(false);
throw;
}
return false;
}
static bool callCBWriteHandler(Request::kCallType calltype, const std::string& callback_name,
const DistributeDriver::CBWriteHandlerT& cb_handler)
{
DistributeRequestHooker::get()->processLocalBegin();
DistributeTestSuit::incWriteRequestTimes("callback_" + callback_name);
bool ret = cb_handler(calltype);
if (!ret)
{
LOG(ERROR) << "callback handler failed." << callback_name;
}
else
{
LOG(INFO) << "a callback write request finished :" << callback_name;
}
DistributeRequestHooker::get()->processLocalFinished(ret);
return ret;
}
void DistributeDriver::removeCallbackWriteHandler(const std::string& name)
{
// no lock needed because of this will only happen while stopping collection,
// it will be sure there is no any callback write request.
callback_handlers_.erase(name);
LOG(INFO) << "callback handler removed :" << name;
}
bool DistributeDriver::addCallbackWriteHandler(const std::string& name, const CBWriteHandlerT& handler)
{
if (callback_handlers_.find(name) != callback_handlers_.end())
{
LOG(WARNING) << "callback handler already existed";
return false;
}
if (!handler)
{
LOG(WARNING) << "callback NULL handler!";
return false;
}
callback_handlers_[name] = handler;
return true;
}
bool DistributeDriver::handleRequest(const std::string& reqjsondata, const std::string& packed_data, Request::kCallType calltype)
{
static izenelib::driver::JsonReader reader;
Value requestValue;
if(reader.read(reqjsondata, requestValue))
{
if (requestValue.type() != Value::kObjectType)
{
LOG(ERROR) << "read request data type error: Malformed request: require an object as input.";
return false;
}
Request request;
request.assignTmp(requestValue);
izenelib::driver::Router::handler_ptr handler = router_->find(
request.controller(),
request.action()
);
if (!handler)
{
LOG(ERROR) << "Handler not found for the request : " << request.controller() <<
"," << request.action();
return false;
}
if (!ReqLogMgr::isWriteRequest(request.controller(), request.action()))
{
LOG(ERROR) << "=== Wrong, not a write request in DistributeDriver!!";
return false;
}
try
{
if (!asyncWriteTasks_.empty())
{
LOG(ERROR) << "another write task is running in async_task_worker_!!";
return false;
}
DistributeTestSuit::incWriteRequestTimes(request.controller() + "_" + request.action());
request.setCallType(calltype);
if (calltype == Request::FromLog)
{
// redo log must process the request one by one, so sync needed.
DistributeRequestHooker::get()->setHook(calltype, packed_data);
DistributeRequestHooker::get()->hookCurrentReq(packed_data);
return callHandler(handler, calltype, packed_data, request);
}
else
{
if (!async_task_worker_.interruption_requested())
{
DistributeRequestHooker::get()->setHook(calltype, packed_data);
DistributeRequestHooker::get()->hookCurrentReq(packed_data);
asyncWriteTasks_.push(boost::bind(&callHandler,
handler, calltype, packed_data, request));
}
else
{
LOG(INFO) << "write request has been interrupt.";
return false;
}
}
return true;
}
catch (const std::exception& e)
{
LOG(ERROR) << "process request exception: " << e.what();
}
}
else
{
// malformed request
LOG(WARNING) << "read request data error: " << reader.errorMessages();
}
return false;
}
bool DistributeDriver::handleReqFromLog(int reqtype, const std::string& reqjsondata, const std::string& packed_data)
{
if ((ReqLogType)reqtype == Req_CronJob)
{
if (!asyncWriteTasks_.empty())
{
LOG(ERROR) << "another write task is running in async_task_worker_!!";
return false;
}
LOG(INFO) << "got a cron job request in log." << reqjsondata;
DistributeRequestHooker::get()->setHook(Request::FromLog, packed_data);
DistributeRequestHooker::get()->hookCurrentReq(packed_data);
return callCronJob(Request::FromLog, reqjsondata, packed_data);
}
else if ((ReqLogType)reqtype == Req_Callback)
{
if (!asyncWriteTasks_.empty())
{
LOG(ERROR) << "another write task is running in async_task_worker_!!";
return false;
}
LOG(INFO) << "got a callback request in log." << reqjsondata;
std::map<std::string, CBWriteHandlerT>::const_iterator it = callback_handlers_.find(reqjsondata);
if (it == callback_handlers_.end())
{
LOG(WARNING) << "callback write request not found on the node: " << reqjsondata;
return false;
}
DistributeRequestHooker::get()->setHook(Request::FromLog, packed_data);
DistributeRequestHooker::get()->hookCurrentReq(packed_data);
return callCBWriteHandler(Request::FromLog, reqjsondata, it->second);
}
return handleRequest(reqjsondata, packed_data, Request::FromLog);
}
bool DistributeDriver::handleReqFromPrimary(int reqtype, const std::string& reqjsondata, const std::string& packed_data)
{
if ((ReqLogType)reqtype == Req_CronJob)
{
LOG(INFO) << "got a cron job request from primary." << reqjsondata;
if (!async_task_worker_.interruption_requested())
{
DistributeRequestHooker::get()->setHook(Request::FromPrimaryWorker, packed_data);
DistributeRequestHooker::get()->hookCurrentReq(packed_data);
asyncWriteTasks_.push(boost::bind(&callCronJob,
Request::FromPrimaryWorker, reqjsondata, packed_data));
}
else
{
LOG(INFO) << "write task has been interrupt : " << reqjsondata;
return false;
}
return true;
}
else if((ReqLogType)reqtype == Req_Callback)
{
LOG(INFO) << "got a callback request from primary." << reqjsondata;
std::map<std::string, CBWriteHandlerT>::const_iterator it = callback_handlers_.find(reqjsondata);
if (it == callback_handlers_.end())
{
LOG(WARNING) << "callback write request not found on the node: " << reqjsondata;
return false;
}
if (!async_task_worker_.interruption_requested())
{
DistributeRequestHooker::get()->setHook(Request::FromPrimaryWorker, packed_data);
DistributeRequestHooker::get()->hookCurrentReq(packed_data);
asyncWriteTasks_.push(boost::bind(&callCBWriteHandler,
Request::FromPrimaryWorker, reqjsondata, it->second));
}
else
{
LOG(INFO) << "write task has been interrupt : " << reqjsondata;
return false;
}
return true;
}
return handleRequest(reqjsondata, packed_data, Request::FromPrimaryWorker);
}
bool DistributeDriver::pushCallbackWrite(const std::string& name, const std::string& packed_data)
{
LOG(INFO) << "a callback write pushed to queue: " << name;
MasterManagerBase::get()->pushWriteReq(name + "::" + packed_data, "callback");
return true;
}
bool DistributeDriver::on_new_req_available()
{
if (!MasterManagerBase::get()->prepareWriteReq())
{
LOG(WARNING) << "prepare new request failed. maybe some other primary master prepared first. ";
return false;
}
while(true)
{
std::string reqdata;
std::string reqtype;
if(!MasterManagerBase::get()->popWriteReq(reqdata, reqtype))
{
LOG(INFO) << "no more request.";
return false;
}
if(reqtype.empty() && !handleRequest(reqdata, reqdata, Request::FromDistribute) )
{
LOG(WARNING) << "one write request failed to deliver :" << reqdata;
// a write request failed to deliver means the worker did not
// started to handle this request, so the request is ignored, and
// continue to deliver next write request in the queue.
}
else if (reqtype == "api_from_shard")
{
if(!handleRequest(reqdata, reqdata, Request::FromOtherShard))
{
LOG(WARNING) << "one api write request from shard failed to deliver :" << reqdata;
}
else
{
break;
}
}
else if (reqtype == "cron")
{
LOG(INFO) << "got a cron job request from queue." << reqdata;
if (!async_task_worker_.interruption_requested())
{
DistributeRequestHooker::get()->setHook(Request::FromDistribute, reqdata);
DistributeRequestHooker::get()->hookCurrentReq(reqdata);
asyncWriteTasks_.push(boost::bind(&callCronJob,
Request::FromDistribute, reqdata, reqdata));
break;
}
else
{
return false;
}
}
else if (reqtype == "callback")
{
LOG(INFO) << "got a callback write request : " << reqdata;
// get the callback name and packed_data.
size_t split_pos = reqdata.find("::");
if (split_pos == std::string::npos)
{
LOG(WARNING) << "callback data invalid.";
continue;
}
std::string callback_name = reqdata.substr(0, split_pos);
std::string packed_data = reqdata.substr(split_pos + 2);
std::map<std::string, CBWriteHandlerT>::const_iterator it = callback_handlers_.find(callback_name);
if (it == callback_handlers_.end())
{
LOG(WARNING) << "callback write request not found on the node: " << callback_name;
continue;
}
if (!async_task_worker_.interruption_requested())
{
DistributeRequestHooker::get()->setHook(Request::FromOtherShard, packed_data);
DistributeRequestHooker::get()->hookCurrentReq(packed_data);
asyncWriteTasks_.push(boost::bind(&callCBWriteHandler, Request::FromOtherShard,
callback_name, it->second));
break;
}
else
{
return false;
}
}
else
{
// a write request deliver success from master to worker.
// this mean the worker has started to process this request,
// may be not finish writing, so we break here to wait the finished
// event from primary worker.
break;
}
}
return true;
}
}
<|endoftext|>
|
<commit_before>
#include <cppexpose/reflection/Object.h>
#include <cassert>
#include <typeinfo>
#include <unordered_set>
#include <cppexpose/base/string_helpers.h>
#include <cppexpose/variant/Variant.h>
namespace
{
static const char g_separator = '.';
static const std::string g_separatorString = ".";
static const std::string g_parent = "parent";
}
namespace cppexpose
{
Object::Object()
: Object("")
{
}
Object::Object(const std::string & name)
: m_className("Object")
{
initProperty(name, nullptr, PropertyOwnership::None);
}
Object::~Object()
{
clear();
}
const std::string & Object::className() const
{
return m_className;
}
void Object::setClassName(const std::string & className)
{
m_className = className;
}
void Object::clear()
{
// Destroy managed properties
while (m_managedProperties.size() > 0)
{
delete m_managedProperties.front();
}
}
const std::unordered_map<std::string, AbstractProperty *> & Object::properties() const
{
return m_propertiesMap;
}
bool Object::propertyExists(const std::string & name) const
{
return m_propertiesMap.find(name) != m_propertiesMap.end();
}
AbstractProperty * Object::property(size_t index)
{
if (index < m_properties.size()) {
return m_properties[index];
}
return nullptr;
}
const AbstractProperty * Object::property(size_t index) const
{
if (index < m_properties.size()) {
return m_properties[index];
}
return nullptr;
}
AbstractProperty * Object::property(const std::string & path)
{
std::vector<std::string> splittedPath = helper::split(path, g_separator);
return const_cast<AbstractProperty *>(findProperty(splittedPath));
}
const AbstractProperty * Object::property(const std::string & path) const
{
std::vector<std::string> splittedPath = helper::split(path, g_separator);
return findProperty(splittedPath);
}
bool Object::addProperty(AbstractProperty * property, PropertyOwnership ownership)
{
// Reject properties that have no name, or whose name already exists,
// or that already have a parent object.
if (!property || this->propertyExists(property->name()) || property->parent() != nullptr)
{
return false;
}
// Set parent
property->setParent(this);
// Invoke callback
auto newIndex = m_properties.size();
beforeAdd(newIndex, property);
// Add property
m_properties.push_back(property);
m_propertiesMap.insert(std::make_pair(property->name(), property));
// Take ownership over property?
if (ownership == PropertyOwnership::Parent)
{
m_managedProperties.push_back(property);
}
// Invoke callback
afterAdd(newIndex, property);
// Success
return true;
}
bool Object::removeProperty(AbstractProperty * property)
{
// Reject properties that are not part of the object
if (!property || property->parent() != this)
{
return false;
}
// Find property in object
auto it = std::find(m_properties.begin(), m_properties.end(), property);
if (it == m_properties.end())
{
return false;
}
// Get property index
size_t index = std::distance(m_properties.begin(), it);
// Invoke callback
beforeRemove(index, property);
// Remove property from object
m_properties.erase(it);
m_propertiesMap.erase(property->name());
// Remove from managed list
auto it2 = std::find(m_managedProperties.begin(), m_managedProperties.end(), property);
if (it2 != m_managedProperties.end())
{
m_managedProperties.erase(it2);
}
// Reset property parent
property->setParent(nullptr);
// Invoke callback
afterRemove(index, property);
// Success
return true;
}
bool Object::destroyProperty(AbstractProperty * property)
{
// Check that property exists and belongs to the object
if (!property || property->parent() != this)
{
return false;
}
// Chec that property is owned by the object
auto it = std::find(m_managedProperties.begin(), m_managedProperties.end(), property);
if (it == m_properties.end())
{
return false;
}
// Destroy property
delete property;
// Property removed
return true;
}
const std::vector<Method> & Object::functions() const
{
return m_functions;
}
bool Object::isObject() const
{
return true;
}
AbstractTyped * Object::clone() const
{
// [TODO]
return new Object(name());
}
const std::type_info & Object::type() const
{
return typeid(Object);
}
std::string Object::typeName() const
{
return "Object";
}
bool Object::isReadOnly() const
{
return false;
}
bool Object::isComposite() const
{
return true;
}
size_t Object::numSubValues() const
{
return m_properties.size();
}
AbstractTyped * Object::subValue(size_t index)
{
if (index < m_properties.size()) {
return m_properties[index];
}
return nullptr;
}
bool Object::isEnum() const
{
return false;
}
bool Object::isArray() const
{
return false;
}
bool Object::isVariant() const
{
return false;
}
bool Object::isString() const
{
return false;
}
bool Object::isBool() const
{
return false;
}
bool Object::isNumber() const
{
return false;
}
bool Object::isIntegral() const
{
return false;
}
bool Object::isSignedIntegral() const
{
return false;
}
bool Object::isUnsignedIntegral() const
{
return false;
}
bool Object::isFloatingPoint() const
{
return false;
}
Variant Object::toVariant() const
{
// Create variant map from all properties in the object
Variant map = Variant::map();
for (auto it : m_propertiesMap) {
// Get name and property
std::string name = it.first;
AbstractProperty * prop = it.second;
// Add to variant map
(*map.asMap())[name] = prop->toVariant();
}
// Return variant representation
return map;
}
bool Object::fromVariant(const Variant & value)
{
// Check if variant is a map
if (!value.isVariantMap()) {
return false;
}
// Get all values from variant map
for (auto it : *value.asMap()) {
// Get name and value
std::string name = it.first;
const Variant & var = it.second;
// If this names an existing property, set its value
AbstractProperty * prop = this->property(name);
if (prop) {
prop->fromVariant(var);
}
}
// Done
return true;
}
std::string Object::toString() const
{
// Convert object into JSON
SerializerJSON json;
return json.toString(this->toVariant());
}
bool Object::fromString(const std::string & str)
{
// Convert from JSON
Variant values;
SerializerJSON json;
if (json.fromString(values, str)) {
return fromVariant(values);
}
// Error
return false;
}
bool Object::toBool() const
{
return false;
}
bool Object::fromBool(bool)
{
return false;
}
long long Object::toLongLong() const
{
return 0ll;
}
bool Object::fromLongLong(long long)
{
return false;
}
unsigned long long Object::toULongLong() const
{
return 0ull;
}
bool Object::fromULongLong(unsigned long long)
{
return false;
}
double Object::toDouble() const
{
return 0.0;
}
bool Object::fromDouble(double)
{
return false;
}
std::string Object::relativePathTo(const Object * const other) const
{
if(this == other){
return g_separatorString;
}
// find all ancestors of "this"
std::unordered_set<const Object*> ancestors;
std::vector<std::string> thisPath;
const Object * parent = nullptr;
const Object * curObject = this;
while(curObject->hasParent())
{
parent = curObject->parent();
thisPath.push_back(curObject->name());
ancestors.insert(parent);
curObject = parent;
}
// find the intersection from "other"
std::vector<std::string> otherPath;
curObject = other;
bool found = false;
while(curObject->hasParent())
{
parent = curObject->parent();
otherPath.push_back(curObject->name());
if(ancestors.count(parent)){
found = true;
}
curObject = parent;
}
// Ensure there was an intersection
if(!found){
return "";
}
// Shorten the paths
while(thisPath.back() == otherPath.back()){
thisPath.pop_back();
otherPath.pop_back();
}
size_t numParents = thisPath.size();
size_t numChildren = otherPath.size();
// Build the relative Path
std::fill(thisPath.begin(), thisPath.end(), g_parent);
thisPath.insert(thisPath.end(), otherPath.begin(), otherPath.end());
std::string pathString;
// Reserve space for all elements, remembering the seperators and guessing the average length of a property name as 10
pathString.reserve(numParents * (g_parent.size() + 1) + numChildren * (10 +1));
for(const auto& element : thisPath){
pathString.append(element);
pathString.append(g_separatorString);
}
// The above writes one seperator to much
pathString.pop_back();
return pathString;
}
const AbstractProperty * Object::findProperty(const std::vector<std::string> & path) const
{
// [TODO] Use iterative approach rather than recursion
// Check if path is valid
if (path.size() == 0) {
return nullptr;
}
AbstractProperty * property = nullptr;
// Check whether the path points to the parent
if (path.front() == g_parent){
// Check that the parent actually exists
if(m_parent == nullptr){
return nullptr;
}
property = m_parent;
}
else{
// Check if first element of the path exists in this object
if (!propertyExists(path.front())) {
return nullptr;
}
// Get the respective property
property = m_propertiesMap.at(path.front());
}
// If there are no more sub-paths, return the found property
if (path.size() == 1) {
return property;
}
// Otherwise, it is an element in the middle of the path, so ensure it is an object
if (!property->isObject()) {
return nullptr;
}
// Call recursively on sub-object
return static_cast<Object *>(property)->findProperty({ path.begin() + 1, path.end() });
}
} // namespace cppexpose
<commit_msg>Correctly calculating the size of the intermediate string<commit_after>
#include <cppexpose/reflection/Object.h>
#include <cassert>
#include <typeinfo>
#include <unordered_set>
#include <cppexpose/base/string_helpers.h>
#include <cppexpose/variant/Variant.h>
namespace
{
static const char g_separator = '.';
static const std::string g_separatorString = ".";
static const std::string g_parent = "parent";
}
namespace cppexpose
{
Object::Object()
: Object("")
{
}
Object::Object(const std::string & name)
: m_className("Object")
{
initProperty(name, nullptr, PropertyOwnership::None);
}
Object::~Object()
{
clear();
}
const std::string & Object::className() const
{
return m_className;
}
void Object::setClassName(const std::string & className)
{
m_className = className;
}
void Object::clear()
{
// Destroy managed properties
while (m_managedProperties.size() > 0)
{
delete m_managedProperties.front();
}
}
const std::unordered_map<std::string, AbstractProperty *> & Object::properties() const
{
return m_propertiesMap;
}
bool Object::propertyExists(const std::string & name) const
{
return m_propertiesMap.find(name) != m_propertiesMap.end();
}
AbstractProperty * Object::property(size_t index)
{
if (index < m_properties.size()) {
return m_properties[index];
}
return nullptr;
}
const AbstractProperty * Object::property(size_t index) const
{
if (index < m_properties.size()) {
return m_properties[index];
}
return nullptr;
}
AbstractProperty * Object::property(const std::string & path)
{
std::vector<std::string> splittedPath = helper::split(path, g_separator);
return const_cast<AbstractProperty *>(findProperty(splittedPath));
}
const AbstractProperty * Object::property(const std::string & path) const
{
std::vector<std::string> splittedPath = helper::split(path, g_separator);
return findProperty(splittedPath);
}
bool Object::addProperty(AbstractProperty * property, PropertyOwnership ownership)
{
// Reject properties that have no name, or whose name already exists,
// or that already have a parent object.
if (!property || this->propertyExists(property->name()) || property->parent() != nullptr)
{
return false;
}
// Set parent
property->setParent(this);
// Invoke callback
auto newIndex = m_properties.size();
beforeAdd(newIndex, property);
// Add property
m_properties.push_back(property);
m_propertiesMap.insert(std::make_pair(property->name(), property));
// Take ownership over property?
if (ownership == PropertyOwnership::Parent)
{
m_managedProperties.push_back(property);
}
// Invoke callback
afterAdd(newIndex, property);
// Success
return true;
}
bool Object::removeProperty(AbstractProperty * property)
{
// Reject properties that are not part of the object
if (!property || property->parent() != this)
{
return false;
}
// Find property in object
auto it = std::find(m_properties.begin(), m_properties.end(), property);
if (it == m_properties.end())
{
return false;
}
// Get property index
size_t index = std::distance(m_properties.begin(), it);
// Invoke callback
beforeRemove(index, property);
// Remove property from object
m_properties.erase(it);
m_propertiesMap.erase(property->name());
// Remove from managed list
auto it2 = std::find(m_managedProperties.begin(), m_managedProperties.end(), property);
if (it2 != m_managedProperties.end())
{
m_managedProperties.erase(it2);
}
// Reset property parent
property->setParent(nullptr);
// Invoke callback
afterRemove(index, property);
// Success
return true;
}
bool Object::destroyProperty(AbstractProperty * property)
{
// Check that property exists and belongs to the object
if (!property || property->parent() != this)
{
return false;
}
// Chec that property is owned by the object
auto it = std::find(m_managedProperties.begin(), m_managedProperties.end(), property);
if (it == m_properties.end())
{
return false;
}
// Destroy property
delete property;
// Property removed
return true;
}
const std::vector<Method> & Object::functions() const
{
return m_functions;
}
bool Object::isObject() const
{
return true;
}
AbstractTyped * Object::clone() const
{
// [TODO]
return new Object(name());
}
const std::type_info & Object::type() const
{
return typeid(Object);
}
std::string Object::typeName() const
{
return "Object";
}
bool Object::isReadOnly() const
{
return false;
}
bool Object::isComposite() const
{
return true;
}
size_t Object::numSubValues() const
{
return m_properties.size();
}
AbstractTyped * Object::subValue(size_t index)
{
if (index < m_properties.size()) {
return m_properties[index];
}
return nullptr;
}
bool Object::isEnum() const
{
return false;
}
bool Object::isArray() const
{
return false;
}
bool Object::isVariant() const
{
return false;
}
bool Object::isString() const
{
return false;
}
bool Object::isBool() const
{
return false;
}
bool Object::isNumber() const
{
return false;
}
bool Object::isIntegral() const
{
return false;
}
bool Object::isSignedIntegral() const
{
return false;
}
bool Object::isUnsignedIntegral() const
{
return false;
}
bool Object::isFloatingPoint() const
{
return false;
}
Variant Object::toVariant() const
{
// Create variant map from all properties in the object
Variant map = Variant::map();
for (auto it : m_propertiesMap) {
// Get name and property
std::string name = it.first;
AbstractProperty * prop = it.second;
// Add to variant map
(*map.asMap())[name] = prop->toVariant();
}
// Return variant representation
return map;
}
bool Object::fromVariant(const Variant & value)
{
// Check if variant is a map
if (!value.isVariantMap()) {
return false;
}
// Get all values from variant map
for (auto it : *value.asMap()) {
// Get name and value
std::string name = it.first;
const Variant & var = it.second;
// If this names an existing property, set its value
AbstractProperty * prop = this->property(name);
if (prop) {
prop->fromVariant(var);
}
}
// Done
return true;
}
std::string Object::toString() const
{
// Convert object into JSON
SerializerJSON json;
return json.toString(this->toVariant());
}
bool Object::fromString(const std::string & str)
{
// Convert from JSON
Variant values;
SerializerJSON json;
if (json.fromString(values, str)) {
return fromVariant(values);
}
// Error
return false;
}
bool Object::toBool() const
{
return false;
}
bool Object::fromBool(bool)
{
return false;
}
long long Object::toLongLong() const
{
return 0ll;
}
bool Object::fromLongLong(long long)
{
return false;
}
unsigned long long Object::toULongLong() const
{
return 0ull;
}
bool Object::fromULongLong(unsigned long long)
{
return false;
}
double Object::toDouble() const
{
return 0.0;
}
bool Object::fromDouble(double)
{
return false;
}
std::string Object::relativePathTo(const Object * const other) const
{
if(this == other){
return g_separatorString;
}
// find all ancestors of "this"
std::unordered_set<const Object*> ancestors;
std::vector<std::string> thisPath;
const Object * parent = nullptr;
const Object * curObject = this;
while(curObject->hasParent())
{
parent = curObject->parent();
thisPath.push_back(curObject->name());
ancestors.insert(parent);
curObject = parent;
}
// find the intersection from "other"
std::vector<std::string> otherPath;
curObject = other;
bool found = false;
while(curObject->hasParent())
{
parent = curObject->parent();
otherPath.push_back(curObject->name());
if(ancestors.count(parent)){
found = true;
}
curObject = parent;
}
// Ensure there was an intersection
if(!found){
return "";
}
// Shorten the paths
while(thisPath.back() == otherPath.back()){
thisPath.pop_back();
otherPath.pop_back();
}
size_t parentsCharCount = thisPath.size() * (g_parent.size() + 1);
size_t childrenCharCount = 0;
for(const auto & child : otherPath)
{
childrenCharCount += child.size() + 1;
}
// Build the relative Path
std::fill(thisPath.begin(), thisPath.end(), g_parent);
thisPath.insert(thisPath.end(), otherPath.begin(), otherPath.end());
std::string pathString;
pathString.reserve(parentsCharCount + childrenCharCount);
for(const auto& element : thisPath){
pathString.append(element);
pathString.append(g_separatorString);
}
// The above writes one seperator to much
pathString.pop_back();
return pathString;
}
const AbstractProperty * Object::findProperty(const std::vector<std::string> & path) const
{
// [TODO] Use iterative approach rather than recursion
// Check if path is valid
if (path.size() == 0) {
return nullptr;
}
AbstractProperty * property = nullptr;
// Check whether the path points to the parent
if (path.front() == g_parent){
// Check that the parent actually exists
if(m_parent == nullptr){
return nullptr;
}
property = m_parent;
}
else{
// Check if first element of the path exists in this object
if (!propertyExists(path.front())) {
return nullptr;
}
// Get the respective property
property = m_propertiesMap.at(path.front());
}
// If there are no more sub-paths, return the found property
if (path.size() == 1) {
return property;
}
// Otherwise, it is an element in the middle of the path, so ensure it is an object
if (!property->isObject()) {
return nullptr;
}
// Call recursively on sub-object
return static_cast<Object *>(property)->findProperty({ path.begin() + 1, path.end() });
}
} // namespace cppexpose
<|endoftext|>
|
<commit_before>/*
* Copyright (C) 2013 Daniel Nicoletti <dantti12@gmail.com>
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Library General Public
* License as published by the Free Software Foundation; either
* version 2 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Library General Public License for more details.
*
* You should have received a copy of the GNU Library General Public License
* along with this library; see the file COPYING.LIB. If not, write to
* the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
* Boston, MA 02110-1301, USA.
*/
#include "dispatcher_p.h"
#include "common.h"
#include "context.h"
#include "controller.h"
#include "action.h"
#include "request_p.h"
#include "dispatchtypepath.h"
#include <QUrl>
#include <QMetaMethod>
#include <QStringBuilder>
#include <QDebug>
using namespace Cutelyst;
Dispatcher::Dispatcher(QObject *parent) :
QObject(parent),
d_ptr(new DispatcherPrivate)
{
Q_D(Dispatcher);
}
Dispatcher::~Dispatcher()
{
delete d_ptr;
}
void Dispatcher::setupActions(const QList<Controller*> &controllers)
{
Q_D(Dispatcher);
if (d->dispatchers.isEmpty()) {
registerDispatchType(new DispatchTypePath(this));
}
foreach (Controller *controller, controllers) {
// App controller
// qDebug() << "Found a controller:" << controller << meta->className();
const QMetaObject *meta = controller->metaObject();
controller->setObjectName(meta->className());
bool instanceUsed = false;
for (int i = 0; i < meta->methodCount(); ++i) {
QMetaMethod method = meta->method(i);
if (method.methodType() == QMetaMethod::Method) {
// qDebug() << Q_FUNC_INFO << method.name() << method.attributes() << method.methodType() << method.methodSignature();
// qDebug() << Q_FUNC_INFO << method.parameterTypes() << method.tag() << method.access();
bool registered = false;
Action *action = new Action(method, controller);
if (action->isValid() && !d->actionHash.contains(action->privateName())) {
if (!action->attributes().contains("Private")) {
// Register the action with each dispatcher
foreach (DispatchType *dispatch, d->dispatchers) {
if (dispatch->registerAction(action)) {
registered = true;
}
}
} else {
// We register private actions
registered = true;
}
}
// The Begin, Auto, End actions are not
// registered by Dispatchers but we need them
// as private actions anyway
if (registered || action->isValid()) {
d->actionHash.insert(action->privateName(), action);
d->containerHash[action->ns()] << action;
instanceUsed = true;
} else {
delete action;
}
}
}
if (instanceUsed) {
d->constrollerHash.insert(meta->className(), controller);
}
}
printActions();
}
bool Dispatcher::dispatch(Context *ctx)
{
if (ctx->action()) {
return ctx->forward(QLatin1Char('/') % ctx->action()->ns() % QLatin1String("/_DISPATCH"));
} else {
QString error;
const QString &path = ctx->req()->path();
if (path.isEmpty()) {
error = QLatin1String("No default action defined");
} else {
error = QLatin1String("Unknown resource \"") % path % QLatin1Char('"');
}
qCDebug(CUTELYST_DISPATCHER) << error;
ctx->error(error);
}
return false;
}
bool Dispatcher::forward(Context *ctx, const QString &opname, const QStringList &arguments)
{
Action *action = command2Action(ctx, opname);
if (action) {
return action->dispatch(ctx);
}
qCCritical(CUTELYST_DISPATCHER) << "Action not found" << action;
return false;
}
void Dispatcher::prepareAction(Context *ctx)
{
Q_D(Dispatcher);
QString path = ctx->req()->path();
QStringList pathParts = path.split(QLatin1Char('/'));
QStringList args;
// Root action
pathParts.prepend(QLatin1String(""));
while (!pathParts.isEmpty()) {
path = pathParts.join(QLatin1Char('/'));
path.remove(d->initialSlash);
foreach (DispatchType *type, d->dispatchers) {
if (type->match(ctx, path)) {
if (!path.isEmpty()) {
qCDebug(CUTELYST_DISPATCHER) << "Path is" << path;
}
if (!ctx->args().isEmpty()) {
qCDebug(CUTELYST_DISPATCHER) << "Arguments are" << ctx->args().join(QLatin1Char('/'));
}
return;
}
}
args.prepend(pathParts.takeLast());
ctx->req()->d_ptr->args = unexcapedArgs(args);
}
}
Action *Dispatcher::getAction(const QString &name, const QString &ns) const
{
Q_D(const Dispatcher);
if (name.isEmpty()) {
return 0;
}
QString _ns = cleanNamespace(ns);
return d->actionHash.value(_ns % QLatin1Char('/') % name);
}
ActionList Dispatcher::getActions(const QString &name, const QString &ns) const
{
Q_D(const Dispatcher);
ActionList ret;
if (name.isEmpty()) {
return ret;
}
QString _ns = cleanNamespace(ns);
ActionList containers = d->getContainers(_ns);
foreach (Action *action, containers) {
if (action->name() == name) {
ret.prepend(action);
}
}
return ret;
}
QHash<QString, Controller *> Dispatcher::controllers() const
{
Q_D(const Dispatcher);
return d->constrollerHash;
}
QString Dispatcher::uriForAction(Action *action, const QStringList &captures)
{
Q_D(const Dispatcher);
foreach (DispatchType *dispatch, d->dispatchers) {
QString uri = dispatch->uriForAction(action, captures);
if (!uri.isNull()) {
return uri.isEmpty() ? QLatin1String("/") : uri;
}
}
return QString();
}
void Dispatcher::registerDispatchType(DispatchType *dispatchType)
{
Q_D(Dispatcher);
d->dispatchers.append(dispatchType);
}
void Dispatcher::printActions()
{
Q_D(Dispatcher);
QString buffer;
QTextStream out(&buffer, QIODevice::WriteOnly);
bool showInternalActions = false;
out << "Loaded Private actions:" << endl;
QString privateTitle("Private");
QString classTitle("Class");
QString methodTitle("Method");
int privateLength = privateTitle.length();
int classLength = classTitle.length();
int actionLength = methodTitle.length();
QMap<QString, Action*>::ConstIterator it = d->actionHash.constBegin();
while (it != d->actionHash.constEnd()) {
Action *action = it.value();
QString path = it.key();
if (!path.startsWith(QLatin1String("/"))) {
path.prepend(QLatin1String("/"));
}
privateLength = qMax(privateLength, path.length());
classLength = qMax(classLength, action->className().length());
actionLength = qMax(actionLength, action->name().length());
++it;
}
out << "." << QString().fill(QLatin1Char('-'), privateLength).toUtf8().data()
<< "+" << QString().fill(QLatin1Char('-'), classLength).toUtf8().data()
<< "+" << QString().fill(QLatin1Char('-'), actionLength).toUtf8().data()
<< "." << endl;
out << "|" << privateTitle.leftJustified(privateLength).toUtf8().data()
<< "|" << classTitle.leftJustified(classLength).toUtf8().data()
<< "|" << methodTitle.leftJustified(actionLength).toUtf8().data()
<< "|" << endl;
out << "." << QString().fill(QLatin1Char('-'), privateLength).toUtf8().data()
<< "+" << QString().fill(QLatin1Char('-'), classLength).toUtf8().data()
<< "+" << QString().fill(QLatin1Char('-'), actionLength).toUtf8().data()
<< "." << endl;
it = d->actionHash.constBegin();
while (it != d->actionHash.constEnd()) {
Action *action = it.value();
if (showInternalActions || !action->name().startsWith(QLatin1Char('_'))) {
QString path = it.key();
if (!path.startsWith(QLatin1String("/"))) {
path.prepend(QLatin1String("/"));
}
out << "|" << path.leftJustified(privateLength).toUtf8().data()
<< "|" << action->className().leftJustified(classLength).toUtf8().data()
<< "|" << action->name().leftJustified(actionLength).toUtf8().data()
<< "|" << endl;
}
++it;
}
out << "." << QString().fill(QLatin1Char('-'), privateLength).toUtf8().data()
<< "+" << QString().fill(QLatin1Char('-'), classLength).toUtf8().data()
<< "+" << QString().fill(QLatin1Char('-'), actionLength).toUtf8().data()
<< ".";
qCDebug(CUTELYST_DISPATCHER) << buffer.toUtf8().data();
// List all public actions
foreach (DispatchType *dispatch, d->dispatchers) {
dispatch->list();
}
}
Action *Dispatcher::command2Action(Context *ctx, const QString &command, const QStringList &extraParams)
{
Q_D(Dispatcher);
// qDebug() << Q_FUNC_INFO << "Command" << command;
Action *ret = d->actionHash.value(command);
if (!ret) {
ret = invokeAsPath(ctx, command, ctx->args());
}
return ret;
}
QStringList Dispatcher::unexcapedArgs(const QStringList &args)
{
QStringList ret;
foreach (const QString &arg, args) {
ret << QUrl::fromPercentEncoding(arg.toLocal8Bit());
}
return ret;
}
QString Dispatcher::actionRel2Abs(Context *ctx, const QString &path)
{
QString ret = path;
if (!ret.startsWith(QLatin1Char('/'))) {
// TODO at Catalyst it uses
// c->stack->last()->namespace
QString ns = ctx->action()->ns();
ret = ns % QLatin1Char('/') % path;
}
if (ret.startsWith(QLatin1Char('/'))) {
ret.remove(0, 1);
}
return ret;
}
Action *Dispatcher::invokeAsPath(Context *ctx, const QString &relativePath, const QStringList &args)
{
Action *ret = 0;
QString path = actionRel2Abs(ctx, relativePath);
QRegularExpression re("^(?:(.*)/)?(\\w+)?$");
while (!path.isEmpty()) {
QRegularExpressionMatch match = re.match(path);
if (match.hasMatch()) {
path = match.captured(1);
ret = getAction(match.captured(2), path);
if (ret) {
break;
}
} else {
break;
}
}
return ret;
}
QString Dispatcher::cleanNamespace(const QString &ns) const
{
QStringList ret;
foreach (const QString &part, ns.split(QLatin1Char('/'))) {
if (!part.isEmpty()) {
ret << part;
}
}
return ret.join(QLatin1Char('/'));
}
ActionList DispatcherPrivate::getContainers(const QString &ns) const
{
ActionList ret;
QString _ns = ns;
if (_ns == QLatin1String("/")) {
_ns = QLatin1String("");
}
while (!_ns.isEmpty()) {
ret << containerHash.value(_ns);
_ns = _ns.section(QLatin1Char('/'), 0, -2);
}
ret << containerHash.value(_ns);
return ret;
}
<commit_msg>Let the dispatcher work with slots too<commit_after>/*
* Copyright (C) 2013 Daniel Nicoletti <dantti12@gmail.com>
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Library General Public
* License as published by the Free Software Foundation; either
* version 2 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Library General Public License for more details.
*
* You should have received a copy of the GNU Library General Public License
* along with this library; see the file COPYING.LIB. If not, write to
* the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
* Boston, MA 02110-1301, USA.
*/
#include "dispatcher_p.h"
#include "common.h"
#include "context.h"
#include "controller.h"
#include "action.h"
#include "request_p.h"
#include "dispatchtypepath.h"
#include <QUrl>
#include <QMetaMethod>
#include <QStringBuilder>
#include <QDebug>
using namespace Cutelyst;
Dispatcher::Dispatcher(QObject *parent) :
QObject(parent),
d_ptr(new DispatcherPrivate)
{
Q_D(Dispatcher);
}
Dispatcher::~Dispatcher()
{
delete d_ptr;
}
void Dispatcher::setupActions(const QList<Controller*> &controllers)
{
Q_D(Dispatcher);
if (d->dispatchers.isEmpty()) {
registerDispatchType(new DispatchTypePath(this));
}
foreach (Controller *controller, controllers) {
// App controller
// qDebug() << "Found a controller:" << controller << meta->className();
const QMetaObject *meta = controller->metaObject();
controller->setObjectName(meta->className());
bool instanceUsed = false;
for (int i = 0; i < meta->methodCount(); ++i) {
QMetaMethod method = meta->method(i);
if (method.methodType() == QMetaMethod::Method ||
method.methodType() == QMetaMethod::Slot) {
bool registered = false;
Action *action = new Action(method, controller);
if (action->isValid() && !d->actionHash.contains(action->privateName())) {
if (!action->attributes().contains("Private")) {
// Register the action with each dispatcher
foreach (DispatchType *dispatch, d->dispatchers) {
if (dispatch->registerAction(action)) {
registered = true;
}
}
} else {
// We register private actions
registered = true;
}
}
// The Begin, Auto, End actions are not
// registered by Dispatchers but we need them
// as private actions anyway
if (registered || action->isValid()) {
d->actionHash.insert(action->privateName(), action);
d->containerHash[action->ns()] << action;
instanceUsed = true;
} else {
delete action;
}
}
}
if (instanceUsed) {
d->constrollerHash.insert(meta->className(), controller);
}
}
printActions();
}
bool Dispatcher::dispatch(Context *ctx)
{
if (ctx->action()) {
return ctx->forward(QLatin1Char('/') % ctx->action()->ns() % QLatin1String("/_DISPATCH"));
} else {
QString error;
const QString &path = ctx->req()->path();
if (path.isEmpty()) {
error = QLatin1String("No default action defined");
} else {
error = QLatin1String("Unknown resource \"") % path % QLatin1Char('"');
}
qCDebug(CUTELYST_DISPATCHER) << error;
ctx->error(error);
}
return false;
}
bool Dispatcher::forward(Context *ctx, const QString &opname, const QStringList &arguments)
{
Action *action = command2Action(ctx, opname);
if (action) {
return action->dispatch(ctx);
}
qCCritical(CUTELYST_DISPATCHER) << "Action not found" << action;
return false;
}
void Dispatcher::prepareAction(Context *ctx)
{
Q_D(Dispatcher);
QString path = ctx->req()->path();
QStringList pathParts = path.split(QLatin1Char('/'));
QStringList args;
// Root action
pathParts.prepend(QLatin1String(""));
while (!pathParts.isEmpty()) {
path = pathParts.join(QLatin1Char('/'));
path.remove(d->initialSlash);
foreach (DispatchType *type, d->dispatchers) {
if (type->match(ctx, path)) {
if (!path.isEmpty()) {
qCDebug(CUTELYST_DISPATCHER) << "Path is" << path;
}
if (!ctx->args().isEmpty()) {
qCDebug(CUTELYST_DISPATCHER) << "Arguments are" << ctx->args().join(QLatin1Char('/'));
}
return;
}
}
args.prepend(pathParts.takeLast());
ctx->req()->d_ptr->args = unexcapedArgs(args);
}
}
Action *Dispatcher::getAction(const QString &name, const QString &ns) const
{
Q_D(const Dispatcher);
if (name.isEmpty()) {
return 0;
}
QString _ns = cleanNamespace(ns);
return d->actionHash.value(_ns % QLatin1Char('/') % name);
}
ActionList Dispatcher::getActions(const QString &name, const QString &ns) const
{
Q_D(const Dispatcher);
ActionList ret;
if (name.isEmpty()) {
return ret;
}
QString _ns = cleanNamespace(ns);
ActionList containers = d->getContainers(_ns);
foreach (Action *action, containers) {
if (action->name() == name) {
ret.prepend(action);
}
}
return ret;
}
QHash<QString, Controller *> Dispatcher::controllers() const
{
Q_D(const Dispatcher);
return d->constrollerHash;
}
QString Dispatcher::uriForAction(Action *action, const QStringList &captures)
{
Q_D(const Dispatcher);
foreach (DispatchType *dispatch, d->dispatchers) {
QString uri = dispatch->uriForAction(action, captures);
if (!uri.isNull()) {
return uri.isEmpty() ? QLatin1String("/") : uri;
}
}
return QString();
}
void Dispatcher::registerDispatchType(DispatchType *dispatchType)
{
Q_D(Dispatcher);
d->dispatchers.append(dispatchType);
}
void Dispatcher::printActions()
{
Q_D(Dispatcher);
QString buffer;
QTextStream out(&buffer, QIODevice::WriteOnly);
bool showInternalActions = false;
out << "Loaded Private actions:" << endl;
QString privateTitle("Private");
QString classTitle("Class");
QString methodTitle("Method");
int privateLength = privateTitle.length();
int classLength = classTitle.length();
int actionLength = methodTitle.length();
QMap<QString, Action*>::ConstIterator it = d->actionHash.constBegin();
while (it != d->actionHash.constEnd()) {
Action *action = it.value();
QString path = it.key();
if (!path.startsWith(QLatin1String("/"))) {
path.prepend(QLatin1String("/"));
}
privateLength = qMax(privateLength, path.length());
classLength = qMax(classLength, action->className().length());
actionLength = qMax(actionLength, action->name().length());
++it;
}
out << "." << QString().fill(QLatin1Char('-'), privateLength).toUtf8().data()
<< "+" << QString().fill(QLatin1Char('-'), classLength).toUtf8().data()
<< "+" << QString().fill(QLatin1Char('-'), actionLength).toUtf8().data()
<< "." << endl;
out << "|" << privateTitle.leftJustified(privateLength).toUtf8().data()
<< "|" << classTitle.leftJustified(classLength).toUtf8().data()
<< "|" << methodTitle.leftJustified(actionLength).toUtf8().data()
<< "|" << endl;
out << "." << QString().fill(QLatin1Char('-'), privateLength).toUtf8().data()
<< "+" << QString().fill(QLatin1Char('-'), classLength).toUtf8().data()
<< "+" << QString().fill(QLatin1Char('-'), actionLength).toUtf8().data()
<< "." << endl;
it = d->actionHash.constBegin();
while (it != d->actionHash.constEnd()) {
Action *action = it.value();
if (showInternalActions || !action->name().startsWith(QLatin1Char('_'))) {
QString path = it.key();
if (!path.startsWith(QLatin1String("/"))) {
path.prepend(QLatin1String("/"));
}
out << "|" << path.leftJustified(privateLength).toUtf8().data()
<< "|" << action->className().leftJustified(classLength).toUtf8().data()
<< "|" << action->name().leftJustified(actionLength).toUtf8().data()
<< "|" << endl;
}
++it;
}
out << "." << QString().fill(QLatin1Char('-'), privateLength).toUtf8().data()
<< "+" << QString().fill(QLatin1Char('-'), classLength).toUtf8().data()
<< "+" << QString().fill(QLatin1Char('-'), actionLength).toUtf8().data()
<< ".";
qCDebug(CUTELYST_DISPATCHER) << buffer.toUtf8().data();
// List all public actions
foreach (DispatchType *dispatch, d->dispatchers) {
dispatch->list();
}
}
Action *Dispatcher::command2Action(Context *ctx, const QString &command, const QStringList &extraParams)
{
Q_D(Dispatcher);
// qDebug() << Q_FUNC_INFO << "Command" << command;
Action *ret = d->actionHash.value(command);
if (!ret) {
ret = invokeAsPath(ctx, command, ctx->args());
}
return ret;
}
QStringList Dispatcher::unexcapedArgs(const QStringList &args)
{
QStringList ret;
foreach (const QString &arg, args) {
ret << QUrl::fromPercentEncoding(arg.toLocal8Bit());
}
return ret;
}
QString Dispatcher::actionRel2Abs(Context *ctx, const QString &path)
{
QString ret = path;
if (!ret.startsWith(QLatin1Char('/'))) {
// TODO at Catalyst it uses
// c->stack->last()->namespace
QString ns = ctx->action()->ns();
ret = ns % QLatin1Char('/') % path;
}
if (ret.startsWith(QLatin1Char('/'))) {
ret.remove(0, 1);
}
return ret;
}
Action *Dispatcher::invokeAsPath(Context *ctx, const QString &relativePath, const QStringList &args)
{
Action *ret = 0;
QString path = actionRel2Abs(ctx, relativePath);
QRegularExpression re("^(?:(.*)/)?(\\w+)?$");
while (!path.isEmpty()) {
QRegularExpressionMatch match = re.match(path);
if (match.hasMatch()) {
path = match.captured(1);
ret = getAction(match.captured(2), path);
if (ret) {
break;
}
} else {
break;
}
}
return ret;
}
QString Dispatcher::cleanNamespace(const QString &ns) const
{
QStringList ret;
foreach (const QString &part, ns.split(QLatin1Char('/'))) {
if (!part.isEmpty()) {
ret << part;
}
}
return ret.join(QLatin1Char('/'));
}
ActionList DispatcherPrivate::getContainers(const QString &ns) const
{
ActionList ret;
QString _ns = ns;
if (_ns == QLatin1String("/")) {
_ns = QLatin1String("");
}
while (!_ns.isEmpty()) {
ret << containerHash.value(_ns);
_ns = _ns.section(QLatin1Char('/'), 0, -2);
}
ret << containerHash.value(_ns);
return ret;
}
<|endoftext|>
|
<commit_before>#pragma once
namespace Channel9
{
// Forward declare stuff to avoid loops in headers.
union Value;
class Environment;
class CallableContext;
struct String;
struct Tuple;
struct RunningContext;
struct RunnableContext;
class IStream;
class Message;
enum ValueType
{
POSITIVE_NUMBER = 0x00,
BTRUE = 0x10,
FLOAT_NUM = 0x20,
// these are types that will eventually
// be made into full heap types, but for now
// are allocated on the normal heap so need
// to be treated as plain old values.
CALLABLE_CONTEXT= 0x40,
// Bit pattern of 0000 1000 indicates falsy,
// all other type patterns are truthy.
FALSY_MASK = 0xCF,
FALSY_PATTERN = 0x80,
NIL = 0x80,
UNDEF = 0x90,
BFALSE = 0xA0,
// don't use = 0xB0,
// All heap types have E as their high nibble,
// as that nibble comes from the reference itself
// and indicates that the full type is in the
// next nibble of the address
HEAP_TYPE = 0xE0,
VARIABLE_FRAME = 0xE2,
STRING = 0xE3,
TUPLE = 0xE4,
MESSAGE = 0xE5,
RUNNABLE_CONTEXT= 0xE7,
RUNNING_CONTEXT = 0xE8,
NEGATIVE_NUMBER = 0xF0
};
}
#include "trace.hpp"
#if defined(DEBUG)
# define DO_DEBUG if (true)
#else
# define DO_DEBUG if (false)
#endif
<commit_msg>Add a ptrdiff_t that isn't screwed up on osx.<commit_after>#pragma once
#include <stddef.h>
#include <stdint.h>
namespace Channel9
{
// Forward declare stuff to avoid loops in headers.
union Value;
class Environment;
class CallableContext;
struct String;
struct Tuple;
struct RunningContext;
struct RunnableContext;
class IStream;
class Message;
enum ValueType
{
POSITIVE_NUMBER = 0x00,
BTRUE = 0x10,
FLOAT_NUM = 0x20,
// these are types that will eventually
// be made into full heap types, but for now
// are allocated on the normal heap so need
// to be treated as plain old values.
CALLABLE_CONTEXT= 0x40,
// Bit pattern of 0000 1000 indicates falsy,
// all other type patterns are truthy.
FALSY_MASK = 0xCF,
FALSY_PATTERN = 0x80,
NIL = 0x80,
UNDEF = 0x90,
BFALSE = 0xA0,
// don't use = 0xB0,
// All heap types have E as their high nibble,
// as that nibble comes from the reference itself
// and indicates that the full type is in the
// next nibble of the address
HEAP_TYPE = 0xE0,
VARIABLE_FRAME = 0xE2,
STRING = 0xE3,
TUPLE = 0xE4,
MESSAGE = 0xE5,
RUNNABLE_CONTEXT= 0xE7,
RUNNING_CONTEXT = 0xE8,
NEGATIVE_NUMBER = 0xF0
};
/* On some platforms (*cough* OSX/x64 *cough*), uintptr_t doesn't map
* to the same type as any of the uint*_t types (uint64 is long long and
* uintptr_t is long), and this makes function overloading just plain not
* work. To get around this, we redefine uintptr_t for the channel9
* namespace so it matches one of those types.
*/
template <size_t ptrsize_t>
struct ptrsize;
template <>
struct ptrsize<4>
{
typedef uint32_t ptrtype_t;
};
template <>
struct ptrsize<8>
{
typedef uint64_t ptrtype_t;
};
typedef ptrsize<sizeof(void*)>::ptrtype_t uintptr_t;
}
#include "trace.hpp"
#if defined(DEBUG)
# define DO_DEBUG if (true)
#else
# define DO_DEBUG if (false)
#endif
<|endoftext|>
|
<commit_before>/****************************************************************************
**
** Copyright (C) 2010 Nokia Corporation and/or its subsidiary(-ies).
** All rights reserved.
** Contact: Nokia Corporation (qt-info@nokia.com)
**
** This file is part of the Qt Mobility Components.
**
** $QT_BEGIN_LICENSE:LGPL$
** No Commercial Usage
** This file contains pre-release code and may not be distributed.
** You may use this file in accordance with the terms and conditions
** contained in the Technology Preview License Agreement accompanying
** this package.
**
** GNU Lesser General Public License Usage
** Alternatively, this file may be used under the terms of the GNU Lesser
** General Public License version 2.1 as published by the Free Software
** Foundation and appearing in the file LICENSE.LGPL included in the
** packaging of this file. Please review the following information to
** ensure the GNU Lesser General Public License version 2.1 requirements
** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
**
** In addition, as a special exception, Nokia gives you certain additional
** rights. These rights are described in the Nokia Qt LGPL Exception
** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
**
** If you have questions regarding the use of this file, please contact
** Nokia at qt-info@nokia.com.
**
**
**
**
**
**
**
**
** $QT_END_LICENSE$
**
****************************************************************************/
#include "qbluetoothservicediscoveryagent_p.h"
#include <QUrl>
#include <arpa/inet.h>
#include <netinet/in.h>
QTM_BEGIN_NAMESPACE
QBluetoothServiceDiscoveryAgentPrivate::QBluetoothServiceDiscoveryAgentPrivate(const QBluetoothAddress &address)
: error(QBluetoothServiceDiscoveryAgent::NoError)
, state(Inactive)
, deviceAddress(address)
, deviceDiscoveryAgent(0)
, mode(QBluetoothServiceDiscoveryAgent::MinimalDiscovery)
, m_sdpAgent(NULL)
, m_filter(NULL)
, m_attributes(NULL)
{
}
QBluetoothServiceDiscoveryAgentPrivate::~QBluetoothServiceDiscoveryAgentPrivate()
{
delete m_filter;
delete m_attributes;
delete m_sdpAgent;
}
void QBluetoothServiceDiscoveryAgentPrivate::start(const QBluetoothAddress &address)
{
Q_Q(QBluetoothServiceDiscoveryAgent);
TRAPD(err, startL(address));
if (err != KErrNone) {
error = QBluetoothServiceDiscoveryAgent::UnknownError;
emit q->error(error);
}
}
void QBluetoothServiceDiscoveryAgentPrivate::startL(const QBluetoothAddress &address)
{
initL(address);
if (uuidFilter.isEmpty()) {
m_filter->AddL(QBluetoothUuid::PublicBrowseGroup);
} else {
foreach (const QBluetoothUuid &uuid, uuidFilter) {
if (uuid.minimumSize() == 2) {
TUUID sUuid(uuid.toUInt16());
m_filter->AddL(sUuid);
} else if (uuid.minimumSize() == 4) {
TUUID sUuid(uuid.toUInt32());
m_filter->AddL(sUuid);
} else if (uuid.minimumSize() == 16) {
TUint32 *dataPointer = (TUint32*)uuid.toUInt128().data;
TUint32 lL = *(dataPointer++);
TUint32 lH = *(dataPointer++);
TUint32 hL = *(dataPointer++);
TUint32 hH = *(dataPointer);
TUUID sUuid(hH, hL, lH, lL);
m_filter->AddL(sUuid);
} else {
// filter size can be 0 on error cases, searching all services
m_filter->AddL(QBluetoothUuid::PublicBrowseGroup);
}
}
}
m_sdpAgent->SetRecordFilterL(*m_filter);
m_sdpAgent->NextRecordRequestL();
}
void QBluetoothServiceDiscoveryAgentPrivate::stop()
{
delete m_sdpAgent;
m_sdpAgent = NULL;
delete m_filter;
m_filter = NULL;
delete m_attributes;
m_attributes = NULL;
}
void QBluetoothServiceDiscoveryAgentPrivate::initL(const QBluetoothAddress &address)
{
TBTDevAddr btAddress(address.toUInt64());
stop();
//Trapped in Start
m_sdpAgent = q_check_ptr(CSdpAgent::NewL(*this, btAddress));
m_filter = q_check_ptr(CSdpSearchPattern::NewL());
m_attributes = q_check_ptr(CSdpAttrIdMatchList::NewL());
m_attributes->AddL(KAttrRangeAll);
}
bool QBluetoothServiceDiscoveryAgentPrivate::quickDiscovery(const QBluetoothAddress &address, const QBluetoothDeviceInfo &info)
{
return false;
}
void QBluetoothServiceDiscoveryAgentPrivate::NextRecordRequestComplete(TInt aError, TSdpServRecordHandle aHandle, TInt aTotalRecordsCount)
{
Q_Q(QBluetoothServiceDiscoveryAgent);
if (aError == KErrNone && aTotalRecordsCount > 0 && m_sdpAgent && m_attributes) {
// request attributes
TRAPD(err, m_sdpAgent->AttributeRequestL(aHandle, *m_attributes));
if (err) {
error = QBluetoothServiceDiscoveryAgent::UnknownError;
emit q->error(error);
}
} else if (aError == KErrEof) {
_q_serviceDiscoveryFinished();
} else {
_q_serviceDiscoveryFinished();
}
}
void QBluetoothServiceDiscoveryAgentPrivate::AttributeRequestResult(TSdpServRecordHandle, TSdpAttributeID aAttrID, CSdpAttrValue *aAttrValue)
{
Q_Q(QBluetoothServiceDiscoveryAgent);
m_currentAttributeId = aAttrID;
TRAPD(err, aAttrValue->AcceptVisitorL(*this));
if (m_stack.size() != 1) {
error = QBluetoothServiceDiscoveryAgent::UnknownError;
emit q->error(error);
delete aAttrValue;
return;
}
m_serviceInfo.setAttribute(aAttrID, m_stack.pop());
if (err != KErrNone) {
error = QBluetoothServiceDiscoveryAgent::UnknownError;
emit q->error(error);
}
delete aAttrValue;
}
void QBluetoothServiceDiscoveryAgentPrivate::AttributeRequestComplete(TSdpServRecordHandle, TInt aError)
{
Q_Q(QBluetoothServiceDiscoveryAgent);
if (aError == KErrNone && m_sdpAgent) {
m_serviceInfo.setDevice(discoveredDevices.at(0));
discoveredServices.append(m_serviceInfo);
m_serviceInfo = QBluetoothServiceInfo();
TRAPD(err, m_sdpAgent->NextRecordRequestL());
if (err != KErrNone) {
error = QBluetoothServiceDiscoveryAgent::UnknownError;
emit q->error(error);
}
} else if (aError != KErrEof) {
error = QBluetoothServiceDiscoveryAgent::UnknownError;
emit q->error(error);
}
// emit found service.
if (discoveredServices.last().isValid())
emit q->serviceDiscovered(discoveredServices.last());
}
void QBluetoothServiceDiscoveryAgentPrivate::VisitAttributeValueL(CSdpAttrValue &aValue, TSdpElementType aType)
{
QVariant var;
TUint datasize = aValue.DataSize();
switch (aType) {
case ETypeNil:
break;
case ETypeUint:
if (datasize == 8) {
TUint64 value;
aValue.Uint64(value);
var = QVariant::fromValue(value);
} else
var = QVariant::fromValue(aValue.Uint());
break;
case ETypeInt:
var = QVariant::fromValue(aValue.Int());
break;
case ETypeUUID: {
TPtrC8 shortForm(aValue.UUID().ShortestForm());
if (shortForm.Size() == 2) {
QBluetoothUuid uuid(ntohs(*reinterpret_cast<const quint16 *>(shortForm.Ptr())));
var = QVariant::fromValue(uuid);
} else if (shortForm.Size() == 4) {
QBluetoothUuid uuid(ntohl(*reinterpret_cast<const quint32 *>(shortForm.Ptr())));
var = QVariant::fromValue(uuid);
} else if (shortForm.Size() == 16) {
QBluetoothUuid uuid(*reinterpret_cast<const quint128 *>(shortForm.Ptr()));
var = QVariant::fromValue(uuid);
}
break;
}
case ETypeString: {
TPtrC8 stringBuffer = aValue.Des();
var = QVariant::fromValue(QString::fromLocal8Bit(reinterpret_cast<const char *>(stringBuffer.Ptr()), stringBuffer.Size()));
break;
}
case ETypeBoolean:
var = QVariant::fromValue(static_cast<bool>(aValue.Bool()));
break;
case ETypeDES:
m_stack.push(QVariant::fromValue(QBluetoothServiceInfo::Sequence()));
break;
case ETypeDEA:
m_stack.push(QVariant::fromValue(QBluetoothServiceInfo::Alternative()));
break;
case ETypeURL: {
TPtrC8 stringBuffer = aValue.Des();
var = QVariant::fromValue(QUrl(QString::fromLocal8Bit(reinterpret_cast<const char *>(stringBuffer.Ptr()), stringBuffer.Size())));
break;
}
case ETypeEncoded:
qWarning() << "Don't know how to handle encoded type.";
break;
default:
qWarning() << "Don't know how to handle type" << aType;
}
if (aType != ETypeDES && aType != ETypeDEA) {
if (m_stack.size() == 0) {
// single value attribute, just push onto stack
m_stack.push(var);
} else if (m_stack.size() >= 1) {
// sequence or alternate attribute, add non-DES -DEA values to DES or DEA
if (m_stack.top().canConvert<QBluetoothServiceInfo::Sequence>()) {
QBluetoothServiceInfo::Sequence *sequence = static_cast<QBluetoothServiceInfo::Sequence *>(m_stack.top().data());
sequence->append(var);
} else if (m_stack.top().canConvert<QBluetoothServiceInfo::Alternative>()) {
QBluetoothServiceInfo::Alternative *alternative = static_cast<QBluetoothServiceInfo::Alternative *>(m_stack.top().data());
alternative->append(var);
} else {
qWarning("Unknown type in the QVariant, should be either a QBluetoothServiceInfo::Sequence or an QBluetoothServiceInfo::Alternative");
}
}
}
}
void QBluetoothServiceDiscoveryAgentPrivate::StartListL(CSdpAttrValueList &)
{
}
void QBluetoothServiceDiscoveryAgentPrivate::EndListL()
{
if (m_stack.size() > 1) {
// finished a sequence or alternative add it to the parent sequence or alternative
QVariant var = m_stack.pop();
if (m_stack.top().canConvert<QBluetoothServiceInfo::Sequence>()) {
QBluetoothServiceInfo::Sequence *sequence = static_cast<QBluetoothServiceInfo::Sequence *>(m_stack.top().data());
sequence->append(var);
} else if (m_stack.top().canConvert<QBluetoothServiceInfo::Alternative>()) {
QBluetoothServiceInfo::Alternative *alternative = static_cast<QBluetoothServiceInfo::Alternative *>(m_stack.top().data());
alternative->append(var);
} else {
qWarning("Unknown type in the QVariant, should be either a QBluetoothServiceInfo::Sequence or an QBluetoothServiceInfo::Alternative");
}
}
}
QTM_END_NAMESPACE
<commit_msg>Fix convertion of QBluetoothUuid to TUUID<commit_after>/****************************************************************************
**
** Copyright (C) 2010 Nokia Corporation and/or its subsidiary(-ies).
** All rights reserved.
** Contact: Nokia Corporation (qt-info@nokia.com)
**
** This file is part of the Qt Mobility Components.
**
** $QT_BEGIN_LICENSE:LGPL$
** No Commercial Usage
** This file contains pre-release code and may not be distributed.
** You may use this file in accordance with the terms and conditions
** contained in the Technology Preview License Agreement accompanying
** this package.
**
** GNU Lesser General Public License Usage
** Alternatively, this file may be used under the terms of the GNU Lesser
** General Public License version 2.1 as published by the Free Software
** Foundation and appearing in the file LICENSE.LGPL included in the
** packaging of this file. Please review the following information to
** ensure the GNU Lesser General Public License version 2.1 requirements
** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
**
** In addition, as a special exception, Nokia gives you certain additional
** rights. These rights are described in the Nokia Qt LGPL Exception
** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
**
** If you have questions regarding the use of this file, please contact
** Nokia at qt-info@nokia.com.
**
**
**
**
**
**
**
**
** $QT_END_LICENSE$
**
****************************************************************************/
#include "qbluetoothservicediscoveryagent_p.h"
#include <QUrl>
#include <QtEndian>
#include <arpa/inet.h>
#include <netinet/in.h>
QTM_BEGIN_NAMESPACE
QBluetoothServiceDiscoveryAgentPrivate::QBluetoothServiceDiscoveryAgentPrivate(const QBluetoothAddress &address)
: error(QBluetoothServiceDiscoveryAgent::NoError)
, state(Inactive)
, deviceAddress(address)
, deviceDiscoveryAgent(0)
, mode(QBluetoothServiceDiscoveryAgent::MinimalDiscovery)
, m_sdpAgent(NULL)
, m_filter(NULL)
, m_attributes(NULL)
{
}
QBluetoothServiceDiscoveryAgentPrivate::~QBluetoothServiceDiscoveryAgentPrivate()
{
delete m_filter;
delete m_attributes;
delete m_sdpAgent;
}
void QBluetoothServiceDiscoveryAgentPrivate::start(const QBluetoothAddress &address)
{
Q_Q(QBluetoothServiceDiscoveryAgent);
TRAPD(err, startL(address));
if (err != KErrNone) {
error = QBluetoothServiceDiscoveryAgent::UnknownError;
emit q->error(error);
}
}
void QBluetoothServiceDiscoveryAgentPrivate::startL(const QBluetoothAddress &address)
{
initL(address);
if (uuidFilter.isEmpty()) {
m_filter->AddL(QBluetoothUuid::PublicBrowseGroup);
} else {
foreach (const QBluetoothUuid &uuid, uuidFilter) {
if (uuid.minimumSize() == 2) {
TUUID sUuid(uuid.toUInt16());
m_filter->AddL(sUuid);
} else if (uuid.minimumSize() == 4) {
TUUID sUuid(uuid.toUInt32());
m_filter->AddL(sUuid);
} else if (uuid.minimumSize() == 16) {
TUint32 *dataPointer = (TUint32*)uuid.toUInt128().data;
TUint32 hH = qToBigEndian<quint32>(*(dataPointer++));
TUint32 hL = qToBigEndian<quint32>(*(dataPointer++));
TUint32 lH = qToBigEndian<quint32>(*(dataPointer++));
TUint32 lL = qToBigEndian<quint32>(*(dataPointer));
TUUID sUuid(hH, hL, lH, lL);
m_filter->AddL(sUuid);
} else {
// filter size can be 0 on error cases, searching all services
m_filter->AddL(QBluetoothUuid::PublicBrowseGroup);
}
}
}
m_sdpAgent->SetRecordFilterL(*m_filter);
m_sdpAgent->NextRecordRequestL();
}
void QBluetoothServiceDiscoveryAgentPrivate::stop()
{
delete m_sdpAgent;
m_sdpAgent = NULL;
delete m_filter;
m_filter = NULL;
delete m_attributes;
m_attributes = NULL;
}
void QBluetoothServiceDiscoveryAgentPrivate::initL(const QBluetoothAddress &address)
{
TBTDevAddr btAddress(address.toUInt64());
stop();
//Trapped in Start
m_sdpAgent = q_check_ptr(CSdpAgent::NewL(*this, btAddress));
m_filter = q_check_ptr(CSdpSearchPattern::NewL());
m_attributes = q_check_ptr(CSdpAttrIdMatchList::NewL());
m_attributes->AddL(KAttrRangeAll);
}
bool QBluetoothServiceDiscoveryAgentPrivate::quickDiscovery(const QBluetoothAddress &address, const QBluetoothDeviceInfo &info)
{
return false;
}
void QBluetoothServiceDiscoveryAgentPrivate::NextRecordRequestComplete(TInt aError, TSdpServRecordHandle aHandle, TInt aTotalRecordsCount)
{
Q_Q(QBluetoothServiceDiscoveryAgent);
if (aError == KErrNone && aTotalRecordsCount > 0 && m_sdpAgent && m_attributes) {
// request attributes
TRAPD(err, m_sdpAgent->AttributeRequestL(aHandle, *m_attributes));
if (err) {
error = QBluetoothServiceDiscoveryAgent::UnknownError;
emit q->error(error);
}
} else if (aError == KErrEof) {
_q_serviceDiscoveryFinished();
} else {
_q_serviceDiscoveryFinished();
}
}
void QBluetoothServiceDiscoveryAgentPrivate::AttributeRequestResult(TSdpServRecordHandle, TSdpAttributeID aAttrID, CSdpAttrValue *aAttrValue)
{
Q_Q(QBluetoothServiceDiscoveryAgent);
m_currentAttributeId = aAttrID;
TRAPD(err, aAttrValue->AcceptVisitorL(*this));
if (m_stack.size() != 1) {
error = QBluetoothServiceDiscoveryAgent::UnknownError;
emit q->error(error);
delete aAttrValue;
return;
}
m_serviceInfo.setAttribute(aAttrID, m_stack.pop());
if (err != KErrNone) {
error = QBluetoothServiceDiscoveryAgent::UnknownError;
emit q->error(error);
}
delete aAttrValue;
}
void QBluetoothServiceDiscoveryAgentPrivate::AttributeRequestComplete(TSdpServRecordHandle, TInt aError)
{
Q_Q(QBluetoothServiceDiscoveryAgent);
if (aError == KErrNone && m_sdpAgent) {
m_serviceInfo.setDevice(discoveredDevices.at(0));
discoveredServices.append(m_serviceInfo);
m_serviceInfo = QBluetoothServiceInfo();
TRAPD(err, m_sdpAgent->NextRecordRequestL());
if (err != KErrNone) {
error = QBluetoothServiceDiscoveryAgent::UnknownError;
emit q->error(error);
}
} else if (aError != KErrEof) {
error = QBluetoothServiceDiscoveryAgent::UnknownError;
emit q->error(error);
}
// emit found service.
if (discoveredServices.last().isValid())
emit q->serviceDiscovered(discoveredServices.last());
}
void QBluetoothServiceDiscoveryAgentPrivate::VisitAttributeValueL(CSdpAttrValue &aValue, TSdpElementType aType)
{
QVariant var;
TUint datasize = aValue.DataSize();
switch (aType) {
case ETypeNil:
break;
case ETypeUint:
if (datasize == 8) {
TUint64 value;
aValue.Uint64(value);
var = QVariant::fromValue(value);
} else
var = QVariant::fromValue(aValue.Uint());
break;
case ETypeInt:
var = QVariant::fromValue(aValue.Int());
break;
case ETypeUUID: {
TPtrC8 shortForm(aValue.UUID().ShortestForm());
if (shortForm.Size() == 2) {
QBluetoothUuid uuid(ntohs(*reinterpret_cast<const quint16 *>(shortForm.Ptr())));
var = QVariant::fromValue(uuid);
} else if (shortForm.Size() == 4) {
QBluetoothUuid uuid(ntohl(*reinterpret_cast<const quint32 *>(shortForm.Ptr())));
var = QVariant::fromValue(uuid);
} else if (shortForm.Size() == 16) {
QBluetoothUuid uuid(*reinterpret_cast<const quint128 *>(shortForm.Ptr()));
var = QVariant::fromValue(uuid);
}
break;
}
case ETypeString: {
TPtrC8 stringBuffer = aValue.Des();
var = QVariant::fromValue(QString::fromLocal8Bit(reinterpret_cast<const char *>(stringBuffer.Ptr()), stringBuffer.Size()));
break;
}
case ETypeBoolean:
var = QVariant::fromValue(static_cast<bool>(aValue.Bool()));
break;
case ETypeDES:
m_stack.push(QVariant::fromValue(QBluetoothServiceInfo::Sequence()));
break;
case ETypeDEA:
m_stack.push(QVariant::fromValue(QBluetoothServiceInfo::Alternative()));
break;
case ETypeURL: {
TPtrC8 stringBuffer = aValue.Des();
var = QVariant::fromValue(QUrl(QString::fromLocal8Bit(reinterpret_cast<const char *>(stringBuffer.Ptr()), stringBuffer.Size())));
break;
}
case ETypeEncoded:
qWarning() << "Don't know how to handle encoded type.";
break;
default:
qWarning() << "Don't know how to handle type" << aType;
}
if (aType != ETypeDES && aType != ETypeDEA) {
if (m_stack.size() == 0) {
// single value attribute, just push onto stack
m_stack.push(var);
} else if (m_stack.size() >= 1) {
// sequence or alternate attribute, add non-DES -DEA values to DES or DEA
if (m_stack.top().canConvert<QBluetoothServiceInfo::Sequence>()) {
QBluetoothServiceInfo::Sequence *sequence = static_cast<QBluetoothServiceInfo::Sequence *>(m_stack.top().data());
sequence->append(var);
} else if (m_stack.top().canConvert<QBluetoothServiceInfo::Alternative>()) {
QBluetoothServiceInfo::Alternative *alternative = static_cast<QBluetoothServiceInfo::Alternative *>(m_stack.top().data());
alternative->append(var);
} else {
qWarning("Unknown type in the QVariant, should be either a QBluetoothServiceInfo::Sequence or an QBluetoothServiceInfo::Alternative");
}
}
}
}
void QBluetoothServiceDiscoveryAgentPrivate::StartListL(CSdpAttrValueList &)
{
}
void QBluetoothServiceDiscoveryAgentPrivate::EndListL()
{
if (m_stack.size() > 1) {
// finished a sequence or alternative add it to the parent sequence or alternative
QVariant var = m_stack.pop();
if (m_stack.top().canConvert<QBluetoothServiceInfo::Sequence>()) {
QBluetoothServiceInfo::Sequence *sequence = static_cast<QBluetoothServiceInfo::Sequence *>(m_stack.top().data());
sequence->append(var);
} else if (m_stack.top().canConvert<QBluetoothServiceInfo::Alternative>()) {
QBluetoothServiceInfo::Alternative *alternative = static_cast<QBluetoothServiceInfo::Alternative *>(m_stack.top().data());
alternative->append(var);
} else {
qWarning("Unknown type in the QVariant, should be either a QBluetoothServiceInfo::Sequence or an QBluetoothServiceInfo::Alternative");
}
}
}
QTM_END_NAMESPACE
<|endoftext|>
|
<commit_before>// =============================================================================
// PROJECT CHRONO - http://projectchrono.org
//
// Copyright (c) 2014 projectchrono.org
// All right reserved.
//
// Use of this source code is governed by a BSD-style license that can be found
// in the LICENSE file at the top level of the distribution and at
// http://projectchrono.org/license-chrono.txt.
//
// =============================================================================
// Author: Radu Serban
// =============================================================================
//
// Chrono::Vehicle + ChronoParallel demo program for simulating a HMMWV vehicle
// over rigid or granular material.
//
// The vehicle model uses the utility class ChWheeledVehicleAssembly and is
// based on JSON specification files from the Chrono data directory.
//
// Contact uses the DEM-P (penalty) formulation.
//
// The global reference frame has Z up.
// All units SI.
// =============================================================================
#include <stdio.h>
#include <cmath>
#include <vector>
#include "chrono/core/ChFileutils.h"
#include "chrono/utils/ChUtilsInputOutput.h"
#include "chrono_vehicle/ChVehicleModelData.h"
#include "chrono_vehicle/ChDriver.h"
#include "chrono_vehicle/terrain/DeformableTerrain.h"
#include "chrono_vehicle/terrain/RigidTerrain.h"
#include "chrono_vehicle/wheeled_vehicle/utils/ChWheeledVehicleAssembly.h"
#include "chrono_vehicle/wheeled_vehicle/utils/ChWheeledVehicleIrrApp.h"
#include "chrono_models/vehicle/hmmwv/HMMWV.h"
using namespace chrono;
using namespace chrono::collision;
using namespace chrono::irrlicht;
using namespace chrono::vehicle;
using namespace chrono::vehicle::hmmwv;
using std::cout;
using std::endl;
// =============================================================================
// USER SETTINGS
// =============================================================================
// -----------------------------------------------------------------------------
// Terrain parameters
// -----------------------------------------------------------------------------
// Dimensions
double terrainHeight = 0;
double terrainLength = 16.0; // size in X direction
double terrainWidth = 8.0; // size in Y direction
// Divisions (X and Y)
int divLength = 1024;
int divWidth = 512;
// -----------------------------------------------------------------------------
// Vehicle parameters
// -----------------------------------------------------------------------------
// Type of wheel/tire (controls both contact and visualization)
enum WheelType { CYLINDRICAL, LUGGED };
WheelType wheel_type = LUGGED;
// Type of terrain
enum TerrainType { DEFORMABLE_SOIL, RIGID_SOIL };
TerrainType terrain_type = DEFORMABLE_SOIL;
// Type of powertrain model (SHAFTS, SIMPLE)
PowertrainModelType powertrain_model = PowertrainModelType::SHAFTS;
// Drive type (FWD, RWD, or AWD)
DrivelineType drive_type = DrivelineType::AWD;
// Chassis visualization (MESH, PRIMITIVES, NONE)
VisualizationType chassis_vis = VisualizationType::NONE;
// Initial vehicle position and orientation
ChVector<> initLoc(-5, -2, 0.6);
ChQuaternion<> initRot(1, 0, 0, 0);
// Contact material properties
float Y_t = 1.0e6f;
float cr_t = 0.1f;
float mu_t = 0.8f;
// -----------------------------------------------------------------------------
// Simulation parameters
// -----------------------------------------------------------------------------
// Simulation step size
double step_size = 1e-3;
// Time interval between two render frames (1/FPS)
double render_step_size = 1.0 / 100;
// Point on chassis tracked by the camera
ChVector<> trackPoint(0.0, 0.0, 1.75);
// Output directories
const std::string out_dir = "../HMMWV_DEF_SOIL";
const std::string img_dir = out_dir + "/IMG";
// Visualization output
bool img_output = false;
// =============================================================================
class MyDriver : public ChDriver {
public:
MyDriver(ChVehicle& vehicle, double delay) : ChDriver(vehicle), m_delay(delay) {}
~MyDriver() {}
virtual void Synchronize(double time) override {
m_throttle = 0;
m_steering = 0;
m_braking = 0;
double eff_time = time - m_delay;
// Do not generate any driver inputs for a duration equal to m_delay.
if (eff_time < 0)
return;
if (eff_time > 0.2)
m_throttle = 0.7;
else
m_throttle = 3.5 * eff_time;
if (eff_time < 2)
m_steering = 0;
else
m_steering = 0.6 * std::sin(CH_C_2PI * (eff_time - 2) / 6);
}
private:
double m_delay;
};
// =============================================================================
void CreateLuggedGeometry(std::shared_ptr<ChBody> wheelBody) {
std::string lugged_file("hmmwv/lugged_wheel_section.obj");
geometry::ChTriangleMeshConnected lugged_mesh;
ChConvexDecompositionHACDv2 lugged_convex;
utils::LoadConvexMesh(vehicle::GetDataFile(lugged_file), lugged_mesh, lugged_convex);
int num_hulls = lugged_convex.GetHullCount();
ChCollisionModel* coll_model = wheelBody->GetCollisionModel();
coll_model->ClearModel();
// Assemble the tire contact from 15 segments, properly offset.
// Each segment is further decomposed in convex hulls.
for (int iseg = 0; iseg < 15; iseg++) {
ChQuaternion<> rot = Q_from_AngAxis(iseg * 24 * CH_C_DEG_TO_RAD, VECT_Y);
for (int ihull = 0; ihull < num_hulls; ihull++) {
std::vector<ChVector<> > convexhull;
lugged_convex.GetConvexHullResult(ihull, convexhull);
coll_model->AddConvexHull(convexhull, VNULL, rot);
}
}
// Add a cylinder to represent the wheel hub.
coll_model->AddCylinder(0.223, 0.223, 0.126);
coll_model->BuildModel();
// Visualization
geometry::ChTriangleMeshConnected trimesh;
trimesh.LoadWavefrontMesh(vehicle::GetDataFile("hmmwv/lugged_wheel.obj"), false, false);
auto trimesh_shape = std::make_shared<ChTriangleMeshShape>();
trimesh_shape->SetMesh(trimesh);
trimesh_shape->SetName("lugged_wheel");
wheelBody->AddAsset(trimesh_shape);
auto mcolor = std::make_shared<ChColorAsset>(0.3f, 0.3f, 0.3f);
wheelBody->AddAsset(mcolor);
}
// =============================================================================
int main(int argc, char* argv[]) {
// --------------------
// Create HMMWV vehicle
// --------------------
HMMWV_Full my_hmmwv;
my_hmmwv.SetContactMethod(ChMaterialSurfaceBase::DEM);
my_hmmwv.SetChassisFixed(false);
my_hmmwv.SetInitPosition(ChCoordsys<>(initLoc, initRot));
my_hmmwv.SetPowertrainType(powertrain_model);
my_hmmwv.SetDriveType(drive_type);
my_hmmwv.SetTireType(TireModelType::RIGID);
my_hmmwv.Initialize();
VisualizationType wheel_vis = (wheel_type == CYLINDRICAL) ? VisualizationType::MESH : VisualizationType::NONE;
my_hmmwv.SetChassisVisualizationType(chassis_vis);
my_hmmwv.SetWheelVisualizationType(wheel_vis);
ChSystem* system = my_hmmwv.GetSystem();
// --------------------------------------------------------
// Set wheel contact material.
// If needed, modify wheel contact and visualization models
// --------------------------------------------------------
for (int i = 0; i < 4; i++) {
auto wheelBody = my_hmmwv.GetVehicle().GetWheelBody(i);
wheelBody->GetMaterialSurfaceDEM()->SetFriction(mu_t);
wheelBody->GetMaterialSurfaceDEM()->SetYoungModulus(Y_t);
wheelBody->GetMaterialSurfaceDEM()->SetRestitution(cr_t);
CreateLuggedGeometry(wheelBody);
}
// --------------------
// Create driver system
// --------------------
MyDriver driver(my_hmmwv.GetVehicle(), 0.5);
driver.Initialize();
// ------------------
// Create the terrain
// ------------------
ChTerrain* terrain;
switch (terrain_type) {
case DEFORMABLE_SOIL: {
DeformableTerrain* terrainD = new DeformableTerrain(system);
terrainD->SetPlane(ChCoordsys<>(VNULL, Q_from_AngX(CH_C_PI_2)));
terrainD->SetSoilParametersSCM(2e6, // Bekker Kphi
0, // Bekker Kc
1.1, // Bekker n exponent
0, // Mohr cohesive limit (Pa)
30, // Mohr friction limit (degrees)
0.01, // Janosi shear coefficient (m)
2e8 // Elastic stiffness (Pa/m), before plastic yeld
);
////terrainD->SetBulldozingFlow(true); // inflate soil at the border of the rut
////terrainD->SetBulldozingParameters(40, // angle of friction for erosion of displaced material at the border
//// 1.6); // displaced material vs. downward pressed material
////terrainD->SetTexture(vehicle::GetDataFile("terrain/textures/grass.jpg"), 80, 16);
////terrainD->SetPlotType(vehicle::DeformableTerrain::PLOT_PRESSURE_YELD, 0, 30000.2);
terrainD->SetPlotType(vehicle::DeformableTerrain::PLOT_SINKAGE, 0, 0.1);
terrainD->Initialize(terrainHeight, terrainLength, terrainWidth, divLength, divWidth);
terrain = terrainD;
break;
}
case RIGID_SOIL: {
RigidTerrain* terrainR = new RigidTerrain(system);
terrainR->SetContactFrictionCoefficient(0.9f);
terrainR->SetContactRestitutionCoefficient(0.01f);
terrainR->SetContactMaterialProperties(2e7f, 0.3f);
terrainR->SetColor(ChColor(0.8f, 0.8f, 0.5f));
terrainR->SetTexture(vehicle::GetDataFile("terrain/textures/tile4.jpg"), 200, 200);
terrainR->Initialize(terrainHeight, terrainLength, terrainWidth);
terrain = terrainR;
break;
}
}
// Complete system construction
system->SetupInitial();
// ---------------------------------------
// Create the vehicle Irrlicht application
// ---------------------------------------
ChWheeledVehicleIrrApp app(&my_hmmwv.GetVehicle(), &my_hmmwv.GetPowertrain(), L"HMMWV Deformable Soil Demo");
app.SetSkyBox();
app.AddTypicalLights(irr::core::vector3df(30.f, -30.f, 100.f), irr::core::vector3df(30.f, 50.f, 100.f), 250, 130);
app.SetChaseCamera(trackPoint, 6.0, 0.5);
app.SetTimestep(step_size);
app.AssetBindAll();
app.AssetUpdateAll();
// -----------------
// Initialize output
// -----------------
if (ChFileutils::MakeDirectory(out_dir.c_str()) < 0) {
std::cout << "Error creating directory " << out_dir << std::endl;
return 1;
}
if (img_output) {
if (ChFileutils::MakeDirectory(img_dir.c_str()) < 0) {
std::cout << "Error creating directory " << img_dir << std::endl;
return 1;
}
}
// ---------------
// Simulation loop
// ---------------
// Solver settings.
////system->SetSolverType(ChSystem::SOLVER_MINRES);
system->SetMaxItersSolverSpeed(50);
system->SetMaxItersSolverStab(50);
////system->SetTol(0);
////system->SetMaxPenetrationRecoverySpeed(1.5);
////system->SetMinBounceSpeed(2.0);
////system->SetSolverOverrelaxationParam(0.8);
////system->SetSolverSharpnessParam(1.0);
// Number of simulation steps between two 3D view render frames
int render_steps = (int)std::ceil(render_step_size / step_size);
// Initialize simulation frame counter
int step_number = 0;
int render_frame = 0;
ChRealtimeStepTimer realtime_timer;
while (app.GetDevice()->run()) {
double time = system->GetChTime();
// Render scene
if (step_number % render_steps == 0) {
app.BeginScene(true, true, irr::video::SColor(255, 140, 161, 192));
app.DrawAll();
ChIrrTools::drawColorbar(0, 0.1, "Sinkage", app.GetDevice(), 30);
app.EndScene();
if (img_output && step_number >= 0) {
char filename[100];
sprintf(filename, "%s/img_%03d.jpg", img_dir.c_str(), render_frame + 1);
app.WriteImageToFile(filename);
}
render_frame++;
}
double throttle_input = driver.GetThrottle();
double steering_input = driver.GetSteering();
double braking_input = driver.GetBraking();
// Update modules
driver.Synchronize(time);
terrain->Synchronize(time);
my_hmmwv.Synchronize(time, steering_input, braking_input, throttle_input, *terrain);
app.Synchronize("", steering_input, throttle_input, braking_input);
// Advance dynamics
double step = realtime_timer.SuggestSimulationStep(step_size);
system->DoStepDynamics(step);
app.Advance(step);
// Increment frame number
step_number++;
}
// Cleanup
delete terrain;
return 0;
}
<commit_msg>Use adaptive mesh refinement for the HMMWVV + SCM demo<commit_after>// =============================================================================
// PROJECT CHRONO - http://projectchrono.org
//
// Copyright (c) 2014 projectchrono.org
// All right reserved.
//
// Use of this source code is governed by a BSD-style license that can be found
// in the LICENSE file at the top level of the distribution and at
// http://projectchrono.org/license-chrono.txt.
//
// =============================================================================
// Author: Radu Serban
// =============================================================================
//
// Chrono::Vehicle + ChronoParallel demo program for simulating a HMMWV vehicle
// over rigid or granular material.
//
// The vehicle model uses the utility class ChWheeledVehicleAssembly and is
// based on JSON specification files from the Chrono data directory.
//
// Contact uses the DEM-P (penalty) formulation.
//
// The global reference frame has Z up.
// All units SI.
// =============================================================================
#include <stdio.h>
#include <cmath>
#include <vector>
#include "chrono/core/ChFileutils.h"
#include "chrono/utils/ChUtilsInputOutput.h"
#include "chrono_vehicle/ChVehicleModelData.h"
#include "chrono_vehicle/ChDriver.h"
#include "chrono_vehicle/terrain/DeformableTerrain.h"
#include "chrono_vehicle/terrain/RigidTerrain.h"
#include "chrono_vehicle/wheeled_vehicle/utils/ChWheeledVehicleAssembly.h"
#include "chrono_vehicle/wheeled_vehicle/utils/ChWheeledVehicleIrrApp.h"
#include "chrono_models/vehicle/hmmwv/HMMWV.h"
using namespace chrono;
using namespace chrono::collision;
using namespace chrono::irrlicht;
using namespace chrono::vehicle;
using namespace chrono::vehicle::hmmwv;
using std::cout;
using std::endl;
// =============================================================================
// USER SETTINGS
// =============================================================================
// -----------------------------------------------------------------------------
// Terrain parameters
// -----------------------------------------------------------------------------
// Dimensions
double terrainHeight = 0;
double terrainLength = 16.0; // size in X direction
double terrainWidth = 8.0; // size in Y direction
// Divisions (X and Y)
int divLength = 128;//1024;
int divWidth = 64;//512;
// -----------------------------------------------------------------------------
// Vehicle parameters
// -----------------------------------------------------------------------------
// Type of wheel/tire (controls both contact and visualization)
enum WheelType { CYLINDRICAL, LUGGED };
WheelType wheel_type = LUGGED;
// Type of terrain
enum TerrainType { DEFORMABLE_SOIL, RIGID_SOIL };
TerrainType terrain_type = DEFORMABLE_SOIL;
// Type of powertrain model (SHAFTS, SIMPLE)
PowertrainModelType powertrain_model = PowertrainModelType::SHAFTS;
// Drive type (FWD, RWD, or AWD)
DrivelineType drive_type = DrivelineType::AWD;
// Chassis visualization (MESH, PRIMITIVES, NONE)
VisualizationType chassis_vis = VisualizationType::NONE;
// Initial vehicle position and orientation
ChVector<> initLoc(-5, -2, 0.6);
ChQuaternion<> initRot(1, 0, 0, 0);
// Contact material properties
float Y_t = 1.0e6f;
float cr_t = 0.1f;
float mu_t = 0.8f;
// -----------------------------------------------------------------------------
// Simulation parameters
// -----------------------------------------------------------------------------
// Simulation step size
double step_size = 1e-3;
// Time interval between two render frames (1/FPS)
double render_step_size = 1.0 / 100;
// Point on chassis tracked by the camera
ChVector<> trackPoint(0.0, 0.0, 1.75);
// Output directories
const std::string out_dir = "../HMMWV_DEF_SOIL";
const std::string img_dir = out_dir + "/IMG";
// Visualization output
bool img_output = false;
// =============================================================================
class MyDriver : public ChDriver {
public:
MyDriver(ChVehicle& vehicle, double delay) : ChDriver(vehicle), m_delay(delay) {}
~MyDriver() {}
virtual void Synchronize(double time) override {
m_throttle = 0;
m_steering = 0;
m_braking = 0;
double eff_time = time - m_delay;
// Do not generate any driver inputs for a duration equal to m_delay.
if (eff_time < 0)
return;
if (eff_time > 0.2)
m_throttle = 0.7;
else
m_throttle = 3.5 * eff_time;
if (eff_time < 2)
m_steering = 0;
else
m_steering = 0.6 * std::sin(CH_C_2PI * (eff_time - 2) / 6);
}
private:
double m_delay;
};
// =============================================================================
void CreateLuggedGeometry(std::shared_ptr<ChBody> wheelBody) {
std::string lugged_file("hmmwv/lugged_wheel_section.obj");
geometry::ChTriangleMeshConnected lugged_mesh;
ChConvexDecompositionHACDv2 lugged_convex;
utils::LoadConvexMesh(vehicle::GetDataFile(lugged_file), lugged_mesh, lugged_convex);
int num_hulls = lugged_convex.GetHullCount();
ChCollisionModel* coll_model = wheelBody->GetCollisionModel();
coll_model->ClearModel();
// Assemble the tire contact from 15 segments, properly offset.
// Each segment is further decomposed in convex hulls.
for (int iseg = 0; iseg < 15; iseg++) {
ChQuaternion<> rot = Q_from_AngAxis(iseg * 24 * CH_C_DEG_TO_RAD, VECT_Y);
for (int ihull = 0; ihull < num_hulls; ihull++) {
std::vector<ChVector<> > convexhull;
lugged_convex.GetConvexHullResult(ihull, convexhull);
coll_model->AddConvexHull(convexhull, VNULL, rot);
}
}
// Add a cylinder to represent the wheel hub.
coll_model->AddCylinder(0.223, 0.223, 0.126);
coll_model->BuildModel();
// Visualization
geometry::ChTriangleMeshConnected trimesh;
trimesh.LoadWavefrontMesh(vehicle::GetDataFile("hmmwv/lugged_wheel.obj"), false, false);
auto trimesh_shape = std::make_shared<ChTriangleMeshShape>();
trimesh_shape->SetMesh(trimesh);
trimesh_shape->SetName("lugged_wheel");
wheelBody->AddAsset(trimesh_shape);
auto mcolor = std::make_shared<ChColorAsset>(0.3f, 0.3f, 0.3f);
wheelBody->AddAsset(mcolor);
}
// =============================================================================
int main(int argc, char* argv[]) {
// --------------------
// Create HMMWV vehicle
// --------------------
HMMWV_Full my_hmmwv;
my_hmmwv.SetContactMethod(ChMaterialSurfaceBase::DEM);
my_hmmwv.SetChassisFixed(false);
my_hmmwv.SetInitPosition(ChCoordsys<>(initLoc, initRot));
my_hmmwv.SetPowertrainType(powertrain_model);
my_hmmwv.SetDriveType(drive_type);
my_hmmwv.SetTireType(TireModelType::RIGID);
my_hmmwv.Initialize();
VisualizationType wheel_vis = (wheel_type == CYLINDRICAL) ? VisualizationType::MESH : VisualizationType::NONE;
my_hmmwv.SetChassisVisualizationType(chassis_vis);
my_hmmwv.SetWheelVisualizationType(wheel_vis);
ChSystem* system = my_hmmwv.GetSystem();
// --------------------------------------------------------
// Set wheel contact material.
// If needed, modify wheel contact and visualization models
// --------------------------------------------------------
for (int i = 0; i < 4; i++) {
auto wheelBody = my_hmmwv.GetVehicle().GetWheelBody(i);
wheelBody->GetMaterialSurfaceDEM()->SetFriction(mu_t);
wheelBody->GetMaterialSurfaceDEM()->SetYoungModulus(Y_t);
wheelBody->GetMaterialSurfaceDEM()->SetRestitution(cr_t);
CreateLuggedGeometry(wheelBody);
}
// --------------------
// Create driver system
// --------------------
MyDriver driver(my_hmmwv.GetVehicle(), 0.5);
driver.Initialize();
// ------------------
// Create the terrain
// ------------------
ChTerrain* terrain;
switch (terrain_type) {
case DEFORMABLE_SOIL: {
DeformableTerrain* terrainD = new DeformableTerrain(system);
terrainD->SetPlane(ChCoordsys<>(VNULL, Q_from_AngX(CH_C_PI_2)));
terrainD->SetSoilParametersSCM(2e6, // Bekker Kphi
0, // Bekker Kc
1.1, // Bekker n exponent
0, // Mohr cohesive limit (Pa)
30, // Mohr friction limit (degrees)
0.01, // Janosi shear coefficient (m)
2e8 // Elastic stiffness (Pa/m), before plastic yeld
);
/*
terrainD->SetBulldozingFlow(true); // inflate soil at the border of the rut
terrainD->SetBulldozingParameters(55, // angle of friction for erosion of displaced material at the border of the rut
0.8, // displaced material vs downward pressed material.
5, // number of erosion refinements per timestep
10); // number of concentric vertex selections subject to erosion
*/
// Turn on the automatic level of detail refinement, so a coarse terrain mesh
// is automatically improved by adding more points under the wheel contact patch:
terrainD->SetAutomaticRefinement(true);
terrainD->SetAutomaticRefinementResolution(0.04);
////terrainD->SetTexture(vehicle::GetDataFile("terrain/textures/grass.jpg"), 80, 16);
////terrainD->SetPlotType(vehicle::DeformableTerrain::PLOT_PRESSURE_YELD, 0, 30000.2);
terrainD->SetPlotType(vehicle::DeformableTerrain::PLOT_SINKAGE, 0, 0.1);
terrainD->Initialize(terrainHeight, terrainLength, terrainWidth, divLength, divWidth);
terrain = terrainD;
break;
}
case RIGID_SOIL: {
RigidTerrain* terrainR = new RigidTerrain(system);
terrainR->SetContactFrictionCoefficient(0.9f);
terrainR->SetContactRestitutionCoefficient(0.01f);
terrainR->SetContactMaterialProperties(2e7f, 0.3f);
terrainR->SetColor(ChColor(0.8f, 0.8f, 0.5f));
terrainR->SetTexture(vehicle::GetDataFile("terrain/textures/tile4.jpg"), 200, 200);
terrainR->Initialize(terrainHeight, terrainLength, terrainWidth);
terrain = terrainR;
break;
}
}
// Complete system construction
system->SetupInitial();
// ---------------------------------------
// Create the vehicle Irrlicht application
// ---------------------------------------
ChWheeledVehicleIrrApp app(&my_hmmwv.GetVehicle(), &my_hmmwv.GetPowertrain(), L"HMMWV Deformable Soil Demo");
app.SetSkyBox();
app.AddTypicalLights(irr::core::vector3df(30.f, -30.f, 100.f), irr::core::vector3df(30.f, 50.f, 100.f), 250, 130);
app.SetChaseCamera(trackPoint, 6.0, 0.5);
app.SetTimestep(step_size);
app.AssetBindAll();
app.AssetUpdateAll();
// -----------------
// Initialize output
// -----------------
if (ChFileutils::MakeDirectory(out_dir.c_str()) < 0) {
std::cout << "Error creating directory " << out_dir << std::endl;
return 1;
}
if (img_output) {
if (ChFileutils::MakeDirectory(img_dir.c_str()) < 0) {
std::cout << "Error creating directory " << img_dir << std::endl;
return 1;
}
}
// ---------------
// Simulation loop
// ---------------
// Solver settings.
////system->SetSolverType(ChSystem::SOLVER_MINRES);
system->SetMaxItersSolverSpeed(50);
system->SetMaxItersSolverStab(50);
////system->SetTol(0);
////system->SetMaxPenetrationRecoverySpeed(1.5);
////system->SetMinBounceSpeed(2.0);
////system->SetSolverOverrelaxationParam(0.8);
////system->SetSolverSharpnessParam(1.0);
// Number of simulation steps between two 3D view render frames
int render_steps = (int)std::ceil(render_step_size / step_size);
// Initialize simulation frame counter
int step_number = 0;
int render_frame = 0;
ChRealtimeStepTimer realtime_timer;
while (app.GetDevice()->run()) {
double time = system->GetChTime();
// Render scene
if (step_number % render_steps == 0) {
app.BeginScene(true, true, irr::video::SColor(255, 140, 161, 192));
app.DrawAll();
ChIrrTools::drawColorbar(0, 0.1, "Sinkage", app.GetDevice(), 30);
app.EndScene();
if (img_output && step_number >= 0) {
char filename[100];
sprintf(filename, "%s/img_%03d.jpg", img_dir.c_str(), render_frame + 1);
app.WriteImageToFile(filename);
}
render_frame++;
}
double throttle_input = driver.GetThrottle();
double steering_input = driver.GetSteering();
double braking_input = driver.GetBraking();
// Update modules
driver.Synchronize(time);
terrain->Synchronize(time);
my_hmmwv.Synchronize(time, steering_input, braking_input, throttle_input, *terrain);
app.Synchronize("", steering_input, throttle_input, braking_input);
// Advance dynamics
double step = realtime_timer.SuggestSimulationStep(step_size);
system->DoStepDynamics(step);
app.Advance(step);
// Increment frame number
step_number++;
}
// Cleanup
delete terrain;
return 0;
}
<|endoftext|>
|
<commit_before>// $Id: Quaternion_test.C,v 1.6 2000/05/26 19:25:04 amoll Exp $
#include <BALL/CONCEPT/classTest.h>
///////////////////////////
#include <BALL/MATHS/matrix44.h>
#include <BALL/MATHS/vector3.h>
#include <BALL/MATHS/quaternion.h>
///////////////////////////
START_TEST(class_name, "$Id: Quaternion_test.C,v 1.6 2000/05/26 19:25:04 amoll Exp $")
/////////////////////////////////////////////////////////////
/////////////////////////////////////////////////////////////
using namespace BALL;
Vector3 const v = Vector3(1.0, 2.0, 3.0);
String filename;
using std::ofstream;
using std::ios;
PRECISION(1E-4)
CHECK(TQuaternion::BALL_CREATE(TQuaternion<T>))
Quaternion q(v, 4.0);
Quaternion* q_ptr = (Quaternion*)q.create(false, true);
TEST_REAL_EQUAL(q_ptr->i, 0)
TEST_REAL_EQUAL(q_ptr->j, 0)
TEST_REAL_EQUAL(q_ptr->k, 0)
TEST_REAL_EQUAL(q_ptr->angle, 1.0)
delete q_ptr;
q_ptr = (Quaternion*)q.create();
TEST_REAL_EQUAL(q_ptr->i, 0.24302)
TEST_REAL_EQUAL(q_ptr->j, 0.48604)
TEST_REAL_EQUAL(q_ptr->k, 0.72906)
TEST_REAL_EQUAL(q_ptr->angle, -0.416147)
delete q_ptr;
RESULT
CHECK(TQuaternion();)
Quaternion* p;
p = new Quaternion();
TEST_NOT_EQUAL(p, 0)
RESULT
CHECK(~TQuaternion();)
Quaternion* p;
p = new Quaternion();
delete p;
RESULT
Quaternion q, q1, q2;
float i = 0.24302, j = 2 * i, k = 3 * i, angle = -0.416147;
CHECK(TQuaternion(const TVector3<T>& axis, const T &angle))
q = Quaternion(v, 4.0);
TEST_REAL_EQUAL(q.i, i)
TEST_REAL_EQUAL(q.j, j)
TEST_REAL_EQUAL(q.k, k)
TEST_REAL_EQUAL(q.angle, angle)
RESULT
CHECK(TQuaternion(const TQuaternion& q, bool deep = true))
q = Quaternion(v, 4.0);
q1 = Quaternion(q);
TEST_REAL_EQUAL(q1.i, i)
TEST_REAL_EQUAL(q1.j, j)
TEST_REAL_EQUAL(q1.k, k)
TEST_REAL_EQUAL(q1.angle, angle)
RESULT
CHECK(TQuaternion(const T& x, const T& y, const T& z, const T& angle))
q1 = Quaternion(1.0, 2.0, 3.0, 4.0);
TEST_REAL_EQUAL(q1.i, i)
TEST_REAL_EQUAL(q1.j, j)
TEST_REAL_EQUAL(q1.k, k)
TEST_REAL_EQUAL(q1.angle, angle)
RESULT
CHECK(TQuaternion::getAngle() const )
TEST_REAL_EQUAL(q.getAngle(), (2.0 * atan2(sqrt(i * i + j * j + k * k), angle)) )
RESULT
CHECK(TQuaternion::getAxis())
Vector3 v2 = Vector3(i, j, k), v3;
v2.normalize();
v3 = q.getAxis();
TEST_EQUAL(v3, v2)
v3 = Vector3();
q1 = Quaternion(v3, 4);
TEST_EXCEPTION(Exception::DivisionByZero, q1.getAxis())
RESULT
CHECK(TQuaternion::getRotationMatrix(TMatrix4x4<T>& m) const )
Matrix4x4 m, m2;
m.set((1.0 - 2.0 * (j * j + k * k)),
(2.0 * (i * j - k * angle)),
(2.0 * (k * i + j * angle)),
0,
(2.0 * (i * j + k * angle)),
(1.0 - 2.0 * (k * k + i * i)),
(2.0 * (j * k - i * angle)),
0,
(2.0 * (k * i - j * angle)),
(2.0 * (j * k + i * angle)),
(1.0 - 2.0 * (j * j + i * i)),
0,
0, 0, 0, 1);
q.getRotationMatrix(m2);
TEST_REAL_EQUAL(m2.m11, m.m11);
TEST_REAL_EQUAL(m2.m12, m.m12);
TEST_REAL_EQUAL(m2.m13, m.m13);
TEST_REAL_EQUAL(m2.m14, m.m14);
TEST_REAL_EQUAL(m2.m21, m.m21);
TEST_REAL_EQUAL(m2.m22, m.m22);
TEST_REAL_EQUAL(m2.m23, m.m23);
TEST_REAL_EQUAL(m2.m24, m.m24);
TEST_REAL_EQUAL(m2.m31, m.m31);
TEST_REAL_EQUAL(m2.m32, m.m32);
TEST_REAL_EQUAL(m2.m33, m.m33);
TEST_REAL_EQUAL(m2.m34, m.m34);
TEST_REAL_EQUAL(m2.m41, m.m41);
TEST_REAL_EQUAL(m2.m42, m.m42);
TEST_REAL_EQUAL(m2.m43, m.m43);
TEST_REAL_EQUAL(m2.m44, m.m44);
RESULT
CHECK(TQuaternion::TQuaternion operator - () const )
float tmp = 1 / ::sqrt(angle * angle + i * i + j * j + k * k);
q2 = -q;
q1 = Quaternion(-i * tmp, -j * tmp, -k * tmp, angle * tmp);
TEST_REAL_EQUAL(q2.i, q1.i)
TEST_REAL_EQUAL(q2.j, q1.j)
TEST_REAL_EQUAL(q2.k, q1.k)
TEST_REAL_EQUAL(q2.angle, q1.angle)
q1 = Quaternion();
q1.angle = 0;
q2 = Quaternion();
TEST_EQUAL(-q1, q2);
RESULT
CHECK(TQuaternion::getInverse() const )
q1 = -Quaternion(q);
q2 = q.getInverse();
TEST_EQUAL(q2, q1)
RESULT
CHECK(TQuaternion::getConjugate() const )
q1 = q.getConjugate();
TEST_REAL_EQUAL(q1.i, -i)
TEST_REAL_EQUAL(q1.j, -j)
TEST_REAL_EQUAL(q1.k, -k)
TEST_REAL_EQUAL(q1.angle, angle)
RESULT
CHECK(TQuaternion::bool operator == (const TQuaternion& q) const )
q1 = Quaternion(q);
TEST_EQUAL(q1 == q, true)
q1 = Quaternion(v, 4.1);
TEST_EQUAL(q1 == q, false)
RESULT
CHECK(TQuaternion::TQuaternion& operator += (const TQuaternion& q))
q1 = Quaternion();
q1 += q;
TEST_REAL_EQUAL(q1.i, i)
TEST_REAL_EQUAL(q1.j, j)
TEST_REAL_EQUAL(q1.k, k)
TEST_REAL_EQUAL(q1.angle, angle)
RESULT
CHECK(TQuaternion::TQuaternion& operator -= (const TQuaternion& q))
q1 = q2 = Quaternion();
q1 += - q;
q2 -= q;
TEST_REAL_EQUAL(q1.i, q2.i)
TEST_REAL_EQUAL(q1.j, q2.j)
TEST_REAL_EQUAL(q1.k, q2.k)
TEST_REAL_EQUAL(q1.angle, q2.angle)
RESULT
CHECK(TQuaternion::bool operator != (const TQuaternion& q) const )
q1 = Quaternion(q);
TEST_EQUAL(q1 != q, false)
q1 = Quaternion(v, 4.1);
TEST_EQUAL(q1 != q, true)
RESULT
CHECK(TQuaternion::set(const TVector3<T>& axis, const T& angle))
q1 = Quaternion();
q1.set(v, 4.0);
TEST_EQUAL(q1, q)
RESULT
CHECK(TQuaternion::set(const TQuaternion<T>& q, bool /* deep */))
q1 = Quaternion();
q1.set(q);
TEST_EQUAL(q1, q)
RESULT
CHECK(TQuaternion::set(const T& x, const T& y, const T& z, const T& phi))
q1.set(1.0, 2.0, 3.0, 4.0);
TEST_EQUAL(q1 == q, true)
RESULT
CHECK(TQuaternion::get(TQuaternion<T>& q, bool deep))
q.get(q1);
TEST_EQUAL(q1, q)
RESULT
CHECK(TQuaternion::operator = (const TQuaternion<T>& q))
q1 = Quaternion();
q1 = q;
TEST_EQUAL(q1 == q, true)
RESULT
CHECK(TQuaternion::setIdentity())
q1 = Quaternion();
q2.setIdentity();
TEST_EQUAL(q2 == q1, true)
RESULT
CHECK(TQuaternion operator + (const TQuaternion<T>& a, const TQuaternion<T>& b))
q1 = Quaternion(q);
q2 = q + q1;
q1 += q;
TEST_EQUAL(q2, q1)
RESULT
CHECK(TQuaternion operator - (const TQuaternion<T>& a, const TQuaternion<T>& b))
q1 = Quaternion(q);
q2 = q - q1;
q1 -= q;
TEST_EQUAL(q2, q1)
RESULT
NEW_TMP_FILE(filename)
CHECK(std::istream& operator >>(std::istream& s, TQuaternion<T>& q))
std::ifstream instr("data/Quaternion_test2.txt");
q1 = Quaternion();
instr >> q1;
instr.close();
TEST_REAL_EQUAL(q1.i, i)
TEST_REAL_EQUAL(q1.j, j)
TEST_REAL_EQUAL(q1.k, k)
TEST_REAL_EQUAL(q1.angle, angle)
RESULT
CHECK(std::ostream& operator << (std::ostream& s, const TQuaternion<T>& q))
std::ofstream outstr(filename.c_str(), std::ios::out);
outstr << q;
outstr.close();
TEST_FILE(filename.c_str(), "data/Quaternion_test3.txt", true)
RESULT
CHECK(TQuaternion::dump(std::ostream& s, Size depth) const )
String filename;
NEW_TMP_FILE(filename)
std::ofstream outfile(filename.c_str(), ios::out);
q.dump(outfile);
outfile.close();
TEST_FILE(filename.c_str(), "data/Quaternion_test.txt", true)
RESULT
/////////////////////////////////////////////////////////////
/////////////////////////////////////////////////////////////
END_TEST
<commit_msg>improved test:setIdentity<commit_after>// $Id: Quaternion_test.C,v 1.7 2000/06/27 23:29:00 amoll Exp $
#include <BALL/CONCEPT/classTest.h>
///////////////////////////
#include <BALL/MATHS/matrix44.h>
#include <BALL/MATHS/vector3.h>
#include <BALL/MATHS/quaternion.h>
///////////////////////////
START_TEST(class_name, "$Id: Quaternion_test.C,v 1.7 2000/06/27 23:29:00 amoll Exp $")
/////////////////////////////////////////////////////////////
/////////////////////////////////////////////////////////////
using namespace BALL;
Vector3 const v = Vector3(1.0, 2.0, 3.0);
String filename;
using std::ofstream;
using std::ios;
PRECISION(1E-4)
CHECK(TQuaternion::BALL_CREATE(TQuaternion<T>))
Quaternion q(v, 4.0);
Quaternion* q_ptr = (Quaternion*)q.create(false, true);
TEST_REAL_EQUAL(q_ptr->i, 0)
TEST_REAL_EQUAL(q_ptr->j, 0)
TEST_REAL_EQUAL(q_ptr->k, 0)
TEST_REAL_EQUAL(q_ptr->angle, 1.0)
delete q_ptr;
q_ptr = (Quaternion*)q.create();
TEST_REAL_EQUAL(q_ptr->i, 0.24302)
TEST_REAL_EQUAL(q_ptr->j, 0.48604)
TEST_REAL_EQUAL(q_ptr->k, 0.72906)
TEST_REAL_EQUAL(q_ptr->angle, -0.416147)
delete q_ptr;
RESULT
CHECK(TQuaternion();)
Quaternion* p;
p = new Quaternion();
TEST_NOT_EQUAL(p, 0)
RESULT
CHECK(~TQuaternion();)
Quaternion* p;
p = new Quaternion();
delete p;
RESULT
Quaternion q, q1, q2;
float i = 0.24302, j = 2 * i, k = 3 * i, angle = -0.416147;
CHECK(TQuaternion(const TVector3<T>& axis, const T &angle))
q = Quaternion(v, 4.0);
TEST_REAL_EQUAL(q.i, i)
TEST_REAL_EQUAL(q.j, j)
TEST_REAL_EQUAL(q.k, k)
TEST_REAL_EQUAL(q.angle, angle)
RESULT
CHECK(TQuaternion(const TQuaternion& q, bool deep = true))
q = Quaternion(v, 4.0);
q1 = Quaternion(q);
TEST_REAL_EQUAL(q1.i, i)
TEST_REAL_EQUAL(q1.j, j)
TEST_REAL_EQUAL(q1.k, k)
TEST_REAL_EQUAL(q1.angle, angle)
RESULT
CHECK(TQuaternion(const T& x, const T& y, const T& z, const T& angle))
q1 = Quaternion(1.0, 2.0, 3.0, 4.0);
TEST_REAL_EQUAL(q1.i, i)
TEST_REAL_EQUAL(q1.j, j)
TEST_REAL_EQUAL(q1.k, k)
TEST_REAL_EQUAL(q1.angle, angle)
RESULT
CHECK(TQuaternion::getAngle() const )
TEST_REAL_EQUAL(q.getAngle(), (2.0 * atan2(sqrt(i * i + j * j + k * k), angle)) )
RESULT
CHECK(TQuaternion::getAxis())
Vector3 v2 = Vector3(i, j, k), v3;
v2.normalize();
v3 = q.getAxis();
TEST_EQUAL(v3, v2)
v3 = Vector3();
q1 = Quaternion(v3, 4);
TEST_EXCEPTION(Exception::DivisionByZero, q1.getAxis())
RESULT
CHECK(TQuaternion::getRotationMatrix(TMatrix4x4<T>& m) const )
Matrix4x4 m, m2;
m.set((1.0 - 2.0 * (j * j + k * k)),
(2.0 * (i * j - k * angle)),
(2.0 * (k * i + j * angle)),
0,
(2.0 * (i * j + k * angle)),
(1.0 - 2.0 * (k * k + i * i)),
(2.0 * (j * k - i * angle)),
0,
(2.0 * (k * i - j * angle)),
(2.0 * (j * k + i * angle)),
(1.0 - 2.0 * (j * j + i * i)),
0,
0, 0, 0, 1);
q.getRotationMatrix(m2);
TEST_REAL_EQUAL(m2.m11, m.m11);
TEST_REAL_EQUAL(m2.m12, m.m12);
TEST_REAL_EQUAL(m2.m13, m.m13);
TEST_REAL_EQUAL(m2.m14, m.m14);
TEST_REAL_EQUAL(m2.m21, m.m21);
TEST_REAL_EQUAL(m2.m22, m.m22);
TEST_REAL_EQUAL(m2.m23, m.m23);
TEST_REAL_EQUAL(m2.m24, m.m24);
TEST_REAL_EQUAL(m2.m31, m.m31);
TEST_REAL_EQUAL(m2.m32, m.m32);
TEST_REAL_EQUAL(m2.m33, m.m33);
TEST_REAL_EQUAL(m2.m34, m.m34);
TEST_REAL_EQUAL(m2.m41, m.m41);
TEST_REAL_EQUAL(m2.m42, m.m42);
TEST_REAL_EQUAL(m2.m43, m.m43);
TEST_REAL_EQUAL(m2.m44, m.m44);
RESULT
CHECK(TQuaternion::TQuaternion operator - () const )
float tmp = 1 / ::sqrt(angle * angle + i * i + j * j + k * k);
q2 = -q;
q1 = Quaternion(-i * tmp, -j * tmp, -k * tmp, angle * tmp);
TEST_REAL_EQUAL(q2.i, q1.i)
TEST_REAL_EQUAL(q2.j, q1.j)
TEST_REAL_EQUAL(q2.k, q1.k)
TEST_REAL_EQUAL(q2.angle, q1.angle)
q1 = Quaternion();
q1.angle = 0;
q2 = Quaternion();
TEST_EQUAL(-q1, q2);
RESULT
CHECK(TQuaternion::getInverse() const )
q1 = -Quaternion(q);
q2 = q.getInverse();
TEST_EQUAL(q2, q1)
RESULT
CHECK(TQuaternion::getConjugate() const )
q1 = q.getConjugate();
TEST_REAL_EQUAL(q1.i, -i)
TEST_REAL_EQUAL(q1.j, -j)
TEST_REAL_EQUAL(q1.k, -k)
TEST_REAL_EQUAL(q1.angle, angle)
RESULT
CHECK(TQuaternion::bool operator == (const TQuaternion& q) const )
q1 = Quaternion(q);
TEST_EQUAL(q1 == q, true)
q1 = Quaternion(v, 4.1);
TEST_EQUAL(q1 == q, false)
RESULT
CHECK(TQuaternion::TQuaternion& operator += (const TQuaternion& q))
q1 = Quaternion();
q1 += q;
TEST_REAL_EQUAL(q1.i, i)
TEST_REAL_EQUAL(q1.j, j)
TEST_REAL_EQUAL(q1.k, k)
TEST_REAL_EQUAL(q1.angle, angle)
RESULT
CHECK(TQuaternion::TQuaternion& operator -= (const TQuaternion& q))
q1 = q2 = Quaternion();
q1 += - q;
q2 -= q;
TEST_REAL_EQUAL(q1.i, q2.i)
TEST_REAL_EQUAL(q1.j, q2.j)
TEST_REAL_EQUAL(q1.k, q2.k)
TEST_REAL_EQUAL(q1.angle, q2.angle)
RESULT
CHECK(TQuaternion::bool operator != (const TQuaternion& q) const )
q1 = Quaternion(q);
TEST_EQUAL(q1 != q, false)
q1 = Quaternion(v, 4.1);
TEST_EQUAL(q1 != q, true)
RESULT
CHECK(TQuaternion::set(const TVector3<T>& axis, const T& angle))
q1 = Quaternion();
q1.set(v, 4.0);
TEST_EQUAL(q1, q)
RESULT
CHECK(TQuaternion::set(const TQuaternion<T>& q, bool /* deep */))
q1 = Quaternion();
q1.set(q);
TEST_EQUAL(q1, q)
RESULT
CHECK(TQuaternion::set(const T& x, const T& y, const T& z, const T& phi))
q1.set(1.0, 2.0, 3.0, 4.0);
TEST_EQUAL(q1 == q, true)
RESULT
CHECK(TQuaternion::get(TQuaternion<T>& q, bool deep))
q.get(q1);
TEST_EQUAL(q1, q)
RESULT
CHECK(TQuaternion::operator = (const TQuaternion<T>& q))
q1 = Quaternion();
q1 = q;
TEST_EQUAL(q1 == q, true)
RESULT
CHECK(TQuaternion::setIdentity())
q1.setIdentity();
TEST_EQUAL(q1.i, 0)
TEST_EQUAL(q1.j, 0)
TEST_EQUAL(q1.k, 0)
TEST_EQUAL(q1.angle, 1)
RESULT
CHECK(TQuaternion operator + (const TQuaternion<T>& a, const TQuaternion<T>& b))
q1 = Quaternion(q);
q2 = q + q1;
q1 += q;
TEST_EQUAL(q2, q1)
RESULT
CHECK(TQuaternion operator - (const TQuaternion<T>& a, const TQuaternion<T>& b))
q1 = Quaternion(q);
q2 = q - q1;
q1 -= q;
TEST_EQUAL(q2, q1)
RESULT
NEW_TMP_FILE(filename)
CHECK(std::istream& operator >>(std::istream& s, TQuaternion<T>& q))
std::ifstream instr("data/Quaternion_test2.txt");
q1 = Quaternion();
instr >> q1;
instr.close();
TEST_REAL_EQUAL(q1.i, i)
TEST_REAL_EQUAL(q1.j, j)
TEST_REAL_EQUAL(q1.k, k)
TEST_REAL_EQUAL(q1.angle, angle)
RESULT
CHECK(std::ostream& operator << (std::ostream& s, const TQuaternion<T>& q))
std::ofstream outstr(filename.c_str(), std::ios::out);
outstr << q;
outstr.close();
TEST_FILE(filename.c_str(), "data/Quaternion_test3.txt", true)
RESULT
CHECK(TQuaternion::dump(std::ostream& s, Size depth) const )
String filename;
NEW_TMP_FILE(filename)
std::ofstream outfile(filename.c_str(), ios::out);
q.dump(outfile);
outfile.close();
TEST_FILE(filename.c_str(), "data/Quaternion_test.txt", true)
RESULT
/////////////////////////////////////////////////////////////
/////////////////////////////////////////////////////////////
END_TEST
<|endoftext|>
|
<commit_before>/**
* \file
* \brief Stack class implementation
*
* \author Copyright (C) 2014-2017 Kamil Szczygiel http://www.distortec.com http://www.freddiechopin.info
*
* \par License
* This Source Code Form is subject to the terms of the Mozilla Public License, v. 2.0. If a copy of the MPL was not
* distributed with this file, You can obtain one at http://mozilla.org/MPL/2.0/.
*/
#include "distortos/architecture/Stack.hpp"
#include "distortos/architecture/initializeStack.hpp"
#include "distortos/internal/memory/dummyDeleter.hpp"
#include <algorithm>
#if CONFIG_ARCHITECTURE_STACK_ALIGNMENT <= 0
#error "Stack alignment must be greater than 0!"
#endif // CONFIG_ARCHITECTURE_STACK_ALIGNMENT <= 0
namespace distortos
{
namespace architecture
{
namespace
{
/*---------------------------------------------------------------------------------------------------------------------+
| local objects
+---------------------------------------------------------------------------------------------------------------------*/
/// alignment of stack, bytes
constexpr size_t stackAlignment {CONFIG_ARCHITECTURE_STACK_ALIGNMENT};
/// sentinel used for stack usage/overflow detection
constexpr uint32_t stackSentinel {0xed419f25};
/*---------------------------------------------------------------------------------------------------------------------+
| local functions' declarations
+---------------------------------------------------------------------------------------------------------------------*/
/**
* \brief Adjusts storage's address to suit architecture's alignment requirements.
*
* \param [in] storage is a pointer to stack's storage
* \param [in] alignment is the required stack alignment, bytes
*
* \return adjusted storage's address
*/
void* adjustStorage(void* const storage, const size_t alignment)
{
return reinterpret_cast<void*>((reinterpret_cast<uintptr_t>(storage) + alignment - 1) / alignment * alignment);
}
/**
* \brief Adjusts storage's size to suit architecture's alignment requirements.
*
* \param [in] storage is a pointer to stack's storage
* \param [in] size is the size of stack's storage, bytes
* \param [in] adjustedStorage is an adjusted storage's address
* \param [in] alignment is the required stack alignment, bytes
*
* \return adjusted storage's size
*/
size_t adjustSize(void* const storage, const size_t size, void* const adjustedStorage, const size_t alignment)
{
const auto storageEnd = reinterpret_cast<uintptr_t>(storage) + size;
const auto adjustedStorageEnd = storageEnd / alignment * alignment;
return adjustedStorageEnd - reinterpret_cast<decltype(adjustedStorageEnd)>(adjustedStorage);
}
/**
* \brief Proxy for initializeStack() which fills stack with stack sentinel before actually initializing it.
*
* \param [in] storage is a pointer to stack's storage
* \param [in] size is the size of stack's storage, bytes
* \param [in] stackGuardSize is the size of "stack guard", bytes
* \param [in] thread is a reference to Thread object passed to function
* \param [in] run is a reference to Thread's "run" function
* \param [in] preTerminationHook is a pointer to Thread's pre-termination hook, nullptr to skip
* \param [in] terminationHook is a reference to Thread's termination hook
*
* \return value that can be used as thread's stack pointer, ready for context switching
*/
void* initializeStackProxy(void* const storage, const size_t size, const size_t stackGuardSize, Thread& thread,
void (& run)(Thread&), void (* preTerminationHook)(Thread&), void (& terminationHook)(Thread&))
{
std::fill_n(static_cast<std::decay<decltype(stackSentinel)>::type*>(storage), size / sizeof(stackSentinel),
stackSentinel);
return initializeStack(static_cast<uint8_t*>(storage) + stackGuardSize,
size > stackGuardSize ? size - stackGuardSize : 0, thread, run, preTerminationHook, terminationHook);
}
} // namespace
/*---------------------------------------------------------------------------------------------------------------------+
| public functions
+---------------------------------------------------------------------------------------------------------------------*/
Stack::Stack(StorageUniquePointer&& storageUniquePointer, const size_t size, Thread& thread, void (& run)(Thread&),
void (* preTerminationHook)(Thread&), void (& terminationHook)(Thread&)) :
storageUniquePointer_{std::move(storageUniquePointer)},
adjustedStorage_{adjustStorage(storageUniquePointer_.get(), stackAlignment)},
adjustedSize_{adjustSize(storageUniquePointer_.get(), size, adjustedStorage_, stackAlignment)},
stackPointer_{initializeStackProxy(adjustedStorage_, adjustedSize_, stackGuardSize_, thread, run,
preTerminationHook, terminationHook)}
{
/// \todo implement minimal size check
}
Stack::Stack(void* const storage, const size_t size) :
storageUniquePointer_{storage, internal::dummyDeleter<void*>},
adjustedStorage_{storage},
adjustedSize_{size},
stackPointer_{}
{
/// \todo implement minimal size check
}
Stack::~Stack()
{
}
bool Stack::checkStackGuard() const
{
return std::all_of(static_cast<decltype(&stackSentinel)>(adjustedStorage_),
static_cast<decltype(&stackSentinel)>(adjustedStorage_) + stackGuardSize_ / sizeof(stackSentinel),
[](decltype(stackSentinel)& element)
{
return element == stackSentinel;
});
}
size_t Stack::getHighWaterMark() const
{
const auto begin =
static_cast<decltype(&stackSentinel)>(adjustedStorage_) + stackGuardSize_ / sizeof(stackSentinel);
const auto end = static_cast<decltype(&stackSentinel)>(adjustedStorage_) + adjustedSize_ / sizeof(stackSentinel);
const auto usedElement = std::find_if_not(begin, end,
[](decltype(stackSentinel)& element) -> bool
{
return element == stackSentinel;
});
return (end - usedElement) * sizeof(*begin);
}
} // namespace architecture
} // namespace distortos
<commit_msg>Explicitly state return type of lambda in Stack::checkStackGuard()<commit_after>/**
* \file
* \brief Stack class implementation
*
* \author Copyright (C) 2014-2017 Kamil Szczygiel http://www.distortec.com http://www.freddiechopin.info
*
* \par License
* This Source Code Form is subject to the terms of the Mozilla Public License, v. 2.0. If a copy of the MPL was not
* distributed with this file, You can obtain one at http://mozilla.org/MPL/2.0/.
*/
#include "distortos/architecture/Stack.hpp"
#include "distortos/architecture/initializeStack.hpp"
#include "distortos/internal/memory/dummyDeleter.hpp"
#include <algorithm>
#if CONFIG_ARCHITECTURE_STACK_ALIGNMENT <= 0
#error "Stack alignment must be greater than 0!"
#endif // CONFIG_ARCHITECTURE_STACK_ALIGNMENT <= 0
namespace distortos
{
namespace architecture
{
namespace
{
/*---------------------------------------------------------------------------------------------------------------------+
| local objects
+---------------------------------------------------------------------------------------------------------------------*/
/// alignment of stack, bytes
constexpr size_t stackAlignment {CONFIG_ARCHITECTURE_STACK_ALIGNMENT};
/// sentinel used for stack usage/overflow detection
constexpr uint32_t stackSentinel {0xed419f25};
/*---------------------------------------------------------------------------------------------------------------------+
| local functions' declarations
+---------------------------------------------------------------------------------------------------------------------*/
/**
* \brief Adjusts storage's address to suit architecture's alignment requirements.
*
* \param [in] storage is a pointer to stack's storage
* \param [in] alignment is the required stack alignment, bytes
*
* \return adjusted storage's address
*/
void* adjustStorage(void* const storage, const size_t alignment)
{
return reinterpret_cast<void*>((reinterpret_cast<uintptr_t>(storage) + alignment - 1) / alignment * alignment);
}
/**
* \brief Adjusts storage's size to suit architecture's alignment requirements.
*
* \param [in] storage is a pointer to stack's storage
* \param [in] size is the size of stack's storage, bytes
* \param [in] adjustedStorage is an adjusted storage's address
* \param [in] alignment is the required stack alignment, bytes
*
* \return adjusted storage's size
*/
size_t adjustSize(void* const storage, const size_t size, void* const adjustedStorage, const size_t alignment)
{
const auto storageEnd = reinterpret_cast<uintptr_t>(storage) + size;
const auto adjustedStorageEnd = storageEnd / alignment * alignment;
return adjustedStorageEnd - reinterpret_cast<decltype(adjustedStorageEnd)>(adjustedStorage);
}
/**
* \brief Proxy for initializeStack() which fills stack with stack sentinel before actually initializing it.
*
* \param [in] storage is a pointer to stack's storage
* \param [in] size is the size of stack's storage, bytes
* \param [in] stackGuardSize is the size of "stack guard", bytes
* \param [in] thread is a reference to Thread object passed to function
* \param [in] run is a reference to Thread's "run" function
* \param [in] preTerminationHook is a pointer to Thread's pre-termination hook, nullptr to skip
* \param [in] terminationHook is a reference to Thread's termination hook
*
* \return value that can be used as thread's stack pointer, ready for context switching
*/
void* initializeStackProxy(void* const storage, const size_t size, const size_t stackGuardSize, Thread& thread,
void (& run)(Thread&), void (* preTerminationHook)(Thread&), void (& terminationHook)(Thread&))
{
std::fill_n(static_cast<std::decay<decltype(stackSentinel)>::type*>(storage), size / sizeof(stackSentinel),
stackSentinel);
return initializeStack(static_cast<uint8_t*>(storage) + stackGuardSize,
size > stackGuardSize ? size - stackGuardSize : 0, thread, run, preTerminationHook, terminationHook);
}
} // namespace
/*---------------------------------------------------------------------------------------------------------------------+
| public functions
+---------------------------------------------------------------------------------------------------------------------*/
Stack::Stack(StorageUniquePointer&& storageUniquePointer, const size_t size, Thread& thread, void (& run)(Thread&),
void (* preTerminationHook)(Thread&), void (& terminationHook)(Thread&)) :
storageUniquePointer_{std::move(storageUniquePointer)},
adjustedStorage_{adjustStorage(storageUniquePointer_.get(), stackAlignment)},
adjustedSize_{adjustSize(storageUniquePointer_.get(), size, adjustedStorage_, stackAlignment)},
stackPointer_{initializeStackProxy(adjustedStorage_, adjustedSize_, stackGuardSize_, thread, run,
preTerminationHook, terminationHook)}
{
/// \todo implement minimal size check
}
Stack::Stack(void* const storage, const size_t size) :
storageUniquePointer_{storage, internal::dummyDeleter<void*>},
adjustedStorage_{storage},
adjustedSize_{size},
stackPointer_{}
{
/// \todo implement minimal size check
}
Stack::~Stack()
{
}
bool Stack::checkStackGuard() const
{
return std::all_of(static_cast<decltype(&stackSentinel)>(adjustedStorage_),
static_cast<decltype(&stackSentinel)>(adjustedStorage_) + stackGuardSize_ / sizeof(stackSentinel),
[](decltype(stackSentinel)& element) -> bool
{
return element == stackSentinel;
});
}
size_t Stack::getHighWaterMark() const
{
const auto begin =
static_cast<decltype(&stackSentinel)>(adjustedStorage_) + stackGuardSize_ / sizeof(stackSentinel);
const auto end = static_cast<decltype(&stackSentinel)>(adjustedStorage_) + adjustedSize_ / sizeof(stackSentinel);
const auto usedElement = std::find_if_not(begin, end,
[](decltype(stackSentinel)& element) -> bool
{
return element == stackSentinel;
});
return (end - usedElement) * sizeof(*begin);
}
} // namespace architecture
} // namespace distortos
<|endoftext|>
|
<commit_before>//
// Aspia Project
// Copyright (C) 2018 Dmitry Chapyshev <dmitry@aspia.ru>
//
// 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 <https://www.gnu.org/licenses/>.
//
#include "base/thread_checker.h"
namespace aspia {
ThreadChecker::ThreadChecker()
{
ensureAssigned();
}
bool ThreadChecker::calledOnValidThread() const
{
std::scoped_lock lock(thread_id_lock_);
if (thread_id_ == std::this_thread::get_id())
return true;
return false;
}
void ThreadChecker::detachFromThread()
{
std::scoped_lock<std::mutex> lock(thread_id_lock_);
thread_id_ = std::thread::id();
}
void ThreadChecker::ensureAssigned()
{
std::scoped_lock lock(thread_id_lock_);
thread_id_ = std::this_thread::get_id();
}
} // namespace aspia
<commit_msg>- Using C++17.<commit_after>//
// Aspia Project
// Copyright (C) 2018 Dmitry Chapyshev <dmitry@aspia.ru>
//
// 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 <https://www.gnu.org/licenses/>.
//
#include "base/thread_checker.h"
namespace aspia {
ThreadChecker::ThreadChecker()
{
ensureAssigned();
}
bool ThreadChecker::calledOnValidThread() const
{
std::scoped_lock lock(thread_id_lock_);
if (thread_id_ == std::this_thread::get_id())
return true;
return false;
}
void ThreadChecker::detachFromThread()
{
std::scoped_lock lock(thread_id_lock_);
thread_id_ = std::thread::id();
}
void ThreadChecker::ensureAssigned()
{
std::scoped_lock lock(thread_id_lock_);
thread_id_ = std::this_thread::get_id();
}
} // namespace aspia
<|endoftext|>
|
<commit_before>/*
* TTBlue Audio Signal Class
* Copyright © 2008, Timothy Place
*
* License: This code is licensed under the terms of the GNU LGPL
* http://www.gnu.org/licenses/lgpl.html
*/
#include "TTAudioSignal.h"
/****************************************************************************************************/
TTAudioSignal::TTAudioSignal(TTUInt8 initialMaxNumChannels)
: isLocallyOwned(false), maxNumChannels(0), vs(0), numChannels(0), sampleVectors(NULL)
{
TTUInt8 i;
maxNumChannels = initialMaxNumChannels;
sampleVectors = (TTSampleVector *)malloc(sizeof(TTSampleVector) * maxNumChannels);
for(i=0; i<maxNumChannels; i++)
sampleVectors[i] = NULL;
}
TTAudioSignal::~TTAudioSignal()
{
TTUInt32 i;
if(isLocallyOwned){
for(i=0; i<maxNumChannels; i++){
free(sampleVectors[i]);
sampleVectors[i] = NULL;
}
isLocallyOwned = false;
}
free(sampleVectors);
}
TTErr TTAudioSignal::setVector(TTUInt8 channel, TTUInt16 vectorSize, TTSampleVector newVector)
{
TTUInt32 i;
// could check against maxnumchannels here
bitdepth = 64;
vs = vectorSize;
if(isLocallyOwned){
for(i=0; i<maxNumChannels; i++){
free(sampleVectors[i]);
sampleVectors[i] = NULL;
}
isLocallyOwned = false;
}
sampleVectors[channel] = newVector;
return kTTErrNone;
}
/*
It sucks if someone sets a 32-bit audio vector, since we have translate it into a 64-bit buffer.
There may be a better way to do this...
For now, we don't simply reference the data passed in. Instead we allocate our own buffer and copy the data.
Unfortunately, this is very slow.
Also note that we are relying on the vector size already being set!
If we passed the vs in to this method, we could avoid having to realloc the memory every single time.
This would probably be a very good idea.
*/
TTErr TTAudioSignal::setVector(TTUInt8 channel, TTUInt16 vectorSize, TTFloat32* newVector)
{
TTUInt32 i;
// 1. could check against maxnumchannels here
// 2. allocate the vector if need be
if(bitdepth != 32 || !isLocallyOwned || vectorSize != vs)
{
bitdepth = 32;
vs = vectorSize;
alloc();
}
// 3. copy the vector (from 32-bits to 64-bits)
for(i=0; i<vectorSize; i++)
sampleVectors[channel][i] = newVector[i];
return kTTErrNone;
}
TTErr TTAudioSignal::getVector(TTUInt8 channel, TTUInt16 vectorSize, TTSampleVector returnedVector)
{
returnedVector = sampleVectors[channel];
return kTTErrNone;
}
TTErr TTAudioSignal::getVector(TTUInt8 channel, TTUInt16 vectorSize, TTFloat32* returnedVector)
{
TTUInt16 i;
for(i=0; i<vectorSize; i++)
returnedVector[i] = (TTFloat32)sampleVectors[channel][i];
return kTTErrNone;
}
TTErr TTAudioSignal::alloc()
{
TTUInt32 i;
if(isLocallyOwned){
for(i=0; i<maxNumChannels; i++){
free(sampleVectors[i]);
sampleVectors[i] = NULL;
}
}
for(i=0; i<maxNumChannels; i++)
sampleVectors[i] = (TTSampleVector)malloc(sizeof(TTSampleValue) * vs);
isLocallyOwned = true;
return kTTErrNone;
}
TTErr TTAudioSignal::allocWithSize(TTUInt16 newVectorSize)
{
if(newVectorSize != vs){
vs = newVectorSize;
return alloc();
}
else
return kTTErrNone;
}
TTUInt8 TTAudioSignal::getMinChannelCount(TTAudioSignal& signal1, TTAudioSignal& signal2)
{
if(signal1.numChannels > signal2.numChannels)
return signal2.numChannels;
else
return signal1.numChannels;
}
TTUInt8 TTAudioSignal::getMinChannelCount(TTAudioSignal& signal1, TTAudioSignal& signal2, TTAudioSignal& signal3)
{
TTUInt8 numChannels = signal1.numChannels;
if(signal2.numChannels < numChannels)
numChannels = signal2.numChannels;
if(signal3.numChannels < numChannels)
numChannels = signal3.numChannels;
return numChannels;
}
TTUInt8 TTAudioSignal::getMaxChannelCount(TTAudioSignal& signal1, TTAudioSignal& signal2)
{
if(signal1.numChannels < signal2.numChannels)
return signal2.numChannels;
else
return signal1.numChannels;
}
TTUInt8 TTAudioSignal::getMaxChannelCount(TTAudioSignal& signal1, TTAudioSignal& signal2, TTAudioSignal& signal3)
{
TTUInt8 numChannels = signal1.numChannels;
if(signal2.numChannels > numChannels)
numChannels = signal2.numChannels;
if(signal3.numChannels > numChannels)
numChannels = signal3.numChannels;
return numChannels;
}
TTUInt8 TTAudioSignal::getNumChannels(TTAudioSignal& signal)
{
return signal.numChannels;
}
// TODO: The old tt audio signal could point to external memory, or allocate its own for the vectors
// This enum was used to keep trac of which was the case:
// enum selectors{
// k_mode_local = 1,
// k_mode_external = 0,
//};
// TODO: implement clear() method -- ZERO OUT A VECTOR'S CONTENTS
TTErr TTAudioSignal::clear()
{
TTUInt8 channel;
TTUInt16 i;
if(!sampleVectors)
return kTTErrGeneric;
for(channel=0; channel<numChannels; channel++){
for(i=0; i<vs; i++)
sampleVectors[channel][i] = 0.0;
}
return kTTErrNone;
}
// TODO: implement fill() method --- SET ALL VALUES IN THE SIGNAL TO A CONSTANT
<commit_msg>Fixes committed by Dave to the Jamoma repository. This includes not malloc() ing zero-sized memory, and not freeing memory that is not owned locally.<commit_after>/*
* TTBlue Audio Signal Class
* Copyright © 2008, Timothy Place
*
* License: This code is licensed under the terms of the GNU LGPL
* http://www.gnu.org/licenses/lgpl.html
*/
#include "TTAudioSignal.h"
/****************************************************************************************************/
TTAudioSignal::TTAudioSignal(TTUInt8 initialMaxNumChannels)
: isLocallyOwned(false), maxNumChannels(0), vs(0), numChannels(0), sampleVectors(NULL)
{
TTUInt8 i;
maxNumChannels = initialMaxNumChannels;
if(maxNumChannels) {
sampleVectors = (TTSampleVector *)malloc(sizeof(TTSampleVector) * maxNumChannels);
for(i=0; i<maxNumChannels; i++)
sampleVectors[i] = NULL;
}
}
TTAudioSignal::~TTAudioSignal()
{
TTUInt32 i;
if(isLocallyOwned){
for(i=0; i<maxNumChannels; i++){
free(sampleVectors[i]);
sampleVectors[i] = NULL;
}
isLocallyOwned = false;
}
free(sampleVectors);
}
TTErr TTAudioSignal::setVector(TTUInt8 channel, TTUInt16 vectorSize, TTSampleVector newVector)
{
TTUInt32 i;
// could check against maxnumchannels here
bitdepth = 64;
vs = vectorSize;
if(isLocallyOwned){
for(i=0; i<maxNumChannels; i++){
free(sampleVectors[i]);
sampleVectors[i] = NULL;
}
isLocallyOwned = false;
}
sampleVectors[channel] = newVector;
return kTTErrNone;
}
/*
It sucks if someone sets a 32-bit audio vector, since we have translate it into a 64-bit buffer.
There may be a better way to do this...
For now, we don't simply reference the data passed in. Instead we allocate our own buffer and copy the data.
Unfortunately, this is very slow.
Also note that we are relying on the vector size already being set!
If we passed the vs in to this method, we could avoid having to realloc the memory every single time.
This would probably be a very good idea.
*/
TTErr TTAudioSignal::setVector(TTUInt8 channel, TTUInt16 vectorSize, TTFloat32* newVector)
{
TTUInt32 i;
// 1. could check against maxnumchannels here
// 2. allocate the vector if need be
if(bitdepth != 32 || !isLocallyOwned || vectorSize != vs)
{
bitdepth = 32;
vs = vectorSize;
alloc();
}
// 3. copy the vector (from 32-bits to 64-bits)
for(i=0; i<vectorSize; i++)
sampleVectors[channel][i] = newVector[i];
return kTTErrNone;
}
TTErr TTAudioSignal::getVector(TTUInt8 channel, TTUInt16 vectorSize, TTSampleVector returnedVector)
{
returnedVector = sampleVectors[channel];
return kTTErrNone;
}
TTErr TTAudioSignal::getVector(TTUInt8 channel, TTUInt16 vectorSize, TTFloat32* returnedVector)
{
TTUInt16 i;
for(i=0; i<vectorSize; i++)
returnedVector[i] = (TTFloat32)sampleVectors[channel][i];
return kTTErrNone;
}
TTErr TTAudioSignal::alloc()
{
TTUInt32 i;
if(isLocallyOwned){
for(i=0; i<maxNumChannels; i++){
free(sampleVectors[i]);
sampleVectors[i] = NULL;
}
}
for(i=0; i<maxNumChannels; i++) {
sampleVectors[i] = (TTSampleVector)malloc(sizeof(TTSampleValue) * vs);
}
isLocallyOwned = maxNumChannels > 0 ? true : false;
return kTTErrNone;
}
TTErr TTAudioSignal::allocWithSize(TTUInt16 newVectorSize)
{
if(newVectorSize != vs){
vs = newVectorSize;
return alloc();
}
else
return kTTErrNone;
}
TTUInt8 TTAudioSignal::getMinChannelCount(TTAudioSignal& signal1, TTAudioSignal& signal2)
{
if(signal1.numChannels > signal2.numChannels)
return signal2.numChannels;
else
return signal1.numChannels;
}
TTUInt8 TTAudioSignal::getMinChannelCount(TTAudioSignal& signal1, TTAudioSignal& signal2, TTAudioSignal& signal3)
{
TTUInt8 numChannels = signal1.numChannels;
if(signal2.numChannels < numChannels)
numChannels = signal2.numChannels;
if(signal3.numChannels < numChannels)
numChannels = signal3.numChannels;
return numChannels;
}
TTUInt8 TTAudioSignal::getMaxChannelCount(TTAudioSignal& signal1, TTAudioSignal& signal2)
{
if(signal1.numChannels < signal2.numChannels)
return signal2.numChannels;
else
return signal1.numChannels;
}
TTUInt8 TTAudioSignal::getMaxChannelCount(TTAudioSignal& signal1, TTAudioSignal& signal2, TTAudioSignal& signal3)
{
TTUInt8 numChannels = signal1.numChannels;
if(signal2.numChannels > numChannels)
numChannels = signal2.numChannels;
if(signal3.numChannels > numChannels)
numChannels = signal3.numChannels;
return numChannels;
}
TTUInt8 TTAudioSignal::getNumChannels(TTAudioSignal& signal)
{
return signal.numChannels;
}
// TODO: The old tt audio signal could point to external memory, or allocate its own for the vectors
// This enum was used to keep trac of which was the case:
// enum selectors{
// k_mode_local = 1,
// k_mode_external = 0,
//};
// TODO: implement clear() method -- ZERO OUT A VECTOR'S CONTENTS
TTErr TTAudioSignal::clear()
{
TTUInt8 channel;
TTUInt16 i;
if(!sampleVectors)
return kTTErrGeneric;
for(channel=0; channel<numChannels; channel++){
for(i=0; i<vs; i++)
sampleVectors[channel][i] = 0.0;
}
return kTTErrNone;
}
// TODO: implement fill() method --- SET ALL VALUES IN THE SIGNAL TO A CONSTANT
<|endoftext|>
|
<commit_before>#include <sys/types.h>
#include <sys/mman.h>
#include <stdlib.h>
#include <unistd.h>
//#include "atexit.h"
//#include "thread_private.h"
#include <iostream>
#include <vector>
#include <unordered_map>
#include <map>
#include <algorithm>
#include <sstream>
#include "xstring.h"
#define NO_ALLOC_MACRO_OVERRIDE
// NEED TWO MEM_TRACKER header files
// one for this .cc file
// another one for the target source files
#include "mem_tracker.h"
using namespace std;
/** actually define the global (extern-ed) variables here
* and do some initialization directly at the beginning of main() */
unsigned long long CALL_COUNT_NEW;
unsigned long long CALL_COUNT_DELETE;
unsigned long long MEMORY_COUNT_NEW;
unsigned long long MEMORY_COUNT_DELETE;
/** this flag activates the tracking */
bool USE_MEM_TRACKER;
/** temporary save variables provided during "delete" call " */
const char* ____DELETE_FILENAME____;
size_t ____DELETE_LINE____;
/** the two main "databases" for the pointers */
tPtrDataStorage ALLOCATED_PTRS;
tPtrDataList ARCHIVED_PTRS;
/** no args ctor */
PtrData::PtrData()
: p(nullptr), size(0), allocated(false), deleted(false),
new_call(), delete_call() { }
/** copy ctor */
PtrData::PtrData(const PtrData& obj)
: p(obj.p), size(obj.size), allocated(obj.allocated), deleted(obj.deleted),
new_call(obj.new_call), delete_call(obj.delete_call) { }
/** keeps all the data for one pointer */
PtrData::PtrData(void* ptr, const size_t& len)
: p(ptr), size(len), allocated(true), deleted(false),
new_call(), delete_call() { }
/** handle new-call */
void* __handle_new_request(size_t size, const char* fn, size_t line) _GLIBCXX_THROW(std::bad_alloc) {
if(USE_MEM_TRACKER) {
CALL_COUNT_NEW++;
MEMORY_COUNT_NEW += size;
}
void* out = malloc(size);
if(USE_MEM_TRACKER) {
USE_MEM_TRACKER = false;
ALLOCATED_PTRS[out] = PtrData(out, size);
ALLOCATED_PTRS[out].new_call = make_pair(string(fn), line);
USE_MEM_TRACKER = true;
}
return out;
}
/** save meta-data (filename, lineno) into tmp-vars for __handle_delete_request */
void __handle_delete_meta_data(const char* fn, const size_t& line) {
____DELETE_FILENAME____ = fn;
____DELETE_LINE____ = line;
}
/** handle delete-call */
void __handle_delete_request(void* ptr) {
if(USE_MEM_TRACKER) {
tPtrDataStorageIter i = ALLOCATED_PTRS.find(ptr);
if(i != ALLOCATED_PTRS.end()) {
USE_MEM_TRACKER = false;
// move PtrData instance from ALLOCATED to ARCHIVED
ARCHIVED_PTRS.push_back(ALLOCATED_PTRS[ptr]);
ALLOCATED_PTRS.erase(ptr);
ARCHIVED_PTRS.back().deleted = true;
ARCHIVED_PTRS.back().delete_call = \
make_pair(string(____DELETE_FILENAME____), ____DELETE_LINE____);
CALL_COUNT_DELETE++;
MEMORY_COUNT_DELETE += ARCHIVED_PTRS.back().size;
USE_MEM_TRACKER = true;
}
}
free(ptr);
}
/** Global "new" operator overload */
void* operator new(size_t size, const char* fn, size_t line) _GLIBCXX_THROW(std::bad_alloc) {
return __handle_new_request(size, fn, line);
}
void* operator new[](size_t size, const char* fn, size_t line) _GLIBCXX_THROW(std::bad_alloc) {
return __handle_new_request(size, fn, line);
}
/** Global "delete" operator overload */
void operator delete(void* ptr) _GLIBCXX_USE_NOEXCEPT {
__handle_delete_request(ptr);
}
void operator delete[](void* ptr) _GLIBCXX_USE_NOEXCEPT {
__handle_delete_request(ptr);
}
/** return delete or new statistics */
string __print_memory_details(bool delete_mode, bool verbose) {
stringstream ss;
tOpPtrDataMap pos2ptr;
tPtrDataList data;
// generate reverse table
if(!delete_mode) {
for(tPtrDataStorage::value_type& i : ALLOCATED_PTRS) {
pos2ptr[i.second.new_call].push_back(i.second);
data.push_back(i.second);
}
} else {
for(PtrData& i : ARCHIVED_PTRS) {
pos2ptr[i.delete_call].push_back(i);
data.push_back(i);
}
}
// directly return, if no details are available
if(data.size() == 0)
return "";
// find PtrData instance allocating most bytes
tPtrDataIter max_iter = std::max_element(data.begin(), data.end(), \
[](const PtrData& a, const PtrData& b) \
{ return (a.size <= b.size); } \
);
// calc/set formatting vars
size_t max_size = max_iter->size;
size_t max_width = 0;
size_t max_cols = 6;
while(max_size) {
max_size /= 10.0;
max_width++;
}
// go over generated map and gen. results
for(tOpPtrDataIter i=pos2ptr.begin(); i!=pos2ptr.end(); ++i) {
// calculate sum of bytes alloced/deleted
unsigned long long sum = 0;
std::for_each(i->second.begin(), i->second.end(), \
[&](const PtrData& x) {
sum += x.size;
}
);
ss << "[i] " << setw(5) << i->first.first << setw(10) <<
" line: " << setw(6) << i->first.second << setw(10) <<
"#calls: " << setw(8) << i->second.size() << setw(10) <<
" bytes: " << setw(16) << sum << endl;
// print: ptr-addr[size] x (max_cols) each line
size_t col = 0;
if(verbose) {
ss << "[E] ";
for(tPtrDataIter p=i->second.begin(); p!=i->second.end(); ++p, col++) {
ss << p->p << "[" << setw(max_width) << p->size << "]";
ss << (((p+1) != i->second.end()) ? ", " : "\n");
if((col % max_cols) == (max_cols - 1))
ss << endl << " ";
}
}
}
return ss.str();
}
/** show some results and hints to search the leaks */
string get_memory_tracker_results(bool verbose) {
long m_diff = (MEMORY_COUNT_NEW - MEMORY_COUNT_DELETE);
long ptr_diff = CALL_COUNT_NEW - CALL_COUNT_DELETE;
stringstream ss;
ss << endl;
ss << "[STATS] Memory tracking overview:" << endl;
ss << endl;
string sep = " | ";
size_t pad = 14;
size_t loff = 8;
size_t hline = 82;
ss << setw(pad+loff) << "tracked" << sep << setw(pad) << "tracked" << sep <<
setw(pad) << "leaked" << sep << setw(pad) << "leaked" << sep << endl;
ss << setw(pad+loff) << "calls" << sep << setw(pad) << "bytes" << sep <<
setw(pad) << "calls" << sep << setw(pad) << "bytes" << sep << endl;
ss << setw(hline) << setfill('-') << "" << setfill(' ') << endl;
ss << setw(loff) << "NEW" << setw(pad) << CALL_COUNT_NEW << sep <<
setw(pad) << MEMORY_COUNT_NEW << sep << setw(pad) << "n/a" << sep <<
setw(pad) << "n/a" << sep << endl;
ss << setw(hline) << setfill('-') << "" << setfill(' ') << endl;
ss << setw(loff) << "DELETE" << setw(pad) << CALL_COUNT_DELETE << sep <<
setw(pad) << MEMORY_COUNT_DELETE << sep << setw(pad) << ptr_diff << sep <<
setw(pad) << m_diff << sep << endl;
if(m_diff > 0) {
ss << endl;
ss << "[LEAK DATA] showing not deleted (bad) calls:" << endl;
ss << __print_memory_details(false, verbose);
} else
cout << "[+] no leaks found!" << endl;
ss << endl;
if(verbose) {
if(CALL_COUNT_DELETE > 0) {
ss << "[DELETE DATA] showing deleted (good) calls:" << endl;
ss << __print_memory_details(true, verbose);
ss << endl;
} else
cout << "[i] no delete calls tracked..." << endl;
}
return ss.str();
}
// saving pointer to original ::exit() function call
auto original_exit = &::exit;
/** To avoid a segfault on exit, if MEM_TRACKER is used.
* (Segfault due to the automated cleanup of MemTracker datastructures on leaving scope) */
void exit(int status) throw() {
ALLOCATED_PTRS.clear();
ARCHIVED_PTRS.clear();
// calling "real" exit()
original_exit(status);
}
/** initilize the memory tracker variables */
void init_memory_tracker() {
CALL_COUNT_NEW = 0;
CALL_COUNT_DELETE = 0;
MEMORY_COUNT_NEW = 0;
MEMORY_COUNT_DELETE = 0;
____DELETE_FILENAME____ = "";
____DELETE_LINE____ = 0;
// set to true to start tracking!
USE_MEM_TRACKER = false;
ALLOCATED_PTRS.clear();
ARCHIVED_PTRS.clear();
}
<commit_msg>fixed segfault exit behavior<commit_after>#include <sys/types.h>
#include <sys/mman.h>
#include <stdlib.h>
#include <unistd.h>
//#include "atexit.h"
//#include "thread_private.h"
#include <iostream>
#include <vector>
#include <unordered_map>
#include <map>
#include <algorithm>
#include <sstream>
#include "xstring.h"
#define NO_ALLOC_MACRO_OVERRIDE
// NEED TWO MEM_TRACKER header files
// one for this .cc file
// another one for the target source files
#include "mem_tracker.h"
using namespace std;
/** actually define the global (extern-ed) variables here
* and do some initialization directly at the beginning of main() */
unsigned long long CALL_COUNT_NEW;
unsigned long long CALL_COUNT_DELETE;
unsigned long long MEMORY_COUNT_NEW;
unsigned long long MEMORY_COUNT_DELETE;
/** this flag activates the tracking */
bool USE_MEM_TRACKER;
/** temporary save variables provided during "delete" call " */
const char* ____DELETE_FILENAME____;
size_t ____DELETE_LINE____;
/** the two main "databases" for the pointers */
tPtrDataStorage ALLOCATED_PTRS;
tPtrDataList ARCHIVED_PTRS;
/** no args ctor */
PtrData::PtrData()
: p(nullptr), size(0), allocated(false), deleted(false),
new_call(), delete_call() { }
/** copy ctor */
PtrData::PtrData(const PtrData& obj)
: p(obj.p), size(obj.size), allocated(obj.allocated), deleted(obj.deleted),
new_call(obj.new_call), delete_call(obj.delete_call) { }
/** keeps all the data for one pointer */
PtrData::PtrData(void* ptr, const size_t& len)
: p(ptr), size(len), allocated(true), deleted(false),
new_call(), delete_call() { }
/** handle new-call */
void* __handle_new_request(size_t size, const char* fn, size_t line) _GLIBCXX_THROW(std::bad_alloc) {
if(USE_MEM_TRACKER) {
CALL_COUNT_NEW++;
MEMORY_COUNT_NEW += size;
}
void* out = malloc(size);
if(USE_MEM_TRACKER) {
USE_MEM_TRACKER = false;
ALLOCATED_PTRS[out] = PtrData(out, size);
ALLOCATED_PTRS[out].new_call = make_pair(string(fn), line);
USE_MEM_TRACKER = true;
}
return out;
}
/** save meta-data (filename, lineno) into tmp-vars for __handle_delete_request */
void __handle_delete_meta_data(const char* fn, const size_t& line) {
____DELETE_FILENAME____ = fn;
____DELETE_LINE____ = line;
}
/** handle delete-call */
void __handle_delete_request(void* ptr) {
if(USE_MEM_TRACKER) {
tPtrDataStorageIter i = ALLOCATED_PTRS.find(ptr);
if(i != ALLOCATED_PTRS.end()) {
USE_MEM_TRACKER = false;
// move PtrData instance from ALLOCATED to ARCHIVED
ARCHIVED_PTRS.push_back(ALLOCATED_PTRS[ptr]);
ALLOCATED_PTRS.erase(ptr);
ARCHIVED_PTRS.back().deleted = true;
ARCHIVED_PTRS.back().delete_call = \
make_pair(string(____DELETE_FILENAME____), ____DELETE_LINE____);
CALL_COUNT_DELETE++;
MEMORY_COUNT_DELETE += ARCHIVED_PTRS.back().size;
USE_MEM_TRACKER = true;
}
}
free(ptr);
}
/** Global "new" operator overload */
void* operator new(size_t size, const char* fn, size_t line) _GLIBCXX_THROW(std::bad_alloc) {
return __handle_new_request(size, fn, line);
}
void* operator new[](size_t size, const char* fn, size_t line) _GLIBCXX_THROW(std::bad_alloc) {
return __handle_new_request(size, fn, line);
}
/** Global "delete" operator overload */
void operator delete(void* ptr) _GLIBCXX_USE_NOEXCEPT {
__handle_delete_request(ptr);
}
void operator delete[](void* ptr) _GLIBCXX_USE_NOEXCEPT {
__handle_delete_request(ptr);
}
/** return delete or new statistics */
string __print_memory_details(bool delete_mode, bool verbose) {
stringstream ss;
tOpPtrDataMap pos2ptr;
tPtrDataList data;
// generate reverse table
if(!delete_mode) {
for(tPtrDataStorage::value_type& i : ALLOCATED_PTRS) {
pos2ptr[i.second.new_call].push_back(i.second);
data.push_back(i.second);
}
} else {
for(PtrData& i : ARCHIVED_PTRS) {
pos2ptr[i.delete_call].push_back(i);
data.push_back(i);
}
}
// directly return, if no details are available
if(data.size() == 0)
return "";
// find PtrData instance allocating most bytes
tPtrDataIter max_iter = std::max_element(data.begin(), data.end(), \
[](const PtrData& a, const PtrData& b) \
{ return (a.size <= b.size); } \
);
// calc/set formatting vars
size_t max_size = max_iter->size;
size_t max_width = 0;
size_t max_cols = 6;
while(max_size) {
max_size /= 10.0;
max_width++;
}
// go over generated map and gen. results
for(tOpPtrDataIter i=pos2ptr.begin(); i!=pos2ptr.end(); ++i) {
// calculate sum of bytes alloced/deleted
unsigned long long sum = 0;
std::for_each(i->second.begin(), i->second.end(), \
[&](const PtrData& x) {
sum += x.size;
}
);
ss << "[i] " << setw(5) << i->first.first << setw(10) <<
" line: " << setw(6) << i->first.second << setw(10) <<
"#calls: " << setw(8) << i->second.size() << setw(10) <<
" bytes: " << setw(16) << sum << endl;
// print: ptr-addr[size] x (max_cols) each line
size_t col = 0;
if(verbose) {
ss << "[E] ";
for(tPtrDataIter p=i->second.begin(); p!=i->second.end(); ++p, col++) {
ss << p->p << "[" << setw(max_width) << p->size << "]";
ss << (((p+1) != i->second.end()) ? ", " : "\n");
if((col % max_cols) == (max_cols - 1))
ss << endl << " ";
}
}
}
return ss.str();
}
/** show some results and hints to search the leaks */
string get_memory_tracker_results(bool verbose) {
long m_diff = (MEMORY_COUNT_NEW - MEMORY_COUNT_DELETE);
long ptr_diff = CALL_COUNT_NEW - CALL_COUNT_DELETE;
stringstream ss;
ss << endl;
ss << "[STATS] Memory tracking overview:" << endl;
ss << endl;
string sep = " | ";
size_t pad = 14;
size_t loff = 8;
size_t hline = 82;
ss << setw(pad+loff) << "tracked" << sep << setw(pad) << "tracked" << sep <<
setw(pad) << "leaked" << sep << setw(pad) << "leaked" << sep << endl;
ss << setw(pad+loff) << "calls" << sep << setw(pad) << "bytes" << sep <<
setw(pad) << "calls" << sep << setw(pad) << "bytes" << sep << endl;
ss << setw(hline) << setfill('-') << "" << setfill(' ') << endl;
ss << setw(loff) << "NEW" << setw(pad) << CALL_COUNT_NEW << sep <<
setw(pad) << MEMORY_COUNT_NEW << sep << setw(pad) << "n/a" << sep <<
setw(pad) << "n/a" << sep << endl;
ss << setw(hline) << setfill('-') << "" << setfill(' ') << endl;
ss << setw(loff) << "DELETE" << setw(pad) << CALL_COUNT_DELETE << sep <<
setw(pad) << MEMORY_COUNT_DELETE << sep << setw(pad) << ptr_diff << sep <<
setw(pad) << m_diff << sep << endl;
if(m_diff > 0) {
ss << endl;
ss << "[LEAK DATA] showing not deleted (bad) calls:" << endl;
ss << __print_memory_details(false, verbose);
} else
cout << "[+] no leaks found!" << endl;
ss << endl;
if(verbose) {
if(CALL_COUNT_DELETE > 0) {
ss << "[DELETE DATA] showing deleted (good) calls:" << endl;
ss << __print_memory_details(true, verbose);
ss << endl;
} else
cout << "[i] no delete calls tracked..." << endl;
}
return ss.str();
}
/** To avoid a segfault on exit, if MEM_TRACKER is used.
* (Segfault due to the automated cleanup of MemTracker datastructures on leaving scope) */
void exit(int status) throw() {
ALLOCATED_PTRS.clear();
ARCHIVED_PTRS.clear();
// calling "real" exit()
_exit(status);
}
/** initilize the memory tracker variables */
void init_memory_tracker() {
CALL_COUNT_NEW = 0;
CALL_COUNT_DELETE = 0;
MEMORY_COUNT_NEW = 0;
MEMORY_COUNT_DELETE = 0;
____DELETE_FILENAME____ = "";
____DELETE_LINE____ = 0;
// set to true to start tracking!
USE_MEM_TRACKER = false;
ALLOCATED_PTRS.clear();
ARCHIVED_PTRS.clear();
}
<|endoftext|>
|
<commit_before>#include <glow/memory.h>
#include <glow/global.h>
#include <glow/Extension.h>
namespace {
GLint getMemoryInformation(GLenum pname)
{
if (!glow::hasExtension("NVX_gpu_memory_info"))
return -1;
return glow::getInteger(pname);
}
}
namespace glow
{
namespace memory
{
GLint total()
{
return getMemoryInformation(GPU_MEMORY_INFO_TOTAL_AVAILABLE_MEMORY_NVX);
}
GLint dedicated()
{
return getMemoryInformation(GPU_MEMORY_INFO_DEDICATED_VIDMEM_NVX);
}
GLint available()
{
return getMemoryInformation(GPU_MEMORY_INFO_CURRENT_AVAILABLE_VIDMEM_NVX);
}
GLint evicted()
{
return getMemoryInformation(GPU_MEMORY_INFO_EVICTED_MEMORY_NVX);
}
GLint evictionCount()
{
return getMemoryInformation(GPU_MEMORY_INFO_EVICTION_COUNT_NVX);
}
}
}
<commit_msg>Add missing GL_ prefixes to previously removed constants<commit_after>#include <glow/memory.h>
#include <glow/global.h>
#include <glow/Extension.h>
namespace {
GLint getMemoryInformation(GLenum pname)
{
if (!glow::hasExtension("NVX_gpu_memory_info"))
return -1;
return glow::getInteger(pname);
}
}
namespace glow
{
namespace memory
{
GLint total()
{
return getMemoryInformation(GL_GPU_MEMORY_INFO_TOTAL_AVAILABLE_MEMORY_NVX);
}
GLint dedicated()
{
return getMemoryInformation(GL_GPU_MEMORY_INFO_DEDICATED_VIDMEM_NVX);
}
GLint available()
{
return getMemoryInformation(GL_GPU_MEMORY_INFO_CURRENT_AVAILABLE_VIDMEM_NVX);
}
GLint evicted()
{
return getMemoryInformation(GL_GPU_MEMORY_INFO_EVICTED_MEMORY_NVX);
}
GLint evictionCount()
{
return getMemoryInformation(GL_GPU_MEMORY_INFO_EVICTION_COUNT_NVX);
}
}
}
<|endoftext|>
|
<commit_before>#include <cassert>
#include <GL/glew.h>
#include <glow/logging.h>
#include <glow/global.h>
#include <glow/Error.h>
#include <GLFW/glfw3.h> // specifies APIENTRY, should be after Error.h include,
// which requires APIENTRY in windows..
#include <glowwindow/Context.h>
using namespace glow;
namespace glowwindow
{
Context::Context()
: m_swapInterval(VerticalSyncronization)
, m_window(nullptr)
{
}
Context::~Context()
{
release();
}
GLFWwindow * Context::window()
{
return m_window;
}
bool Context::create(const ContextFormat & format, const int width, const int height, GLFWmonitor * monitor)
{
if (isValid())
{
warning() << "Context is already valid. Create was probably called before.";
return true;
}
if (!glfwInit())
{
fatal() << "Could not initialize GLFW.";
return false;
}
m_format = format;
prepareFormat(m_format);
/*
* GLFW3 does not set default hint values on window creation so at least
* the default values must be set before glfwCreateWindow can be called.
* c.f. http://www.glfw.org/docs/latest/group__window.html#ga4fd9e504bb937e79588a0ffdca9f620b
*/
glfwDefaultWindowHints();
m_window = glfwCreateWindow(width, height, "glow", monitor, nullptr);
if (!m_window)
{
fatal() << "Context creation failed (GLFW).";
release();
return false;
}
makeCurrent();
if (!glow::init())
{
fatal() << "GLOW/GLEW initialization failed.";
release();
return false;
}
glfwSwapInterval(m_swapInterval);
doneCurrent();
// TODO: gather actual context format information and verify
//ContextFormat::verify(format, m_format);
return true;
}
void Context::prepareFormat(const ContextFormat & format)
{
Version version = validateVersion(format.version());
if (!format.version().isNull() && format.version() != version)
{
glow::warning() << "Changed unsupported OpenGL version from " << format.version() << " to " << version << ".";
}
glfwDefaultWindowHints();
glfwWindowHint(GLFW_CONTEXT_VERSION_MAJOR, version.majorVersion);
glfwWindowHint(GLFW_CONTEXT_VERSION_MINOR, version.minorVersion);
glfwWindowHint(GLFW_OPENGL_FORWARD_COMPAT, GL_TRUE);
if (version >= Version(3, 2))
{
glfwWindowHint(GLFW_OPENGL_PROFILE, format.profile() == ContextFormat::CoreProfile ? GLFW_OPENGL_CORE_PROFILE : GLFW_OPENGL_COMPAT_PROFILE);
}
glfwWindowHint(GLFW_DEPTH_BITS, format.depthBufferSize());
glfwWindowHint(GLFW_STENCIL_BITS, format.stencilBufferSize());
glfwWindowHint(GLFW_RED_BITS, format.redBufferSize());
glfwWindowHint(GLFW_GREEN_BITS, format.greenBufferSize());
glfwWindowHint(GLFW_BLUE_BITS, format.blueBufferSize());
glfwWindowHint(GLFW_ALPHA_BITS, format.alphaBufferSize());
glfwWindowHint(GLFW_SAMPLES, format.samples());
}
void Context::release()
{
if (!isValid())
return;
glfwDestroyWindow(m_window);
m_window = nullptr;
}
void Context::swap()
{
if (!isValid())
return;
glfwSwapBuffers(m_window);
}
bool Context::isValid() const
{
return m_window != nullptr;
}
const ContextFormat & Context::format() const
{
return m_format;
}
const std::string Context::swapIntervalString(const SwapInterval swapInterval)
{
switch(swapInterval)
{
case NoVerticalSyncronization:
return "NoVerticalSyncronization";
case VerticalSyncronization:
return "VerticalSyncronization";
case AdaptiveVerticalSyncronization:
return "AdaptiveVerticalSyncronization";
default:
return "";
};
}
Context::SwapInterval Context::swapInterval() const
{
return m_swapInterval;
}
void Context::setSwapInterval(const SwapInterval interval)
{
if (interval == m_swapInterval)
return;
m_swapInterval = interval;
makeCurrent();
glfwSwapInterval(m_swapInterval);
doneCurrent();
}
void Context::makeCurrent()
{
if (!isValid())
return;
glfwMakeContextCurrent(m_window);
}
void Context::doneCurrent()
{
if (!isValid())
return;
glfwMakeContextCurrent(0);
}
Version Context::maximumSupportedVersion()
{
Version maxVersion;
GLFWwindow * versionCheckWindow = glfwCreateWindow(1, 1, "VersionCheck", nullptr, nullptr);
if (versionCheckWindow)
{
glfwMakeContextCurrent(versionCheckWindow);
if (glow::init())
{
maxVersion = glow::Version::current();
}
glfwDestroyWindow(versionCheckWindow);
}
return maxVersion;
}
Version Context::validateVersion(const Version & version)
{
Version maxVersion = maximumSupportedVersion();
if (maxVersion.isNull())
{
maxVersion = Version(3, 0);
}
if (version.isNull() || version > maxVersion)
{
return maxVersion;
}
if (!version.isValid())
{
Version nearestValidVersion = version.nearestValidVersion();
if (nearestValidVersion > maxVersion)
{
return maxVersion;
}
return nearestValidVersion;
}
return version;
}
} // namespace glowwindow
<commit_msg>(1) Removed the call to glfwDefaultWindowHints() from Context::create() so that the hints set in prepareFomrate() are not overridden.<commit_after>#include <cassert>
#include <GL/glew.h>
#include <glow/logging.h>
#include <glow/global.h>
#include <glow/Error.h>
#include <GLFW/glfw3.h> // specifies APIENTRY, should be after Error.h include,
// which requires APIENTRY in windows..
#include <glowwindow/Context.h>
using namespace glow;
namespace glowwindow
{
Context::Context()
: m_swapInterval(VerticalSyncronization)
, m_window(nullptr)
{
}
Context::~Context()
{
release();
}
GLFWwindow * Context::window()
{
return m_window;
}
bool Context::create(const ContextFormat & format, const int width, const int height, GLFWmonitor * monitor)
{
if (isValid())
{
warning() << "Context is already valid. Create was probably called before.";
return true;
}
if (!glfwInit())
{
fatal() << "Could not initialize GLFW.";
return false;
}
m_format = format;
prepareFormat(m_format);
m_window = glfwCreateWindow(width, height, "glow", monitor, nullptr);
if (!m_window)
{
fatal() << "Context creation failed (GLFW).";
release();
return false;
}
makeCurrent();
if (!glow::init())
{
fatal() << "GLOW/GLEW initialization failed.";
release();
return false;
}
glfwSwapInterval(m_swapInterval);
doneCurrent();
// TODO: gather actual context format information and verify
//ContextFormat::verify(format, m_format);
return true;
}
void Context::prepareFormat(const ContextFormat & format)
{
Version version = validateVersion(format.version());
if (!format.version().isNull() && format.version() != version)
{
glow::warning() << "Changed unsupported OpenGL version from " << format.version() << " to " << version << ".";
}
/*
* GLFW3 does not set default hint values on window creation so at least
* the default values must be set before glfwCreateWindow can be called.
* c.f. http://www.glfw.org/docs/latest/group__window.html#ga4fd9e504bb937e79588a0ffdca9f620b
*/
glfwDefaultWindowHints();
glfwWindowHint(GLFW_CONTEXT_VERSION_MAJOR, version.majorVersion);
glfwWindowHint(GLFW_CONTEXT_VERSION_MINOR, version.minorVersion);
glfwWindowHint(GLFW_OPENGL_FORWARD_COMPAT, GL_TRUE);
if (version >= Version(3, 2))
{
glfwWindowHint(GLFW_OPENGL_PROFILE, format.profile() == ContextFormat::CoreProfile ? GLFW_OPENGL_CORE_PROFILE : GLFW_OPENGL_COMPAT_PROFILE);
}
glfwWindowHint(GLFW_DEPTH_BITS, format.depthBufferSize());
glfwWindowHint(GLFW_STENCIL_BITS, format.stencilBufferSize());
glfwWindowHint(GLFW_RED_BITS, format.redBufferSize());
glfwWindowHint(GLFW_GREEN_BITS, format.greenBufferSize());
glfwWindowHint(GLFW_BLUE_BITS, format.blueBufferSize());
glfwWindowHint(GLFW_ALPHA_BITS, format.alphaBufferSize());
glfwWindowHint(GLFW_SAMPLES, format.samples());
}
void Context::release()
{
if (!isValid())
return;
glfwDestroyWindow(m_window);
m_window = nullptr;
}
void Context::swap()
{
if (!isValid())
return;
glfwSwapBuffers(m_window);
}
bool Context::isValid() const
{
return m_window != nullptr;
}
const ContextFormat & Context::format() const
{
return m_format;
}
const std::string Context::swapIntervalString(const SwapInterval swapInterval)
{
switch(swapInterval)
{
case NoVerticalSyncronization:
return "NoVerticalSyncronization";
case VerticalSyncronization:
return "VerticalSyncronization";
case AdaptiveVerticalSyncronization:
return "AdaptiveVerticalSyncronization";
default:
return "";
};
}
Context::SwapInterval Context::swapInterval() const
{
return m_swapInterval;
}
void Context::setSwapInterval(const SwapInterval interval)
{
if (interval == m_swapInterval)
return;
m_swapInterval = interval;
makeCurrent();
glfwSwapInterval(m_swapInterval);
doneCurrent();
}
void Context::makeCurrent()
{
if (!isValid())
return;
glfwMakeContextCurrent(m_window);
}
void Context::doneCurrent()
{
if (!isValid())
return;
glfwMakeContextCurrent(0);
}
Version Context::maximumSupportedVersion()
{
Version maxVersion;
GLFWwindow * versionCheckWindow = glfwCreateWindow(1, 1, "VersionCheck", nullptr, nullptr);
if (versionCheckWindow)
{
glfwMakeContextCurrent(versionCheckWindow);
if (glow::init())
{
maxVersion = glow::Version::current();
}
glfwDestroyWindow(versionCheckWindow);
}
return maxVersion;
}
Version Context::validateVersion(const Version & version)
{
Version maxVersion = maximumSupportedVersion();
if (maxVersion.isNull())
{
maxVersion = Version(3, 0);
}
if (version.isNull() || version > maxVersion)
{
return maxVersion;
}
if (!version.isValid())
{
Version nearestValidVersion = version.nearestValidVersion();
if (nearestValidVersion > maxVersion)
{
return maxVersion;
}
return nearestValidVersion;
}
return version;
}
} // namespace glowwindow
<|endoftext|>
|
<commit_before>
// MIT License
//
// Copyright (c) 2017 Thibault Martinez
//
// 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 <iota/constants.hpp>
#include <iota/crypto/sponge_factory.hpp>
#include <iota/models/transaction.hpp>
#include <iota/types/trinary.hpp>
namespace IOTA {
namespace Models {
const std::pair<int, int> Transaction::SignatureFragmentsOffset = { 0, 2187 };
const std::pair<int, int> Transaction::AddressOffset = { 2187, 2268 };
const std::pair<int, int> Transaction::ValueOffset = { 6804, 6837 };
const std::pair<int, int> Transaction::TagOffset = { 2295, 2322 };
const std::pair<int, int> Transaction::TimestampOffset = { 6966, 6993 };
const std::pair<int, int> Transaction::CurrentIndexOffset = { 6993, 7020 };
const std::pair<int, int> Transaction::LastIndexOffset = { 7020, 7047 };
const std::pair<int, int> Transaction::BundleOffset = { 2349, 2430 };
const std::pair<int, int> Transaction::TrunkOffset = { 2430, 2511 };
const std::pair<int, int> Transaction::BranchOffset = { 2511, 2592 };
const std::pair<int, int> Transaction::NonceOffset = { 2592, 2673 };
Transaction::Transaction() : value_(0), timestamp_(0), currentIndex_(0), lastIndex_(0) {
}
Transaction::Transaction(const std::string& trytes) {
initFromTrytes(trytes);
}
Transaction::Transaction(const std::string& signatureFragments, int64_t currentIndex,
int64_t lastIndex, const std::string& nonce, const std::string& hash,
const std::string& tag, int64_t timestamp,
const std::string& trunkTransaction, const std::string& branchTransaction,
const std::string& address, int64_t value, const std::string& bundle)
: hash_(hash),
signatureFragments_(signatureFragments),
address_(address),
value_(value),
tag_(tag),
timestamp_(timestamp),
currentIndex_(currentIndex),
lastIndex_(lastIndex),
bundle_(bundle),
trunkTransaction_(trunkTransaction),
branchTransaction_(branchTransaction),
nonce_(nonce) {
}
Transaction::Transaction(const std::string& address, int64_t value, const std::string& tag,
int64_t timestamp)
: address_(address),
value_(value),
tag_(tag),
timestamp_(timestamp),
currentIndex_(0),
lastIndex_(0) {
}
bool
Transaction::isTailTransaction() const {
return getCurrentIndex() == 0;
}
const std::string&
Transaction::getHash() const {
return hash_;
}
void
Transaction::setHash(const std::string& hash) {
hash_ = hash;
}
const std::string&
Transaction::getSignatureFragments() const {
return signatureFragments_;
}
void
Transaction::setSignatureFragments(const std::string& signatureFragments) {
signatureFragments_ = signatureFragments;
}
const std::string&
Transaction::getAddress() const {
return address_;
}
void
Transaction::setAddress(const std::string& address) {
address_ = address;
}
int64_t
Transaction::getValue() const {
return value_;
}
void
Transaction::setValue(int64_t value) {
value_ = value;
}
const std::string&
Transaction::getTag() const {
return tag_;
}
void
Transaction::setTag(const std::string& tag) {
tag_ = tag;
}
int64_t
Transaction::getTimestamp() const {
return timestamp_;
}
void
Transaction::setTimestamp(int64_t timestamp) {
timestamp_ = timestamp;
}
int64_t
Transaction::getCurrentIndex() const {
return currentIndex_;
}
void
Transaction::setCurrentIndex(int64_t currentIndex) {
currentIndex_ = currentIndex;
}
int64_t
Transaction::getLastIndex() const {
return lastIndex_;
}
void
Transaction::setLastIndex(int64_t lastIndex) {
lastIndex_ = lastIndex;
}
const std::string&
Transaction::getBundle() const {
return bundle_;
}
void
Transaction::setBundle(const std::string& bundle) {
bundle_ = bundle;
}
const std::string&
Transaction::getTrunkTransaction() const {
return trunkTransaction_;
}
void
Transaction::setTrunkTransaction(const std::string& trunkTransaction) {
trunkTransaction_ = trunkTransaction;
}
const std::string&
Transaction::getBranchTransaction() const {
return branchTransaction_;
}
void
Transaction::setBranchTransaction(const std::string& branchTransaction) {
branchTransaction_ = branchTransaction;
}
const std::string&
Transaction::getNonce() const {
return nonce_;
}
void
Transaction::setNonce(const std::string& nonce) {
nonce_ = nonce;
}
bool
Transaction::getPersistence() const {
return persistence_;
}
void
Transaction::setPersistence(bool persistence) {
persistence_ = persistence;
}
bool
Transaction::operator==(Transaction rhs) const {
return hash_ == rhs.getHash();
}
bool
Transaction::operator!=(Transaction rhs) const {
return !operator==(rhs);
}
std::string
Transaction::toTrytes() const {
auto value = IOTA::Types::tritsToTrytes(IOTA::Types::intToTrits(getValue(), SeedLength));
auto timestamp =
IOTA::Types::tritsToTrytes(IOTA::Types::intToTrits(getTimestamp(), TryteAlphabetLength));
auto currentIndex =
IOTA::Types::tritsToTrytes(IOTA::Types::intToTrits(getCurrentIndex(), TryteAlphabetLength));
auto lastIndex =
IOTA::Types::tritsToTrytes(IOTA::Types::intToTrits(getLastIndex(), TryteAlphabetLength));
return getSignatureFragments() + getAddress() + value + getTag() + timestamp + currentIndex +
lastIndex + getBundle() + getTrunkTransaction() + getBranchTransaction() + getNonce();
}
void
Transaction::initFromTrytes(const std::string& trytes) {
if (trytes.empty()) {
return;
}
//! TODO: length check
//! what length are we supposed to receive?
// validity check
for (int i = 2279; i < 2295; i++) {
if (trytes[i] != '9') {
return;
}
}
auto transactionTrits = IOTA::Types::trytesToTrits(trytes);
auto hash = IOTA::Types::Trits(TritHashLength);
// generate the correct transaction hash
auto curl = IOTA::Crypto::create(IOTA::Crypto::SpongeType::CURL);
curl->absorb(transactionTrits);
curl->squeeze(hash);
//! Hash
setHash(IOTA::Types::tritsToTrytes(hash));
//! Signature
setSignatureFragments(
trytes.substr(SignatureFragmentsOffset.first,
SignatureFragmentsOffset.second - SignatureFragmentsOffset.first));
//! Address
setAddress(trytes.substr(AddressOffset.first, AddressOffset.second - AddressOffset.first));
//! Value
setValue(IOTA::Types::tritsToInt<int64_t>(IOTA::Types::Trits(
std::vector<int8_t>{ std::begin(transactionTrits) + ValueOffset.first,
std::begin(transactionTrits) + ValueOffset.second })));
//! Tag
setTag(trytes.substr(TagOffset.first, TagOffset.second - TagOffset.first));
//! Timestamp
setTimestamp(IOTA::Types::tritsToInt<int64_t>(IOTA::Types::Trits(
std::vector<int8_t>{ std::begin(transactionTrits) + TimestampOffset.first,
std::begin(transactionTrits) + TimestampOffset.second })));
//! Current Index
setCurrentIndex(IOTA::Types::tritsToInt<int64_t>(IOTA::Types::Trits(
std::vector<int8_t>{ std::begin(transactionTrits) + CurrentIndexOffset.first,
std::begin(transactionTrits) + CurrentIndexOffset.second })));
//! Last Index
setLastIndex(IOTA::Types::tritsToInt<int64_t>(IOTA::Types::Trits(
std::vector<int8_t>{ std::begin(transactionTrits) + LastIndexOffset.first,
std::begin(transactionTrits) + LastIndexOffset.second })));
//! Bundle
setBundle(trytes.substr(BundleOffset.first, BundleOffset.second - BundleOffset.first));
//! Trunk Transaction
setTrunkTransaction(trytes.substr(TrunkOffset.first, TrunkOffset.second - TrunkOffset.first));
//! Branch Transaction
setBranchTransaction(trytes.substr(BranchOffset.first, BranchOffset.second - BranchOffset.first));
//! Nonce
setNonce(trytes.substr(NonceOffset.first, NonceOffset.second - NonceOffset.first));
}
} // namespace Models
} // namespace IOTA
<commit_msg>explicit init of bool Transaction::persistence_ to false (apparently default is false on macOS but true on debian?)<commit_after>
// MIT License
//
// Copyright (c) 2017 Thibault Martinez
//
// 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 <iota/constants.hpp>
#include <iota/crypto/sponge_factory.hpp>
#include <iota/models/transaction.hpp>
#include <iota/types/trinary.hpp>
namespace IOTA {
namespace Models {
const std::pair<int, int> Transaction::SignatureFragmentsOffset = { 0, 2187 };
const std::pair<int, int> Transaction::AddressOffset = { 2187, 2268 };
const std::pair<int, int> Transaction::ValueOffset = { 6804, 6837 };
const std::pair<int, int> Transaction::TagOffset = { 2295, 2322 };
const std::pair<int, int> Transaction::TimestampOffset = { 6966, 6993 };
const std::pair<int, int> Transaction::CurrentIndexOffset = { 6993, 7020 };
const std::pair<int, int> Transaction::LastIndexOffset = { 7020, 7047 };
const std::pair<int, int> Transaction::BundleOffset = { 2349, 2430 };
const std::pair<int, int> Transaction::TrunkOffset = { 2430, 2511 };
const std::pair<int, int> Transaction::BranchOffset = { 2511, 2592 };
const std::pair<int, int> Transaction::NonceOffset = { 2592, 2673 };
Transaction::Transaction()
: value_(0), timestamp_(0), currentIndex_(0), lastIndex_(0), persistence_(false) {
}
Transaction::Transaction(const std::string& trytes) : persistence_(false) {
initFromTrytes(trytes);
}
Transaction::Transaction(const std::string& signatureFragments, int64_t currentIndex,
int64_t lastIndex, const std::string& nonce, const std::string& hash,
const std::string& tag, int64_t timestamp,
const std::string& trunkTransaction, const std::string& branchTransaction,
const std::string& address, int64_t value, const std::string& bundle)
: hash_(hash),
signatureFragments_(signatureFragments),
address_(address),
value_(value),
tag_(tag),
timestamp_(timestamp),
currentIndex_(currentIndex),
lastIndex_(lastIndex),
bundle_(bundle),
trunkTransaction_(trunkTransaction),
branchTransaction_(branchTransaction),
nonce_(nonce),
persistence_(false) {
}
Transaction::Transaction(const std::string& address, int64_t value, const std::string& tag,
int64_t timestamp)
: address_(address),
value_(value),
tag_(tag),
timestamp_(timestamp),
currentIndex_(0),
lastIndex_(0) {
}
bool
Transaction::isTailTransaction() const {
return getCurrentIndex() == 0;
}
const std::string&
Transaction::getHash() const {
return hash_;
}
void
Transaction::setHash(const std::string& hash) {
hash_ = hash;
}
const std::string&
Transaction::getSignatureFragments() const {
return signatureFragments_;
}
void
Transaction::setSignatureFragments(const std::string& signatureFragments) {
signatureFragments_ = signatureFragments;
}
const std::string&
Transaction::getAddress() const {
return address_;
}
void
Transaction::setAddress(const std::string& address) {
address_ = address;
}
int64_t
Transaction::getValue() const {
return value_;
}
void
Transaction::setValue(int64_t value) {
value_ = value;
}
const std::string&
Transaction::getTag() const {
return tag_;
}
void
Transaction::setTag(const std::string& tag) {
tag_ = tag;
}
int64_t
Transaction::getTimestamp() const {
return timestamp_;
}
void
Transaction::setTimestamp(int64_t timestamp) {
timestamp_ = timestamp;
}
int64_t
Transaction::getCurrentIndex() const {
return currentIndex_;
}
void
Transaction::setCurrentIndex(int64_t currentIndex) {
currentIndex_ = currentIndex;
}
int64_t
Transaction::getLastIndex() const {
return lastIndex_;
}
void
Transaction::setLastIndex(int64_t lastIndex) {
lastIndex_ = lastIndex;
}
const std::string&
Transaction::getBundle() const {
return bundle_;
}
void
Transaction::setBundle(const std::string& bundle) {
bundle_ = bundle;
}
const std::string&
Transaction::getTrunkTransaction() const {
return trunkTransaction_;
}
void
Transaction::setTrunkTransaction(const std::string& trunkTransaction) {
trunkTransaction_ = trunkTransaction;
}
const std::string&
Transaction::getBranchTransaction() const {
return branchTransaction_;
}
void
Transaction::setBranchTransaction(const std::string& branchTransaction) {
branchTransaction_ = branchTransaction;
}
const std::string&
Transaction::getNonce() const {
return nonce_;
}
void
Transaction::setNonce(const std::string& nonce) {
nonce_ = nonce;
}
bool
Transaction::getPersistence() const {
return persistence_;
}
void
Transaction::setPersistence(bool persistence) {
persistence_ = persistence;
}
bool
Transaction::operator==(Transaction rhs) const {
return hash_ == rhs.getHash();
}
bool
Transaction::operator!=(Transaction rhs) const {
return !operator==(rhs);
}
std::string
Transaction::toTrytes() const {
auto value = IOTA::Types::tritsToTrytes(IOTA::Types::intToTrits(getValue(), SeedLength));
auto timestamp =
IOTA::Types::tritsToTrytes(IOTA::Types::intToTrits(getTimestamp(), TryteAlphabetLength));
auto currentIndex =
IOTA::Types::tritsToTrytes(IOTA::Types::intToTrits(getCurrentIndex(), TryteAlphabetLength));
auto lastIndex =
IOTA::Types::tritsToTrytes(IOTA::Types::intToTrits(getLastIndex(), TryteAlphabetLength));
return getSignatureFragments() + getAddress() + value + getTag() + timestamp + currentIndex +
lastIndex + getBundle() + getTrunkTransaction() + getBranchTransaction() + getNonce();
}
void
Transaction::initFromTrytes(const std::string& trytes) {
if (trytes.empty()) {
return;
}
//! TODO: length check
//! what length are we supposed to receive?
// validity check
for (int i = 2279; i < 2295; i++) {
if (trytes[i] != '9') {
return;
}
}
auto transactionTrits = IOTA::Types::trytesToTrits(trytes);
auto hash = IOTA::Types::Trits(TritHashLength);
// generate the correct transaction hash
auto curl = IOTA::Crypto::create(IOTA::Crypto::SpongeType::CURL);
curl->absorb(transactionTrits);
curl->squeeze(hash);
//! Hash
setHash(IOTA::Types::tritsToTrytes(hash));
//! Signature
setSignatureFragments(
trytes.substr(SignatureFragmentsOffset.first,
SignatureFragmentsOffset.second - SignatureFragmentsOffset.first));
//! Address
setAddress(trytes.substr(AddressOffset.first, AddressOffset.second - AddressOffset.first));
//! Value
setValue(IOTA::Types::tritsToInt<int64_t>(IOTA::Types::Trits(
std::vector<int8_t>{ std::begin(transactionTrits) + ValueOffset.first,
std::begin(transactionTrits) + ValueOffset.second })));
//! Tag
setTag(trytes.substr(TagOffset.first, TagOffset.second - TagOffset.first));
//! Timestamp
setTimestamp(IOTA::Types::tritsToInt<int64_t>(IOTA::Types::Trits(
std::vector<int8_t>{ std::begin(transactionTrits) + TimestampOffset.first,
std::begin(transactionTrits) + TimestampOffset.second })));
//! Current Index
setCurrentIndex(IOTA::Types::tritsToInt<int64_t>(IOTA::Types::Trits(
std::vector<int8_t>{ std::begin(transactionTrits) + CurrentIndexOffset.first,
std::begin(transactionTrits) + CurrentIndexOffset.second })));
//! Last Index
setLastIndex(IOTA::Types::tritsToInt<int64_t>(IOTA::Types::Trits(
std::vector<int8_t>{ std::begin(transactionTrits) + LastIndexOffset.first,
std::begin(transactionTrits) + LastIndexOffset.second })));
//! Bundle
setBundle(trytes.substr(BundleOffset.first, BundleOffset.second - BundleOffset.first));
//! Trunk Transaction
setTrunkTransaction(trytes.substr(TrunkOffset.first, TrunkOffset.second - TrunkOffset.first));
//! Branch Transaction
setBranchTransaction(trytes.substr(BranchOffset.first, BranchOffset.second - BranchOffset.first));
//! Nonce
setNonce(trytes.substr(NonceOffset.first, NonceOffset.second - NonceOffset.first));
}
} // namespace Models
} // namespace IOTA
<|endoftext|>
|
<commit_before>#include <iostream>
#include <map>
#include <Ice/Ice.h>
#include "server.h"
// TODO: remove this global variable
Ice::CommunicatorPtr ic;
class MetaServer : public Player::IMetaServer
{
public:
MetaServer();
virtual void add(const std::string& endpointStr, const Player::Song& s, const Ice::Current& c);
virtual void remove(const Player::MediaInfo& media, const Ice::Current& c);
virtual Player::MediaInfoSeq find(const std::string& s, const Ice::Current& c);
virtual Player::StreamToken setupStreaming(const Player::MediaInfo& media, const Ice::Current& c);
virtual void play(const Player::StreamToken& token, const Ice::Current& c);
virtual void stop(const Player::StreamToken& token, const Ice::Current& c);
private:
/* std::map<std::string, Player::IMusicServerPrx> serverList; */
std::map<std::string, std::string> serverList;
};
MetaServer::MetaServer()
{
serverList.emplace("MusicServer:default -h onche.ovh -p 10001", "onche.ovh");
}
void MetaServer::add(const std::string& endpointStr, const Player::Song& s, const Ice::Current& c)
{
std::cout << "Adding to " << endpointStr << " : " << s.artist << " - " << s.title << " - " << s.path << '\n';
Ice::ObjectPrx base = ic->stringToProxy(endpointStr);
Player::IMusicServerPrx srv = Player::IMusicServerPrx::checkedCast(base);
if (srv)
srv->add(s);
}
void MetaServer::remove(const Player::MediaInfo& media, const Ice::Current& c)
{
std::cout << "Removing on " << media.endpointStr << " : " << media.media.path << '\n';
Ice::ObjectPrx base = ic->stringToProxy(media.endpointStr);
Player::IMusicServerPrx srv = Player::IMusicServerPrx::checkedCast(base);
if (srv)
srv->remove(media.media.path);
}
Player::MediaInfoSeq MetaServer::find(const std::string& s, const Ice::Current& c)
{
std::cout << "Searching for: " << s << '\n';
Player::MediaInfoSeq medias;
for (const auto& it : serverList) {
Ice::ObjectPrx base = ic->stringToProxy(it.first);
Player::IMusicServerPrx srv = Player::IMusicServerPrx::checkedCast(base);
if (srv) {
auto results = srv->find(s);
for (const auto& r : results) {
Player::MediaInfo m;
m.endpointStr = it.first;
m.media = r;
medias.push_back(m);
}
}
}
return medias;
}
Player::StreamToken MetaServer::setupStreaming(const Player::MediaInfo& media, const Ice::Current& c)
{
std::cout << "Setup stream on " << media.endpointStr << ", " << media.media.path << '\n';
Player::StreamToken token;
Ice::ObjectPrx base = ic->stringToProxy(media.endpointStr);
Player::IMusicServerPrx srv = Player::IMusicServerPrx::checkedCast(base);
if (srv) {
Ice::IPConnectionInfo* ipConInfo = dynamic_cast<Ice::IPConnectionInfo*>(c.con->getInfo().get());
token = srv->setupStreaming(media.media.path, ipConInfo->remoteAddress, std::to_string(ipConInfo->remotePort));
token.endpointStr = media.endpointStr;
try {
token.streamingURL = "http://" + serverList.at(media.endpointStr) + ":8090" + '/' + token.streamingURL; // prepend http://hostname:8090
}
catch (const std::exception& e) {
return Player::StreamToken();
}
}
return token;
}
void MetaServer::play(const Player::StreamToken& token, const Ice::Current& c)
{
Ice::ObjectPrx base = ic->stringToProxy(token.endpointStr);
Player::IMusicServerPrx srv = Player::IMusicServerPrx::checkedCast(base);
if (srv)
srv->play(token);
}
void MetaServer::stop(const Player::StreamToken& token, const Ice::Current& c)
{
Ice::ObjectPrx base = ic->stringToProxy(token.endpointStr);
Player::IMusicServerPrx srv = Player::IMusicServerPrx::checkedCast(base);
if (srv)
srv->stop(token);
}
int main(int argc, char **argv)
{
int status = 0;
try {
ic = Ice::initialize(argc, argv);
Ice::ObjectAdapterPtr adapter = ic->createObjectAdapterWithEndpoints("MetaServerAdapter", "default -p 10000");
Ice::ObjectPtr object = new MetaServer;
adapter->add(object, ic->stringToIdentity("MetaServer"));
adapter->activate();
ic->waitForShutdown();
}
catch (const Ice::Exception& e) {
std::cerr << e << std::endl;
status = 1;
}
catch (const std::exception& e) {
std::cerr << e.what() << std::endl;
status = 1;
}
catch (...) {
status = 1;
}
if (ic) {
try {
ic->destroy();
}
catch (const Ice::Exception& e) {
std::cerr << e << std::endl;
status = 1;
}
}
return status;
}
<commit_msg>global ice communicator removed<commit_after>#include <iostream>
#include <map>
#include <Ice/Ice.h>
#include "server.h"
class MetaServer : public Player::IMetaServer
{
public:
MetaServer();
virtual void add(const std::string& endpointStr, const Player::Song& s, const Ice::Current& c);
virtual void remove(const Player::MediaInfo& media, const Ice::Current& c);
virtual Player::MediaInfoSeq find(const std::string& s, const Ice::Current& c);
virtual Player::StreamToken setupStreaming(const Player::MediaInfo& media, const Ice::Current& c);
virtual void play(const Player::StreamToken& token, const Ice::Current& c);
virtual void stop(const Player::StreamToken& token, const Ice::Current& c);
void setCommunicator(const Ice::CommunicatorPtr ic) { this->ic = ic; }
private:
Ice::CommunicatorPtr ic = nullptr;
/* std::map<std::string, Player::IMusicServerPrx> serverList; */
std::map<std::string, std::string> serverList;
};
MetaServer::MetaServer()
{
serverList.emplace("MusicServer:default -h onche.ovh -p 10001", "onche.ovh");
}
void MetaServer::add(const std::string& endpointStr, const Player::Song& s, const Ice::Current& c)
{
std::cout << "Adding to " << endpointStr << " : " << s.artist << " - " << s.title << " - " << s.path << '\n';
Ice::ObjectPrx base = ic->stringToProxy(endpointStr);
Player::IMusicServerPrx srv = Player::IMusicServerPrx::checkedCast(base);
if (srv)
srv->add(s);
}
void MetaServer::remove(const Player::MediaInfo& media, const Ice::Current& c)
{
std::cout << "Removing on " << media.endpointStr << " : " << media.media.path << '\n';
Ice::ObjectPrx base = ic->stringToProxy(media.endpointStr);
Player::IMusicServerPrx srv = Player::IMusicServerPrx::checkedCast(base);
if (srv)
srv->remove(media.media.path);
}
Player::MediaInfoSeq MetaServer::find(const std::string& s, const Ice::Current& c)
{
std::cout << "Searching for: " << s << '\n';
Player::MediaInfoSeq medias;
for (const auto& it : serverList) {
Ice::ObjectPrx base = ic->stringToProxy(it.first);
Player::IMusicServerPrx srv = Player::IMusicServerPrx::checkedCast(base);
if (srv) {
auto results = srv->find(s);
for (const auto& r : results) {
Player::MediaInfo m;
m.endpointStr = it.first;
m.media = r;
medias.push_back(m);
}
}
}
return medias;
}
Player::StreamToken MetaServer::setupStreaming(const Player::MediaInfo& media, const Ice::Current& c)
{
std::cout << "Setup stream on " << media.endpointStr << ", " << media.media.path << '\n';
Player::StreamToken token;
Ice::ObjectPrx base = ic->stringToProxy(media.endpointStr);
Player::IMusicServerPrx srv = Player::IMusicServerPrx::checkedCast(base);
if (srv) {
Ice::IPConnectionInfo* ipConInfo = dynamic_cast<Ice::IPConnectionInfo*>(c.con->getInfo().get());
token = srv->setupStreaming(media.media.path, ipConInfo->remoteAddress, std::to_string(ipConInfo->remotePort));
token.endpointStr = media.endpointStr;
try {
token.streamingURL = "http://" + serverList.at(media.endpointStr) + ":8090" + '/' + token.streamingURL; // prepend http://hostname:8090
}
catch (const std::exception& e) {
return Player::StreamToken();
}
}
return token;
}
void MetaServer::play(const Player::StreamToken& token, const Ice::Current& c)
{
Ice::ObjectPrx base = ic->stringToProxy(token.endpointStr);
Player::IMusicServerPrx srv = Player::IMusicServerPrx::checkedCast(base);
if (srv)
srv->play(token);
}
void MetaServer::stop(const Player::StreamToken& token, const Ice::Current& c)
{
Ice::ObjectPrx base = ic->stringToProxy(token.endpointStr);
Player::IMusicServerPrx srv = Player::IMusicServerPrx::checkedCast(base);
if (srv)
srv->stop(token);
}
int main(int argc, char **argv)
{
Ice::CommunicatorPtr ic;
int status = 0;
try {
ic = Ice::initialize(argc, argv);
Ice::ObjectAdapterPtr adapter = ic->createObjectAdapterWithEndpoints("MetaServerAdapter", "default -p 10000");
MetaServer* srv = new MetaServer;
srv->setCommunicator(ic);
Ice::ObjectPtr object = srv;
adapter->add(object, ic->stringToIdentity("MetaServer"));
adapter->activate();
ic->waitForShutdown();
}
catch (const Ice::Exception& e) {
std::cerr << e << std::endl;
status = 1;
}
catch (const std::exception& e) {
std::cerr << e.what() << std::endl;
status = 1;
}
catch (...) {
status = 1;
}
if (ic) {
try {
ic->destroy();
}
catch (const Ice::Exception& e) {
std::cerr << e << std::endl;
status = 1;
}
}
return status;
}
<|endoftext|>
|
<commit_before>// Copyright (c) 2012 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "chrome/renderer/extensions/miscellaneous_bindings.h"
#include <map>
#include <string>
#include "base/basictypes.h"
#include "base/lazy_instance.h"
#include "chrome/common/extensions/extension_messages.h"
#include "chrome/common/extensions/message_bundle.h"
#include "chrome/common/url_constants.h"
#include "chrome/renderer/extensions/chrome_v8_context.h"
#include "chrome/renderer/extensions/chrome_v8_context_set.h"
#include "chrome/renderer/extensions/chrome_v8_extension.h"
#include "chrome/renderer/extensions/dispatcher.h"
#include "chrome/renderer/extensions/event_bindings.h"
#include "content/public/renderer/render_thread.h"
#include "content/public/renderer/render_view.h"
#include "grit/renderer_resources.h"
#include "third_party/WebKit/Source/WebKit/chromium/public/WebScopedMicrotaskSuppression.h"
#include "v8/include/v8.h"
// Message passing API example (in a content script):
// var extension =
// new chrome.Extension('00123456789abcdef0123456789abcdef0123456');
// var port = extension.connect();
// port.postMessage('Can you hear me now?');
// port.onmessage.addListener(function(msg, port) {
// alert('response=' + msg);
// port.postMessage('I got your reponse');
// });
using content::RenderThread;
namespace {
struct ExtensionData {
struct PortData {
int ref_count; // how many contexts have a handle to this port
PortData() : ref_count(0) {}
};
std::map<int, PortData> ports; // port ID -> data
};
static base::LazyInstance<ExtensionData> g_extension_data =
LAZY_INSTANCE_INITIALIZER;
static bool HasPortData(int port_id) {
return g_extension_data.Get().ports.find(port_id) !=
g_extension_data.Get().ports.end();
}
static ExtensionData::PortData& GetPortData(int port_id) {
return g_extension_data.Get().ports[port_id];
}
static void ClearPortData(int port_id) {
g_extension_data.Get().ports.erase(port_id);
}
const char kPortClosedError[] = "Attempting to use a disconnected port object";
class ExtensionImpl : public extensions::ChromeV8Extension {
public:
explicit ExtensionImpl(extensions::Dispatcher* dispatcher)
: extensions::ChromeV8Extension(dispatcher) {
RouteStaticFunction("CloseChannel", &CloseChannel);
RouteStaticFunction("PortAddRef", &PortAddRef);
RouteStaticFunction("PortRelease", &PortRelease);
RouteStaticFunction("PostMessage", &PostMessage);
RouteStaticFunction("BindToGC", &BindToGC);
}
~ExtensionImpl() {}
// Sends a message along the given channel.
static v8::Handle<v8::Value> PostMessage(const v8::Arguments& args) {
content::RenderView* renderview = GetCurrentRenderView();
if (!renderview)
return v8::Undefined();
if (args.Length() >= 2 && args[0]->IsInt32() && args[1]->IsString()) {
int port_id = args[0]->Int32Value();
if (!HasPortData(port_id)) {
return v8::ThrowException(v8::Exception::Error(
v8::String::New(kPortClosedError)));
}
std::string message = *v8::String::Utf8Value(args[1]->ToString());
renderview->Send(new ExtensionHostMsg_PostMessage(
renderview->GetRoutingID(), port_id, message));
}
return v8::Undefined();
}
// Forcefully disconnects a port.
static v8::Handle<v8::Value> CloseChannel(const v8::Arguments& args) {
if (args.Length() >= 2 && args[0]->IsInt32() && args[1]->IsBoolean()) {
int port_id = args[0]->Int32Value();
if (!HasPortData(port_id)) {
return v8::Undefined();
}
// Send via the RenderThread because the RenderView might be closing.
bool notify_browser = args[1]->BooleanValue();
if (notify_browser)
content::RenderThread::Get()->Send(
new ExtensionHostMsg_CloseChannel(port_id, false));
ClearPortData(port_id);
}
return v8::Undefined();
}
// A new port has been created for a context. This occurs both when script
// opens a connection, and when a connection is opened to this script.
static v8::Handle<v8::Value> PortAddRef(const v8::Arguments& args) {
if (args.Length() >= 1 && args[0]->IsInt32()) {
int port_id = args[0]->Int32Value();
++GetPortData(port_id).ref_count;
}
return v8::Undefined();
}
// The frame a port lived in has been destroyed. When there are no more
// frames with a reference to a given port, we will disconnect it and notify
// the other end of the channel.
static v8::Handle<v8::Value> PortRelease(const v8::Arguments& args) {
if (args.Length() >= 1 && args[0]->IsInt32()) {
int port_id = args[0]->Int32Value();
if (HasPortData(port_id) && --GetPortData(port_id).ref_count == 0) {
// Send via the RenderThread because the RenderView might be closing.
content::RenderThread::Get()->Send(
new ExtensionHostMsg_CloseChannel(port_id, false));
ClearPortData(port_id);
}
}
return v8::Undefined();
}
struct GCCallbackArgs {
v8::Persistent<v8::Object> object;
v8::Persistent<v8::Function> callback;
};
static void GCCallback(v8::Persistent<v8::Value> object, void* parameter) {
v8::HandleScope handle_scope;
GCCallbackArgs* args = reinterpret_cast<GCCallbackArgs*>(parameter);
WebKit::WebScopedMicrotaskSuppression suppression;
args->callback->Call(args->callback->CreationContext()->Global(), 0, NULL);
args->callback.Dispose();
args->object.Dispose();
delete args;
}
// Binds a callback to be invoked when the given object is garbage collected.
static v8::Handle<v8::Value> BindToGC(const v8::Arguments& args) {
if (args.Length() == 2 && args[0]->IsObject() && args[1]->IsFunction()) {
GCCallbackArgs* context = new GCCallbackArgs;
context->callback = v8::Persistent<v8::Function>::New(
v8::Handle<v8::Function>::Cast(args[1]));
context->object = v8::Persistent<v8::Object>::New(
v8::Handle<v8::Object>::Cast(args[0]));
context->object.MakeWeak(context, GCCallback);
} else {
NOTREACHED();
}
return v8::Undefined();
}
};
} // namespace
namespace extensions {
ChromeV8Extension* MiscellaneousBindings::Get(Dispatcher* dispatcher) {
return new ExtensionImpl(dispatcher);
}
// static
void MiscellaneousBindings::DispatchOnConnect(
const ChromeV8ContextSet::ContextSet& contexts,
int target_port_id,
const std::string& channel_name,
const std::string& tab_json,
const std::string& source_extension_id,
const std::string& target_extension_id,
content::RenderView* restrict_to_render_view) {
v8::HandleScope handle_scope;
bool port_created = false;
for (ChromeV8ContextSet::ContextSet::const_iterator it = contexts.begin();
it != contexts.end(); ++it) {
if (restrict_to_render_view &&
restrict_to_render_view != (*it)->GetRenderView()) {
continue;
}
std::vector<v8::Handle<v8::Value> > arguments;
arguments.push_back(v8::Integer::New(target_port_id));
arguments.push_back(v8::String::New(channel_name.c_str(),
channel_name.size()));
arguments.push_back(v8::String::New(tab_json.c_str(),
tab_json.size()));
arguments.push_back(v8::String::New(source_extension_id.c_str(),
source_extension_id.size()));
arguments.push_back(v8::String::New(target_extension_id.c_str(),
target_extension_id.size()));
v8::Handle<v8::Value> retval;
v8::TryCatch try_catch;
if (!(*it)->CallChromeHiddenMethod("Port.dispatchOnConnect",
arguments.size(), &arguments[0],
&retval)) {
continue;
}
if (try_catch.HasCaught()) {
LOG(ERROR) << "Exception caught when calling Port.dispatchOnConnect.";
continue;
}
CHECK(!retval.IsEmpty());
CHECK(retval->IsBoolean());
if (retval->BooleanValue())
port_created = true;
}
// If we didn't create a port, notify the other end of the channel (treat it
// as a disconnect).
if (!port_created) {
content::RenderThread::Get()->Send(
new ExtensionHostMsg_CloseChannel(target_port_id, true));
}
}
// static
void MiscellaneousBindings::DeliverMessage(
const ChromeV8ContextSet::ContextSet& contexts,
int target_port_id,
const std::string& message,
content::RenderView* restrict_to_render_view) {
v8::HandleScope handle_scope;
for (ChromeV8ContextSet::ContextSet::const_iterator it = contexts.begin();
it != contexts.end(); ++it) {
if (restrict_to_render_view &&
restrict_to_render_view != (*it)->GetRenderView()) {
continue;
}
// Check to see whether the context has this port before bothering to create
// the message.
v8::Handle<v8::Value> port_id_handle = v8::Integer::New(target_port_id);
v8::Handle<v8::Value> has_port;
v8::TryCatch try_catch;
if (!(*it)->CallChromeHiddenMethod("Port.hasPort", 1, &port_id_handle,
&has_port)) {
continue;
}
if (try_catch.HasCaught()) {
LOG(ERROR) << "Exception caught when calling Port.hasPort.";
continue;
}
CHECK(!has_port.IsEmpty());
if (!has_port->BooleanValue())
continue;
std::vector<v8::Handle<v8::Value> > arguments;
arguments.push_back(v8::String::New(message.c_str(), message.size()));
arguments.push_back(port_id_handle);
CHECK((*it)->CallChromeHiddenMethod("Port.dispatchOnMessage",
arguments.size(),
&arguments[0],
NULL));
}
}
// static
void MiscellaneousBindings::DispatchOnDisconnect(
const ChromeV8ContextSet::ContextSet& contexts,
int port_id,
bool connection_error,
content::RenderView* restrict_to_render_view) {
v8::HandleScope handle_scope;
for (ChromeV8ContextSet::ContextSet::const_iterator it = contexts.begin();
it != contexts.end(); ++it) {
if (restrict_to_render_view &&
restrict_to_render_view != (*it)->GetRenderView()) {
continue;
}
std::vector<v8::Handle<v8::Value> > arguments;
arguments.push_back(v8::Integer::New(port_id));
arguments.push_back(v8::Boolean::New(connection_error));
(*it)->CallChromeHiddenMethod("Port.dispatchOnDisconnect",
arguments.size(), &arguments[0],
NULL);
}
}
} // namespace extensions
<commit_msg>Change a CHECK in MiscellaneousBindings::DispatchOnConnect to a non-fatal warning.<commit_after>// Copyright (c) 2012 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "chrome/renderer/extensions/miscellaneous_bindings.h"
#include <map>
#include <string>
#include "base/basictypes.h"
#include "base/lazy_instance.h"
#include "chrome/common/extensions/extension_messages.h"
#include "chrome/common/extensions/message_bundle.h"
#include "chrome/common/url_constants.h"
#include "chrome/renderer/extensions/chrome_v8_context.h"
#include "chrome/renderer/extensions/chrome_v8_context_set.h"
#include "chrome/renderer/extensions/chrome_v8_extension.h"
#include "chrome/renderer/extensions/dispatcher.h"
#include "chrome/renderer/extensions/event_bindings.h"
#include "content/public/renderer/render_thread.h"
#include "content/public/renderer/render_view.h"
#include "grit/renderer_resources.h"
#include "third_party/WebKit/Source/WebKit/chromium/public/WebScopedMicrotaskSuppression.h"
#include "v8/include/v8.h"
// Message passing API example (in a content script):
// var extension =
// new chrome.Extension('00123456789abcdef0123456789abcdef0123456');
// var port = extension.connect();
// port.postMessage('Can you hear me now?');
// port.onmessage.addListener(function(msg, port) {
// alert('response=' + msg);
// port.postMessage('I got your reponse');
// });
using content::RenderThread;
namespace {
struct ExtensionData {
struct PortData {
int ref_count; // how many contexts have a handle to this port
PortData() : ref_count(0) {}
};
std::map<int, PortData> ports; // port ID -> data
};
static base::LazyInstance<ExtensionData> g_extension_data =
LAZY_INSTANCE_INITIALIZER;
static bool HasPortData(int port_id) {
return g_extension_data.Get().ports.find(port_id) !=
g_extension_data.Get().ports.end();
}
static ExtensionData::PortData& GetPortData(int port_id) {
return g_extension_data.Get().ports[port_id];
}
static void ClearPortData(int port_id) {
g_extension_data.Get().ports.erase(port_id);
}
const char kPortClosedError[] = "Attempting to use a disconnected port object";
class ExtensionImpl : public extensions::ChromeV8Extension {
public:
explicit ExtensionImpl(extensions::Dispatcher* dispatcher)
: extensions::ChromeV8Extension(dispatcher) {
RouteStaticFunction("CloseChannel", &CloseChannel);
RouteStaticFunction("PortAddRef", &PortAddRef);
RouteStaticFunction("PortRelease", &PortRelease);
RouteStaticFunction("PostMessage", &PostMessage);
RouteStaticFunction("BindToGC", &BindToGC);
}
~ExtensionImpl() {}
// Sends a message along the given channel.
static v8::Handle<v8::Value> PostMessage(const v8::Arguments& args) {
content::RenderView* renderview = GetCurrentRenderView();
if (!renderview)
return v8::Undefined();
if (args.Length() >= 2 && args[0]->IsInt32() && args[1]->IsString()) {
int port_id = args[0]->Int32Value();
if (!HasPortData(port_id)) {
return v8::ThrowException(v8::Exception::Error(
v8::String::New(kPortClosedError)));
}
std::string message = *v8::String::Utf8Value(args[1]->ToString());
renderview->Send(new ExtensionHostMsg_PostMessage(
renderview->GetRoutingID(), port_id, message));
}
return v8::Undefined();
}
// Forcefully disconnects a port.
static v8::Handle<v8::Value> CloseChannel(const v8::Arguments& args) {
if (args.Length() >= 2 && args[0]->IsInt32() && args[1]->IsBoolean()) {
int port_id = args[0]->Int32Value();
if (!HasPortData(port_id)) {
return v8::Undefined();
}
// Send via the RenderThread because the RenderView might be closing.
bool notify_browser = args[1]->BooleanValue();
if (notify_browser)
content::RenderThread::Get()->Send(
new ExtensionHostMsg_CloseChannel(port_id, false));
ClearPortData(port_id);
}
return v8::Undefined();
}
// A new port has been created for a context. This occurs both when script
// opens a connection, and when a connection is opened to this script.
static v8::Handle<v8::Value> PortAddRef(const v8::Arguments& args) {
if (args.Length() >= 1 && args[0]->IsInt32()) {
int port_id = args[0]->Int32Value();
++GetPortData(port_id).ref_count;
}
return v8::Undefined();
}
// The frame a port lived in has been destroyed. When there are no more
// frames with a reference to a given port, we will disconnect it and notify
// the other end of the channel.
static v8::Handle<v8::Value> PortRelease(const v8::Arguments& args) {
if (args.Length() >= 1 && args[0]->IsInt32()) {
int port_id = args[0]->Int32Value();
if (HasPortData(port_id) && --GetPortData(port_id).ref_count == 0) {
// Send via the RenderThread because the RenderView might be closing.
content::RenderThread::Get()->Send(
new ExtensionHostMsg_CloseChannel(port_id, false));
ClearPortData(port_id);
}
}
return v8::Undefined();
}
struct GCCallbackArgs {
v8::Persistent<v8::Object> object;
v8::Persistent<v8::Function> callback;
};
static void GCCallback(v8::Persistent<v8::Value> object, void* parameter) {
v8::HandleScope handle_scope;
GCCallbackArgs* args = reinterpret_cast<GCCallbackArgs*>(parameter);
WebKit::WebScopedMicrotaskSuppression suppression;
args->callback->Call(args->callback->CreationContext()->Global(), 0, NULL);
args->callback.Dispose();
args->object.Dispose();
delete args;
}
// Binds a callback to be invoked when the given object is garbage collected.
static v8::Handle<v8::Value> BindToGC(const v8::Arguments& args) {
if (args.Length() == 2 && args[0]->IsObject() && args[1]->IsFunction()) {
GCCallbackArgs* context = new GCCallbackArgs;
context->callback = v8::Persistent<v8::Function>::New(
v8::Handle<v8::Function>::Cast(args[1]));
context->object = v8::Persistent<v8::Object>::New(
v8::Handle<v8::Object>::Cast(args[0]));
context->object.MakeWeak(context, GCCallback);
} else {
NOTREACHED();
}
return v8::Undefined();
}
};
} // namespace
namespace extensions {
ChromeV8Extension* MiscellaneousBindings::Get(Dispatcher* dispatcher) {
return new ExtensionImpl(dispatcher);
}
// static
void MiscellaneousBindings::DispatchOnConnect(
const ChromeV8ContextSet::ContextSet& contexts,
int target_port_id,
const std::string& channel_name,
const std::string& tab_json,
const std::string& source_extension_id,
const std::string& target_extension_id,
content::RenderView* restrict_to_render_view) {
v8::HandleScope handle_scope;
bool port_created = false;
for (ChromeV8ContextSet::ContextSet::const_iterator it = contexts.begin();
it != contexts.end(); ++it) {
if (restrict_to_render_view &&
restrict_to_render_view != (*it)->GetRenderView()) {
continue;
}
std::vector<v8::Handle<v8::Value> > arguments;
arguments.push_back(v8::Integer::New(target_port_id));
arguments.push_back(v8::String::New(channel_name.c_str(),
channel_name.size()));
arguments.push_back(v8::String::New(tab_json.c_str(),
tab_json.size()));
arguments.push_back(v8::String::New(source_extension_id.c_str(),
source_extension_id.size()));
arguments.push_back(v8::String::New(target_extension_id.c_str(),
target_extension_id.size()));
v8::Handle<v8::Value> retval;
v8::TryCatch try_catch;
if (!(*it)->CallChromeHiddenMethod("Port.dispatchOnConnect",
arguments.size(), &arguments[0],
&retval)) {
continue;
}
if (try_catch.HasCaught()) {
LOG(ERROR) << "Exception caught when calling Port.dispatchOnConnect.";
continue;
}
if (retval.IsEmpty()) {
LOG(ERROR) << "Empty return value from Port.dispatchOnConnect.";
continue;
}
CHECK(retval->IsBoolean());
if (retval->BooleanValue())
port_created = true;
}
// If we didn't create a port, notify the other end of the channel (treat it
// as a disconnect).
if (!port_created) {
content::RenderThread::Get()->Send(
new ExtensionHostMsg_CloseChannel(target_port_id, true));
}
}
// static
void MiscellaneousBindings::DeliverMessage(
const ChromeV8ContextSet::ContextSet& contexts,
int target_port_id,
const std::string& message,
content::RenderView* restrict_to_render_view) {
v8::HandleScope handle_scope;
for (ChromeV8ContextSet::ContextSet::const_iterator it = contexts.begin();
it != contexts.end(); ++it) {
if (restrict_to_render_view &&
restrict_to_render_view != (*it)->GetRenderView()) {
continue;
}
// Check to see whether the context has this port before bothering to create
// the message.
v8::Handle<v8::Value> port_id_handle = v8::Integer::New(target_port_id);
v8::Handle<v8::Value> has_port;
v8::TryCatch try_catch;
if (!(*it)->CallChromeHiddenMethod("Port.hasPort", 1, &port_id_handle,
&has_port)) {
continue;
}
if (try_catch.HasCaught()) {
LOG(ERROR) << "Exception caught when calling Port.hasPort.";
continue;
}
CHECK(!has_port.IsEmpty());
if (!has_port->BooleanValue())
continue;
std::vector<v8::Handle<v8::Value> > arguments;
arguments.push_back(v8::String::New(message.c_str(), message.size()));
arguments.push_back(port_id_handle);
CHECK((*it)->CallChromeHiddenMethod("Port.dispatchOnMessage",
arguments.size(),
&arguments[0],
NULL));
}
}
// static
void MiscellaneousBindings::DispatchOnDisconnect(
const ChromeV8ContextSet::ContextSet& contexts,
int port_id,
bool connection_error,
content::RenderView* restrict_to_render_view) {
v8::HandleScope handle_scope;
for (ChromeV8ContextSet::ContextSet::const_iterator it = contexts.begin();
it != contexts.end(); ++it) {
if (restrict_to_render_view &&
restrict_to_render_view != (*it)->GetRenderView()) {
continue;
}
std::vector<v8::Handle<v8::Value> > arguments;
arguments.push_back(v8::Integer::New(port_id));
arguments.push_back(v8::Boolean::New(connection_error));
(*it)->CallChromeHiddenMethod("Port.dispatchOnDisconnect",
arguments.size(), &arguments[0],
NULL);
}
}
} // namespace extensions
<|endoftext|>
|
<commit_before>// Copyright (c) 2011 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "base/file_util.h"
#include "chrome/renderer/print_web_view_helper.h"
#include "chrome/test/render_view_test.h"
#include "printing/image.h"
#include "testing/gtest/include/gtest/gtest.h"
#include "third_party/WebKit/Source/WebKit/chromium/public/WebFrame.h"
#include "third_party/WebKit/Source/WebKit/chromium/public/WebString.h"
#include "third_party/WebKit/Source/WebKit/chromium/public/WebView.h"
using WebKit::WebFrame;
using WebKit::WebString;
using WebKit::WebView;
namespace {
const char kPrintWithJSHTML[] =
"<body>Hello<script>window.print()</script>World</body>";
} // namespace
// Tests that printing pages work and sending and receiving messages through
// that channel all works.
TEST_F(RenderViewTest, OnPrintPages) {
// Lets simulate a print pages with Hello world.
LoadHTML("<body><p>Hello World!</p></body>");
PrintWebViewHelper::Get(view_)->OnPrintPages();
VerifyPageCount(1);
VerifyPagesPrinted(true);
}
// Duplicate of OnPrintPagesTest only using javascript to print.
TEST_F(RenderViewTest, PrintWithJavascript) {
// HTML contains a call to window.print()
LoadHTML(kPrintWithJSHTML);
VerifyPageCount(1);
VerifyPagesPrinted(true);
}
// Tests that the renderer blocks window.print() calls if they occur too
// frequently.
TEST_F(RenderViewTest, BlockScriptInitiatedPrinting) {
// Pretend user will cancel printing.
render_thread_.set_print_dialog_user_response(false);
// Try to print with window.print() a few times.
LoadHTML(kPrintWithJSHTML);
LoadHTML(kPrintWithJSHTML);
LoadHTML(kPrintWithJSHTML);
VerifyPagesPrinted(false);
// Pretend user will print. (but printing is blocked.)
render_thread_.set_print_dialog_user_response(true);
LoadHTML(kPrintWithJSHTML);
VerifyPagesPrinted(false);
// Unblock script initiated printing and verify printing works.
PrintWebViewHelper::Get(view_)->ResetScriptedPrintCount();
render_thread_.printer()->ResetPrinter();
LoadHTML(kPrintWithJSHTML);
VerifyPageCount(1);
VerifyPagesPrinted(true);
}
#if defined(OS_WIN) || defined(OS_MACOSX)
// TODO(estade): I don't think this test is worth porting to Linux. We will have
// to rip out and replace most of the IPC code if we ever plan to improve
// printing, and the comment below by sverrir suggests that it doesn't do much
// for us anyway.
TEST_F(RenderViewTest, PrintWithIframe) {
// Document that populates an iframe.
const char html[] =
"<html><body>Lorem Ipsum:"
"<iframe name=\"sub1\" id=\"sub1\"></iframe><script>"
" document.write(frames['sub1'].name);"
" frames['sub1'].document.write("
" '<p>Cras tempus ante eu felis semper luctus!</p>');"
"</script></body></html>";
LoadHTML(html);
// Find the frame and set it as the focused one. This should mean that that
// the printout should only contain the contents of that frame.
WebFrame* sub1_frame =
view_->webview()->findFrameByName(WebString::fromUTF8("sub1"));
ASSERT_TRUE(sub1_frame);
view_->webview()->setFocusedFrame(sub1_frame);
ASSERT_NE(view_->webview()->focusedFrame(),
view_->webview()->mainFrame());
// Initiate printing.
PrintWebViewHelper::Get(view_)->OnPrintPages();
// Verify output through MockPrinter.
const MockPrinter* printer(render_thread_.printer());
ASSERT_EQ(1, printer->GetPrintedPages());
const printing::Image& image1(printer->GetPrintedPage(0)->image());
// TODO(sverrir): Figure out a way to improve this test to actually print
// only the content of the iframe. Currently image1 will contain the full
// page.
EXPECT_NE(0, image1.size().width());
EXPECT_NE(0, image1.size().height());
}
#endif
// Tests if we can print a page and verify its results.
// This test prints HTML pages into a pseudo printer and check their outputs,
// i.e. a simplified version of the PrintingLayoutTextTest UI test.
namespace {
// Test cases used in this test.
struct TestPageData {
const char* page;
size_t printed_pages;
int width;
int height;
const char* checksum;
const wchar_t* file;
};
const TestPageData kTestPages[] = {
{"<html>"
"<head>"
"<meta"
" http-equiv=\"Content-Type\""
" content=\"text/html; charset=utf-8\"/>"
"<title>Test 1</title>"
"</head>"
"<body style=\"background-color: white;\">"
"<p style=\"font-family: arial;\">Hello World!</p>"
"</body>",
#if defined(OS_MACOSX)
// Mac printing code compensates for the WebKit scale factor while generating
// the metafile, so we expect smaller pages.
1, 540, 720,
#else
1, 675, 900,
#endif
NULL,
NULL,
},
};
} // namespace
// TODO(estade): need to port MockPrinter to get this on Linux. This involves
// hooking up Cairo to read a pdf stream, or accessing the cairo surface in the
// metafile directly.
#if defined(OS_WIN) || defined(OS_MACOSX)
TEST_F(RenderViewTest, PrintLayoutTest) {
bool baseline = false;
EXPECT_TRUE(render_thread_.printer() != NULL);
for (size_t i = 0; i < arraysize(kTestPages); ++i) {
// Load an HTML page and print it.
LoadHTML(kTestPages[i].page);
PrintWebViewHelper::Get(view_)->OnPrintPages();
// MockRenderThread::Send() just calls MockRenderThread::OnMsgReceived().
// So, all IPC messages sent in the above RenderView::OnPrintPages() call
// has been handled by the MockPrinter object, i.e. this printing job
// has been already finished.
// So, we can start checking the output pages of this printing job.
// Retrieve the number of pages actually printed.
size_t pages = render_thread_.printer()->GetPrintedPages();
EXPECT_EQ(kTestPages[i].printed_pages, pages);
// Retrieve the width and height of the output page.
int width = render_thread_.printer()->GetWidth(0);
int height = render_thread_.printer()->GetHeight(0);
// Check with margin for error. This has been failing with a one pixel
// offset on our buildbot.
const int kErrorMargin = 5; // 5%
EXPECT_GT(kTestPages[i].width * (100 + kErrorMargin) / 100, width);
EXPECT_LT(kTestPages[i].width * (100 - kErrorMargin) / 100, width);
EXPECT_GT(kTestPages[i].height * (100 + kErrorMargin) / 100, height);
EXPECT_LT(kTestPages[i].height* (100 - kErrorMargin) / 100, height);
// Retrieve the checksum of the bitmap data from the pseudo printer and
// compare it with the expected result.
std::string bitmap_actual;
EXPECT_TRUE(render_thread_.printer()->GetBitmapChecksum(0, &bitmap_actual));
if (kTestPages[i].checksum)
EXPECT_EQ(kTestPages[i].checksum, bitmap_actual);
if (baseline) {
// Save the source data and the bitmap data into temporary files to
// create base-line results.
FilePath source_path;
file_util::CreateTemporaryFile(&source_path);
render_thread_.printer()->SaveSource(0, source_path);
FilePath bitmap_path;
file_util::CreateTemporaryFile(&bitmap_path);
render_thread_.printer()->SaveBitmap(0, bitmap_path);
}
}
}
#endif<commit_msg>Really fix build break<commit_after>// Copyright (c) 2011 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "base/file_util.h"
#include "chrome/renderer/print_web_view_helper.h"
#include "chrome/test/render_view_test.h"
#include "printing/image.h"
#include "testing/gtest/include/gtest/gtest.h"
#include "third_party/WebKit/Source/WebKit/chromium/public/WebFrame.h"
#include "third_party/WebKit/Source/WebKit/chromium/public/WebString.h"
#include "third_party/WebKit/Source/WebKit/chromium/public/WebView.h"
using WebKit::WebFrame;
using WebKit::WebString;
using WebKit::WebView;
namespace {
const char kPrintWithJSHTML[] =
"<body>Hello<script>window.print()</script>World</body>";
} // namespace
// Tests that printing pages work and sending and receiving messages through
// that channel all works.
TEST_F(RenderViewTest, OnPrintPages) {
// Lets simulate a print pages with Hello world.
LoadHTML("<body><p>Hello World!</p></body>");
PrintWebViewHelper::Get(view_)->OnPrintPages();
VerifyPageCount(1);
VerifyPagesPrinted(true);
}
// Duplicate of OnPrintPagesTest only using javascript to print.
TEST_F(RenderViewTest, PrintWithJavascript) {
// HTML contains a call to window.print()
LoadHTML(kPrintWithJSHTML);
VerifyPageCount(1);
VerifyPagesPrinted(true);
}
// Tests that the renderer blocks window.print() calls if they occur too
// frequently.
TEST_F(RenderViewTest, BlockScriptInitiatedPrinting) {
// Pretend user will cancel printing.
render_thread_.set_print_dialog_user_response(false);
// Try to print with window.print() a few times.
LoadHTML(kPrintWithJSHTML);
LoadHTML(kPrintWithJSHTML);
LoadHTML(kPrintWithJSHTML);
VerifyPagesPrinted(false);
// Pretend user will print. (but printing is blocked.)
render_thread_.set_print_dialog_user_response(true);
LoadHTML(kPrintWithJSHTML);
VerifyPagesPrinted(false);
// Unblock script initiated printing and verify printing works.
PrintWebViewHelper::Get(view_)->ResetScriptedPrintCount();
render_thread_.printer()->ResetPrinter();
LoadHTML(kPrintWithJSHTML);
VerifyPageCount(1);
VerifyPagesPrinted(true);
}
#if defined(OS_WIN) || defined(OS_MACOSX)
// TODO(estade): I don't think this test is worth porting to Linux. We will have
// to rip out and replace most of the IPC code if we ever plan to improve
// printing, and the comment below by sverrir suggests that it doesn't do much
// for us anyway.
TEST_F(RenderViewTest, PrintWithIframe) {
// Document that populates an iframe.
const char html[] =
"<html><body>Lorem Ipsum:"
"<iframe name=\"sub1\" id=\"sub1\"></iframe><script>"
" document.write(frames['sub1'].name);"
" frames['sub1'].document.write("
" '<p>Cras tempus ante eu felis semper luctus!</p>');"
"</script></body></html>";
LoadHTML(html);
// Find the frame and set it as the focused one. This should mean that that
// the printout should only contain the contents of that frame.
WebFrame* sub1_frame =
view_->webview()->findFrameByName(WebString::fromUTF8("sub1"));
ASSERT_TRUE(sub1_frame);
view_->webview()->setFocusedFrame(sub1_frame);
ASSERT_NE(view_->webview()->focusedFrame(),
view_->webview()->mainFrame());
// Initiate printing.
PrintWebViewHelper::Get(view_)->OnPrintPages();
// Verify output through MockPrinter.
const MockPrinter* printer(render_thread_.printer());
ASSERT_EQ(1, printer->GetPrintedPages());
const printing::Image& image1(printer->GetPrintedPage(0)->image());
// TODO(sverrir): Figure out a way to improve this test to actually print
// only the content of the iframe. Currently image1 will contain the full
// page.
EXPECT_NE(0, image1.size().width());
EXPECT_NE(0, image1.size().height());
}
#endif
// Tests if we can print a page and verify its results.
// This test prints HTML pages into a pseudo printer and check their outputs,
// i.e. a simplified version of the PrintingLayoutTextTest UI test.
namespace {
// Test cases used in this test.
struct TestPageData {
const char* page;
size_t printed_pages;
int width;
int height;
const char* checksum;
const wchar_t* file;
};
const TestPageData kTestPages[] = {
{"<html>"
"<head>"
"<meta"
" http-equiv=\"Content-Type\""
" content=\"text/html; charset=utf-8\"/>"
"<title>Test 1</title>"
"</head>"
"<body style=\"background-color: white;\">"
"<p style=\"font-family: arial;\">Hello World!</p>"
"</body>",
#if defined(OS_MACOSX)
// Mac printing code compensates for the WebKit scale factor while generating
// the metafile, so we expect smaller pages.
1, 540, 720,
#else
1, 675, 900,
#endif
NULL,
NULL,
},
};
} // namespace
// TODO(estade): need to port MockPrinter to get this on Linux. This involves
// hooking up Cairo to read a pdf stream, or accessing the cairo surface in the
// metafile directly.
#if defined(OS_WIN) || defined(OS_MACOSX)
TEST_F(RenderViewTest, PrintLayoutTest) {
bool baseline = false;
EXPECT_TRUE(render_thread_.printer() != NULL);
for (size_t i = 0; i < arraysize(kTestPages); ++i) {
// Load an HTML page and print it.
LoadHTML(kTestPages[i].page);
PrintWebViewHelper::Get(view_)->OnPrintPages();
// MockRenderThread::Send() just calls MockRenderThread::OnMsgReceived().
// So, all IPC messages sent in the above RenderView::OnPrintPages() call
// has been handled by the MockPrinter object, i.e. this printing job
// has been already finished.
// So, we can start checking the output pages of this printing job.
// Retrieve the number of pages actually printed.
size_t pages = render_thread_.printer()->GetPrintedPages();
EXPECT_EQ(kTestPages[i].printed_pages, pages);
// Retrieve the width and height of the output page.
int width = render_thread_.printer()->GetWidth(0);
int height = render_thread_.printer()->GetHeight(0);
// Check with margin for error. This has been failing with a one pixel
// offset on our buildbot.
const int kErrorMargin = 5; // 5%
EXPECT_GT(kTestPages[i].width * (100 + kErrorMargin) / 100, width);
EXPECT_LT(kTestPages[i].width * (100 - kErrorMargin) / 100, width);
EXPECT_GT(kTestPages[i].height * (100 + kErrorMargin) / 100, height);
EXPECT_LT(kTestPages[i].height* (100 - kErrorMargin) / 100, height);
// Retrieve the checksum of the bitmap data from the pseudo printer and
// compare it with the expected result.
std::string bitmap_actual;
EXPECT_TRUE(render_thread_.printer()->GetBitmapChecksum(0, &bitmap_actual));
if (kTestPages[i].checksum)
EXPECT_EQ(kTestPages[i].checksum, bitmap_actual);
if (baseline) {
// Save the source data and the bitmap data into temporary files to
// create base-line results.
FilePath source_path;
file_util::CreateTemporaryFile(&source_path);
render_thread_.printer()->SaveSource(0, source_path);
FilePath bitmap_path;
file_util::CreateTemporaryFile(&bitmap_path);
render_thread_.printer()->SaveBitmap(0, bitmap_path);
}
}
}
#endif
<|endoftext|>
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.