text stringlengths 54 60.6k |
|---|
<commit_before>/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: t; c-basic-offset: 4 -*- */
/* libwps
* Copyright (C) 2009, 2011 Alonso Laurent (alonso@loria.fr)
* Copyright (C) 2006, 2007 Andrew Ziem
* Copyright (C) 2004-2006 Fridrich Strba (fridrich.strba@bluewin.ch)
* Copyright (C) 2004 Marc Maurer (uwog@uwog.net)
* Copyright (C) 2003-2005 William Lachance (william.lachance@sympatico.ca)
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Library General Public
* License as published by the Free Software Foundation; either
* version 2 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Library General Public License for more details.
*
* You should have received a copy of the GNU Library General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA
*
* For further information visit http://libwps.sourceforge.net
*/
/* "This product is not manufactured, approved, or supported by
* Corel Corporation or Corel Corporation Limited."
*/
#include <iomanip>
#include <sstream>
#include <libwpd/WPXBinaryData.h>
#include <libwpd-stream/WPXStream.h>
#include "WPSDebug.h"
#if defined(DEBUG_WITH_FILES)
namespace libwps
{
bool DebugFile::open(std::string const &filename)
{
std::string name=Debug::flattenFileName(filename);
name += ".ascii";
m_file.open(name.c_str());
return m_on = m_file.is_open();
}
void DebugFile::addPos(long pos)
{
if (!m_on) return;
m_actOffset = pos;
}
void DebugFile::addNote(char const *note)
{
if (!m_on || note == 0L) return;
size_t numNotes = m_notes.size();
if (!numNotes || m_notes[numNotes-1].m_pos != m_actOffset)
{
std::string empty("");
m_notes.push_back(NotePos(m_actOffset, empty));
numNotes++;
}
m_notes[numNotes-1].m_text += std::string(note);
}
void DebugFile::addDelimiter(long pos, char c)
{
if (!m_on) return;
std::string s;
s+=c;
m_notes.push_back(NotePos(pos,s,false));
}
void DebugFile::sort()
{
if (!m_on) return;
size_t numNotes = m_notes.size();
if (m_actOffset >= 0 && (numNotes == 0 || m_notes[numNotes-1].m_pos != m_actOffset))
{
std::string empty("");
m_notes.push_back(NotePos(m_actOffset, empty));
numNotes++;
}
NotePos::Map map;
for (size_t i = 0; i < numNotes; i++) map[m_notes[i]] = 0;
size_t i = 0;
for (NotePos::Map::iterator it = map.begin(); it != map.end(); i++, it++)
m_notes[i] = it->first;
if (i != numNotes) m_notes.resize(i);
Vec2i::MapX sMap;
size_t numSkip = m_skipZones.size();
for (size_t s = 0; s < numSkip; s++) sMap[m_skipZones[s]] = 0;
i = 0;
for (Vec2i::MapX::iterator it = sMap.begin();
it != sMap.end(); i++, it++)
m_skipZones[i] = it->first;
}
void DebugFile::write()
{
if (!m_on || m_input.get() == 0) return;
sort();
long readPos = m_input->tell();
std::vector<NotePos>::const_iterator noteIter = m_notes.begin();
//! write the notes which does not have any position
while(noteIter != m_notes.end() && noteIter->m_pos < 0)
{
if (!noteIter->m_text.empty())
std::cerr << "DebugFile::write: skipped: " << noteIter->m_text << std::endl;
noteIter++;
}
long actualPos = 0;
int numSkip = int(m_skipZones.size()), actSkip = (numSkip == 0) ? -1 : 0;
long actualSkipEndPos = (numSkip == 0) ? -1 : m_skipZones[0].x();
m_input->seek(0,WPX_SEEK_SET);
m_file << std::hex << std::right << std::setfill('0') << std::setw(6) << 0 << " ";
do
{
bool printAdr = false;
bool stop = false;
while (actualSkipEndPos != -1 && actualPos >= actualSkipEndPos)
{
printAdr = true;
actualPos = m_skipZones[size_t(actSkip)].y()+1;
m_file << "\nSkip : " << std::hex << std::setw(6) << actualSkipEndPos << "-"
<< actualPos-1 << "\n\n";
m_input->seek(actualPos, WPX_SEEK_SET);
stop = m_input->atEOS();
actSkip++;
actualSkipEndPos = (actSkip < numSkip) ? m_skipZones[size_t(actSkip)].x() : -1;
}
if (stop) break;
while(noteIter != m_notes.end() && noteIter->m_pos < actualPos)
{
if (!noteIter->m_text.empty())
m_file << "Skipped: " << noteIter->m_text << std::endl;
noteIter++;
}
bool printNote = noteIter != m_notes.end() && noteIter->m_pos == actualPos;
if (printAdr || (printNote && noteIter->m_breaking))
m_file << "\n" << std::setw(6) << actualPos << " ";
while(noteIter != m_notes.end() && noteIter->m_pos == actualPos)
{
if (noteIter->m_text.empty())
{
noteIter++;
continue;
}
if (noteIter->m_breaking)
m_file << "[" << noteIter->m_text << "]";
else
m_file << noteIter->m_text;
noteIter++;
}
long ch = libwps::readU8(m_input);
m_file << std::setw(2) << ch;
actualPos++;
}
while (!m_input->atEOS());
m_file << "\n\n";
m_input->seek(readPos,WPX_SEEK_SET);
m_actOffset=-1;
m_notes.resize(0);
}
////////////////////////////////////////////////////////////
//
// save WPXBinaryData in a file
//
////////////////////////////////////////////////////////////
namespace Debug
{
bool dumpFile(WPXBinaryData &data, char const *fileName)
{
if (!fileName) return false;
std::string fName = Debug::flattenFileName(fileName);
FILE *file = fopen(fName.c_str(), "wb");
if (!file) return false;
WPXInputStream *tmpStream =
const_cast<WPXInputStream *>(data.getDataStream());
while (!tmpStream->atEOS())
fprintf(file, "%c", libwps::readU8(tmpStream));
fclose(file);
return true;
}
std::string flattenFileName(std::string const &name)
{
std::string res;
for (size_t i = 0; i < name.length(); i++)
{
char c = name[i];
switch(c)
{
case '\0':
case '/':
case '\\':
case ':': // potential file system separator
case ' ':
case '\t':
case '\n': // potential text separator
res += '_';
break;
default:
if (c <= 28) res += '#'; // potential trouble potential char
else res += c;
}
}
return res;
}
}
}
#endif
/* vim:set shiftwidth=4 softtabstop=4 noexpandtab: */
<commit_msg>Add safeguards to prevent problem if we can not read a picture in debug mode...<commit_after>/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: t; c-basic-offset: 4 -*- */
/* libwps
* Copyright (C) 2009, 2011 Alonso Laurent (alonso@loria.fr)
* Copyright (C) 2006, 2007 Andrew Ziem
* Copyright (C) 2004-2006 Fridrich Strba (fridrich.strba@bluewin.ch)
* Copyright (C) 2004 Marc Maurer (uwog@uwog.net)
* Copyright (C) 2003-2005 William Lachance (william.lachance@sympatico.ca)
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Library General Public
* License as published by the Free Software Foundation; either
* version 2 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Library General Public License for more details.
*
* You should have received a copy of the GNU Library General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA
*
* For further information visit http://libwps.sourceforge.net
*/
/* "This product is not manufactured, approved, or supported by
* Corel Corporation or Corel Corporation Limited."
*/
#include <iomanip>
#include <sstream>
#include <libwpd/WPXBinaryData.h>
#include <libwpd-stream/WPXStream.h>
#include "WPSDebug.h"
#if defined(DEBUG_WITH_FILES)
namespace libwps
{
bool DebugFile::open(std::string const &filename)
{
std::string name=Debug::flattenFileName(filename);
name += ".ascii";
m_file.open(name.c_str());
return m_on = m_file.is_open();
}
void DebugFile::addPos(long pos)
{
if (!m_on) return;
m_actOffset = pos;
}
void DebugFile::addNote(char const *note)
{
if (!m_on || note == 0L) return;
size_t numNotes = m_notes.size();
if (!numNotes || m_notes[numNotes-1].m_pos != m_actOffset)
{
std::string empty("");
m_notes.push_back(NotePos(m_actOffset, empty));
numNotes++;
}
m_notes[numNotes-1].m_text += std::string(note);
}
void DebugFile::addDelimiter(long pos, char c)
{
if (!m_on) return;
std::string s;
s+=c;
m_notes.push_back(NotePos(pos,s,false));
}
void DebugFile::sort()
{
if (!m_on) return;
size_t numNotes = m_notes.size();
if (m_actOffset >= 0 && (numNotes == 0 || m_notes[numNotes-1].m_pos != m_actOffset))
{
std::string empty("");
m_notes.push_back(NotePos(m_actOffset, empty));
numNotes++;
}
NotePos::Map map;
for (size_t i = 0; i < numNotes; i++) map[m_notes[i]] = 0;
size_t i = 0;
for (NotePos::Map::iterator it = map.begin(); it != map.end(); i++, it++)
m_notes[i] = it->first;
if (i != numNotes) m_notes.resize(i);
Vec2i::MapX sMap;
size_t numSkip = m_skipZones.size();
for (size_t s = 0; s < numSkip; s++) sMap[m_skipZones[s]] = 0;
i = 0;
for (Vec2i::MapX::iterator it = sMap.begin();
it != sMap.end(); i++, it++)
m_skipZones[i] = it->first;
}
void DebugFile::write()
{
if (!m_on || m_input.get() == 0) return;
sort();
long readPos = m_input->tell();
std::vector<NotePos>::const_iterator noteIter = m_notes.begin();
//! write the notes which does not have any position
while(noteIter != m_notes.end() && noteIter->m_pos < 0)
{
if (!noteIter->m_text.empty())
std::cerr << "DebugFile::write: skipped: " << noteIter->m_text << std::endl;
noteIter++;
}
long actualPos = 0;
int numSkip = int(m_skipZones.size()), actSkip = (numSkip == 0) ? -1 : 0;
long actualSkipEndPos = (numSkip == 0) ? -1 : m_skipZones[0].x();
m_input->seek(0,WPX_SEEK_SET);
m_file << std::hex << std::right << std::setfill('0') << std::setw(6) << 0 << " ";
do
{
bool printAdr = false;
bool stop = false;
while (actualSkipEndPos != -1 && actualPos >= actualSkipEndPos)
{
printAdr = true;
actualPos = m_skipZones[size_t(actSkip)].y()+1;
m_file << "\nSkip : " << std::hex << std::setw(6) << actualSkipEndPos << "-"
<< actualPos-1 << "\n\n";
m_input->seek(actualPos, WPX_SEEK_SET);
stop = m_input->atEOS();
actSkip++;
actualSkipEndPos = (actSkip < numSkip) ? m_skipZones[size_t(actSkip)].x() : -1;
}
if (stop) break;
while(noteIter != m_notes.end() && noteIter->m_pos < actualPos)
{
if (!noteIter->m_text.empty())
m_file << "Skipped: " << noteIter->m_text << std::endl;
noteIter++;
}
bool printNote = noteIter != m_notes.end() && noteIter->m_pos == actualPos;
if (printAdr || (printNote && noteIter->m_breaking))
m_file << "\n" << std::setw(6) << actualPos << " ";
while(noteIter != m_notes.end() && noteIter->m_pos == actualPos)
{
if (noteIter->m_text.empty())
{
noteIter++;
continue;
}
if (noteIter->m_breaking)
m_file << "[" << noteIter->m_text << "]";
else
m_file << noteIter->m_text;
noteIter++;
}
long ch = libwps::readU8(m_input);
m_file << std::setw(2) << ch;
actualPos++;
}
while (!m_input->atEOS());
m_file << "\n\n";
m_input->seek(readPos,WPX_SEEK_SET);
m_actOffset=-1;
m_notes.resize(0);
}
////////////////////////////////////////////////////////////
//
// save WPXBinaryData in a file
//
////////////////////////////////////////////////////////////
namespace Debug
{
bool dumpFile(WPXBinaryData &data, char const *fileName)
{
if (!fileName) return false;
std::string fName = Debug::flattenFileName(fileName);
FILE *file = fopen(fName.c_str(), "wb");
if (!file) return false;
WPXInputStream *tmpStream =
const_cast<WPXInputStream *>(data.getDataStream());
if (!tmpStream) return false;
while (!tmpStream->atEOS())
fprintf(file, "%c", libwps::readU8(tmpStream));
fclose(file);
return true;
}
std::string flattenFileName(std::string const &name)
{
std::string res;
for (size_t i = 0; i < name.length(); i++)
{
char c = name[i];
switch(c)
{
case '\0':
case '/':
case '\\':
case ':': // potential file system separator
case ' ':
case '\t':
case '\n': // potential text separator
res += '_';
break;
default:
if (c <= 28) res += '#'; // potential trouble potential char
else res += c;
}
}
return res;
}
}
}
#endif
/* vim:set shiftwidth=4 softtabstop=4 noexpandtab: */
<|endoftext|> |
<commit_before>#include "types.hh"
#include <cstring>
#include <cstddef>
#include <cstdlib>
#include <unistd.h>
#include <signal.h>
namespace nix {
static void sigsegvHandler(int signo, siginfo_t * info, void * ctx)
{
/* Detect stack overflows by comparing the faulting address with
the stack pointer. Unfortunately, getting the stack pointer is
not portable. */
bool haveSP = true;
char * sp = 0;
#if defined(__x86_64__) && defined(REG_RSP)
sp = (char *) ((ucontext_t *) ctx)->uc_mcontext.gregs[REG_RSP];
#elif defined(REG_ESP)
sp = (char *) ((ucontext_t *) ctx)->uc_mcontext.gregs[REG_ESP];
#else
haveSP = false;
#endif
if (haveSP) {
ptrdiff_t diff = (char *) info->si_addr - sp;
if (diff < 0) diff = -diff;
if (diff < 4096) {
char msg[] = "error: stack overflow (possible infinite recursion)\n";
[[gnu::unused]] auto res = write(2, msg, strlen(msg));
_exit(1); // maybe abort instead?
}
}
/* Restore default behaviour (i.e. segfault and dump core). */
struct sigaction act;
sigfillset(&act.sa_mask);
act.sa_handler = SIG_DFL;
act.sa_flags = 0;
if (sigaction(SIGSEGV, &act, 0)) abort();
}
void detectStackOverflow()
{
#if defined(SA_SIGINFO) && defined (SA_ONSTACK)
/* Install a SIGSEGV handler to detect stack overflows. This
requires an alternative stack, otherwise the signal cannot be
delivered when we're out of stack space. */
stack_t stack;
stack.ss_size = 4096 * 4 + MINSIGSTKSZ;
static auto stackBuf = std::make_unique<std::vector<char>>(stack.ss_size);
stack.ss_sp = stackBuf->data();
if (!stack.ss_sp) throw Error("cannot allocate alternative stack");
stack.ss_flags = 0;
if (sigaltstack(&stack, 0) == -1) throw SysError("cannot set alternative stack");
struct sigaction act;
sigfillset(&act.sa_mask);
act.sa_sigaction = sigsegvHandler;
act.sa_flags = SA_SIGINFO | SA_ONSTACK;
if (sigaction(SIGSEGV, &act, 0))
throw SysError("resetting SIGCHLD");
#endif
}
}
<commit_msg>Fix typo<commit_after>#include "types.hh"
#include <cstring>
#include <cstddef>
#include <cstdlib>
#include <unistd.h>
#include <signal.h>
namespace nix {
static void sigsegvHandler(int signo, siginfo_t * info, void * ctx)
{
/* Detect stack overflows by comparing the faulting address with
the stack pointer. Unfortunately, getting the stack pointer is
not portable. */
bool haveSP = true;
char * sp = 0;
#if defined(__x86_64__) && defined(REG_RSP)
sp = (char *) ((ucontext_t *) ctx)->uc_mcontext.gregs[REG_RSP];
#elif defined(REG_ESP)
sp = (char *) ((ucontext_t *) ctx)->uc_mcontext.gregs[REG_ESP];
#else
haveSP = false;
#endif
if (haveSP) {
ptrdiff_t diff = (char *) info->si_addr - sp;
if (diff < 0) diff = -diff;
if (diff < 4096) {
char msg[] = "error: stack overflow (possible infinite recursion)\n";
[[gnu::unused]] auto res = write(2, msg, strlen(msg));
_exit(1); // maybe abort instead?
}
}
/* Restore default behaviour (i.e. segfault and dump core). */
struct sigaction act;
sigfillset(&act.sa_mask);
act.sa_handler = SIG_DFL;
act.sa_flags = 0;
if (sigaction(SIGSEGV, &act, 0)) abort();
}
void detectStackOverflow()
{
#if defined(SA_SIGINFO) && defined (SA_ONSTACK)
/* Install a SIGSEGV handler to detect stack overflows. This
requires an alternative stack, otherwise the signal cannot be
delivered when we're out of stack space. */
stack_t stack;
stack.ss_size = 4096 * 4 + MINSIGSTKSZ;
static auto stackBuf = std::make_unique<std::vector<char>>(stack.ss_size);
stack.ss_sp = stackBuf->data();
if (!stack.ss_sp) throw Error("cannot allocate alternative stack");
stack.ss_flags = 0;
if (sigaltstack(&stack, 0) == -1) throw SysError("cannot set alternative stack");
struct sigaction act;
sigfillset(&act.sa_mask);
act.sa_sigaction = sigsegvHandler;
act.sa_flags = SA_SIGINFO | SA_ONSTACK;
if (sigaction(SIGSEGV, &act, 0))
throw SysError("resetting SIGSEGV");
#endif
}
}
<|endoftext|> |
<commit_before>/* ************************************************************************
* Copyright 2013 Advanced Micro Devices, 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.
* ************************************************************************/
// clfft.repo.cpp : Defines the entry point for the console application.
//
#include "stdafx.h"
#include "repo.h"
using std::map;
using std::string;
// Static initialization of the repo lock variable
lockRAII FFTRepo::lockRepo( _T( "FFTRepo" ) );
// Static initialization of the plan count variable
size_t FFTRepo::planCount = 1;
// Handle/Address of the dynamic module that contains the timer, that we discover and load during runtime
void* FFTRepo::timerHandle = NULL;
GpuStatTimer* FFTRepo::pStatTimer = NULL;
clfftStatus FFTRepo::releaseResources( )
{
scopedLock sLock( lockRepo, _T( "releaseResources" ) );
// Release all handles to Kernels
//
for(Kernel_iterator iKern = mapKernels.begin( ); iKern != mapKernels.end( ); ++iKern )
{
cl_kernel k = iKern->second.kernel_fwd;
iKern->second.kernel_fwd = NULL;
if (NULL != k)
clReleaseKernel( k );
k = iKern->second.kernel_back;
iKern->second.kernel_back = NULL;
if (NULL != k)
clReleaseKernel( k );
if (NULL != iKern->second.kernel_fwd_lock)
{
delete iKern->second.kernel_fwd_lock;
iKern->second.kernel_fwd_lock = NULL;
}
if (NULL != iKern->second.kernel_back_lock)
{
delete iKern->second.kernel_back_lock;
iKern->second.kernel_back_lock = NULL;
}
}
mapKernels.clear( );
// Release all handles to programs
//
for (fftRepo_iterator iProg = mapFFTs.begin( ); iProg != mapFFTs.end( ); ++iProg )
{
if (iProg->first.data != NULL)
{
const_cast<FFTRepoKey*>(&iProg->first)->deleteData();
}
cl_program p = iProg->second.clProgram;
iProg->second.clProgram = NULL;
if (NULL != p)
clReleaseProgram (p);
}
// Free all memory allocated in the repoPlans; represents cached plans that were not destroyed by the client
//
for( repoPlansType::iterator iter = repoPlans.begin( ); iter != repoPlans.end( ); ++iter )
{
FFTPlan* plan = iter->second.first;
lockRAII* lock = iter->second.second;
if( plan != NULL )
{
delete plan;
}
if( lock != NULL )
{
delete lock;
}
}
// Reset the plan count to zero because we are guaranteed to have destroyed all plans
planCount = 1;
// Release all strings
mapFFTs.clear( );
return CLFFT_SUCCESS;
}
clfftStatus FFTRepo::setProgramCode( const clfftGenerators gen, const FFTKernelSignatureHeader * data, const std::string& kernel, const cl_device_id &device, const cl_context& planContext )
{
scopedLock sLock( lockRepo, _T( "setProgramCode" ) );
FFTRepoKey key(gen, data, planContext, device);
key.privatizeData();
// Prefix copyright statement at the top of generated kernels
std::stringstream ss;
ss <<
"/* ************************************************************************\n"
" * Copyright 2013 Advanced Micro Devices, Inc.\n"
" *\n"
" * Licensed under the Apache License, Version 2.0 (the \"License\");\n"
" * you may not use this file except in compliance with the License.\n"
" * You may obtain a copy of the License at\n"
" *\n"
" * http://www.apache.org/licenses/LICENSE-2.0\n"
" *\n"
" * Unless required by applicable law or agreed to in writing, software\n"
" * distributed under the License is distributed on an \"AS IS\" BASIS,\n"
" * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n"
" * See the License for the specific language governing permissions and\n"
" * limitations under the License.\n"
" * ************************************************************************/"
<< std::endl << std::endl;
std::string prefixCopyright = ss.str();
mapFFTs[ key ].ProgramString = prefixCopyright + kernel;
return CLFFT_SUCCESS;
}
clfftStatus FFTRepo::getProgramCode( const clfftGenerators gen, const FFTKernelSignatureHeader * data, std::string& kernel, const cl_device_id &device, const cl_context& planContext )
{
scopedLock sLock( lockRepo, _T( "getProgramCode" ) );
FFTRepoKey key(gen, data, planContext, device);
fftRepo_iterator pos = mapFFTs.find( key);
if( pos == mapFFTs.end( ) )
return CLFFT_FILE_NOT_FOUND;
kernel = pos->second.ProgramString;
return CLFFT_SUCCESS;
}
clfftStatus FFTRepo::setProgramEntryPoints( const clfftGenerators gen, const FFTKernelSignatureHeader * data,
const char * kernel_fwd, const char * kernel_back, const cl_device_id &device, const cl_context& planContext )
{
scopedLock sLock( lockRepo, _T( "setProgramEntryPoints" ) );
FFTRepoKey key(gen, data, planContext, device);
fftRepoValue& fft = mapFFTs[ key ];
fft.EntryPoint_fwd = kernel_fwd;
fft.EntryPoint_back = kernel_back;
return CLFFT_SUCCESS;
}
clfftStatus FFTRepo::getProgramEntryPoint( const clfftGenerators gen, const FFTKernelSignatureHeader * data,
clfftDirection dir, std::string& kernel, const cl_device_id &device, const cl_context& planContext )
{
scopedLock sLock( lockRepo, _T( "getProgramEntryPoint" ) );
FFTRepoKey key(gen, data, planContext, device);
fftRepo_iterator pos = mapFFTs.find( key );
if( pos == mapFFTs.end( ) )
return CLFFT_FILE_NOT_FOUND;
switch (dir) {
case CLFFT_FORWARD:
kernel = pos->second.EntryPoint_fwd;
break;
case CLFFT_BACKWARD:
kernel = pos->second.EntryPoint_back;
break;
default:
assert (false);
return CLFFT_INVALID_ARG_VALUE;
}
if (0 == kernel.size())
return CLFFT_FILE_NOT_FOUND;
return CLFFT_SUCCESS;
}
clfftStatus FFTRepo::setclProgram( const clfftGenerators gen, const FFTKernelSignatureHeader * data, const cl_program& prog, const cl_device_id &device, const cl_context& planContext )
{
scopedLock sLock( lockRepo, _T( "setclProgram" ) );
FFTRepoKey key(gen, data, planContext, device);
fftRepo_iterator pos = mapFFTs.find( key );
if( pos == mapFFTs.end( ) )
{
key.privatizeData(); // the key owns the data
mapFFTs[ key ].clProgram = prog;
}
else {
cl_program p = pos->second.clProgram;
assert (NULL == p);
if (NULL != p)
clReleaseProgram (p);
pos->second.clProgram = prog;
}
return CLFFT_SUCCESS;
}
clfftStatus FFTRepo::getclProgram( const clfftGenerators gen, const FFTKernelSignatureHeader * data, cl_program& prog, const cl_device_id &device, const cl_context& planContext )
{
scopedLock sLock( lockRepo, _T( "getclProgram" ) );
FFTRepoKey key(gen, data, planContext, device);
fftRepo_iterator pos = mapFFTs.find( key );
if( pos == mapFFTs.end( ) )
return CLFFT_INVALID_PROGRAM;
prog = pos->second.clProgram;
if (NULL == prog)
return CLFFT_INVALID_PROGRAM;
cl_context progContext;
clGetProgramInfo(prog, CL_PROGRAM_CONTEXT, sizeof(cl_context), &progContext, NULL);
if (planContext!=progContext)
return CLFFT_INVALID_PROGRAM;
return CLFFT_SUCCESS;
}
clfftStatus FFTRepo::setclKernel( cl_program prog, clfftDirection dir, const cl_kernel& kernel )
{
scopedLock sLock( lockRepo, _T( "setclKernel" ) );
fftKernels & Kernels = mapKernels[ prog ];
cl_kernel * pk;
lockRAII ** kernelLock;
switch (dir) {
case CLFFT_FORWARD:
pk = & Kernels.kernel_fwd;
kernelLock = & Kernels.kernel_fwd_lock;
break;
case CLFFT_BACKWARD:
pk = & Kernels.kernel_back;
kernelLock = & Kernels.kernel_back_lock;
break;
default:
assert (false);
return CLFFT_INVALID_ARG_VALUE;
}
assert (NULL == *pk);
if (NULL != *pk)
clReleaseKernel( *pk );
*pk = kernel;
if (NULL != *kernelLock)
delete kernelLock;
*kernelLock = new lockRAII;
return CLFFT_SUCCESS;
}
clfftStatus FFTRepo::getclKernel( cl_program prog, clfftDirection dir, cl_kernel& kernel, lockRAII*& kernelLock)
{
scopedLock sLock( lockRepo, _T( "getclKernel" ) );
Kernel_iterator pos = mapKernels.find( prog );
if (pos == mapKernels.end( ) )
return CLFFT_INVALID_KERNEL;
switch (dir) {
case CLFFT_FORWARD:
kernel = pos->second.kernel_fwd;
kernelLock = pos->second.kernel_fwd_lock;
break;
case CLFFT_BACKWARD:
kernel = pos->second.kernel_back;
kernelLock = pos->second.kernel_back_lock;
break;
default:
assert (false);
return CLFFT_INVALID_ARG_VALUE;
}
if (NULL == kernel)
return CLFFT_INVALID_KERNEL;
return CLFFT_SUCCESS;
}
clfftStatus FFTRepo::createPlan( clfftPlanHandle* plHandle, FFTPlan*& fftPlan )
{
scopedLock sLock( lockRepo, _T( "insertPlan" ) );
// We keep track of this memory in our own collection class, to make sure it's freed in releaseResources
// The lifetime of a plan is tracked by the client and is freed when the client calls ::clfftDestroyPlan()
fftPlan = new FFTPlan;
// We allocate a new lock here, and expect it to be freed in ::clfftDestroyPlan();
// The lifetime of the lock is the same as the lifetime of the plan
lockRAII* lockPlan = new lockRAII;
// Add and remember the fftPlan in our map
repoPlans[ planCount ] = std::make_pair( fftPlan, lockPlan );
// Assign the user handle the plan count (unique identifier), and bump the count for the next plan
*plHandle = planCount++;
return CLFFT_SUCCESS;
}
clfftStatus FFTRepo::getPlan( clfftPlanHandle plHandle, FFTPlan*& fftPlan, lockRAII*& planLock )
{
scopedLock sLock( lockRepo, _T( "getPlan" ) );
// First, check if we have already created a plan with this exact same FFTPlan
repoPlansType::iterator iter = repoPlans.find( plHandle );
if( iter == repoPlans.end( ) )
return CLFFT_INVALID_PLAN;
// If plan is valid, return fill out the output pointers
fftPlan = iter->second.first;
planLock = iter->second.second;
return CLFFT_SUCCESS;
}
clfftStatus FFTRepo::deletePlan( clfftPlanHandle* plHandle )
{
scopedLock sLock( lockRepo, _T( "deletePlan" ) );
// First, check if we have already created a plan with this exact same FFTPlan
repoPlansType::iterator iter = repoPlans.find( *plHandle );
if( iter == repoPlans.end( ) )
return CLFFT_INVALID_PLAN;
// We lock the plan object while we are in the process of deleting it
{
scopedLock sLock( *iter->second.second, _T( "clfftDestroyPlan" ) );
clReleaseContext( iter->second.first->context );
// Delete the FFTPlan
delete iter->second.first;
}
// Delete the lockRAII
delete iter->second.second;
// Remove entry from our map object
repoPlans.erase( iter );
// Clear the client's handle to signify that the plan is gone
*plHandle = 0;
return CLFFT_SUCCESS;
}
<commit_msg>fixing a memory leak issue in key creation, fixes #172<commit_after>/* ************************************************************************
* Copyright 2013 Advanced Micro Devices, 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.
* ************************************************************************/
// clfft.repo.cpp : Defines the entry point for the console application.
//
#include "stdafx.h"
#include "repo.h"
using std::map;
using std::string;
// Static initialization of the repo lock variable
lockRAII FFTRepo::lockRepo( _T( "FFTRepo" ) );
// Static initialization of the plan count variable
size_t FFTRepo::planCount = 1;
// Handle/Address of the dynamic module that contains the timer, that we discover and load during runtime
void* FFTRepo::timerHandle = NULL;
GpuStatTimer* FFTRepo::pStatTimer = NULL;
clfftStatus FFTRepo::releaseResources( )
{
scopedLock sLock( lockRepo, _T( "releaseResources" ) );
// Release all handles to Kernels
//
for(Kernel_iterator iKern = mapKernels.begin( ); iKern != mapKernels.end( ); ++iKern )
{
cl_kernel k = iKern->second.kernel_fwd;
iKern->second.kernel_fwd = NULL;
if (NULL != k)
clReleaseKernel( k );
k = iKern->second.kernel_back;
iKern->second.kernel_back = NULL;
if (NULL != k)
clReleaseKernel( k );
if (NULL != iKern->second.kernel_fwd_lock)
{
delete iKern->second.kernel_fwd_lock;
iKern->second.kernel_fwd_lock = NULL;
}
if (NULL != iKern->second.kernel_back_lock)
{
delete iKern->second.kernel_back_lock;
iKern->second.kernel_back_lock = NULL;
}
}
mapKernels.clear( );
// Release all handles to programs
//
for (fftRepo_iterator iProg = mapFFTs.begin( ); iProg != mapFFTs.end( ); ++iProg )
{
if (iProg->first.data != NULL)
{
const_cast<FFTRepoKey*>(&iProg->first)->deleteData();
}
cl_program p = iProg->second.clProgram;
iProg->second.clProgram = NULL;
if (NULL != p)
clReleaseProgram (p);
}
// Free all memory allocated in the repoPlans; represents cached plans that were not destroyed by the client
//
for( repoPlansType::iterator iter = repoPlans.begin( ); iter != repoPlans.end( ); ++iter )
{
FFTPlan* plan = iter->second.first;
lockRAII* lock = iter->second.second;
if( plan != NULL )
{
delete plan;
}
if( lock != NULL )
{
delete lock;
}
}
// Reset the plan count to zero because we are guaranteed to have destroyed all plans
planCount = 1;
// Release all strings
mapFFTs.clear( );
return CLFFT_SUCCESS;
}
clfftStatus FFTRepo::setProgramCode( const clfftGenerators gen, const FFTKernelSignatureHeader * data, const std::string& kernel, const cl_device_id &device, const cl_context& planContext )
{
scopedLock sLock( lockRepo, _T( "setProgramCode" ) );
FFTRepoKey key(gen, data, planContext, device);
key.privatizeData();
// Prefix copyright statement at the top of generated kernels
std::stringstream ss;
ss <<
"/* ************************************************************************\n"
" * Copyright 2013 Advanced Micro Devices, Inc.\n"
" *\n"
" * Licensed under the Apache License, Version 2.0 (the \"License\");\n"
" * you may not use this file except in compliance with the License.\n"
" * You may obtain a copy of the License at\n"
" *\n"
" * http://www.apache.org/licenses/LICENSE-2.0\n"
" *\n"
" * Unless required by applicable law or agreed to in writing, software\n"
" * distributed under the License is distributed on an \"AS IS\" BASIS,\n"
" * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n"
" * See the License for the specific language governing permissions and\n"
" * limitations under the License.\n"
" * ************************************************************************/"
<< std::endl << std::endl;
std::string prefixCopyright = ss.str();
fftRepoType::iterator it = mapFFTs.find(key);
if (it == mapFFTs.end())
mapFFTs[key].ProgramString = prefixCopyright + kernel;
else
key.deleteData();
return CLFFT_SUCCESS;
}
clfftStatus FFTRepo::getProgramCode( const clfftGenerators gen, const FFTKernelSignatureHeader * data, std::string& kernel, const cl_device_id &device, const cl_context& planContext )
{
scopedLock sLock( lockRepo, _T( "getProgramCode" ) );
FFTRepoKey key(gen, data, planContext, device);
fftRepo_iterator pos = mapFFTs.find( key);
if( pos == mapFFTs.end( ) )
return CLFFT_FILE_NOT_FOUND;
kernel = pos->second.ProgramString;
return CLFFT_SUCCESS;
}
clfftStatus FFTRepo::setProgramEntryPoints( const clfftGenerators gen, const FFTKernelSignatureHeader * data,
const char * kernel_fwd, const char * kernel_back, const cl_device_id &device, const cl_context& planContext )
{
scopedLock sLock( lockRepo, _T( "setProgramEntryPoints" ) );
FFTRepoKey key(gen, data, planContext, device);
fftRepoValue& fft = mapFFTs[ key ];
fft.EntryPoint_fwd = kernel_fwd;
fft.EntryPoint_back = kernel_back;
return CLFFT_SUCCESS;
}
clfftStatus FFTRepo::getProgramEntryPoint( const clfftGenerators gen, const FFTKernelSignatureHeader * data,
clfftDirection dir, std::string& kernel, const cl_device_id &device, const cl_context& planContext )
{
scopedLock sLock( lockRepo, _T( "getProgramEntryPoint" ) );
FFTRepoKey key(gen, data, planContext, device);
fftRepo_iterator pos = mapFFTs.find( key );
if( pos == mapFFTs.end( ) )
return CLFFT_FILE_NOT_FOUND;
switch (dir) {
case CLFFT_FORWARD:
kernel = pos->second.EntryPoint_fwd;
break;
case CLFFT_BACKWARD:
kernel = pos->second.EntryPoint_back;
break;
default:
assert (false);
return CLFFT_INVALID_ARG_VALUE;
}
if (0 == kernel.size())
return CLFFT_FILE_NOT_FOUND;
return CLFFT_SUCCESS;
}
clfftStatus FFTRepo::setclProgram( const clfftGenerators gen, const FFTKernelSignatureHeader * data, const cl_program& prog, const cl_device_id &device, const cl_context& planContext )
{
scopedLock sLock( lockRepo, _T( "setclProgram" ) );
FFTRepoKey key(gen, data, planContext, device);
fftRepo_iterator pos = mapFFTs.find( key );
if( pos == mapFFTs.end( ) )
{
key.privatizeData(); // the key owns the data
mapFFTs[ key ].clProgram = prog;
}
else {
cl_program p = pos->second.clProgram;
assert (NULL == p);
if (NULL != p)
clReleaseProgram (p);
pos->second.clProgram = prog;
}
return CLFFT_SUCCESS;
}
clfftStatus FFTRepo::getclProgram( const clfftGenerators gen, const FFTKernelSignatureHeader * data, cl_program& prog, const cl_device_id &device, const cl_context& planContext )
{
scopedLock sLock( lockRepo, _T( "getclProgram" ) );
FFTRepoKey key(gen, data, planContext, device);
fftRepo_iterator pos = mapFFTs.find( key );
if( pos == mapFFTs.end( ) )
return CLFFT_INVALID_PROGRAM;
prog = pos->second.clProgram;
if (NULL == prog)
return CLFFT_INVALID_PROGRAM;
cl_context progContext;
clGetProgramInfo(prog, CL_PROGRAM_CONTEXT, sizeof(cl_context), &progContext, NULL);
if (planContext!=progContext)
return CLFFT_INVALID_PROGRAM;
return CLFFT_SUCCESS;
}
clfftStatus FFTRepo::setclKernel( cl_program prog, clfftDirection dir, const cl_kernel& kernel )
{
scopedLock sLock( lockRepo, _T( "setclKernel" ) );
fftKernels & Kernels = mapKernels[ prog ];
cl_kernel * pk;
lockRAII ** kernelLock;
switch (dir) {
case CLFFT_FORWARD:
pk = & Kernels.kernel_fwd;
kernelLock = & Kernels.kernel_fwd_lock;
break;
case CLFFT_BACKWARD:
pk = & Kernels.kernel_back;
kernelLock = & Kernels.kernel_back_lock;
break;
default:
assert (false);
return CLFFT_INVALID_ARG_VALUE;
}
assert (NULL == *pk);
if (NULL != *pk)
clReleaseKernel( *pk );
*pk = kernel;
if (NULL != *kernelLock)
delete kernelLock;
*kernelLock = new lockRAII;
return CLFFT_SUCCESS;
}
clfftStatus FFTRepo::getclKernel( cl_program prog, clfftDirection dir, cl_kernel& kernel, lockRAII*& kernelLock)
{
scopedLock sLock( lockRepo, _T( "getclKernel" ) );
Kernel_iterator pos = mapKernels.find( prog );
if (pos == mapKernels.end( ) )
return CLFFT_INVALID_KERNEL;
switch (dir) {
case CLFFT_FORWARD:
kernel = pos->second.kernel_fwd;
kernelLock = pos->second.kernel_fwd_lock;
break;
case CLFFT_BACKWARD:
kernel = pos->second.kernel_back;
kernelLock = pos->second.kernel_back_lock;
break;
default:
assert (false);
return CLFFT_INVALID_ARG_VALUE;
}
if (NULL == kernel)
return CLFFT_INVALID_KERNEL;
return CLFFT_SUCCESS;
}
clfftStatus FFTRepo::createPlan( clfftPlanHandle* plHandle, FFTPlan*& fftPlan )
{
scopedLock sLock( lockRepo, _T( "insertPlan" ) );
// We keep track of this memory in our own collection class, to make sure it's freed in releaseResources
// The lifetime of a plan is tracked by the client and is freed when the client calls ::clfftDestroyPlan()
fftPlan = new FFTPlan;
// We allocate a new lock here, and expect it to be freed in ::clfftDestroyPlan();
// The lifetime of the lock is the same as the lifetime of the plan
lockRAII* lockPlan = new lockRAII;
// Add and remember the fftPlan in our map
repoPlans[ planCount ] = std::make_pair( fftPlan, lockPlan );
// Assign the user handle the plan count (unique identifier), and bump the count for the next plan
*plHandle = planCount++;
return CLFFT_SUCCESS;
}
clfftStatus FFTRepo::getPlan( clfftPlanHandle plHandle, FFTPlan*& fftPlan, lockRAII*& planLock )
{
scopedLock sLock( lockRepo, _T( "getPlan" ) );
// First, check if we have already created a plan with this exact same FFTPlan
repoPlansType::iterator iter = repoPlans.find( plHandle );
if( iter == repoPlans.end( ) )
return CLFFT_INVALID_PLAN;
// If plan is valid, return fill out the output pointers
fftPlan = iter->second.first;
planLock = iter->second.second;
return CLFFT_SUCCESS;
}
clfftStatus FFTRepo::deletePlan( clfftPlanHandle* plHandle )
{
scopedLock sLock( lockRepo, _T( "deletePlan" ) );
// First, check if we have already created a plan with this exact same FFTPlan
repoPlansType::iterator iter = repoPlans.find( *plHandle );
if( iter == repoPlans.end( ) )
return CLFFT_INVALID_PLAN;
// We lock the plan object while we are in the process of deleting it
{
scopedLock sLock( *iter->second.second, _T( "clfftDestroyPlan" ) );
clReleaseContext( iter->second.first->context );
// Delete the FFTPlan
delete iter->second.first;
}
// Delete the lockRAII
delete iter->second.second;
// Remove entry from our map object
repoPlans.erase( iter );
// Clear the client's handle to signify that the plan is gone
*plHandle = 0;
return CLFFT_SUCCESS;
}
<|endoftext|> |
<commit_before>/*
Copyright (C) 2017 Tadeusz Puźniakowski
This file is part of mhttp.
This program 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.
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 Affero General Public License for more details.
You should have received a copy of the GNU Affero General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
you can contact me via http://www.puzniakowski.pl
*/
#include "http_session.hpp"
#include "http_memorysessionstorage.hpp"
#include "http_request.hpp"
#include "http_response.hpp"
#include <iostream>
#include <list>
namespace tp {
namespace http {
std::string MemorySessionStorage::generateSessionId() {
while ( true ) {
int m = uniform_dist( e1 ) & 0x07fffffff;
if ( sessions.count( std::to_string( m ) ) < 1 ) {
return std::to_string( m );
}
}
}
Session &MemorySessionStorage::getSessionForRequest ( Request &req ) {
std::lock_guard<std::mutex> guard( session_mutex );
std::string sid = "";
std::string cookiestring = req.header["cookie"];
//std::cout << "getSessionForRequest cookie: " << cookiestring << " ; " << std::endl;
std::regex pieces_regex( "sessionId=([0123456789][0123456789]*)" );
std::smatch pieces_match;
if ( std::regex_match ( cookiestring, pieces_match, pieces_regex ) ) {
for ( size_t i = 0; i < pieces_match.size(); ++i ) {
std::ssub_match sub_match = pieces_match[i];
auto fsid = sub_match.str();
if ( sessions.count( fsid ) > 0 ) {
sid = fsid;
break;
}
}
}
//std::cout << "getSessionForRequest cookie - sid: " << sid << " ; " << std::endl;
// std::cout << cookiestring << std::endl;
if ( sid == "" ) {
sid = generateSessionId();
if ((sessions.size() % sessionCleanupCycle) == 0) {
std::list < std::string > sessionToDelete;
for (auto &s : sessions) {
if (s.second.getSecondsOfLife() > sessionTimeout) {
sessionToDelete.push_back(s.first);
}
}
for (auto &sidd : sessionToDelete) {
sessions.erase(sidd);
}
}
if ((maxSessions == -1) || ((int)sessions.size() > maxSessions)) {
throw std::overflow_error("could not allocate another session");
}
sessions[sid].setId( sid );
}
return sessions[sid];
}
void MemorySessionStorage::storeSession ( Session session ) {
std::lock_guard<std::mutex> guard( session_mutex );
sessions[session.getId()] = session;
}
t_Response MemorySessionStorage::storeSessionForRequest ( Session session, t_Response &res ) {
storeSession ( session );
std::stringstream setcookie;
setcookie << "sessionId" << "=" << session.getId();
res.getHeader()["set-cookie"] = setcookie.str();
//std::cout << "set-cookie header: " << res.getHeader()["set-cookie"] << std::endl;
return res;
}
MemorySessionStorage::MemorySessionStorage(int sessionLifeTimeSeconds,int maxSessions_, int sessionCleanupCycle_)
: e1( r() ),
uniform_dist( 1001, 1 << ( sizeof( int ) * 8 - 2 ) ),
sessionTimeout(sessionLifeTimeSeconds),
maxSessions(maxSessions_),
sessionCleanupCycle(sessionCleanupCycle_) {
}
}
}
<commit_msg>bugfix in session handling - long info<commit_after>/*
Copyright (C) 2017 Tadeusz Puźniakowski
This file is part of mhttp.
This program 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.
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 Affero General Public License for more details.
You should have received a copy of the GNU Affero General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
you can contact me via http://www.puzniakowski.pl
*/
#include "http_session.hpp"
#include "http_memorysessionstorage.hpp"
#include "http_request.hpp"
#include "http_response.hpp"
#include <iostream>
#include <list>
namespace tp {
namespace http {
std::string MemorySessionStorage::generateSessionId() {
while ( true ) {
int m = uniform_dist( e1 ) & 0x07fffffff;
if ( sessions.count( std::to_string( m ) ) < 1 ) {
return std::to_string( m );
}
}
}
Session &MemorySessionStorage::getSessionForRequest ( Request &req ) {
std::lock_guard<std::mutex> guard( session_mutex );
std::string sid = "";
std::string cookiestring = req.header["cookie"];
std::cout << "getSessionForRequest cookie: " << cookiestring << " ; " << std::endl;
std::regex pieces_regex( "sessionId=([0123456789][0123456789]*)" );
std::smatch pieces_match;
if ( std::regex_match ( cookiestring, pieces_match, pieces_regex ) ) {
for ( size_t i = 0; i < pieces_match.size(); ++i ) {
std::ssub_match sub_match = pieces_match[i];
auto fsid = sub_match.str();
if ( sessions.count( fsid ) > 0 ) {
sid = fsid;
break;
}
}
}
std::cout << "getSessionForRequest cookie - sid: " << sid << " ; " << std::endl;
// std::cout << cookiestring << std::endl;
if ( sid == "" ) {
sid = generateSessionId();
if ((sessions.size() % sessionCleanupCycle) == 0) {
std::list < std::string > sessionToDelete;
for (auto &s : sessions) {
if (s.second.getSecondsOfLife() > sessionTimeout) {
sessionToDelete.push_back(s.first);
}
}
for (auto &sidd : sessionToDelete) {
sessions.erase(sidd);
}
}
if ((maxSessions == -1) || ((int)sessions.size() > maxSessions)) {
throw std::overflow_error("could not allocate another session");
}
sessions[sid].setId( sid );
}
return sessions[sid];
}
void MemorySessionStorage::storeSession ( Session session ) {
std::lock_guard<std::mutex> guard( session_mutex );
sessions[session.getId()] = session;
}
t_Response MemorySessionStorage::storeSessionForRequest ( Session session, t_Response &res ) {
storeSession ( session );
std::stringstream setcookie;
setcookie << "sessionId" << "=" << session.getId();
res.getHeader()["set-cookie"] = setcookie.str();
//std::cout << "set-cookie header: " << res.getHeader()["set-cookie"] << std::endl;
return res;
}
MemorySessionStorage::MemorySessionStorage(int sessionLifeTimeSeconds,int maxSessions_, int sessionCleanupCycle_)
: e1( r() ),
uniform_dist( 1001, 1 << ( sizeof( int ) * 8 - 2 ) ),
sessionTimeout(sessionLifeTimeSeconds),
maxSessions(maxSessions_),
sessionCleanupCycle(sessionCleanupCycle_) {
}
}
}
<|endoftext|> |
<commit_before>/*
* Copyright (c) [2017-2018] SUSE LLC
*
* All Rights Reserved.
*
* This program is free software; you can redistribute it and/or modify it
* under the terms of version 2 of the GNU General Public License as published
* by the Free Software Foundation.
*
* This program is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
* more details.
*
* You should have received a copy of the GNU General Public License along
* with this program; if not, contact Novell, Inc.
*
* To contact Novell about this file by physical or electronic mail, you may
* find current contact information at www.novell.com.
*/
#include "storage/Devices/BlkDeviceImpl.h"
#include "storage/Filesystems/ReiserfsImpl.h"
#include "storage/Utils/StorageDefines.h"
#include "storage/Utils/HumanString.h"
#include "storage/Utils/SystemCmd.h"
#include "storage/FreeInfo.h"
#include "storage/UsedFeatures.h"
namespace storage
{
using namespace std;
const char* DeviceTraits<Reiserfs>::classname = "Reiserfs";
Reiserfs::Impl::Impl(const xmlNode* node)
: BlkFilesystem::Impl(node)
{
}
string
Reiserfs::Impl::get_pretty_classname() const
{
// TRANSLATORS: name of object
return _("Reiserfs").translated;
}
uint64_t
Reiserfs::Impl::used_features() const
{
return UF_REISERFS | BlkFilesystem::Impl::used_features();
}
void
Reiserfs::Impl::do_create()
{
const BlkDevice* blk_device = get_blk_device();
string cmd_line = MKFSREISERFSBIN " -f -f " + get_mkfs_options() + " " +
quote(blk_device->get_name());
wait_for_devices();
SystemCmd cmd(cmd_line, SystemCmd::DoThrow);
// uuid is included in mkfs output
probe_uuid();
}
void
Reiserfs::Impl::do_set_label() const
{
const BlkDevice* blk_device = get_blk_device();
// TODO handle mounted
string cmd_line = TUNEREISERFSBIN " -l " + quote(get_label()) + " " +
quote(blk_device->get_name());
SystemCmd cmd(cmd_line, SystemCmd::DoThrow);
}
void
Reiserfs::Impl::do_set_tune_options() const
{
const BlkDevice* blk_device = get_blk_device();
string cmd_line = TUNEREISERFSBIN " " + get_tune_options() + " " + quote(blk_device->get_name());
SystemCmd cmd(cmd_line, SystemCmd::DoThrow);
}
void
Reiserfs::Impl::do_resize(const CommitData& commit_data, const Action::Resize* action) const
{
const Reiserfs* reiserfs_rhs = to_reiserfs(action->get_device(commit_data.actiongraph, RHS));
const BlkDevice* blk_device_rhs = reiserfs_rhs->get_impl().get_blk_device();
string cmd_line = REISERFSRESIZEBIN " -f";
if (action->resize_mode == ResizeMode::SHRINK)
cmd_line = "echo y | " + cmd_line + " -s " +
to_string(blk_device_rhs->get_size() / KiB) + "K";
cmd_line += " " + quote(action->blk_device->get_name());
wait_for_devices();
SystemCmd cmd(cmd_line, SystemCmd::DoThrow);
}
}
<commit_msg>- fixed message<commit_after>/*
* Copyright (c) [2017-2020] SUSE LLC
*
* All Rights Reserved.
*
* This program is free software; you can redistribute it and/or modify it
* under the terms of version 2 of the GNU General Public License as published
* by the Free Software Foundation.
*
* This program is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
* more details.
*
* You should have received a copy of the GNU General Public License along
* with this program; if not, contact Novell, Inc.
*
* To contact Novell about this file by physical or electronic mail, you may
* find current contact information at www.novell.com.
*/
#include "storage/Devices/BlkDeviceImpl.h"
#include "storage/Filesystems/ReiserfsImpl.h"
#include "storage/Utils/StorageDefines.h"
#include "storage/Utils/HumanString.h"
#include "storage/Utils/SystemCmd.h"
#include "storage/FreeInfo.h"
#include "storage/UsedFeatures.h"
namespace storage
{
using namespace std;
const char* DeviceTraits<Reiserfs>::classname = "Reiserfs";
Reiserfs::Impl::Impl(const xmlNode* node)
: BlkFilesystem::Impl(node)
{
}
string
Reiserfs::Impl::get_pretty_classname() const
{
// TRANSLATORS: name of object
return _("ReiserFS").translated;
}
uint64_t
Reiserfs::Impl::used_features() const
{
return UF_REISERFS | BlkFilesystem::Impl::used_features();
}
void
Reiserfs::Impl::do_create()
{
const BlkDevice* blk_device = get_blk_device();
string cmd_line = MKFSREISERFSBIN " -f -f " + get_mkfs_options() + " " +
quote(blk_device->get_name());
wait_for_devices();
SystemCmd cmd(cmd_line, SystemCmd::DoThrow);
// uuid is included in mkfs output
probe_uuid();
}
void
Reiserfs::Impl::do_set_label() const
{
const BlkDevice* blk_device = get_blk_device();
// TODO handle mounted
string cmd_line = TUNEREISERFSBIN " -l " + quote(get_label()) + " " +
quote(blk_device->get_name());
SystemCmd cmd(cmd_line, SystemCmd::DoThrow);
}
void
Reiserfs::Impl::do_set_tune_options() const
{
const BlkDevice* blk_device = get_blk_device();
string cmd_line = TUNEREISERFSBIN " " + get_tune_options() + " " + quote(blk_device->get_name());
SystemCmd cmd(cmd_line, SystemCmd::DoThrow);
}
void
Reiserfs::Impl::do_resize(const CommitData& commit_data, const Action::Resize* action) const
{
const Reiserfs* reiserfs_rhs = to_reiserfs(action->get_device(commit_data.actiongraph, RHS));
const BlkDevice* blk_device_rhs = reiserfs_rhs->get_impl().get_blk_device();
string cmd_line = REISERFSRESIZEBIN " -f";
if (action->resize_mode == ResizeMode::SHRINK)
cmd_line = "echo y | " + cmd_line + " -s " +
to_string(blk_device_rhs->get_size() / KiB) + "K";
cmd_line += " " + quote(action->blk_device->get_name());
wait_for_devices();
SystemCmd cmd(cmd_line, SystemCmd::DoThrow);
}
}
<|endoftext|> |
<commit_before>/**
* \file Chebyshev1Filter.cpp
*/
#include <boost/math/special_functions/asinh.hpp>
#include "Chebyshev1Filter.h"
#include "IIRFilter.h"
namespace
{
template<typename DataType>
void create_chebyshev1_analog_coefficients(int order, DataType ripple, std::vector<std::complex<DataType> >& z, std::vector<std::complex<DataType> >& p, DataType& k)
{
z.clear(); // no zeros for this filter type
p.clear();
if(order == 0)
{
k = std::pow(10, (-ripple / 20));
return;
}
DataType eps = std::sqrt(std::pow(10, (0.1 * ripple)) - 1.0);
DataType mu = 1.0 / order * boost::math::asinh(1 / eps);
for(int i = -order+1; i < order; i += 2)
{
DataType theta = boost::math::constants::pi<DataType>() * i / (2*order);
p.push_back(-std::sinh(std::complex<DataType>(mu, theta)));
}
std::complex<DataType> f = 1;
for(int i = 0; i < p.size(); ++i)
{
f *= -p[i];
}
k = f.real();
if(order % 2 == 0)
{
k = k / std::sqrt((1 + eps * eps));
}
}
template<typename DataType>
void create_default_chebyshev1_coeffs(int order, DataType ripple, DataType Wn, std::vector<DataType>& coefficients_in, std::vector<DataType>& coefficients_out)
{
std::vector<std::complex<DataType> > z;
std::vector<std::complex<DataType> > p;
DataType k;
int fs = 2;
create_chebyshev1_analog_coefficients(order, ripple, z, p, k);
DataType warped = 2 * fs * std::tan(boost::math::constants::pi<DataType>() * Wn / fs);
zpk_lp2lp(warped, z, p, k);
zpk_bilinear(fs, z, p, k);
boost::math::tools::polynomial<DataType> b;
boost::math::tools::polynomial<DataType> a;
zpk2ba(fs, z, p, k, b, a);
for(int i = 0; i < order + 1; ++i)
{
coefficients_in[i] = b[i];
}
for(int i = 0; i < order; ++i)
{
coefficients_out[i] = -a[i];
}
}
template<typename DataType>
void create_bp_chebyshev1_coeffs(int order, DataType ripple, DataType wc1, DataType wc2, std::vector<DataType>& coefficients_in, std::vector<DataType>& coefficients_out)
{
std::vector<std::complex<DataType> > z;
std::vector<std::complex<DataType> > p;
DataType k;
int fs = 2;
create_chebyshev1_analog_coefficients(order/2, ripple, z, p, k);
wc1 = 2 * fs * std::tan(boost::math::constants::pi<DataType>() * wc1 / fs);
wc2 = 2 * fs * std::tan(boost::math::constants::pi<DataType>() * wc2 / fs);
zpk_lp2bp(std::sqrt(wc1 * wc2), wc2 - wc1, z, p, k);
zpk_bilinear(fs, z, p, k);
boost::math::tools::polynomial<DataType> b;
boost::math::tools::polynomial<DataType> a;
zpk2ba(fs, z, p, k, b, a);
for(int i = 0; i < order + 1; ++i)
{
coefficients_in[i] = b[i];
}
for(int i = 0; i < order; ++i)
{
coefficients_out[i] = -a[i];
}
}
template<typename DataType>
void create_bs_chebyshev1_coeffs(int order, DataType ripple, DataType wc1, DataType wc2, std::vector<DataType>& coefficients_in, std::vector<DataType>& coefficients_out)
{
std::vector<std::complex<DataType> > z;
std::vector<std::complex<DataType> > p;
DataType k;
int fs = 2;
create_chebyshev1_analog_coefficients(order/2, ripple, z, p, k);
wc1 = 2 * fs * std::tan(boost::math::constants::pi<DataType>() * wc1 / fs);
wc2 = 2 * fs * std::tan(boost::math::constants::pi<DataType>() * wc2 / fs);
zpk_lp2bs(std::sqrt(wc1 * wc2), wc2 - wc1, z, p, k);
zpk_bilinear(fs, z, p, k);
boost::math::tools::polynomial<DataType> b;
boost::math::tools::polynomial<DataType> a;
zpk2ba(fs, z, p, k, b, a);
for(int i = 0; i < order + 1; ++i)
{
coefficients_in[i] = b[i];
}
for(int i = 0; i < order; ++i)
{
coefficients_out[i] = -a[i];
}
}
}
namespace ATK
{
template <typename DataType>
Chebyshev1LowPassCoefficients<DataType>::Chebyshev1LowPassCoefficients()
:Parent(1, 1), cut_frequency(0), ripple(0), in_order(1), out_order(1)
{
}
template <typename DataType>
void Chebyshev1LowPassCoefficients<DataType>::set_ripple(DataType ripple)
{
this->ripple = ripple;
setup();
}
template <typename DataType>
typename Chebyshev1LowPassCoefficients<DataType>::DataType Chebyshev1LowPassCoefficients<DataType>::get_ripple() const
{
return ripple;
}
template <typename DataType>
void Chebyshev1LowPassCoefficients<DataType>::set_cut_frequency(DataType cut_frequency)
{
this->cut_frequency = cut_frequency;
setup();
}
template <typename DataType>
typename Chebyshev1LowPassCoefficients<DataType>::DataType Chebyshev1LowPassCoefficients<DataType>::get_cut_frequency() const
{
return cut_frequency;
}
template <typename DataType>
void Chebyshev1LowPassCoefficients<DataType>::set_order(int order)
{
in_order = out_order = order;
setup();
}
template <typename DataType>
void Chebyshev1LowPassCoefficients<DataType>::setup()
{
Parent::setup();
coefficients_in.assign(in_order+1, 0);
coefficients_out.assign(out_order, 0);
create_default_chebyshev1_coeffs(in_order, ripple, 2 * cut_frequency / input_sampling_rate, coefficients_in, coefficients_out);
}
template <typename DataType>
Chebyshev1HighPassCoefficients<DataType>::Chebyshev1HighPassCoefficients()
:Parent(1, 1), cut_frequency(0), ripple(0), in_order(1), out_order(1)
{
}
template <typename DataType>
void Chebyshev1HighPassCoefficients<DataType>::set_cut_frequency(DataType cut_frequency)
{
this->cut_frequency = cut_frequency;
setup();
}
template <typename DataType>
typename Chebyshev1HighPassCoefficients<DataType>::DataType Chebyshev1HighPassCoefficients<DataType>::get_cut_frequency() const
{
return cut_frequency;
}
template <typename DataType>
void Chebyshev1HighPassCoefficients<DataType>::set_ripple(DataType ripple)
{
this->ripple = ripple;
setup();
}
template <typename DataType>
typename Chebyshev1HighPassCoefficients<DataType>::DataType Chebyshev1HighPassCoefficients<DataType>::get_ripple() const
{
return ripple;
}
template <typename DataType>
void Chebyshev1HighPassCoefficients<DataType>::set_order(int order)
{
in_order = out_order = order;
setup();
}
template <typename DataType>
void Chebyshev1HighPassCoefficients<DataType>::setup()
{
Parent::setup();
coefficients_in.assign(in_order+1, 0);
coefficients_out.assign(out_order, 0);
create_default_chebyshev1_coeffs(in_order, ripple, (input_sampling_rate - 2 * cut_frequency) / input_sampling_rate, coefficients_in, coefficients_out);
for(int i = in_order - 1; i >= 0; i -= 2)
{
coefficients_in[i] = - coefficients_in[i];
coefficients_out[i] = - coefficients_out[i];
}
}
template <typename DataType>
Chebyshev1BandPassCoefficients<DataType>::Chebyshev1BandPassCoefficients()
:Parent(1, 1), cut_frequencies(0, 0), ripple(0), in_order(1), out_order(1)
{
}
template <typename DataType>
void Chebyshev1BandPassCoefficients<DataType>::set_cut_frequencies(std::pair<DataType, DataType> cut_frequencies)
{
this->cut_frequencies = cut_frequencies;
setup();
}
template <typename DataType>
void Chebyshev1BandPassCoefficients<DataType>::set_cut_frequencies(DataType f0, DataType f1)
{
this->cut_frequencies = std::make_pair(f0, f1);
setup();
}
template <typename DataType>
std::pair<typename Chebyshev1BandPassCoefficients<DataType>::DataType, typename Chebyshev1BandPassCoefficients<DataType>::DataType> Chebyshev1BandPassCoefficients<DataType>::get_cut_frequencies() const
{
return cut_frequencies;
}
template <typename DataType>
void Chebyshev1BandPassCoefficients<DataType>::set_ripple(DataType ripple)
{
this->ripple = ripple;
setup();
}
template <typename DataType>
typename Chebyshev1BandPassCoefficients<DataType>::DataType Chebyshev1BandPassCoefficients<DataType>::get_ripple() const
{
return ripple;
}
template <typename DataType>
void Chebyshev1BandPassCoefficients<DataType>::set_order(int order)
{
in_order = out_order = 2 * order;
setup();
}
template <typename DataType>
void Chebyshev1BandPassCoefficients<DataType>::setup()
{
Parent::setup();
coefficients_in.assign(in_order+1, 0);
coefficients_out.assign(out_order, 0);
create_bp_chebyshev1_coeffs(in_order, ripple, 2 * cut_frequencies.first / input_sampling_rate, 2 * cut_frequencies.second / input_sampling_rate, coefficients_in, coefficients_out);
}
template <typename DataType>
Chebyshev1BandStopCoefficients<DataType>::Chebyshev1BandStopCoefficients()
:Parent(1, 1), cut_frequencies(0, 0), ripple(0), in_order(1), out_order(1)
{
}
template <typename DataType>
void Chebyshev1BandStopCoefficients<DataType>::set_cut_frequencies(std::pair<DataType, DataType> cut_frequencies)
{
this->cut_frequencies = cut_frequencies;
setup();
}
template <typename DataType>
void Chebyshev1BandStopCoefficients<DataType>::set_cut_frequencies(DataType f0, DataType f1)
{
this->cut_frequencies = std::make_pair(f0, f1);
setup();
}
template <typename DataType>
std::pair<typename Chebyshev1BandStopCoefficients<DataType>::DataType, typename Chebyshev1BandStopCoefficients<DataType>::DataType> Chebyshev1BandStopCoefficients<DataType>::get_cut_frequencies() const
{
return cut_frequencies;
}
template <typename DataType>
void Chebyshev1BandStopCoefficients<DataType>::set_ripple(DataType ripple)
{
this->ripple = ripple;
setup();
}
template <typename DataType>
typename Chebyshev1BandStopCoefficients<DataType>::DataType Chebyshev1BandStopCoefficients<DataType>::get_ripple() const
{
return ripple;
}
template <typename DataType>
void Chebyshev1BandStopCoefficients<DataType>::set_order(int order)
{
in_order = out_order = 2 * order;
setup();
}
template <typename DataType>
void Chebyshev1BandStopCoefficients<DataType>::setup()
{
Parent::setup();
coefficients_in.assign(in_order+1, 0);
coefficients_out.assign(out_order, 0);
create_bs_chebyshev1_coeffs(in_order, ripple, 2 * cut_frequencies.first / input_sampling_rate, 2 * cut_frequencies.second / input_sampling_rate, coefficients_in, coefficients_out);
}
template class Chebyshev1LowPassCoefficients<float>;
template class Chebyshev1LowPassCoefficients<double>;
template class Chebyshev1HighPassCoefficients<float>;
template class Chebyshev1HighPassCoefficients<double>;
template class Chebyshev1BandPassCoefficients<float>;
template class Chebyshev1BandPassCoefficients<double>;
template class Chebyshev1BandStopCoefficients<float>;
template class Chebyshev1BandStopCoefficients<double>;
template class IIRFilter<Chebyshev1LowPassCoefficients<float> >;
template class IIRFilter<Chebyshev1LowPassCoefficients<double> >;
template class IIRFilter<Chebyshev1HighPassCoefficients<float> >;
template class IIRFilter<Chebyshev1HighPassCoefficients<double> >;
template class IIRFilter<Chebyshev1BandPassCoefficients<float> >;
template class IIRFilter<Chebyshev1BandPassCoefficients<double> >;
template class IIRFilter<Chebyshev1BandStopCoefficients<float> >;
template class IIRFilter<Chebyshev1BandStopCoefficients<double> >;
}
<commit_msg>Fixing Chebyshev type 1 setup<commit_after>/**
* \file Chebyshev1Filter.cpp
*/
#include <boost/math/special_functions/asinh.hpp>
#include "Chebyshev1Filter.h"
#include "IIRFilter.h"
namespace
{
template<typename DataType>
void create_chebyshev1_analog_coefficients(int order, DataType ripple, std::vector<std::complex<DataType> >& z, std::vector<std::complex<DataType> >& p, DataType& k)
{
z.clear(); // no zeros for this filter type
p.clear();
if(ripple == 0)
{
return;
}
if(order == 0)
{
k = std::pow(10, (-ripple / 20));
return;
}
DataType eps = std::sqrt(std::pow(10, (0.1 * ripple)) - 1.0);
DataType mu = 1.0 / order * boost::math::asinh(1 / eps);
for(int i = -order+1; i < order; i += 2)
{
DataType theta = boost::math::constants::pi<DataType>() * i / (2*order);
p.push_back(-std::sinh(std::complex<DataType>(mu, theta)));
}
std::complex<DataType> f = 1;
for(int i = 0; i < p.size(); ++i)
{
f *= -p[i];
}
k = f.real();
if(order % 2 == 0)
{
k = k / std::sqrt((1 + eps * eps));
}
}
template<typename DataType>
void create_default_chebyshev1_coeffs(int order, DataType ripple, DataType Wn, std::vector<DataType>& coefficients_in, std::vector<DataType>& coefficients_out)
{
std::vector<std::complex<DataType> > z;
std::vector<std::complex<DataType> > p;
DataType k;
int fs = 2;
create_chebyshev1_analog_coefficients(order, ripple, z, p, k);
DataType warped = 2 * fs * std::tan(boost::math::constants::pi<DataType>() * Wn / fs);
zpk_lp2lp(warped, z, p, k);
zpk_bilinear(fs, z, p, k);
boost::math::tools::polynomial<DataType> b;
boost::math::tools::polynomial<DataType> a;
zpk2ba(fs, z, p, k, b, a);
for(int i = 0; i < order + 1; ++i)
{
coefficients_in[i] = b[i];
}
for(int i = 0; i < order; ++i)
{
coefficients_out[i] = -a[i];
}
}
template<typename DataType>
void create_bp_chebyshev1_coeffs(int order, DataType ripple, DataType wc1, DataType wc2, std::vector<DataType>& coefficients_in, std::vector<DataType>& coefficients_out)
{
std::vector<std::complex<DataType> > z;
std::vector<std::complex<DataType> > p;
DataType k;
int fs = 2;
create_chebyshev1_analog_coefficients(order/2, ripple, z, p, k);
wc1 = 2 * fs * std::tan(boost::math::constants::pi<DataType>() * wc1 / fs);
wc2 = 2 * fs * std::tan(boost::math::constants::pi<DataType>() * wc2 / fs);
zpk_lp2bp(std::sqrt(wc1 * wc2), wc2 - wc1, z, p, k);
zpk_bilinear(fs, z, p, k);
boost::math::tools::polynomial<DataType> b;
boost::math::tools::polynomial<DataType> a;
zpk2ba(fs, z, p, k, b, a);
for(int i = 0; i < order + 1; ++i)
{
coefficients_in[i] = b[i];
}
for(int i = 0; i < order; ++i)
{
coefficients_out[i] = -a[i];
}
}
template<typename DataType>
void create_bs_chebyshev1_coeffs(int order, DataType ripple, DataType wc1, DataType wc2, std::vector<DataType>& coefficients_in, std::vector<DataType>& coefficients_out)
{
std::vector<std::complex<DataType> > z;
std::vector<std::complex<DataType> > p;
DataType k;
int fs = 2;
create_chebyshev1_analog_coefficients(order/2, ripple, z, p, k);
wc1 = 2 * fs * std::tan(boost::math::constants::pi<DataType>() * wc1 / fs);
wc2 = 2 * fs * std::tan(boost::math::constants::pi<DataType>() * wc2 / fs);
zpk_lp2bs(std::sqrt(wc1 * wc2), wc2 - wc1, z, p, k);
zpk_bilinear(fs, z, p, k);
boost::math::tools::polynomial<DataType> b;
boost::math::tools::polynomial<DataType> a;
zpk2ba(fs, z, p, k, b, a);
for(int i = 0; i < order + 1; ++i)
{
coefficients_in[i] = b[i];
}
for(int i = 0; i < order; ++i)
{
coefficients_out[i] = -a[i];
}
}
}
namespace ATK
{
template <typename DataType>
Chebyshev1LowPassCoefficients<DataType>::Chebyshev1LowPassCoefficients()
:Parent(1, 1), cut_frequency(0), ripple(0), in_order(1), out_order(1)
{
}
template <typename DataType>
void Chebyshev1LowPassCoefficients<DataType>::set_ripple(DataType ripple)
{
this->ripple = ripple;
setup();
}
template <typename DataType>
typename Chebyshev1LowPassCoefficients<DataType>::DataType Chebyshev1LowPassCoefficients<DataType>::get_ripple() const
{
return ripple;
}
template <typename DataType>
void Chebyshev1LowPassCoefficients<DataType>::set_cut_frequency(DataType cut_frequency)
{
this->cut_frequency = cut_frequency;
setup();
}
template <typename DataType>
typename Chebyshev1LowPassCoefficients<DataType>::DataType Chebyshev1LowPassCoefficients<DataType>::get_cut_frequency() const
{
return cut_frequency;
}
template <typename DataType>
void Chebyshev1LowPassCoefficients<DataType>::set_order(int order)
{
in_order = out_order = order;
setup();
}
template <typename DataType>
void Chebyshev1LowPassCoefficients<DataType>::setup()
{
Parent::setup();
coefficients_in.assign(in_order+1, 0);
coefficients_out.assign(out_order, 0);
create_default_chebyshev1_coeffs(in_order, ripple, 2 * cut_frequency / input_sampling_rate, coefficients_in, coefficients_out);
}
template <typename DataType>
Chebyshev1HighPassCoefficients<DataType>::Chebyshev1HighPassCoefficients()
:Parent(1, 1), cut_frequency(0), ripple(0), in_order(1), out_order(1)
{
}
template <typename DataType>
void Chebyshev1HighPassCoefficients<DataType>::set_cut_frequency(DataType cut_frequency)
{
this->cut_frequency = cut_frequency;
setup();
}
template <typename DataType>
typename Chebyshev1HighPassCoefficients<DataType>::DataType Chebyshev1HighPassCoefficients<DataType>::get_cut_frequency() const
{
return cut_frequency;
}
template <typename DataType>
void Chebyshev1HighPassCoefficients<DataType>::set_ripple(DataType ripple)
{
this->ripple = ripple;
setup();
}
template <typename DataType>
typename Chebyshev1HighPassCoefficients<DataType>::DataType Chebyshev1HighPassCoefficients<DataType>::get_ripple() const
{
return ripple;
}
template <typename DataType>
void Chebyshev1HighPassCoefficients<DataType>::set_order(int order)
{
in_order = out_order = order;
setup();
}
template <typename DataType>
void Chebyshev1HighPassCoefficients<DataType>::setup()
{
Parent::setup();
coefficients_in.assign(in_order+1, 0);
coefficients_out.assign(out_order, 0);
create_default_chebyshev1_coeffs(in_order, ripple, (input_sampling_rate - 2 * cut_frequency) / input_sampling_rate, coefficients_in, coefficients_out);
for(int i = in_order - 1; i >= 0; i -= 2)
{
coefficients_in[i] = - coefficients_in[i];
coefficients_out[i] = - coefficients_out[i];
}
}
template <typename DataType>
Chebyshev1BandPassCoefficients<DataType>::Chebyshev1BandPassCoefficients()
:Parent(1, 1), cut_frequencies(0, 0), ripple(0), in_order(1), out_order(1)
{
}
template <typename DataType>
void Chebyshev1BandPassCoefficients<DataType>::set_cut_frequencies(std::pair<DataType, DataType> cut_frequencies)
{
this->cut_frequencies = cut_frequencies;
setup();
}
template <typename DataType>
void Chebyshev1BandPassCoefficients<DataType>::set_cut_frequencies(DataType f0, DataType f1)
{
this->cut_frequencies = std::make_pair(f0, f1);
setup();
}
template <typename DataType>
std::pair<typename Chebyshev1BandPassCoefficients<DataType>::DataType, typename Chebyshev1BandPassCoefficients<DataType>::DataType> Chebyshev1BandPassCoefficients<DataType>::get_cut_frequencies() const
{
return cut_frequencies;
}
template <typename DataType>
void Chebyshev1BandPassCoefficients<DataType>::set_ripple(DataType ripple)
{
this->ripple = ripple;
setup();
}
template <typename DataType>
typename Chebyshev1BandPassCoefficients<DataType>::DataType Chebyshev1BandPassCoefficients<DataType>::get_ripple() const
{
return ripple;
}
template <typename DataType>
void Chebyshev1BandPassCoefficients<DataType>::set_order(int order)
{
in_order = out_order = 2 * order;
setup();
}
template <typename DataType>
void Chebyshev1BandPassCoefficients<DataType>::setup()
{
Parent::setup();
coefficients_in.assign(in_order+1, 0);
coefficients_out.assign(out_order, 0);
create_bp_chebyshev1_coeffs(in_order, ripple, 2 * cut_frequencies.first / input_sampling_rate, 2 * cut_frequencies.second / input_sampling_rate, coefficients_in, coefficients_out);
}
template <typename DataType>
Chebyshev1BandStopCoefficients<DataType>::Chebyshev1BandStopCoefficients()
:Parent(1, 1), cut_frequencies(0, 0), ripple(0), in_order(1), out_order(1)
{
}
template <typename DataType>
void Chebyshev1BandStopCoefficients<DataType>::set_cut_frequencies(std::pair<DataType, DataType> cut_frequencies)
{
this->cut_frequencies = cut_frequencies;
setup();
}
template <typename DataType>
void Chebyshev1BandStopCoefficients<DataType>::set_cut_frequencies(DataType f0, DataType f1)
{
this->cut_frequencies = std::make_pair(f0, f1);
setup();
}
template <typename DataType>
std::pair<typename Chebyshev1BandStopCoefficients<DataType>::DataType, typename Chebyshev1BandStopCoefficients<DataType>::DataType> Chebyshev1BandStopCoefficients<DataType>::get_cut_frequencies() const
{
return cut_frequencies;
}
template <typename DataType>
void Chebyshev1BandStopCoefficients<DataType>::set_ripple(DataType ripple)
{
this->ripple = ripple;
setup();
}
template <typename DataType>
typename Chebyshev1BandStopCoefficients<DataType>::DataType Chebyshev1BandStopCoefficients<DataType>::get_ripple() const
{
return ripple;
}
template <typename DataType>
void Chebyshev1BandStopCoefficients<DataType>::set_order(int order)
{
in_order = out_order = 2 * order;
setup();
}
template <typename DataType>
void Chebyshev1BandStopCoefficients<DataType>::setup()
{
Parent::setup();
coefficients_in.assign(in_order+1, 0);
coefficients_out.assign(out_order, 0);
create_bs_chebyshev1_coeffs(in_order, ripple, 2 * cut_frequencies.first / input_sampling_rate, 2 * cut_frequencies.second / input_sampling_rate, coefficients_in, coefficients_out);
}
template class Chebyshev1LowPassCoefficients<float>;
template class Chebyshev1LowPassCoefficients<double>;
template class Chebyshev1HighPassCoefficients<float>;
template class Chebyshev1HighPassCoefficients<double>;
template class Chebyshev1BandPassCoefficients<float>;
template class Chebyshev1BandPassCoefficients<double>;
template class Chebyshev1BandStopCoefficients<float>;
template class Chebyshev1BandStopCoefficients<double>;
template class IIRFilter<Chebyshev1LowPassCoefficients<float> >;
template class IIRFilter<Chebyshev1LowPassCoefficients<double> >;
template class IIRFilter<Chebyshev1HighPassCoefficients<float> >;
template class IIRFilter<Chebyshev1HighPassCoefficients<double> >;
template class IIRFilter<Chebyshev1BandPassCoefficients<float> >;
template class IIRFilter<Chebyshev1BandPassCoefficients<double> >;
template class IIRFilter<Chebyshev1BandStopCoefficients<float> >;
template class IIRFilter<Chebyshev1BandStopCoefficients<double> >;
}
<|endoftext|> |
<commit_before>#pragma once
#include <archive.h>
#include "../stream/stream.hh"
#include "../stream/buffer.hh"
#include "../non-copyable.hh"
#include "entry.hh"
namespace mimosa
{
namespace archive
{
class Reader : public stream::Stream
{
public:
MIMOSA_DEF_PTR(Reader);
inline Reader() : archive_(archive_read_new()) {}
inline ~Reader() { archive_read_free(archive_); }
inline operator struct ::archive *() const { return archive_; }
int open(stream::Stream::Ptr input);
int nextHeader(Entry &e);
int64_t read(char *data, uint64_t nbytes) override;
int64_t write(const char *data, uint64_t nbytes) override;
//////////////
/// Filter ///
//////////////
inline int filterBzip2() { return archive_read_support_filter_bzip2(archive_); }
inline int filterCompress() { return archive_read_support_filter_compress(archive_); }
inline int filterGzip() { return archive_read_support_filter_gzip(archive_); }
inline int filterLrzip() { return archive_read_support_filter_lrzip(archive_); }
inline int filterLzip() { return archive_read_support_filter_lzip(archive_); }
inline int filterLzma() { return archive_read_support_filter_lzma(archive_); }
inline int filterLzop() { return archive_read_support_filter_lzop(archive_); }
inline int filterNone() { return archive_read_support_filter_none(archive_); }
inline int filterProgram(const std::string & cmd) {
return archive_read_support_filter_program(archive_, cmd.c_str());
}
inline int filterXz() { return archive_read_support_filter_xz(archive_); }
//////////////
/// Format ///
//////////////
inline int format7zip() { return archive_read_support_format_7zip(archive_); }
inline int formatAr() { return archive_read_support_format_ar(archive_); }
inline int formatCpio() { return archive_read_support_format_cpio(archive_); }
inline int formatGnutar() { return archive_read_support_format_gnutar(archive_); }
inline int formatIso9660() { return archive_read_support_format_iso9660(archive_); }
inline int formatMtree() { return archive_read_support_format_mtree(archive_); }
inline int formatTar() { return archive_read_support_format_tar(archive_); }
inline int formatXar() { return archive_read_support_format_xar(archive_); }
inline int formatZip() { return archive_read_support_format_zip(archive_); }
private:
static int openCb(struct archive *, void *_client_data);
static ssize_t readCb(struct archive *,
void *_client_data, const void **_buffer);
static int closeCb(struct archive *, void *_client_data);
void close() { archive_read_close(archive_); }
struct ::archive *archive_;
stream::Stream::Ptr stream_;
stream::Buffer::Ptr buffer_;
};
}
}
<commit_msg>Fix warning<commit_after>#pragma once
#include <archive.h>
#include "../stream/stream.hh"
#include "../stream/buffer.hh"
#include "../non-copyable.hh"
#include "entry.hh"
namespace mimosa
{
namespace archive
{
class Reader : public stream::Stream
{
public:
MIMOSA_DEF_PTR(Reader);
inline Reader() : archive_(archive_read_new()) {}
inline ~Reader() { archive_read_free(archive_); }
inline operator struct ::archive *() const { return archive_; }
int open(stream::Stream::Ptr input);
int nextHeader(Entry &e);
int64_t read(char *data, uint64_t nbytes) override;
int64_t write(const char *data, uint64_t nbytes) override;
//////////////
/// Filter ///
//////////////
inline int filterBzip2() { return archive_read_support_filter_bzip2(archive_); }
inline int filterCompress() { return archive_read_support_filter_compress(archive_); }
inline int filterGzip() { return archive_read_support_filter_gzip(archive_); }
inline int filterLrzip() { return archive_read_support_filter_lrzip(archive_); }
inline int filterLzip() { return archive_read_support_filter_lzip(archive_); }
inline int filterLzma() { return archive_read_support_filter_lzma(archive_); }
inline int filterLzop() { return archive_read_support_filter_lzop(archive_); }
inline int filterNone() { return archive_read_support_filter_none(archive_); }
inline int filterProgram(const std::string & cmd) {
return archive_read_support_filter_program(archive_, cmd.c_str());
}
inline int filterXz() { return archive_read_support_filter_xz(archive_); }
//////////////
/// Format ///
//////////////
inline int format7zip() { return archive_read_support_format_7zip(archive_); }
inline int formatAr() { return archive_read_support_format_ar(archive_); }
inline int formatCpio() { return archive_read_support_format_cpio(archive_); }
inline int formatGnutar() { return archive_read_support_format_gnutar(archive_); }
inline int formatIso9660() { return archive_read_support_format_iso9660(archive_); }
inline int formatMtree() { return archive_read_support_format_mtree(archive_); }
inline int formatTar() { return archive_read_support_format_tar(archive_); }
inline int formatXar() { return archive_read_support_format_xar(archive_); }
inline int formatZip() { return archive_read_support_format_zip(archive_); }
private:
static int openCb(struct archive *, void *_client_data);
static ssize_t readCb(struct archive *,
void *_client_data, const void **_buffer);
static int closeCb(struct archive *, void *_client_data);
void close() override { archive_read_close(archive_); }
struct ::archive *archive_;
stream::Stream::Ptr stream_;
stream::Buffer::Ptr buffer_;
};
}
}
<|endoftext|> |
<commit_before>/*
* Copyright 2017 The Imaging Source Europe GmbH
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include "Archive.h"
#include "lib/7z/7zCrc.h"
// gcc only offers a full c++11 implementation with >= v5.1
// codecvt for unicode conversions is not always available
// thus use iconv in such cases
#include <features.h>
#if __GNUC_PREREQ(5,1)
#include <codecvt>
#else
#include <iconv.h>
#endif
#include <string>
#include <locale>
#include <stdexcept>
#include <memory>
namespace lib33u
{
namespace util
{
namespace sz
{
struct DefaultAlloc : public ISzAlloc
{
DefaultAlloc()
{
Alloc = SzAlloc;
Free = SzFree;
}
};
struct TempAlloc : public ISzAlloc
{
TempAlloc()
{
Alloc = SzAllocTemp;
Free = SzFreeTemp;
}
};
int SzCrcGenerateTableOnce()
{
CrcGenerateTable();
return 0;
}
Archive::Data::Data( const std::string& fn )
{
// static int x = SzCrcGenerateTableOnce();
auto wres = InFile_Open( &archive_stream_.file, fn.c_str() );
if( wres )
{
throw std::runtime_error( "Unable to open archive file" );
}
FileInStream_CreateVTable( &archive_stream_ );
LookToRead_CreateVTable( &look_stream_, False );
look_stream_.realStream = &archive_stream_.s;
LookToRead_Init( &look_stream_ );
SzArEx_Init( &db_ );
DefaultAlloc default_alloc_;
TempAlloc temp_alloc_;
auto sres = SzArEx_Open(&db_, &look_stream_.s,
&default_alloc_, &temp_alloc_);
if( sres )
{
throw std::runtime_error( "Failed to open archive" );
}
struct ArchiveBuffer
{
UInt32 block_index_ = 0xFFFFFFFF;
Byte* out_buffer_ = nullptr;
size_t out_buffer_size_ = 0;
~ArchiveBuffer()
{
DefaultAlloc default_alloc;
IAlloc_Free( &default_alloc, out_buffer_ );
}
};
#ifdef __linux__
typedef std::u16string utf16string;
#else
typedef std::wstring utf16string;
#endif
utf16string utf16name;
auto buffer = std::make_shared<ArchiveBuffer>();
for( unsigned i = 0; i < db_.NumFiles; ++i )
{
size_t len = SzArEx_GetFileNameUtf16( &db_, i, nullptr );
utf16name.resize(len);
SzArEx_GetFileNameUtf16( &db_, i, (UInt16*)utf16name.data() );
#if __GNUC_PREREQ(5,1)
std::wstring_convert<std::codecvt_utf8_utf16<utf16string::value_type>,
utf16string::value_type> conversion;
std::string utf8name = conversion.to_bytes( utf16name );
#else
iconv_t ico = iconv_open("UTF8", "UTF16");
size_t out_size = 1024;
char buf [out_size];
char* tmp = buf;
const char16_t* tmp16 = utf16name.data();
size_t in_size = len*2;
size_t ret = iconv(ico, (char**)&tmp16, &in_size, &tmp, &out_size);
std::string utf8name(buf);
iconv_close(ico);
#endif
while( utf8name.back() == '\0' )
utf8name.pop_back();
size_t offset = 0;
size_t outSizeProcessed = 0;
sres = SzArEx_Extract(&db_, &look_stream_.s, i,
&buffer->block_index_,
&buffer->out_buffer_,
&buffer->out_buffer_size_,
&offset,
&outSizeProcessed,
&default_alloc_,
&temp_alloc_ );
// file_index_.try_emplace( utf8name, std::shared_ptr<uint8_t>( buffer, buffer->out_buffer_ + offset ), outSizeProcessed );
file_index_.emplace(utf8name,
Entry(std::shared_ptr<uint8_t>(buffer, buffer->out_buffer_ + offset),
outSizeProcessed ));
}
}
Archive::Entry Archive::Data::read (const std::string& fn) const
{
auto it = file_index_.find(fn);
if (it == file_index_.end())
{
throw std::runtime_error("Entry not found");
}
return it->second;
}
Archive::Archive (const std::string& fn)
: data { std::unique_ptr<Data>(new Data(fn)) }
{
}
Archive Archive::open (const std::string& fn)
{
return Archive( fn );
}
Archive::Entry Archive::read (const std::string& fn) const
{
return data->read( fn );
}
} /* namespace sz */
} /* namespace util */
} /* namespace lib33u */
<commit_msg>Fix segfault in firmware-update for 33u cameras<commit_after>/*
* Copyright 2017 The Imaging Source Europe GmbH
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include "Archive.h"
#include "lib/7z/7zCrc.h"
// gcc only offers a full c++11 implementation with >= v5.1
// codecvt for unicode conversions is not always available
// thus use iconv in such cases
#include <features.h>
#if __GNUC_PREREQ(5,1)
#include <codecvt>
#else
#include <iconv.h>
#endif
#include <string>
#include <locale>
#include <stdexcept>
#include <memory>
namespace lib33u
{
namespace util
{
namespace sz
{
struct DefaultAlloc : public ISzAlloc
{
DefaultAlloc()
{
Alloc = SzAlloc;
Free = SzFree;
}
};
struct TempAlloc : public ISzAlloc
{
TempAlloc()
{
Alloc = SzAllocTemp;
Free = SzFreeTemp;
}
};
int SzCrcGenerateTableOnce()
{
CrcGenerateTable();
return 0;
}
Archive::Data::Data( const std::string& fn )
{
SzCrcGenerateTableOnce();
auto wres = InFile_Open( &archive_stream_.file, fn.c_str() );
if( wres )
{
throw std::runtime_error( "Unable to open archive file" );
}
FileInStream_CreateVTable( &archive_stream_ );
LookToRead_CreateVTable( &look_stream_, False );
look_stream_.realStream = &archive_stream_.s;
LookToRead_Init( &look_stream_ );
SzArEx_Init( &db_ );
DefaultAlloc default_alloc_;
TempAlloc temp_alloc_;
auto sres = SzArEx_Open(&db_, &look_stream_.s,
&default_alloc_, &temp_alloc_);
if( sres )
{
throw std::runtime_error( "Failed to open archive" );
}
struct ArchiveBuffer
{
UInt32 block_index_ = 0xFFFFFFFF;
Byte* out_buffer_ = nullptr;
size_t out_buffer_size_ = 0;
~ArchiveBuffer()
{
DefaultAlloc default_alloc;
IAlloc_Free( &default_alloc, out_buffer_ );
}
};
#ifdef __linux__
typedef std::u16string utf16string;
#else
typedef std::wstring utf16string;
#endif
utf16string utf16name;
auto buffer = std::make_shared<ArchiveBuffer>();
for( unsigned i = 0; i < db_.NumFiles; ++i )
{
size_t len = SzArEx_GetFileNameUtf16( &db_, i, nullptr );
utf16name.resize(len);
SzArEx_GetFileNameUtf16( &db_, i, (UInt16*)utf16name.data() );
#if __GNUC_PREREQ(5,1)
std::wstring_convert<std::codecvt_utf8_utf16<utf16string::value_type>,
utf16string::value_type> conversion;
std::string utf8name = conversion.to_bytes( utf16name );
#else
iconv_t ico = iconv_open("UTF8", "UTF16");
size_t out_size = 1024;
char buf [out_size];
char* tmp = buf;
const char16_t* tmp16 = utf16name.data();
size_t in_size = len*2;
size_t ret = iconv(ico, (char**)&tmp16, &in_size, &tmp, &out_size);
std::string utf8name(buf);
iconv_close(ico);
#endif
while( utf8name.back() == '\0' )
utf8name.pop_back();
size_t offset = 0;
size_t outSizeProcessed = 0;
sres = SzArEx_Extract(&db_, &look_stream_.s, i,
&buffer->block_index_,
&buffer->out_buffer_,
&buffer->out_buffer_size_,
&offset,
&outSizeProcessed,
&default_alloc_,
&temp_alloc_ );
// file_index_.try_emplace( utf8name, std::shared_ptr<uint8_t>( buffer, buffer->out_buffer_ + offset ), outSizeProcessed );
file_index_.emplace(utf8name,
Entry(std::shared_ptr<uint8_t>(buffer, buffer->out_buffer_ + offset),
outSizeProcessed ));
}
}
Archive::Entry Archive::Data::read (const std::string& fn) const
{
auto it = file_index_.find(fn);
if (it == file_index_.end())
{
throw std::runtime_error("Entry not found");
}
return it->second;
}
Archive::Archive (const std::string& fn)
: data { std::unique_ptr<Data>(new Data(fn)) }
{
}
Archive Archive::open (const std::string& fn)
{
return Archive( fn );
}
Archive::Entry Archive::read (const std::string& fn) const
{
return data->read( fn );
}
} /* namespace sz */
} /* namespace util */
} /* namespace lib33u */
<|endoftext|> |
<commit_before>#include "boid.h"
/**
* @brief Create a new boid
*
* Creates a new QQmlComponent using the main QQmlApplicationEngine of the program and
* the Boid.qml file.
* After the component is created and ready, the QObject is created and parented to the
* canvas object.
* Lastly we set the position randomly, but staying within the boundaries.
*/
Boid::Boid() {
component = new QQmlComponent(getEngine(), QUrl(QStringLiteral("qrc:/Boid.qml")));
if(component->status() == component->Ready) {
object = component->create(getEngine()->rootContext());
object->setProperty("parent", QVariant::fromValue(getCanvas()));
QQmlEngine::setObjectOwnership(object, QQmlEngine::CppOwnership);
}
else
qDebug() << component->errorString();
setY(50 + ((double)rand()/(double)(RAND_MAX)) * (getCanvasHeight() - 100));
setX(50 + ((double)rand()/(double)(RAND_MAX)) * (getCanvasWidth() - 100));
lastVel = Vector2();
}
Boid::~Boid() {
delete component;
delete object;
}
/**
* @brief Boid logic
*/
void Boid::update(){
Vector2 v1 = Vector2();
Vector2 v2 = Vector2();
Vector2 v3 = Vector2();
Vector2 v4 = Vector2();
Vector2 center = Vector2();
// Rule1: move to local center of mass ( center becomes average of surrounding boids)
for(int i = 0; i < 3; i++){
center = center + neighbours[i].position2;
}
center /= 3;
v1 = center - position;
// Rule2: Avoidance : if distance to next boid smaller than threshold T boid changes course.
center = Vector2();
for(int i = 0; i < 3; i++){
if ((neighbours[i].position2 - position).getSqrMagnitude() < (getSize() + 10.0) * (getSize() + 10.0)){
center = center - (neighbours[i].position2 - position);
}
}
v2 = center;
// Rule3: Match velocity to surrounding Boids
for(int i = 0; i < 3; i++){
v3 = v3 + neighbours[i].velocity2;
}
v3 = v3/3;
// Rule 4: Follow mouse position
Vector2 mp = getMousePosition();
if(!(mp == Vector2(0, 0))) {
if((mp - position).getSqrMagnitude() > 7500)
v4 = mp - position;
}
// Rule 5: Stray away from the boundaries
Vector2 v5 = Vector2();
if(position.getX() < 80)
v5.setX(1);
else if(position.getX() >= getCanvasWidth() - 80)
v5.setX(-1);
if(position.getY() < 80)
v5.setY(1);
else if(position.getY() >= getCanvasHeight() - 80){
v5.setY(-1);
}
//Replace position with mouse position and look through the force-parameter with the mouse
double power = 0.0;
double power2 = 0.0;
if(position.getX() < 80)
power = 100 - position.getX();
else if(position.getX() >= getCanvasWidth() - 80)
power = 100 + position.getX() - getCanvasWidth() ;
else if(position.getY() < 80)
power2 = 100 - position.getY();
else if(position.getY() >= getCanvasHeight() - 80)
power2 = 100 + position.getY() - getCanvasHeight();
double force = 10*exp((power+ power2) *0.05);
//qDebug << force;
velocity = Vector2::lerp(lastVel,
velocity + v1.normalize()*getFlockingFactor() + v2.normalize()*getAvoidanceFactor() +
v3.normalize()*getVelocityMatchFactor() + v4.normalize()*getTargetFactor() + v5 * force,
0.016f);
lastVel = velocity;
}
<commit_msg>Tweak threshold and function.<commit_after>#include "boid.h"
/**
* @brief Create a new boid
*
* Creates a new QQmlComponent using the main QQmlApplicationEngine of the program and
* the Boid.qml file.
* After the component is created and ready, the QObject is created and parented to the
* canvas object.
* Lastly we set the position randomly, but staying within the boundaries.
*/
Boid::Boid() {
component = new QQmlComponent(getEngine(), QUrl(QStringLiteral("qrc:/Boid.qml")));
if(component->status() == component->Ready) {
object = component->create(getEngine()->rootContext());
object->setProperty("parent", QVariant::fromValue(getCanvas()));
QQmlEngine::setObjectOwnership(object, QQmlEngine::CppOwnership);
}
else
qDebug() << component->errorString();
setY(50 + ((double)rand()/(double)(RAND_MAX)) * (getCanvasHeight() - 100));
setX(50 + ((double)rand()/(double)(RAND_MAX)) * (getCanvasWidth() - 100));
lastVel = Vector2();
}
Boid::~Boid() {
delete component;
delete object;
}
/**
* @brief Boid logic
*/
void Boid::update(){
Vector2 v1 = Vector2();
Vector2 v2 = Vector2();
Vector2 v3 = Vector2();
Vector2 v4 = Vector2();
Vector2 center = Vector2();
// Rule1: move to local center of mass ( center becomes average of surrounding boids)
for(int i = 0; i < 3; i++){
center = center + neighbours[i].position2;
}
center /= 3;
v1 = center - position;
// Rule2: Avoidance : if distance to next boid smaller than threshold T boid changes course.
center = Vector2();
for(int i = 0; i < 3; i++){
if ((neighbours[i].position2 - position).getSqrMagnitude() < (getSize() + 10.0) * (getSize() + 10.0)){
center = center - (neighbours[i].position2 - position);
}
}
v2 = center;
// Rule3: Match velocity to surrounding Boids
for(int i = 0; i < 3; i++){
v3 = v3 + neighbours[i].velocity2;
}
v3 = v3/3;
// Rule 4: Follow mouse position
Vector2 mp = getMousePosition();
if(!(mp == Vector2(0, 0))) {
if((mp - position).getSqrMagnitude() > 7500)
v4 = mp - position;
}
// Rule 5: Stray away from the boundaries
Vector2 v5 = Vector2();
if(position.getX() < 80)
v5.setX(1);
else if(position.getX() >= getCanvasWidth() - 80)
v5.setX(-1);
if(position.getY() < 80)
v5.setY(1);
else if(position.getY() >= getCanvasHeight() - 80){
v5.setY(-1);
}
//Replace position with mouse position and look through the force-parameter with the mouse
double power = 0.0;
double power2 = 0.0;
if(position.getX() < 150)
power = 150 - position.getX();
else if(position.getX() >= getCanvasWidth() - 150)
power = 150 + position.getX() - getCanvasWidth() ;
else if(position.getY() < 150)
power2 = 150 - position.getY();
else if(position.getY() >= getCanvasHeight() - 150)
power2 = 150 + position.getY() - getCanvasHeight();
double force = 5.0 * ((power + power2));
//qDebug << force;
velocity = Vector2::lerp(lastVel,
velocity + v1.normalize()*getFlockingFactor() + v2.normalize()*getAvoidanceFactor() +
v3.normalize()*getVelocityMatchFactor() + v4.normalize()*getTargetFactor() + v5 * force,
0.016f);
lastVel = velocity;
}
<|endoftext|> |
<commit_before>#include "aquila/source/generator/SineGenerator.h"
#include <SFML/System.hpp>
#include <SFML/Audio.hpp>
#include <algorithm>
#include <iostream>
void convertSourceToBuffer(const Aquila::SignalSource& source, sf::SoundBuffer& buffer)
{
sf::Int16* samples = new sf::Int16[source.getSamplesCount()];
std::copy(source.begin(), source.end(), samples);
buffer.LoadFromSamples(samples,
source.getSamplesCount(),
1,
static_cast<unsigned int>(source.getSampleFrequency()));
delete [] samples;
}
int main(int argc, char** argv)
{
const Aquila::FrequencyType SAMPLE_FREQUENCY = 44100;
Aquila::SineGenerator generator(SAMPLE_FREQUENCY);
generator.setFrequency(440).setAmplitude(8192).generate(2 * SAMPLE_FREQUENCY);
sf::SoundBuffer buffer;
convertSourceToBuffer(generator, buffer);
sf::Sound sound;
sound.SetBuffer(buffer);
sound.Play();
while (sound.GetStatus() == sf::Sound::Playing)
{
sf::Sleep(0.1f);
}
return 0;
}
<commit_msg>In the sfml_generator example, one can now choose signal type and frequency.<commit_after>#include "aquila/source/generator/SineGenerator.h"
#include "aquila/source/generator/SquareGenerator.h"
#include "aquila/source/generator/PinkNoiseGenerator.h"
#include "aquila/source/generator/WhiteNoiseGenerator.h"
#include <SFML/System.hpp>
#include <SFML/Audio.hpp>
#include <algorithm>
#include <iostream>
void convertSourceToBuffer(const Aquila::SignalSource& source,
sf::SoundBuffer& buffer)
{
sf::Int16* samples = new sf::Int16[source.getSamplesCount()];
std::copy(source.begin(), source.end(), samples);
buffer.LoadFromSamples(samples,
source.getSamplesCount(),
1,
static_cast<unsigned int>(source.getSampleFrequency()));
delete [] samples;
}
void handleGeneratorOptions(Aquila::Generator* generator)
{
Aquila::FrequencyType frequency, maxFrequency = generator->getSampleFrequency() / 2;
std::cout << "\nSignal frequency in Hz: \n"
"Enter a number (0-" << maxFrequency << "): ";
std::cin >> frequency;
if (frequency < 0 || frequency > maxFrequency)
{
frequency = 1000;
}
generator->setFrequency(frequency);
}
Aquila::Generator* createGenerator(unsigned int whichGenerator,
Aquila::FrequencyType sampleFrequency)
{
Aquila::Generator* generator;
switch (whichGenerator)
{
case 1:
generator = new Aquila::SineGenerator(sampleFrequency);
handleGeneratorOptions(generator);
break;
case 2:
generator = new Aquila::SquareGenerator(sampleFrequency);
handleGeneratorOptions(generator);
break;
case 3:
generator = new Aquila::PinkNoiseGenerator(sampleFrequency);
break;
case 4:
generator = new Aquila::WhiteNoiseGenerator(sampleFrequency);
break;
default:
generator = new Aquila::SineGenerator(sampleFrequency);
handleGeneratorOptions(generator);
break;
}
generator->setAmplitude(8192);
return generator;
}
int main(int argc, char** argv)
{
std::cout << "Choose which kind of signal to play: \n"
"\t 1: Sine wave \n"
"\t 2: Square wave \n"
"\t 3: Pink noise \n"
"\t 4: White noise \n"
"Enter a number (1-4): ";
unsigned int whichGenerator = 1;
std::cin >> whichGenerator;
const Aquila::FrequencyType SAMPLE_FREQUENCY = 44100;
Aquila::Generator* generator = createGenerator(whichGenerator, SAMPLE_FREQUENCY);
generator->generate(5 * SAMPLE_FREQUENCY);
sf::SoundBuffer buffer;
convertSourceToBuffer(*generator, buffer);
sf::Sound sound;
sound.SetBuffer(buffer);
sound.Play();
std::cout << "Playing..." << std::endl;
while (sound.GetStatus() == sf::Sound::Playing)
{
std::cout << ".";
sf::Sleep(0.1f);
}
std::cout << "\nFinished." << std::endl;
delete generator;
return 0;
}
<|endoftext|> |
<commit_before><commit_msg>Multipart cleanup of T3000 - 7<commit_after><|endoftext|> |
<commit_before>/**
* @file Vector.hpp
*
* Vector class.
*
* @author James Goppert <james.goppert@gmail.com>
*/
#pragma once
#include <Matrix.hpp>
namespace matrix
{
template <typename Type, size_t M, size_t N>
class Matrix;
template<typename Type, size_t M>
class Vector : public Matrix<Type, M, 1>
{
public:
virtual ~Vector() {};
Vector() : Matrix<Type, M, 1>()
{
}
Vector(const Vector<Type, M> & other) :
Matrix<Type, M, 1>(other)
{
}
Vector(const Matrix<Type, M, 1> & other) :
Matrix<Type, M, 1>(other)
{
}
inline Type operator()(size_t i) const
{
const Matrix<Type, M, 1> &v = *this;
return v(i, 0);
}
inline Type &operator()(size_t i)
{
Matrix<Type, M, 1> &v = *this;
return v(i, 0);
}
Type dot(const Vector & b) const {
const Vector &a(*this);
Type r = 0;
for (int i = 0; i<M; i++) {
r += a(i)*b(i);
}
return r;
}
Type norm() const {
const Vector &a(*this);
return Type(sqrt(a.dot(a)));
}
inline void normalize() {
(*this) /= norm();
}
/**
* Vector Operations
*/
Vector<Type, M> operator+(const Vector<Type, M> &other) const
{
Vector<Type, M> res;
const Vector<Type, M> &self = *this;
for (size_t i = 0; i < M; i++) {
res(i) = self(i) + other(i);
}
return res;
}
Vector<Type, M> operator-(const Vector<Type, M> &other) const
{
Vector<Type, M> res;
const Vector<Type, M> &self = *this;
for (size_t i = 0; i < M; i++) {
res(i) = self(i) - other(i);
}
return res;
}
void operator+=(const Vector<Type, M> &other)
{
Vector<Type, M> &self = *this;
self = self + other;
}
void operator-=(const Vector<Type, M> &other)
{
Vector<Type, M> &self = *this;
self = self - other;
}
/**
* Scalar Operations
*/
Vector<Type, M> operator*(Type scalar) const
{
Vector<Type, M> res;
const Vector<Type, M> &self = *this;
for (size_t i = 0; i < M; i++) {
res(i) = self(i) * scalar;
}
return res;
}
Vector<Type, M> operator/(Type scalar) const
{
return (*this)*(1.0/scalar);
}
Vector<Type, M> operator+(Type scalar) const
{
Vector<Type, M> res;
const Vector<Type, M> &self = *this;
for (size_t i = 0; i < M; i++) {
res(i) = self(i) + scalar;
}
return res;
}
void operator*=(Type scalar)
{
Vector<Type, M> &self = *this;
for (size_t i = 0; i < M; i++) {
self(i) = self(i) * scalar;
}
}
void operator/=(Type scalar)
{
Vector<Type, M> &self = *this;
self = self * (1.0f / scalar);
}
};
}; // namespace matrix
/* vim: set et fenc=utf-8 ff=unix sts=0 sw=4 ts=4 : */
<commit_msg>Travis fix.<commit_after>/**
* @file Vector.hpp
*
* Vector class.
*
* @author James Goppert <james.goppert@gmail.com>
*/
#pragma once
#include <Matrix.hpp>
namespace matrix
{
template <typename Type, size_t M, size_t N>
class Matrix;
template<typename Type, size_t M>
class Vector : public Matrix<Type, M, 1>
{
public:
virtual ~Vector() {};
Vector() : Matrix<Type, M, 1>()
{
}
Vector(const Vector<Type, M> & other) :
Matrix<Type, M, 1>(other)
{
}
Vector(const Matrix<Type, M, 1> & other) :
Matrix<Type, M, 1>(other)
{
}
inline Type operator()(size_t i) const
{
const Matrix<Type, M, 1> &v = *this;
return v(i, 0);
}
inline Type &operator()(size_t i)
{
Matrix<Type, M, 1> &v = *this;
return v(i, 0);
}
Type dot(const Vector & b) const {
const Vector &a(*this);
Type r = 0;
for (int i = 0; i<M; i++) {
r += a(i)*b(i);
}
return r;
}
Type norm() const {
const Vector &a(*this);
return Type(sqrt(a.dot(a)));
}
inline void normalize() {
(*this) /= norm();
}
/**
* Vector Operations
*/
Vector<Type, M> operator+(const Vector<Type, M> &other) const
{
Vector<Type, M> res;
const Vector<Type, M> &self = *this;
for (size_t i = 0; i < M; i++) {
res(i) = self(i) + other(i);
}
return res;
}
Vector<Type, M> operator-(const Vector<Type, M> &other) const
{
Vector<Type, M> res;
const Vector<Type, M> &self = *this;
for (size_t i = 0; i < M; i++) {
res(i) = self(i) - other(i);
}
return res;
}
void operator+=(const Vector<Type, M> &other)
{
Vector<Type, M> &self = *this;
self = self + other;
}
void operator-=(const Vector<Type, M> &other)
{
Vector<Type, M> &self = *this;
self = self - other;
}
/**
* Scalar Operations
*/
Vector<Type, M> operator*(Type scalar) const
{
Vector<Type, M> res;
const Vector<Type, M> &self = *this;
for (size_t i = 0; i < M; i++) {
res(i) = self(i) * scalar;
}
return res;
}
Vector<Type, M> operator/(Type scalar) const
{
return (*this)*(Type(1.0)/scalar);
}
Vector<Type, M> operator+(Type scalar) const
{
Vector<Type, M> res;
const Vector<Type, M> &self = *this;
for (size_t i = 0; i < M; i++) {
res(i) = self(i) + scalar;
}
return res;
}
void operator*=(Type scalar)
{
Vector<Type, M> &self = *this;
for (size_t i = 0; i < M; i++) {
self(i) = self(i) * scalar;
}
}
void operator/=(Type scalar)
{
Vector<Type, M> &self = *this;
self = self * (1.0f / scalar);
}
};
}; // namespace matrix
/* vim: set et fenc=utf-8 ff=unix sts=0 sw=4 ts=4 : */
<|endoftext|> |
<commit_before>/*************************************************************************
*
* $RCSfile: taskmisc.cxx,v $
*
* $Revision: 1.1.1.1 $
*
* last change: $Author: hr $ $Date: 2000-09-18 16:58:57 $
*
* 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): _______________________________________
*
*
************************************************************************/
#define _TASKBAR_CXX
#ifndef _TOOLS_LIST_HXX
#include <tools/list.hxx>
#endif
#ifndef _TOOLS_DEBUG_HXX
#include <tools/debug.hxx>
#endif
#ifndef _SV_HELP_HXX
#include <vcl/help.hxx>
#endif
#include <taskbar.hxx>
// =======================================================================
TaskButtonBar::TaskButtonBar( Window* pParent, WinBits nWinStyle ) :
ToolBox( pParent, nWinStyle | WB_3DLOOK )
{
SetAlign( WINDOWALIGN_BOTTOM );
SetButtonType( BUTTON_SYMBOLTEXT );
}
// -----------------------------------------------------------------------
TaskButtonBar::~TaskButtonBar()
{
}
// -----------------------------------------------------------------------
void TaskButtonBar::RequestHelp( const HelpEvent& rHEvt )
{
ToolBox::RequestHelp( rHEvt );
}
// =======================================================================
WindowArrange::WindowArrange()
{
mpWinList = new List;
}
// -----------------------------------------------------------------------
WindowArrange::~WindowArrange()
{
delete mpWinList;
}
// -----------------------------------------------------------------------
static USHORT ImplCeilSqareRoot( USHORT nVal )
{
USHORT i;
// Ueberlauf verhindern
if ( nVal > 0xFE * 0xFE )
return 0xFE;
for ( i=0; i*i < nVal; i++ )
{}
return i;
}
// -----------------------------------------------------------------------
static void ImplPosSizeWindow( Window* pWindow,
long nX, long nY, long nWidth, long nHeight )
{
if ( nWidth < 32 )
nWidth = 32;
if ( nHeight < 24 )
nHeight = 24;
pWindow->SetPosSizePixel( nX, nY, nWidth, nHeight );
}
// -----------------------------------------------------------------------
void WindowArrange::ImplTile( const Rectangle& rRect )
{
USHORT nCount = (USHORT)mpWinList->Count();
if ( nCount < 3 )
{
ImplVert( rRect );
return;
}
USHORT i;
USHORT j;
USHORT nCols;
USHORT nRows;
USHORT nActRows;
USHORT nOffset;
long nOverWidth;
long nOverHeight;
Window* pWindow;
long nX = rRect.Left();
long nY = rRect.Top();
long nWidth = rRect.GetWidth();
long nHeight = rRect.GetHeight();
long nRectY = nY;
long nRectWidth = nWidth;
long nRectHeight = nHeight;
long nTempWidth;
long nTempHeight;
nCols = ImplCeilSqareRoot( nCount );
nOffset = (nCols*nCols) - nCount;
if ( nOffset >= nCols )
{
nRows = nCols -1;
nOffset -= nCols;
}
else
nRows = nCols;
nWidth /= nCols;
if ( nWidth < 1 )
nWidth = 1;
nOverWidth = nRectWidth-(nWidth*nCols);
pWindow = (Window*)mpWinList->First();
for ( i = 0; i < nCols; i++ )
{
if ( i < nOffset )
nActRows = nRows - 1;
else
nActRows = nRows;
nTempWidth = nWidth;
if ( nOverWidth > 0 )
{
nTempWidth++;
nOverWidth--;
}
nHeight = nRectHeight / nActRows;
if ( nHeight < 1 )
nHeight = 1;
nOverHeight = nRectHeight-(nHeight*nActRows);
for ( j = 0; j < nActRows; j++ )
{
// Ueberhang verteilen
nTempHeight = nHeight;
if ( nOverHeight > 0 )
{
nTempHeight++;
nOverHeight--;
}
ImplPosSizeWindow( pWindow, nX, nY, nTempWidth, nTempHeight );
nY += nTempHeight;
pWindow = (Window*)mpWinList->Next();
if ( !pWindow )
break;
}
nX += nWidth;
nY = nRectY;
if ( !pWindow )
break;
}
}
// -----------------------------------------------------------------------
void WindowArrange::ImplHorz( const Rectangle& rRect )
{
long nCount = (long)mpWinList->Count();
long nX = rRect.Left();
long nY = rRect.Top();
long nWidth = rRect.GetWidth();
long nHeight = rRect.GetHeight();
long nRectHeight = nHeight;
long nOver;
long nTempHeight;
Window* pWindow;
nHeight /= nCount;
if ( nHeight < 1 )
nHeight = 1;
nOver = nRectHeight - (nCount*nHeight);
pWindow = (Window*)mpWinList->First();
while ( pWindow )
{
nTempHeight = nHeight;
if ( nOver > 0 )
{
nTempHeight++;
nOver--;
}
ImplPosSizeWindow( pWindow, nX, nY, nWidth, nTempHeight );
nY += nTempHeight;
pWindow = (Window*)mpWinList->Next();
}
}
// -----------------------------------------------------------------------
void WindowArrange::ImplVert( const Rectangle& rRect )
{
long nCount = (long)mpWinList->Count();
long nX = rRect.Left();
long nY = rRect.Top();
long nWidth = rRect.GetWidth();
long nHeight = rRect.GetHeight();
long nRectWidth = nWidth;
long nOver;
long nTempWidth;
Window* pWindow;
nWidth /= nCount;
if ( nWidth < 1 )
nWidth = 1;
nOver = nRectWidth - (nCount*nWidth);
pWindow = (Window*)mpWinList->First();
while ( pWindow )
{
nTempWidth = nWidth;
if ( nOver > 0 )
{
nTempWidth++;
nOver--;
}
ImplPosSizeWindow( pWindow, nX, nY, nTempWidth, nHeight );
nX += nTempWidth;
pWindow = (Window*)mpWinList->Next();
}
}
// -----------------------------------------------------------------------
void WindowArrange::ImplCascade( const Rectangle& rRect )
{
long nX = rRect.Left();
long nY = rRect.Top();
long nWidth = rRect.GetWidth();
long nHeight = rRect.GetHeight();
long nRectWidth = nWidth;
long nRectHeight = nHeight;
long nOff;
long nCascadeWins;
long nLeftBorder;
long nTopBorder;
long nRightBorder;
long nBottomBorder;
long nStartOverWidth;
long nStartOverHeight;
long nOverWidth;
long nOverHeight;
long nTempX;
long nTempY;
long nTempWidth;
long nTempHeight;
long i;
Window* pWindow;
Window* pTempWindow;
// Border-Fenster suchen um den Versatz zu ermitteln
pTempWindow = (Window*)mpWinList->First();
pTempWindow->GetBorder( nLeftBorder, nTopBorder, nRightBorder, nBottomBorder );
while ( !nTopBorder )
{
Window* pBrdWin = pTempWindow->GetWindow( WINDOW_REALPARENT );
if ( !pBrdWin || (pBrdWin->GetWindow( WINDOW_CLIENT ) != pTempWindow) )
break;
pTempWindow = pBrdWin;
pTempWindow->GetBorder( nLeftBorder, nTopBorder, nRightBorder, nBottomBorder );
}
if ( !nTopBorder )
nTopBorder = 22;
nOff = nTopBorder;
nCascadeWins = nRectHeight / 3 / nOff;
if ( !nCascadeWins )
nCascadeWins = 1;
nWidth -= nCascadeWins*nOff;
nHeight -= nCascadeWins*nOff;
if ( nWidth < 1 )
nWidth = 1;
if ( nHeight < 1 )
nHeight = 1;
nStartOverWidth = nRectWidth-(nWidth+(nCascadeWins*nOff));
nStartOverHeight = nRectHeight-(nHeight+(nCascadeWins*nOff));
i = 0;
pWindow = (Window*)mpWinList->First();
while ( pWindow )
{
if ( !i )
{
nOverWidth = nStartOverWidth;
nOverHeight = nStartOverHeight;
}
// Position
nTempX = nX + (i*nOff);
nTempY = nY + (i*nOff);
// Ueberhang verteilen
nTempWidth = nWidth;
if ( nOverWidth > 0 )
{
nTempWidth++;
nOverWidth--;
}
nTempHeight = nHeight;
if ( nOverHeight > 0 )
{
nTempHeight++;
nOverHeight--;
}
ImplPosSizeWindow( pWindow, nTempX, nTempY, nTempWidth, nTempHeight );
if ( i < nCascadeWins )
i++;
else
i = 0;
pWindow = (Window*)mpWinList->Next();
}
}
// -----------------------------------------------------------------------
void WindowArrange::Arrange( USHORT nType, const Rectangle& rRect )
{
if ( !mpWinList->Count() )
return;
switch ( nType )
{
case WINDOWARRANGE_TILE:
ImplTile( rRect );
break;
case WINDOWARRANGE_HORZ:
ImplHorz( rRect );
break;
case WINDOWARRANGE_VERT:
ImplVert( rRect );
break;
case WINDOWARRANGE_CASCADE:
ImplCascade( rRect );
break;
}
}
<commit_msg>INTEGRATION: CWS ooo20040509 (1.1.1.1.588); FILE MERGED 2004/05/06 13:40:19 waratah 1.1.1.1.588.1: Initialise variables where they need it<commit_after>/*************************************************************************
*
* $RCSfile: taskmisc.cxx,v $
*
* $Revision: 1.2 $
*
* last change: $Author: rt $ $Date: 2004-06-16 10:13:08 $
*
* 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): _______________________________________
*
*
************************************************************************/
#define _TASKBAR_CXX
#ifndef _TOOLS_LIST_HXX
#include <tools/list.hxx>
#endif
#ifndef _TOOLS_DEBUG_HXX
#include <tools/debug.hxx>
#endif
#ifndef _SV_HELP_HXX
#include <vcl/help.hxx>
#endif
#include <taskbar.hxx>
// =======================================================================
TaskButtonBar::TaskButtonBar( Window* pParent, WinBits nWinStyle ) :
ToolBox( pParent, nWinStyle | WB_3DLOOK )
{
SetAlign( WINDOWALIGN_BOTTOM );
SetButtonType( BUTTON_SYMBOLTEXT );
}
// -----------------------------------------------------------------------
TaskButtonBar::~TaskButtonBar()
{
}
// -----------------------------------------------------------------------
void TaskButtonBar::RequestHelp( const HelpEvent& rHEvt )
{
ToolBox::RequestHelp( rHEvt );
}
// =======================================================================
WindowArrange::WindowArrange()
{
mpWinList = new List;
}
// -----------------------------------------------------------------------
WindowArrange::~WindowArrange()
{
delete mpWinList;
}
// -----------------------------------------------------------------------
static USHORT ImplCeilSqareRoot( USHORT nVal )
{
USHORT i;
// Ueberlauf verhindern
if ( nVal > 0xFE * 0xFE )
return 0xFE;
for ( i=0; i*i < nVal; i++ )
{}
return i;
}
// -----------------------------------------------------------------------
static void ImplPosSizeWindow( Window* pWindow,
long nX, long nY, long nWidth, long nHeight )
{
if ( nWidth < 32 )
nWidth = 32;
if ( nHeight < 24 )
nHeight = 24;
pWindow->SetPosSizePixel( nX, nY, nWidth, nHeight );
}
// -----------------------------------------------------------------------
void WindowArrange::ImplTile( const Rectangle& rRect )
{
USHORT nCount = (USHORT)mpWinList->Count();
if ( nCount < 3 )
{
ImplVert( rRect );
return;
}
USHORT i;
USHORT j;
USHORT nCols;
USHORT nRows;
USHORT nActRows;
USHORT nOffset;
long nOverWidth;
long nOverHeight;
Window* pWindow;
long nX = rRect.Left();
long nY = rRect.Top();
long nWidth = rRect.GetWidth();
long nHeight = rRect.GetHeight();
long nRectY = nY;
long nRectWidth = nWidth;
long nRectHeight = nHeight;
long nTempWidth;
long nTempHeight;
nCols = ImplCeilSqareRoot( nCount );
nOffset = (nCols*nCols) - nCount;
if ( nOffset >= nCols )
{
nRows = nCols -1;
nOffset -= nCols;
}
else
nRows = nCols;
nWidth /= nCols;
if ( nWidth < 1 )
nWidth = 1;
nOverWidth = nRectWidth-(nWidth*nCols);
pWindow = (Window*)mpWinList->First();
for ( i = 0; i < nCols; i++ )
{
if ( i < nOffset )
nActRows = nRows - 1;
else
nActRows = nRows;
nTempWidth = nWidth;
if ( nOverWidth > 0 )
{
nTempWidth++;
nOverWidth--;
}
nHeight = nRectHeight / nActRows;
if ( nHeight < 1 )
nHeight = 1;
nOverHeight = nRectHeight-(nHeight*nActRows);
for ( j = 0; j < nActRows; j++ )
{
// Ueberhang verteilen
nTempHeight = nHeight;
if ( nOverHeight > 0 )
{
nTempHeight++;
nOverHeight--;
}
ImplPosSizeWindow( pWindow, nX, nY, nTempWidth, nTempHeight );
nY += nTempHeight;
pWindow = (Window*)mpWinList->Next();
if ( !pWindow )
break;
}
nX += nWidth;
nY = nRectY;
if ( !pWindow )
break;
}
}
// -----------------------------------------------------------------------
void WindowArrange::ImplHorz( const Rectangle& rRect )
{
long nCount = (long)mpWinList->Count();
long nX = rRect.Left();
long nY = rRect.Top();
long nWidth = rRect.GetWidth();
long nHeight = rRect.GetHeight();
long nRectHeight = nHeight;
long nOver;
long nTempHeight;
Window* pWindow;
nHeight /= nCount;
if ( nHeight < 1 )
nHeight = 1;
nOver = nRectHeight - (nCount*nHeight);
pWindow = (Window*)mpWinList->First();
while ( pWindow )
{
nTempHeight = nHeight;
if ( nOver > 0 )
{
nTempHeight++;
nOver--;
}
ImplPosSizeWindow( pWindow, nX, nY, nWidth, nTempHeight );
nY += nTempHeight;
pWindow = (Window*)mpWinList->Next();
}
}
// -----------------------------------------------------------------------
void WindowArrange::ImplVert( const Rectangle& rRect )
{
long nCount = (long)mpWinList->Count();
long nX = rRect.Left();
long nY = rRect.Top();
long nWidth = rRect.GetWidth();
long nHeight = rRect.GetHeight();
long nRectWidth = nWidth;
long nOver;
long nTempWidth;
Window* pWindow;
nWidth /= nCount;
if ( nWidth < 1 )
nWidth = 1;
nOver = nRectWidth - (nCount*nWidth);
pWindow = (Window*)mpWinList->First();
while ( pWindow )
{
nTempWidth = nWidth;
if ( nOver > 0 )
{
nTempWidth++;
nOver--;
}
ImplPosSizeWindow( pWindow, nX, nY, nTempWidth, nHeight );
nX += nTempWidth;
pWindow = (Window*)mpWinList->Next();
}
}
// -----------------------------------------------------------------------
void WindowArrange::ImplCascade( const Rectangle& rRect )
{
long nX = rRect.Left();
long nY = rRect.Top();
long nWidth = rRect.GetWidth();
long nHeight = rRect.GetHeight();
long nRectWidth = nWidth;
long nRectHeight = nHeight;
long nOff;
long nCascadeWins;
long nLeftBorder;
long nTopBorder;
long nRightBorder;
long nBottomBorder;
long nStartOverWidth;
long nStartOverHeight;
long nOverWidth = 0;
long nOverHeight = 0;
long nTempX;
long nTempY;
long nTempWidth;
long nTempHeight;
long i;
Window* pWindow;
Window* pTempWindow;
// Border-Fenster suchen um den Versatz zu ermitteln
pTempWindow = (Window*)mpWinList->First();
pTempWindow->GetBorder( nLeftBorder, nTopBorder, nRightBorder, nBottomBorder );
while ( !nTopBorder )
{
Window* pBrdWin = pTempWindow->GetWindow( WINDOW_REALPARENT );
if ( !pBrdWin || (pBrdWin->GetWindow( WINDOW_CLIENT ) != pTempWindow) )
break;
pTempWindow = pBrdWin;
pTempWindow->GetBorder( nLeftBorder, nTopBorder, nRightBorder, nBottomBorder );
}
if ( !nTopBorder )
nTopBorder = 22;
nOff = nTopBorder;
nCascadeWins = nRectHeight / 3 / nOff;
if ( !nCascadeWins )
nCascadeWins = 1;
nWidth -= nCascadeWins*nOff;
nHeight -= nCascadeWins*nOff;
if ( nWidth < 1 )
nWidth = 1;
if ( nHeight < 1 )
nHeight = 1;
nStartOverWidth = nRectWidth-(nWidth+(nCascadeWins*nOff));
nStartOverHeight = nRectHeight-(nHeight+(nCascadeWins*nOff));
i = 0;
pWindow = (Window*)mpWinList->First();
while ( pWindow )
{
if ( !i )
{
nOverWidth = nStartOverWidth;
nOverHeight = nStartOverHeight;
}
// Position
nTempX = nX + (i*nOff);
nTempY = nY + (i*nOff);
// Ueberhang verteilen
nTempWidth = nWidth;
if ( nOverWidth > 0 )
{
nTempWidth++;
nOverWidth--;
}
nTempHeight = nHeight;
if ( nOverHeight > 0 )
{
nTempHeight++;
nOverHeight--;
}
ImplPosSizeWindow( pWindow, nTempX, nTempY, nTempWidth, nTempHeight );
if ( i < nCascadeWins )
i++;
else
i = 0;
pWindow = (Window*)mpWinList->Next();
}
}
// -----------------------------------------------------------------------
void WindowArrange::Arrange( USHORT nType, const Rectangle& rRect )
{
if ( !mpWinList->Count() )
return;
switch ( nType )
{
case WINDOWARRANGE_TILE:
ImplTile( rRect );
break;
case WINDOWARRANGE_HORZ:
ImplHorz( rRect );
break;
case WINDOWARRANGE_VERT:
ImplVert( rRect );
break;
case WINDOWARRANGE_CASCADE:
ImplCascade( rRect );
break;
}
}
<|endoftext|> |
<commit_before>/*
* This file is part of ALVAR, A Library for Virtual and Augmented Reality.
*
* Copyright 2007-2012 VTT Technical Research Centre of Finland
*
* Contact: VTT Augmented Reality Team <alvar.info@vtt.fi>
* <http://www.vtt.fi/multimedia/alvar.html>
*
* ALVAR 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 ALVAR; if not, see
* <http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html>.
*/
#include "CaptureFactory_private.h"
#include <stdlib.h>
namespace alvar {
void CaptureFactoryPrivate::setupPluginPaths()
{
// application path and default plugin path
const int bufferSize = 4096;
char applicationBuffer[bufferSize];
int count = readlink("/proc/self/exe", applicationBuffer, bufferSize);
if (count != 0 && count < bufferSize) {
std::string applicationPath(applicationBuffer, count);
applicationPath = std::string(applicationPath, 0, applicationPath.find_last_of("/"));
mPluginPaths.push_back(applicationPath);
mPluginPaths.push_back(applicationPath + "/alvarplugins");
}
// ALVAR library path
parseEnvironmentVariable(std::string("ALVAR_LIBRARY_PATH"));
// ALVAR plugin path
parseEnvironmentVariable(std::string("ALVAR_PLUGIN_PATH"));
}
void CaptureFactoryPrivate::parseEnvironmentVariable(const std::string &variable)
{
// acquire environment variable
char *buffer;
std::string path("");
buffer = getenv(variable.data());
if (buffer) {
path = std::string(buffer);
}
// tokenize paths
char delimitor = ':';
if (!path.empty()) {
std::string::size_type start = 0;
std::string::size_type end = 0;
while ((end = path.find_first_of(delimitor, start)) != std::string::npos) {
std::string tmp(path, start, end - start);
if (!tmp.empty()) {
mPluginPaths.push_back(tmp);
}
start = end + 1;
}
if (start != path.size()) {
std::string tmp(path, start, std::string::npos);
if (!tmp.empty()) {
mPluginPaths.push_back(tmp);
}
}
}
}
std::string CaptureFactoryPrivate::pluginPrefix()
{
return std::string("lib");
}
std::string CaptureFactoryPrivate::pluginExtension()
{
return std::string("so");
}
} // namespace alvar
<commit_msg>Add missing unistd include<commit_after>/*
* This file is part of ALVAR, A Library for Virtual and Augmented Reality.
*
* Copyright 2007-2012 VTT Technical Research Centre of Finland
*
* Contact: VTT Augmented Reality Team <alvar.info@vtt.fi>
* <http://www.vtt.fi/multimedia/alvar.html>
*
* ALVAR 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 ALVAR; if not, see
* <http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html>.
*/
#include "CaptureFactory_private.h"
#include <stdlib.h>
#include <unistd.h>
namespace alvar {
void CaptureFactoryPrivate::setupPluginPaths()
{
// application path and default plugin path
const int bufferSize = 4096;
char applicationBuffer[bufferSize];
int count = readlink("/proc/self/exe", applicationBuffer, bufferSize);
if (count != 0 && count < bufferSize) {
std::string applicationPath(applicationBuffer, count);
applicationPath = std::string(applicationPath, 0, applicationPath.find_last_of("/"));
mPluginPaths.push_back(applicationPath);
mPluginPaths.push_back(applicationPath + "/alvarplugins");
}
// ALVAR library path
parseEnvironmentVariable(std::string("ALVAR_LIBRARY_PATH"));
// ALVAR plugin path
parseEnvironmentVariable(std::string("ALVAR_PLUGIN_PATH"));
}
void CaptureFactoryPrivate::parseEnvironmentVariable(const std::string &variable)
{
// acquire environment variable
char *buffer;
std::string path("");
buffer = getenv(variable.data());
if (buffer) {
path = std::string(buffer);
}
// tokenize paths
char delimitor = ':';
if (!path.empty()) {
std::string::size_type start = 0;
std::string::size_type end = 0;
while ((end = path.find_first_of(delimitor, start)) != std::string::npos) {
std::string tmp(path, start, end - start);
if (!tmp.empty()) {
mPluginPaths.push_back(tmp);
}
start = end + 1;
}
if (start != path.size()) {
std::string tmp(path, start, std::string::npos);
if (!tmp.empty()) {
mPluginPaths.push_back(tmp);
}
}
}
}
std::string CaptureFactoryPrivate::pluginPrefix()
{
return std::string("lib");
}
std::string CaptureFactoryPrivate::pluginExtension()
{
return std::string("so");
}
} // namespace alvar
<|endoftext|> |
<commit_before>#include "ConfigController.h"
#include "GameController.h"
#include <QAction>
#include <QMenu>
extern "C" {
#include "platform/commandline.h"
}
using namespace QGBA;
ConfigOption::ConfigOption(QObject* parent)
: QObject(parent)
{
}
void ConfigOption::connect(std::function<void(const QVariant&)> slot) {
m_slot = slot;
}
QAction* ConfigOption::addValue(const QString& text, const QVariant& value, QMenu* parent) {
QAction* action = new QAction(text, parent);
action->setCheckable(true);
QObject::connect(action, &QAction::triggered, [this, value]() {
emit valueChanged(value);
});
parent->addAction(action);
m_actions.append(qMakePair(action, value));
return action;
}
QAction* ConfigOption::addValue(const QString& text, const char* value, QMenu* parent) {
return addValue(text, QString(value), parent);
}
QAction* ConfigOption::addBoolean(const QString& text, QMenu* parent) {
QAction* action = new QAction(text, parent);
action->setCheckable(true);
QObject::connect(action, &QAction::triggered, [this, action]() {
emit valueChanged(action->isChecked());
});
parent->addAction(action);
m_actions.append(qMakePair(action, true));
return action;
}
void ConfigOption::setValue(bool value) {
setValue(QVariant(value));
}
void ConfigOption::setValue(int value) {
setValue(QVariant(value));
}
void ConfigOption::setValue(unsigned value) {
setValue(QVariant(value));
}
void ConfigOption::setValue(const char* value) {
setValue(QVariant(QString(value)));
}
void ConfigOption::setValue(const QVariant& value) {
QPair<QAction*, QVariant> action;
foreach(action, m_actions) {
bool signalsEnabled = action.first->blockSignals(true);
action.first->setChecked(value == action.second);
action.first->blockSignals(signalsEnabled);
}
m_slot(value);
}
ConfigController::ConfigController(QObject* parent)
: QObject(parent)
, m_opts()
{
GBAConfigInit(&m_config, PORT);
m_opts.audioSync = GameController::AUDIO_SYNC;
m_opts.videoSync = GameController::VIDEO_SYNC;
m_opts.fpsTarget = 60;
m_opts.audioBuffers = 768;
GBAConfigLoadDefaults(&m_config, &m_opts);
GBAConfigLoad(&m_config);
GBAConfigMap(&m_config, &m_opts);
}
ConfigController::~ConfigController() {
write();
GBAConfigDeinit(&m_config);
GBAConfigFreeOpts(&m_opts);
}
bool ConfigController::parseArguments(GBAArguments* args, int argc, char* argv[]) {
return ::parseArguments(args, &m_config, argc, argv, 0);
}
ConfigOption* ConfigController::addOption(const char* key) {
QString optionName(key);
if (m_optionSet.contains(optionName)) {
return m_optionSet[optionName];
}
ConfigOption* newOption = new ConfigOption(this);
m_optionSet[optionName] = newOption;
connect(newOption, &ConfigOption::valueChanged, [this, key](const QVariant& value) {
setOption(key, value);
});
return newOption;
}
void ConfigController::updateOption(const char* key) {
if (!key) {
return;
}
QString optionName(key);
if (!m_optionSet.contains(optionName)) {
return;
}
m_optionSet[optionName]->setValue(GBAConfigGetValue(&m_config, key));
}
void ConfigController::setOption(const char* key, bool value) {
setOption(key, (int) value);
ConfigOption* option = m_optionSet[QString(key)];
if (option) {
option->setValue(value);
}
}
void ConfigController::setOption(const char* key, int value) {
GBAConfigSetIntValue(&m_config, key, value);
ConfigOption* option = m_optionSet[QString(key)];
if (option) {
option->setValue(value);
}
}
void ConfigController::setOption(const char* key, unsigned value) {
GBAConfigSetUIntValue(&m_config, key, value);
ConfigOption* option = m_optionSet[QString(key)];
if (option) {
option->setValue(value);
}
}
void ConfigController::setOption(const char* key, const char* value) {
GBAConfigSetValue(&m_config, key, value);
ConfigOption* option = m_optionSet[QString(key)];
if (option) {
option->setValue(value);
}
}
void ConfigController::setOption(const char* key, const QVariant& value) {
QString stringValue(value.toString());
setOption(key, stringValue.toLocal8Bit().constData());
}
void ConfigController::write() {
GBAConfigSave(&m_config);
}
<commit_msg>Qt: Fix boolean setting loading<commit_after>#include "ConfigController.h"
#include "GameController.h"
#include <QAction>
#include <QMenu>
extern "C" {
#include "platform/commandline.h"
}
using namespace QGBA;
ConfigOption::ConfigOption(QObject* parent)
: QObject(parent)
{
}
void ConfigOption::connect(std::function<void(const QVariant&)> slot) {
m_slot = slot;
}
QAction* ConfigOption::addValue(const QString& text, const QVariant& value, QMenu* parent) {
QAction* action = new QAction(text, parent);
action->setCheckable(true);
QObject::connect(action, &QAction::triggered, [this, value]() {
emit valueChanged(value);
});
parent->addAction(action);
m_actions.append(qMakePair(action, value));
return action;
}
QAction* ConfigOption::addValue(const QString& text, const char* value, QMenu* parent) {
return addValue(text, QString(value), parent);
}
QAction* ConfigOption::addBoolean(const QString& text, QMenu* parent) {
QAction* action = new QAction(text, parent);
action->setCheckable(true);
QObject::connect(action, &QAction::triggered, [this, action]() {
emit valueChanged(action->isChecked());
});
parent->addAction(action);
m_actions.append(qMakePair(action, 1));
return action;
}
void ConfigOption::setValue(bool value) {
setValue(QVariant(value));
}
void ConfigOption::setValue(int value) {
setValue(QVariant(value));
}
void ConfigOption::setValue(unsigned value) {
setValue(QVariant(value));
}
void ConfigOption::setValue(const char* value) {
setValue(QVariant(QString(value)));
}
void ConfigOption::setValue(const QVariant& value) {
QPair<QAction*, QVariant> action;
foreach(action, m_actions) {
bool signalsEnabled = action.first->blockSignals(true);
action.first->setChecked(value == action.second);
action.first->blockSignals(signalsEnabled);
}
m_slot(value);
}
ConfigController::ConfigController(QObject* parent)
: QObject(parent)
, m_opts()
{
GBAConfigInit(&m_config, PORT);
m_opts.audioSync = GameController::AUDIO_SYNC;
m_opts.videoSync = GameController::VIDEO_SYNC;
m_opts.fpsTarget = 60;
m_opts.audioBuffers = 768;
GBAConfigLoadDefaults(&m_config, &m_opts);
GBAConfigLoad(&m_config);
GBAConfigMap(&m_config, &m_opts);
}
ConfigController::~ConfigController() {
write();
GBAConfigDeinit(&m_config);
GBAConfigFreeOpts(&m_opts);
}
bool ConfigController::parseArguments(GBAArguments* args, int argc, char* argv[]) {
return ::parseArguments(args, &m_config, argc, argv, 0);
}
ConfigOption* ConfigController::addOption(const char* key) {
QString optionName(key);
if (m_optionSet.contains(optionName)) {
return m_optionSet[optionName];
}
ConfigOption* newOption = new ConfigOption(this);
m_optionSet[optionName] = newOption;
connect(newOption, &ConfigOption::valueChanged, [this, key](const QVariant& value) {
setOption(key, value);
});
return newOption;
}
void ConfigController::updateOption(const char* key) {
if (!key) {
return;
}
QString optionName(key);
if (!m_optionSet.contains(optionName)) {
return;
}
m_optionSet[optionName]->setValue(GBAConfigGetValue(&m_config, key));
}
void ConfigController::setOption(const char* key, bool value) {
GBAConfigSetIntValue(&m_config, key, value);
ConfigOption* option = m_optionSet[QString(key)];
if (option) {
option->setValue(value);
}
}
void ConfigController::setOption(const char* key, int value) {
GBAConfigSetIntValue(&m_config, key, value);
ConfigOption* option = m_optionSet[QString(key)];
if (option) {
option->setValue(value);
}
}
void ConfigController::setOption(const char* key, unsigned value) {
GBAConfigSetUIntValue(&m_config, key, value);
ConfigOption* option = m_optionSet[QString(key)];
if (option) {
option->setValue(value);
}
}
void ConfigController::setOption(const char* key, const char* value) {
GBAConfigSetValue(&m_config, key, value);
ConfigOption* option = m_optionSet[QString(key)];
if (option) {
option->setValue(value);
}
}
void ConfigController::setOption(const char* key, const QVariant& value) {
if (value.type() == QVariant::Bool) {
setOption(key, value.toBool());
return;
}
QString stringValue(value.toString());
setOption(key, stringValue.toLocal8Bit().constData());
}
void ConfigController::write() {
GBAConfigSave(&m_config);
}
<|endoftext|> |
<commit_before>#include "HaxeRuntime.h"
#if WITH_EDITOR
#include "uhx/DynamicClass.h"
#include "Misc/Paths.h"
#include "uhx/expose/HxcppRuntime.h"
#ifndef UHX_NO_UOBJECT
static int uhx_uniqueId = 0;
static TMap<FName, uint32> getCrcMapPvt() {
TMap<FName, uint32> map;
FString path = FPaths::ConvertRelativePathToFull(FPaths::GameDir()) + TEXT("/Binaries/Haxe/gameCrcs.data");
auto file = FPlatformFileManager::Get().GetPlatformFile().OpenRead(*path, false);
if (file == nullptr) {
return map;
}
uint8 classNameSize = 0;
char className[257];
uint32 crc = 0;
bool success = true;
int magic = 0;
if (!file->Read((uint8*) &magic, 4) || magic != 0xC5CC991A) {
UE_LOG(HaxeLog, Error, TEXT("Invalid gameCrcs magic"));
success = false;
}
int ntry = 0;
if (!success || !file->Read((uint8*) &ntry, 4)) {
success = false;
}
uhx_uniqueId = ntry;
#define READ(destination, bytesToRead) if (!file->Read(destination, bytesToRead)) { success = false; break; }
while(success) {
READ(&classNameSize, 1);
if (classNameSize == 0) {
break;
}
READ((uint8 *) className, classNameSize);
className[classNameSize] = 0;
READ((uint8 *) &crc, 4);
// crc += ntry;
FName classFName = FName( UTF8_TO_TCHAR(className) );
if (crc == 0) {
UE_LOG(HaxeLog, Error, TEXT("Unreal.hx CRC for class %s was 0"), *classFName.ToString());
}
map.Add(classFName, crc);
}
#undef READ
if (!success) {
UE_LOG(HaxeLog,Error,TEXT("Unreal.hx CRC data was corrupt"));
}
delete file;
return map;
}
TMap<FName, uint32>& ::uhx::DynamicClassHelper::getCrcMap() {
static TMap<FName, uint32> map = getCrcMapPvt();
return map;
}
TMap<FName, UClass *>& ::uhx::DynamicClassHelper::getDynamicsMap() {
static TMap<FName, UClass *> map;
return map;
}
#endif
#if (WITH_EDITOR && !NO_DYNAMIC_UCLASS)
/**
* In order to add cppia dynamic class support, we need to be able to call `addDynamicProperties` in a very precise location - which is
* right before the CDO is created. We must call this before the class CDO is created because otherwise the CDO will have the wrong size,
* and bad things will happen. This UHxBootstrap class implements an intrinsic class so we can have a callback right when the classes
* are registering, which is the exact place where we should add the dynamic properties
**/
class UHxBootstrap : public UObject {
#if UE_VER >= 416
#define UHX_HOTRELOAD 1
#else
#define UHX_HOTRELOAD WITH_HOT_RELOAD_CTORS
#endif
#if UHX_HOTRELOAD
DECLARE_CASTED_CLASS_INTRINSIC_NO_CTOR_NO_VTABLE_CTOR(UHxBootstrap, UObject, 0, TEXT("/Script/HaxeRuntime"), 0, HAXERUNTIME_API)
UHxBootstrap(FVTableHelper& Helper) : UObject(Helper) {
}
#else
DECLARE_CASTED_CLASS_INTRINSIC_NO_CTOR(UHxBootstrap, UObject, 0, HaxeRuntime, 0, HAXERUNTIME_API)
#endif
UHxBootstrap(const FObjectInitializer& ObjectInitializer = FObjectInitializer::Get()) : UObject(ObjectInitializer) {
static bool endLoadingDynamicCalled = false;
if (!endLoadingDynamicCalled) {
endLoadingDynamicCalled = true;
uhx::expose::HxcppRuntime::endLoadingDynamic();
}
}
#undef UHX_HOTRELOAD
};
// make sure that UHxBootstrap is always hot reloaded, as its CRC constantly changes
template<>
struct TClassCompiledInDefer<UHxBootstrap> : public FFieldCompiledInInfo
{
TClassCompiledInDefer(const TCHAR* InName, SIZE_T InClassSize, uint32 InCrc)
: FFieldCompiledInInfo(InClassSize, InCrc)
{
static FName className = FName("UHxBootstrap");
::uhx::DynamicClassHelper::getCrcMap(); // make sure that the crc map is initialized
this->Crc = uhx_uniqueId;
UClassCompiledInDefer(this, InName, InClassSize, this->Crc);
}
virtual UClass* Register() const override {
return UHxBootstrap::StaticClass();
}
#if UE_VER >= 416
const TCHAR* ClassPackage() const {
return UHxBootstrap::StaticPackage();
}
#endif
};
#if UE_VER >= 416
#define UHX_IMPLEMENT_INTRINSIC_CLASS(TClass, TRequiredAPI, TSuperClass, TSuperRequiredAPI, InitCode) IMPLEMENT_INTRINSIC_CLASS(TClass, TRequiredAPI, TSuperClass, TSuperRequiredAPI, "/Script/HaxeRuntime", InitCode)
#else
#define UHX_IMPLEMENT_INTRINSIC_CLASS(TClass, TRequiredAPI, TSuperClass, TSuperRequiredAPI, InitCode) IMPLEMENT_INTRINSIC_CLASS(TClass, TRequiredAPI, TSuperClass, TSuperRequiredAPI, InitCode)
#endif
UHX_IMPLEMENT_INTRINSIC_CLASS(UHxBootstrap, HAXERUNTIME_API, UObject, COREUOBJECT_API,
{
check_hx_init();
uhx::expose::HxcppRuntime::startLoadingDynamic();
for (auto It = ::uhx::DynamicClassHelper::getDynamicsMap().CreateIterator(); It; ++It) {
UClass *val = It.Value();
uhx::expose::HxcppRuntime::setDynamicNative((unreal::UIntPtr) val, TCHAR_TO_UTF8(*It.Key().ToString()));
}
uhx::expose::HxcppRuntime::setNativeTypes();
for (auto It = ::uhx::DynamicClassHelper::getDynamicsMap().CreateIterator(); It; ++It) {
UClass *val = It.Value();
uhx::expose::HxcppRuntime::addDynamicProperties((unreal::UIntPtr) val, TCHAR_TO_UTF8(*It.Key().ToString()));
}
});
#undef UHX_IMPLEMENT_INTRINSIC_CLASS
#endif
#endif // WITH_EDITOR
<commit_msg>[CL-14383] Update to latest perforce change Change 14383 by waneck@wnk-asus-win-ls on 2017/12/06 22:37:05<commit_after>#include "HaxeRuntime.h"
#if WITH_EDITOR
#include "uhx/DynamicClass.h"
#include "Misc/Paths.h"
#include "uhx/expose/HxcppRuntime.h"
#ifndef UHX_NO_UOBJECT
static int uhx_uniqueId = 0;
static TMap<FName, uint32> getCrcMapPvt() {
TMap<FName, uint32> map;
FString path = FPaths::ConvertRelativePathToFull(FPaths::GameDir()) + TEXT("/Binaries/Haxe/gameCrcs.data");
auto file = FPlatformFileManager::Get().GetPlatformFile().OpenRead(*path, false);
if (file == nullptr) {
return map;
}
uint8 classNameSize = 0;
char className[257];
uint32 crc = 0;
bool success = true;
int magic = 0;
if (!file->Read((uint8*) &magic, 4) || magic != 0xC5CC991A) {
UE_LOG(HaxeLog, Error, TEXT("Invalid gameCrcs magic"));
success = false;
}
int ntry = 0;
if (!success || !file->Read((uint8*) &ntry, 4)) {
success = false;
}
uhx_uniqueId = ntry;
#define READ(destination, bytesToRead) if (!file->Read(destination, bytesToRead)) { success = false; break; }
while(success) {
READ(&classNameSize, 1);
if (classNameSize == 0) {
break;
}
READ((uint8 *) className, classNameSize);
className[classNameSize] = 0;
READ((uint8 *) &crc, 4);
// crc += ntry;
FName classFName = FName( UTF8_TO_TCHAR(className) );
if (crc == 0) {
UE_LOG(HaxeLog, Error, TEXT("Unreal.hx CRC for class %s was 0"), *classFName.ToString());
}
map.Add(classFName, crc);
}
#undef READ
if (!success) {
UE_LOG(HaxeLog,Error,TEXT("Unreal.hx CRC data was corrupt"));
}
delete file;
return map;
}
TMap<FName, uint32>& ::uhx::DynamicClassHelper::getCrcMap() {
static TMap<FName, uint32> map = getCrcMapPvt();
return map;
}
TMap<FName, UClass *>& ::uhx::DynamicClassHelper::getDynamicsMap() {
static TMap<FName, UClass *> map;
return map;
}
#endif
#if (WITH_EDITOR && !NO_DYNAMIC_UCLASS)
/**
* In order to add cppia dynamic class support, we need to be able to call `addDynamicProperties` in a very precise location - which is
* right before the CDO is created. We must call this before the class CDO is created because otherwise the CDO will have the wrong size,
* and bad things will happen. This UHxBootstrap class implements an intrinsic class so we can have a callback right when the classes
* are registering, which is the exact place where we should add the dynamic properties
**/
class UHxBootstrap : public UObject {
#if UE_VER >= 416
#define UHX_HOTRELOAD 1
#else
#define UHX_HOTRELOAD WITH_HOT_RELOAD_CTORS
#endif
#if UHX_HOTRELOAD
DECLARE_CASTED_CLASS_INTRINSIC_NO_CTOR_NO_VTABLE_CTOR(UHxBootstrap, UObject, 0, TEXT("/Script/HaxeRuntime"), 0, HAXERUNTIME_API)
UHxBootstrap(FVTableHelper& Helper) : UObject(Helper) {
}
#else
DECLARE_CASTED_CLASS_INTRINSIC_NO_CTOR(UHxBootstrap, UObject, 0, HaxeRuntime, 0, HAXERUNTIME_API)
#endif
UHxBootstrap(const FObjectInitializer& ObjectInitializer = FObjectInitializer::Get()) : UObject(ObjectInitializer) {
static bool endLoadingDynamicCalled = false;
if (!endLoadingDynamicCalled) {
endLoadingDynamicCalled = true;
uhx::expose::HxcppRuntime::endLoadingDynamic();
}
}
#undef UHX_HOTRELOAD
};
// make sure that UHxBootstrap is always hot reloaded, as its CRC constantly changes
template<>
struct TClassCompiledInDefer<UHxBootstrap> : public FFieldCompiledInInfo
{
TClassCompiledInDefer(const TCHAR* InName, SIZE_T InClassSize, uint32 InCrc)
: FFieldCompiledInInfo(InClassSize, InCrc)
{
static FName className = FName("UHxBootstrap");
::uhx::DynamicClassHelper::getCrcMap(); // make sure that the crc map is initialized
this->Crc = uhx_uniqueId;
UClassCompiledInDefer(this, InName, InClassSize, this->Crc);
}
virtual UClass* Register() const override {
check_hx_init();
return UHxBootstrap::StaticClass();
}
#if UE_VER >= 416
const TCHAR* ClassPackage() const {
return UHxBootstrap::StaticPackage();
}
#endif
};
#if UE_VER >= 416
#define UHX_IMPLEMENT_INTRINSIC_CLASS(TClass, TRequiredAPI, TSuperClass, TSuperRequiredAPI, InitCode) IMPLEMENT_INTRINSIC_CLASS(TClass, TRequiredAPI, TSuperClass, TSuperRequiredAPI, "/Script/HaxeRuntime", InitCode)
#else
#define UHX_IMPLEMENT_INTRINSIC_CLASS(TClass, TRequiredAPI, TSuperClass, TSuperRequiredAPI, InitCode) IMPLEMENT_INTRINSIC_CLASS(TClass, TRequiredAPI, TSuperClass, TSuperRequiredAPI, InitCode)
#endif
UHX_IMPLEMENT_INTRINSIC_CLASS(UHxBootstrap, HAXERUNTIME_API, UObject, COREUOBJECT_API,
{
check_hx_init();
uhx::expose::HxcppRuntime::startLoadingDynamic();
for (auto It = ::uhx::DynamicClassHelper::getDynamicsMap().CreateIterator(); It; ++It) {
UClass *val = It.Value();
uhx::expose::HxcppRuntime::setDynamicNative((unreal::UIntPtr) val, TCHAR_TO_UTF8(*It.Key().ToString()));
}
uhx::expose::HxcppRuntime::setNativeTypes();
for (auto It = ::uhx::DynamicClassHelper::getDynamicsMap().CreateIterator(); It; ++It) {
UClass *val = It.Value();
uhx::expose::HxcppRuntime::addDynamicProperties((unreal::UIntPtr) val, TCHAR_TO_UTF8(*It.Key().ToString()));
}
});
#undef UHX_IMPLEMENT_INTRINSIC_CLASS
#endif
#endif // WITH_EDITOR
<|endoftext|> |
<commit_before>/* Copyright (c) 2013-2014 Jeffrey Pfau
*
* 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 "ConfigController.h"
#include "GameController.h"
#include <QAction>
#include <QMenu>
extern "C" {
#include "platform/commandline.h"
}
using namespace QGBA;
ConfigOption::ConfigOption(QObject* parent)
: QObject(parent)
{
}
void ConfigOption::connect(std::function<void(const QVariant&)> slot) {
m_slot = slot;
}
QAction* ConfigOption::addValue(const QString& text, const QVariant& value, QMenu* parent) {
QAction* action = new QAction(text, parent);
action->setCheckable(true);
QObject::connect(action, &QAction::triggered, [this, value]() {
emit valueChanged(value);
});
parent->addAction(action);
m_actions.append(qMakePair(action, value));
return action;
}
QAction* ConfigOption::addValue(const QString& text, const char* value, QMenu* parent) {
return addValue(text, QString(value), parent);
}
QAction* ConfigOption::addBoolean(const QString& text, QMenu* parent) {
QAction* action = new QAction(text, parent);
action->setCheckable(true);
QObject::connect(action, &QAction::triggered, [this, action]() {
emit valueChanged(action->isChecked());
});
parent->addAction(action);
m_actions.append(qMakePair(action, 1));
return action;
}
void ConfigOption::setValue(bool value) {
setValue(QVariant(value));
}
void ConfigOption::setValue(int value) {
setValue(QVariant(value));
}
void ConfigOption::setValue(unsigned value) {
setValue(QVariant(value));
}
void ConfigOption::setValue(const char* value) {
setValue(QVariant(QString(value)));
}
void ConfigOption::setValue(const QVariant& value) {
QPair<QAction*, QVariant> action;
foreach(action, m_actions) {
bool signalsEnabled = action.first->blockSignals(true);
action.first->setChecked(value == action.second);
action.first->blockSignals(signalsEnabled);
}
m_slot(value);
}
ConfigController::ConfigController(QObject* parent)
: QObject(parent)
, m_opts()
{
GBAConfigInit(&m_config, PORT);
m_opts.audioSync = GameController::AUDIO_SYNC;
m_opts.videoSync = GameController::VIDEO_SYNC;
m_opts.fpsTarget = 60;
m_opts.audioBuffers = 2048;
GBAConfigLoadDefaults(&m_config, &m_opts);
GBAConfigLoad(&m_config);
GBAConfigMap(&m_config, &m_opts);
}
ConfigController::~ConfigController() {
write();
GBAConfigDeinit(&m_config);
GBAConfigFreeOpts(&m_opts);
}
bool ConfigController::parseArguments(GBAArguments* args, int argc, char* argv[]) {
return ::parseArguments(args, &m_config, argc, argv, 0);
}
ConfigOption* ConfigController::addOption(const char* key) {
QString optionName(key);
if (m_optionSet.contains(optionName)) {
return m_optionSet[optionName];
}
ConfigOption* newOption = new ConfigOption(this);
m_optionSet[optionName] = newOption;
connect(newOption, &ConfigOption::valueChanged, [this, key](const QVariant& value) {
setOption(key, value);
});
return newOption;
}
void ConfigController::updateOption(const char* key) {
if (!key) {
return;
}
QString optionName(key);
if (!m_optionSet.contains(optionName)) {
return;
}
m_optionSet[optionName]->setValue(GBAConfigGetValue(&m_config, key));
}
void ConfigController::setOption(const char* key, bool value) {
GBAConfigSetIntValue(&m_config, key, value);
ConfigOption* option = m_optionSet[QString(key)];
if (option) {
option->setValue(value);
}
}
void ConfigController::setOption(const char* key, int value) {
GBAConfigSetIntValue(&m_config, key, value);
ConfigOption* option = m_optionSet[QString(key)];
if (option) {
option->setValue(value);
}
}
void ConfigController::setOption(const char* key, unsigned value) {
GBAConfigSetUIntValue(&m_config, key, value);
ConfigOption* option = m_optionSet[QString(key)];
if (option) {
option->setValue(value);
}
}
void ConfigController::setOption(const char* key, const char* value) {
GBAConfigSetValue(&m_config, key, value);
ConfigOption* option = m_optionSet[QString(key)];
if (option) {
option->setValue(value);
}
}
void ConfigController::setOption(const char* key, const QVariant& value) {
if (value.type() == QVariant::Bool) {
setOption(key, value.toBool());
return;
}
QString stringValue(value.toString());
setOption(key, stringValue.toLocal8Bit().constData());
}
void ConfigController::write() {
GBAConfigSave(&m_config);
}
<commit_msg>Qt: Fix config options being erroneously added as null<commit_after>/* Copyright (c) 2013-2014 Jeffrey Pfau
*
* 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 "ConfigController.h"
#include "GameController.h"
#include <QAction>
#include <QMenu>
extern "C" {
#include "platform/commandline.h"
}
using namespace QGBA;
ConfigOption::ConfigOption(QObject* parent)
: QObject(parent)
{
}
void ConfigOption::connect(std::function<void(const QVariant&)> slot) {
m_slot = slot;
}
QAction* ConfigOption::addValue(const QString& text, const QVariant& value, QMenu* parent) {
QAction* action = new QAction(text, parent);
action->setCheckable(true);
QObject::connect(action, &QAction::triggered, [this, value]() {
emit valueChanged(value);
});
parent->addAction(action);
m_actions.append(qMakePair(action, value));
return action;
}
QAction* ConfigOption::addValue(const QString& text, const char* value, QMenu* parent) {
return addValue(text, QString(value), parent);
}
QAction* ConfigOption::addBoolean(const QString& text, QMenu* parent) {
QAction* action = new QAction(text, parent);
action->setCheckable(true);
QObject::connect(action, &QAction::triggered, [this, action]() {
emit valueChanged(action->isChecked());
});
parent->addAction(action);
m_actions.append(qMakePair(action, 1));
return action;
}
void ConfigOption::setValue(bool value) {
setValue(QVariant(value));
}
void ConfigOption::setValue(int value) {
setValue(QVariant(value));
}
void ConfigOption::setValue(unsigned value) {
setValue(QVariant(value));
}
void ConfigOption::setValue(const char* value) {
setValue(QVariant(QString(value)));
}
void ConfigOption::setValue(const QVariant& value) {
QPair<QAction*, QVariant> action;
foreach(action, m_actions) {
bool signalsEnabled = action.first->blockSignals(true);
action.first->setChecked(value == action.second);
action.first->blockSignals(signalsEnabled);
}
m_slot(value);
}
ConfigController::ConfigController(QObject* parent)
: QObject(parent)
, m_opts()
{
GBAConfigInit(&m_config, PORT);
m_opts.audioSync = GameController::AUDIO_SYNC;
m_opts.videoSync = GameController::VIDEO_SYNC;
m_opts.fpsTarget = 60;
m_opts.audioBuffers = 2048;
GBAConfigLoadDefaults(&m_config, &m_opts);
GBAConfigLoad(&m_config);
GBAConfigMap(&m_config, &m_opts);
}
ConfigController::~ConfigController() {
write();
GBAConfigDeinit(&m_config);
GBAConfigFreeOpts(&m_opts);
}
bool ConfigController::parseArguments(GBAArguments* args, int argc, char* argv[]) {
return ::parseArguments(args, &m_config, argc, argv, 0);
}
ConfigOption* ConfigController::addOption(const char* key) {
QString optionName(key);
if (m_optionSet.contains(optionName)) {
return m_optionSet[optionName];
}
ConfigOption* newOption = new ConfigOption(this);
m_optionSet[optionName] = newOption;
connect(newOption, &ConfigOption::valueChanged, [this, key](const QVariant& value) {
setOption(key, value);
});
return newOption;
}
void ConfigController::updateOption(const char* key) {
if (!key) {
return;
}
QString optionName(key);
if (!m_optionSet.contains(optionName)) {
return;
}
m_optionSet[optionName]->setValue(GBAConfigGetValue(&m_config, key));
}
void ConfigController::setOption(const char* key, bool value) {
GBAConfigSetIntValue(&m_config, key, value);
QString optionName(key);
if (m_optionSet.contains(optionName)) {
m_optionSet[optionName]->setValue(value);
}
}
void ConfigController::setOption(const char* key, int value) {
GBAConfigSetIntValue(&m_config, key, value);
QString optionName(key);
if (m_optionSet.contains(optionName)) {
m_optionSet[optionName]->setValue(value);
}
}
void ConfigController::setOption(const char* key, unsigned value) {
GBAConfigSetUIntValue(&m_config, key, value);
QString optionName(key);
if (m_optionSet.contains(optionName)) {
m_optionSet[optionName]->setValue(value);
}
}
void ConfigController::setOption(const char* key, const char* value) {
GBAConfigSetValue(&m_config, key, value);
QString optionName(key);
if (m_optionSet.contains(optionName)) {
m_optionSet[optionName]->setValue(value);
}
}
void ConfigController::setOption(const char* key, const QVariant& value) {
if (value.type() == QVariant::Bool) {
setOption(key, value.toBool());
return;
}
QString stringValue(value.toString());
setOption(key, stringValue.toLocal8Bit().constData());
}
void ConfigController::write() {
GBAConfigSave(&m_config);
}
<|endoftext|> |
<commit_before>#include <iostream>
#include <stdexcept>
#include "Token.hpp"
#include "TokenStream.hpp"
#include "Calculator.hpp"
int main(int argc, char* argv[])
{
if(argc < 2)
{
std::cout << "There aren't any operations send to Calculator" << std::endl;
return 1;
}
std::cout << ">> " << argv[1] << std::endl;
std::string expression{argv[1]};
TokenStream tokenStream{expression + END_OF_EXPR + QUIT};
try
{
double value = 0;
Calculator parser{tokenStream};
while (std::cin)
{
try
{
Token token = tokenStream.get();
while (token.kind == END_OF_EXPR)
{
token = tokenStream.get();
}
if(token.kind == QUIT)
{
return 0;
}
tokenStream.putback(token);
value = parser.expression();
std::cout << "= " << value << std::endl;
}
catch (std::logic_error& error)
{
std::cerr << error.what() << std::endl;
clean(tokenStream);
}
}
return 0;
}
catch (std::logic_error& error)
{
std::cerr << error.what() << std::endl;
return 1;
}
catch (...)
{
std::cerr << "Unexpected exception";
return 2;
}
return 0;
}
<commit_msg>Splitting body of main into functions<commit_after>#include <iostream>
#include <stdexcept>
#include "Token.hpp"
#include "TokenStream.hpp"
#include "Calculator.hpp"
void calculate(ITokenStream& tokenStream)
{
double value = 0;
Calculator parser{tokenStream};
while (std::cin)
{
Token token = tokenStream.get();
while (token.kind == END_OF_EXPR)
{
token = tokenStream.get();
}
if(token.kind == QUIT)
{
return;
}
tokenStream.putback(token);
value = parser.expression();
std::cout << "= " << value << std::endl;
}
}
TokenStream passArgsToTokenStream(const char* argv[])
{
std::cout << ">> " << argv[1] << std::endl;
std::string expression{argv[1]};
TokenStream tokenStream{expression + END_OF_EXPR + QUIT};
return tokenStream;
}
int main(int argc, const char* argv[])
{
if(argc < 2)
{
std::cout << "There aren't any operations send to Calculator" << std::endl;
return 1;
}
TokenStream tokenStream = passArgsToTokenStream(argv);
try
{
calculate(tokenStream);
return 0;
}
catch (std::logic_error& error)
{
std::cerr << error.what() << std::endl;
clean(tokenStream);
return 1;
}
catch (...)
{
std::cerr << "Unexpected exception";
return 2;
}
}
<|endoftext|> |
<commit_before>/**************************************************************************
**
** This file is part of Qt Creator
**
** Copyright (c) 2011 Nokia Corporation and/or its subsidiary(-ies).
**
** Contact: Nokia Corporation (info@qt.nokia.com)
**
**
** GNU Lesser General Public License Usage
**
** 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.
**
** Other Usage
**
** Alternatively, this file may be used in accordance with the terms and
** conditions contained in a signed written agreement between you and Nokia.
**
** If you have questions regarding the use of this file, please contact
** Nokia at info@qt.nokia.com.
**
**************************************************************************/
#include "stackwindow.h"
#include "stackhandler.h"
#include "debuggeractions.h"
#include "debuggercore.h"
#include "debuggerengine.h"
#include "debuggerdialogs.h"
#include "memoryagent.h"
#include <utils/qtcassert.h>
#include <utils/savedaction.h>
#include <QtCore/QDebug>
#include <QtGui/QApplication>
#include <QtGui/QClipboard>
#include <QtGui/QContextMenuEvent>
#include <QtGui/QHeaderView>
#include <QtGui/QMenu>
namespace Debugger {
namespace Internal {
static DebuggerEngine *currentEngine()
{
return debuggerCore()->currentEngine();
}
StackWindow::StackWindow(QWidget *parent)
: BaseWindow(parent)
{
setWindowTitle(tr("Stack"));
setAlwaysAdjustColumnsAction(debuggerCore()->action(AlwaysAdjustStackColumnWidths));
connect(debuggerCore()->action(UseAddressInStackView), SIGNAL(toggled(bool)),
SLOT(showAddressColumn(bool)));
connect(debuggerCore()->action(ExpandStack), SIGNAL(triggered()),
SLOT(reloadFullStack()));
connect(debuggerCore()->action(MaximalStackDepth), SIGNAL(triggered()),
SLOT(reloadFullStack()));
showAddressColumn(false);
}
void StackWindow::showAddressColumn(bool on)
{
setColumnHidden(4, !on);
}
void StackWindow::rowActivated(const QModelIndex &index)
{
currentEngine()->activateFrame(index.row());
}
void StackWindow::setModel(QAbstractItemModel *model)
{
BaseWindow::setModel(model);
resizeColumnToContents(0);
resizeColumnToContents(3);
}
void StackWindow::contextMenuEvent(QContextMenuEvent *ev)
{
DebuggerEngine *engine = currentEngine();
StackHandler *handler = engine->stackHandler();
const QModelIndex index = indexAt(ev->pos());
const int row = index.row();
const unsigned engineCapabilities = engine->debuggerCapabilities();
StackFrame frame;
if (row >= 0 && row < handler->stackSize())
frame = handler->frameAt(row);
const quint64 address = frame.address;
QMenu menu;
menu.addAction(debuggerCore()->action(ExpandStack));
QAction *actCopyContents = menu.addAction(tr("Copy Contents to Clipboard"));
actCopyContents->setEnabled(model() != 0);
if (engineCapabilities & CreateFullBacktraceCapability)
menu.addAction(debuggerCore()->action(CreateFullBacktrace));
QAction *actShowMemory = menu.addAction(QString());
if (address == 0) {
actShowMemory->setText(tr("Open Memory Editor"));
actShowMemory->setEnabled(false);
} else {
actShowMemory->setText(tr("Open Memory Editor at 0x%1").arg(address, 0, 16));
actShowMemory->setEnabled(engineCapabilities & ShowMemoryCapability);
}
QAction *actShowDisassemblerAt = menu.addAction(QString());
QAction *actShowDisassembler = menu.addAction(tr("Open Disassembler..."));
actShowDisassembler->setEnabled(engineCapabilities & DisassemblerCapability);
if (address == 0) {
actShowDisassemblerAt->setText(tr("Open Disassembler"));
actShowDisassemblerAt->setEnabled(false);
} else {
actShowDisassemblerAt->setText(tr("Open Disassembler at 0x%1").arg(address, 0, 16));
actShowDisassemblerAt->setEnabled(engineCapabilities & DisassemblerCapability);
}
QAction *actLoadSymbols = 0;
if (engineCapabilities & ShowModuleSymbolsCapability)
actLoadSymbols = menu.addAction(tr("Try to Load Unknown Symbols"));
menu.addSeparator();
#if 0 // @TODO: not implemented
menu.addAction(debuggerCore()->action(UseToolTipsInStackView));
#endif
menu.addAction(debuggerCore()->action(UseAddressInStackView));
addBaseContextActions(&menu);
QAction *act = menu.exec(ev->globalPos());
if (act == actCopyContents)
copyContentsToClipboard();
else if (act == actShowMemory) {
const QString title = tr("Memory at Frame #%1 (%2) 0x%3").
arg(row).arg(frame.function).arg(address, 0, 16);
QList<MemoryMarkup> ml;
ml.push_back(MemoryMarkup(address, 1, QColor(Qt::blue).lighter(),
tr("Frame #%1 (%2)").arg(row).arg(frame.function)));
engine->openMemoryView(address, 0, ml, QPoint(), title);
} else if (act == actShowDisassembler) {
AddressDialog dialog;
if (address)
dialog.setAddress(address);
if (dialog.exec() == QDialog::Accepted)
currentEngine()->openDisassemblerView(Location(dialog.address()));
} else if (act == actShowDisassemblerAt)
engine->openDisassemblerView(frame);
else if (act == actLoadSymbols)
engine->loadSymbolsForStack();
else
handleBaseContextAction(act);
}
void StackWindow::copyContentsToClipboard()
{
QString str;
int n = model()->rowCount();
int m = model()->columnCount();
for (int i = 0; i != n; ++i) {
for (int j = 0; j != m; ++j) {
QModelIndex index = model()->index(i, j);
str += model()->data(index).toString();
str += '\t';
}
str += '\n';
}
QClipboard *clipboard = QApplication::clipboard();
# ifdef Q_WS_X11
clipboard->setText(str, QClipboard::Selection);
# endif
clipboard->setText(str, QClipboard::Clipboard);
}
void StackWindow::reloadFullStack()
{
currentEngine()->reloadFullStack();
}
} // namespace Internal
} // namespace Debugger
<commit_msg>Debugger: Show/Hide Address Column in Stack Window<commit_after>/**************************************************************************
**
** This file is part of Qt Creator
**
** Copyright (c) 2011 Nokia Corporation and/or its subsidiary(-ies).
**
** Contact: Nokia Corporation (info@qt.nokia.com)
**
**
** GNU Lesser General Public License Usage
**
** 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.
**
** Other Usage
**
** Alternatively, this file may be used in accordance with the terms and
** conditions contained in a signed written agreement between you and Nokia.
**
** If you have questions regarding the use of this file, please contact
** Nokia at info@qt.nokia.com.
**
**************************************************************************/
#include "stackwindow.h"
#include "stackhandler.h"
#include "debuggeractions.h"
#include "debuggercore.h"
#include "debuggerengine.h"
#include "debuggerdialogs.h"
#include "memoryagent.h"
#include <utils/qtcassert.h>
#include <utils/savedaction.h>
#include <QtCore/QDebug>
#include <QtGui/QApplication>
#include <QtGui/QClipboard>
#include <QtGui/QContextMenuEvent>
#include <QtGui/QHeaderView>
#include <QtGui/QMenu>
namespace Debugger {
namespace Internal {
static DebuggerEngine *currentEngine()
{
return debuggerCore()->currentEngine();
}
StackWindow::StackWindow(QWidget *parent)
: BaseWindow(parent)
{
setWindowTitle(tr("Stack"));
setAlwaysAdjustColumnsAction(debuggerCore()->action(AlwaysAdjustStackColumnWidths));
connect(debuggerCore()->action(UseAddressInStackView), SIGNAL(toggled(bool)),
SLOT(showAddressColumn(bool)));
connect(debuggerCore()->action(ExpandStack), SIGNAL(triggered()),
SLOT(reloadFullStack()));
connect(debuggerCore()->action(MaximalStackDepth), SIGNAL(triggered()),
SLOT(reloadFullStack()));
showAddressColumn(false);
}
void StackWindow::showAddressColumn(bool on)
{
setColumnHidden(4, !on);
}
void StackWindow::rowActivated(const QModelIndex &index)
{
currentEngine()->activateFrame(index.row());
}
void StackWindow::setModel(QAbstractItemModel *model)
{
BaseWindow::setModel(model);
resizeColumnToContents(0);
resizeColumnToContents(3);
showAddressColumn(debuggerCore()->action(UseAddressInStackView)->isChecked());
}
void StackWindow::contextMenuEvent(QContextMenuEvent *ev)
{
DebuggerEngine *engine = currentEngine();
StackHandler *handler = engine->stackHandler();
const QModelIndex index = indexAt(ev->pos());
const int row = index.row();
const unsigned engineCapabilities = engine->debuggerCapabilities();
StackFrame frame;
if (row >= 0 && row < handler->stackSize())
frame = handler->frameAt(row);
const quint64 address = frame.address;
QMenu menu;
menu.addAction(debuggerCore()->action(ExpandStack));
QAction *actCopyContents = menu.addAction(tr("Copy Contents to Clipboard"));
actCopyContents->setEnabled(model() != 0);
if (engineCapabilities & CreateFullBacktraceCapability)
menu.addAction(debuggerCore()->action(CreateFullBacktrace));
QAction *actShowMemory = menu.addAction(QString());
if (address == 0) {
actShowMemory->setText(tr("Open Memory Editor"));
actShowMemory->setEnabled(false);
} else {
actShowMemory->setText(tr("Open Memory Editor at 0x%1").arg(address, 0, 16));
actShowMemory->setEnabled(engineCapabilities & ShowMemoryCapability);
}
QAction *actShowDisassemblerAt = menu.addAction(QString());
QAction *actShowDisassembler = menu.addAction(tr("Open Disassembler..."));
actShowDisassembler->setEnabled(engineCapabilities & DisassemblerCapability);
if (address == 0) {
actShowDisassemblerAt->setText(tr("Open Disassembler"));
actShowDisassemblerAt->setEnabled(false);
} else {
actShowDisassemblerAt->setText(tr("Open Disassembler at 0x%1").arg(address, 0, 16));
actShowDisassemblerAt->setEnabled(engineCapabilities & DisassemblerCapability);
}
QAction *actLoadSymbols = 0;
if (engineCapabilities & ShowModuleSymbolsCapability)
actLoadSymbols = menu.addAction(tr("Try to Load Unknown Symbols"));
menu.addSeparator();
#if 0 // @TODO: not implemented
menu.addAction(debuggerCore()->action(UseToolTipsInStackView));
#endif
menu.addAction(debuggerCore()->action(UseAddressInStackView));
addBaseContextActions(&menu);
QAction *act = menu.exec(ev->globalPos());
if (act == actCopyContents)
copyContentsToClipboard();
else if (act == actShowMemory) {
const QString title = tr("Memory at Frame #%1 (%2) 0x%3").
arg(row).arg(frame.function).arg(address, 0, 16);
QList<MemoryMarkup> ml;
ml.push_back(MemoryMarkup(address, 1, QColor(Qt::blue).lighter(),
tr("Frame #%1 (%2)").arg(row).arg(frame.function)));
engine->openMemoryView(address, 0, ml, QPoint(), title);
} else if (act == actShowDisassembler) {
AddressDialog dialog;
if (address)
dialog.setAddress(address);
if (dialog.exec() == QDialog::Accepted)
currentEngine()->openDisassemblerView(Location(dialog.address()));
} else if (act == actShowDisassemblerAt)
engine->openDisassemblerView(frame);
else if (act == actLoadSymbols)
engine->loadSymbolsForStack();
else
handleBaseContextAction(act);
}
void StackWindow::copyContentsToClipboard()
{
QString str;
int n = model()->rowCount();
int m = model()->columnCount();
for (int i = 0; i != n; ++i) {
for (int j = 0; j != m; ++j) {
QModelIndex index = model()->index(i, j);
str += model()->data(index).toString();
str += '\t';
}
str += '\n';
}
QClipboard *clipboard = QApplication::clipboard();
# ifdef Q_WS_X11
clipboard->setText(str, QClipboard::Selection);
# endif
clipboard->setText(str, QClipboard::Clipboard);
}
void StackWindow::reloadFullStack()
{
currentEngine()->reloadFullStack();
}
} // namespace Internal
} // namespace Debugger
<|endoftext|> |
<commit_before>#include "pipeline.h"
#include <iostream>
int main()
{
using namespace pipeline;
auto for_each = [](auto&& rng){
return source([rng](auto&& sink){
for (auto const& x : rng) if (!sink(x)) return;
});
};
auto pipeline = []{
return filter ([](auto x){ return x>3; })
| transform ([](auto x){ return x*x; })
| filter ([](auto x){ return x<150; })
| transform ([](auto x){ return x-10; })
| take(3)
| repeat(2)
;
};
auto p = pipeline() | sink([](auto x) { std::cout << "sink: " << x << std::endl; return true; });
int n = 0;
do { std::cout << "source: " << n << std::endl; }
while ( p(n++) );
std::cout << "cancelled" << std::endl;
for_each(std::initializer_list<int>{1,2,3,4,5,6,7,8,9,10,11})
| pipeline()
| sink([](auto x) { std::cout << "sink: " << x << std::endl; return true; });;
std::cout << "cancelled" << std::endl;
}
<commit_msg>fixing for_each source to not capture range by value.<commit_after>#include "pipeline.h"
#include <iostream>
int main()
{
using namespace pipeline;
auto for_each = [](auto&& rng){
return source([&rng](auto&& sink){
for (auto const& x : rng) if (!sink(x)) return;
});
};
auto pipeline = []{
return filter ([](auto x){ return x>3; })
| transform ([](auto x){ return x*x; })
| filter ([](auto x){ return x<150; })
| transform ([](auto x){ return x-10; })
| take(3)
| repeat(2)
;
};
auto p = pipeline() | sink([](auto x) { std::cout << "sink: " << x << std::endl; return true; });
int n = 0;
do { std::cout << "source: " << n << std::endl; }
while ( p(n++) );
std::cout << "cancelled" << std::endl;
for_each(std::initializer_list<int>{1,2,3,4,5,6,7,8,9,10,11})
| pipeline()
| sink([](auto x) { std::cout << "sink: " << x << std::endl; return true; });;
std::cout << "cancelled" << std::endl;
}
<|endoftext|> |
<commit_before>/*
* Copyright(c) Sophist Solutions, Inc. 1990-2022. All rights reserved
*/
#ifndef _Stroika_Foundation_Execution_IntervalTimer_inl_
#define _Stroika_Foundation_Execution_IntervalTimer_inl_ 1
/*
********************************************************************************
***************************** Implementation Details ***************************
********************************************************************************
*/
namespace Stroika::Foundation::Execution {
/*
********************************************************************************
*************************** IntervalTimer::Manager *****************************
********************************************************************************
*/
inline IntervalTimer::Manager::Manager (const shared_ptr<IRep>& rep)
: fRep_{rep}
{
}
inline void IntervalTimer::Manager::AddOneShot (const TimerCallback& intervalTimer, const Time::Duration& when)
{
AssertNotNull (fRep_); // If this fails, and its accessed through IntervalTimer::Manager::sThe, its probably because of lack of construction of IntervalTimer::Manager::Active object.
fRep_->AddOneShot (intervalTimer, when);
}
inline void IntervalTimer::Manager ::AddRepeating (const TimerCallback& intervalTimer, const Time::Duration& repeatInterval, const optional<Time::Duration>& hysteresis)
{
AssertNotNull (fRep_); // If this fails, and its accessed through IntervalTimer::Manager::sThe, its probably because of lack of construction of IntervalTimer::Manager::Active object.
fRep_->AddRepeating (intervalTimer, repeatInterval, hysteresis);
}
inline void IntervalTimer::Manager::RemoveRepeating (const TimerCallback& intervalTimer) noexcept
{
AssertNotNull (fRep_); // If this fails, and its accessed through IntervalTimer::Manager::sThe, its probably because of lack of construction of IntervalTimer::Manager::Active object.
fRep_->RemoveRepeating (intervalTimer);
}
inline IntervalTimer::Manager IntervalTimer::Manager::sThe{nullptr};
/*
********************************************************************************
***************************** IntervalTimer::Adder *****************************
********************************************************************************
*/
inline IntervalTimer::Adder::Adder (IntervalTimer::Manager& manager, const Function<void (void)>& f, const Time::Duration& repeatInterval, RunImmediatelyFlag runImmediately, const optional<Time::Duration>& hysteresis)
: fRepeatInterval_{repeatInterval}
, fHysteresis_{hysteresis}
, fManager_{&manager}
, fFunction_{f}
{
Manager::sThe.AddRepeating (fFunction_, repeatInterval, hysteresis);
if (runImmediately == RunImmediatelyFlag::eRunImmediately) {
fFunction_ ();
}
}
inline IntervalTimer::Adder::Adder (const Function<void (void)>& f, const Time::Duration& repeatInterval, RunImmediatelyFlag runImmediately, const optional<Time::Duration>& hysteresis)
: Adder{Manager::sThe, f, repeatInterval, runImmediately, hysteresis}
{
}
inline IntervalTimer::Adder::Adder (IntervalTimer::Manager& manager, const Function<void (void)>& f, const Time::Duration& repeatInterval, RunImmediatelyFlag runImmediately)
: Adder{manager, f, repeatInterval, runImmediately, nullopt}
{
}
inline IntervalTimer::Adder::Adder (const Function<void (void)>& f, const Time::Duration& repeatInterval, RunImmediatelyFlag runImmediately)
: Adder{f, repeatInterval, runImmediately, nullopt}
{
}
inline IntervalTimer::Adder::Adder (IntervalTimer::Manager& manager, const Function<void (void)>& f, const Time::Duration& repeatInterval, const optional<Time::Duration>& hysteresis)
: Adder{manager, f, repeatInterval, RunImmediatelyFlag::eDontRunImmediately, hysteresis}
{
}
inline IntervalTimer::Adder::Adder (const Function<void (void)>& f, const Time::Duration& repeatInterval, const optional<Time::Duration>& hysteresis)
: Adder{Manager::sThe, f, repeatInterval, RunImmediatelyFlag::eDontRunImmediately, hysteresis}
{
}
inline IntervalTimer::Adder::Adder (Adder&& src)
: fRepeatInterval_{move (src.fRepeatInterval_)}
, fHysteresis_{move (src.fHysteresis_)}
, fManager_{src.fManager_}
, fFunction_{move (src.fFunction_)}
{
// Move does not trigger re-add to manager
src.fManager_ = nullptr; // so its DTOR does nothing
}
inline IntervalTimer::Adder::~Adder ()
{
if (fManager_ != nullptr) { // null check cuz Adder can be moved
fManager_->RemoveRepeating (fFunction_);
}
}
inline IntervalTimer::Adder& IntervalTimer::Adder::operator= (Adder&& rhs)
{
if (this != &rhs) {
if (fManager_ != nullptr) { // null check cuz Adder can be moved
fManager_->RemoveRepeating (fFunction_);
}
fManager_ = rhs.fManager_;
rhs.fManager_ = nullptr; // so its DTOR doesnt remove
fFunction_ = move (rhs.fFunction_);
Manager::sThe.AddRepeating (fFunction_, fRepeatInterval_, fHysteresis_);
}
return *this;
}
inline Function<void (void)> IntervalTimer::Adder::GetCallback () const
{
return fFunction_;
}
}
#endif /*_Stroika_Foundation_Execution_IntervalTimer_inl_*/
<commit_msg>tweak last checkin<commit_after>/*
* Copyright(c) Sophist Solutions, Inc. 1990-2022. All rights reserved
*/
#ifndef _Stroika_Foundation_Execution_IntervalTimer_inl_
#define _Stroika_Foundation_Execution_IntervalTimer_inl_ 1
/*
********************************************************************************
***************************** Implementation Details ***************************
********************************************************************************
*/
namespace Stroika::Foundation::Execution {
/*
********************************************************************************
*************************** IntervalTimer::Manager *****************************
********************************************************************************
*/
inline IntervalTimer::Manager::Manager (const shared_ptr<IRep>& rep)
: fRep_{rep}
{
}
inline void IntervalTimer::Manager::AddOneShot (const TimerCallback& intervalTimer, const Time::Duration& when)
{
AssertNotNull (fRep_); // If this fails, and its accessed through IntervalTimer::Manager::sThe, its probably because of lack of construction of IntervalTimer::Manager::Active object.
fRep_->AddOneShot (intervalTimer, when);
}
inline void IntervalTimer::Manager ::AddRepeating (const TimerCallback& intervalTimer, const Time::Duration& repeatInterval, const optional<Time::Duration>& hysteresis)
{
AssertNotNull (fRep_); // If this fails, and its accessed through IntervalTimer::Manager::sThe, its probably because of lack of construction of IntervalTimer::Manager::Active object.
fRep_->AddRepeating (intervalTimer, repeatInterval, hysteresis);
}
inline void IntervalTimer::Manager::RemoveRepeating (const TimerCallback& intervalTimer) noexcept
{
AssertNotNull (fRep_); // If this fails, and its accessed through IntervalTimer::Manager::sThe, its probably because of lack of construction of IntervalTimer::Manager::Active object.
fRep_->RemoveRepeating (intervalTimer);
}
inline IntervalTimer::Manager IntervalTimer::Manager::sThe{nullptr};
/*
********************************************************************************
***************************** IntervalTimer::Adder *****************************
********************************************************************************
*/
inline IntervalTimer::Adder::Adder (IntervalTimer::Manager& manager, const Function<void (void)>& f, const Time::Duration& repeatInterval, RunImmediatelyFlag runImmediately, const optional<Time::Duration>& hysteresis)
: fRepeatInterval_{repeatInterval}
, fHysteresis_{hysteresis}
, fManager_{&manager}
, fFunction_{f}
{
Manager::sThe.AddRepeating (fFunction_, repeatInterval, hysteresis);
if (runImmediately == RunImmediatelyFlag::eRunImmediately) {
IgnoreExceptionsExceptThreadAbortForCall (fFunction_ ());
}
}
inline IntervalTimer::Adder::Adder (const Function<void (void)>& f, const Time::Duration& repeatInterval, RunImmediatelyFlag runImmediately, const optional<Time::Duration>& hysteresis)
: Adder{Manager::sThe, f, repeatInterval, runImmediately, hysteresis}
{
}
inline IntervalTimer::Adder::Adder (IntervalTimer::Manager& manager, const Function<void (void)>& f, const Time::Duration& repeatInterval, RunImmediatelyFlag runImmediately)
: Adder{manager, f, repeatInterval, runImmediately, nullopt}
{
}
inline IntervalTimer::Adder::Adder (const Function<void (void)>& f, const Time::Duration& repeatInterval, RunImmediatelyFlag runImmediately)
: Adder{f, repeatInterval, runImmediately, nullopt}
{
}
inline IntervalTimer::Adder::Adder (IntervalTimer::Manager& manager, const Function<void (void)>& f, const Time::Duration& repeatInterval, const optional<Time::Duration>& hysteresis)
: Adder{manager, f, repeatInterval, RunImmediatelyFlag::eDontRunImmediately, hysteresis}
{
}
inline IntervalTimer::Adder::Adder (const Function<void (void)>& f, const Time::Duration& repeatInterval, const optional<Time::Duration>& hysteresis)
: Adder{Manager::sThe, f, repeatInterval, RunImmediatelyFlag::eDontRunImmediately, hysteresis}
{
}
inline IntervalTimer::Adder::Adder (Adder&& src)
: fRepeatInterval_{move (src.fRepeatInterval_)}
, fHysteresis_{move (src.fHysteresis_)}
, fManager_{src.fManager_}
, fFunction_{move (src.fFunction_)}
{
// Move does not trigger re-add to manager
src.fManager_ = nullptr; // so its DTOR does nothing
}
inline IntervalTimer::Adder::~Adder ()
{
if (fManager_ != nullptr) { // null check cuz Adder can be moved
fManager_->RemoveRepeating (fFunction_);
}
}
inline IntervalTimer::Adder& IntervalTimer::Adder::operator= (Adder&& rhs)
{
if (this != &rhs) {
if (fManager_ != nullptr) { // null check cuz Adder can be moved
fManager_->RemoveRepeating (fFunction_);
}
fManager_ = rhs.fManager_;
rhs.fManager_ = nullptr; // so its DTOR doesnt remove
fFunction_ = move (rhs.fFunction_);
Manager::sThe.AddRepeating (fFunction_, fRepeatInterval_, fHysteresis_);
}
return *this;
}
inline Function<void (void)> IntervalTimer::Adder::GetCallback () const
{
return fFunction_;
}
}
#endif /*_Stroika_Foundation_Execution_IntervalTimer_inl_*/
<|endoftext|> |
<commit_before>
#include <arpa/inet.h>
#include <string>
#include "format.h"
#include "config.h"
#include "error.h"
#include "udp_socket.h"
#include "strutils.h"
////////////////////////////////////////
std::string pack_name( const std::string &name )
{
std::string ret;
size_t loc = 0;
ret.push_back( '\0' );
for ( size_t i = 0; i < name.size(); ++i )
{
if ( std::isalnum( name[i] ) )
{
ret.push_back( name[i] );
ret[loc]++;
}
else if ( name[i] == '.' )
{
loc = ret.size();
ret.push_back( '\0' );
}
else if ( !std::isspace( name[i] ) )
error( "Invalid character in domain name" );
}
if ( ret.back() == '\0' )
error( "Domain name ended with '.'" );
if ( ret.empty() )
error( "Domain name is empty." );
ret.push_back( '\0' );
return ret;
}
////////////////////////////////////////
void unpack_names( const std::string &str, std::vector<std::string> &n )
{
std::string ret;
for ( size_t i = 0; i < str.size(); )
{
uint8_t s = str[i++];
if ( s == 0 )
{
if ( !ret.empty() )
n.push_back( ret );
ret.clear();
}
else
{
if ( !ret.empty() )
ret.push_back( '.' );
ret += str.substr( i, s );
i += s;
}
}
if ( !ret.empty() )
n.push_back( ret );
}
////////////////////////////////////////
std::string from_hex( const std::string &h )
{
std::string ret;
for ( size_t i = 0; i+1 < h.size(); i += 2 )
ret.push_back( std::stoul( h.substr( i, 2 ), NULL, 16 ) );
return ret;
}
////////////////////////////////////////
std::string parse_mac( const std::string &opt )
{
std::string ret( 6, '\0' );
size_t p = 0;
for ( size_t i = 0; i < ret.size(); ++i )
{
size_t tmp = p;
uint32_t v = std::stoi( opt.substr( p ), &tmp, 16 );
ret[i] = v;
p += tmp + 1;
}
return ret;
}
////////////////////////////////////////
std::string parse_option( const std::string &opt )
{
std::string name;
std::vector<std::string> args;
parse_function( opt, name, args );
if ( dhcp_options.find( name ) == dhcp_options.end() )
error( format( "Unknown DHCP option '{0}'", name ) );
int o = dhcp_options[name];
std::vector<Type> &argtypes = dhcp_args[o];
if ( argtypes.back() == TYPE_MORE )
{
argtypes.pop_back();
while ( argtypes.size() < args.size() )
argtypes.push_back( argtypes.back() );
}
if ( argtypes.size() == 1 && argtypes[0] == TYPE_NAMES )
{
while ( argtypes.size() < args.size() )
argtypes.push_back( argtypes.back() );
}
if ( argtypes.size() != args.size() )
error( format( "Expected {0} arguments, got {1} instead", argtypes.size(), args.size() ) );
std::string ret;
ret.push_back( o );
ret.push_back( '\0' );
size_t size = 0;
for ( size_t i = 0; i < args.size(); ++i )
{
switch ( argtypes[i] )
{
case TYPE_ADDRESS:
{
size += 4;
uint32_t ip = dns_lookup( args[i].c_str() );
ret.append( std::string( reinterpret_cast<const char*>(&ip), 4 ) );
break;
}
case TYPE_HWADDR:
error( "Not yet implemented" );
break;
case TYPE_STRING:
size += args[i].size();
ret.append( args[i] );
break;
case TYPE_NAMES:
{
std::string tmp = pack_name( args[i] );
ret.append( tmp );
size += tmp.size();
break;
}
case TYPE_UINT32:
{
size += 4;
uint32_t ip = std::stoul( args[i] );
ret.append( reinterpret_cast<const char *>(&ip), 4 );
break;
}
case TYPE_UINT16:
{
size += 2;
uint16_t n = htons( std::stoul( args[i] ) );
ret.append( reinterpret_cast<const char*>( &n ), 2 );
break;
}
case TYPE_UINT8:
{
size += 1;
uint32_t n = std::stoul( args[0] );
if ( n > 255 )
error( format( "Number (argument {0}) too large for option {1}", i, name ) );
ret.push_back( n );
break;
}
case TYPE_HEX:
{
std::string hex = from_hex( args[i] );
ret.push_back( hex.size() );
ret.append( hex );
break;
}
default:
error( "Unknown option type" );
break;
}
}
ret[1] = size;
return ret;
}
////////////////////////////////////////
std::string print_options( const std::string &opt )
{
std::string ret;
if ( opt.empty() )
error( "Invalid empty option" );
auto name = dhcp_names.find( uint8_t(opt[0]) );
if ( name == dhcp_names.end() )
{
ret = format( "{0,B16,w2,f0}", as_hex<char>( opt ) );
return ret;
}
ret += name->second;
ret.push_back( '(' );
std::vector<Type> &argtypes = dhcp_args[uint8_t(opt[0])];
size_t p = 2;
Type last = TYPE_MORE;
for ( size_t i = 0; i < argtypes.size(); ++i )
{
if ( i > 0 )
ret.push_back( ',' );
ret.push_back( ' ' );
Type atype = argtypes[i];
if ( atype == TYPE_MORE )
atype = last;
if ( atype == TYPE_MORE )
error( "Invalid option specification" );
switch ( atype )
{
case TYPE_ADDRESS:
if ( p+4 > opt.size() )
error( "Not enough data for IP address" );
ret += format( "{0}", as_hex<char>( &opt[p], 4, '.' ) );
break;
case TYPE_HWADDR:
error( "Not yet implemented" );
break;
case TYPE_UINT32:
{
if ( p+4 > opt.size() )
error( "Not enough data for uint32" );
uint32_t n = 0;
for ( int i = 0; i < 4; ++i )
n = ( n << 8 ) + uint8_t(opt[p+i]);
ret += format( "{0}", n );
break;
}
case TYPE_UINT16:
{
if ( p+2 > opt.size() )
error( "Not enough data for uint16" );
uint32_t n = 0;
for ( int i = 0; i < 2; ++i )
n = ( n << 8 ) + uint8_t(opt[p+i]);
ret += format( "{0}", n );
break;
}
case TYPE_UINT8:
{
if ( p+1 > opt.size() )
error( "Not enough data for uint8" );
uint32_t n = uint8_t(opt[p]);
ret += format( "{0}", n );
break;
}
case TYPE_STRING:
ret += opt.substr( p, size_t(uint8_t(opt[1])) );
break;
case TYPE_HEX:
{
if ( opt.size() < 3 )
error( format( "Invalid option size {0}", opt.size() ) );
ret += format( "{0,B16,w2,f0}", as_hex<char>( opt.substr( 2, opt[1] ) ) );
break;
}
case TYPE_NAMES:
{
std::vector<std::string> names;
unpack_names( opt.substr( p, size_t(uint8_t(opt[1])) ), names );
for ( size_t i = 0; i < names.size(); ++i )
{
if ( i > 0 )
ret.append( ", " );
ret += names[i];
}
break;
}
default:
error( "Unknown option type" );
break;
}
last = atype;
}
ret += " )";
return ret;
}
<commit_msg>Fixed various bugs when printing options.<commit_after>
#include <arpa/inet.h>
#include <string>
#include "format.h"
#include "config.h"
#include "error.h"
#include "udp_socket.h"
#include "strutils.h"
////////////////////////////////////////
std::string pack_name( const std::string &name )
{
std::string ret;
size_t loc = 0;
ret.push_back( '\0' );
for ( size_t i = 0; i < name.size(); ++i )
{
if ( std::isalnum( name[i] ) )
{
ret.push_back( name[i] );
ret[loc]++;
}
else if ( name[i] == '.' )
{
loc = ret.size();
ret.push_back( '\0' );
}
else if ( !std::isspace( name[i] ) )
error( "Invalid character in domain name" );
}
if ( ret.back() == '\0' )
error( "Domain name ended with '.'" );
if ( ret.empty() )
error( "Domain name is empty." );
ret.push_back( '\0' );
return ret;
}
////////////////////////////////////////
void unpack_names( const std::string &str, std::vector<std::string> &n )
{
std::string ret;
for ( size_t i = 0; i < str.size(); )
{
uint8_t s = str[i++];
if ( s == 0 )
{
if ( !ret.empty() )
n.push_back( ret );
ret.clear();
}
else
{
if ( !ret.empty() )
ret.push_back( '.' );
ret += str.substr( i, s );
i += s;
}
}
if ( !ret.empty() )
n.push_back( ret );
}
////////////////////////////////////////
std::string from_hex( const std::string &h )
{
std::string ret;
for ( size_t i = 0; i+1 < h.size(); i += 2 )
ret.push_back( std::stoul( h.substr( i, 2 ), NULL, 16 ) );
return ret;
}
////////////////////////////////////////
std::string parse_mac( const std::string &opt )
{
std::string ret( 6, '\0' );
size_t p = 0;
for ( size_t i = 0; i < ret.size(); ++i )
{
size_t tmp = p;
uint32_t v = std::stoi( opt.substr( p ), &tmp, 16 );
ret[i] = v;
p += tmp + 1;
}
return ret;
}
////////////////////////////////////////
std::string parse_option( const std::string &opt )
{
std::string name;
std::vector<std::string> args;
parse_function( opt, name, args );
if ( dhcp_options.find( name ) == dhcp_options.end() )
error( format( "Unknown DHCP option '{0}'", name ) );
int o = dhcp_options[name];
std::vector<Type> argtypes = dhcp_args[o];
if ( argtypes.back() == TYPE_MORE )
{
argtypes.pop_back();
while ( argtypes.size() < args.size() )
argtypes.push_back( argtypes.back() );
}
if ( argtypes.size() == 1 && argtypes[0] == TYPE_NAMES )
{
while ( argtypes.size() < args.size() )
argtypes.push_back( argtypes.back() );
}
if ( argtypes.size() != args.size() )
error( format( "Expected {0} arguments, got {1} instead", argtypes.size(), args.size() ) );
std::string ret;
ret.push_back( o );
ret.push_back( '\0' );
size_t size = 0;
for ( size_t i = 0; i < args.size(); ++i )
{
switch ( argtypes[i] )
{
case TYPE_ADDRESS:
{
size += 4;
uint32_t ip = dns_lookup( args[i].c_str() );
ret.append( std::string( reinterpret_cast<const char*>(&ip), 4 ) );
break;
}
case TYPE_HWADDR:
error( "Not yet implemented" );
break;
case TYPE_STRING:
size += args[i].size();
ret.append( args[i] );
break;
case TYPE_NAMES:
{
std::string tmp = pack_name( args[i] );
ret.append( tmp );
size += tmp.size();
break;
}
case TYPE_UINT32:
{
size += 4;
uint32_t ip = std::stoul( args[i] );
ret.append( reinterpret_cast<const char *>(&ip), 4 );
break;
}
case TYPE_UINT16:
{
size += 2;
uint16_t n = htons( std::stoul( args[i] ) );
ret.append( reinterpret_cast<const char*>( &n ), 2 );
break;
}
case TYPE_UINT8:
{
size += 1;
uint32_t n = std::stoul( args[i] );
if ( n > 255 )
error( format( "Number (argument {0}) too large for option {1}", i, name ) );
ret.push_back( n );
break;
}
case TYPE_HEX:
{
std::string hex = from_hex( args[i] );
ret.push_back( hex.size() );
ret.append( hex );
break;
}
default:
error( "Unknown option type" );
break;
}
}
ret[1] = size;
return ret;
}
////////////////////////////////////////
std::string print_options( const std::string &opt )
{
std::string ret;
if ( opt.empty() )
error( "Invalid empty option" );
auto name = dhcp_names.find( uint8_t(opt[0]) );
if ( name == dhcp_names.end() )
{
ret = format( "{0,B16,w2,f0}", as_hex<char>( opt ) );
return ret;
}
ret += name->second;
ret.push_back( '(' );
std::vector<Type> argtypes = dhcp_args[uint8_t(opt[0])];
size_t p = 2;
Type last = TYPE_MORE;
for ( size_t i = 0; i < argtypes.size() && p != opt.size(); ++i )
{
if ( i > 0 )
ret.push_back( ',' );
ret.push_back( ' ' );
Type atype = argtypes[i];
if ( atype == TYPE_MORE )
{
atype = last;
argtypes.push_back( TYPE_MORE );
}
if ( atype == TYPE_MORE )
error( "Invalid option specification" );
switch ( atype )
{
case TYPE_ADDRESS:
if ( p+4 > opt.size() )
error( "Not enough data for IP address" );
ret += format( "{0}", as_hex<char>( &opt[p], 4, '.' ) );
p += 4;
break;
case TYPE_HWADDR:
error( "Not yet implemented" );
break;
case TYPE_UINT32:
{
if ( p+4 > opt.size() )
error( "Not enough data for uint32" );
uint32_t n = 0;
for ( int i = 0; i < 4; ++i )
n = ( n << 8 ) + uint8_t(opt[p+i]);
ret += format( "{0}", n );
p += 4;
break;
}
case TYPE_UINT16:
{
if ( p+2 > opt.size() )
error( "Not enough data for uint16" );
uint32_t n = 0;
for ( int i = 0; i < 2; ++i )
n = ( n << 8 ) + uint8_t(opt[p+i]);
ret += format( "{0}", n );
p += 2;
break;
}
case TYPE_UINT8:
{
if ( p+1 > opt.size() )
error( "Not enough data for uint8" );
uint32_t n = uint8_t(opt[p]);
ret += format( "{0}", n );
p += 1;
break;
}
case TYPE_STRING:
{
size_t size = uint8_t( opt[1] );
ret += opt.substr( p, size );
p += size;
break;
}
case TYPE_HEX:
{
if ( opt.size() < 3 )
error( format( "Invalid option size {0}", opt.size() ) );
size_t size = uint8_t( opt[1] );
ret += format( "{0,B16,w2,f0}", as_hex<char>( opt.substr( 2, size ) ) );
p += size;
break;
}
case TYPE_NAMES:
{
std::vector<std::string> names;
size_t size = uint8_t( opt[1] );
unpack_names( opt.substr( p, size ), names );
for ( size_t i = 0; i < names.size(); ++i )
{
if ( i > 0 )
ret.append( ", " );
ret += names[i];
}
p += size;
break;
}
default:
error( "Unknown option type" );
break;
}
last = atype;
}
ret += " )";
return ret;
}
<|endoftext|> |
<commit_before>/*
* Copyright(c) Sophist Solutions, Inc. 1990-2018. All rights reserved
*/
#ifndef _Stroika_Foundation_Memory_SmallStackBuffer_inl_
#define _Stroika_Foundation_Memory_SmallStackBuffer_inl_ 1
/*
********************************************************************************
***************************** Implementation Details ***************************
********************************************************************************
*/
#include <algorithm>
#include <cstring>
#include <type_traits>
#include "../Debug/Assertions.h"
#include "../Execution/Exceptions.h"
#include "Common.h"
namespace Stroika::Foundation::Memory {
/*
********************************************************************************
************************* SmallStackBuffer<T, BUF_SIZE> ************************
********************************************************************************
*/
template <typename T, size_t BUF_SIZE>
inline SmallStackBuffer<T, BUF_SIZE>::SmallStackBuffer ()
: fLiveData_ (BufferAsT_ ())
{
#if qDebug
::memcpy (fGuard1_, kGuard1_, sizeof (kGuard1_));
::memcpy (fGuard2_, kGuard2_, sizeof (kGuard2_));
#endif
Invariant ();
}
template <typename T, size_t BUF_SIZE>
inline SmallStackBuffer<T, BUF_SIZE>::SmallStackBuffer (size_t nElements)
: SmallStackBuffer ()
{
resize (nElements);
Invariant ();
}
template <typename T, size_t BUF_SIZE>
inline SmallStackBuffer<T, BUF_SIZE>::SmallStackBuffer (UninitializedConstructorFlag, size_t nElements)
: SmallStackBuffer ()
{
static_assert (is_trivially_default_constructible_v<T>);
resize_uninitialized (nElements);
Invariant ();
}
template <typename T, size_t BUF_SIZE>
template <typename ITERATOR_OF_T, enable_if_t<Configuration::is_iterator_v<ITERATOR_OF_T>, char>*>
SmallStackBuffer<T, BUF_SIZE>::SmallStackBuffer (ITERATOR_OF_T start, ITERATOR_OF_T end)
: SmallStackBuffer (distance (start, end))
{
#if qCompilerAndStdLib_uninitialized_copy_n_Warning_Buggy
Configuration::uninitialized_copy_MSFT_BWA (start, end, this->begin ());
#else
uninitialized_copy (start, end, this->begin ());
#endif
Invariant ();
}
template <typename T, size_t BUF_SIZE>
template <size_t FROM_BUF_SIZE>
SmallStackBuffer<T, BUF_SIZE>::SmallStackBuffer (const SmallStackBuffer<T, FROM_BUF_SIZE>& from)
: SmallStackBuffer (from.begin (), from.end ())
{
}
template <typename T, size_t BUF_SIZE>
inline SmallStackBuffer<T, BUF_SIZE>::SmallStackBuffer (const SmallStackBuffer& from)
: SmallStackBuffer (from.begin (), from.end ())
{
}
template <typename T, size_t BUF_SIZE>
inline SmallStackBuffer<T, BUF_SIZE>::~SmallStackBuffer ()
{
Invariant ();
DestroyElts_ (this->begin (), this->end ());
if (fLiveData_ != BufferAsT_ ()) {
// we must have used the heap...
Deallocate_ (LiveDataAsAllocatedBytes_ ());
}
}
template <typename T, size_t BUF_SIZE>
template <size_t FROM_BUF_SIZE>
SmallStackBuffer<T, BUF_SIZE>& SmallStackBuffer<T, BUF_SIZE>::operator= (const SmallStackBuffer<T, FROM_BUF_SIZE>& rhs)
{
Invariant ();
// @todo this simple implementation could be more efficient
DestroyElts_ (this->begin (), this->end ());
fSize_ = 0;
ReserveAtLeast (rhs.size ());
#if qCompilerAndStdLib_uninitialized_copy_n_Warning_Buggy
Configuration::uninitialized_copy_MSFT_BWA (rhs.begin (), rhs.end (), this->begin ());
#else
uninitialized_copy (rhs.begin (), rhs.end (), this->begin ());
#endif
Invariant ();
return *this;
}
template <typename T, size_t BUF_SIZE>
SmallStackBuffer<T, BUF_SIZE>& SmallStackBuffer<T, BUF_SIZE>::operator= (const SmallStackBuffer& rhs)
{
Invariant ();
if (this != &rhs) {
// @todo this simple implementation could be more efficient
DestroyElts_ (this->begin (), this->end ());
fSize_ = 0;
ReserveAtLeast (rhs.size ());
#if qCompilerAndStdLib_uninitialized_copy_n_Warning_Buggy
Configuration::uninitialized_copy_MSFT_BWA (rhs.begin (), rhs.end (), this->begin ());
#else
uninitialized_copy (rhs.begin (), rhs.end (), this->begin ());
#endif
Invariant ();
}
return *this;
}
template <typename T, size_t BUF_SIZE>
inline void SmallStackBuffer<T, BUF_SIZE>::GrowToSize (size_t nElements)
{
if (nElements > size ()) {
resize (nElements);
}
}
template <typename T, size_t BUF_SIZE>
inline void SmallStackBuffer<T, BUF_SIZE>::GrowToSize_uninitialized (size_t nElements)
{
static_assert (is_trivially_default_constructible_v<T>);
if (nElements > size ()) {
resize_uninitialized (nElements);
}
}
template <typename T, size_t BUF_SIZE>
inline void SmallStackBuffer<T, BUF_SIZE>::resize (size_t nElements)
{
if (nElements > fSize_) {
// Growing
if (nElements > capacity ()) {
/*
* If we REALLY must grow, the double in size so unlikely we'll have to grow/malloc/copy again.
*/
reserve (max (nElements, capacity () * 2));
}
uninitialized_fill (this->begin () + fSize_, this->begin () + nElements, T{});
fSize_ = nElements;
}
else if (nElements < fSize_) {
// Shrinking
DestroyElts_ (this->begin () + nElements, this->end ());
fSize_ = nElements;
}
Assert (fSize_ == nElements);
Ensure (size () <= capacity ());
}
template <typename T, size_t BUF_SIZE>
inline void SmallStackBuffer<T, BUF_SIZE>::resize_uninitialized (size_t nElements)
{
static_assert (is_trivially_default_constructible_v<T>);
if (nElements > fSize_) {
// Growing
if (nElements > capacity ())
[[UNLIKELY_ATTR]]
{
/*
* If we REALLY must grow, the double in size so unlikely we'll have to grow/malloc/copy again.
*/
reserve (max (nElements, capacity () * 2));
}
fSize_ = nElements;
}
else if (nElements < fSize_) {
// Shrinking
DestroyElts_ (this->begin () + nElements, this->end ());
fSize_ = nElements;
}
Assert (fSize_ == nElements);
Ensure (size () <= capacity ());
}
template <typename T, size_t BUF_SIZE>
void SmallStackBuffer<T, BUF_SIZE>::reserve_ (size_t nElements)
{
Assert (nElements >= size ());
Invariant ();
size_t oldEltCount = capacity ();
if (nElements != oldEltCount) {
bool oldInPlaceBuffer = oldEltCount <= BUF_SIZE;
bool newInPlaceBuffer = nElements <= BUF_SIZE;
// Only if we changed if using inplace buffer, or if was and is using ramBuffer, and eltCount changed do we need to do anything
if (oldInPlaceBuffer != newInPlaceBuffer or (not newInPlaceBuffer)) {
bool memoryAllocationNeeded = not newInPlaceBuffer;
Memory::Byte* newPtr = memoryAllocationNeeded ? Allocate_ (SizeInBytes_ (nElements)) : std::begin (fInlinePreallocatedBuffer_);
// Initialize new memory from old
Assert (this->begin () != reinterpret_cast<T*> (newPtr));
#if qCompilerAndStdLib_uninitialized_copy_n_Warning_Buggy
Configuration::uninitialized_copy_MSFT_BWA (this->begin (), this->end (), reinterpret_cast<T*> (newPtr));
#else
uninitialized_copy (this->begin (), this->end (), reinterpret_cast<T*> (newPtr));
#endif
// destroy objects in old memory
DestroyElts_ (this->begin (), this->end ());
// free old memory if needed
if (not oldInPlaceBuffer) {
Assert (fLiveData_ != BufferAsT_ ());
Deallocate_ (LiveDataAsAllocatedBytes_ ());
}
fLiveData_ = reinterpret_cast<T*> (newPtr);
if (not newInPlaceBuffer) {
fCapacityOfFreeStoreAllocation_ = nElements;
}
}
}
Ensure ((nElements <= BUF_SIZE && capacity () == BUF_SIZE) or (nElements > BUF_SIZE and nElements == capacity ()));
Invariant ();
}
template <typename T, size_t BUF_SIZE>
inline typename SmallStackBuffer<T, BUF_SIZE>::iterator SmallStackBuffer<T, BUF_SIZE>::begin ()
{
return fLiveData_;
}
template <typename T, size_t BUF_SIZE>
inline typename SmallStackBuffer<T, BUF_SIZE>::iterator SmallStackBuffer<T, BUF_SIZE>::end ()
{
return fLiveData_ + fSize_;
}
template <typename T, size_t BUF_SIZE>
inline typename SmallStackBuffer<T, BUF_SIZE>::const_iterator SmallStackBuffer<T, BUF_SIZE>::begin () const
{
return fLiveData_;
}
template <typename T, size_t BUF_SIZE>
inline typename SmallStackBuffer<T, BUF_SIZE>::const_iterator SmallStackBuffer<T, BUF_SIZE>::end () const
{
return fLiveData_ + fSize_;
}
template <typename T, size_t BUF_SIZE>
inline size_t SmallStackBuffer<T, BUF_SIZE>::capacity () const
{
return (fLiveData_ == BufferAsT_ ()) ? BUF_SIZE : fCapacityOfFreeStoreAllocation_; // @see class Design Note
}
template <typename T, size_t BUF_SIZE>
inline void SmallStackBuffer<T, BUF_SIZE>::reserve (size_t newCapacity)
{
Require (newCapacity >= size ());
reserve_ (newCapacity);
}
template <typename T, size_t BUF_SIZE>
inline void SmallStackBuffer<T, BUF_SIZE>::ReserveAtLeast (size_t newCapacity)
{
if (newCapacity > capacity ()) {
reserve_ (newCapacity);
}
}
template <typename T, size_t BUF_SIZE>
inline size_t SmallStackBuffer<T, BUF_SIZE>::GetSize () const
{
Ensure (fSize_ <= capacity ());
return fSize_;
}
template <typename T, size_t BUF_SIZE>
inline size_t SmallStackBuffer<T, BUF_SIZE>::size () const
{
Ensure (fSize_ <= capacity ());
return fSize_;
}
template <typename T, size_t BUF_SIZE>
inline typename SmallStackBuffer<T, BUF_SIZE>::reference SmallStackBuffer<T, BUF_SIZE>::at (size_t i)
{
Require (i < fSize_);
return *(fLiveData_ + i);
}
template <typename T, size_t BUF_SIZE>
inline typename SmallStackBuffer<T, BUF_SIZE>::const_reference SmallStackBuffer<T, BUF_SIZE>::at (size_t i) const
{
Require (i < fSize_);
return *(fLiveData_ + i);
}
template <typename T, size_t BUF_SIZE>
inline void SmallStackBuffer<T, BUF_SIZE>::push_back (Configuration::ArgByValueType<T> e)
{
size_t s = size ();
if (s < capacity ()) {
#if qCompilerAndStdLib_uninitialized_copy_n_Warning_Buggy
Configuration::uninitialized_copy_MSFT_BWA (&e, &e + 1, this->end ());
#else
uninitialized_copy (&e, &e + 1, this->end ());
#endif
this->fSize_++;
}
else {
if constexpr (is_trivially_default_constructible_v<T>) {
resize_uninitialized (s + 1);
}
else {
resize (s + 1);
}
fLiveData_[s] = e;
}
}
template <typename T, size_t BUF_SIZE>
inline SmallStackBuffer<T, BUF_SIZE>::operator T* ()
{
AssertNotNull (fLiveData_);
return fLiveData_;
}
template <typename T, size_t BUF_SIZE>
inline SmallStackBuffer<T, BUF_SIZE>::operator const T* () const
{
AssertNotNull (fLiveData_);
return fLiveData_;
}
template <typename T, size_t BUF_SIZE>
inline void SmallStackBuffer<T, BUF_SIZE>::Invariant () const
{
#if qDebug
Invariant_ ();
#endif
}
#if qDebug
template <typename T, size_t BUF_SIZE>
void SmallStackBuffer<T, BUF_SIZE>::Invariant_ () const
{
Assert (capacity () >= size ());
ValidateGuards_ ();
}
#if qCompiler_cpp17InlineStaticMemberOfTemplateLinkerUndefined_Buggy
template <typename T, size_t BUF_SIZE>
constexpr Byte SmallStackBuffer<T, BUF_SIZE>::kGuard1_[8];
template <typename T, size_t BUF_SIZE>
constexpr Byte SmallStackBuffer<T, BUF_SIZE>::kGuard2_[8];
#endif
template <typename T, size_t BUF_SIZE>
void SmallStackBuffer<T, BUF_SIZE>::ValidateGuards_ () const
{
Assert (::memcmp (kGuard1_, fGuard1_, sizeof (kGuard1_)) == 0);
Assert (::memcmp (kGuard2_, fGuard2_, sizeof (kGuard2_)) == 0);
}
#endif
template <typename T, size_t BUF_SIZE>
inline T* SmallStackBuffer<T, BUF_SIZE>::BufferAsT_ () noexcept
{
return reinterpret_cast<T*> (&fInlinePreallocatedBuffer_[0]);
}
template <typename T, size_t BUF_SIZE>
inline const T* SmallStackBuffer<T, BUF_SIZE>::BufferAsT_ () const noexcept
{
return reinterpret_cast<const T*> (&fInlinePreallocatedBuffer_[0]);
}
template <typename T, size_t BUF_SIZE>
inline void SmallStackBuffer<T, BUF_SIZE>::DestroyElts_ (T* start, T* end) noexcept
{
for (auto i = start; i != end; ++i) {
i->~T ();
}
}
template <typename T, size_t BUF_SIZE>
inline Memory::Byte* SmallStackBuffer<T, BUF_SIZE>::LiveDataAsAllocatedBytes_ ()
{
Require (fLiveData_ != BufferAsT_ ());
return reinterpret_cast<Memory::Byte*> (fLiveData_);
}
template <typename T, size_t BUF_SIZE>
inline Memory::Byte* SmallStackBuffer<T, BUF_SIZE>::Allocate_ (size_t bytes)
{
void* p = ::malloc (bytes);
Execution::ThrowIfNull (p);
return reinterpret_cast<Memory::Byte*> (p);
}
template <typename T, size_t BUF_SIZE>
inline void SmallStackBuffer<T, BUF_SIZE>::Deallocate_ (Memory::Byte* bytes)
{
if (bytes != nullptr) {
::free (bytes);
}
}
}
#endif /*_Stroika_Foundation_Memory_SmallStackBuffer_inl_*/
<commit_msg>Cosmetic<commit_after>/*
* Copyright(c) Sophist Solutions, Inc. 1990-2018. All rights reserved
*/
#ifndef _Stroika_Foundation_Memory_SmallStackBuffer_inl_
#define _Stroika_Foundation_Memory_SmallStackBuffer_inl_ 1
/*
********************************************************************************
***************************** Implementation Details ***************************
********************************************************************************
*/
#include <algorithm>
#include <cstring>
#include <type_traits>
#include "../Debug/Assertions.h"
#include "../Execution/Exceptions.h"
#include "Common.h"
namespace Stroika::Foundation::Memory {
/*
********************************************************************************
************************* SmallStackBuffer<T, BUF_SIZE> ************************
********************************************************************************
*/
template <typename T, size_t BUF_SIZE>
inline SmallStackBuffer<T, BUF_SIZE>::SmallStackBuffer ()
: fLiveData_ (BufferAsT_ ())
{
#if qDebug
::memcpy (fGuard1_, kGuard1_, sizeof (kGuard1_));
::memcpy (fGuard2_, kGuard2_, sizeof (kGuard2_));
#endif
Invariant ();
}
template <typename T, size_t BUF_SIZE>
inline SmallStackBuffer<T, BUF_SIZE>::SmallStackBuffer (size_t nElements)
: SmallStackBuffer ()
{
resize (nElements);
Invariant ();
}
template <typename T, size_t BUF_SIZE>
inline SmallStackBuffer<T, BUF_SIZE>::SmallStackBuffer (UninitializedConstructorFlag, size_t nElements)
: SmallStackBuffer ()
{
static_assert (is_trivially_default_constructible_v<T>);
resize_uninitialized (nElements);
Invariant ();
}
template <typename T, size_t BUF_SIZE>
template <typename ITERATOR_OF_T, enable_if_t<Configuration::is_iterator_v<ITERATOR_OF_T>, char>*>
SmallStackBuffer<T, BUF_SIZE>::SmallStackBuffer (ITERATOR_OF_T start, ITERATOR_OF_T end)
: SmallStackBuffer (distance (start, end))
{
#if qCompilerAndStdLib_uninitialized_copy_n_Warning_Buggy
Configuration::uninitialized_copy_MSFT_BWA (start, end, this->begin ());
#else
uninitialized_copy (start, end, this->begin ());
#endif
Invariant ();
}
template <typename T, size_t BUF_SIZE>
template <size_t FROM_BUF_SIZE>
SmallStackBuffer<T, BUF_SIZE>::SmallStackBuffer (const SmallStackBuffer<T, FROM_BUF_SIZE>& from)
: SmallStackBuffer (from.begin (), from.end ())
{
}
template <typename T, size_t BUF_SIZE>
inline SmallStackBuffer<T, BUF_SIZE>::SmallStackBuffer (const SmallStackBuffer& from)
: SmallStackBuffer (from.begin (), from.end ())
{
}
template <typename T, size_t BUF_SIZE>
inline SmallStackBuffer<T, BUF_SIZE>::~SmallStackBuffer ()
{
Invariant ();
DestroyElts_ (this->begin (), this->end ());
if (fLiveData_ != BufferAsT_ ()) {
// we must have used the heap...
Deallocate_ (LiveDataAsAllocatedBytes_ ());
}
}
template <typename T, size_t BUF_SIZE>
template <size_t FROM_BUF_SIZE>
SmallStackBuffer<T, BUF_SIZE>& SmallStackBuffer<T, BUF_SIZE>::operator= (const SmallStackBuffer<T, FROM_BUF_SIZE>& rhs)
{
Invariant ();
// @todo this simple implementation could be more efficient
DestroyElts_ (this->begin (), this->end ());
fSize_ = 0;
ReserveAtLeast (rhs.size ());
#if qCompilerAndStdLib_uninitialized_copy_n_Warning_Buggy
Configuration::uninitialized_copy_MSFT_BWA (rhs.begin (), rhs.end (), this->begin ());
#else
uninitialized_copy (rhs.begin (), rhs.end (), this->begin ());
#endif
Invariant ();
return *this;
}
template <typename T, size_t BUF_SIZE>
SmallStackBuffer<T, BUF_SIZE>& SmallStackBuffer<T, BUF_SIZE>::operator= (const SmallStackBuffer& rhs)
{
Invariant ();
if (this != &rhs) {
// @todo this simple implementation could be more efficient
DestroyElts_ (this->begin (), this->end ());
fSize_ = 0;
ReserveAtLeast (rhs.size ());
#if qCompilerAndStdLib_uninitialized_copy_n_Warning_Buggy
Configuration::uninitialized_copy_MSFT_BWA (rhs.begin (), rhs.end (), this->begin ());
#else
uninitialized_copy (rhs.begin (), rhs.end (), this->begin ());
#endif
Invariant ();
}
return *this;
}
template <typename T, size_t BUF_SIZE>
inline void SmallStackBuffer<T, BUF_SIZE>::GrowToSize (size_t nElements)
{
if (nElements > size ()) {
resize (nElements);
}
}
template <typename T, size_t BUF_SIZE>
inline void SmallStackBuffer<T, BUF_SIZE>::GrowToSize_uninitialized (size_t nElements)
{
static_assert (is_trivially_default_constructible_v<T>);
if (nElements > size ()) {
resize_uninitialized (nElements);
}
}
template <typename T, size_t BUF_SIZE>
inline void SmallStackBuffer<T, BUF_SIZE>::resize (size_t nElements)
{
if (nElements > fSize_) {
// Growing
if (nElements > capacity ()) {
/*
* If we REALLY must grow, the double in size so unlikely we'll have to grow/malloc/copy again.
*/
reserve (max (nElements, capacity () * 2));
}
uninitialized_fill (this->begin () + fSize_, this->begin () + nElements, T{});
fSize_ = nElements;
}
else if (nElements < fSize_) {
// Shrinking
DestroyElts_ (this->begin () + nElements, this->end ());
fSize_ = nElements;
}
Assert (fSize_ == nElements);
Ensure (size () <= capacity ());
}
template <typename T, size_t BUF_SIZE>
inline void SmallStackBuffer<T, BUF_SIZE>::resize_uninitialized (size_t nElements)
{
static_assert (is_trivially_default_constructible_v<T>);
if (nElements > fSize_) {
// Growing
if (nElements > capacity ())
[[UNLIKELY_ATTR]]
{
/*
* If we REALLY must grow, the double in size so unlikely we'll have to grow/malloc/copy again.
*/
reserve (max (nElements, capacity () * 2));
}
fSize_ = nElements;
}
else if (nElements < fSize_) {
// Shrinking
DestroyElts_ (this->begin () + nElements, this->end ());
fSize_ = nElements;
}
Assert (fSize_ == nElements);
Ensure (size () <= capacity ());
}
template <typename T, size_t BUF_SIZE>
void SmallStackBuffer<T, BUF_SIZE>::reserve_ (size_t nElements)
{
Assert (nElements >= size ());
Invariant ();
size_t oldEltCount = capacity ();
if (nElements != oldEltCount) {
bool oldInPlaceBuffer = oldEltCount <= BUF_SIZE;
bool newInPlaceBuffer = nElements <= BUF_SIZE;
// Only if we changed if using inplace buffer, or if was and is using ramBuffer, and eltCount changed do we need to do anything
if (oldInPlaceBuffer != newInPlaceBuffer or (not newInPlaceBuffer)) {
bool memoryAllocationNeeded = not newInPlaceBuffer;
Memory::Byte* newPtr = memoryAllocationNeeded ? Allocate_ (SizeInBytes_ (nElements)) : std::begin (fInlinePreallocatedBuffer_);
// Initialize new memory from old
Assert (this->begin () != reinterpret_cast<T*> (newPtr));
#if qCompilerAndStdLib_uninitialized_copy_n_Warning_Buggy
Configuration::uninitialized_copy_MSFT_BWA (this->begin (), this->end (), reinterpret_cast<T*> (newPtr));
#else
uninitialized_copy (this->begin (), this->end (), reinterpret_cast<T*> (newPtr));
#endif
// destroy objects in old memory
DestroyElts_ (this->begin (), this->end ());
// free old memory if needed
if (not oldInPlaceBuffer) {
Assert (fLiveData_ != BufferAsT_ ());
Deallocate_ (LiveDataAsAllocatedBytes_ ());
}
fLiveData_ = reinterpret_cast<T*> (newPtr);
if (not newInPlaceBuffer) {
fCapacityOfFreeStoreAllocation_ = nElements;
}
}
}
Ensure ((nElements <= BUF_SIZE && capacity () == BUF_SIZE) or (nElements > BUF_SIZE and nElements == capacity ()));
Invariant ();
}
template <typename T, size_t BUF_SIZE>
inline typename SmallStackBuffer<T, BUF_SIZE>::iterator SmallStackBuffer<T, BUF_SIZE>::begin ()
{
return fLiveData_;
}
template <typename T, size_t BUF_SIZE>
inline typename SmallStackBuffer<T, BUF_SIZE>::iterator SmallStackBuffer<T, BUF_SIZE>::end ()
{
return fLiveData_ + fSize_;
}
template <typename T, size_t BUF_SIZE>
inline typename SmallStackBuffer<T, BUF_SIZE>::const_iterator SmallStackBuffer<T, BUF_SIZE>::begin () const
{
return fLiveData_;
}
template <typename T, size_t BUF_SIZE>
inline typename SmallStackBuffer<T, BUF_SIZE>::const_iterator SmallStackBuffer<T, BUF_SIZE>::end () const
{
return fLiveData_ + fSize_;
}
template <typename T, size_t BUF_SIZE>
inline size_t SmallStackBuffer<T, BUF_SIZE>::capacity () const
{
return (fLiveData_ == BufferAsT_ ()) ? BUF_SIZE : fCapacityOfFreeStoreAllocation_; // @see class Design Note
}
template <typename T, size_t BUF_SIZE>
inline void SmallStackBuffer<T, BUF_SIZE>::reserve (size_t newCapacity)
{
Require (newCapacity >= size ());
reserve_ (newCapacity);
}
template <typename T, size_t BUF_SIZE>
inline void SmallStackBuffer<T, BUF_SIZE>::ReserveAtLeast (size_t newCapacity)
{
if (newCapacity > capacity ()) {
reserve_ (newCapacity);
}
}
template <typename T, size_t BUF_SIZE>
inline size_t SmallStackBuffer<T, BUF_SIZE>::GetSize () const
{
Ensure (fSize_ <= capacity ());
return fSize_;
}
template <typename T, size_t BUF_SIZE>
inline size_t SmallStackBuffer<T, BUF_SIZE>::size () const
{
Ensure (fSize_ <= capacity ());
return fSize_;
}
template <typename T, size_t BUF_SIZE>
inline typename SmallStackBuffer<T, BUF_SIZE>::reference SmallStackBuffer<T, BUF_SIZE>::at (size_t i)
{
Require (i < fSize_);
return *(fLiveData_ + i);
}
template <typename T, size_t BUF_SIZE>
inline typename SmallStackBuffer<T, BUF_SIZE>::const_reference SmallStackBuffer<T, BUF_SIZE>::at (size_t i) const
{
Require (i < fSize_);
return *(fLiveData_ + i);
}
template <typename T, size_t BUF_SIZE>
inline void SmallStackBuffer<T, BUF_SIZE>::push_back (Configuration::ArgByValueType<T> e)
{
size_t s = size ();
if (s < capacity ()) {
#if qCompilerAndStdLib_uninitialized_copy_n_Warning_Buggy
Configuration::uninitialized_copy_MSFT_BWA (&e, &e + 1, this->end ());
#else
uninitialized_copy (&e, &e + 1, this->end ());
#endif
this->fSize_++;
}
else {
if constexpr (is_trivially_default_constructible_v<T>) {
resize_uninitialized (s + 1);
}
else {
resize (s + 1);
}
fLiveData_[s] = e;
}
}
template <typename T, size_t BUF_SIZE>
inline SmallStackBuffer<T, BUF_SIZE>::operator T* ()
{
AssertNotNull (fLiveData_);
return fLiveData_;
}
template <typename T, size_t BUF_SIZE>
inline SmallStackBuffer<T, BUF_SIZE>::operator const T* () const
{
AssertNotNull (fLiveData_);
return fLiveData_;
}
template <typename T, size_t BUF_SIZE>
inline void SmallStackBuffer<T, BUF_SIZE>::Invariant () const
{
#if qDebug
Invariant_ ();
#endif
}
#if qDebug
template <typename T, size_t BUF_SIZE>
void SmallStackBuffer<T, BUF_SIZE>::Invariant_ () const
{
Assert (capacity () >= size ());
ValidateGuards_ ();
}
#if qCompiler_cpp17InlineStaticMemberOfTemplateLinkerUndefined_Buggy
template <typename T, size_t BUF_SIZE>
constexpr Byte SmallStackBuffer<T, BUF_SIZE>::kGuard1_[8];
template <typename T, size_t BUF_SIZE>
constexpr Byte SmallStackBuffer<T, BUF_SIZE>::kGuard2_[8];
#endif
template <typename T, size_t BUF_SIZE>
void SmallStackBuffer<T, BUF_SIZE>::ValidateGuards_ () const
{
Assert (::memcmp (kGuard1_, fGuard1_, sizeof (kGuard1_)) == 0);
Assert (::memcmp (kGuard2_, fGuard2_, sizeof (kGuard2_)) == 0);
}
#endif
template <typename T, size_t BUF_SIZE>
inline T* SmallStackBuffer<T, BUF_SIZE>::BufferAsT_ () noexcept
{
return reinterpret_cast<T*> (&fInlinePreallocatedBuffer_[0]);
}
template <typename T, size_t BUF_SIZE>
inline const T* SmallStackBuffer<T, BUF_SIZE>::BufferAsT_ () const noexcept
{
return reinterpret_cast<const T*> (&fInlinePreallocatedBuffer_[0]);
}
template <typename T, size_t BUF_SIZE>
inline void SmallStackBuffer<T, BUF_SIZE>::DestroyElts_ (T* start, T* end) noexcept
{
for (auto i = start; i != end; ++i) {
i->~T ();
}
}
template <typename T, size_t BUF_SIZE>
inline Memory::Byte* SmallStackBuffer<T, BUF_SIZE>::LiveDataAsAllocatedBytes_ ()
{
Require (fLiveData_ != BufferAsT_ ());
return reinterpret_cast<Memory::Byte*> (fLiveData_);
}
template <typename T, size_t BUF_SIZE>
inline Memory::Byte* SmallStackBuffer<T, BUF_SIZE>::Allocate_ (size_t bytes)
{
void* p = ::malloc (bytes);
Execution::ThrowIfNull (p);
return reinterpret_cast<Memory::Byte*> (p);
}
template <typename T, size_t BUF_SIZE>
inline void SmallStackBuffer<T, BUF_SIZE>::Deallocate_ (Memory::Byte* bytes)
{
if (bytes != nullptr) {
::free (bytes);
}
}
}
#endif /*_Stroika_Foundation_Memory_SmallStackBuffer_inl_*/
<|endoftext|> |
<commit_before>#include "balance.h"
int count = 0;
BalanceState::BalanceState(Adafruit_BNO055* imu)
: imu(imu),
drive(&leftServo, &rightServo),
pid(&pidInput, &pidOutput, &pidTarget, 10, 1, 1, DIRECT) {}
void BalanceState::enter() {
Serial.println(F("\n\nEntering: Robot Balance State"));
if (!readConfig(cd)) {
Serial.println(F("ERROR: Config Not found"));
stateGoto(NULL);
return;
}
drive.setServoConfig(cd.lconfig, cd.rconfig);
leftServo.attach(servoLeftPin);
rightServo.attach(servoRightPin);
pid.SetTunings(cd.Kp, cd.Ki, cd.Kd);
pid.SetOutputLimits(-1.0, 1.0);
pid.SetSampleTime(10);
drive.drive(0);
pid.SetMode(AUTOMATIC);
pidTarget = 0;
}
void BalanceState::action() {
sensors_event_t event;
imu->getEvent(&event);
pidInput = event.orientation.y / 90.0;
pid.Compute();
if (event.orientation.y < 10.0 && event.orientation.y > -10.0)
drive.drive(1000 * pidOutput);
else
drive.drive(0);
delay(5);
int ch = Serial.read();
if (ch == 'q') {
stateGoto(NULL);
}
switch (ch) {
case 'p':
cd.Kp += 0.1;
break;
case 'P':
cd.Kp -= 0.1;
break;
case 'i':
cd.Ki += 0.1;
break;
case 'I':
cd.Ki -= 0.1;
break;
case 'd':
cd.Kd += 0.1;
break;
case 'D':
cd.Kd -= 0.1;
break;
case 'w':
pidTarget += 0.01;
break;
case 's':
pidTarget -= 0.01;
break;
}
pid.SetTunings(cd.Kp, cd.Ki, cd.Kd);
if (count == 100) {
Serial.print("Y: ");
Serial.print(event.orientation.y, 2);
Serial.print("\tKp: ");
Serial.print(cd.Kp, 2);
Serial.print("\tKi: ");
Serial.print(cd.Ki, 2);
Serial.print("\tKd: ");
Serial.print(cd.Kd, 2);
Serial.println("");
count = 0;
}
count++;
}
void BalanceState::leave() {
leftServo.detach();
rightServo.detach();
writeConfig(cd);
}
<commit_msg>suspend pid calculation if angle is exceeded<commit_after>#include "balance.h"
int count = 0;
BalanceState::BalanceState(Adafruit_BNO055* imu)
: imu(imu),
drive(&leftServo, &rightServo),
pid(&pidInput, &pidOutput, &pidTarget, 10, 1, 1, DIRECT) {}
void BalanceState::enter() {
Serial.println(F("\n\nEntering: Robot Balance State"));
if (!readConfig(cd)) {
Serial.println(F("ERROR: Config Not found"));
stateGoto(NULL);
return;
}
drive.setServoConfig(cd.lconfig, cd.rconfig);
leftServo.attach(servoLeftPin);
rightServo.attach(servoRightPin);
pid.SetTunings(cd.Kp, cd.Ki, cd.Kd);
pid.SetOutputLimits(-1.0, 1.0);
pid.SetSampleTime(10);
drive.drive(0);
pid.SetMode(AUTOMATIC);
pidTarget = 0;
}
void BalanceState::action() {
sensors_event_t event;
imu->getEvent(&event);
if (event.orientation.y < 10.0 && event.orientation.y > -10.0) {
pidInput = event.orientation.y / 90.0;
pid.Compute();
drive.drive(1000 * pidOutput);
} else {
drive.drive(0);
}
delay(5);
int ch = Serial.read();
if (ch == 'q') {
stateGoto(NULL);
}
switch (ch) {
case 'p':
cd.Kp += 0.1;
break;
case 'P':
cd.Kp -= 0.1;
break;
case 'i':
cd.Ki += 0.1;
break;
case 'I':
cd.Ki -= 0.1;
break;
case 'd':
cd.Kd += 0.1;
break;
case 'D':
cd.Kd -= 0.1;
break;
case 'w':
pidTarget += 0.01;
break;
case 's':
pidTarget -= 0.01;
break;
}
pid.SetTunings(cd.Kp, cd.Ki, cd.Kd);
if (count == 100) {
Serial.print("Y: ");
Serial.print(event.orientation.y, 2);
Serial.print("\tKp: ");
Serial.print(cd.Kp, 2);
Serial.print("\tKi: ");
Serial.print(cd.Ki, 2);
Serial.print("\tKd: ");
Serial.print(cd.Kd, 2);
Serial.println("");
count = 0;
}
count++;
}
void BalanceState::leave() {
leftServo.detach();
rightServo.detach();
writeConfig(cd);
}
<|endoftext|> |
<commit_before>/* mbed Microcontroller Library
* Copyright (c) 2018 ARM Limited
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include <ctype.h>
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include "cmsis_os.h"
#include "fvp_emac.h"
#include "mbed_interface.h"
#include "mbed_assert.h"
#include "netsocket/nsapi_types.h"
#include "mbed_shared_queues.h"
/********************************************************************************
* Internal data
********************************************************************************/
#define THREAD_STACKSIZE 512
/* Flags for worker thread */
#define FLAG_TX (0x1u << 0)
#define FLAG_RX (0x1u << 1)
/** \brief Driver thread priority */
#define THREAD_PRIORITY (osPriorityNormal)
#define PHY_TASK_PERIOD_MS 200
fvp_EMAC::fvp_EMAC() : _thread(THREAD_PRIORITY,THREAD_STACKSIZE,NULL,"fvp_emac_thread")
{
}
void fvp_EMAC::ethernet_callback(lan91_event_t event, void *param)
{
fvp_EMAC *enet = static_cast<fvp_EMAC *>(param);
switch (event)
{
case LAN91_RxEvent:
enet->rx_isr();
break;
case LAN91_TxEvent:
enet->tx_isr();
break;
default:
break;
}
}
/** \brief Ethernet receive interrupt handler */
void fvp_EMAC::rx_isr()
{
_thread.flags_set(FLAG_RX);
}
/** \brief Ethernet transmit interrupt handler */
void fvp_EMAC::tx_isr()
{
_thread.flags_set(FLAG_TX);
}
/** \brief Low level init of the MAC and PHY. */
bool fvp_EMAC::low_level_init_successful()
{
LAN91_init();
LAN91_SetCallback(&fvp_EMAC::ethernet_callback, this);
return true;
}
/** \brief Worker thread.
*
* Woken by thread flags to receive packets or clean up transmit
*
* \param[in] pvParameters pointer to the interface data
*/
void fvp_EMAC::thread_function(void* pvParameters)
{
struct fvp_EMAC *fvp_enet = static_cast<fvp_EMAC *>(pvParameters);
for (;;) {
uint32_t flags = ThisThread::flags_wait_any(FLAG_RX|FLAG_TX);
if (flags & FLAG_RX) {
fvp_enet->packet_rx();
}
}
}
/** \brief Packet reception task
*
* This task is called when a packet is received. It will
* pass the packet to the LWIP core.
*/
void fvp_EMAC::packet_rx()
{
while(!LAN91_RxFIFOEmpty())
{
emac_mem_buf_t *temp_rxbuf = NULL;
uint32_t *rx_payload_ptr;
uint32_t rx_length = 0;
temp_rxbuf = _memory_manager->alloc_heap(FVP_ETH_MAX_FLEN, LAN91_BUFF_ALIGNMENT);
/* no memory been allocated*/
if (NULL != temp_rxbuf) {
rx_payload_ptr = (uint32_t*)_memory_manager->get_ptr(temp_rxbuf);
rx_length = _memory_manager->get_len(temp_rxbuf);
bool state;
#ifdef LOCK_RX_THREAD
/* Get exclusive access */
_TXLockMutex.lock();
#endif
state = LAN91_receive_frame(rx_payload_ptr, &rx_length);
#ifdef LOCK_RX_THREAD
_TXLockMutex.unlock();
#endif
if(!state)
{
_memory_manager->free(temp_rxbuf);
continue;
}
else
{
_memory_manager->set_len(temp_rxbuf, rx_length);
}
_emac_link_input_cb(temp_rxbuf);
}
}
LAN91_SetInterruptMasks(MSK_RCV);
}
/** \brief Low level output of a packet. Never call this from an
* interrupt context, as it may block until TX descriptors
* become available.
*
* \param[in] buf the MAC packet to send (e.g. IP packet including MAC addresses and type)
* \return ERR_OK if the packet could be sent or an err_t value if the packet couldn't be sent
*/
bool fvp_EMAC::link_out(emac_mem_buf_t *buf)
{
// If buffer is chained or not aligned then make a contiguous aligned copy of it
if (_memory_manager->get_next(buf) ||
reinterpret_cast<uint32_t>(_memory_manager->get_ptr(buf)) % LAN91_BUFF_ALIGNMENT) {
emac_mem_buf_t *copy_buf;
copy_buf = _memory_manager->alloc_heap(_memory_manager->get_total_len(buf), LAN91_BUFF_ALIGNMENT);
if (NULL == copy_buf) {
_memory_manager->free(buf);
return false;
}
// Copy to new buffer and free original
_memory_manager->copy(copy_buf, buf);
_memory_manager->free(buf);
buf = copy_buf;
}
/* Save the buffer so that it can be freed when transmit is done */
uint32_t * buffer;
uint32_t tx_length = 0;
bool state;
buffer = (uint32_t *)(_memory_manager->get_ptr(buf));
tx_length = _memory_manager->get_len(buf);
/* Get exclusive access */
_TXLockMutex.lock();
/* Setup transfers */
state = LAN91_send_frame(buffer,&tx_length);
_TXLockMutex.unlock();
/* Restore access */
if(!state){
return false;
}
/* Free the buffer */
_memory_manager->free(buf);
return true;
}
/** \brief PHY task monitoring the link */
void fvp_EMAC::phy_task()
{
// Get current status
lan91_phy_status_t connection_status;
connection_status = LAN91_GetLinkStatus();
if (connection_status != _prev_state && _emac_link_state_cb) {
_emac_link_state_cb(connection_status);
}
_prev_state = connection_status;
}
bool fvp_EMAC::power_up()
{
/* Initialize the hardware */
if (!low_level_init_successful()) {
return false;
}
/* Start ethernet Worker thread */
_thread.start(callback(&fvp_EMAC::thread_function, this));
/* Trigger thread to deal with any RX packets that arrived before thread was started */
rx_isr();
/* PHY monitoring task */
_prev_state = STATE_LINK_DOWN;
mbed::mbed_event_queue()->call(mbed::callback(this, &fvp_EMAC::phy_task));
/* Allow the PHY task to detect the initial link state and set up the proper flags */
wait_ms(10);
_phy_task_handle = mbed::mbed_event_queue()->call_every(PHY_TASK_PERIOD_MS, mbed::callback(this, &fvp_EMAC::phy_task));
return true;
}
uint32_t fvp_EMAC::get_mtu_size() const
{
return LAN91_ETH_MTU_SIZE;
}
uint32_t fvp_EMAC::get_align_preference() const
{
return LAN91_BUFF_ALIGNMENT;
}
void fvp_EMAC::get_ifname(char *name, uint8_t size) const
{
memcpy(name, FVP_ETH_IF_NAME, (size < sizeof(FVP_ETH_IF_NAME)) ? size : sizeof(FVP_ETH_IF_NAME));
}
uint8_t fvp_EMAC::get_hwaddr_size() const
{
return FVP_HWADDR_SIZE;
}
bool fvp_EMAC::get_hwaddr(uint8_t *addr) const
{
read_MACaddr(addr);
return true;
}
void fvp_EMAC::set_hwaddr(const uint8_t *addr)
{
/* No-op at this stage */
}
void fvp_EMAC::set_link_input_cb(emac_link_input_cb_t input_cb)
{
_emac_link_input_cb = input_cb;
}
void fvp_EMAC::set_link_state_cb(emac_link_state_change_cb_t state_cb)
{
_emac_link_state_cb = state_cb;
}
void fvp_EMAC::add_multicast_group(const uint8_t *addr)
{
/* No-op at this stage */
}
void fvp_EMAC::remove_multicast_group(const uint8_t *addr)
{
/* No-op at this stage */
}
void fvp_EMAC::set_all_multicast(bool all)
{
/* No-op at this stage */
}
void fvp_EMAC::power_down()
{
/* No-op at this stage */
}
void fvp_EMAC::set_memory_manager(EMACMemoryManager &mem_mngr)
{
_memory_manager = &mem_mngr;
}
fvp_EMAC &fvp_EMAC::get_instance() {
static fvp_EMAC emac;
return emac;
}
// Weak so a module can override
MBED_WEAK EMAC &EMAC::get_default_instance() {
return fvp_EMAC::get_instance();
}
/** @} */
/* --------------------------------- End Of File ------------------------------ */
<commit_msg>update wait_ms() to sleep_for()<commit_after>/* mbed Microcontroller Library
* Copyright (c) 2018 ARM Limited
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include <ctype.h>
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include "cmsis_os.h"
#include "fvp_emac.h"
#include "mbed_interface.h"
#include "mbed_assert.h"
#include "netsocket/nsapi_types.h"
#include "mbed_shared_queues.h"
/********************************************************************************
* Internal data
********************************************************************************/
#define THREAD_STACKSIZE 512
/* Flags for worker thread */
#define FLAG_TX (0x1u << 0)
#define FLAG_RX (0x1u << 1)
/** \brief Driver thread priority */
#define THREAD_PRIORITY (osPriorityNormal)
#define PHY_TASK_PERIOD_MS 200
fvp_EMAC::fvp_EMAC() : _thread(THREAD_PRIORITY,THREAD_STACKSIZE,NULL,"fvp_emac_thread")
{
}
void fvp_EMAC::ethernet_callback(lan91_event_t event, void *param)
{
fvp_EMAC *enet = static_cast<fvp_EMAC *>(param);
switch (event)
{
case LAN91_RxEvent:
enet->rx_isr();
break;
case LAN91_TxEvent:
enet->tx_isr();
break;
default:
break;
}
}
/** \brief Ethernet receive interrupt handler */
void fvp_EMAC::rx_isr()
{
_thread.flags_set(FLAG_RX);
}
/** \brief Ethernet transmit interrupt handler */
void fvp_EMAC::tx_isr()
{
_thread.flags_set(FLAG_TX);
}
/** \brief Low level init of the MAC and PHY. */
bool fvp_EMAC::low_level_init_successful()
{
LAN91_init();
LAN91_SetCallback(&fvp_EMAC::ethernet_callback, this);
return true;
}
/** \brief Worker thread.
*
* Woken by thread flags to receive packets or clean up transmit
*
* \param[in] pvParameters pointer to the interface data
*/
void fvp_EMAC::thread_function(void* pvParameters)
{
struct fvp_EMAC *fvp_enet = static_cast<fvp_EMAC *>(pvParameters);
for (;;) {
uint32_t flags = ThisThread::flags_wait_any(FLAG_RX|FLAG_TX);
if (flags & FLAG_RX) {
fvp_enet->packet_rx();
}
}
}
/** \brief Packet reception task
*
* This task is called when a packet is received. It will
* pass the packet to the LWIP core.
*/
void fvp_EMAC::packet_rx()
{
while(!LAN91_RxFIFOEmpty())
{
emac_mem_buf_t *temp_rxbuf = NULL;
uint32_t *rx_payload_ptr;
uint32_t rx_length = 0;
temp_rxbuf = _memory_manager->alloc_heap(FVP_ETH_MAX_FLEN, LAN91_BUFF_ALIGNMENT);
/* no memory been allocated*/
if (NULL != temp_rxbuf) {
rx_payload_ptr = (uint32_t*)_memory_manager->get_ptr(temp_rxbuf);
rx_length = _memory_manager->get_len(temp_rxbuf);
bool state;
#ifdef LOCK_RX_THREAD
/* Get exclusive access */
_TXLockMutex.lock();
#endif
state = LAN91_receive_frame(rx_payload_ptr, &rx_length);
#ifdef LOCK_RX_THREAD
_TXLockMutex.unlock();
#endif
if(!state)
{
_memory_manager->free(temp_rxbuf);
continue;
}
else
{
_memory_manager->set_len(temp_rxbuf, rx_length);
}
_emac_link_input_cb(temp_rxbuf);
}
}
LAN91_SetInterruptMasks(MSK_RCV);
}
/** \brief Low level output of a packet. Never call this from an
* interrupt context, as it may block until TX descriptors
* become available.
*
* \param[in] buf the MAC packet to send (e.g. IP packet including MAC addresses and type)
* \return ERR_OK if the packet could be sent or an err_t value if the packet couldn't be sent
*/
bool fvp_EMAC::link_out(emac_mem_buf_t *buf)
{
// If buffer is chained or not aligned then make a contiguous aligned copy of it
if (_memory_manager->get_next(buf) ||
reinterpret_cast<uint32_t>(_memory_manager->get_ptr(buf)) % LAN91_BUFF_ALIGNMENT) {
emac_mem_buf_t *copy_buf;
copy_buf = _memory_manager->alloc_heap(_memory_manager->get_total_len(buf), LAN91_BUFF_ALIGNMENT);
if (NULL == copy_buf) {
_memory_manager->free(buf);
return false;
}
// Copy to new buffer and free original
_memory_manager->copy(copy_buf, buf);
_memory_manager->free(buf);
buf = copy_buf;
}
/* Save the buffer so that it can be freed when transmit is done */
uint32_t * buffer;
uint32_t tx_length = 0;
bool state;
buffer = (uint32_t *)(_memory_manager->get_ptr(buf));
tx_length = _memory_manager->get_len(buf);
/* Get exclusive access */
_TXLockMutex.lock();
/* Setup transfers */
state = LAN91_send_frame(buffer,&tx_length);
_TXLockMutex.unlock();
/* Restore access */
if(!state){
return false;
}
/* Free the buffer */
_memory_manager->free(buf);
return true;
}
/** \brief PHY task monitoring the link */
void fvp_EMAC::phy_task()
{
// Get current status
lan91_phy_status_t connection_status;
connection_status = LAN91_GetLinkStatus();
if (connection_status != _prev_state && _emac_link_state_cb) {
_emac_link_state_cb(connection_status);
}
_prev_state = connection_status;
}
bool fvp_EMAC::power_up()
{
/* Initialize the hardware */
if (!low_level_init_successful()) {
return false;
}
/* Start ethernet Worker thread */
_thread.start(callback(&fvp_EMAC::thread_function, this));
/* Trigger thread to deal with any RX packets that arrived before thread was started */
rx_isr();
/* PHY monitoring task */
_prev_state = STATE_LINK_DOWN;
mbed::mbed_event_queue()->call(mbed::callback(this, &fvp_EMAC::phy_task));
/* Allow the PHY task to detect the initial link state and set up the proper flags */
ThisThread::sleep_for(10);
_phy_task_handle = mbed::mbed_event_queue()->call_every(PHY_TASK_PERIOD_MS, mbed::callback(this, &fvp_EMAC::phy_task));
return true;
}
uint32_t fvp_EMAC::get_mtu_size() const
{
return LAN91_ETH_MTU_SIZE;
}
uint32_t fvp_EMAC::get_align_preference() const
{
return LAN91_BUFF_ALIGNMENT;
}
void fvp_EMAC::get_ifname(char *name, uint8_t size) const
{
memcpy(name, FVP_ETH_IF_NAME, (size < sizeof(FVP_ETH_IF_NAME)) ? size : sizeof(FVP_ETH_IF_NAME));
}
uint8_t fvp_EMAC::get_hwaddr_size() const
{
return FVP_HWADDR_SIZE;
}
bool fvp_EMAC::get_hwaddr(uint8_t *addr) const
{
read_MACaddr(addr);
return true;
}
void fvp_EMAC::set_hwaddr(const uint8_t *addr)
{
/* No-op at this stage */
}
void fvp_EMAC::set_link_input_cb(emac_link_input_cb_t input_cb)
{
_emac_link_input_cb = input_cb;
}
void fvp_EMAC::set_link_state_cb(emac_link_state_change_cb_t state_cb)
{
_emac_link_state_cb = state_cb;
}
void fvp_EMAC::add_multicast_group(const uint8_t *addr)
{
/* No-op at this stage */
}
void fvp_EMAC::remove_multicast_group(const uint8_t *addr)
{
/* No-op at this stage */
}
void fvp_EMAC::set_all_multicast(bool all)
{
/* No-op at this stage */
}
void fvp_EMAC::power_down()
{
/* No-op at this stage */
}
void fvp_EMAC::set_memory_manager(EMACMemoryManager &mem_mngr)
{
_memory_manager = &mem_mngr;
}
fvp_EMAC &fvp_EMAC::get_instance() {
static fvp_EMAC emac;
return emac;
}
// Weak so a module can override
MBED_WEAK EMAC &EMAC::get_default_instance() {
return fvp_EMAC::get_instance();
}
/** @} */
/* --------------------------------- End Of File ------------------------------ */
<|endoftext|> |
<commit_before>/*
* Copyright (C) 2015 Dan Leinir Turthra Jensen <admin@leinir.dk>
*
* 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) version 3, or any
* later version accepted by the membership of KDE e.V. (or its
* successor approved by the membership of KDE e.V.), which shall
* act as a proxy defined in Section 6 of version 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 "CategoryEntriesModel.h"
#include "PropertyContainer.h"
#include <KFileMetaData/UserMetaData>
#include <QDir>
#include <QFileInfo>
#include <QDebug>
class CategoryEntriesModel::Private {
public:
Private(CategoryEntriesModel* qq)
: q(qq)
{};
~Private()
{
// No deleting the entries - this is done by the master BookListModel already, so do that at your own risk
}
CategoryEntriesModel* q;
QString name;
QList<BookEntry*> entries;
QList<CategoryEntriesModel*> categoryModels;
QObject* wrapBookEntry(const BookEntry* entry) {
PropertyContainer* obj = new PropertyContainer("book", q);
obj->setProperty("author", entry->author);
obj->setProperty("currentPage", QString::number(entry->currentPage));
obj->setProperty("filename", entry->filename);
obj->setProperty("filetitle", entry->filetitle);
obj->setProperty("created", entry->created);
obj->setProperty("lastOpenedTime", entry->lastOpenedTime);
obj->setProperty("publisher", entry->publisher);
obj->setProperty("series", entry->series);
obj->setProperty("title", entry->title);
obj->setProperty("totalPages", entry->totalPages);
obj->setProperty("thumbnail", entry->thumbnail);
return obj;
}
};
CategoryEntriesModel::CategoryEntriesModel(QObject* parent)
: QAbstractListModel(parent)
, d(new Private(this))
{
connect(this, SIGNAL(entryDataUpdated(BookEntry*)), this, SLOT(entryDataChanged(BookEntry*)));
connect(this, SIGNAL(entryRemoved(BookEntry*)), this, SLOT(entryRemove(BookEntry*)));
}
CategoryEntriesModel::~CategoryEntriesModel()
{
delete d;
}
QHash<int, QByteArray> CategoryEntriesModel::roleNames() const
{
QHash<int, QByteArray> roles;
roles[FilenameRole] = "filename";
roles[FiletitleRole] = "filetitle";
roles[TitleRole] = "title";
roles[SeriesRole] = "series";
roles[AuthorRole] = "author";
roles[PublisherRole] = "publisher";
roles[CreatedRole] = "created";
roles[LastOpenedTimeRole] = "lastOpenedTime";
roles[TotalPagesRole] = "totalPages";
roles[CurrentPageRole] = "currentPage";
roles[CategoryEntriesModelRole] = "categoryEntriesModel";
roles[CategoryEntryCountRole] = "categoryEntriesCount";
roles[ThumbnailRole] = "thumbnail";
return roles;
}
QVariant CategoryEntriesModel::data(const QModelIndex& index, int role) const
{
QVariant result;
if(index.isValid() && index.row() > -1)
{
if(index.row() < d->categoryModels.count())
{
CategoryEntriesModel* model = d->categoryModels[index.row()];
switch(role)
{
case Qt::DisplayRole:
case TitleRole:
result.setValue(model->name());
break;
case CategoryEntryCountRole:
result.setValue(model->bookCount());
break;
case CategoryEntriesModelRole:
result.setValue(model);
break;
default:
result.setValue(QString("Unknown role"));
break;
}
}
else
{
const BookEntry* entry = d->entries[index.row() - d->categoryModels.count()];
switch(role)
{
case Qt::DisplayRole:
case FilenameRole:
result.setValue(entry->filename);
break;
case FiletitleRole:
result.setValue(entry->filetitle);
break;
case TitleRole:
result.setValue(entry->title);
break;
case SeriesRole:
result.setValue(entry->series);
break;
case AuthorRole:
result.setValue(entry->author);
break;
case PublisherRole:
result.setValue(entry->publisher);
break;
case CreatedRole:
result.setValue(entry->created);
break;
case LastOpenedTimeRole:
result.setValue(entry->lastOpenedTime);
break;
case TotalPagesRole:
result.setValue(entry->totalPages);
break;
case CurrentPageRole:
result.setValue(entry->currentPage);
break;
case CategoryEntriesModelRole:
// Nothing, if we're not equipped with one such...
break;
case CategoryEntryCountRole:
result.setValue<int>(0);
break;
case ThumbnailRole:
result.setValue(entry->thumbnail);
break;
default:
result.setValue(QString("Unknown role"));
break;
}
}
}
return result;
}
int CategoryEntriesModel::rowCount(const QModelIndex& parent) const
{
if(parent.isValid())
return 0;
return d->categoryModels.count() + d->entries.count();
}
void CategoryEntriesModel::append(BookEntry* entry, Roles compareRole)
{
int insertionIndex = 0;
for(; insertionIndex < d->entries.count(); ++insertionIndex)
{
if(compareRole == CreatedRole)
{
if(entry->created <= d->entries.at(insertionIndex)->created)
{ continue; }
break;
}
else
{
if(QString::localeAwareCompare(d->entries.at(insertionIndex)->title, entry->title) > 0)
{ break; }
}
}
beginInsertRows(QModelIndex(), insertionIndex, insertionIndex);
d->entries.insert(insertionIndex, entry);
endInsertRows();
}
QString CategoryEntriesModel::name() const
{
return d->name;
}
void CategoryEntriesModel::setName(const QString& newName)
{
d->name = newName;
}
QObject * CategoryEntriesModel::leafModelForEntry(BookEntry* entry)
{
QObject* model(0);
if(d->categoryModels.count() == 0)
{
if(d->entries.contains(entry)) {
model = this;
}
}
else
{
Q_FOREACH(CategoryEntriesModel* testModel, d->categoryModels)
{
model = testModel->leafModelForEntry(entry);
if(model) {
break;
}
}
}
return model;
}
void CategoryEntriesModel::addCategoryEntry(const QString& categoryName, BookEntry* entry)
{
if(categoryName.length() > 0)
{
QStringList splitName = categoryName.split("/");
// qDebug() << "Parsing" << categoryName;
QString nextCategory = splitName.takeFirst();
CategoryEntriesModel* categoryModel = 0;
Q_FOREACH(CategoryEntriesModel* existingModel, d->categoryModels)
{
if(existingModel->name() == nextCategory)
{
categoryModel = existingModel;
break;
}
}
if(!categoryModel)
{
categoryModel = new CategoryEntriesModel(this);
connect(this, SIGNAL(entryDataUpdated(BookEntry*)), categoryModel, SIGNAL(entryDataUpdated(BookEntry*)));
connect(this, SIGNAL(entryRemoved(BookEntry*)), categoryModel, SIGNAL(entryRemoved(BookEntry*)));
categoryModel->setName(nextCategory);
int insertionIndex = 0;
for(; insertionIndex < d->categoryModels.count(); ++insertionIndex)
{
if(QString::localeAwareCompare(d->categoryModels.at(insertionIndex)->name(), categoryModel->name()) > 0)
{
break;
}
}
beginInsertRows(QModelIndex(), insertionIndex, insertionIndex);
d->categoryModels.insert(insertionIndex, categoryModel);
endInsertRows();
}
categoryModel->append(entry);
categoryModel->addCategoryEntry(splitName.join("/"), entry);
}
}
QObject* CategoryEntriesModel::get(int index)
{
BookEntry* entry = new BookEntry();
bool deleteEntry = true;
if(index > -1 && index < d->entries.count())
{
entry = d->entries.at(index);
deleteEntry = false;
}
QObject* obj = d->wrapBookEntry(entry);
if(deleteEntry)
{
delete entry;
}
return obj;
}
int CategoryEntriesModel::indexOfFile(QString filename)
{
int index = -1, i = 0;
if(QFile::exists(filename))
{
Q_FOREACH(BookEntry* entry, d->entries)
{
if(entry->filename == filename)
{
index = i;
break;
}
++i;
}
}
return index;
}
bool CategoryEntriesModel::indexIsBook(int index)
{
if(index < d->categoryModels.count() || index >= rowCount()) {
return false;
}
return true;
}
int CategoryEntriesModel::bookCount() const
{
return d->entries.count();
}
QObject* CategoryEntriesModel::getEntry(int index)
{
PropertyContainer* obj = new PropertyContainer("book", this);
if(index < 0 && index > rowCount() -1) {
// don't be a silly person, you can't get a nothing...
}
else if(index > d->categoryModels.count()) {
// This is a book - get a book!
obj = qobject_cast<PropertyContainer*>(get(index - d->categoryModels.count()));
}
else {
CategoryEntriesModel* catEntry = d->categoryModels.at(index);
obj->setProperty("title", catEntry->name());
obj->setProperty("categoryEntriesCount", catEntry->rowCount());
obj->setProperty("entriesModel", QVariant::fromValue(catEntry));
}
return obj;
}
QObject* CategoryEntriesModel::bookFromFile(QString filename)
{
PropertyContainer* obj = qobject_cast<PropertyContainer*>(get(indexOfFile(filename)));
if(obj->property("filename").toString().isEmpty()) {
if(QFileInfo::exists(filename)) {
QFileInfo info(filename);
obj->setProperty("title", info.completeBaseName());
obj->setProperty("created", info.created());
KFileMetaData::UserMetaData data(filename);
if (data.hasAttribute("peruse.currentPage")) {
int currentPage = data.attribute("peruse.currentPage").toInt();
obj->setProperty("currentPage", QVariant::fromValue<int>(currentPage));
}
if (data.hasAttribute("peruse.totalPages")) {
int totalPages = data.attribute("peruse.totalPages").toInt();
obj->setProperty("totalPages", QVariant::fromValue<int>(totalPages));
}
obj->setProperty("filename", filename);
QString thumbnail;
if(filename.toLower().endsWith("cbr")) {
thumbnail = QString("image://comiccover/").append(filename);
}
#ifdef USE_PERUSE_PDFTHUMBNAILER
else if(filename.toLower().endsWith("pdf")) {
thumbnail = QString("image://pdfcover/").append(filename);
}
#endif
else {
thumbnail = QString("image://preview/").append(filename);
}
obj->setProperty("thumbnail", thumbnail);
}
}
return obj;
}
void CategoryEntriesModel::entryDataChanged(BookEntry* entry)
{
int entryIndex = d->entries.indexOf(entry) + d->categoryModels.count();
QModelIndex changed = index(entryIndex);
dataChanged(changed, changed);
}
void CategoryEntriesModel::entryRemove(BookEntry* entry)
{
int listIndex = d->entries.indexOf(entry);
if(listIndex > -1) {
int entryIndex = listIndex + d->categoryModels.count();
beginRemoveRows(QModelIndex(), entryIndex, entryIndex);
d->entries.removeAll(entry);
endRemoveRows();
}
}
<commit_msg>Make the category get function return count as well<commit_after>/*
* Copyright (C) 2015 Dan Leinir Turthra Jensen <admin@leinir.dk>
*
* 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) version 3, or any
* later version accepted by the membership of KDE e.V. (or its
* successor approved by the membership of KDE e.V.), which shall
* act as a proxy defined in Section 6 of version 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 "CategoryEntriesModel.h"
#include "PropertyContainer.h"
#include <KFileMetaData/UserMetaData>
#include <QDir>
#include <QFileInfo>
#include <QDebug>
class CategoryEntriesModel::Private {
public:
Private(CategoryEntriesModel* qq)
: q(qq)
{};
~Private()
{
// No deleting the entries - this is done by the master BookListModel already, so do that at your own risk
}
CategoryEntriesModel* q;
QString name;
QList<BookEntry*> entries;
QList<CategoryEntriesModel*> categoryModels;
QObject* wrapBookEntry(const BookEntry* entry) {
PropertyContainer* obj = new PropertyContainer("book", q);
obj->setProperty("author", entry->author);
obj->setProperty("currentPage", QString::number(entry->currentPage));
obj->setProperty("filename", entry->filename);
obj->setProperty("filetitle", entry->filetitle);
obj->setProperty("created", entry->created);
obj->setProperty("lastOpenedTime", entry->lastOpenedTime);
obj->setProperty("publisher", entry->publisher);
obj->setProperty("series", entry->series);
obj->setProperty("title", entry->title);
obj->setProperty("totalPages", entry->totalPages);
obj->setProperty("thumbnail", entry->thumbnail);
return obj;
}
};
CategoryEntriesModel::CategoryEntriesModel(QObject* parent)
: QAbstractListModel(parent)
, d(new Private(this))
{
connect(this, SIGNAL(entryDataUpdated(BookEntry*)), this, SLOT(entryDataChanged(BookEntry*)));
connect(this, SIGNAL(entryRemoved(BookEntry*)), this, SLOT(entryRemove(BookEntry*)));
}
CategoryEntriesModel::~CategoryEntriesModel()
{
delete d;
}
QHash<int, QByteArray> CategoryEntriesModel::roleNames() const
{
QHash<int, QByteArray> roles;
roles[FilenameRole] = "filename";
roles[FiletitleRole] = "filetitle";
roles[TitleRole] = "title";
roles[SeriesRole] = "series";
roles[AuthorRole] = "author";
roles[PublisherRole] = "publisher";
roles[CreatedRole] = "created";
roles[LastOpenedTimeRole] = "lastOpenedTime";
roles[TotalPagesRole] = "totalPages";
roles[CurrentPageRole] = "currentPage";
roles[CategoryEntriesModelRole] = "categoryEntriesModel";
roles[CategoryEntryCountRole] = "categoryEntriesCount";
roles[ThumbnailRole] = "thumbnail";
return roles;
}
QVariant CategoryEntriesModel::data(const QModelIndex& index, int role) const
{
QVariant result;
if(index.isValid() && index.row() > -1)
{
if(index.row() < d->categoryModels.count())
{
CategoryEntriesModel* model = d->categoryModels[index.row()];
switch(role)
{
case Qt::DisplayRole:
case TitleRole:
result.setValue(model->name());
break;
case CategoryEntryCountRole:
result.setValue(model->bookCount());
break;
case CategoryEntriesModelRole:
result.setValue(model);
break;
default:
result.setValue(QString("Unknown role"));
break;
}
}
else
{
const BookEntry* entry = d->entries[index.row() - d->categoryModels.count()];
switch(role)
{
case Qt::DisplayRole:
case FilenameRole:
result.setValue(entry->filename);
break;
case FiletitleRole:
result.setValue(entry->filetitle);
break;
case TitleRole:
result.setValue(entry->title);
break;
case SeriesRole:
result.setValue(entry->series);
break;
case AuthorRole:
result.setValue(entry->author);
break;
case PublisherRole:
result.setValue(entry->publisher);
break;
case CreatedRole:
result.setValue(entry->created);
break;
case LastOpenedTimeRole:
result.setValue(entry->lastOpenedTime);
break;
case TotalPagesRole:
result.setValue(entry->totalPages);
break;
case CurrentPageRole:
result.setValue(entry->currentPage);
break;
case CategoryEntriesModelRole:
// Nothing, if we're not equipped with one such...
break;
case CategoryEntryCountRole:
result.setValue<int>(0);
break;
case ThumbnailRole:
result.setValue(entry->thumbnail);
break;
default:
result.setValue(QString("Unknown role"));
break;
}
}
}
return result;
}
int CategoryEntriesModel::rowCount(const QModelIndex& parent) const
{
if(parent.isValid())
return 0;
return d->categoryModels.count() + d->entries.count();
}
void CategoryEntriesModel::append(BookEntry* entry, Roles compareRole)
{
int insertionIndex = 0;
for(; insertionIndex < d->entries.count(); ++insertionIndex)
{
if(compareRole == CreatedRole)
{
if(entry->created <= d->entries.at(insertionIndex)->created)
{ continue; }
break;
}
else
{
if(QString::localeAwareCompare(d->entries.at(insertionIndex)->title, entry->title) > 0)
{ break; }
}
}
beginInsertRows(QModelIndex(), insertionIndex, insertionIndex);
d->entries.insert(insertionIndex, entry);
endInsertRows();
}
QString CategoryEntriesModel::name() const
{
return d->name;
}
void CategoryEntriesModel::setName(const QString& newName)
{
d->name = newName;
}
QObject * CategoryEntriesModel::leafModelForEntry(BookEntry* entry)
{
QObject* model(0);
if(d->categoryModels.count() == 0)
{
if(d->entries.contains(entry)) {
model = this;
}
}
else
{
Q_FOREACH(CategoryEntriesModel* testModel, d->categoryModels)
{
model = testModel->leafModelForEntry(entry);
if(model) {
break;
}
}
}
return model;
}
void CategoryEntriesModel::addCategoryEntry(const QString& categoryName, BookEntry* entry)
{
if(categoryName.length() > 0)
{
QStringList splitName = categoryName.split("/");
// qDebug() << "Parsing" << categoryName;
QString nextCategory = splitName.takeFirst();
CategoryEntriesModel* categoryModel = 0;
Q_FOREACH(CategoryEntriesModel* existingModel, d->categoryModels)
{
if(existingModel->name() == nextCategory)
{
categoryModel = existingModel;
break;
}
}
if(!categoryModel)
{
categoryModel = new CategoryEntriesModel(this);
connect(this, SIGNAL(entryDataUpdated(BookEntry*)), categoryModel, SIGNAL(entryDataUpdated(BookEntry*)));
connect(this, SIGNAL(entryRemoved(BookEntry*)), categoryModel, SIGNAL(entryRemoved(BookEntry*)));
categoryModel->setName(nextCategory);
int insertionIndex = 0;
for(; insertionIndex < d->categoryModels.count(); ++insertionIndex)
{
if(QString::localeAwareCompare(d->categoryModels.at(insertionIndex)->name(), categoryModel->name()) > 0)
{
break;
}
}
beginInsertRows(QModelIndex(), insertionIndex, insertionIndex);
d->categoryModels.insert(insertionIndex, categoryModel);
endInsertRows();
}
categoryModel->append(entry);
categoryModel->addCategoryEntry(splitName.join("/"), entry);
}
}
QObject* CategoryEntriesModel::get(int index)
{
BookEntry* entry = new BookEntry();
bool deleteEntry = true;
if(index > -1 && index < d->entries.count())
{
entry = d->entries.at(index);
deleteEntry = false;
}
QObject* obj = d->wrapBookEntry(entry);
if(deleteEntry)
{
delete entry;
}
return obj;
}
int CategoryEntriesModel::indexOfFile(QString filename)
{
int index = -1, i = 0;
if(QFile::exists(filename))
{
Q_FOREACH(BookEntry* entry, d->entries)
{
if(entry->filename == filename)
{
index = i;
break;
}
++i;
}
}
return index;
}
bool CategoryEntriesModel::indexIsBook(int index)
{
if(index < d->categoryModels.count() || index >= rowCount()) {
return false;
}
return true;
}
int CategoryEntriesModel::bookCount() const
{
return d->entries.count();
}
QObject* CategoryEntriesModel::getEntry(int index)
{
PropertyContainer* obj = new PropertyContainer("book", this);
if(index < 0 && index > rowCount() -1) {
// don't be a silly person, you can't get a nothing...
}
else if(index > d->categoryModels.count()) {
// This is a book - get a book!
obj = qobject_cast<PropertyContainer*>(get(index - d->categoryModels.count()));
}
else {
CategoryEntriesModel* catEntry = d->categoryModels.at(index);
obj->setProperty("title", catEntry->name());
obj->setProperty("categoryEntriesCount", catEntry->bookCount());
obj->setProperty("entriesModel", QVariant::fromValue(catEntry));
}
return obj;
}
QObject* CategoryEntriesModel::bookFromFile(QString filename)
{
PropertyContainer* obj = qobject_cast<PropertyContainer*>(get(indexOfFile(filename)));
if(obj->property("filename").toString().isEmpty()) {
if(QFileInfo::exists(filename)) {
QFileInfo info(filename);
obj->setProperty("title", info.completeBaseName());
obj->setProperty("created", info.created());
KFileMetaData::UserMetaData data(filename);
if (data.hasAttribute("peruse.currentPage")) {
int currentPage = data.attribute("peruse.currentPage").toInt();
obj->setProperty("currentPage", QVariant::fromValue<int>(currentPage));
}
if (data.hasAttribute("peruse.totalPages")) {
int totalPages = data.attribute("peruse.totalPages").toInt();
obj->setProperty("totalPages", QVariant::fromValue<int>(totalPages));
}
obj->setProperty("filename", filename);
QString thumbnail;
if(filename.toLower().endsWith("cbr")) {
thumbnail = QString("image://comiccover/").append(filename);
}
#ifdef USE_PERUSE_PDFTHUMBNAILER
else if(filename.toLower().endsWith("pdf")) {
thumbnail = QString("image://pdfcover/").append(filename);
}
#endif
else {
thumbnail = QString("image://preview/").append(filename);
}
obj->setProperty("thumbnail", thumbnail);
}
}
return obj;
}
void CategoryEntriesModel::entryDataChanged(BookEntry* entry)
{
int entryIndex = d->entries.indexOf(entry) + d->categoryModels.count();
QModelIndex changed = index(entryIndex);
dataChanged(changed, changed);
}
void CategoryEntriesModel::entryRemove(BookEntry* entry)
{
int listIndex = d->entries.indexOf(entry);
if(listIndex > -1) {
int entryIndex = listIndex + d->categoryModels.count();
beginRemoveRows(QModelIndex(), entryIndex, entryIndex);
d->entries.removeAll(entry);
endRemoveRows();
}
}
<|endoftext|> |
<commit_before>#include <aleph/persistentHomology/Calculation.hh>
#include <aleph/topology/Simplex.hh>
#include <aleph/topology/SimplicialComplex.hh>
#include <aleph/topology/filtrations/Data.hh>
#include <aleph/topology/io/Matrix.hh>
#include <iostream>
#include <string>
#include <getopt.h>
using DataType = float;
using VertexType = unsigned;
using Simplex = aleph::topology::Simplex<DataType, VertexType>;
using SimplicialComplex = aleph::topology::SimplicialComplex<Simplex>;
using Filtration = aleph::topology::filtrations::Data<Simplex>;
int main( int argc, char** argv )
{
bool useSuperlevelSets = false;
{
static option commandLineOptions[] = {
{ "sublevel" , no_argument, nullptr, 's' },
{ "superlevel" , no_argument, nullptr, 'S' },
{ nullptr , 0 , nullptr, 0 }
};
int option = -1;
while( ( option = getopt_long( argc, argv, "sS", commandLineOptions, nullptr ) ) != - 1)
{
switch( option )
{
case 's':
useSuperlevelSets = false;
break;
case 'S':
useSuperlevelSets = true;
break;
default:
break;
}
}
}
if( ( argc - optind ) < 1 )
return -1;
std::string filename = argv[1];
SimplicialComplex K;
aleph::topology::io::MatrixReader reader;
reader( filename, K );
K.sort( Filtration() );
auto diagrams = aleph::calculatePersistenceDiagrams( K );
for( auto&& D : diagrams )
{
D.removeDiagonal();
std::cout << D << "\n";
}
}
<commit_msg>Added superlevel set filtration support<commit_after>#include <aleph/persistentHomology/Calculation.hh>
#include <aleph/topology/Simplex.hh>
#include <aleph/topology/SimplicialComplex.hh>
#include <aleph/topology/filtrations/Data.hh>
#include <aleph/topology/io/Matrix.hh>
#include <functional>
#include <iostream>
#include <string>
#include <getopt.h>
using DataType = float;
using VertexType = unsigned;
using Simplex = aleph::topology::Simplex<DataType, VertexType>;
using SimplicialComplex = aleph::topology::SimplicialComplex<Simplex>;
using Filtration = aleph::topology::filtrations::Data<Simplex>;
int main( int argc, char** argv )
{
bool useSuperlevelSets = false;
{
static option commandLineOptions[] = {
{ "sublevel" , no_argument, nullptr, 's' },
{ "superlevel" , no_argument, nullptr, 'S' },
{ nullptr , 0 , nullptr, 0 }
};
int option = -1;
while( ( option = getopt_long( argc, argv, "sS", commandLineOptions, nullptr ) ) != - 1)
{
switch( option )
{
case 's':
useSuperlevelSets = false;
break;
case 'S':
useSuperlevelSets = true;
break;
default:
break;
}
}
}
if( ( argc - optind ) < 1 )
return -1;
std::string filename = argv[1];
SimplicialComplex K;
aleph::topology::io::MatrixReader reader;
reader( filename, K );
if( useSuperlevelSets )
{
using Filtration =
aleph::topology::filtrations::Data<Simplex, std::greater<DataType> >;
K.sort( Filtration() );
}
else
K.sort( Filtration() );
auto diagrams = aleph::calculatePersistenceDiagrams( K );
for( auto&& D : diagrams )
{
D.removeDiagonal();
std::cout << D << "\n";
}
}
<|endoftext|> |
<commit_before>#ifndef AMGCL_IO_MM_HPP
#define AMGCL_IO_MM_HPP
/*
The MIT License
Copyright (c) 2012-2018 Denis Demidov <dennis.demidov@gmail.com>
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
*/
/**
* \file amgcl/io/mm.hpp
* \author Denis Demidov <dennis.demidov@gmail.com>
* \brief Readers for Matrix Market sparse matrices and dense vectors.
*/
#include <vector>
#include <string>
#include <fstream>
#include <sstream>
#include <numeric>
#include <boost/type_traits.hpp>
#include <boost/tuple/tuple.hpp>
#include <amgcl/util.hpp>
#include <amgcl/backend/interface.hpp>
#include <amgcl/value_type/interface.hpp>
#include <amgcl/detail/sort_row.hpp>
namespace amgcl {
namespace io {
/// Matrix market reader.
class mm_reader {
public:
/// Open the file by name
mm_reader(const std::string &fname) : f(fname.c_str()) {
precondition(f, "Failed to open file \"" + fname + "\"");
// Read banner.
std::string line;
precondition(std::getline(f, line), format_error());
std::istringstream is(line);
std::string banner, mtx, coord, dtype, storage;
precondition(
is >> banner >> mtx >> coord >> dtype >> storage,
format_error());
precondition(banner == "%%MatrixMarket", format_error("no banner"));
precondition(mtx == "matrix", format_error("not a matrix"));
if (storage == "general") {
_symmetric = false;
} else if (storage == "symmetric") {
_symmetric = true;
} else {
precondition(false, "unsupported storage type");
}
if (coord == "coordinate") {
_sparse = true;
} else if (coord == "array") {
_sparse = false;
} else {
precondition(false, format_error("unsupported coordinate type"));
}
if (dtype == "real") {
_complex = false;
_integer = false;
} else if (dtype == "complex") {
_complex = true;
_integer = false;
} else if (dtype == "integer") {
_complex = false;
_integer = true;
} else {
precondition(false, format_error("unsupported data type"));
}
// Skip comments.
std::streampos pos;
do {
pos = f.tellg();
precondition(std::getline(f, line), format_error("unexpected eof"));
} while (line[0] == '%');
// Get back to the first non-comment line.
f.seekg(pos);
// Read matrix size
is.clear(); is.str(line);
precondition(is >> nrows >> ncols, format_error());
}
/// Matrix in the file is symmetric.
bool is_symmetric() const { return _symmetric; }
/// Matrix in the file is sparse.
bool is_sparse() const { return _sparse; }
/// Matrix in the file is complex-valued.
bool is_complex() const { return _complex; }
/// Matrix in the file is integer-valued.
bool is_integer() const { return _integer; }
/// Number of rows.
size_t rows() const { return nrows; }
/// Number of rows.
size_t cols() const { return ncols; }
/// Read sparse matrix from the file.
template <typename Idx, typename Val>
boost::tuple<size_t, size_t> operator()(
std::vector<Idx> &ptr,
std::vector<Idx> &col,
std::vector<Val> &val,
ptrdiff_t row_beg = -1,
ptrdiff_t row_end = -1
)
{
precondition(_sparse, format_error("not a sparse matrix"));
precondition(boost::is_complex<Val>::value == _complex,
_complex ?
"attempt to read complex values into real vector" :
"attempt to read real values into complex vector"
);
precondition(boost::is_integral<Val>::value == _integer,
_integer ?
"attempt to read integer values into real vector" :
"attempt to read real values into integer vector"
);
// Read sizes
ptrdiff_t n, m;
size_t nnz;
std::string line;
std::istringstream is;
{
precondition(std::getline(f, line), format_error("unexpected eof"));
is.clear(); is.str(line);
precondition(is >> n >> m >> nnz, format_error());
}
if (row_beg < 0) row_beg = 0;
if (row_end < 0) row_end = n;
precondition(row_beg >= 0 && row_end <= n,
"Wrong subset of rows is requested");
ptrdiff_t _nnz = _symmetric ? 2 * nnz : nnz;
if (row_beg != 0 || row_end != n)
_nnz *= 1.2 * (row_end - row_beg) / n;
std::vector<Idx> _row; _row.reserve(_nnz);
std::vector<Idx> _col; _col.reserve(_nnz);
std::vector<Val> _val; _val.reserve(_nnz);
ptr.resize(n+1); std::fill(ptr.begin(), ptr.end(), 0);
for(size_t k = 0; k < nnz; ++k) {
precondition(std::getline(f, line), format_error("unexpected eof"));
is.clear(); is.str(line);
Idx i, j;
Val v;
precondition(is >> i >> j, format_error());
i -= 1;
j -= 1;
v = read_value<Val>(is);
if (row_beg <= i && i < row_end) {
++ptr[i - row_beg + 1];
_row.push_back(i - row_beg);
_col.push_back(j);
_val.push_back(v);
}
if (_symmetric && i != j && row_beg <= j && j < row_end) {
++ptr[j - row_beg + 1];
_row.push_back(j - row_beg);
_col.push_back(i);
_val.push_back(v);
}
}
std::partial_sum(ptr.begin(), ptr.end(), ptr.begin());
col.resize(ptr.back());
val.resize(ptr.back());
for(size_t k = 0, e = val.size(); k < e; ++k) {
Idx i = _row[k];
Idx j = _col[k];
Val v = _val[k];
Idx head = ptr[i]++;
col[head] = j;
val[head] = v;
}
std::rotate(ptr.begin(), ptr.end() - 1, ptr.end());
ptr.front() = 0;
#pragma omp parallel for
for(ptrdiff_t i = 0; i < n; ++i) {
Idx beg = ptr[i];
Idx end = ptr[i+1];
amgcl::detail::sort_row(&col[0] + beg, &val[0] + beg, end - beg);
}
return boost::make_tuple(row_end - row_beg, m);
}
/// Read dense array from the file.
template <typename Val>
boost::tuple<size_t, size_t> operator()(
std::vector<Val> &val,
ptrdiff_t row_beg = -1,
ptrdiff_t row_end = -1
)
{
precondition(!_sparse, format_error("not a dense array"));
precondition(boost::is_complex<Val>::value == _complex,
_complex ?
"attempt to read complex values into real vector" :
"attempt to read real values into complex vector"
);
precondition(boost::is_integral<Val>::value == _integer,
_integer ?
"attempt to read integer values into real vector" :
"attempt to read real values into integer vector"
);
// Read sizes
ptrdiff_t n, m;
std::string line;
std::istringstream is;
{
precondition(std::getline(f, line), format_error("unexpected eof"));
is.clear(); is.str(line);
precondition(is >> n >> m, format_error());
}
if (row_beg < 0) row_beg = 0;
if (row_end < 0) row_end = n;
precondition(row_beg >= 0 && row_end <= n,
"Wrong subset of rows is requested");
val.resize((row_end - row_beg) * m);
for(ptrdiff_t j = 0; j < m; ++j) {
for(ptrdiff_t i = 0; i < n; ++i) {
precondition(std::getline(f, line), format_error("unexpected eof"));
if (row_beg >= i && i < row_end) {
is.clear(); is.str(line);
val[(i - row_beg) * m + j] = read_value<Val>(is);
}
}
}
return boost::make_tuple(row_end - row_beg, m);
}
private:
std::ifstream f;
bool _sparse;
bool _symmetric;
bool _complex;
bool _integer;
size_t nrows, ncols;
std::string format_error(const std::string &msg = "") const {
std::string err_string = "MatrixMarket format error";
if (!msg.empty())
err_string += " (" + msg + ")";
return err_string;
}
template <typename T>
typename boost::enable_if<typename boost::is_complex<T>::type, T>::type
read_value(std::istream &s) {
typename math::scalar_of<T>::type x,y;
precondition(s >> x >> y, format_error());
return T(x,y);
}
template <typename T>
typename boost::disable_if<typename boost::is_complex<T>::type, T>::type
read_value(std::istream &s) {
T x;
if (boost::is_same<T, char>::value) {
// Special case:
// We want to read 8bit integers from MatrixMarket, not chars.
int i;
precondition(s >> i, format_error());
x = static_cast<char>(i);
} else {
precondition(s >> x, format_error());
}
return x;
}
};
namespace detail {
template <typename Val>
typename boost::enable_if<typename boost::is_complex<Val>::type, std::ostream&>::type
write_value(std::ostream &s, Val v) {
return s << std::real(v) << " " << std::imag(v);
}
template <typename Val>
typename boost::disable_if<typename boost::is_complex<Val>::type, std::ostream&>::type
write_value(std::ostream &s, Val v) {
return s << v;
}
} // namespace detail
/// Write dense array in Matrix Market format.
template <typename Val>
void mm_write(
const std::string &fname,
const Val *data,
size_t rows,
size_t cols = 1
)
{
std::ofstream f(fname.c_str());
precondition(f, "Failed to open file \"" + fname + "\" for writing");
// Banner
f << "%%MatrixMarket matrix array ";
if (boost::is_complex<Val>::value) {
f << "complex ";
} else if(boost::is_integral<Val>::value) {
f << "integer ";
} else {
f << "real ";
}
f << "general\n";
// Sizes
f << rows << " " << cols << "\n";
// Data
for(size_t j = 0; j < cols; ++j) {
for(size_t i = 0; i < rows; ++i) {
detail::write_value(f, data[i * cols + j]) << "\n";
}
}
}
/// Write sparse matrix in Matrix Market format.
template <class Matrix>
void mm_write(const std::string &fname, const Matrix &A) {
typedef typename backend::value_type<Matrix>::type Val;
typedef typename backend::row_iterator<Matrix>::type row_iterator;
const size_t rows = backend::rows(A);
const size_t cols = backend::cols(A);
const size_t nnz = backend::nonzeros(A);
std::ofstream f(fname.c_str());
precondition(f, "Failed to open file \"" + fname + "\" for writing");
// Banner
f << "%%MatrixMarket matrix coordinate ";
if (boost::is_complex<Val>::value) {
f << "complex ";
} else if(boost::is_integral<Val>::value) {
f << "integer ";
} else {
f << "real ";
}
f << "general\n";
// Sizes
f << rows << " " << cols << " " << nnz << "\n";
// Data
for(size_t i = 0; i < rows; ++i) {
for(row_iterator a = backend::row_begin(A, i); a; ++a) {
f << i + 1 << " " << a.col() + 1 << " ";
detail::write_value(f, a.value()) << "\n";
}
}
}
} // namespace io
} // namespace amgcl
#endif
<commit_msg>Fix a bug in chunked MatrixMarket reader<commit_after>#ifndef AMGCL_IO_MM_HPP
#define AMGCL_IO_MM_HPP
/*
The MIT License
Copyright (c) 2012-2018 Denis Demidov <dennis.demidov@gmail.com>
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
*/
/**
* \file amgcl/io/mm.hpp
* \author Denis Demidov <dennis.demidov@gmail.com>
* \brief Readers for Matrix Market sparse matrices and dense vectors.
*/
#include <vector>
#include <string>
#include <fstream>
#include <sstream>
#include <numeric>
#include <boost/type_traits.hpp>
#include <boost/tuple/tuple.hpp>
#include <amgcl/util.hpp>
#include <amgcl/backend/interface.hpp>
#include <amgcl/value_type/interface.hpp>
#include <amgcl/detail/sort_row.hpp>
namespace amgcl {
namespace io {
/// Matrix market reader.
class mm_reader {
public:
/// Open the file by name
mm_reader(const std::string &fname) : f(fname.c_str()) {
precondition(f, "Failed to open file \"" + fname + "\"");
// Read banner.
std::string line;
precondition(std::getline(f, line), format_error());
std::istringstream is(line);
std::string banner, mtx, coord, dtype, storage;
precondition(
is >> banner >> mtx >> coord >> dtype >> storage,
format_error());
precondition(banner == "%%MatrixMarket", format_error("no banner"));
precondition(mtx == "matrix", format_error("not a matrix"));
if (storage == "general") {
_symmetric = false;
} else if (storage == "symmetric") {
_symmetric = true;
} else {
precondition(false, "unsupported storage type");
}
if (coord == "coordinate") {
_sparse = true;
} else if (coord == "array") {
_sparse = false;
} else {
precondition(false, format_error("unsupported coordinate type"));
}
if (dtype == "real") {
_complex = false;
_integer = false;
} else if (dtype == "complex") {
_complex = true;
_integer = false;
} else if (dtype == "integer") {
_complex = false;
_integer = true;
} else {
precondition(false, format_error("unsupported data type"));
}
// Skip comments.
std::streampos pos;
do {
pos = f.tellg();
precondition(std::getline(f, line), format_error("unexpected eof"));
} while (line[0] == '%');
// Get back to the first non-comment line.
f.seekg(pos);
// Read matrix size
is.clear(); is.str(line);
precondition(is >> nrows >> ncols, format_error());
}
/// Matrix in the file is symmetric.
bool is_symmetric() const { return _symmetric; }
/// Matrix in the file is sparse.
bool is_sparse() const { return _sparse; }
/// Matrix in the file is complex-valued.
bool is_complex() const { return _complex; }
/// Matrix in the file is integer-valued.
bool is_integer() const { return _integer; }
/// Number of rows.
size_t rows() const { return nrows; }
/// Number of rows.
size_t cols() const { return ncols; }
/// Read sparse matrix from the file.
template <typename Idx, typename Val>
boost::tuple<size_t, size_t> operator()(
std::vector<Idx> &ptr,
std::vector<Idx> &col,
std::vector<Val> &val,
ptrdiff_t row_beg = -1,
ptrdiff_t row_end = -1
)
{
precondition(_sparse, format_error("not a sparse matrix"));
precondition(boost::is_complex<Val>::value == _complex,
_complex ?
"attempt to read complex values into real vector" :
"attempt to read real values into complex vector"
);
precondition(boost::is_integral<Val>::value == _integer,
_integer ?
"attempt to read integer values into real vector" :
"attempt to read real values into integer vector"
);
// Read sizes
ptrdiff_t n, m;
size_t nnz;
std::string line;
std::istringstream is;
{
precondition(std::getline(f, line), format_error("unexpected eof"));
is.clear(); is.str(line);
precondition(is >> n >> m >> nnz, format_error());
}
if (row_beg < 0) row_beg = 0;
if (row_end < 0) row_end = n;
precondition(row_beg >= 0 && row_end <= n,
"Wrong subset of rows is requested");
ptrdiff_t _nnz = _symmetric ? 2 * nnz : nnz;
if (row_beg != 0 || row_end != n)
_nnz *= 1.2 * (row_end - row_beg) / n;
std::vector<Idx> _row; _row.reserve(_nnz);
std::vector<Idx> _col; _col.reserve(_nnz);
std::vector<Val> _val; _val.reserve(_nnz);
ptr.resize(n+1); std::fill(ptr.begin(), ptr.end(), 0);
for(size_t k = 0; k < nnz; ++k) {
precondition(std::getline(f, line), format_error("unexpected eof"));
is.clear(); is.str(line);
Idx i, j;
Val v;
precondition(is >> i >> j, format_error());
i -= 1;
j -= 1;
v = read_value<Val>(is);
if (row_beg <= i && i < row_end) {
++ptr[i - row_beg + 1];
_row.push_back(i - row_beg);
_col.push_back(j);
_val.push_back(v);
}
if (_symmetric && i != j && row_beg <= j && j < row_end) {
++ptr[j - row_beg + 1];
_row.push_back(j - row_beg);
_col.push_back(i);
_val.push_back(v);
}
}
std::partial_sum(ptr.begin(), ptr.end(), ptr.begin());
col.resize(ptr.back());
val.resize(ptr.back());
for(size_t k = 0, e = val.size(); k < e; ++k) {
Idx i = _row[k];
Idx j = _col[k];
Val v = _val[k];
Idx head = ptr[i]++;
col[head] = j;
val[head] = v;
}
std::rotate(ptr.begin(), ptr.end() - 1, ptr.end());
ptr.front() = 0;
#pragma omp parallel for
for(ptrdiff_t i = 0; i < n; ++i) {
Idx beg = ptr[i];
Idx end = ptr[i+1];
amgcl::detail::sort_row(&col[0] + beg, &val[0] + beg, end - beg);
}
return boost::make_tuple(row_end - row_beg, m);
}
/// Read dense array from the file.
template <typename Val>
boost::tuple<size_t, size_t> operator()(
std::vector<Val> &val,
ptrdiff_t row_beg = -1,
ptrdiff_t row_end = -1
)
{
precondition(!_sparse, format_error("not a dense array"));
precondition(boost::is_complex<Val>::value == _complex,
_complex ?
"attempt to read complex values into real vector" :
"attempt to read real values into complex vector"
);
precondition(boost::is_integral<Val>::value == _integer,
_integer ?
"attempt to read integer values into real vector" :
"attempt to read real values into integer vector"
);
// Read sizes
ptrdiff_t n, m;
std::string line;
std::istringstream is;
{
precondition(std::getline(f, line), format_error("unexpected eof"));
is.clear(); is.str(line);
precondition(is >> n >> m, format_error());
}
if (row_beg < 0) row_beg = 0;
if (row_end < 0) row_end = n;
precondition(row_beg >= 0 && row_end <= n,
"Wrong subset of rows is requested");
val.resize((row_end - row_beg) * m);
for(ptrdiff_t j = 0; j < m; ++j) {
for(ptrdiff_t i = 0; i < n; ++i) {
precondition(std::getline(f, line), format_error("unexpected eof"));
if (row_beg <= i && i < row_end) {
is.clear(); is.str(line);
val[(i - row_beg) * m + j] = read_value<Val>(is);
}
}
}
return boost::make_tuple(row_end - row_beg, m);
}
private:
std::ifstream f;
bool _sparse;
bool _symmetric;
bool _complex;
bool _integer;
size_t nrows, ncols;
std::string format_error(const std::string &msg = "") const {
std::string err_string = "MatrixMarket format error";
if (!msg.empty())
err_string += " (" + msg + ")";
return err_string;
}
template <typename T>
typename boost::enable_if<typename boost::is_complex<T>::type, T>::type
read_value(std::istream &s) {
typename math::scalar_of<T>::type x,y;
precondition(s >> x >> y, format_error());
return T(x,y);
}
template <typename T>
typename boost::disable_if<typename boost::is_complex<T>::type, T>::type
read_value(std::istream &s) {
T x;
if (boost::is_same<T, char>::value) {
// Special case:
// We want to read 8bit integers from MatrixMarket, not chars.
int i;
precondition(s >> i, format_error());
x = static_cast<char>(i);
} else {
precondition(s >> x, format_error());
}
return x;
}
};
namespace detail {
template <typename Val>
typename boost::enable_if<typename boost::is_complex<Val>::type, std::ostream&>::type
write_value(std::ostream &s, Val v) {
return s << std::real(v) << " " << std::imag(v);
}
template <typename Val>
typename boost::disable_if<typename boost::is_complex<Val>::type, std::ostream&>::type
write_value(std::ostream &s, Val v) {
return s << v;
}
} // namespace detail
/// Write dense array in Matrix Market format.
template <typename Val>
void mm_write(
const std::string &fname,
const Val *data,
size_t rows,
size_t cols = 1
)
{
std::ofstream f(fname.c_str());
precondition(f, "Failed to open file \"" + fname + "\" for writing");
// Banner
f << "%%MatrixMarket matrix array ";
if (boost::is_complex<Val>::value) {
f << "complex ";
} else if(boost::is_integral<Val>::value) {
f << "integer ";
} else {
f << "real ";
}
f << "general\n";
// Sizes
f << rows << " " << cols << "\n";
// Data
for(size_t j = 0; j < cols; ++j) {
for(size_t i = 0; i < rows; ++i) {
detail::write_value(f, data[i * cols + j]) << "\n";
}
}
}
/// Write sparse matrix in Matrix Market format.
template <class Matrix>
void mm_write(const std::string &fname, const Matrix &A) {
typedef typename backend::value_type<Matrix>::type Val;
typedef typename backend::row_iterator<Matrix>::type row_iterator;
const size_t rows = backend::rows(A);
const size_t cols = backend::cols(A);
const size_t nnz = backend::nonzeros(A);
std::ofstream f(fname.c_str());
precondition(f, "Failed to open file \"" + fname + "\" for writing");
// Banner
f << "%%MatrixMarket matrix coordinate ";
if (boost::is_complex<Val>::value) {
f << "complex ";
} else if(boost::is_integral<Val>::value) {
f << "integer ";
} else {
f << "real ";
}
f << "general\n";
// Sizes
f << rows << " " << cols << " " << nnz << "\n";
// Data
for(size_t i = 0; i < rows; ++i) {
for(row_iterator a = backend::row_begin(A, i); a; ++a) {
f << i + 1 << " " << a.col() + 1 << " ";
detail::write_value(f, a.value()) << "\n";
}
}
}
} // namespace io
} // namespace amgcl
#endif
<|endoftext|> |
<commit_before>// This file may be redistributed and modified under the terms of the
// GNU Lesser General Public License (See COPYING for details).
// Copyright (C) 2000 Stefanus Du Toit
#include "../Stream/Codec.h"
#include "Utility.h"
using namespace std;
using namespace Atlas::Stream;
/** Packed ASCII codec
[type][name]=[data]
{} for message
() for lists
[] for maps
$ for string
@ for int
# for float
*/
class PackedAscii : public Codec
{
public:
PackedAscii(iostream&, Filter*, Bridge*);
virtual void Initialise(iostream&, Filter*, Bridge*);
virtual void MessageBegin();
virtual void MessageMapBegin();
virtual void MessageEnd();
virtual void MapItem(const std::string& name, const Map&);
virtual void MapItem(const std::string& name, const List&);
virtual void MapItem(const std::string& name, int);
virtual void MapItem(const std::string& name, float);
virtual void MapItem(const std::string& name, const std::string&);
virtual void MapItem(const std::string& name, const Atlas::Object&);
virtual void MapEnd();
virtual void ListItem(const Map&);
virtual void ListItem(const List&);
virtual void ListItem(int);
virtual void ListItem(float);
virtual void ListItem(const std::string&);
virtual void ListItem(const Atlas::Object&);
virtual void ListEnd();
protected:
iostream& socket;
Filter* filter;
Bridge* bridge;
};
namespace {
Codec::Factory<PackedAscii> factor("PackedAscii", Codec::Metrics(1, 2));
}
PackedAscii::PackedAscii(iostream& socket, Filter* f, Bridge* b) :
socket(socket), filter(f), bridge(b)
{
}
void PackedAscii::MessageBegin()
{
socket << "{";
}
void PackedAscii::MessageMapBegin()
{
socket << "[=";
}
void PackedAscii::MessageEnd()
{
socket << "}";
}
void PackedAscii::MapItem(const std::string& name, const Map&)
{
socket << "[" << name << "=";
}
void PackedAscii::MapItem(const std::string& name, const List&)
{
socket << "(" << name << "=";
}
void PackedAscii::MapItem(const std::string& name, int data)
{
socket << "@" << name << "=" << data;
}
void PackedAscii::MapItem(const std::string& name, float data)
{
socket << "#" << name << "=" << data;
}
void PackedAscii::MapItem(const std::string& name, const std::string& data)
{
socket << "$" << name << "=" << data;
}
void PackedAscii::MapItem(const std::string& name, const Atlas::Object& data)
{
// FIXME recursive...
}
void PackedAscii::MapEnd()
{
socket << "]";
}
void PackedAscii::ListItem(const Map&)
{
socket << "[=";
}
void PackedAscii::ListItem(const List&)
{
socket << "(=";
}
void PackedAscii::ListItem(int data)
{
socket << "@=" << data;
}
void PackedAscii::ListItem(float data)
{
socket << "#=" << data;
}
void PackedAscii::ListItem(const std::string& data)
{
socket << "$=" << data;
}
void PackedAscii::ListItem(const Atlas::Object& data)
{
// FIXME recursive...
}
void PackedAscii::ListEnd()
{
socket << ")";
}
<commit_msg>It actually *uses* hexEncode() now :)<commit_after>// This file may be redistributed and modified under the terms of the
// GNU Lesser General Public License (See COPYING for details).
// Copyright (C) 2000 Stefanus Du Toit
#include "../Stream/Codec.h"
#include "Utility.h"
using namespace std;
using namespace Atlas::Stream;
/** Packed ASCII codec
[type][name]=[data]
{} for message
() for lists
[] for maps
$ for string
@ for int
# for float
*/
class PackedAscii : public Codec
{
public:
PackedAscii(iostream&, Filter*, Bridge*);
virtual void Initialise(iostream&, Filter*, Bridge*);
virtual void MessageBegin();
virtual void MessageMapBegin();
virtual void MessageEnd();
virtual void MapItem(const std::string& name, const Map&);
virtual void MapItem(const std::string& name, const List&);
virtual void MapItem(const std::string& name, int);
virtual void MapItem(const std::string& name, float);
virtual void MapItem(const std::string& name, const std::string&);
virtual void MapItem(const std::string& name, const Atlas::Object&);
virtual void MapEnd();
virtual void ListItem(const Map&);
virtual void ListItem(const List&);
virtual void ListItem(int);
virtual void ListItem(float);
virtual void ListItem(const std::string&);
virtual void ListItem(const Atlas::Object&);
virtual void ListEnd();
protected:
iostream& socket;
Filter* filter;
Bridge* bridge;
};
namespace {
Codec::Factory<PackedAscii> factor("PackedAscii", Codec::Metrics(1, 2));
}
PackedAscii::PackedAscii(iostream& socket, Filter* f, Bridge* b) :
socket(socket), filter(f), bridge(b)
{
}
void PackedAscii::MessageBegin()
{
socket << "{";
}
void PackedAscii::MessageMapBegin()
{
socket << "[=";
}
void PackedAscii::MessageEnd()
{
socket << "}";
}
void PackedAscii::MapItem(const std::string& name, const Map&)
{
socket << "[" << hexEncode("+", "", "+{}[]()@#$=", name) << "=";
}
void PackedAscii::MapItem(const std::string& name, const List&)
{
socket << "(" << hexEncode("+", "", "+{}[]()@#$=", name) << "=";
}
void PackedAscii::MapItem(const std::string& name, int data)
{
socket << "@" << hexEncode("+", "", "+{}[]()@#$=", name) << "=" << data;
}
void PackedAscii::MapItem(const std::string& name, float data)
{
socket << "#" << hexEncode("+", "", "+{}[]()@#$=", name) << "=" << data;
}
void PackedAscii::MapItem(const std::string& name, const std::string& data)
{
socket << "$" << hexEncode("+", "", "+{}[]()@#$=", name) << "=" <<
hexEncode("+", "+{}[]()@#$=", "", data);
}
void PackedAscii::MapItem(const std::string& name, const Atlas::Object& data)
{
// FIXME recursive...
}
void PackedAscii::MapEnd()
{
socket << "]";
}
void PackedAscii::ListItem(const Map&)
{
socket << "[=";
}
void PackedAscii::ListItem(const List&)
{
socket << "(=";
}
void PackedAscii::ListItem(int data)
{
socket << "@=" << data;
}
void PackedAscii::ListItem(float data)
{
socket << "#=" << data;
}
void PackedAscii::ListItem(const std::string& data)
{
socket << "$=" << hexEncode("+", "", "+{}[]()@#$=", data);
}
void PackedAscii::ListItem(const Atlas::Object& data)
{
// FIXME recursive...
}
void PackedAscii::ListEnd()
{
socket << ")";
}
<|endoftext|> |
<commit_before>#ifndef __ARRAYS_HPP__
#define __ARRAYS_HPP__
#include <string>
#include <type_traits>
#ifdef __CYGWIN__
#include <sstream>
namespace std {
inline std::string to_string(unsigned long val) { ostringstream os; os << val; return os.str(); }
}
#endif
namespace {
namespace __typedecl {
struct split_string {
std::string begin;
std::string end;
explicit operator std::string() const {
return begin + end;
}
};
inline split_string operator+(const std::string& s, const split_string& ss) {
return { s + ss.begin, ss.end };
}
inline split_string operator+(const split_string& ss, const std::string& s) {
return { ss.begin, ss.end + s };
}
enum type_type { BASICTYPE, COMPOSITION };
struct basic_type { static constexpr type_type type = BASICTYPE; };
struct composition { static constexpr type_type type = COMPOSITION; };
template <typename T>
struct impl;
template <typename T, type_type = impl<T>::type>
struct prefix_cv_qual_if_basictype;
template <typename T>
struct prefix_cv_qual_if_basictype<T, BASICTYPE> {
inline static split_string value(const std::string& cv_qual, const split_string& suffix) {
return impl<T>::value_with_cv_qual(cv_qual, suffix);
}
};
template <typename T>
struct prefix_cv_qual_if_basictype<T, COMPOSITION> {
inline static split_string value(const std::string& cv_qual, const split_string& suffix) {
return impl<T>::value(cv_qual + suffix);
}
};
template <typename T>
struct impl<const T> {
inline static split_string value(const split_string& suffix = {}) {
return prefix_cv_qual_if_basictype<T>::value("const", suffix);
}
};
template <typename T>
struct impl<volatile T> {
inline static split_string value(const split_string& suffix = {}) {
return prefix_cv_qual_if_basictype<T>::value("volatile", suffix);
}
};
// Required to disambiguate between <const T> and <volatile T>
template <typename T>
struct impl<const volatile T> {
inline static split_string value(const split_string& suffix = {}) {
return prefix_cv_qual_if_basictype<T>::value("const volatile", suffix);
}
};
template <typename T, bool = std::is_array<T>::value || std::is_function<T>::value>
struct parenthesize_if_array_or_function;
template <typename T>
struct parenthesize_if_array_or_function<T, false> {
inline static split_string value(const split_string& arg) {
return impl<T>::value(arg);
}
};
template <typename T>
struct parenthesize_if_array_or_function<T, true> {
inline static split_string value(const split_string& arg) {
return impl<T>::value("(" + arg + ")");
}
};
template <typename T>
struct impl<T*> : composition {
inline static split_string value(const split_string& suffix = {}) {
return parenthesize_if_array_or_function<T>::value("*" + suffix);
}
};
template <typename T>
struct impl<T&> {
inline static split_string value(const split_string& suffix = {}) {
return parenthesize_if_array_or_function<T>::value("&" + suffix);
}
};
template <typename T>
struct impl<T&&> {
inline static split_string value(const split_string& suffix = {}) {
return parenthesize_if_array_or_function<T>::value("&&" + suffix);
}
};
template <typename T>
struct array_impl : composition {
inline static split_string value(const split_string& prefix = {}) {
return impl<T>::value(prefix + "[]");
}
};
template <typename T>
struct impl<T[]> : array_impl<T> {};
// Required to disambiguate between <const T> and <T[]>
template <typename T>
struct impl<const T[]> : array_impl<const T> {};
// Required to disambiguate between <volatile T> and <T[]>
template <typename T>
struct impl<volatile T[]> : array_impl<volatile T> {};
// Required to disambiguate between <const T>, <volatile T>, <const volatile T>, <T[]>, <const T[]> and <volatile T[]>
template <typename T>
struct impl<const volatile T[]> : array_impl<const volatile T> {};
template <typename T, size_t N>
struct sized_array_impl : composition {
inline static split_string value(const split_string& prefix = {}) {
return impl<T>::value(prefix + ("[" + std::to_string(N) + "]"));
}
};
template <typename T, size_t N>
struct impl<T[N]> : sized_array_impl<T, N> {};
// Required to disambiguate between <const T> and <T[N]>
template <typename T, size_t N>
struct impl<const T[N]> : sized_array_impl<const T, N> {};
// Required to disambiguate between <volatile T> and <T[N]>
template <typename T, size_t N>
struct impl<volatile T[N]> : sized_array_impl<volatile T, N> {};
// Required to disambiguate between <const T>, <volatile T>, <const volatile T>, <T[N]>, <const T[N]> and <volatile T[N]>
template <typename T, size_t N>
struct impl<const volatile T[N]> : sized_array_impl<const volatile T, N> {};
template <bool VA, typename... T>
struct type_list_impl;
template <bool VA>
struct type_list_impl<VA> {
inline static std::string value() {
return VA ? "..." : "";
}
};
template <bool VA, typename T>
struct type_list_impl<VA, T> {
inline static std::string value() {
return static_cast<std::string>(impl<T>::value()) + (VA ? ", ..." : "");
}
};
template <bool VA, typename T1, typename T2, typename... U>
struct type_list_impl<VA, T1, T2, U...> {
inline static std::string value() {
return static_cast<std::string>(impl<T1>::value()) + ", " + type_list_impl<VA, T2, U...>::value();
}
};
template <bool P, typename R, bool VA, typename... A>
struct function_impl;
template <typename R, bool VA, typename... A>
struct function_impl<false, R, VA, A...> {
inline static split_string value(const split_string& infix = {}) {
return static_cast<std::string>(impl<R>::value()) + infix + "(" + type_list_impl<VA, A...>::value() + ")";
}
};
template <typename R, bool VA, typename... A>
struct function_impl<true, R, VA, A...> {
inline static split_string value(const split_string& prefix = {}) {
return impl<R>::value(prefix + "(" + type_list_impl<VA, A...>::value() + ")");
}
};
template <typename T>
struct is_pointer_or_reference : std::integral_constant<
bool,
std::is_pointer<T>::value || std::is_reference<T>::value
> {};
template <typename R, typename... A>
struct impl<R(A...)> : function_impl<is_pointer_or_reference<typename std::remove_cv<R>::type>::value, R, false, A...> {};
template <typename R, typename... A>
struct impl<R(A..., ...)> : function_impl<is_pointer_or_reference<typename std::remove_cv<R>::type>::value, R, true, A...> {};
} /* namespace __typedecl */
} /* unnamed namespace */
template <typename T>
inline std::string typedecl() {
__typedecl::split_string ss = __typedecl::impl<T>::value();
return ss.begin + ss.end;
}
template <typename T>
inline std::string namedecl(const std::string& name) {
__typedecl::split_string ss = __typedecl::impl<T>::value();
return ss.begin + " " + name + ss.end;
}
#define DEFINE_TYPEDECL(T) \
namespace { \
namespace __typedecl { \
template <> \
struct impl<T> : basic_type { \
inline static split_string value(const split_string& suffix = {}) { \
return #T + suffix; \
} \
inline static split_string value_with_cv_qual(const std::string& cv_qual, const split_string& suffix) { \
return (cv_qual + " " #T) + suffix; \
} \
}; \
} /* namespace __typedecl */ \
} /* unnamed namespace */
DEFINE_TYPEDECL(void);
DEFINE_TYPEDECL(char);
DEFINE_TYPEDECL(int);
#endif
<commit_msg>Split template specializations where a bool template argument was used<commit_after>#ifndef __ARRAYS_HPP__
#define __ARRAYS_HPP__
#include <string>
#include <type_traits>
#ifdef __CYGWIN__
#include <sstream>
namespace std {
inline std::string to_string(unsigned long val) { ostringstream os; os << val; return os.str(); }
}
#endif
namespace {
namespace __typedecl {
struct split_string {
std::string begin;
std::string end;
explicit operator std::string() const {
return begin + end;
}
};
inline split_string operator+(const std::string& s, const split_string& ss) {
return { s + ss.begin, ss.end };
}
inline split_string operator+(const split_string& ss, const std::string& s) {
return { ss.begin, ss.end + s };
}
enum type_type { BASICTYPE, COMPOSITION };
struct basic_type { static constexpr type_type type = BASICTYPE; };
struct composition { static constexpr type_type type = COMPOSITION; };
template <typename T>
struct impl;
template <typename T, type_type = impl<T>::type>
struct prefix_cv_qual_if_basictype;
template <typename T>
struct prefix_cv_qual_if_basictype<T, BASICTYPE> {
inline static split_string value(const std::string& cv_qual, const split_string& suffix) {
return impl<T>::value_with_cv_qual(cv_qual, suffix);
}
};
template <typename T>
struct prefix_cv_qual_if_basictype<T, COMPOSITION> {
inline static split_string value(const std::string& cv_qual, const split_string& suffix) {
return impl<T>::value(cv_qual + suffix);
}
};
template <typename T>
struct impl<const T> {
inline static split_string value(const split_string& suffix = {}) {
return prefix_cv_qual_if_basictype<T>::value("const", suffix);
}
};
template <typename T>
struct impl<volatile T> {
inline static split_string value(const split_string& suffix = {}) {
return prefix_cv_qual_if_basictype<T>::value("volatile", suffix);
}
};
// Required to disambiguate between <const T> and <volatile T>
template <typename T>
struct impl<const volatile T> {
inline static split_string value(const split_string& suffix = {}) {
return prefix_cv_qual_if_basictype<T>::value("const volatile", suffix);
}
};
template <typename T, bool = std::is_array<T>::value || std::is_function<T>::value>
struct parenthesize_if_array_or_function;
template <typename T>
struct parenthesize_if_array_or_function<T, false> {
inline static split_string value(const split_string& arg) {
return impl<T>::value(arg);
}
};
template <typename T>
struct parenthesize_if_array_or_function<T, true> {
inline static split_string value(const split_string& arg) {
return impl<T>::value("(" + arg + ")");
}
};
template <typename T>
struct impl<T*> : composition {
inline static split_string value(const split_string& suffix = {}) {
return parenthesize_if_array_or_function<T>::value("*" + suffix);
}
};
template <typename T>
struct impl<T&> {
inline static split_string value(const split_string& suffix = {}) {
return parenthesize_if_array_or_function<T>::value("&" + suffix);
}
};
template <typename T>
struct impl<T&&> {
inline static split_string value(const split_string& suffix = {}) {
return parenthesize_if_array_or_function<T>::value("&&" + suffix);
}
};
template <typename T>
struct array_impl : composition {
inline static split_string value(const split_string& prefix = {}) {
return impl<T>::value(prefix + "[]");
}
};
template <typename T>
struct impl<T[]> : array_impl<T> {};
// Required to disambiguate between <const T> and <T[]>
template <typename T>
struct impl<const T[]> : array_impl<const T> {};
// Required to disambiguate between <volatile T> and <T[]>
template <typename T>
struct impl<volatile T[]> : array_impl<volatile T> {};
// Required to disambiguate between <const T>, <volatile T>, <const volatile T>, <T[]>, <const T[]> and <volatile T[]>
template <typename T>
struct impl<const volatile T[]> : array_impl<const volatile T> {};
template <typename T, size_t N>
struct sized_array_impl : composition {
inline static split_string value(const split_string& prefix = {}) {
return impl<T>::value(prefix + ("[" + std::to_string(N) + "]"));
}
};
template <typename T, size_t N>
struct impl<T[N]> : sized_array_impl<T, N> {};
// Required to disambiguate between <const T> and <T[N]>
template <typename T, size_t N>
struct impl<const T[N]> : sized_array_impl<const T, N> {};
// Required to disambiguate between <volatile T> and <T[N]>
template <typename T, size_t N>
struct impl<volatile T[N]> : sized_array_impl<volatile T, N> {};
// Required to disambiguate between <const T>, <volatile T>, <const volatile T>, <T[N]>, <const T[N]> and <volatile T[N]>
template <typename T, size_t N>
struct impl<const volatile T[N]> : sized_array_impl<const volatile T, N> {};
template <bool VA, typename... T>
struct type_list_impl;
template <>
struct type_list_impl<true> {
inline static std::string value() {
return "...";
}
};
template <>
struct type_list_impl<false> {
inline static std::string value() {
return "";
}
};
template <typename T>
struct type_list_impl<true, T> {
inline static std::string value() {
return static_cast<std::string>(impl<T>::value()) + ", ...";
}
};
template <typename T>
struct type_list_impl<false, T> {
inline static std::string value() {
return static_cast<std::string>(impl<T>::value());
}
};
template <bool VA, typename T1, typename T2, typename... U>
struct type_list_impl<VA, T1, T2, U...> {
inline static std::string value() {
return static_cast<std::string>(impl<T1>::value()) + ", " + type_list_impl<VA, T2, U...>::value();
}
};
template <bool P, typename R, bool VA, typename... A>
struct function_impl;
template <typename R, bool VA, typename... A>
struct function_impl<false, R, VA, A...> {
inline static split_string value(const split_string& infix = {}) {
return static_cast<std::string>(impl<R>::value()) + infix + "(" + type_list_impl<VA, A...>::value() + ")";
}
};
template <typename R, bool VA, typename... A>
struct function_impl<true, R, VA, A...> {
inline static split_string value(const split_string& prefix = {}) {
return impl<R>::value(prefix + "(" + type_list_impl<VA, A...>::value() + ")");
}
};
template <typename T>
struct is_pointer_or_reference : std::integral_constant<
bool,
std::is_pointer<T>::value || std::is_reference<T>::value
> {};
template <typename R, typename... A>
struct impl<R(A...)> : function_impl<is_pointer_or_reference<typename std::remove_cv<R>::type>::value, R, false, A...> {};
template <typename R, typename... A>
struct impl<R(A..., ...)> : function_impl<is_pointer_or_reference<typename std::remove_cv<R>::type>::value, R, true, A...> {};
} /* namespace __typedecl */
} /* unnamed namespace */
template <typename T>
inline std::string typedecl() {
__typedecl::split_string ss = __typedecl::impl<T>::value();
return ss.begin + ss.end;
}
template <typename T>
inline std::string namedecl(const std::string& name) {
__typedecl::split_string ss = __typedecl::impl<T>::value();
return ss.begin + " " + name + ss.end;
}
#define DEFINE_TYPEDECL(T) \
namespace { \
namespace __typedecl { \
template <> \
struct impl<T> : basic_type { \
inline static split_string value(const split_string& suffix = {}) { \
return #T + suffix; \
} \
inline static split_string value_with_cv_qual(const std::string& cv_qual, const split_string& suffix) { \
return (cv_qual + " " #T) + suffix; \
} \
}; \
} /* namespace __typedecl */ \
} /* unnamed namespace */
DEFINE_TYPEDECL(void);
DEFINE_TYPEDECL(char);
DEFINE_TYPEDECL(int);
#endif
<|endoftext|> |
<commit_before>/*%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
Module: FGRocket.cpp
Author: Jon S. Berndt
Date started: 09/12/2000
Purpose: This module models a rocket engine
------------- Copyright (C) 2000 Jon S. Berndt (jon@jsbsim.org) --------------
This program is free software; you can redistribute it and/or modify it under
the terms of the GNU Lesser General Public License as published by the Free Software
Foundation; either version 2 of the License, or (at your option) any later
version.
This 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 Lesser General Public License for more
details.
You should have received a copy of the GNU Lesser 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.
Further information about the GNU Lesser General Public License can also be found on
the world wide web at http://www.gnu.org.
FUNCTIONAL DESCRIPTION
--------------------------------------------------------------------------------
This class descends from the FGEngine class and models a rocket engine based on
parameters given in the engine config file for this class
HISTORY
--------------------------------------------------------------------------------
09/12/2000 JSB Created
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
INCLUDES
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%*/
#include <iostream>
#include <sstream>
#include "FGRocket.h"
#include "FGThruster.h"
using namespace std;
namespace JSBSim {
static const char *IdSrc = "$Id: FGRocket.cpp,v 1.29 2013/01/12 21:11:59 jberndt Exp $";
static const char *IdHdr = ID_ROCKET;
/*%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
CLASS IMPLEMENTATION
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%*/
FGRocket::FGRocket(FGFDMExec* exec, Element *el, int engine_number, struct Inputs& input)
: FGEngine(exec, el, engine_number, input), isp_function(0L)
{
Type = etRocket;
Element* thrust_table_element = 0;
ThrustTable = 0L;
BurnTime = 0.0;
previousFuelNeedPerTank = 0.0;
previousOxiNeedPerTank = 0.0;
PropellantFlowRate = 0.0;
TotalPropellantExpended = 0.0;
FuelFlowRate = FuelExpended = 0.0;
OxidizerFlowRate = OxidizerExpended = 0.0;
SLOxiFlowMax = SLFuelFlowMax = PropFlowMax = 0.0;
MxR = 0.0;
BuildupTime = 0.0;
It = ItVac = 0.0;
ThrustVariation = 0.0;
TotalIspVariation = 0.0;
VacThrust = 0.0;
Flameout = false;
// Defaults
MinThrottle = 0.0;
MaxThrottle = 1.0;
string base_property_name = CreateIndexedPropertyName("propulsion/engine", EngineNumber);
std::stringstream strEngineNumber;
strEngineNumber << EngineNumber;
Element* isp_el = el->FindElement("isp");
Element* isp_func_el=0;
bindmodel(); // Bind model properties first, since they might be needed in functions.
// Specific impulse may be specified as a constant value or as a function - perhaps as a function of mixture ratio.
if (isp_el) {
isp_func_el = isp_el->FindElement("function");
if (isp_func_el) {
isp_function = new FGFunction(exec->GetPropertyManager(),isp_func_el, strEngineNumber.str());
} else {
Isp = el->FindElementValueAsNumber("isp");
}
} else {
throw("Specific Impulse <isp> must be specified for a rocket engine");
}
if (el->FindElement("builduptime"))
BuildupTime = el->FindElementValueAsNumber("builduptime");
if (el->FindElement("maxthrottle"))
MaxThrottle = el->FindElementValueAsNumber("maxthrottle");
if (el->FindElement("minthrottle"))
MinThrottle = el->FindElementValueAsNumber("minthrottle");
if (el->FindElement("slfuelflowmax")) {
SLFuelFlowMax = el->FindElementValueAsNumberConvertTo("slfuelflowmax", "LBS/SEC");
if (el->FindElement("sloxiflowmax")) {
SLOxiFlowMax = el->FindElementValueAsNumberConvertTo("sloxiflowmax", "LBS/SEC");
}
PropFlowMax = SLOxiFlowMax + SLFuelFlowMax;
MxR = SLOxiFlowMax/SLFuelFlowMax;
} else if (el->FindElement("propflowmax")) {
PropFlowMax = el->FindElementValueAsNumberConvertTo("propflowmax", "LBS/SEC");
// Mixture ratio may be specified here, but it can also be specified as a function or via property
if (el->FindElement("mixtureratio")) {
MxR = el->FindElementValueAsNumber("mixtureratio");
}
}
if (isp_function) Isp = isp_function->GetValue(); // cause Isp function to be executed if present.
// If there is a thrust table element, this is a solid propellant engine.
thrust_table_element = el->FindElement("thrust_table");
if (thrust_table_element) {
ThrustTable = new FGTable(PropertyManager, thrust_table_element);
Element* variation_element = el->FindElement("variation");
if (variation_element) {
if (variation_element->FindElement("thrust")) {
ThrustVariation = variation_element->FindElementValueAsNumber("thrust");
}
if (variation_element->FindElement("total_isp")) {
TotalIspVariation = variation_element->FindElementValueAsNumber("total_isp");
}
}
}
Debug(0);
}
//%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
FGRocket::~FGRocket(void)
{
delete ThrustTable;
Debug(1);
}
//%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
void FGRocket::Calculate(void)
{
if (FDMExec->IntegrationSuspended()) return;
RunPreFunctions();
PropellantFlowRate = (FuelExpended + OxidizerExpended)/in.TotalDeltaT;
TotalPropellantExpended += FuelExpended + OxidizerExpended;
// If Isp has been specified as a function, override the value of Isp to that, otherwise
// assume a constant value is given.
if (isp_function) Isp = isp_function->GetValue();
// If there is a thrust table, it is a function of propellant burned. The
// engine is started when the throttle is advanced to 1.0. After that, it
// burns without regard to throttle setting.
if (ThrustTable != 0L) { // Thrust table given -> Solid fuel used
if ((in.ThrottlePos[EngineNumber] == 1 || BurnTime > 0.0 ) && !Starved) {
VacThrust = ThrustTable->GetValue(TotalPropellantExpended)
* (ThrustVariation + 1)
* (TotalIspVariation + 1);
if (BurnTime <= BuildupTime && BuildupTime > 0.0) {
VacThrust *= sin((BurnTime/BuildupTime)*M_PI/2.0);
// VacThrust *= (1-cos((BurnTime/BuildupTime)*M_PI))/2.0; // 1 - cos approach
}
BurnTime += in.TotalDeltaT; // Increment burn time
} else {
VacThrust = 0.0;
}
} else { // liquid fueled rocket assumed
if (in.ThrottlePos[EngineNumber] < MinThrottle || Starved) { // Combustion not supported
PctPower = 0.0; // desired thrust
Flameout = true;
VacThrust = 0.0;
} else { // Calculate thrust
// PctPower = Throttle / MaxThrottle; // Min and MaxThrottle range from 0.0 to 1.0, normally.
PctPower = in.ThrottlePos[EngineNumber];
Flameout = false;
VacThrust = Isp * PropellantFlowRate;
}
} // End thrust calculations
LoadThrusterInputs();
It += Thruster->Calculate(VacThrust) * in.TotalDeltaT;
ItVac += VacThrust * in.TotalDeltaT;
RunPostFunctions();
}
//%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
//
// The FuelFlowRate can be affected by the TotalIspVariation value (settable
// in a config file or via properties). The TotalIspVariation parameter affects
// thrust, but the thrust determines fuel flow rate, so it must be adjusted
// for Total Isp Variation.
double FGRocket::CalcFuelNeed(void)
{
if (ThrustTable != 0L) { // Thrust table given - infers solid fuel
FuelFlowRate = VacThrust/Isp; // This calculates wdot (weight flow rate in lbs/sec)
FuelFlowRate /= (1 + TotalIspVariation);
} else {
SLFuelFlowMax = PropFlowMax / (1 + MxR);
FuelFlowRate = SLFuelFlowMax * PctPower;
}
FuelExpended = FuelFlowRate * in.TotalDeltaT; // For this time step ...
return FuelExpended;
}
//%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
double FGRocket::CalcOxidizerNeed(void)
{
SLOxiFlowMax = PropFlowMax * MxR / (1 + MxR);
OxidizerFlowRate = SLOxiFlowMax * PctPower;
OxidizerExpended = OxidizerFlowRate * in.TotalDeltaT;
return OxidizerExpended;
}
//%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
string FGRocket::GetEngineLabels(const string& delimiter)
{
std::ostringstream buf;
buf << Name << " Total Impulse (engine " << EngineNumber << " in psf)" << delimiter
<< Name << " Total Vacuum Impulse (engine " << EngineNumber << " in psf)" << delimiter
<< Thruster->GetThrusterLabels(EngineNumber, delimiter);
return buf.str();
}
//%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
string FGRocket::GetEngineValues(const string& delimiter)
{
std::ostringstream buf;
buf << It << delimiter
<< ItVac << delimiter
<< Thruster->GetThrusterValues(EngineNumber, delimiter);
return buf.str();
}
//%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
// This function should tie properties to rocket engine specific properties
// that are not bound in the base class (FGEngine) code.
//
void FGRocket::bindmodel()
{
string property_name, base_property_name;
base_property_name = CreateIndexedPropertyName("propulsion/engine", EngineNumber);
property_name = base_property_name + "/total-impulse";
PropertyManager->Tie( property_name.c_str(), this, &FGRocket::GetTotalImpulse);
property_name = base_property_name + "/vacuum-thrust_lbs";
PropertyManager->Tie( property_name.c_str(), this, &FGRocket::GetVacThrust);
if (ThrustTable) { // Solid rocket motor
property_name = base_property_name + "/thrust-variation_pct";
PropertyManager->Tie( property_name.c_str(), this, &FGRocket::GetThrustVariation,
&FGRocket::SetThrustVariation);
property_name = base_property_name + "/total-isp-variation_pct";
PropertyManager->Tie( property_name.c_str(), this, &FGRocket::GetTotalIspVariation,
&FGRocket::SetTotalIspVariation);
} else { // Liquid rocket motor
property_name = base_property_name + "/oxi-flow-rate-pps";
PropertyManager->Tie( property_name.c_str(), this, &FGRocket::GetOxiFlowRate);
property_name = base_property_name + "/mixture-ratio";
PropertyManager->Tie( property_name.c_str(), this, &FGRocket::GetMixtureRatio,
&FGRocket::SetMixtureRatio);
property_name = base_property_name + "/isp";
PropertyManager->Tie( property_name.c_str(), this, &FGRocket::GetIsp,
&FGRocket::SetIsp);
}
}
//%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
// The bitmasked value choices are as follows:
// unset: In this case (the default) JSBSim would only print
// out the normally expected messages, essentially echoing
// the config files as they are read. If the environment
// variable is not set, debug_lvl is set to 1 internally
// 0: This requests JSBSim not to output any messages
// whatsoever.
// 1: This value explicity requests the normal JSBSim
// startup messages
// 2: This value asks for a message to be printed out when
// a class is instantiated
// 4: When this value is set, a message is displayed when a
// FGModel object executes its Run() method
// 8: When this value is set, various runtime state variables
// are printed out periodically
// 16: When set various parameters are sanity checked and
// a message is printed out when they go out of bounds
void FGRocket::Debug(int from)
{
if (debug_lvl <= 0) return;
if (debug_lvl & 1) { // Standard console startup message output
if (from == 0) { // Constructor
cout << " Engine Name: " << Name << endl;
cout << " Vacuum Isp = " << Isp << endl;
cout << " Maximum Throttle = " << MaxThrottle << endl;
cout << " Minimum Throttle = " << MinThrottle << endl;
cout << " Fuel Flow (max) = " << SLFuelFlowMax << endl;
cout << " Oxidizer Flow (max) = " << SLOxiFlowMax << endl;
if (SLFuelFlowMax > 0)
cout << " Mixture ratio = " << SLOxiFlowMax/SLFuelFlowMax << endl;
}
}
if (debug_lvl & 2 ) { // Instantiation/Destruction notification
if (from == 0) cout << "Instantiated: FGRocket" << endl;
if (from == 1) cout << "Destroyed: FGRocket" << endl;
}
if (debug_lvl & 4 ) { // Run() method entry print for FGModel-derived objects
}
if (debug_lvl & 8 ) { // Runtime state variables
}
if (debug_lvl & 16) { // Sanity checking
}
if (debug_lvl & 64) {
if (from == 0) { // Constructor
cout << IdSrc << endl;
cout << IdHdr << endl;
}
}
}
}
<commit_msg>Fixed units text in output<commit_after>/*%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
Module: FGRocket.cpp
Author: Jon S. Berndt
Date started: 09/12/2000
Purpose: This module models a rocket engine
------------- Copyright (C) 2000 Jon S. Berndt (jon@jsbsim.org) --------------
This program is free software; you can redistribute it and/or modify it under
the terms of the GNU Lesser General Public License as published by the Free Software
Foundation; either version 2 of the License, or (at your option) any later
version.
This 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 Lesser General Public License for more
details.
You should have received a copy of the GNU Lesser 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.
Further information about the GNU Lesser General Public License can also be found on
the world wide web at http://www.gnu.org.
FUNCTIONAL DESCRIPTION
--------------------------------------------------------------------------------
This class descends from the FGEngine class and models a rocket engine based on
parameters given in the engine config file for this class
HISTORY
--------------------------------------------------------------------------------
09/12/2000 JSB Created
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
INCLUDES
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%*/
#include <iostream>
#include <sstream>
#include "FGRocket.h"
#include "FGThruster.h"
using namespace std;
namespace JSBSim {
static const char *IdSrc = "$Id: FGRocket.cpp,v 1.30 2013/06/10 02:00:11 jberndt Exp $";
static const char *IdHdr = ID_ROCKET;
/*%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
CLASS IMPLEMENTATION
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%*/
FGRocket::FGRocket(FGFDMExec* exec, Element *el, int engine_number, struct Inputs& input)
: FGEngine(exec, el, engine_number, input), isp_function(0L)
{
Type = etRocket;
Element* thrust_table_element = 0;
ThrustTable = 0L;
BurnTime = 0.0;
previousFuelNeedPerTank = 0.0;
previousOxiNeedPerTank = 0.0;
PropellantFlowRate = 0.0;
TotalPropellantExpended = 0.0;
FuelFlowRate = FuelExpended = 0.0;
OxidizerFlowRate = OxidizerExpended = 0.0;
SLOxiFlowMax = SLFuelFlowMax = PropFlowMax = 0.0;
MxR = 0.0;
BuildupTime = 0.0;
It = ItVac = 0.0;
ThrustVariation = 0.0;
TotalIspVariation = 0.0;
VacThrust = 0.0;
Flameout = false;
// Defaults
MinThrottle = 0.0;
MaxThrottle = 1.0;
string base_property_name = CreateIndexedPropertyName("propulsion/engine", EngineNumber);
std::stringstream strEngineNumber;
strEngineNumber << EngineNumber;
Element* isp_el = el->FindElement("isp");
Element* isp_func_el=0;
bindmodel(); // Bind model properties first, since they might be needed in functions.
// Specific impulse may be specified as a constant value or as a function - perhaps as a function of mixture ratio.
if (isp_el) {
isp_func_el = isp_el->FindElement("function");
if (isp_func_el) {
isp_function = new FGFunction(exec->GetPropertyManager(),isp_func_el, strEngineNumber.str());
} else {
Isp = el->FindElementValueAsNumber("isp");
}
} else {
throw("Specific Impulse <isp> must be specified for a rocket engine");
}
if (el->FindElement("builduptime"))
BuildupTime = el->FindElementValueAsNumber("builduptime");
if (el->FindElement("maxthrottle"))
MaxThrottle = el->FindElementValueAsNumber("maxthrottle");
if (el->FindElement("minthrottle"))
MinThrottle = el->FindElementValueAsNumber("minthrottle");
if (el->FindElement("slfuelflowmax")) {
SLFuelFlowMax = el->FindElementValueAsNumberConvertTo("slfuelflowmax", "LBS/SEC");
if (el->FindElement("sloxiflowmax")) {
SLOxiFlowMax = el->FindElementValueAsNumberConvertTo("sloxiflowmax", "LBS/SEC");
}
PropFlowMax = SLOxiFlowMax + SLFuelFlowMax;
MxR = SLOxiFlowMax/SLFuelFlowMax;
} else if (el->FindElement("propflowmax")) {
PropFlowMax = el->FindElementValueAsNumberConvertTo("propflowmax", "LBS/SEC");
// Mixture ratio may be specified here, but it can also be specified as a function or via property
if (el->FindElement("mixtureratio")) {
MxR = el->FindElementValueAsNumber("mixtureratio");
}
}
if (isp_function) Isp = isp_function->GetValue(); // cause Isp function to be executed if present.
// If there is a thrust table element, this is a solid propellant engine.
thrust_table_element = el->FindElement("thrust_table");
if (thrust_table_element) {
ThrustTable = new FGTable(PropertyManager, thrust_table_element);
Element* variation_element = el->FindElement("variation");
if (variation_element) {
if (variation_element->FindElement("thrust")) {
ThrustVariation = variation_element->FindElementValueAsNumber("thrust");
}
if (variation_element->FindElement("total_isp")) {
TotalIspVariation = variation_element->FindElementValueAsNumber("total_isp");
}
}
}
Debug(0);
}
//%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
FGRocket::~FGRocket(void)
{
delete ThrustTable;
Debug(1);
}
//%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
void FGRocket::Calculate(void)
{
if (FDMExec->IntegrationSuspended()) return;
RunPreFunctions();
PropellantFlowRate = (FuelExpended + OxidizerExpended)/in.TotalDeltaT;
TotalPropellantExpended += FuelExpended + OxidizerExpended;
// If Isp has been specified as a function, override the value of Isp to that, otherwise
// assume a constant value is given.
if (isp_function) Isp = isp_function->GetValue();
// If there is a thrust table, it is a function of propellant burned. The
// engine is started when the throttle is advanced to 1.0. After that, it
// burns without regard to throttle setting.
if (ThrustTable != 0L) { // Thrust table given -> Solid fuel used
if ((in.ThrottlePos[EngineNumber] == 1 || BurnTime > 0.0 ) && !Starved) {
VacThrust = ThrustTable->GetValue(TotalPropellantExpended)
* (ThrustVariation + 1)
* (TotalIspVariation + 1);
if (BurnTime <= BuildupTime && BuildupTime > 0.0) {
VacThrust *= sin((BurnTime/BuildupTime)*M_PI/2.0);
// VacThrust *= (1-cos((BurnTime/BuildupTime)*M_PI))/2.0; // 1 - cos approach
}
BurnTime += in.TotalDeltaT; // Increment burn time
} else {
VacThrust = 0.0;
}
} else { // liquid fueled rocket assumed
if (in.ThrottlePos[EngineNumber] < MinThrottle || Starved) { // Combustion not supported
PctPower = 0.0; // desired thrust
Flameout = true;
VacThrust = 0.0;
} else { // Calculate thrust
// PctPower = Throttle / MaxThrottle; // Min and MaxThrottle range from 0.0 to 1.0, normally.
PctPower = in.ThrottlePos[EngineNumber];
Flameout = false;
VacThrust = Isp * PropellantFlowRate;
}
} // End thrust calculations
LoadThrusterInputs();
It += Thruster->Calculate(VacThrust) * in.TotalDeltaT;
ItVac += VacThrust * in.TotalDeltaT;
RunPostFunctions();
}
//%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
//
// The FuelFlowRate can be affected by the TotalIspVariation value (settable
// in a config file or via properties). The TotalIspVariation parameter affects
// thrust, but the thrust determines fuel flow rate, so it must be adjusted
// for Total Isp Variation.
double FGRocket::CalcFuelNeed(void)
{
if (ThrustTable != 0L) { // Thrust table given - infers solid fuel
FuelFlowRate = VacThrust/Isp; // This calculates wdot (weight flow rate in lbs/sec)
FuelFlowRate /= (1 + TotalIspVariation);
} else {
SLFuelFlowMax = PropFlowMax / (1 + MxR);
FuelFlowRate = SLFuelFlowMax * PctPower;
}
FuelExpended = FuelFlowRate * in.TotalDeltaT; // For this time step ...
return FuelExpended;
}
//%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
double FGRocket::CalcOxidizerNeed(void)
{
SLOxiFlowMax = PropFlowMax * MxR / (1 + MxR);
OxidizerFlowRate = SLOxiFlowMax * PctPower;
OxidizerExpended = OxidizerFlowRate * in.TotalDeltaT;
return OxidizerExpended;
}
//%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
string FGRocket::GetEngineLabels(const string& delimiter)
{
std::ostringstream buf;
buf << Name << " Total Impulse (engine " << EngineNumber << " in lbf)" << delimiter
<< Name << " Total Vacuum Impulse (engine " << EngineNumber << " in lbf)" << delimiter
<< Thruster->GetThrusterLabels(EngineNumber, delimiter);
return buf.str();
}
//%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
string FGRocket::GetEngineValues(const string& delimiter)
{
std::ostringstream buf;
buf << It << delimiter
<< ItVac << delimiter
<< Thruster->GetThrusterValues(EngineNumber, delimiter);
return buf.str();
}
//%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
// This function should tie properties to rocket engine specific properties
// that are not bound in the base class (FGEngine) code.
//
void FGRocket::bindmodel()
{
string property_name, base_property_name;
base_property_name = CreateIndexedPropertyName("propulsion/engine", EngineNumber);
property_name = base_property_name + "/total-impulse";
PropertyManager->Tie( property_name.c_str(), this, &FGRocket::GetTotalImpulse);
property_name = base_property_name + "/vacuum-thrust_lbs";
PropertyManager->Tie( property_name.c_str(), this, &FGRocket::GetVacThrust);
if (ThrustTable) { // Solid rocket motor
property_name = base_property_name + "/thrust-variation_pct";
PropertyManager->Tie( property_name.c_str(), this, &FGRocket::GetThrustVariation,
&FGRocket::SetThrustVariation);
property_name = base_property_name + "/total-isp-variation_pct";
PropertyManager->Tie( property_name.c_str(), this, &FGRocket::GetTotalIspVariation,
&FGRocket::SetTotalIspVariation);
} else { // Liquid rocket motor
property_name = base_property_name + "/oxi-flow-rate-pps";
PropertyManager->Tie( property_name.c_str(), this, &FGRocket::GetOxiFlowRate);
property_name = base_property_name + "/mixture-ratio";
PropertyManager->Tie( property_name.c_str(), this, &FGRocket::GetMixtureRatio,
&FGRocket::SetMixtureRatio);
property_name = base_property_name + "/isp";
PropertyManager->Tie( property_name.c_str(), this, &FGRocket::GetIsp,
&FGRocket::SetIsp);
}
}
//%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
// The bitmasked value choices are as follows:
// unset: In this case (the default) JSBSim would only print
// out the normally expected messages, essentially echoing
// the config files as they are read. If the environment
// variable is not set, debug_lvl is set to 1 internally
// 0: This requests JSBSim not to output any messages
// whatsoever.
// 1: This value explicity requests the normal JSBSim
// startup messages
// 2: This value asks for a message to be printed out when
// a class is instantiated
// 4: When this value is set, a message is displayed when a
// FGModel object executes its Run() method
// 8: When this value is set, various runtime state variables
// are printed out periodically
// 16: When set various parameters are sanity checked and
// a message is printed out when they go out of bounds
void FGRocket::Debug(int from)
{
if (debug_lvl <= 0) return;
if (debug_lvl & 1) { // Standard console startup message output
if (from == 0) { // Constructor
cout << " Engine Name: " << Name << endl;
cout << " Vacuum Isp = " << Isp << endl;
cout << " Maximum Throttle = " << MaxThrottle << endl;
cout << " Minimum Throttle = " << MinThrottle << endl;
cout << " Fuel Flow (max) = " << SLFuelFlowMax << endl;
cout << " Oxidizer Flow (max) = " << SLOxiFlowMax << endl;
if (SLFuelFlowMax > 0)
cout << " Mixture ratio = " << SLOxiFlowMax/SLFuelFlowMax << endl;
}
}
if (debug_lvl & 2 ) { // Instantiation/Destruction notification
if (from == 0) cout << "Instantiated: FGRocket" << endl;
if (from == 1) cout << "Destroyed: FGRocket" << endl;
}
if (debug_lvl & 4 ) { // Run() method entry print for FGModel-derived objects
}
if (debug_lvl & 8 ) { // Runtime state variables
}
if (debug_lvl & 16) { // Sanity checking
}
if (debug_lvl & 64) {
if (from == 0) { // Constructor
cout << IdSrc << endl;
cout << IdHdr << endl;
}
}
}
}
<|endoftext|> |
<commit_before>#include "scanner/api/kernel.h"
#include "scanner/api/op.h"
#include "scanner/util/memory.h"
namespace scanner {
class DiscardKernel : public BatchedKernel {
public:
DiscardKernel(const KernelConfig& config)
: BatchedKernel(config),
device_(config.devices[0]),
work_item_size_(config.work_item_size) {}
void execute(const BatchedColumns& input_columns,
BatchedColumns& output_columns) override {
i32 input_count = (i32)num_rows(input_columns[0]);
u8* output_block = new_block_buffer(device_, 1, input_count);
for (i32 i = 0; i < input_count; ++i) {
insert_element(output_columns[0], output_block, 1);
}
}
private:
DeviceHandle device_;
i32 work_item_size_;
};
REGISTER_OP(Discard).input("ignore").output("dummy");
REGISTER_OP(DiscardFrame).frame_input("ignore").output("dummy");
REGISTER_KERNEL(Discard, DiscardKernel).device(DeviceType::CPU).num_devices(1);
REGISTER_KERNEL(Discard, DiscardKernel).device(DeviceType::GPU).num_devices(1);
REGISTER_KERNEL(DiscardFrame, DiscardKernel)
.device(DeviceType::CPU)
.num_devices(1);
REGISTER_KERNEL(DiscardFrame, DiscardKernel)
.device(DeviceType::GPU)
.num_devices(1);
}
<commit_msg>Support batching on discard kernel<commit_after>#include "scanner/api/kernel.h"
#include "scanner/api/op.h"
#include "scanner/util/memory.h"
namespace scanner {
class DiscardKernel : public BatchedKernel {
public:
DiscardKernel(const KernelConfig& config)
: BatchedKernel(config),
device_(config.devices[0]),
work_item_size_(config.work_item_size) {}
void execute(const BatchedColumns& input_columns,
BatchedColumns& output_columns) override {
i32 input_count = (i32)num_rows(input_columns[0]);
u8* output_block = new_block_buffer(device_, 1, input_count);
for (i32 i = 0; i < input_count; ++i) {
insert_element(output_columns[0], output_block, 1);
}
}
private:
DeviceHandle device_;
i32 work_item_size_;
};
REGISTER_OP(Discard).input("ignore").output("dummy");
REGISTER_OP(DiscardFrame).frame_input("ignore").output("dummy");
REGISTER_KERNEL(Discard, DiscardKernel).device(DeviceType::CPU).num_devices(1);
REGISTER_KERNEL(Discard, DiscardKernel).device(DeviceType::GPU).num_devices(1);
REGISTER_KERNEL(DiscardFrame, DiscardKernel)
.device(DeviceType::CPU)
.batch()
.num_devices(1);
REGISTER_KERNEL(DiscardFrame, DiscardKernel)
.device(DeviceType::GPU)
.batch()
.num_devices(1);
}
<|endoftext|> |
<commit_before>/*
Copyright (C) 2014 Alexandr Akulich <akulichalexander@gmail.com>
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.
*/
#ifndef CTELEGRAMCONNECTION_HPP
#define CTELEGRAMCONNECTION_HPP
#include <QObject>
#include <QByteArray>
#include <QVector>
#include <QMap>
#include <QStringList>
#include "TLTypes.hpp"
#include "crypto-rsa.hpp"
#include "crypto-aes.hpp"
class CAppInformation;
class CTelegramStream;
class CTelegramTransport;
class CTelegramConnection : public QObject
{
Q_OBJECT
public:
enum AuthState {
AuthStateNone,
AuthStatePqRequested,
AuthStateDhRequested,
AuthStateDhGenerationResultRequested,
AuthStateSuccess,
AuthStateSignedIn
};
enum DeltaTimeHeuristicState {
DeltaTimeIsOk,
DeltaTimeCorrectionForward,
DeltaTimeCorrectionBackward,
};
explicit CTelegramConnection(const CAppInformation *appInfo, QObject *parent = 0);
void setDcInfo(const TLDcOption &newDcInfo);
inline TLDcOption dcInfo() const { return m_dcInfo; }
void connectToDc();
bool isConnected() const;
static quint64 formatTimeStamp(qint64 timeInMs);
static inline quint64 formatClientTimeStamp(qint64 timeInMs) { return formatTimeStamp(timeInMs) & ~quint64(3); }
static quint64 timeStampToMSecsSinceEpoch(quint64 ts);
void initAuth();
void getConfiguration();
void requestPhoneStatus(const QString &phoneNumber);
void requestPhoneCode(const QString &phoneNumber);
void signIn(const QString &phoneNumber, const QString &authCode);
void signUp(const QString &phoneNumber, const QString &authCode, const QString &firstName, const QString &lastName);
void requestContacts();
void getFile(const TLInputFileLocation &location, quint32 fileId);
void addContacts(const QStringList &phoneNumbers, bool replace);
void sendMessage(const TLInputPeer &peer, const QString &message);
AuthState authState() { return m_authState; }
void requestPqAuthorization();
bool answerPqAuthorization(const QByteArray &payload);
void requestDhParameters();
bool answerDh(const QByteArray &payload);
void requestDhGenerationResult();
bool processServersDHAnswer(const QByteArray &payload);
inline TLNumber128 clientNonce() const { return m_clientNonce; }
inline TLNumber128 serverNonce() const { return m_serverNonce; }
inline quint64 pq() const { return m_pq; }
inline quint64 p() const { return m_p; }
inline quint64 q() const { return m_q; }
inline quint64 serverPublicFingersprint() const { return m_serverPublicFingersprint; }
inline QByteArray authKey() const { return m_authKey; }
void setAuthKey(const QByteArray &newAuthKey);
inline quint64 authId() const { return m_authId; }
inline quint64 serverSalt() const { return m_serverSalt; }
void setServerSalt(const quint64 salt) { m_serverSalt = salt; }
inline quint64 sessionId() const { return m_sessionId; }
inline QVector<TLDcOption> dcConfiguration() const { return m_dcConfiguration; }
inline qint32 deltaTime() const { return m_deltaTime; }
void setDeltaTime(const qint32 delta) { m_deltaTime = delta; }
void processRedirectedPackage(const QByteArray &data);
signals:
void wantedActiveDcChanged(int dc);
void newRedirectedPackage(const QByteArray &data, int dc);
void selfPhoneReceived(const QString &phoneNumber);
void authStateChanged(int dc, int state);
void actualDcIdReceived(int dc, int newDcId);
void dcConfigurationReceived(int dc);
void phoneStatusReceived(const QString &phone, bool registered, bool invited);
void phoneCodeRequired();
void phoneCodeIsInvalid();
void usersReceived(const QVector<TLUser> &users);
void usersAdded(const QVector<TLUser> &users);
void fileReceived(const TLUploadFile &file, quint32 fileId);
void updatesReceived(const TLUpdates &update);
private slots:
void whenConnected();
void whenReadyRead();
protected:
void processRpcQuery(const QByteArray &data);
void processSessionCreated(CTelegramStream &stream);
void processContainer(CTelegramStream &stream);
void processRpcResult(CTelegramStream &stream);
void processGzipPacked(CTelegramStream &stream);
bool processRpcError(CTelegramStream &stream, quint64 id, TLValue request);
void processMessageAck(CTelegramStream &stream);
void processIgnoredMessageNotification(CTelegramStream &stream);
TLValue processHelpGetConfig(CTelegramStream &stream, quint64 id);
TLValue processContactsGetContacts(CTelegramStream &stream, quint64 id);
TLValue processContactsImportContacts(CTelegramStream &stream, quint64 id);
TLValue processAuthCheckPhone(CTelegramStream &stream, quint64 id);
TLValue processAuthSendCode(CTelegramStream &stream, quint64 id);
TLValue processAuthSign(CTelegramStream &stream, quint64 id);
TLValue processUploadGetFile(CTelegramStream &stream, quint64 id);
TLValue processMessagesSendMessage(CTelegramStream &stream, quint64 id);
bool processErrorSeeOther(const QString errorMessage, quint64 id);
TLValue processUpdate(CTelegramStream &stream);
SAesKey generateTmpAesKey() const;
SAesKey generateClientToServerAesKey(const QByteArray &messageKey) const;
SAesKey generateServerToClientAesKey(const QByteArray &messageKey) const;
SAesKey generateAesKey(const QByteArray &messageKey, int xValue) const;
void insertInitConnection(QByteArray *data) const;
quint64 sendPlainPackage(const QByteArray &buffer);
quint64 sendEncryptedPackage(const QByteArray &buffer);
void setTransport(CTelegramTransport *newTransport);
void setAuthState(AuthState newState);
quint64 newMessageId();
const CAppInformation *m_appInfo;
QMap<quint64, QByteArray> m_submittedPackages; // <message id, package data>
QMap<quint64, quint32> m_requestedFilesIds; // <message id, file id>
CTelegramTransport *m_transport;
AuthState m_authState;
QByteArray m_authKey;
quint64 m_authId;
quint64 m_authKeyAuxHash;
quint64 m_serverSalt;
quint64 m_receivedServerSalt;
quint64 m_sessionId;
quint64 m_lastMessageId;
quint32 m_sequenceNumber;
quint32 m_contentRelatedMessages;
qint32 m_deltaTime;
DeltaTimeHeuristicState m_deltaTimeHeuristicState;
TLNumber128 m_clientNonce;
TLNumber128 m_serverNonce;
TLNumber256 m_newNonce;
quint64 m_pq;
quint32 m_p;
quint32 m_q;
quint64 m_serverPublicFingersprint;
SRsaKey m_rsaKey;
SAesKey m_tmpAesKey;
quint32 m_g;
QByteArray m_dhPrime;
QByteArray m_gA;
QByteArray m_b;
quint64 m_authRetryId;
TLDcOption m_dcInfo;
QVector<TLDcOption> m_dcConfiguration;
QString m_authCodeHash;
};
inline SAesKey CTelegramConnection::generateClientToServerAesKey(const QByteArray &messageKey) const
{
return generateAesKey(messageKey, 0);
}
inline SAesKey CTelegramConnection::generateServerToClientAesKey(const QByteArray &messageKey) const
{
return generateAesKey(messageKey, 8);
}
#endif // CTELEGRAMCONNECTION_HPP
<commit_msg>Fixed compilation.<commit_after>/*
Copyright (C) 2014 Alexandr Akulich <akulichalexander@gmail.com>
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.
*/
#ifndef CTELEGRAMCONNECTION_HPP
#define CTELEGRAMCONNECTION_HPP
#include <QObject>
#include <QByteArray>
#include <QVector>
#include <QMap>
#include <QStringList>
#include "TLTypes.hpp"
#include "crypto-rsa.hpp"
#include "crypto-aes.hpp"
class CAppInformation;
class CTelegramStream;
class CTelegramTransport;
class CTelegramConnection : public QObject
{
Q_OBJECT
public:
enum AuthState {
AuthStateNone,
AuthStatePqRequested,
AuthStateDhRequested,
AuthStateDhGenerationResultRequested,
AuthStateSuccess,
AuthStateSignedIn
};
enum DeltaTimeHeuristicState {
DeltaTimeIsOk,
DeltaTimeCorrectionForward,
DeltaTimeCorrectionBackward,
};
explicit CTelegramConnection(const CAppInformation *appInfo, QObject *parent = 0);
void setDcInfo(const TLDcOption &newDcInfo);
inline TLDcOption dcInfo() const { return m_dcInfo; }
void connectToDc();
bool isConnected() const;
static quint64 formatTimeStamp(qint64 timeInMs);
static inline quint64 formatClientTimeStamp(qint64 timeInMs) { return formatTimeStamp(timeInMs) & ~quint64(3); }
static quint64 timeStampToMSecsSinceEpoch(quint64 ts);
void initAuth();
void getConfiguration();
void requestPhoneStatus(const QString &phoneNumber);
void requestPhoneCode(const QString &phoneNumber);
void signIn(const QString &phoneNumber, const QString &authCode);
void signUp(const QString &phoneNumber, const QString &authCode, const QString &firstName, const QString &lastName);
void requestContacts();
void getFile(const TLInputFileLocation &location, quint32 fileId);
void addContacts(const QStringList &phoneNumbers, bool replace);
void sendMessage(const TLInputPeer &peer, const QString &message);
AuthState authState() { return m_authState; }
void requestPqAuthorization();
bool answerPqAuthorization(const QByteArray &payload);
void requestDhParameters();
bool answerDh(const QByteArray &payload);
void requestDhGenerationResult();
bool processServersDHAnswer(const QByteArray &payload);
inline TLNumber128 clientNonce() const { return m_clientNonce; }
inline TLNumber128 serverNonce() const { return m_serverNonce; }
inline quint64 pq() const { return m_pq; }
inline quint64 p() const { return m_p; }
inline quint64 q() const { return m_q; }
inline quint64 serverPublicFingersprint() const { return m_serverPublicFingersprint; }
inline QByteArray authKey() const { return m_authKey; }
void setAuthKey(const QByteArray &newAuthKey);
inline quint64 authId() const { return m_authId; }
inline quint64 serverSalt() const { return m_serverSalt; }
void setServerSalt(const quint64 salt) { m_serverSalt = salt; }
inline quint64 sessionId() const { return m_sessionId; }
inline QVector<TLDcOption> dcConfiguration() const { return m_dcConfiguration; }
inline qint32 deltaTime() const { return m_deltaTime; }
void setDeltaTime(const qint32 delta) { m_deltaTime = delta; }
void processRedirectedPackage(const QByteArray &data);
signals:
void wantedActiveDcChanged(int dc);
void newRedirectedPackage(const QByteArray &data, int dc);
void selfPhoneReceived(const QString &phoneNumber);
void authStateChanged(int dc, int state);
void actualDcIdReceived(int dc, int newDcId);
void dcConfigurationReceived(int dc);
void phoneStatusReceived(const QString &phone, bool registered, bool invited);
void phoneCodeRequired();
void phoneCodeIsInvalid();
void usersReceived(const QVector<TLUser> &users);
void usersAdded(const QVector<TLUser> &users);
void fileReceived(const TLUploadFile &file, quint32 fileId);
void updatesReceived(const TLUpdates &update);
private slots:
void whenConnected();
void whenReadyRead();
protected:
void processRpcQuery(const QByteArray &data);
void processSessionCreated(CTelegramStream &stream);
void processContainer(CTelegramStream &stream);
void processRpcResult(CTelegramStream &stream);
void processGzipPacked(CTelegramStream &stream);
bool processRpcError(CTelegramStream &stream, quint64 id, TLValue request);
void processMessageAck(CTelegramStream &stream);
void processIgnoredMessageNotification(CTelegramStream &stream);
TLValue processHelpGetConfig(CTelegramStream &stream, quint64 id);
TLValue processContactsGetContacts(CTelegramStream &stream, quint64 id);
TLValue processContactsImportContacts(CTelegramStream &stream, quint64 id);
TLValue processAuthCheckPhone(CTelegramStream &stream, quint64 id);
TLValue processAuthSendCode(CTelegramStream &stream, quint64 id);
TLValue processAuthSign(CTelegramStream &stream, quint64 id);
TLValue processUploadGetFile(CTelegramStream &stream, quint64 id);
TLValue processMessagesSendMessage(CTelegramStream &stream, quint64 id);
bool processErrorSeeOther(const QString errorMessage, quint64 id);
TLValue processUpdate(CTelegramStream &stream, bool *ok);
SAesKey generateTmpAesKey() const;
SAesKey generateClientToServerAesKey(const QByteArray &messageKey) const;
SAesKey generateServerToClientAesKey(const QByteArray &messageKey) const;
SAesKey generateAesKey(const QByteArray &messageKey, int xValue) const;
void insertInitConnection(QByteArray *data) const;
quint64 sendPlainPackage(const QByteArray &buffer);
quint64 sendEncryptedPackage(const QByteArray &buffer);
void setTransport(CTelegramTransport *newTransport);
void setAuthState(AuthState newState);
quint64 newMessageId();
const CAppInformation *m_appInfo;
QMap<quint64, QByteArray> m_submittedPackages; // <message id, package data>
QMap<quint64, quint32> m_requestedFilesIds; // <message id, file id>
CTelegramTransport *m_transport;
AuthState m_authState;
QByteArray m_authKey;
quint64 m_authId;
quint64 m_authKeyAuxHash;
quint64 m_serverSalt;
quint64 m_receivedServerSalt;
quint64 m_sessionId;
quint64 m_lastMessageId;
quint32 m_sequenceNumber;
quint32 m_contentRelatedMessages;
qint32 m_deltaTime;
DeltaTimeHeuristicState m_deltaTimeHeuristicState;
TLNumber128 m_clientNonce;
TLNumber128 m_serverNonce;
TLNumber256 m_newNonce;
quint64 m_pq;
quint32 m_p;
quint32 m_q;
quint64 m_serverPublicFingersprint;
SRsaKey m_rsaKey;
SAesKey m_tmpAesKey;
quint32 m_g;
QByteArray m_dhPrime;
QByteArray m_gA;
QByteArray m_b;
quint64 m_authRetryId;
TLDcOption m_dcInfo;
QVector<TLDcOption> m_dcConfiguration;
QString m_authCodeHash;
};
inline SAesKey CTelegramConnection::generateClientToServerAesKey(const QByteArray &messageKey) const
{
return generateAesKey(messageKey, 0);
}
inline SAesKey CTelegramConnection::generateServerToClientAesKey(const QByteArray &messageKey) const
{
return generateAesKey(messageKey, 8);
}
#endif // CTELEGRAMCONNECTION_HPP
<|endoftext|> |
<commit_before>/*************************************************************************
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: jvmargs.cxx,v $
*
* $Revision: 1.16 $
*
* last change: $Author: rt $ $Date: 2005-09-08 07:59:29 $
*
* 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
*
************************************************************************/
#include "jvmargs.hxx"
#include <rtl/ustring.hxx>
#define OUSTR(x) rtl::OUString(RTL_CONSTASCII_USTRINGPARAM( x ))
using namespace rtl;
namespace stoc_javavm {
JVM::JVM() throw()//: _enabled(sal_False)
{
}
void JVM::pushProp(const OUString & property)
{
sal_Int32 index = property.indexOf((sal_Unicode)'=');
if(index > 0)
{
OUString left = property.copy(0, index).trim();
OUString right(property.copy(index + 1).trim());
_props.push_back(property);
}
else
{ // no '=', could be -X
_props.push_back(property);
}
}
const ::std::vector< ::rtl::OUString > & JVM::getProperties() const
{
return _props;
}
}
<commit_msg>INTEGRATION: CWS pchfix02 (1.16.36); FILE MERGED 2006/09/01 17:41:13 kaib 1.16.36.1: #i68856# Added header markers and pch files<commit_after>/*************************************************************************
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: jvmargs.cxx,v $
*
* $Revision: 1.17 $
*
* last change: $Author: obo $ $Date: 2006-09-16 17:31: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
*
************************************************************************/
// MARKER(update_precomp.py): autogen include statement, do not remove
#include "precompiled_stoc.hxx"
#include "jvmargs.hxx"
#include <rtl/ustring.hxx>
#define OUSTR(x) rtl::OUString(RTL_CONSTASCII_USTRINGPARAM( x ))
using namespace rtl;
namespace stoc_javavm {
JVM::JVM() throw()//: _enabled(sal_False)
{
}
void JVM::pushProp(const OUString & property)
{
sal_Int32 index = property.indexOf((sal_Unicode)'=');
if(index > 0)
{
OUString left = property.copy(0, index).trim();
OUString right(property.copy(index + 1).trim());
_props.push_back(property);
}
else
{ // no '=', could be -X
_props.push_back(property);
}
}
const ::std::vector< ::rtl::OUString > & JVM::getProperties() const
{
return _props;
}
}
<|endoftext|> |
<commit_before>/***********************************************************************************************************************
**
** Copyright (c) 2011, 2014 ETH Zurich
** All rights reserved.
**
** Redistribution and use in source and binary forms, with or without modification, are permitted provided that the
** following conditions are met:
**
** * Redistributions of source code must retain the above copyright notice, this list of conditions and the
** following disclaimer.
** * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the
** following disclaimer in the documentation and/or other materials provided with the distribution.
** * Neither the name of the ETH Zurich nor the names of its contributors may be used to endorse or promote products
** derived from this software without specific prior written permission.
**
**
** THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES,
** INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
** DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
** SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
** SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
** WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
** OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
**
**********************************************************************************************************************/
#include "StringComponents.h"
#include "ModelBase/src/nodes/Node.h"
#include "../expression_editor/CompoundObjectDescriptor.h"
#include "OOModel/src/allOOModelNodes.h"
namespace OOInteraction {
QMap<int, QStringList(*)(Model::Node* node)>& StringComponents::componentFunctions()
{
static QMap<int, QStringList(*)(Model::Node* node)> funcs;
return funcs;
}
StringComponents::StringComponents(Model::Node* node) : node_{node}
{}
StringComponents::~StringComponents()
{}
QStringList StringComponents::components()
{
//if (!node_) return QStringList{};
Q_ASSERT(node_);
auto iter = componentFunctions().find(node_->typeId());
if (iter != componentFunctions().end()) return iter.value()(node_);
if (auto listNode = DCast<Model::List>(node_)) return c( list(listNode) );
throw OOInteractionException{"No string component function registered for node of type " + node_->typeName()};
}
QString StringComponents::stringForNode(Model::Node* node)
{
QString res = componentsForNode(node).join("");
if (res.isNull()) res = "";
return res;
}
QStringList StringComponents::componentsForNode(Model::Node* node)
{
if (!node) return QStringList{};
else return StringComponents{node}.components();
}
StringComponents::Optional StringComponents::list(Model::List* listNode)
{
QStringList result;
if (!listNode) return result;
for (int i=0; i< listNode->size(); ++i)
result << stringForNode(listNode->at<Model::Node>(i));
return result;
}
StringComponents::Optional StringComponents::list(Model::List* listNode, const QString& prefix,
const QString& separator, const QString& postfix, bool nothingIfEmpty, bool collapse)
{
if (nothingIfEmpty && listNode->size() == 0)
return Optional{};
QStringList list;
list << prefix;
for (int i=0; i< listNode->size(); ++i)
{
if (i>0) list << separator;
list << stringForNode(listNode->at<Model::Node>(i));
}
list << postfix;
if (collapse) return list.join("");
else return list;
}
using namespace OOModel;
void StringComponents::initConversions()
{
// Types
add<ArrayTypeExpression>([](ArrayTypeExpression* e){ return c( Optional{e->typeExpression(), AUTO}, "[]"); });
add<ReferenceTypeExpression>([](ReferenceTypeExpression* e){ return c( Optional{e->typeExpression(), AUTO}, "&"); });
add<PointerTypeExpression>([](PointerTypeExpression* e){ return c( Optional{e->typeExpression(), AUTO}, "*"); });
add<ClassTypeExpression>([](ClassTypeExpression* e){ return c( Optional{e->typeExpression(), AUTO} ); });
add<PrimitiveTypeExpression>([](PrimitiveTypeExpression* e){ return c(
choose(e->typeValue(),
PrimitiveTypeExpression::PrimitiveTypes::INT, "int",
PrimitiveTypeExpression::PrimitiveTypes::LONG, "long",
PrimitiveTypeExpression::PrimitiveTypes::UNSIGNED_INT, "uint",
PrimitiveTypeExpression::PrimitiveTypes::UNSIGNED_LONG, "ulong",
PrimitiveTypeExpression::PrimitiveTypes::FLOAT, "float",
PrimitiveTypeExpression::PrimitiveTypes::DOUBLE, "double",
PrimitiveTypeExpression::PrimitiveTypes::BOOLEAN, "bool",
PrimitiveTypeExpression::PrimitiveTypes::CHAR, "char",
PrimitiveTypeExpression::PrimitiveTypes::VOID, "void")
); });
add<TypeQualifierExpression>([](TypeQualifierExpression* e ){ return c(
choose(e->qualifier(),
TypeQualifierExpression::Qualifier::CONST, "const",
TypeQualifierExpression::Qualifier::VOLATILE, "volatile"),
" ", e->typeExpression() ); });
add<AutoTypeExpression>([](AutoTypeExpression* ){ return c( "auto" ); });
add<FunctionTypeExpression>([](FunctionTypeExpression* e){ return c( "[]",
list(e->arguments(), "(", ",", ")", false, true),
Optional{"->", e->results()->size() > 0},
list(e->results(), "(", ",", ")", true, true)
);});
// Operators
add<AssignmentExpression>([](AssignmentExpression* e){ return c(
QString{}, e->left(), choose(e->op(),
AssignmentExpression::ASSIGN, "=",
AssignmentExpression::PLUS_ASSIGN, "+=",
AssignmentExpression::MINUS_ASSIGN, "-=",
AssignmentExpression::TIMES_ASSIGN, "*=",
AssignmentExpression::DIVIDE_ASSIGN, "/=",
AssignmentExpression::BIT_AND_ASSIGN, "&=",
AssignmentExpression::BIT_OR_ASSIGN, "|=",
AssignmentExpression::BIT_XOR_ASSIGN, "^=",
AssignmentExpression::REMAINDER_ASSIGN, "%=",
AssignmentExpression::LEFT_SHIFT_ASSIGN, "<<=",
AssignmentExpression::RIGHT_SHIFT_SIGNED_ASSIGN, ">>=",
AssignmentExpression::RIGHT_SHIFT_UNSIGNED_ASSIGN, ">>>="),
e->right(), QString{}
); });
add<BinaryOperation>([](BinaryOperation* e){ return c(
QString{}, e->left(), choose(e->op(),
BinaryOperation::TIMES, "*",
BinaryOperation::DIVIDE, "/",
BinaryOperation::REMAINDER, "%",
BinaryOperation::PLUS, "+",
BinaryOperation::MINUS, "-",
BinaryOperation::LEFT_SHIFT, "<<",
BinaryOperation::RIGHT_SHIFT_SIGNED, ">>",
BinaryOperation::RIGHT_SHIFT_UNSIGNED, ">>>",
BinaryOperation::LESS, "<",
BinaryOperation::GREATER, ">",
BinaryOperation::LESS_EQUALS, "<=",
BinaryOperation::GREATER_EQUALS, ">=",
BinaryOperation::EQUALS, "==",
BinaryOperation::NOT_EQUALS, "!=",
BinaryOperation::XOR, "^",
BinaryOperation::AND, "&",
BinaryOperation::OR, "|",
BinaryOperation::CONDITIONAL_AND, "&&",
BinaryOperation::CONDITIONAL_OR, "||",
BinaryOperation::ARRAY_INDEX, "["),
e->right(),
e->op() == OOModel::BinaryOperation::ARRAY_INDEX ? "]" : QString{}
); });
add<UnaryOperation>([](UnaryOperation* e){ return c(
choose(e->op(),
UnaryOperation::PREINCREMENT, "++",
UnaryOperation::PREDECREMENT, "--",
UnaryOperation::POSTINCREMENT, Optional{},
UnaryOperation::POSTDECREMENT, Optional{},
UnaryOperation::PLUS, "+",
UnaryOperation::MINUS, "-",
UnaryOperation::NOT, "!",
UnaryOperation::COMPLEMENT, "~",
UnaryOperation::PARENTHESIS, "(",
UnaryOperation::DEREFERENCE, "*",
UnaryOperation::ADDRESSOF, "&"),
e->operand(),
choose(e->op(),
UnaryOperation::PREINCREMENT, Optional{},
UnaryOperation::PREDECREMENT, Optional{},
UnaryOperation::POSTINCREMENT, "++",
UnaryOperation::POSTDECREMENT, "--",
UnaryOperation::PLUS, Optional{},
UnaryOperation::MINUS, Optional{},
UnaryOperation::NOT, Optional{},
UnaryOperation::COMPLEMENT, Optional{},
UnaryOperation::PARENTHESIS, ")",
UnaryOperation::DEREFERENCE, Optional{},
UnaryOperation::ADDRESSOF, Optional{})
); });
add<TypeTraitExpression>([](TypeTraitExpression* e){ return c(
choose( static_cast<int>(e->typeTraitKind()),
static_cast<int>(TypeTraitExpression::TypeTraitKind::SizeOf), "sizeof",
static_cast<int>(TypeTraitExpression::TypeTraitKind::AlignOf), "alignof",
static_cast<int>(TypeTraitExpression::TypeTraitKind::TypeId), "typeid"),
"(",
e->operand(),
")"
); });
// Literals
add<BooleanLiteral>([](BooleanLiteral* e){ return c( e->value() ? "true" : "false" ); });
add<IntegerLiteral>([](IntegerLiteral* e){ return c( e->value() ); });
add<FloatLiteral>([](FloatLiteral* e){ return c( e->value() ); });
add<NullLiteral>([](NullLiteral*){ return c( "null" ); });
add<StringLiteral>([](StringLiteral* e){ return c( "\"", e->value(), "\"" ); });
add<CharacterLiteral>([](CharacterLiteral* e){ return c( "'", e->value(), "'" ); });
// Misc
add<CastExpression>([](CastExpression* e){ return c( "(", e->castType(), ")", e->expr() ); });
add<InstanceOfExpression>(
[](InstanceOfExpression* e){ return c( e->expr(), " ", "instanceof", " ", e->typeExpression() ); });
add<CommaExpression>([](CommaExpression* e){ return c( QString{}, e->left(), ",", e->right(), QString{} ); });
add<ConditionalExpression>([](ConditionalExpression* e){ return c(
QString{}, e->condition(), "?", e->trueExpression(), ":", e->falseExpression(), QString{} ); });
add<SuperExpression>([](SuperExpression* ){ return c( "super" ); });
add<ThisExpression>([](ThisExpression* ){ return c( "this" ); });
add<GlobalScopeExpression>([](GlobalScopeExpression* ){ return c( "::" ); });
add<ThrowExpression>([](ThrowExpression* e ){ return c( "throw", " ", e->expr() ); });
add<TypeNameOperator>([](TypeNameOperator* e ){ return c( "typename", " ", e->typeExpression() ); });
add<DeleteExpression>([](DeleteExpression* e ){ return c( e->isArray() ? "delete[]":"delete", " ", e->expr() ); });
add<VariableDeclarationExpression>([](VariableDeclarationExpression* e ){ return c( e->decl()->typeExpression(), " ",
e->decl()->name(), Optional{"=", e->decl()->initialValue()}, Optional{e->decl()->initialValue()}); });
add<LambdaExpression>([](LambdaExpression* e ){ return c( CompoundObjectDescriptor::storeExpression(e)); });
add<ArrayInitializer>([](ArrayInitializer* e){ return c( list(e->values(), "{", ",", "}", false, false) ); });
add<MethodCallExpression>([](MethodCallExpression* e){ return c(
e->callee(), list(e->arguments(), "(", ",", ")", false, true) ); });
add<MetaCallExpression>([](MetaCallExpression* e){ return c( "#",
e->callee(), list(e->arguments(), "(", ",", ")", false, true) ); });
add<NewExpression>([](NewExpression* e){ return c( "new", " ",
Optional{ (e->dimensions()->size() > 0 || !e->initializer()) ? e->newType() : nullptr, AUTO},
list(e->dimensions(), "[", ",", "]", true, true), Optional{e->initializer(), AUTO} ); });
add<ReferenceExpression>([](ReferenceExpression* e){ return c(
Optional{e->prefix(), AUTO}, Optional{
(e->memberKind() == ReferenceExpression::MemberKind::Dot ? "." :
e->memberKind() == ReferenceExpression::MemberKind::Pointer ? "->" :
e->memberKind() == ReferenceExpression::MemberKind::Static ? "::" : "::template"),
e->prefix()}, e->name(),
list(e->typeArguments(), "<", ",", ">", true, true) ); });
add<OOReference>([](OOReference* e){ return c( e->name() ); });
// Flexible input expressions
add<EmptyExpression>([](EmptyExpression*){ return c( "" ); });
add<ErrorExpression>([](ErrorExpression* e){ return c(
Optional{e->prefix(), !e->prefix().isEmpty()}, e->arg(), Optional{e->postfix(), !e->postfix().isEmpty()} ); });
add<UnfinishedOperator>([](UnfinishedOperator* e)
{
QStringList result;
for (int i=0; i< e->operands()->size(); ++i)
{
QString delim = e->delimiters()->at(i)->get();
result << delim << stringForNode(e->operands()->at(i));
}
if (e->delimiters()->size() > e->operands()->size())
{
QString delim = e->delimiters()->last()->get();
result << delim;
}
// Insert spaces on the insdie of the result to make sure they don't stick to each other
int i = 0;
int lastNonEmpty = -1;
while (i<result.size())
{
if (!result[i].isEmpty())
{
if (lastNonEmpty >= 0)
{
result.insert(lastNonEmpty + 1, " ");
++i;
}
lastNonEmpty = i;
}
++i;
}
return result;
});
}
}
<commit_msg>Add a clarification comment<commit_after>/***********************************************************************************************************************
**
** Copyright (c) 2011, 2014 ETH Zurich
** All rights reserved.
**
** Redistribution and use in source and binary forms, with or without modification, are permitted provided that the
** following conditions are met:
**
** * Redistributions of source code must retain the above copyright notice, this list of conditions and the
** following disclaimer.
** * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the
** following disclaimer in the documentation and/or other materials provided with the distribution.
** * Neither the name of the ETH Zurich nor the names of its contributors may be used to endorse or promote products
** derived from this software without specific prior written permission.
**
**
** THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES,
** INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
** DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
** SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
** SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
** WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
** OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
**
**********************************************************************************************************************/
#include "StringComponents.h"
#include "ModelBase/src/nodes/Node.h"
#include "../expression_editor/CompoundObjectDescriptor.h"
#include "OOModel/src/allOOModelNodes.h"
namespace OOInteraction {
QMap<int, QStringList(*)(Model::Node* node)>& StringComponents::componentFunctions()
{
static QMap<int, QStringList(*)(Model::Node* node)> funcs;
return funcs;
}
StringComponents::StringComponents(Model::Node* node) : node_{node}
{}
StringComponents::~StringComponents()
{}
QStringList StringComponents::components()
{
//if (!node_) return QStringList{};
Q_ASSERT(node_);
auto iter = componentFunctions().find(node_->typeId());
if (iter != componentFunctions().end()) return iter.value()(node_);
if (auto listNode = DCast<Model::List>(node_)) return c( list(listNode) );
throw OOInteractionException{"No string component function registered for node of type " + node_->typeName()};
}
QString StringComponents::stringForNode(Model::Node* node)
{
QString res = componentsForNode(node).join("");
if (res.isNull()) res = "";
return res;
}
QStringList StringComponents::componentsForNode(Model::Node* node)
{
if (!node) return QStringList{};
else return StringComponents{node}.components();
}
StringComponents::Optional StringComponents::list(Model::List* listNode)
{
QStringList result;
if (!listNode) return result;
for (int i=0; i< listNode->size(); ++i)
result << stringForNode(listNode->at<Model::Node>(i));
return result;
}
StringComponents::Optional StringComponents::list(Model::List* listNode, const QString& prefix,
const QString& separator, const QString& postfix, bool nothingIfEmpty, bool collapse)
{
if (nothingIfEmpty && listNode->size() == 0)
return Optional{};
QStringList list;
list << prefix;
for (int i=0; i< listNode->size(); ++i)
{
if (i>0) list << separator;
list << stringForNode(listNode->at<Model::Node>(i));
}
list << postfix;
if (collapse) return list.join("");
else return list;
}
using namespace OOModel;
void StringComponents::initConversions()
{
// Types
add<ArrayTypeExpression>([](ArrayTypeExpression* e){ return c( Optional{e->typeExpression(), AUTO}, "[]"); });
add<ReferenceTypeExpression>([](ReferenceTypeExpression* e){ return c( Optional{e->typeExpression(), AUTO}, "&"); });
add<PointerTypeExpression>([](PointerTypeExpression* e){ return c( Optional{e->typeExpression(), AUTO}, "*"); });
add<ClassTypeExpression>([](ClassTypeExpression* e){ return c( Optional{e->typeExpression(), AUTO} ); });
add<PrimitiveTypeExpression>([](PrimitiveTypeExpression* e){ return c(
choose(e->typeValue(),
PrimitiveTypeExpression::PrimitiveTypes::INT, "int",
PrimitiveTypeExpression::PrimitiveTypes::LONG, "long",
PrimitiveTypeExpression::PrimitiveTypes::UNSIGNED_INT, "uint",
PrimitiveTypeExpression::PrimitiveTypes::UNSIGNED_LONG, "ulong",
PrimitiveTypeExpression::PrimitiveTypes::FLOAT, "float",
PrimitiveTypeExpression::PrimitiveTypes::DOUBLE, "double",
PrimitiveTypeExpression::PrimitiveTypes::BOOLEAN, "bool",
PrimitiveTypeExpression::PrimitiveTypes::CHAR, "char",
PrimitiveTypeExpression::PrimitiveTypes::VOID, "void")
); });
add<TypeQualifierExpression>([](TypeQualifierExpression* e ){ return c(
choose(e->qualifier(),
TypeQualifierExpression::Qualifier::CONST, "const",
TypeQualifierExpression::Qualifier::VOLATILE, "volatile"),
" ", e->typeExpression() ); });
add<AutoTypeExpression>([](AutoTypeExpression* ){ return c( "auto" ); });
add<FunctionTypeExpression>([](FunctionTypeExpression* e){ return c( "[]",
list(e->arguments(), "(", ",", ")", false, true),
Optional{"->", e->results()->size() > 0},
list(e->results(), "(", ",", ")", true, true)
);});
// Operators
add<AssignmentExpression>([](AssignmentExpression* e){ return c(
QString{}, e->left(), choose(e->op(),
AssignmentExpression::ASSIGN, "=",
AssignmentExpression::PLUS_ASSIGN, "+=",
AssignmentExpression::MINUS_ASSIGN, "-=",
AssignmentExpression::TIMES_ASSIGN, "*=",
AssignmentExpression::DIVIDE_ASSIGN, "/=",
AssignmentExpression::BIT_AND_ASSIGN, "&=",
AssignmentExpression::BIT_OR_ASSIGN, "|=",
AssignmentExpression::BIT_XOR_ASSIGN, "^=",
AssignmentExpression::REMAINDER_ASSIGN, "%=",
AssignmentExpression::LEFT_SHIFT_ASSIGN, "<<=",
AssignmentExpression::RIGHT_SHIFT_SIGNED_ASSIGN, ">>=",
AssignmentExpression::RIGHT_SHIFT_UNSIGNED_ASSIGN, ">>>="),
e->right(), QString{}
); });
add<BinaryOperation>([](BinaryOperation* e){ return c(
QString{}, e->left(), choose(e->op(),
BinaryOperation::TIMES, "*",
BinaryOperation::DIVIDE, "/",
BinaryOperation::REMAINDER, "%",
BinaryOperation::PLUS, "+",
BinaryOperation::MINUS, "-",
BinaryOperation::LEFT_SHIFT, "<<",
BinaryOperation::RIGHT_SHIFT_SIGNED, ">>",
BinaryOperation::RIGHT_SHIFT_UNSIGNED, ">>>",
BinaryOperation::LESS, "<",
BinaryOperation::GREATER, ">",
BinaryOperation::LESS_EQUALS, "<=",
BinaryOperation::GREATER_EQUALS, ">=",
BinaryOperation::EQUALS, "==",
BinaryOperation::NOT_EQUALS, "!=",
BinaryOperation::XOR, "^",
BinaryOperation::AND, "&",
BinaryOperation::OR, "|",
BinaryOperation::CONDITIONAL_AND, "&&",
BinaryOperation::CONDITIONAL_OR, "||",
BinaryOperation::ARRAY_INDEX, "["),
e->right(),
e->op() == OOModel::BinaryOperation::ARRAY_INDEX ? "]" : QString{}
); });
add<UnaryOperation>([](UnaryOperation* e){ return c(
choose(e->op(),
UnaryOperation::PREINCREMENT, "++",
UnaryOperation::PREDECREMENT, "--",
UnaryOperation::POSTINCREMENT, Optional{},
UnaryOperation::POSTDECREMENT, Optional{},
UnaryOperation::PLUS, "+",
UnaryOperation::MINUS, "-",
UnaryOperation::NOT, "!",
UnaryOperation::COMPLEMENT, "~",
UnaryOperation::PARENTHESIS, "(",
UnaryOperation::DEREFERENCE, "*",
UnaryOperation::ADDRESSOF, "&"),
e->operand(),
choose(e->op(),
UnaryOperation::PREINCREMENT, Optional{},
UnaryOperation::PREDECREMENT, Optional{},
UnaryOperation::POSTINCREMENT, "++",
UnaryOperation::POSTDECREMENT, "--",
UnaryOperation::PLUS, Optional{},
UnaryOperation::MINUS, Optional{},
UnaryOperation::NOT, Optional{},
UnaryOperation::COMPLEMENT, Optional{},
UnaryOperation::PARENTHESIS, ")",
UnaryOperation::DEREFERENCE, Optional{},
UnaryOperation::ADDRESSOF, Optional{})
); });
add<TypeTraitExpression>([](TypeTraitExpression* e){ return c(
choose( static_cast<int>(e->typeTraitKind()),
static_cast<int>(TypeTraitExpression::TypeTraitKind::SizeOf), "sizeof",
static_cast<int>(TypeTraitExpression::TypeTraitKind::AlignOf), "alignof",
static_cast<int>(TypeTraitExpression::TypeTraitKind::TypeId), "typeid"),
"(",
e->operand(),
")"
); });
// Literals
add<BooleanLiteral>([](BooleanLiteral* e){ return c( e->value() ? "true" : "false" ); });
add<IntegerLiteral>([](IntegerLiteral* e){ return c( e->value() ); });
add<FloatLiteral>([](FloatLiteral* e){ return c( e->value() ); });
add<NullLiteral>([](NullLiteral*){ return c( "null" ); });
add<StringLiteral>([](StringLiteral* e){ return c( "\"", e->value(), "\"" ); });
add<CharacterLiteral>([](CharacterLiteral* e){ return c( "'", e->value(), "'" ); });
// Misc
add<CastExpression>([](CastExpression* e){ return c( "(", e->castType(), ")", e->expr() ); });
add<InstanceOfExpression>(
[](InstanceOfExpression* e){ return c( e->expr(), " ", "instanceof", " ", e->typeExpression() ); });
add<CommaExpression>([](CommaExpression* e){ return c( QString{}, e->left(), ",", e->right(), QString{} ); });
add<ConditionalExpression>([](ConditionalExpression* e){ return c(
QString{}, e->condition(), "?", e->trueExpression(), ":", e->falseExpression(), QString{} ); });
add<SuperExpression>([](SuperExpression* ){ return c( "super" ); });
add<ThisExpression>([](ThisExpression* ){ return c( "this" ); });
add<GlobalScopeExpression>([](GlobalScopeExpression* ){ return c( "::" ); });
add<ThrowExpression>([](ThrowExpression* e ){ return c( "throw", " ", e->expr() ); });
add<TypeNameOperator>([](TypeNameOperator* e ){ return c( "typename", " ", e->typeExpression() ); });
add<DeleteExpression>([](DeleteExpression* e ){ return c( e->isArray() ? "delete[]":"delete", " ", e->expr() ); });
add<VariableDeclarationExpression>([](VariableDeclarationExpression* e ){ return c( e->decl()->typeExpression(), " ",
e->decl()->name(), Optional{"=", e->decl()->initialValue()}, Optional{e->decl()->initialValue()}); });
add<LambdaExpression>([](LambdaExpression* e ){ return c( CompoundObjectDescriptor::storeExpression(e)); });
add<ArrayInitializer>([](ArrayInitializer* e){ return c( list(e->values(), "{", ",", "}", false, false) ); });
add<MethodCallExpression>([](MethodCallExpression* e){ return c(
e->callee(), list(e->arguments(), "(", ",", ")", false, true) ); });
add<MetaCallExpression>([](MetaCallExpression* e){ return c( "#",
e->callee(), list(e->arguments(), "(", ",", ")", false, true) ); });
add<NewExpression>([](NewExpression* e){ return c( "new", " ",
Optional{ (e->dimensions()->size() > 0 || !e->initializer()) ? e->newType() : nullptr, AUTO},
list(e->dimensions(), "[", ",", "]", true, true), Optional{e->initializer(), AUTO} ); });
add<ReferenceExpression>([](ReferenceExpression* e){ return c(
Optional{e->prefix(), AUTO}, Optional{
(e->memberKind() == ReferenceExpression::MemberKind::Dot ? "." :
e->memberKind() == ReferenceExpression::MemberKind::Pointer ? "->" :
e->memberKind() == ReferenceExpression::MemberKind::Static ? "::" : "::template"),
e->prefix()}, e->name(),
list(e->typeArguments(), "<", ",", ">", true, true) ); });
add<OOReference>([](OOReference* e){ return c( e->name() ); });
// Flexible input expressions
add<EmptyExpression>([](EmptyExpression*){ return c( "" ); });
add<ErrorExpression>([](ErrorExpression* e){ return c(
Optional{e->prefix(), !e->prefix().isEmpty()}, e->arg(), Optional{e->postfix(), !e->postfix().isEmpty()} ); });
add<UnfinishedOperator>([](UnfinishedOperator* e)
{
QStringList result;
for (int i=0; i< e->operands()->size(); ++i)
{
QString delim = e->delimiters()->at(i)->get();
result << delim << stringForNode(e->operands()->at(i));
}
if (e->delimiters()->size() > e->operands()->size())
{
QString delim = e->delimiters()->last()->get();
result << delim;
}
// Insert spaces on the insdie of the result to make sure they don't stick to each other
// E.g. when typing 'delete new foo'
int i = 0;
int lastNonEmpty = -1;
while (i<result.size())
{
if (!result[i].isEmpty())
{
if (lastNonEmpty >= 0)
{
result.insert(lastNonEmpty + 1, " ");
++i;
}
lastNonEmpty = i;
}
++i;
}
return result;
});
}
}
<|endoftext|> |
<commit_before><commit_msg>CEQU - Crucial Equation.cpp<commit_after><|endoftext|> |
<commit_before>#include <vector>
#include "base/basictypes.h"
#include "base/logging.h"
#include "gfx/gl_lost_manager.h"
std::vector<GfxResourceHolder *> *holders;
static bool inLost;
void register_gl_resource_holder(GfxResourceHolder *holder) {
if (inLost) {
FLOG("BAD: Should not call register_gl_resource_holder from lost path");
return;
}
if (holders) {
holders->push_back(holder);
} else {
WLOG("GL resource holder not initialized, cannot register resource");
}
}
void unregister_gl_resource_holder(GfxResourceHolder *holder) {
if (inLost) {
FLOG("BAD: Should not call unregister_gl_resource_holder from lost path");
return;
}
if (holders) {
for (size_t i = 0; i < holders->size(); i++) {
if ((*holders)[i] == holder) {
holders->erase(holders->begin() + i);
return;
}
}
WLOG("unregister_gl_resource_holder: Resource not registered");
} else {
WLOG("GL resource holder not initialized or already shutdown, cannot unregister resource");
}
}
void gl_lost() {
inLost = true;
if (!holders) {
WLOG("GL resource holder not initialized, cannot process lost request");
inLost = false;
return;
}
// TODO: We should really do this when we get the context back, not during gl_lost...
ILOG("gl_lost() restoring %i items:", (int)holders->size());
for (size_t i = 0; i < holders->size(); i++) {
ILOG("GLLost(%i / %i, %p)", (int)(i + 1), (int) holders->size(), (*holders)[i]);
(*holders)[i]->GLLost();
}
ILOG("gl_lost() completed restoring %i items:", (int)holders->size());
inLost = false;
}
void gl_lost_manager_init() {
if (holders) {
FLOG("Double GL lost manager init");
// Dead here (FLOG), no need to delete holders
}
holders = new std::vector<GfxResourceHolder *>();
}
void gl_lost_manager_shutdown() {
if (!holders) {
FLOG("Lost manager already shutdown");
}
delete holders;
holders = 0;
}
<commit_msg>Log an error if lost manager exits with objects still registered<commit_after>#include <vector>
#include "base/basictypes.h"
#include "base/logging.h"
#include "gfx/gl_lost_manager.h"
std::vector<GfxResourceHolder *> *holders;
static bool inLost;
void register_gl_resource_holder(GfxResourceHolder *holder) {
if (inLost) {
FLOG("BAD: Should not call register_gl_resource_holder from lost path");
return;
}
if (holders) {
holders->push_back(holder);
} else {
WLOG("GL resource holder not initialized, cannot register resource");
}
}
void unregister_gl_resource_holder(GfxResourceHolder *holder) {
if (inLost) {
FLOG("BAD: Should not call unregister_gl_resource_holder from lost path");
return;
}
if (holders) {
for (size_t i = 0; i < holders->size(); i++) {
if ((*holders)[i] == holder) {
holders->erase(holders->begin() + i);
return;
}
}
WLOG("unregister_gl_resource_holder: Resource not registered");
} else {
WLOG("GL resource holder not initialized or already shutdown, cannot unregister resource");
}
}
void gl_lost() {
inLost = true;
if (!holders) {
WLOG("GL resource holder not initialized, cannot process lost request");
inLost = false;
return;
}
// TODO: We should really do this when we get the context back, not during gl_lost...
ILOG("gl_lost() restoring %i items:", (int)holders->size());
for (size_t i = 0; i < holders->size(); i++) {
ILOG("GLLost(%i / %i, %p)", (int)(i + 1), (int) holders->size(), (*holders)[i]);
(*holders)[i]->GLLost();
}
ILOG("gl_lost() completed restoring %i items:", (int)holders->size());
inLost = false;
}
void gl_lost_manager_init() {
if (holders) {
FLOG("Double GL lost manager init");
// Dead here (FLOG), no need to delete holders
}
holders = new std::vector<GfxResourceHolder *>();
}
void gl_lost_manager_shutdown() {
if (!holders) {
FLOG("Lost manager already shutdown");
} else if (holders->size() > 0) {
ELOG("Lost manager shutdown with %i objects still registered", (int)holders->size());
}
delete holders;
holders = 0;
}
<|endoftext|> |
<commit_before>/******************************************************************************
*
* package: Log4Qt
* file: loggingevent.cpp
* created: September 2007
* author: Martin Heinrich
*
*
* Copyright 2007 Martin Heinrich
*
* 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.
*
*****************************************************************************/
/******************************************************************************
* Dependencies
******************************************************************************/
#include "loggingevent.h"
#include <QtCore/QBuffer>
#include <QtCore/QByteArray>
#include <QtCore/QDataStream>
#include <QtCore/QDebug>
#include <QtCore/QMutex>
#include <QtCore/QThread>
#include "helpers/datetime.h"
#include "helpers/initialisationhelper.h"
#include "logger.h"
#include "mdc.h"
#include "ndc.h"
namespace Log4Qt
{
/**************************************************************************
* Declarations
**************************************************************************/
LOG4QT_GLOBAL_STATIC(QMutex, sequence_guard)
/**************************************************************************
* C helper functions
**************************************************************************/
/**************************************************************************
* Class implementation: LoggingEvent
**************************************************************************/
LoggingEvent::LoggingEvent() :
mLevel(Level::NULL_INT),
mpLogger(0),
mMessage(),
mNdc(NDC::peek()),
mProperties(MDC::context()),
mSequenceNumber(nextSequenceNumber()),
mThreadName(),
mTimeStamp(DateTime::currentDateTime().toMilliSeconds())
{
setThreadNameToCurrent();
}
LoggingEvent::LoggingEvent(const Logger *pLogger,
Level level,
const QString &rMessage) :
mLevel(level),
mpLogger(pLogger),
mMessage(rMessage),
mNdc(NDC::peek()),
mProperties(MDC::context()),
mSequenceNumber(nextSequenceNumber()),
mThreadName(),
mTimeStamp(DateTime::currentDateTime().toMilliSeconds())
{
setThreadNameToCurrent();
}
LoggingEvent::LoggingEvent(const Logger *pLogger,
Level level,
const QString &rMessage,
qint64 timeStamp) :
mLevel(level),
mpLogger(pLogger),
mMessage(rMessage),
mNdc(NDC::peek()),
mProperties(MDC::context()),
mSequenceNumber(nextSequenceNumber()),
mThreadName(),
mTimeStamp(timeStamp)
{
setThreadNameToCurrent();
}
LoggingEvent::LoggingEvent(const Logger *pLogger,
Level level,
const QString &rMessage,
const QString &rNdc,
const QHash<QString, QString> &rProperties,
const QString &rThreadName,
qint64 timeStamp) :
mLevel(level),
mpLogger(pLogger),
mMessage(rMessage),
mNdc(rNdc),
mProperties(rProperties),
mSequenceNumber(nextSequenceNumber()),
mThreadName(rThreadName),
mTimeStamp(timeStamp)
{
}
QString LoggingEvent::loggerName() const
{
if (mpLogger)
return mpLogger->name();
else
return QString();
}
QString LoggingEvent::toString() const
{
return level().toString() + QLatin1Char(':') + message();
}
qint64 LoggingEvent::sequenceCount()
{
QMutexLocker locker(sequence_guard());
return msSequenceCount;
}
qint64 LoggingEvent::startTime()
{
return InitialisationHelper::startTime();
}
void LoggingEvent::setThreadNameToCurrent()
{
if (QThread::currentThread())
mThreadName = QThread::currentThread()->objectName();
}
qint64 LoggingEvent::nextSequenceNumber()
{
QMutexLocker locker(sequence_guard());
return ++msSequenceCount;
}
qint64 LoggingEvent::msSequenceCount = 0;
/**************************************************************************
* Implementation: Operators, Helper
**************************************************************************/
#ifndef QT_NO_DATASTREAM
QDataStream &operator<<(QDataStream &rStream, const LoggingEvent &rLoggingEvent)
{
QBuffer buffer;
buffer.open(QIODevice::WriteOnly);
QDataStream stream(&buffer);
// version
quint16 version = 0;
stream << version;
// version 0 data
stream << rLoggingEvent.mLevel
<< rLoggingEvent.loggerName()
<< rLoggingEvent.mMessage
<< rLoggingEvent.mNdc
<< rLoggingEvent.mProperties
<< rLoggingEvent.mSequenceNumber
<< rLoggingEvent.mThreadName
<< rLoggingEvent.mTimeStamp;
buffer.close();
rStream << buffer.buffer();
return rStream;
}
QDataStream &operator>>(QDataStream &rStream, LoggingEvent &rLoggingEvent)
{
QByteArray array;
rStream >> array;
QBuffer buffer(&array);
buffer.open(QIODevice::ReadOnly);
QDataStream stream(&buffer);
// version
quint16 version;
stream >> version;
// Version 0 data
QString logger;
stream >> rLoggingEvent.mLevel
>> logger
>> rLoggingEvent.mMessage
>> rLoggingEvent.mNdc
>> rLoggingEvent.mProperties
>> rLoggingEvent.mSequenceNumber
>> rLoggingEvent.mThreadName
>> rLoggingEvent.mTimeStamp;
if (logger.isEmpty())
rLoggingEvent.mpLogger = 0;
else
rLoggingEvent.mpLogger = Logger::logger(logger);
buffer.close();
return rStream;
}
#endif // QT_NO_DATASTREAM
#ifndef QT_NO_DEBUG_STREAM
QDebug operator<<(QDebug debug,
const LoggingEvent &rLoggingEvent)
{
QString logger;
if (rLoggingEvent.logger() != 0)
logger = rLoggingEvent.logger()->name();
debug.nospace() << "LoggingEvent("
<< "level:" << rLoggingEvent.level().toString() << " "
<< "logger:" << logger << " "
<< "message:" << rLoggingEvent.message() << " "
<< "sequencenumber:" << rLoggingEvent.sequenceNumber() << " "
<< "threadname:" << rLoggingEvent.threadName() << " "
<< "timestamp:" << rLoggingEvent.timeStamp()
<< "(" << DateTime::fromMilliSeconds(rLoggingEvent.timeStamp()) << ")"
<< "sequenceCount:" << rLoggingEvent.sequenceCount()
<< ")";
return debug.space();
}
#endif // QT_NO_DEBUG_STREAM
} // namespace Log4Qt
<commit_msg>If object name is not defined for thread use thread ID instead if object name for thread identification<commit_after>/******************************************************************************
*
* package: Log4Qt
* file: loggingevent.cpp
* created: September 2007
* author: Martin Heinrich
*
*
* Copyright 2007 Martin Heinrich
*
* 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.
*
*****************************************************************************/
/******************************************************************************
* Dependencies
******************************************************************************/
#include "loggingevent.h"
#include <QtCore/QBuffer>
#include <QtCore/QByteArray>
#include <QtCore/QDataStream>
#include <QtCore/QDebug>
#include <QtCore/QMutex>
#include <QtCore/QThread>
#include "helpers/datetime.h"
#include "helpers/initialisationhelper.h"
#include "logger.h"
#include "mdc.h"
#include "ndc.h"
namespace Log4Qt
{
/**************************************************************************
* Declarations
**************************************************************************/
LOG4QT_GLOBAL_STATIC(QMutex, sequence_guard)
/**************************************************************************
* C helper functions
**************************************************************************/
/**************************************************************************
* Class implementation: LoggingEvent
**************************************************************************/
LoggingEvent::LoggingEvent() :
mLevel(Level::NULL_INT),
mpLogger(0),
mMessage(),
mNdc(NDC::peek()),
mProperties(MDC::context()),
mSequenceNumber(nextSequenceNumber()),
mThreadName(),
mTimeStamp(DateTime::currentDateTime().toMilliSeconds())
{
setThreadNameToCurrent();
}
LoggingEvent::LoggingEvent(const Logger *pLogger,
Level level,
const QString &rMessage) :
mLevel(level),
mpLogger(pLogger),
mMessage(rMessage),
mNdc(NDC::peek()),
mProperties(MDC::context()),
mSequenceNumber(nextSequenceNumber()),
mThreadName(),
mTimeStamp(DateTime::currentDateTime().toMilliSeconds())
{
setThreadNameToCurrent();
}
LoggingEvent::LoggingEvent(const Logger *pLogger,
Level level,
const QString &rMessage,
qint64 timeStamp) :
mLevel(level),
mpLogger(pLogger),
mMessage(rMessage),
mNdc(NDC::peek()),
mProperties(MDC::context()),
mSequenceNumber(nextSequenceNumber()),
mThreadName(),
mTimeStamp(timeStamp)
{
setThreadNameToCurrent();
}
LoggingEvent::LoggingEvent(const Logger *pLogger,
Level level,
const QString &rMessage,
const QString &rNdc,
const QHash<QString, QString> &rProperties,
const QString &rThreadName,
qint64 timeStamp) :
mLevel(level),
mpLogger(pLogger),
mMessage(rMessage),
mNdc(rNdc),
mProperties(rProperties),
mSequenceNumber(nextSequenceNumber()),
mThreadName(rThreadName),
mTimeStamp(timeStamp)
{
}
QString LoggingEvent::loggerName() const
{
if (mpLogger)
return mpLogger->name();
else
return QString();
}
QString LoggingEvent::toString() const
{
return level().toString() + QLatin1Char(':') + message();
}
qint64 LoggingEvent::sequenceCount()
{
QMutexLocker locker(sequence_guard());
return msSequenceCount;
}
qint64 LoggingEvent::startTime()
{
return InitialisationHelper::startTime();
}
void LoggingEvent::setThreadNameToCurrent()
{
if (QThread::currentThread())
{
mThreadName = QThread::currentThread()->objectName();
// if object name is not set use thread id for thead identification
if (mThreadName.isEmpty())
mThreadName = QString("0x%0").arg(QThread::currentThreadId(),4,16);
}
}
qint64 LoggingEvent::nextSequenceNumber()
{
QMutexLocker locker(sequence_guard());
return ++msSequenceCount;
}
qint64 LoggingEvent::msSequenceCount = 0;
/**************************************************************************
* Implementation: Operators, Helper
**************************************************************************/
#ifndef QT_NO_DATASTREAM
QDataStream &operator<<(QDataStream &rStream, const LoggingEvent &rLoggingEvent)
{
QBuffer buffer;
buffer.open(QIODevice::WriteOnly);
QDataStream stream(&buffer);
// version
quint16 version = 0;
stream << version;
// version 0 data
stream << rLoggingEvent.mLevel
<< rLoggingEvent.loggerName()
<< rLoggingEvent.mMessage
<< rLoggingEvent.mNdc
<< rLoggingEvent.mProperties
<< rLoggingEvent.mSequenceNumber
<< rLoggingEvent.mThreadName
<< rLoggingEvent.mTimeStamp;
buffer.close();
rStream << buffer.buffer();
return rStream;
}
QDataStream &operator>>(QDataStream &rStream, LoggingEvent &rLoggingEvent)
{
QByteArray array;
rStream >> array;
QBuffer buffer(&array);
buffer.open(QIODevice::ReadOnly);
QDataStream stream(&buffer);
// version
quint16 version;
stream >> version;
// Version 0 data
QString logger;
stream >> rLoggingEvent.mLevel
>> logger
>> rLoggingEvent.mMessage
>> rLoggingEvent.mNdc
>> rLoggingEvent.mProperties
>> rLoggingEvent.mSequenceNumber
>> rLoggingEvent.mThreadName
>> rLoggingEvent.mTimeStamp;
if (logger.isEmpty())
rLoggingEvent.mpLogger = 0;
else
rLoggingEvent.mpLogger = Logger::logger(logger);
buffer.close();
return rStream;
}
#endif // QT_NO_DATASTREAM
#ifndef QT_NO_DEBUG_STREAM
QDebug operator<<(QDebug debug,
const LoggingEvent &rLoggingEvent)
{
QString logger;
if (rLoggingEvent.logger() != 0)
logger = rLoggingEvent.logger()->name();
debug.nospace() << "LoggingEvent("
<< "level:" << rLoggingEvent.level().toString() << " "
<< "logger:" << logger << " "
<< "message:" << rLoggingEvent.message() << " "
<< "sequencenumber:" << rLoggingEvent.sequenceNumber() << " "
<< "threadname:" << rLoggingEvent.threadName() << " "
<< "timestamp:" << rLoggingEvent.timeStamp()
<< "(" << DateTime::fromMilliSeconds(rLoggingEvent.timeStamp()) << ")"
<< "sequenceCount:" << rLoggingEvent.sequenceCount()
<< ")";
return debug.space();
}
#endif // QT_NO_DEBUG_STREAM
} // namespace Log4Qt
<|endoftext|> |
<commit_before>/*************************************************************************
*
* $RCSfile: Edit.hxx,v $
*
* $Revision: 1.10 $
*
* last change: $Author: rt $ $Date: 2004-05-07 16:06:52 $
*
* 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 _FORMS_EDIT_HXX_
#define _FORMS_EDIT_HXX_
#ifndef _FORMS_EDITBASE_HXX_
#include "EditBase.hxx"
#endif
#ifndef _CPPUHELPER_IMPLBASE3_HXX_
#include <cppuhelper/implbase3.hxx>
#endif
//.........................................................................
namespace frm
{
//==================================================================
//= OEditModel
//==================================================================
class OEditModel
:public OEditBaseModel
,public ::comphelper::OAggregationArrayUsageHelper< OEditModel >
{
::com::sun::star::uno::Reference< ::com::sun::star::util::XNumberFormatter> m_xFormatter;
::rtl::OUString m_aSaveValue;
sal_Int32 m_nFormatKey;
::com::sun::star::util::Date m_aNullDate;
sal_Int32 m_nFieldType;
sal_Int16 m_nKeyType;
sal_Bool m_bMaxTextLenModified : 1; // set to <TRUE/> when we change the MaxTextLen of the aggregate
sal_Bool m_bWritingFormattedFake : 1;
// are we writing something which should be interpreted as formatted upon reading?
sal_Bool m_bNumericField : 1;
// are we bound to some kind of numeric field?
protected:
virtual ::com::sun::star::uno::Sequence< ::com::sun::star::uno::Type> _getTypes();
DECLARE_DEFAULT_LEAF_XTOR( OEditModel );
void enableFormattedWriteFake() { m_bWritingFormattedFake = sal_True; }
void disableFormattedWriteFake() { m_bWritingFormattedFake = sal_False; }
sal_Bool lastReadWasFormattedFake() const { return (getLastReadVersion() & PF_FAKE_FORMATTED_FIELD) != 0; }
friend InterfaceRef SAL_CALL OEditModel_CreateInstance(const ::com::sun::star::uno::Reference< ::com::sun::star::lang::XMultiServiceFactory>& _rxFactory);
friend class OFormattedFieldWrapper;
friend class OFormattedModel; // temporary
public:
virtual void SAL_CALL disposing();
// XPropertySet
virtual void SAL_CALL getFastPropertyValue(::com::sun::star::uno::Any& rValue, sal_Int32 nHandle ) const;
// ::com::sun::star::io::XPersistObject
virtual void SAL_CALL write(const ::com::sun::star::uno::Reference< ::com::sun::star::io::XObjectOutputStream>& _rxOutStream) throw ( ::com::sun::star::io::IOException, ::com::sun::star::uno::RuntimeException);
virtual void SAL_CALL read(const ::com::sun::star::uno::Reference< ::com::sun::star::io::XObjectInputStream>& _rxInStream) throw ( ::com::sun::star::io::IOException, ::com::sun::star::uno::RuntimeException);
virtual ::rtl::OUString SAL_CALL getServiceName() throw ( ::com::sun::star::uno::RuntimeException);
// ::com::sun::star::beans::XPropertySet
virtual ::com::sun::star::uno::Reference< ::com::sun::star::beans::XPropertySetInfo> SAL_CALL getPropertySetInfo() throw(::com::sun::star::uno::RuntimeException);
virtual ::cppu::IPropertyArrayHelper& SAL_CALL getInfoHelper();
// XReset
virtual void SAL_CALL reset( ) throw(::com::sun::star::uno::RuntimeException);
// ::com::sun::star::lang::XServiceInfo
IMPLEMENTATION_NAME(OEditModel);
virtual StringSequence SAL_CALL getSupportedServiceNames() throw();
// OAggregationArrayUsageHelper
virtual void fillProperties(
::com::sun::star::uno::Sequence< ::com::sun::star::beans::Property >& /* [out] */ _rProps,
::com::sun::star::uno::Sequence< ::com::sun::star::beans::Property >& /* [out] */ _rAggregateProps
) const;
IMPLEMENT_INFO_SERVICE()
protected:
// OControlModel overridables
virtual void writeAggregate( const ::com::sun::star::uno::Reference< ::com::sun::star::io::XObjectOutputStream >& _rxOutStream ) const;
virtual void readAggregate( const ::com::sun::star::uno::Reference< ::com::sun::star::io::XObjectInputStream >& _rxInStream );
// OBoundControlModel overridables
virtual ::com::sun::star::uno::Any
translateDbColumnToControlValue( );
virtual sal_Bool commitControlValueToDbColumn( bool _bPostReset );
virtual ::com::sun::star::uno::Any
getDefaultForReset() const;
virtual void onConnectedDbColumn( const ::com::sun::star::uno::Reference< ::com::sun::star::uno::XInterface >& _rxForm );
virtual void onDisconnectedDbColumn();
virtual sal_Bool approveValueBinding( const ::com::sun::star::uno::Reference< ::com::sun::star::form::binding::XValueBinding >& _rxBinding );
virtual sal_Bool approveDbColumnType( sal_Int32 _nColumnType );
protected:
virtual sal_Int16 getPersistenceFlags() const;
DECLARE_XCLONEABLE();
private:
bool implActsAsRichText( ) const;
};
//==================================================================
//= OEditControl
//==================================================================
typedef ::cppu::ImplHelper3< ::com::sun::star::awt::XFocusListener,
::com::sun::star::awt::XKeyListener,
::com::sun::star::form::XChangeBroadcaster > OEditControl_BASE;
class OEditControl : public OBoundControl
,public OEditControl_BASE
{
::cppu::OInterfaceContainerHelper
m_aChangeListeners;
::rtl::OUString m_aHtmlChangeValue;
sal_uInt32 m_nKeyEvent;
public:
OEditControl(const ::com::sun::star::uno::Reference< ::com::sun::star::lang::XMultiServiceFactory>& _rxFactory);
virtual ~OEditControl();
DECLARE_UNO3_AGG_DEFAULTS(OEditControl, OBoundControl);
virtual ::com::sun::star::uno::Any SAL_CALL queryAggregation(const ::com::sun::star::uno::Type& _rType) throw(::com::sun::star::uno::RuntimeException);
virtual ::com::sun::star::uno::Sequence< ::com::sun::star::uno::Type> _getTypes();
// OComponentHelper
virtual void SAL_CALL disposing();
// ::com::sun::star::lang::XEventListener
virtual void SAL_CALL disposing(const ::com::sun::star::lang::EventObject& _rSource) throw(::com::sun::star::uno::RuntimeException);
// ::com::sun::star::lang::XServiceInfo
IMPLEMENTATION_NAME(OEditControl);
virtual StringSequence SAL_CALL getSupportedServiceNames() throw();
// ::com::sun::star::form::XChangeBroadcaster
virtual void SAL_CALL addChangeListener(const ::com::sun::star::uno::Reference< ::com::sun::star::form::XChangeListener>& _rxListener) throw ( ::com::sun::star::uno::RuntimeException);
virtual void SAL_CALL removeChangeListener(const ::com::sun::star::uno::Reference< ::com::sun::star::form::XChangeListener>& _rxListener) throw ( ::com::sun::star::uno::RuntimeException);
// ::com::sun::star::awt::XFocusListener
virtual void SAL_CALL focusGained( const ::com::sun::star::awt::FocusEvent& e ) throw ( ::com::sun::star::uno::RuntimeException);
virtual void SAL_CALL focusLost( const ::com::sun::star::awt::FocusEvent& e ) throw ( ::com::sun::star::uno::RuntimeException);
// ::com::sun::star::awt::XKeyListener
virtual void SAL_CALL keyPressed(const ::com::sun::star::awt::KeyEvent& e) throw ( ::com::sun::star::uno::RuntimeException);
virtual void SAL_CALL keyReleased(const ::com::sun::star::awt::KeyEvent& e) throw ( ::com::sun::star::uno::RuntimeException);
private:
DECL_LINK( OnKeyPressed, void* );
};
//.........................................................................
}
//.........................................................................
#endif // _FORMS_EDIT_HXX_
<commit_msg>INTEGRATION: CWS dba12 (1.9.6); FILE MERGED 2004/06/14 20:59:21 fs 1.9.6.2: RESYNC: (1.9-1.10); FILE MERGED 2004/04/26 09:18:43 fs 1.9.6.1: #i27072# disable Java-like text notifications on the peer<commit_after>/*************************************************************************
*
* $RCSfile: Edit.hxx,v $
*
* $Revision: 1.11 $
*
* last change: $Author: hjs $ $Date: 2004-06-28 17:08:39 $
*
* 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 _FORMS_EDIT_HXX_
#define _FORMS_EDIT_HXX_
#ifndef _FORMS_EDITBASE_HXX_
#include "EditBase.hxx"
#endif
#ifndef _CPPUHELPER_IMPLBASE3_HXX_
#include <cppuhelper/implbase3.hxx>
#endif
//.........................................................................
namespace frm
{
//==================================================================
//= OEditModel
//==================================================================
class OEditModel
:public OEditBaseModel
,public ::comphelper::OAggregationArrayUsageHelper< OEditModel >
{
::com::sun::star::uno::Reference< ::com::sun::star::util::XNumberFormatter> m_xFormatter;
::rtl::OUString m_aSaveValue;
sal_Int32 m_nFormatKey;
::com::sun::star::util::Date m_aNullDate;
sal_Int32 m_nFieldType;
sal_Int16 m_nKeyType;
sal_Bool m_bMaxTextLenModified : 1; // set to <TRUE/> when we change the MaxTextLen of the aggregate
sal_Bool m_bWritingFormattedFake : 1;
// are we writing something which should be interpreted as formatted upon reading?
sal_Bool m_bNumericField : 1;
// are we bound to some kind of numeric field?
protected:
virtual ::com::sun::star::uno::Sequence< ::com::sun::star::uno::Type> _getTypes();
DECLARE_DEFAULT_LEAF_XTOR( OEditModel );
void enableFormattedWriteFake() { m_bWritingFormattedFake = sal_True; }
void disableFormattedWriteFake() { m_bWritingFormattedFake = sal_False; }
sal_Bool lastReadWasFormattedFake() const { return (getLastReadVersion() & PF_FAKE_FORMATTED_FIELD) != 0; }
friend InterfaceRef SAL_CALL OEditModel_CreateInstance(const ::com::sun::star::uno::Reference< ::com::sun::star::lang::XMultiServiceFactory>& _rxFactory);
friend class OFormattedFieldWrapper;
friend class OFormattedModel; // temporary
public:
virtual void SAL_CALL disposing();
// XPropertySet
virtual void SAL_CALL getFastPropertyValue(::com::sun::star::uno::Any& rValue, sal_Int32 nHandle ) const;
// ::com::sun::star::io::XPersistObject
virtual void SAL_CALL write(const ::com::sun::star::uno::Reference< ::com::sun::star::io::XObjectOutputStream>& _rxOutStream) throw ( ::com::sun::star::io::IOException, ::com::sun::star::uno::RuntimeException);
virtual void SAL_CALL read(const ::com::sun::star::uno::Reference< ::com::sun::star::io::XObjectInputStream>& _rxInStream) throw ( ::com::sun::star::io::IOException, ::com::sun::star::uno::RuntimeException);
virtual ::rtl::OUString SAL_CALL getServiceName() throw ( ::com::sun::star::uno::RuntimeException);
// ::com::sun::star::beans::XPropertySet
virtual ::com::sun::star::uno::Reference< ::com::sun::star::beans::XPropertySetInfo> SAL_CALL getPropertySetInfo() throw(::com::sun::star::uno::RuntimeException);
virtual ::cppu::IPropertyArrayHelper& SAL_CALL getInfoHelper();
// XReset
virtual void SAL_CALL reset( ) throw(::com::sun::star::uno::RuntimeException);
// ::com::sun::star::lang::XServiceInfo
IMPLEMENTATION_NAME(OEditModel);
virtual StringSequence SAL_CALL getSupportedServiceNames() throw();
// OAggregationArrayUsageHelper
virtual void fillProperties(
::com::sun::star::uno::Sequence< ::com::sun::star::beans::Property >& /* [out] */ _rProps,
::com::sun::star::uno::Sequence< ::com::sun::star::beans::Property >& /* [out] */ _rAggregateProps
) const;
IMPLEMENT_INFO_SERVICE()
protected:
// OControlModel overridables
virtual void writeAggregate( const ::com::sun::star::uno::Reference< ::com::sun::star::io::XObjectOutputStream >& _rxOutStream ) const;
virtual void readAggregate( const ::com::sun::star::uno::Reference< ::com::sun::star::io::XObjectInputStream >& _rxInStream );
// OBoundControlModel overridables
virtual ::com::sun::star::uno::Any
translateDbColumnToControlValue( );
virtual sal_Bool commitControlValueToDbColumn( bool _bPostReset );
virtual ::com::sun::star::uno::Any
getDefaultForReset() const;
virtual void onConnectedDbColumn( const ::com::sun::star::uno::Reference< ::com::sun::star::uno::XInterface >& _rxForm );
virtual void onDisconnectedDbColumn();
virtual sal_Bool approveValueBinding( const ::com::sun::star::uno::Reference< ::com::sun::star::form::binding::XValueBinding >& _rxBinding );
virtual sal_Bool approveDbColumnType( sal_Int32 _nColumnType );
protected:
virtual sal_Int16 getPersistenceFlags() const;
DECLARE_XCLONEABLE();
private:
bool implActsAsRichText( ) const;
};
//==================================================================
//= OEditControl
//==================================================================
typedef ::cppu::ImplHelper3< ::com::sun::star::awt::XFocusListener,
::com::sun::star::awt::XKeyListener,
::com::sun::star::form::XChangeBroadcaster > OEditControl_BASE;
class OEditControl : public OBoundControl
,public OEditControl_BASE
{
::cppu::OInterfaceContainerHelper
m_aChangeListeners;
::rtl::OUString m_aHtmlChangeValue;
sal_uInt32 m_nKeyEvent;
public:
OEditControl(const ::com::sun::star::uno::Reference< ::com::sun::star::lang::XMultiServiceFactory>& _rxFactory);
virtual ~OEditControl();
DECLARE_UNO3_AGG_DEFAULTS(OEditControl, OBoundControl);
virtual ::com::sun::star::uno::Any SAL_CALL queryAggregation(const ::com::sun::star::uno::Type& _rType) throw(::com::sun::star::uno::RuntimeException);
virtual ::com::sun::star::uno::Sequence< ::com::sun::star::uno::Type> _getTypes();
// OComponentHelper
virtual void SAL_CALL disposing();
// ::com::sun::star::lang::XEventListener
virtual void SAL_CALL disposing(const ::com::sun::star::lang::EventObject& _rSource) throw(::com::sun::star::uno::RuntimeException);
// ::com::sun::star::lang::XServiceInfo
IMPLEMENTATION_NAME(OEditControl);
virtual StringSequence SAL_CALL getSupportedServiceNames() throw();
// ::com::sun::star::form::XChangeBroadcaster
virtual void SAL_CALL addChangeListener(const ::com::sun::star::uno::Reference< ::com::sun::star::form::XChangeListener>& _rxListener) throw ( ::com::sun::star::uno::RuntimeException);
virtual void SAL_CALL removeChangeListener(const ::com::sun::star::uno::Reference< ::com::sun::star::form::XChangeListener>& _rxListener) throw ( ::com::sun::star::uno::RuntimeException);
// ::com::sun::star::awt::XFocusListener
virtual void SAL_CALL focusGained( const ::com::sun::star::awt::FocusEvent& e ) throw ( ::com::sun::star::uno::RuntimeException);
virtual void SAL_CALL focusLost( const ::com::sun::star::awt::FocusEvent& e ) throw ( ::com::sun::star::uno::RuntimeException);
// ::com::sun::star::awt::XKeyListener
virtual void SAL_CALL keyPressed(const ::com::sun::star::awt::KeyEvent& e) throw ( ::com::sun::star::uno::RuntimeException);
virtual void SAL_CALL keyReleased(const ::com::sun::star::awt::KeyEvent& e) throw ( ::com::sun::star::uno::RuntimeException);
// XControl
virtual void SAL_CALL createPeer( const ::com::sun::star::uno::Reference< ::com::sun::star::awt::XToolkit >& _rxToolkit, const ::com::sun::star::uno::Reference< ::com::sun::star::awt::XWindowPeer >& _rxParent ) throw ( ::com::sun::star::uno::RuntimeException );
private:
DECL_LINK( OnKeyPressed, void* );
};
//.........................................................................
}
//.........................................................................
#endif // _FORMS_EDIT_HXX_
<|endoftext|> |
<commit_before>/**
Copyright (c) 2017, Philip Deegan.
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are
met:
* Redistributions of source code must retain the above copyright
notice, this list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above
copyright notice, this list of conditions and the following disclaimer
in the documentation and/or other materials provided with the
distribution.
* Neither the name of Philip Deegan nor the names of its
contributors may be used to endorse or promote products derived from
this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
"AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
#include "maiken.hpp"
void maiken::Application::link(const kul::hash::set::String& objects)
KTHROW(kul::Exception) {
showConfig();
if (objects.size() > 0) {
buildDir().mk();
if (!main.empty())
buildExecutable(objects);
else
buildLibrary(objects);
if (CommandStateMachine::INSTANCE().commands().count(STR_TEST) &&
!tests.empty())
buildTest(objects);
kul::os::PushDir pushd(this->project().dir());
kul::Dir build(".mkn/build");
build.mk();
kul::File ts("timestamp", build);
if (ts) ts.rm();
{
kul::io::Writer w(ts);
w << kul::Now::MILLIS();
}
} else
KEXIT(1, "No link objects found, try compile or build.");
}
void maiken::Application::checkErrors(const CompilerProcessCapture& cpc)
KTHROW(kul::Exception) {
auto o = [](const std::string& s) {
if (s.size()) KOUT(NON) << s;
};
auto e = [](const std::string& s) {
if (s.size()) KERR << s;
};
if (kul::LogMan::INSTANCE().inf() || cpc.exception()) o(cpc.outs());
if (kul::LogMan::INSTANCE().err() || cpc.exception()) e(cpc.errs());
if (cpc.exception()) std::rethrow_exception(cpc.exception());
}
bool maiken::Application::is_build_required() {
kul::os::PushDir pushd(this->project().dir());
kul::Dir bDir(".mkn/build");
return !bDir || bDir.dirs().size() == 0
|| bDir.files().size() == 0;;
}
bool maiken::Application::is_build_stale() {
kul::os::PushDir pushd(this->project().dir());
kul::Dir d(".mkn/build");
kul::File f("timestamp", d);
if (!d || !f) return true;
kul::io::Reader r(f);
try {
size_t then = (size_t)43200 * ((size_t)60 * (size_t)1000);
size_t now = kul::Now::MILLIS();
size_t _MKN_BUILD_IS_STALE_MINUTES = now - then;
const char* c = r.readLine();
size_t timestamp = kul::String::UINT64(std::string(c));
if (_MKN_BUILD_IS_STALE_MINUTES > timestamp) return true;
} catch (const kul::Exception& e) {
KERR << e.stack();
} catch (const std::exception& e) {
KERR << e.what();
}
return false;
}
<commit_msg>to build or not to build (modules<commit_after>/**
Copyright (c) 2017, Philip Deegan.
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are
met:
* Redistributions of source code must retain the above copyright
notice, this list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above
copyright notice, this list of conditions and the following disclaimer
in the documentation and/or other materials provided with the
distribution.
* Neither the name of Philip Deegan nor the names of its
contributors may be used to endorse or promote products derived from
this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
"AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
#include "maiken.hpp"
void maiken::Application::link(const kul::hash::set::String& objects)
KTHROW(kul::Exception) {
showConfig();
if (objects.size() > 0) {
buildDir().mk();
if (!main.empty())
buildExecutable(objects);
else
buildLibrary(objects);
if (CommandStateMachine::INSTANCE().commands().count(STR_TEST) &&
!tests.empty())
buildTest(objects);
kul::os::PushDir pushd(this->project().dir());
kul::Dir build(".mkn/build");
build.mk();
kul::File ts("timestamp", build);
if (ts) ts.rm();
{
kul::io::Writer w(ts);
w << kul::Now::MILLIS();
}
} else
KEXIT(1, "No link objects found, try compile or build.");
}
void maiken::Application::checkErrors(const CompilerProcessCapture& cpc)
KTHROW(kul::Exception) {
auto o = [](const std::string& s) {
if (s.size()) KOUT(NON) << s;
};
auto e = [](const std::string& s) {
if (s.size()) KERR << s;
};
if (kul::LogMan::INSTANCE().inf() || cpc.exception()) o(cpc.outs());
if (kul::LogMan::INSTANCE().err() || cpc.exception()) e(cpc.errs());
if (cpc.exception()) std::rethrow_exception(cpc.exception());
}
bool maiken::Application::is_build_required() {
kul::os::PushDir pushd(this->project().dir());
kul::Dir bDir(".mkn/build");
return !bDir || bDir.files().size() == 0
|| buildDir().dirs().size() == 0
|| buildDir().files().size() == 0;
}
bool maiken::Application::is_build_stale() {
kul::os::PushDir pushd(this->project().dir());
kul::Dir d(".mkn/build");
kul::File f("timestamp", d);
if (!d || !f) return true;
kul::io::Reader r(f);
try {
size_t then = (size_t)43200 * ((size_t)60 * (size_t)1000);
size_t now = kul::Now::MILLIS();
size_t _MKN_BUILD_IS_STALE_MINUTES = now - then;
const char* c = r.readLine();
size_t timestamp = kul::String::UINT64(std::string(c));
if (_MKN_BUILD_IS_STALE_MINUTES > timestamp) return true;
} catch (const kul::Exception& e) {
KERR << e.stack();
} catch (const std::exception& e) {
KERR << e.what();
}
return false;
}
<|endoftext|> |
<commit_before>/**
* @file DenseMatrix.cpp
*/
// Copyright 2001 California Institute of Technology
#ifdef WIN32
#pragma warning(disable:4786)
#pragma warning(disable:4503)
#endif
#include "ct_defs.h"
#include "ctlapack.h"
#include "utilities.h"
#include "DenseMatrix.h"
namespace Cantera {
/// assignment.
DenseMatrix& DenseMatrix::operator=(const DenseMatrix& y) {
if (&y == this) return *this;
Array2D::operator=(y);
m_ipiv = y.ipiv();
return *this;
}
void DenseMatrix::resize(int n, int m, doublereal v) {
Array2D::resize(n,m,v);
m_ipiv.resize( max(n,m) );
}
void DenseMatrix::mult(const double* b, double* prod) const {
ct_dgemv(ctlapack::ColMajor, ctlapack::NoTranspose, nRows(),
nRows(), 1.0, begin(), nRows(), b, 1, 0.0, prod, 1);
}
void DenseMatrix::leftMult(const double* b, double* prod) const {
int nc = nColumns();
int nr = nRows();
int n, i;
double sum = 0.0;
for (n = 0; n < nc; n++) {
sum = 0.0;
for (i = 0; i < nr; i++) {
sum += value(i,n)*b[i];
}
prod[n] = sum;
}
}
/**
* Solve Ax = b. Array b is overwritten on exit with x.
*/
int solve(DenseMatrix& A, double* b) {
int info=0;
ct_dgetrf(A.nRows(), A.nColumns(), A.begin(), A.nRows(),
A.ipiv().begin(), info);
if (info != 0)
throw CanteraError("DenseMatrix::solve",
"DGETRF returned INFO = "+int2str(info));
ct_dgetrs(ctlapack::NoTranspose, A.nRows(), 1, A.begin(), A.nRows(),
A.ipiv().begin(), b, A.nColumns(), info);
if (info != 0)
throw CanteraError("DenseMatrix::solve",
"DGETRS returned INFO = "+int2str(info));
return 0;
}
/** Solve Ax = b for multiple right-hand-side vectors. */
int solve(DenseMatrix& A, DenseMatrix& b) {
int info=0;
ct_dgetrf(A.nRows(), A.nColumns(), A.begin(), A.nRows(),
A.ipiv().begin(), info);
if (info != 0)
throw CanteraError("DenseMatrix::solve",
"DGETRF returned INFO = "+int2str(info));
ct_dgetrs(ctlapack::NoTranspose, A.nRows(), b.nColumns(),
A.begin(), A.nRows(),
A.ipiv().begin(), b.begin(), b.nRows(), info);
if (info != 0)
throw CanteraError("DenseMatrix::solve",
"DGETRS returned INFO = "+int2str(info));
return 0;
}
/** @todo fix lwork */
int leastSquares(DenseMatrix& A, double* b) {
int info = 0;
int rank = 0;
double rcond = -1.0;
// fix this!
int lwork = 6000; // 2*(3*min(m,n) + max(2*min(m,n), max(m,n)));
vector_fp work(lwork);
vector_fp s(min(A.nRows(),A.nColumns()));
ct_dgelss(A.nRows(), A.nColumns(), 1, A.begin(),
A.nRows(), b, A.nColumns(), s.begin(),
rcond, rank, work.begin(), work.size(), info);
if (info != 0)
throw CanteraError("DenseMatrix::leaseSquares",
"DGELSS returned INFO = "+int2str(info));
return 0;
}
/**
* Multiply \c A*b and return the result in \c prod. Uses BLAS
* routine DGEMV.
*/
void multiply(const DenseMatrix& A, const double* b, double* prod) {
ct_dgemv(ctlapack::ColMajor, ctlapack::NoTranspose,
A.nRows(), A.nRows(), 1.0,
A.begin(), A.nRows(), b, 1, 0.0, prod, 1);
}
void increment(const DenseMatrix& A,
const double* b, double* prod) {
ct_dgemv(ctlapack::ColMajor, ctlapack::NoTranspose,
A.nRows(), A.nRows(), 1.0,
A.begin(), A.nRows(), b, 1, 1.0, prod, 1);
}
/**
* invert A. A is overwritten with A^-1.
*/
int invert(DenseMatrix& A, int nn) {
integer n = (nn > 0 ? nn : A.nRows());
integer info=0;
ct_dgetrf(n, n, A.begin(), A.nRows(), A.ipiv().begin(), info);
if (info != 0)
throw CanteraError("invert",
"DGETRF returned INFO="+int2str(info));
vector_fp work(n);
integer lwork = work.size();
ct_dgetri(n, A.begin(), A.nRows(), A.ipiv().begin(),
work.begin(), lwork, info);
if (info != 0)
throw CanteraError("invert",
"DGETRI returned INFO="+int2str(info));
return 0;
}
}
<commit_msg>static_cast to eliminate VC++ warnings<commit_after>/**
* @file DenseMatrix.cpp
*/
// Copyright 2001 California Institute of Technology
#ifdef WIN32
#pragma warning(disable:4786)
#pragma warning(disable:4503)
#endif
#include "ct_defs.h"
#include "ctlapack.h"
#include "utilities.h"
#include "DenseMatrix.h"
namespace Cantera {
/// assignment.
DenseMatrix& DenseMatrix::operator=(const DenseMatrix& y) {
if (&y == this) return *this;
Array2D::operator=(y);
m_ipiv = y.ipiv();
return *this;
}
void DenseMatrix::resize(int n, int m, doublereal v) {
Array2D::resize(n,m,v);
m_ipiv.resize( max(n,m) );
}
void DenseMatrix::mult(const double* b, double* prod) const {
ct_dgemv(ctlapack::ColMajor, ctlapack::NoTranspose,
static_cast<int>(nRows()),
static_cast<int>(nRows()), 1.0, begin(),
static_cast<int>(nRows()), b, 1, 0.0, prod, 1);
}
void DenseMatrix::leftMult(const double* b, double* prod) const {
int nc = static_cast<int>(nColumns());
int nr = static_cast<int>(nRows());
int n, i;
double sum = 0.0;
for (n = 0; n < nc; n++) {
sum = 0.0;
for (i = 0; i < nr; i++) {
sum += value(i,n)*b[i];
}
prod[n] = sum;
}
}
/**
* Solve Ax = b. Array b is overwritten on exit with x.
*/
int solve(DenseMatrix& A, double* b) {
int info=0;
ct_dgetrf(static_cast<int>(A.nRows()),
static_cast<int>(A.nColumns()), A.begin(),
static_cast<int>(A.nRows()), A.ipiv().begin(), info);
if (info != 0)
throw CanteraError("DenseMatrix::solve",
"DGETRF returned INFO = "+int2str(info));
ct_dgetrs(ctlapack::NoTranspose,
static_cast<int>(A.nRows()), 1, A.begin(),
static_cast<int>(A.nRows()),
A.ipiv().begin(), b,
static_cast<int>(A.nColumns()), info);
if (info != 0)
throw CanteraError("DenseMatrix::solve",
"DGETRS returned INFO = "+int2str(info));
return 0;
}
/** Solve Ax = b for multiple right-hand-side vectors. */
int solve(DenseMatrix& A, DenseMatrix& b) {
int info=0;
ct_dgetrf(static_cast<int>(A.nRows()),
static_cast<int>(A.nColumns()), A.begin(),
static_cast<int>(A.nRows()), A.ipiv().begin(), info);
if (info != 0)
throw CanteraError("DenseMatrix::solve",
"DGETRF returned INFO = "+int2str(info));
ct_dgetrs(ctlapack::NoTranspose, static_cast<int>(A.nRows()),
static_cast<int>(b.nColumns()),
A.begin(), static_cast<int>(A.nRows()),
A.ipiv().begin(), b.begin(),
static_cast<int>(b.nRows()), info);
if (info != 0)
throw CanteraError("DenseMatrix::solve",
"DGETRS returned INFO = "+int2str(info));
return 0;
}
/** @todo fix lwork */
int leastSquares(DenseMatrix& A, double* b) {
int info = 0;
int rank = 0;
double rcond = -1.0;
// fix this!
int lwork = 6000; // 2*(3*min(m,n) + max(2*min(m,n), max(m,n)));
vector_fp work(lwork);
vector_fp s(min(static_cast<int>(A.nRows()),
static_cast<int>(A.nColumns())));
ct_dgelss(static_cast<int>(A.nRows()),
static_cast<int>(A.nColumns()), 1, A.begin(),
static_cast<int>(A.nRows()), b,
static_cast<int>(A.nColumns()), s.begin(),
rcond, rank, work.begin(), work.size(), info);
if (info != 0)
throw CanteraError("DenseMatrix::leaseSquares",
"DGELSS returned INFO = "+int2str(info));
return 0;
}
/**
* Multiply \c A*b and return the result in \c prod. Uses BLAS
* routine DGEMV.
*/
void multiply(const DenseMatrix& A, const double* b, double* prod) {
ct_dgemv(ctlapack::ColMajor, ctlapack::NoTranspose,
static_cast<int>(A.nRows()), static_cast<int>(A.nRows()), 1.0,
A.begin(), static_cast<int>(A.nRows()), b, 1, 0.0, prod, 1);
}
void increment(const DenseMatrix& A,
const double* b, double* prod) {
ct_dgemv(ctlapack::ColMajor, ctlapack::NoTranspose,
static_cast<int>(A.nRows()), static_cast<int>(A.nRows()), 1.0,
A.begin(), static_cast<int>(A.nRows()), b, 1, 1.0, prod, 1);
}
/**
* invert A. A is overwritten with A^-1.
*/
int invert(DenseMatrix& A, int nn) {
integer n = (nn > 0 ? nn : static_cast<int>(A.nRows()));
integer info=0;
ct_dgetrf(n, n, A.begin(), static_cast<int>(A.nRows()),
A.ipiv().begin(), info);
if (info != 0)
throw CanteraError("invert",
"DGETRF returned INFO="+int2str(info));
vector_fp work(n);
integer lwork = static_cast<int>(work.size());
ct_dgetri(n, A.begin(), static_cast<int>(A.nRows()),
A.ipiv().begin(),
work.begin(), lwork, info);
if (info != 0)
throw CanteraError("invert",
"DGETRI returned INFO="+int2str(info));
return 0;
}
}
<|endoftext|> |
<commit_before>#include <sstream>
#include <zorba/item.h>
#include "runtime/core/arithmetic_impl.h"
#include "errors/error_factory.h"
#include "system/globalenv.h"
#include "types/root_typemanager.h"
#include "types/casting.h"
#include "util/Assert.h"
#include "runtime/numerics/NumericsImpl.h"
#include "runtime/dateTime/DurationsDatesTimes.h"
#include "errors/error_factory.h"
#include "system/zorba.h"
#include "store/api/item_factory.h"
#include "system/zorba_engine.h"
#include "context/dynamic_context.h"
namespace zorba {
void ArithOperationsCommons::createError(
const char* aOp,
const QueryLoc* aLoc,
TypeConstants::atomic_type_code_t aType0,
TypeConstants::atomic_type_code_t aType1
)
{
AtomicXQType lAType0(aType0, TypeConstants::QUANT_ONE);
AtomicXQType lAType1(aType1, TypeConstants::QUANT_ONE);
std::stringstream lStream;
lStream << "The operation '";
lStream << aOp;
lStream << "' is not possible with parameters of the type ";
lAType0.serialize(lStream);
lStream << " and ";
lAType1.serialize(lStream);
lStream << "!";
ZORBA_ERROR_ALERT(
ZorbaError::XPTY0004,
aLoc,
DONT_CONTINUE_EXECUTION,
lStream.str()
);
}
/* begin class GenericArithIterator */
template< class Operations>
GenericArithIterator<Operations>::GenericArithIterator
( const QueryLoc& loc, PlanIter_t& iter0, PlanIter_t& iter1 )
:
BinaryBaseIterator<GenericArithIterator<Operations>, PlanIteratorState > ( loc, iter0, iter1 )
{ }
template < class Operation >
store::Item_t GenericArithIterator<Operation>::nextImpl ( PlanState& planState ) const
{
store::Item_t n0;
store::Item_t n1;
store::Item_t res;
PlanIteratorState* state;
DEFAULT_STACK_INIT ( PlanIteratorState, state, planState );
n0 = consumeNext( this->theChild0.getp(), planState );
if ( n0 != NULL )
{
n1 = consumeNext( this->theChild1.getp(), planState );
if ( n1 != NULL )
{
res = compute(this->loc, n0, n1);
if ( consumeNext(this->theChild0.getp(), planState ) != NULL
|| consumeNext(this->theChild1.getp(), planState ) != NULL )
ZORBA_ERROR_ALERT(ZorbaError::XPTY0004,
NULL, DONT_CONTINUE_EXECUTION, "Arithmetic operation has a sequences greater than one as an operator.");
STACK_PUSH ( res, state );
}
}
STACK_END();
}
template < class Operation >
store::Item_t GenericArithIterator<Operation>::compute(const QueryLoc& aLoc, store::Item_t n0, store::Item_t n1)
{
n0 = n0->getAtomizationValue();
n1 = n1->getAtomizationValue();
xqtref_t type0 = GENV_TYPESYSTEM.create_type ( n0->getType(), TypeConstants::QUANT_ONE );
xqtref_t type1 = GENV_TYPESYSTEM.create_type ( n1->getType(), TypeConstants::QUANT_ONE );
if(GENV_TYPESYSTEM.is_subtype ( *type0, *GENV_TYPESYSTEM.DURATION_TYPE_ONE ) )
{
if(GENV_TYPESYSTEM.is_numeric(*type1))
{
if(GENV_TYPESYSTEM.is_equal( *type0, *GENV_TYPESYSTEM.YM_DURATION_TYPE_ONE) ||
GENV_TYPESYSTEM.is_equal( *type0, *GENV_TYPESYSTEM.DT_DURATION_TYPE_ONE))
{
n1 = GenericCast::instance()->cast ( n1, GENV_TYPESYSTEM.DOUBLE_TYPE_ONE );
return Operation::template compute<TypeConstants::XS_DURATION,TypeConstants::XS_DOUBLE> ( &aLoc, n0, n1 );
}
}
else
return Operation::template computeSingleType<TypeConstants::XS_DURATION> ( &aLoc, n0, n1 );
}
else if(GENV_TYPESYSTEM.is_subtype ( *type0, *GENV_TYPESYSTEM.DATETIME_TYPE_ONE ))
{
if(GENV_TYPESYSTEM.is_subtype ( *type1, *GENV_TYPESYSTEM.DATETIME_TYPE_ONE ))
return Operation::template compute<TypeConstants::XS_DATETIME,TypeConstants::XS_DATETIME> ( &aLoc, n0, n1 );
else
return Operation::template compute<TypeConstants::XS_DATETIME,TypeConstants::XS_DURATION> ( &aLoc, n0, n1 );
}
else if(GENV_TYPESYSTEM.is_subtype ( *type0, *GENV_TYPESYSTEM.DATE_TYPE_ONE ))
{
if(GENV_TYPESYSTEM.is_subtype ( *type1, *GENV_TYPESYSTEM.DATE_TYPE_ONE ))
return Operation::template compute<TypeConstants::XS_DATE,TypeConstants::XS_DATE> ( &aLoc, n0, n1 );
else
return Operation::template compute<TypeConstants::XS_DATE,TypeConstants::XS_DURATION> ( &aLoc, n0, n1 );
}
else if(GENV_TYPESYSTEM.is_subtype ( *type0, *GENV_TYPESYSTEM.TIME_TYPE_ONE ))
{
if(GENV_TYPESYSTEM.is_subtype ( *type1, *GENV_TYPESYSTEM.TIME_TYPE_ONE ))
return Operation::template compute<TypeConstants::XS_TIME,TypeConstants::XS_TIME> ( &aLoc, n0, n1 );
else
return Operation::template compute<TypeConstants::XS_TIME,TypeConstants::XS_DURATION> ( &aLoc, n0, n1 );
}
else if (( GENV_TYPESYSTEM.is_numeric(*type0)
|| GENV_TYPESYSTEM.is_numeric(*type1)
|| GENV_TYPESYSTEM.is_subtype(*type0, *GENV_TYPESYSTEM.UNTYPED_ATOMIC_TYPE_ONE)
|| GENV_TYPESYSTEM.is_subtype(*type1, *GENV_TYPESYSTEM.UNTYPED_ATOMIC_TYPE_ONE)))
{
return NumArithIterator<Operation>::computeAtomic(aLoc, n0, type0, n1, type1);
}
else
{
ZORBA_ERROR_ALERT(ZorbaError::XPTY0004,
NULL, DONT_CONTINUE_EXECUTION, "Arithmetic operation not defined between the given types(" + type0->toString() + " and " + type1->toString() + ").");
}
return 0;
}
/**
* Information: It is not possible to move this function to
* runtime/visitors/accept.cpp!
*/
template < class Operation >
void GenericArithIterator<Operation>::accept(PlanIterVisitor& v) const {
v.beginVisit(*this);
this->theChild0->accept(v);
this->theChild1->accept(v);
v.endVisit(*this);
}
// FIXME Why can the following template specializations not be moved to src/runtime/dateTime/DurationsDatesTimes.cpp?
//moved from DurationsDatesTimes
/* begin class AddOperations */
template<>
store::Item_t AddOperation::compute<TypeConstants::XS_DURATION,TypeConstants::XS_DURATION>
( const QueryLoc* loc, const store::Item* i0, const store::Item* i1 )
{
xqp_duration d = *i0->getDurationValue() + *i1->getDurationValue();
return Zorba::getItemFactory()->createDuration (d);
}
template<>
store::Item_t AddOperation::compute<TypeConstants::XS_DATETIME,TypeConstants::XS_DURATION>
( const QueryLoc* loc, const store::Item* i0, const store::Item* i1 )
{
xqp_dateTime d = *i0->getDateTimeValue() + *i1->getDurationValue()->toDuration();
return Zorba::getItemFactory()->createDateTime (d);
}
template<>
store::Item_t AddOperation::compute<TypeConstants::XS_DATE,TypeConstants::XS_DURATION>
( const QueryLoc* loc, const store::Item* i0, const store::Item* i1 )
{
xqp_date d = *i0->getDateValue() + *i1->getDurationValue()->toDuration();
return Zorba::getItemFactory()->createDate (d);
}
template<>
store::Item_t AddOperation::compute<TypeConstants::XS_TIME,TypeConstants::XS_DURATION>
( const QueryLoc* loc, const store::Item* i0, const store::Item* i1 )
{
xqp_time t = *i0->getTimeValue() + *i1->getDurationValue()->toDuration();
return Zorba::getItemFactory()->createTime (t);
}
/* end class AddOperations */
/* start class SubtractOperations */
template<>
store::Item_t SubtractOperation::compute<TypeConstants::XS_DURATION,TypeConstants::XS_DURATION>
( const QueryLoc* loc, const store::Item* i0, const store::Item* i1 )
{
xqp_duration d = *i0->getDurationValue() - *i1->getDurationValue();
return Zorba::getItemFactory()->createDuration (d);
}
template<>
store::Item_t SubtractOperation::compute<TypeConstants::XS_DATETIME,TypeConstants::XS_DURATION>
( const QueryLoc* loc, const store::Item* i0, const store::Item* i1 )
{
xqp_dateTime d = *i0->getDateTimeValue() + *i1->getDurationValue()->toNegDuration();
return Zorba::getItemFactory()->createDateTime (d);
}
template<>
store::Item_t SubtractOperation::compute<TypeConstants::XS_DATE,TypeConstants::XS_DURATION>
( const QueryLoc* loc, const store::Item* i0, const store::Item* i1 )
{
xqp_date d = *i0->getDateValue() + *i1->getDurationValue()->toNegDuration();
return Zorba::getItemFactory()->createDate (d);
}
template<>
store::Item_t SubtractOperation::compute<TypeConstants::XS_TIME,TypeConstants::XS_DURATION>
( const QueryLoc* loc, const store::Item* i0, const store::Item* i1 )
{
xqp_time t = *i0->getTimeValue() + *i1->getDurationValue()->toNegDuration();
return Zorba::getItemFactory()->createTime (t);
}
template<>
store::Item_t SubtractOperation::compute<TypeConstants::XS_DATETIME,TypeConstants::XS_DATETIME>
( const QueryLoc* loc, const store::Item* i0, const store::Item* i1 )
{
int timezone_secs = ZORBA_FOR_CURRENT_THREAD()->get_base_dynamic_context()->get_implicit_timezone();
xqp_duration d = *i0->getDateTimeValue()->normalizeTimeZone(timezone_secs) -
*i1->getDateTimeValue()->normalizeTimeZone(timezone_secs);
return Zorba::getItemFactory()->createDuration (d);
}
template<>
store::Item_t SubtractOperation::compute<TypeConstants::XS_DATE,TypeConstants::XS_DATE>
( const QueryLoc* loc, const store::Item* i0, const store::Item* i1 )
{
long timezone_sec = /*18000;*/ ZORBA_FOR_CURRENT_THREAD()->get_base_dynamic_context()->get_implicit_timezone();
xqp_duration d = *i0->getDateValue()->normalize(timezone_sec) - *i1->getDateValue()->normalize(timezone_sec);
return Zorba::getItemFactory()->createDuration (d);
}
template<>
store::Item_t SubtractOperation::compute<TypeConstants::XS_TIME,TypeConstants::XS_TIME>
( const QueryLoc* loc, const store::Item* i0, const store::Item* i1 )
{
long timezone_sec = /*-18000;*/ ZORBA_FOR_CURRENT_THREAD()->get_base_dynamic_context()->get_implicit_timezone();
xqp_duration d = *i0->getTimeValue()->normalize(timezone_sec) - * i1->getTimeValue()->normalize(timezone_sec);
return Zorba::getItemFactory()->createDuration (d);
}
/* end class SubtractOperations */
/* start class MultiplyOperations */
template<>
store::Item_t MultiplyOperation::compute<TypeConstants::XS_DURATION,TypeConstants::XS_DOUBLE>
( const QueryLoc* loc, const store::Item* i0, const store::Item* i1 )
{
xqp_duration d;
if( i1->getDoubleValue().isZero() )
{
xqtref_t type0 = GENV_TYPESYSTEM.create_type(i0->getType(), TypeConstants::QUANT_ONE);
if( GENV_TYPESYSTEM.is_subtype(*type0, *GENV_TYPESYSTEM.YM_DURATION_TYPE_ONE))
d = new YearMonthDuration();
else
d = new DayTimeDuration();
return Zorba::getItemFactory()->createDuration(d);
}
else if ( i1->getDoubleValue().isPosInf() || i1->getDoubleValue().isNegInf() )
ZORBA_ERROR_ALERT( ZorbaError::FODT0002, NULL, DONT_CONTINUE_EXECUTION, "Overflow/underflow in duration operation.");
else if ( i1->getDoubleValue().isNaN() )
ZORBA_ERROR_ALERT( ZorbaError::FOCA0005, NULL, DONT_CONTINUE_EXECUTION, "NaN supplied as float/double value");
else
d = *i0->getDurationValue() * (i1->getDoubleValue());
return Zorba::getItemFactory()->createDuration (d);
}
/* end class MultiplyOperations */
/* start class DivideOperations */
template<>
store::Item_t DivideOperation::compute<TypeConstants::XS_DURATION,TypeConstants::XS_DOUBLE>
( const QueryLoc* loc, const store::Item* i0, const store::Item* i1 )
{
xqp_duration d;
if( i1->getDoubleValue().isPosInf() || i1->getDoubleValue().isNegInf() )
{
xqtref_t type0 = GENV_TYPESYSTEM.create_type(i0->getType(), TypeConstants::QUANT_ONE);
if( GENV_TYPESYSTEM.is_subtype(*type0, *GENV_TYPESYSTEM.YM_DURATION_TYPE_ONE))
d = new YearMonthDuration();
else
d = new DayTimeDuration();
return Zorba::getItemFactory()->createDuration(d);
}
else if ( i1->getDoubleValue().isZero() )
ZORBA_ERROR_ALERT( ZorbaError::FODT0002, NULL, DONT_CONTINUE_EXECUTION, "Overflow/underflow in duration operation.");
else if ( i1->getDoubleValue().isNaN() )
ZORBA_ERROR_ALERT( ZorbaError::FOCA0005, NULL, DONT_CONTINUE_EXECUTION, "NaN supplied as float/double value");
else
d= *i0->getDurationValue() / i1->getDoubleValue();
return Zorba::getItemFactory()->createDuration (d);
}
template<>
store::Item_t DivideOperation::compute<TypeConstants::XS_DURATION,TypeConstants::XS_DURATION>
( const QueryLoc* loc, const store::Item* i0, const store::Item* i1 )
{
xqp_decimal d = *i0->getDurationValue() / *i1->getDurationValue();
return Zorba::getItemFactory()->createDecimal(d);
}
/* end class DivideOperations */
/* instantiate GenericArithIterator for all types */
template class GenericArithIterator<AddOperation>;
template class GenericArithIterator<SubtractOperation>;
template class GenericArithIterator<MultiplyOperation>;
template class GenericArithIterator<DivideOperation>;
template class GenericArithIterator<IntegerDivideOperation>;
template class GenericArithIterator<ModOperation>;
/* end class GenericArithIterator */
}
<commit_msg>Soved trac #278.<commit_after>#include <sstream>
#include <zorba/item.h>
#include "runtime/core/arithmetic_impl.h"
#include "errors/error_factory.h"
#include "system/globalenv.h"
#include "types/root_typemanager.h"
#include "types/casting.h"
#include "util/Assert.h"
#include "runtime/numerics/NumericsImpl.h"
#include "runtime/dateTime/DurationsDatesTimes.h"
#include "errors/error_factory.h"
#include "system/zorba.h"
#include "store/api/item_factory.h"
#include "system/zorba_engine.h"
#include "context/dynamic_context.h"
namespace zorba {
void ArithOperationsCommons::createError(
const char* aOp,
const QueryLoc* aLoc,
TypeConstants::atomic_type_code_t aType0,
TypeConstants::atomic_type_code_t aType1
)
{
AtomicXQType lAType0(aType0, TypeConstants::QUANT_ONE);
AtomicXQType lAType1(aType1, TypeConstants::QUANT_ONE);
std::stringstream lStream;
lStream << "The operation '";
lStream << aOp;
lStream << "' is not possible with parameters of the type ";
lAType0.serialize(lStream);
lStream << " and ";
lAType1.serialize(lStream);
lStream << "!";
ZORBA_ERROR_ALERT(
ZorbaError::XPTY0004,
aLoc,
DONT_CONTINUE_EXECUTION,
lStream.str()
);
}
/* begin class GenericArithIterator */
template< class Operations>
GenericArithIterator<Operations>::GenericArithIterator
( const QueryLoc& loc, PlanIter_t& iter0, PlanIter_t& iter1 )
:
BinaryBaseIterator<GenericArithIterator<Operations>, PlanIteratorState > ( loc, iter0, iter1 )
{ }
template < class Operation >
store::Item_t GenericArithIterator<Operation>::nextImpl ( PlanState& planState ) const
{
store::Item_t n0;
store::Item_t n1;
store::Item_t res;
PlanIteratorState* state;
DEFAULT_STACK_INIT ( PlanIteratorState, state, planState );
n0 = consumeNext( this->theChild0.getp(), planState );
if ( n0 != NULL )
{
n1 = consumeNext( this->theChild1.getp(), planState );
if ( n1 != NULL )
{
res = compute(this->loc, n0, n1);
if ( consumeNext(this->theChild0.getp(), planState ) != NULL
|| consumeNext(this->theChild1.getp(), planState ) != NULL )
ZORBA_ERROR_ALERT(ZorbaError::XPTY0004,
NULL, DONT_CONTINUE_EXECUTION, "Arithmetic operation has a sequences greater than one as an operator.");
STACK_PUSH ( res, state );
}
}
STACK_END();
}
template < class Operation >
store::Item_t GenericArithIterator<Operation>::compute(const QueryLoc& aLoc, store::Item_t n0, store::Item_t n1)
{
n0 = n0->getAtomizationValue();
n1 = n1->getAtomizationValue();
xqtref_t type0 = GENV_TYPESYSTEM.create_type ( n0->getType(), TypeConstants::QUANT_ONE );
xqtref_t type1 = GENV_TYPESYSTEM.create_type ( n1->getType(), TypeConstants::QUANT_ONE );
if(GENV_TYPESYSTEM.is_subtype ( *type0, *GENV_TYPESYSTEM.YM_DURATION_TYPE_ONE )
|| GENV_TYPESYSTEM.is_subtype ( *type0, *GENV_TYPESYSTEM.DT_DURATION_TYPE_ONE ))
{
if(GENV_TYPESYSTEM.is_numeric(*type1))
{
n1 = GenericCast::instance()->cast ( n1, GENV_TYPESYSTEM.DOUBLE_TYPE_ONE );
return Operation::template compute<TypeConstants::XS_DURATION,TypeConstants::XS_DOUBLE> ( &aLoc, n0, n1 );
}
else if(GENV_TYPESYSTEM.is_equal(*type0, *type1))
return Operation::template computeSingleType<TypeConstants::XS_DURATION> ( &aLoc, n0, n1 );
else
ZORBA_ERROR_ALERT(ZorbaError::XPTY0004,
NULL, DONT_CONTINUE_EXECUTION, "Arithmetic operation not defined between the given types(" + type0->toString() + " and " + type1->toString() + ").");
}
else if(GENV_TYPESYSTEM.is_subtype ( *type0, *GENV_TYPESYSTEM.DATETIME_TYPE_ONE ))
{
if(GENV_TYPESYSTEM.is_subtype ( *type1, *GENV_TYPESYSTEM.DATETIME_TYPE_ONE ))
return Operation::template compute<TypeConstants::XS_DATETIME,TypeConstants::XS_DATETIME> ( &aLoc, n0, n1 );
else
return Operation::template compute<TypeConstants::XS_DATETIME,TypeConstants::XS_DURATION> ( &aLoc, n0, n1 );
}
else if(GENV_TYPESYSTEM.is_subtype ( *type0, *GENV_TYPESYSTEM.DATE_TYPE_ONE ))
{
if(GENV_TYPESYSTEM.is_subtype ( *type1, *GENV_TYPESYSTEM.DATE_TYPE_ONE ))
return Operation::template compute<TypeConstants::XS_DATE,TypeConstants::XS_DATE> ( &aLoc, n0, n1 );
else
return Operation::template compute<TypeConstants::XS_DATE,TypeConstants::XS_DURATION> ( &aLoc, n0, n1 );
}
else if(GENV_TYPESYSTEM.is_subtype ( *type0, *GENV_TYPESYSTEM.TIME_TYPE_ONE ))
{
if(GENV_TYPESYSTEM.is_subtype ( *type1, *GENV_TYPESYSTEM.TIME_TYPE_ONE ))
return Operation::template compute<TypeConstants::XS_TIME,TypeConstants::XS_TIME> ( &aLoc, n0, n1 );
else
return Operation::template compute<TypeConstants::XS_TIME,TypeConstants::XS_DURATION> ( &aLoc, n0, n1 );
}
else if (
(GENV_TYPESYSTEM.is_numeric(*type0)
|| GENV_TYPESYSTEM.is_subtype(*type0, *GENV_TYPESYSTEM.UNTYPED_ATOMIC_TYPE_ONE))
&& ( GENV_TYPESYSTEM.is_numeric(*type1)
|| GENV_TYPESYSTEM.is_subtype(*type1, *GENV_TYPESYSTEM.UNTYPED_ATOMIC_TYPE_ONE))
)
{
return NumArithIterator<Operation>::computeAtomic(aLoc, n0, type0, n1, type1);
}
else
{
ZORBA_ERROR_ALERT(ZorbaError::XPTY0004,
NULL, DONT_CONTINUE_EXECUTION, "Arithmetic operation not defined between the given types(" + type0->toString() + " and " + type1->toString() + ").");
}
return 0;
}
/**
* Information: It is not possible to move this function to
* runtime/visitors/accept.cpp!
*/
template < class Operation >
void GenericArithIterator<Operation>::accept(PlanIterVisitor& v) const {
v.beginVisit(*this);
this->theChild0->accept(v);
this->theChild1->accept(v);
v.endVisit(*this);
}
// FIXME Why can the following template specializations not be moved to src/runtime/dateTime/DurationsDatesTimes.cpp?
//moved from DurationsDatesTimes
/* begin class AddOperations */
template<>
store::Item_t AddOperation::compute<TypeConstants::XS_DURATION,TypeConstants::XS_DURATION>
( const QueryLoc* loc, const store::Item* i0, const store::Item* i1 )
{
xqp_duration d = *i0->getDurationValue() + *i1->getDurationValue();
return Zorba::getItemFactory()->createDuration (d);
}
template<>
store::Item_t AddOperation::compute<TypeConstants::XS_DATETIME,TypeConstants::XS_DURATION>
( const QueryLoc* loc, const store::Item* i0, const store::Item* i1 )
{
xqp_dateTime d = *i0->getDateTimeValue() + *i1->getDurationValue()->toDuration();
return Zorba::getItemFactory()->createDateTime (d);
}
template<>
store::Item_t AddOperation::compute<TypeConstants::XS_DATE,TypeConstants::XS_DURATION>
( const QueryLoc* loc, const store::Item* i0, const store::Item* i1 )
{
xqp_date d = *i0->getDateValue() + *i1->getDurationValue()->toDuration();
return Zorba::getItemFactory()->createDate (d);
}
template<>
store::Item_t AddOperation::compute<TypeConstants::XS_TIME,TypeConstants::XS_DURATION>
( const QueryLoc* loc, const store::Item* i0, const store::Item* i1 )
{
xqp_time t = *i0->getTimeValue() + *i1->getDurationValue()->toDuration();
return Zorba::getItemFactory()->createTime (t);
}
/* end class AddOperations */
/* start class SubtractOperations */
template<>
store::Item_t SubtractOperation::compute<TypeConstants::XS_DURATION,TypeConstants::XS_DURATION>
( const QueryLoc* loc, const store::Item* i0, const store::Item* i1 )
{
xqp_duration d = *i0->getDurationValue() - *i1->getDurationValue();
return Zorba::getItemFactory()->createDuration (d);
}
template<>
store::Item_t SubtractOperation::compute<TypeConstants::XS_DATETIME,TypeConstants::XS_DURATION>
( const QueryLoc* loc, const store::Item* i0, const store::Item* i1 )
{
xqp_dateTime d = *i0->getDateTimeValue() + *i1->getDurationValue()->toNegDuration();
return Zorba::getItemFactory()->createDateTime (d);
}
template<>
store::Item_t SubtractOperation::compute<TypeConstants::XS_DATE,TypeConstants::XS_DURATION>
( const QueryLoc* loc, const store::Item* i0, const store::Item* i1 )
{
xqp_date d = *i0->getDateValue() + *i1->getDurationValue()->toNegDuration();
return Zorba::getItemFactory()->createDate (d);
}
template<>
store::Item_t SubtractOperation::compute<TypeConstants::XS_TIME,TypeConstants::XS_DURATION>
( const QueryLoc* loc, const store::Item* i0, const store::Item* i1 )
{
xqp_time t = *i0->getTimeValue() + *i1->getDurationValue()->toNegDuration();
return Zorba::getItemFactory()->createTime (t);
}
template<>
store::Item_t SubtractOperation::compute<TypeConstants::XS_DATETIME,TypeConstants::XS_DATETIME>
( const QueryLoc* loc, const store::Item* i0, const store::Item* i1 )
{
int timezone_secs = ZORBA_FOR_CURRENT_THREAD()->get_base_dynamic_context()->get_implicit_timezone();
xqp_duration d = *i0->getDateTimeValue()->normalizeTimeZone(timezone_secs) -
*i1->getDateTimeValue()->normalizeTimeZone(timezone_secs);
return Zorba::getItemFactory()->createDuration (d);
}
template<>
store::Item_t SubtractOperation::compute<TypeConstants::XS_DATE,TypeConstants::XS_DATE>
( const QueryLoc* loc, const store::Item* i0, const store::Item* i1 )
{
long timezone_sec = /*18000;*/ ZORBA_FOR_CURRENT_THREAD()->get_base_dynamic_context()->get_implicit_timezone();
xqp_duration d = *i0->getDateValue()->normalize(timezone_sec) - *i1->getDateValue()->normalize(timezone_sec);
return Zorba::getItemFactory()->createDuration (d);
}
template<>
store::Item_t SubtractOperation::compute<TypeConstants::XS_TIME,TypeConstants::XS_TIME>
( const QueryLoc* loc, const store::Item* i0, const store::Item* i1 )
{
long timezone_sec = /*-18000;*/ ZORBA_FOR_CURRENT_THREAD()->get_base_dynamic_context()->get_implicit_timezone();
xqp_duration d = *i0->getTimeValue()->normalize(timezone_sec) - * i1->getTimeValue()->normalize(timezone_sec);
return Zorba::getItemFactory()->createDuration (d);
}
/* end class SubtractOperations */
/* start class MultiplyOperations */
template<>
store::Item_t MultiplyOperation::compute<TypeConstants::XS_DURATION,TypeConstants::XS_DOUBLE>
( const QueryLoc* loc, const store::Item* i0, const store::Item* i1 )
{
xqp_duration d;
if( i1->getDoubleValue().isZero() )
{
xqtref_t type0 = GENV_TYPESYSTEM.create_type(i0->getType(), TypeConstants::QUANT_ONE);
if( GENV_TYPESYSTEM.is_subtype(*type0, *GENV_TYPESYSTEM.YM_DURATION_TYPE_ONE))
d = new YearMonthDuration();
else
d = new DayTimeDuration();
return Zorba::getItemFactory()->createDuration(d);
}
else if ( i1->getDoubleValue().isPosInf() || i1->getDoubleValue().isNegInf() )
ZORBA_ERROR_ALERT( ZorbaError::FODT0002, NULL, DONT_CONTINUE_EXECUTION, "Overflow/underflow in duration operation.");
else if ( i1->getDoubleValue().isNaN() )
ZORBA_ERROR_ALERT( ZorbaError::FOCA0005, NULL, DONT_CONTINUE_EXECUTION, "NaN supplied as float/double value");
else
d = *i0->getDurationValue() * (i1->getDoubleValue());
return Zorba::getItemFactory()->createDuration (d);
}
/* end class MultiplyOperations */
/* start class DivideOperations */
template<>
store::Item_t DivideOperation::compute<TypeConstants::XS_DURATION,TypeConstants::XS_DOUBLE>
( const QueryLoc* loc, const store::Item* i0, const store::Item* i1 )
{
xqp_duration d;
if( i1->getDoubleValue().isPosInf() || i1->getDoubleValue().isNegInf() )
{
xqtref_t type0 = GENV_TYPESYSTEM.create_type(i0->getType(), TypeConstants::QUANT_ONE);
if( GENV_TYPESYSTEM.is_subtype(*type0, *GENV_TYPESYSTEM.YM_DURATION_TYPE_ONE))
d = new YearMonthDuration();
else
d = new DayTimeDuration();
return Zorba::getItemFactory()->createDuration(d);
}
else if ( i1->getDoubleValue().isZero() )
ZORBA_ERROR_ALERT( ZorbaError::FODT0002, NULL, DONT_CONTINUE_EXECUTION, "Overflow/underflow in duration operation.");
else if ( i1->getDoubleValue().isNaN() )
ZORBA_ERROR_ALERT( ZorbaError::FOCA0005, NULL, DONT_CONTINUE_EXECUTION, "NaN supplied as float/double value");
else
d= *i0->getDurationValue() / i1->getDoubleValue();
return Zorba::getItemFactory()->createDuration (d);
}
template<>
store::Item_t DivideOperation::compute<TypeConstants::XS_DURATION,TypeConstants::XS_DURATION>
( const QueryLoc* loc, const store::Item* i0, const store::Item* i1 )
{
xqp_decimal d = *i0->getDurationValue() / *i1->getDurationValue();
return Zorba::getItemFactory()->createDecimal(d);
}
/* end class DivideOperations */
/* instantiate GenericArithIterator for all types */
template class GenericArithIterator<AddOperation>;
template class GenericArithIterator<SubtractOperation>;
template class GenericArithIterator<MultiplyOperation>;
template class GenericArithIterator<DivideOperation>;
template class GenericArithIterator<IntegerDivideOperation>;
template class GenericArithIterator<ModOperation>;
/* end class GenericArithIterator */
}
<|endoftext|> |
<commit_before>/*
* Copyright 2006-2008 The FLWOR Foundation.
*
* 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 <zorba/item.h>
#include <zorba/item_sequence.h>
#include <zorba/stateless_function.h>
#include "zorbaerrors/error_manager.h"
#include "runtime/core/var_iterators.h"
#include "runtime/core/fncall_iterator.h"
#include "runtime/misc/MiscImpl.h" // for ExitException
#include "runtime/api/plan_iterator_wrapper.h"
#include "functions/function.h"
#include "api/unmarshaller.h"
namespace zorba {
UDFunctionCallIteratorState::UDFunctionCallIteratorState()
:
theFnBodyStateBlock(NULL),
thePlan(NULL),
thePlanStateSize(0),
thePlanOpen(false)
{
}
UDFunctionCallIteratorState::~UDFunctionCallIteratorState()
{
}
void UDFunctionCallIteratorState::openPlan()
{
uint32_t planOffset = 0;
if (!thePlanOpen) {
thePlan->open(*theFnBodyStateBlock, planOffset);
}
thePlanOpen = true;
}
void UDFunctionCallIteratorState::closePlan()
{
if (thePlanOpen) {
thePlan->close(*theFnBodyStateBlock);
}
thePlanOpen = false;
}
void UDFunctionCallIteratorState::resetPlan()
{
if (thePlanOpen) {
thePlan->reset(*theFnBodyStateBlock);
}
}
void UDFunctionCallIteratorState::resetChildIters()
{
std::vector<store::Iterator_t>::const_iterator lIter = theChildIterators.begin();
std::vector<store::Iterator_t>::const_iterator lEnd = theChildIterators.end();
for ( ; lIter != lEnd; ++lIter)
(*lIter)->close();
theChildIterators.clear();
}
bool UDFunctionCallIterator::isUpdating() const
{
return theUDF->isUpdating();
}
void UDFunctionCallIterator::openImpl(PlanState& planState, uint32_t& offset)
{
NaryBaseIterator<UDFunctionCallIterator, UDFunctionCallIteratorState>::openImpl(planState, offset);
UDFunctionCallIteratorState *state = StateTraitsImpl<UDFunctionCallIteratorState>::getState(planState, this->stateOffset);
state->thePlan = theUDF->get_plan(planState.theCompilerCB).getp();
state->thePlanStateSize = state->thePlan->getStateSizeOfSubtree();
state->theFnBodyStateBlock = new PlanState(state->thePlanStateSize, planState.theStackDepth + 1);
state->theFnBodyStateBlock->checkDepth (loc);
state->theFnBodyStateBlock->theRuntimeCB = planState.theRuntimeCB;
state->theFnBodyStateBlock->theCompilerCB = planState.theCompilerCB;
}
void UDFunctionCallIterator::closeImpl(PlanState& planState)
{
UDFunctionCallIteratorState *state = StateTraitsImpl<UDFunctionCallIteratorState>::getState(planState, this->stateOffset);
state->closePlan();
delete state->theFnBodyStateBlock;
state->resetChildIters();
NaryBaseIterator<UDFunctionCallIterator, UDFunctionCallIteratorState>::closeImpl(planState);
}
void UDFunctionCallIterator::resetImpl(PlanState& planState) const
{
NaryBaseIterator<UDFunctionCallIterator, UDFunctionCallIteratorState>::resetImpl(planState);
UDFunctionCallIteratorState *state = StateTraitsImpl<UDFunctionCallIteratorState>::getState(planState, this->stateOffset);
state->resetPlan();
state->resetChildIters();
}
bool UDFunctionCallIterator::nextImpl(store::Item_t& result, PlanState& planState) const
{
UDFunctionCallIteratorState *state;
bool success;
DEFAULT_STACK_INIT(UDFunctionCallIteratorState, state, planState);
{
// Bind the args.
state->openPlan();
std::vector<LetVarIter_t>& iters = theUDF->get_param_iters();
for (uint32_t i = 0; i < iters.size (); ++i)
{
LetVarIter_t& ref = iters[i];
if ( ref != NULL)
{
state->theChildIterators.push_back(new PlanIteratorWrapper(theChildren[i], planState));
state->theChildIterators.back()->open();
ref->bind(state->theChildIterators.back(), *state->theFnBodyStateBlock);
}
}
}
for (;;) {
try {
success = consumeNext (result, state->thePlan, *state->theFnBodyStateBlock);
} catch (FlowCtlIterator::ExitException &e) {
state->exitValue = e.val;
success = false;
}
if (success)
STACK_PUSH(true, state);
else break;
}
if (state->exitValue != NULL)
while (state->exitValue->next (result))
STACK_PUSH(true, state);
STACK_END (state);
}
// external functions
class ExtFuncArgItemSequence : public ItemSequence
{
public:
ExtFuncArgItemSequence(PlanIter_t child, PlanState& stateBlock)
: m_child(child),
m_stateBlock(stateBlock) { }
bool next(Item& item)
{
store::Item_t result;
bool status = m_child->consumeNext(result, m_child.getp(), m_stateBlock);
item = status ? result : NULL;
return status;
}
private:
PlanIter_t m_child;
PlanState& m_stateBlock;
};
StatelessExtFunctionCallIteratorState::StatelessExtFunctionCallIteratorState() { }
StatelessExtFunctionCallIteratorState::~StatelessExtFunctionCallIteratorState() { }
void StatelessExtFunctionCallIteratorState::reset(PlanState& planState)
{
PlanIteratorState::reset(planState);
m_result.reset();
}
StatelessExtFunctionCallIterator::StatelessExtFunctionCallIterator(const QueryLoc& loc,
std::vector<PlanIter_t>& args,
const StatelessExternalFunction *function,
bool aIsUpdating)
:
NaryBaseIterator<StatelessExtFunctionCallIterator,
StatelessExtFunctionCallIteratorState>(loc, args),
m_function(function),
theIsUpdating(aIsUpdating)
{
}
void StatelessExtFunctionCallIterator::openImpl(PlanState& planState, uint32_t& offset)
{
NaryBaseIterator<StatelessExtFunctionCallIterator,
StatelessExtFunctionCallIteratorState>::openImpl(planState, offset);
StatelessExtFunctionCallIteratorState
*state = StateTraitsImpl<StatelessExtFunctionCallIteratorState>::getState(planState,
this->stateOffset);
int n = theChildren.size();
state->m_extArgs.resize(n);
for(int i = 0; i < n; ++i)
{
state->m_extArgs[i] = new ExtFuncArgItemSequence(theChildren[i], planState);
}
}
bool StatelessExtFunctionCallIterator::nextImpl(store::Item_t& result, PlanState& planState) const
{
StatelessExtFunctionCallIteratorState *state;
Item lOutsideItem;
DEFAULT_STACK_INIT(StatelessExtFunctionCallIteratorState, state, planState);
state->m_result = m_function->evaluate(state->m_extArgs);
while (state->m_result->next(lOutsideItem))
{
result = Unmarshaller::getInternalItem(lOutsideItem);
if (theIsUpdating)
{
if (!result->isPul())
{
ZORBA_ERROR_LOC(XUDY0019, loc);
}
}
else
{
if (result->isPul())
{
ZORBA_ERROR_LOC(XUDY0018, loc);
}
}
STACK_PUSH(true, state);
}
STACK_END (state);
}
void StatelessExtFunctionCallIterator::closeImpl(PlanState& planState)
{
StatelessExtFunctionCallIteratorState *state =
StateTraitsImpl<StatelessExtFunctionCallIteratorState>::getState(planState, this->stateOffset);
// we have the ownership for the item sequences
int n = theChildren.size();
for(int i = 0; i < n; ++i) {
delete state->m_extArgs[i];
}
NaryBaseIterator<StatelessExtFunctionCallIterator,
StatelessExtFunctionCallIteratorState>::closeImpl(planState);
}
}
/* vim:set ts=2 sw=2: */
<commit_msg>Added error reporting ability to external functions<commit_after>/*
* Copyright 2006-2008 The FLWOR Foundation.
*
* 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 <zorba/item.h>
#include <zorba/item_sequence.h>
#include <zorba/stateless_function.h>
#include <zorba/exception.h>
#include "zorbaerrors/error_manager.h"
#include "runtime/core/var_iterators.h"
#include "runtime/core/fncall_iterator.h"
#include "runtime/misc/MiscImpl.h" // for ExitException
#include "runtime/api/plan_iterator_wrapper.h"
#include "functions/function.h"
#include "api/unmarshaller.h"
namespace zorba {
UDFunctionCallIteratorState::UDFunctionCallIteratorState()
:
theFnBodyStateBlock(NULL),
thePlan(NULL),
thePlanStateSize(0),
thePlanOpen(false)
{
}
UDFunctionCallIteratorState::~UDFunctionCallIteratorState()
{
}
void UDFunctionCallIteratorState::openPlan()
{
uint32_t planOffset = 0;
if (!thePlanOpen) {
thePlan->open(*theFnBodyStateBlock, planOffset);
}
thePlanOpen = true;
}
void UDFunctionCallIteratorState::closePlan()
{
if (thePlanOpen) {
thePlan->close(*theFnBodyStateBlock);
}
thePlanOpen = false;
}
void UDFunctionCallIteratorState::resetPlan()
{
if (thePlanOpen) {
thePlan->reset(*theFnBodyStateBlock);
}
}
void UDFunctionCallIteratorState::resetChildIters()
{
std::vector<store::Iterator_t>::const_iterator lIter = theChildIterators.begin();
std::vector<store::Iterator_t>::const_iterator lEnd = theChildIterators.end();
for ( ; lIter != lEnd; ++lIter)
(*lIter)->close();
theChildIterators.clear();
}
bool UDFunctionCallIterator::isUpdating() const
{
return theUDF->isUpdating();
}
void UDFunctionCallIterator::openImpl(PlanState& planState, uint32_t& offset)
{
NaryBaseIterator<UDFunctionCallIterator, UDFunctionCallIteratorState>::openImpl(planState, offset);
UDFunctionCallIteratorState *state = StateTraitsImpl<UDFunctionCallIteratorState>::getState(planState, this->stateOffset);
state->thePlan = theUDF->get_plan(planState.theCompilerCB).getp();
state->thePlanStateSize = state->thePlan->getStateSizeOfSubtree();
state->theFnBodyStateBlock = new PlanState(state->thePlanStateSize, planState.theStackDepth + 1);
state->theFnBodyStateBlock->checkDepth (loc);
state->theFnBodyStateBlock->theRuntimeCB = planState.theRuntimeCB;
state->theFnBodyStateBlock->theCompilerCB = planState.theCompilerCB;
}
void UDFunctionCallIterator::closeImpl(PlanState& planState)
{
UDFunctionCallIteratorState *state = StateTraitsImpl<UDFunctionCallIteratorState>::getState(planState, this->stateOffset);
state->closePlan();
delete state->theFnBodyStateBlock;
state->resetChildIters();
NaryBaseIterator<UDFunctionCallIterator, UDFunctionCallIteratorState>::closeImpl(planState);
}
void UDFunctionCallIterator::resetImpl(PlanState& planState) const
{
NaryBaseIterator<UDFunctionCallIterator, UDFunctionCallIteratorState>::resetImpl(planState);
UDFunctionCallIteratorState *state = StateTraitsImpl<UDFunctionCallIteratorState>::getState(planState, this->stateOffset);
state->resetPlan();
state->resetChildIters();
}
bool UDFunctionCallIterator::nextImpl(store::Item_t& result, PlanState& planState) const
{
UDFunctionCallIteratorState *state;
bool success;
DEFAULT_STACK_INIT(UDFunctionCallIteratorState, state, planState);
{
// Bind the args.
state->openPlan();
std::vector<LetVarIter_t>& iters = theUDF->get_param_iters();
for (uint32_t i = 0; i < iters.size (); ++i)
{
LetVarIter_t& ref = iters[i];
if ( ref != NULL)
{
state->theChildIterators.push_back(new PlanIteratorWrapper(theChildren[i], planState));
state->theChildIterators.back()->open();
ref->bind(state->theChildIterators.back(), *state->theFnBodyStateBlock);
}
}
}
for (;;) {
try {
success = consumeNext (result, state->thePlan, *state->theFnBodyStateBlock);
} catch (FlowCtlIterator::ExitException &e) {
state->exitValue = e.val;
success = false;
}
if (success)
STACK_PUSH(true, state);
else break;
}
if (state->exitValue != NULL)
while (state->exitValue->next (result))
STACK_PUSH(true, state);
STACK_END (state);
}
// external functions
class ExtFuncArgItemSequence : public ItemSequence
{
public:
ExtFuncArgItemSequence(PlanIter_t child, PlanState& stateBlock)
: m_child(child),
m_stateBlock(stateBlock) { }
bool next(Item& item)
{
store::Item_t result;
bool status = m_child->consumeNext(result, m_child.getp(), m_stateBlock);
item = status ? result : NULL;
return status;
}
private:
PlanIter_t m_child;
PlanState& m_stateBlock;
};
StatelessExtFunctionCallIteratorState::StatelessExtFunctionCallIteratorState() { }
StatelessExtFunctionCallIteratorState::~StatelessExtFunctionCallIteratorState() { }
void StatelessExtFunctionCallIteratorState::reset(PlanState& planState)
{
PlanIteratorState::reset(planState);
m_result.reset();
}
StatelessExtFunctionCallIterator::StatelessExtFunctionCallIterator(const QueryLoc& loc,
std::vector<PlanIter_t>& args,
const StatelessExternalFunction *function,
bool aIsUpdating)
:
NaryBaseIterator<StatelessExtFunctionCallIterator,
StatelessExtFunctionCallIteratorState>(loc, args),
m_function(function),
theIsUpdating(aIsUpdating)
{
}
void StatelessExtFunctionCallIterator::openImpl(PlanState& planState, uint32_t& offset)
{
NaryBaseIterator<StatelessExtFunctionCallIterator,
StatelessExtFunctionCallIteratorState>::openImpl(planState, offset);
StatelessExtFunctionCallIteratorState
*state = StateTraitsImpl<StatelessExtFunctionCallIteratorState>::getState(planState,
this->stateOffset);
int n = theChildren.size();
state->m_extArgs.resize(n);
for(int i = 0; i < n; ++i)
{
state->m_extArgs[i] = new ExtFuncArgItemSequence(theChildren[i], planState);
}
}
bool StatelessExtFunctionCallIterator::nextImpl(store::Item_t& result, PlanState& planState) const
{
StatelessExtFunctionCallIteratorState *state;
Item lOutsideItem;
DEFAULT_STACK_INIT(StatelessExtFunctionCallIteratorState, state, planState);
try {
state->m_result = m_function->evaluate(state->m_extArgs);
} catch(const ZorbaException& e) {
ZORBA_ERROR_LOC(e.getErrorCode(), loc);
}
while (true)
{
try {
if (!state->m_result->next(lOutsideItem)) {
break;
}
} catch(const ZorbaException& e) {
ZORBA_ERROR_LOC(e.getErrorCode(), loc);
}
result = Unmarshaller::getInternalItem(lOutsideItem);
if (theIsUpdating)
{
if (!result->isPul())
{
ZORBA_ERROR_LOC(XUDY0019, loc);
}
}
else
{
if (result->isPul())
{
ZORBA_ERROR_LOC(XUDY0018, loc);
}
}
STACK_PUSH(true, state);
}
STACK_END (state);
}
void StatelessExtFunctionCallIterator::closeImpl(PlanState& planState)
{
StatelessExtFunctionCallIteratorState *state =
StateTraitsImpl<StatelessExtFunctionCallIteratorState>::getState(planState, this->stateOffset);
// we have the ownership for the item sequences
int n = theChildren.size();
for(int i = 0; i < n; ++i) {
delete state->m_extArgs[i];
}
NaryBaseIterator<StatelessExtFunctionCallIterator,
StatelessExtFunctionCallIteratorState>::closeImpl(planState);
}
}
/* vim:set ts=2 sw=2: */
<|endoftext|> |
<commit_before>/********************************************************************
* AUTHORS: Vijay Ganesh
*
* BEGIN DATE: November, 2005
*
* LICENSE: Please view LICENSE file in the home dir of this Program
********************************************************************/
// -*- c++ -*-
#include "../AST/AST.h"
namespace BEEV
{
//some global variables that are set through commandline options. it
//is best that these variables remain global. Default values set
//here
//
//collect statistics on certain functions
bool stats_flag = false;
//print DAG nodes
bool print_nodes_flag = false;
//run STP in optimized mode
bool optimize_flag = true;
//do sat refinement, i.e. underconstraint the problem, and feed to
//SAT. if this works, great. else, add a set of suitable constraints
//to re-constraint the problem correctly, and call SAT again, until
//all constraints have been added.
bool arrayread_refinement_flag = true;
//flag to control write refinement
bool arraywrite_refinement_flag = true;
//check the counterexample against the original input to STP
bool check_counterexample_flag = false;
//construct the counterexample in terms of original variable based
//on the counterexample returned by SAT solver
bool construct_counterexample_flag = true;
bool print_counterexample_flag = false;
bool print_binary_flag = false;
//if this option is true then print the way dawson wants using a
//different printer. do not use this printer.
bool print_arrayval_declaredorder_flag = false;
//flag to decide whether to print "valid/invalid" or not
bool print_output_flag = false;
//print the variable order chosen by the sat solver while it is
//solving.
bool print_sat_varorder_flag = false;
//turn on word level bitvector solver
bool wordlevel_solve_flag = true;
//turn off XOR flattening
bool xor_flatten_flag = false;
//Flag to switch on the smtlib parser
bool smtlib_parser_flag = false;
//print the input back
bool print_STPinput_back_flag = false;
// If enabled. division, mod and remainder by zero will evaluate to
// 1.
bool division_by_zero_returns_one = false;
enum inputStatus input_status = NOT_DECLARED;
//global BEEVMGR for the parser
BeevMgr * GlobalBeevMgr;
void (*vc_error_hdlr)(const char* err_msg) = NULL;
/** This is reusable empty vector, for representing empty children
arrays */
ASTVec _empty_ASTVec;
//Some global vars for the Main function.
const std::string version = "$Id: main.cpp 174 2009-09-03 19:22:47Z vijay_ganesh $";
const char * prog = "stp";
int linenum = 1;
const char * usage = "Usage: %s [-option] [infile]\n";
std::string helpstring = "\n\n";
}; //end of namespace BEEV
<commit_msg>Adding SVN property to replace $Id$ with the version number<commit_after>/********************************************************************
* AUTHORS: Vijay Ganesh
*
* BEGIN DATE: November, 2005
*
* LICENSE: Please view LICENSE file in the home dir of this Program
********************************************************************/
// -*- c++ -*-
#include "../AST/AST.h"
namespace BEEV
{
//some global variables that are set through commandline options. it
//is best that these variables remain global. Default values set
//here
//
//collect statistics on certain functions
bool stats_flag = false;
//print DAG nodes
bool print_nodes_flag = false;
//run STP in optimized mode
bool optimize_flag = true;
//do sat refinement, i.e. underconstraint the problem, and feed to
//SAT. if this works, great. else, add a set of suitable constraints
//to re-constraint the problem correctly, and call SAT again, until
//all constraints have been added.
bool arrayread_refinement_flag = true;
//flag to control write refinement
bool arraywrite_refinement_flag = true;
//check the counterexample against the original input to STP
bool check_counterexample_flag = false;
//construct the counterexample in terms of original variable based
//on the counterexample returned by SAT solver
bool construct_counterexample_flag = true;
bool print_counterexample_flag = false;
bool print_binary_flag = false;
//if this option is true then print the way dawson wants using a
//different printer. do not use this printer.
bool print_arrayval_declaredorder_flag = false;
//flag to decide whether to print "valid/invalid" or not
bool print_output_flag = false;
//print the variable order chosen by the sat solver while it is
//solving.
bool print_sat_varorder_flag = false;
//turn on word level bitvector solver
bool wordlevel_solve_flag = true;
//turn off XOR flattening
bool xor_flatten_flag = false;
//Flag to switch on the smtlib parser
bool smtlib_parser_flag = false;
//print the input back
bool print_STPinput_back_flag = false;
// If enabled. division, mod and remainder by zero will evaluate to
// 1.
bool division_by_zero_returns_one = false;
enum inputStatus input_status = NOT_DECLARED;
//global BEEVMGR for the parser
BeevMgr * GlobalBeevMgr;
void (*vc_error_hdlr)(const char* err_msg) = NULL;
/** This is reusable empty vector, for representing empty children
arrays */
ASTVec _empty_ASTVec;
//Some global vars for the Main function.
const std::string version = "$Id$";
const char * prog = "stp";
int linenum = 1;
const char * usage = "Usage: %s [-option] [infile]\n";
std::string helpstring = "\n\n";
}; //end of namespace BEEV
<|endoftext|> |
<commit_before>#include <stdint.h>
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
#include <time.h>
#include <math.h>
// stochasticPerfectHash
// Uses stochastic remainder sampling to derive a Pearson mixing table for small sets of alphabetic keys
// orthopteroid@gmail.com
// g++ -std=c++0x -O3 -lrt sph.cpp -o sph
//
// for background, read:
// http://cs.mwsu.edu/~griffin/courses/2133/downloads/Spring11/p677-pearson.pdf
// stochastic remainder sampler
size_t sample( uint8_t* counts, uint32_t sum )
{
int32_t target = rand() % sum;
size_t i = 0;
while( (target -= counts[ i ]) > 0 ) { i++; }
return i;
}
// calculates a mixtable for the pearson hash to create a perfect hash.
// restrictions are keys can only be ascii lowercase, but can be of any length.
// keys are seperated in the input string using the ! delimiter. ! must also be at end of string.
size_t calcMixTable( char* sz )
{
const size_t MAXITER = 25000;
// special marker '!' in the string designates the end of a key
size_t keyCount = 0;
for( size_t i=0;sz[i];i++ ) { if( sz[i] == '!' ) { keyCount++; } }
bool hashed[ keyCount ];
// the defualt mix table is a null transform
uint8_t mix[32] = {0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31};
// these weights influence convergence rate.
// they are used by the stochastic sampling method that adjusts the mixing table to resolve hash collisions
const uint8_t DEFAULT = 1;
const uint8_t SIGNAL = 100;
// reset flags...
size_t iterations = 0;
do {
// counts will track mix table usage each iteration we evaluate the hashed
uint8_t counts[32];
for( size_t i=0;i<32;i++ ) { counts[i] = DEFAULT; }
for( size_t i=0;i<keyCount;i++ ) { hashed[i] = false; }
// compute the pearson hash using the current mix table.
uint8_t hash = 0;
bool collision = false;
for( size_t i=0;sz[i];i++ )
{
if( sz[i] == '!' ) // end of key detected
{
size_t j = hash % keyCount; // mod with keyCount as we are trying to find the perfect hash function;
if( hashed[ j ] ) { collision = true; }
hashed[ j ] = true;
hash = 0;
}
else
{
uint8_t j = 31 & ( hash ^ ( sz[i] - 'a' ) );
hash = mix[ j ];
counts[ j ] = SIGNAL; // inc the mix item that was used to compute the hashs this iteration.
}
}
if( !collision ) { break; }
// calc sum and swap items
uint32_t countsum = 0;
for( size_t i=0;i<32;i++ ) { countsum += counts[i]; }
size_t i = sample( counts, countsum ); // select item i.
countsum -= counts[i]; counts[i] = 0; // remove from possible selection set
size_t j = sample( counts, countsum ); // select item j
uint8_t t = mix[i]; mix[i] = mix[j]; mix[j] = t; // swap i and j
} while( ++iterations < MAXITER );
if( iterations < MAXITER )
{ printf("uint_8 mix[] = {"); for( size_t i=0;i<32;i++ ) { printf("%d, ",mix[i]); } printf("};\n"); }
else
{ printf("ack! can't do it.\n"); }
return iterations;
}
int main()
{
time_t ltime;
time(<ime);
srand((unsigned int)ltime);
char buf[1000]; // a fixed buffer for a sequence of keys we wish to perfect-hash
for( size_t k=0;k<10;k++)
{
const size_t keyCount = 10;
size_t pos = 0;
for( size_t i=0;i<keyCount;i++)
{
// keys are all ascii lowsercase
const size_t keyLength = 10;
for( size_t j=0;j<keyLength;j++) { buf[ pos++ ] = 'a' + rand() % 26; }
// keys end with special '!' char
buf[ pos++ ] = '!';
}
buf[ pos ] = 0; // zero term buffer
printf("Finding mix table for %s:\n", buf);
size_t iter = calcMixTable( buf );
printf("Took %lu iterations\n",iter);
}
return 0;
}
<commit_msg>short int rand fixup<commit_after>#include <stdint.h>
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
#include <time.h>
#include <math.h>
// stochasticPerfectHash
// Uses stochastic remainder sampling to derive a Pearson mixing table for small sets of alphabetic keys
// orthopteroid@gmail.com
// g++ -std=c++0x -O3 -lrt sph.cpp -o sph
//
// for background, read:
// http://cs.mwsu.edu/~griffin/courses/2133/downloads/Spring11/p677-pearson.pdf
// stochastic remainder sampler
size_t sample( uint8_t* counts, uint32_t sum )
{
int32_t target = (((int32_t)rand() << 20) + ((int32_t)rand() << 10) + (int32_t)rand()) % sum; // impl fix for short int rand()
size_t i = 0;
while( (target -= counts[ i ]) > 0 ) { i++; }
return i;
}
// calculates a mixtable for the pearson hash to create a perfect hash.
// restrictions are keys can only be ascii lowercase, but can be of any length.
// keys are seperated in the input string using the ! delimiter. ! must also be at end of string.
size_t calcMixTable( char* sz )
{
const size_t MAXITER = 25000;
// special marker '!' in the string designates the end of a key
size_t keyCount = 0;
for( size_t i=0;sz[i];i++ ) { if( sz[i] == '!' ) { keyCount++; } }
bool hashed[ keyCount ];
// the defualt mix table is a null transform
uint8_t mix[32] = {0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31};
// these weights influence convergence rate.
// they are used by the stochastic sampling method that adjusts the mixing table to resolve hash collisions
const uint8_t DEFAULT = 1;
const uint8_t SIGNAL = 100;
// reset flags...
size_t iterations = 0;
do {
// counts will track mix table usage each iteration we evaluate the hashed
uint8_t counts[32];
for( size_t i=0;i<32;i++ ) { counts[i] = DEFAULT; }
for( size_t i=0;i<keyCount;i++ ) { hashed[i] = false; }
// compute the pearson hash using the current mix table.
uint8_t hash = 0;
bool collision = false;
for( size_t i=0;sz[i];i++ )
{
if( sz[i] == '!' ) // end of key detected
{
size_t j = hash % keyCount; // mod with keyCount as we are trying to find the perfect hash function;
if( hashed[ j ] ) { collision = true; }
hashed[ j ] = true;
hash = 0;
}
else
{
uint8_t j = 31 & ( hash ^ ( sz[i] - 'a' ) );
hash = mix[ j ];
counts[ j ] = SIGNAL; // inc the mix item that was used to compute the hashs this iteration.
}
}
if( !collision ) { break; }
// calc sum and swap items
uint32_t countsum = 0;
for( size_t i=0;i<32;i++ ) { countsum += counts[i]; }
size_t i = sample( counts, countsum ); // select item i.
countsum -= counts[i]; counts[i] = 0; // remove from possible selection set
size_t j = sample( counts, countsum ); // select item j
uint8_t t = mix[i]; mix[i] = mix[j]; mix[j] = t; // swap i and j
} while( ++iterations < MAXITER );
if( iterations < MAXITER )
{ printf("uint_8 mix[] = {"); for( size_t i=0;i<32;i++ ) { printf("%d, ",mix[i]); } printf("};\n"); }
else
{ printf("ack! can't do it.\n"); }
return iterations;
}
int main()
{
time_t ltime;
time(<ime);
srand((unsigned int)ltime);
char buf[1000]; // a fixed buffer for a sequence of keys we wish to perfect-hash
for( size_t k=0;k<10;k++)
{
const size_t keyCount = 10;
size_t pos = 0;
for( size_t i=0;i<keyCount;i++)
{
// keys are all ascii lowsercase
const size_t keyLength = 10;
for( size_t j=0;j<keyLength;j++) { buf[ pos++ ] = 'a' + rand() % 26; }
// keys end with special '!' char
buf[ pos++ ] = '!';
}
buf[ pos ] = 0; // zero term buffer
printf("Finding mix table for %s:\n", buf);
size_t iter = calcMixTable( buf );
printf("Took %lu iterations\n",iter);
}
return 0;
}
<|endoftext|> |
<commit_before>#ifndef __NODE_MAPNIK_FONTS_H__
#define __NODE_MAPNIK_FONTS_H__
// v8
#include <v8.h>
// node
#include <node.h>
// mapnik
#include <mapnik/font_engine_freetype.hpp>
// stl
#include <vector>
#include "utils.hpp"
using namespace v8;
using namespace node;
namespace node_mapnik {
static inline Handle<Value> register_fonts(const Arguments& args)
{
HandleScope scope;
try
{
if (!args.Length() >= 1 || !args[0]->IsString())
return ThrowException(Exception::TypeError(
String::New("first argument must be a path to a directory of fonts")));
bool found = false;
std::vector<std::string> const names_before = mapnik::freetype_engine::face_names();
// option hash
if (args.Length() == 2){
if (!args[1]->IsObject())
return ThrowException(Exception::TypeError(
String::New("second argument is optional, but if provided must be an object, eg. { recurse:Boolean }")));
Local<Object> options = args[1]->ToObject();
if (options->Has(String::New("recurse")))
{
Local<Value> recurse_opt = options->Get(String::New("recurse"));
if (!recurse_opt->IsBoolean())
return ThrowException(Exception::TypeError(
String::New("'recurse' must be a Boolean")));
bool recurse = recurse_opt->BooleanValue();
std::string const& path = TOSTR(args[0]);
found = mapnik::freetype_engine::register_fonts(path,recurse);
}
}
else
{
std::string const& path = TOSTR(args[0]);
found = mapnik::freetype_engine::register_fonts(path);
}
std::vector<std::string> const& names_after = mapnik::freetype_engine::face_names();
if (names_after.size() == names_before.size())
found = false;
return scope.Close(Boolean::New(found));
}
catch (const std::exception & ex)
{
return ThrowException(Exception::Error(
String::New(ex.what())));
}
}
static inline Handle<Value> available_font_faces(const Arguments& args)
{
HandleScope scope;
std::vector<std::string> const& names = mapnik::freetype_engine::face_names();
Local<Array> a = Array::New(names.size());
for (unsigned i = 0; i < names.size(); ++i)
{
a->Set(i, String::New(names[i].c_str()));
}
return scope.Close(a);
}
static inline Handle<Value> available_font_files(const Arguments& args)
{
HandleScope scope;
std::map<std::string,std::string> const& mapping = mapnik::freetype_engine::get_mapping();
Local<Object> obj = Object::New();
std::map<std::string,std::string>::const_iterator itr;
for (itr = mapping.begin();itr!=mapping.end();++itr)
{
obj->Set(String::NewSymbol(itr->first.c_str()),String::New(itr->second.c_str()));
}
return scope.Close(obj);
}
}
#endif // __NODE_MAPNIK_FONTS_H__
<commit_msg>upgrade to new mapnik::freetype_engine::get_mapping signature<commit_after>#ifndef __NODE_MAPNIK_FONTS_H__
#define __NODE_MAPNIK_FONTS_H__
// v8
#include <v8.h>
// node
#include <node.h>
// mapnik
#include <mapnik/font_engine_freetype.hpp>
// stl
#include <vector>
#include "utils.hpp"
using namespace v8;
using namespace node;
namespace node_mapnik {
static inline Handle<Value> register_fonts(const Arguments& args)
{
HandleScope scope;
try
{
if (!args.Length() >= 1 || !args[0]->IsString())
return ThrowException(Exception::TypeError(
String::New("first argument must be a path to a directory of fonts")));
bool found = false;
std::vector<std::string> const names_before = mapnik::freetype_engine::face_names();
// option hash
if (args.Length() == 2){
if (!args[1]->IsObject())
return ThrowException(Exception::TypeError(
String::New("second argument is optional, but if provided must be an object, eg. { recurse:Boolean }")));
Local<Object> options = args[1]->ToObject();
if (options->Has(String::New("recurse")))
{
Local<Value> recurse_opt = options->Get(String::New("recurse"));
if (!recurse_opt->IsBoolean())
return ThrowException(Exception::TypeError(
String::New("'recurse' must be a Boolean")));
bool recurse = recurse_opt->BooleanValue();
std::string const& path = TOSTR(args[0]);
found = mapnik::freetype_engine::register_fonts(path,recurse);
}
}
else
{
std::string const& path = TOSTR(args[0]);
found = mapnik::freetype_engine::register_fonts(path);
}
std::vector<std::string> const& names_after = mapnik::freetype_engine::face_names();
if (names_after.size() == names_before.size())
found = false;
return scope.Close(Boolean::New(found));
}
catch (const std::exception & ex)
{
return ThrowException(Exception::Error(
String::New(ex.what())));
}
}
static inline Handle<Value> available_font_faces(const Arguments& args)
{
HandleScope scope;
std::vector<std::string> const& names = mapnik::freetype_engine::face_names();
Local<Array> a = Array::New(names.size());
for (unsigned i = 0; i < names.size(); ++i)
{
a->Set(i, String::New(names[i].c_str()));
}
return scope.Close(a);
}
static inline Handle<Value> available_font_files(const Arguments& args)
{
HandleScope scope;
std::map<std::string,std::pair<int,std::string> > const& mapping = mapnik::freetype_engine::get_mapping();
Local<Object> obj = Object::New();
std::map<std::string,std::pair<int,std::string> >::const_iterator itr;
for (itr = mapping.begin();itr!=mapping.end();++itr)
{
obj->Set(String::NewSymbol(itr->first.c_str()),String::New(itr->second.second.c_str()));
}
return scope.Close(obj);
}
}
#endif // __NODE_MAPNIK_FONTS_H__
<|endoftext|> |
<commit_before>#include <karl/api/response_handler.hpp>
#include <supermarx/serialization/xml_serializer.hpp>
#include <supermarx/serialization/msgpack_serializer.hpp>
#include <supermarx/serialization/msgpack_compact_serializer.hpp>
#include <supermarx/serialization/json_serializer.hpp>
#include <supermarx/serialization/msgpack_deserializer.hpp>
#include <supermarx/serialization/serialize_fusion.hpp>
#include <supermarx/serialization/deserialize_fusion.hpp>
#include <supermarx/api/add_product.hpp>
#include <karl/api/api_exception.hpp>
#include <karl/api/uri.hpp>
#include <karl/util/log.hpp>
#include <karl/util/guard.hpp>
namespace supermarx
{
void init_serializer(request& r, response_handler::serializer_ptr& s)
{
const guard g([&]()
{
//Fall back to XML
if(s == nullptr)
{
s.reset(new xml_serializer());
r.write_header("Content-Type", "application/xml");
}
});
const auto& format = r.env().gets.find("format");
if(format == r.env().gets.end() || format->second == "xml")
{
s.reset(new xml_serializer());
r.write_header("Content-Type", "application/xml");
}
else if(format->second == "json")
s.reset(new json_serializer());
else if(format->second == "msgpack")
s.reset(new msgpack_serializer());
else if(format->second == "msgpack_compact")
s.reset(new msgpack_compact_serializer());
else
throw api_exception::format_unknown;
}
bool url_decode(const std::string& in, std::string& out)
{
out.clear();
out.reserve(in.size());
for(std::size_t i = 0; i < in.size(); ++i)
{
if(in[i] == '%')
{
if(i + 3 <= in.size())
{
int value = 0;
std::istringstream is(in.substr(i + 1, 2));
if(is >> std::hex >> value)
{
out += static_cast<char>(value);
i += 2;
}
else
return false;
}
else
return false;
}
else if(in[i] == '+')
out += ' ';
else
out += in[i];
}
return true;
}
void write_exception(request& r, response_handler::serializer_ptr& s, api_exception e)
{
s->clear(); //Clear any previous content
r.write_header("Status", api_exception_status(e));
s->write_object("exception", 3);
s->write("code", e);
s->write("message", api_exception_message(e));
s->write("help", "http://supermarx.nl/docs/api_exception/" + boost::lexical_cast<std::string>(e) + "/");
}
std::string fetch_payload(const request& r)
{
const auto payload_itr = r.env().posts.find("payload");
if(payload_itr == r.env().posts.end())
throw api_exception::payload_expected;
return payload_itr->second.value;
}
template<typename T>
T deserialize_payload(const request& r, const std::string& name)
{
std::unique_ptr<deserializer> d(new msgpack_deserializer);
d->feed(fetch_payload(r));
return deserialize<T>(d, name);
}
template<typename T>
void package(response_handler::serializer_ptr& s, const T& x, const std::string& name)
{
serialize<T>(s, name, x);
}
bool process(request& r, response_handler::serializer_ptr& s, karl& k, const uri& u)
{
if(u.match_path(0, "find_products"))
{
if(u.path.size() != 3)
return false;
id_t supermarket_id = boost::lexical_cast<id_t>(u.path[1]);
std::string name = u.path[2];
serialize(s, "products", k.get_products(name, supermarket_id));
return true;
}
if(u.match_path(0, "add_product"))
{
if(u.path.size() != 2)
return false;
id_t supermarket_id = boost::lexical_cast<id_t>(u.path[1]);
api::add_product request = deserialize_payload<api::add_product>(r, "addproduct");
k.add_product(request.p, supermarket_id, request.retrieved_on, request.c);
s->write_object("response", 1);
s->write("status", std::string("done"));
return true;
}
if(u.match_path(0, "get_product_summary"))
{
if(u.path.size() != 3)
return false;
id_t supermarket_id = boost::lexical_cast<id_t>(u.path[1]);
std::string identifier = u.path[2];
auto p_opt = k.get_product_summary(identifier, supermarket_id);
if(!p_opt)
throw api_exception::product_not_found;
serialize(s, "product_summary", *p_opt);
return true;
}
return false;
}
void response_handler::respond(request& r, karl& k)
{
r.write_header("Server", "karl/0.1");
// Decode url to path.
std::string request_path;
if(!url_decode(r.env().requestUri, request_path))
{
r.write_header("Status", "400 Bad Request");
r.write_endofheader();
return;
}
// Request path must be absolute and not contain "..".
if(request_path.empty() || request_path[0] != '/' || request_path.find("..") != std::string::npos)
{
r.write_header("Status", "400 Bad Request");
r.write_endofheader();
r.write_text("400 bad request");
return;
}
uri u(request_path);
serializer_ptr s(nullptr);
try
{
init_serializer(r, s);
if(process(r, s, k, u))
r.write_header("Status", "200 OK");
else
throw api_exception::path_unknown;
}
catch(api_exception e)
{
log("api::response_handler", log::WARNING)() << "api_exception - " << api_exception_message(e) << " (" << e << ")";
write_exception(r, s, e);
}
catch(std::exception& e)
{
log("api::response_handler", log::ERROR)() << "Uncaught exception: " << e.what();
write_exception(r, s, api_exception::unknown);
}
catch( ... )
{
log("api::response_handler", log::ERROR)() << "Unknown exception";
write_exception(r, s, api_exception::unknown);
}
r.write_endofheader();
s->dump([&](const char* data, size_t size){ r.write_bytes(data, size); });
}
}
<commit_msg>Added application/json stanza to json output<commit_after>#include <karl/api/response_handler.hpp>
#include <supermarx/serialization/xml_serializer.hpp>
#include <supermarx/serialization/msgpack_serializer.hpp>
#include <supermarx/serialization/msgpack_compact_serializer.hpp>
#include <supermarx/serialization/json_serializer.hpp>
#include <supermarx/serialization/msgpack_deserializer.hpp>
#include <supermarx/serialization/serialize_fusion.hpp>
#include <supermarx/serialization/deserialize_fusion.hpp>
#include <supermarx/api/add_product.hpp>
#include <karl/api/api_exception.hpp>
#include <karl/api/uri.hpp>
#include <karl/util/log.hpp>
#include <karl/util/guard.hpp>
namespace supermarx
{
void init_serializer(request& r, response_handler::serializer_ptr& s)
{
const guard g([&]()
{
//Fall back to XML
if(s == nullptr)
{
s.reset(new xml_serializer());
r.write_header("Content-Type", "application/xml");
}
});
const auto& format = r.env().gets.find("format");
if(format == r.env().gets.end() || format->second == "xml")
{
s.reset(new xml_serializer());
r.write_header("Content-Type", "application/xml");
}
else if(format->second == "json")
{
s.reset(new json_serializer());
r.write_header("Content-Type", "application/json");
}
else if(format->second == "msgpack")
s.reset(new msgpack_serializer());
else if(format->second == "msgpack_compact")
s.reset(new msgpack_compact_serializer());
else
throw api_exception::format_unknown;
}
bool url_decode(const std::string& in, std::string& out)
{
out.clear();
out.reserve(in.size());
for(std::size_t i = 0; i < in.size(); ++i)
{
if(in[i] == '%')
{
if(i + 3 <= in.size())
{
int value = 0;
std::istringstream is(in.substr(i + 1, 2));
if(is >> std::hex >> value)
{
out += static_cast<char>(value);
i += 2;
}
else
return false;
}
else
return false;
}
else if(in[i] == '+')
out += ' ';
else
out += in[i];
}
return true;
}
void write_exception(request& r, response_handler::serializer_ptr& s, api_exception e)
{
s->clear(); //Clear any previous content
r.write_header("Status", api_exception_status(e));
s->write_object("exception", 3);
s->write("code", e);
s->write("message", api_exception_message(e));
s->write("help", "http://supermarx.nl/docs/api_exception/" + boost::lexical_cast<std::string>(e) + "/");
}
std::string fetch_payload(const request& r)
{
const auto payload_itr = r.env().posts.find("payload");
if(payload_itr == r.env().posts.end())
throw api_exception::payload_expected;
return payload_itr->second.value;
}
template<typename T>
T deserialize_payload(const request& r, const std::string& name)
{
std::unique_ptr<deserializer> d(new msgpack_deserializer);
d->feed(fetch_payload(r));
return deserialize<T>(d, name);
}
template<typename T>
void package(response_handler::serializer_ptr& s, const T& x, const std::string& name)
{
serialize<T>(s, name, x);
}
bool process(request& r, response_handler::serializer_ptr& s, karl& k, const uri& u)
{
if(u.match_path(0, "find_products"))
{
if(u.path.size() != 3)
return false;
id_t supermarket_id = boost::lexical_cast<id_t>(u.path[1]);
std::string name = u.path[2];
serialize(s, "products", k.get_products(name, supermarket_id));
return true;
}
if(u.match_path(0, "add_product"))
{
if(u.path.size() != 2)
return false;
id_t supermarket_id = boost::lexical_cast<id_t>(u.path[1]);
api::add_product request = deserialize_payload<api::add_product>(r, "addproduct");
k.add_product(request.p, supermarket_id, request.retrieved_on, request.c);
s->write_object("response", 1);
s->write("status", std::string("done"));
return true;
}
if(u.match_path(0, "get_product_summary"))
{
if(u.path.size() != 3)
return false;
id_t supermarket_id = boost::lexical_cast<id_t>(u.path[1]);
std::string identifier = u.path[2];
auto p_opt = k.get_product_summary(identifier, supermarket_id);
if(!p_opt)
throw api_exception::product_not_found;
serialize(s, "product_summary", *p_opt);
return true;
}
return false;
}
void response_handler::respond(request& r, karl& k)
{
r.write_header("Server", "karl/0.1");
// Decode url to path.
std::string request_path;
if(!url_decode(r.env().requestUri, request_path))
{
r.write_header("Status", "400 Bad Request");
r.write_endofheader();
return;
}
// Request path must be absolute and not contain "..".
if(request_path.empty() || request_path[0] != '/' || request_path.find("..") != std::string::npos)
{
r.write_header("Status", "400 Bad Request");
r.write_endofheader();
r.write_text("400 bad request");
return;
}
uri u(request_path);
serializer_ptr s(nullptr);
try
{
init_serializer(r, s);
if(process(r, s, k, u))
r.write_header("Status", "200 OK");
else
throw api_exception::path_unknown;
}
catch(api_exception e)
{
log("api::response_handler", log::WARNING)() << "api_exception - " << api_exception_message(e) << " (" << e << ")";
write_exception(r, s, e);
}
catch(std::exception& e)
{
log("api::response_handler", log::ERROR)() << "Uncaught exception: " << e.what();
write_exception(r, s, api_exception::unknown);
}
catch( ... )
{
log("api::response_handler", log::ERROR)() << "Unknown exception";
write_exception(r, s, api_exception::unknown);
}
r.write_endofheader();
s->dump([&](const char* data, size_t size){ r.write_bytes(data, size); });
}
}
<|endoftext|> |
<commit_before>// Licensed GNU LGPL v2.1 or later: http://www.gnu.org/licenses/lgpl.html
#include "bsestartup.hh"
#include "../config/config.h" // BST_VERSION
#include "bsemain.hh"
#include "bse/internal.hh"
#include <bse/bseapi_handles.hh>
#include <bse/bse.hh> // init_server_connection
namespace Bse {
// == BSE Initialization ==
/** Create SFI glue layer context.
* Create and push an SFI glue layer context for the calling thread, to enable communications with the
* main BSE thread library.
*/
SfiGlueContext*
init_glue_context (const gchar *client, const std::function<void()> &caller_wakeup)
{
return _bse_glue_context_create (client, caller_wakeup);
}
/** Initialize and start BSE.
* Initialize the BSE library and start the main BSE thread. Arguments specific to BSE are removed
* from @a argc / @a argv.
*/
void
init_async (int *argc, char **argv, const char *app_name, const StringVector &args)
{
_bse_init_async (argc, argv, app_name, args);
}
/// Check wether init_async() still needs to be called.
bool
init_needed ()
{
return _bse_initialized() == false;
}
// == TaskRegistry ==
static std::mutex task_registry_mutex_;
static TaskRegistry::List task_registry_tasks_;
void
TaskRegistry::add (const std::string &name, int pid, int tid)
{
Bse::TaskStatus task (pid, tid);
task.name = name;
task.update();
std::lock_guard<std::mutex> locker (task_registry_mutex_);
task_registry_tasks_.push_back (task);
}
bool
TaskRegistry::remove (int tid)
{
std::lock_guard<std::mutex> locker (task_registry_mutex_);
for (auto it = task_registry_tasks_.begin(); it != task_registry_tasks_.end(); it++)
if (it->task_id == tid)
{
task_registry_tasks_.erase (it);
return true;
}
return false;
}
void
TaskRegistry::update ()
{
std::lock_guard<std::mutex> locker (task_registry_mutex_);
for (auto &task : task_registry_tasks_)
task.update();
}
TaskRegistry::List
TaskRegistry::list ()
{
std::lock_guard<std::mutex> locker (task_registry_mutex_);
return task_registry_tasks_;
}
class AidaGlibSourceImpl : public AidaGlibSource {
static AidaGlibSourceImpl* self_ (GSource *src) { return (AidaGlibSourceImpl*) src; }
static int glib_prepare (GSource *src, int *timeoutp) { return self_ (src)->prepare (timeoutp); }
static int glib_check (GSource *src) { return self_ (src)->check(); }
static int glib_dispatch (GSource *src, GSourceFunc, void*) { return self_ (src)->dispatch(); }
static void glib_finalize (GSource *src) { self_ (src)->~AidaGlibSourceImpl(); }
Aida::BaseConnection *connection_;
GPollFD pfd_;
AidaGlibSourceImpl (Aida::BaseConnection *connection) :
connection_ (connection), pfd_ { -1, 0, 0 }
{
pfd_.fd = connection_->notify_fd();
pfd_.events = G_IO_IN;
g_source_add_poll (this, &pfd_);
}
~AidaGlibSourceImpl ()
{
g_source_remove_poll (this, &pfd_);
}
bool
prepare (int *timeoutp)
{
return pfd_.revents || connection_->pending();
}
bool
check ()
{
return pfd_.revents || connection_->pending();
}
bool
dispatch ()
{
pfd_.revents = 0;
connection_->dispatch();
return true;
}
public:
static AidaGlibSourceImpl*
create (Aida::BaseConnection *connection)
{
assert_return (connection != NULL, NULL);
static GSourceFuncs glib_source_funcs = { glib_prepare, glib_check, glib_dispatch, glib_finalize, NULL, NULL };
GSource *src = g_source_new (&glib_source_funcs, sizeof (AidaGlibSourceImpl));
return new (src) AidaGlibSourceImpl (connection);
}
};
AidaGlibSource*
AidaGlibSource::create (Aida::BaseConnection *connection)
{
return AidaGlibSourceImpl::create (connection);
}
static Aida::ClientConnectionP *client_connection = NULL;
/// Retrieve a handle for the Bse::Server instance managing the Bse thread.
ServerHandle
init_server_instance () // bse.hh
{
ServerH server;
Aida::ClientConnectionP connection = init_server_connection();
if (connection)
server = connection->remote_origin<ServerH>();
return server;
}
/// Retrieve the ClientConnection used for RPC communication with the Bse thread.
Aida::ClientConnectionP
init_server_connection () // bse.hh
{
if (!client_connection)
{
Aida::ClientConnectionP connection = Aida::ClientConnection::connect ("inproc://BSE-" BST_VERSION);
ServerH bseconnection_server_handle;
if (connection)
bseconnection_server_handle = connection->remote_origin<ServerH>(); // sets errno
assert_return (bseconnection_server_handle != NULL, NULL);
constexpr SfiProxy BSE_SERVER = 1;
assert_return (bseconnection_server_handle.proxy_id() == BSE_SERVER, NULL);
assert_return (bseconnection_server_handle.from_proxy (BSE_SERVER) == bseconnection_server_handle, NULL);
assert_return (client_connection == NULL, NULL);
client_connection = new Aida::ClientConnectionP (connection);
}
return *client_connection;
}
} // Bse
#include "bseapi_handles.cc" // build IDL client interface
<commit_msg>BSE: bsestartup: fix Bse::version() usage<commit_after>// Licensed GNU LGPL v2.1 or later: http://www.gnu.org/licenses/lgpl.html
#include "bsestartup.hh"
#include "bsemain.hh"
#include "bse/internal.hh"
#include <bse/bseapi_handles.hh>
#include <bse/bse.hh> // init_server_connection
namespace Bse {
// == BSE Initialization ==
/** Create SFI glue layer context.
* Create and push an SFI glue layer context for the calling thread, to enable communications with the
* main BSE thread library.
*/
SfiGlueContext*
init_glue_context (const gchar *client, const std::function<void()> &caller_wakeup)
{
return _bse_glue_context_create (client, caller_wakeup);
}
/** Initialize and start BSE.
* Initialize the BSE library and start the main BSE thread. Arguments specific to BSE are removed
* from @a argc / @a argv.
*/
void
init_async (int *argc, char **argv, const char *app_name, const StringVector &args)
{
_bse_init_async (argc, argv, app_name, args);
}
/// Check wether init_async() still needs to be called.
bool
init_needed ()
{
return _bse_initialized() == false;
}
// == TaskRegistry ==
static std::mutex task_registry_mutex_;
static TaskRegistry::List task_registry_tasks_;
void
TaskRegistry::add (const std::string &name, int pid, int tid)
{
Bse::TaskStatus task (pid, tid);
task.name = name;
task.update();
std::lock_guard<std::mutex> locker (task_registry_mutex_);
task_registry_tasks_.push_back (task);
}
bool
TaskRegistry::remove (int tid)
{
std::lock_guard<std::mutex> locker (task_registry_mutex_);
for (auto it = task_registry_tasks_.begin(); it != task_registry_tasks_.end(); it++)
if (it->task_id == tid)
{
task_registry_tasks_.erase (it);
return true;
}
return false;
}
void
TaskRegistry::update ()
{
std::lock_guard<std::mutex> locker (task_registry_mutex_);
for (auto &task : task_registry_tasks_)
task.update();
}
TaskRegistry::List
TaskRegistry::list ()
{
std::lock_guard<std::mutex> locker (task_registry_mutex_);
return task_registry_tasks_;
}
class AidaGlibSourceImpl : public AidaGlibSource {
static AidaGlibSourceImpl* self_ (GSource *src) { return (AidaGlibSourceImpl*) src; }
static int glib_prepare (GSource *src, int *timeoutp) { return self_ (src)->prepare (timeoutp); }
static int glib_check (GSource *src) { return self_ (src)->check(); }
static int glib_dispatch (GSource *src, GSourceFunc, void*) { return self_ (src)->dispatch(); }
static void glib_finalize (GSource *src) { self_ (src)->~AidaGlibSourceImpl(); }
Aida::BaseConnection *connection_;
GPollFD pfd_;
AidaGlibSourceImpl (Aida::BaseConnection *connection) :
connection_ (connection), pfd_ { -1, 0, 0 }
{
pfd_.fd = connection_->notify_fd();
pfd_.events = G_IO_IN;
g_source_add_poll (this, &pfd_);
}
~AidaGlibSourceImpl ()
{
g_source_remove_poll (this, &pfd_);
}
bool
prepare (int *timeoutp)
{
return pfd_.revents || connection_->pending();
}
bool
check ()
{
return pfd_.revents || connection_->pending();
}
bool
dispatch ()
{
pfd_.revents = 0;
connection_->dispatch();
return true;
}
public:
static AidaGlibSourceImpl*
create (Aida::BaseConnection *connection)
{
assert_return (connection != NULL, NULL);
static GSourceFuncs glib_source_funcs = { glib_prepare, glib_check, glib_dispatch, glib_finalize, NULL, NULL };
GSource *src = g_source_new (&glib_source_funcs, sizeof (AidaGlibSourceImpl));
return new (src) AidaGlibSourceImpl (connection);
}
};
AidaGlibSource*
AidaGlibSource::create (Aida::BaseConnection *connection)
{
return AidaGlibSourceImpl::create (connection);
}
static Aida::ClientConnectionP *client_connection = NULL;
/// Retrieve a handle for the Bse::Server instance managing the Bse thread.
ServerHandle
init_server_instance () // bse.hh
{
ServerH server;
Aida::ClientConnectionP connection = init_server_connection();
if (connection)
server = connection->remote_origin<ServerH>();
return server;
}
/// Retrieve the ClientConnection used for RPC communication with the Bse thread.
Aida::ClientConnectionP
init_server_connection () // bse.hh
{
if (!client_connection)
{
Aida::ClientConnectionP connection = Aida::ClientConnection::connect ("inproc://BSE-" + Bse::version());
ServerH bseconnection_server_handle;
if (connection)
bseconnection_server_handle = connection->remote_origin<ServerH>(); // sets errno
assert_return (bseconnection_server_handle != NULL, NULL);
constexpr SfiProxy BSE_SERVER = 1;
assert_return (bseconnection_server_handle.proxy_id() == BSE_SERVER, NULL);
assert_return (bseconnection_server_handle.from_proxy (BSE_SERVER) == bseconnection_server_handle, NULL);
assert_return (client_connection == NULL, NULL);
client_connection = new Aida::ClientConnectionP (connection);
}
return *client_connection;
}
} // Bse
#include "bse/bseapi_handles.cc" // build IDL client interface
<|endoftext|> |
<commit_before>#pragma once
#include "constants.hpp"
#include "file_monitor.hpp"
#include "filesystem.hpp"
#include "gcd_utility.hpp"
#include "logger.hpp"
#include <fstream>
namespace krbn {
class grabber_alerts_monitor final {
public:
typedef std::function<void(void)> callback;
grabber_alerts_monitor(const grabber_alerts_monitor&) = delete;
grabber_alerts_monitor(const callback& callback) : callback_(callback) {
auto file_path = constants::get_grabber_alerts_json_file_path();
auto directory = filesystem::dirname(file_path);
std::vector<std::pair<std::string, std::vector<std::string>>> targets = {
{directory, {file_path}},
};
file_monitor_ = std::make_unique<file_monitor>(targets,
[this](const std::string&) {
std::ifstream stream(constants::get_grabber_alerts_json_file_path());
if (stream) {
auto json = nlohmann::json::parse(stream);
// json example
//
// {
// "alerts": [
// "system_policy_prevents_loading_kext"
// ]
// }
const std::string key = "alerts";
if (json.find(key) != std::end(json)) {
auto alerts = json[key];
if (alerts.is_array() && !alerts.empty()) {
auto s = json.dump();
if (json_string_ != s) {
json_string_ = s;
if (callback_) {
callback_();
}
}
}
}
}
});
}
~grabber_alerts_monitor(void) {
gcd_utility::dispatch_sync_in_main_queue(^{
file_monitor_ = nullptr;
});
}
private:
callback callback_;
std::string json_string_;
std::unique_ptr<file_monitor> file_monitor_;
};
} // namespace krbn
<commit_msg>catch json::parse error<commit_after>#pragma once
#include "constants.hpp"
#include "file_monitor.hpp"
#include "filesystem.hpp"
#include "gcd_utility.hpp"
#include "logger.hpp"
#include <fstream>
namespace krbn {
class grabber_alerts_monitor final {
public:
typedef std::function<void(void)> callback;
grabber_alerts_monitor(const grabber_alerts_monitor&) = delete;
grabber_alerts_monitor(const callback& callback) : callback_(callback) {
auto file_path = constants::get_grabber_alerts_json_file_path();
auto directory = filesystem::dirname(file_path);
std::vector<std::pair<std::string, std::vector<std::string>>> targets = {
{directory, {file_path}},
};
file_monitor_ = std::make_unique<file_monitor>(targets,
[this](const std::string&) {
auto file_path = constants::get_grabber_alerts_json_file_path();
std::ifstream stream(file_path);
if (stream) {
try {
auto json = nlohmann::json::parse(stream);
// json example
//
// {
// "alerts": [
// "system_policy_prevents_loading_kext"
// ]
// }
const std::string key = "alerts";
if (json.find(key) != std::end(json)) {
auto alerts = json[key];
if (alerts.is_array() && !alerts.empty()) {
auto s = json.dump();
if (json_string_ != s) {
json_string_ = s;
if (callback_) {
callback_();
}
}
}
}
} catch (std::exception& e) {
logger::get_logger().error("parse error in {0}: {1}", file_path, e.what());
}
}
});
}
~grabber_alerts_monitor(void) {
gcd_utility::dispatch_sync_in_main_queue(^{
file_monitor_ = nullptr;
});
}
private:
callback callback_;
std::string json_string_;
std::unique_ptr<file_monitor> file_monitor_;
};
} // namespace krbn
<|endoftext|> |
<commit_before>/*
* Copyright (c) 2006, Ondrej Danek (www.ondrej-danek.net)
* All rights reserved.
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* * Neither the name of Ondrej Danek nor the
* names of its contributors may be used to endorse or promote products
* derived from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
* LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
* CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE
* GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
* HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
* LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT
* OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
#include "Level.h"
#include "json/JsonParser.h"
namespace Duel6
{
Level::Level(const std::string& path, bool mirror, const Block::Meta& blockMeta)
: blockMeta(blockMeta)
{
load(path, mirror);
}
void Level::load(const std::string& path, bool mirror)
{
levelData.clear();
waterLevel = 0;
Json::Parser parser;
Json::Value root = parser.parse(path);
width = root.get("width").asInt();
height = root.get("height").asInt();
Int32 blockCount = width * height;
Json::Value blocks = root.get("blocks");
levelData.resize(blockCount);
for (Size i = 0; i < blocks.getLength(); i++)
{
levelData[i] = blocks.get(i).asInt();
}
if (mirror)
{
mirrorLevelData();
}
waterBlock = findWaterType();
}
void Level::mirrorLevelData()
{
for (Int32 y = 0; y < height; y++)
{
for (Int32 x = 0; x < width / 2; x++)
{
std::swap(levelData[y * width + x], levelData[y * width + width - 1 - x]);
}
}
}
void Level::raiseWater()
{
if(waterLevel < getHeight() - 2)
{
waterLevel++;
for(Int32 x = 1; x < getWidth() - 1; x++)
{
if(!isWall(x, waterLevel, false))
{
setBlock(waterBlock, x, waterLevel);
}
}
}
}
Uint16 Level::findWaterType() const
{
for (Int32 y = 0; y < getHeight(); y++)
{
for (Int32 x = 0; x < getWidth(); x++)
{
if (isWater(x, y))
{
return getBlock(x, y);
}
}
}
static Uint16 waterBlocks[] = { 4, 16, 33 };
return waterBlocks[rand() % 3];
}
Water::Type Level::getWaterType(Int32 x, Int32 y) const
{
if (isWater(x, y))
{
Uint16 block = getBlock(x, y);
if (block == 4)
{
return Water::Type::Blue;
}
else if (block == 16)
{
return Water::Type::Red;
}
else if (block == 33)
{
return Water::Type::Green;
}
}
return Water::Type::None;
}
}<commit_msg>Fix water raising<commit_after>/*
* Copyright (c) 2006, Ondrej Danek (www.ondrej-danek.net)
* All rights reserved.
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* * Neither the name of Ondrej Danek nor the
* names of its contributors may be used to endorse or promote products
* derived from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
* LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
* CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE
* GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
* HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
* LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT
* OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
#include "Level.h"
#include "json/JsonParser.h"
namespace Duel6
{
Level::Level(const std::string& path, bool mirror, const Block::Meta& blockMeta)
: blockMeta(blockMeta)
{
load(path, mirror);
}
void Level::load(const std::string& path, bool mirror)
{
levelData.clear();
waterLevel = 0;
Json::Parser parser;
Json::Value root = parser.parse(path);
width = root.get("width").asInt();
height = root.get("height").asInt();
Int32 blockCount = width * height;
Json::Value blocks = root.get("blocks");
levelData.resize(blockCount);
for (Size i = 0; i < blocks.getLength(); i++)
{
levelData[i] = blocks.get(i).asInt();
}
if (mirror)
{
mirrorLevelData();
}
waterBlock = findWaterType();
}
void Level::mirrorLevelData()
{
for (Int32 y = 0; y < height; y++)
{
for (Int32 x = 0; x < width / 2; x++)
{
std::swap(levelData[y * width + x], levelData[y * width + width - 1 - x]);
}
}
}
void Level::raiseWater()
{
if(waterLevel < getHeight() - 1)
{
waterLevel++;
for(Int32 x = 0; x < getWidth(); x++)
{
if(!isWall(x, waterLevel, false))
{
setBlock(waterBlock, x, waterLevel);
}
}
}
}
Uint16 Level::findWaterType() const
{
for (Int32 y = 0; y < getHeight(); y++)
{
for (Int32 x = 0; x < getWidth(); x++)
{
if (isWater(x, y))
{
return getBlock(x, y);
}
}
}
static Uint16 waterBlocks[] = { 4, 16, 33 };
return waterBlocks[rand() % 3];
}
Water::Type Level::getWaterType(Int32 x, Int32 y) const
{
if (isWater(x, y))
{
Uint16 block = getBlock(x, y);
if (block == 4)
{
return Water::Type::Blue;
}
else if (block == 16)
{
return Water::Type::Red;
}
else if (block == 33)
{
return Water::Type::Green;
}
}
return Water::Type::None;
}
}<|endoftext|> |
<commit_before>#include "HdmiDisplay.h"
HdmiDisplayIndications::HdmiDisplayIndications()
{
}
HdmiDisplayIndications::~HdmiDisplayIndications()
{
}
struct HdmiDisplayIndicationsvsyncMSG : public PortalMessage
{
//fix Adapter.bsv to unreverse these
unsigned long long v:64;
};
void HdmiDisplayIndications::handleMessage(PortalMessage *msg)
{
switch (msg->channel) {
case 0: vsync(((HdmiDisplayIndicationsvsyncMSG *)msg)->v); break;
default: break;
}
}
HdmiDisplay *HdmiDisplay::createHdmiDisplay(const char *instanceName, HdmiDisplayIndications *indications)
{
HdmiDisplay *instance = new HdmiDisplay(instanceName, indications);
return instance;
}
HdmiDisplay::HdmiDisplay(const char *instanceName, HdmiDisplayIndications *indications)
: PortalInstance(instanceName, indications)
{
}
HdmiDisplay::~HdmiDisplay()
{
close();
}
struct HdmiDisplaysetPatternRegMSG : public PortalMessage
{
struct Request {
//fix Adapter.bsv to unreverse these
unsigned long yuv422;
} request;
};
void HdmiDisplay::setPatternReg ( unsigned long yuv422 )
{
HdmiDisplaysetPatternRegMSG msg;
msg.size = sizeof(msg.request);
msg.channel = 0;
msg.request.yuv422 = yuv422;
sendMessage(&msg);
};
struct HdmiDisplaystartFrameBuffer0MSG : public PortalMessage
{
struct Request {
//fix Adapter.bsv to unreverse these
unsigned long base;
} request;
};
void HdmiDisplay::startFrameBuffer0 ( unsigned long base )
{
HdmiDisplaystartFrameBuffer0MSG msg;
msg.size = sizeof(msg.request);
msg.channel = 1;
msg.request.base = base;
sendMessage(&msg);
};
struct HdmiDisplaystartFrameBuffer1MSG : public PortalMessage
{
struct Request {
//fix Adapter.bsv to unreverse these
unsigned long base;
} request;
};
void HdmiDisplay::startFrameBuffer1 ( unsigned long base )
{
HdmiDisplaystartFrameBuffer1MSG msg;
msg.size = sizeof(msg.request);
msg.channel = 2;
msg.request.base = base;
sendMessage(&msg);
};
struct HdmiDisplaywaitForVsyncMSG : public PortalMessage
{
struct Request {
//fix Adapter.bsv to unreverse these
unsigned long unused;
} request;
};
void HdmiDisplay::waitForVsync ( unsigned long unused )
{
HdmiDisplaywaitForVsyncMSG msg;
msg.size = sizeof(msg.request);
msg.channel = 3;
msg.request.unused = unused;
sendMessage(&msg);
};
struct HdmiDisplayhdmiLinesPixelsMSG : public PortalMessage
{
struct Request {
//fix Adapter.bsv to unreverse these
unsigned long value;
} request;
};
void HdmiDisplay::hdmiLinesPixels ( unsigned long value )
{
HdmiDisplayhdmiLinesPixelsMSG msg;
msg.size = sizeof(msg.request);
msg.channel = 4;
msg.request.value = value;
sendMessage(&msg);
};
struct HdmiDisplayhdmiBlankLinesPixelsMSG : public PortalMessage
{
struct Request {
//fix Adapter.bsv to unreverse these
unsigned long value;
} request;
};
void HdmiDisplay::hdmiBlankLinesPixels ( unsigned long value )
{
HdmiDisplayhdmiBlankLinesPixelsMSG msg;
msg.size = sizeof(msg.request);
msg.channel = 5;
msg.request.value = value;
sendMessage(&msg);
};
struct HdmiDisplayhdmiStrideBytesMSG : public PortalMessage
{
struct Request {
//fix Adapter.bsv to unreverse these
unsigned long strideBytes;
} request;
};
void HdmiDisplay::hdmiStrideBytes ( unsigned long strideBytes )
{
HdmiDisplayhdmiStrideBytesMSG msg;
msg.size = sizeof(msg.request);
msg.channel = 6;
msg.request.strideBytes = strideBytes;
sendMessage(&msg);
};
struct HdmiDisplayhdmiLineCountMinMaxMSG : public PortalMessage
{
struct Request {
//fix Adapter.bsv to unreverse these
unsigned long value;
} request;
};
void HdmiDisplay::hdmiLineCountMinMax ( unsigned long value )
{
HdmiDisplayhdmiLineCountMinMaxMSG msg;
msg.size = sizeof(msg.request);
msg.channel = 7;
msg.request.value = value;
sendMessage(&msg);
};
struct HdmiDisplayhdmiPixelCountMinMaxMSG : public PortalMessage
{
struct Request {
//fix Adapter.bsv to unreverse these
unsigned long value;
} request;
};
void HdmiDisplay::hdmiPixelCountMinMax ( unsigned long value )
{
HdmiDisplayhdmiPixelCountMinMaxMSG msg;
msg.size = sizeof(msg.request);
msg.channel = 8;
msg.request.value = value;
sendMessage(&msg);
};
struct HdmiDisplayhdmiSyncWidthsMSG : public PortalMessage
{
struct Request {
//fix Adapter.bsv to unreverse these
unsigned long value;
} request;
};
void HdmiDisplay::hdmiSyncWidths ( unsigned long value )
{
HdmiDisplayhdmiSyncWidthsMSG msg;
msg.size = sizeof(msg.request);
msg.channel = 9;
msg.request.value = value;
sendMessage(&msg);
};
struct HdmiDisplaybeginTranslationTableMSG : public PortalMessage
{
struct Request {
//fix Adapter.bsv to unreverse these
unsigned long index:8;
} request;
};
void HdmiDisplay::beginTranslationTable ( unsigned long index )
{
HdmiDisplaybeginTranslationTableMSG msg;
msg.size = sizeof(msg.request);
msg.channel = 10;
msg.request.index = index;
sendMessage(&msg);
};
struct HdmiDisplayaddTranslationEntryMSG : public PortalMessage
{
struct Request {
//fix Adapter.bsv to unreverse these
unsigned long length:12;
unsigned long address:20;
} request;
};
void HdmiDisplay::addTranslationEntry ( unsigned long address, unsigned long length )
{
HdmiDisplayaddTranslationEntryMSG msg;
msg.size = sizeof(msg.request);
msg.channel = 11;
msg.request.address = address;
msg.request.length = length;
sendMessage(&msg);
};
<commit_msg>updated HdmiDisplay.cpp<commit_after>#include "HdmiDisplay.h"
HdmiDisplayIndications::HdmiDisplayIndications()
{
}
HdmiDisplayIndications::~HdmiDisplayIndications()
{
}
struct HdmiDisplayIndicationsvsyncMSG : public PortalMessage
{
//fix Adapter.bsv to unreverse these
unsigned long long v:64;
};
void HdmiDisplayIndications::handleMessage(PortalMessage *msg)
{
switch (msg->channel) {
case 12: vsync(((HdmiDisplayIndicationsvsyncMSG *)msg)->v); break;
default: break;
}
}
HdmiDisplay *HdmiDisplay::createHdmiDisplay(const char *instanceName, HdmiDisplayIndications *indications)
{
HdmiDisplay *instance = new HdmiDisplay(instanceName, indications);
return instance;
}
HdmiDisplay::HdmiDisplay(const char *instanceName, HdmiDisplayIndications *indications)
: PortalInstance(instanceName, indications)
{
}
HdmiDisplay::~HdmiDisplay()
{
close();
}
struct HdmiDisplaysetPatternRegMSG : public PortalMessage
{
struct Request {
//fix Adapter.bsv to unreverse these
unsigned long yuv422;
} request;
};
void HdmiDisplay::setPatternReg ( unsigned long yuv422 )
{
HdmiDisplaysetPatternRegMSG msg;
msg.size = sizeof(msg.request);
msg.channel = 0;
msg.request.yuv422 = yuv422;
sendMessage(&msg);
};
struct HdmiDisplaystartFrameBuffer0MSG : public PortalMessage
{
struct Request {
//fix Adapter.bsv to unreverse these
unsigned long base;
} request;
};
void HdmiDisplay::startFrameBuffer0 ( unsigned long base )
{
HdmiDisplaystartFrameBuffer0MSG msg;
msg.size = sizeof(msg.request);
msg.channel = 1;
msg.request.base = base;
sendMessage(&msg);
};
struct HdmiDisplaystartFrameBuffer1MSG : public PortalMessage
{
struct Request {
//fix Adapter.bsv to unreverse these
unsigned long base;
} request;
};
void HdmiDisplay::startFrameBuffer1 ( unsigned long base )
{
HdmiDisplaystartFrameBuffer1MSG msg;
msg.size = sizeof(msg.request);
msg.channel = 2;
msg.request.base = base;
sendMessage(&msg);
};
struct HdmiDisplaywaitForVsyncMSG : public PortalMessage
{
struct Request {
//fix Adapter.bsv to unreverse these
unsigned long unused;
} request;
};
void HdmiDisplay::waitForVsync ( unsigned long unused )
{
HdmiDisplaywaitForVsyncMSG msg;
msg.size = sizeof(msg.request);
msg.channel = 3;
msg.request.unused = unused;
sendMessage(&msg);
};
struct HdmiDisplayhdmiLinesPixelsMSG : public PortalMessage
{
struct Request {
//fix Adapter.bsv to unreverse these
unsigned long value;
} request;
};
void HdmiDisplay::hdmiLinesPixels ( unsigned long value )
{
HdmiDisplayhdmiLinesPixelsMSG msg;
msg.size = sizeof(msg.request);
msg.channel = 4;
msg.request.value = value;
sendMessage(&msg);
};
struct HdmiDisplayhdmiBlankLinesPixelsMSG : public PortalMessage
{
struct Request {
//fix Adapter.bsv to unreverse these
unsigned long value;
} request;
};
void HdmiDisplay::hdmiBlankLinesPixels ( unsigned long value )
{
HdmiDisplayhdmiBlankLinesPixelsMSG msg;
msg.size = sizeof(msg.request);
msg.channel = 5;
msg.request.value = value;
sendMessage(&msg);
};
struct HdmiDisplayhdmiStrideBytesMSG : public PortalMessage
{
struct Request {
//fix Adapter.bsv to unreverse these
unsigned long strideBytes;
} request;
};
void HdmiDisplay::hdmiStrideBytes ( unsigned long strideBytes )
{
HdmiDisplayhdmiStrideBytesMSG msg;
msg.size = sizeof(msg.request);
msg.channel = 6;
msg.request.strideBytes = strideBytes;
sendMessage(&msg);
};
struct HdmiDisplayhdmiLineCountMinMaxMSG : public PortalMessage
{
struct Request {
//fix Adapter.bsv to unreverse these
unsigned long value;
} request;
};
void HdmiDisplay::hdmiLineCountMinMax ( unsigned long value )
{
HdmiDisplayhdmiLineCountMinMaxMSG msg;
msg.size = sizeof(msg.request);
msg.channel = 7;
msg.request.value = value;
sendMessage(&msg);
};
struct HdmiDisplayhdmiPixelCountMinMaxMSG : public PortalMessage
{
struct Request {
//fix Adapter.bsv to unreverse these
unsigned long value;
} request;
};
void HdmiDisplay::hdmiPixelCountMinMax ( unsigned long value )
{
HdmiDisplayhdmiPixelCountMinMaxMSG msg;
msg.size = sizeof(msg.request);
msg.channel = 8;
msg.request.value = value;
sendMessage(&msg);
};
struct HdmiDisplayhdmiSyncWidthsMSG : public PortalMessage
{
struct Request {
//fix Adapter.bsv to unreverse these
unsigned long value;
} request;
};
void HdmiDisplay::hdmiSyncWidths ( unsigned long value )
{
HdmiDisplayhdmiSyncWidthsMSG msg;
msg.size = sizeof(msg.request);
msg.channel = 9;
msg.request.value = value;
sendMessage(&msg);
};
struct HdmiDisplaybeginTranslationTableMSG : public PortalMessage
{
struct Request {
//fix Adapter.bsv to unreverse these
unsigned long index:8;
} request;
};
void HdmiDisplay::beginTranslationTable ( unsigned long index )
{
HdmiDisplaybeginTranslationTableMSG msg;
msg.size = sizeof(msg.request);
msg.channel = 10;
msg.request.index = index;
sendMessage(&msg);
};
struct HdmiDisplayaddTranslationEntryMSG : public PortalMessage
{
struct Request {
//fix Adapter.bsv to unreverse these
unsigned long length:12;
unsigned long address:20;
} request;
};
void HdmiDisplay::addTranslationEntry ( unsigned long address, unsigned long length )
{
HdmiDisplayaddTranslationEntryMSG msg;
msg.size = sizeof(msg.request);
msg.channel = 11;
msg.request.address = address;
msg.request.length = length;
sendMessage(&msg);
};
<|endoftext|> |
<commit_before>#include "library/sp.h"
#include "game/apocresources/loftemps.h"
#include "framework/logger.h"
#include "framework/data.h"
namespace OpenApoc
{
LOFTemps::LOFTemps(IFile &datFile, IFile &tabFile)
{
if (!tabFile)
{
LogError("Invalid TAB file");
return;
}
if (!datFile)
{
LogError("Invalid DAT file");
return;
}
uint32_t offset;
while (tabFile.readule32(offset))
{
datFile.seekg(offset * 4, std::ios::beg);
if (!datFile)
{
LogError("Seeking beyond end of file reading offset %u", offset * 4);
return;
}
uint32_t width;
if (!datFile.readule32(width))
{
LogError("Failed to read width");
return;
}
uint32_t height;
if (!datFile.readule32(height))
{
LogError("Failed to read height");
return;
}
if (width % 8)
{
LogError("Non-8-bit-aligned width: %u", width);
return;
}
auto slice = std::make_shared<VoxelSlice>(Vec2<int>{width, height});
for (unsigned int y = 0; y < height; y++)
{
// Bitmasks are packed into a 32-bit word, so all strides will
// be 4-byte aligned
for (unsigned int x = 0; x < width; x += 32)
{
uint32_t bitmask;
if (!datFile.readule32(bitmask))
{
LogError("Failed to read bitmask at {%u,%u}", x, y);
return;
}
for (unsigned int bit = 0; bit < 32; bit++)
{
if (x >= width)
break;
bool b;
if (bitmask & 0x80000000)
b = true;
else
b = false;
bitmask >>= 1;
slice->setBit(Vec2<int>{x + bit, y}, b);
}
}
}
LogInfo("Read voxel slice of size {%u,%u}", width, height);
this->slices.push_back(slice);
}
}
sp<VoxelSlice> LOFTemps::getSlice(unsigned int idx)
{
if (idx >= this->slices.size())
{
LogError("Requested slice %d - only %u in file", idx, this->slices.size());
return nullptr;
}
return this->slices[idx];
}
}; // namespace OpenApoc
<commit_msg>Fix collisions<commit_after>#include "library/sp.h"
#include "game/apocresources/loftemps.h"
#include "framework/logger.h"
#include "framework/data.h"
namespace OpenApoc
{
LOFTemps::LOFTemps(IFile &datFile, IFile &tabFile)
{
if (!tabFile)
{
LogError("Invalid TAB file");
return;
}
if (!datFile)
{
LogError("Invalid DAT file");
return;
}
uint32_t offset;
while (tabFile.readule32(offset))
{
datFile.seekg(offset * 4, std::ios::beg);
if (!datFile)
{
LogError("Seeking beyond end of file reading offset %u", offset * 4);
return;
}
uint32_t width;
if (!datFile.readule32(width))
{
LogError("Failed to read width");
return;
}
uint32_t height;
if (!datFile.readule32(height))
{
LogError("Failed to read height");
return;
}
if (width % 8)
{
LogError("Non-8-bit-aligned width: %u", width);
return;
}
auto slice = std::make_shared<VoxelSlice>(Vec2<int>{width, height});
for (unsigned int y = 0; y < height; y++)
{
// Bitmasks are packed into a 32-bit word, so all strides will
// be 4-byte aligned
for (unsigned int x = 0; x < width; x += 32)
{
uint32_t bitmask;
if (!datFile.readule32(bitmask))
{
LogError("Failed to read bitmask at {%u,%u}", x, y);
return;
}
for (unsigned int bit = 0; bit < 32; bit++)
{
if (x >= width)
break;
bool b;
if (bitmask & 0x80000000)
b = true;
else
b = false;
bitmask <<= 1;
slice->setBit(Vec2<int>{x + bit, y}, b);
}
}
}
LogInfo("Read voxel slice of size {%u,%u}", width, height);
this->slices.push_back(slice);
}
}
sp<VoxelSlice> LOFTemps::getSlice(unsigned int idx)
{
if (idx >= this->slices.size())
{
LogError("Requested slice %d - only %u in file", idx, this->slices.size());
return nullptr;
}
return this->slices[idx];
}
}; // namespace OpenApoc
<|endoftext|> |
<commit_before>/* Copyright (c) 2013 Fabian Schuiki */
#pragma once
#include "../math.hpp"
#include "../matrix.hpp"
#define GAMMA_HAS_TRANSFORM_PERSPECTIVE
namespace gamma {
namespace transform {
/** A perspective projection, as it would be generated by the gluPerspective
* OpenGL call. Note that the field-of-view is vertical, aspect is the ratio
* between the horizontal and vertical field-of-view, and near and far refer to
* the near and far clipping planes. */
template <typename T> struct perspective
{
typedef perspective<T> self;
typedef T scalar_type;
typedef matrix4<T> matrix_type;
const T fov; // vertical field of view [radians]
const T aspect;
const T near, far; // clipping planes
perspective(): m(1) {}
perspective(T fov, T aspect, T near, T far): fov(fov), aspect(aspect), near(near), far(far)
{
T f = tan(M_PI_2 - fov/2); // cot(x) = tan(pi/2 - x)
T g = f/aspect;
T a = near+far;
T b = near-far;
T c = 2*near*far;
m = matrix_type(
g, 0, 0, 0,
0, f, 0, 0,
0, 0, a/b, c/b,
0, 0, -1, 0
);
}
operator matrix_type() const { return m; }
protected:
matrix_type m;
};
typedef perspective<float> perspectivef;
typedef perspective<double> perspectived;
} // namespace transform
} // namespace gamma<commit_msg>fixed: perspective now follows gluPerspective<commit_after>/* Copyright (c) 2013 Fabian Schuiki */
#pragma once
#include "../math.hpp"
#include "../matrix.hpp"
#define GAMMA_HAS_TRANSFORM_PERSPECTIVE
namespace gamma {
namespace transform {
/** A perspective projection, as it would be generated by the gluPerspective
* OpenGL call. Note that the field-of-view is vertical, aspect is the ratio
* between the horizontal and vertical field-of-view, and near and far refer to
* the near and far clipping planes. */
template <typename T> struct perspective
{
typedef perspective<T> self;
typedef T scalar_type;
typedef matrix4<T> matrix_type;
const T fov; // vertical field of view [radians]
const T aspect;
const T near, far; // clipping planes
perspective(): m(1) {}
perspective(T fov, T aspect, T near, T far): fov(fov), aspect(aspect), near(near), far(far)
{
T f = tan(M_PI_2 - fov/2); // cot(x) = tan(pi/2 - x)
T g = f/aspect;
T a = far+near;
T b = far-near;
T c = 2*near*far;
m = matrix_type(
g, 0, 0, 0,
0, f, 0, 0,
0, 0, -a/b, -c/b,
0, 0, -1, 0
);
}
operator matrix_type() const { return m; }
protected:
matrix_type m;
};
typedef perspective<float> perspectivef;
typedef perspective<double> perspectived;
} // namespace transform
} // namespace gamma<|endoftext|> |
<commit_before>#if defined(__linux__) || defined(__APPLE__)
#include <unistd.h>
#include <syslog.h>
#include "dobby_internal.h"
#include "Interceptor.h"
__attribute__((constructor)) static void ctor() {
DLOG(-1, "================================");
DLOG(-1, "Dobby");
DLOG(-1, "================================");
DLOG(-1, "dobby in debug log mode, disable with cmake flag \"-DDOBBY_DEBUG=OFF\"");
}
PUBLIC const char *DobbyBuildVersion() {
return __DOBBY_BUILD_VERSION__;
}
PUBLIC int DobbyDestroy(void *address) {
Interceptor *interceptor = Interceptor::SharedInstance();
// check if we already hook
HookEntry *entry = interceptor->FindHookEntry(address);
if (entry) {
uint8_t *buffer = entry->origin_chunk_.chunk_buffer;
uint32_t buffer_size = entry->origin_chunk_.chunk.length;
#if defined(TARGET_ARCH_ARM)
address = (void *)((addr_t)address - 1);
#endif
CodePatch(address, buffer, buffer_size);
return RT_SUCCESS;
}
return RT_FAILED;
}
#endif<commit_msg>[misc] update<commit_after>#if defined(__linux__) || defined(__APPLE__)
#include <unistd.h>
#include <syslog.h>
#include "dobby_internal.h"
#include "Interceptor.h"
__attribute__((constructor)) static void ctor() {
DLOG(-1, "================================");
DLOG(-1, "Dobby");
DLOG(-1, "================================");
DLOG(-1, "dobby in debug log mode, disable with cmake flag \"-DDOBBY_DEBUG=OFF\"");
}
PUBLIC const char *DobbyBuildVersion() {
return __DOBBY_BUILD_VERSION__;
}
PUBLIC int DobbyDestroy(void *address) {
// check if we already hook
HookEntry *entry = Interceptor::SharedInstance()->FindHookEntry(address);
if (entry) {
uint8_t *buffer = entry->origin_chunk_.chunk_buffer;
uint32_t buffer_size = entry->origin_chunk_.chunk.length;
#if defined(TARGET_ARCH_ARM)
address = (void *)((addr_t)address - 1);
#endif
CodePatch(address, buffer, buffer_size);
Interceptor::SharedInstance()->RemoveHookEntry(address);
return RT_SUCCESS;
}
return RT_FAILED;
}
#endif<|endoftext|> |
<commit_before>/*
Copyright (c) 2014, William Magato
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
1. Redistributions of source code must retain the above copyright notice,
this list of conditions and the following disclaimer.
2. Redistributions in binary form must reproduce the above copyright notice,
this list of conditions and the following disclaimer in the documentation
and/or other materials provided with the distribution.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDER(S) AND CONTRIBUTORS ''AS IS''
AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER(S) OR CONTRIBUTORS BE LIABLE
FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
The views and conclusions contained in the software and documentation are those
of the authors and should not be interpreted as representing official policies,
either expressed or implied, of the copyright holder(s) or contributors.
*/
#include <cstring>
#include <iostream>
#include <sstream>
#include <llamaos/xen/Hypervisor.h>
#include <llamaos/xen/Shared_memory.h>
#include <llamaos/llamaOS.h>
using std::cout;
using std::endl;
using std::string;
using std::istringstream;
using std::vector;
using namespace llamaos;
using llamaos::xen::Hypervisor;
using llamaos::xen::Shared_memory;
using llamaos::xen::Shared_memory_creator;
using llamaos::xen::Shared_memory_user;
// static const int SHARED_PAGES = 6080;
// static const int SHARED_PAGES = 4096;
static const int SHARED_PAGES = 2048;
// static const int MAX_ENTRIES = 31; // NEED MORE !!!!
static const int MAX_ENTRIES = 28;
// static const int MAX_ENTRIES = 48;
static const int MAX_NAME = 55;
static const int MAX_ALIAS = 47;
#pragma pack(1)
typedef struct
{
uint8_t name [MAX_NAME+1];
uint8_t alias [MAX_ALIAS+1];
uint64_t lock;
uint64_t lock2;
uint64_t offset;
uint64_t size;
} directory_entry_t;
typedef struct
{
uint64_t nodes;
uint64_t barrier_count;
bool barrier_sense;
uint64_t next_offset;
directory_entry_t entries [MAX_ENTRIES];
} directory_t;
#pragma pack()
Shared_memory *Shared_memory::create (const std::string &name, domid_t domid)
{
// check if resource node
size_t pos = name.find("-r.");
if (pos != string::npos)
{
istringstream s(name.substr(pos+3));
int nodes;
s >> nodes;
return new Shared_memory_creator (domid, nodes);
}
pos = name.find("-");
if (pos != string::npos)
{
istringstream s(name.substr(pos+1));
int node;
s >> node;
return new Shared_memory_user (domid, node);
}
return nullptr;
}
Shared_memory::Shared_memory ()
: barrier_sense(false)
{
}
Shared_memory::~Shared_memory ()
{
}
int Shared_memory::open (const std::string &name) const
{
directory_t *directory = reinterpret_cast<directory_t *>(get_pointer ());
if (directory != nullptr)
{
// cout << "nodes: " << directory->nodes << endl;
// cout << "opening " << name << endl;
for (int i = 0; i < MAX_ENTRIES; i++)
{
// cout << " [" << i << "] " << directory->entries [i].name << endl;
// if (__sync_lock_test_and_set(&directory->entries [i].lock, 1) == 0)
if (__sync_fetch_and_add(&directory->entries [i].lock, 1) == 0)
{
cout << " writing to entry " << i << ", " << name.c_str () << endl;
strncpy(reinterpret_cast<char *>(directory->entries [i].name), name.c_str (), MAX_NAME);
wmb();
return i + 200;
}
// cout << " searching in entry " << i << endl;
while (directory->entries [i].name [0] == '\0')
{
cout << " open waiting for entry name to be written: " << i << endl;
mb();
}
if (strncmp(name.c_str(), reinterpret_cast<const char *>(directory->entries [i].name), MAX_NAME) == 0)
{
// cout << " found in entry " << i << endl;
return i + 200;
}
}
}
return -1;
}
void *Shared_memory::map (int fd, uint64_t size) const
{
uint8_t *pointer = get_pointer ();
directory_t *directory = reinterpret_cast<directory_t *>(pointer);
if (directory != nullptr)
{
// cout << "nodes: " << directory->nodes << endl;
cout << "mapping fd " << fd << ", size " << size << endl;
int index = fd - 200;
// uint64_t offset = PAGE_SIZE;
if (__sync_fetch_and_add(&directory->entries [index].lock2, 1) == 0)
{
uint64_t offset = __sync_fetch_and_add(&directory->next_offset, size);
directory->entries [index].offset = offset;
directory->entries [index].size = size;
wmb();
}
while (directory->entries [index].offset == 0)
{
cout << " map waiting for entry offset to be written..." << index << endl;
mb();
}
// for (int i = 0; i < index; i++)
// {
// offset += directory->entries [i].size;
// }
// directory->entries [index].offset = offset;
if ((directory->entries [index].offset + size) > (SHARED_PAGES * PAGE_SIZE))
{
cout << "exceeded shared memory space!!!!!" << endl;
// throw
for (;;);
return nullptr;
}
cout << " mapped to offset " << directory->entries [index].offset << endl;
return pointer + directory->entries [index].offset;
}
return nullptr;
}
void Shared_memory::unmap (int ) const
{
}
void *Shared_memory::get (int fd) const
{
uint8_t *pointer = get_pointer ();
directory_t *directory = reinterpret_cast<directory_t *>(pointer);
if (directory != nullptr)
{
// cout << "nodes: " << directory->nodes << endl;
return pointer + directory->entries [fd - 200].offset;
}
return nullptr;
}
int Shared_memory::get_size () const
{
directory_t *directory = reinterpret_cast<directory_t *>(get_pointer ());
if (directory != nullptr)
{
// cout << "nodes: " << directory->nodes << endl;
for (int i = 0; i < MAX_ENTRIES; i++)
{
if (!directory->entries [i].lock)
{
return i;
}
}
return MAX_ENTRIES;
}
return 0;
}
vector<string> Shared_memory::get_names () const
{
vector<string> names;
directory_t *directory = reinterpret_cast<directory_t *>(get_pointer ());
if (directory != nullptr)
{
// cout << "nodes: " << directory->nodes << endl;
for (int i = 0; i < MAX_ENTRIES; i++)
{
// if (directory->entries [i].name [0] == '\0')
// {
// break;
// }
if (!directory->entries [i].lock)
{
break;
}
while (directory->entries [i].name [0] == '\0')
{
cout << " get_names waiting for entry to be written..." << i << endl;
mb();
}
names.push_back (reinterpret_cast<const char *>(directory->entries [i].name));
}
}
return names;
}
void Shared_memory::put_alias (const string &name, const string &alias) const
{
directory_t *directory = reinterpret_cast<directory_t *>(get_pointer ());
if (directory != nullptr)
{
// cout << "nodes: " << directory->nodes << endl;
for (int i = 0; i < MAX_ENTRIES; i++)
{
// if (directory->entries [i].name [0] == '\0')
// {
// break;
// }
if (!directory->entries [i].lock)
{
break;
}
while (directory->entries [i].name [0] == '\0')
{
cout << " put_alias waiting for entry name to be written..." << i << endl;
mb();
}
if (strncmp(name.c_str(), reinterpret_cast<const char *>(directory->entries [i].name), MAX_NAME) == 0)
{
strncpy(reinterpret_cast<char *>(directory->entries [i].alias), alias.c_str (), MAX_ALIAS);
break;
}
}
}
}
string Shared_memory::get_name (const string &alias) const
{
directory_t *directory = reinterpret_cast<directory_t *>(get_pointer ());
if (directory != nullptr)
{
// cout << "nodes: " << directory->nodes << endl;
for (int i = 0; i < MAX_ENTRIES; i++)
{
// if (directory->entries [i].name [0] == '\0')
// {
// break;
// }
if (!directory->entries [i].lock)
{
break;
}
while (directory->entries [i].alias [0] == '\0')
{
cout << " get_name waiting for entry alias to be written..." << i << endl;
mb();
}
if (strncmp(alias.c_str(), reinterpret_cast<const char *>(directory->entries [i].alias), MAX_ALIAS) == 0)
{
return reinterpret_cast<const char *>(directory->entries [i].name);
}
}
}
return "name not found";
}
void Shared_memory::barrier ()
{
directory_t *directory = reinterpret_cast<directory_t *>(get_pointer ());
// cout << "nodes: " << directory->nodes << endl;
barrier_sense ^= true;
if (__sync_sub_and_fetch (&directory->barrier_count, 1) == 0)
{
cout << "resetting barrier..." << endl;
cout << "barrier: " << directory->barrier_count
<< ", " << directory->barrier_sense
<< ", " << barrier_sense << endl;
cout << "nodes: " << directory->nodes << endl;
directory->barrier_count = directory->nodes;
wmb();
directory->barrier_sense = barrier_sense;
cout << "barrier: " << directory->barrier_count
<< ", " << directory->barrier_sense
<< ", " << barrier_sense << endl;
cout << "nodes: " << directory->nodes << endl;
}
else
{
cout << "barrier: " << directory->barrier_count
<< ", " << directory->barrier_sense
<< ", " << barrier_sense << endl;
cout << "nodes: " << directory->nodes << endl;
while (barrier_sense != directory->barrier_sense)
{
mb();
}
cout << "barrier: " << directory->barrier_count
<< ", " << directory->barrier_sense
<< ", " << barrier_sense << endl;
cout << "nodes: " << directory->nodes << endl;
}
}
static uint8_t *create_pointer (domid_t domid, int nodes)
{
Hypervisor *hypervisor = Hypervisor::get_instance ();
const unsigned int size = SHARED_PAGES * PAGE_SIZE;
uint8_t *pointer = static_cast<uint8_t *>(aligned_alloc (PAGE_SIZE, size));
memset(static_cast<void *>(pointer), 0, size);
for (int i = 0; i < nodes; i++)
{
for (int j = 0; j < SHARED_PAGES; j++)
{
hypervisor->grant_table.grant_access (domid + 1 + i, &pointer [j * PAGE_SIZE]);
}
}
return pointer;
}
Shared_memory_creator::Shared_memory_creator (domid_t domid, int nodes)
: pointer(create_pointer(domid, nodes))
{
directory_t *directory = reinterpret_cast<directory_t *>(pointer);
directory->nodes = nodes;
directory->barrier_count = nodes;
directory->barrier_sense = false;
directory->next_offset = 2 * PAGE_SIZE;
// cout << "nodes: " << directory->nodes << endl;
}
Shared_memory_creator::~Shared_memory_creator ()
{
delete pointer;
}
uint8_t *Shared_memory_creator::get_pointer () const
{
return pointer;
}
Shared_memory_user::Shared_memory_user (domid_t domid, int node)
: grant_map(domid-1-node, (node * SHARED_PAGES), SHARED_PAGES)
// : grant_map(domid-1-node, 49151 - (node * SHARED_PAGES), SHARED_PAGES)
// : grant_map(domid-1-node, 32767 - (node * SHARED_PAGES), SHARED_PAGES)
// : grant_map(domid-1-node, 16383 - (node * SHARED_PAGES), SHARED_PAGES)
{
directory_t *directory = reinterpret_cast<directory_t *>(get_pointer ());
cout << "nodes: " << directory->nodes << endl;
}
uint8_t *Shared_memory_user::get_pointer () const
{
return reinterpret_cast<uint8_t *>(grant_map.get_pointer ());
}
<commit_msg>temp commit, force shared memory to 96 grant frame size<commit_after>/*
Copyright (c) 2014, William Magato
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
1. Redistributions of source code must retain the above copyright notice,
this list of conditions and the following disclaimer.
2. Redistributions in binary form must reproduce the above copyright notice,
this list of conditions and the following disclaimer in the documentation
and/or other materials provided with the distribution.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDER(S) AND CONTRIBUTORS ''AS IS''
AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER(S) OR CONTRIBUTORS BE LIABLE
FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
The views and conclusions contained in the software and documentation are those
of the authors and should not be interpreted as representing official policies,
either expressed or implied, of the copyright holder(s) or contributors.
*/
#include <cstring>
#include <iostream>
#include <sstream>
#include <llamaos/xen/Hypervisor.h>
#include <llamaos/xen/Shared_memory.h>
#include <llamaos/llamaOS.h>
using std::cout;
using std::endl;
using std::string;
using std::istringstream;
using std::vector;
using namespace llamaos;
using llamaos::xen::Hypervisor;
using llamaos::xen::Shared_memory;
using llamaos::xen::Shared_memory_creator;
using llamaos::xen::Shared_memory_user;
// !BAM TEMP - this will not work on default xen config
static const int SHARED_PAGES = 6080;
// static const int SHARED_PAGES = 4096;
// static const int SHARED_PAGES = 2048;
// static const int MAX_ENTRIES = 31; // NEED MORE !!!!
// static const int MAX_ENTRIES = 28;
static const int MAX_ENTRIES = 48;
static const int MAX_NAME = 55;
static const int MAX_ALIAS = 47;
#pragma pack(1)
typedef struct
{
uint8_t name [MAX_NAME+1];
uint8_t alias [MAX_ALIAS+1];
uint64_t lock;
uint64_t lock2;
uint64_t offset;
uint64_t size;
} directory_entry_t;
typedef struct
{
uint64_t nodes;
uint64_t barrier_count;
bool barrier_sense;
uint64_t next_offset;
directory_entry_t entries [MAX_ENTRIES];
} directory_t;
#pragma pack()
Shared_memory *Shared_memory::create (const std::string &name, domid_t domid)
{
// check if resource node
size_t pos = name.find("-r.");
if (pos != string::npos)
{
istringstream s(name.substr(pos+3));
int nodes;
s >> nodes;
return new Shared_memory_creator (domid, nodes);
}
pos = name.find("-");
if (pos != string::npos)
{
istringstream s(name.substr(pos+1));
int node;
s >> node;
return new Shared_memory_user (domid, node);
}
return nullptr;
}
Shared_memory::Shared_memory ()
: barrier_sense(false)
{
}
Shared_memory::~Shared_memory ()
{
}
int Shared_memory::open (const std::string &name) const
{
directory_t *directory = reinterpret_cast<directory_t *>(get_pointer ());
if (directory != nullptr)
{
// cout << "nodes: " << directory->nodes << endl;
// cout << "opening " << name << endl;
for (int i = 0; i < MAX_ENTRIES; i++)
{
// cout << " [" << i << "] " << directory->entries [i].name << endl;
// if (__sync_lock_test_and_set(&directory->entries [i].lock, 1) == 0)
if (__sync_fetch_and_add(&directory->entries [i].lock, 1) == 0)
{
cout << " writing to entry " << i << ", " << name.c_str () << endl;
strncpy(reinterpret_cast<char *>(directory->entries [i].name), name.c_str (), MAX_NAME);
wmb();
return i + 200;
}
// cout << " searching in entry " << i << endl;
while (directory->entries [i].name [0] == '\0')
{
cout << " open waiting for entry name to be written: " << i << endl;
mb();
}
if (strncmp(name.c_str(), reinterpret_cast<const char *>(directory->entries [i].name), MAX_NAME) == 0)
{
// cout << " found in entry " << i << endl;
return i + 200;
}
}
}
return -1;
}
void *Shared_memory::map (int fd, uint64_t size) const
{
uint8_t *pointer = get_pointer ();
directory_t *directory = reinterpret_cast<directory_t *>(pointer);
if (directory != nullptr)
{
// cout << "nodes: " << directory->nodes << endl;
cout << "mapping fd " << fd << ", size " << size << endl;
int index = fd - 200;
// uint64_t offset = PAGE_SIZE;
if (__sync_fetch_and_add(&directory->entries [index].lock2, 1) == 0)
{
uint64_t offset = __sync_fetch_and_add(&directory->next_offset, size);
directory->entries [index].offset = offset;
directory->entries [index].size = size;
wmb();
}
while (directory->entries [index].offset == 0)
{
cout << " map waiting for entry offset to be written..." << index << endl;
mb();
}
// for (int i = 0; i < index; i++)
// {
// offset += directory->entries [i].size;
// }
// directory->entries [index].offset = offset;
if ((directory->entries [index].offset + size) > (SHARED_PAGES * PAGE_SIZE))
{
cout << "exceeded shared memory space!!!!!" << endl;
// throw
for (;;);
return nullptr;
}
cout << " mapped to offset " << directory->entries [index].offset << endl;
return pointer + directory->entries [index].offset;
}
return nullptr;
}
void Shared_memory::unmap (int ) const
{
}
void *Shared_memory::get (int fd) const
{
uint8_t *pointer = get_pointer ();
directory_t *directory = reinterpret_cast<directory_t *>(pointer);
if (directory != nullptr)
{
// cout << "nodes: " << directory->nodes << endl;
return pointer + directory->entries [fd - 200].offset;
}
return nullptr;
}
int Shared_memory::get_size () const
{
directory_t *directory = reinterpret_cast<directory_t *>(get_pointer ());
if (directory != nullptr)
{
// cout << "nodes: " << directory->nodes << endl;
for (int i = 0; i < MAX_ENTRIES; i++)
{
if (!directory->entries [i].lock)
{
return i;
}
}
return MAX_ENTRIES;
}
return 0;
}
vector<string> Shared_memory::get_names () const
{
vector<string> names;
directory_t *directory = reinterpret_cast<directory_t *>(get_pointer ());
if (directory != nullptr)
{
// cout << "nodes: " << directory->nodes << endl;
for (int i = 0; i < MAX_ENTRIES; i++)
{
// if (directory->entries [i].name [0] == '\0')
// {
// break;
// }
if (!directory->entries [i].lock)
{
break;
}
while (directory->entries [i].name [0] == '\0')
{
cout << " get_names waiting for entry to be written..." << i << endl;
mb();
}
names.push_back (reinterpret_cast<const char *>(directory->entries [i].name));
}
}
return names;
}
void Shared_memory::put_alias (const string &name, const string &alias) const
{
directory_t *directory = reinterpret_cast<directory_t *>(get_pointer ());
if (directory != nullptr)
{
// cout << "nodes: " << directory->nodes << endl;
for (int i = 0; i < MAX_ENTRIES; i++)
{
// if (directory->entries [i].name [0] == '\0')
// {
// break;
// }
if (!directory->entries [i].lock)
{
break;
}
while (directory->entries [i].name [0] == '\0')
{
cout << " put_alias waiting for entry name to be written..." << i << endl;
mb();
}
if (strncmp(name.c_str(), reinterpret_cast<const char *>(directory->entries [i].name), MAX_NAME) == 0)
{
strncpy(reinterpret_cast<char *>(directory->entries [i].alias), alias.c_str (), MAX_ALIAS);
break;
}
}
}
}
string Shared_memory::get_name (const string &alias) const
{
directory_t *directory = reinterpret_cast<directory_t *>(get_pointer ());
if (directory != nullptr)
{
// cout << "nodes: " << directory->nodes << endl;
for (int i = 0; i < MAX_ENTRIES; i++)
{
// if (directory->entries [i].name [0] == '\0')
// {
// break;
// }
if (!directory->entries [i].lock)
{
break;
}
while (directory->entries [i].alias [0] == '\0')
{
cout << " get_name waiting for entry alias to be written..." << i << endl;
mb();
}
if (strncmp(alias.c_str(), reinterpret_cast<const char *>(directory->entries [i].alias), MAX_ALIAS) == 0)
{
return reinterpret_cast<const char *>(directory->entries [i].name);
}
}
}
return "name not found";
}
void Shared_memory::barrier ()
{
directory_t *directory = reinterpret_cast<directory_t *>(get_pointer ());
// cout << "nodes: " << directory->nodes << endl;
barrier_sense ^= true;
if (__sync_sub_and_fetch (&directory->barrier_count, 1) == 0)
{
cout << "resetting barrier..." << endl;
cout << "barrier: " << directory->barrier_count
<< ", " << directory->barrier_sense
<< ", " << barrier_sense << endl;
cout << "nodes: " << directory->nodes << endl;
directory->barrier_count = directory->nodes;
wmb();
directory->barrier_sense = barrier_sense;
cout << "barrier: " << directory->barrier_count
<< ", " << directory->barrier_sense
<< ", " << barrier_sense << endl;
cout << "nodes: " << directory->nodes << endl;
}
else
{
cout << "barrier: " << directory->barrier_count
<< ", " << directory->barrier_sense
<< ", " << barrier_sense << endl;
cout << "nodes: " << directory->nodes << endl;
while (barrier_sense != directory->barrier_sense)
{
mb();
}
cout << "barrier: " << directory->barrier_count
<< ", " << directory->barrier_sense
<< ", " << barrier_sense << endl;
cout << "nodes: " << directory->nodes << endl;
}
}
static uint8_t *create_pointer (domid_t domid, int nodes)
{
Hypervisor *hypervisor = Hypervisor::get_instance ();
const unsigned int size = SHARED_PAGES * PAGE_SIZE;
uint8_t *pointer = static_cast<uint8_t *>(aligned_alloc (PAGE_SIZE, size));
memset(static_cast<void *>(pointer), 0, size);
for (int i = 0; i < nodes; i++)
{
for (int j = 0; j < SHARED_PAGES; j++)
{
hypervisor->grant_table.grant_access (domid + 1 + i, &pointer [j * PAGE_SIZE]);
}
}
return pointer;
}
Shared_memory_creator::Shared_memory_creator (domid_t domid, int nodes)
: pointer(create_pointer(domid, nodes))
{
directory_t *directory = reinterpret_cast<directory_t *>(pointer);
directory->nodes = nodes;
directory->barrier_count = nodes;
directory->barrier_sense = false;
directory->next_offset = 2 * PAGE_SIZE;
// cout << "nodes: " << directory->nodes << endl;
}
Shared_memory_creator::~Shared_memory_creator ()
{
delete pointer;
}
uint8_t *Shared_memory_creator::get_pointer () const
{
return pointer;
}
Shared_memory_user::Shared_memory_user (domid_t domid, int node)
: grant_map(domid-1-node, (node * SHARED_PAGES), SHARED_PAGES)
// : grant_map(domid-1-node, 49151 - (node * SHARED_PAGES), SHARED_PAGES)
// : grant_map(domid-1-node, 32767 - (node * SHARED_PAGES), SHARED_PAGES)
// : grant_map(domid-1-node, 16383 - (node * SHARED_PAGES), SHARED_PAGES)
{
directory_t *directory = reinterpret_cast<directory_t *>(get_pointer ());
cout << "nodes: " << directory->nodes << endl;
}
uint8_t *Shared_memory_user::get_pointer () const
{
return reinterpret_cast<uint8_t *>(grant_map.get_pointer ());
}
<|endoftext|> |
<commit_before>/* -*- Mode: C++; c-basic-offset: 2; tab-width: 2; indent-tabs-mode: nil -*-
*
* Quadra, an action puzzle game
* Copyright (C) 1998-2000 Ludus Design
*
* This program 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 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
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*/
#include <string.h>
#include <stdarg.h>
#include <stdio.h>
#include "config.h"
#include "url.h"
#include "http_post.h"
#include "dict.h"
#include "stringtable.h"
#include "video.h"
#include "qserv.h"
RCSID("$Id$")
Dword Qserv::http_addr=0;
int Qserv::http_port=0;
Qserv::Qserv() {
req=NULL;
status[0]=0;
reply=NULL;
const char* host;
int port;
char path[256];
Url url(config.info.game_server_address);
if(!url.getPort())
url.setPort(80);
if(!strcmp(url.getHost(), ""))
url.setHost("ludusdesign.com:80");
if(!strcmp(url.getPath(), "/"))
url.setPath("/cgibin/qserv.pl");
Url proxy(config.info2.proxy_address);
if(!proxy.getPort())
proxy.setPort(80);
if(strlen(proxy.getHost())) {
//Use proxy info for host and port, and full game server address for path
host = proxy.getHost();
port = proxy.getPort();
url.getFull(path);
}
else {
//No proxy configuration, use game server address for everything
host = url.getHost();
port = url.getPort();
strcpy(path, url.getPath());
}
//Use IP cache if set
if(http_addr)
req=new Http_post(host, http_addr, http_port, path);
else
req=new Http_post(host, port, path);
req->add_data_raw("data=");
}
Qserv::~Qserv() {
if(req)
delete req;
if(reply)
delete reply;
}
bool Qserv::done() {
if(!req)
return true;
if(!req->done())
return false;
//Save ip info for future requests
Qserv::http_addr = req->gethostaddr();
Qserv::http_port = req->gethostport();
//Parse reply
reply=new Dict();
if(!req->getsize()) {
strcpy(status, "");
}
else {
Stringtable st(req->getbuf(), req->getsize());
int i=0;
for(i=0; i<st.size(); i++)
if(strlen(st.get(i))==0) { //end of HTTP header
i++; // Skip blank line
if(i>=st.size())
strcpy(status, "");
else {
strncpy(status, st.get(i), sizeof(status)-1);
status[sizeof(status)-1]=0;
i++; // Skip status line
}
break;
}
while(i<st.size()) {
//msgbox("Qserv::done: adding [%-60.60s]\n", st.get(i));
reply->add(st.get(i));
i++;
}
}
delete req;
req=NULL;
msgbox("Qserv::done: done\n");
return true;
}
void Qserv::add_data(const char *s, ...) {
char st[32768];
Textbuf buf;
va_list marker;
va_start(marker, s);
vsprintf(st, s, marker);
va_end(marker);
Http_request::url_encode(st, buf);
req->add_data_raw(buf.get());
}
void Qserv::send() {
req->add_data_encode("info/language %i\n", config.info.language);
req->add_data_encode("info/registered %i\n", 1);
req->add_data_encode("info/quadra_version %i.%i.%i\n", config.major, config.minor, config.patchlevel);
req->add_data_encode("info/platform/os %s\n",
#if defined(UGS_DIRECTX)
"Windows"
#elif defined(UGS_LINUX)
"Linux i386"
#else
#error "What platform???"
#endif
);
if(video_is_dumb)
req->add_data_encode("info/platform/display None\n");
else {
#if defined(UGS_LINUX)
req->add_data_encode("info/platform/display %s\n", video->xwindow ? "Xlib":"Svgalib");
#endif
#if defined(UGS_DIRECTX)
req->add_data_encode("info/platform/display DirectX\n");
#endif
}
req->send();
}
const char *Qserv::get_status() {
if(status[0])
return status;
else
return NULL;
}
Dict *Qserv::get_reply() {
return reply;
}
bool Qserv::isconnected() const {
if(req && req->isconnected())
return true;
return false;
}
Dword Qserv::getnbrecv() const {
int val = 0;
if(req) {
val = req->getsize();
if(val < 0)
val = 0;
}
return val;
}
<commit_msg>Started changing the URL for qserv.<commit_after>/* -*- Mode: C++; c-basic-offset: 2; tab-width: 2; indent-tabs-mode: nil -*-
*
* Quadra, an action puzzle game
* Copyright (C) 1998-2000 Ludus Design
*
* This program 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 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
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*/
#include <string.h>
#include <stdarg.h>
#include <stdio.h>
#include "config.h"
#include "url.h"
#include "http_post.h"
#include "dict.h"
#include "stringtable.h"
#include "video.h"
#include "qserv.h"
RCSID("$Id$")
Dword Qserv::http_addr=0;
int Qserv::http_port=0;
Qserv::Qserv() {
req=NULL;
status[0]=0;
reply=NULL;
const char* host;
int port;
char path[256];
Url url(config.info.game_server_address);
if(!url.getPort())
url.setPort(80);
if(!strcmp(url.getHost(), ""))
url.setHost("ludusdesign.com:80");
if(!strcmp(url.getPath(), "/"))
url.setPath("/cgi-bin/qserv.pl");
Url proxy(config.info2.proxy_address);
if(!proxy.getPort())
proxy.setPort(80);
if(strlen(proxy.getHost())) {
//Use proxy info for host and port, and full game server address for path
host = proxy.getHost();
port = proxy.getPort();
url.getFull(path);
}
else {
//No proxy configuration, use game server address for everything
host = url.getHost();
port = url.getPort();
strcpy(path, url.getPath());
}
//Use IP cache if set
if(http_addr)
req=new Http_post(host, http_addr, http_port, path);
else
req=new Http_post(host, port, path);
req->add_data_raw("data=");
}
Qserv::~Qserv() {
if(req)
delete req;
if(reply)
delete reply;
}
bool Qserv::done() {
if(!req)
return true;
if(!req->done())
return false;
//Save ip info for future requests
Qserv::http_addr = req->gethostaddr();
Qserv::http_port = req->gethostport();
//Parse reply
reply=new Dict();
if(!req->getsize()) {
strcpy(status, "");
}
else {
Stringtable st(req->getbuf(), req->getsize());
int i=0;
for(i=0; i<st.size(); i++)
if(strlen(st.get(i))==0) { //end of HTTP header
i++; // Skip blank line
if(i>=st.size())
strcpy(status, "");
else {
strncpy(status, st.get(i), sizeof(status)-1);
status[sizeof(status)-1]=0;
i++; // Skip status line
}
break;
}
while(i<st.size()) {
//msgbox("Qserv::done: adding [%-60.60s]\n", st.get(i));
reply->add(st.get(i));
i++;
}
}
delete req;
req=NULL;
msgbox("Qserv::done: done\n");
return true;
}
void Qserv::add_data(const char *s, ...) {
char st[32768];
Textbuf buf;
va_list marker;
va_start(marker, s);
vsprintf(st, s, marker);
va_end(marker);
Http_request::url_encode(st, buf);
req->add_data_raw(buf.get());
}
void Qserv::send() {
req->add_data_encode("info/language %i\n", config.info.language);
req->add_data_encode("info/registered %i\n", 1);
req->add_data_encode("info/quadra_version %i.%i.%i\n", config.major, config.minor, config.patchlevel);
req->add_data_encode("info/platform/os %s\n",
#if defined(UGS_DIRECTX)
"Windows"
#elif defined(UGS_LINUX)
"Linux i386"
#else
#error "What platform???"
#endif
);
if(video_is_dumb)
req->add_data_encode("info/platform/display None\n");
else {
#if defined(UGS_LINUX)
req->add_data_encode("info/platform/display %s\n", video->xwindow ? "Xlib":"Svgalib");
#endif
#if defined(UGS_DIRECTX)
req->add_data_encode("info/platform/display DirectX\n");
#endif
}
req->send();
}
const char *Qserv::get_status() {
if(status[0])
return status;
else
return NULL;
}
Dict *Qserv::get_reply() {
return reply;
}
bool Qserv::isconnected() const {
if(req && req->isconnected())
return true;
return false;
}
Dword Qserv::getnbrecv() const {
int val = 0;
if(req) {
val = req->getsize();
if(val < 0)
val = 0;
}
return val;
}
<|endoftext|> |
<commit_before>/* BSD 3-Clause License:
* Copyright (c) 2018, bitsofcotton.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met:
*
* Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation or other materials provided with the distribution.
* Neither the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
#if !defined(_TILT_)
#include <Eigen/Core>
#include <Eigen/LU>
#include <vector>
#include <cmath>
using namespace Eigen;
using std::min;
using std::max;
using std::ceil;
using std::sqrt;
using std::cerr;
using std::endl;
using std::flush;
using std::vector;
using std::abs;
using std::isfinite;
template <typename T> class triangles_t {
public:
Eigen::Matrix<T, 3, 3> p;
Eigen::Matrix<T, 3, 1> n;
T c;
T z;
triangles_t<T>& rotate(const Eigen::Matrix<T, 3, 3>& R, const Eigen::Matrix<T, 3, 1>& origin) {
for(int i = 0; i < 3; i ++)
p.col(i) = R * (p.col(i) - origin) + origin;
return *this;
}
triangles_t<T>& solveN() {
const auto pq(p.col(1) - p.col(0));
const auto pr(p.col(2) - p.col(0));
n[0] = (pq[1] * pr[2] - pq[2] * pr[1]);
n[1] = - (pq[0] * pr[2] - pq[2] * pr[0]);
n[2] = (pq[0] * pr[1] - pq[1] * pr[0]);
if(n.dot(n) > 0)
n /= sqrt(n.dot(n));
z = n.dot(p.col(0));
return *this;
}
};
template <typename T> class match_t;
template <typename T> class tilter {
public:
typedef Matrix<T, Dynamic, Dynamic> Mat;
typedef Matrix<T, 3, 3> Mat3x3;
typedef Matrix<T, 3, 1> Vec3;
typedef Matrix<T, 2, 1> Vec2;
typedef triangles_t<T> Triangles;
tilter();
~tilter();
void initialize(const T& z_ratio);
Mat tilt(const Mat& in, const Mat& bump, const int& idx, const int& samples, const T& psi);
Mat tilt(const Mat& in, const Mat& bump, const match_t<T>& m);
Mat tilt(const Mat& in, const vector<Triangles>& triangles0, const match_t<T>& m);
Mat tilt(const Mat& in, const vector<Triangles>& triangles);
Triangles makeTriangle(const int& u, const int& v, const Mat& in, const Mat& bump, const int& flg);
bool sameSide2(const Vec2& p0, const Vec2& p1, const Vec2& p, const Vec2& q, const bool& extend = true, const T& err = T(1e-5));
bool sameSide2(const Vec3& p0, const Vec3& p1, const Vec3& p, const Vec3& q, const bool& extend = true, const T& err = T(1e-5));
private:
T sgn(const T& x);
bool onTriangle(T& z, const Triangles& tri, const Vec2& geom);
T Pi;
T z_ratio;
};
template <typename T> tilter<T>::tilter() {
initialize(1.);
return;
}
template <typename T> tilter<T>::~tilter() {
;
}
template <typename T> void tilter<T>::initialize(const T& z_ratio) {
this->z_ratio = z_ratio;
Pi = atan2(T(1), T(1)) * T(4);
return;
}
template <typename T> T tilter<T>::sgn(const T& x) {
if(x < T(0))
return - T(1);
if(x > T(0))
return T(1);
return T(0);
}
template <typename T> triangles_t<T> tilter<T>::makeTriangle(const int& u, const int& v, const Mat& in, const Mat& bump, const int& flg) {
Triangles work;
if(flg) {
work.p(0, 0) = u;
work.p(1, 0) = v;
work.p(0, 1) = u + 1;
work.p(1, 1) = v;
work.p(0, 2) = u + 1;
work.p(1, 2) = v + 1;
} else {
work.p(0, 0) = u;
work.p(1, 0) = v;
work.p(0, 1) = u;
work.p(1, 1) = v + 1;
work.p(0, 2) = u + 1;
work.p(1, 2) = v + 1;
}
work.c = T(0);
for(int i = 0; i < 3; i ++) {
work.p(2, i) = bump(int(work.p(0, i)), int(work.p(1, i))) * z_ratio;
work.c += in(int(work.p(0, i)), int(work.p(1, i)));
}
work.c /= T(3);
return work.solveN();
}
template <typename T> bool tilter<T>::sameSide2(const Vec2& p0, const Vec2& p1, const Vec2& p2, const Vec2& q, const bool& extend, const T& err) {
const Vec2 dlt(p1 - p0);
Vec2 dp(p2 - p0);
dp -= dlt.dot(dp) * dlt / dlt.dot(dlt);
// N.B. dp.dot(p1 - p0) >> 0.
return dp.dot(q - p0) >= (extend ? - T(1) : T(1)) * (abs(dp[0]) + abs(dp[1])) * err;
}
template <typename T> bool tilter<T>::sameSide2(const Vec3& p0, const Vec3& p1, const Vec3& p2, const Vec3& q, const bool& extend, const T& err) {
return sameSide2(Vec2(p0[0], p0[1]), Vec2(p1[0], p1[1]),
Vec2(p2[0], p2[1]), Vec2(q[0], q[1]),
extend, err);
}
// <[x, y, t], triangle.n> == triangle.z
template <typename T> bool tilter<T>::onTriangle(T& z, const Triangles& tri, const Vec2& geom) {
Vec3 v0;
Vec3 camera;
v0[0] = 0;
v0[1] = 0;
v0[2] = 1;
camera[0] = geom[0];
camera[1] = geom[1];
camera[2] = 0;
// <v0 t + camera, tri.n> = tri.z
const T t((tri.z - tri.n.dot(camera)) / (tri.n.dot(v0)));
z = camera[2] + v0[2] * t;
return (sameSide2(tri.p.col(0), tri.p.col(1), tri.p.col(2), camera, true, T(.125)) &&
sameSide2(tri.p.col(1), tri.p.col(2), tri.p.col(0), camera, true, T(.125)) &&
sameSide2(tri.p.col(2), tri.p.col(0), tri.p.col(1), camera, true, T(.125)));
}
template <typename T> Eigen::Matrix<T, Eigen::Dynamic, Eigen::Dynamic> tilter<T>::tilt(const Mat& in, const Mat& bump, const int& idx, const int& samples, const T& psi) {
const T theta(2. * Pi * idx / samples);
const T lpsi(Pi * psi);
Mat3x3 R0;
Mat3x3 R1;
R0(0, 0) = cos(theta);
R0(0, 1) = - sin(theta);
R0(0, 2) = 0.;
R0(1, 0) = sin(theta);
R0(1, 1) = cos(theta);
R0(1, 2) = 0.;
R0(2, 0) = 0.;
R0(2, 1) = 0.;
R0(2, 2) = 1.;
R1(0, 0) = 1.;
R1(0, 1) = 0.;
R1(0, 2) = 0.;
R1(1, 0) = 0.;
R1(1, 1) = cos(lpsi);
R1(1, 2) = - sin(lpsi);
R1(2, 0) = 0.;
R1(2, 1) = sin(lpsi);
R1(2, 2) = cos(lpsi);
Vec3 pcenter;
pcenter[0] = T(in.rows() - 1.) / 2;
pcenter[1] = T(in.cols() - 1.) / 2;
pcenter[2] = T(.5);
match_t<T> m;
m.rot = R0.transpose() * R1 * R0;
m.offset = pcenter - m.rot * pcenter;
m.ratio = T(1);
return tilt(in, bump, m);
}
template <typename T> Eigen::Matrix<T, Eigen::Dynamic, Eigen::Dynamic> tilter<T>::tilt(const Mat& in, const Mat& bump, const match_t<T>& m) {
assert(in.rows() == bump.rows() && in.cols() == bump.cols());
vector<Triangles> triangles;
triangles.reserve((in.rows() - 1) * (in.cols() - 1) * 2);
for(int i = 0; i < in.rows() - 1; i ++)
for(int j = 0; j < in.cols() - 1; j ++) {
triangles.push_back(makeTriangle(i, j, in, bump, false));
triangles.push_back(makeTriangle(i, j, in, bump, true));
}
return tilt(in, triangles, m);
}
template <typename T> Eigen::Matrix<T, Eigen::Dynamic, Eigen::Dynamic> tilter<T>::tilt(const Mat& in, const vector<Triangles>& triangles0, const match_t<T>& m) {
vector<Triangles> triangles(triangles0);
for(int j = 0; j < triangles.size(); j ++) {
for(int k = 0; k < 3; k ++)
triangles[j].p.col(k) = m.transform(triangles[j].p.col(k));
triangles[j].solveN();
}
return tilt(in, triangles);
}
template <typename T> Eigen::Matrix<T, Eigen::Dynamic, Eigen::Dynamic> tilter<T>::tilt(const Mat& in, const vector<Triangles>& triangles) {
Mat result(in.rows(), in.cols());
for(int i = 0; i < in.rows(); i ++)
for(int j = 0; j < in.cols(); j ++)
result(i, j) = 0.;
cerr << "t" << flush;
Mat zb(in.rows(), in.cols());
for(int j = 0; j < zb.rows(); j ++)
for(int k = 0; k < zb.cols(); k ++)
zb(j, k) = - T(1e8);
// able to boost with divide and conquer.
#if defined(_OPENMP)
#pragma omp parallel for schedule(static, 1)
#endif
for(int j = 0; j < triangles.size(); j ++) {
const Triangles& tri(triangles[j]);
int ll = int( min(min(tri.p(0, 0), tri.p(0, 1)), tri.p(0, 2)));
int rr = ceil(max(max(tri.p(0, 0), tri.p(0, 1)), tri.p(0, 2))) + 1;
int bb = int( min(min(tri.p(1, 0), tri.p(1, 1)), tri.p(1, 2)));
int tt = ceil(max(max(tri.p(1, 0), tri.p(1, 1)), tri.p(1, 2))) + 1;
for(int y = max(0, ll); y < min(rr, int(in.rows())); y ++)
for(int x = max(0, bb); x < min(tt, int(in.cols())); x ++) {
T z;
Vec2 midgeom;
midgeom[0] = y;
midgeom[1] = x;
#if defined(_OPENMP)
#pragma omp critical
#endif
{
if(onTriangle(z, tri, midgeom) && isfinite(z) && zb(y, x) < z) {
result(y, x) = tri.c;
zb(y, x) = z;
}
}
}
}
return result;
}
#define _TILT_
#endif
<commit_msg>Delete tilt.hh<commit_after><|endoftext|> |
<commit_before>// The libMesh Finite Element Library.
// Copyright (C) 2002-2014 Benjamin S. Kirk, John W. Peterson, Roy H. Stogner
// This library is free software; you can redistribute it and/or
// modify it under the terms of the GNU Lesser General Public
// License as published by the Free Software Foundation; either
// version 2.1 of the License, or (at your option) any later version.
// This library is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
// Lesser General Public License for more details.
// You should have received a copy of the GNU Lesser General Public
// License along with this library; if not, write to the Free Software
// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
// C++ includes
// Local includes
#include "libmesh/libmesh_config.h"
#ifdef LIBMESH_HAVE_EIGEN
#include "libmesh/eigen_sparse_vector.h"
#include "libmesh/eigen_sparse_matrix.h"
#include "libmesh/dense_matrix.h"
#include "libmesh/dof_map.h"
#include "libmesh/sparsity_pattern.h"
namespace libMesh
{
//-----------------------------------------------------------------------
// EigenSparseMatrix members
template <typename T>
void EigenSparseMatrix<T>::init (const numeric_index_type m_in,
const numeric_index_type n_in,
const numeric_index_type libmesh_dbg_var(m_l),
const numeric_index_type libmesh_Dbg_var(n_l),
const numeric_index_type nnz,
const numeric_index_type,
const numeric_index_type)
{
// noz ignored... only used for multiple processors!
libmesh_assert_equal_to (m_in, m_l);
libmesh_assert_equal_to (n_in, n_l);
libmesh_assert_equal_to (m_in, n_in);
libmesh_assert_greater (nnz, 0);
_mat.resize(m_in, n_in);
_mat.reserve(Eigen::Matrix<numeric_index_type, Eigen::Dynamic, 1>::Constant(m_in,nnz));
this->_is_initialized = true;
}
template <typename T>
void EigenSparseMatrix<T>::init ()
{
// Ignore calls on initialized objects
if (this->initialized())
return;
// We need the DofMap for this!
libmesh_assert(this->_dof_map);
// Clear intialized matrices
if (this->initialized())
this->clear();
const numeric_index_type n_rows = this->_dof_map->n_dofs();
const numeric_index_type n_cols = n_rows;
#ifndef NDEBUG
// The following variables are only used for assertions,
// so avoid declaring them when asserts are inactive.
const numeric_index_type n_l = this->_dof_map->n_dofs_on_processor(0);
const numeric_index_type m_l = n_l;
#endif
// Laspack Matrices only work for uniprocessor cases
libmesh_assert_equal_to (n_rows, n_cols);
libmesh_assert_equal_to (m_l, n_rows);
libmesh_assert_equal_to (n_l, n_cols);
const std::vector<numeric_index_type>& n_nz = this->_dof_map->get_n_nz();
#ifndef NDEBUG
// The following variables are only used for assertions,
// so avoid declaring them when asserts are inactive.
const std::vector<numeric_index_type>& n_oz = this->_dof_map->get_n_oz();
#endif
// Make sure the sparsity pattern isn't empty
libmesh_assert_equal_to (n_nz.size(), n_l);
libmesh_assert_equal_to (n_oz.size(), n_l);
if (n_rows==0)
{
_mat.resize(0,0);
return;
}
_mat.resize(n_rows,n_cols);
_mat.reserve(n_nz);
this->_is_initialized = true;
libmesh_assert_equal_to (n_rows, this->m());
libmesh_assert_equal_to (n_cols, this->n());
}
template <typename T>
void EigenSparseMatrix<T>::add_matrix(const DenseMatrix<T>& dm,
const std::vector<numeric_index_type>& rows,
const std::vector<numeric_index_type>& cols)
{
libmesh_assert (this->initialized());
unsigned int n_rows = cast_int<unsigned int>(rows.size());
unsigned int n_cols = cast_int<unsigned int>(cols.size());
libmesh_assert_equal_to (dm.m(), n_rows);
libmesh_assert_equal_to (dm.n(), n_cols);
for (unsigned int i=0; i<n_rows; i++)
for (unsigned int j=0; j<n_cols; j++)
this->add(rows[i],cols[j],dm(i,j));
}
template <typename T>
void EigenSparseMatrix<T>::get_diagonal (NumericVector<T>& dest_in) const
{
EigenSparseVector<T>& dest = cast_ref<EigenSparseVector<T>&>(dest_in);
dest._vec = _mat.diagonal();
}
template <typename T>
void EigenSparseMatrix<T>::get_transpose (SparseMatrix<T>& dest_in) const
{
EigenSparseMatrix<T>& dest = cast_ref<EigenSparseMatrix<T>&>(dest_in);
dest._mat = _mat.transpose();
}
template <typename T>
EigenSparseMatrix<T>::EigenSparseMatrix
(const Parallel::Communicator &comm_in) :
SparseMatrix<T>(comm_in),
_closed (false)
{
}
template <typename T>
EigenSparseMatrix<T>::~EigenSparseMatrix ()
{
this->clear ();
}
template <typename T>
void EigenSparseMatrix<T>::clear ()
{
_mat.resize(0,0);
_closed = false;
this->_is_initialized = false;
}
template <typename T>
void EigenSparseMatrix<T>::zero ()
{
_mat.setZero();
}
template <typename T>
numeric_index_type EigenSparseMatrix<T>::m () const
{
libmesh_assert (this->initialized());
return _mat.rows();
}
template <typename T>
numeric_index_type EigenSparseMatrix<T>::n () const
{
libmesh_assert (this->initialized());
return _mat.cols();
}
template <typename T>
numeric_index_type EigenSparseMatrix<T>::row_start () const
{
return 0;
}
template <typename T>
numeric_index_type EigenSparseMatrix<T>::row_stop () const
{
return this->m();
}
template <typename T>
void EigenSparseMatrix<T>::set (const numeric_index_type i,
const numeric_index_type j,
const T value)
{
libmesh_assert (this->initialized());
libmesh_assert_less (i, this->m());
libmesh_assert_less (j, this->n());
_mat.coeffRef(i,j) = value;
}
template <typename T>
void EigenSparseMatrix<T>::add (const numeric_index_type i,
const numeric_index_type j,
const T value)
{
libmesh_assert (this->initialized());
libmesh_assert_less (i, this->m());
libmesh_assert_less (j, this->n());
_mat.coeffRef(i,j) += value;
}
template <typename T>
void EigenSparseMatrix<T>::add_matrix(const DenseMatrix<T>& dm,
const std::vector<numeric_index_type>& dof_indices)
{
this->add_matrix (dm, dof_indices, dof_indices);
}
template <typename T>
void EigenSparseMatrix<T>::add (const T a_in, SparseMatrix<T> &X_in)
{
libmesh_assert (this->initialized());
libmesh_assert_equal_to (this->m(), X_in.m());
libmesh_assert_equal_to (this->n(), X_in.n());
EigenSparseMatrix<T> &X = cast_ref<EigenSparseMatrix<T>&> (X_in);
_mat += X._mat*a_in;
}
template <typename T>
T EigenSparseMatrix<T>::operator () (const numeric_index_type i,
const numeric_index_type j) const
{
libmesh_assert (this->initialized());
libmesh_assert_less (i, this->m());
libmesh_assert_less (j, this->n());
return _mat.coeff(i,j);
}
//------------------------------------------------------------------
// Explicit instantiations
template class EigenSparseMatrix<Number>;
} // namespace libMesh
#endif // #ifdef LIBMESH_HAVE_EIGEN
<commit_msg>Typo fix<commit_after>// The libMesh Finite Element Library.
// Copyright (C) 2002-2014 Benjamin S. Kirk, John W. Peterson, Roy H. Stogner
// This library is free software; you can redistribute it and/or
// modify it under the terms of the GNU Lesser General Public
// License as published by the Free Software Foundation; either
// version 2.1 of the License, or (at your option) any later version.
// This library is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
// Lesser General Public License for more details.
// You should have received a copy of the GNU Lesser General Public
// License along with this library; if not, write to the Free Software
// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
// C++ includes
// Local includes
#include "libmesh/libmesh_config.h"
#ifdef LIBMESH_HAVE_EIGEN
#include "libmesh/eigen_sparse_vector.h"
#include "libmesh/eigen_sparse_matrix.h"
#include "libmesh/dense_matrix.h"
#include "libmesh/dof_map.h"
#include "libmesh/sparsity_pattern.h"
namespace libMesh
{
//-----------------------------------------------------------------------
// EigenSparseMatrix members
template <typename T>
void EigenSparseMatrix<T>::init (const numeric_index_type m_in,
const numeric_index_type n_in,
const numeric_index_type libmesh_dbg_var(m_l),
const numeric_index_type libmesh_dbg_var(n_l),
const numeric_index_type nnz,
const numeric_index_type,
const numeric_index_type)
{
// noz ignored... only used for multiple processors!
libmesh_assert_equal_to (m_in, m_l);
libmesh_assert_equal_to (n_in, n_l);
libmesh_assert_equal_to (m_in, n_in);
libmesh_assert_greater (nnz, 0);
_mat.resize(m_in, n_in);
_mat.reserve(Eigen::Matrix<numeric_index_type, Eigen::Dynamic, 1>::Constant(m_in,nnz));
this->_is_initialized = true;
}
template <typename T>
void EigenSparseMatrix<T>::init ()
{
// Ignore calls on initialized objects
if (this->initialized())
return;
// We need the DofMap for this!
libmesh_assert(this->_dof_map);
// Clear intialized matrices
if (this->initialized())
this->clear();
const numeric_index_type n_rows = this->_dof_map->n_dofs();
const numeric_index_type n_cols = n_rows;
#ifndef NDEBUG
// The following variables are only used for assertions,
// so avoid declaring them when asserts are inactive.
const numeric_index_type n_l = this->_dof_map->n_dofs_on_processor(0);
const numeric_index_type m_l = n_l;
#endif
// Laspack Matrices only work for uniprocessor cases
libmesh_assert_equal_to (n_rows, n_cols);
libmesh_assert_equal_to (m_l, n_rows);
libmesh_assert_equal_to (n_l, n_cols);
const std::vector<numeric_index_type>& n_nz = this->_dof_map->get_n_nz();
#ifndef NDEBUG
// The following variables are only used for assertions,
// so avoid declaring them when asserts are inactive.
const std::vector<numeric_index_type>& n_oz = this->_dof_map->get_n_oz();
#endif
// Make sure the sparsity pattern isn't empty
libmesh_assert_equal_to (n_nz.size(), n_l);
libmesh_assert_equal_to (n_oz.size(), n_l);
if (n_rows==0)
{
_mat.resize(0,0);
return;
}
_mat.resize(n_rows,n_cols);
_mat.reserve(n_nz);
this->_is_initialized = true;
libmesh_assert_equal_to (n_rows, this->m());
libmesh_assert_equal_to (n_cols, this->n());
}
template <typename T>
void EigenSparseMatrix<T>::add_matrix(const DenseMatrix<T>& dm,
const std::vector<numeric_index_type>& rows,
const std::vector<numeric_index_type>& cols)
{
libmesh_assert (this->initialized());
unsigned int n_rows = cast_int<unsigned int>(rows.size());
unsigned int n_cols = cast_int<unsigned int>(cols.size());
libmesh_assert_equal_to (dm.m(), n_rows);
libmesh_assert_equal_to (dm.n(), n_cols);
for (unsigned int i=0; i<n_rows; i++)
for (unsigned int j=0; j<n_cols; j++)
this->add(rows[i],cols[j],dm(i,j));
}
template <typename T>
void EigenSparseMatrix<T>::get_diagonal (NumericVector<T>& dest_in) const
{
EigenSparseVector<T>& dest = cast_ref<EigenSparseVector<T>&>(dest_in);
dest._vec = _mat.diagonal();
}
template <typename T>
void EigenSparseMatrix<T>::get_transpose (SparseMatrix<T>& dest_in) const
{
EigenSparseMatrix<T>& dest = cast_ref<EigenSparseMatrix<T>&>(dest_in);
dest._mat = _mat.transpose();
}
template <typename T>
EigenSparseMatrix<T>::EigenSparseMatrix
(const Parallel::Communicator &comm_in) :
SparseMatrix<T>(comm_in),
_closed (false)
{
}
template <typename T>
EigenSparseMatrix<T>::~EigenSparseMatrix ()
{
this->clear ();
}
template <typename T>
void EigenSparseMatrix<T>::clear ()
{
_mat.resize(0,0);
_closed = false;
this->_is_initialized = false;
}
template <typename T>
void EigenSparseMatrix<T>::zero ()
{
_mat.setZero();
}
template <typename T>
numeric_index_type EigenSparseMatrix<T>::m () const
{
libmesh_assert (this->initialized());
return _mat.rows();
}
template <typename T>
numeric_index_type EigenSparseMatrix<T>::n () const
{
libmesh_assert (this->initialized());
return _mat.cols();
}
template <typename T>
numeric_index_type EigenSparseMatrix<T>::row_start () const
{
return 0;
}
template <typename T>
numeric_index_type EigenSparseMatrix<T>::row_stop () const
{
return this->m();
}
template <typename T>
void EigenSparseMatrix<T>::set (const numeric_index_type i,
const numeric_index_type j,
const T value)
{
libmesh_assert (this->initialized());
libmesh_assert_less (i, this->m());
libmesh_assert_less (j, this->n());
_mat.coeffRef(i,j) = value;
}
template <typename T>
void EigenSparseMatrix<T>::add (const numeric_index_type i,
const numeric_index_type j,
const T value)
{
libmesh_assert (this->initialized());
libmesh_assert_less (i, this->m());
libmesh_assert_less (j, this->n());
_mat.coeffRef(i,j) += value;
}
template <typename T>
void EigenSparseMatrix<T>::add_matrix(const DenseMatrix<T>& dm,
const std::vector<numeric_index_type>& dof_indices)
{
this->add_matrix (dm, dof_indices, dof_indices);
}
template <typename T>
void EigenSparseMatrix<T>::add (const T a_in, SparseMatrix<T> &X_in)
{
libmesh_assert (this->initialized());
libmesh_assert_equal_to (this->m(), X_in.m());
libmesh_assert_equal_to (this->n(), X_in.n());
EigenSparseMatrix<T> &X = cast_ref<EigenSparseMatrix<T>&> (X_in);
_mat += X._mat*a_in;
}
template <typename T>
T EigenSparseMatrix<T>::operator () (const numeric_index_type i,
const numeric_index_type j) const
{
libmesh_assert (this->initialized());
libmesh_assert_less (i, this->m());
libmesh_assert_less (j, this->n());
return _mat.coeff(i,j);
}
//------------------------------------------------------------------
// Explicit instantiations
template class EigenSparseMatrix<Number>;
} // namespace libMesh
#endif // #ifdef LIBMESH_HAVE_EIGEN
<|endoftext|> |
<commit_before>////////////////////////////////////////////////////////////////////////////
//
// Copyright 2015 Realm 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.
//
////////////////////////////////////////////////////////////////////////////
#include "parser.hpp"
#include <iostream>
#include <pegtl.hh>
#include <pegtl/analyze.hh>
#include <pegtl/trace.hh>
using namespace pegtl;
namespace realm {
namespace parser {
// strings
struct unicode : list< seq< one< 'u' >, rep< 4, must< xdigit > > >, one< '\\' > > {};
struct escaped_char : one< '"', '\'', '\\', '/', 'b', 'f', 'n', 'r', 't' > {};
struct escaped : sor< escaped_char, unicode > {};
struct unescaped : utf8::range< 0x20, 0x10FFFF > {};
struct char_ : if_then_else< one< '\\' >, must< escaped >, unescaped > {};
struct dq_string_content : until< at< one< '"' > >, must< char_ > > {};
struct dq_string : seq< one< '"' >, must< dq_string_content >, any > {};
struct sq_string_content : until< at< one< '\'' > >, must< char_ > > {};
struct sq_string : seq< one< '\'' >, must< sq_string_content >, any > {};
// numbers
struct minus : opt< one< '-' > > {};
struct dot : one< '.' > {};
struct float_num : sor<
seq< plus< digit >, dot, star< digit > >,
seq< star< digit >, dot, plus< digit > >
> {};
struct hex_num : seq< one< '0' >, one< 'x', 'X' >, plus< xdigit > > {};
struct int_num : plus< digit > {};
struct number : seq< minus, sor< float_num, hex_num, int_num > > {};
struct true_value : pegtl_istring_t("true") {};
struct false_value : pegtl_istring_t("false") {};
// key paths
struct key_path : list< seq< sor< alpha, one< '_' > >, star< sor< alnum, one< '_', '-' > > > >, one< '.' > > {};
// argument
struct argument_index : until< at< one< '}' > >, must< digit > > {};
struct argument : seq< one< '{' >, must< argument_index >, any > {};
// expressions and operators
struct expr : sor< dq_string, sq_string, number, argument, true_value, false_value, key_path > {};
struct eq : sor< two< '=' >, one< '=' > > {};
struct noteq : pegtl::string< '!', '=' > {};
struct lteq : pegtl::string< '<', '=' > {};
struct lt : one< '<' > {};
struct gteq : pegtl::string< '>', '=' > {};
struct gt : one< '>' > {};
struct contains : pegtl_istring_t("contains") {};
struct begins : pegtl_istring_t("beginswith") {};
struct ends : pegtl_istring_t("endswith") {};
template<typename A, typename B>
struct pad_plus : seq< plus< B >, A, plus< B > > {};
struct padded_oper : pad_plus< sor< contains, begins, ends >, blank > {};
struct symbolic_oper : pad< sor< eq, noteq, lteq, lt, gteq, gt >, blank > {};
// predicates
struct comparison_pred : seq< expr, sor< padded_oper, symbolic_oper >, expr > {};
struct pred;
struct group_pred : if_must< one< '(' >, pad< pred, blank >, one< ')' > > {};
struct true_pred : pegtl_istring_t("truepredicate") {};
struct false_pred : pegtl_istring_t("falsepredicate") {};
struct not_pre : sor< seq< one< '!' >, star< blank > >, seq< pegtl_istring_t("not"), plus< blank > > > {};
struct atom_pred : seq< opt< not_pre >, pad< sor< group_pred, true_pred, false_pred, comparison_pred >, blank > > {};
struct and_op : sor< pad< two< '&' >, blank >, pad_plus< pegtl_istring_t("and"), blank > > {};
struct or_op : sor< pad< two< '|' >, blank> , pad_plus< pegtl_istring_t("or"), blank > > {};
struct or_ext : if_must< or_op, pred > {};
struct and_ext : if_must< and_op, pred > {};
struct and_pred : seq< atom_pred, star< and_ext > > {};
struct pred : seq< and_pred, star< or_ext > > {};
// state
struct ParserState
{
std::vector<Predicate *> predicate_stack;
Predicate ¤t() {
return *predicate_stack.back();
}
bool negate_next = false;
void addExpression(Expression && exp)
{
if (current().type == Predicate::Type::Comparison) {
current().cmpr.expr[1] = std::move(exp);
predicate_stack.pop_back();
}
else {
Predicate p(Predicate::Type::Comparison);
p.cmpr.expr[0] = std::move(exp);
if (negate_next) {
p.negate = true;
negate_next = false;
}
current().cpnd.sub_predicates.emplace_back(std::move(p));
predicate_stack.push_back(¤t().cpnd.sub_predicates.back());
}
}
};
// rules
template< typename Rule >
struct action : nothing< Rule > {};
template<> struct action< and_ext >
{
static void apply( const input & in, ParserState & state )
{
std::cout << "<and>" << in.string() << std::endl;
// if we were put into an OR group we need to rearrange
auto ¤t = state.current();
if (current.type == Predicate::Type::Or) {
auto &sub_preds = state.current().cpnd.sub_predicates;
auto &second_last = sub_preds[sub_preds.size()-2];
if (second_last.type == Predicate::Type::And) {
// if we are in an OR group and second to last predicate group is
// an AND group then move the last predicate inside
second_last.cpnd.sub_predicates.push_back(std::move(sub_preds.back()));
sub_preds.pop_back();
}
else {
// otherwise combine last two into a new AND group
Predicate pred(Predicate::Type::And);
pred.cpnd.sub_predicates.emplace_back(std::move(second_last));
pred.cpnd.sub_predicates.emplace_back(std::move(sub_preds.back()));
sub_preds.pop_back();
sub_preds.pop_back();
sub_preds.push_back(std::move(pred));
}
}
}
};
template<> struct action< or_ext >
{
static void apply( const input & in, ParserState & state )
{
std::cout << "<or>" << in.string() << std::endl;
// if already an OR group do nothing
auto ¤t = state.current();
if (current.type == Predicate::Type::Or) {
return;
}
// if only two predicates in the group, then convert to OR
auto &sub_preds = state.current().cpnd.sub_predicates;
if (sub_preds.size()) {
current.type = Predicate::Type::Or;
return;
}
// split the current group into to groups which are ORed together
Predicate pred1(Predicate::Type::And), pred2(Predicate::Type::And);
pred1.cpnd.sub_predicates.insert(sub_preds.begin(), sub_preds.back());
pred2.cpnd.sub_predicates.push_back(std::move(sub_preds.back()));
current.type = Predicate::Type::Or;
sub_preds.clear();
sub_preds.emplace_back(std::move(pred1));
sub_preds.emplace_back(std::move(pred2));
}
};
#define EXPRESSION_ACTION(rule, type) \
template<> struct action< rule > { \
static void apply( const input & in, ParserState & state ) { \
std::cout << in.string() << std::endl; \
state.addExpression(Expression(type, in.string())); }};
EXPRESSION_ACTION(dq_string_content, Expression::Type::String)
EXPRESSION_ACTION(sq_string_content, Expression::Type::String)
EXPRESSION_ACTION(key_path, Expression::Type::KeyPath)
EXPRESSION_ACTION(number, Expression::Type::Number)
EXPRESSION_ACTION(true_value, Expression::Type::True)
EXPRESSION_ACTION(false_value, Expression::Type::False)
EXPRESSION_ACTION(argument_index, Expression::Type::Argument)
template<> struct action< true_pred >
{
static void apply( const input & in, ParserState & state )
{
std::cout << in.string() << std::endl;
state.current().cpnd.sub_predicates.emplace_back(Predicate::Type::True);
}
};
template<> struct action< false_pred >
{
static void apply( const input & in, ParserState & state )
{
std::cout << in.string() << std::endl;
state.current().cpnd.sub_predicates.emplace_back(Predicate::Type::False);
}
};
#define OPERATOR_ACTION(rule, oper) \
template<> struct action< rule > { \
static void apply( const input & in, ParserState & state ) { \
std::cout << in.string() << std::endl; \
state.current().cmpr.op = oper; }};
OPERATOR_ACTION(eq, Predicate::Operator::Equal)
OPERATOR_ACTION(noteq, Predicate::Operator::NotEqual)
OPERATOR_ACTION(gteq, Predicate::Operator::GreaterThanOrEqual)
OPERATOR_ACTION(gt, Predicate::Operator::GreaterThan)
OPERATOR_ACTION(lteq, Predicate::Operator::LessThanOrEqual)
OPERATOR_ACTION(lt, Predicate::Operator::LessThan)
OPERATOR_ACTION(begins, Predicate::Operator::BeginsWith)
OPERATOR_ACTION(ends, Predicate::Operator::EndsWith)
OPERATOR_ACTION(contains, Predicate::Operator::Contains)
template<> struct action< one< '(' > >
{
static void apply( const input & in, ParserState & state )
{
std::cout << "<begin_group>" << std::endl;
Predicate group(Predicate::Type::And);
if (state.negate_next) {
group.negate = true;
state.negate_next = false;
}
state.current().cpnd.sub_predicates.emplace_back(std::move(group));
state.predicate_stack.push_back(&state.current().cpnd.sub_predicates.back());
}
};
template<> struct action< group_pred >
{
static void apply( const input & in, ParserState & state )
{
std::cout << "<end_group>" << std::endl;
state.predicate_stack.pop_back();
}
};
template<> struct action< not_pre >
{
static void apply( const input & in, ParserState & state )
{
std::cout << "<not>" << std::endl;
state.negate_next = true;
}
};
Predicate parse(const std::string &query)
{
analyze< pred >();
const std::string source = "user query";
Predicate out_predicate(Predicate::Type::And);
ParserState state;
state.predicate_stack.push_back(&out_predicate);
pegtl::parse< must< pred, eof >, action >(query, source, state);
if (out_predicate.type == Predicate::Type::And && out_predicate.cpnd.sub_predicates.size() == 1) {
return std::move(out_predicate.cpnd.sub_predicates.back());
}
return std::move(out_predicate);
}
}}
<commit_msg>add macro to enable/disable debug token printing<commit_after>////////////////////////////////////////////////////////////////////////////
//
// Copyright 2015 Realm 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.
//
////////////////////////////////////////////////////////////////////////////
#include "parser.hpp"
#include <iostream>
#include <pegtl.hh>
#include <pegtl/analyze.hh>
#include <pegtl/trace.hh>
using namespace pegtl;
namespace realm {
namespace parser {
// strings
struct unicode : list< seq< one< 'u' >, rep< 4, must< xdigit > > >, one< '\\' > > {};
struct escaped_char : one< '"', '\'', '\\', '/', 'b', 'f', 'n', 'r', 't' > {};
struct escaped : sor< escaped_char, unicode > {};
struct unescaped : utf8::range< 0x20, 0x10FFFF > {};
struct char_ : if_then_else< one< '\\' >, must< escaped >, unescaped > {};
struct dq_string_content : until< at< one< '"' > >, must< char_ > > {};
struct dq_string : seq< one< '"' >, must< dq_string_content >, any > {};
struct sq_string_content : until< at< one< '\'' > >, must< char_ > > {};
struct sq_string : seq< one< '\'' >, must< sq_string_content >, any > {};
// numbers
struct minus : opt< one< '-' > > {};
struct dot : one< '.' > {};
struct float_num : sor<
seq< plus< digit >, dot, star< digit > >,
seq< star< digit >, dot, plus< digit > >
> {};
struct hex_num : seq< one< '0' >, one< 'x', 'X' >, plus< xdigit > > {};
struct int_num : plus< digit > {};
struct number : seq< minus, sor< float_num, hex_num, int_num > > {};
struct true_value : pegtl_istring_t("true") {};
struct false_value : pegtl_istring_t("false") {};
// key paths
struct key_path : list< seq< sor< alpha, one< '_' > >, star< sor< alnum, one< '_', '-' > > > >, one< '.' > > {};
// argument
struct argument_index : until< at< one< '}' > >, must< digit > > {};
struct argument : seq< one< '{' >, must< argument_index >, any > {};
// expressions and operators
struct expr : sor< dq_string, sq_string, number, argument, true_value, false_value, key_path > {};
struct eq : sor< two< '=' >, one< '=' > > {};
struct noteq : pegtl::string< '!', '=' > {};
struct lteq : pegtl::string< '<', '=' > {};
struct lt : one< '<' > {};
struct gteq : pegtl::string< '>', '=' > {};
struct gt : one< '>' > {};
struct contains : pegtl_istring_t("contains") {};
struct begins : pegtl_istring_t("beginswith") {};
struct ends : pegtl_istring_t("endswith") {};
template<typename A, typename B>
struct pad_plus : seq< plus< B >, A, plus< B > > {};
struct padded_oper : pad_plus< sor< contains, begins, ends >, blank > {};
struct symbolic_oper : pad< sor< eq, noteq, lteq, lt, gteq, gt >, blank > {};
// predicates
struct comparison_pred : seq< expr, sor< padded_oper, symbolic_oper >, expr > {};
struct pred;
struct group_pred : if_must< one< '(' >, pad< pred, blank >, one< ')' > > {};
struct true_pred : pegtl_istring_t("truepredicate") {};
struct false_pred : pegtl_istring_t("falsepredicate") {};
struct not_pre : sor< seq< one< '!' >, star< blank > >, seq< pegtl_istring_t("not"), plus< blank > > > {};
struct atom_pred : seq< opt< not_pre >, pad< sor< group_pred, true_pred, false_pred, comparison_pred >, blank > > {};
struct and_op : sor< pad< two< '&' >, blank >, pad_plus< pegtl_istring_t("and"), blank > > {};
struct or_op : sor< pad< two< '|' >, blank> , pad_plus< pegtl_istring_t("or"), blank > > {};
struct or_ext : if_must< or_op, pred > {};
struct and_ext : if_must< and_op, pred > {};
struct and_pred : seq< atom_pred, star< and_ext > > {};
struct pred : seq< and_pred, star< or_ext > > {};
// state
struct ParserState
{
std::vector<Predicate *> predicate_stack;
Predicate ¤t() {
return *predicate_stack.back();
}
bool negate_next = false;
void addExpression(Expression && exp)
{
if (current().type == Predicate::Type::Comparison) {
current().cmpr.expr[1] = std::move(exp);
predicate_stack.pop_back();
}
else {
Predicate p(Predicate::Type::Comparison);
p.cmpr.expr[0] = std::move(exp);
if (negate_next) {
p.negate = true;
negate_next = false;
}
current().cpnd.sub_predicates.emplace_back(std::move(p));
predicate_stack.push_back(¤t().cpnd.sub_predicates.back());
}
}
};
// rules
template< typename Rule >
struct action : nothing< Rule > {};
#define REALM_PARSER_PRINT_TOKENS
#ifdef REALM_PARSER_PRINT_TOKENS
#define DEBUG_PRINT_TOKEN(string) std::cout << string << std::endl
#else
#define DEBUG_PRINT_TOKEN(string)
#endif
template<> struct action< and_ext >
{
static void apply( const input & in, ParserState & state )
{
DEBUG_PRINT_TOKEN("<and>");
// if we were put into an OR group we need to rearrange
auto ¤t = state.current();
if (current.type == Predicate::Type::Or) {
auto &sub_preds = state.current().cpnd.sub_predicates;
auto &second_last = sub_preds[sub_preds.size()-2];
if (second_last.type == Predicate::Type::And) {
// if we are in an OR group and second to last predicate group is
// an AND group then move the last predicate inside
second_last.cpnd.sub_predicates.push_back(std::move(sub_preds.back()));
sub_preds.pop_back();
}
else {
// otherwise combine last two into a new AND group
Predicate pred(Predicate::Type::And);
pred.cpnd.sub_predicates.emplace_back(std::move(second_last));
pred.cpnd.sub_predicates.emplace_back(std::move(sub_preds.back()));
sub_preds.pop_back();
sub_preds.pop_back();
sub_preds.push_back(std::move(pred));
}
}
}
};
template<> struct action< or_ext >
{
static void apply( const input & in, ParserState & state )
{
DEBUG_PRINT_TOKEN("<or>");
// if already an OR group do nothing
auto ¤t = state.current();
if (current.type == Predicate::Type::Or) {
return;
}
// if only two predicates in the group, then convert to OR
auto &sub_preds = state.current().cpnd.sub_predicates;
if (sub_preds.size()) {
current.type = Predicate::Type::Or;
return;
}
// split the current group into to groups which are ORed together
Predicate pred1(Predicate::Type::And), pred2(Predicate::Type::And);
pred1.cpnd.sub_predicates.insert(sub_preds.begin(), sub_preds.back());
pred2.cpnd.sub_predicates.push_back(std::move(sub_preds.back()));
current.type = Predicate::Type::Or;
sub_preds.clear();
sub_preds.emplace_back(std::move(pred1));
sub_preds.emplace_back(std::move(pred2));
}
};
#define EXPRESSION_ACTION(rule, type) \
template<> struct action< rule > { \
static void apply( const input & in, ParserState & state ) { \
DEBUG_PRINT_TOKEN(in.string()); \
state.addExpression(Expression(type, in.string())); }};
EXPRESSION_ACTION(dq_string_content, Expression::Type::String)
EXPRESSION_ACTION(sq_string_content, Expression::Type::String)
EXPRESSION_ACTION(key_path, Expression::Type::KeyPath)
EXPRESSION_ACTION(number, Expression::Type::Number)
EXPRESSION_ACTION(true_value, Expression::Type::True)
EXPRESSION_ACTION(false_value, Expression::Type::False)
EXPRESSION_ACTION(argument_index, Expression::Type::Argument)
template<> struct action< true_pred >
{
static void apply( const input & in, ParserState & state )
{
DEBUG_PRINT_TOKEN(in.string());
state.current().cpnd.sub_predicates.emplace_back(Predicate::Type::True);
}
};
template<> struct action< false_pred >
{
static void apply( const input & in, ParserState & state )
{
DEBUG_PRINT_TOKEN(in.string());
state.current().cpnd.sub_predicates.emplace_back(Predicate::Type::False);
}
};
#define OPERATOR_ACTION(rule, oper) \
template<> struct action< rule > { \
static void apply( const input & in, ParserState & state ) { \
DEBUG_PRINT_TOKEN(in.string()); \
state.current().cmpr.op = oper; }};
OPERATOR_ACTION(eq, Predicate::Operator::Equal)
OPERATOR_ACTION(noteq, Predicate::Operator::NotEqual)
OPERATOR_ACTION(gteq, Predicate::Operator::GreaterThanOrEqual)
OPERATOR_ACTION(gt, Predicate::Operator::GreaterThan)
OPERATOR_ACTION(lteq, Predicate::Operator::LessThanOrEqual)
OPERATOR_ACTION(lt, Predicate::Operator::LessThan)
OPERATOR_ACTION(begins, Predicate::Operator::BeginsWith)
OPERATOR_ACTION(ends, Predicate::Operator::EndsWith)
OPERATOR_ACTION(contains, Predicate::Operator::Contains)
template<> struct action< one< '(' > >
{
static void apply( const input & in, ParserState & state )
{
DEBUG_PRINT_TOKEN("<begin_group>");
Predicate group(Predicate::Type::And);
if (state.negate_next) {
group.negate = true;
state.negate_next = false;
}
state.current().cpnd.sub_predicates.emplace_back(std::move(group));
state.predicate_stack.push_back(&state.current().cpnd.sub_predicates.back());
}
};
template<> struct action< group_pred >
{
static void apply( const input & in, ParserState & state )
{
DEBUG_PRINT_TOKEN("<end_group>");
state.predicate_stack.pop_back();
}
};
template<> struct action< not_pre >
{
static void apply( const input & in, ParserState & state )
{
DEBUG_PRINT_TOKEN("<not>");
state.negate_next = true;
}
};
Predicate parse(const std::string &query)
{
analyze< pred >();
const std::string source = "user query";
Predicate out_predicate(Predicate::Type::And);
ParserState state;
state.predicate_stack.push_back(&out_predicate);
pegtl::parse< must< pred, eof >, action >(query, source, state);
if (out_predicate.type == Predicate::Type::And && out_predicate.cpnd.sub_predicates.size() == 1) {
return std::move(out_predicate.cpnd.sub_predicates.back());
}
return std::move(out_predicate);
}
}}
<|endoftext|> |
<commit_before>/*************************************************************************
*
* $RCSfile: xmlexchg.cxx,v $
*
* $Revision: 1.2 $
*
* last change: $Author: obo $ $Date: 2004-11-16 11:21:11 $
*
* 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 EXPRESS 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 _SVX_XMLEXCHG_HXX_
#include "xmlexchg.hxx"
#endif
#ifndef _SOT_FORMATS_HXX
#include <sot/formats.hxx>
#endif
#ifndef _SOT_EXCHANGE_HXX
#include <sot/exchange.hxx>
#endif
//........................................................................
namespace svx
{
//........................................................................
using namespace ::com::sun::star::datatransfer;
//====================================================================
//= OXFormsTransferable
//====================================================================
//--------------------------------------------------------------------
OXFormsTransferable::OXFormsTransferable()
{
}
//--------------------------------------------------------------------
sal_uInt32 OXFormsTransferable::getDescriptorFormatId()
{
static sal_uInt32 s_nFormat = (sal_uInt32)-1;
if ((sal_uInt32)-1 == s_nFormat)
{
s_nFormat = SotExchange::RegisterFormatName( String::CreateFromAscii("application/x-openoffice;windows_formatname=\"???\"") );
OSL_ENSURE( (sal_uInt32)-1 != s_nFormat, "OXFormsTransferable::getDescriptorFormatId: bad exchange id!" );
}
return s_nFormat;
}
//--------------------------------------------------------------------
void OXFormsTransferable::AddSupportedFormats()
{
AddFormat( SOT_FORMATSTR_ID_XFORMS );
}
//--------------------------------------------------------------------
sal_Bool OXFormsTransferable::GetData( const DataFlavor& _rFlavor )
{
const sal_uInt32 nFormatId = SotExchange::GetFormat( _rFlavor );
if ( SOT_FORMATSTR_ID_XFORMS == nFormatId )
{
return SetString( ::rtl::OUString( String::CreateFromAscii("XForms-Transferable") ), _rFlavor );
}
return sal_False;
}
//........................................................................
} // namespace svx
//........................................................................
<commit_msg>INTEGRATION: CWS eforms4 (1.2.22); FILE MERGED 2004/12/06 09:27:42 mbu 1.2.22.1: OXFormsDescriptor handling added<commit_after>/*************************************************************************
*
* $RCSfile: xmlexchg.cxx,v $
*
* $Revision: 1.3 $
*
* last change: $Author: vg $ $Date: 2005-03-23 11:48:57 $
*
* 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 EXPRESS 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 _SVX_XMLEXCHG_HXX_
#include "xmlexchg.hxx"
#endif
#ifndef _SOT_FORMATS_HXX
#include <sot/formats.hxx>
#endif
#ifndef _SOT_EXCHANGE_HXX
#include <sot/exchange.hxx>
#endif
#ifndef _DEBUG_HXX
#include <tools/debug.hxx>
#endif
//........................................................................
namespace svx
{
//........................................................................
using namespace ::com::sun::star::datatransfer;
//====================================================================
//= OXFormsTransferable
//====================================================================
//--------------------------------------------------------------------
OXFormsTransferable::OXFormsTransferable( const OXFormsDescriptor &rhs ) :
m_aDescriptor(rhs)
{
}
//--------------------------------------------------------------------
sal_uInt32 OXFormsTransferable::getDescriptorFormatId()
{
static sal_uInt32 s_nFormat = (sal_uInt32)-1;
if ((sal_uInt32)-1 == s_nFormat)
{
s_nFormat = SotExchange::RegisterFormatName( String::CreateFromAscii("application/x-openoffice;windows_formatname=\"???\"") );
OSL_ENSURE( (sal_uInt32)-1 != s_nFormat, "OXFormsTransferable::getDescriptorFormatId: bad exchange id!" );
}
return s_nFormat;
}
//--------------------------------------------------------------------
void OXFormsTransferable::AddSupportedFormats()
{
AddFormat( SOT_FORMATSTR_ID_XFORMS );
}
//--------------------------------------------------------------------
sal_Bool OXFormsTransferable::GetData( const DataFlavor& _rFlavor )
{
const sal_uInt32 nFormatId = SotExchange::GetFormat( _rFlavor );
if ( SOT_FORMATSTR_ID_XFORMS == nFormatId )
{
return SetString( ::rtl::OUString( String::CreateFromAscii("XForms-Transferable") ), _rFlavor );
}
return sal_False;
}
//--------------------------------------------------------------------
const OXFormsDescriptor &OXFormsTransferable::extractDescriptor( const TransferableDataHelper &_rData ) {
using namespace ::com::sun::star::uno;
using namespace ::com::sun::star::datatransfer;
Reference<XTransferable> &transfer = const_cast<Reference<XTransferable> &>(_rData.GetTransferable());
XTransferable *pInterface = transfer.get();
OXFormsTransferable *pThis = dynamic_cast<OXFormsTransferable *>(pInterface);
DBG_ASSERT(pThis,"XTransferable is NOT an OXFormsTransferable???");
return pThis->m_aDescriptor;
}
//........................................................................
} // namespace svx
//........................................................................
<|endoftext|> |
<commit_before><commit_msg>Resolves: #i123181# Corrected mirroring of shear angle...<commit_after><|endoftext|> |
<commit_before><commit_msg>fixed the German translations<commit_after><|endoftext|> |
<commit_before>/*************************************************************************
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: colmgr.cxx,v $
*
* $Revision: 1.5 $
*
* last change: $Author: obo $ $Date: 2006-09-16 23:01:20 $
*
* 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_sw.hxx"
#include "hintids.hxx"
#ifndef _SVX_LRSPITEM_HXX //autogen
#include <svx/lrspitem.hxx>
#endif
#include "frmmgr.hxx"
#include "frmfmt.hxx"
#include "colmgr.hxx"
// PRIVATE METHODES ------------------------------------------------------
/*------------------------------------------------------------------------
Beschreibung: Spaltenbreite auf aktuelle Breite einstellen
------------------------------------------------------------------------*/
void FitToActualSize(SwFmtCol& rCol, USHORT nWidth)
{
const USHORT nCount = rCol.GetColumns().Count();
for(USHORT i = 0; i < nCount; ++i)
{
const USHORT nTmp = rCol.CalcColWidth(i, nWidth);
rCol.GetColumns()[i]->SetWishWidth(nTmp);
}
rCol.SetWishWidth(nWidth);
}
// PUBLIC METHODES -------------------------------------------------------
/*------------------------------------------------------------------------
Beschreibung: Setzen Spaltenanzahl und Gutterwidth
------------------------------------------------------------------------*/
void SwColMgr::SetCount(USHORT nCount, USHORT nGutterWidth)
{
aFmtCol.Init(nCount, nGutterWidth, nWidth);
aFmtCol.SetWishWidth(nWidth);
aFmtCol.SetGutterWidth(nGutterWidth, nWidth);
}
USHORT SwColMgr::GetGutterWidth( USHORT nPos ) const
{
USHORT nRet;
if(nPos == USHRT_MAX )
nRet = GetCount() > 1 ? aFmtCol.GetGutterWidth() : DEF_GUTTER_WIDTH;
else
{
DBG_ASSERT(nPos < GetCount() - 1, "Spalte ueberindiziert" )
const SwColumns& rCols = aFmtCol.GetColumns();
nRet = rCols.GetObject(nPos)->GetRight() + rCols.GetObject(nPos + 1)->GetLeft();
}
return nRet;
}
/*-----------------22.10.96 14.28-------------------
--------------------------------------------------*/
void SwColMgr::SetGutterWidth(USHORT nGutterWidth, USHORT nPos )
{
if(nPos == USHRT_MAX)
aFmtCol.SetGutterWidth(nGutterWidth, nWidth);
else
{
DBG_ASSERT(nPos < GetCount() - 1, "Spalte ueberindiziert" )
SwColumns& rCols = aFmtCol.GetColumns();
USHORT nGutterWidth2 = nGutterWidth / 2;
rCols.GetObject(nPos)->SetRight(nGutterWidth2);
rCols.GetObject(nPos + 1)->SetLeft(nGutterWidth2);
}
}
/*------------------------------------------------------------------------
Beschreibung: Hoehe Trennlinie
------------------------------------------------------------------------*/
short SwColMgr::GetLineHeightPercent() const
{
return (short)aFmtCol.GetLineHeight();
}
void SwColMgr::SetLineHeightPercent(short nPercent)
{
ASSERT(nPercent <= 100, LineHeight darf nur bis 100 % gross sein);
aFmtCol.SetLineHeight((BYTE)nPercent);
}
/*------------------------------------------------------------------------
Beschreibung: Spaltenbreite
------------------------------------------------------------------------*/
USHORT SwColMgr::GetColWidth(USHORT nIdx) const
{
ASSERT(nIdx < GetCount(), Spaltenarray ueberindiziert.);
return aFmtCol.CalcPrtColWidth(nIdx, nWidth);
}
void SwColMgr::SetColWidth(USHORT nIdx, USHORT nWd)
{
ASSERT(nIdx < GetCount(), Spaltenarray ueberindiziert.);
aFmtCol.GetColumns()[nIdx]->SetWishWidth(nWd);
}
/*--------------------------------------------------------------------
Beschreibung: Groesse neu setzen
--------------------------------------------------------------------*/
void SwColMgr::SetActualWidth(USHORT nW)
{
nWidth = nW;
::FitToActualSize(aFmtCol, nW);
}
/*--------------------------------------------------------------------
Beschreibung: ctor
--------------------------------------------------------------------*/
SwColMgr::SwColMgr(const SfxItemSet& rSet, USHORT nActWidth) :
aFmtCol((const SwFmtCol&)rSet.Get(RES_COL)),
nWidth(nActWidth)
{
if(nWidth == USHRT_MAX)
{
nWidth = (USHORT)((const SwFmtFrmSize&)rSet.Get(RES_FRM_SIZE)).GetWidth();
if (nWidth < MINLAY)
nWidth = USHRT_MAX;
const SvxLRSpaceItem &rLR = (const SvxLRSpaceItem&)rSet.Get(RES_LR_SPACE);
nWidth -= (USHORT)rLR.GetLeft();
nWidth -= (USHORT)rLR.GetRight();
}
::FitToActualSize(aFmtCol, nWidth);
}
SwColMgr::~SwColMgr() {}
<commit_msg>INTEGRATION: CWS swwarnings (1.5.222); FILE MERGED 2007/04/03 13:01:11 tl 1.5.222.1: #i69287# warning-free code<commit_after>/*************************************************************************
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: colmgr.cxx,v $
*
* $Revision: 1.6 $
*
* last change: $Author: hr $ $Date: 2007-09-27 11:51:07 $
*
* 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_sw.hxx"
#include "hintids.hxx"
#ifndef _SVX_LRSPITEM_HXX //autogen
#include <svx/lrspitem.hxx>
#endif
#include "frmmgr.hxx"
#include "frmfmt.hxx"
#include "colmgr.hxx"
// PRIVATE METHODES ------------------------------------------------------
/*------------------------------------------------------------------------
Beschreibung: Spaltenbreite auf aktuelle Breite einstellen
------------------------------------------------------------------------*/
void FitToActualSize(SwFmtCol& rCol, USHORT nWidth)
{
const USHORT nCount = rCol.GetColumns().Count();
for(USHORT i = 0; i < nCount; ++i)
{
const USHORT nTmp = rCol.CalcColWidth(i, nWidth);
rCol.GetColumns()[i]->SetWishWidth(nTmp);
}
rCol.SetWishWidth(nWidth);
}
// PUBLIC METHODES -------------------------------------------------------
/*------------------------------------------------------------------------
Beschreibung: Setzen Spaltenanzahl und Gutterwidth
------------------------------------------------------------------------*/
void SwColMgr::SetCount(USHORT nCount, USHORT nGutterWidth)
{
aFmtCol.Init(nCount, nGutterWidth, nWidth);
aFmtCol.SetWishWidth(nWidth);
aFmtCol.SetGutterWidth(nGutterWidth, nWidth);
}
USHORT SwColMgr::GetGutterWidth( USHORT nPos ) const
{
USHORT nRet;
if(nPos == USHRT_MAX )
nRet = GetCount() > 1 ? aFmtCol.GetGutterWidth() : DEF_GUTTER_WIDTH;
else
{
DBG_ASSERT(nPos < GetCount() - 1, "Spalte ueberindiziert" )
const SwColumns& rCols = aFmtCol.GetColumns();
nRet = rCols.GetObject(nPos)->GetRight() + rCols.GetObject(nPos + 1)->GetLeft();
}
return nRet;
}
/*-----------------22.10.96 14.28-------------------
--------------------------------------------------*/
void SwColMgr::SetGutterWidth(USHORT nGutterWidth, USHORT nPos )
{
if(nPos == USHRT_MAX)
aFmtCol.SetGutterWidth(nGutterWidth, nWidth);
else
{
DBG_ASSERT(nPos < GetCount() - 1, "Spalte ueberindiziert" )
SwColumns& rCols = aFmtCol.GetColumns();
USHORT nGutterWidth2 = nGutterWidth / 2;
rCols.GetObject(nPos)->SetRight(nGutterWidth2);
rCols.GetObject(nPos + 1)->SetLeft(nGutterWidth2);
}
}
/*------------------------------------------------------------------------
Beschreibung: Hoehe Trennlinie
------------------------------------------------------------------------*/
short SwColMgr::GetLineHeightPercent() const
{
return (short)aFmtCol.GetLineHeight();
}
void SwColMgr::SetLineHeightPercent(short nPercent)
{
ASSERT(nPercent <= 100, LineHeight darf nur bis 100 % gross sein);
aFmtCol.SetLineHeight((BYTE)nPercent);
}
/*------------------------------------------------------------------------
Beschreibung: Spaltenbreite
------------------------------------------------------------------------*/
USHORT SwColMgr::GetColWidth(USHORT nIdx) const
{
ASSERT(nIdx < GetCount(), Spaltenarray ueberindiziert.);
return aFmtCol.CalcPrtColWidth(nIdx, nWidth);
}
void SwColMgr::SetColWidth(USHORT nIdx, USHORT nWd)
{
ASSERT(nIdx < GetCount(), Spaltenarray ueberindiziert.);
aFmtCol.GetColumns()[nIdx]->SetWishWidth(nWd);
}
/*--------------------------------------------------------------------
Beschreibung: Groesse neu setzen
--------------------------------------------------------------------*/
void SwColMgr::SetActualWidth(USHORT nW)
{
nWidth = nW;
::FitToActualSize(aFmtCol, nW);
}
/*--------------------------------------------------------------------
Beschreibung: ctor
--------------------------------------------------------------------*/
SwColMgr::SwColMgr(const SfxItemSet& rSet, USHORT nActWidth) :
aFmtCol((const SwFmtCol&)rSet.Get(RES_COL)),
nWidth(nActWidth)
{
if(nWidth == USHRT_MAX)
{
nWidth = (USHORT)((const SwFmtFrmSize&)rSet.Get(RES_FRM_SIZE)).GetWidth();
if (nWidth < MINLAY)
nWidth = USHRT_MAX;
const SvxLRSpaceItem &rLR = (const SvxLRSpaceItem&)rSet.Get(RES_LR_SPACE);
nWidth = nWidth - (USHORT)rLR.GetLeft();
nWidth = nWidth - (USHORT)rLR.GetRight();
}
::FitToActualSize(aFmtCol, nWidth);
}
SwColMgr::~SwColMgr() {}
<|endoftext|> |
<commit_before>/*************************************************************************
*
* $RCSfile: bookmark.cxx,v $
*
* $Revision: 1.5 $
*
* last change: $Author: os $ $Date: 2002-12-05 12:45:04 $
*
* 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): _______________________________________
*
*
************************************************************************/
#ifdef PRECOMPILED
#include "ui_pch.hxx"
#endif
#pragma hdrstop
#ifndef _SFXREQUEST_HXX //autogen
#include <sfx2/request.hxx>
#endif
#ifndef _SFXSTRITEM_HXX //autogen
#include <svtools/stritem.hxx>
#endif
#ifndef _SV_MSGBOX_HXX //autogen
#include <vcl/msgbox.hxx>
#endif
#include "view.hxx"
#include "basesh.hxx"
#include "wrtsh.hxx" //
#include "cmdid.h"
#include "bookmark.hxx" // SwInsertBookmarkDlg
#include "bookmrk.hxx" // SwBookmark
#include "bookmark.hrc"
#include "misc.hrc"
const String BookmarkCombo::aForbiddenChars = String::CreateFromAscii("/\\@:*?\";,.#");
IMPL_LINK( SwInsertBookmarkDlg, ModifyHdl, BookmarkCombo *, pBox )
{
BOOL bSelEntries = pBox->GetSelectEntryCount() != 0;
// if a string has been pasted from the clipboard then
// there may be illegal characters in the box
if(!bSelEntries)
{
String sTmp = pBox->GetText();
USHORT nLen = sTmp.Len();
String sMsg;
for(USHORT i = 0; i < BookmarkCombo::aForbiddenChars.Len(); i++)
{
USHORT nTmpLen = sTmp.Len();
sTmp.EraseAllChars(BookmarkCombo::aForbiddenChars.GetChar(i));
if(sTmp.Len() != nTmpLen)
sMsg += BookmarkCombo::aForbiddenChars.GetChar(i);
}
if(sTmp.Len() != nLen)
{
pBox->SetText(sTmp);
String sWarning(sRemoveWarning);
sWarning += sMsg;
InfoBox(this, sWarning).Execute();
}
}
aOkBtn.Enable(!bSelEntries); // neue Textmarke
aDeleteBtn.Enable(bSelEntries); // loeschbar?
return 0;
}
/*------------------------------------------------------------------------
Beschreibung: Callback zum Loeschen einer Textmarke
-----------------------------------------------------------------------*/
IMPL_LINK( SwInsertBookmarkDlg, DeleteHdl, Button *, EMPTYARG )
{
// Textmarken aus der ComboBox entfernen
for (USHORT i = aBookmarkBox.GetSelectEntryCount(); i; i-- )
aBookmarkBox.RemoveEntry(aBookmarkBox.GetSelectEntryPos(i - 1));
aBookmarkBox.SetText(aEmptyStr);
aDeleteBtn.Enable(FALSE); // keine weiteren Eintraege vorhanden
// aBookmarkBox.SetText(aEmptyStr);
aOkBtn.Enable(); // Im OK Handler wird geloescht
return 0;
}
/*------------------------------------------------------------------------
Beschreibung: Callback fuer OKButton. Fuegt eine neue Textmarke
an die akt. Position ein. Geloeschte Textmarken werden auch am Modell
entfernt.
-----------------------------------------------------------------------*/
void SwInsertBookmarkDlg::Apply()
{
// Textmarke einfuegen
USHORT nLen = aBookmarkBox.GetText().Len();
SwBoxEntry aTmpEntry(aBookmarkBox.GetText(), 0 );
if ( nLen && (aBookmarkBox.GetEntryPos(aTmpEntry) == COMBOBOX_ENTRY_NOTFOUND) )
{
String sEntry(aBookmarkBox.GetText());
sEntry.EraseAllChars(aBookmarkBox.GetMultiSelectionSeparator());
rSh.SetBookmark( KeyCode(), sEntry, aEmptyStr );
rReq.AppendItem( SfxStringItem( FN_INSERT_BOOKMARK, sEntry ) );
rReq.Done();
}
if ( !rReq.IsDone() )
rReq.Ignore();
for (USHORT nCount = aBookmarkBox.GetRemovedCount(); nCount > 0; nCount--)
{
String sRemoved = aBookmarkBox.GetRemovedEntry( nCount -1 ).aName;
rSh.DelBookmark( sRemoved );
SfxRequest aReq( rSh.GetView().GetViewFrame(), FN_DELETE_BOOKMARK );
aReq.AppendItem( SfxStringItem( FN_DELETE_BOOKMARK, sRemoved ) );
aReq.Done();
}
}
/*------------------------------------------------------------------------
Beschreibung: CTOR
-----------------------------------------------------------------------*/
SwInsertBookmarkDlg::SwInsertBookmarkDlg( Window *pParent, SwWrtShell &rS, SfxRequest& rRequest ) :
SvxStandardDialog(pParent,SW_RES(DLG_INSERT_BOOKMARK)),
aBookmarkBox(this,SW_RES(CB_BOOKMARK)),
aBookmarkFl(this,SW_RES(FL_BOOKMARK)),
aOkBtn(this,SW_RES(BT_OK)),
aCancelBtn(this,SW_RES(BT_CANCEL)),
aDeleteBtn(this,SW_RES(BT_DELETE)),
rSh( rS ),
rReq( rRequest )
{
aBookmarkBox.SetModifyHdl(LINK(this, SwInsertBookmarkDlg, ModifyHdl));
aBookmarkBox.EnableMultiSelection(TRUE);
aBookmarkBox.EnableAutocomplete( TRUE, TRUE );
aDeleteBtn.SetClickHdl(LINK(this, SwInsertBookmarkDlg, DeleteHdl));
// Combobox mit vorhandenen Bookmarks fuellen
USHORT nCount = rSh.GetBookmarkCnt(TRUE);
for( USHORT nId = 0; nId < nCount; nId++ )
{
SwBookmark& rBkmk = rSh.GetBookmark( nId, TRUE );
aBookmarkBox.InsertEntry( SwBoxEntry( rBkmk.GetName(), nId ) );
}
FreeResource();
sRemoveWarning = String(SW_RES(STR_REMOVE_WARNING));
}
/*------------------------------------------------------------------------
Beschreibung:
-----------------------------------------------------------------------*/
SwInsertBookmarkDlg::~SwInsertBookmarkDlg()
{
}
/*------------------------------------------------------------------------
Beschreibung:
-----------------------------------------------------------------------*/
BookmarkCombo::BookmarkCombo( Window* pWin, const ResId& rResId ) :
SwComboBox(pWin, rResId)
{
}
/*------------------------------------------------------------------------
Beschreibung:
-----------------------------------------------------------------------*/
USHORT BookmarkCombo::GetFirstSelEntryPos() const
{
return GetSelEntryPos(0);
}
/*------------------------------------------------------------------------
Beschreibung:
-----------------------------------------------------------------------*/
USHORT BookmarkCombo::GetNextSelEntryPos(USHORT nPos) const
{
return GetSelEntryPos(nPos + 1);
}
/*------------------------------------------------------------------------
Beschreibung:
-----------------------------------------------------------------------*/
USHORT BookmarkCombo::GetSelEntryPos(USHORT nPos) const
{
char cSep = GetMultiSelectionSeparator();
USHORT nCnt = GetText().GetTokenCount(cSep);
for (; nPos < nCnt; nPos++)
{
String sEntry(GetText().GetToken(nPos, cSep));
sEntry.EraseLeadingChars();
sEntry.EraseTrailingChars();
if (GetEntryPos(sEntry) != COMBOBOX_ENTRY_NOTFOUND)
return nPos;
}
return COMBOBOX_ENTRY_NOTFOUND;
}
/*------------------------------------------------------------------------
Beschreibung:
-----------------------------------------------------------------------*/
USHORT BookmarkCombo::GetSelectEntryCount() const
{
USHORT nCnt = 0;
USHORT nPos = GetFirstSelEntryPos();
while (nPos != COMBOBOX_ENTRY_NOTFOUND)
{
nPos = GetNextSelEntryPos(nPos);
nCnt++;
}
return nCnt;
}
/*------------------------------------------------------------------------
Beschreibung:
-----------------------------------------------------------------------*/
String BookmarkCombo::GetSelectEntry( USHORT nSelIndex ) const
{
USHORT nCnt = 0;
USHORT nPos = GetFirstSelEntryPos();
String sEntry;
while (nPos != COMBOBOX_ENTRY_NOTFOUND)
{
if (nSelIndex == nCnt)
{
char cSep = GetMultiSelectionSeparator();
sEntry = GetText().GetToken(nPos, cSep);
sEntry.EraseLeadingChars();
sEntry.EraseTrailingChars();
break;
}
nPos = GetNextSelEntryPos(nPos);
nCnt++;
}
return sEntry;
}
/*------------------------------------------------------------------------
Beschreibung: Position in der Listbox (der ComboBox)
-----------------------------------------------------------------------*/
USHORT BookmarkCombo::GetSelectEntryPos( USHORT nSelIndex ) const
{
USHORT nCnt = 0;
USHORT nPos = GetFirstSelEntryPos();
while (nPos != COMBOBOX_ENTRY_NOTFOUND)
{
if (nSelIndex == nCnt)
{
char cSep = GetMultiSelectionSeparator();
String sEntry(GetText().GetToken(nPos, cSep));
sEntry.EraseLeadingChars();
sEntry.EraseTrailingChars();
return GetEntryPos(sEntry);
}
nPos = GetNextSelEntryPos(nPos);
nCnt++;
}
return COMBOBOX_ENTRY_NOTFOUND;
}
/* -----------------05.02.99 08:39-------------------
*
* --------------------------------------------------*/
long BookmarkCombo::PreNotify( NotifyEvent& rNEvt )
{
long nHandled = 0;
if( EVENT_KEYINPUT == rNEvt.GetType() &&
rNEvt.GetKeyEvent()->GetCharCode() )
{
String sKey( rNEvt.GetKeyEvent()->GetCharCode() );
if(STRING_NOTFOUND != aForbiddenChars.Search(sKey))
nHandled = 1;
}
if(!nHandled)
nHandled = SwComboBox::PreNotify( rNEvt );
return nHandled;
}
<commit_msg>INTEGRATION: CWS os8 (1.5.138); FILE MERGED 2003/04/03 07:14:39 os 1.5.138.1: #108583# precompiled headers removed<commit_after>/*************************************************************************
*
* $RCSfile: bookmark.cxx,v $
*
* $Revision: 1.6 $
*
* last change: $Author: vg $ $Date: 2003-04-17 15:35:10 $
*
* 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): _______________________________________
*
*
************************************************************************/
#pragma hdrstop
#ifndef _SFXREQUEST_HXX //autogen
#include <sfx2/request.hxx>
#endif
#ifndef _SFXSTRITEM_HXX //autogen
#include <svtools/stritem.hxx>
#endif
#ifndef _SV_MSGBOX_HXX //autogen
#include <vcl/msgbox.hxx>
#endif
#include "view.hxx"
#include "basesh.hxx"
#include "wrtsh.hxx" //
#include "cmdid.h"
#include "bookmark.hxx" // SwInsertBookmarkDlg
#include "bookmrk.hxx" // SwBookmark
#include "bookmark.hrc"
#include "misc.hrc"
const String BookmarkCombo::aForbiddenChars = String::CreateFromAscii("/\\@:*?\";,.#");
IMPL_LINK( SwInsertBookmarkDlg, ModifyHdl, BookmarkCombo *, pBox )
{
BOOL bSelEntries = pBox->GetSelectEntryCount() != 0;
// if a string has been pasted from the clipboard then
// there may be illegal characters in the box
if(!bSelEntries)
{
String sTmp = pBox->GetText();
USHORT nLen = sTmp.Len();
String sMsg;
for(USHORT i = 0; i < BookmarkCombo::aForbiddenChars.Len(); i++)
{
USHORT nTmpLen = sTmp.Len();
sTmp.EraseAllChars(BookmarkCombo::aForbiddenChars.GetChar(i));
if(sTmp.Len() != nTmpLen)
sMsg += BookmarkCombo::aForbiddenChars.GetChar(i);
}
if(sTmp.Len() != nLen)
{
pBox->SetText(sTmp);
String sWarning(sRemoveWarning);
sWarning += sMsg;
InfoBox(this, sWarning).Execute();
}
}
aOkBtn.Enable(!bSelEntries); // neue Textmarke
aDeleteBtn.Enable(bSelEntries); // loeschbar?
return 0;
}
/*------------------------------------------------------------------------
Beschreibung: Callback zum Loeschen einer Textmarke
-----------------------------------------------------------------------*/
IMPL_LINK( SwInsertBookmarkDlg, DeleteHdl, Button *, EMPTYARG )
{
// Textmarken aus der ComboBox entfernen
for (USHORT i = aBookmarkBox.GetSelectEntryCount(); i; i-- )
aBookmarkBox.RemoveEntry(aBookmarkBox.GetSelectEntryPos(i - 1));
aBookmarkBox.SetText(aEmptyStr);
aDeleteBtn.Enable(FALSE); // keine weiteren Eintraege vorhanden
// aBookmarkBox.SetText(aEmptyStr);
aOkBtn.Enable(); // Im OK Handler wird geloescht
return 0;
}
/*------------------------------------------------------------------------
Beschreibung: Callback fuer OKButton. Fuegt eine neue Textmarke
an die akt. Position ein. Geloeschte Textmarken werden auch am Modell
entfernt.
-----------------------------------------------------------------------*/
void SwInsertBookmarkDlg::Apply()
{
// Textmarke einfuegen
USHORT nLen = aBookmarkBox.GetText().Len();
SwBoxEntry aTmpEntry(aBookmarkBox.GetText(), 0 );
if ( nLen && (aBookmarkBox.GetEntryPos(aTmpEntry) == COMBOBOX_ENTRY_NOTFOUND) )
{
String sEntry(aBookmarkBox.GetText());
sEntry.EraseAllChars(aBookmarkBox.GetMultiSelectionSeparator());
rSh.SetBookmark( KeyCode(), sEntry, aEmptyStr );
rReq.AppendItem( SfxStringItem( FN_INSERT_BOOKMARK, sEntry ) );
rReq.Done();
}
if ( !rReq.IsDone() )
rReq.Ignore();
for (USHORT nCount = aBookmarkBox.GetRemovedCount(); nCount > 0; nCount--)
{
String sRemoved = aBookmarkBox.GetRemovedEntry( nCount -1 ).aName;
rSh.DelBookmark( sRemoved );
SfxRequest aReq( rSh.GetView().GetViewFrame(), FN_DELETE_BOOKMARK );
aReq.AppendItem( SfxStringItem( FN_DELETE_BOOKMARK, sRemoved ) );
aReq.Done();
}
}
/*------------------------------------------------------------------------
Beschreibung: CTOR
-----------------------------------------------------------------------*/
SwInsertBookmarkDlg::SwInsertBookmarkDlg( Window *pParent, SwWrtShell &rS, SfxRequest& rRequest ) :
SvxStandardDialog(pParent,SW_RES(DLG_INSERT_BOOKMARK)),
aBookmarkBox(this,SW_RES(CB_BOOKMARK)),
aBookmarkFl(this,SW_RES(FL_BOOKMARK)),
aOkBtn(this,SW_RES(BT_OK)),
aCancelBtn(this,SW_RES(BT_CANCEL)),
aDeleteBtn(this,SW_RES(BT_DELETE)),
rSh( rS ),
rReq( rRequest )
{
aBookmarkBox.SetModifyHdl(LINK(this, SwInsertBookmarkDlg, ModifyHdl));
aBookmarkBox.EnableMultiSelection(TRUE);
aBookmarkBox.EnableAutocomplete( TRUE, TRUE );
aDeleteBtn.SetClickHdl(LINK(this, SwInsertBookmarkDlg, DeleteHdl));
// Combobox mit vorhandenen Bookmarks fuellen
USHORT nCount = rSh.GetBookmarkCnt(TRUE);
for( USHORT nId = 0; nId < nCount; nId++ )
{
SwBookmark& rBkmk = rSh.GetBookmark( nId, TRUE );
aBookmarkBox.InsertEntry( SwBoxEntry( rBkmk.GetName(), nId ) );
}
FreeResource();
sRemoveWarning = String(SW_RES(STR_REMOVE_WARNING));
}
/*------------------------------------------------------------------------
Beschreibung:
-----------------------------------------------------------------------*/
SwInsertBookmarkDlg::~SwInsertBookmarkDlg()
{
}
/*------------------------------------------------------------------------
Beschreibung:
-----------------------------------------------------------------------*/
BookmarkCombo::BookmarkCombo( Window* pWin, const ResId& rResId ) :
SwComboBox(pWin, rResId)
{
}
/*------------------------------------------------------------------------
Beschreibung:
-----------------------------------------------------------------------*/
USHORT BookmarkCombo::GetFirstSelEntryPos() const
{
return GetSelEntryPos(0);
}
/*------------------------------------------------------------------------
Beschreibung:
-----------------------------------------------------------------------*/
USHORT BookmarkCombo::GetNextSelEntryPos(USHORT nPos) const
{
return GetSelEntryPos(nPos + 1);
}
/*------------------------------------------------------------------------
Beschreibung:
-----------------------------------------------------------------------*/
USHORT BookmarkCombo::GetSelEntryPos(USHORT nPos) const
{
char cSep = GetMultiSelectionSeparator();
USHORT nCnt = GetText().GetTokenCount(cSep);
for (; nPos < nCnt; nPos++)
{
String sEntry(GetText().GetToken(nPos, cSep));
sEntry.EraseLeadingChars();
sEntry.EraseTrailingChars();
if (GetEntryPos(sEntry) != COMBOBOX_ENTRY_NOTFOUND)
return nPos;
}
return COMBOBOX_ENTRY_NOTFOUND;
}
/*------------------------------------------------------------------------
Beschreibung:
-----------------------------------------------------------------------*/
USHORT BookmarkCombo::GetSelectEntryCount() const
{
USHORT nCnt = 0;
USHORT nPos = GetFirstSelEntryPos();
while (nPos != COMBOBOX_ENTRY_NOTFOUND)
{
nPos = GetNextSelEntryPos(nPos);
nCnt++;
}
return nCnt;
}
/*------------------------------------------------------------------------
Beschreibung:
-----------------------------------------------------------------------*/
String BookmarkCombo::GetSelectEntry( USHORT nSelIndex ) const
{
USHORT nCnt = 0;
USHORT nPos = GetFirstSelEntryPos();
String sEntry;
while (nPos != COMBOBOX_ENTRY_NOTFOUND)
{
if (nSelIndex == nCnt)
{
char cSep = GetMultiSelectionSeparator();
sEntry = GetText().GetToken(nPos, cSep);
sEntry.EraseLeadingChars();
sEntry.EraseTrailingChars();
break;
}
nPos = GetNextSelEntryPos(nPos);
nCnt++;
}
return sEntry;
}
/*------------------------------------------------------------------------
Beschreibung: Position in der Listbox (der ComboBox)
-----------------------------------------------------------------------*/
USHORT BookmarkCombo::GetSelectEntryPos( USHORT nSelIndex ) const
{
USHORT nCnt = 0;
USHORT nPos = GetFirstSelEntryPos();
while (nPos != COMBOBOX_ENTRY_NOTFOUND)
{
if (nSelIndex == nCnt)
{
char cSep = GetMultiSelectionSeparator();
String sEntry(GetText().GetToken(nPos, cSep));
sEntry.EraseLeadingChars();
sEntry.EraseTrailingChars();
return GetEntryPos(sEntry);
}
nPos = GetNextSelEntryPos(nPos);
nCnt++;
}
return COMBOBOX_ENTRY_NOTFOUND;
}
/* -----------------05.02.99 08:39-------------------
*
* --------------------------------------------------*/
long BookmarkCombo::PreNotify( NotifyEvent& rNEvt )
{
long nHandled = 0;
if( EVENT_KEYINPUT == rNEvt.GetType() &&
rNEvt.GetKeyEvent()->GetCharCode() )
{
String sKey( rNEvt.GetKeyEvent()->GetCharCode() );
if(STRING_NOTFOUND != aForbiddenChars.Search(sKey))
nHandled = 1;
}
if(!nHandled)
nHandled = SwComboBox::PreNotify( rNEvt );
return nHandled;
}
<|endoftext|> |
<commit_before>/*************************************************************************
*
* $RCSfile: tbxmgr.cxx,v $
*
* $Revision: 1.4 $
*
* last change: $Author: obo $ $Date: 2004-07-06 11:33:21 $
*
* 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): _______________________________________
*
*
************************************************************************/
#pragma hdrstop
#include "cmdid.h"
#include "swtypes.hxx" // nur wegen aEmptyString??
#include "errhdl.hxx"
#include "wdocsh.hxx"
#include "tbxmgr.hxx"
/*************************************************************************
|*
|*
|*
\************************************************************************/
/*
SwPopupWindowTbxMgr::SwPopupWindowTbxMgr( USHORT nId, WindowAlign eAlign,
ResId aRIdWin, ResId aRIdTbx,
SfxBindings& rBindings ) :
SvxPopupWindowTbxMgr( nId, eAlign, aRIdWin, aRIdTbx ),
bWeb(FALSE),
aRIdWinTemp(aRIdWin),
aRIdTbxTemp(aRIdTbx),
eAlignment( eAlign ),
mrBindings( rBindings )
{
SfxObjectShell* pObjShell = SfxObjectShell::Current();
if(PTR_CAST(SwWebDocShell, pObjShell))
{
bWeb = TRUE;
ToolBox& rTbx = GetTbxMgr().GetToolBox();
// jetzt muessen ein paar Items aus der Toolbox versteckt werden:
switch(nId)
{
case FN_INSERT_CTRL:
rTbx.ShowItem(FN_INSERT_FRAME_INTERACT_NOCOL);
rTbx.HideItem(FN_INSERT_FRAME_INTERACT);
rTbx.HideItem(FN_INSERT_FOOTNOTE);
rTbx.HideItem(FN_INSERT_ENDNOTE);
rTbx.HideItem(FN_PAGE_STYLE_SET_COLS);
rTbx.HideItem(FN_INSERT_IDX_ENTRY_DLG);
break;
case FN_INSERT_FIELD_CTRL:
rTbx.HideItem(FN_INSERT_FLD_PGNUMBER);
rTbx.HideItem(FN_INSERT_FLD_PGCOUNT);
rTbx.HideItem(FN_INSERT_FLD_TOPIC);
rTbx.HideItem(FN_INSERT_FLD_TITLE);
break;
}
}
else if( FN_INSERT_CTRL == nId)
{
ToolBox& rTbx = GetTbxMgr().GetToolBox();
rTbx.ShowItem(FN_INSERT_FRAME_INTERACT);
rTbx.HideItem(FN_INSERT_FRAME_INTERACT_NOCOL);
}
Size aSize = GetTbxMgr().CalcWindowSizePixel();
GetTbxMgr().SetPosSizePixel( Point(), aSize );
SetOutputSizePixel( aSize );
}
*/
/*************************************************************************
|*
|*
|*
\************************************************************************/
/*
void SwPopupWindowTbxMgr::StateChanged(USHORT nSID, SfxItemState eState,
const SfxPoolItem* pState)
{
static USHORT __READONLY_DATA aInsertCtrl[] =
{
FN_INSERT_FRAME_INTERACT,
FN_INSERT_FOOTNOTE,
FN_INSERT_ENDNOTE,
FN_PAGE_STYLE_SET_COLS,
FN_INSERT_IDX_ENTRY_DLG,
0
};
static USHORT __READONLY_DATA aInsertFld[] =
{
FN_INSERT_FLD_PGNUMBER,
FN_INSERT_FLD_PGCOUNT,
FN_INSERT_FLD_TOPIC,
FN_INSERT_FLD_TITLE,
0
};
SfxObjectShell* pObjShell = SfxObjectShell::Current();
BOOL bNewWeb = 0 != PTR_CAST(SwWebDocShell, pObjShell);
if(bWeb != bNewWeb)
{
bWeb = bNewWeb;
ToolBox& rTbx = GetTbxMgr().GetToolBox();
// jetzt muessen ein paar Items aus der Toolbox versteckt werden:
const USHORT* pSid = 0;
switch(nSID)
{
case FN_INSERT_CTRL:
pSid = &aInsertCtrl[0];
if(bWeb)
rTbx.ShowItem(FN_INSERT_FRAME_INTERACT_NOCOL);
else
rTbx.HideItem(FN_INSERT_FRAME_INTERACT_NOCOL);
break;
case FN_INSERT_FIELD_CTRL:
pSid = & aInsertFld[0];
break;
}
if(pSid)
{
if(bWeb)
while(*pSid)
{
rTbx.HideItem(*pSid);
pSid++;
}
else
while(*pSid)
{
rTbx.ShowItem(*pSid);
pSid++;
}
Size aSize = GetTbxMgr().CalcWindowSizePixel();
GetTbxMgr().SetPosSizePixel( Point(), aSize );
SetOutputSizePixel( aSize );
}
}
SfxPopupWindow::StateChanged(nSID, eState, pState);
}
*/
/*
SfxPopupWindow* SwPopupWindowTbxMgr::Clone() const
{
return new SwPopupWindowTbxMgr(
GetId(),
eAlignment,
// ((SwPopupWindowTbxMgr*)this)->GetTbxMgr().GetToolBox().GetAlign(),
aRIdWinTemp,
aRIdTbxTemp,
mrBindings
// (SfxBindings&)GetBindings()
);
}
*/
<commit_msg>INTEGRATION: CWS ooo19126 (1.4.692); FILE MERGED 2005/09/05 13:47:07 rt 1.4.692.1: #i54170# Change license header: remove SISSL<commit_after>/*************************************************************************
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: tbxmgr.cxx,v $
*
* $Revision: 1.5 $
*
* last change: $Author: rt $ $Date: 2005-09-09 10:47:20 $
*
* 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
*
************************************************************************/
#pragma hdrstop
#include "cmdid.h"
#include "swtypes.hxx" // nur wegen aEmptyString??
#include "errhdl.hxx"
#include "wdocsh.hxx"
#include "tbxmgr.hxx"
/*************************************************************************
|*
|*
|*
\************************************************************************/
/*
SwPopupWindowTbxMgr::SwPopupWindowTbxMgr( USHORT nId, WindowAlign eAlign,
ResId aRIdWin, ResId aRIdTbx,
SfxBindings& rBindings ) :
SvxPopupWindowTbxMgr( nId, eAlign, aRIdWin, aRIdTbx ),
bWeb(FALSE),
aRIdWinTemp(aRIdWin),
aRIdTbxTemp(aRIdTbx),
eAlignment( eAlign ),
mrBindings( rBindings )
{
SfxObjectShell* pObjShell = SfxObjectShell::Current();
if(PTR_CAST(SwWebDocShell, pObjShell))
{
bWeb = TRUE;
ToolBox& rTbx = GetTbxMgr().GetToolBox();
// jetzt muessen ein paar Items aus der Toolbox versteckt werden:
switch(nId)
{
case FN_INSERT_CTRL:
rTbx.ShowItem(FN_INSERT_FRAME_INTERACT_NOCOL);
rTbx.HideItem(FN_INSERT_FRAME_INTERACT);
rTbx.HideItem(FN_INSERT_FOOTNOTE);
rTbx.HideItem(FN_INSERT_ENDNOTE);
rTbx.HideItem(FN_PAGE_STYLE_SET_COLS);
rTbx.HideItem(FN_INSERT_IDX_ENTRY_DLG);
break;
case FN_INSERT_FIELD_CTRL:
rTbx.HideItem(FN_INSERT_FLD_PGNUMBER);
rTbx.HideItem(FN_INSERT_FLD_PGCOUNT);
rTbx.HideItem(FN_INSERT_FLD_TOPIC);
rTbx.HideItem(FN_INSERT_FLD_TITLE);
break;
}
}
else if( FN_INSERT_CTRL == nId)
{
ToolBox& rTbx = GetTbxMgr().GetToolBox();
rTbx.ShowItem(FN_INSERT_FRAME_INTERACT);
rTbx.HideItem(FN_INSERT_FRAME_INTERACT_NOCOL);
}
Size aSize = GetTbxMgr().CalcWindowSizePixel();
GetTbxMgr().SetPosSizePixel( Point(), aSize );
SetOutputSizePixel( aSize );
}
*/
/*************************************************************************
|*
|*
|*
\************************************************************************/
/*
void SwPopupWindowTbxMgr::StateChanged(USHORT nSID, SfxItemState eState,
const SfxPoolItem* pState)
{
static USHORT __READONLY_DATA aInsertCtrl[] =
{
FN_INSERT_FRAME_INTERACT,
FN_INSERT_FOOTNOTE,
FN_INSERT_ENDNOTE,
FN_PAGE_STYLE_SET_COLS,
FN_INSERT_IDX_ENTRY_DLG,
0
};
static USHORT __READONLY_DATA aInsertFld[] =
{
FN_INSERT_FLD_PGNUMBER,
FN_INSERT_FLD_PGCOUNT,
FN_INSERT_FLD_TOPIC,
FN_INSERT_FLD_TITLE,
0
};
SfxObjectShell* pObjShell = SfxObjectShell::Current();
BOOL bNewWeb = 0 != PTR_CAST(SwWebDocShell, pObjShell);
if(bWeb != bNewWeb)
{
bWeb = bNewWeb;
ToolBox& rTbx = GetTbxMgr().GetToolBox();
// jetzt muessen ein paar Items aus der Toolbox versteckt werden:
const USHORT* pSid = 0;
switch(nSID)
{
case FN_INSERT_CTRL:
pSid = &aInsertCtrl[0];
if(bWeb)
rTbx.ShowItem(FN_INSERT_FRAME_INTERACT_NOCOL);
else
rTbx.HideItem(FN_INSERT_FRAME_INTERACT_NOCOL);
break;
case FN_INSERT_FIELD_CTRL:
pSid = & aInsertFld[0];
break;
}
if(pSid)
{
if(bWeb)
while(*pSid)
{
rTbx.HideItem(*pSid);
pSid++;
}
else
while(*pSid)
{
rTbx.ShowItem(*pSid);
pSid++;
}
Size aSize = GetTbxMgr().CalcWindowSizePixel();
GetTbxMgr().SetPosSizePixel( Point(), aSize );
SetOutputSizePixel( aSize );
}
}
SfxPopupWindow::StateChanged(nSID, eState, pState);
}
*/
/*
SfxPopupWindow* SwPopupWindowTbxMgr::Clone() const
{
return new SwPopupWindowTbxMgr(
GetId(),
eAlignment,
// ((SwPopupWindowTbxMgr*)this)->GetTbxMgr().GetToolBox().GetAlign(),
aRIdWinTemp,
aRIdTbxTemp,
mrBindings
// (SfxBindings&)GetBindings()
);
}
*/
<|endoftext|> |
<commit_before>/*************************************************************************
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: uiitems.cxx,v $
*
* $Revision: 1.11 $
*
* last change: $Author: hr $ $Date: 2007-09-27 12:49:33 $
*
* 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_sw.hxx"
#ifndef _SVX_ITEMTYPE_HXX
#include <svx/itemtype.hxx>
#endif
#ifndef _UNOSETT_HXX
#include <unosett.hxx>
#endif
#include "swtypes.hxx"
#include "cmdid.h"
#include "pagedesc.hxx"
#include "uiitems.hxx"
#include "utlui.hrc"
#include "attrdesc.hrc"
#ifndef _UNOMID_H
#include <unomid.h>
#endif
using namespace ::com::sun::star;
using namespace ::com::sun::star::uno;
// Breitenangaben der Fussnotenlinien, mit TabPage abstimmen
static const USHORT __FAR_DATA nFtnLines[] = {
0,
10,
50,
80,
100,
150
};
#define FTN_LINE_STYLE_COUNT 5
SwPageFtnInfoItem::SwPageFtnInfoItem( const USHORT nId, SwPageFtnInfo& rInfo) :
SfxPoolItem( nId ),
aFtnInfo(rInfo)
{
}
SwPageFtnInfoItem::SwPageFtnInfoItem( const SwPageFtnInfoItem& rItem ) :
SfxPoolItem( rItem ),
aFtnInfo(rItem.GetPageFtnInfo())
{
}
SwPageFtnInfoItem::~SwPageFtnInfoItem()
{
}
SfxPoolItem* SwPageFtnInfoItem::Clone( SfxItemPool * /*pPool*/ ) const
{
return new SwPageFtnInfoItem( *this );
}
int SwPageFtnInfoItem::operator==( const SfxPoolItem& rAttr ) const
{
DBG_ASSERT( Which() == rAttr.Which(), "keine gleichen Attribute" );
return ( aFtnInfo == ((SwPageFtnInfoItem&)rAttr).GetPageFtnInfo());
}
SfxItemPresentation SwPageFtnInfoItem::GetPresentation
(
SfxItemPresentation ePres,
SfxMapUnit eCoreUnit,
SfxMapUnit ePresUnit,
String& rText,
const IntlWrapper* pIntl
) const
{
switch ( ePres )
{
case SFX_ITEM_PRESENTATION_NONE:
rText.Erase();
return SFX_ITEM_PRESENTATION_NONE;
case SFX_ITEM_PRESENTATION_NAMELESS:
case SFX_ITEM_PRESENTATION_COMPLETE:
{
USHORT nHght = (USHORT) GetPageFtnInfo().GetHeight();
if ( nHght )
{
rText = SW_RESSTR( STR_MAX_FTN_HEIGHT );
rText += ' ';
rText += ::GetMetricText( nHght, eCoreUnit, ePresUnit, pIntl );
rText += ::GetSvxString( ::GetMetricId( ePresUnit ) );
}
return ePres;
}
default:; //prevent warning
}
return SFX_ITEM_PRESENTATION_NONE;
}
/* -----------------------------26.04.01 12:25--------------------------------
---------------------------------------------------------------------------*/
BOOL SwPageFtnInfoItem::QueryValue( Any& rVal, BYTE nMemberId ) const
{
sal_Bool bRet = sal_True;
switch(nMemberId & ~CONVERT_TWIPS)
{
case MID_FTN_HEIGHT : rVal <<= (sal_Int32)TWIP_TO_MM100(aFtnInfo.GetHeight());break;
case MID_LINE_WEIGHT : rVal <<= (sal_Int16)TWIP_TO_MM100_UNSIGNED(aFtnInfo.GetLineWidth());break;
case MID_LINE_COLOR : rVal <<= (sal_Int32)aFtnInfo.GetLineColor().GetColor();break;
case MID_LINE_RELWIDTH :
{
Fraction aTmp( 100, 1 );
aTmp *= aFtnInfo.GetWidth();
rVal <<= (sal_Int8)(long)aTmp;
}
break;
case MID_LINE_ADJUST : rVal <<= (sal_Int16)aFtnInfo.GetAdj();break;//text::HorizontalAdjust
case MID_LINE_TEXT_DIST : rVal <<= (sal_Int32)TWIP_TO_MM100(aFtnInfo.GetTopDist());break;
case MID_LINE_FOOTNOTE_DIST: rVal <<= (sal_Int32)TWIP_TO_MM100(aFtnInfo.GetBottomDist());break;
default:
bRet = sal_False;
}
return bRet;
}
/* -----------------------------26.04.01 12:26--------------------------------
---------------------------------------------------------------------------*/
BOOL SwPageFtnInfoItem::PutValue(const Any& rVal, BYTE nMemberId)
{
sal_Int32 nSet32;
sal_Bool bRet = sal_True;
switch(nMemberId & ~CONVERT_TWIPS)
{
case MID_LINE_COLOR :
rVal >>= nSet32;
aFtnInfo.SetLineColor(nSet32);
break;
case MID_FTN_HEIGHT:
case MID_LINE_TEXT_DIST :
case MID_LINE_FOOTNOTE_DIST:
rVal >>= nSet32;
if(nSet32 < 0)
bRet = sal_False;
else
{
nSet32 = MM100_TO_TWIP(nSet32);
switch(nMemberId & ~CONVERT_TWIPS)
{
case MID_FTN_HEIGHT: aFtnInfo.SetHeight(nSet32); break;
case MID_LINE_TEXT_DIST: aFtnInfo.SetTopDist(nSet32);break;
case MID_LINE_FOOTNOTE_DIST: aFtnInfo.SetBottomDist(nSet32);break;
}
}
break;
case MID_LINE_WEIGHT :
{
sal_Int16 nSet; rVal >>= nSet;
if(nSet >= 0)
aFtnInfo.SetLineWidth(MM100_TO_TWIP(nSet));
else
bRet = sal_False;
}
break;
case MID_LINE_RELWIDTH :
{
sal_Int8 nSet; rVal >>= nSet;
if(nSet < 0)
bRet = sal_False;
else
aFtnInfo.SetWidth(Fraction(nSet, 100));
}
break;
case MID_LINE_ADJUST :
{
sal_Int16 nSet; rVal >>= nSet;
if(nSet >= 0 && nSet < 3) //text::HorizontalAdjust
aFtnInfo.SetAdj((SwFtnAdj)nSet);
else
bRet = sal_False;
}
break;
default:
bRet = sal_False;
}
return bRet;
}
SwPtrItem::SwPtrItem( const USHORT nId, void* pPtr ) :
SfxPoolItem( nId ),
pMisc(pPtr)
{
}
/*--------------------------------------------------------------------
Beschreibung: Copy-Konstruktor
--------------------------------------------------------------------*/
SwPtrItem::SwPtrItem( const SwPtrItem& rItem ) : SfxPoolItem( rItem )
{
pMisc = rItem.pMisc;
}
/*--------------------------------------------------------------------
Beschreibung: Clonen
--------------------------------------------------------------------*/
SfxPoolItem* SwPtrItem::Clone( SfxItemPool * /*pPool*/ ) const
{
return new SwPtrItem( *this );
}
/*--------------------------------------------------------------------
Beschreibung:
--------------------------------------------------------------------*/
int SwPtrItem::operator==( const SfxPoolItem& rAttr ) const
{
DBG_ASSERT( SfxPoolItem::operator==(rAttr), "unequal types" );
const SwPtrItem& rItem = (SwPtrItem&)rAttr;
return ( pMisc == rItem.pMisc );
}
/*-----------------12.11.97 12:55-------------------------------
SwUINumRuleItem fuer die NumTabPages der FormatNumRule/Stylisten
---------------------------------------------------------------*/
SwUINumRuleItem::SwUINumRuleItem( const SwNumRule& rRul, const USHORT nId )
: SfxPoolItem( nId ), pRule( new SwNumRule( rRul ) )
{
}
SwUINumRuleItem::SwUINumRuleItem( const SwUINumRuleItem& rItem )
: SfxPoolItem( rItem ),
pRule( new SwNumRule( *rItem.pRule ))
{
}
SwUINumRuleItem::~SwUINumRuleItem()
{
delete pRule;
}
SfxPoolItem* SwUINumRuleItem::Clone( SfxItemPool * /*pPool*/ ) const
{
return new SwUINumRuleItem( *this );
}
int SwUINumRuleItem::operator==( const SfxPoolItem& rAttr ) const
{
DBG_ASSERT( SfxPoolItem::operator==(rAttr), "unequal types" );
return *pRule == *((SwUINumRuleItem&)rAttr).pRule;
}
BOOL SwUINumRuleItem::QueryValue( uno::Any& rVal, BYTE /*nMemberId*/ ) const
{
uno::Reference< container::XIndexReplace >xRules = new SwXNumberingRules(*pRule);
rVal.setValue(&xRules, ::getCppuType((uno::Reference< container::XIndexReplace>*)0));
return TRUE;
}
BOOL SwUINumRuleItem::PutValue( const uno::Any& rVal, BYTE /*nMemberId*/ )
{
uno::Reference< container::XIndexReplace> xRulesRef;
if(rVal >>= xRulesRef)
{
uno::Reference< lang::XUnoTunnel > xTunnel(xRulesRef, uno::UNO_QUERY);
SwXNumberingRules* pSwXRules = xTunnel.is() ? reinterpret_cast<SwXNumberingRules*>(
xTunnel->getSomething(SwXNumberingRules::getUnoTunnelId())) : 0;
if(pSwXRules)
{
*pRule = *pSwXRules->GetNumRule();
}
}
return TRUE;
}
/* -----------------17.06.98 17:43-------------------
*
* --------------------------------------------------*/
SwBackgroundDestinationItem::SwBackgroundDestinationItem(USHORT _nWhich, USHORT nValue) :
SfxUInt16Item(_nWhich, nValue)
{
}
/* -----------------17.06.98 17:44-------------------
*
* --------------------------------------------------*/
SfxPoolItem* SwBackgroundDestinationItem::Clone( SfxItemPool * /*pPool*/ ) const
{
return new SwBackgroundDestinationItem(Which(), GetValue());
}
<commit_msg>INTEGRATION: CWS pj86 (1.11.4); FILE MERGED 2007/09/28 21:36:50 pjanik 1.11.4.1: #i81574#: Initialize variable(s) to prevent warnings on Mac OS X with gcc-4.0.1.<commit_after>/*************************************************************************
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: uiitems.cxx,v $
*
* $Revision: 1.12 $
*
* last change: $Author: rt $ $Date: 2007-11-12 16:33:40 $
*
* 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_sw.hxx"
#ifndef _SVX_ITEMTYPE_HXX
#include <svx/itemtype.hxx>
#endif
#ifndef _UNOSETT_HXX
#include <unosett.hxx>
#endif
#include "swtypes.hxx"
#include "cmdid.h"
#include "pagedesc.hxx"
#include "uiitems.hxx"
#include "utlui.hrc"
#include "attrdesc.hrc"
#ifndef _UNOMID_H
#include <unomid.h>
#endif
using namespace ::com::sun::star;
using namespace ::com::sun::star::uno;
// Breitenangaben der Fussnotenlinien, mit TabPage abstimmen
static const USHORT __FAR_DATA nFtnLines[] = {
0,
10,
50,
80,
100,
150
};
#define FTN_LINE_STYLE_COUNT 5
SwPageFtnInfoItem::SwPageFtnInfoItem( const USHORT nId, SwPageFtnInfo& rInfo) :
SfxPoolItem( nId ),
aFtnInfo(rInfo)
{
}
SwPageFtnInfoItem::SwPageFtnInfoItem( const SwPageFtnInfoItem& rItem ) :
SfxPoolItem( rItem ),
aFtnInfo(rItem.GetPageFtnInfo())
{
}
SwPageFtnInfoItem::~SwPageFtnInfoItem()
{
}
SfxPoolItem* SwPageFtnInfoItem::Clone( SfxItemPool * /*pPool*/ ) const
{
return new SwPageFtnInfoItem( *this );
}
int SwPageFtnInfoItem::operator==( const SfxPoolItem& rAttr ) const
{
DBG_ASSERT( Which() == rAttr.Which(), "keine gleichen Attribute" );
return ( aFtnInfo == ((SwPageFtnInfoItem&)rAttr).GetPageFtnInfo());
}
SfxItemPresentation SwPageFtnInfoItem::GetPresentation
(
SfxItemPresentation ePres,
SfxMapUnit eCoreUnit,
SfxMapUnit ePresUnit,
String& rText,
const IntlWrapper* pIntl
) const
{
switch ( ePres )
{
case SFX_ITEM_PRESENTATION_NONE:
rText.Erase();
return SFX_ITEM_PRESENTATION_NONE;
case SFX_ITEM_PRESENTATION_NAMELESS:
case SFX_ITEM_PRESENTATION_COMPLETE:
{
USHORT nHght = (USHORT) GetPageFtnInfo().GetHeight();
if ( nHght )
{
rText = SW_RESSTR( STR_MAX_FTN_HEIGHT );
rText += ' ';
rText += ::GetMetricText( nHght, eCoreUnit, ePresUnit, pIntl );
rText += ::GetSvxString( ::GetMetricId( ePresUnit ) );
}
return ePres;
}
default:; //prevent warning
}
return SFX_ITEM_PRESENTATION_NONE;
}
/* -----------------------------26.04.01 12:25--------------------------------
---------------------------------------------------------------------------*/
BOOL SwPageFtnInfoItem::QueryValue( Any& rVal, BYTE nMemberId ) const
{
sal_Bool bRet = sal_True;
switch(nMemberId & ~CONVERT_TWIPS)
{
case MID_FTN_HEIGHT : rVal <<= (sal_Int32)TWIP_TO_MM100(aFtnInfo.GetHeight());break;
case MID_LINE_WEIGHT : rVal <<= (sal_Int16)TWIP_TO_MM100_UNSIGNED(aFtnInfo.GetLineWidth());break;
case MID_LINE_COLOR : rVal <<= (sal_Int32)aFtnInfo.GetLineColor().GetColor();break;
case MID_LINE_RELWIDTH :
{
Fraction aTmp( 100, 1 );
aTmp *= aFtnInfo.GetWidth();
rVal <<= (sal_Int8)(long)aTmp;
}
break;
case MID_LINE_ADJUST : rVal <<= (sal_Int16)aFtnInfo.GetAdj();break;//text::HorizontalAdjust
case MID_LINE_TEXT_DIST : rVal <<= (sal_Int32)TWIP_TO_MM100(aFtnInfo.GetTopDist());break;
case MID_LINE_FOOTNOTE_DIST: rVal <<= (sal_Int32)TWIP_TO_MM100(aFtnInfo.GetBottomDist());break;
default:
bRet = sal_False;
}
return bRet;
}
/* -----------------------------26.04.01 12:26--------------------------------
---------------------------------------------------------------------------*/
BOOL SwPageFtnInfoItem::PutValue(const Any& rVal, BYTE nMemberId)
{
sal_Int32 nSet32 = 0;
sal_Bool bRet = sal_True;
switch(nMemberId & ~CONVERT_TWIPS)
{
case MID_LINE_COLOR :
rVal >>= nSet32;
aFtnInfo.SetLineColor(nSet32);
break;
case MID_FTN_HEIGHT:
case MID_LINE_TEXT_DIST :
case MID_LINE_FOOTNOTE_DIST:
rVal >>= nSet32;
if(nSet32 < 0)
bRet = sal_False;
else
{
nSet32 = MM100_TO_TWIP(nSet32);
switch(nMemberId & ~CONVERT_TWIPS)
{
case MID_FTN_HEIGHT: aFtnInfo.SetHeight(nSet32); break;
case MID_LINE_TEXT_DIST: aFtnInfo.SetTopDist(nSet32);break;
case MID_LINE_FOOTNOTE_DIST: aFtnInfo.SetBottomDist(nSet32);break;
}
}
break;
case MID_LINE_WEIGHT :
{
sal_Int16 nSet = 0;
rVal >>= nSet;
if(nSet >= 0)
aFtnInfo.SetLineWidth(MM100_TO_TWIP(nSet));
else
bRet = sal_False;
}
break;
case MID_LINE_RELWIDTH :
{
sal_Int8 nSet = 0;
rVal >>= nSet;
if(nSet < 0)
bRet = sal_False;
else
aFtnInfo.SetWidth(Fraction(nSet, 100));
}
break;
case MID_LINE_ADJUST :
{
sal_Int16 nSet = 0;
rVal >>= nSet;
if(nSet >= 0 && nSet < 3) //text::HorizontalAdjust
aFtnInfo.SetAdj((SwFtnAdj)nSet);
else
bRet = sal_False;
}
break;
default:
bRet = sal_False;
}
return bRet;
}
SwPtrItem::SwPtrItem( const USHORT nId, void* pPtr ) :
SfxPoolItem( nId ),
pMisc(pPtr)
{
}
/*--------------------------------------------------------------------
Beschreibung: Copy-Konstruktor
--------------------------------------------------------------------*/
SwPtrItem::SwPtrItem( const SwPtrItem& rItem ) : SfxPoolItem( rItem )
{
pMisc = rItem.pMisc;
}
/*--------------------------------------------------------------------
Beschreibung: Clonen
--------------------------------------------------------------------*/
SfxPoolItem* SwPtrItem::Clone( SfxItemPool * /*pPool*/ ) const
{
return new SwPtrItem( *this );
}
/*--------------------------------------------------------------------
Beschreibung:
--------------------------------------------------------------------*/
int SwPtrItem::operator==( const SfxPoolItem& rAttr ) const
{
DBG_ASSERT( SfxPoolItem::operator==(rAttr), "unequal types" );
const SwPtrItem& rItem = (SwPtrItem&)rAttr;
return ( pMisc == rItem.pMisc );
}
/*-----------------12.11.97 12:55-------------------------------
SwUINumRuleItem fuer die NumTabPages der FormatNumRule/Stylisten
---------------------------------------------------------------*/
SwUINumRuleItem::SwUINumRuleItem( const SwNumRule& rRul, const USHORT nId )
: SfxPoolItem( nId ), pRule( new SwNumRule( rRul ) )
{
}
SwUINumRuleItem::SwUINumRuleItem( const SwUINumRuleItem& rItem )
: SfxPoolItem( rItem ),
pRule( new SwNumRule( *rItem.pRule ))
{
}
SwUINumRuleItem::~SwUINumRuleItem()
{
delete pRule;
}
SfxPoolItem* SwUINumRuleItem::Clone( SfxItemPool * /*pPool*/ ) const
{
return new SwUINumRuleItem( *this );
}
int SwUINumRuleItem::operator==( const SfxPoolItem& rAttr ) const
{
DBG_ASSERT( SfxPoolItem::operator==(rAttr), "unequal types" );
return *pRule == *((SwUINumRuleItem&)rAttr).pRule;
}
BOOL SwUINumRuleItem::QueryValue( uno::Any& rVal, BYTE /*nMemberId*/ ) const
{
uno::Reference< container::XIndexReplace >xRules = new SwXNumberingRules(*pRule);
rVal.setValue(&xRules, ::getCppuType((uno::Reference< container::XIndexReplace>*)0));
return TRUE;
}
BOOL SwUINumRuleItem::PutValue( const uno::Any& rVal, BYTE /*nMemberId*/ )
{
uno::Reference< container::XIndexReplace> xRulesRef;
if(rVal >>= xRulesRef)
{
uno::Reference< lang::XUnoTunnel > xTunnel(xRulesRef, uno::UNO_QUERY);
SwXNumberingRules* pSwXRules = xTunnel.is() ? reinterpret_cast<SwXNumberingRules*>(
xTunnel->getSomething(SwXNumberingRules::getUnoTunnelId())) : 0;
if(pSwXRules)
{
*pRule = *pSwXRules->GetNumRule();
}
}
return TRUE;
}
/* -----------------17.06.98 17:43-------------------
*
* --------------------------------------------------*/
SwBackgroundDestinationItem::SwBackgroundDestinationItem(USHORT _nWhich, USHORT nValue) :
SfxUInt16Item(_nWhich, nValue)
{
}
/* -----------------17.06.98 17:44-------------------
*
* --------------------------------------------------*/
SfxPoolItem* SwBackgroundDestinationItem::Clone( SfxItemPool * /*pPool*/ ) const
{
return new SwBackgroundDestinationItem(Which(), GetValue());
}
<|endoftext|> |
<commit_before>/*************************************************************************
*
* $RCSfile: wrtundo.cxx,v $
*
* $Revision: 1.3 $
*
* last change: $Author: jp $ $Date: 2001-09-11 14:57: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): _______________________________________
*
*
************************************************************************/
#ifdef PRECOMPILED
#include "ui_pch.hxx"
#endif
#pragma hdrstop
#define _SVSTDARR_STRINGSDTOR
#ifndef _TOOLS_RESID_HXX
#include <tools/resid.hxx>
#endif
#ifndef _SFXAPP_HXX //autogen
#include <sfx2/app.hxx>
#endif
#ifndef _SFXSLSTITM_HXX
#include <svtools/slstitm.hxx>
#endif
#ifndef _WRTSH_HXX
#include <wrtsh.hxx>
#endif
#ifndef _SWUNDO_HXX
#include <swundo.hxx> // fuer Undo-Ids
#endif
#ifndef _SWDTFLVR_HXX
#include <swdtflvr.hxx>
#endif
#ifndef _WRTSH_HRC
#include <wrtsh.hrc>
#endif
#include <sfx2/sfx.hrc>
// Undo beendet alle Modi. Falls eine Selektion durch das Undo entstanden
// ist, muss die fuer die weiteren Aktionen beruecksichtigt werden.
void SwWrtShell::Do( DoType eDoType, USHORT nCnt )
{
StartAllAction();
switch( eDoType )
{
case UNDO:
// Modi zuruecksetzen
EnterStdMode();
SwEditShell::Undo(0, nCnt );
break;
case REDO:
// Modi zuruecksetzen
EnterStdMode();
SwEditShell::Redo( nCnt );
break;
case REPEAT:
SwEditShell::Repeat( nCnt );
break;
}
EndAllAction();
BOOL bCreateXSelection = FALSE;
const FASTBOOL bFrmSelected = IsFrmSelected() || IsObjSelected();
if ( IsSelection() )
{
if ( bFrmSelected )
UnSelectFrm();
// Funktionspointer fuer das Aufheben der Selektion setzen
// bei Cursor setzen
fnKillSel = &SwWrtShell::ResetSelect;
fnSetCrsr = &SwWrtShell::SetCrsrKillSel;
bCreateXSelection = TRUE;
}
else if ( bFrmSelected )
{
EnterSelFrmMode();
bCreateXSelection = TRUE;
}
else if( (CNT_GRF | CNT_OLE ) & GetCntType() )
{
SelectObj( GetCharRect().Pos() );
EnterSelFrmMode();
bCreateXSelection = TRUE;
}
if( bCreateXSelection )
SwTransferable::CreateSelection( *this );
// Bug 32918: nach loeschen der Numerierung bleibt die Obj. Leiste stehen
// Warum wird hier nicht immer ein CallChgLink gerufen?
CallChgLnk();
}
String SwWrtShell::GetDoString( DoType eDoType ) const
{
String aStr;
USHORT nId = 0, nResStr;
switch( eDoType )
{
case UNDO:
nResStr = STR_UNDO;
nId = GetUndoIds( &aStr );
break;
case REDO:
nResStr = STR_REDO;
nId = GetRedoIds( &aStr );
break;
}
if( UNDO_END < nId )
{
aStr.Insert( String(ResId( nResStr, SFX_APP()->GetSfxResManager() )), 0 );
if( UNDO_DRAWUNDO != nId )
aStr += SW_RESSTR( UNDO_BASE + nId );
}
return aStr;
}
USHORT SwWrtShell::GetDoStrings( DoType eDoType, SfxStringListItem& rStrs ) const
{
SwUndoIds aIds;
switch( eDoType )
{
case UNDO:
GetUndoIds( 0, &aIds );
break;
case REDO:
GetRedoIds( 0, &aIds );
break;
}
String sList;
for( USHORT n = 0, nEnd = aIds.Count(); n < nEnd; ++n )
{
const SwUndoIdAndName& rIdNm = *aIds[ n ];
if( UNDO_DRAWUNDO != rIdNm.GetUndoId() )
sList += String( ResId( UNDO_BASE + rIdNm.GetUndoId(), pSwResMgr ));
else if( rIdNm.GetUndoStr() )
sList += *rIdNm.GetUndoStr();
else
{
ASSERT( !this, "no Undo/Redo Test set" );
}
sList += '\n';
}
rStrs.SetString( sList );
return aIds.Count();
}
String SwWrtShell::GetRepeatString() const
{
String aStr;
USHORT nId = GetRepeatIds( &aStr );
if( UNDO_END < nId )
{
aStr.Insert( ResId( STR_REPEAT, SFX_APP()->GetSfxResManager()), 0 );
if( UNDO_DRAWUNDO != nId )
aStr += SW_RESSTR( UNDO_BASE + nId );
}
return aStr;
}
/*************************************************************************
$Log: not supported by cvs2svn $
Revision 1.2 2001/04/09 07:28:55 tl
Undo/Redo controller modifications
Revision 1.1.1.1 2000/09/18 17:14:53 hr
initial import
Revision 1.53 2000/09/18 16:06:27 willem.vandorp
OpenOffice header added.
Revision 1.52 2000/07/27 21:01:41 jp
Bug #76923#: Do - clamp the enterstdmode and Undo/Redo/Repeat call
Revision 1.51 2000/03/03 15:17:06 os
StarView remainders removed
Revision 1.50 1998/04/15 14:35:34 OS
STR_UNDO/REDO/REPEAT aus dem Sfx
Rev 1.49 15 Apr 1998 16:35:34 OS
STR_UNDO/REDO/REPEAT aus dem Sfx
Rev 1.48 24 Nov 1997 14:35:02 MA
includes
Rev 1.47 03 Nov 1997 14:02:56 MA
precomp entfernt
Rev 1.46 22 Jan 1997 11:55:56 MA
opt: bSelection entfernt
Rev 1.45 11 Nov 1996 10:18:48 MA
ResMgr
Rev 1.44 31 Oct 1996 18:32:30 JP
Bug #32918#: nach Undo der View sagen, das sich was getan hat
Rev 1.43 29 Aug 1996 09:25:56 OS
includes
Rev 1.42 24 Nov 1995 16:59:06 OM
PCH->PRECOMPILED
Rev 1.41 19 Sep 1995 19:11:52 JP
Bug 19431: Repeat funkt. wieder
Rev 1.40 12 Sep 1995 17:59:32 JP
Bug19137: vor Undo den Cursor in den StandardMode setzen
Rev 1.39 28 Aug 1995 15:59:40 MA
Renovierung: IDL, Shells, Textshell-Doktrin aufgegeben
Rev 1.38 22 Aug 1995 17:30:04 JP
GetUndo-/-Redo-/-RepeatIds: optional mit String-Ptr - DrawUndo-Objecte erzeuge die Strings selbst
Rev 1.37 15 Aug 1995 19:52:20 JP
Nach Undo/Redo kann der Cursor in OLE oder GRF stehen, selektieren dann den Frame
Rev 1.36 27 Apr 1995 13:14:16 AMA
Fix (JP): ResId-Ueberpruef. bei Undo
Rev 1.35 23 Feb 1995 17:51:58 MA
Rudimentaer Undo/Redo fuer Zeichenobjekte.
Rev 1.34 08 Feb 1995 23:36:12 ER
undo.hxx -> swundo.hxx wegen solar undo.hxx
Rev 1.33 08 Feb 1995 19:01:30 JP
UI-UndoIds ins undo.hxx verschoben
*************************************************************************/
<commit_msg>#105332# SwWrtShell::Do: Unable undo while doing Undo/Redo/Repeat<commit_after>/*************************************************************************
*
* $RCSfile: wrtundo.cxx,v $
*
* $Revision: 1.4 $
*
* last change: $Author: hbrinkm $ $Date: 2002-11-22 15:00:50 $
*
* 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): _______________________________________
*
*
************************************************************************/
#ifdef PRECOMPILED
#include "ui_pch.hxx"
#endif
#pragma hdrstop
#define _SVSTDARR_STRINGSDTOR
#ifndef _TOOLS_RESID_HXX
#include <tools/resid.hxx>
#endif
#ifndef _SFXAPP_HXX //autogen
#include <sfx2/app.hxx>
#endif
#ifndef _SFXSLSTITM_HXX
#include <svtools/slstitm.hxx>
#endif
#ifndef _WRTSH_HXX
#include <wrtsh.hxx>
#endif
#ifndef _SWUNDO_HXX
#include <swundo.hxx> // fuer Undo-Ids
#endif
#ifndef _SWDTFLVR_HXX
#include <swdtflvr.hxx>
#endif
#ifndef _WRTSH_HRC
#include <wrtsh.hrc>
#endif
#include <sfx2/sfx.hrc>
// Undo beendet alle Modi. Falls eine Selektion durch das Undo entstanden
// ist, muss die fuer die weiteren Aktionen beruecksichtigt werden.
void SwWrtShell::Do( DoType eDoType, USHORT nCnt )
{
// #105332# save current state of DoesUndo() and disable undo.
sal_Bool bSaveDoesUndo = DoesUndo();
DoUndo(sal_False);
StartAllAction();
switch( eDoType )
{
case UNDO:
// Modi zuruecksetzen
EnterStdMode();
SwEditShell::Undo(0, nCnt );
break;
case REDO:
// Modi zuruecksetzen
EnterStdMode();
SwEditShell::Redo( nCnt );
break;
case REPEAT:
SwEditShell::Repeat( nCnt );
break;
}
EndAllAction();
// #105332# restore undo state
DoUndo(bSaveDoesUndo);
BOOL bCreateXSelection = FALSE;
const FASTBOOL bFrmSelected = IsFrmSelected() || IsObjSelected();
if ( IsSelection() )
{
if ( bFrmSelected )
UnSelectFrm();
// Funktionspointer fuer das Aufheben der Selektion setzen
// bei Cursor setzen
fnKillSel = &SwWrtShell::ResetSelect;
fnSetCrsr = &SwWrtShell::SetCrsrKillSel;
bCreateXSelection = TRUE;
}
else if ( bFrmSelected )
{
EnterSelFrmMode();
bCreateXSelection = TRUE;
}
else if( (CNT_GRF | CNT_OLE ) & GetCntType() )
{
SelectObj( GetCharRect().Pos() );
EnterSelFrmMode();
bCreateXSelection = TRUE;
}
if( bCreateXSelection )
SwTransferable::CreateSelection( *this );
// Bug 32918: nach loeschen der Numerierung bleibt die Obj. Leiste stehen
// Warum wird hier nicht immer ein CallChgLink gerufen?
CallChgLnk();
}
String SwWrtShell::GetDoString( DoType eDoType ) const
{
String aStr;
USHORT nId = 0, nResStr;
switch( eDoType )
{
case UNDO:
nResStr = STR_UNDO;
nId = GetUndoIds( &aStr );
break;
case REDO:
nResStr = STR_REDO;
nId = GetRedoIds( &aStr );
break;
}
if( UNDO_END < nId )
{
aStr.Insert( String(ResId( nResStr, SFX_APP()->GetSfxResManager() )), 0 );
if( UNDO_DRAWUNDO != nId )
aStr += SW_RESSTR( UNDO_BASE + nId );
}
return aStr;
}
USHORT SwWrtShell::GetDoStrings( DoType eDoType, SfxStringListItem& rStrs ) const
{
SwUndoIds aIds;
switch( eDoType )
{
case UNDO:
GetUndoIds( 0, &aIds );
break;
case REDO:
GetRedoIds( 0, &aIds );
break;
}
String sList;
for( USHORT n = 0, nEnd = aIds.Count(); n < nEnd; ++n )
{
const SwUndoIdAndName& rIdNm = *aIds[ n ];
if( UNDO_DRAWUNDO != rIdNm.GetUndoId() )
sList += String( ResId( UNDO_BASE + rIdNm.GetUndoId(), pSwResMgr ));
else if( rIdNm.GetUndoStr() )
sList += *rIdNm.GetUndoStr();
else
{
ASSERT( !this, "no Undo/Redo Test set" );
}
sList += '\n';
}
rStrs.SetString( sList );
return aIds.Count();
}
String SwWrtShell::GetRepeatString() const
{
String aStr;
USHORT nId = GetRepeatIds( &aStr );
if( UNDO_END < nId )
{
aStr.Insert( ResId( STR_REPEAT, SFX_APP()->GetSfxResManager()), 0 );
if( UNDO_DRAWUNDO != nId )
aStr += SW_RESSTR( UNDO_BASE + nId );
}
return aStr;
}
/*************************************************************************
$Log: not supported by cvs2svn $
Revision 1.3 2001/09/11 14:57:42 jp
Task #91678#: 'selection clipbord' implemented
Revision 1.2 2001/04/09 07:28:55 tl
Undo/Redo controller modifications
Revision 1.1.1.1 2000/09/18 17:14:53 hr
initial import
Revision 1.53 2000/09/18 16:06:27 willem.vandorp
OpenOffice header added.
Revision 1.52 2000/07/27 21:01:41 jp
Bug #76923#: Do - clamp the enterstdmode and Undo/Redo/Repeat call
Revision 1.51 2000/03/03 15:17:06 os
StarView remainders removed
Revision 1.50 1998/04/15 14:35:34 OS
STR_UNDO/REDO/REPEAT aus dem Sfx
Rev 1.49 15 Apr 1998 16:35:34 OS
STR_UNDO/REDO/REPEAT aus dem Sfx
Rev 1.48 24 Nov 1997 14:35:02 MA
includes
Rev 1.47 03 Nov 1997 14:02:56 MA
precomp entfernt
Rev 1.46 22 Jan 1997 11:55:56 MA
opt: bSelection entfernt
Rev 1.45 11 Nov 1996 10:18:48 MA
ResMgr
Rev 1.44 31 Oct 1996 18:32:30 JP
Bug #32918#: nach Undo der View sagen, das sich was getan hat
Rev 1.43 29 Aug 1996 09:25:56 OS
includes
Rev 1.42 24 Nov 1995 16:59:06 OM
PCH->PRECOMPILED
Rev 1.41 19 Sep 1995 19:11:52 JP
Bug 19431: Repeat funkt. wieder
Rev 1.40 12 Sep 1995 17:59:32 JP
Bug19137: vor Undo den Cursor in den StandardMode setzen
Rev 1.39 28 Aug 1995 15:59:40 MA
Renovierung: IDL, Shells, Textshell-Doktrin aufgegeben
Rev 1.38 22 Aug 1995 17:30:04 JP
GetUndo-/-Redo-/-RepeatIds: optional mit String-Ptr - DrawUndo-Objecte erzeuge die Strings selbst
Rev 1.37 15 Aug 1995 19:52:20 JP
Nach Undo/Redo kann der Cursor in OLE oder GRF stehen, selektieren dann den Frame
Rev 1.36 27 Apr 1995 13:14:16 AMA
Fix (JP): ResId-Ueberpruef. bei Undo
Rev 1.35 23 Feb 1995 17:51:58 MA
Rudimentaer Undo/Redo fuer Zeichenobjekte.
Rev 1.34 08 Feb 1995 23:36:12 ER
undo.hxx -> swundo.hxx wegen solar undo.hxx
Rev 1.33 08 Feb 1995 19:01:30 JP
UI-UndoIds ins undo.hxx verschoben
*************************************************************************/
<|endoftext|> |
<commit_before><commit_msg>add a TODO to exchange<commit_after><|endoftext|> |
<commit_before>#ifndef SDR_H_
#define SDR_H_
#include <vector>
#include <array>
#include <bitset>
#include <iostream>
#include <utility>
#include <algorithm>
#include <iostream>
#include <cmath>
#include <unordered_set>
namespace sdr
{
typedef std::size_t position_t;
typedef std::size_t width_t;
// this holds all of the traits for a single concept
// ie - if width is 1024, this could hold up to 1024 values between 0 and 1024
struct concept
{
std::vector<position_t> data;
// for vector of positions we assume the data has already been dealt with
concept(const std::vector<position_t> & input) : data(input)
{}
// otherwise we assume that is hasn't, thus we only add non zero fields
template <typename T>
concept(const T & input) : data()
{
for(std::size_t i=0; i < input.size(); ++i) {
if(input[i]) {
data.push_back(i);
}
}
}
};
template <width_t Width>
struct node
{
// store the positions of all set bits from 0 -> width
std::unordered_set<position_t> positions;
node(const concept & concept) : positions(concept.data.begin(), concept.data.end())
{}
void fill(const concept & concept)
{
std::copy(concept.data.begin(), concept.data.end(), std::inserter(positions, positions.begin()));
}
void clear()
{
positions.clear();
}
void print() const
{
const std::size_t sroot = std::sqrt(Width);
for(std::size_t y=0; y < sroot; ++y) {
for(std::size_t x=0; x < sroot; ++x) {
std::cout << (positions.count((y * sroot) + x) ? '1' : '0');
}
std::cout << std::endl;
}
}
};
template <width_t Width>
struct bank
{
// all inputs we have ever received, we store here compressed into storage
std::vector<node<Width>> storage;
// this holds our sets of vectors for easy comparison of different objects in storage
std::array<std::unordered_set<position_t>, Width> bitmap;
bank() : storage(), bitmap()
{}
void print(const position_t pos) const
{
storage[pos].print();
}
position_t insert(const concept & concept)
{
storage.push_back(node<Width>(concept));
const position_t last_pos = storage.size() - 1;
for(position_t pos : concept.data) {
bitmap[pos].insert(last_pos);
}
return last_pos;
}
void update(const position_t pos, const concept & concept)
{
node<Width> & node = storage[pos];
for(position_t i : node.positions) {
bitmap[i].erase(pos);
}
node.clear();
node.fill(concept);
for(position_t p : node.positions) {
bitmap[p].insert(pos);
}
}
// find amount of matching bits between two vectors
std::size_t similarity(const position_t a, const position_t b) const
{
std::size_t result = 0;
for(position_t pos : storage[a].positions) {
result += bitmap[pos].count(b);
}
return result;
}
// find amount of matching bits between two vectors
double weighted_similarity(const position_t a, const position_t b, const std::array<double, Width> & weights) const
{
double result = 0;
for(position_t pos : storage[a].positions) {
result += bitmap[pos].count(b) * weights[pos];
}
return result;
}
// find similarity of one object compared to the OR'd result of a list of objects
std::size_t union_similarity(const position_t pos, const std::vector<position_t> & positions) const
{
std::bitset<Width> punions;
for(const position_t ppos : positions) {
for(const position_t spos : storage[ppos].positions) {
punions.set(spos);
}
}
std::size_t result = 0;
for(const position_t cmp : storage[pos].positions) {
result += punions[cmp];
}
return result;
}
// find similarity of one object compared to the OR'd result of a list of objects
double weighted_union_similarity(const position_t pos, const std::vector<position_t> & positions, const std::array<double, Width> & weights) const
{
std::bitset<Width> punions;
for(const position_t ppos : positions) {
for(const position_t spos : storage[ppos].positions) {
punions.set(spos);
}
}
double result = 0;
for(const position_t cmp : storage[pos].positions) {
result += punions[cmp] * weights[cmp];
}
return result;
}
// find most similar to object at pos
// first refers to position
// second refers to matching number of bits
std::vector<std::pair<position_t, std::size_t>> closest(const position_t pos, const std::size_t amount) const
{
std::vector<position_t> idx(storage.size());
std::vector<unsigned> v(storage.size());
std::iota(idx.begin(), idx.end(), 0);
// count matching bits for each
for(const position_t spos : storage[pos].positions) {
for(const position_t bpos : bitmap[spos]) {
++v[bpos];
}
}
// we dont care about our self similarity
v[pos] = 0;
// if there are less than amount in storage, just return amount that exist
const auto partial_amount = ((amount >= idx.size()) ? idx.size() : amount);
std::partial_sort(idx.begin(), idx.begin() + partial_amount, idx.end(), [&](
const position_t a,
const position_t b
) {
return v[a] > v[b];
});
// create std::pair for result
std::vector<std::pair<position_t, std::size_t>> ret;
ret.reserve(partial_amount);
for(std::size_t i=0; i<partial_amount; ++i) {
const auto m = idx[i];
ret.push_back(std::make_pair(m, static_cast<std::size_t>(v[m])));
}
return ret;
}
// find most similar to object at pos
// first refers to position
// second refers to matching number of bits
std::vector<std::pair<position_t, double>> weighted_closest(const position_t pos, const std::size_t amount, const std::array<double, Width> & weights) const
{
std::vector<position_t> idx(storage.size());
std::vector<double> v(storage.size());
std::iota(idx.begin(), idx.end(), 0);
// count matching bits for each
for(const position_t spos : storage[pos].positions) {
for(const position_t bpos : bitmap[spos]) {
v[bpos] += weights[spos];
}
}
// we dont care about our self similarity
v[pos] = 0.0;
// if there are less than amount in storage, just return amount that exist
const auto partial_amount = ((amount >= idx.size()) ? idx.size() : amount);
std::partial_sort(idx.begin(), idx.begin() + partial_amount, idx.end(), [&](
const position_t a,
const position_t b
) {
return v[a] > v[b];
});
// create std::pair for result
std::vector<std::pair<position_t, double>> ret;
ret.reserve(partial_amount);
for(std::size_t i=0; i<partial_amount; ++i) {
const auto m = idx[i];
ret.push_back(std::make_pair(m, v[m]));
}
return ret;
}
// return all items matching all in data
std::vector<position_t> matching(const concept & concept) const
{
std::unordered_set<position_t> matching;
for(const std::size_t item : concept.data) {
for(const std::size_t pos : bitmap[item]) {
for(const std::size_t m : concept.data) {
if(bitmap[m].count(pos) == 0) {
goto skip;
}
}
matching.insert(pos);
skip:;
}
}
return std::vector<position_t>(matching.begin(), matching.end());
}
// has to match amount in data
std::vector<position_t> matching(const concept & concept, const std::size_t amount) const
{
std::unordered_set<position_t> matching;
for(const std::size_t item : concept.data) {
for(const std::size_t pos : bitmap[item]) {
std::size_t amount_matching = 0;
for(const std::size_t m : concept.data) {
amount_matching += bitmap[m].count(pos);
}
if(amount_matching >= amount) {
matching.insert(pos);
}
}
}
return std::vector<position_t>(matching.begin(), matching.end());
}
// has to match amount in data
std::vector<position_t> weighted_matching(const std::vector<position_t> & data, const double amount, const std::array<double, Width> & weights) const
{
std::unordered_set<position_t> matching;
for(const std::size_t item : data) {
for(const std::size_t pos : bitmap[item]) {
double amount_matching = 0;
for(const std::size_t m : data) {
amount_matching += bitmap[m].count(pos) * weights[m];
}
if(amount_matching >= amount) {
matching.insert(pos);
}
}
}
return std::vector<position_t>(matching.begin(), matching.end());
}
};
} //namespace sdr
#endif
<commit_msg>more docs<commit_after>#ifndef SDR_H_
#define SDR_H_
#include <vector>
#include <array>
#include <bitset>
#include <iostream>
#include <utility>
#include <algorithm>
#include <iostream>
#include <cmath>
#include <unordered_set>
namespace sdr
{
typedef std::size_t position_t;
typedef std::size_t width_t;
// this holds all of the traits for a single concept
// ie - if width is 1024, this could hold up to 1024 values between 0 and 1024
struct concept
{
std::vector<position_t> data;
// for vector of positions we assume the data has already been dealt with
concept(const std::vector<position_t> & input) : data(input)
{}
// otherwise we assume that is hasn't, thus we only add non zero fields
template <typename T> concept(const T & input) : data()
{
for(std::size_t i=0; i < input.size(); ++i) {
if(input[i]) {
data.push_back(i);
}
}
}
};
// represents a concept in storage
// designed to be able to be quickly queried and modified
template <width_t Width> struct node
{
// store the positions of all set bits from 0 -> width
std::unordered_set<position_t> positions;
node(const concept & concept) : positions(concept.data.begin(), concept.data.end())
{}
void fill(const concept & concept)
{
std::copy(concept.data.begin(), concept.data.end(), std::inserter(positions, positions.begin()));
}
void clear()
{
positions.clear();
}
void print() const
{
const std::size_t sroot = std::sqrt(Width);
for(std::size_t y=0; y < sroot; ++y) {
for(std::size_t x=0; x < sroot; ++x) {
std::cout << (positions.count((y * sroot) + x) ? '1' : '0');
}
std::cout << std::endl;
}
}
};
// this is the memory bank for the sdr memory unit
template <width_t Width> struct bank
{
// all inputs we have ever received, we store here compressed into storage
std::vector<node<Width>> storage;
// this holds our sets of vectors for easy comparison of different objects in storage
std::array<std::unordered_set<position_t>, Width> bitmap;
bank() : storage(), bitmap()
{}
void print(const position_t pos) const
{
storage[pos].print();
}
position_t insert(const concept & concept)
{
storage.push_back(node<Width>(concept));
const position_t last_pos = storage.size() - 1;
for(position_t pos : concept.data) {
bitmap[pos].insert(last_pos);
}
return last_pos;
}
void update(const position_t pos, const concept & concept)
{
node<Width> & node = storage[pos];
for(position_t i : node.positions) {
bitmap[i].erase(pos);
}
node.clear();
node.fill(concept);
for(position_t p : node.positions) {
bitmap[p].insert(pos);
}
}
// find amount of matching bits between two vectors
std::size_t similarity(const position_t a, const position_t b) const
{
std::size_t result = 0;
for(position_t pos : storage[a].positions) {
result += bitmap[pos].count(b);
}
return result;
}
// find amount of matching bits between two vectors
double weighted_similarity(const position_t a, const position_t b, const std::array<double, Width> & weights) const
{
double result = 0;
for(position_t pos : storage[a].positions) {
result += bitmap[pos].count(b) * weights[pos];
}
return result;
}
// find similarity of one object compared to the OR'd result of a list of objects
std::size_t union_similarity(const position_t pos, const std::vector<position_t> & positions) const
{
std::bitset<Width> punions;
for(const position_t ppos : positions) {
for(const position_t spos : storage[ppos].positions) {
punions.set(spos);
}
}
std::size_t result = 0;
for(const position_t cmp : storage[pos].positions) {
result += punions[cmp];
}
return result;
}
// find similarity of one object compared to the OR'd result of a list of objects
double weighted_union_similarity(const position_t pos, const std::vector<position_t> & positions, const std::array<double, Width> & weights) const
{
std::bitset<Width> punions;
for(const position_t ppos : positions) {
for(const position_t spos : storage[ppos].positions) {
punions.set(spos);
}
}
double result = 0;
for(const position_t cmp : storage[pos].positions) {
result += punions[cmp] * weights[cmp];
}
return result;
}
// find most similar to object at pos
// first refers to position
// second refers to matching number of bits
std::vector<std::pair<position_t, std::size_t>> closest(const position_t pos, const std::size_t amount) const
{
std::vector<position_t> idx(storage.size());
std::vector<unsigned> v(storage.size());
std::iota(idx.begin(), idx.end(), 0);
// count matching bits for each
for(const position_t spos : storage[pos].positions) {
for(const position_t bpos : bitmap[spos]) {
++v[bpos];
}
}
// we dont care about our self similarity
v[pos] = 0;
// if there are less than amount in storage, just return amount that exist
const auto partial_amount = ((amount >= idx.size()) ? idx.size() : amount);
std::partial_sort(idx.begin(), idx.begin() + partial_amount, idx.end(), [&](
const position_t a,
const position_t b
) {
return v[a] > v[b];
});
// create std::pair for result
std::vector<std::pair<position_t, std::size_t>> ret;
ret.reserve(partial_amount);
for(std::size_t i=0; i<partial_amount; ++i) {
const auto m = idx[i];
ret.push_back(std::make_pair(m, static_cast<std::size_t>(v[m])));
}
return ret;
}
// find most similar to object at pos
// first refers to position
// second refers to matching number of bits
std::vector<std::pair<position_t, double>> weighted_closest(const position_t pos, const std::size_t amount, const std::array<double, Width> & weights) const
{
std::vector<position_t> idx(storage.size());
std::vector<double> v(storage.size());
std::iota(idx.begin(), idx.end(), 0);
// count matching bits for each
for(const position_t spos : storage[pos].positions) {
for(const position_t bpos : bitmap[spos]) {
v[bpos] += weights[spos];
}
}
// we dont care about our self similarity
v[pos] = 0.0;
// if there are less than amount in storage, just return amount that exist
const auto partial_amount = ((amount >= idx.size()) ? idx.size() : amount);
std::partial_sort(idx.begin(), idx.begin() + partial_amount, idx.end(), [&](
const position_t a,
const position_t b
) {
return v[a] > v[b];
});
// create std::pair for result
std::vector<std::pair<position_t, double>> ret;
ret.reserve(partial_amount);
for(std::size_t i=0; i<partial_amount; ++i) {
const auto m = idx[i];
ret.push_back(std::make_pair(m, v[m]));
}
return ret;
}
// return all items matching all in data
std::vector<position_t> matching(const concept & concept) const
{
std::unordered_set<position_t> matching;
for(const std::size_t item : concept.data) {
for(const std::size_t pos : bitmap[item]) {
for(const std::size_t m : concept.data) {
if(bitmap[m].count(pos) == 0) {
goto skip;
}
}
matching.insert(pos);
skip:;
}
}
return std::vector<position_t>(matching.begin(), matching.end());
}
// has to match amount in data
std::vector<position_t> matching(const concept & concept, const std::size_t amount) const
{
std::unordered_set<position_t> matching;
for(const std::size_t item : concept.data) {
for(const std::size_t pos : bitmap[item]) {
std::size_t amount_matching = 0;
for(const std::size_t m : concept.data) {
amount_matching += bitmap[m].count(pos);
}
if(amount_matching >= amount) {
matching.insert(pos);
}
}
}
return std::vector<position_t>(matching.begin(), matching.end());
}
// has to match amount in data
std::vector<position_t> weighted_matching(const std::vector<position_t> & data, const double amount, const std::array<double, Width> & weights) const
{
std::unordered_set<position_t> matching;
for(const std::size_t item : data) {
for(const std::size_t pos : bitmap[item]) {
double amount_matching = 0;
for(const std::size_t m : data) {
amount_matching += bitmap[m].count(pos) * weights[m];
}
if(amount_matching >= amount) {
matching.insert(pos);
}
}
}
return std::vector<position_t>(matching.begin(), matching.end());
}
};
} //namespace sdr
#endif
<|endoftext|> |
<commit_before>/*
* =====================================================================================
*
* Filename: mpu9150_node.cpp
*
* Description: ROS package that launches a node and publishes
* the Invensense MPU-9150 in the format Imu.msgs and MagneticField.msgs to the topics
* /imu/data_raw and /imu/mag
*
* Version: 1.1
* Created: 27/07/13 15:06:50
* Revision: Morgan Dykshorn <mdd27@vt.edu> 2015
*
* Author: Víctor Mayoral Vilches <v.mayoralv@gmail.com>
*
* =====================================================================================
*/
#include "ros/ros.h"
#include "std_msgs/String.h"
//include IMU message, geometry message quaternion, geometry message vector3, and magnetic field
#include "sensor_msgs/Imu.h"
#include "geometry_msgs/Quaternion.h"
#include "geometry_msgs/Vector3.h"
#include "sensor_msgs/MagneticField.h"
#include <sstream>
#include <stdio.h>
#include <stdint.h>
#include <stdlib.h>
#include <string.h>
#include <signal.h>
#include <getopt.h>
#include <errno.h>
// Needed when mixing C and C++ code/libraries
#ifdef __cplusplus
extern "C" {
#endif
#include "mpu9150.h"
#include "linux_glue.h"
#include "local_defaults.h"
#ifdef __cplusplus
}
#endif
//calibration function
int set_cal(int mag, char *cal_file);
//
void register_sig_handler();
void sigint_handler(int sig);
int done;
int main(int argc, char **argv)
{
ros::init(argc, argv, "mpu9150_node");
ros::NodeHandle n;
//creates publisher of IMU message
ros::Publisher pub = n.advertise<sensor_msgs::Imu>("imu/data_raw", 1000);
//creates publisher of Magnetic FIeld message
ros::Publisher pubM = n.advertise<sensor_msgs::MagneticField>("imu/mag", 1000);
ros::Rate loop_rate(10);
/* Init the sensor the values are hardcoded at the local_defaults.h file */
int opt, len;
int i2c_bus = DEFAULT_I2C_BUS;
int sample_rate = DEFAULT_SAMPLE_RATE_HZ;
int yaw_mix_factor = DEFAULT_YAW_MIX_FACTOR;
int verbose = 0;
char *mag_cal_file = NULL;
char *accel_cal_file = NULL;
//creates object of mpudata_t
mpudata_t mpu;
// Initialize the MPU-9150
register_sig_handler();
mpu9150_set_debug(verbose);
if (mpu9150_init(i2c_bus, sample_rate, yaw_mix_factor))
exit(1);
set_cal(0, accel_cal_file);
set_cal(1, mag_cal_file);
if (accel_cal_file)
free(accel_cal_file);
if (mag_cal_file)
free(mag_cal_file);
if (sample_rate == 0)
return -1;
/**
* A count of how many messages we have sent. This is used to create
* a unique string for each message.
*/
int count = 0;
while (ros::ok())
{
//creates objects of each message type
//IMU Message
sensor_msgs::Imu msgIMU;
std_msgs::String header;
geometry_msgs::Quaternion orientation;
geometry_msgs::Vector3 angular_velocity;
geometry_msgs::Vector3 linear_acceleration;
//magnetometer message
sensor_msgs::MagneticField msgMAG;
geometry_msgs::Vector3 magnetic_field;
//modified to output in the format of IMU message
if (mpu9150_read(&mpu) == 0) {
//IMU Message
//sets up header for IMU message
msgIMU.header.seq = count;
msgIMU.header.stamp.sec = ros::Time::now().toSec();
msgIMU.header.frame_id = "/base_link";
//adds data to the sensor message
//orientation
msgIMU.orientation.x = mpu.fusedQuat[QUAT_X];
msgIMU.orientation.y = mpu.fusedQuat[QUAT_Y];
msgIMU.orientation.z = mpu.fusedQuat[QUAT_Z];
msgIMU.orientation.w = mpu.fusedQuat[QUAT_W];
//msgIMU.orientation_covariance[0] =
//angular velocity
msgIMU.angular_velocity.x = mpu.fusedEuler[VEC3_X] * RAD_TO_DEGREE;
msgIMU.angular_velocity.y = mpu.fusedEuler[VEC3_Y] * RAD_TO_DEGREE;
msgIMU.angular_velocity.z = mpu.fusedEuler[VEC3_Z] * RAD_TO_DEGREE;
//msgIMU.angular_velocity_covariance[] =
//linear acceleration
msgIMU.linear_acceleration.x = mpu.calibratedAccel[VEC3_X];
msgIMU.linear_acceleration.y = mpu.calibratedAccel[VEC3_Y];
msgIMU.linear_acceleration.z = mpu.calibratedAccel[VEC3_Z];
//msgIMU.linear_acceleration_covariance[] =
//Magnetometer Message
//sets up header
msgMAG.header.seq = count;
msgMAG.header.stamp.sec = ros::Time::now().toSec();
msgMAG.header.frame_id = "/base_link";
//adds data to magnetic field message
msgMAG.magnetic_field.x = mpu.calibratedMag[VEC3_X];
msgMAG.magnetic_field.y = mpu.calibratedMag[VEC3_Y];
msgMAG.magnetic_field.z = mpu.calibratedMag[VEC3_Z];
//fills the list with zeros as per message spec when no covariance is known
//msgMAG.magnetic_field_covariance[9] = {0, 0, 0, 0, 0, 0, 0, 0, 0};
}
//publish both messages
pub.publish(msgIMU);
pubM.publish(msgMAG);
ros::spinOnce();
loop_rate.sleep();
++count;
}
mpu9150_exit();
return 0;
}
int set_cal(int mag, char *cal_file)
{
int i;
FILE *f;
char buff[32];
long val[6];
caldata_t cal;
if (cal_file) {
f = fopen(cal_file, "r");
if (!f) {
perror("open(<cal-file>)");
return -1;
}
}
else {
if (mag) {
f = fopen("./magcal.txt", "r");
if (!f) {
printf("Default magcal.txt not found\n");
return 0;
}
}
else {
f = fopen("./accelcal.txt", "r");
if (!f) {
printf("Default accelcal.txt not found\n");
return 0;
}
}
}
memset(buff, 0, sizeof(buff));
for (i = 0; i < 6; i++) {
if (!fgets(buff, 20, f)) {
printf("Not enough lines in calibration file\n");
break;
}
val[i] = atoi(buff);
if (val[i] == 0) {
printf("Invalid cal value: %s\n", buff);
break;
}
}
fclose(f);
if (i != 6)
return -1;
cal.offset[0] = (short)((val[0] + val[1]) / 2);
cal.offset[1] = (short)((val[2] + val[3]) / 2);
cal.offset[2] = (short)((val[4] + val[5]) / 2);
cal.range[0] = (short)(val[1] - cal.offset[0]);
cal.range[1] = (short)(val[3] - cal.offset[1]);
cal.range[2] = (short)(val[5] - cal.offset[2]);
if (mag)
mpu9150_set_mag_cal(&cal);
else
mpu9150_set_accel_cal(&cal);
return 0;
}
void register_sig_handler()
{
struct sigaction sia;
bzero(&sia, sizeof sia);
sia.sa_handler = sigint_handler;
if (sigaction(SIGINT, &sia, NULL) < 0) {
perror("sigaction(SIGINT)");
exit(1);
}
}
void sigint_handler(int sig)
{
done = 1;
}<commit_msg>added loop control<commit_after>/*
* =====================================================================================
*
* Filename: mpu9150_node.cpp
*
* Description: ROS package that launches a node and publishes
* the Invensense MPU-9150 in the format Imu.msgs and MagneticField.msgs to the topics
* /imu/data_raw and /imu/mag
*
* Version: 1.1
* Created: 27/07/13 15:06:50
* Revision: Morgan Dykshorn <mdd27@vt.edu> 2015
*
* Author: Víctor Mayoral Vilches <v.mayoralv@gmail.com>
*
* =====================================================================================
*/
#include "ros/ros.h"
#include "std_msgs/String.h"
//include IMU message, geometry message quaternion, geometry message vector3, and magnetic field
#include "sensor_msgs/Imu.h"
#include "geometry_msgs/Quaternion.h"
#include "geometry_msgs/Vector3.h"
#include "sensor_msgs/MagneticField.h"
#include <sstream>
#include <stdio.h>
#include <stdint.h>
#include <stdlib.h>
#include <string.h>
#include <signal.h>
#include <getopt.h>
#include <errno.h>
// Needed when mixing C and C++ code/libraries
#ifdef __cplusplus
extern "C" {
#endif
#include "mpu9150.h"
#include "linux_glue.h"
#include "local_defaults.h"
#ifdef __cplusplus
}
#endif
//calibration function
int set_cal(int mag, char *cal_file);
//
void register_sig_handler();
void sigint_handler(int sig);
int done;
int main(int argc, char **argv)
{
ros::init(argc, argv, "mpu9150_node");
ros::NodeHandle n;
//creates publisher of IMU message
ros::Publisher pub = n.advertise<sensor_msgs::Imu>("imu/data_raw", 1000);
//creates publisher of Magnetic FIeld message
ros::Publisher pubM = n.advertise<sensor_msgs::MagneticField>("imu/mag", 1000);
ros::Rate loop_rate(10);
/* Init the sensor the values are hardcoded at the local_defaults.h file */
int opt, len;
int i2c_bus = DEFAULT_I2C_BUS;
int sample_rate = DEFAULT_SAMPLE_RATE_HZ;
int yaw_mix_factor = DEFAULT_YAW_MIX_FACTOR;
int verbose = 0;
char *mag_cal_file = NULL;
char *accel_cal_file = NULL;
//creates object of mpudata_t
mpudata_t mpu;
// Initialize the MPU-9150
register_sig_handler();
mpu9150_set_debug(verbose);
if (mpu9150_init(i2c_bus, sample_rate, yaw_mix_factor))
exit(1);
set_cal(0, accel_cal_file);
set_cal(1, mag_cal_file);
if (accel_cal_file)
free(accel_cal_file);
if (mag_cal_file)
free(mag_cal_file);
if (sample_rate == 0)
return -1;
// ROS loop config
loop_delay = (1000 / sample_rate) - 2;
printf("\nEntering MPU read loop (ctrl-c to exit)\n\n");
linux_delay_ms(loop_delay);
/**
* A count of how many messages we have sent. This is used to create
* a unique string for each message.
*/
int count = 0;
while (ros::ok())
{
//creates objects of each message type
//IMU Message
sensor_msgs::Imu msgIMU;
std_msgs::String header;
geometry_msgs::Quaternion orientation;
geometry_msgs::Vector3 angular_velocity;
geometry_msgs::Vector3 linear_acceleration;
//magnetometer message
sensor_msgs::MagneticField msgMAG;
geometry_msgs::Vector3 magnetic_field;
//modified to output in the format of IMU message
if (mpu9150_read(&mpu) == 0) {
//IMU Message
//sets up header for IMU message
msgIMU.header.seq = count;
msgIMU.header.stamp.sec = ros::Time::now().toSec();
msgIMU.header.frame_id = "/base_link";
//adds data to the sensor message
//orientation
msgIMU.orientation.x = mpu.fusedQuat[QUAT_X];
msgIMU.orientation.y = mpu.fusedQuat[QUAT_Y];
msgIMU.orientation.z = mpu.fusedQuat[QUAT_Z];
msgIMU.orientation.w = mpu.fusedQuat[QUAT_W];
//msgIMU.orientation_covariance[0] =
//angular velocity
msgIMU.angular_velocity.x = mpu.fusedEuler[VEC3_X] * RAD_TO_DEGREE;
msgIMU.angular_velocity.y = mpu.fusedEuler[VEC3_Y] * RAD_TO_DEGREE;
msgIMU.angular_velocity.z = mpu.fusedEuler[VEC3_Z] * RAD_TO_DEGREE;
//msgIMU.angular_velocity_covariance[] =
//linear acceleration
msgIMU.linear_acceleration.x = mpu.calibratedAccel[VEC3_X];
msgIMU.linear_acceleration.y = mpu.calibratedAccel[VEC3_Y];
msgIMU.linear_acceleration.z = mpu.calibratedAccel[VEC3_Z];
//msgIMU.linear_acceleration_covariance[] =
//Magnetometer Message
//sets up header
msgMAG.header.seq = count;
msgMAG.header.stamp.sec = ros::Time::now().toSec();
msgMAG.header.frame_id = "/base_link";
//adds data to magnetic field message
msgMAG.magnetic_field.x = mpu.calibratedMag[VEC3_X];
msgMAG.magnetic_field.y = mpu.calibratedMag[VEC3_Y];
msgMAG.magnetic_field.z = mpu.calibratedMag[VEC3_Z];
//fills the list with zeros as per message spec when no covariance is known
//msgMAG.magnetic_field_covariance[9] = {0, 0, 0, 0, 0, 0, 0, 0, 0};
}
//publish both messages
pub.publish(msgIMU);
pubM.publish(msgMAG);
ros::spinOnce();
loop_rate.sleep();
++count;
}
mpu9150_exit();
return 0;
}
int set_cal(int mag, char *cal_file)
{
int i;
FILE *f;
char buff[32];
long val[6];
caldata_t cal;
if (cal_file) {
f = fopen(cal_file, "r");
if (!f) {
perror("open(<cal-file>)");
return -1;
}
}
else {
if (mag) {
f = fopen("./magcal.txt", "r");
if (!f) {
printf("Default magcal.txt not found\n");
return 0;
}
}
else {
f = fopen("./accelcal.txt", "r");
if (!f) {
printf("Default accelcal.txt not found\n");
return 0;
}
}
}
memset(buff, 0, sizeof(buff));
for (i = 0; i < 6; i++) {
if (!fgets(buff, 20, f)) {
printf("Not enough lines in calibration file\n");
break;
}
val[i] = atoi(buff);
if (val[i] == 0) {
printf("Invalid cal value: %s\n", buff);
break;
}
}
fclose(f);
if (i != 6)
return -1;
cal.offset[0] = (short)((val[0] + val[1]) / 2);
cal.offset[1] = (short)((val[2] + val[3]) / 2);
cal.offset[2] = (short)((val[4] + val[5]) / 2);
cal.range[0] = (short)(val[1] - cal.offset[0]);
cal.range[1] = (short)(val[3] - cal.offset[1]);
cal.range[2] = (short)(val[5] - cal.offset[2]);
if (mag)
mpu9150_set_mag_cal(&cal);
else
mpu9150_set_accel_cal(&cal);
return 0;
}
void register_sig_handler()
{
struct sigaction sia;
bzero(&sia, sizeof sia);
sia.sa_handler = sigint_handler;
if (sigaction(SIGINT, &sia, NULL) < 0) {
perror("sigaction(SIGINT)");
exit(1);
}
}
void sigint_handler(int sig)
{
done = 1;
}<|endoftext|> |
<commit_before>/*
Persons Model Contact Item
Represents person's contact item in the model
Copyright (C) 2012 Martin Klapetek <martin.klapetek@gmail.com>
Copyright (C) 2012 Aleix Pol Gonzalez <aleixpol@blue-systems.com>
This library is free software; you can redistribute it and/or
modify it under the terms of the GNU Lesser General Public
License as published by the Free Software Foundation; either
version 2.1 of the License, or (at your option) any later version.
This library is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public
License along with this library; if not, write to the Free Software
Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
*/
#include "persons-model-contact-item.h"
#include <KIcon>
#include <KDebug>
#include <Nepomuk/Vocabulary/NCO>
#include <Soprano/Vocabulary/NAO>
#include <Soprano/Model>
#include <Soprano/QueryResultIterator>
#include <Nepomuk/Resource>
#include <Nepomuk/Variant>
#include <Nepomuk/ResourceManager>
class PersonsModelContactItemPrivate {
public:
QHash<QUrl, QVariant> data;
};
PersonsModelContactItem::PersonsModelContactItem(const QUrl& uri, const QString& displayName)
: d_ptr(new PersonsModelContactItemPrivate)
{
setData(uri, PersonsModel::UriRole);
setText(displayName);
refreshIcon();
}
PersonsModelContactItem::~PersonsModelContactItem()
{
delete d_ptr;
}
QMap<PersonsModel::ContactType, QIcon> initializeTypeIcons()
{
QMap<PersonsModel::ContactType, QIcon> ret;
ret.insert(PersonsModel::Email, QIcon::fromTheme(QLatin1String("mail-mark-unread")));
ret.insert(PersonsModel::IM, QIcon::fromTheme(QLatin1String("im-user")));
ret.insert(PersonsModel::Phone, QIcon::fromTheme(QLatin1String("phone")));
ret.insert(PersonsModel::MobilePhone, QIcon::fromTheme(QLatin1String("phone")));
ret.insert(PersonsModel::Postal, QIcon::fromTheme(QLatin1String("mail-message")));
return ret;
}
static QMap<PersonsModel::ContactType, QIcon> s_contactTypeMap = initializeTypeIcons();
void PersonsModelContactItem::refreshIcon()
{
PersonsModel::ContactType type = (PersonsModel::ContactType) data(PersonsModel::ContactTypeRole).toInt();
setIcon(s_contactTypeMap[type]);
}
void PersonsModelContactItem::addData(const QUrl &key, const QVariant &value)
{
if(value.isNull())
return;
if(Nepomuk::Vocabulary::NCO::imNickname() == key) {
setText(value.toString());
} else if (Nepomuk::Vocabulary::NCO::imID() == key) {
setType(PersonsModel::IM);
} else if (Nepomuk::Vocabulary::NCO::hasEmailAddress() == key) {
setType(PersonsModel::Email);
}else if (Nepomuk::Vocabulary::NCO::emailAddress() == key) {
setText(value.toString());
}
Q_D(PersonsModelContactItem);
// kDebug() << "Inserting" << value << "(" << key << ")";
d->data.insert(key, value);
emitDataChanged();
}
QVariant PersonsModelContactItem::dataValue(const QUrl &key)
{
Q_D(PersonsModelContactItem);
return d->data.value(key);
}
QUrl PersonsModelContactItem::uri() const
{
return data(PersonsModel::UriRole).toUrl();
}
void PersonsModelContactItem::setType (PersonsModel::ContactType type)
{
setData(type, PersonsModel::ContactTypeRole);
refreshIcon();
}
QVariant PersonsModelContactItem::data(int role) const
{
Q_D(const PersonsModelContactItem);
switch(role) {
case PersonsModel::NickRole: return d->data.value(Nepomuk::Vocabulary::NCO::imNickname());
case PersonsModel::PhoneRole: return d->data.value(Nepomuk::Vocabulary::NCO::phoneNumber());
case PersonsModel::EmailRole: return d->data.value(Nepomuk::Vocabulary::NCO::emailAddress());
case PersonsModel::IMRole: return d->data.value(Nepomuk::Vocabulary::NCO::imID());
case PersonsModel::PhotoRole: {
QHash<QUrl, QVariant>::const_iterator it = d->data.constFind(Nepomuk::Vocabulary::NCO::photo());
if(it==d->data.constEnd()) {
const QString query = QString::fromLatin1("select ?url where { %1 nco:photo ?phRes. ?phRes nie:url ?url . }")
.arg( Soprano::Node::resourceToN3(uri()) );
Soprano::Model* model = Nepomuk::ResourceManager::instance()->mainModel();
Soprano::QueryResultIterator qit = model->executeQuery( query, Soprano::Query::QueryLanguageSparql );
QUrl url;
if( qit.next() ) {
url = qit["url"].uri();
}
it = d_ptr->data.insert(Nepomuk::Vocabulary::NCO::photo(), url);
}
return it!=d->data.constEnd() ? it.value() : QVariant();
}
}
return QStandardItem::data(role);
}
<commit_msg>Implement the ContactIdRole for contacts<commit_after>/*
Persons Model Contact Item
Represents person's contact item in the model
Copyright (C) 2012 Martin Klapetek <martin.klapetek@gmail.com>
Copyright (C) 2012 Aleix Pol Gonzalez <aleixpol@blue-systems.com>
This library is free software; you can redistribute it and/or
modify it under the terms of the GNU Lesser General Public
License as published by the Free Software Foundation; either
version 2.1 of the License, or (at your option) any later version.
This library is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public
License along with this library; if not, write to the Free Software
Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
*/
#include "persons-model-contact-item.h"
#include <KIcon>
#include <KDebug>
#include <Nepomuk/Vocabulary/NCO>
#include <Soprano/Vocabulary/NAO>
#include <Soprano/Model>
#include <Soprano/QueryResultIterator>
#include <Nepomuk/Resource>
#include <Nepomuk/Variant>
#include <Nepomuk/ResourceManager>
class PersonsModelContactItemPrivate {
public:
QHash<QUrl, QVariant> data;
};
PersonsModelContactItem::PersonsModelContactItem(const QUrl& uri, const QString& displayName)
: d_ptr(new PersonsModelContactItemPrivate)
{
setData(uri, PersonsModel::UriRole);
setText(displayName);
refreshIcon();
}
PersonsModelContactItem::~PersonsModelContactItem()
{
delete d_ptr;
}
QMap<PersonsModel::ContactType, QIcon> initializeTypeIcons()
{
QMap<PersonsModel::ContactType, QIcon> ret;
ret.insert(PersonsModel::Email, QIcon::fromTheme(QLatin1String("mail-mark-unread")));
ret.insert(PersonsModel::IM, QIcon::fromTheme(QLatin1String("im-user")));
ret.insert(PersonsModel::Phone, QIcon::fromTheme(QLatin1String("phone")));
ret.insert(PersonsModel::MobilePhone, QIcon::fromTheme(QLatin1String("phone")));
ret.insert(PersonsModel::Postal, QIcon::fromTheme(QLatin1String("mail-message")));
return ret;
}
static QMap<PersonsModel::ContactType, QIcon> s_contactTypeMap = initializeTypeIcons();
void PersonsModelContactItem::refreshIcon()
{
PersonsModel::ContactType type = (PersonsModel::ContactType) data(PersonsModel::ContactTypeRole).toInt();
setIcon(s_contactTypeMap[type]);
}
void PersonsModelContactItem::addData(const QUrl &key, const QVariant &value)
{
if(value.isNull())
return;
if(Nepomuk::Vocabulary::NCO::imNickname() == key) {
setText(value.toString());
} else if (Nepomuk::Vocabulary::NCO::imID() == key) {
setType(PersonsModel::IM);
} else if (Nepomuk::Vocabulary::NCO::hasEmailAddress() == key) {
setType(PersonsModel::Email);
}else if (Nepomuk::Vocabulary::NCO::emailAddress() == key) {
setText(value.toString());
}
Q_D(PersonsModelContactItem);
// kDebug() << "Inserting" << value << "(" << key << ")";
d->data.insert(key, value);
emitDataChanged();
}
QVariant PersonsModelContactItem::dataValue(const QUrl &key)
{
Q_D(PersonsModelContactItem);
return d->data.value(key);
}
QUrl PersonsModelContactItem::uri() const
{
return data(PersonsModel::UriRole).toUrl();
}
void PersonsModelContactItem::setType (PersonsModel::ContactType type)
{
setData(type, PersonsModel::ContactTypeRole);
refreshIcon();
}
QVariant PersonsModelContactItem::data(int role) const
{
Q_D(const PersonsModelContactItem);
switch(role) {
case PersonsModel::NickRole: return d->data.value(Nepomuk::Vocabulary::NCO::imNickname());
case PersonsModel::PhoneRole: return d->data.value(Nepomuk::Vocabulary::NCO::phoneNumber());
case PersonsModel::EmailRole: return d->data.value(Nepomuk::Vocabulary::NCO::emailAddress());
case PersonsModel::IMRole: return d->data.value(Nepomuk::Vocabulary::NCO::imID());
case PersonsModel::PhotoRole: {
QHash<QUrl, QVariant>::const_iterator it = d->data.constFind(Nepomuk::Vocabulary::NCO::photo());
if(it==d->data.constEnd()) {
const QString query = QString::fromLatin1("select ?url where { %1 nco:photo ?phRes. ?phRes nie:url ?url . }")
.arg( Soprano::Node::resourceToN3(uri()) );
Soprano::Model* model = Nepomuk::ResourceManager::instance()->mainModel();
Soprano::QueryResultIterator qit = model->executeQuery( query, Soprano::Query::QueryLanguageSparql );
QUrl url;
if( qit.next() ) {
url = qit["url"].uri();
}
it = d_ptr->data.insert(Nepomuk::Vocabulary::NCO::photo(), url);
}
return it!=d->data.constEnd() ? it.value() : QVariant();
}
case PersonsModel::ContactIdRole: {
int role = -1;
switch((PersonsModel::ContactType) data(PersonsModel::ContactTypeRole).toInt()) {
case PersonsModel::IM: role = PersonsModel::IMRole; break;
case PersonsModel::Phone: role = PersonsModel::PhoneRole; break;
case PersonsModel::Email: role = PersonsModel::EmailRole; break;
case PersonsModel::MobilePhone: role = PersonsModel::PhoneRole; break;
case PersonsModel::Postal: role = -1; break;
}
if(role>=0)
return data(role);
} break;
}
return QStandardItem::data(role);
}
<|endoftext|> |
<commit_before>//-----------------------------------------------------------------------bl-
//--------------------------------------------------------------------------
//
// GRINS - General Reacting Incompressible Navier-Stokes
//
// Copyright (C) 2014-2015 Paul T. Bauman, Roy H. Stogner
// Copyright (C) 2010-2013 The PECOS Development Team
//
// This library is free software; you can redistribute it and/or
// modify it under the terms of the Version 2.1 GNU Lesser General
// Public License 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. 51 Franklin Street, Fifth Floor,
// Boston, MA 02110-1301 USA
//
//-----------------------------------------------------------------------el-
// This class
#include "grins/multiphysics_sys.h"
// GRINS
#include "grins/assembly_context.h"
// libMesh
#include "libmesh/composite_function.h"
#include "libmesh/getpot.h"
namespace GRINS
{
MultiphysicsSystem::MultiphysicsSystem( libMesh::EquationSystems& es,
const std::string& name,
const unsigned int number )
: FEMSystem(es, name, number),
_use_numerical_jacobians_only(false)
{
return;
}
MultiphysicsSystem::~MultiphysicsSystem()
{
return;
}
void MultiphysicsSystem::attach_physics_list( PhysicsList physics_list )
{
_physics_list = physics_list;
return;
}
void MultiphysicsSystem::read_input_options( const GetPot& input )
{
// Read options for MultiphysicsSystem first
this->verify_analytic_jacobians = input("linear-nonlinear-solver/verify_analytic_jacobians", 0.0 );
this->print_solution_norms = input("screen-options/print_solution_norms", false );
this->print_solutions = input("screen-options/print_solutions", false );
this->print_residual_norms = input("screen-options/print_residual_norms", false );
// backwards compatibility with old config files.
/*! \todo Remove old print_residual nomenclature */
this->print_residuals = input("screen-options/print_residual", false );
if (this->print_residuals)
libmesh_deprecated();
this->print_residuals = input("screen-options/print_residuals", this->print_residuals );
this->print_jacobian_norms = input("screen-options/print_jacobian_norms", false );
this->print_jacobians = input("screen-options/print_jacobians", false );
this->print_element_solutions = input("screen-options/print_element_solutions", false );
this->print_element_residuals = input("screen-options/print_element_residuals", false );
this->print_element_jacobians = input("screen-options/print_element_jacobians", false );
_use_numerical_jacobians_only = input("linear-nonlinear-solver/use_numerical_jacobians_only", false );
numerical_jacobian_h =
input("linear-nonlinear-solver/numerical_jacobian_h",
numerical_jacobian_h);
}
void MultiphysicsSystem::init_data()
{
// Need this to be true because of our overloading of the
// mass_residual function.
// This is data in FEMSystem. MUST be set before FEMSystem::init_data.
use_fixed_solution = true;
// Initalize all the variables. We pass this pointer for the system.
/* NOTE: We CANNOT fuse this loop with the others. This loop
MUST complete first. */
/*! \todo Figure out how to tell compilers not to fuse this loop when
they want to be aggressive. */
for( PhysicsListIter physics_iter = _physics_list.begin();
physics_iter != _physics_list.end();
physics_iter++ )
{
(physics_iter->second)->init_variables( this );
}
// Now set time_evolving variables
for( PhysicsListIter physics_iter = _physics_list.begin();
physics_iter != _physics_list.end();
physics_iter++ )
{
(physics_iter->second)->set_time_evolving_vars( this );
}
// Set whether the problem we're solving is steady or not
// Since the variable is static, just call one Physics class
{
(_physics_list.begin()->second)->set_is_steady((this->time_solver)->is_steady());
}
for( PhysicsListIter physics_iter = _physics_list.begin();
physics_iter != _physics_list.end();
physics_iter++ )
{
// Initialize builtin BC's for each physics
(physics_iter->second)->init_bcs( this );
}
// Next, call parent init_data function to intialize everything.
libMesh::FEMSystem::init_data();
// After solution has been initialized we can project initial
// conditions to it
libMesh::CompositeFunction<libMesh::Number> ic_function;
for( PhysicsListIter physics_iter = _physics_list.begin();
physics_iter != _physics_list.end();
physics_iter++ )
{
// Initialize builtin IC's for each physics
(physics_iter->second)->init_ics( this, ic_function );
}
if (ic_function.n_subfunctions())
{
this->project_solution(&ic_function);
}
return;
}
libMesh::AutoPtr<libMesh::DiffContext> MultiphysicsSystem::build_context()
{
AssemblyContext* context = new AssemblyContext(*this);
libMesh::AutoPtr<libMesh::DiffContext> ap(context);
libMesh::DifferentiablePhysics* phys = libMesh::FEMSystem::get_physics();
libmesh_assert(phys);
// If we are solving a moving mesh problem, tell that to the Context
context->set_mesh_system(phys->get_mesh_system());
context->set_mesh_x_var(phys->get_mesh_x_var());
context->set_mesh_y_var(phys->get_mesh_y_var());
context->set_mesh_z_var(phys->get_mesh_z_var());
ap->set_deltat_pointer( &deltat );
// If we are solving the adjoint problem, tell that to the Context
ap->is_adjoint() = this->get_time_solver().is_adjoint();
return ap;
}
void MultiphysicsSystem::register_postprocessing_vars( const GetPot& input,
PostProcessedQuantities<libMesh::Real>& postprocessing )
{
for( PhysicsListIter physics_iter = _physics_list.begin();
physics_iter != _physics_list.end();
physics_iter++ )
{
(physics_iter->second)->register_postprocessing_vars( input, postprocessing );
}
return;
}
void MultiphysicsSystem::init_context( libMesh::DiffContext& context )
{
AssemblyContext& c = libMesh::libmesh_cast_ref<AssemblyContext&>(context);
//Loop over each physics to initialize relevant variable structures for assembling system
for( PhysicsListIter physics_iter = _physics_list.begin();
physics_iter != _physics_list.end();
physics_iter++ )
{
(physics_iter->second)->init_context( c );
}
return;
}
bool MultiphysicsSystem::_general_residual( bool request_jacobian,
libMesh::DiffContext& context,
ResFuncType resfunc,
CacheFuncType cachefunc)
{
AssemblyContext& c = libMesh::libmesh_cast_ref<AssemblyContext&>(context);
bool compute_jacobian = true;
if( !request_jacobian || _use_numerical_jacobians_only ) compute_jacobian = false;
CachedValues cache;
// Now compute cache for this element
for( PhysicsListIter physics_iter = _physics_list.begin();
physics_iter != _physics_list.end();
physics_iter++ )
{
// boost::shared_ptr gets confused by operator->*
((*(physics_iter->second)).*cachefunc)( c, cache );
}
// Loop over each physics and compute their contributions
for( PhysicsListIter physics_iter = _physics_list.begin();
physics_iter != _physics_list.end();
physics_iter++ )
{
if(c.has_elem())
{
if( (physics_iter->second)->enabled_on_elem( &c.get_elem() ) )
{
((*(physics_iter->second)).*resfunc)( compute_jacobian, c, cache );
}
}
else
{
((*(physics_iter->second)).*resfunc)( compute_jacobian, c, cache );
}
}
// TODO: Need to think about the implications of this because there might be some
// TODO: jacobian terms we don't want to compute for efficiency reasons
return compute_jacobian;
}
bool MultiphysicsSystem::element_time_derivative( bool request_jacobian,
libMesh::DiffContext& context )
{
return this->_general_residual
(request_jacobian,
context,
&GRINS::Physics::element_time_derivative,
&GRINS::Physics::compute_element_time_derivative_cache);
}
bool MultiphysicsSystem::side_time_derivative( bool request_jacobian,
libMesh::DiffContext& context )
{
return this->_general_residual
(request_jacobian,
context,
&GRINS::Physics::side_time_derivative,
&GRINS::Physics::compute_side_time_derivative_cache);
}
bool MultiphysicsSystem::nonlocal_time_derivative( bool request_jacobian,
libMesh::DiffContext& context )
{
return this->_general_residual
(request_jacobian,
context,
&GRINS::Physics::nonlocal_time_derivative,
&GRINS::Physics::compute_nonlocal_time_derivative_cache);
}
bool MultiphysicsSystem::element_constraint( bool request_jacobian,
libMesh::DiffContext& context )
{
return this->_general_residual
(request_jacobian,
context,
&GRINS::Physics::element_constraint,
&GRINS::Physics::compute_element_constraint_cache);
}
bool MultiphysicsSystem::side_constraint( bool request_jacobian,
libMesh::DiffContext& context )
{
return this->_general_residual
(request_jacobian,
context,
&GRINS::Physics::side_constraint,
&GRINS::Physics::compute_side_constraint_cache);
}
bool MultiphysicsSystem::nonlocal_constraint( bool request_jacobian,
libMesh::DiffContext& context )
{
return this->_general_residual
(request_jacobian,
context,
&GRINS::Physics::nonlocal_constraint,
&GRINS::Physics::compute_nonlocal_constraint_cache);
}
bool MultiphysicsSystem::mass_residual( bool request_jacobian,
libMesh::DiffContext& context )
{
return this->_general_residual
(request_jacobian,
context,
&GRINS::Physics::mass_residual,
&GRINS::Physics::compute_mass_residual_cache);
}
bool MultiphysicsSystem::nonlocal_mass_residual( bool request_jacobian,
libMesh::DiffContext& context )
{
return this->_general_residual
(request_jacobian,
context,
&GRINS::Physics::nonlocal_mass_residual,
&GRINS::Physics::compute_nonlocal_mass_residual_cache);
}
std::tr1::shared_ptr<Physics> MultiphysicsSystem::get_physics( const std::string physics_name )
{
if( _physics_list.find( physics_name ) == _physics_list.end() )
{
std::cerr << "Error: Could not find physics " << physics_name << std::endl;
libmesh_error();
}
return _physics_list[physics_name];
}
bool MultiphysicsSystem::has_physics( const std::string physics_name ) const
{
bool has_physics = false;
if( _physics_list.find(physics_name) != _physics_list.end() )
has_physics = true;
return has_physics;
}
void MultiphysicsSystem::compute_postprocessed_quantity( unsigned int quantity_index,
const AssemblyContext& context,
const libMesh::Point& point,
libMesh::Real& value )
{
for( PhysicsListIter physics_iter = _physics_list.begin();
physics_iter != _physics_list.end();
physics_iter++ )
{
// Only compute if physics is active on current subdomain or globally
if( (physics_iter->second)->enabled_on_elem( &context.get_elem() ) )
{
(physics_iter->second)->compute_postprocessed_quantity( quantity_index, context, point, value );
}
}
return;
}
#ifdef GRINS_USE_GRVY_TIMERS
void MultiphysicsSystem::attach_grvy_timer( GRVY::GRVY_Timer_Class* grvy_timer )
{
_timer = grvy_timer;
// Attach timers to each physics
for( PhysicsListIter physics_iter = _physics_list.begin();
physics_iter != _physics_list.end();
physics_iter++ )
{
(physics_iter->second)->attach_grvy_timer( grvy_timer );
}
return;
}
#endif
} // namespace GRINS
<commit_msg>Have MultiphysicsSystem call Physics::auxiliary_init<commit_after>//-----------------------------------------------------------------------bl-
//--------------------------------------------------------------------------
//
// GRINS - General Reacting Incompressible Navier-Stokes
//
// Copyright (C) 2014-2015 Paul T. Bauman, Roy H. Stogner
// Copyright (C) 2010-2013 The PECOS Development Team
//
// This library is free software; you can redistribute it and/or
// modify it under the terms of the Version 2.1 GNU Lesser General
// Public License 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. 51 Franklin Street, Fifth Floor,
// Boston, MA 02110-1301 USA
//
//-----------------------------------------------------------------------el-
// This class
#include "grins/multiphysics_sys.h"
// GRINS
#include "grins/assembly_context.h"
// libMesh
#include "libmesh/composite_function.h"
#include "libmesh/getpot.h"
namespace GRINS
{
MultiphysicsSystem::MultiphysicsSystem( libMesh::EquationSystems& es,
const std::string& name,
const unsigned int number )
: FEMSystem(es, name, number),
_use_numerical_jacobians_only(false)
{
return;
}
MultiphysicsSystem::~MultiphysicsSystem()
{
return;
}
void MultiphysicsSystem::attach_physics_list( PhysicsList physics_list )
{
_physics_list = physics_list;
return;
}
void MultiphysicsSystem::read_input_options( const GetPot& input )
{
// Read options for MultiphysicsSystem first
this->verify_analytic_jacobians = input("linear-nonlinear-solver/verify_analytic_jacobians", 0.0 );
this->print_solution_norms = input("screen-options/print_solution_norms", false );
this->print_solutions = input("screen-options/print_solutions", false );
this->print_residual_norms = input("screen-options/print_residual_norms", false );
// backwards compatibility with old config files.
/*! \todo Remove old print_residual nomenclature */
this->print_residuals = input("screen-options/print_residual", false );
if (this->print_residuals)
libmesh_deprecated();
this->print_residuals = input("screen-options/print_residuals", this->print_residuals );
this->print_jacobian_norms = input("screen-options/print_jacobian_norms", false );
this->print_jacobians = input("screen-options/print_jacobians", false );
this->print_element_solutions = input("screen-options/print_element_solutions", false );
this->print_element_residuals = input("screen-options/print_element_residuals", false );
this->print_element_jacobians = input("screen-options/print_element_jacobians", false );
_use_numerical_jacobians_only = input("linear-nonlinear-solver/use_numerical_jacobians_only", false );
numerical_jacobian_h =
input("linear-nonlinear-solver/numerical_jacobian_h",
numerical_jacobian_h);
}
void MultiphysicsSystem::init_data()
{
// Need this to be true because of our overloading of the
// mass_residual function.
// This is data in FEMSystem. MUST be set before FEMSystem::init_data.
use_fixed_solution = true;
// Initalize all the variables. We pass this pointer for the system.
/* NOTE: We CANNOT fuse this loop with the others. This loop
MUST complete first. */
/*! \todo Figure out how to tell compilers not to fuse this loop when
they want to be aggressive. */
for( PhysicsListIter physics_iter = _physics_list.begin();
physics_iter != _physics_list.end();
physics_iter++ )
{
(physics_iter->second)->init_variables( this );
}
// Now set time_evolving variables
for( PhysicsListIter physics_iter = _physics_list.begin();
physics_iter != _physics_list.end();
physics_iter++ )
{
(physics_iter->second)->set_time_evolving_vars( this );
}
// Set whether the problem we're solving is steady or not
// Since the variable is static, just call one Physics class
{
(_physics_list.begin()->second)->set_is_steady((this->time_solver)->is_steady());
}
for( PhysicsListIter physics_iter = _physics_list.begin();
physics_iter != _physics_list.end();
physics_iter++ )
{
// Initialize builtin BC's for each physics
(physics_iter->second)->init_bcs( this );
}
// Next, call parent init_data function to intialize everything.
libMesh::FEMSystem::init_data();
// After solution has been initialized we can project initial
// conditions to it
libMesh::CompositeFunction<libMesh::Number> ic_function;
for( PhysicsListIter physics_iter = _physics_list.begin();
physics_iter != _physics_list.end();
physics_iter++ )
{
// Initialize builtin IC's for each physics
(physics_iter->second)->init_ics( this, ic_function );
}
if (ic_function.n_subfunctions())
{
this->project_solution(&ic_function);
}
// Now do any auxillary initialization required by each Physics
for( PhysicsListIter physics_iter = _physics_list.begin();
physics_iter != _physics_list.end();
physics_iter++ )
{
(physics_iter->second)->auxiliary_init( *this );
}
return;
}
libMesh::AutoPtr<libMesh::DiffContext> MultiphysicsSystem::build_context()
{
AssemblyContext* context = new AssemblyContext(*this);
libMesh::AutoPtr<libMesh::DiffContext> ap(context);
libMesh::DifferentiablePhysics* phys = libMesh::FEMSystem::get_physics();
libmesh_assert(phys);
// If we are solving a moving mesh problem, tell that to the Context
context->set_mesh_system(phys->get_mesh_system());
context->set_mesh_x_var(phys->get_mesh_x_var());
context->set_mesh_y_var(phys->get_mesh_y_var());
context->set_mesh_z_var(phys->get_mesh_z_var());
ap->set_deltat_pointer( &deltat );
// If we are solving the adjoint problem, tell that to the Context
ap->is_adjoint() = this->get_time_solver().is_adjoint();
return ap;
}
void MultiphysicsSystem::register_postprocessing_vars( const GetPot& input,
PostProcessedQuantities<libMesh::Real>& postprocessing )
{
for( PhysicsListIter physics_iter = _physics_list.begin();
physics_iter != _physics_list.end();
physics_iter++ )
{
(physics_iter->second)->register_postprocessing_vars( input, postprocessing );
}
return;
}
void MultiphysicsSystem::init_context( libMesh::DiffContext& context )
{
AssemblyContext& c = libMesh::libmesh_cast_ref<AssemblyContext&>(context);
//Loop over each physics to initialize relevant variable structures for assembling system
for( PhysicsListIter physics_iter = _physics_list.begin();
physics_iter != _physics_list.end();
physics_iter++ )
{
(physics_iter->second)->init_context( c );
}
return;
}
bool MultiphysicsSystem::_general_residual( bool request_jacobian,
libMesh::DiffContext& context,
ResFuncType resfunc,
CacheFuncType cachefunc)
{
AssemblyContext& c = libMesh::libmesh_cast_ref<AssemblyContext&>(context);
bool compute_jacobian = true;
if( !request_jacobian || _use_numerical_jacobians_only ) compute_jacobian = false;
CachedValues cache;
// Now compute cache for this element
for( PhysicsListIter physics_iter = _physics_list.begin();
physics_iter != _physics_list.end();
physics_iter++ )
{
// boost::shared_ptr gets confused by operator->*
((*(physics_iter->second)).*cachefunc)( c, cache );
}
// Loop over each physics and compute their contributions
for( PhysicsListIter physics_iter = _physics_list.begin();
physics_iter != _physics_list.end();
physics_iter++ )
{
if(c.has_elem())
{
if( (physics_iter->second)->enabled_on_elem( &c.get_elem() ) )
{
((*(physics_iter->second)).*resfunc)( compute_jacobian, c, cache );
}
}
else
{
((*(physics_iter->second)).*resfunc)( compute_jacobian, c, cache );
}
}
// TODO: Need to think about the implications of this because there might be some
// TODO: jacobian terms we don't want to compute for efficiency reasons
return compute_jacobian;
}
bool MultiphysicsSystem::element_time_derivative( bool request_jacobian,
libMesh::DiffContext& context )
{
return this->_general_residual
(request_jacobian,
context,
&GRINS::Physics::element_time_derivative,
&GRINS::Physics::compute_element_time_derivative_cache);
}
bool MultiphysicsSystem::side_time_derivative( bool request_jacobian,
libMesh::DiffContext& context )
{
return this->_general_residual
(request_jacobian,
context,
&GRINS::Physics::side_time_derivative,
&GRINS::Physics::compute_side_time_derivative_cache);
}
bool MultiphysicsSystem::nonlocal_time_derivative( bool request_jacobian,
libMesh::DiffContext& context )
{
return this->_general_residual
(request_jacobian,
context,
&GRINS::Physics::nonlocal_time_derivative,
&GRINS::Physics::compute_nonlocal_time_derivative_cache);
}
bool MultiphysicsSystem::element_constraint( bool request_jacobian,
libMesh::DiffContext& context )
{
return this->_general_residual
(request_jacobian,
context,
&GRINS::Physics::element_constraint,
&GRINS::Physics::compute_element_constraint_cache);
}
bool MultiphysicsSystem::side_constraint( bool request_jacobian,
libMesh::DiffContext& context )
{
return this->_general_residual
(request_jacobian,
context,
&GRINS::Physics::side_constraint,
&GRINS::Physics::compute_side_constraint_cache);
}
bool MultiphysicsSystem::nonlocal_constraint( bool request_jacobian,
libMesh::DiffContext& context )
{
return this->_general_residual
(request_jacobian,
context,
&GRINS::Physics::nonlocal_constraint,
&GRINS::Physics::compute_nonlocal_constraint_cache);
}
bool MultiphysicsSystem::mass_residual( bool request_jacobian,
libMesh::DiffContext& context )
{
return this->_general_residual
(request_jacobian,
context,
&GRINS::Physics::mass_residual,
&GRINS::Physics::compute_mass_residual_cache);
}
bool MultiphysicsSystem::nonlocal_mass_residual( bool request_jacobian,
libMesh::DiffContext& context )
{
return this->_general_residual
(request_jacobian,
context,
&GRINS::Physics::nonlocal_mass_residual,
&GRINS::Physics::compute_nonlocal_mass_residual_cache);
}
std::tr1::shared_ptr<Physics> MultiphysicsSystem::get_physics( const std::string physics_name )
{
if( _physics_list.find( physics_name ) == _physics_list.end() )
{
std::cerr << "Error: Could not find physics " << physics_name << std::endl;
libmesh_error();
}
return _physics_list[physics_name];
}
bool MultiphysicsSystem::has_physics( const std::string physics_name ) const
{
bool has_physics = false;
if( _physics_list.find(physics_name) != _physics_list.end() )
has_physics = true;
return has_physics;
}
void MultiphysicsSystem::compute_postprocessed_quantity( unsigned int quantity_index,
const AssemblyContext& context,
const libMesh::Point& point,
libMesh::Real& value )
{
for( PhysicsListIter physics_iter = _physics_list.begin();
physics_iter != _physics_list.end();
physics_iter++ )
{
// Only compute if physics is active on current subdomain or globally
if( (physics_iter->second)->enabled_on_elem( &context.get_elem() ) )
{
(physics_iter->second)->compute_postprocessed_quantity( quantity_index, context, point, value );
}
}
return;
}
#ifdef GRINS_USE_GRVY_TIMERS
void MultiphysicsSystem::attach_grvy_timer( GRVY::GRVY_Timer_Class* grvy_timer )
{
_timer = grvy_timer;
// Attach timers to each physics
for( PhysicsListIter physics_iter = _physics_list.begin();
physics_iter != _physics_list.end();
physics_iter++ )
{
(physics_iter->second)->attach_grvy_timer( grvy_timer );
}
return;
}
#endif
} // namespace GRINS
<|endoftext|> |
<commit_before>/**
** \file object/object.cc
** \brief Implementation of object::Object.
*/
#include <algorithm>
#include <boost/foreach.hpp>
#include <boost/lexical_cast.hpp>
#include "libport/containers.hh"
#include "object/object.hh"
#include "object/atom.hh"
#include "object/urbi-exception.hh"
namespace object
{
/*-------.
| kind. |
`-------*/
const char*
Object::string_of (Object::kind_type k)
{
switch (k)
{
#define CASE(What, Name) case kind_ ## What: return #Name; break;
APPLY_ON_ALL_PRIMITIVES(CASE);
#undef CASE
}
pabort("unreachable");
}
/*--------.
| Slots. |
`--------*/
Object::locate_type
Object::slot_locate (const key_type& k, Object::objects_type& os) const
{
/// Look in local slots.
slots_type::const_iterator it = slots_.find (k);
if (libport::mhas(slots_, k))
return locate_type(true, rObject());
/// Break recursive loops.
if (libport::mhas(os, this))
return locate_type(false, rObject());
os.insert (this);
/// Look in proto slots (depth first search).
locate_type res;
BOOST_FOREACH(rObject p, protos_)
if ((res = p->slot_locate(k, os)).first)
return res.second?res:locate_type(true, p);
return locate_type(false, rObject());
}
rObject slot_locate(const rObject& ref, const Object::key_type& k)
{
Object::objects_type os;
Object::locate_type l = ref->slot_locate(k, os);
if (l.first)
return l.second? l.second:ref;
else
return rObject();
}
Object*
Object::slot_locate(const key_type& k) const
{
objects_type os;
Object::locate_type l = slot_locate(k, os);
if (l.first)
return const_cast<Object*>(l.second?l.second.get():this);
else
return 0;
}
Object&
Object::safe_slot_locate(const key_type& k) const
{
Object* r = slot_locate(k);
if (!r)
boost::throw_exception (LookupError(k));
return *r;
}
const rObject&
Object::slot_get (const key_type& k) const
{
Object& cont = safe_slot_locate(k);
return cont.own_slot_get(k);
}
rObject&
Object::slot_get (const key_type& k)
{
return const_cast<rObject&>(const_cast<const Object*>(this)->slot_get(k));
}
Object&
Object::slot_set (const Object::key_type& k, rObject o)
{
if (libport::mhas(slots_, k))
boost::throw_exception (RedefinitionError(k));
slots_[k] = o;
return *this;
}
Object&
Object::slot_update (const Object::key_type& k, rObject o)
{
Object& l = safe_slot_locate(k);
if (locals_ && l.locals_) // Local scope writes local var: no copyonwrite.
l.own_slot_get(k) = o;
else if (locals_ && !l.locals_)
{
// Local->class: copyonwrite to "self".
rObject self = slot_get(SYMBOL(self));
assert(self);
if (self.get() == this)
slots_[k] = o;
else
self->slot_update(k, o);
}
else // Class->class: copy on write.
slots_[k] = o;
return *this;
}
/*-----------.
| Printing. |
`-----------*/
std::ostream&
Object::special_slots_dump (std::ostream& o) const
{
return o;
}
bool
Object::operator< (const Object& rhs) const
{
return this < &rhs;
}
std::ostream&
Object::id_dump (std::ostream& o) const
{
try
{
// Should be an rString.
o << slot_get(SYMBOL(type)).cast<String>()->value_get ();
}
catch (UrbiException&)
{}
return o << '_' << this;
}
std::ostream&
Object::dump (std::ostream& o) const
{
id_dump (o);
/// Use xalloc/iword to store our current depth within the stream object.
static const long idx = o.xalloc();
static const long depth_max = 3;
long& current_depth = o.iword(idx);
/// Stop recursion at depth_max.
if (current_depth > depth_max)
return o << " <...>";
++current_depth;
o << " {" << libport::incendl;
if (protos_.begin () != protos_.end ())
{
o << "protos = ";
for (protos_type::const_iterator i = protos_.begin ();
i != protos_.end (); ++i)
{
if (i != protos_.begin())
o << ", ";
(*i)->id_dump (o);
}
o << libport::iendl;
}
special_slots_dump (o);
BOOST_FOREACH (slot_type s, slots_)
o << s << libport::iendl;
o << libport::decindent << '}';
//We can not reuse current_depth variable above according to spec.
o.iword(idx)--;
return o;
}
std::ostream&
Object::print(std::ostream& out) const
{
// Temporary hack, detect void and print nothing
if (this == void_class.get())
return out;
// FIXME: Decide what should be printed, but at least print something
return out << "<object_" << std::hex << (long) (this) << ">";
}
} // namespace object
<commit_msg>Simplify useless recursion<commit_after>/**
** \file object/object.cc
** \brief Implementation of object::Object.
*/
#include <algorithm>
#include <boost/foreach.hpp>
#include <boost/lexical_cast.hpp>
#include "libport/containers.hh"
#include "object/object.hh"
#include "object/atom.hh"
#include "object/urbi-exception.hh"
namespace object
{
/*-------.
| kind. |
`-------*/
const char*
Object::string_of (Object::kind_type k)
{
switch (k)
{
#define CASE(What, Name) case kind_ ## What: return #Name; break;
APPLY_ON_ALL_PRIMITIVES(CASE);
#undef CASE
}
pabort("unreachable");
}
/*--------.
| Slots. |
`--------*/
Object::locate_type
Object::slot_locate (const key_type& k, Object::objects_type& os) const
{
/// Look in local slots.
slots_type::const_iterator it = slots_.find (k);
if (libport::mhas(slots_, k))
return locate_type(true, rObject());
/// Break recursive loops.
if (libport::mhas(os, this))
return locate_type(false, rObject());
os.insert (this);
/// Look in proto slots (depth first search).
locate_type res;
BOOST_FOREACH(rObject p, protos_)
if ((res = p->slot_locate(k, os)).first)
return res.second?res:locate_type(true, p);
return locate_type(false, rObject());
}
rObject slot_locate(const rObject& ref, const Object::key_type& k)
{
Object::objects_type os;
Object::locate_type l = ref->slot_locate(k, os);
if (l.first)
return l.second? l.second:ref;
else
return rObject();
}
Object*
Object::slot_locate(const key_type& k) const
{
objects_type os;
Object::locate_type l = slot_locate(k, os);
if (l.first)
return const_cast<Object*>(l.second?l.second.get():this);
else
return 0;
}
Object&
Object::safe_slot_locate(const key_type& k) const
{
Object* r = slot_locate(k);
if (!r)
boost::throw_exception (LookupError(k));
return *r;
}
const rObject&
Object::slot_get (const key_type& k) const
{
Object& cont = safe_slot_locate(k);
return cont.own_slot_get(k);
}
rObject&
Object::slot_get (const key_type& k)
{
return const_cast<rObject&>(const_cast<const Object*>(this)->slot_get(k));
}
Object&
Object::slot_set (const Object::key_type& k, rObject o)
{
if (libport::mhas(slots_, k))
boost::throw_exception (RedefinitionError(k));
slots_[k] = o;
return *this;
}
Object&
Object::slot_update (const Object::key_type& k, rObject o)
{
Object& l = safe_slot_locate(k);
if (locals_ && l.locals_) // Local scope writes local var: no copyonwrite.
l.own_slot_get(k) = o;
else if (locals_ && !l.locals_)
{
// Local->class: copyonwrite to "self".
rObject self = slot_get(SYMBOL(self));
assert(self);
self.get ()->slots_[k] = o;
}
else // Class->class: copy on write.
slots_[k] = o;
return *this;
}
/*-----------.
| Printing. |
`-----------*/
std::ostream&
Object::special_slots_dump (std::ostream& o) const
{
return o;
}
bool
Object::operator< (const Object& rhs) const
{
return this < &rhs;
}
std::ostream&
Object::id_dump (std::ostream& o) const
{
try
{
// Should be an rString.
o << slot_get(SYMBOL(type)).cast<String>()->value_get ();
}
catch (UrbiException&)
{}
return o << '_' << this;
}
std::ostream&
Object::dump (std::ostream& o) const
{
id_dump (o);
/// Use xalloc/iword to store our current depth within the stream object.
static const long idx = o.xalloc();
static const long depth_max = 3;
long& current_depth = o.iword(idx);
/// Stop recursion at depth_max.
if (current_depth > depth_max)
return o << " <...>";
++current_depth;
o << " {" << libport::incendl;
if (protos_.begin () != protos_.end ())
{
o << "protos = ";
for (protos_type::const_iterator i = protos_.begin ();
i != protos_.end (); ++i)
{
if (i != protos_.begin())
o << ", ";
(*i)->id_dump (o);
}
o << libport::iendl;
}
special_slots_dump (o);
BOOST_FOREACH (slot_type s, slots_)
o << s << libport::iendl;
o << libport::decindent << '}';
//We can not reuse current_depth variable above according to spec.
o.iword(idx)--;
return o;
}
std::ostream&
Object::print(std::ostream& out) const
{
// Temporary hack, detect void and print nothing
if (this == void_class.get())
return out;
// FIXME: Decide what should be printed, but at least print something
return out << "<object_" << std::hex << (long) (this) << ">";
}
} // namespace object
<|endoftext|> |
<commit_before>// Copyright (C) 2009, 2010 by Florent Lamiraux, Thomas Moulard, JRL.
//
// This file is part of the hpp-corbaserver.
//
// This software is provided "as is" without warranty of any kind,
// either expressed or implied, including but not limited to the
// implied warranties of fitness for a particular purpose.
//
// See the COPYING file for more information.
#include <iostream>
#include <hpp/util/debug.hh>
#include <fcl/BVH/BVH_model.h>
#include <fcl/shape/geometric_shapes.h>
#include <hpp/model/collision-object.hh>
#include <hpp/model/urdf/util.hh>
#include "obstacle.impl.hh"
#include "tools.hh"
#include "hpp/corbaserver/server.hh"
namespace hpp
{
namespace corbaServer
{
namespace impl
{
Obstacle::Obstacle (corbaServer::Server* server)
: server_ (server),
problemSolver_ (server->problemSolver ())
{}
void Obstacle::loadObstacleModel (const char* package,
const char* filename,
const char* prefix)
throw (hpp::Error)
{
try {
model::DevicePtr_t device (model::Device::create
(std::string (filename)));
hpp::model::urdf::loadUrdfModel (device,
"anchor",
std::string (package),
std::string (filename));
// Detach objects from joints
for (ObjectIterator itObj = device->objectIterator
(hpp::model::COLLISION); !itObj.isEnd (); ++itObj) {
CollisionObjectPtr_t obj = model::CollisionObject::create
((*itObj)->fcl ()->collisionGeometry(), (*itObj)->getTransform (),
std::string (prefix) + (*itObj)->name ());
problemSolver_->addObstacle (obj, true, true);
hppDout (info, "Adding obstacle " << obj->name ());
}
} catch (const std::exception& exc) {
throw hpp::Error (exc.what ());
}
}
void Obstacle::removeObstacleFromJoint
(const char* objectName, const char* jointName, Boolean collision,
Boolean distance) throw (hpp::Error)
{
using model::JointPtr_t;
using model::ObjectVector_t;
using model::COLLISION;
using model::DISTANCE;
std::string objName (objectName);
std::string jName (jointName);
try {
JointPtr_t joint = problemSolver_->robot ()->getJointByName (jName);
BodyPtr_t body = joint->linkedBody ();
if (!body) {
throw std::runtime_error
(std::string ("Joint " + jName + std::string (" has no body.")));
}
if (collision) {
bool found = false;
for (ObjectVector_t::const_iterator itObj =
body->outerObjects (COLLISION).begin ();
itObj != body->outerObjects (COLLISION).end () &&
!found; ++itObj) {
if ((*itObj)->name () == objName) {
found = true;
body->removeOuterObject (*itObj, true, false);
}
}
if (!found) {
throw std::runtime_error
(std::string ("Joint ") + jName +
std::string (" has no outer object called ") + objName);
}
}
if (distance) {
bool found = false;
for (ObjectVector_t::const_iterator itObj =
body->outerObjects (DISTANCE).begin ();
itObj != body->outerObjects (DISTANCE).end () &&
!found; ++itObj) {
if ((*itObj)->name () == objName) {
found = true;
body->removeOuterObject (*itObj, false, true);
}
}
if (!found) {
throw std::runtime_error
(std::string ("Joint ") + jName +
std::string (" has no outer object called ") + objName);
}
}
} catch (const std::exception& exc) {
throw hpp::Error (exc.what ());
}
}
void
Obstacle::addObstacle(const char* objectName, Boolean collision,
Boolean distance)
throw (hpp::Error)
{
std::string objName (objectName);
CollisionGeometryPtr_t geometry;
// Check that polyhedron exists.
VertexMap_t::const_iterator itVertex = vertexMap_.find(objName);
if (itVertex != vertexMap_.end ()) {
PolyhedronPtr_t polyhedron = PolyhedronPtr_t (new Polyhedron_t);
int res = polyhedron->beginModel ();
if (res != fcl::BVH_OK) {
std::ostringstream oss ("fcl BVHReturnCode = ");
oss << res;
throw hpp::Error (oss.str ().c_str ());
}
polyhedron->addSubModel (itVertex->second, triangleMap_ [objName]);
polyhedron->endModel ();
geometry = polyhedron;
} else {
ShapeMap_t::iterator itShape = shapeMap_.find (objName);
if (itShape != shapeMap_.end ()) {
geometry = itShape->second;
}
}
if (!geometry) {
std::ostringstream oss ("Object ");
oss << objName << " does not exist.";
throw hpp::Error (oss.str ().c_str ());
}
Transform3f pos; pos.setIdentity ();
CollisionObjectPtr_t collisionObject
(CollisionObject_t::create (geometry, pos, objName));
problemSolver_->addObstacle (collisionObject, collision, distance);
}
CollisionObjectPtr_t Obstacle::getObstacleByName (const char* name)
{
const ObjectVector_t& collisionObstacles
(problemSolver_->collisionObstacles ());
for (ObjectVector_t::const_iterator it = collisionObstacles.begin ();
it != collisionObstacles.end (); it++) {
CollisionObjectPtr_t object = *it;
if (object->name () == name) {
hppDout (info, "found \""
<< object->name () << "\" in the obstacle list.");
return object;
}
}
const ObjectVector_t& distanceObstacles
(problemSolver_->distanceObstacles ());
for (ObjectVector_t::const_iterator it = distanceObstacles.begin ();
it != distanceObstacles.end (); it++) {
CollisionObjectPtr_t object = *it;
if (object->name () == name) {
hppDout (info, "found \""
<< object->name () << "\" in the obstacle list.");
return object;
}
}
return CollisionObjectPtr_t ();
}
void Obstacle::moveObstacle
(const char* objectName, const CORBA::Double* cfg)
throw(hpp::Error)
{
CollisionObjectPtr_t object = getObstacleByName (objectName);
if (object) {
Transform3f mat;
hppTransformToTransform3f (cfg, mat);
object->move (mat);
return;
}
std::ostringstream oss ("Object ");
oss << objectName << " not found";
throw hpp::Error (oss.str ().c_str ());
}
void Obstacle::getObstaclePosition (const char* objectName,
Double* cfg)
throw (hpp::Error)
{
CollisionObjectPtr_t object = getObstacleByName (objectName);
if (object) {
Transform3f transform = object->getTransform ();
Transform3fTohppTransform (transform, cfg);
return;
}
std::ostringstream oss ("Object ");
oss << objectName << " not found";
throw hpp::Error (oss.str ().c_str ());
}
void Obstacle::createPolyhedron
(const char* polyhedronName) throw (hpp::Error)
{
// Check that polyhedron does not already exist.
if (vertexMap_.find(polyhedronName) != vertexMap_.end ()) {
std::ostringstream oss ("polyhedron ");
oss << polyhedronName << " already exists.";
throw hpp::Error (oss.str ().c_str ());
}
vertexMap_ [polyhedronName] = std::vector <fcl::Vec3f> ();
triangleMap_ [polyhedronName] = std::vector <fcl::Triangle> ();
}
void Obstacle::createBox
(const char* boxName, Double x, Double y, Double z)
throw (hpp::Error)
{
std::string shapeName(boxName);
// Check that object does not already exist.
if (vertexMap_.find(shapeName) != vertexMap_.end () ||
shapeMap_.find (shapeName) != shapeMap_.end ()) {
std::ostringstream oss ("object ");
oss << shapeName << " already exists.";
throw hpp::Error (oss.str ().c_str ());
}
BasicShapePtr_t box (new fcl::Box ( x, y, z));
shapeMap_[shapeName] = box;
}
Short Obstacle::addPoint
(const char* polyhedronName, Double x, Double y, Double z)
throw (hpp::Error)
{
// Check that polyhedron exists.
VertexMap_t::iterator itVertex = vertexMap_.find (polyhedronName);
if (itVertex == vertexMap_.end ()) {
std::ostringstream oss ("polyhedron ");
oss << polyhedronName << " does not exist.";
throw hpp::Error (oss.str ().c_str ());
}
itVertex->second.push_back (fcl::Vec3f (x, y, z));
return static_cast<Short> (vertexMap_.size ());
}
Short
Obstacle::addTriangle
(const char* polyhedronName, ULong pt1, ULong pt2, ULong pt3)
throw (hpp::Error)
{
// Check that polyhedron exists.
TriangleMap_t::iterator itTriangle = triangleMap_.find (polyhedronName);
if (itTriangle == triangleMap_.end ()) {
std::ostringstream oss ("polyhedron ");
oss << polyhedronName << " does not exist.";
throw hpp::Error (oss.str ().c_str ());
}
itTriangle->second.push_back (fcl::Triangle (pt1, pt2, pt3));
return static_cast<Short> (triangleMap_.size ());
}
} // end of namespace implementation.
} // end of namespace corbaServer.
} // end of namespace hpp.
<commit_msg>Update method removeObstacleFromJoint.<commit_after>// Copyright (C) 2009, 2010 by Florent Lamiraux, Thomas Moulard, JRL.
//
// This file is part of the hpp-corbaserver.
//
// This software is provided "as is" without warranty of any kind,
// either expressed or implied, including but not limited to the
// implied warranties of fitness for a particular purpose.
//
// See the COPYING file for more information.
#include <iostream>
#include <hpp/util/debug.hh>
#include <fcl/BVH/BVH_model.h>
#include <fcl/shape/geometric_shapes.h>
#include <hpp/model/collision-object.hh>
#include <hpp/model/urdf/util.hh>
#include "obstacle.impl.hh"
#include "tools.hh"
#include "hpp/corbaserver/server.hh"
namespace hpp
{
namespace corbaServer
{
namespace impl
{
Obstacle::Obstacle (corbaServer::Server* server)
: server_ (server),
problemSolver_ (server->problemSolver ())
{}
void Obstacle::loadObstacleModel (const char* package,
const char* filename,
const char* prefix)
throw (hpp::Error)
{
try {
model::DevicePtr_t device (model::Device::create
(std::string (filename)));
hpp::model::urdf::loadUrdfModel (device,
"anchor",
std::string (package),
std::string (filename));
// Detach objects from joints
for (ObjectIterator itObj = device->objectIterator
(hpp::model::COLLISION); !itObj.isEnd (); ++itObj) {
CollisionObjectPtr_t obj = model::CollisionObject::create
((*itObj)->fcl ()->collisionGeometry(), (*itObj)->getTransform (),
std::string (prefix) + (*itObj)->name ());
problemSolver_->addObstacle (obj, true, true);
hppDout (info, "Adding obstacle " << obj->name ());
}
} catch (const std::exception& exc) {
throw hpp::Error (exc.what ());
}
}
void Obstacle::removeObstacleFromJoint
(const char* objectName, const char* jointName, Boolean collision,
Boolean distance) throw (hpp::Error)
{
using model::JointPtr_t;
using model::ObjectVector_t;
using model::COLLISION;
using model::DISTANCE;
std::string objName (objectName);
std::string jName (jointName);
try {
if (collision) {
problemSolver_->removeObstacleFromJoint (objectName, jointName);
}
if (distance) {
throw std::runtime_error ("Not implemented.");
}
} catch (const std::exception& exc) {
throw hpp::Error (exc.what ());
}
}
void
Obstacle::addObstacle(const char* objectName, Boolean collision,
Boolean distance)
throw (hpp::Error)
{
std::string objName (objectName);
CollisionGeometryPtr_t geometry;
// Check that polyhedron exists.
VertexMap_t::const_iterator itVertex = vertexMap_.find(objName);
if (itVertex != vertexMap_.end ()) {
PolyhedronPtr_t polyhedron = PolyhedronPtr_t (new Polyhedron_t);
int res = polyhedron->beginModel ();
if (res != fcl::BVH_OK) {
std::ostringstream oss ("fcl BVHReturnCode = ");
oss << res;
throw hpp::Error (oss.str ().c_str ());
}
polyhedron->addSubModel (itVertex->second, triangleMap_ [objName]);
polyhedron->endModel ();
geometry = polyhedron;
} else {
ShapeMap_t::iterator itShape = shapeMap_.find (objName);
if (itShape != shapeMap_.end ()) {
geometry = itShape->second;
}
}
if (!geometry) {
std::ostringstream oss ("Object ");
oss << objName << " does not exist.";
throw hpp::Error (oss.str ().c_str ());
}
Transform3f pos; pos.setIdentity ();
CollisionObjectPtr_t collisionObject
(CollisionObject_t::create (geometry, pos, objName));
problemSolver_->addObstacle (collisionObject, collision, distance);
}
CollisionObjectPtr_t Obstacle::getObstacleByName (const char* name)
{
const ObjectVector_t& collisionObstacles
(problemSolver_->collisionObstacles ());
for (ObjectVector_t::const_iterator it = collisionObstacles.begin ();
it != collisionObstacles.end (); it++) {
CollisionObjectPtr_t object = *it;
if (object->name () == name) {
hppDout (info, "found \""
<< object->name () << "\" in the obstacle list.");
return object;
}
}
const ObjectVector_t& distanceObstacles
(problemSolver_->distanceObstacles ());
for (ObjectVector_t::const_iterator it = distanceObstacles.begin ();
it != distanceObstacles.end (); it++) {
CollisionObjectPtr_t object = *it;
if (object->name () == name) {
hppDout (info, "found \""
<< object->name () << "\" in the obstacle list.");
return object;
}
}
return CollisionObjectPtr_t ();
}
void Obstacle::moveObstacle
(const char* objectName, const CORBA::Double* cfg)
throw(hpp::Error)
{
CollisionObjectPtr_t object = getObstacleByName (objectName);
if (object) {
Transform3f mat;
hppTransformToTransform3f (cfg, mat);
object->move (mat);
return;
}
std::ostringstream oss ("Object ");
oss << objectName << " not found";
throw hpp::Error (oss.str ().c_str ());
}
void Obstacle::getObstaclePosition (const char* objectName,
Double* cfg)
throw (hpp::Error)
{
CollisionObjectPtr_t object = getObstacleByName (objectName);
if (object) {
Transform3f transform = object->getTransform ();
Transform3fTohppTransform (transform, cfg);
return;
}
std::ostringstream oss ("Object ");
oss << objectName << " not found";
throw hpp::Error (oss.str ().c_str ());
}
void Obstacle::createPolyhedron
(const char* polyhedronName) throw (hpp::Error)
{
// Check that polyhedron does not already exist.
if (vertexMap_.find(polyhedronName) != vertexMap_.end ()) {
std::ostringstream oss ("polyhedron ");
oss << polyhedronName << " already exists.";
throw hpp::Error (oss.str ().c_str ());
}
vertexMap_ [polyhedronName] = std::vector <fcl::Vec3f> ();
triangleMap_ [polyhedronName] = std::vector <fcl::Triangle> ();
}
void Obstacle::createBox
(const char* boxName, Double x, Double y, Double z)
throw (hpp::Error)
{
std::string shapeName(boxName);
// Check that object does not already exist.
if (vertexMap_.find(shapeName) != vertexMap_.end () ||
shapeMap_.find (shapeName) != shapeMap_.end ()) {
std::ostringstream oss ("object ");
oss << shapeName << " already exists.";
throw hpp::Error (oss.str ().c_str ());
}
BasicShapePtr_t box (new fcl::Box ( x, y, z));
shapeMap_[shapeName] = box;
}
Short Obstacle::addPoint
(const char* polyhedronName, Double x, Double y, Double z)
throw (hpp::Error)
{
// Check that polyhedron exists.
VertexMap_t::iterator itVertex = vertexMap_.find (polyhedronName);
if (itVertex == vertexMap_.end ()) {
std::ostringstream oss ("polyhedron ");
oss << polyhedronName << " does not exist.";
throw hpp::Error (oss.str ().c_str ());
}
itVertex->second.push_back (fcl::Vec3f (x, y, z));
return static_cast<Short> (vertexMap_.size ());
}
Short
Obstacle::addTriangle
(const char* polyhedronName, ULong pt1, ULong pt2, ULong pt3)
throw (hpp::Error)
{
// Check that polyhedron exists.
TriangleMap_t::iterator itTriangle = triangleMap_.find (polyhedronName);
if (itTriangle == triangleMap_.end ()) {
std::ostringstream oss ("polyhedron ");
oss << polyhedronName << " does not exist.";
throw hpp::Error (oss.str ().c_str ());
}
itTriangle->second.push_back (fcl::Triangle (pt1, pt2, pt3));
return static_cast<Short> (triangleMap_.size ());
}
} // end of namespace implementation.
} // end of namespace corbaServer.
} // end of namespace hpp.
<|endoftext|> |
<commit_before>/*
* Copyright (C) 2004-2008 See the AUTHORS file for details.
*
* This program is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 as published
* by the Free Software Foundation.
*/
#include "User.h"
#include "znc.h"
// Forward Declaration
class CShellMod;
class CShellSock : public CExecSock {
public:
CShellSock(CShellMod* pShellMod, CClient* pClient, const CString& sExec) : CExecSock( sExec ) {
EnableReadLine();
m_pParent = pShellMod;
m_pClient = pClient;
}
// These next two function's bodies are at the bottom of the file since they reference CShellMod
virtual void ReadLine(const CString& sData);
virtual void Disconnected();
CShellMod* m_pParent;
private:
CClient* m_pClient;
};
class CShellMod : public CModule {
public:
MODCONSTRUCTOR(CShellMod) {
m_sPath = CZNC::Get().GetHomePath();
}
virtual ~CShellMod() {
vector<Csock*> vSocks = m_pManager->FindSocksByName("SHELL");
for (unsigned int a = 0; a < vSocks.size(); a++) {
m_pManager->DelSockByAddr(vSocks[a]);
}
}
virtual bool OnLoad(const CString& sArgs, CString& sMessage)
{
#ifndef MOD_SHELL_ALLOW_EVERYONE
if (!m_pUser->IsAdmin()) {
sMessage = "You must be admin to use the shell module";
return false;
}
#endif
return true;
}
virtual void OnModCommand(const CString& sCommand) {
if ((strcasecmp(sCommand.c_str(), "cd") == 0) || (strncasecmp(sCommand.c_str(), "cd ", 3) == 0)) {
CString sPath = CUtils::ChangeDir(m_sPath, ((sCommand.length() == 2) ? CString(CZNC::Get().GetHomePath()) : CString(sCommand.substr(3))), CZNC::Get().GetHomePath());
CFile Dir(sPath);
if (Dir.IsDir()) {
m_sPath = sPath;
} else if (Dir.Exists()) {
PutShell("cd: not a directory [" + sPath + "]");
} else {
PutShell("cd: no such directory [" + sPath + "]");
}
PutShell("znc$");
} else if (strcasecmp(sCommand.Token(0).c_str(), "SEND") == 0) {
CString sToNick = sCommand.Token(1);
CString sFile = sCommand.Token(2);
if ((sToNick.empty()) || (sFile.empty())) {
PutShell("usage: Send <nick> <file>");
} else {
sFile = CUtils::ChangeDir(m_sPath, sFile, CZNC::Get().GetHomePath());
if (!CFile::Exists(sFile)) {
PutShell("get: no such file [" + sFile + "]");
} else if (!CFile::IsReg(sFile)) {
PutShell("get: not a file [" + sFile + "]");
} else {
m_pUser->SendFile(sToNick, sFile, GetModName());
}
}
} else if (strcasecmp(sCommand.Token(0).c_str(), "GET") == 0) {
CString sFile = sCommand.Token(1);
if (sFile.empty()) {
PutShell("usage: Get <file>");
} else {
sFile = CUtils::ChangeDir(m_sPath, sFile, CZNC::Get().GetHomePath());
if (!CFile::Exists(sFile)) {
PutShell("get: no such file [" + sFile + "]");
} else if (!CFile::IsReg(sFile)) {
PutShell("get: not a file [" + sFile + "]");
} else {
m_pUser->SendFile(m_pUser->GetCurNick(), sFile, GetModName());
}
}
} else {
RunCommand(sCommand);
}
}
virtual EModRet OnStatusCommand(const CString& sCommand) {
if (strcasecmp(sCommand.c_str(), "SHELL") == 0) {
PutShell("-- ZNC Shell Service --");
return HALT;
}
return CONTINUE;
}
virtual EModRet OnDCCUserSend(const CNick& RemoteNick, unsigned long uLongIP, unsigned short uPort, const CString& sFile, unsigned long uFileSize) {
if (strcasecmp(RemoteNick.GetNick().c_str(), CString(GetModNick()).c_str()) == 0) {
CString sLocalFile = CUtils::ChangeDir(m_sPath, sFile, CZNC::Get().GetHomePath());
m_pUser->GetFile(m_pUser->GetCurNick(), CUtils::GetIP(uLongIP), uPort, sLocalFile, uFileSize, GetModName());
return HALT;
}
return CONTINUE;
}
void PutShell(const CString& sLine) {
CString sPath = m_sPath;
CString::size_type a = sPath.find(' ');
while (a != CString::npos) {
sPath.replace(a, 1, "_");
a = sPath.find(' ');
}
PutModule(sLine, m_pUser->GetCurNick(), sPath);
}
void RunCommand(const CString& sCommand) {
m_pManager->AddSock((Csock*) new CShellSock(this, m_pClient, "cd " + m_sPath + " && " + sCommand), "SHELL");
}
private:
CString m_sPath;
};
void CShellSock::ReadLine(const CString& sData) {
CString sLine = sData;
while (sLine.length() && (sLine[sLine.length() -1] == '\r' || sLine[sLine.length() -1] == '\n')) {
sLine = sLine.substr(0, sLine.length() -1);
}
CString::size_type a = sLine.find('\t');
while (a != CString::npos) {
sLine.replace(a, 1, " ");
a = sLine.find('\t');
}
m_pParent->SetClient(m_pClient);
m_pParent->PutShell(sLine);
m_pParent->SetClient(NULL);
}
void CShellSock::Disconnected() {
m_pParent->SetClient(m_pClient);
m_pParent->PutShell("znc$");
m_pParent->SetClient(NULL);
}
MODULEDEFS(CShellMod, "Gives shell access")
<commit_msg>Shell module: Also read incomplete lines (no trailing newline) and display them<commit_after>/*
* Copyright (C) 2004-2008 See the AUTHORS file for details.
*
* This program is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 as published
* by the Free Software Foundation.
*/
#include "User.h"
#include "znc.h"
// Forward Declaration
class CShellMod;
class CShellSock : public CExecSock {
public:
CShellSock(CShellMod* pShellMod, CClient* pClient, const CString& sExec) : CExecSock( sExec ) {
EnableReadLine();
m_pParent = pShellMod;
m_pClient = pClient;
}
// These next two function's bodies are at the bottom of the file since they reference CShellMod
virtual void ReadLine(const CString& sData);
virtual void Disconnected();
CShellMod* m_pParent;
private:
CClient* m_pClient;
};
class CShellMod : public CModule {
public:
MODCONSTRUCTOR(CShellMod) {
m_sPath = CZNC::Get().GetHomePath();
}
virtual ~CShellMod() {
vector<Csock*> vSocks = m_pManager->FindSocksByName("SHELL");
for (unsigned int a = 0; a < vSocks.size(); a++) {
m_pManager->DelSockByAddr(vSocks[a]);
}
}
virtual bool OnLoad(const CString& sArgs, CString& sMessage)
{
#ifndef MOD_SHELL_ALLOW_EVERYONE
if (!m_pUser->IsAdmin()) {
sMessage = "You must be admin to use the shell module";
return false;
}
#endif
return true;
}
virtual void OnModCommand(const CString& sCommand) {
if ((strcasecmp(sCommand.c_str(), "cd") == 0) || (strncasecmp(sCommand.c_str(), "cd ", 3) == 0)) {
CString sPath = CUtils::ChangeDir(m_sPath, ((sCommand.length() == 2) ? CString(CZNC::Get().GetHomePath()) : CString(sCommand.substr(3))), CZNC::Get().GetHomePath());
CFile Dir(sPath);
if (Dir.IsDir()) {
m_sPath = sPath;
} else if (Dir.Exists()) {
PutShell("cd: not a directory [" + sPath + "]");
} else {
PutShell("cd: no such directory [" + sPath + "]");
}
PutShell("znc$");
} else if (strcasecmp(sCommand.Token(0).c_str(), "SEND") == 0) {
CString sToNick = sCommand.Token(1);
CString sFile = sCommand.Token(2);
if ((sToNick.empty()) || (sFile.empty())) {
PutShell("usage: Send <nick> <file>");
} else {
sFile = CUtils::ChangeDir(m_sPath, sFile, CZNC::Get().GetHomePath());
if (!CFile::Exists(sFile)) {
PutShell("get: no such file [" + sFile + "]");
} else if (!CFile::IsReg(sFile)) {
PutShell("get: not a file [" + sFile + "]");
} else {
m_pUser->SendFile(sToNick, sFile, GetModName());
}
}
} else if (strcasecmp(sCommand.Token(0).c_str(), "GET") == 0) {
CString sFile = sCommand.Token(1);
if (sFile.empty()) {
PutShell("usage: Get <file>");
} else {
sFile = CUtils::ChangeDir(m_sPath, sFile, CZNC::Get().GetHomePath());
if (!CFile::Exists(sFile)) {
PutShell("get: no such file [" + sFile + "]");
} else if (!CFile::IsReg(sFile)) {
PutShell("get: not a file [" + sFile + "]");
} else {
m_pUser->SendFile(m_pUser->GetCurNick(), sFile, GetModName());
}
}
} else {
RunCommand(sCommand);
}
}
virtual EModRet OnStatusCommand(const CString& sCommand) {
if (strcasecmp(sCommand.c_str(), "SHELL") == 0) {
PutShell("-- ZNC Shell Service --");
return HALT;
}
return CONTINUE;
}
virtual EModRet OnDCCUserSend(const CNick& RemoteNick, unsigned long uLongIP, unsigned short uPort, const CString& sFile, unsigned long uFileSize) {
if (strcasecmp(RemoteNick.GetNick().c_str(), CString(GetModNick()).c_str()) == 0) {
CString sLocalFile = CUtils::ChangeDir(m_sPath, sFile, CZNC::Get().GetHomePath());
m_pUser->GetFile(m_pUser->GetCurNick(), CUtils::GetIP(uLongIP), uPort, sLocalFile, uFileSize, GetModName());
return HALT;
}
return CONTINUE;
}
void PutShell(const CString& sLine) {
CString sPath = m_sPath;
CString::size_type a = sPath.find(' ');
while (a != CString::npos) {
sPath.replace(a, 1, "_");
a = sPath.find(' ');
}
PutModule(sLine, m_pUser->GetCurNick(), sPath);
}
void RunCommand(const CString& sCommand) {
m_pManager->AddSock((Csock*) new CShellSock(this, m_pClient, "cd " + m_sPath + " && " + sCommand), "SHELL");
}
private:
CString m_sPath;
};
void CShellSock::ReadLine(const CString& sData) {
CString sLine = sData;
while (sLine.length() && (sLine[sLine.length() -1] == '\r' || sLine[sLine.length() -1] == '\n')) {
sLine = sLine.substr(0, sLine.length() -1);
}
CString::size_type a = sLine.find('\t');
while (a != CString::npos) {
sLine.replace(a, 1, " ");
a = sLine.find('\t');
}
m_pParent->SetClient(m_pClient);
m_pParent->PutShell(sLine);
m_pParent->SetClient(NULL);
}
void CShellSock::Disconnected() {
// If there is some incomplete line in the buffer, read it
// (e.g. echo echo -n "hi" triggered this)
CString &sBuffer = GetInternalBuffer();
if (!sBuffer.empty())
ReadLine(sBuffer);
m_pParent->SetClient(m_pClient);
m_pParent->PutShell("znc$");
m_pParent->SetClient(NULL);
}
MODULEDEFS(CShellMod, "Gives shell access")
<|endoftext|> |
<commit_before>#include <iostream>
#include <cstdlib>
const double FIRST_BRACKET_LENGTH = 18200;
const double SECOND_BRACKET_LENGTH = 18799;
const double THIRD_BRACKET_LENGTH = 42999;
const double FOURTH_BRACKET_LENGTH = 100000;
const double P_FIRST_BRACKET = 1;
const double P_SECOND_BRACKET = 0.81;
const double P_THIRD_BRACKET = 0.675;
const double P_FOURTH_BRACKET = 0.63;
const double P_LAST_BRACKET = 0.55;
double tax_money_in_year(double income){
double money_to_tax = income;
double taxed_money = 0;
// Between $0 - $18201
if(money_to_tax >= 0){
//If under the first bracket, no tax is taken.
if(money_to_tax < FIRST_BRACKET_LENGTH){
return money_to_tax;
}
taxed_money += FIRST_BRACKET_LENGTH * P_FIRST_BRACKET;
money_to_tax -= FIRST_BRACKET_LENGTH;
}
// Between $18,201 - $37,000
if(money_to_tax >= 0){
if(money_to_tax < SECOND_BRACKET_LENGTH){
return taxed_money + (money_to_tax * P_SECOND_BRACKET);
}
taxed_money += SECOND_BRACKET_LENGTH * P_SECOND_BRACKET;
money_to_tax -= SECOND_BRACKET_LENGTH;
}
// Between $37,001 - $80,000
if(money_to_tax >= 0){
if(money_to_tax < THIRD_BRACKET_LENGTH){
return taxed_money + (money_to_tax * P_THIRD_BRACKET);
}
taxed_money += THIRD_BRACKET_LENGTH * P_THIRD_BRACKET;
money_to_tax -= THIRD_BRACKET_LENGTH;
}
// Between $80,001 - $180,000
if(money_to_tax >= 0){
if(money_to_tax < FOURTH_BRACKET_LENGTH){
return taxed_money + (money_to_tax * P_FOURTH_BRACKET);
}
taxed_money += FOURTH_BRACKET_LENGTH * P_FOURTH_BRACKET;
money_to_tax -= FOURTH_BRACKET_LENGTH;
}
// Greater than $180,000
if(money_to_tax >= 0){
taxed_money += money_to_tax * P_LAST_BRACKET;
money_to_tax = 0;
}
return taxed_money;
}
int main(int argc, char* argv[]){
if(argc != 4){
std::cerr << "Usage: <y,m,w>(input) <dollars earned> <y,m,w>(output)" << std::endl;
return 1;
}
const double user_input_wage = atof(argv[2]);
double taxed_money_years;
//Convers it to yearly for storage
switch(*argv[1]){
case 'y': taxed_money_years = tax_money_in_year(user_input_wage); break;
case 'm': taxed_money_years = tax_money_in_year(user_input_wage * 12); break;
case 'w': taxed_money_years = tax_money_in_year(user_input_wage * 52); break;
}
//Simply divides it back out.
switch(*argv[3]){
case 'y': std::cout << "Yearly earnings after tax is $" << taxed_money_years / 1.0 << std::endl; break;
case 'm': std::cout << "Monthly earnings after tax is $" << taxed_money_years / 12.0 << std::endl; break;
case 'w': std::cout << "Weekly earnings after tax is $" << taxed_money_years / 52.0 << std::endl; break;
}
switch(*argv[3]){
case 'y': std::cout << "You lose $" << (user_input_wage ) - (taxed_money_years / 1.0) << " per year to the tax man" << std::endl; break;
case 'm': std::cout << "You lose $" << (user_input_wage ) - (taxed_money_years / 12.0) << " per month to the tax man" << std::endl; break;
case 'w': std::cout << "You lose $" << (user_input_wage ) - (taxed_money_years / 52.0) << " per week to the tax man" << std::endl; break;
}
std::cout << "Done by Dale Salter(Note the estimates only work if the input and output are the same)" << std::endl;
return 0;
}<commit_msg>CHANGE FOR VCS<commit_after>#include <iostream>
#include <cstdlib>
const double FIRST_BRACKET_LENGTH = 18200;
const double SECOND_BRACKET_LENGTH = 18799;
const double THIRD_BRACKET_LENGTH = 42999;
const double FOURTH_BRACKET_LENGTH = 100000;
const double P_FIRST_BRACKET = 1;
const double P_SECOND_BRACKET = 0.81;
const double P_THIRD_BRACKET = 0.675;
const double P_FOURTH_BRACKET = 0.63;
const double P_LAST_BRACKET = 0.55;
double tax_money_in_year(double income){
double money_to_tax = income;
double taxed_money = 0;
// Between $0 - $18201
if(money_to_tax >= 0){
//If under the first bracket, no tax is taken.
if(money_to_tax < FIRST_BRACKET_LENGTH){
return money_to_tax;
}
taxed_money += FIRST_BRACKET_LENGTH * P_FIRST_BRACKET;
money_to_tax -= FIRST_BRACKET_LENGTH;
}
// Between $18,201 - $37,000
if(money_to_tax >= 0){
if(money_to_tax < SECOND_BRACKET_LENGTH){
return taxed_money + (money_to_tax * P_SECOND_BRACKET);
}
taxed_money += SECOND_BRACKET_LENGTH * P_SECOND_BRACKET;
money_to_tax -= SECOND_BRACKET_LENGTH;
}
// Between $37,001 - $80,000
if(money_to_tax >= 0){
if(money_to_tax < THIRD_BRACKET_LENGTH){
return taxed_money + (money_to_tax * P_THIRD_BRACKET);
}
taxed_money += THIRD_BRACKET_LENGTH * P_THIRD_BRACKET;
money_to_tax -= THIRD_BRACKET_LENGTH;
}
// Between $80,001 - $180,000
if(money_to_tax >= 0){
if(money_to_tax < FOURTH_BRACKET_LENGTH){
return taxed_money + (money_to_tax * P_FOURTH_BRACKET);
}
taxed_money += FOURTH_BRACKET_LENGTH * P_FOURTH_BRACKET;
money_to_tax -= FOURTH_BRACKET_LENGTH;
}
// Greater than $180,000
if(money_to_tax >= 0){
taxed_money += money_to_tax * P_LAST_BRACKET;
money_to_tax = 0;
}
return taxed_money;
}
int main(int argc, char* argv[]){
if(argc != 4){
std::cerr << "Usage: <y,m,w>(input) <dollars earned> <y,m,w>(output)" << std::endl;
return 1;
}
const double user_input_wage = atof(argv[2]);
double taxed_money_years;
//Convers it to yearly for storage
switch(*argv[1]){
case 'y': taxed_money_years = tax_money_in_year(user_input_wage); break;
case 'm': taxed_money_years = tax_money_in_year(user_input_wage * 12); break;
case 'w': taxed_money_years = tax_money_in_year(user_input_wage * 52); break;
}
//Simply divides it back out.
switch(*argv[3]){
case 'y': std::cout << "Yearly earnings after tax is $" << taxed_money_years / 1.0 << std::endl; break;
case 'm': std::cout << "Monthly earnings after tax is $" << taxed_money_years / 12.0 << std::endl; break;
case 'w': std::cout << "Weekly earnings after tax is $" << taxed_money_years / 52.0 << std::endl; break;
}
switch(*argv[3]){
case 'y': std::cout << "You lose $" << (user_input_wage ) - (taxed_money_years / 1.0) << " per year to the tax man" << std::endl; break;
case 'm': std::cout << "You lose $" << (user_input_wage ) - (taxed_money_years / 12.0) << " per month to the tax man" << std::endl; break;
case 'w': std::cout << "You lose $" << (user_input_wage ) - (taxed_money_years / 52.0) << " per week to the tax man" << std::endl; break;
}
std::cout << "Done by Dale Salter(the input and output y/m/w have to be the same)" << std::endl;
return 0;
}
<|endoftext|> |
<commit_before>/******************************************************************************
* Copyright (c) 2014 Jamis Hoo
* Distributed under the MIT license
* (See accompanying file LICENSE or copy at http://opensource.org/licenses/MIT)
*
* Project:
* Filename: test.cc
* Version: 1.0
* Author: Jamis Hoo
* E-mail: hjm211324@gmail.com
* Date: Dec. 29, 2014
* Time: 11:10:09
* Description:
*****************************************************************************/
#include <iostream>
int main() {
std::cout << "Hello world!" << std::endl;
}
<commit_msg>--allow-empty_message<commit_after>/******************************************************************************
* Copyright (c) 2014 Jamis Hoo
* Distributed under the MIT license
* (See accompanying file LICENSE or copy at http://opensource.org/licenses/MIT)
*
* Project:
* Filename: test.cc
* Version: 1.0
* Author: Jamis Hoo
* E-mail: hjm211324@gmail.com
* Date: Dec. 29, 2014
* Time: 11:10:09
* Description:
*****************************************************************************/
#include <iostream>
int main() {
std::cout << "Hello world!" << std::endl;
}
<|endoftext|> |
<commit_before><commit_msg>planning: do not check traffic light color while creeping on right turn<commit_after><|endoftext|> |
<commit_before>
#include <locale>
#include <vector>
#include <stdlib.h>
#ifdef __APPLE__
#include <TargetConditionals.h>
#endif //
#include <lemon/fs/fs.hpp>
#include <lemon/strings.hpp>
#include <lemon/os/sysinfo.hpp>
namespace lemon { namespace os {
typedef std::wstring_convert<std::codecvt<wchar_t, char, std::mbstate_t>, wchar_t> convert;
host_t hostname()
{
#ifdef WIN32
return host_t::Windows;
#elif defined(__linux)
#ifdef __android
return host_t::Android;
#else
return host_t::Linux;
#endif
#elif defined(__sun)
return host_t::Solaris;
#elif defined(__hppa)
return host_t::HPUX;
#elif defined(_AIX)
return host_t::AIX;
#elif defined(__APPLE__)
#if TARGET_OS_SIMULATOR == 1
return host_t::iOS_Simulator;
#elif TARGET_OS_IPHONE == 1
return host_t::iOS;
#elif TARGET_OS_MAC == 1
return host_t::OSX;
#else
return host_t::OSX_Unknown;
#endif
#endif //WIN32
}
arch_t arch()
{
#if defined(__alpha__) || defined(_M_ALPHA) || defined(__alpha)
return arch_t::Alpha;
#elif defined(__amd64__) || defined(__amd64) || defined(_M_X64)
return arch_t::AMD64;
#elif defined(__arm__) || defined(_ARM) || defined(_M_ARM) || defined(_M_ARMT) || defined(__arm)
return arch_t::ARM;
#elif defined(__aarch64__) || defined(__arm64__)
return arch_t::ARM64;
#elif defined(__hppa__) || defined(__HPPA__)
return arch_t::HP_PA;
#elif defined(__i386__) || defined(__i386) || defined(__i386) || defined(_M_IX86) || defined(_X86_)
return arch_t::X86;
#elif defined(__mips__) || defined(__mips)
return arch_t::MIPS;
#elif defined(__powerpc) || defined(_M_PPC) || defined(_ARCH_PPC64) || defined(_ARCH_PPC)
return arch_t::PowerPC;
#elif defined(__sparc__)
return arch_t::SPARC;
#endif
}
#ifdef WIN32
std::tuple<std::string, bool> getenv(const std::string &name)
{
auto namew = convert().from_bytes(name);
DWORD length = ::GetEnvironmentVariableW(namew.c_str(), NULL, 0);
if(length == 0)
{
return std::make_tuple(std::string(), false);
}
std::vector<wchar_t> buff(length);
::GetEnvironmentVariableW(namew.c_str(), &buff[0], (DWORD)buff.size());
return std::make_tuple(convert().to_bytes(&buff[0]), true);
}
void setenv(const std::string &name, const std::string &val,std::error_code &ec)
{
auto namew = convert().from_bytes(name);
auto valnew = convert().from_bytes(val);
if (!::SetEnvironmentVariableW(namew.c_str(), valnew.c_str()))
{
ec = std::error_code(GetLastError(),std::system_category());
}
}
#else
std::tuple<std::string,bool> getenv(const std::string &name)
{
const char *val = ::getenv(name.c_str());
if(val)
{
return std::make_tuple(std::string(val),true);
}
return std::make_tuple(std::string(), false);
}
void setenv(const std::string &name, const std::string &val, std::error_code &ec)
{
if (-1 == setenv(name.c_str(), val.c_str(), 1))
{
ec = std::make_error_code(errno, std::system_category());
}
}
#endif //WIN32
std::string execute_suffix()
{
#ifdef WIN32
return ".exe";
#else
return "";
#endif
}
#ifndef WIN32
std::string tmpdir(std::error_code & )
{
auto val = getenv("TMPDIR");
if(std::get<1>(val))
{
return std::get<0>(val);
}
#ifdef __android
return "/data/local/tmp";
#endif
return "/tmp";
}
#else
std::string tmpdir(std::error_code & err)
{
wchar_t buff[MAX_PATH + 1];
auto length = ::GetTempPathW(MAX_PATH, buff);
if(length == 0)
{
err = std::error_code(GetLastError(),std::system_category());
return "";
}
return convert().to_bytes(std::wstring(buff, buff + length));
}
#endif
std::tuple<std::string, bool> lookup(const std::string & cmd)
{
if(fs::exists(cmd))
{
return std::make_tuple(fs::absolute(cmd).string(), true);
}
auto path = os::getenv("PATH");
if(!std::get<1>(path))
{
return std::make_tuple(std::string(),false);
}
#ifdef WIN32
const std::string delimiter = ";";
const std::string extend = ".exe";
#else
const std::string delimiter = ":";
const std::string extend = "";
#endif //WIN32
auto paths = strings::split(std::get<0>(path), delimiter);
#ifdef WIN32
DWORD length = ::GetSystemDirectoryW(0, 0);
std::vector<wchar_t> buff(length);
::GetSystemDirectoryW(&buff[0], (UINT)buff.size());
paths.push_back(convert().to_bytes(&buff[0]));
#else
#endif
for(auto p : paths)
{
auto fullPath = fs::filepath(p) / (cmd + extend);
if(fs::exists(fullPath))
{
return std::make_tuple(fullPath.string(), true);
}
}
return std::make_tuple(std::string(), false);
}
}}<commit_msg>fix some bugs<commit_after>
#include <locale>
#include <vector>
#include <stdlib.h>
#ifdef __APPLE__
#include <TargetConditionals.h>
#endif //
#include <lemon/fs/fs.hpp>
#include <lemon/strings.hpp>
#include <lemon/os/sysinfo.hpp>
namespace lemon { namespace os {
typedef std::wstring_convert<std::codecvt<wchar_t, char, std::mbstate_t>, wchar_t> convert;
host_t hostname()
{
#ifdef WIN32
return host_t::Windows;
#elif defined(__linux)
#ifdef __android
return host_t::Android;
#else
return host_t::Linux;
#endif
#elif defined(__sun)
return host_t::Solaris;
#elif defined(__hppa)
return host_t::HPUX;
#elif defined(_AIX)
return host_t::AIX;
#elif defined(__APPLE__)
#if TARGET_OS_SIMULATOR == 1
return host_t::iOS_Simulator;
#elif TARGET_OS_IPHONE == 1
return host_t::iOS;
#elif TARGET_OS_MAC == 1
return host_t::OSX;
#else
return host_t::OSX_Unknown;
#endif
#endif //WIN32
}
arch_t arch()
{
#if defined(__alpha__) || defined(_M_ALPHA) || defined(__alpha)
return arch_t::Alpha;
#elif defined(__amd64__) || defined(__amd64) || defined(_M_X64)
return arch_t::AMD64;
#elif defined(__arm__) || defined(_ARM) || defined(_M_ARM) || defined(_M_ARMT) || defined(__arm)
return arch_t::ARM;
#elif defined(__aarch64__) || defined(__arm64__)
return arch_t::ARM64;
#elif defined(__hppa__) || defined(__HPPA__)
return arch_t::HP_PA;
#elif defined(__i386__) || defined(__i386) || defined(__i386) || defined(_M_IX86) || defined(_X86_)
return arch_t::X86;
#elif defined(__mips__) || defined(__mips)
return arch_t::MIPS;
#elif defined(__powerpc) || defined(_M_PPC) || defined(_ARCH_PPC64) || defined(_ARCH_PPC)
return arch_t::PowerPC;
#elif defined(__sparc__)
return arch_t::SPARC;
#endif
}
#ifdef WIN32
std::tuple<std::string, bool> getenv(const std::string &name)
{
auto namew = convert().from_bytes(name);
DWORD length = ::GetEnvironmentVariableW(namew.c_str(), NULL, 0);
if(length == 0)
{
return std::make_tuple(std::string(), false);
}
std::vector<wchar_t> buff(length);
::GetEnvironmentVariableW(namew.c_str(), &buff[0], (DWORD)buff.size());
return std::make_tuple(convert().to_bytes(&buff[0]), true);
}
void setenv(const std::string &name, const std::string &val,std::error_code &ec)
{
auto namew = convert().from_bytes(name);
auto valnew = convert().from_bytes(val);
if (!::SetEnvironmentVariableW(namew.c_str(), valnew.c_str()))
{
ec = std::error_code(GetLastError(),std::system_category());
}
}
#else
std::tuple<std::string,bool> getenv(const std::string &name)
{
const char *val = ::getenv(name.c_str());
if(val)
{
return std::make_tuple(std::string(val),true);
}
return std::make_tuple(std::string(), false);
}
void setenv(const std::string &name, const std::string &val, std::error_code &ec)
{
if (-1 == setenv(name.c_str(), val.c_str(), 1))
{
ec = std::make_error_code(errno, std::system_category());
}
}
#endif //WIN32
std::string execute_suffix()
{
#ifdef WIN32
return ".exe";
#else
return "";
#endif
}
#ifndef WIN32
std::string tmpdir(std::error_code & )
{
auto val = getenv("TMPDIR");
if(std::get<1>(val))
{
return std::get<0>(val);
}
#ifdef __android
return "/data/local/tmp";
#endif
return "/tmp";
}
#else
std::string tmpdir(std::error_code & err)
{
wchar_t buff[MAX_PATH + 1];
auto length = ::GetTempPathW(MAX_PATH, buff);
if(length == 0)
{
err = std::error_code(GetLastError(),std::system_category());
return "";
}
return convert().to_bytes(std::wstring(buff, buff + length));
}
#endif
std::tuple<std::string, bool> lookup(const std::string & cmd)
{
if(fs::exists(cmd))
{
return std::make_tuple(fs::absolute(cmd).string(), true);
}
auto path = os::getenv("PATH");
if(!std::get<1>(path))
{
return std::make_tuple(std::string(),false);
}
#ifdef WIN32
const std::string delimiter = ";";
const std::vector<std::string> extends = { ".exe",".cmd",".bat",".com" };
#else
const std::string delimiter = ":";
const std::vector<std::string> extends = { "" };
#endif //WIN32
auto paths = strings::split(std::get<0>(path), delimiter);
#ifdef WIN32
DWORD length = ::GetSystemDirectoryW(0, 0);
std::vector<wchar_t> buff(length);
::GetSystemDirectoryW(&buff[0], (UINT)buff.size());
paths.push_back(convert().to_bytes(&buff[0]));
#else
#endif
for(auto p : paths)
{
for (auto extend : extends)
{
auto fullPath = fs::filepath(p) / (cmd + extend);
if (fs::exists(fullPath))
{
return std::make_tuple(fullPath.string(), true);
}
}
}
return std::make_tuple(std::string(), false);
}
}}<|endoftext|> |
<commit_before>//===-- Writer.cpp - Library for writing LLVM bytecode files --------------===//
//
// The LLVM Compiler Infrastructure
//
// This file was developed by the LLVM research group and is distributed under
// the University of Illinois Open Source License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
//
// This library implements the functionality defined in llvm/Bytecode/Writer.h
//
// Note that this file uses an unusual technique of outputting all the bytecode
// to a deque of unsigned char, then copies the deque to an ostream. The
// reason for this is that we must do "seeking" in the stream to do back-
// patching, and some very important ostreams that we want to support (like
// pipes) do not support seeking. :( :( :(
//
// The choice of the deque data structure is influenced by the extremely fast
// "append" speed, plus the free "seek"/replace in the middle of the stream. I
// didn't use a vector because the stream could end up very large and copying
// the whole thing to reallocate would be kinda silly.
//
//===----------------------------------------------------------------------===//
#include "WriterInternals.h"
#include "llvm/Bytecode/WriteBytecodePass.h"
#include "llvm/Constants.h"
#include "llvm/DerivedTypes.h"
#include "llvm/Module.h"
#include "llvm/SymbolTable.h"
#include "Support/STLExtras.h"
#include "Support/Statistic.h"
#include <cstring>
#include <algorithm>
using namespace llvm;
static RegisterPass<WriteBytecodePass> X("emitbytecode", "Bytecode Writer");
static Statistic<>
BytesWritten("bytecodewriter", "Number of bytecode bytes written");
BytecodeWriter::BytecodeWriter(std::deque<unsigned char> &o, const Module *M)
: Out(o), Table(M, true) {
// Emit the signature...
static const unsigned char *Sig = (const unsigned char*)"llvm";
output_data(Sig, Sig+4, Out);
// Emit the top level CLASS block.
BytecodeBlock ModuleBlock(BytecodeFormat::Module, Out);
bool isBigEndian = M->getEndianness() == Module::BigEndian;
bool hasLongPointers = M->getPointerSize() == Module::Pointer64;
bool hasNoEndianness = M->getEndianness() == Module::AnyEndianness;
bool hasNoPointerSize = M->getPointerSize() == Module::AnyPointerSize;
// Output the version identifier... we are currently on bytecode version #2,
// which corresponds to LLVM v1.3.
unsigned Version = (2 << 4) | isBigEndian | (hasLongPointers << 1) |
(hasNoEndianness << 2) | (hasNoPointerSize << 3);
output_vbr(Version, Out);
align32(Out);
{
BytecodeBlock CPool(BytecodeFormat::GlobalTypePlane, Out);
// Write the type plane for types first because earlier planes (e.g. for a
// primitive type like float) may have constants constructed using types
// coming later (e.g., via getelementptr from a pointer type). The type
// plane is needed before types can be fwd or bkwd referenced.
const std::vector<const Value*> &Plane = Table.getPlane(Type::TypeTyID);
assert(!Plane.empty() && "No types at all?");
unsigned ValNo = Type::FirstDerivedTyID; // Start at the derived types...
outputConstantsInPlane(Plane, ValNo); // Write out the types
}
// The ModuleInfoBlock follows directly after the type information
outputModuleInfoBlock(M);
// Output module level constants, used for global variable initializers
outputConstants(false);
// Do the whole module now! Process each function at a time...
for (Module::const_iterator I = M->begin(), E = M->end(); I != E; ++I)
outputFunction(I);
// If needed, output the symbol table for the module...
outputSymbolTable(M->getSymbolTable());
}
// Helper function for outputConstants().
// Writes out all the constants in the plane Plane starting at entry StartNo.
//
void BytecodeWriter::outputConstantsInPlane(const std::vector<const Value*>
&Plane, unsigned StartNo) {
unsigned ValNo = StartNo;
// Scan through and ignore function arguments, global values, and constant
// strings.
for (; ValNo < Plane.size() &&
(isa<Argument>(Plane[ValNo]) || isa<GlobalValue>(Plane[ValNo]) ||
(isa<ConstantArray>(Plane[ValNo]) &&
cast<ConstantArray>(Plane[ValNo])->isString())); ValNo++)
/*empty*/;
unsigned NC = ValNo; // Number of constants
for (; NC < Plane.size() &&
(isa<Constant>(Plane[NC]) || isa<Type>(Plane[NC])); NC++)
/*empty*/;
NC -= ValNo; // Convert from index into count
if (NC == 0) return; // Skip empty type planes...
// FIXME: Most slabs only have 1 or 2 entries! We should encode this much
// more compactly.
// Output type header: [num entries][type id number]
//
output_vbr(NC, Out);
// Output the Type ID Number...
int Slot = Table.getSlot(Plane.front()->getType());
assert (Slot != -1 && "Type in constant pool but not in function!!");
output_vbr((unsigned)Slot, Out);
//cerr << "Emitting " << NC << " constants of type '"
// << Plane.front()->getType()->getName() << "' = Slot #" << Slot << "\n";
for (unsigned i = ValNo; i < ValNo+NC; ++i) {
const Value *V = Plane[i];
if (const Constant *CPV = dyn_cast<Constant>(V)) {
//cerr << "Serializing value: <" << V->getType() << ">: " << V << ":"
// << Out.size() << "\n";
outputConstant(CPV);
} else {
outputType(cast<Type>(V));
}
}
}
static inline bool hasNullValue(unsigned TyID) {
return TyID != Type::LabelTyID && TyID != Type::TypeTyID &&
TyID != Type::VoidTyID;
}
void BytecodeWriter::outputConstants(bool isFunction) {
BytecodeBlock CPool(BytecodeFormat::ConstantPool, Out,
true /* Elide block if empty */);
unsigned NumPlanes = Table.getNumPlanes();
// Output the type plane before any constants!
if (isFunction && NumPlanes > Type::TypeTyID) {
const std::vector<const Value*> &Plane = Table.getPlane(Type::TypeTyID);
if (!Plane.empty()) { // Skip empty type planes...
unsigned ValNo = Table.getModuleLevel(Type::TypeTyID);
outputConstantsInPlane(Plane, ValNo);
}
}
// Output module-level string constants before any other constants.x
if (!isFunction)
outputConstantStrings();
for (unsigned pno = 0; pno != NumPlanes; pno++)
if (pno != Type::TypeTyID) { // Type plane handled above.
const std::vector<const Value*> &Plane = Table.getPlane(pno);
if (!Plane.empty()) { // Skip empty type planes...
unsigned ValNo = 0;
if (isFunction) // Don't re-emit module constants
ValNo += Table.getModuleLevel(pno);
if (hasNullValue(pno)) {
// Skip zero initializer
if (ValNo == 0)
ValNo = 1;
}
// Write out constants in the plane
outputConstantsInPlane(Plane, ValNo);
}
}
}
static unsigned getEncodedLinkage(const GlobalValue *GV) {
switch (GV->getLinkage()) {
default: assert(0 && "Invalid linkage!");
case GlobalValue::ExternalLinkage: return 0;
case GlobalValue::WeakLinkage: return 1;
case GlobalValue::AppendingLinkage: return 2;
case GlobalValue::InternalLinkage: return 3;
case GlobalValue::LinkOnceLinkage: return 4;
}
}
void BytecodeWriter::outputModuleInfoBlock(const Module *M) {
BytecodeBlock ModuleInfoBlock(BytecodeFormat::ModuleGlobalInfo, Out);
// Output the types for the global variables in the module...
for (Module::const_giterator I = M->gbegin(), End = M->gend(); I != End;++I) {
int Slot = Table.getSlot(I->getType());
assert(Slot != -1 && "Module global vars is broken!");
// Fields: bit0 = isConstant, bit1 = hasInitializer, bit2-4=Linkage,
// bit5+ = Slot # for type
unsigned oSlot = ((unsigned)Slot << 5) | (getEncodedLinkage(I) << 2) |
(I->hasInitializer() << 1) | I->isConstant();
output_vbr(oSlot, Out);
// If we have an initializer, output it now.
if (I->hasInitializer()) {
Slot = Table.getSlot((Value*)I->getInitializer());
assert(Slot != -1 && "No slot for global var initializer!");
output_vbr((unsigned)Slot, Out);
}
}
output_vbr((unsigned)Table.getSlot(Type::VoidTy), Out);
// Output the types of the functions in this module...
for (Module::const_iterator I = M->begin(), End = M->end(); I != End; ++I) {
int Slot = Table.getSlot(I->getType());
assert(Slot != -1 && "Module const pool is broken!");
assert(Slot >= Type::FirstDerivedTyID && "Derived type not in range!");
output_vbr((unsigned)Slot, Out);
}
output_vbr((unsigned)Table.getSlot(Type::VoidTy), Out);
}
void BytecodeWriter::outputInstructions(const Function *F) {
BytecodeBlock ILBlock(BytecodeFormat::InstructionList, Out);
for (Function::const_iterator BB = F->begin(), E = F->end(); BB != E; ++BB)
for (BasicBlock::const_iterator I = BB->begin(), E = BB->end(); I!=E; ++I)
outputInstruction(*I);
}
void BytecodeWriter::outputFunction(const Function *F) {
BytecodeBlock FunctionBlock(BytecodeFormat::Function, Out);
output_vbr(getEncodedLinkage(F), Out);
// If this is an external function, there is nothing else to emit!
if (F->isExternal()) return;
// Get slot information about the function...
Table.incorporateFunction(F);
if (Table.getCompactionTable().empty()) {
// Output information about the constants in the function if the compaction
// table is not being used.
outputConstants(true);
} else {
// Otherwise, emit the compaction table.
outputCompactionTable();
}
// Output all of the instructions in the body of the function
outputInstructions(F);
// If needed, output the symbol table for the function...
outputSymbolTable(F->getSymbolTable());
Table.purgeFunction();
}
void BytecodeWriter::outputCompactionTablePlane(unsigned PlaneNo,
const std::vector<const Value*> &Plane,
unsigned StartNo) {
unsigned End = Table.getModuleLevel(PlaneNo);
if (Plane.empty() || StartNo == End || End == 0) return; // Nothing to emit
assert(StartNo < End && "Cannot emit negative range!");
assert(StartNo < Plane.size() && End <= Plane.size());
// Do not emit the null initializer!
if (PlaneNo != Type::TypeTyID) ++StartNo;
// Figure out which encoding to use. By far the most common case we have is
// to emit 0-2 entries in a compaction table plane.
switch (End-StartNo) {
case 0: // Avoid emitting two vbr's if possible.
case 1:
case 2:
output_vbr((PlaneNo << 2) | End-StartNo, Out);
break;
default:
// Output the number of things.
output_vbr((unsigned(End-StartNo) << 2) | 3, Out);
output_vbr(PlaneNo, Out); // Emit the type plane this is
break;
}
for (unsigned i = StartNo; i != End; ++i)
output_vbr(Table.getGlobalSlot(Plane[i]), Out);
}
void BytecodeWriter::outputCompactionTable() {
BytecodeBlock CTB(BytecodeFormat::CompactionTable, Out, true/*ElideIfEmpty*/);
const std::vector<std::vector<const Value*> > &CT =Table.getCompactionTable();
// First thing is first, emit the type compaction table if there is one.
if (CT.size() > Type::TypeTyID)
outputCompactionTablePlane(Type::TypeTyID, CT[Type::TypeTyID],
Type::FirstDerivedTyID);
for (unsigned i = 0, e = CT.size(); i != e; ++i)
if (i != Type::TypeTyID)
outputCompactionTablePlane(i, CT[i], 0);
}
void BytecodeWriter::outputSymbolTable(const SymbolTable &MST) {
// Do not output the Bytecode block for an empty symbol table, it just wastes
// space!
if (MST.begin() == MST.end()) return;
BytecodeBlock SymTabBlock(BytecodeFormat::SymbolTable, Out,
true/* ElideIfEmpty*/);
for (SymbolTable::const_iterator TI = MST.begin(); TI != MST.end(); ++TI) {
SymbolTable::type_const_iterator I = MST.type_begin(TI->first);
SymbolTable::type_const_iterator End = MST.type_end(TI->first);
int Slot;
if (I == End) continue; // Don't mess with an absent type...
// Symtab block header: [num entries][type id number]
output_vbr(MST.type_size(TI->first), Out);
Slot = Table.getSlot(TI->first);
assert(Slot != -1 && "Type in symtab, but not in table!");
output_vbr((unsigned)Slot, Out);
for (; I != End; ++I) {
// Symtab entry: [def slot #][name]
const Value *V = I->second;
Slot = Table.getSlot(I->second);
assert(Slot != -1 && "Value in symtab but has no slot number!!");
output_vbr((unsigned)Slot, Out);
output(I->first, Out, false); // Don't force alignment...
}
}
}
void llvm::WriteBytecodeToFile(const Module *C, std::ostream &Out) {
assert(C && "You can't write a null module!!");
std::deque<unsigned char> Buffer;
// This object populates buffer for us...
BytecodeWriter BCW(Buffer, C);
// Keep track of how much we've written...
BytesWritten += Buffer.size();
// Okay, write the deque out to the ostream now... the deque is not
// sequential in memory, however, so write out as much as possible in big
// chunks, until we're done.
//
std::deque<unsigned char>::const_iterator I = Buffer.begin(),E = Buffer.end();
while (I != E) { // Loop until it's all written
// Scan to see how big this chunk is...
const unsigned char *ChunkPtr = &*I;
const unsigned char *LastPtr = ChunkPtr;
while (I != E) {
const unsigned char *ThisPtr = &*++I;
if (LastPtr+1 != ThisPtr) { // Advanced by more than a byte of memory?
++LastPtr;
break;
}
LastPtr = ThisPtr;
}
// Write out the chunk...
Out.write((char*)ChunkPtr, LastPtr-ChunkPtr);
}
Out.flush();
}
<commit_msg>Changed to use SymbolTable's new iteration interfaces.<commit_after>//===-- Writer.cpp - Library for writing LLVM bytecode files --------------===//
//
// The LLVM Compiler Infrastructure
//
// This file was developed by the LLVM research group and is distributed under
// the University of Illinois Open Source License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
//
// This library implements the functionality defined in llvm/Bytecode/Writer.h
//
// Note that this file uses an unusual technique of outputting all the bytecode
// to a deque of unsigned char, then copies the deque to an ostream. The
// reason for this is that we must do "seeking" in the stream to do back-
// patching, and some very important ostreams that we want to support (like
// pipes) do not support seeking. :( :( :(
//
// The choice of the deque data structure is influenced by the extremely fast
// "append" speed, plus the free "seek"/replace in the middle of the stream. I
// didn't use a vector because the stream could end up very large and copying
// the whole thing to reallocate would be kinda silly.
//
//===----------------------------------------------------------------------===//
#include "WriterInternals.h"
#include "llvm/Bytecode/WriteBytecodePass.h"
#include "llvm/Constants.h"
#include "llvm/DerivedTypes.h"
#include "llvm/Module.h"
#include "llvm/SymbolTable.h"
#include "Support/STLExtras.h"
#include "Support/Statistic.h"
#include <cstring>
#include <algorithm>
using namespace llvm;
static RegisterPass<WriteBytecodePass> X("emitbytecode", "Bytecode Writer");
static Statistic<>
BytesWritten("bytecodewriter", "Number of bytecode bytes written");
BytecodeWriter::BytecodeWriter(std::deque<unsigned char> &o, const Module *M)
: Out(o), Table(M, true) {
// Emit the signature...
static const unsigned char *Sig = (const unsigned char*)"llvm";
output_data(Sig, Sig+4, Out);
// Emit the top level CLASS block.
BytecodeBlock ModuleBlock(BytecodeFormat::Module, Out);
bool isBigEndian = M->getEndianness() == Module::BigEndian;
bool hasLongPointers = M->getPointerSize() == Module::Pointer64;
bool hasNoEndianness = M->getEndianness() == Module::AnyEndianness;
bool hasNoPointerSize = M->getPointerSize() == Module::AnyPointerSize;
// Output the version identifier... we are currently on bytecode version #2,
// which corresponds to LLVM v1.3.
unsigned Version = (2 << 4) | isBigEndian | (hasLongPointers << 1) |
(hasNoEndianness << 2) | (hasNoPointerSize << 3);
output_vbr(Version, Out);
align32(Out);
{
BytecodeBlock CPool(BytecodeFormat::GlobalTypePlane, Out);
// Write the type plane for types first because earlier planes (e.g. for a
// primitive type like float) may have constants constructed using types
// coming later (e.g., via getelementptr from a pointer type). The type
// plane is needed before types can be fwd or bkwd referenced.
const std::vector<const Value*> &Plane = Table.getPlane(Type::TypeTyID);
assert(!Plane.empty() && "No types at all?");
unsigned ValNo = Type::FirstDerivedTyID; // Start at the derived types...
outputConstantsInPlane(Plane, ValNo); // Write out the types
}
// The ModuleInfoBlock follows directly after the type information
outputModuleInfoBlock(M);
// Output module level constants, used for global variable initializers
outputConstants(false);
// Do the whole module now! Process each function at a time...
for (Module::const_iterator I = M->begin(), E = M->end(); I != E; ++I)
outputFunction(I);
// If needed, output the symbol table for the module...
outputSymbolTable(M->getSymbolTable());
}
// Helper function for outputConstants().
// Writes out all the constants in the plane Plane starting at entry StartNo.
//
void BytecodeWriter::outputConstantsInPlane(const std::vector<const Value*>
&Plane, unsigned StartNo) {
unsigned ValNo = StartNo;
// Scan through and ignore function arguments, global values, and constant
// strings.
for (; ValNo < Plane.size() &&
(isa<Argument>(Plane[ValNo]) || isa<GlobalValue>(Plane[ValNo]) ||
(isa<ConstantArray>(Plane[ValNo]) &&
cast<ConstantArray>(Plane[ValNo])->isString())); ValNo++)
/*empty*/;
unsigned NC = ValNo; // Number of constants
for (; NC < Plane.size() &&
(isa<Constant>(Plane[NC]) || isa<Type>(Plane[NC])); NC++)
/*empty*/;
NC -= ValNo; // Convert from index into count
if (NC == 0) return; // Skip empty type planes...
// FIXME: Most slabs only have 1 or 2 entries! We should encode this much
// more compactly.
// Output type header: [num entries][type id number]
//
output_vbr(NC, Out);
// Output the Type ID Number...
int Slot = Table.getSlot(Plane.front()->getType());
assert (Slot != -1 && "Type in constant pool but not in function!!");
output_vbr((unsigned)Slot, Out);
//cerr << "Emitting " << NC << " constants of type '"
// << Plane.front()->getType()->getName() << "' = Slot #" << Slot << "\n";
for (unsigned i = ValNo; i < ValNo+NC; ++i) {
const Value *V = Plane[i];
if (const Constant *CPV = dyn_cast<Constant>(V)) {
//cerr << "Serializing value: <" << V->getType() << ">: " << V << ":"
// << Out.size() << "\n";
outputConstant(CPV);
} else {
outputType(cast<Type>(V));
}
}
}
static inline bool hasNullValue(unsigned TyID) {
return TyID != Type::LabelTyID && TyID != Type::TypeTyID &&
TyID != Type::VoidTyID;
}
void BytecodeWriter::outputConstants(bool isFunction) {
BytecodeBlock CPool(BytecodeFormat::ConstantPool, Out,
true /* Elide block if empty */);
unsigned NumPlanes = Table.getNumPlanes();
// Output the type plane before any constants!
if (isFunction && NumPlanes > Type::TypeTyID) {
const std::vector<const Value*> &Plane = Table.getPlane(Type::TypeTyID);
if (!Plane.empty()) { // Skip empty type planes...
unsigned ValNo = Table.getModuleLevel(Type::TypeTyID);
outputConstantsInPlane(Plane, ValNo);
}
}
// Output module-level string constants before any other constants.x
if (!isFunction)
outputConstantStrings();
for (unsigned pno = 0; pno != NumPlanes; pno++)
if (pno != Type::TypeTyID) { // Type plane handled above.
const std::vector<const Value*> &Plane = Table.getPlane(pno);
if (!Plane.empty()) { // Skip empty type planes...
unsigned ValNo = 0;
if (isFunction) // Don't re-emit module constants
ValNo += Table.getModuleLevel(pno);
if (hasNullValue(pno)) {
// Skip zero initializer
if (ValNo == 0)
ValNo = 1;
}
// Write out constants in the plane
outputConstantsInPlane(Plane, ValNo);
}
}
}
static unsigned getEncodedLinkage(const GlobalValue *GV) {
switch (GV->getLinkage()) {
default: assert(0 && "Invalid linkage!");
case GlobalValue::ExternalLinkage: return 0;
case GlobalValue::WeakLinkage: return 1;
case GlobalValue::AppendingLinkage: return 2;
case GlobalValue::InternalLinkage: return 3;
case GlobalValue::LinkOnceLinkage: return 4;
}
}
void BytecodeWriter::outputModuleInfoBlock(const Module *M) {
BytecodeBlock ModuleInfoBlock(BytecodeFormat::ModuleGlobalInfo, Out);
// Output the types for the global variables in the module...
for (Module::const_giterator I = M->gbegin(), End = M->gend(); I != End;++I) {
int Slot = Table.getSlot(I->getType());
assert(Slot != -1 && "Module global vars is broken!");
// Fields: bit0 = isConstant, bit1 = hasInitializer, bit2-4=Linkage,
// bit5+ = Slot # for type
unsigned oSlot = ((unsigned)Slot << 5) | (getEncodedLinkage(I) << 2) |
(I->hasInitializer() << 1) | I->isConstant();
output_vbr(oSlot, Out);
// If we have an initializer, output it now.
if (I->hasInitializer()) {
Slot = Table.getSlot((Value*)I->getInitializer());
assert(Slot != -1 && "No slot for global var initializer!");
output_vbr((unsigned)Slot, Out);
}
}
output_vbr((unsigned)Table.getSlot(Type::VoidTy), Out);
// Output the types of the functions in this module...
for (Module::const_iterator I = M->begin(), End = M->end(); I != End; ++I) {
int Slot = Table.getSlot(I->getType());
assert(Slot != -1 && "Module const pool is broken!");
assert(Slot >= Type::FirstDerivedTyID && "Derived type not in range!");
output_vbr((unsigned)Slot, Out);
}
output_vbr((unsigned)Table.getSlot(Type::VoidTy), Out);
}
void BytecodeWriter::outputInstructions(const Function *F) {
BytecodeBlock ILBlock(BytecodeFormat::InstructionList, Out);
for (Function::const_iterator BB = F->begin(), E = F->end(); BB != E; ++BB)
for (BasicBlock::const_iterator I = BB->begin(), E = BB->end(); I!=E; ++I)
outputInstruction(*I);
}
void BytecodeWriter::outputFunction(const Function *F) {
BytecodeBlock FunctionBlock(BytecodeFormat::Function, Out);
output_vbr(getEncodedLinkage(F), Out);
// If this is an external function, there is nothing else to emit!
if (F->isExternal()) return;
// Get slot information about the function...
Table.incorporateFunction(F);
if (Table.getCompactionTable().empty()) {
// Output information about the constants in the function if the compaction
// table is not being used.
outputConstants(true);
} else {
// Otherwise, emit the compaction table.
outputCompactionTable();
}
// Output all of the instructions in the body of the function
outputInstructions(F);
// If needed, output the symbol table for the function...
outputSymbolTable(F->getSymbolTable());
Table.purgeFunction();
}
void BytecodeWriter::outputCompactionTablePlane(unsigned PlaneNo,
const std::vector<const Value*> &Plane,
unsigned StartNo) {
unsigned End = Table.getModuleLevel(PlaneNo);
if (Plane.empty() || StartNo == End || End == 0) return; // Nothing to emit
assert(StartNo < End && "Cannot emit negative range!");
assert(StartNo < Plane.size() && End <= Plane.size());
// Do not emit the null initializer!
if (PlaneNo != Type::TypeTyID) ++StartNo;
// Figure out which encoding to use. By far the most common case we have is
// to emit 0-2 entries in a compaction table plane.
switch (End-StartNo) {
case 0: // Avoid emitting two vbr's if possible.
case 1:
case 2:
output_vbr((PlaneNo << 2) | End-StartNo, Out);
break;
default:
// Output the number of things.
output_vbr((unsigned(End-StartNo) << 2) | 3, Out);
output_vbr(PlaneNo, Out); // Emit the type plane this is
break;
}
for (unsigned i = StartNo; i != End; ++i)
output_vbr(Table.getGlobalSlot(Plane[i]), Out);
}
void BytecodeWriter::outputCompactionTable() {
BytecodeBlock CTB(BytecodeFormat::CompactionTable, Out, true/*ElideIfEmpty*/);
const std::vector<std::vector<const Value*> > &CT =Table.getCompactionTable();
// First thing is first, emit the type compaction table if there is one.
if (CT.size() > Type::TypeTyID)
outputCompactionTablePlane(Type::TypeTyID, CT[Type::TypeTyID],
Type::FirstDerivedTyID);
for (unsigned i = 0, e = CT.size(); i != e; ++i)
if (i != Type::TypeTyID)
outputCompactionTablePlane(i, CT[i], 0);
}
void BytecodeWriter::outputSymbolTable(const SymbolTable &MST) {
// Do not output the Bytecode block for an empty symbol table, it just wastes
// space!
if (MST.plane_begin() == MST.plane_end()) return;
BytecodeBlock SymTabBlock(BytecodeFormat::SymbolTable, Out,
true/* ElideIfEmpty*/);
//Symtab block header: [num entries][type id number]
output_vbr(MST.num_types(), Out);
output_vbr((unsigned)Table.getSlot(Type::TypeTy), Out);
for (SymbolTable::type_const_iterator TI = MST.type_begin(),
TE = MST.type_end(); TI != TE; ++TI ) {
//Symtab entry:[def slot #][name]
output_vbr((unsigned)Table.getSlot(TI->second), Out);
output(TI->first, Out, /*align=*/false);
}
// Now do each of the type planes in order.
for (SymbolTable::plane_const_iterator PI = MST.plane_begin(),
PE = MST.plane_end(); PI != PE; ++PI) {
SymbolTable::value_const_iterator I = MST.value_begin(PI->first);
SymbolTable::value_const_iterator End = MST.value_end(PI->first);
int Slot;
if (I == End) continue; // Don't mess with an absent type...
// Symtab block header: [num entries][type id number]
output_vbr(MST.type_size(PI->first), Out);
Slot = Table.getSlot(PI->first);
assert(Slot != -1 && "Type in symtab, but not in table!");
output_vbr((unsigned)Slot, Out);
for (; I != End; ++I) {
// Symtab entry: [def slot #][name]
const Value *V = I->second;
Slot = Table.getSlot(I->second);
assert(Slot != -1 && "Value in symtab but has no slot number!!");
output_vbr((unsigned)Slot, Out);
output(I->first, Out, false); // Don't force alignment...
}
}
}
void llvm::WriteBytecodeToFile(const Module *C, std::ostream &Out) {
assert(C && "You can't write a null module!!");
std::deque<unsigned char> Buffer;
// This object populates buffer for us...
BytecodeWriter BCW(Buffer, C);
// Keep track of how much we've written...
BytesWritten += Buffer.size();
// Okay, write the deque out to the ostream now... the deque is not
// sequential in memory, however, so write out as much as possible in big
// chunks, until we're done.
//
std::deque<unsigned char>::const_iterator I = Buffer.begin(),E = Buffer.end();
while (I != E) { // Loop until it's all written
// Scan to see how big this chunk is...
const unsigned char *ChunkPtr = &*I;
const unsigned char *LastPtr = ChunkPtr;
while (I != E) {
const unsigned char *ThisPtr = &*++I;
if (LastPtr+1 != ThisPtr) { // Advanced by more than a byte of memory?
++LastPtr;
break;
}
LastPtr = ThisPtr;
}
// Write out the chunk...
Out.write((char*)ChunkPtr, LastPtr-ChunkPtr);
}
Out.flush();
}
<|endoftext|> |
<commit_before><commit_msg>better error message<commit_after><|endoftext|> |
<commit_before><commit_msg>Don't trim whitespace while parsing xml<commit_after><|endoftext|> |
<commit_before>/////////////////////////////////////////
//
// LieroX Game Script Compiler
//
// Copyright Auxiliary Software 2002
//
//
/////////////////////////////////////////
// OpenLieroX
// code under LGPL
// Main compiler
// Created 7/2/02
// Jason Boettcher
#include <cstdio>
#include <cstdlib>
#include <cstring>
#include <string>
#include "CVec.h"
#include "CGameScript.h"
#include "ConfigHandler.h"
#include "SmartPointer.h"
#include "CrashHandler.h"
// Prototypes
int CheckArgs(int argc, char *argv[]);
///////////////////
// Main entry point
int main(int argc, char *argv[])
{
notes << "Liero Xtreme Game Script Compiler" << endl;
notes << "(c) ..-2002 Auxiliary Software " << endl;
notes << " 2002-.. OpenLieroX team" << endl;
notes << "Version: " << GetGameVersion().asString() << endl;
notes << "GameScript Version: " << GS_VERSION << endl << endl << endl;
if( !CheckArgs(argc, argv) ) {
return 1;
}
CGameScript *Game = new CGameScript;
if(Game == NULL) {
errors << "GameCompiler: Out of memory while creating gamescript" << endl;
return false;
}
// Compile
bool comp = Game->Compile(argv[1]);
// Only save if the compile went ok
if(comp) {
printf("\nSaving...\n");
Game->Save(argv[2]);
}
if(comp)
printf("\nInfo:\nWeapons: %d\nProjectiles: %d\n",Game->GetNumWeapons(),Game->getProjectileCount());
if(Game) {
delete Game;
Game = NULL;
}
return 0;
}
///////////////////
// Check the arguments
int CheckArgs(int argc, char *argv[])
{
char *d = strrchr(argv[0],'\\');
if(!d)
d = argv[0];
else
d++;
if(argc != 3) {
printf("Usage:\n");
printf("%s [Mod dir] [filename]\n",d);
printf("\nExample:\n");
printf("%s Base script.lgs\n\n",d);
return false;
}
return true;
}
// some dummies/stubs are following to be able to compile with OLX sources
FILE* OpenGameFile(const std::string& file, const char* mod) {
// stub
return fopen(file.c_str(), mod);
}
bool GetExactFileName(const std::string& fn, std::string& exactfn) {
// sub
exactfn = fn;
return true;
}
struct SoundSample;
template <> void SmartPointer_ObjectDeinit<SoundSample> ( SoundSample * obj )
{
errors << "SmartPointer_ObjectDeinit SoundSample: stub" << endl;
}
template <> void SmartPointer_ObjectDeinit<SDL_Surface> ( SDL_Surface * obj )
{
errors << "SmartPointer_ObjectDeinit SDL_Surface: stub" << endl;
}
SmartPointer<SoundSample> LoadSample(const std::string& _filename, int maxplaying) {
// stub
return NULL;
}
SmartPointer<SDL_Surface> LoadGameImage(const std::string& _filename, bool withalpha) {
// stub
return NULL;
}
void SetColorKey(SDL_Surface * dst) {} // stub
bool bDedicated = true;
void SetError(const std::string& text) { errors << "SetError: " << text << endl; }
struct GameOptions;
GameOptions *tLXOptions = NULL;
bool Con_IsInited() { return false; }
CrashHandler* CrashHandler::get() { return NULL; }
void Con_AddText(int colour, const std::string& text, bool alsoToLogger) {}
SDL_PixelFormat defaultFallbackFormat =
{
NULL, //SDL_Palette *palette;
32, //Uint8 BitsPerPixel;
4, //Uint8 BytesPerPixel;
0, 0, 0, 0, //Uint8 Rloss, Gloss, Bloss, Aloss;
24, 16, 8, 0, //Uint8 Rshift, Gshift, Bshift, Ashift;
0xff000000, 0xff0000, 0xff00, 0xff, //Uint32 Rmask, Gmask, Bmask, Amask;
0, //Uint32 colorkey;
255 //Uint8 alpha;
};
SDL_PixelFormat* mainPixelFormat = &defaultFallbackFormat;
<commit_msg>better output<commit_after>/////////////////////////////////////////
//
// LieroX Game Script Compiler
//
// Copyright Auxiliary Software 2002
//
//
/////////////////////////////////////////
// OpenLieroX
// code under LGPL
// Main compiler
// Created 7/2/02
// Jason Boettcher
#include <cstdio>
#include <cstdlib>
#include <cstring>
#include <string>
#include "CVec.h"
#include "CGameScript.h"
#include "ConfigHandler.h"
#include "SmartPointer.h"
#include "CrashHandler.h"
// Prototypes
int CheckArgs(int argc, char *argv[]);
///////////////////
// Main entry point
int main(int argc, char *argv[])
{
notes << "Liero Xtreme Game Script Compiler" << endl;
notes << "(c) ..-2002 Auxiliary Software " << endl;
notes << " 2002-.. OpenLieroX team" << endl;
notes << "Version: " << GetGameVersion().asString() << endl;
notes << "GameScript Version: " << GS_VERSION << endl << endl << endl;
if( !CheckArgs(argc, argv) ) {
return 1;
}
CGameScript *Game = new CGameScript;
if(Game == NULL) {
errors << "GameCompiler: Out of memory while creating gamescript" << endl;
return false;
}
// Compile
bool comp = Game->Compile(argv[1]);
// Only save if the compile went ok
if(comp) {
notes << endl << "Saving..." << endl;
Game->Save(argv[2]);
}
if(comp)
notes << endl <<
"Info:" << endl <<
"Weapons: " << Game->GetNumWeapons() << endl <<
"Projectiles: " << Game->getProjectileCount() << endl;
if(Game) {
delete Game;
Game = NULL;
}
return 0;
}
///////////////////
// Check the arguments
int CheckArgs(int argc, char *argv[])
{
char *d = strrchr(argv[0],'\\');
if(!d)
d = argv[0];
else
d++;
if(argc != 3) {
notes << "Usage:" << endl;
notes << d << " [Mod dir] [filename]" << endl;
notes << endl << "Example:" << endl;
notes << d << " Base script.lgs" << endl << endl;
return false;
}
return true;
}
// some dummies/stubs are following to be able to compile with OLX sources
FILE* OpenGameFile(const std::string& file, const char* mod) {
// stub
return fopen(file.c_str(), mod);
}
bool GetExactFileName(const std::string& fn, std::string& exactfn) {
// sub
exactfn = fn;
return true;
}
struct SoundSample;
template <> void SmartPointer_ObjectDeinit<SoundSample> ( SoundSample * obj )
{
errors << "SmartPointer_ObjectDeinit SoundSample: stub" << endl;
}
template <> void SmartPointer_ObjectDeinit<SDL_Surface> ( SDL_Surface * obj )
{
errors << "SmartPointer_ObjectDeinit SDL_Surface: stub" << endl;
}
SmartPointer<SoundSample> LoadSample(const std::string& _filename, int maxplaying) {
// stub
return NULL;
}
SmartPointer<SDL_Surface> LoadGameImage(const std::string& _filename, bool withalpha) {
// stub
return NULL;
}
void SetColorKey(SDL_Surface * dst) {} // stub
bool bDedicated = true;
void SetError(const std::string& text) { errors << "SetError: " << text << endl; }
struct GameOptions;
GameOptions *tLXOptions = NULL;
bool Con_IsInited() { return false; }
CrashHandler* CrashHandler::get() { return NULL; }
void Con_AddText(int colour, const std::string& text, bool alsoToLogger) {}
SDL_PixelFormat defaultFallbackFormat =
{
NULL, //SDL_Palette *palette;
32, //Uint8 BitsPerPixel;
4, //Uint8 BytesPerPixel;
0, 0, 0, 0, //Uint8 Rloss, Gloss, Bloss, Aloss;
24, 16, 8, 0, //Uint8 Rshift, Gshift, Bshift, Ashift;
0xff000000, 0xff0000, 0xff00, 0xff, //Uint32 Rmask, Gmask, Bmask, Amask;
0, //Uint32 colorkey;
255 //Uint8 alpha;
};
SDL_PixelFormat* mainPixelFormat = &defaultFallbackFormat;
<|endoftext|> |
<commit_before><commit_msg>mention the -directory option if no fonts are found<commit_after><|endoftext|> |
<commit_before>//===-- PhiElimination.cpp - Eliminate PHI nodes by inserting copies ------===//
//
// The LLVM Compiler Infrastructure
//
// This file was developed by the LLVM research group and is distributed under
// the University of Illinois Open Source License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
//
// This pass eliminates machine instruction PHI nodes by inserting copy
// instructions. This destroys SSA information, but is the desired input for
// some register allocators.
//
//===----------------------------------------------------------------------===//
#include "llvm/CodeGen/LiveVariables.h"
#include "llvm/CodeGen/Passes.h"
#include "llvm/CodeGen/MachineFunctionPass.h"
#include "llvm/CodeGen/MachineInstr.h"
#include "llvm/CodeGen/SSARegMap.h"
#include "llvm/Target/TargetInstrInfo.h"
#include "llvm/Target/TargetMachine.h"
#include "llvm/ADT/DenseMap.h"
#include "llvm/ADT/STLExtras.h"
#include <set>
using namespace llvm;
namespace {
struct PNE : public MachineFunctionPass {
bool runOnMachineFunction(MachineFunction &Fn) {
bool Changed = false;
// Eliminate PHI instructions by inserting copies into predecessor blocks.
for (MachineFunction::iterator I = Fn.begin(), E = Fn.end(); I != E; ++I)
Changed |= EliminatePHINodes(Fn, *I);
return Changed;
}
virtual void getAnalysisUsage(AnalysisUsage &AU) const {
AU.addPreserved<LiveVariables>();
MachineFunctionPass::getAnalysisUsage(AU);
}
private:
/// EliminatePHINodes - Eliminate phi nodes by inserting copy instructions
/// in predecessor basic blocks.
///
bool EliminatePHINodes(MachineFunction &MF, MachineBasicBlock &MBB);
void LowerAtomicPHINode(MachineBasicBlock &MBB,
MachineBasicBlock::iterator AfterPHIsIt,
DenseMap<unsigned, VirtReg2IndexFunctor> &VUC,
unsigned BBIsSuccOfPreds);
};
RegisterPass<PNE> X("phi-node-elimination",
"Eliminate PHI nodes for register allocation");
}
const PassInfo *llvm::PHIEliminationID = X.getPassInfo();
/// EliminatePHINodes - Eliminate phi nodes by inserting copy instructions in
/// predecessor basic blocks.
///
bool PNE::EliminatePHINodes(MachineFunction &MF, MachineBasicBlock &MBB) {
if (MBB.empty() || MBB.front().getOpcode() != TargetInstrInfo::PHI)
return false; // Quick exit for basic blocks without PHIs.
// VRegPHIUseCount - Keep track of the number of times each virtual register
// is used by PHI nodes in successors of this block.
DenseMap<unsigned, VirtReg2IndexFunctor> VRegPHIUseCount;
VRegPHIUseCount.grow(MF.getSSARegMap()->getLastVirtReg());
unsigned BBIsSuccOfPreds = 0; // Number of times MBB is a succ of preds
for (MachineBasicBlock::pred_iterator PI = MBB.pred_begin(),
E = MBB.pred_end(); PI != E; ++PI)
for (MachineBasicBlock::succ_iterator SI = (*PI)->succ_begin(),
E = (*PI)->succ_end(); SI != E; ++SI) {
BBIsSuccOfPreds += *SI == &MBB;
for (MachineBasicBlock::iterator BBI = (*SI)->begin(); BBI !=(*SI)->end() &&
BBI->getOpcode() == TargetInstrInfo::PHI; ++BBI)
for (unsigned i = 1, e = BBI->getNumOperands(); i != e; i += 2)
VRegPHIUseCount[BBI->getOperand(i).getReg()]++;
}
// Get an iterator to the first instruction after the last PHI node (this may
// also be the end of the basic block).
MachineBasicBlock::iterator AfterPHIsIt = MBB.begin();
while (AfterPHIsIt != MBB.end() &&
AfterPHIsIt->getOpcode() == TargetInstrInfo::PHI)
++AfterPHIsIt; // Skip over all of the PHI nodes...
while (MBB.front().getOpcode() == TargetInstrInfo::PHI) {
LowerAtomicPHINode(MBB, AfterPHIsIt, VRegPHIUseCount, BBIsSuccOfPreds);
}
return true;
}
/// LowerAtomicPHINode - Lower the PHI node at the top of the specified block,
/// under the assuption that it needs to be lowered in a way that supports
/// atomic execution of PHIs. This lowering method is always correct all of the
/// time.
void PNE::LowerAtomicPHINode(MachineBasicBlock &MBB,
MachineBasicBlock::iterator AfterPHIsIt,
DenseMap<unsigned, VirtReg2IndexFunctor> &VRegPHIUseCount,
unsigned BBIsSuccOfPreds) {
// Unlink the PHI node from the basic block, but don't delete the PHI yet.
MachineInstr *MPhi = MBB.remove(MBB.begin());
unsigned DestReg = MPhi->getOperand(0).getReg();
// Create a new register for the incoming PHI arguments/
MachineFunction &MF = *MBB.getParent();
const TargetRegisterClass *RC = MF.getSSARegMap()->getRegClass(DestReg);
unsigned IncomingReg = MF.getSSARegMap()->createVirtualRegister(RC);
// Insert a register to register copy in the top of the current block (but
// after any remaining phi nodes) which copies the new incoming register
// into the phi node destination.
//
const MRegisterInfo *RegInfo = MF.getTarget().getRegisterInfo();
RegInfo->copyRegToReg(MBB, AfterPHIsIt, DestReg, IncomingReg, RC);
// Update live variable information if there is any...
LiveVariables *LV = getAnalysisToUpdate<LiveVariables>();
if (LV) {
MachineInstr *PHICopy = prior(AfterPHIsIt);
// Add information to LiveVariables to know that the incoming value is
// killed. Note that because the value is defined in several places (once
// each for each incoming block), the "def" block and instruction fields
// for the VarInfo is not filled in.
//
LV->addVirtualRegisterKilled(IncomingReg, PHICopy);
// Since we are going to be deleting the PHI node, if it is the last use
// of any registers, or if the value itself is dead, we need to move this
// information over to the new copy we just inserted.
//
LV->removeVirtualRegistersKilled(MPhi);
std::pair<LiveVariables::killed_iterator, LiveVariables::killed_iterator>
RKs = LV->dead_range(MPhi);
if (RKs.first != RKs.second) {
for (LiveVariables::killed_iterator I = RKs.first; I != RKs.second; ++I)
LV->addVirtualRegisterDead(*I, PHICopy);
LV->removeVirtualRegistersDead(MPhi);
}
}
// Adjust the VRegPHIUseCount map to account for the removal of this PHI
// node.
for (unsigned i = 1; i != MPhi->getNumOperands(); i += 2)
VRegPHIUseCount[MPhi->getOperand(i).getReg()] -= BBIsSuccOfPreds;
// Now loop over all of the incoming arguments, changing them to copy into
// the IncomingReg register in the corresponding predecessor basic block.
//
for (int i = MPhi->getNumOperands() - 1; i >= 2; i-=2) {
MachineOperand &opVal = MPhi->getOperand(i-1);
// Get the MachineBasicBlock equivalent of the BasicBlock that is the
// source path the PHI.
MachineBasicBlock &opBlock = *MPhi->getOperand(i).getMachineBasicBlock();
MachineBasicBlock::iterator I = opBlock.getFirstTerminator();
// Check to make sure we haven't already emitted the copy for this block.
// This can happen because PHI nodes may have multiple entries for the
// same basic block. It doesn't matter which entry we use though, because
// all incoming values are guaranteed to be the same for a particular bb.
//
// If we emitted a copy for this basic block already, it will be right
// where we want to insert one now. Just check for a definition of the
// register we are interested in!
//
bool HaveNotEmitted = true;
if (I != opBlock.begin()) {
MachineBasicBlock::iterator PrevInst = prior(I);
for (unsigned i = 0, e = PrevInst->getNumOperands(); i != e; ++i) {
MachineOperand &MO = PrevInst->getOperand(i);
if (MO.isRegister() && MO.getReg() == IncomingReg)
if (MO.isDef()) {
HaveNotEmitted = false;
break;
}
}
}
if (HaveNotEmitted) { // If the copy has not already been emitted, do it.
assert(MRegisterInfo::isVirtualRegister(opVal.getReg()) &&
"Machine PHI Operands must all be virtual registers!");
unsigned SrcReg = opVal.getReg();
RegInfo->copyRegToReg(opBlock, I, IncomingReg, SrcReg, RC);
// Now update live variable information if we have it.
if (LV) {
// We want to be able to insert a kill of the register if this PHI
// (aka, the copy we just inserted) is the last use of the source
// value. Live variable analysis conservatively handles this by
// saying that the value is live until the end of the block the PHI
// entry lives in. If the value really is dead at the PHI copy, there
// will be no successor blocks which have the value live-in.
//
// Check to see if the copy is the last use, and if so, update the
// live variables information so that it knows the copy source
// instruction kills the incoming value.
//
LiveVariables::VarInfo &InRegVI = LV->getVarInfo(SrcReg);
// Loop over all of the successors of the basic block, checking to see
// if the value is either live in the block, or if it is killed in the
// block. Also check to see if this register is in use by another PHI
// node which has not yet been eliminated. If so, it will be killed
// at an appropriate point later.
//
bool ValueIsLive = false;
for (MachineBasicBlock::succ_iterator SI = opBlock.succ_begin(),
E = opBlock.succ_end(); SI != E && !ValueIsLive; ++SI) {
MachineBasicBlock *SuccMBB = *SI;
// Is it alive in this successor?
unsigned SuccIdx = SuccMBB->getNumber();
if (SuccIdx < InRegVI.AliveBlocks.size() &&
InRegVI.AliveBlocks[SuccIdx]) {
ValueIsLive = true;
break;
}
// Is it killed in this successor?
for (unsigned i = 0, e = InRegVI.Kills.size(); i != e; ++i)
if (InRegVI.Kills[i]->getParent() == SuccMBB) {
ValueIsLive = true;
break;
}
// Is it used by any PHI instructions in this block?
if (!ValueIsLive)
ValueIsLive = VRegPHIUseCount[SrcReg] != 0;
}
// Okay, if we now know that the value is not live out of the block,
// we can add a kill marker to the copy we inserted saying that it
// kills the incoming value!
//
if (!ValueIsLive) {
MachineBasicBlock::iterator Prev = prior(I);
LV->addVirtualRegisterKilled(SrcReg, Prev);
// This vreg no longer lives all of the way through opBlock.
unsigned opBlockNum = opBlock.getNumber();
if (opBlockNum < InRegVI.AliveBlocks.size())
InRegVI.AliveBlocks[opBlockNum] = false;
}
}
}
}
// Really delete the PHI instruction now!
delete MPhi;
}
<commit_msg>clean up this code a bit, no functionality change<commit_after>//===-- PhiElimination.cpp - Eliminate PHI nodes by inserting copies ------===//
//
// The LLVM Compiler Infrastructure
//
// This file was developed by the LLVM research group and is distributed under
// the University of Illinois Open Source License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
//
// This pass eliminates machine instruction PHI nodes by inserting copy
// instructions. This destroys SSA information, but is the desired input for
// some register allocators.
//
//===----------------------------------------------------------------------===//
#include "llvm/CodeGen/LiveVariables.h"
#include "llvm/CodeGen/Passes.h"
#include "llvm/CodeGen/MachineFunctionPass.h"
#include "llvm/CodeGen/MachineInstr.h"
#include "llvm/CodeGen/SSARegMap.h"
#include "llvm/Target/TargetInstrInfo.h"
#include "llvm/Target/TargetMachine.h"
#include "llvm/ADT/DenseMap.h"
#include "llvm/ADT/STLExtras.h"
#include "llvm/ADT/Statistic.h"
#include <set>
#include <algorithm>
using namespace llvm;
namespace {
Statistic<> NumAtomic("phielim", "Number of atomic phis lowered");
Statistic<> NumSimple("phielim", "Number of simple phis lowered");
struct PNE : public MachineFunctionPass {
bool runOnMachineFunction(MachineFunction &Fn) {
bool Changed = false;
// Eliminate PHI instructions by inserting copies into predecessor blocks.
for (MachineFunction::iterator I = Fn.begin(), E = Fn.end(); I != E; ++I)
Changed |= EliminatePHINodes(Fn, *I);
return Changed;
}
virtual void getAnalysisUsage(AnalysisUsage &AU) const {
AU.addPreserved<LiveVariables>();
MachineFunctionPass::getAnalysisUsage(AU);
}
private:
/// EliminatePHINodes - Eliminate phi nodes by inserting copy instructions
/// in predecessor basic blocks.
///
bool EliminatePHINodes(MachineFunction &MF, MachineBasicBlock &MBB);
void LowerAtomicPHINode(MachineBasicBlock &MBB,
MachineBasicBlock::iterator AfterPHIsIt,
DenseMap<unsigned, VirtReg2IndexFunctor> &VUC);
};
RegisterPass<PNE> X("phi-node-elimination",
"Eliminate PHI nodes for register allocation");
}
const PassInfo *llvm::PHIEliminationID = X.getPassInfo();
/// EliminatePHINodes - Eliminate phi nodes by inserting copy instructions in
/// predecessor basic blocks.
///
bool PNE::EliminatePHINodes(MachineFunction &MF, MachineBasicBlock &MBB) {
if (MBB.empty() || MBB.front().getOpcode() != TargetInstrInfo::PHI)
return false; // Quick exit for basic blocks without PHIs.
// VRegPHIUseCount - Keep track of the number of times each virtual register
// is used by PHI nodes in successors of this block.
DenseMap<unsigned, VirtReg2IndexFunctor> VRegPHIUseCount;
VRegPHIUseCount.grow(MF.getSSARegMap()->getLastVirtReg());
for (MachineBasicBlock::pred_iterator PI = MBB.pred_begin(),
E = MBB.pred_end(); PI != E; ++PI)
for (MachineBasicBlock::succ_iterator SI = (*PI)->succ_begin(),
E = (*PI)->succ_end(); SI != E; ++SI)
for (MachineBasicBlock::iterator BBI = (*SI)->begin(), E = (*SI)->end();
BBI != E && BBI->getOpcode() == TargetInstrInfo::PHI; ++BBI)
for (unsigned i = 1, e = BBI->getNumOperands(); i != e; i += 2)
VRegPHIUseCount[BBI->getOperand(i).getReg()]++;
// Get an iterator to the first instruction after the last PHI node (this may
// also be the end of the basic block).
MachineBasicBlock::iterator AfterPHIsIt = MBB.begin();
while (AfterPHIsIt != MBB.end() &&
AfterPHIsIt->getOpcode() == TargetInstrInfo::PHI)
++AfterPHIsIt; // Skip over all of the PHI nodes...
while (MBB.front().getOpcode() == TargetInstrInfo::PHI) {
LowerAtomicPHINode(MBB, AfterPHIsIt, VRegPHIUseCount);
}
return true;
}
/// LowerAtomicPHINode - Lower the PHI node at the top of the specified block,
/// under the assuption that it needs to be lowered in a way that supports
/// atomic execution of PHIs. This lowering method is always correct all of the
/// time.
void PNE::LowerAtomicPHINode(MachineBasicBlock &MBB,
MachineBasicBlock::iterator AfterPHIsIt,
DenseMap<unsigned, VirtReg2IndexFunctor> &VRegPHIUseCount) {
// Unlink the PHI node from the basic block, but don't delete the PHI yet.
MachineInstr *MPhi = MBB.remove(MBB.begin());
unsigned DestReg = MPhi->getOperand(0).getReg();
// Create a new register for the incoming PHI arguments/
MachineFunction &MF = *MBB.getParent();
const TargetRegisterClass *RC = MF.getSSARegMap()->getRegClass(DestReg);
unsigned IncomingReg = MF.getSSARegMap()->createVirtualRegister(RC);
// Insert a register to register copy in the top of the current block (but
// after any remaining phi nodes) which copies the new incoming register
// into the phi node destination.
//
const MRegisterInfo *RegInfo = MF.getTarget().getRegisterInfo();
RegInfo->copyRegToReg(MBB, AfterPHIsIt, DestReg, IncomingReg, RC);
// Update live variable information if there is any...
LiveVariables *LV = getAnalysisToUpdate<LiveVariables>();
if (LV) {
MachineInstr *PHICopy = prior(AfterPHIsIt);
// Add information to LiveVariables to know that the incoming value is
// killed. Note that because the value is defined in several places (once
// each for each incoming block), the "def" block and instruction fields
// for the VarInfo is not filled in.
//
LV->addVirtualRegisterKilled(IncomingReg, PHICopy);
// Since we are going to be deleting the PHI node, if it is the last use
// of any registers, or if the value itself is dead, we need to move this
// information over to the new copy we just inserted.
//
LV->removeVirtualRegistersKilled(MPhi);
// If the result is dead, update LV.
if (LV->RegisterDefIsDead(MPhi, DestReg)) {
LV->addVirtualRegisterDead(DestReg, PHICopy);
LV->removeVirtualRegistersDead(MPhi);
}
}
// Adjust the VRegPHIUseCount map to account for the removal of this PHI
// node.
unsigned NumPreds = (MPhi->getNumOperands()-1)/2;
for (unsigned i = 1; i != MPhi->getNumOperands(); i += 2)
VRegPHIUseCount[MPhi->getOperand(i).getReg()] -= NumPreds;
// Now loop over all of the incoming arguments, changing them to copy into
// the IncomingReg register in the corresponding predecessor basic block.
//
std::set<MachineBasicBlock*> MBBsInsertedInto;
for (int i = MPhi->getNumOperands() - 1; i >= 2; i-=2) {
unsigned SrcReg = MPhi->getOperand(i-1).getReg();
assert(MRegisterInfo::isVirtualRegister(SrcReg) &&
"Machine PHI Operands must all be virtual registers!");
// Get the MachineBasicBlock equivalent of the BasicBlock that is the
// source path the PHI.
MachineBasicBlock &opBlock = *MPhi->getOperand(i).getMachineBasicBlock();
// Check to make sure we haven't already emitted the copy for this block.
// This can happen because PHI nodes may have multiple entries for the
// same basic block.
if (!MBBsInsertedInto.insert(&opBlock).second)
continue; // If the copy has already been emitted, we're done.
// Get an iterator pointing to the first terminator in the block (or end()).
// This is the point where we can insert a copy if we'd like to.
MachineBasicBlock::iterator I = opBlock.getFirstTerminator();
// Insert the copy.
RegInfo->copyRegToReg(opBlock, I, IncomingReg, SrcReg, RC);
// Now update live variable information if we have it. Otherwise we're done
if (!LV) continue;
// We want to be able to insert a kill of the register if this PHI
// (aka, the copy we just inserted) is the last use of the source
// value. Live variable analysis conservatively handles this by
// saying that the value is live until the end of the block the PHI
// entry lives in. If the value really is dead at the PHI copy, there
// will be no successor blocks which have the value live-in.
//
// Check to see if the copy is the last use, and if so, update the
// live variables information so that it knows the copy source
// instruction kills the incoming value.
//
LiveVariables::VarInfo &InRegVI = LV->getVarInfo(SrcReg);
// Loop over all of the successors of the basic block, checking to see
// if the value is either live in the block, or if it is killed in the
// block. Also check to see if this register is in use by another PHI
// node which has not yet been eliminated. If so, it will be killed
// at an appropriate point later.
//
// Is it used by any PHI instructions in this block?
bool ValueIsLive = VRegPHIUseCount[SrcReg] != 0;
std::vector<MachineBasicBlock*> OpSuccBlocks;
// Otherwise, scan successors, including the BB the PHI node lives in.
for (MachineBasicBlock::succ_iterator SI = opBlock.succ_begin(),
E = opBlock.succ_end(); SI != E && !ValueIsLive; ++SI) {
MachineBasicBlock *SuccMBB = *SI;
// Is it alive in this successor?
unsigned SuccIdx = SuccMBB->getNumber();
if (SuccIdx < InRegVI.AliveBlocks.size() &&
InRegVI.AliveBlocks[SuccIdx]) {
ValueIsLive = true;
break;
}
OpSuccBlocks.push_back(SuccMBB);
}
// Check to see if this value is live because there is a use in a successor
// that kills it.
if (!ValueIsLive) {
switch (OpSuccBlocks.size()) {
case 1: {
MachineBasicBlock *MBB = OpSuccBlocks[0];
for (unsigned i = 0, e = InRegVI.Kills.size(); i != e; ++i)
if (InRegVI.Kills[i]->getParent() == MBB) {
ValueIsLive = true;
break;
}
break;
}
case 2: {
MachineBasicBlock *MBB1 = OpSuccBlocks[0], *MBB2 = OpSuccBlocks[1];
for (unsigned i = 0, e = InRegVI.Kills.size(); i != e; ++i)
if (InRegVI.Kills[i]->getParent() == MBB1 ||
InRegVI.Kills[i]->getParent() == MBB2) {
ValueIsLive = true;
break;
}
break;
}
default:
std::sort(OpSuccBlocks.begin(), OpSuccBlocks.end());
for (unsigned i = 0, e = InRegVI.Kills.size(); i != e; ++i)
if (std::binary_search(OpSuccBlocks.begin(), OpSuccBlocks.end(),
InRegVI.Kills[i]->getParent())) {
ValueIsLive = true;
break;
}
}
}
// Okay, if we now know that the value is not live out of the block,
// we can add a kill marker to the copy we inserted saying that it
// kills the incoming value!
//
if (!ValueIsLive) {
MachineBasicBlock::iterator Prev = prior(I);
LV->addVirtualRegisterKilled(SrcReg, Prev);
// This vreg no longer lives all of the way through opBlock.
unsigned opBlockNum = opBlock.getNumber();
if (opBlockNum < InRegVI.AliveBlocks.size())
InRegVI.AliveBlocks[opBlockNum] = false;
}
}
// Really delete the PHI instruction now!
delete MPhi;
++NumAtomic;
}
<|endoftext|> |
<commit_before>/*=========================================================================
Program: ORFEO Toolbox
Language: C++
Date: $Date$
Version: $Revision$
Copyright (c) Centre National d'Etudes Spatiales. All rights reserved.
See OTBCopyright.txt for details.
This software is distributed WITHOUT ANY WARRANTY; without even
the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
PURPOSE. See the above copyright notices for more information.
=========================================================================*/
#include "itkExceptionObject.h"
#include "otbTerraSarCalibrationImageFilter.h"
#include "otbImage.h"
#include "otbVectorImage.h"
#include "itkExtractImageFilter.h"
#include "otbImageFileReader.h"
#include "otbImageFileWriter.h"
int otbTerraSarCalibrationImageComplexFilterTest(int argc, char * argv[])
{
const char * inputFileName = argv[1];
const char * outputFileName = argv[2];
const bool useFastCalibration = atoi(argv[3]);
const bool resultsInDbs = atoi(argv[4]);
typedef std::complex<double> ComplexType;
typedef otb::Image<ComplexType, 2> ImageType;
typedef otb::ImageFileReader<ImageType> ReaderType;
typedef otb::ImageFileWriter<ImageType> WriterType;
typedef otb::TerraSarCalibrationImageFilter<ImageType, ImageType> FilterType;
typedef itk::ExtractImageFilter<ImageType, ImageType> ExtractorType;
ReaderType::Pointer reader = ReaderType::New();
WriterType::Pointer writer = WriterType::New();
FilterType::Pointer filter = FilterType::New();
ExtractorType::Pointer extractor = ExtractorType::New();
reader->SetFileName(inputFileName);
writer->SetFileName(outputFileName);
reader->UpdateOutputInformation();
filter->SetInput(reader->GetOutput());
filter->SetUseFastCalibration(useFastCalibration);
filter->SetResultsInDecibels(resultsInDbs);
if (argc == 9)
{
ImageType::RegionType region;
ImageType::IndexType id;
id[0] = atoi(argv[5]);
id[1] = atoi(argv[6]);
ImageType::SizeType size;
size[0] = atoi(argv[7]);
size[1] = atoi(argv[8]);
region.SetIndex(id);
region.SetSize(size);
extractor->SetExtractionRegion(region);
extractor->SetInput(filter->GetOutput());
writer->SetInput(extractor->GetOutput());
}
else
{
writer->SetInput(filter->GetOutput());
}
writer->Update();
return EXIT_SUCCESS;
}
<commit_msg>Coorect test TorontoDb : write vectorimage<commit_after>/*=========================================================================
Program: ORFEO Toolbox
Language: C++
Date: $Date$
Version: $Revision$
Copyright (c) Centre National d'Etudes Spatiales. All rights reserved.
See OTBCopyright.txt for details.
This software is distributed WITHOUT ANY WARRANTY; without even
the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
PURPOSE. See the above copyright notices for more information.
=========================================================================*/
#include "itkExceptionObject.h"
#include "otbTerraSarCalibrationImageFilter.h"
#include "otbImage.h"
#include "otbVectorImage.h"
#include "otbVectorImage.h"
#include "itkExtractImageFilter.h"
#include "otbImageFileReader.h"
#include "otbImageFileWriter.h"
#include "itkComplexToRealImageFilter.h"
#include "itkComplexToImaginaryImageFilter.h"
#include "otbImageList.h"
#include "otbImageListToVectorImageFilter.h"
int otbTerraSarCalibrationImageComplexFilterTest(int argc, char * argv[])
{
const char * inputFileName = argv[1];
const char * outputFileName = argv[2];
const bool useFastCalibration = atoi(argv[3]);
const bool resultsInDbs = atoi(argv[4]);
typedef std::complex<double> ComplexType;
typedef otb::Image<ComplexType, 2> ImageCplxType;
typedef otb::Image<double, 2> ImageScalarType;
typedef otb::VectorImage<double, 2> OutputImageType;
typedef otb::ImageList<ImageScalarType> ImageListType;
typedef otb::ImageFileReader<ImageCplxType> ReaderType;
typedef otb::ImageFileWriter<OutputImageType> WriterType;
typedef otb::TerraSarCalibrationImageFilter<ImageCplxType, ImageCplxType> FilterType;
typedef itk::ExtractImageFilter<ImageCplxType, ImageCplxType> ExtractorType;
typedef itk::ComplexToRealImageFilter<ImageCplxType, ImageScalarType> RealExtractorType;
typedef itk::ComplexToImaginaryImageFilter<ImageCplxType, ImageScalarType> ImaginaryExtractorType;
typedef otb::ImageListToVectorImageFilter<ImageListType, OutputImageType> ListToVectorImageFilterType;
ReaderType::Pointer reader = ReaderType::New();
WriterType::Pointer writer = WriterType::New();
FilterType::Pointer filter = FilterType::New();
ExtractorType::Pointer extractor = ExtractorType::New();
reader->SetFileName(inputFileName);
writer->SetFileName(outputFileName);
reader->UpdateOutputInformation();
filter->SetInput(reader->GetOutput());
filter->SetUseFastCalibration(useFastCalibration);
filter->SetResultsInDecibels(resultsInDbs);
// The rest of the code is here to translate the image complexe into
// a VectorImage of int which each channel is the real and imagynary part
RealExtractorType::Pointer realExt = RealExtractorType::New();
ImaginaryExtractorType::Pointer imgExt = ImaginaryExtractorType::New();
if (argc == 9)
{
ImageCplxType::RegionType region;
ImageCplxType::IndexType id;
id[0] = atoi(argv[5]);
id[1] = atoi(argv[6]);
ImageCplxType::SizeType size;
size[0] = atoi(argv[7]);
size[1] = atoi(argv[8]);
region.SetIndex(id);
region.SetSize(size);
extractor->SetExtractionRegion(region);
extractor->SetInput(filter->GetOutput());
realExt->SetInput(extractor->GetOutput());
imgExt->SetInput(extractor->GetOutput());
}
else
{
realExt->SetInput(filter->GetOutput());
imgExt->SetInput(filter->GetOutput());
}
ImageListType::Pointer imList = ImageListType::New();
imList->PushBack(realExt->GetOutput());
imList->PushBack(imgExt->GetOutput());
ListToVectorImageFilterType::Pointer listCaster = ListToVectorImageFilterType::New();
listCaster->SetInput(imList);
writer->SetInput(listCaster->GetOutput());
writer->Update();
return EXIT_SUCCESS;
}
<|endoftext|> |
<commit_before>//===--- REPLCodeCompletion.cpp - Code completion for REPL ----------------===//
//
// This source file is part of the Swift.org open source project
//
// Copyright (c) 2014 - 2015 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See http://swift.org/LICENSE.txt for license information
// See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
//
//===----------------------------------------------------------------------===//
//
// This module provides completions to the immediate mode environment.
//
//===----------------------------------------------------------------------===//
#include "swift/IDE/REPLCodeCompletion.h"
#include "swift/AST/ASTContext.h"
#include "swift/AST/Module.h"
#include "swift/Basic/LLVM.h"
#include "swift/Basic/SourceManager.h"
#include "swift/Parse/DelayedParsingCallbacks.h"
#include "swift/Parse/Parser.h"
#include "swift/IDE/CodeCompletion.h"
#include "swift/Subsystems.h"
#include "llvm/Support/raw_ostream.h"
#include "llvm/Support/MemoryBuffer.h"
#include <algorithm>
using namespace swift;
using namespace ide;
std::string toInsertableString(CodeCompletionResult *Result) {
std::string Str;
for (auto C : Result->getCompletionString()->getChunks()) {
switch (C.getKind()) {
case CodeCompletionString::Chunk::ChunkKind::Text:
case CodeCompletionString::Chunk::ChunkKind::LeftParen:
case CodeCompletionString::Chunk::ChunkKind::RightParen:
case CodeCompletionString::Chunk::ChunkKind::LeftBracket:
case CodeCompletionString::Chunk::ChunkKind::RightBracket:
case CodeCompletionString::Chunk::ChunkKind::LeftAngle:
case CodeCompletionString::Chunk::ChunkKind::RightAngle:
case CodeCompletionString::Chunk::ChunkKind::Dot:
case CodeCompletionString::Chunk::ChunkKind::Comma:
case CodeCompletionString::Chunk::ChunkKind::ExclamationMark:
case CodeCompletionString::Chunk::ChunkKind::QuestionMark:
case CodeCompletionString::Chunk::ChunkKind::Ampersand:
case CodeCompletionString::Chunk::ChunkKind::DynamicLookupMethodCallTail:
Str += C.getText();
break;
case CodeCompletionString::Chunk::ChunkKind::CallParameterName:
case CodeCompletionString::Chunk::ChunkKind::CallParameterColon:
case CodeCompletionString::Chunk::ChunkKind::CallParameterType:
case CodeCompletionString::Chunk::ChunkKind::OptionalBegin:
case CodeCompletionString::Chunk::ChunkKind::CallParameterBegin:
case CodeCompletionString::Chunk::ChunkKind::GenericParameterBegin:
case CodeCompletionString::Chunk::ChunkKind::GenericParameterName:
case CodeCompletionString::Chunk::ChunkKind::TypeAnnotation:
return Str;
}
}
return Str;
}
namespace swift {
class REPLCodeCompletionConsumer : public CodeCompletionConsumer {
REPLCompletions &Completions;
public:
REPLCodeCompletionConsumer(REPLCompletions &Completions)
: Completions(Completions) {}
void handleResults(MutableArrayRef<CodeCompletionResult *> Results) override {
CodeCompletionContext::sortCompletionResults(Results);
for (auto Result : Results) {
std::string InsertableString = toInsertableString(Result);
if (StringRef(InsertableString).startswith(Completions.Prefix)) {
llvm::SmallString<128> PrintedResult;
{
llvm::raw_svector_ostream OS(PrintedResult);
Result->print(OS);
}
Completions.CompletionStrings.push_back(
Completions.CompletionContext.copyString(PrintedResult));
InsertableString = InsertableString.substr(Completions.Prefix.size());
Completions.CookedResults.push_back(
{ Completions.CompletionContext.copyString(InsertableString),
Result->getNumBytesToErase() });
}
}
}
};
} // namespace swift
REPLCompletions::REPLCompletions()
: State(CompletionState::Invalid), CompletionContext(CompletionCache) {
// Create a CodeCompletionConsumer.
Consumer.reset(new REPLCodeCompletionConsumer(*this));
// Cerate a factory for code completion callbacks that will feed the
// Consumer.
CompletionCallbacksFactory.reset(
ide::makeCodeCompletionCallbacksFactory(CompletionContext,
*Consumer.get()));
}
static void
doCodeCompletion(SourceFile &SF, StringRef EnteredCode, unsigned *BufferID,
CodeCompletionCallbacksFactory *CompletionCallbacksFactory) {
// Temporarily disable printing the diagnostics.
ASTContext &Ctx = SF.getASTContext();
auto DiagnosticConsumers = Ctx.Diags.takeConsumers();
std::string AugmentedCode = EnteredCode.str();
AugmentedCode += '\0';
*BufferID = Ctx.SourceMgr.addMemBufferCopy(AugmentedCode, "<REPL Input>");
const unsigned CodeCompletionOffset = AugmentedCode.size() - 1;
Ctx.SourceMgr.setCodeCompletionPoint(*BufferID, CodeCompletionOffset);
// Parse, typecheck and temporarily insert the incomplete code into the AST.
const unsigned OriginalDeclCount = SF.Decls.size();
unsigned CurElem = OriginalDeclCount;
PersistentParserState PersistentState;
std::unique_ptr<DelayedParsingCallbacks> DelayedCB(
new CodeCompleteDelayedCallbacks(Ctx.SourceMgr.getCodeCompletionLoc()));
bool Done;
do {
parseIntoSourceFile(SF, *BufferID, &Done, nullptr, &PersistentState,
DelayedCB.get());
performTypeChecking(SF, PersistentState.getTopLevelContext(), CurElem);
CurElem = SF.Decls.size();
} while (!Done);
performDelayedParsing(&SF, PersistentState, CompletionCallbacksFactory);
// Now we are done with code completion. Remove the declarations we
// temporarily inserted.
SF.Decls.resize(OriginalDeclCount);
// Add the diagnostic consumers back.
for (auto DC : DiagnosticConsumers)
Ctx.Diags.addConsumer(*DC);
Ctx.Diags.resetHadAnyError();
}
void REPLCompletions::populate(SourceFile &SF, StringRef EnteredCode) {
Prefix = "";
Root.reset();
CurrentCompletionIdx = ~size_t(0);
CompletionStrings.clear();
CookedResults.clear();
assert(SF.Kind == SourceFileKind::REPL && "Can't append to a non-REPL file");
unsigned BufferID;
doCodeCompletion(SF, EnteredCode, &BufferID,
CompletionCallbacksFactory.get());
ASTContext &Ctx = SF.getASTContext();
std::vector<Token> Tokens = tokenize(Ctx.LangOpts, Ctx.SourceMgr, BufferID);
if (!Tokens.empty() && Tokens.back().is(tok::code_complete))
Tokens.pop_back();
if (!Tokens.empty()) {
Token &LastToken = Tokens.back();
if (LastToken.is(tok::identifier) || LastToken.isKeyword()) {
Prefix = LastToken.getText();
unsigned Offset = Ctx.SourceMgr.getLocOffsetInBuffer(LastToken.getLoc(),
BufferID);
doCodeCompletion(SF, EnteredCode.substr(0, Offset),
&BufferID, CompletionCallbacksFactory.get());
}
}
if (CookedResults.empty())
State = CompletionState::Empty;
else if (CookedResults.size() == 1)
State = CompletionState::Unique;
else
State = CompletionState::CompletedRoot;
}
StringRef REPLCompletions::getRoot() const {
if (Root)
return Root.getValue();
if (CookedResults.empty()) {
Root = std::string();
return Root.getValue();
}
std::string RootStr = CookedResults[0].InsertableString;
for (auto R : CookedResults) {
if (R.NumBytesToErase != 0) {
RootStr.resize(0);
break;
}
auto MismatchPlace = std::mismatch(RootStr.begin(), RootStr.end(),
R.InsertableString.begin());
RootStr.resize(MismatchPlace.first - RootStr.begin());
}
Root = RootStr;
return Root.getValue();
}
REPLCompletions::CookedResult REPLCompletions::getPreviousStem() const {
if (CurrentCompletionIdx == ~size_t(0) || CookedResults.empty())
return {};
const auto &Result = CookedResults[CurrentCompletionIdx];
return { Result.InsertableString.substr(getRoot().size()),
Result.NumBytesToErase };
}
REPLCompletions::CookedResult REPLCompletions::getNextStem() {
if (CookedResults.empty())
return {};
CurrentCompletionIdx++;
if (CurrentCompletionIdx >= CookedResults.size())
CurrentCompletionIdx = 0;
const auto &Result = CookedResults[CurrentCompletionIdx];
return { Result.InsertableString.substr(getRoot().size()),
Result.NumBytesToErase };
}
void REPLCompletions::reset() { State = CompletionState::Invalid; }
<commit_msg>REPL code completion: handle PreferredCursorPosition chunk<commit_after>//===--- REPLCodeCompletion.cpp - Code completion for REPL ----------------===//
//
// This source file is part of the Swift.org open source project
//
// Copyright (c) 2014 - 2015 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See http://swift.org/LICENSE.txt for license information
// See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
//
//===----------------------------------------------------------------------===//
//
// This module provides completions to the immediate mode environment.
//
//===----------------------------------------------------------------------===//
#include "swift/IDE/REPLCodeCompletion.h"
#include "swift/AST/ASTContext.h"
#include "swift/AST/Module.h"
#include "swift/Basic/LLVM.h"
#include "swift/Basic/SourceManager.h"
#include "swift/Parse/DelayedParsingCallbacks.h"
#include "swift/Parse/Parser.h"
#include "swift/IDE/CodeCompletion.h"
#include "swift/Subsystems.h"
#include "llvm/Support/raw_ostream.h"
#include "llvm/Support/MemoryBuffer.h"
#include <algorithm>
using namespace swift;
using namespace ide;
std::string toInsertableString(CodeCompletionResult *Result) {
std::string Str;
for (auto C : Result->getCompletionString()->getChunks()) {
switch (C.getKind()) {
case CodeCompletionString::Chunk::ChunkKind::Text:
case CodeCompletionString::Chunk::ChunkKind::LeftParen:
case CodeCompletionString::Chunk::ChunkKind::RightParen:
case CodeCompletionString::Chunk::ChunkKind::LeftBracket:
case CodeCompletionString::Chunk::ChunkKind::RightBracket:
case CodeCompletionString::Chunk::ChunkKind::LeftAngle:
case CodeCompletionString::Chunk::ChunkKind::RightAngle:
case CodeCompletionString::Chunk::ChunkKind::Dot:
case CodeCompletionString::Chunk::ChunkKind::Comma:
case CodeCompletionString::Chunk::ChunkKind::ExclamationMark:
case CodeCompletionString::Chunk::ChunkKind::QuestionMark:
case CodeCompletionString::Chunk::ChunkKind::Ampersand:
case CodeCompletionString::Chunk::ChunkKind::DynamicLookupMethodCallTail:
Str += C.getText();
break;
case CodeCompletionString::Chunk::ChunkKind::CallParameterName:
case CodeCompletionString::Chunk::ChunkKind::CallParameterColon:
case CodeCompletionString::Chunk::ChunkKind::CallParameterType:
case CodeCompletionString::Chunk::ChunkKind::OptionalBegin:
case CodeCompletionString::Chunk::ChunkKind::CallParameterBegin:
case CodeCompletionString::Chunk::ChunkKind::GenericParameterBegin:
case CodeCompletionString::Chunk::ChunkKind::GenericParameterName:
case CodeCompletionString::Chunk::ChunkKind::TypeAnnotation:
case CodeCompletionString::Chunk::ChunkKind::PreferredCursorPosition:
return Str;
}
}
return Str;
}
namespace swift {
class REPLCodeCompletionConsumer : public CodeCompletionConsumer {
REPLCompletions &Completions;
public:
REPLCodeCompletionConsumer(REPLCompletions &Completions)
: Completions(Completions) {}
void handleResults(MutableArrayRef<CodeCompletionResult *> Results) override {
CodeCompletionContext::sortCompletionResults(Results);
for (auto Result : Results) {
std::string InsertableString = toInsertableString(Result);
if (StringRef(InsertableString).startswith(Completions.Prefix)) {
llvm::SmallString<128> PrintedResult;
{
llvm::raw_svector_ostream OS(PrintedResult);
Result->print(OS);
}
Completions.CompletionStrings.push_back(
Completions.CompletionContext.copyString(PrintedResult));
InsertableString = InsertableString.substr(Completions.Prefix.size());
Completions.CookedResults.push_back(
{ Completions.CompletionContext.copyString(InsertableString),
Result->getNumBytesToErase() });
}
}
}
};
} // namespace swift
REPLCompletions::REPLCompletions()
: State(CompletionState::Invalid), CompletionContext(CompletionCache) {
// Create a CodeCompletionConsumer.
Consumer.reset(new REPLCodeCompletionConsumer(*this));
// Cerate a factory for code completion callbacks that will feed the
// Consumer.
CompletionCallbacksFactory.reset(
ide::makeCodeCompletionCallbacksFactory(CompletionContext,
*Consumer.get()));
}
static void
doCodeCompletion(SourceFile &SF, StringRef EnteredCode, unsigned *BufferID,
CodeCompletionCallbacksFactory *CompletionCallbacksFactory) {
// Temporarily disable printing the diagnostics.
ASTContext &Ctx = SF.getASTContext();
auto DiagnosticConsumers = Ctx.Diags.takeConsumers();
std::string AugmentedCode = EnteredCode.str();
AugmentedCode += '\0';
*BufferID = Ctx.SourceMgr.addMemBufferCopy(AugmentedCode, "<REPL Input>");
const unsigned CodeCompletionOffset = AugmentedCode.size() - 1;
Ctx.SourceMgr.setCodeCompletionPoint(*BufferID, CodeCompletionOffset);
// Parse, typecheck and temporarily insert the incomplete code into the AST.
const unsigned OriginalDeclCount = SF.Decls.size();
unsigned CurElem = OriginalDeclCount;
PersistentParserState PersistentState;
std::unique_ptr<DelayedParsingCallbacks> DelayedCB(
new CodeCompleteDelayedCallbacks(Ctx.SourceMgr.getCodeCompletionLoc()));
bool Done;
do {
parseIntoSourceFile(SF, *BufferID, &Done, nullptr, &PersistentState,
DelayedCB.get());
performTypeChecking(SF, PersistentState.getTopLevelContext(), CurElem);
CurElem = SF.Decls.size();
} while (!Done);
performDelayedParsing(&SF, PersistentState, CompletionCallbacksFactory);
// Now we are done with code completion. Remove the declarations we
// temporarily inserted.
SF.Decls.resize(OriginalDeclCount);
// Add the diagnostic consumers back.
for (auto DC : DiagnosticConsumers)
Ctx.Diags.addConsumer(*DC);
Ctx.Diags.resetHadAnyError();
}
void REPLCompletions::populate(SourceFile &SF, StringRef EnteredCode) {
Prefix = "";
Root.reset();
CurrentCompletionIdx = ~size_t(0);
CompletionStrings.clear();
CookedResults.clear();
assert(SF.Kind == SourceFileKind::REPL && "Can't append to a non-REPL file");
unsigned BufferID;
doCodeCompletion(SF, EnteredCode, &BufferID,
CompletionCallbacksFactory.get());
ASTContext &Ctx = SF.getASTContext();
std::vector<Token> Tokens = tokenize(Ctx.LangOpts, Ctx.SourceMgr, BufferID);
if (!Tokens.empty() && Tokens.back().is(tok::code_complete))
Tokens.pop_back();
if (!Tokens.empty()) {
Token &LastToken = Tokens.back();
if (LastToken.is(tok::identifier) || LastToken.isKeyword()) {
Prefix = LastToken.getText();
unsigned Offset = Ctx.SourceMgr.getLocOffsetInBuffer(LastToken.getLoc(),
BufferID);
doCodeCompletion(SF, EnteredCode.substr(0, Offset),
&BufferID, CompletionCallbacksFactory.get());
}
}
if (CookedResults.empty())
State = CompletionState::Empty;
else if (CookedResults.size() == 1)
State = CompletionState::Unique;
else
State = CompletionState::CompletedRoot;
}
StringRef REPLCompletions::getRoot() const {
if (Root)
return Root.getValue();
if (CookedResults.empty()) {
Root = std::string();
return Root.getValue();
}
std::string RootStr = CookedResults[0].InsertableString;
for (auto R : CookedResults) {
if (R.NumBytesToErase != 0) {
RootStr.resize(0);
break;
}
auto MismatchPlace = std::mismatch(RootStr.begin(), RootStr.end(),
R.InsertableString.begin());
RootStr.resize(MismatchPlace.first - RootStr.begin());
}
Root = RootStr;
return Root.getValue();
}
REPLCompletions::CookedResult REPLCompletions::getPreviousStem() const {
if (CurrentCompletionIdx == ~size_t(0) || CookedResults.empty())
return {};
const auto &Result = CookedResults[CurrentCompletionIdx];
return { Result.InsertableString.substr(getRoot().size()),
Result.NumBytesToErase };
}
REPLCompletions::CookedResult REPLCompletions::getNextStem() {
if (CookedResults.empty())
return {};
CurrentCompletionIdx++;
if (CurrentCompletionIdx >= CookedResults.size())
CurrentCompletionIdx = 0;
const auto &Result = CookedResults[CurrentCompletionIdx];
return { Result.InsertableString.substr(getRoot().size()),
Result.NumBytesToErase };
}
void REPLCompletions::reset() { State = CompletionState::Invalid; }
<|endoftext|> |
<commit_before>/* /////////////////////////////////////////////////////////////////////////
* File: example.cpp.main.1.cpp
*
* Purpose: Implementation file for the example.cpp.main.1 library.
*
* Created: 5th January 2011
* Updated: 9th February 2021
*
* Status: Wizard-generated
*
* License: (Licensed under the Synesis Software Open License)
*
* Copyright (c) 2011-2021, Synesis Software Pty Ltd.
* All rights reserved.
*
* www: http://www.synesis.com.au/software
*
* ////////////////////////////////////////////////////////////////////// */
/* /////////////////////////////////////////////////////////////////////////
* feature control
*/
// This is defined for illustrative purposes. You are advised to *not*
// define this in production code. See Quality Matters, #5: "Exceptions:
// The Worst Form of Error Handling, Apart From All The Others" for details
// (http://quality-matters-to.us/).
#define PANTHEIOS_EXTRAS_MAIN_USE_CATCHALL
/* /////////////////////////////////////////////////////////////////////////
* includes
*/
/* Pantheios Extras header files */
#include <pantheios/extras/main.hpp>
/* Pantheios header files */
#include <pantheios/pantheios.h>
/* STLSoft header files */
#include <stlsoft/stlsoft.h>
/* Standard C header files */
#include <stdlib.h>
/* /////////////////////////////////////////////////////////////////////////
* globals
*/
PANTHEIOS_EXTERN_C PAN_CHAR_T const PANTHEIOS_FE_PROCESS_IDENTITY[] = PANTHEIOS_LITERAL_STRING("example.cpp.main.1");
/* ////////////////////////////////////////////////////////////////////// */
#ifndef USE_wmain
int main0(int argc, char** argv)
{
/* do the "main" business of main() here, without worrying about
* initialising Pantheios libraries
*/
/* in this case, we simply throw a given type of exception, as
* requested by the user
*/
if (argc == 2)
{
if (0 == strcmp(argv[1], "memory"))
{
throw std::bad_alloc();
}
else
if (0 == strcmp(argv[1], "root"))
{
throw std::runtime_error("oops!");
}
else
{
throw 1.0;
}
}
printf(
"USAGE: %s {memory|root|other}\n"
, argv[0]
);
return EXIT_SUCCESS;
}
int main(int argc, char** argv)
{
return pantheios::extras::main::invoke(argc, argv, main0);
}
#else // ? USE_wmain
int main0(int argc, wchar_t** argv)
{
/* do the "main" business of main() here, without worrying about
* initialising Pantheios libraries
*/
/* in this case, we simply throw a given type of exception, as
* requested by the user
*/
if (argc == 2)
{
if (0 == wcscmp(argv[1], L"memory"))
{
throw std::bad_alloc();
}
else
if (0 == wcscmp(argv[1], L"root"))
{
throw std::runtime_error("oops!");
}
else
{
throw 1.0;
}
}
printf(
"USAGE: %s {memory|root|other}\n"
, argv[0]
);
return EXIT_SUCCESS;
}
int wmain(int argc, wchar_t** argv)
{
return pantheios::extras::main::invoke(argc, argv, main0);
}
#endif // !USE_wmain
/* ///////////////////////////// end of file //////////////////////////// */
<commit_msg>~ wide-string implementation<commit_after>/* /////////////////////////////////////////////////////////////////////////
* File: example.cpp.main.1.cpp
*
* Purpose: Implementation file for the example.cpp.main.1 library.
*
* Created: 5th January 2011
* Updated: 9th February 2021
*
* Status: Wizard-generated
*
* License: (Licensed under the Synesis Software Open License)
*
* Copyright (c) 2011-2021, Synesis Software Pty Ltd.
* All rights reserved.
*
* www: http://www.synesis.com.au/software
*
* ////////////////////////////////////////////////////////////////////// */
/* /////////////////////////////////////////////////////////////////////////
* feature control
*/
// This is defined for illustrative purposes. You are advised to *not*
// define this in production code. See Quality Matters, #5: "Exceptions:
// The Worst Form of Error Handling, Apart From All The Others" for details
// (http://quality-matters-to.us/).
#define PANTHEIOS_EXTRAS_MAIN_USE_CATCHALL
/* /////////////////////////////////////////////////////////////////////////
* includes
*/
/* Pantheios Extras header files */
#include <pantheios/extras/main.hpp>
/* Pantheios header files */
#include <pantheios/pantheios.h>
/* STLSoft header files */
#include <stlsoft/stlsoft.h>
/* Standard C header files */
#include <stdlib.h>
/* /////////////////////////////////////////////////////////////////////////
* globals
*/
PANTHEIOS_EXTERN_C PAN_CHAR_T const PANTHEIOS_FE_PROCESS_IDENTITY[] = PANTHEIOS_LITERAL_STRING("example.cpp.main.1");
/* ////////////////////////////////////////////////////////////////////// */
#ifndef USE_wmain
int main0(int argc, char** argv)
{
/* do the "main" business of main() here, without worrying about
* initialising Pantheios libraries
*/
/* in this case, we simply throw a given type of exception, as
* requested by the user
*/
if (argc == 2)
{
if (0 == strcmp(argv[1], "memory"))
{
throw std::bad_alloc();
}
else
if (0 == strcmp(argv[1], "root"))
{
throw std::runtime_error("oops!");
}
else
{
throw 1.0;
}
}
printf(
"USAGE: %s {memory|root|other}\n"
, argv[0]
);
return EXIT_SUCCESS;
}
int main(int argc, char** argv)
{
return pantheios::extras::main::invoke(argc, argv, main0);
}
#else // ? USE_wmain
int main0(int argc, wchar_t** argv)
{
/* do the "main" business of main() here, without worrying about
* initialising Pantheios libraries
*/
/* in this case, we simply throw a given type of exception, as
* requested by the user
*/
if (argc == 2)
{
if (0 == wcscmp(argv[1], L"memory"))
{
throw std::bad_alloc();
}
else
if (0 == wcscmp(argv[1], L"root"))
{
throw std::runtime_error("oops!");
}
else
{
throw 1.0;
}
}
wprintf(
L"USAGE: %s {memory|root|other}\n"
, argv[0]
);
return EXIT_SUCCESS;
}
int wmain(int argc, wchar_t** argv)
{
return pantheios::extras::main::invoke(argc, argv, main0);
}
#endif // !USE_wmain
/* ///////////////////////////// end of file //////////////////////////// */
<|endoftext|> |
<commit_before>// Copyright (c) 2009-2015 The Bitcoin Core developers
// Distributed under the MIT software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
#include "paymentservertests.h"
#include "optionsmodel.h"
#include "paymentrequestdata.h"
#include "amount.h"
#include "random.h"
#include "script/script.h"
#include "script/standard.h"
#include "util.h"
#include "utilstrencodings.h"
#include <openssl/x509.h>
#include <openssl/x509_vfy.h>
#include <QFileOpenEvent>
#include <QTemporaryFile>
X509 *parse_b64der_cert(const char* cert_data)
{
std::vector<unsigned char> data = DecodeBase64(cert_data);
assert(data.size() > 0);
const unsigned char* dptr = &data[0];
X509 *cert = d2i_X509(NULL, &dptr, data.size());
assert(cert);
return cert;
}
//
// Test payment request handling
//
static SendCoinsRecipient handleRequest(PaymentServer* server, std::vector<unsigned char>& data)
{
RecipientCatcher sigCatcher;
QObject::connect(server, SIGNAL(receivedPaymentRequest(SendCoinsRecipient)),
&sigCatcher, SLOT(getRecipient(SendCoinsRecipient)));
// Write data to a temp file:
QTemporaryFile f;
f.open();
f.write((const char*)&data[0], data.size());
f.close();
// Create a QObject, install event filter from PaymentServer
// and send a file open event to the object
QObject object;
object.installEventFilter(server);
QFileOpenEvent event(f.fileName());
// If sending the event fails, this will cause sigCatcher to be empty,
// which will lead to a test failure anyway.
QCoreApplication::sendEvent(&object, &event);
QObject::disconnect(server, SIGNAL(receivedPaymentRequest(SendCoinsRecipient)),
&sigCatcher, SLOT(getRecipient(SendCoinsRecipient)));
// Return results from sigCatcher
return sigCatcher.recipient;
}
void PaymentServerTests::paymentServerTests()
{
SelectParams(CBaseChainParams::MAIN);
OptionsModel optionsModel;
PaymentServer* server = new PaymentServer(NULL, false);
X509_STORE* caStore = X509_STORE_new();
X509_STORE_add_cert(caStore, parse_b64der_cert(caCert1_BASE64));
PaymentServer::LoadRootCAs(caStore);
server->setOptionsModel(&optionsModel);
server->uiReady();
std::vector<unsigned char> data;
SendCoinsRecipient r;
QString merchant;
// Now feed PaymentRequests to server, and observe signals it produces
// Dogecoin: Disable certificate tests as we don't touch this code, and building test
// data would take significant effort. Also pending discussion on spec
// This payment request validates directly against the
// caCert1 certificate authority:
/* data = DecodeBase64(paymentrequest1_cert1_BASE64);
r = handleRequest(server, data);
r.paymentRequest.getMerchant(caStore, merchant);
QCOMPARE(merchant, QString("testmerchant.org"));
// Signed, but expired, merchant cert in the request:
data = DecodeBase64(paymentrequest2_cert1_BASE64);
r = handleRequest(server, data);
r.paymentRequest.getMerchant(caStore, merchant);
QCOMPARE(merchant, QString(""));
// 10-long certificate chain, all intermediates valid:
data = DecodeBase64(paymentrequest3_cert1_BASE64);
r = handleRequest(server, data);
r.paymentRequest.getMerchant(caStore, merchant);
QCOMPARE(merchant, QString("testmerchant8.org"));
// Long certificate chain, with an expired certificate in the middle:
data = DecodeBase64(paymentrequest4_cert1_BASE64);
r = handleRequest(server, data);
r.paymentRequest.getMerchant(caStore, merchant);
QCOMPARE(merchant, QString(""));
// Validly signed, but by a CA not in our root CA list:
data = DecodeBase64(paymentrequest5_cert1_BASE64);
r = handleRequest(server, data);
r.paymentRequest.getMerchant(caStore, merchant);
QCOMPARE(merchant, QString(""));
// Try again with no root CA's, verifiedMerchant should be empty:
caStore = X509_STORE_new();
PaymentServer::LoadRootCAs(caStore);
data = DecodeBase64(paymentrequest1_cert1_BASE64);
r = handleRequest(server, data);
r.paymentRequest.getMerchant(caStore, merchant);
QCOMPARE(merchant, QString(""));
// Load second root certificate
caStore = X509_STORE_new();
X509_STORE_add_cert(caStore, parse_b64der_cert(caCert2_BASE64));
PaymentServer::LoadRootCAs(caStore); */
QByteArray byteArray;
// For the tests below we just need the payment request data from
// paymentrequestdata.h parsed + stored in r.paymentRequest.
//
// These tests require us to bypass the following normal client execution flow
// shown below to be able to explicitly just trigger a certain condition!
//
// handleRequest()
// -> PaymentServer::eventFilter()
// -> PaymentServer::handleURIOrFile()
// -> PaymentServer::readPaymentRequestFromFile()
// -> PaymentServer::processPaymentRequest()
// Contains a testnet paytoaddress, so payment request network doesn't match client network:
data = DecodeBase64(paymentrequest1_cert2_BASE64);
byteArray = QByteArray((const char*)&data[0], data.size());
r.paymentRequest.parse(byteArray);
// Ensure the request is initialized, because network "main" is default, even for
// uninizialized payment requests and that will fail our test here.
QVERIFY(r.paymentRequest.IsInitialized());
QCOMPARE(PaymentServer::verifyNetwork(r.paymentRequest.getDetails()), false);
// Expired payment request (expires is set to 1 = 1970-01-01 00:00:01):
data = DecodeBase64(paymentrequest2_cert2_BASE64);
byteArray = QByteArray((const char*)&data[0], data.size());
r.paymentRequest.parse(byteArray);
// Ensure the request is initialized
QVERIFY(r.paymentRequest.IsInitialized());
// compares 1 < GetTime() == false (treated as expired payment request)
QCOMPARE(PaymentServer::verifyExpired(r.paymentRequest.getDetails()), true);
// Unexpired payment request (expires is set to 0x7FFFFFFFFFFFFFFF = max. int64_t):
// 9223372036854775807 (uint64), 9223372036854775807 (int64_t) and -1 (int32_t)
// -1 is 1969-12-31 23:59:59 (for a 32 bit time values)
data = DecodeBase64(paymentrequest3_cert2_BASE64);
byteArray = QByteArray((const char*)&data[0], data.size());
r.paymentRequest.parse(byteArray);
// Ensure the request is initialized
QVERIFY(r.paymentRequest.IsInitialized());
// compares 9223372036854775807 < GetTime() == false (treated as unexpired payment request)
QCOMPARE(PaymentServer::verifyExpired(r.paymentRequest.getDetails()), false);
// Unexpired payment request (expires is set to 0x8000000000000000 > max. int64_t, allowed uint64):
// 9223372036854775808 (uint64), -9223372036854775808 (int64_t) and 0 (int32_t)
// 0 is 1970-01-01 00:00:00 (for a 32 bit time values)
data = DecodeBase64(paymentrequest4_cert2_BASE64);
byteArray = QByteArray((const char*)&data[0], data.size());
r.paymentRequest.parse(byteArray);
// Ensure the request is initialized
QVERIFY(r.paymentRequest.IsInitialized());
// compares -9223372036854775808 < GetTime() == true (treated as expired payment request)
QCOMPARE(PaymentServer::verifyExpired(r.paymentRequest.getDetails()), true);
// Test BIP70 DoS protection:
unsigned char randData[BIP70_MAX_PAYMENTREQUEST_SIZE + 1];
GetRandBytes(randData, sizeof(randData));
// Write data to a temp file:
QTemporaryFile tempFile;
tempFile.open();
tempFile.write((const char*)randData, sizeof(randData));
tempFile.close();
// compares 50001 <= BIP70_MAX_PAYMENTREQUEST_SIZE == false
QCOMPARE(PaymentServer::verifySize(tempFile.size()), false);
// Payment request with amount overflow (amount is set to 21000001 BTC):
data = DecodeBase64(paymentrequest5_cert2_BASE64);
byteArray = QByteArray((const char*)&data[0], data.size());
r.paymentRequest.parse(byteArray);
// Ensure the request is initialized
QVERIFY(r.paymentRequest.IsInitialized());
// Extract address and amount from the request
QList<std::pair<CScript, CAmount> > sendingTos = r.paymentRequest.getPayTo();
Q_FOREACH (const PAIRTYPE(CScript, CAmount)& sendingTo, sendingTos) {
CTxDestination dest;
if (ExtractDestination(sendingTo.first, dest))
QCOMPARE(PaymentServer::verifyAmount(sendingTo.second), false);
}
delete server;
}
void RecipientCatcher::getRecipient(SendCoinsRecipient r)
{
recipient = r;
}
<commit_msg>qt-tests: Disable payment server test that moves 21M+1 coins.<commit_after>// Copyright (c) 2009-2015 The Bitcoin Core developers
// Distributed under the MIT software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
#include "paymentservertests.h"
#include "optionsmodel.h"
#include "paymentrequestdata.h"
#include "amount.h"
#include "random.h"
#include "script/script.h"
#include "script/standard.h"
#include "util.h"
#include "utilstrencodings.h"
#include <openssl/x509.h>
#include <openssl/x509_vfy.h>
#include <QFileOpenEvent>
#include <QTemporaryFile>
X509 *parse_b64der_cert(const char* cert_data)
{
std::vector<unsigned char> data = DecodeBase64(cert_data);
assert(data.size() > 0);
const unsigned char* dptr = &data[0];
X509 *cert = d2i_X509(NULL, &dptr, data.size());
assert(cert);
return cert;
}
//
// Test payment request handling
//
static SendCoinsRecipient handleRequest(PaymentServer* server, std::vector<unsigned char>& data)
{
RecipientCatcher sigCatcher;
QObject::connect(server, SIGNAL(receivedPaymentRequest(SendCoinsRecipient)),
&sigCatcher, SLOT(getRecipient(SendCoinsRecipient)));
// Write data to a temp file:
QTemporaryFile f;
f.open();
f.write((const char*)&data[0], data.size());
f.close();
// Create a QObject, install event filter from PaymentServer
// and send a file open event to the object
QObject object;
object.installEventFilter(server);
QFileOpenEvent event(f.fileName());
// If sending the event fails, this will cause sigCatcher to be empty,
// which will lead to a test failure anyway.
QCoreApplication::sendEvent(&object, &event);
QObject::disconnect(server, SIGNAL(receivedPaymentRequest(SendCoinsRecipient)),
&sigCatcher, SLOT(getRecipient(SendCoinsRecipient)));
// Return results from sigCatcher
return sigCatcher.recipient;
}
void PaymentServerTests::paymentServerTests()
{
SelectParams(CBaseChainParams::MAIN);
OptionsModel optionsModel;
PaymentServer* server = new PaymentServer(NULL, false);
X509_STORE* caStore = X509_STORE_new();
X509_STORE_add_cert(caStore, parse_b64der_cert(caCert1_BASE64));
PaymentServer::LoadRootCAs(caStore);
server->setOptionsModel(&optionsModel);
server->uiReady();
std::vector<unsigned char> data;
SendCoinsRecipient r;
QString merchant;
// Now feed PaymentRequests to server, and observe signals it produces
// Dogecoin: Disable certificate tests as we don't touch this code, and building test
// data would take significant effort. Also pending discussion on spec
// This payment request validates directly against the
// caCert1 certificate authority:
/* data = DecodeBase64(paymentrequest1_cert1_BASE64);
r = handleRequest(server, data);
r.paymentRequest.getMerchant(caStore, merchant);
QCOMPARE(merchant, QString("testmerchant.org"));
// Signed, but expired, merchant cert in the request:
data = DecodeBase64(paymentrequest2_cert1_BASE64);
r = handleRequest(server, data);
r.paymentRequest.getMerchant(caStore, merchant);
QCOMPARE(merchant, QString(""));
// 10-long certificate chain, all intermediates valid:
data = DecodeBase64(paymentrequest3_cert1_BASE64);
r = handleRequest(server, data);
r.paymentRequest.getMerchant(caStore, merchant);
QCOMPARE(merchant, QString("testmerchant8.org"));
// Long certificate chain, with an expired certificate in the middle:
data = DecodeBase64(paymentrequest4_cert1_BASE64);
r = handleRequest(server, data);
r.paymentRequest.getMerchant(caStore, merchant);
QCOMPARE(merchant, QString(""));
// Validly signed, but by a CA not in our root CA list:
data = DecodeBase64(paymentrequest5_cert1_BASE64);
r = handleRequest(server, data);
r.paymentRequest.getMerchant(caStore, merchant);
QCOMPARE(merchant, QString(""));
// Try again with no root CA's, verifiedMerchant should be empty:
caStore = X509_STORE_new();
PaymentServer::LoadRootCAs(caStore);
data = DecodeBase64(paymentrequest1_cert1_BASE64);
r = handleRequest(server, data);
r.paymentRequest.getMerchant(caStore, merchant);
QCOMPARE(merchant, QString(""));
// Load second root certificate
caStore = X509_STORE_new();
X509_STORE_add_cert(caStore, parse_b64der_cert(caCert2_BASE64));
PaymentServer::LoadRootCAs(caStore); */
QByteArray byteArray;
// For the tests below we just need the payment request data from
// paymentrequestdata.h parsed + stored in r.paymentRequest.
//
// These tests require us to bypass the following normal client execution flow
// shown below to be able to explicitly just trigger a certain condition!
//
// handleRequest()
// -> PaymentServer::eventFilter()
// -> PaymentServer::handleURIOrFile()
// -> PaymentServer::readPaymentRequestFromFile()
// -> PaymentServer::processPaymentRequest()
// Contains a testnet paytoaddress, so payment request network doesn't match client network:
data = DecodeBase64(paymentrequest1_cert2_BASE64);
byteArray = QByteArray((const char*)&data[0], data.size());
r.paymentRequest.parse(byteArray);
// Ensure the request is initialized, because network "main" is default, even for
// uninizialized payment requests and that will fail our test here.
QVERIFY(r.paymentRequest.IsInitialized());
QCOMPARE(PaymentServer::verifyNetwork(r.paymentRequest.getDetails()), false);
// Expired payment request (expires is set to 1 = 1970-01-01 00:00:01):
data = DecodeBase64(paymentrequest2_cert2_BASE64);
byteArray = QByteArray((const char*)&data[0], data.size());
r.paymentRequest.parse(byteArray);
// Ensure the request is initialized
QVERIFY(r.paymentRequest.IsInitialized());
// compares 1 < GetTime() == false (treated as expired payment request)
QCOMPARE(PaymentServer::verifyExpired(r.paymentRequest.getDetails()), true);
// Unexpired payment request (expires is set to 0x7FFFFFFFFFFFFFFF = max. int64_t):
// 9223372036854775807 (uint64), 9223372036854775807 (int64_t) and -1 (int32_t)
// -1 is 1969-12-31 23:59:59 (for a 32 bit time values)
data = DecodeBase64(paymentrequest3_cert2_BASE64);
byteArray = QByteArray((const char*)&data[0], data.size());
r.paymentRequest.parse(byteArray);
// Ensure the request is initialized
QVERIFY(r.paymentRequest.IsInitialized());
// compares 9223372036854775807 < GetTime() == false (treated as unexpired payment request)
QCOMPARE(PaymentServer::verifyExpired(r.paymentRequest.getDetails()), false);
// Unexpired payment request (expires is set to 0x8000000000000000 > max. int64_t, allowed uint64):
// 9223372036854775808 (uint64), -9223372036854775808 (int64_t) and 0 (int32_t)
// 0 is 1970-01-01 00:00:00 (for a 32 bit time values)
data = DecodeBase64(paymentrequest4_cert2_BASE64);
byteArray = QByteArray((const char*)&data[0], data.size());
r.paymentRequest.parse(byteArray);
// Ensure the request is initialized
QVERIFY(r.paymentRequest.IsInitialized());
// compares -9223372036854775808 < GetTime() == true (treated as expired payment request)
QCOMPARE(PaymentServer::verifyExpired(r.paymentRequest.getDetails()), true);
// Test BIP70 DoS protection:
unsigned char randData[BIP70_MAX_PAYMENTREQUEST_SIZE + 1];
GetRandBytes(randData, sizeof(randData));
// Write data to a temp file:
QTemporaryFile tempFile;
tempFile.open();
tempFile.write((const char*)randData, sizeof(randData));
tempFile.close();
// compares 50001 <= BIP70_MAX_PAYMENTREQUEST_SIZE == false
QCOMPARE(PaymentServer::verifySize(tempFile.size()), false);
// Payment request with amount overflow (amount is set to 21000001 BTC):
/* PL: This doesn't work for Dogecoin (as there is no actual maximum coins)
* I'm disabling this test for now.
data = DecodeBase64(paymentrequest5_cert2_BASE64);
byteArray = QByteArray((const char*)&data[0], data.size());
r.paymentRequest.parse(byteArray);
// Ensure the request is initialized
QVERIFY(r.paymentRequest.IsInitialized());
// Extract address and amount from the request
QList<std::pair<CScript, CAmount> > sendingTos = r.paymentRequest.getPayTo();
Q_FOREACH (const PAIRTYPE(CScript, CAmount)& sendingTo, sendingTos) {
CTxDestination dest;
if (ExtractDestination(sendingTo.first, dest))
QCOMPARE(PaymentServer::verifyAmount(sendingTo.second), false);
}
*/
delete server;
}
void RecipientCatcher::getRecipient(SendCoinsRecipient r)
{
recipient = r;
}
<|endoftext|> |
<commit_before>/******************************************************************************
* ____ _ _____ *
* / ___| / \ | ___| C++ *
* | | / _ \ | |_ Actor *
* | |___ / ___ \| _| Framework *
* \____/_/ \_|_| *
* *
* Copyright 2011-2018 Dominik Charousset *
* *
* Distributed under the terms and conditions of the BSD 3-Clause License or *
* (at your option) under the terms and conditions of the Boost Software *
* License 1.0. See accompanying files LICENSE and LICENSE_ALTERNATIVE. *
* *
* If you did not receive a copy of the license files, see *
* http://opensource.org/licenses/BSD-3-Clause and *
* http://www.boost.org/LICENSE_1_0.txt. *
******************************************************************************/
#pragma once
#include <chrono>
#include <cstddef>
#include <string>
#include <vector>
#include "caf/atom.hpp"
#include "caf/string_view.hpp"
#include "caf/timestamp.hpp"
// -- hard-coded default values for various CAF options ------------------------
namespace caf {
namespace defaults {
namespace stream {
extern const timespan desired_batch_complexity;
extern const timespan max_batch_delay;
extern const timespan credit_round_interval;
} // namespace streaming
namespace scheduler {
extern const atom_value policy;
extern string_view profiling_output_file;
extern const size_t max_threads;
extern const size_t max_throughput;
extern const timespan profiling_resolution;
} // namespace scheduler
namespace work_stealing {
extern const size_t aggressive_poll_attempts;
extern const size_t aggressive_steal_interval;
extern const size_t moderate_poll_attempts;
extern const size_t moderate_steal_interval;
extern const timespan moderate_sleep_duration;
extern const size_t relaxed_steal_interval;
extern const timespan relaxed_sleep_duration;
} // namespace work_stealing
namespace logger {
extern string_view component_filter;
extern const atom_value console;
extern string_view console_format;
extern const atom_value console_verbosity;
extern string_view file_format;
extern string_view file_name;
extern const atom_value file_verbosity;
} // namespace logger
namespace middleman {
extern std::vector<std::string> app_identifiers;
extern const atom_value network_backend;
extern const size_t max_consecutive_reads;
extern const size_t heartbeat_interval;
extern const size_t cached_udp_buffers;
extern const size_t max_pending_msgs;
extern const size_t workers;
} // namespace middleman
} // namespace defaults
} // namespace caf
<commit_msg>Mark hardcoded defaults as explicitly visible<commit_after>/******************************************************************************
* ____ _ _____ *
* / ___| / \ | ___| C++ *
* | | / _ \ | |_ Actor *
* | |___ / ___ \| _| Framework *
* \____/_/ \_|_| *
* *
* Copyright 2011-2018 Dominik Charousset *
* *
* Distributed under the terms and conditions of the BSD 3-Clause License or *
* (at your option) under the terms and conditions of the Boost Software *
* License 1.0. See accompanying files LICENSE and LICENSE_ALTERNATIVE. *
* *
* If you did not receive a copy of the license files, see *
* http://opensource.org/licenses/BSD-3-Clause and *
* http://www.boost.org/LICENSE_1_0.txt. *
******************************************************************************/
#pragma once
#include <chrono>
#include <cstddef>
#include <string>
#include <vector>
#include "caf/config.hpp"
#include "caf/atom.hpp"
#include "caf/string_view.hpp"
#include "caf/timestamp.hpp"
// -- hard-coded default values for various CAF options ------------------------
namespace caf {
namespace defaults {
namespace stream {
extern CAF_API const timespan desired_batch_complexity;
extern CAF_API const timespan max_batch_delay;
extern CAF_API const timespan credit_round_interval;
} // namespace streaming
namespace scheduler {
extern CAF_API const atom_value policy;
extern CAF_API string_view profiling_output_file;
extern CAF_API const size_t max_threads;
extern CAF_API const size_t max_throughput;
extern CAF_API const timespan profiling_resolution;
} // namespace scheduler
namespace work_stealing {
extern CAF_API const size_t aggressive_poll_attempts;
extern CAF_API const size_t aggressive_steal_interval;
extern CAF_API const size_t moderate_poll_attempts;
extern CAF_API const size_t moderate_steal_interval;
extern CAF_API const timespan moderate_sleep_duration;
extern CAF_API const size_t relaxed_steal_interval;
extern CAF_API const timespan relaxed_sleep_duration;
} // namespace work_stealing
namespace logger {
extern CAF_API string_view component_filter;
extern CAF_API const atom_value console;
extern CAF_API string_view console_format;
extern CAF_API const atom_value console_verbosity;
extern CAF_API string_view file_format;
extern CAF_API string_view file_name;
extern CAF_API const atom_value file_verbosity;
} // namespace logger
namespace middleman {
extern CAF_API std::vector<std::string> app_identifiers;
extern CAF_API const atom_value network_backend;
extern CAF_API const size_t max_consecutive_reads;
extern CAF_API const size_t heartbeat_interval;
extern CAF_API const size_t cached_udp_buffers;
extern CAF_API const size_t max_pending_msgs;
extern CAF_API const size_t workers;
} // namespace middleman
} // namespace defaults
} // namespace caf
<|endoftext|> |
<commit_before>/*
* cf. M. Hjorth-Jensen, Computational Physics, University of Oslo (2015)
* http://www.mn.uio.no/fysikk/english/people/aca/mhjensen/
* Ernest Yeung (I typed it up and made modifications)
* ernestyalumni@gmail.com
* MIT License
* cf. Chapter 3 Numerical differentiation and interpolation
* 3.1 Numerical Differentiation
* 3.1.1.1 Initializations and main program
*/
/*
** Program to compute the second derivative of exp(x).
** Three calling functions are included
** in this version. In one function we read in the data from screen,
** the next function computes the second derivative
** while the last function prints out data to screen.
*/
using namespace std;
#include <iostream>
void initialize(double *, double *, int *);
void second_derivative(int, double, double, double *, double *);
void output(double *, double *, double, int);
int main()
{
// declarations of variables
int number_of_steps;
double x, initial_step;
double *h_step, *computed_derivative;
// read in input data from screen
initialize(&initial_step, &x, &number_of_steps);
// allocate space in memory for the one-dimensional arrays
// h_step and computed_derivative
h_step = new double[number_of_steps];
computed_derivative = new double[number_of_steps];
// compute the second derivative of exp(x)
second_derivative(number_of_steps, x, initial_step, h_step, computed_derivative);
// Then we print the results to file
output(h_step, computed_derivative, x, number_of_steps);
// free memory
delete [] h_step;
delete [] computed_derivative;
return 0;
} // end main program
<commit_msg>program1.cpp compiles and works<commit_after>/*
* cf. M. Hjorth-Jensen, Computational Physics, University of Oslo (2015)
* http://www.mn.uio.no/fysikk/english/people/aca/mhjensen/
* Ernest Yeung (I typed it up and made modifications)
* ernestyalumni@gmail.com
* MIT License
* cf. Chapter 3 Numerical differentiation and interpolation
* 3.1 Numerical Differentiation
* 3.1.1.1 Initializations and main program
*/
/*
** Program to compute the second derivative of exp(x).
** Three calling functions are included
** in this version. In one function we read in the data from screen,
** the next function computes the second derivative
** while the last function prints out data to screen.
*/
/*
** Big note - at least to me, program1.cpp in pp. 51 of Hjorth-Jensen's notes
** code appears incomplete, and wouldn't compile (I don't think). I looked here:
** https://github.com/CompPhysics/ComputationalPhysicsMSU/blob/master/doc/Programs/LecturePrograms/programs/Classes/cpp/program1.cpp
** and the entire code for program1.cpp appears there
*/
using namespace std;
// #include <iostream> I don't think this is correct of Hjorth-Jensen since printf,scanf are used
#include <stdio.h>
#include <cmath>
void initialize(double *, double *, int *);
void second_derivative(int, double, double, double *, double *);
void output(double *, double *, double, int);
int main()
{
// declarations of variables
int number_of_steps;
double x, initial_step;
double *h_step, *computed_derivative;
// read in input data from screen
initialize(&initial_step, &x, &number_of_steps);
// allocate space in memory for the one-dimensional arrays
// h_step and computed_derivative
h_step = new double[number_of_steps];
computed_derivative = new double[number_of_steps];
// compute the second derivative of exp(x)
second_derivative(number_of_steps, x, initial_step, h_step, computed_derivative);
// Then we print the results to file
output(h_step, computed_derivative, x, number_of_steps);
// free memory
delete [] h_step;
delete [] computed_derivative;
return 0;
} // end main program
// Read in from screen the air temp, the number of steps
// final time and the initial temperature */
void initialize(double *initial_step, double *x, int *number_of_steps)
{
printf("Read in from screen initial step, x, and number of steps\n");
scanf("%lf %lf %d", initial_step, x, number_of_steps);
return;
} // end of function initialize
// This function computes the second derivative
void second_derivative( int number_of_steps, double x, double initial_step,
double *h_step, double *computed_derivative)
{
int counter;
double h;
// calculate the step size
// initialize the derivative, y and x (in minutes)
// and iteration counter
h = initial_step;
// start computing for different step sizes
for (counter=0; counter < number_of_steps; counter++ )
{
// setup arrays with derivatives and step sizes
h_step[counter] = h;
computed_derivative[counter] =
(exp(x+h)-2.*exp(x) + exp(x-h))/(h*h);
h = h*0.5;
} // end of do loop
return;
} // end of function second derivative
// function to write out the final results
void output(double *h_step, double *computed_derivative, double x,
int number_of_steps)
{
int i;
FILE *output_file;
output_file = fopen("out.dat", "w");
for (i=0; i < number_of_steps; i++)
{
fprintf(output_file, "%12.5E %12.5E \n",
log10(h_step[i]),log10(fabs(computed_derivative[i]-exp(x))/exp(x)));
}
fclose(output_file);
} // end of function output
<|endoftext|> |
<commit_before>/****************************************************************************
**
** Copyright (C) 2008 Nokia Corporation and/or its subsidiary(-ies).
** Contact: Qt Software Information (qt-info@nokia.com)
**
** This file is part of the examples of the Qt Toolkit.
**
** $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 either Technology Preview License Agreement or the
** Beta Release License Agreement.
**
** 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.0, included in the file LGPL_EXCEPTION.txt in this
** package.
**
** GNU General Public License Usage
** Alternatively, this file may be used under the terms of the GNU
** General Public License version 3.0 as published by the Free Software
** Foundation and appearing in the file LICENSE.GPL included in the
** packaging of this file. Please review the following information to
** ensure the GNU General Public License version 3.0 requirements will be
** met: http://www.gnu.org/copyleft/gpl.html.
**
** If you are unsure which license is appropriate for your use, please
** contact the sales department at qt-sales@nokia.com.
** $QT_END_LICENSE$
**
****************************************************************************/
#include "mainwindow.h"
#include "stationdialog.h"
#include <QtCore/QSettings>
#include <QtCore/QTimer>
#include <QtGui/QAction>
#include <QtGui/QApplication>
#include <QtGui/QBitmap>
#include <QtGui/QLinearGradient>
#include <QtGui/QMouseEvent>
#include <QtGui/QPainter>
MainWindow::MainWindow()
: QWidget(0, Qt::FramelessWindowHint | Qt::WindowStaysOnTopHint)
{
QAction *quitAction = new QAction(tr("E&xit"), this);
quitAction->setShortcut(tr("Ctrl+Q"));
connect(quitAction, SIGNAL(triggered()), qApp, SLOT(quit()));
QAction *configAction = new QAction(tr("&Select station..."), this);
configAction->setShortcut(tr("Ctrl+C"));
connect(configAction, SIGNAL(triggered()), this, SLOT(configure()));
addAction(configAction);
addAction(quitAction);
setContextMenuPolicy(Qt::ActionsContextMenu);
setWindowTitle(tr("Traffic Info Oslo"));
QTimer *timer = new QTimer(this);
connect(timer, SIGNAL(timeout()), this, SLOT(updateTimeInformation()));
timer->start(1000*60);
const QSettings settings("Qt Software", "trafficinfo");
m_station = StationInformation(settings.value("stationId", "03012130").toString(),
settings.value("stationName", "Nydalen [T-bane] (OSL)").toString());
m_lines = settings.value("lines", QStringList()).toStringList();
updateTimeInformation();
}
MainWindow::~MainWindow()
{
QSettings settings("Qt Software", "trafficinfo");
settings.setValue("stationId", m_station.id());
settings.setValue("stationName", m_station.name());
settings.setValue("lines", m_lines);
}
QSize MainWindow::sizeHint() const
{
return QSize(300, 200);
}
void MainWindow::mouseMoveEvent(QMouseEvent *event)
{
if (event->buttons() & Qt::LeftButton) {
move(event->globalPos() - m_dragPosition);
event->accept();
}
}
void MainWindow::mousePressEvent(QMouseEvent *event)
{
if (event->button() == Qt::LeftButton) {
m_dragPosition = event->globalPos() - frameGeometry().topLeft();
event->accept();
}
}
void MainWindow::paintEvent(QPaintEvent*)
{
QLinearGradient gradient(QPoint(width()/2, 0), QPoint(width()/2, height()));
const QColor qtGreen(102, 176, 54);
gradient.setColorAt(0, qtGreen.dark());
gradient.setColorAt(0.5, qtGreen);
gradient.setColorAt(1, qtGreen.dark());
QPainter p(this);
p.fillRect(0, 0, width(), height(), gradient);
QFont headerFont("Sans Serif", 12, QFont::Bold);
QFont normalFont("Sans Serif", 9, QFont::Normal);
// draw it twice for shadow effect
p.setFont(headerFont);
QRect headerRect(1, 1, width(), 25);
p.setPen(Qt::black);
p.drawText(headerRect, Qt::AlignCenter, m_station.name());
headerRect.moveTopLeft(QPoint(0, 0));
p.setPen(Qt::white);
p.drawText(headerRect, Qt::AlignCenter, m_station.name());
p.setFont(normalFont);
int pos = 40;
for (int i = 0; i < m_times.count() && i < 9; ++i) {
p.setPen(Qt::black);
p.drawText(51, pos + 1, m_times.at(i).time());
p.drawText(101, pos + 1, m_times.at(i).direction());
p.setPen(Qt::white);
p.drawText(50, pos, m_times.at(i).time());
p.drawText(100, pos, m_times.at(i).direction());
pos += 18;
}
}
void MainWindow::resizeEvent(QResizeEvent*)
{
QBitmap maskBitmap(width(), height());
maskBitmap.clear();
QPainter p(&maskBitmap);
p.setBrush(Qt::black);
p.drawRoundRect(0, 0, width(), height(), 20, 30);
p.end();
setMask(maskBitmap);
}
void MainWindow::updateTimeInformation()
{
TimeQuery query;
m_times = query.query(m_station.id(), m_lines, QDateTime::currentDateTime());
update();
}
void MainWindow::configure()
{
StationDialog dlg(m_station.name(), m_lines, this);
if (dlg.exec()) {
m_station = dlg.selectedStation();
m_lines = dlg.lineNumbers();
updateTimeInformation();
}
}
<commit_msg>Make the traffic info example not hit the server every minute.<commit_after>/****************************************************************************
**
** Copyright (C) 2008 Nokia Corporation and/or its subsidiary(-ies).
** Contact: Qt Software Information (qt-info@nokia.com)
**
** This file is part of the examples of the Qt Toolkit.
**
** $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 either Technology Preview License Agreement or the
** Beta Release License Agreement.
**
** 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.0, included in the file LGPL_EXCEPTION.txt in this
** package.
**
** GNU General Public License Usage
** Alternatively, this file may be used under the terms of the GNU
** General Public License version 3.0 as published by the Free Software
** Foundation and appearing in the file LICENSE.GPL included in the
** packaging of this file. Please review the following information to
** ensure the GNU General Public License version 3.0 requirements will be
** met: http://www.gnu.org/copyleft/gpl.html.
**
** If you are unsure which license is appropriate for your use, please
** contact the sales department at qt-sales@nokia.com.
** $QT_END_LICENSE$
**
****************************************************************************/
#include "mainwindow.h"
#include "stationdialog.h"
#include <QtCore/QSettings>
#include <QtCore/QTimer>
#include <QtGui/QAction>
#include <QtGui/QApplication>
#include <QtGui/QBitmap>
#include <QtGui/QLinearGradient>
#include <QtGui/QMouseEvent>
#include <QtGui/QPainter>
MainWindow::MainWindow()
: QWidget(0, Qt::FramelessWindowHint | Qt::WindowStaysOnTopHint)
{
QAction *quitAction = new QAction(tr("E&xit"), this);
quitAction->setShortcut(tr("Ctrl+Q"));
connect(quitAction, SIGNAL(triggered()), qApp, SLOT(quit()));
QAction *configAction = new QAction(tr("&Select station..."), this);
configAction->setShortcut(tr("Ctrl+C"));
connect(configAction, SIGNAL(triggered()), this, SLOT(configure()));
addAction(configAction);
addAction(quitAction);
setContextMenuPolicy(Qt::ActionsContextMenu);
setWindowTitle(tr("Traffic Info Oslo"));
QTimer *timer = new QTimer(this);
connect(timer, SIGNAL(timeout()), this, SLOT(updateTimeInformation()));
timer->start(1000*60*5);
const QSettings settings("Qt Software", "trafficinfo");
m_station = StationInformation(settings.value("stationId", "03012130").toString(),
settings.value("stationName", "Nydalen [T-bane] (OSL)").toString());
m_lines = settings.value("lines", QStringList()).toStringList();
updateTimeInformation();
}
MainWindow::~MainWindow()
{
QSettings settings("Qt Software", "trafficinfo");
settings.setValue("stationId", m_station.id());
settings.setValue("stationName", m_station.name());
settings.setValue("lines", m_lines);
}
QSize MainWindow::sizeHint() const
{
return QSize(300, 200);
}
void MainWindow::mouseMoveEvent(QMouseEvent *event)
{
if (event->buttons() & Qt::LeftButton) {
move(event->globalPos() - m_dragPosition);
event->accept();
}
}
void MainWindow::mousePressEvent(QMouseEvent *event)
{
if (event->button() == Qt::LeftButton) {
m_dragPosition = event->globalPos() - frameGeometry().topLeft();
event->accept();
}
}
void MainWindow::paintEvent(QPaintEvent*)
{
QLinearGradient gradient(QPoint(width()/2, 0), QPoint(width()/2, height()));
const QColor qtGreen(102, 176, 54);
gradient.setColorAt(0, qtGreen.dark());
gradient.setColorAt(0.5, qtGreen);
gradient.setColorAt(1, qtGreen.dark());
QPainter p(this);
p.fillRect(0, 0, width(), height(), gradient);
QFont headerFont("Sans Serif", 12, QFont::Bold);
QFont normalFont("Sans Serif", 9, QFont::Normal);
// draw it twice for shadow effect
p.setFont(headerFont);
QRect headerRect(1, 1, width(), 25);
p.setPen(Qt::black);
p.drawText(headerRect, Qt::AlignCenter, m_station.name());
headerRect.moveTopLeft(QPoint(0, 0));
p.setPen(Qt::white);
p.drawText(headerRect, Qt::AlignCenter, m_station.name());
p.setFont(normalFont);
int pos = 40;
for (int i = 0; i < m_times.count() && i < 9; ++i) {
p.setPen(Qt::black);
p.drawText(51, pos + 1, m_times.at(i).time());
p.drawText(101, pos + 1, m_times.at(i).direction());
p.setPen(Qt::white);
p.drawText(50, pos, m_times.at(i).time());
p.drawText(100, pos, m_times.at(i).direction());
pos += 18;
}
}
void MainWindow::resizeEvent(QResizeEvent*)
{
QBitmap maskBitmap(width(), height());
maskBitmap.clear();
QPainter p(&maskBitmap);
p.setBrush(Qt::black);
p.drawRoundRect(0, 0, width(), height(), 20, 30);
p.end();
setMask(maskBitmap);
}
void MainWindow::updateTimeInformation()
{
TimeQuery query;
m_times = query.query(m_station.id(), m_lines, QDateTime::currentDateTime());
update();
}
void MainWindow::configure()
{
StationDialog dlg(m_station.name(), m_lines, this);
if (dlg.exec()) {
m_station = dlg.selectedStation();
m_lines = dlg.lineNumbers();
updateTimeInformation();
}
}
<|endoftext|> |
<commit_before>/*
This file is part of cpp-ethereum.
cpp-ethereum 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.
cpp-ethereum 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 cpp-ethereum. If not, see <http://www.gnu.org/licenses/>.
*/
/** @file EthereumHost.cpp
* @author Gav Wood <i@gavwood.com>
* @date 2014
*/
#include "EthereumHost.h"
#include <set>
#include <chrono>
#include <thread>
#include <libdevcore/Common.h>
#include <libp2p/Host.h>
#include <libp2p/Session.h>
#include <libethcore/Exceptions.h>
#include "BlockChain.h"
#include "TransactionQueue.h"
#include "BlockQueue.h"
#include "EthereumPeer.h"
#include "DownloadMan.h"
using namespace std;
using namespace dev;
using namespace dev::eth;
using namespace p2p;
EthereumHost::EthereumHost(BlockChain const& _ch, TransactionQueue& _tq, BlockQueue& _bq, u256 _networkId):
HostCapability<EthereumPeer>(),
Worker ("ethsync"),
m_chain (_ch),
m_tq (_tq),
m_bq (_bq),
m_networkId (_networkId)
{
m_latestBlockSent = _ch.currentHash();
}
EthereumHost::~EthereumHost()
{
for (auto i: peerSessions())
i.first->cap<EthereumPeer>().get()->abortSync();
}
bool EthereumHost::ensureInitialised()
{
if (!m_latestBlockSent)
{
// First time - just initialise.
m_latestBlockSent = m_chain.currentHash();
clog(NetNote) << "Initialising: latest=" << m_latestBlockSent.abridged();
for (auto const& i: m_tq.transactions())
m_transactionsSent.insert(i.first);
return true;
}
return false;
}
void EthereumHost::noteNeedsSyncing(EthereumPeer* _who)
{
// if already downloading hash-chain, ignore.
if (isSyncing())
{
clog(NetAllDetail) << "Sync in progress: Just set to help out.";
if (m_syncer->m_asking == Asking::Blocks)
_who->transition(Asking::Blocks);
}
else
// otherwise check to see if we should be downloading...
_who->attemptSync();
}
void EthereumHost::changeSyncer(EthereumPeer* _syncer)
{
if (_syncer)
clog(NetAllDetail) << "Changing syncer to" << _syncer->session()->socketId();
else
clog(NetAllDetail) << "Clearing syncer.";
m_syncer = _syncer;
if (isSyncing())
{
if (_syncer->m_asking == Asking::Blocks)
for (auto j: peerSessions())
{
auto e = j.first->cap<EthereumPeer>().get();
if (e != _syncer && e->m_asking == Asking::Nothing)
e->transition(Asking::Blocks);
}
}
else
{
// start grabbing next hash chain if there is one.
for (auto j: peerSessions())
{
j.first->cap<EthereumPeer>()->attemptSync();
if (isSyncing())
return;
}
clog(NetNote) << "No more peers to sync with.";
}
}
void EthereumHost::noteDoneBlocks(EthereumPeer* _who, bool _clemency)
{
if (m_man.isComplete())
{
// Done our chain-get.
clog(NetNote) << "Chain download complete.";
// 1/100th for each useful block hash.
_who->addRating(m_man.chain().size() / 100);
m_man.reset();
}
else if (_who->isSyncing())
{
if (_clemency)
clog(NetNote) << "Chain download failed. Aborted while incomplete.";
else
{
// Done our chain-get.
clog(NetWarn) << "Chain download failed. Peer with blocks didn't have them all. This peer is bad and should be punished.";
clog(NetWarn) << m_man.remaining();
clog(NetWarn) << "WOULD BAN.";
// m_banned.insert(_who->session()->id()); // We know who you are!
// _who->disable("Peer sent hashes but was unable to provide the blocks.");
}
m_man.reset();
}
}
void EthereumHost::reset()
{
if (m_syncer)
m_syncer->abortSync();
m_man.resetToChain(h256s());
m_latestBlockSent = h256();
m_transactionsSent.clear();
}
void EthereumHost::doWork()
{
bool netChange = ensureInitialised();
auto h = m_chain.currentHash();
// If we've finished our initial sync (including getting all the blocks into the chain so as to reduce invalid transactions), start trading transactions & blocks
if (!isSyncing() && m_chain.isKnown(m_latestBlockSent))
{
if (m_newTransactions)
{
m_newTransactions = false;
maintainTransactions();
}
if (m_newBlocks)
{
m_newBlocks = false;
maintainBlocks(h);
}
}
for (auto p: peerSessions())
if (shared_ptr<EthereumPeer> const& ep = p.first->cap<EthereumPeer>())
ep->tick();
// return netChange;
// TODO: Figure out what to do with netChange.
(void)netChange;
}
void EthereumHost::maintainTransactions()
{
// Send any new transactions.
map<std::shared_ptr<EthereumPeer>, h256s> peerTransactions;
auto ts = m_tq.transactions();
for (auto const& i: ts)
{
bool unsent = !m_transactionsSent.count(i.first);
for (auto const& p: randomSelection(25, [&](EthereumPeer* p) { return p->m_requireTransactions || (unsent && !p->m_knownTransactions.count(i.first)); }))
peerTransactions[p].push_back(i.first);
}
for (auto const& t: ts)
m_transactionsSent.insert(t.first);
for (auto p: peerSessions())
if (auto ep = p.first->cap<EthereumPeer>())
{
bytes b;
unsigned n = 0;
for (auto const& h: peerTransactions[ep])
{
ep->m_knownTransactions.insert(h);
b += ts[h].rlp();
++n;
}
ep->clearKnownTransactions();
if (n || ep->m_requireTransactions)
{
RLPStream ts;
ep->prep(ts, TransactionsPacket, n).appendRaw(b, n);
ep->sealAndSend(ts);
}
ep->m_requireTransactions = false;
}
}
std::vector<std::shared_ptr<EthereumPeer>> EthereumHost::randomSelection(unsigned _percent, std::function<bool(EthereumPeer*)> const& _allow)
{
std::vector<std::shared_ptr<EthereumPeer>> candidates;
candidates.reserve(peerSessions().size());
for (auto const& j: peerSessions())
{
auto pp = j.first->cap<EthereumPeer>();
if (_allow(pp.get()))
candidates.push_back(pp);
}
std::vector<std::shared_ptr<EthereumPeer>> ret;
for (unsigned i = (peerSessions().size() * _percent + 99) / 100; i-- && candidates.size();)
{
unsigned n = rand() % candidates.size();
ret.push_back(std::move(candidates[n]));
candidates.erase(candidates.begin() + n);
}
return ret;
}
void EthereumHost::maintainBlocks(h256 _currentHash)
{
// Send any new blocks.
auto detailsFrom = m_chain.details(m_latestBlockSent);
auto detailsTo = m_chain.details(_currentHash);
if (detailsFrom.totalDifficulty < detailsTo.totalDifficulty)
{
if (diff(detailsFrom.number, detailsTo.number) < 20)
{
// don't be sending more than 20 "new" blocks. if there are any more we were probably waaaay behind.
clog(NetMessageSummary) << "Sending a new block (current is" << _currentHash << ", was" << m_latestBlockSent << ")";
h256s blocks = get<0>(m_chain.treeRoute(m_latestBlockSent, _currentHash, false, false, true));
for (auto const& p: randomSelection(25, [&](EthereumPeer* p){return !p->m_knownBlocks.count(_currentHash); }))
for (auto const& b: blocks)
if (!p->m_knownBlocks.count(b))
{
RLPStream ts;
p->prep(ts, NewBlockPacket, 2).appendRaw(m_chain.block(b), 1).append(m_chain.details(b).totalDifficulty);
Guard l(p->x_knownBlocks);
p->sealAndSend(ts);
p->m_knownBlocks.clear();
}
}
m_latestBlockSent = _currentHash;
}
}
<commit_msg>Broadcast everything to everyone.<commit_after>/*
This file is part of cpp-ethereum.
cpp-ethereum 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.
cpp-ethereum 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 cpp-ethereum. If not, see <http://www.gnu.org/licenses/>.
*/
/** @file EthereumHost.cpp
* @author Gav Wood <i@gavwood.com>
* @date 2014
*/
#include "EthereumHost.h"
#include <set>
#include <chrono>
#include <thread>
#include <libdevcore/Common.h>
#include <libp2p/Host.h>
#include <libp2p/Session.h>
#include <libethcore/Exceptions.h>
#include "BlockChain.h"
#include "TransactionQueue.h"
#include "BlockQueue.h"
#include "EthereumPeer.h"
#include "DownloadMan.h"
using namespace std;
using namespace dev;
using namespace dev::eth;
using namespace p2p;
EthereumHost::EthereumHost(BlockChain const& _ch, TransactionQueue& _tq, BlockQueue& _bq, u256 _networkId):
HostCapability<EthereumPeer>(),
Worker ("ethsync"),
m_chain (_ch),
m_tq (_tq),
m_bq (_bq),
m_networkId (_networkId)
{
m_latestBlockSent = _ch.currentHash();
}
EthereumHost::~EthereumHost()
{
for (auto i: peerSessions())
i.first->cap<EthereumPeer>().get()->abortSync();
}
bool EthereumHost::ensureInitialised()
{
if (!m_latestBlockSent)
{
// First time - just initialise.
m_latestBlockSent = m_chain.currentHash();
clog(NetNote) << "Initialising: latest=" << m_latestBlockSent.abridged();
for (auto const& i: m_tq.transactions())
m_transactionsSent.insert(i.first);
return true;
}
return false;
}
void EthereumHost::noteNeedsSyncing(EthereumPeer* _who)
{
// if already downloading hash-chain, ignore.
if (isSyncing())
{
clog(NetAllDetail) << "Sync in progress: Just set to help out.";
if (m_syncer->m_asking == Asking::Blocks)
_who->transition(Asking::Blocks);
}
else
// otherwise check to see if we should be downloading...
_who->attemptSync();
}
void EthereumHost::changeSyncer(EthereumPeer* _syncer)
{
if (_syncer)
clog(NetAllDetail) << "Changing syncer to" << _syncer->session()->socketId();
else
clog(NetAllDetail) << "Clearing syncer.";
m_syncer = _syncer;
if (isSyncing())
{
if (_syncer->m_asking == Asking::Blocks)
for (auto j: peerSessions())
{
auto e = j.first->cap<EthereumPeer>().get();
if (e != _syncer && e->m_asking == Asking::Nothing)
e->transition(Asking::Blocks);
}
}
else
{
// start grabbing next hash chain if there is one.
for (auto j: peerSessions())
{
j.first->cap<EthereumPeer>()->attemptSync();
if (isSyncing())
return;
}
clog(NetNote) << "No more peers to sync with.";
}
}
void EthereumHost::noteDoneBlocks(EthereumPeer* _who, bool _clemency)
{
if (m_man.isComplete())
{
// Done our chain-get.
clog(NetNote) << "Chain download complete.";
// 1/100th for each useful block hash.
_who->addRating(m_man.chain().size() / 100);
m_man.reset();
}
else if (_who->isSyncing())
{
if (_clemency)
clog(NetNote) << "Chain download failed. Aborted while incomplete.";
else
{
// Done our chain-get.
clog(NetWarn) << "Chain download failed. Peer with blocks didn't have them all. This peer is bad and should be punished.";
clog(NetWarn) << m_man.remaining();
clog(NetWarn) << "WOULD BAN.";
// m_banned.insert(_who->session()->id()); // We know who you are!
// _who->disable("Peer sent hashes but was unable to provide the blocks.");
}
m_man.reset();
}
}
void EthereumHost::reset()
{
if (m_syncer)
m_syncer->abortSync();
m_man.resetToChain(h256s());
m_latestBlockSent = h256();
m_transactionsSent.clear();
}
void EthereumHost::doWork()
{
bool netChange = ensureInitialised();
auto h = m_chain.currentHash();
// If we've finished our initial sync (including getting all the blocks into the chain so as to reduce invalid transactions), start trading transactions & blocks
if (!isSyncing() && m_chain.isKnown(m_latestBlockSent))
{
if (m_newTransactions)
{
m_newTransactions = false;
maintainTransactions();
}
if (m_newBlocks)
{
m_newBlocks = false;
maintainBlocks(h);
}
}
for (auto p: peerSessions())
if (shared_ptr<EthereumPeer> const& ep = p.first->cap<EthereumPeer>())
ep->tick();
// return netChange;
// TODO: Figure out what to do with netChange.
(void)netChange;
}
void EthereumHost::maintainTransactions()
{
// Send any new transactions.
map<std::shared_ptr<EthereumPeer>, h256s> peerTransactions;
auto ts = m_tq.transactions();
for (auto const& i: ts)
{
bool unsent = !m_transactionsSent.count(i.first);
for (auto const& p: randomSelection(100, [&](EthereumPeer* p) { return p->m_requireTransactions || (unsent && !p->m_knownTransactions.count(i.first)); }))
peerTransactions[p].push_back(i.first);
}
for (auto const& t: ts)
m_transactionsSent.insert(t.first);
for (auto p: peerSessions())
if (auto ep = p.first->cap<EthereumPeer>())
{
bytes b;
unsigned n = 0;
for (auto const& h: peerTransactions[ep])
{
ep->m_knownTransactions.insert(h);
b += ts[h].rlp();
++n;
}
ep->clearKnownTransactions();
if (n || ep->m_requireTransactions)
{
RLPStream ts;
ep->prep(ts, TransactionsPacket, n).appendRaw(b, n);
ep->sealAndSend(ts);
}
ep->m_requireTransactions = false;
}
}
std::vector<std::shared_ptr<EthereumPeer>> EthereumHost::randomSelection(unsigned _percent, std::function<bool(EthereumPeer*)> const& _allow)
{
std::vector<std::shared_ptr<EthereumPeer>> candidates;
candidates.reserve(peerSessions().size());
for (auto const& j: peerSessions())
{
auto pp = j.first->cap<EthereumPeer>();
if (_allow(pp.get()))
candidates.push_back(pp);
}
std::vector<std::shared_ptr<EthereumPeer>> ret;
for (unsigned i = (peerSessions().size() * _percent + 99) / 100; i-- && candidates.size();)
{
unsigned n = rand() % candidates.size();
ret.push_back(std::move(candidates[n]));
candidates.erase(candidates.begin() + n);
}
return ret;
}
void EthereumHost::maintainBlocks(h256 _currentHash)
{
// Send any new blocks.
auto detailsFrom = m_chain.details(m_latestBlockSent);
auto detailsTo = m_chain.details(_currentHash);
if (detailsFrom.totalDifficulty < detailsTo.totalDifficulty)
{
if (diff(detailsFrom.number, detailsTo.number) < 20)
{
// don't be sending more than 20 "new" blocks. if there are any more we were probably waaaay behind.
clog(NetMessageSummary) << "Sending a new block (current is" << _currentHash << ", was" << m_latestBlockSent << ")";
h256s blocks = get<0>(m_chain.treeRoute(m_latestBlockSent, _currentHash, false, false, true));
for (auto const& p: randomSelection(100, [&](EthereumPeer* p){return !p->m_knownBlocks.count(_currentHash); }))
for (auto const& b: blocks)
if (!p->m_knownBlocks.count(b))
{
RLPStream ts;
p->prep(ts, NewBlockPacket, 2).appendRaw(m_chain.block(b), 1).append(m_chain.details(b).totalDifficulty);
Guard l(p->x_knownBlocks);
p->sealAndSend(ts);
p->m_knownBlocks.clear();
}
}
m_latestBlockSent = _currentHash;
}
}
<|endoftext|> |
<commit_before>/*
* Copyright 2014 Milian Wolff <mail@milianw.de>
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU Library General Public License as
* published by the Free Software Foundation; either version 2 of the
* License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public
* License along with this program; if not, write to the
* Free Software Foundation, Inc.,
* 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*/
/**
* @file heaptrack_interpret.cpp
*
* @brief Interpret raw heaptrack data and add Dwarf based debug information.
*/
#include <iostream>
#include <sstream>
#include <unordered_map>
#include <vector>
#include <tuple>
#include <algorithm>
#include <stdio_ext.h>
#include <cxxabi.h>
#include <boost/algorithm/string/predicate.hpp>
#include "libbacktrace/backtrace.h"
#include "libbacktrace/internal.h"
#include "linereader.h"
using namespace std;
namespace {
string demangle(const char* function)
{
if (!function) {
return {};
} else if (function[0] != '_' || function[1] != 'Z') {
return {function};
}
string ret;
int status = 0;
char* demangled = abi::__cxa_demangle(function, 0, 0, &status);
if (demangled) {
ret = demangled;
free(demangled);
}
return ret;
}
struct AddressInformation
{
string function;
string file;
int line = 0;
};
struct Module
{
Module(uintptr_t addressStart, uintptr_t addressEnd, backtrace_state* backtraceState, size_t moduleIndex)
: addressStart(addressStart)
, addressEnd(addressEnd)
, moduleIndex(moduleIndex)
, backtraceState(backtraceState)
{
}
AddressInformation resolveAddress(uintptr_t address) const
{
AddressInformation info;
if (!backtraceState) {
return info;
}
backtrace_pcinfo(backtraceState, address,
[] (void *data, uintptr_t /*addr*/, const char *file, int line, const char *function) -> int {
auto info = reinterpret_cast<AddressInformation*>(data);
info->function = demangle(function);
info->file = file ? file : "";
info->line = line;
return 0;
}, [] (void */*data*/, const char */*msg*/, int /*errnum*/) {}, &info);
if (info.function.empty()) {
backtrace_syminfo(backtraceState, address,
[] (void *data, uintptr_t /*pc*/, const char *symname, uintptr_t /*symval*/, uintptr_t /*symsize*/) {
if (symname) {
reinterpret_cast<AddressInformation*>(data)->function = demangle(symname);
}
}, [] (void */*data*/, const char *msg, int errnum) {
cerr << "Module backtrace error (code " << errnum << "): " << msg << endl;
}, &info);
}
return info;
}
bool operator<(const Module& module) const
{
return make_tuple(addressStart, addressEnd, moduleIndex)
< make_tuple(module.addressStart, module.addressEnd, module.moduleIndex);
}
bool operator!=(const Module& module) const
{
return make_tuple(addressStart, addressEnd, moduleIndex)
!= make_tuple(module.addressStart, module.addressEnd, module.moduleIndex);
}
uintptr_t addressStart;
uintptr_t addressEnd;
size_t moduleIndex;
backtrace_state* backtraceState;
};
struct Allocation
{
// backtrace entry point
size_t ipIndex;
// number of allocations
size_t allocations;
// amount of bytes leaked
size_t leaked;
};
/**
* Information for a single call to an allocation function
*/
struct AllocationInfo
{
size_t ipIndex;
size_t size;
};
struct ResolvedIP
{
size_t moduleIndex = 0;
size_t fileIndex = 0;
size_t functionIndex = 0;
int line = 0;
};
struct AccumulatedTraceData
{
AccumulatedTraceData()
{
m_modules.reserve(256);
m_backtraceStates.reserve(64);
m_internedData.reserve(4096);
m_encounteredIps.reserve(32768);
}
~AccumulatedTraceData()
{
fprintf(stdout, "# strings: %lu\n# ips: %lu\n",
m_internedData.size(), m_encounteredIps.size());
}
ResolvedIP resolve(const uintptr_t ip)
{
if (m_modulesDirty) {
// sort by addresses, required for binary search below
sort(m_modules.begin(), m_modules.end());
for (size_t i = 0; i < m_modules.size(); ++i) {
const auto& m1 = m_modules[i];
for (size_t j = i + 1; j < m_modules.size(); ++j) {
if (i == j) {
continue;
}
const auto& m2 = m_modules[j];
if ((m1.addressStart <= m2.addressStart && m1.addressEnd > m2.addressStart) ||
(m1.addressStart < m2.addressEnd && m1.addressEnd >= m2.addressEnd))
{
cerr << "OVERLAPPING MODULES: " << hex
<< m1.moduleIndex << " (" << m1.addressStart << " to " << m1.addressEnd << ") and "
<< m1.moduleIndex << " (" << m2.addressStart << " to " << m2.addressEnd << ")\n"
<< dec;
} else if (m2.addressStart >= m1.addressEnd) {
break;
}
}
}
m_modulesDirty = false;
}
ResolvedIP data;
// find module for this instruction pointer
auto module = lower_bound(m_modules.begin(), m_modules.end(), ip,
[] (const Module& module, const uintptr_t ip) -> bool {
return module.addressEnd < ip;
});
if (module != m_modules.end() && module->addressStart <= ip && module->addressEnd >= ip) {
data.moduleIndex = module->moduleIndex;
const auto info = module->resolveAddress(ip);
data.fileIndex = intern(info.file);
data.functionIndex = intern(info.function);
data.line = info.line;
}
return data;
}
size_t intern(const string& str)
{
if (str.empty()) {
return 0;
}
auto it = m_internedData.find(str);
if (it != m_internedData.end()) {
return it->second;
}
const size_t id = m_internedData.size() + 1;
m_internedData.insert(it, make_pair(str, id));
fprintf(stdout, "s %s\n", str.c_str());
return id;
}
void addModule(backtrace_state* backtraceState, const size_t moduleIndex,
const uintptr_t addressStart, const uintptr_t addressEnd)
{
m_modules.emplace_back(addressStart, addressEnd, backtraceState, moduleIndex);
m_modulesDirty = true;
}
void clearModules()
{
// TODO: optimize this, reuse modules that are still valid
m_modules.clear();
m_modulesDirty = true;
}
size_t addIp(const uintptr_t instructionPointer)
{
if (!instructionPointer) {
return 0;
}
auto it = m_encounteredIps.find(instructionPointer);
if (it != m_encounteredIps.end()) {
return it->second;
}
const size_t ipId = m_encounteredIps.size() + 1;
m_encounteredIps.insert(it, make_pair(instructionPointer, ipId));
const auto ip = resolve(instructionPointer);
fprintf(stdout, "i %lx %lx", instructionPointer, ip.moduleIndex);
if (ip.functionIndex || ip.fileIndex) {
fprintf(stdout, " %lx", ip.functionIndex);
if (ip.fileIndex) {
fprintf(stdout, " %lx %x", ip.fileIndex, ip.line);
}
}
fputc('\n', stdout);
return ipId;
}
/**
* Prevent the same file from being initialized multiple times.
* This drastically cuts the memory consumption down
*/
backtrace_state* findBacktraceState(const string& fileName, uintptr_t addressStart, bool isExe)
{
if (boost::algorithm::starts_with(fileName, "linux-vdso.so")) {
// prevent warning, since this will always fail
return nullptr;
}
auto it = m_backtraceStates.find(fileName);
if (it != m_backtraceStates.end()) {
return it->second;
}
struct CallbackData {
const string* fileName;
};
CallbackData data = {&fileName};
auto errorHandler = [] (void *rawData, const char *msg, int errnum) {
auto data = reinterpret_cast<const CallbackData*>(rawData);
cerr << "Failed to create backtrace state for module " << *data->fileName << ": "
<< msg << " / " << strerror(errnum) << " (error code " << errnum << ")" << endl;
};
auto state = backtrace_create_state(fileName.c_str(), /* we are single threaded, so: not thread safe */ false,
errorHandler, &data);
if (state) {
const int descriptor = backtrace_open(fileName.c_str(), errorHandler, &data, nullptr);
if (descriptor >= 1) {
int foundSym = 0;
int foundDwarf = 0;
auto ret = elf_add(state, descriptor, addressStart, errorHandler, &data,
&state->fileline_fn, &foundSym, &foundDwarf, isExe);
if (ret && foundSym) {
state->syminfo_fn = &elf_syminfo;
}
}
}
m_backtraceStates.insert(it, make_pair(fileName, state));
return state;
}
private:
vector<Module> m_modules;
unordered_map<string, backtrace_state*> m_backtraceStates;
bool m_modulesDirty = false;
unordered_map<string, size_t> m_internedData;
unordered_map<uintptr_t, size_t> m_encounteredIps;
};
}
int main(int /*argc*/, char** /*argv*/)
{
// optimize: we only have a single thread
ios_base::sync_with_stdio(false);
AccumulatedTraceData data;
LineReader reader;
string exe;
__fsetlocking(stdout, FSETLOCKING_BYCALLER);
__fsetlocking(stdin, FSETLOCKING_BYCALLER);
while (reader.getLine(cin)) {
if (reader.mode() == 'x') {
reader >> exe;
} else if (reader.mode() == 'm') {
string fileName;
reader >> fileName;
if (fileName == "-") {
data.clearModules();
} else {
const bool isExe = (fileName == "x");
if (isExe) {
fileName = exe;
}
const auto moduleIndex = data.intern(fileName);
uintptr_t addressStart = 0;
if (!(reader >> addressStart)) {
cerr << "failed to parse line: " << reader.line() << endl;
return 1;
}
auto state = data.findBacktraceState(fileName, addressStart, isExe);
uintptr_t vAddr = 0;
uintptr_t memSize = 0;
while ((reader >> vAddr) && (reader >> memSize)) {
data.addModule(state, moduleIndex,
addressStart + vAddr,
addressStart + vAddr + memSize);
}
}
} else if (reader.mode() == 't') {
uintptr_t instructionPointer = 0;
size_t parentIndex = 0;
if (!(reader >> instructionPointer) || !(reader >> parentIndex)) {
cerr << "failed to parse line: " << reader.line() << endl;
return 1;
}
// ensure ip is encountered
const auto ipId = data.addIp(instructionPointer);
// trace point, map current output index to parent index
fprintf(stdout, "t %lx %lx\n", ipId, parentIndex);
} else {
fputs(reader.line().c_str(), stdout);
fputc('\n', stdout);
}
}
return 0;
}
<commit_msg>Group disabling of stdio locking code.<commit_after>/*
* Copyright 2014 Milian Wolff <mail@milianw.de>
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU Library General Public License as
* published by the Free Software Foundation; either version 2 of the
* License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public
* License along with this program; if not, write to the
* Free Software Foundation, Inc.,
* 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*/
/**
* @file heaptrack_interpret.cpp
*
* @brief Interpret raw heaptrack data and add Dwarf based debug information.
*/
#include <iostream>
#include <sstream>
#include <unordered_map>
#include <vector>
#include <tuple>
#include <algorithm>
#include <stdio_ext.h>
#include <cxxabi.h>
#include <boost/algorithm/string/predicate.hpp>
#include "libbacktrace/backtrace.h"
#include "libbacktrace/internal.h"
#include "linereader.h"
using namespace std;
namespace {
string demangle(const char* function)
{
if (!function) {
return {};
} else if (function[0] != '_' || function[1] != 'Z') {
return {function};
}
string ret;
int status = 0;
char* demangled = abi::__cxa_demangle(function, 0, 0, &status);
if (demangled) {
ret = demangled;
free(demangled);
}
return ret;
}
struct AddressInformation
{
string function;
string file;
int line = 0;
};
struct Module
{
Module(uintptr_t addressStart, uintptr_t addressEnd, backtrace_state* backtraceState, size_t moduleIndex)
: addressStart(addressStart)
, addressEnd(addressEnd)
, moduleIndex(moduleIndex)
, backtraceState(backtraceState)
{
}
AddressInformation resolveAddress(uintptr_t address) const
{
AddressInformation info;
if (!backtraceState) {
return info;
}
backtrace_pcinfo(backtraceState, address,
[] (void *data, uintptr_t /*addr*/, const char *file, int line, const char *function) -> int {
auto info = reinterpret_cast<AddressInformation*>(data);
info->function = demangle(function);
info->file = file ? file : "";
info->line = line;
return 0;
}, [] (void */*data*/, const char */*msg*/, int /*errnum*/) {}, &info);
if (info.function.empty()) {
backtrace_syminfo(backtraceState, address,
[] (void *data, uintptr_t /*pc*/, const char *symname, uintptr_t /*symval*/, uintptr_t /*symsize*/) {
if (symname) {
reinterpret_cast<AddressInformation*>(data)->function = demangle(symname);
}
}, [] (void */*data*/, const char *msg, int errnum) {
cerr << "Module backtrace error (code " << errnum << "): " << msg << endl;
}, &info);
}
return info;
}
bool operator<(const Module& module) const
{
return make_tuple(addressStart, addressEnd, moduleIndex)
< make_tuple(module.addressStart, module.addressEnd, module.moduleIndex);
}
bool operator!=(const Module& module) const
{
return make_tuple(addressStart, addressEnd, moduleIndex)
!= make_tuple(module.addressStart, module.addressEnd, module.moduleIndex);
}
uintptr_t addressStart;
uintptr_t addressEnd;
size_t moduleIndex;
backtrace_state* backtraceState;
};
struct Allocation
{
// backtrace entry point
size_t ipIndex;
// number of allocations
size_t allocations;
// amount of bytes leaked
size_t leaked;
};
/**
* Information for a single call to an allocation function
*/
struct AllocationInfo
{
size_t ipIndex;
size_t size;
};
struct ResolvedIP
{
size_t moduleIndex = 0;
size_t fileIndex = 0;
size_t functionIndex = 0;
int line = 0;
};
struct AccumulatedTraceData
{
AccumulatedTraceData()
{
m_modules.reserve(256);
m_backtraceStates.reserve(64);
m_internedData.reserve(4096);
m_encounteredIps.reserve(32768);
}
~AccumulatedTraceData()
{
fprintf(stdout, "# strings: %lu\n# ips: %lu\n",
m_internedData.size(), m_encounteredIps.size());
}
ResolvedIP resolve(const uintptr_t ip)
{
if (m_modulesDirty) {
// sort by addresses, required for binary search below
sort(m_modules.begin(), m_modules.end());
for (size_t i = 0; i < m_modules.size(); ++i) {
const auto& m1 = m_modules[i];
for (size_t j = i + 1; j < m_modules.size(); ++j) {
if (i == j) {
continue;
}
const auto& m2 = m_modules[j];
if ((m1.addressStart <= m2.addressStart && m1.addressEnd > m2.addressStart) ||
(m1.addressStart < m2.addressEnd && m1.addressEnd >= m2.addressEnd))
{
cerr << "OVERLAPPING MODULES: " << hex
<< m1.moduleIndex << " (" << m1.addressStart << " to " << m1.addressEnd << ") and "
<< m1.moduleIndex << " (" << m2.addressStart << " to " << m2.addressEnd << ")\n"
<< dec;
} else if (m2.addressStart >= m1.addressEnd) {
break;
}
}
}
m_modulesDirty = false;
}
ResolvedIP data;
// find module for this instruction pointer
auto module = lower_bound(m_modules.begin(), m_modules.end(), ip,
[] (const Module& module, const uintptr_t ip) -> bool {
return module.addressEnd < ip;
});
if (module != m_modules.end() && module->addressStart <= ip && module->addressEnd >= ip) {
data.moduleIndex = module->moduleIndex;
const auto info = module->resolveAddress(ip);
data.fileIndex = intern(info.file);
data.functionIndex = intern(info.function);
data.line = info.line;
}
return data;
}
size_t intern(const string& str)
{
if (str.empty()) {
return 0;
}
auto it = m_internedData.find(str);
if (it != m_internedData.end()) {
return it->second;
}
const size_t id = m_internedData.size() + 1;
m_internedData.insert(it, make_pair(str, id));
fprintf(stdout, "s %s\n", str.c_str());
return id;
}
void addModule(backtrace_state* backtraceState, const size_t moduleIndex,
const uintptr_t addressStart, const uintptr_t addressEnd)
{
m_modules.emplace_back(addressStart, addressEnd, backtraceState, moduleIndex);
m_modulesDirty = true;
}
void clearModules()
{
// TODO: optimize this, reuse modules that are still valid
m_modules.clear();
m_modulesDirty = true;
}
size_t addIp(const uintptr_t instructionPointer)
{
if (!instructionPointer) {
return 0;
}
auto it = m_encounteredIps.find(instructionPointer);
if (it != m_encounteredIps.end()) {
return it->second;
}
const size_t ipId = m_encounteredIps.size() + 1;
m_encounteredIps.insert(it, make_pair(instructionPointer, ipId));
const auto ip = resolve(instructionPointer);
fprintf(stdout, "i %lx %lx", instructionPointer, ip.moduleIndex);
if (ip.functionIndex || ip.fileIndex) {
fprintf(stdout, " %lx", ip.functionIndex);
if (ip.fileIndex) {
fprintf(stdout, " %lx %x", ip.fileIndex, ip.line);
}
}
fputc('\n', stdout);
return ipId;
}
/**
* Prevent the same file from being initialized multiple times.
* This drastically cuts the memory consumption down
*/
backtrace_state* findBacktraceState(const string& fileName, uintptr_t addressStart, bool isExe)
{
if (boost::algorithm::starts_with(fileName, "linux-vdso.so")) {
// prevent warning, since this will always fail
return nullptr;
}
auto it = m_backtraceStates.find(fileName);
if (it != m_backtraceStates.end()) {
return it->second;
}
struct CallbackData {
const string* fileName;
};
CallbackData data = {&fileName};
auto errorHandler = [] (void *rawData, const char *msg, int errnum) {
auto data = reinterpret_cast<const CallbackData*>(rawData);
cerr << "Failed to create backtrace state for module " << *data->fileName << ": "
<< msg << " / " << strerror(errnum) << " (error code " << errnum << ")" << endl;
};
auto state = backtrace_create_state(fileName.c_str(), /* we are single threaded, so: not thread safe */ false,
errorHandler, &data);
if (state) {
const int descriptor = backtrace_open(fileName.c_str(), errorHandler, &data, nullptr);
if (descriptor >= 1) {
int foundSym = 0;
int foundDwarf = 0;
auto ret = elf_add(state, descriptor, addressStart, errorHandler, &data,
&state->fileline_fn, &foundSym, &foundDwarf, isExe);
if (ret && foundSym) {
state->syminfo_fn = &elf_syminfo;
}
}
}
m_backtraceStates.insert(it, make_pair(fileName, state));
return state;
}
private:
vector<Module> m_modules;
unordered_map<string, backtrace_state*> m_backtraceStates;
bool m_modulesDirty = false;
unordered_map<string, size_t> m_internedData;
unordered_map<uintptr_t, size_t> m_encounteredIps;
};
}
int main(int /*argc*/, char** /*argv*/)
{
// optimize: we only have a single thread
ios_base::sync_with_stdio(false);
__fsetlocking(stdout, FSETLOCKING_BYCALLER);
__fsetlocking(stdin, FSETLOCKING_BYCALLER);
AccumulatedTraceData data;
LineReader reader;
string exe;
while (reader.getLine(cin)) {
if (reader.mode() == 'x') {
reader >> exe;
} else if (reader.mode() == 'm') {
string fileName;
reader >> fileName;
if (fileName == "-") {
data.clearModules();
} else {
const bool isExe = (fileName == "x");
if (isExe) {
fileName = exe;
}
const auto moduleIndex = data.intern(fileName);
uintptr_t addressStart = 0;
if (!(reader >> addressStart)) {
cerr << "failed to parse line: " << reader.line() << endl;
return 1;
}
auto state = data.findBacktraceState(fileName, addressStart, isExe);
uintptr_t vAddr = 0;
uintptr_t memSize = 0;
while ((reader >> vAddr) && (reader >> memSize)) {
data.addModule(state, moduleIndex,
addressStart + vAddr,
addressStart + vAddr + memSize);
}
}
} else if (reader.mode() == 't') {
uintptr_t instructionPointer = 0;
size_t parentIndex = 0;
if (!(reader >> instructionPointer) || !(reader >> parentIndex)) {
cerr << "failed to parse line: " << reader.line() << endl;
return 1;
}
// ensure ip is encountered
const auto ipId = data.addIp(instructionPointer);
// trace point, map current output index to parent index
fprintf(stdout, "t %lx %lx\n", ipId, parentIndex);
} else {
fputs(reader.line().c_str(), stdout);
fputc('\n', stdout);
}
}
return 0;
}
<|endoftext|> |
<commit_before>/*
* 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.
*
* Written (W) 2011 Heiko Strathmann
* Copyright (C) 2011 Berlin Institute of Technology and Max-Planck-Society
*/
#include <shogun/base/init.h>
#include <shogun/base/Parameter.h>
#include <shogun/base/ParameterMap.h>
using namespace shogun;
void print_message(FILE* target, const char* str)
{
fprintf(target, "%s", str);
}
void test_mapping_1()
{
ParameterMap* map=new ParameterMap();
map->put(
new SGParamInfo("number", CT_SCALAR, ST_NONE, PT_FLOAT64, 2),
new SGParamInfo("number", CT_SCALAR, ST_NONE, PT_INT32, 1)
);
map->put(
new SGParamInfo("number", CT_SCALAR, ST_NONE, PT_INT32, 1),
new SGParamInfo("number", CT_SCALAR, ST_NONE, PT_FLOAT64, 0)
);
map->put(
new SGParamInfo("number_2", CT_SCALAR, ST_NONE, PT_INT32, 1),
new SGParamInfo("number_to_keep", CT_SCALAR, ST_NONE, PT_INT32, 0)
);
/* finalizing the map is needed before accessing it */
map->finalize_map();
map->print_map();
SG_SPRINT("\n");
/* get some elements from map, one/two ARE in map, three and four are NOT */
DynArray<SGParamInfo*> dummies;
dummies.append_element(new SGParamInfo("number", CT_SCALAR, ST_NONE,
PT_INT32, 1));
dummies.append_element(new SGParamInfo("number", CT_SCALAR, ST_NONE,
PT_FLOAT64, 2));
dummies.append_element(new SGParamInfo("number", CT_SCALAR, ST_NONE,
PT_INT32, 2));
dummies.append_element(new SGParamInfo("number", CT_SCALAR, ST_NONE,
PT_FLOAT64, 0));
dummies.append_element(new SGParamInfo("number_2", CT_SCALAR, ST_NONE,
PT_INT32, 1));
for (index_t i=0; i<dummies.get_num_elements(); ++i)
{
SGParamInfo* current=dummies.get_element(i);
char* s=current->to_string();
SG_SPRINT("searching for: %s\n", s);
SG_FREE(s);
const SGParamInfo* result=map->get(current);
if (result)
{
s=result->to_string();
SG_SPRINT("found: %s\n\n", s);
SG_FREE(s);
}
else
SG_SPRINT("nothing found\n\n");
delete current;
}
delete map;
}
void print_value(const SGParamInfo* key, ParameterMap* map)
{
const SGParamInfo* current=map->get(key);
key->print_param_info();
SG_SPRINT("value: ");
if (current)
current->print_param_info();
else
SG_SPRINT("no element\n");
SG_SPRINT("\n");
}
void test_mapping_2()
{
ParameterMap* map=new ParameterMap();
EContainerType cfrom=CT_SCALAR;
EContainerType cto=CT_MATRIX;
EStructType sfrom=ST_NONE;
EStructType sto=ST_STRING;
EPrimitiveType pfrom=PT_BOOL;
EPrimitiveType pto=PT_SGOBJECT;
map->put(new SGParamInfo("1", cfrom, sfrom, pfrom, 2),
new SGParamInfo("eins", cto, sto, pto, 1));
map->put(new SGParamInfo("2", cfrom, sfrom, pfrom, 2),
new SGParamInfo("zwei", cto, sto, pto, 1));
map->put(new SGParamInfo("3", cfrom, sfrom, pfrom, 4),
new SGParamInfo("drei", cto, sto, pto, 3));
map->put(new SGParamInfo("4", cfrom, sfrom, pfrom, 4),
new SGParamInfo("vier", cto, sto, pto, 3));
SG_SPRINT("before finalization:\n");
map->print_map();
map->finalize_map();
SG_SPRINT("\n\nafter finalization:\n");
map->print_map();
const SGParamInfo* key;
SG_SPRINT("\n\ntesting map\n");
key=new SGParamInfo("1", cfrom, sfrom, pfrom, 1);
print_value(key, map);
delete key;
key=new SGParamInfo("2", cfrom, sfrom, pfrom, 2);
print_value(key, map);
delete key;
key=new SGParamInfo("2", cto, sfrom, pfrom, 2);
print_value(key, map);
delete key;
key=new SGParamInfo("2", cfrom, sto, pfrom, 2);
print_value(key, map);
delete key;
key=new SGParamInfo("2", cfrom, sfrom, pto, 2);
print_value(key, map);
delete key;
key=new SGParamInfo("5", cfrom, sfrom, pfrom, 4);
print_value(key, map);
delete key;
delete map;
}
int main(int argc, char **argv)
{
init_shogun(&print_message, &print_message, &print_message);
test_mapping_1();
test_mapping_2();
exit_shogun();
return 0;
}
<commit_msg>adapted for new mutli-value per key parameter map and added testcase<commit_after>/*
* 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.
*
* Written (W) 2011 Heiko Strathmann
* Copyright (C) 2011 Berlin Institute of Technology and Max-Planck-Society
*/
#include <shogun/base/init.h>
#include <shogun/base/Parameter.h>
#include <shogun/base/ParameterMap.h>
using namespace shogun;
void print_message(FILE* target, const char* str)
{
fprintf(target, "%s", str);
}
void test_mapping_1()
{
ParameterMap* map=new ParameterMap();
map->put(
new SGParamInfo("number", CT_SCALAR, ST_NONE, PT_FLOAT64, 2),
new SGParamInfo("number", CT_SCALAR, ST_NONE, PT_INT32, 1)
);
map->put(
new SGParamInfo("number", CT_SCALAR, ST_NONE, PT_INT32, 1),
new SGParamInfo("number", CT_SCALAR, ST_NONE, PT_FLOAT64, 0)
);
map->put(
new SGParamInfo("number_2", CT_SCALAR, ST_NONE, PT_INT32, 1),
new SGParamInfo("number_to_keep", CT_SCALAR, ST_NONE, PT_INT32, 0)
);
/* finalizing the map is needed before accessing it */
SG_SPRINT("\n\before finalization:\n");
map->finalize_map();
SG_SPRINT("\n\nafter finalization:\n");
map->print_map();
SG_SPRINT("\n");
/* get some elements from map, one/two ARE in map, three and four are NOT */
DynArray<SGParamInfo*> dummies;
dummies.append_element(new SGParamInfo("number", CT_SCALAR, ST_NONE,
PT_INT32, 1));
dummies.append_element(new SGParamInfo("number", CT_SCALAR, ST_NONE,
PT_FLOAT64, 2));
dummies.append_element(new SGParamInfo("number", CT_SCALAR, ST_NONE,
PT_INT32, 2));
dummies.append_element(new SGParamInfo("number", CT_SCALAR, ST_NONE,
PT_FLOAT64, 0));
dummies.append_element(new SGParamInfo("number_2", CT_SCALAR, ST_NONE,
PT_INT32, 1));
for (index_t i=0; i<dummies.get_num_elements(); ++i)
{
SGParamInfo* current=dummies.get_element(i);
char* s=current->to_string();
SG_SPRINT("searching for: %s\n", s);
SG_FREE(s);
DynArray<const SGParamInfo*>* result=map->get(current, 0);
if (result)
{
for (index_t i=0; i<result->get_num_elements(); ++i)
{
s=result->get_element(i)->to_string();
SG_SPRINT("found: %s\n\n", s);
SG_FREE(s);
}
}
else
SG_SPRINT("nothing found\n\n");
delete current;
}
delete map;
}
void print_value(const SGParamInfo* key, ParameterMap* map)
{
DynArray<const SGParamInfo*>* current=map->get(key, 0);
key->print_param_info();
SG_SPRINT("value: ");
if (current)
{
for (index_t i=0; i<current->get_num_elements(); ++i)
current->get_element(i)->print_param_info("\t");
}
else
SG_SPRINT("no elements\n");
SG_SPRINT("\n");
}
void test_mapping_2()
{
ParameterMap* map=new ParameterMap();
EContainerType cfrom=CT_SCALAR;
EContainerType cto=CT_MATRIX;
EStructType sfrom=ST_NONE;
EStructType sto=ST_STRING;
EPrimitiveType pfrom=PT_BOOL;
EPrimitiveType pto=PT_SGOBJECT;
map->put(new SGParamInfo("1", cfrom, sfrom, pfrom, 2),
new SGParamInfo("eins", cto, sto, pto, 1));
map->put(new SGParamInfo("2", cfrom, sfrom, pfrom, 2),
new SGParamInfo("zwei", cto, sto, pto, 1));
map->put(new SGParamInfo("3", cfrom, sfrom, pfrom, 4),
new SGParamInfo("drei", cto, sto, pto, 3));
map->put(new SGParamInfo("4", cfrom, sfrom, pfrom, 4),
new SGParamInfo("vier", cto, sto, pto, 3));
map->finalize_map();
SG_SPRINT("\n\nafter finalization:\n");
map->print_map();
const SGParamInfo* key;
SG_SPRINT("\n\ntesting map\n");
key=new SGParamInfo("1", cfrom, sfrom, pfrom, 1);
print_value(key, map);
delete key;
key=new SGParamInfo("2", cfrom, sfrom, pfrom, 2);
print_value(key, map);
delete key;
key=new SGParamInfo("2", cto, sfrom, pfrom, 2);
print_value(key, map);
delete key;
key=new SGParamInfo("2", cfrom, sto, pfrom, 2);
print_value(key, map);
delete key;
key=new SGParamInfo("2", cfrom, sfrom, pto, 2);
print_value(key, map);
delete key;
key=new SGParamInfo("5", cfrom, sfrom, pfrom, 4);
print_value(key, map);
delete key;
delete map;
}
void test_mapping_0()
{
/* test multiple values per key */
ParameterMap* map=new ParameterMap();
EContainerType cfrom=CT_SCALAR;
EContainerType cto=CT_MATRIX;
EStructType sfrom=ST_NONE;
EStructType sto=ST_STRING;
EPrimitiveType pfrom=PT_BOOL;
EPrimitiveType pto=PT_SGOBJECT;
/* 3 equal keys */
map->put(new SGParamInfo("1", cfrom, sfrom, pfrom, 2),
new SGParamInfo("eins a", cto, sto, pto, 1));
map->put(new SGParamInfo("1", cfrom, sfrom, pfrom, 2),
new SGParamInfo("eins b", cto, sto, pto, 1));
map->put(new SGParamInfo("1", cfrom, sfrom, pfrom, 2),
new SGParamInfo("eins c", cto, sto, pto, 1));
/* 2 equal keys */
map->put(new SGParamInfo("2", cfrom, sfrom, pfrom, 2),
new SGParamInfo("zwei a", cto, sto, pto, 1));
map->put(new SGParamInfo("2", cfrom, sfrom, pfrom, 2),
new SGParamInfo("zwei b", cto, sto, pto, 1));
map->finalize_map();
SG_SPRINT("printing finalized map\n");
map->print_map();
/* assert that all is there */
DynArray<const SGParamInfo*>* result;
bool found;
/* key 0 */
result=map->get(SGParamInfo("1", cfrom, sfrom, pfrom, 2));
ASSERT(result);
/* first value element */
found=false;
for (index_t i=0; i<result->get_num_elements(); ++i)
{
if (*result->get_element(i) == SGParamInfo("eins a", cto, sto, pto, 1))
found=true;
}
ASSERT(found);
/* second value element */
found=false;
for (index_t i=0; i<result->get_num_elements(); ++i)
{
if (*result->get_element(i) == SGParamInfo("eins b", cto, sto, pto, 1))
found=true;
}
ASSERT(found);
/* third value element */
found=false;
for (index_t i=0; i<result->get_num_elements(); ++i)
{
if (*result->get_element(i) == SGParamInfo("eins c", cto, sto, pto, 1))
found=true;
}
ASSERT(found);
/* key 1 */
result=map->get(SGParamInfo("2", cfrom, sfrom, pfrom, 2));
ASSERT(result);
/* first value element */
found=false;
for (index_t i=0; i<result->get_num_elements(); ++i)
{
if (*result->get_element(i) == SGParamInfo("zwei a", cto, sto, pto, 1))
found=true;
}
ASSERT(found);
/* second value element */
found=false;
for (index_t i=0; i<result->get_num_elements(); ++i)
{
if (*result->get_element(i) == SGParamInfo("zwei b", cto, sto, pto, 1))
found=true;
}
ASSERT(found);
delete map;
}
int main(int argc, char **argv)
{
init_shogun(&print_message, &print_message, &print_message);
test_mapping_0();
test_mapping_1();
test_mapping_2();
exit_shogun();
return 0;
}
<|endoftext|> |
<commit_before>//===-- Local.cpp - Functions to perform local transformations ------------===//
//
// The LLVM Compiler Infrastructure
//
// This file was developed by the LLVM research group and is distributed under
// the University of Illinois Open Source License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
//
// This family of functions perform various local transformations to the
// program.
//
//===----------------------------------------------------------------------===//
#include "llvm/Transforms/Utils/Local.h"
#include "llvm/Constants.h"
#include "llvm/Instructions.h"
#include "llvm/Intrinsics.h"
#include <cerrno>
#include <cmath>
using namespace llvm;
//===----------------------------------------------------------------------===//
// Local constant propagation...
//
/// doConstantPropagation - If an instruction references constants, try to fold
/// them together...
///
bool llvm::doConstantPropagation(BasicBlock::iterator &II) {
if (Constant *C = ConstantFoldInstruction(II)) {
// Replaces all of the uses of a variable with uses of the constant.
II->replaceAllUsesWith(C);
// Remove the instruction from the basic block...
II = II->getParent()->getInstList().erase(II);
return true;
}
return false;
}
/// ConstantFoldInstruction - Attempt to constant fold the specified
/// instruction. If successful, the constant result is returned, if not, null
/// is returned. Note that this function can only fail when attempting to fold
/// instructions like loads and stores, which have no constant expression form.
///
Constant *llvm::ConstantFoldInstruction(Instruction *I) {
if (PHINode *PN = dyn_cast<PHINode>(I)) {
if (PN->getNumIncomingValues() == 0)
return Constant::getNullValue(PN->getType());
Constant *Result = dyn_cast<Constant>(PN->getIncomingValue(0));
if (Result == 0) return 0;
// Handle PHI nodes specially here...
for (unsigned i = 1, e = PN->getNumIncomingValues(); i != e; ++i)
if (PN->getIncomingValue(i) != Result && PN->getIncomingValue(i) != PN)
return 0; // Not all the same incoming constants...
// If we reach here, all incoming values are the same constant.
return Result;
} else if (CallInst *CI = dyn_cast<CallInst>(I)) {
if (Function *F = CI->getCalledFunction())
if (canConstantFoldCallTo(F)) {
std::vector<Constant*> Args;
for (unsigned i = 1, e = CI->getNumOperands(); i != e; ++i)
if (Constant *Op = dyn_cast<Constant>(CI->getOperand(i)))
Args.push_back(Op);
else
return 0;
return ConstantFoldCall(F, Args);
}
return 0;
}
Constant *Op0 = 0, *Op1 = 0;
switch (I->getNumOperands()) {
default:
case 2:
Op1 = dyn_cast<Constant>(I->getOperand(1));
if (Op1 == 0) return 0; // Not a constant?, can't fold
case 1:
Op0 = dyn_cast<Constant>(I->getOperand(0));
if (Op0 == 0) return 0; // Not a constant?, can't fold
break;
case 0: return 0;
}
if (isa<BinaryOperator>(I) || isa<ShiftInst>(I))
return ConstantExpr::get(I->getOpcode(), Op0, Op1);
switch (I->getOpcode()) {
default: return 0;
case Instruction::Cast:
return ConstantExpr::getCast(Op0, I->getType());
case Instruction::Select:
if (Constant *Op2 = dyn_cast<Constant>(I->getOperand(2)))
return ConstantExpr::getSelect(Op0, Op1, Op2);
return 0;
case Instruction::GetElementPtr:
std::vector<Constant*> IdxList;
IdxList.reserve(I->getNumOperands()-1);
if (Op1) IdxList.push_back(Op1);
for (unsigned i = 2, e = I->getNumOperands(); i != e; ++i)
if (Constant *C = dyn_cast<Constant>(I->getOperand(i)))
IdxList.push_back(C);
else
return 0; // Non-constant operand
return ConstantExpr::getGetElementPtr(Op0, IdxList);
}
}
// ConstantFoldTerminator - If a terminator instruction is predicated on a
// constant value, convert it into an unconditional branch to the constant
// destination.
//
bool llvm::ConstantFoldTerminator(BasicBlock *BB) {
TerminatorInst *T = BB->getTerminator();
// Branch - See if we are conditional jumping on constant
if (BranchInst *BI = dyn_cast<BranchInst>(T)) {
if (BI->isUnconditional()) return false; // Can't optimize uncond branch
BasicBlock *Dest1 = cast<BasicBlock>(BI->getOperand(0));
BasicBlock *Dest2 = cast<BasicBlock>(BI->getOperand(1));
if (ConstantBool *Cond = dyn_cast<ConstantBool>(BI->getCondition())) {
// Are we branching on constant?
// YES. Change to unconditional branch...
BasicBlock *Destination = Cond->getValue() ? Dest1 : Dest2;
BasicBlock *OldDest = Cond->getValue() ? Dest2 : Dest1;
//cerr << "Function: " << T->getParent()->getParent()
// << "\nRemoving branch from " << T->getParent()
// << "\n\nTo: " << OldDest << endl;
// Let the basic block know that we are letting go of it. Based on this,
// it will adjust it's PHI nodes.
assert(BI->getParent() && "Terminator not inserted in block!");
OldDest->removePredecessor(BI->getParent());
// Set the unconditional destination, and change the insn to be an
// unconditional branch.
BI->setUnconditionalDest(Destination);
return true;
} else if (Dest2 == Dest1) { // Conditional branch to same location?
// This branch matches something like this:
// br bool %cond, label %Dest, label %Dest
// and changes it into: br label %Dest
// Let the basic block know that we are letting go of one copy of it.
assert(BI->getParent() && "Terminator not inserted in block!");
Dest1->removePredecessor(BI->getParent());
// Change a conditional branch to unconditional.
BI->setUnconditionalDest(Dest1);
return true;
}
} else if (SwitchInst *SI = dyn_cast<SwitchInst>(T)) {
// If we are switching on a constant, we can convert the switch into a
// single branch instruction!
ConstantInt *CI = dyn_cast<ConstantInt>(SI->getCondition());
BasicBlock *TheOnlyDest = SI->getSuccessor(0); // The default dest
BasicBlock *DefaultDest = TheOnlyDest;
assert(TheOnlyDest == SI->getDefaultDest() &&
"Default destination is not successor #0?");
// Figure out which case it goes to...
for (unsigned i = 1, e = SI->getNumSuccessors(); i != e; ++i) {
// Found case matching a constant operand?
if (SI->getSuccessorValue(i) == CI) {
TheOnlyDest = SI->getSuccessor(i);
break;
}
// Check to see if this branch is going to the same place as the default
// dest. If so, eliminate it as an explicit compare.
if (SI->getSuccessor(i) == DefaultDest) {
// Remove this entry...
DefaultDest->removePredecessor(SI->getParent());
SI->removeCase(i);
--i; --e; // Don't skip an entry...
continue;
}
// Otherwise, check to see if the switch only branches to one destination.
// We do this by reseting "TheOnlyDest" to null when we find two non-equal
// destinations.
if (SI->getSuccessor(i) != TheOnlyDest) TheOnlyDest = 0;
}
if (CI && !TheOnlyDest) {
// Branching on a constant, but not any of the cases, go to the default
// successor.
TheOnlyDest = SI->getDefaultDest();
}
// If we found a single destination that we can fold the switch into, do so
// now.
if (TheOnlyDest) {
// Insert the new branch..
new BranchInst(TheOnlyDest, SI);
BasicBlock *BB = SI->getParent();
// Remove entries from PHI nodes which we no longer branch to...
for (unsigned i = 0, e = SI->getNumSuccessors(); i != e; ++i) {
// Found case matching a constant operand?
BasicBlock *Succ = SI->getSuccessor(i);
if (Succ == TheOnlyDest)
TheOnlyDest = 0; // Don't modify the first branch to TheOnlyDest
else
Succ->removePredecessor(BB);
}
// Delete the old switch...
BB->getInstList().erase(SI);
return true;
} else if (SI->getNumSuccessors() == 2) {
// Otherwise, we can fold this switch into a conditional branch
// instruction if it has only one non-default destination.
Value *Cond = new SetCondInst(Instruction::SetEQ, SI->getCondition(),
SI->getSuccessorValue(1), "cond", SI);
// Insert the new branch...
new BranchInst(SI->getSuccessor(1), SI->getSuccessor(0), Cond, SI);
// Delete the old switch...
SI->getParent()->getInstList().erase(SI);
return true;
}
}
return false;
}
/// canConstantFoldCallTo - Return true if its even possible to fold a call to
/// the specified function.
bool llvm::canConstantFoldCallTo(Function *F) {
const std::string &Name = F->getName();
switch (F->getIntrinsicID()) {
case Intrinsic::isnan: return true;
default: break;
}
return Name == "sin" || Name == "cos" || Name == "tan" || Name == "sqrt" ||
Name == "log" || Name == "log10" || Name == "exp" || Name == "pow" ||
Name == "acos" || Name == "asin" || Name == "atan" || Name == "fmod";
}
static Constant *ConstantFoldFP(double (*NativeFP)(double), double V,
const Type *Ty) {
errno = 0;
V = NativeFP(V);
if (errno == 0)
return ConstantFP::get(Ty, V);
return 0;
}
/// ConstantFoldCall - Attempt to constant fold a call to the specified function
/// with the specified arguments, returning null if unsuccessful.
Constant *llvm::ConstantFoldCall(Function *F,
const std::vector<Constant*> &Operands) {
const std::string &Name = F->getName();
const Type *Ty = F->getReturnType();
if (Operands.size() == 1) {
if (ConstantFP *Op = dyn_cast<ConstantFP>(Operands[0])) {
double V = Op->getValue();
if (Name == "llvm.isnan")
return ConstantBool::get(isnan(V));
else if (Name == "sin")
return ConstantFP::get(Ty, sin(V));
else if (Name == "cos")
return ConstantFP::get(Ty, cos(V));
else if (Name == "tan")
return ConstantFP::get(Ty, tan(V));
else if (Name == "sqrt" && V >= 0)
return ConstantFP::get(Ty, sqrt(V));
else if (Name == "exp")
return ConstantFP::get(Ty, exp(V));
else if (Name == "log" && V > 0)
return ConstantFP::get(Ty, log(V));
else if (Name == "log10")
return ConstantFoldFP(log10, V, Ty);
else if (Name == "acos")
return ConstantFoldFP(acos, V, Ty);
else if (Name == "asin")
return ConstantFoldFP(asin, V, Ty);
else if (Name == "atan")
return ConstantFP::get(Ty, atan(V));
}
} else if (Operands.size() == 2) {
if (ConstantFP *Op1 = dyn_cast<ConstantFP>(Operands[0]))
if (ConstantFP *Op2 = dyn_cast<ConstantFP>(Operands[1])) {
double Op1V = Op1->getValue(), Op2V = Op2->getValue();
if (Name == "pow") {
errno = 0;
double V = pow(Op1V, Op2V);
if (errno == 0)
return ConstantFP::get(Ty, V);
} else if (Name == "fmod") {
errno = 0;
double V = fmod(Op1V, Op2V);
if (errno == 0)
return ConstantFP::get(Ty, V);
}
}
}
return 0;
}
//===----------------------------------------------------------------------===//
// Local dead code elimination...
//
bool llvm::isInstructionTriviallyDead(Instruction *I) {
return I->use_empty() && !I->mayWriteToMemory() && !isa<TerminatorInst>(I);
}
// dceInstruction - Inspect the instruction at *BBI and figure out if it's
// [trivially] dead. If so, remove the instruction and update the iterator
// to point to the instruction that immediately succeeded the original
// instruction.
//
bool llvm::dceInstruction(BasicBlock::iterator &BBI) {
// Look for un"used" definitions...
if (isInstructionTriviallyDead(BBI)) {
BBI = BBI->getParent()->getInstList().erase(BBI); // Bye bye
return true;
}
return false;
}
//===----------------------------------------------------------------------===//
// PHI Instruction Simplification
//
/// hasConstantValue - If the specified PHI node always merges together the same
/// value, return the value, otherwise return null.
///
Value *llvm::hasConstantValue(PHINode *PN) {
// If the PHI node only has one incoming value, eliminate the PHI node...
if (PN->getNumIncomingValues() == 1)
return PN->getIncomingValue(0);
// Otherwise if all of the incoming values are the same for the PHI, replace
// the PHI node with the incoming value.
//
Value *InVal = 0;
for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i)
if (PN->getIncomingValue(i) != PN) // Not the PHI node itself...
if (InVal && PN->getIncomingValue(i) != InVal)
return 0; // Not the same, bail out.
else
InVal = PN->getIncomingValue(i);
// The only case that could cause InVal to be null is if we have a PHI node
// that only has entries for itself. In this case, there is no entry into the
// loop, so kill the PHI.
//
if (InVal == 0) InVal = Constant::getNullValue(PN->getType());
// All of the incoming values are the same, return the value now.
return InVal;
}
<commit_msg>Add constant folding capabilities to the isunordered intrinsic.<commit_after>//===-- Local.cpp - Functions to perform local transformations ------------===//
//
// The LLVM Compiler Infrastructure
//
// This file was developed by the LLVM research group and is distributed under
// the University of Illinois Open Source License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
//
// This family of functions perform various local transformations to the
// program.
//
//===----------------------------------------------------------------------===//
#include "llvm/Transforms/Utils/Local.h"
#include "llvm/Constants.h"
#include "llvm/Instructions.h"
#include "llvm/Intrinsics.h"
#include <cerrno>
#include <cmath>
using namespace llvm;
//===----------------------------------------------------------------------===//
// Local constant propagation...
//
/// doConstantPropagation - If an instruction references constants, try to fold
/// them together...
///
bool llvm::doConstantPropagation(BasicBlock::iterator &II) {
if (Constant *C = ConstantFoldInstruction(II)) {
// Replaces all of the uses of a variable with uses of the constant.
II->replaceAllUsesWith(C);
// Remove the instruction from the basic block...
II = II->getParent()->getInstList().erase(II);
return true;
}
return false;
}
/// ConstantFoldInstruction - Attempt to constant fold the specified
/// instruction. If successful, the constant result is returned, if not, null
/// is returned. Note that this function can only fail when attempting to fold
/// instructions like loads and stores, which have no constant expression form.
///
Constant *llvm::ConstantFoldInstruction(Instruction *I) {
if (PHINode *PN = dyn_cast<PHINode>(I)) {
if (PN->getNumIncomingValues() == 0)
return Constant::getNullValue(PN->getType());
Constant *Result = dyn_cast<Constant>(PN->getIncomingValue(0));
if (Result == 0) return 0;
// Handle PHI nodes specially here...
for (unsigned i = 1, e = PN->getNumIncomingValues(); i != e; ++i)
if (PN->getIncomingValue(i) != Result && PN->getIncomingValue(i) != PN)
return 0; // Not all the same incoming constants...
// If we reach here, all incoming values are the same constant.
return Result;
} else if (CallInst *CI = dyn_cast<CallInst>(I)) {
if (Function *F = CI->getCalledFunction())
if (canConstantFoldCallTo(F)) {
std::vector<Constant*> Args;
for (unsigned i = 1, e = CI->getNumOperands(); i != e; ++i)
if (Constant *Op = dyn_cast<Constant>(CI->getOperand(i)))
Args.push_back(Op);
else
return 0;
return ConstantFoldCall(F, Args);
}
return 0;
}
Constant *Op0 = 0, *Op1 = 0;
switch (I->getNumOperands()) {
default:
case 2:
Op1 = dyn_cast<Constant>(I->getOperand(1));
if (Op1 == 0) return 0; // Not a constant?, can't fold
case 1:
Op0 = dyn_cast<Constant>(I->getOperand(0));
if (Op0 == 0) return 0; // Not a constant?, can't fold
break;
case 0: return 0;
}
if (isa<BinaryOperator>(I) || isa<ShiftInst>(I))
return ConstantExpr::get(I->getOpcode(), Op0, Op1);
switch (I->getOpcode()) {
default: return 0;
case Instruction::Cast:
return ConstantExpr::getCast(Op0, I->getType());
case Instruction::Select:
if (Constant *Op2 = dyn_cast<Constant>(I->getOperand(2)))
return ConstantExpr::getSelect(Op0, Op1, Op2);
return 0;
case Instruction::GetElementPtr:
std::vector<Constant*> IdxList;
IdxList.reserve(I->getNumOperands()-1);
if (Op1) IdxList.push_back(Op1);
for (unsigned i = 2, e = I->getNumOperands(); i != e; ++i)
if (Constant *C = dyn_cast<Constant>(I->getOperand(i)))
IdxList.push_back(C);
else
return 0; // Non-constant operand
return ConstantExpr::getGetElementPtr(Op0, IdxList);
}
}
// ConstantFoldTerminator - If a terminator instruction is predicated on a
// constant value, convert it into an unconditional branch to the constant
// destination.
//
bool llvm::ConstantFoldTerminator(BasicBlock *BB) {
TerminatorInst *T = BB->getTerminator();
// Branch - See if we are conditional jumping on constant
if (BranchInst *BI = dyn_cast<BranchInst>(T)) {
if (BI->isUnconditional()) return false; // Can't optimize uncond branch
BasicBlock *Dest1 = cast<BasicBlock>(BI->getOperand(0));
BasicBlock *Dest2 = cast<BasicBlock>(BI->getOperand(1));
if (ConstantBool *Cond = dyn_cast<ConstantBool>(BI->getCondition())) {
// Are we branching on constant?
// YES. Change to unconditional branch...
BasicBlock *Destination = Cond->getValue() ? Dest1 : Dest2;
BasicBlock *OldDest = Cond->getValue() ? Dest2 : Dest1;
//cerr << "Function: " << T->getParent()->getParent()
// << "\nRemoving branch from " << T->getParent()
// << "\n\nTo: " << OldDest << endl;
// Let the basic block know that we are letting go of it. Based on this,
// it will adjust it's PHI nodes.
assert(BI->getParent() && "Terminator not inserted in block!");
OldDest->removePredecessor(BI->getParent());
// Set the unconditional destination, and change the insn to be an
// unconditional branch.
BI->setUnconditionalDest(Destination);
return true;
} else if (Dest2 == Dest1) { // Conditional branch to same location?
// This branch matches something like this:
// br bool %cond, label %Dest, label %Dest
// and changes it into: br label %Dest
// Let the basic block know that we are letting go of one copy of it.
assert(BI->getParent() && "Terminator not inserted in block!");
Dest1->removePredecessor(BI->getParent());
// Change a conditional branch to unconditional.
BI->setUnconditionalDest(Dest1);
return true;
}
} else if (SwitchInst *SI = dyn_cast<SwitchInst>(T)) {
// If we are switching on a constant, we can convert the switch into a
// single branch instruction!
ConstantInt *CI = dyn_cast<ConstantInt>(SI->getCondition());
BasicBlock *TheOnlyDest = SI->getSuccessor(0); // The default dest
BasicBlock *DefaultDest = TheOnlyDest;
assert(TheOnlyDest == SI->getDefaultDest() &&
"Default destination is not successor #0?");
// Figure out which case it goes to...
for (unsigned i = 1, e = SI->getNumSuccessors(); i != e; ++i) {
// Found case matching a constant operand?
if (SI->getSuccessorValue(i) == CI) {
TheOnlyDest = SI->getSuccessor(i);
break;
}
// Check to see if this branch is going to the same place as the default
// dest. If so, eliminate it as an explicit compare.
if (SI->getSuccessor(i) == DefaultDest) {
// Remove this entry...
DefaultDest->removePredecessor(SI->getParent());
SI->removeCase(i);
--i; --e; // Don't skip an entry...
continue;
}
// Otherwise, check to see if the switch only branches to one destination.
// We do this by reseting "TheOnlyDest" to null when we find two non-equal
// destinations.
if (SI->getSuccessor(i) != TheOnlyDest) TheOnlyDest = 0;
}
if (CI && !TheOnlyDest) {
// Branching on a constant, but not any of the cases, go to the default
// successor.
TheOnlyDest = SI->getDefaultDest();
}
// If we found a single destination that we can fold the switch into, do so
// now.
if (TheOnlyDest) {
// Insert the new branch..
new BranchInst(TheOnlyDest, SI);
BasicBlock *BB = SI->getParent();
// Remove entries from PHI nodes which we no longer branch to...
for (unsigned i = 0, e = SI->getNumSuccessors(); i != e; ++i) {
// Found case matching a constant operand?
BasicBlock *Succ = SI->getSuccessor(i);
if (Succ == TheOnlyDest)
TheOnlyDest = 0; // Don't modify the first branch to TheOnlyDest
else
Succ->removePredecessor(BB);
}
// Delete the old switch...
BB->getInstList().erase(SI);
return true;
} else if (SI->getNumSuccessors() == 2) {
// Otherwise, we can fold this switch into a conditional branch
// instruction if it has only one non-default destination.
Value *Cond = new SetCondInst(Instruction::SetEQ, SI->getCondition(),
SI->getSuccessorValue(1), "cond", SI);
// Insert the new branch...
new BranchInst(SI->getSuccessor(1), SI->getSuccessor(0), Cond, SI);
// Delete the old switch...
SI->getParent()->getInstList().erase(SI);
return true;
}
}
return false;
}
/// canConstantFoldCallTo - Return true if its even possible to fold a call to
/// the specified function.
bool llvm::canConstantFoldCallTo(Function *F) {
const std::string &Name = F->getName();
switch (F->getIntrinsicID()) {
case Intrinsic::isnan: return true;
case Intrinsic::isunordered: return true;
default: break;
}
return Name == "sin" || Name == "cos" || Name == "tan" || Name == "sqrt" ||
Name == "log" || Name == "log10" || Name == "exp" || Name == "pow" ||
Name == "acos" || Name == "asin" || Name == "atan" || Name == "fmod";
}
static Constant *ConstantFoldFP(double (*NativeFP)(double), double V,
const Type *Ty) {
errno = 0;
V = NativeFP(V);
if (errno == 0)
return ConstantFP::get(Ty, V);
return 0;
}
/// ConstantFoldCall - Attempt to constant fold a call to the specified function
/// with the specified arguments, returning null if unsuccessful.
Constant *llvm::ConstantFoldCall(Function *F,
const std::vector<Constant*> &Operands) {
const std::string &Name = F->getName();
const Type *Ty = F->getReturnType();
if (Operands.size() == 1) {
if (ConstantFP *Op = dyn_cast<ConstantFP>(Operands[0])) {
double V = Op->getValue();
if (Name == "llvm.isnan")
return ConstantBool::get(isnan(V));
else if (Name == "sin")
return ConstantFP::get(Ty, sin(V));
else if (Name == "cos")
return ConstantFP::get(Ty, cos(V));
else if (Name == "tan")
return ConstantFP::get(Ty, tan(V));
else if (Name == "sqrt" && V >= 0)
return ConstantFP::get(Ty, sqrt(V));
else if (Name == "exp")
return ConstantFP::get(Ty, exp(V));
else if (Name == "log" && V > 0)
return ConstantFP::get(Ty, log(V));
else if (Name == "log10")
return ConstantFoldFP(log10, V, Ty);
else if (Name == "acos")
return ConstantFoldFP(acos, V, Ty);
else if (Name == "asin")
return ConstantFoldFP(asin, V, Ty);
else if (Name == "atan")
return ConstantFP::get(Ty, atan(V));
}
} else if (Operands.size() == 2) {
if (ConstantFP *Op1 = dyn_cast<ConstantFP>(Operands[0]))
if (ConstantFP *Op2 = dyn_cast<ConstantFP>(Operands[1])) {
double Op1V = Op1->getValue(), Op2V = Op2->getValue();
if (Name == "llvm.isunordered")
return ConstantBool::get(isnan(Op1V) | isnan(Op2V));
else if (Name == "pow") {
errno = 0;
double V = pow(Op1V, Op2V);
if (errno == 0)
return ConstantFP::get(Ty, V);
} else if (Name == "fmod") {
errno = 0;
double V = fmod(Op1V, Op2V);
if (errno == 0)
return ConstantFP::get(Ty, V);
}
}
}
return 0;
}
//===----------------------------------------------------------------------===//
// Local dead code elimination...
//
bool llvm::isInstructionTriviallyDead(Instruction *I) {
return I->use_empty() && !I->mayWriteToMemory() && !isa<TerminatorInst>(I);
}
// dceInstruction - Inspect the instruction at *BBI and figure out if it's
// [trivially] dead. If so, remove the instruction and update the iterator
// to point to the instruction that immediately succeeded the original
// instruction.
//
bool llvm::dceInstruction(BasicBlock::iterator &BBI) {
// Look for un"used" definitions...
if (isInstructionTriviallyDead(BBI)) {
BBI = BBI->getParent()->getInstList().erase(BBI); // Bye bye
return true;
}
return false;
}
//===----------------------------------------------------------------------===//
// PHI Instruction Simplification
//
/// hasConstantValue - If the specified PHI node always merges together the same
/// value, return the value, otherwise return null.
///
Value *llvm::hasConstantValue(PHINode *PN) {
// If the PHI node only has one incoming value, eliminate the PHI node...
if (PN->getNumIncomingValues() == 1)
return PN->getIncomingValue(0);
// Otherwise if all of the incoming values are the same for the PHI, replace
// the PHI node with the incoming value.
//
Value *InVal = 0;
for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i)
if (PN->getIncomingValue(i) != PN) // Not the PHI node itself...
if (InVal && PN->getIncomingValue(i) != InVal)
return 0; // Not the same, bail out.
else
InVal = PN->getIncomingValue(i);
// The only case that could cause InVal to be null is if we have a PHI node
// that only has entries for itself. In this case, there is no entry into the
// loop, so kill the PHI.
//
if (InVal == 0) InVal = Constant::getNullValue(PN->getType());
// All of the incoming values are the same, return the value now.
return InVal;
}
<|endoftext|> |
<commit_before>//===-- Local.cpp - Functions to perform local transformations ------------===//
//
// The LLVM Compiler Infrastructure
//
// This file was developed by the LLVM research group and is distributed under
// the University of Illinois Open Source License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
//
// This family of functions perform various local transformations to the
// program.
//
//===----------------------------------------------------------------------===//
#include "llvm/Transforms/Utils/Local.h"
#include "llvm/Constants.h"
#include "llvm/DerivedTypes.h"
#include "llvm/Instructions.h"
#include "llvm/Intrinsics.h"
#include "llvm/Analysis/ConstantFolding.h"
#include "llvm/Support/GetElementPtrTypeIterator.h"
#include "llvm/Support/MathExtras.h"
#include <cerrno>
#include <cmath>
using namespace llvm;
//===----------------------------------------------------------------------===//
// Local constant propagation...
//
/// doConstantPropagation - If an instruction references constants, try to fold
/// them together...
///
bool llvm::doConstantPropagation(BasicBlock::iterator &II) {
if (Constant *C = ConstantFoldInstruction(II)) {
// Replaces all of the uses of a variable with uses of the constant.
II->replaceAllUsesWith(C);
// Remove the instruction from the basic block...
II = II->getParent()->getInstList().erase(II);
return true;
}
return false;
}
/// ConstantFoldInstruction - Attempt to constant fold the specified
/// instruction. If successful, the constant result is returned, if not, null
/// is returned. Note that this function can only fail when attempting to fold
/// instructions like loads and stores, which have no constant expression form.
///
Constant *llvm::ConstantFoldInstruction(Instruction *I) {
if (PHINode *PN = dyn_cast<PHINode>(I)) {
if (PN->getNumIncomingValues() == 0)
return Constant::getNullValue(PN->getType());
Constant *Result = dyn_cast<Constant>(PN->getIncomingValue(0));
if (Result == 0) return 0;
// Handle PHI nodes specially here...
for (unsigned i = 1, e = PN->getNumIncomingValues(); i != e; ++i)
if (PN->getIncomingValue(i) != Result && PN->getIncomingValue(i) != PN)
return 0; // Not all the same incoming constants...
// If we reach here, all incoming values are the same constant.
return Result;
} else if (CallInst *CI = dyn_cast<CallInst>(I)) {
if (Function *F = CI->getCalledFunction())
if (canConstantFoldCallTo(F)) {
std::vector<Constant*> Args;
for (unsigned i = 1, e = CI->getNumOperands(); i != e; ++i)
if (Constant *Op = dyn_cast<Constant>(CI->getOperand(i)))
Args.push_back(Op);
else
return 0;
return ConstantFoldCall(F, Args);
}
return 0;
}
Constant *Op0 = 0, *Op1 = 0;
switch (I->getNumOperands()) {
default:
case 2:
Op1 = dyn_cast<Constant>(I->getOperand(1));
if (Op1 == 0) return 0; // Not a constant?, can't fold
case 1:
Op0 = dyn_cast<Constant>(I->getOperand(0));
if (Op0 == 0) return 0; // Not a constant?, can't fold
break;
case 0: return 0;
}
if (isa<BinaryOperator>(I) || isa<ShiftInst>(I))
return ConstantExpr::get(I->getOpcode(), Op0, Op1);
switch (I->getOpcode()) {
default: return 0;
case Instruction::Cast:
return ConstantExpr::getCast(Op0, I->getType());
case Instruction::Select:
if (Constant *Op2 = dyn_cast<Constant>(I->getOperand(2)))
return ConstantExpr::getSelect(Op0, Op1, Op2);
return 0;
case Instruction::ExtractElement:
return ConstantExpr::getExtractElement(Op0, Op1);
case Instruction::InsertElement:
if (Constant *Op2 = dyn_cast<Constant>(I->getOperand(2)))
return ConstantExpr::getInsertElement(Op0, Op1, Op2);
return 0;
case Instruction::ShuffleVector:
if (Constant *Op2 = dyn_cast<Constant>(I->getOperand(2)))
return ConstantExpr::getShuffleVector(Op0, Op1, Op2);
return 0;
case Instruction::GetElementPtr:
std::vector<Constant*> IdxList;
IdxList.reserve(I->getNumOperands()-1);
if (Op1) IdxList.push_back(Op1);
for (unsigned i = 2, e = I->getNumOperands(); i != e; ++i)
if (Constant *C = dyn_cast<Constant>(I->getOperand(i)))
IdxList.push_back(C);
else
return 0; // Non-constant operand
return ConstantExpr::getGetElementPtr(Op0, IdxList);
}
}
// ConstantFoldTerminator - If a terminator instruction is predicated on a
// constant value, convert it into an unconditional branch to the constant
// destination.
//
bool llvm::ConstantFoldTerminator(BasicBlock *BB) {
TerminatorInst *T = BB->getTerminator();
// Branch - See if we are conditional jumping on constant
if (BranchInst *BI = dyn_cast<BranchInst>(T)) {
if (BI->isUnconditional()) return false; // Can't optimize uncond branch
BasicBlock *Dest1 = cast<BasicBlock>(BI->getOperand(0));
BasicBlock *Dest2 = cast<BasicBlock>(BI->getOperand(1));
if (ConstantBool *Cond = dyn_cast<ConstantBool>(BI->getCondition())) {
// Are we branching on constant?
// YES. Change to unconditional branch...
BasicBlock *Destination = Cond->getValue() ? Dest1 : Dest2;
BasicBlock *OldDest = Cond->getValue() ? Dest2 : Dest1;
//cerr << "Function: " << T->getParent()->getParent()
// << "\nRemoving branch from " << T->getParent()
// << "\n\nTo: " << OldDest << endl;
// Let the basic block know that we are letting go of it. Based on this,
// it will adjust it's PHI nodes.
assert(BI->getParent() && "Terminator not inserted in block!");
OldDest->removePredecessor(BI->getParent());
// Set the unconditional destination, and change the insn to be an
// unconditional branch.
BI->setUnconditionalDest(Destination);
return true;
} else if (Dest2 == Dest1) { // Conditional branch to same location?
// This branch matches something like this:
// br bool %cond, label %Dest, label %Dest
// and changes it into: br label %Dest
// Let the basic block know that we are letting go of one copy of it.
assert(BI->getParent() && "Terminator not inserted in block!");
Dest1->removePredecessor(BI->getParent());
// Change a conditional branch to unconditional.
BI->setUnconditionalDest(Dest1);
return true;
}
} else if (SwitchInst *SI = dyn_cast<SwitchInst>(T)) {
// If we are switching on a constant, we can convert the switch into a
// single branch instruction!
ConstantInt *CI = dyn_cast<ConstantInt>(SI->getCondition());
BasicBlock *TheOnlyDest = SI->getSuccessor(0); // The default dest
BasicBlock *DefaultDest = TheOnlyDest;
assert(TheOnlyDest == SI->getDefaultDest() &&
"Default destination is not successor #0?");
// Figure out which case it goes to...
for (unsigned i = 1, e = SI->getNumSuccessors(); i != e; ++i) {
// Found case matching a constant operand?
if (SI->getSuccessorValue(i) == CI) {
TheOnlyDest = SI->getSuccessor(i);
break;
}
// Check to see if this branch is going to the same place as the default
// dest. If so, eliminate it as an explicit compare.
if (SI->getSuccessor(i) == DefaultDest) {
// Remove this entry...
DefaultDest->removePredecessor(SI->getParent());
SI->removeCase(i);
--i; --e; // Don't skip an entry...
continue;
}
// Otherwise, check to see if the switch only branches to one destination.
// We do this by reseting "TheOnlyDest" to null when we find two non-equal
// destinations.
if (SI->getSuccessor(i) != TheOnlyDest) TheOnlyDest = 0;
}
if (CI && !TheOnlyDest) {
// Branching on a constant, but not any of the cases, go to the default
// successor.
TheOnlyDest = SI->getDefaultDest();
}
// If we found a single destination that we can fold the switch into, do so
// now.
if (TheOnlyDest) {
// Insert the new branch..
new BranchInst(TheOnlyDest, SI);
BasicBlock *BB = SI->getParent();
// Remove entries from PHI nodes which we no longer branch to...
for (unsigned i = 0, e = SI->getNumSuccessors(); i != e; ++i) {
// Found case matching a constant operand?
BasicBlock *Succ = SI->getSuccessor(i);
if (Succ == TheOnlyDest)
TheOnlyDest = 0; // Don't modify the first branch to TheOnlyDest
else
Succ->removePredecessor(BB);
}
// Delete the old switch...
BB->getInstList().erase(SI);
return true;
} else if (SI->getNumSuccessors() == 2) {
// Otherwise, we can fold this switch into a conditional branch
// instruction if it has only one non-default destination.
Value *Cond = new SetCondInst(Instruction::SetEQ, SI->getCondition(),
SI->getSuccessorValue(1), "cond", SI);
// Insert the new branch...
new BranchInst(SI->getSuccessor(1), SI->getSuccessor(0), Cond, SI);
// Delete the old switch...
SI->getParent()->getInstList().erase(SI);
return true;
}
}
return false;
}
/// ConstantFoldLoadThroughGEPConstantExpr - Given a constant and a
/// getelementptr constantexpr, return the constant value being addressed by the
/// constant expression, or null if something is funny and we can't decide.
Constant *llvm::ConstantFoldLoadThroughGEPConstantExpr(Constant *C,
ConstantExpr *CE) {
if (CE->getOperand(1) != Constant::getNullValue(CE->getOperand(1)->getType()))
return 0; // Do not allow stepping over the value!
// Loop over all of the operands, tracking down which value we are
// addressing...
gep_type_iterator I = gep_type_begin(CE), E = gep_type_end(CE);
for (++I; I != E; ++I)
if (const StructType *STy = dyn_cast<StructType>(*I)) {
ConstantUInt *CU = cast<ConstantUInt>(I.getOperand());
assert(CU->getValue() < STy->getNumElements() &&
"Struct index out of range!");
unsigned El = (unsigned)CU->getValue();
if (ConstantStruct *CS = dyn_cast<ConstantStruct>(C)) {
C = CS->getOperand(El);
} else if (isa<ConstantAggregateZero>(C)) {
C = Constant::getNullValue(STy->getElementType(El));
} else if (isa<UndefValue>(C)) {
C = UndefValue::get(STy->getElementType(El));
} else {
return 0;
}
} else if (ConstantInt *CI = dyn_cast<ConstantInt>(I.getOperand())) {
if (const ArrayType *ATy = dyn_cast<ArrayType>(*I)) {
if ((uint64_t)CI->getRawValue() >= ATy->getNumElements())
return 0;
if (ConstantArray *CA = dyn_cast<ConstantArray>(C))
C = CA->getOperand((unsigned)CI->getRawValue());
else if (isa<ConstantAggregateZero>(C))
C = Constant::getNullValue(ATy->getElementType());
else if (isa<UndefValue>(C))
C = UndefValue::get(ATy->getElementType());
else
return 0;
} else if (const PackedType *PTy = dyn_cast<PackedType>(*I)) {
if ((uint64_t)CI->getRawValue() >= PTy->getNumElements())
return 0;
if (ConstantPacked *CP = dyn_cast<ConstantPacked>(C))
C = CP->getOperand((unsigned)CI->getRawValue());
else if (isa<ConstantAggregateZero>(C))
C = Constant::getNullValue(PTy->getElementType());
else if (isa<UndefValue>(C))
C = UndefValue::get(PTy->getElementType());
else
return 0;
} else {
return 0;
}
} else {
return 0;
}
return C;
}
//===----------------------------------------------------------------------===//
// Local dead code elimination...
//
bool llvm::isInstructionTriviallyDead(Instruction *I) {
if (!I->use_empty() || isa<TerminatorInst>(I)) return false;
if (!I->mayWriteToMemory()) return true;
if (CallInst *CI = dyn_cast<CallInst>(I))
if (Function *F = CI->getCalledFunction()) {
unsigned IntrinsicID = F->getIntrinsicID();
#define GET_SIDE_EFFECT_INFO
#include "llvm/Intrinsics.gen"
#undef GET_SIDE_EFFECT_INFO
}
return false;
}
// dceInstruction - Inspect the instruction at *BBI and figure out if it's
// [trivially] dead. If so, remove the instruction and update the iterator
// to point to the instruction that immediately succeeded the original
// instruction.
//
bool llvm::dceInstruction(BasicBlock::iterator &BBI) {
// Look for un"used" definitions...
if (isInstructionTriviallyDead(BBI)) {
BBI = BBI->getParent()->getInstList().erase(BBI); // Bye bye
return true;
}
return false;
}
<commit_msg>Refactor some code to expose an interface to constant fold and instruction given it's opcode, typeand operands.<commit_after>//===-- Local.cpp - Functions to perform local transformations ------------===//
//
// The LLVM Compiler Infrastructure
//
// This file was developed by the LLVM research group and is distributed under
// the University of Illinois Open Source License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
//
// This family of functions perform various local transformations to the
// program.
//
//===----------------------------------------------------------------------===//
#include "llvm/Transforms/Utils/Local.h"
#include "llvm/Constants.h"
#include "llvm/DerivedTypes.h"
#include "llvm/Instructions.h"
#include "llvm/Intrinsics.h"
#include "llvm/Analysis/ConstantFolding.h"
#include "llvm/Support/GetElementPtrTypeIterator.h"
#include "llvm/Support/MathExtras.h"
#include <cerrno>
#include <cmath>
using namespace llvm;
//===----------------------------------------------------------------------===//
// Local constant propagation...
//
/// doConstantPropagation - If an instruction references constants, try to fold
/// them together...
///
bool llvm::doConstantPropagation(BasicBlock::iterator &II) {
if (Constant *C = ConstantFoldInstruction(II)) {
// Replaces all of the uses of a variable with uses of the constant.
II->replaceAllUsesWith(C);
// Remove the instruction from the basic block...
II = II->getParent()->getInstList().erase(II);
return true;
}
return false;
}
/// ConstantFoldInstruction - Attempt to constant fold the specified
/// instruction. If successful, the constant result is returned, if not, null
/// is returned. Note that this function can only fail when attempting to fold
/// instructions like loads and stores, which have no constant expression form.
///
Constant *llvm::ConstantFoldInstruction(Instruction *I) {
if (PHINode *PN = dyn_cast<PHINode>(I)) {
if (PN->getNumIncomingValues() == 0)
return Constant::getNullValue(PN->getType());
Constant *Result = dyn_cast<Constant>(PN->getIncomingValue(0));
if (Result == 0) return 0;
// Handle PHI nodes specially here...
for (unsigned i = 1, e = PN->getNumIncomingValues(); i != e; ++i)
if (PN->getIncomingValue(i) != Result && PN->getIncomingValue(i) != PN)
return 0; // Not all the same incoming constants...
// If we reach here, all incoming values are the same constant.
return Result;
}
Constant *Op0 = 0, *Op1 = 0;
switch (I->getNumOperands()) {
default:
case 2:
Op1 = dyn_cast<Constant>(I->getOperand(1));
if (Op1 == 0) return 0; // Not a constant?, can't fold
case 1:
Op0 = dyn_cast<Constant>(I->getOperand(0));
if (Op0 == 0) return 0; // Not a constant?, can't fold
break;
case 0: return 0;
}
if (isa<BinaryOperator>(I) || isa<ShiftInst>(I)) {
if (Constant *Op0 = dyn_cast<Constant>(I->getOperand(0)))
if (Constant *Op1 = dyn_cast<Constant>(I->getOperand(1)))
return ConstantExpr::get(I->getOpcode(), Op0, Op1);
return 0; // Operands not constants.
}
// Scan the operand list, checking to see if the are all constants, if so,
// hand off to ConstantFoldInstOperands.
std::vector<Constant*> Ops;
for (unsigned i = 0, e = I->getNumOperands(); i != e; ++i)
if (Constant *Op = dyn_cast<Constant>(I->getOperand(i)))
Ops.push_back(Op);
else
return 0; // All operands not constant!
return ConstantFoldInstOperands(I->getOpcode(), I->getType(), Ops);
}
/// ConstantFoldInstOperands - Attempt to constant fold an instruction with the
/// specified opcode and operands. If successful, the constant result is
/// returned, if not, null is returned. Note that this function can fail when
/// attempting to fold instructions like loads and stores, which have no
/// constant expression form.
///
Constant *llvm::ConstantFoldInstOperands(unsigned Opc, const Type *DestTy,
const std::vector<Constant*> &Ops) {
if (Opc >= Instruction::BinaryOpsBegin && Opc < Instruction::BinaryOpsEnd)
return ConstantExpr::get(Opc, Ops[0], Ops[1]);
switch (Opc) {
default: return 0;
case Instruction::Call:
if (Function *F = dyn_cast<Function>(Ops[0])) {
if (canConstantFoldCallTo(F)) {
std::vector<Constant*> Args(Ops.begin()+1, Ops.end());
return ConstantFoldCall(F, Args);
}
}
return 0;
case Instruction::Shl:
case Instruction::Shr:
return ConstantExpr::get(Opc, Ops[0], Ops[1]);
case Instruction::Cast:
return ConstantExpr::getCast(Ops[0], DestTy);
case Instruction::Select:
return ConstantExpr::getSelect(Ops[0], Ops[1], Ops[2]);
case Instruction::ExtractElement:
return ConstantExpr::getExtractElement(Ops[0], Ops[1]);
case Instruction::InsertElement:
return ConstantExpr::getInsertElement(Ops[0], Ops[1], Ops[2]);
case Instruction::ShuffleVector:
return ConstantExpr::getShuffleVector(Ops[0], Ops[1], Ops[2]);
case Instruction::GetElementPtr:
return ConstantExpr::getGetElementPtr(Ops[0],
std::vector<Constant*>(Ops.begin()+1,
Ops.end()));
}
}
// ConstantFoldTerminator - If a terminator instruction is predicated on a
// constant value, convert it into an unconditional branch to the constant
// destination.
//
bool llvm::ConstantFoldTerminator(BasicBlock *BB) {
TerminatorInst *T = BB->getTerminator();
// Branch - See if we are conditional jumping on constant
if (BranchInst *BI = dyn_cast<BranchInst>(T)) {
if (BI->isUnconditional()) return false; // Can't optimize uncond branch
BasicBlock *Dest1 = cast<BasicBlock>(BI->getOperand(0));
BasicBlock *Dest2 = cast<BasicBlock>(BI->getOperand(1));
if (ConstantBool *Cond = dyn_cast<ConstantBool>(BI->getCondition())) {
// Are we branching on constant?
// YES. Change to unconditional branch...
BasicBlock *Destination = Cond->getValue() ? Dest1 : Dest2;
BasicBlock *OldDest = Cond->getValue() ? Dest2 : Dest1;
//cerr << "Function: " << T->getParent()->getParent()
// << "\nRemoving branch from " << T->getParent()
// << "\n\nTo: " << OldDest << endl;
// Let the basic block know that we are letting go of it. Based on this,
// it will adjust it's PHI nodes.
assert(BI->getParent() && "Terminator not inserted in block!");
OldDest->removePredecessor(BI->getParent());
// Set the unconditional destination, and change the insn to be an
// unconditional branch.
BI->setUnconditionalDest(Destination);
return true;
} else if (Dest2 == Dest1) { // Conditional branch to same location?
// This branch matches something like this:
// br bool %cond, label %Dest, label %Dest
// and changes it into: br label %Dest
// Let the basic block know that we are letting go of one copy of it.
assert(BI->getParent() && "Terminator not inserted in block!");
Dest1->removePredecessor(BI->getParent());
// Change a conditional branch to unconditional.
BI->setUnconditionalDest(Dest1);
return true;
}
} else if (SwitchInst *SI = dyn_cast<SwitchInst>(T)) {
// If we are switching on a constant, we can convert the switch into a
// single branch instruction!
ConstantInt *CI = dyn_cast<ConstantInt>(SI->getCondition());
BasicBlock *TheOnlyDest = SI->getSuccessor(0); // The default dest
BasicBlock *DefaultDest = TheOnlyDest;
assert(TheOnlyDest == SI->getDefaultDest() &&
"Default destination is not successor #0?");
// Figure out which case it goes to...
for (unsigned i = 1, e = SI->getNumSuccessors(); i != e; ++i) {
// Found case matching a constant operand?
if (SI->getSuccessorValue(i) == CI) {
TheOnlyDest = SI->getSuccessor(i);
break;
}
// Check to see if this branch is going to the same place as the default
// dest. If so, eliminate it as an explicit compare.
if (SI->getSuccessor(i) == DefaultDest) {
// Remove this entry...
DefaultDest->removePredecessor(SI->getParent());
SI->removeCase(i);
--i; --e; // Don't skip an entry...
continue;
}
// Otherwise, check to see if the switch only branches to one destination.
// We do this by reseting "TheOnlyDest" to null when we find two non-equal
// destinations.
if (SI->getSuccessor(i) != TheOnlyDest) TheOnlyDest = 0;
}
if (CI && !TheOnlyDest) {
// Branching on a constant, but not any of the cases, go to the default
// successor.
TheOnlyDest = SI->getDefaultDest();
}
// If we found a single destination that we can fold the switch into, do so
// now.
if (TheOnlyDest) {
// Insert the new branch..
new BranchInst(TheOnlyDest, SI);
BasicBlock *BB = SI->getParent();
// Remove entries from PHI nodes which we no longer branch to...
for (unsigned i = 0, e = SI->getNumSuccessors(); i != e; ++i) {
// Found case matching a constant operand?
BasicBlock *Succ = SI->getSuccessor(i);
if (Succ == TheOnlyDest)
TheOnlyDest = 0; // Don't modify the first branch to TheOnlyDest
else
Succ->removePredecessor(BB);
}
// Delete the old switch...
BB->getInstList().erase(SI);
return true;
} else if (SI->getNumSuccessors() == 2) {
// Otherwise, we can fold this switch into a conditional branch
// instruction if it has only one non-default destination.
Value *Cond = new SetCondInst(Instruction::SetEQ, SI->getCondition(),
SI->getSuccessorValue(1), "cond", SI);
// Insert the new branch...
new BranchInst(SI->getSuccessor(1), SI->getSuccessor(0), Cond, SI);
// Delete the old switch...
SI->getParent()->getInstList().erase(SI);
return true;
}
}
return false;
}
/// ConstantFoldLoadThroughGEPConstantExpr - Given a constant and a
/// getelementptr constantexpr, return the constant value being addressed by the
/// constant expression, or null if something is funny and we can't decide.
Constant *llvm::ConstantFoldLoadThroughGEPConstantExpr(Constant *C,
ConstantExpr *CE) {
if (CE->getOperand(1) != Constant::getNullValue(CE->getOperand(1)->getType()))
return 0; // Do not allow stepping over the value!
// Loop over all of the operands, tracking down which value we are
// addressing...
gep_type_iterator I = gep_type_begin(CE), E = gep_type_end(CE);
for (++I; I != E; ++I)
if (const StructType *STy = dyn_cast<StructType>(*I)) {
ConstantUInt *CU = cast<ConstantUInt>(I.getOperand());
assert(CU->getValue() < STy->getNumElements() &&
"Struct index out of range!");
unsigned El = (unsigned)CU->getValue();
if (ConstantStruct *CS = dyn_cast<ConstantStruct>(C)) {
C = CS->getOperand(El);
} else if (isa<ConstantAggregateZero>(C)) {
C = Constant::getNullValue(STy->getElementType(El));
} else if (isa<UndefValue>(C)) {
C = UndefValue::get(STy->getElementType(El));
} else {
return 0;
}
} else if (ConstantInt *CI = dyn_cast<ConstantInt>(I.getOperand())) {
if (const ArrayType *ATy = dyn_cast<ArrayType>(*I)) {
if ((uint64_t)CI->getRawValue() >= ATy->getNumElements())
return 0;
if (ConstantArray *CA = dyn_cast<ConstantArray>(C))
C = CA->getOperand((unsigned)CI->getRawValue());
else if (isa<ConstantAggregateZero>(C))
C = Constant::getNullValue(ATy->getElementType());
else if (isa<UndefValue>(C))
C = UndefValue::get(ATy->getElementType());
else
return 0;
} else if (const PackedType *PTy = dyn_cast<PackedType>(*I)) {
if ((uint64_t)CI->getRawValue() >= PTy->getNumElements())
return 0;
if (ConstantPacked *CP = dyn_cast<ConstantPacked>(C))
C = CP->getOperand((unsigned)CI->getRawValue());
else if (isa<ConstantAggregateZero>(C))
C = Constant::getNullValue(PTy->getElementType());
else if (isa<UndefValue>(C))
C = UndefValue::get(PTy->getElementType());
else
return 0;
} else {
return 0;
}
} else {
return 0;
}
return C;
}
//===----------------------------------------------------------------------===//
// Local dead code elimination...
//
bool llvm::isInstructionTriviallyDead(Instruction *I) {
if (!I->use_empty() || isa<TerminatorInst>(I)) return false;
if (!I->mayWriteToMemory()) return true;
if (CallInst *CI = dyn_cast<CallInst>(I))
if (Function *F = CI->getCalledFunction()) {
unsigned IntrinsicID = F->getIntrinsicID();
#define GET_SIDE_EFFECT_INFO
#include "llvm/Intrinsics.gen"
#undef GET_SIDE_EFFECT_INFO
}
return false;
}
// dceInstruction - Inspect the instruction at *BBI and figure out if it's
// [trivially] dead. If so, remove the instruction and update the iterator
// to point to the instruction that immediately succeeded the original
// instruction.
//
bool llvm::dceInstruction(BasicBlock::iterator &BBI) {
// Look for un"used" definitions...
if (isInstructionTriviallyDead(BBI)) {
BBI = BBI->getParent()->getInstList().erase(BBI); // Bye bye
return true;
}
return false;
}
<|endoftext|> |
<commit_before>/*
* face-cleaner.cpp
*
* Created on: Nov 15, 2014
* Author: Michael Williams
*/
#include "facerecogntion/face-cleaner.h"
#include <vector>
#include <stdio.h>
using namespace cv;
using namespace std;
namespace facerecogntion{
Mat clean_face(Mat face){
CascadeClassifier filter;
filter.load( FACE_FILTER );
vector<Rect> faces;
Mat gray_face;
cvtColor( face, gray_face, CV_BGR2GRAY );
gray_face.convertTo(gray_face, CV_8UC1);
equalizeHist( gray_face, gray_face );
filter.detectMultiScale( gray_face, faces, 1.1, 2, 0, Size(100, 100) );
Rect roi;
vector<Rect>::iterator it;
for(it=faces.begin(); it != faces.end(); it++){
if(it->area() > roi.area()){
roi = (*it);
}
}
Mat tmp;
cvtColor(gray_face(roi), tmp, CV_BGR2GRAY);
return tmp;
}
}
<commit_msg>More cleaning to the images<commit_after>/*
* face-cleaner.cpp
*
* Created on: Nov 15, 2014
* Author: Michael Williams
*/
#include "facerecogntion/face-cleaner.h"
#include <vector>
#include <stdio.h>
using namespace cv;
using namespace std;
namespace facerecogntion{
Mat clean_face(Mat face){
CascadeClassifier filter;
filter.load( FACE_FILTER );
vector<Rect> faces;
Mat gray_face;
cvtColor( face, gray_face, CV_BGR2GRAY );
gray_face.convertTo(gray_face, CV_8UC1);
equalizeHist( gray_face, gray_face );
filter.detectMultiScale( gray_face, faces, 1.1, 2, 0, Size(100, 100) );
Rect roi;
vector<Rect>::iterator it;
for(it=faces.begin(); it != faces.end(); it++){
if(it->area() > roi.area()){
roi = (*it);
}
}
Mat tmp;
gray_face(roi).convertTo(tmp, CV_8UC1);
equalizeHist( tmp, tmp );
return tmp;
}
}
<|endoftext|> |
<commit_before>/*************************************************************************
*
* $RCSfile: lockfile.cxx,v $
*
* $Revision: 1.4 $
*
* last change: $Author: hr $ $Date: 2003-03-25 13:51:15 $
*
* 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): lars.oppermann@sun.com
*
*
************************************************************************/
#include <stdlib.h>
#include <time.h>
#include <sal/types.h>
#include <osl/file.hxx>
#include <osl/socket.hxx>
#include <osl/security.hxx>
#include <unotools/bootstrap.hxx>
#include <vcl/msgbox.hxx>
#include <tools/string.hxx>
#include <tools/config.hxx>
#include "desktopresid.hxx"
#include "lockfile.hxx"
#include "desktop.hrc"
using namespace ::osl;
using namespace ::rtl;
using namespace ::utl;
namespace desktop {
// initialize static members...
// lock suffix
const OUString Lockfile::m_aSuffix = OUString::createFromAscii( "/.lock" );
// values for datafile
const ByteString Lockfile::m_aGroup( "Lockdata" );
const ByteString Lockfile::m_aUserkey( "User" );
const ByteString Lockfile::m_aHostkey( "Host" );
const ByteString Lockfile::m_aStampkey( "Stamp" );
const ByteString Lockfile::m_aTimekey( "Time" );
Lockfile::Lockfile(void)
:m_bRemove(sal_False)
,m_bIsLocked(sal_False)
{
// build the file-url to use for the lock
OUString aUserPath;
Bootstrap::locateUserInstallation( aUserPath );
m_aLockname = aUserPath + m_aSuffix;
// generate ID
const int nIdBytes = 16;
char tmpId[nIdBytes*2+1];
time_t t;
srand( (unsigned)(t = time( NULL )) );
int tmpByte = 0;
for (int i = 0; i<nIdBytes; i++) {
tmpByte = rand( ) % 0xFF;
sprintf( tmpId+i*2, "%02X", tmpByte ); // #100211# - checked
}
tmpId[nIdBytes*2]=0x00;
m_aId = OUString::createFromAscii( tmpId );
// generate date string
char *tmpTime = ctime( &t );
tmpTime[24] = 0x00; // buffer is always 26 chars, remove '\n'
m_aDate = OUString::createFromAscii( tmpTime );
// try to create file
File aFile(m_aLockname);
if (aFile.open( OpenFlag_Create ) == File::E_EXIST) {
m_bIsLocked = sal_True;
} else {
// new lock created
aFile.close( );
syncToFile( );
m_bRemove = sal_True;
}
}
sal_Bool Lockfile::check( void )
{
if (m_bIsLocked) {
// lock existed, ask user what to do
if (isStale() || execWarning( ) == RET_YES) {
// remove file and create new
File::remove( m_aLockname );
File aFile(m_aLockname);
aFile.open( OpenFlag_Create );
aFile.close( );
syncToFile( );
m_bRemove = sal_True;
return sal_True;
} else {
//leave alone and return false
m_bRemove = sal_False;
return sal_False;
}
} else {
// lock was created by us
return sal_True;
}
}
sal_Bool Lockfile::isStale( void ) const
{
// this checks whether the lockfile was created on the same
// host by the same user. Should this be the case it is safe
// to assume that it is a stale lookfile which can be overwritten
String aLockname = m_aLockname;
Config aConfig(aLockname);
aConfig.SetGroup(m_aGroup);
ByteString aHost = aConfig.ReadKey( m_aHostkey );
ByteString aUser = aConfig.ReadKey( m_aUserkey );
// lockfile from same host?
oslSocketResult sRes;
ByteString myHost = OUStringToOString(
SocketAddr::getLocalHostname( &sRes ), RTL_TEXTENCODING_ASCII_US );
if (aHost == myHost) {
// lockfile by same UID
OUString myUserName;
Security aSecurity;
aSecurity.getUserName( myUserName );
ByteString myUser = OUStringToOString( myUserName, RTL_TEXTENCODING_ASCII_US );
if (aUser == myUser)
return sal_True;
}
return sal_False;
}
void Lockfile::syncToFile( void ) const
{
String aLockname = m_aLockname;
Config aConfig(aLockname);
aConfig.SetGroup(m_aGroup);
// get information
oslSocketResult sRes;
ByteString aHost = OUStringToOString(
SocketAddr::getLocalHostname( &sRes ), RTL_TEXTENCODING_ASCII_US );
OUString aUserName;
Security aSecurity;
aSecurity.getUserName( aUserName );
ByteString aUser = OUStringToOString( aUserName, RTL_TEXTENCODING_ASCII_US );
ByteString aTime = OUStringToOString( m_aDate, RTL_TEXTENCODING_ASCII_US );
ByteString aStamp = OUStringToOString( m_aId, RTL_TEXTENCODING_ASCII_US );
// write information
aConfig.WriteKey( m_aUserkey, aUser );
aConfig.WriteKey( m_aHostkey, aHost );
aConfig.WriteKey( m_aStampkey, aStamp );
aConfig.WriteKey( m_aTimekey, aTime );
aConfig.Flush( );
}
short Lockfile::execWarning(void) const
{
// read information from lock
String aLockname = m_aLockname;
Config aConfig(aLockname);
aConfig.SetGroup(m_aGroup);
ByteString aHost = aConfig.ReadKey( m_aHostkey );
ByteString aUser = aConfig.ReadKey( m_aUserkey );
ByteString aStamp = aConfig.ReadKey( m_aStampkey );
ByteString aTime = aConfig.ReadKey( m_aTimekey );
// display warning and return response
QueryBox aBox( NULL, DesktopResId( QBX_USERDATALOCKED ) );
// set box title
String aTitle = String( DesktopResId( STR_TITLE_USERDATALOCKED ));
aBox.SetText( aTitle );
// insert values...
String aMsgText = aBox.GetMessText( );
aMsgText.SearchAndReplaceAscii( "$u", String( aUser, RTL_TEXTENCODING_ASCII_US) );
aMsgText.SearchAndReplaceAscii( "$h", String( aHost, RTL_TEXTENCODING_ASCII_US) );
aMsgText.SearchAndReplaceAscii( "$t", String( aTime, RTL_TEXTENCODING_ASCII_US) );
aBox.SetMessText(aMsgText);
// do it
return aBox.Execute( );
}
void Lockfile::clean( void )
{
if ( m_bRemove )
{
File::remove( m_aLockname );
m_bRemove = sal_False;
}
}
Lockfile::~Lockfile( void )
{
// unlock userdata by removing file
if ( m_bRemove )
File::remove( m_aLockname );
}
}
<commit_msg>INTEGRATION: CWS fwk01 (1.2.2.5.16); FILE MERGED 2003/04/01 14:03:31 lo 1.2.2.5.16.1: #i12907# allow startup without splashscreen component being loaded<commit_after>/*************************************************************************
*
* $RCSfile: lockfile.cxx,v $
*
* $Revision: 1.5 $
*
* last change: $Author: hr $ $Date: 2003-04-04 17:22:51 $
*
* 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): lars.oppermann@sun.com
*
*
************************************************************************/
#include <stdlib.h>
#include <time.h>
#include <sal/types.h>
#include <osl/file.hxx>
#include <osl/socket.hxx>
#include <osl/security.hxx>
#include <unotools/bootstrap.hxx>
#include <vcl/msgbox.hxx>
#include <tools/string.hxx>
#include <tools/config.hxx>
#include "desktopresid.hxx"
#include "lockfile.hxx"
#include "desktop.hrc"
using namespace ::osl;
using namespace ::rtl;
using namespace ::utl;
namespace desktop {
// initialize static members...
// lock suffix
const OUString Lockfile::m_aSuffix = OUString::createFromAscii( "/.lock" );
// values for datafile
const ByteString Lockfile::m_aGroup( "Lockdata" );
const ByteString Lockfile::m_aUserkey( "User" );
const ByteString Lockfile::m_aHostkey( "Host" );
const ByteString Lockfile::m_aStampkey( "Stamp" );
const ByteString Lockfile::m_aTimekey( "Time" );
Lockfile::Lockfile(void)
:m_bRemove(sal_False)
,m_bIsLocked(sal_False)
{
// build the file-url to use for the lock
OUString aUserPath;
Bootstrap::locateUserInstallation( aUserPath );
m_aLockname = aUserPath + m_aSuffix;
// generate ID
const int nIdBytes = 16;
char tmpId[nIdBytes*2+1];
time_t t;
srand( (unsigned)(t = time( NULL )) );
int tmpByte = 0;
for (int i = 0; i<nIdBytes; i++) {
tmpByte = rand( ) % 0xFF;
sprintf( tmpId+i*2, "%02X", tmpByte ); // #100211# - checked
}
tmpId[nIdBytes*2]=0x00;
m_aId = OUString::createFromAscii( tmpId );
// generate date string
char *tmpTime = ctime( &t );
tmpTime[24] = 0x00; // buffer is always 26 chars, remove '\n'
m_aDate = OUString::createFromAscii( tmpTime );
// try to create file
File aFile(m_aLockname);
if (aFile.open( OpenFlag_Create ) == File::E_EXIST) {
m_bIsLocked = sal_True;
} else {
// new lock created
aFile.close( );
syncToFile( );
m_bRemove = sal_True;
}
}
sal_Bool Lockfile::check( void )
{
if (m_bIsLocked) {
// lock existed, ask user what to do
if (isStale() || execWarning( ) == RET_YES) {
// remove file and create new
File::remove( m_aLockname );
File aFile(m_aLockname);
aFile.open( OpenFlag_Create );
aFile.close( );
syncToFile( );
m_bRemove = sal_True;
return sal_True;
} else {
//leave alone and return false
m_bRemove = sal_False;
return sal_False;
}
} else {
// lock was created by us
return sal_True;
}
}
sal_Bool Lockfile::isStale( void ) const
{
// this checks whether the lockfile was created on the same
// host by the same user. Should this be the case it is safe
// to assume that it is a stale lockfile which can be overwritten
String aLockname = m_aLockname;
Config aConfig(aLockname);
aConfig.SetGroup(m_aGroup);
ByteString aHost = aConfig.ReadKey( m_aHostkey );
ByteString aUser = aConfig.ReadKey( m_aUserkey );
// lockfile from same host?
oslSocketResult sRes;
ByteString myHost = OUStringToOString(
SocketAddr::getLocalHostname( &sRes ), RTL_TEXTENCODING_ASCII_US );
if (aHost == myHost) {
// lockfile by same UID
OUString myUserName;
Security aSecurity;
aSecurity.getUserName( myUserName );
ByteString myUser = OUStringToOString( myUserName, RTL_TEXTENCODING_ASCII_US );
if (aUser == myUser)
return sal_True;
}
return sal_False;
}
void Lockfile::syncToFile( void ) const
{
String aLockname = m_aLockname;
Config aConfig(aLockname);
aConfig.SetGroup(m_aGroup);
// get information
oslSocketResult sRes;
ByteString aHost = OUStringToOString(
SocketAddr::getLocalHostname( &sRes ), RTL_TEXTENCODING_ASCII_US );
OUString aUserName;
Security aSecurity;
aSecurity.getUserName( aUserName );
ByteString aUser = OUStringToOString( aUserName, RTL_TEXTENCODING_ASCII_US );
ByteString aTime = OUStringToOString( m_aDate, RTL_TEXTENCODING_ASCII_US );
ByteString aStamp = OUStringToOString( m_aId, RTL_TEXTENCODING_ASCII_US );
// write information
aConfig.WriteKey( m_aUserkey, aUser );
aConfig.WriteKey( m_aHostkey, aHost );
aConfig.WriteKey( m_aStampkey, aStamp );
aConfig.WriteKey( m_aTimekey, aTime );
aConfig.Flush( );
}
short Lockfile::execWarning(void) const
{
// read information from lock
String aLockname = m_aLockname;
Config aConfig(aLockname);
aConfig.SetGroup(m_aGroup);
ByteString aHost = aConfig.ReadKey( m_aHostkey );
ByteString aUser = aConfig.ReadKey( m_aUserkey );
ByteString aStamp = aConfig.ReadKey( m_aStampkey );
ByteString aTime = aConfig.ReadKey( m_aTimekey );
// display warning and return response
QueryBox aBox( NULL, DesktopResId( QBX_USERDATALOCKED ) );
// set box title
String aTitle = String( DesktopResId( STR_TITLE_USERDATALOCKED ));
aBox.SetText( aTitle );
// insert values...
String aMsgText = aBox.GetMessText( );
aMsgText.SearchAndReplaceAscii( "$u", String( aUser, RTL_TEXTENCODING_ASCII_US) );
aMsgText.SearchAndReplaceAscii( "$h", String( aHost, RTL_TEXTENCODING_ASCII_US) );
aMsgText.SearchAndReplaceAscii( "$t", String( aTime, RTL_TEXTENCODING_ASCII_US) );
aBox.SetMessText(aMsgText);
// do it
return aBox.Execute( );
}
void Lockfile::clean( void )
{
if ( m_bRemove )
{
File::remove( m_aLockname );
m_bRemove = sal_False;
}
}
Lockfile::~Lockfile( void )
{
// unlock userdata by removing file
if ( m_bRemove )
File::remove( m_aLockname );
}
}
<|endoftext|> |
<commit_before>/*
Copyright(c) 2004 John J.Bolton
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 "ZHash.h"
#include "Chess/Board.h"
#include "Chess/Piece.h"
#include "Chess/Position.h"
#include "Misc/Random.h"
#include <cassert>
ZHash::ZValueTable const ZHash::zValueTable_;
namespace
{
uint64_t generateRandomZ(RandomMT & rng)
{
// Z is 63 bits and RandomMT is 32 bits so we have to concatenate two numbers together to make a Z value.
return ((uint64_t(rng()) << 32) | rng()) & 0x7fffffffffffffff;
}
} // anonymous namespace
ZHash::ZHash(Z z /* = EMPTY */)
: value_(z)
{
}
ZHash::ZHash(Board const & board,
Color whoseTurn,
unsigned castleStatus /* = 0*/,
Color ePColor /* = INVALID*/,
int ePColumn /* = -1*/,
bool fiftyMoveRule /* = false */)
{
value_ = 0;
for (int i = 0; i < Board::SIZE; ++i)
{
for (int j = 0; j < Board::SIZE; ++j)
{
Piece const * const piece = board.pieceAt(i, j);
if (piece)
add(piece, Position(i, j));
}
}
if (whoseTurn != Color::WHITE)
turn();
if (castleStatus != 0)
castle(castleStatus);
if ((ePColor != Color::INVALID) && (ePColumn >= 0))
enPassant(ePColor, ePColumn);
if (fiftyMoveRule)
fifty();
}
ZHash ZHash::add(Piece const * piece, Position const & position)
{
value_ ^= zValueTable_.pieceValue((int)piece->color(), (int)piece->type(), position.row, position.column);
return *this;
}
ZHash ZHash::remove(Piece const * piece, Position const & position)
{
value_ ^= zValueTable_.pieceValue((int)piece->color(), (int)piece->type(), position.row, position.column);
return *this;
}
ZHash ZHash::move(Piece const * piece, Position const & from, Position const & to)
{
remove(piece, from);
return add(piece, to);
}
ZHash ZHash::turn()
{
value_ ^= zValueTable_.turnValue();
return *this;
}
ZHash ZHash::castle(unsigned mask)
{
assert(NUMBER_OF_CASTLE_BITS == 8);
assert(CASTLE_AVAILABILITY_MASK == 0xf0);
for (int i = 0; i < 4; ++i)
{
if (mask & (0x10 << i))
value_ ^= zValueTable_.castleValue(i);
}
return *this;
}
ZHash ZHash::enPassant(Color color, int column)
{
value_ ^= zValueTable_.enPassantValue((int)color, column);
return *this;
}
ZHash ZHash::fifty()
{
value_ ^= zValueTable_.fiftyValue();
return *this;
}
bool ZHash::isUndefined() const
{
// The value is undefined if the high order bit is set
return static_cast<int64_t>(value_) < 0;
}
ZHash::ZValueTable::ZValueTable()
{
RandomMT rng(0);
// Generate piece values
for (int i = 0; i < NUMBER_OF_COLORS; ++i)
{
for (int j = 0; j < Board::SIZE; ++j)
{
for (int k = 0; k < Board::SIZE; ++k)
{
for (int m = 0; m < NUMBER_OF_PIECE_TYPES; ++m)
{
pieceValues_[i][j][k][m] = generateRandomZ(rng);
}
}
}
}
// Generate castle values
for (auto & v : castleValues_)
{
v = generateRandomZ(rng);
}
// Generate en passant values
for (int i = 0; i < NUMBER_OF_COLORS; ++i)
{
for (int j = 0; j < Board::SIZE; ++j)
{
enPassantValues_[i][j] = generateRandomZ(rng);
}
}
// Generate fifty-move rule value
fiftyValue_ = generateRandomZ(rng);
// Generate turn value
turnValue_ = generateRandomZ(rng);
}
ZHash::Z ZHash::ZValueTable::pieceValue(int color, int type, int row, int column) const
{
return pieceValues_[color][row][column][type];
}
ZHash::Z ZHash::ZValueTable::castleValue(int castle) const
{
return castleValues_[castle];
}
ZHash::Z ZHash::ZValueTable::enPassantValue(int color, int column) const
{
return enPassantValues_[color][column];
}
ZHash::Z ZHash::ZValueTable::fiftyValue() const
{
return fiftyValue_;
}
ZHash::Z ZHash::ZValueTable::turnValue() const
{
return turnValue_;
}
bool operator ==(ZHash const & x, ZHash const & y)
{
return x.value_ == y.value_;
}
<commit_msg>Switched to std::random<commit_after>/*
Copyright(c) 2004 John J.Bolton
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 "ZHash.h"
#include "Chess/Board.h"
#include "Chess/Piece.h"
#include "Chess/Position.h"
#include <cassert>
#include <random>
ZHash::ZValueTable const ZHash::zValueTable_;
ZHash::ZHash(Z z /* = EMPTY */)
: value_(z)
{
}
ZHash::ZHash(Board const & board,
Color whoseTurn,
unsigned castleStatus /* = 0*/,
Color ePColor /* = INVALID*/,
int ePColumn /* = -1*/,
bool fiftyMoveRule /* = false */)
{
value_ = 0;
for (int i = 0; i < Board::SIZE; ++i)
{
for (int j = 0; j < Board::SIZE; ++j)
{
Piece const * const piece = board.pieceAt(i, j);
if (piece)
add(piece, Position(i, j));
}
}
if (whoseTurn != Color::WHITE)
turn();
if (castleStatus != 0)
castle(castleStatus);
if ((ePColor != Color::INVALID) && (ePColumn >= 0))
enPassant(ePColor, ePColumn);
if (fiftyMoveRule)
fifty();
}
ZHash ZHash::add(Piece const * piece, Position const & position)
{
value_ ^= zValueTable_.pieceValue((int)piece->color(), (int)piece->type(), position.row, position.column);
return *this;
}
ZHash ZHash::remove(Piece const * piece, Position const & position)
{
value_ ^= zValueTable_.pieceValue((int)piece->color(), (int)piece->type(), position.row, position.column);
return *this;
}
ZHash ZHash::move(Piece const * piece, Position const & from, Position const & to)
{
remove(piece, from);
return add(piece, to);
}
ZHash ZHash::turn()
{
value_ ^= zValueTable_.turnValue();
return *this;
}
ZHash ZHash::castle(unsigned mask)
{
assert(NUMBER_OF_CASTLE_BITS == 8);
assert(CASTLE_AVAILABILITY_MASK == 0xf0);
for (int i = 0; i < 4; ++i)
{
if (mask & (0x10 << i))
value_ ^= zValueTable_.castleValue(i);
}
return *this;
}
ZHash ZHash::enPassant(Color color, int column)
{
value_ ^= zValueTable_.enPassantValue((int)color, column);
return *this;
}
ZHash ZHash::fifty()
{
value_ ^= zValueTable_.fiftyValue();
return *this;
}
bool ZHash::isUndefined() const
{
// The value is undefined if the high order bit is set
return static_cast<int64_t>(value_) < 0;
}
ZHash::ZValueTable::ZValueTable()
{
std::mt19937_64 rng;
static_assert(sizeof(std::mt19937_64::result_type) == 8);
// Generate piece values
for (int i = 0; i < NUMBER_OF_COLORS; ++i)
{
for (int j = 0; j < Board::SIZE; ++j)
{
for (int k = 0; k < Board::SIZE; ++k)
{
for (int m = 0; m < NUMBER_OF_PIECE_TYPES; ++m)
{
pieceValues_[i][j][k][m] = rng();
}
}
}
}
// Generate castle values
for (auto & v : castleValues_)
{
v = rng();
}
// Generate en passant values
for (int i = 0; i < NUMBER_OF_COLORS; ++i)
{
for (int j = 0; j < Board::SIZE; ++j)
{
enPassantValues_[i][j] = rng();
}
}
// Generate fifty-move rule value
fiftyValue_ = rng();
// Generate turn value
turnValue_ = rng();
}
ZHash::Z ZHash::ZValueTable::pieceValue(int color, int type, int row, int column) const
{
return pieceValues_[color][row][column][type];
}
ZHash::Z ZHash::ZValueTable::castleValue(int castle) const
{
return castleValues_[castle];
}
ZHash::Z ZHash::ZValueTable::enPassantValue(int color, int column) const
{
return enPassantValues_[color][column];
}
ZHash::Z ZHash::ZValueTable::fiftyValue() const
{
return fiftyValue_;
}
ZHash::Z ZHash::ZValueTable::turnValue() const
{
return turnValue_;
}
bool operator ==(ZHash const & x, ZHash const & y)
{
return x.value_ == y.value_;
}
<|endoftext|> |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.